🎥 Make videos programmatically with React
integrate feedback and finish documentation
Paul Kuhle4c1dfbf85fe1
diff --git a/packages/docs/components/Spinner.tsx b/packages/docs/components/Spinner.tsxnew file mode 100644index 0000000000..b706806efa--- /dev/null+++ b/packages/docs/components/Spinner.tsx@@ -0,0 +1,12 @@+import React from "react";++const css: React.CSSProperties = {+ border: "10px solid #f3f3f3",+ borderTop: "10px solid var(--ifm-color-primary)",+ borderRadius: "50%",+ width: "80px",+ height: "80px",+ animation: "spin 1s linear infinite",+};++export const Spinner: React.FC = () => <div style={css} />;diff --git a/packages/docs/components/TextInput.tsx b/packages/docs/components/TextInput.tsxindex 85aa6c5006..252e656dcf 100644--- a/packages/docs/components/TextInput.tsx+++ b/packages/docs/components/TextInput.tsx@@ -1,4 +1,4 @@-import type { DetailedHTMLProps} from "react";+import type { DetailedHTMLProps } from "react";import React, { useCallback, useState } from "react";const LIGHT_BLUE = "#42e9f5";@@ -34,7 +34,7 @@ type Props = Omit<"onFocus" | "onBlur">;-export const CoolInput: React.FC<Props> = (props) => {+export const CoolInput: React.FC<Props> = ({ style, ...props }) => {const [focus, setFocused] = useState(false);const onFocus = useCallback(() => {@@ -47,7 +47,12 @@ export const CoolInput: React.FC<Props> = (props) => {return (<div style={backgroundStyle(focus)}>- <input style={inputStyle} {...props} onFocus={onFocus} onBlur={onBlur} />+ <input+ style={{ ...inputStyle, ...style }}+ {...props}+ onFocus={onFocus}+ onBlur={onBlur}+ /></div>);};diff --git a/packages/docs/components/lambda/webhook-test.tsx b/packages/docs/components/lambda/webhook-test.tsxnew file mode 100644index 0000000000..acd89da553--- /dev/null+++ b/packages/docs/components/lambda/webhook-test.tsx@@ -0,0 +1,188 @@+import React, { useCallback, useState } from "react";+import { BlueButton } from "../layout/Button";+import { Spinner } from "../Spinner";+import { CoolInput } from "../TextInput";++// This is a re-implementation of the calculateSignature function+// used in @remotion/lambda. This version uses the Crypto Web APIs+// instead of the NodeJS Crypto library and can therefore run in the browser.+async function calculateSignature(payload: string, secret?: string) {+ if (!secret) {+ return "NO_SECRET_PROVIDED";+ }++ const enc = new TextEncoder();+ const algorithm = { name: "HMAC", hash: "SHA-512" };+ const key = await crypto.subtle.importKey(+ "raw",+ enc.encode(secret),+ algorithm,+ false,+ ["sign", "verify"]+ );+ const signature = await crypto.subtle.sign(+ algorithm.name,+ key,+ enc.encode(payload)+ );+ const digest = Array.from(new Uint8Array(signature))+ .map((x) => x.toString(16).padStart(2, "0"))+ .join("");+ return `sha512=${digest}`;+}++const buttonFlex: React.CSSProperties = {+ paddingBottom: 48,+ paddingTop: 8,+ display: "flex",+ justifyContent: "flex-start",+ gap: 16,+};++const inputFlex: React.CSSProperties = {+ paddingBottom: 16,+ paddingTop: 8,+ display: "flex",+ flexDirection: "column",+ gap: 16,+};++export const WebhookTest: React.FC = () => {+ const [request, setRequest] = useState({});+ const [response, setResponse] = useState<Object | null>(null);+ const [responseStatus, setResponseStatus] = useState<null | boolean>(null);+ const [loading, setLoading] = useState(false);+ const [data, setData] = useState({+ url: "http://localhost:8080/webhook",+ secret: "",+ });+ const handleWebhook = useCallback(+ async (type: "success" | "error" | "timeout") => {+ setLoading(true);+ setRequest({});+ setResponseStatus(null);+ setResponse(null);+ const payload = {+ result: type,+ renderId: 'demo-render-id',+ bucketName: 'demo-bucket-name',+ expectedBucketOwner: 'demo-bucket-owner',+ ...((type === 'success') && {+ outputUrl: 'https://www.example.com',+ outputFile: 'demo-output.mp4',+ timeToFinish: 1500,+ }),+ lambdaErrors: [],+ ...((type === 'error') && {+ errors: [{+ message: "demo-error-message",+ name: "demo-error-name",+ stack: "demo-error-stack",+ }],+ })+ };+ const stringifiedPayload = JSON.stringify(payload);+ const req: RequestInit = {+ method: "POST",+ mode: "cors",+ headers: {+ "Content-Type": "application/json",+ "X-Remotion-Signature": await calculateSignature(+ stringifiedPayload,+ data.secret+ ),+ "X-Remotion-Status": type,+ "X-Remotion-Mode": 'demo',+ },+ body: stringifiedPayload,+ };+ fetch(data.url, req)+ .then((res) => {+ setResponseStatus(res.ok);+ return res.json();+ })+ .then((res) => {+ setResponse(res);+ })+ .catch((err) => {+ setResponse(err);+ })+ .finally(() => {+ setRequest({ ...req, body: payload });+ setLoading(false);+ });+ },+ [data.secret, data.url]+ );+ return (+ <div>+ <div style={inputFlex}>+ <div style={{ display: "flex", flexDirection: "column" }}>+ <span style={{ paddingBottom: 8 }}>Your webhook URL:</span>+ <CoolInput+ style={{ width: "100%" }}+ placeholder="Your webhook endpoint"+ value={data.url}+ onChange={(e) =>+ setData((prev) => ({ ...prev, url: e.target.value }))+ }+ />+ </div>+ <div style={{ display: "flex", flexDirection: "column" }}>+ <span style={{ paddingBottom: 8 }}>Your webhook secret:</span>+ <CoolInput+ style={{ width: "100%" }}+ placeholder="Your webhook secret"+ value={data.secret}+ onChange={(e) =>+ setData((prev) => ({ ...prev, secret: e.target.value }))+ }+ />+ </div>+ </div>+ <div style={buttonFlex}>+ <BlueButton+ size="sm"+ fullWidth={false}+ loading={loading}+ onClick={() => handleWebhook("success")}+ >+ Send success+ </BlueButton>+ <BlueButton+ size="sm"+ fullWidth={false}+ loading={loading}+ onClick={() => handleWebhook("timeout")}+ >+ Send timeout+ </BlueButton>+ <BlueButton+ size="sm"+ fullWidth={false}+ loading={loading}+ onClick={() => handleWebhook("error")}+ >+ Send error+ </BlueButton>+ </div>+ {/* results */}+ {loading ? <div style={{ width: '100%', display: 'flex', justifyContent: 'center'}}><Spinner /></div> : null}+ {response ? (+ <>+ <span style={{ paddingBottom: 8 }}>What we sent:</span>+ <pre>{JSON.stringify(request, null, 2)}</pre>+ <span style={{ paddingBottom: 8 }}>What we received:</span>+ <pre>+ {responseStatus ? (+ <div style={{ color: "green" }}>response ok</div>+ ) : (+ <div style={{ color: "red" }}>response not ok</div>+ )}+ {JSON.stringify(response, null, 2)}+ </pre>+ </>+ ) : null}+ </div>+ );+};diff --git a/packages/docs/docs/lambda/rendermediaonlambda.md b/packages/docs/docs/lambda/rendermediaonlambda.mdindex 6ba6689cab..411006dece 100644--- a/packages/docs/docs/lambda/rendermediaonlambda.md+++ b/packages/docs/docs/lambda/rendermediaonlambda.md@@ -209,41 +209,48 @@ Accepted values:The default for Lambda is `swangle`, but `null` elsewhere.:::-## Return value+### `overwrite`-Returns a promise resolving to an object containing two properties: `renderId`, `bucketName`, `cloudWatchLogs`. Those are useful for passing to `getRenderProgress()`+_available from v3.2.25_-### `renderId`+If a custom out name is specified and a file already exists at this key in the S3 bucket, decide whether that file will be deleted before the render begins. Default `false`.-A unique alphanumeric identifier for this render. Useful for obtaining status and finding the relevant files in the S3 bucket.+An existing file at the output S3 key will conflict with the render and must be deleted beforehand. If this setting is `false` and a conflict occurs, an error will be thrown.-### `bucketName`+### `webhook`-The S3 bucket name in which all files are being saved.+_optional, available from v3.2.26_-### `cloudWatchLogs`+If specified, Remotion will send a POST request to the provided endpoint to notify your application when the Lambda rendering process finishes, errors out or times out.-_available from v3.2.10_+[See here for detailed instructions on how to set up your webhook](/docs/lambda/webhooks#response).-A link to CloudWatch (if you haven't disabled it) that you can visit to see the logs for the render.+### `webhookSecret`-### `overwrite`+_optional, available from v3.2.26_-_available from v3.2.25_+If you pass a webhook secret, the request headers of the webhook will include a cryptographic signature that you can use to [validate incoming webhooks](/docs/lambda/webhooks#validate-webhooks).-If a custom out name is specified and a file already exists at this key in the S3 bucket, decide whether that file will be deleted before the render begins. Default `false`.+We recommend you generate this secret using a service like [randomkeygen.com](https://randomkeygen.com/).-An existing file at the output S3 key will conflict with the render and must be deleted beforehand. If this setting is `false` and a conflict occurs, an error will be thrown.-### `webhook`+## Return value-_optional, available from v3.2.XX_+Returns a promise resolving to an object containing two properties: `renderId`, `bucketName`, `cloudWatchLogs`. Those are useful for passing to `getRenderProgress()`-If specified, Remotion will send a POST request to the provided endpoint to notify your application when the Lambda rendering process finishes, errors out or times out.+### `renderId`-The request headers include a cryptographic signature that you can use to [validate incoming webhooks](/docs/lambda/validate-webhooks).+A unique alphanumeric identifier for this render. Useful for obtaining status and finding the relevant files in the S3 bucket.-DOCUMENT RESPONSE+### `bucketName`++The S3 bucket name in which all files are being saved.++### `cloudWatchLogs`++_available from v3.2.10_++A link to CloudWatch (if you haven't disabled it) that you can visit to see the logs for the render.## See alsodiff --git a/packages/docs/docs/lambda/validate-webhooks.md b/packages/docs/docs/lambda/validate-webhooks.mddeleted file mode 100644index 365a74ee1c..0000000000--- a/packages/docs/docs/lambda/validate-webhooks.md+++ /dev/null@@ -1,25 +0,0 @@-----sidebar_label: Validate Webhooks-title: Validate Webhooks-slug: /lambda/validate-webhooks------```javascript-import * as Crypto from "crypto";--// Express API endpoint-router.post("/my-remotion-webhook-endpoint", (req, res) => {- const hmac = Crypto.createHmac("sha1", REMOTION_AWS_SECRET_ACCESS_KEY);- const signature = `sha1=${hmac- .update(JSON.stringify(req.body))- .digest("hex")}`;-- if (signature !== req.header("X-Remotion-Signature")) {- // Request wasn't sent by Remotion- // ...- } else {- // Request was sent by Remotion- // ...- }-});-```diff --git a/packages/docs/docs/lambda/webhooks.md b/packages/docs/docs/lambda/webhooks.mdnew file mode 100644index 0000000000..0dc7bc9848--- /dev/null+++ b/packages/docs/docs/lambda/webhooks.md@@ -0,0 +1,170 @@+---+sidebar_label: Webhooks+title: Webhooks+slug: /lambda/webhooks+---++import { 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.++Refer to the CLI documentation to [learn how to launch a rendering process with webhooks enabled](/docs/lambda/rendermediaonlambda#wenhook).++## Setup++You will need to set up an API endpoint with a POST request handler. Make sure that the endpoint is reachable and accepts requests from AWS.++:::info+If you run the webhook endpoint on your local machine (i.e. on `localhost`), you will need to set up a public reverse proxy using a tool like [ngrok](https://ngrok.com/).+:::info++## Response++Every webhook has the following headers:++```json+{+ "Content-Type": "application/json",+ "X-Remotion-Mode": "production" | "demo",+ "X-Remotion-Signature": "sha1=HASHED_SIGNATURE" | "NO_SECRET_PROVIDED",+ "X-Remotion-Status": "success" | "timeout" | "error",+}+```++You can use these headers to verify the authenticity of the request, to check the status of your rendering process and to check whether the webhook was called from production code deployed to AWS or a demo application such the tool below or your own test suite.++The 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",+ }],+}+```++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).++If the render process times out, the reponse body will not contain any other fields.++The `outputUrl`, `outputFile` and `timeToFinish` keys are only returned if the render was successful. Note that a successful render process may still have non-fatal `lambdaErrors`:++```json+{+ "s3Location": "string",+ "explanation": "string" | null,+ "type": "renderer" | "browser" | "stitcher",+ "message": "string",+ "name": "string",+ "stack": "string",+ "frame": "number"| null,+ "chunk": "number"| null,+ "isFatal": "boolean",+ "attempt": "number",+ "willRetry": "boolean",+ "totalAttempts": "number",+ "tmpDir": {+ "files": [{+ "filename": "string",+ "size": "number",+ }],+ "total": "number"+ } | null,+}+```++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`.++## Validate Webhooks++Remotion will sign all webhook requests if you provide a webhook secret in the CLI arguments.++:::warning+If you don't provide a secret, the `X-Remotion-Signature` will be set to `NO_SECRET_PROVIDED`. It is not possible to verify the authenticity and data integrity of a webhook request that is sent with a `NO_SECRET_PROVIDED` signature. If you want to verify incoming webhooks, you must provide a webhook secret.+:::warn++Remotion uses [HMAC](https://en.wikipedia.org/wiki/HMAC) with the [SHA-512 algorithm](https://en.wikipedia.org/wiki/SHA-2) to cryptographically sign the webhook requests it sends. This allows you to verify the authenticity and data integrity of incoming webhook requests.++In order to verify a webhook request, you will need to create a hex digest of a SHA-512 HMAC signature using your provided webhook key and the request body. If it matches the `X-Remotion-Signature` header, the request was indeed sent by Remotion and its request body is complete.++If it does not match, either the data integrity is compromised and the request body is incomplete or the request was not sent by Remotion.++This is how Remotion calculates the signature:++```javascript+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 signature;+}+```++In your webhook endpoint, the `payload` parameter is the request body and the `secret` parameter is your webhook secret.++## Example webhook endpoint++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.++```javascript+import express from "express";+import bodyParser from "body-parser";+import * as Crypto from "crypto";++const router = express();++// You'll need to add a JSON parser middleware globally or+// for the webhook route in order to get access to the request+// body.+const jsonParser = bodyParser.json();++// Express API endpoint+router.post("/my-remotion-webhook-endpoint", jsonParser, (req, res) => {+ if (signature === "NO_SECRET_PROVIDED") {+ // webhook request is not signed+ }++ const hmac = Crypto.createHmac("sha512", WEBHOOK_SECRET);+ const signature = `sha512=${hmac+ .update(JSON.stringify(req.body))+ .digest("hex")}`;++ 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+ // ...+ } else {+ // Request was NOT sent by Remotion or has an incomplete request body+ // ...+ }+});+```++## Test your webhook endpoint++You 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"`.++:::info+This 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.+- You can use a server listening on `localhost` and don't need to use a reverse proxy.+:::info++<WebhookTest />diff --git a/packages/docs/sidebars.js b/packages/docs/sidebars.jsindex 11e16dbd12..065b525275 100644--- a/packages/docs/sidebars.js+++ b/packages/docs/sidebars.js@@ -314,7 +314,7 @@ module.exports = {"lambda/custom-layers","lambda/custom-destination","lambda/checklist",- "lambda/validate-webhooks",+ "lambda/webhooks",{type: "category",label: "Troubleshooting",diff --git a/packages/docs/src/css/custom.css b/packages/docs/src/css/custom.cssindex 0e87303d50..f744bb62e1 100644--- a/packages/docs/src/css/custom.css+++ b/packages/docs/src/css/custom.css@@ -138,3 +138,13 @@ code {.no-scroll-bar::-webkit-scrollbar {display: none;}++@keyframes spin {+ 0% {+ transform: rotate(0deg);+ }+ 100% {+ transform: rotate(360deg);+ }+}+diff --git a/packages/lambda/src/api/render-media-on-lambda.ts b/packages/lambda/src/api/render-media-on-lambda.tsindex aee6c1efd2..b55c426f89 100644--- a/packages/lambda/src/api/render-media-on-lambda.ts+++ b/packages/lambda/src/api/render-media-on-lambda.ts@@ -49,6 +49,7 @@ export type RenderMediaOnLambdaInput = {muted?: boolean;overwrite?: boolean;webhook?: string+ webhookSecret?: string};export type RenderMediaOnLambdaOutput = {@@ -106,6 +107,7 @@ export const renderMediaOnLambda = async ({muted,overwrite,webhook,+ webhookSecret}: RenderMediaOnLambdaInput): Promise<RenderMediaOnLambdaOutput> => {const actualCodec = validateLambdaCodec(codec);validateServeUrl(serveUrl);@@ -147,6 +149,7 @@ export const renderMediaOnLambda = async ({version: VERSION,overwrite: overwrite ?? false,webhook,+ webhookSecret,},region,});diff --git a/packages/lambda/src/cli/args.ts b/packages/lambda/src/cli/args.tsindex fff0519d05..81082a6797 100644--- a/packages/lambda/src/cli/args.ts+++ b/packages/lambda/src/cli/args.ts@@ -28,6 +28,7 @@ type LambdaCommandLineOptions = {['custom-role-arn']: string | undefined;privacy: Privacy;webhook: string | undefined;+ webhookSecret: string | undefined;};export const parsedLambdaCli = minimist<LambdaCommandLineOptions>(diff --git a/packages/lambda/src/cli/commands/render/render.ts b/packages/lambda/src/cli/commands/render/render.tsindex 9167f14297..4341d898e6 100644--- a/packages/lambda/src/cli/commands/render/render.ts+++ b/packages/lambda/src/cli/commands/render/render.ts@@ -111,7 +111,8 @@ export const renderCommand = async (args: string[]) => {concurrencyPerLambda: parsedLambdaCli['concurrency-per-lambda'],muted,overwrite,- webhook: parsedLambdaCli.webhook ?? undefined+ webhook: parsedLambdaCli.webhook ?? undefined,+ webhookSecret: parsedLambdaCli.webhookSecret ?? undefined});const totalSteps = outName ? 5 : 4;diff --git a/packages/lambda/src/functions/helpers/write-lambda-error.ts b/packages/lambda/src/functions/helpers/write-lambda-error.tsindex ada608e4ad..d99d25a3a2 100644--- a/packages/lambda/src/functions/helpers/write-lambda-error.ts+++ b/packages/lambda/src/functions/helpers/write-lambda-error.ts@@ -6,7 +6,7 @@ import {lambdaWriteFile} from './io';import {errorIsOutOfSpaceError} from './is-enosp-err';export type LambdaErrorInfo = {- type: 'renderer' | 'browser' | 'stitcher';+ type: 'renderer' | 'browser' | 'stitcher' | 'webhook';message: string;name: string;stack: string;diff --git a/packages/lambda/src/functions/launch.ts b/packages/lambda/src/functions/launch.tsindex f0093a6291..50645ec073 100644--- a/packages/lambda/src/functions/launch.ts+++ b/packages/lambda/src/functions/launch.ts@@ -100,8 +100,16 @@ const innerLaunchHandler = async (params: LambdaPayload, options: Options) => {try {await invokeWebhook({url: params.webhook,+ secret: params.webhookSecret,type: 'timeout',renderId: params.renderId,+ expectedBucketOwner: options.expectedBucketOwner,+ bucketName: params.bucketName,+ outputUrl: undefined,+ errors: [],+ lambdaErrors: [],+ outputFile: undefined,+ timeToFinish: undefined,});webhookInvoked = true;} catch (err) {@@ -109,6 +117,24 @@ const innerLaunchHandler = async (params: LambdaPayload, options: Options) => {throw err;}+ await writeLambdaError({+ bucketName: params.bucketName,+ errorInfo: {+ type: 'webhook',+ message: (err as Error).message,+ name: (err as Error).name as string,+ stack: (err as Error).stack as string,+ tmpDir: null,+ frame: 0,+ chunk: 0,+ isFatal: false,+ attempt: 1,+ willRetry: false,+ totalAttempts: 1,+ },+ renderId: params.renderId,+ expectedBucketOwner: options.expectedBucketOwner,+ });console.log('Failed to invoke webhook:');console.log(err);}@@ -501,6 +527,11 @@ const innerLaunchHandler = async (params: LambdaPayload, options: Options) => {jobs,});+ const outputUrl = getOutputUrlFromMetadata(+ renderMetadata,+ params.bucketName,+ customCredentials+ )const postRenderData = createPostRenderData({expectedBucketOwner: options.expectedBucketOwner,region: getCurrentRegionInFunction(),@@ -514,11 +545,7 @@ const innerLaunchHandler = async (params: LambdaPayload, options: Options) => {outputFile: {lastModified: Date.now(),size: outputSize.size,- url: getOutputUrlFromMetadata(- renderMetadata,- params.bucketName,- customCredentials- ),+ url: outputUrl,},});await finalEncodingProgressProm;@@ -543,8 +570,16 @@ const innerLaunchHandler = async (params: LambdaPayload, options: Options) => {try {await invokeWebhook({url: params.webhook,+ secret: params.webhookSecret,type: 'success',renderId: params.renderId,+ expectedBucketOwner: options.expectedBucketOwner,+ bucketName: params.bucketName,+ outputUrl,+ errors: [],+ lambdaErrors: postRenderData.errors,+ outputFile: postRenderData.outputFile,+ timeToFinish: postRenderData.timeToFinish});webhookInvoked = true;} catch (err) {@@ -552,6 +587,24 @@ const innerLaunchHandler = async (params: LambdaPayload, options: Options) => {throw err;}+ await writeLambdaError({+ bucketName: params.bucketName,+ errorInfo: {+ type: 'webhook',+ message: (err as Error).message,+ name: (err as Error).name as string,+ stack: (err as Error).stack as string,+ tmpDir: null,+ frame: 0,+ chunk: 0,+ isFatal: false,+ attempt: 1,+ willRetry: false,+ totalAttempts: 1,+ },+ renderId: params.renderId,+ expectedBucketOwner: options.expectedBucketOwner,+ });console.log('Failed to invoke webhook:');console.log(err);}@@ -596,14 +649,40 @@ export const launchHandler = async (try {await invokeWebhook({url: params.webhook,+ secret: params.webhookSecret,type: 'error',renderId: params.renderId,+ expectedBucketOwner: options.expectedBucketOwner,+ bucketName: params.bucketName,+ lambdaErrors: [],+ errors: [err as Error],+ outputUrl: undefined,+ outputFile: undefined,+ timeToFinish: undefined,});} catch (error) {if (process.env.NODE_ENV === 'test') {throw error;}+ await writeLambdaError({+ bucketName: params.bucketName,+ errorInfo: {+ type: 'webhook',+ message: (err as Error).message,+ name: (err as Error).name as string,+ stack: (err as Error).stack as string,+ tmpDir: null,+ frame: 0,+ chunk: 0,+ isFatal: false,+ attempt: 1,+ willRetry: false,+ totalAttempts: 1,+ },+ renderId: params.renderId,+ expectedBucketOwner: options.expectedBucketOwner,+ });console.log('Failed to invoke webhook:');console.log(error);}diff --git a/packages/lambda/src/functions/start.ts b/packages/lambda/src/functions/start.tsindex ebb2192e4a..2b05ba1b8b 100644--- a/packages/lambda/src/functions/start.ts+++ b/packages/lambda/src/functions/start.ts@@ -76,6 +76,7 @@ export const startHandler = async (params: LambdaPayload, options: Options) => {muted: params.muted,overwrite: params.overwrite,webhook: params.webhook,+ webhookSecret: params.webhookSecret,};await getLambdaClient(getCurrentRegionInFunction()).send(new InvokeCommand({diff --git a/packages/lambda/src/shared/constants.ts b/packages/lambda/src/shared/constants.tsindex 2c6a1e3e91..6c92cdaa99 100644--- a/packages/lambda/src/shared/constants.ts+++ b/packages/lambda/src/shared/constants.ts@@ -227,6 +227,7 @@ export type LambdaPayloads = {version: string;overwrite: boolean;webhook: string | undefined;+ webhookSecret: string | undefined;};launch: {type: LambdaRoutines.launch;@@ -258,6 +259,7 @@ export type LambdaPayloads = {muted: boolean;overwrite: boolean;webhook: string | undefined;+ webhookSecret: string | undefined;};status: {type: LambdaRoutines.status;diff --git a/packages/lambda/src/shared/invoke-webhook.ts b/packages/lambda/src/shared/invoke-webhook.tsindex 05f0e8941a..2d774c3924 100644--- a/packages/lambda/src/shared/invoke-webhook.ts+++ b/packages/lambda/src/shared/invoke-webhook.ts@@ -1,16 +1,22 @@import * as Crypto from 'crypto';import http from 'http';import https from 'https';+import type {EnhancedErrorInfo} from '../functions/helpers/write-lambda-error';/*** @description Calculates cryptographically secure signature for webhooks using Hmac.- * @link https://remotion.dev/docs/lambda/validate-webhooks+ * @link https://remotion.dev/docs/lambda/webhooks#validate-webhooks* @param payload Stringified request body to encode in the signature.+ * @param secret User-provided webhook secret used to sign the request.+ * @returns {string} Calculated signature*/-export function calculateSignature(payload: string) {- const secret = 'INSECURE_DEFAULT_SECRET';- const hmac = Crypto.createHmac('sha1', secret);- const signature = 'sha1=' + hmac.update(payload).digest('hex');+export 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 signature;}@@ -18,6 +24,14 @@ export type InvokeWebhookInput = {url: string;type: 'success' | 'error' | 'timeout';renderId: string;+ secret: string | undefined;+ expectedBucketOwner: string;+ bucketName: string;+ outputUrl: string | undefined;+ lambdaErrors: EnhancedErrorInfo[];+ errors: Error[];+ outputFile: string | undefined;+ timeToFinish: number | undefined;};const getWebhookClient = (url: string) => {@@ -41,9 +55,45 @@ export const mockableHttpClients = {* @description Calls a webhook.* @link https://remotion.dev/docs/lambda/rendermediaonlambda#webhook* @param params.url URL of webhook to call.+ * @param params.renderId assigned render ID.+ * @param params.secret webhook secret provided by the user.+ * @param params.bucketName S3 bucket name.+ * @param params.expectedBucketOwner owner of S3 bucket.+ * @param params.outputUrl URL of rendered media file.+ * @param params.lambdaErrors non-fatal errors that have occurred during the render process.+ * @param params.errors fatal errors that have been thrown during the render process.+ * @param params.outputFile output file.+ * @param params.timeToFinish time to finish of rendering process.+ * @returns {Promise<void>} Promise of HTTP request with resolve/reject to be used for error handling.*/-export function invokeWebhook({url, type, renderId}: InvokeWebhookInput) {- const payload = JSON.stringify({result: type, renderId});+export function invokeWebhook({+ url,+ type,+ renderId,+ secret,+ bucketName,+ expectedBucketOwner,+ outputUrl,+ lambdaErrors,+ errors,+ outputFile,+ timeToFinish,+}: InvokeWebhookInput) {+ const payload = JSON.stringify({+ result: type,+ renderId,+ bucketName,+ expectedBucketOwner,+ outputUrl,+ outputFile,+ timeToFinish,+ lambdaErrors,+ errors: errors.map((err) => ({+ message: err.message,+ name: err.name as string,+ stack: err.stack as string,+ })),+ });return new Promise<void>((resolve, reject) => {const req = getWebhookClient(url)(@@ -52,7 +102,8 @@ export function invokeWebhook({url, type, renderId}: InvokeWebhookInput) {method: 'POST',headers: {'Content-Type': 'application/json',- 'X-Remotion-Signature': calculateSignature(payload),+ "X-Remotion-Mode": 'production',+ 'X-Remotion-Signature': calculateSignature(payload, secret),'X-Remotion-Status': type,},timeout: 5000,@@ -61,7 +112,7 @@ export function invokeWebhook({url, type, renderId}: InvokeWebhookInput) {if (res.statusCode && res.statusCode > 299) {reject(new Error(- `Sent a webhook but got a status code of ${res.statusCode}`+ `Sent a webhook but got a status code of ${res.statusCode} with message '${res.statusMessage}'`));return;diff --git a/packages/lambda/src/test/integration/renders/gif.test.ts b/packages/lambda/src/test/integration/renders/gif.test.tsindex aa6fd94168..dff65487ff 100644--- a/packages/lambda/src/test/integration/renders/gif.test.ts+++ b/packages/lambda/src/test/integration/renders/gif.test.ts@@ -60,6 +60,7 @@ test('Should make a distributed GIF', async () => {version: VERSION,overwrite: true,webhook: undefined,+ webhookSecret: undefined,},extraContext);diff --git a/packages/lambda/src/test/integration/renders/old-version.test.ts b/packages/lambda/src/test/integration/renders/old-version.test.tsindex c95dae955f..c989ac93f8 100644--- a/packages/lambda/src/test/integration/renders/old-version.test.ts+++ b/packages/lambda/src/test/integration/renders/old-version.test.ts@@ -57,6 +57,7 @@ test('Should fail when using an incompatible version', async () => {version: VERSION,overwrite: true,webhook: undefined,+ webhookSecret: undefined,},extraContext)diff --git a/packages/lambda/src/test/integration/renders/other-bucket.test.ts b/packages/lambda/src/test/integration/renders/other-bucket.test.tsindex 29ba8942c8..8ebf8c0af0 100644--- a/packages/lambda/src/test/integration/renders/other-bucket.test.ts+++ b/packages/lambda/src/test/integration/renders/other-bucket.test.ts@@ -63,6 +63,7 @@ test('Should be able to render to another bucket', async () => {version: VERSION,overwrite: true,webhook: undefined,+ webhookSecret: undefined,},extraContext);diff --git a/packages/lambda/src/test/integration/renders/silent-audio.test.ts b/packages/lambda/src/test/integration/renders/silent-audio.test.tsindex e4ef27868f..637fa0f48c 100644--- a/packages/lambda/src/test/integration/renders/silent-audio.test.ts+++ b/packages/lambda/src/test/integration/renders/silent-audio.test.ts@@ -60,6 +60,7 @@ test('Should add silent audio if there is no audio', async () => {version: VERSION,overwrite: true,webhook: undefined,+ webhookSecret: undefined,},extraContext);diff --git a/packages/lambda/src/test/integration/renders/transparent-webm.test.ts b/packages/lambda/src/test/integration/renders/transparent-webm.test.tsindex 7899e3999c..02d5feec80 100644--- a/packages/lambda/src/test/integration/renders/transparent-webm.test.ts+++ b/packages/lambda/src/test/integration/renders/transparent-webm.test.ts@@ -63,6 +63,7 @@ test('Should make a transparent video', async () => {version: VERSION,overwrite: true,webhook: undefined,+ webhookSecret: undefined,},extraContext);diff --git a/packages/lambda/src/test/integration/webhooks.test.ts b/packages/lambda/src/test/integration/webhooks.test.tsindex 345e364243..36037c4fca 100644--- a/packages/lambda/src/test/integration/webhooks.test.ts+++ b/packages/lambda/src/test/integration/webhooks.test.ts@@ -87,6 +87,7 @@ describe('Webhooks', () => {version: VERSION,overwrite: true,webhook: TEST_URL,+ webhookSecret: 'TEST_SECRET'},extraContext);@@ -109,7 +110,7 @@ describe('Webhooks', () => {method: 'POST',headers: {'Content-Type': 'application/json',- 'X-Remotion-Signature': expect.stringContaining('sha1='),+ 'X-Remotion-Signature': expect.stringContaining('sha512='),'X-Remotion-Status': 'success',},timeout: 5000,@@ -153,6 +154,7 @@ describe('Webhooks', () => {version: VERSION,overwrite: true,webhook: TEST_URL,+ webhookSecret: 'TEST_SECRET'},extraContext);@@ -175,7 +177,7 @@ describe('Webhooks', () => {method: 'POST',headers: {'Content-Type': 'application/json',- 'X-Remotion-Signature': expect.stringContaining('sha1='),+ 'X-Remotion-Signature': expect.stringContaining('sha512='),'X-Remotion-Status': 'timeout',},timeout: 5000,diff --git a/packages/lambda/src/test/unit/invoke-webhook.test.ts b/packages/lambda/src/test/unit/invoke-webhook.test.tsindex 8550aff2a7..71bfb1283d 100644--- a/packages/lambda/src/test/unit/invoke-webhook.test.ts+++ b/packages/lambda/src/test/unit/invoke-webhook.test.ts@@ -1,8 +1,8 @@import {calculateSignature} from '../../shared/invoke-webhook';-test('calculateSignature should return correct sha1 signature', () => {- const signature = calculateSignature(JSON.stringify({payload: 'test'}))-- expect(signature).toEqual('sha1=01b2eb8a50128fbe37f67acc440fbaff1159c454');+test('calculateSignature should return correct sha512 signature', () => {+ const signature = calculateSignature(JSON.stringify({payload: 'test'}), 'INSECURE_DEFAULT_SECRET')+ console.error(signature)+ expect(signature).toEqual('sha512=faa8735b7bac44d521749b45aa2c95cb6204822f54eb18f85aeb30b9a29d309a138f6b7358653336c592a69e29eb696ccc4f2c6c20335d3deb76b09efd4b6a5d');});