🎥 Make videos programmatically with React
validateWebhookSignature() endpoint
Jonny Burgerf1f24367e17a
diff --git a/packages/docs/components/TableOfContents/lambda.tsx b/packages/docs/components/TableOfContents/lambda.tsxindex a627569690..7d09082b75 100644--- a/packages/docs/components/TableOfContents/lambda.tsx+++ b/packages/docs/components/TableOfContents/lambda.tsx@@ -82,6 +82,10 @@ export const TableOfContents: React.FC = () => {<strong>simulatePermissions()</strong><div>Ensure permissions are correctly set up</div></TOCItem>+ <TOCItem link="/docs/lambda/validatewebhooksignature">+ <strong>validateWebhookSignature()</strong>+ <div>Ensure permissions are correctly set up</div>+ </TOCItem></Grid></div>);diff --git a/packages/docs/docs/lambda/light-client.md b/packages/docs/docs/lambda/light-client.mdindex 209097d3c1..ced85cf637 100644--- a/packages/docs/docs/lambda/light-client.md+++ b/packages/docs/docs/lambda/light-client.md@@ -13,6 +13,8 @@ import {getFunctions,AwsRegion,RenderProgress,+ validateWebhookSignature,+ WebhookPayload} from "@remotion/lambda/client";```@@ -21,3 +23,5 @@ These functions don't have any Node.JS dependencies and can be bundled with a bu**We don't recommend calling these functions from the browser directly, as you will leak your AWS credentials.**Instead, this light client is meant to reduce the bundle size and avoid problems if you are calling Remotion Lambda APIs from another Lambda function and therefore need to bundle your function code.++Commonly, Next.JS serverless endpoints or similar use AWS Lambda functions under the hood, for which `@remotion/lambda/client` can be used.\ No newline at end of filediff --git a/packages/docs/docs/lambda/validatewebhooksignature.md b/packages/docs/docs/lambda/validatewebhooksignature.mdnew file mode 100644index 0000000000..4e747a1e6a--- /dev/null+++ b/packages/docs/docs/lambda/validatewebhooksignature.md@@ -0,0 +1,74 @@+---+id: validatewebhooksignature+title: validateWebhookSignature()+slug: /lambda/validatewebhooksignature+---++_Available from v3.2.30_++Validates the signature that was received by a [webhook](/docs/lambda/webhooks) endpoint is authentic and throws an error otherwise.++## API++The function accepts an object with three key-value pairs:++### `secret`++The same webhook secret that was passed to [`renderMediaOnLambda()`](/docs/lambda/rendermediaonlambda)'s webhook options.++### `body`++The body that was received by the endpoint.++### `signatureHeader`++The `X-Remotion-Signature` header from the request that was received by the endpoint.++## Example++In the following Next.JS webhook endpoint, an error gets thrown if the signature does not match the one expected one or is missing..++```tsx twoslash title="pages/api/webhook.ts"+type NextApiRequest = {+ body: string;+ header: (name: string) => string;+};+type NextApiResponse = {+ status: (code: number) => { json: (body: object) => void };+};+// ---cut---+import {+ validateWebhookSignature,+ WebhookPayload,+} from "@remotion/lambda/client";++export default async function handler(+ req: NextApiRequest,+ res: NextApiResponse+) {+ validateWebhookSignature({+ secret: process.env.WEBHOOK_SECRET as string,+ body: req.body,+ signatureHeader: req.header("X-Remotion-Signature") as string,+ });++ // If code reaches this path, the webhook is authentic.+ const payload = JSON.parse(req.body) as WebhookPayload;+ if (payload.type === "success") {+ // ...+ } else if (payload.type === "timeout") {+ // ...+ }++ res.status(200).json({+ success: true,+ });+}+```++See [Webhooks](/docs/lambda/webhooks) for an Express example.++## See also++- [Webhooks](/docs/lambda/webhooks)+- [Source code for this function](https://github.com/remotion-dev/remotion/blob/main/packages/lambda/src/bundle.ts)diff --git a/packages/docs/docs/lambda/webhooks.md b/packages/docs/docs/lambda/webhooks.mdindex fc427fbf41..ac3662aba6 100644--- a/packages/docs/docs/lambda/webhooks.md+++ b/packages/docs/docs/lambda/webhooks.md@@ -6,9 +6,9 @@ slug: /lambda/webhooksimport { WebhookTest } from "../../components/lambda/webhook-test";-When rendering on AWS Lambda, Remotion can send webhooks to notify you when the process terminates. This page describes the webhook payloads and how to set up a webhook API endpoint.+When rendering on AWS Lambda, Remotion can send webhooks to notify you when the render ends, successfully or with failures. This page describes the webhook payloads and how to set up a webhook API endpoint.-Refer to the CLI documentation to [learn how to launch a rendering process with webhooks enabled](/docs/lambda/rendermediaonlambda#wenhook).+Refer to the `renderMediaOnLambda()` documentation to [learn how to trigger a render with webhooks enabled](/docs/lambda/rendermediaonlambda#webhook).## Setup@@ -35,25 +35,38 @@ You can use these headers to verify the authenticity of the request, to check thThe request body has the following structure:-```json-{- "result": "success" | "timeout" | "error",- "renderId": "string",- "bucketName": "string",- "expectedBucketOwner": "string",- "outputUrl": "string",- "outputFile": "string",- "timeToFinish": "number",- "lambdaErrors": [],- "errors": [{- "message": "string",- "name": "string",- "stack": "string",- }],-}+```ts+type WebhookPayload =+ | {+ type: "error";+ errors: {+ message: string;+ name: string;+ stack: string;+ }[];+ renderId: string;+ expectedBucketOwner: string;+ bucketName: string;+ }+ | {+ type: "success";+ lambdaErrors: EnhancedErrorInfo[];+ outputUrl: string | undefined;+ outputFile: string | undefined;+ timeToFinish: number | undefined;+ renderId: string;+ expectedBucketOwner: string;+ bucketName: string;+ }+ | {+ type: "timeout";+ renderId: string;+ expectedBucketOwner: string;+ bucketName: string;+ };```-Note that only the `result`, `renderId`, `bucketName` and `expectedBucketOwner` will always be returned [just like they are returned by the CLI itself](/docs/lambda/rendermediaonlambda#return-value).+The fields [`renderId`](/docs/lambda/rendermediaonlambda#renderid), [`bucketName`](/docs/lambda/rendermediaonlambda#bucketname) will be returned [just like they are returned by `renderMediaOnLambda()` itself](/docs/lambda/rendermediaonlambda#return-value).If the render process times out, the reponse body will not contain any other fields.@@ -83,7 +96,7 @@ The `outputUrl`, `outputFile` and `timeToFinish` keys are only returned if the r}```-The `errors` array will contain the error message and stack trace of any _fatal_ error that occurs during the render process. The `errors` array will be empty if the status is not `error`.+The `errors` array will contain the error message and stack trace of any _fatal_ error that occurs during the render process.## Validate Webhooks@@ -102,28 +115,34 @@ If it does not match, either the data integrity is compromised and the request bThis is how Remotion calculates the signature:```javascript-import * as Crypto from 'crypto';+import * as Crypto from "crypto";function calculateSignature(payload: string, secret?: string) {if (!secret) {- return 'NO_SECRET_PROVIDED';- }- const hmac = Crypto.createHmac('sha512', secret);- const signature = 'sha512=' + hmac.update(payload).digest('hex');+ return "NO_SECRET_PROVIDED";+ }+ const hmac = Crypto.createHmac("sha512", secret);+ const signature = "sha512=" + hmac.update(payload).digest("hex");return signature;}```In your webhook endpoint, the `payload` parameter is the request body and the `secret` parameter is your webhook secret.-## Example webhook endpoint+Instead of validating the signature yourself, you can use the [`validateWebhookSignature()`](/docs/lambda/validatewebhooksignature) function to throw an error if the signature is invalid.-You can use any web framework and language to set up your webhook endpoint. The following example is written in JavaScript using the Express framework, but you can replicate the validation logic using a cryptography/HMAC library for your language.+## Example webhook endpoint (Express)-```javascript+You can use any web framework and language to set up your webhook endpoint. The following example is written in JavaScript using the Express framework.++```javascript title="server.js"import express from "express";import bodyParser from "body-parser";import * as Crypto from "crypto";+import {+ validateWebhookSignature,+ WebhookPayload,+} from "@remotion/lambda/client";const router = express();@@ -134,28 +153,68 @@ const jsonParser = bodyParser.json();// Express API endpointrouter.post("/my-remotion-webhook-endpoint", jsonParser, (req, res) => {- if (req.header("X-Remotion-Signature") === "NO_SECRET_PROVIDED") {- // webhook request is not signed- }+ validateWebhookSignature({+ signatureHeader: req.header("X-Remotion-Signature"),+ body: req.body,+ secret: process.env.WEBHOOK_SECRET as string+ });- const hmac = Crypto.createHmac("sha512", WEBHOOK_SECRET);- const signature = `sha512=${hmac- .update(JSON.stringify(req.body))- .digest("hex")}`;+ const status = req.header("X-Remotion-Status"); // success, timeout, error+ const mode = req.header("X-Remotion-Mode"); // demo or production- if (signature === req.header("X-Remotion-Signature")) {- // Request was sent by Remotion- const status = req.header("X-Remotion-Status"); // success, timeout, error- const mode = req.header("X-Remotion-Mode"); // demo or production- console.log(req.body); // parsed JSON response+ const payload = JSON.parse(req.body) as WebhookPayload;+ if (payload.type === "success") {// ...- } else {- // Request was NOT sent by Remotion or has an incomplete request body+ } else if (payload.type === "timeout") {// ...}});```+## Example webhook endpoint (Next.JS)++Similary, here is an example endpoint in Next.JS.++Since this endpoint is going to be executed in an AWS Lambda function on it's own, you want to import the Remotion functions from [`@remotion/lambda/client`](/docs/lambda/light-client).++```tsx twoslash title="pages/api/webhook.ts"+type NextApiRequest = {+ body: string;+ header: (name: string) => string;+};+type NextApiResponse = {+ status: (code: number) => { json: (body: object) => void };+};+// ---cut---+import {+ validateWebhookSignature,+ WebhookPayload,+} from "@remotion/lambda/client";++export default async function handler(+ req: NextApiRequest,+ res: NextApiResponse+) {+ validateWebhookSignature({+ secret: process.env.WEBHOOK_SECRET as string,+ body: req.body,+ signatureHeader: req.header("X-Remotion-Signature") as string,+ });++ // If code reaches this path, the webhook is authentic.+ const payload = JSON.parse(req.body) as WebhookPayload;+ if (payload.type === "success") {+ // ...+ } else if (payload.type === "timeout") {+ // ...+ }++ res.status(200).json({+ success: true,+ });+}+```+## Test your webhook endpointYou can use this tool to verify that your webhook endpoint is working properly. The tool will send an appropriate demo payload and log the response to the screen. All requests sent by this tool will have the `"X-Remotion-Mode"` header set to `"demo"`.@@ -163,8 +222,16 @@ You can use this tool to verify that your webhook endpoint is working properly.:::infoThis tool sends the demo webhook requests directly from your browser, which has the following implications:-- If your server uses CORS middleware, make sure your API endpoint is configured to accept requests from `remotion.dev`. This is necessary for this tool to work, but **not** for your production webhook endpoint.+- **CORS requirements**:+ - Make sure your API endpoint is configured to accept requests from `remotion.dev` by setting `"Access-Control-Allow-Origin": "true"`. This is necessary for this tool to work, but **not** for your production webhook endpoint.+ - You must set `"Access-Control-Allow-Headers": "X-CSRF-Token, X-Requested-With, Accept, Accept-Version, Content-Length, Content-MD5, Content-Type, Date, X-Api-Version, X-Remotion-Status, X-Remotion-Signature, X-Remotion-Mode"`+ - You must set `"Access-Control-Allow-Methods": "OPTIONS,POST"`.- You can use a server listening on `localhost` and don't need to use a reverse proxy.+:::info<WebhookTest />++## See also++- [validateWebhookSignature()](/docs/lambda/validatewebhooksignature)diff --git a/packages/docs/sidebars.js b/packages/docs/sidebars.jsindex 1ae7194b29..a767db566a 100644--- a/packages/docs/sidebars.js+++ b/packages/docs/sidebars.js@@ -171,6 +171,7 @@ module.exports = {"lambda/rendermediaonlambda","lambda/renderstillonlambda","lambda/simulatepermissions",+ "lambda/validatewebhooksignature",],},{diff --git a/packages/lambda/src/api/validate-webhook-signature.ts b/packages/lambda/src/api/validate-webhook-signature.tsnew file mode 100644index 0000000000..3ca398bd04--- /dev/null+++ b/packages/lambda/src/api/validate-webhook-signature.ts@@ -0,0 +1,46 @@+/**+ * @description Throws if the signature of the finish webhook is missing or inauthentic+ * @link https://remotion.dev/docs/lambda/validate-webhook-signature+ * @param params.secret The secret used for signing the webhook+ * @param params.body The body that was received by the endpoint+ * @param params.signatureHeader The `X-Remotion-Signature` header+ * @returns {void}+ */+export const validateWebhookSignature = ({+ secret,+ body,+ signatureHeader,+}: {+ secret: string;+ body: string;+ signatureHeader: string;+}) => {+ if (!secret) {+ throw new TypeError(+ "No 'secret' was provided to validateWebhookSignature()."+ );+ }++ if (!body) {+ throw new TypeError(+ "No 'body' was provided to validateWebhookSignature()."+ );+ }++ if (typeof require === 'undefined') {+ throw new Error('validateWebhookSignature can only be called from Node.JS');+ }++ const Crypto = require('crypto');++ const hmac = Crypto.createHmac('sha512', secret);+ const signature = `sha512=${hmac.update(JSON.stringify(body)).digest('hex')}`;++ if (!signatureHeader || signatureHeader === 'NO_SECRET_PROVIDED') {+ throw new Error('No webhook signature was provided');+ }++ if (signatureHeader !== signature) {+ throw new Error('Signatures do not match');+ }+};diff --git a/packages/lambda/src/client.ts b/packages/lambda/src/client.tsindex 95c9830cc7..22cf372954 100644--- a/packages/lambda/src/client.ts+++ b/packages/lambda/src/client.ts@@ -5,6 +5,7 @@ import {renderVideoOnLambda,} from './api/render-media-on-lambda';import {renderStillOnLambda} from './api/render-still-on-lambda';+import {validateWebhookSignature} from './api/validate-webhook-signature';import type {AwsRegion} from './pricing/aws-regions';import type {RenderProgress} from './shared/constants';import type {WebhookPayload} from './shared/invoke-webhook';@@ -15,5 +16,6 @@ export {renderStillOnLambda,getRenderProgress,getFunctions,+ validateWebhookSignature,};export type {AwsRegion, RenderProgress, WebhookPayload};diff --git a/packages/lambda/src/index.ts b/packages/lambda/src/index.tsindex b8193e8855..ae283daca1 100644--- a/packages/lambda/src/index.ts+++ b/packages/lambda/src/index.ts@@ -56,6 +56,7 @@ import type {RenderStillOnLambdaOutput,} from './api/render-still-on-lambda';import {renderStillOnLambda} from './api/render-still-on-lambda';+import {validateWebhookSignature} from './api/validate-webhook-signature';import type {LambdaLSInput, LambdaLsReturnType} from './functions/helpers/io';import {LambdaInternals} from './internals';import type {AwsRegion} from './pricing/aws-regions';@@ -88,6 +89,7 @@ export {getAwsClient,presignUrl,deleteRender,+ validateWebhookSignature,};export type {AwsRegion,