diff --git a/.editorconfig b/.editorconfig new file mode 100644 index 0000000..2c16156 --- /dev/null +++ b/.editorconfig @@ -0,0 +1,15 @@ +# EditorConfig is awesome: https://EditorConfig.org + +# top-most EditorConfig file +root = true + +[*] +indent_style = space +indent_size = 4 +end_of_line = lf +charset = utf-8 +trim_trailing_whitespace = true +insert_final_newline = true + +[*.{yaml,yml}] +indent_size = 2 diff --git a/.github/CODEOWNERS b/.github/CODEOWNERS new file mode 100644 index 0000000..ec10dff --- /dev/null +++ b/.github/CODEOWNERS @@ -0,0 +1 @@ +* @martinbean diff --git a/.github/workflows/composer.yml b/.github/workflows/composer.yml new file mode 100644 index 0000000..c48d4cf --- /dev/null +++ b/.github/workflows/composer.yml @@ -0,0 +1,22 @@ +name: Validate Composer + +on: + push: + paths: + - composer.json + +jobs: + validate: + name: Validate + runs-on: ubuntu-latest + steps: + - name: Check out code + uses: actions/checkout@v4 + + - name: Set up PHP + uses: shivammathur/setup-php@v2 + with: + php-version: 8.4 + + - name: Validate + run: composer validate --no-check-lock --no-check-version --strict diff --git a/.github/workflows/lint.yml b/.github/workflows/lint.yml new file mode 100644 index 0000000..47ed22b --- /dev/null +++ b/.github/workflows/lint.yml @@ -0,0 +1,25 @@ +name: Lint + +on: + push: + paths: + - '**.php' + +jobs: + lint: + name: Lint + runs-on: ubuntu-latest + steps: + - name: Check out code + uses: actions/checkout@v4 + + - name: Set up PHP + uses: shivammathur/setup-php@v2 + with: + php-version: 8.4 + + - name: Install dependencies + run: composer install --no-ansi --no-interaction --no-progress --prefer-dist + + - name: Lint + run: composer run-script lint diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml new file mode 100644 index 0000000..7c0868c --- /dev/null +++ b/.github/workflows/test.yml @@ -0,0 +1,32 @@ +name: Test + +on: + push: + paths: + - '.github/workflows/test.yml' + - '**.php' + +jobs: + test: + strategy: + matrix: + php_version: + - '8.2' + - '8.3' + - '8.4' + name: Test + runs-on: ubuntu-latest + steps: + - name: Check out code + uses: actions/checkout@v4 + + - name: Set up PHP + uses: shivammathur/setup-php@v2 + with: + php-version: ${{ matrix.php_version }} + + - name: Install dependencies + run: composer install --no-ansi --no-interaction --no-progress --prefer-dist + + - name: Run tests + run: composer run-script test diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..78b76d5 --- /dev/null +++ b/.gitignore @@ -0,0 +1,4 @@ +/.phpunit.* +/vendor +composer.lock +phpunit.xml diff --git a/CHANGELOG.md b/CHANGELOG.md new file mode 100644 index 0000000..c2dfefe --- /dev/null +++ b/CHANGELOG.md @@ -0,0 +1,6 @@ +# Changelog + +## [1.0.0] - 2024-11-26 + +### Added +- Initial release. Includes configuration and webhook handler. diff --git a/LICENSE.md b/LICENSE.md new file mode 100644 index 0000000..74732c1 --- /dev/null +++ b/LICENSE.md @@ -0,0 +1,7 @@ +Copyright 2024 Martin Bean + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/README.md b/README.md new file mode 100644 index 0000000..0914131 --- /dev/null +++ b/README.md @@ -0,0 +1,102 @@ +# Mux PHP SDK for Laravel + +## Installation +```sh +composer require martinbean/mux-php-laravel +``` + +## Configuration +By default, the package expects two environment variables to be defined: + +- `MUX_CLIENT_ID` +- `MUX_CLIENT_SECRET` + +This should be a Mux access token ID and secret. + +You can generate a Mux access token by: + +1. Logging into your [Mux dashboard][1] +2. Going to “Settings” +3. Then going to “Access Tokens” + +### Verifying webhook signatures +To verify webhook signatures from Mux, specify the signing secret for your webhook endpoint as the value of your `MUX_WEBHOOK_SECRET` environment variable. This means you will need to register your webhook endpoint in the [Mux dashboard][1] first. + +## Usage + +### API clients +The package will register default configuration based on the configured Mux access token. This means you can then type-hint a Mux client in your Laravel application, and it and its dependencies will be automatically resolved: + +```php +namespace App\Http\Controllers; + +use MuxPhp\Api\DirectUploadsApi; + +class UploadController extends Controller +{ + protected DirectUploadsApi $uploads; + + public function __construct(DirectUploadsApi $uploads) + { + $this->uploads = $uploads; + } +} +``` + +### Webhook handling +The package will also automatically register a route to listen for webhooks sent by Mux. The URI of this handler is **/mux/webhook** + +The webhook handler is heavily based on [Cashier][2]’s webhook handler. When a webhook from Mux is received, an instance of the `MartinBean\Laravel\Mux\Events\WebhookReceived` event is dispatched containing the webhook’s payload. + +You can define a listener that listens for this event: + +```php +namespace App\Listeners; + +use MartinBean\Laravel\Mux\Events\WebhookReceived; + +class MuxEventListener +{ + public function handle(WebhookReceived $event): void + { + // Handle Mux webhook event... + } +} +``` + +This is where you would update models, etc in your application based on events from Mux: + +```diff + public function handle(WebhookReceived $event): void + { +- // Handle Mux webhook event... ++ match ($event->payload['type']) { ++ 'video.asset.errored' => $this->handleVideoAssetErrored($event->payload), ++ 'video.asset.ready' => $this->handleVideoAssetReady($event->payload), ++ default => null, // unhandled event ++ }; + } ++ ++ protected function handleVideoAssetErrored(array $payload): void ++ { ++ // TODO: Retrieve associated video ++ // TODO: Update video status to 'errored' ++ // TODO: Notify user processing video errored ++ } ++ ++ protected function handleVideoAssetReady(array $payload): void ++ { ++ // TODO: Retrieve associated video ++ // TODO: Update video status to 'ready' ++ // TODO: Notify user processing video succeeded ++ } +``` + +## Contribution +Contributions are always welcome. Please open a pull request with your proposed changes, with accompanying tests. + +## License +Licensed under the [MIT License](LICENSE.md) + +[1]: https://dashboard.mux.com/ +[2]: https://laravel.com/docs/cashier diff --git a/composer.json b/composer.json new file mode 100644 index 0000000..4b05ccb --- /dev/null +++ b/composer.json @@ -0,0 +1,70 @@ +{ + "$schema": "https://getcomposer.org/schema.json", + "name": "martinbean/mux-php-laravel", + "description": "Laravel wrapper for the official Mux PHP SDK.", + "version": "1.0.0", + "type": "library", + "keywords": [ + "laravel", + "mux", + "php", + "video" + ], + "readme": "README.md", + "license": "MIT", + "authors": [ + { + "name": "Martin Bean", + "homepage": "https://martinbean.dev" + } + ], + "support": { + "issues": "https://github.com/martinbean/mux-php-laravel/issues", + "source": "https://github.com/martinbean/mux-php-laravel" + }, + "funding": [ + { + "type": "other", + "url": "https://buymeacoffee.com/martinbean" + } + ], + "require": { + "illuminate/http": "^11.0", + "illuminate/routing": "^11.0", + "illuminate/support": "^11.0", + "muxinc/mux-php": "^3.0" + }, + "require-dev": { + "orchestra/testbench": "^9.6", + "squizlabs/php_codesniffer": "^3.11" + }, + "autoload": { + "psr-4": { + "MartinBean\\Laravel\\Mux\\": "src/" + } + }, + "autoload-dev": { + "psr-4": { + "MartinBean\\Laravel\\Mux\\Tests\\": "tests/", + "Workbench\\App\\": "workbench/app/", + "Workbench\\Database\\Factories\\": "workbench/database/factories/", + "Workbench\\Database\\Seeders\\": "workbench/database/seeders/" + } + }, + "minimum-stability": "stable", + "prefer-stable": true, + "config": { + "sort-packages": true + }, + "scripts": { + "lint": "phpcs --standard=PSR12 src", + "test": "phpunit" + }, + "extra": { + "laravel": { + "providers": [ + "MartinBean\\Laravel\\Mux\\MuxServiceProvider" + ] + } + } +} diff --git a/config/mux.php b/config/mux.php new file mode 100644 index 0000000..c333840 --- /dev/null +++ b/config/mux.php @@ -0,0 +1,23 @@ + Access Tokens. + | + */ + + 'client_id' => env('MUX_CLIENT_ID'), + 'client_secret' => env('MUX_CLIENT_SECRET'), + + 'webhook' => [ + 'secret' => env('MUX_WEBHOOK_SECRET'), + ], + +]; diff --git a/phpunit.xml.dist b/phpunit.xml.dist new file mode 120000 index 0000000..57be4e3 --- /dev/null +++ b/phpunit.xml.dist @@ -0,0 +1 @@ +phpunit.xml \ No newline at end of file diff --git a/routes/web.php b/routes/web.php new file mode 100644 index 0000000..c22538c --- /dev/null +++ b/routes/web.php @@ -0,0 +1,7 @@ +name('mux.webhook'); diff --git a/src/Events/WebhookReceived.php b/src/Events/WebhookReceived.php new file mode 100644 index 0000000..3b1df82 --- /dev/null +++ b/src/Events/WebhookReceived.php @@ -0,0 +1,19 @@ +payload = $payload; + } +} diff --git a/src/Exception/SignatureException.php b/src/Exception/SignatureException.php new file mode 100644 index 0000000..9dd13b7 --- /dev/null +++ b/src/Exception/SignatureException.php @@ -0,0 +1,9 @@ +events = $events; + $this->config = $config; + + if ($this->config->get('mux.webhook.secret')) { + $this->middleware(VerifyWebhookSignature::class); + } + } + + /** + * Handle the incoming request. + */ + public function __invoke(Request $request): Response + { + $payload = json_decode($request->getContent(), true); + + $this->events->dispatch(new WebhookReceived($payload)); + + return new Response('', Response::HTTP_NO_CONTENT); + } +} diff --git a/src/Http/Middleware/VerifyWebhookSignature.php b/src/Http/Middleware/VerifyWebhookSignature.php new file mode 100644 index 0000000..f79fdb0 --- /dev/null +++ b/src/Http/Middleware/VerifyWebhookSignature.php @@ -0,0 +1,114 @@ +config = $config; + } + + /** + * Handle an incoming request. + * + * @param \Closure(\Illuminate\Http\Request): (\Symfony\Component\HttpFoundation\Response) $next + * + * @throws \Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException + */ + public function handle(Request $request, Closure $next): Response + { + try { + $this->verifySignature($request); + } catch (SignatureException $e) { + throw new AccessDeniedHttpException($e->getMessage(), $e); + } + + return $next($request); + } + + /** + * Verify the Mux webhook signature. + * + * @throws \MartinBean\Laravel\Mux\Exceptions\SignatureException + */ + protected function verifySignature(Request $request): void + { + $timestamp = $this->extractTimestamp($request->header('Mux-Signature')); + $signature = $this->extractSignature($request->header('Mux-Signature')); + + $payload = sprintf('%s.%s', $timestamp, $request->getContent()); + $expectedSignature = $this->computeSignature($payload, $this->config->get('mux.webhook.secret')); + + if (! hash_equals($expectedSignature, $signature)) { + throw new SignatureException('Signature does not match the expected signature for the payload'); + } + + // TODO: Check if timestamp is within tolerance + } + + /** + * Extract the timestamp in the signature header. + * + * @throws \MartinBean\Laravel\Mux\Exceptions\SignatureException + */ + protected function extractTimestamp(string $header): int + { + $items = explode(',', $header); + + foreach ($items as $item) { + [$key, $value] = explode('=', $item, 2); + + if ($key === 't') { + if (is_numeric($value)) { + return (int) $value; + } + } + } + + throw new SignatureException('Unable to extract timestamp from header'); + } + + /** + * Extract the signature in the signature header. + * + * @throws \MartinBean\Laravel\Mux\Exceptions\SignatureException + */ + protected function extractSignature(string $header): string + { + $items = explode(',', $header); + + foreach ($items as $item) { + [$key, $value] = explode('=', $item, 2); + + if ($key === 'v1') { + return $value; + } + } + + throw new SignatureException('Unable to extract signature from header'); + } + + /** + * Compute the signature for the given payload and secret. + */ + protected function computeSignature(string $payload, string $secret): string + { + return hash_hmac('sha256', $payload, $secret); + } +} diff --git a/src/MuxServiceProvider.php b/src/MuxServiceProvider.php new file mode 100644 index 0000000..c2cea0b --- /dev/null +++ b/src/MuxServiceProvider.php @@ -0,0 +1,60 @@ +registerConfiguration(); + } + + /** + * Bootstrap any package services. + */ + public function boot(): void + { + $this->configurePublishing(); + $this->configureRouting(); + } + + /** + * Register the default Mux API configuration. + */ + protected function registerConfiguration(): void + { + $this->app->singleton(Configuration::class, function (): Configuration { + return Configuration::getDefaultConfiguration() + ->setUsername($this->app->make('config')->get('mux.client_id')) + ->setPassword($this->app->make('config')->get('mux.client_secret')); + }); + + $this->mergeConfigFrom(__DIR__ . '/../config/mux.php', 'mux'); + } + + /** + * Configure publishing for the package. + */ + protected function configurePublishing(): void + { + if ($this->app->runningInConsole()) { + $this->publishes([ + __DIR__ . '/../config/mux.php' => $this->app->configPath('mux.php'), + ], 'mux-config'); + } + } + + /** + * Configure routing for the package. + */ + protected function configureRouting(): void + { + $this->loadRoutesFrom(__DIR__ . '/../routes/web.php'); + } +} diff --git a/testbench.yaml b/testbench.yaml new file mode 100644 index 0000000..1a40078 --- /dev/null +++ b/testbench.yaml @@ -0,0 +1,2 @@ +providers: + - MartinBean\Laravel\Mux\MuxServiceProvider diff --git a/tests/TestCase.php b/tests/TestCase.php new file mode 100644 index 0000000..11efac0 --- /dev/null +++ b/tests/TestCase.php @@ -0,0 +1,11 @@ +withoutMiddleware(VerifyWebhookSignature::class) + ->postJson('/mux/webhook', [ + 'type' => 'test', + ]) + ->assertSuccessful(); + + Event::assertDispatched(function (WebhookReceived $event): bool { + $this->assertEqualsCanonicalizing( + expected: [ + 'type' => 'test', + ], + actual: $event->payload, + ); + + return true; + }); + } +}