🎥 Make videos programmatically with React
Remove host access from canvas capture transfers
JonnyBurger9fc2814935f6
diff --git a/.agents/skills/canvas-capture-extension/SKILL.md b/.agents/skills/canvas-capture-extension/SKILL.mdindex cca1fc48b1..a231f9b04b 100644--- a/.agents/skills/canvas-capture-extension/SKILL.md+++ b/.agents/skills/canvas-capture-extension/SKILL.md@@ -27,7 +27,7 @@ the unpacked copy outside the checkout so deleting a worktree cannot break it.is installed, use `$install-canvas-capture-browser` to install one.3. Confirm that the installed directory contains `manifest.json`,- `background.js`, `capture.js`, `drag-image.js`, `logo.svg`, `content-scripts/receiver.js`,+ `background.js`, `capture.js`, `drag-image.js`, `shot-tools.js`, `logo.svg`,and the generated extension icons.## Develop with React and Vite@@ -45,6 +45,12 @@ the unpacked copy outside the checkout so deleting a worktree cannot break it.Use the separate development directory only for `bun run dev`. Continue usingthe production install directory above for manually loaded builds.+The Remotion pages receive recordings through `externally_connectable`+messaging; the extension does not inject a receiver content script. To test a+local destination, set `CANVAS_CAPTURE_HANDOFF_ORIGIN` (for example+`http://localhost:3000`) when running `bun run dev`. Production builds always+use `https://www.remotion.dev`.+To select another Chrome 157.0.8080.0 or newer browser, set`CANVAS_CAPTURE_BROWSER_EXECUTABLE` to its executable path when running`bun run dev`. Development uses the version-neutral@@ -71,7 +77,10 @@ To select another Chrome 157.0.8080.0 or newer browser, setnever from a worktree-local `dist` directory. WXT-managed development buildsuse the separate durable development directory documented above.- Enable `chrome://flags/#canvas-draw-element` and restart Chrome when the- experimental HTML-in-canvas API is unavailable.+ experimental HTML-in-canvas API is unavailable. Alternatively, launch with+ `--enable-features=CanvasDrawElement`; either method is sufficient. Do not add+ `--enable-blink-features=CanvasDrawElement`, which triggers Chrome's+ unsupported-command-line warning.Do not edit Chrome's `Preferences` or `Secure Preferences` files to move orreload the extension. Use Chrome's extensions page so its integrity metadatadiff --git a/.agents/skills/canvas-capture-extension/scripts/rebuild-extension.sh b/.agents/skills/canvas-capture-extension/scripts/rebuild-extension.shindex 638b495ac4..b4f0565f93 100755--- a/.agents/skills/canvas-capture-extension/scripts/rebuild-extension.sh+++ b/.agents/skills/canvas-capture-extension/scripts/rebuild-extension.sh@@ -61,7 +61,7 @@ fibun run make)-for required_file in manifest.json background.js capture.js drag-image.js logo.svg content-scripts/receiver.js; do+for required_file in manifest.json background.js capture.js drag-image.js shot-tools.js logo.svg; doif [[ ! -f "$dist_dir/$required_file" ]]; thenprintf 'Build did not produce %s\n' "$dist_dir/$required_file" >&2exit 1@@ -73,4 +73,4 @@ rsync -a --delete "$dist_dir/" "$install_dir/"printf 'Installed Remotion Canvas Capture in %s\n' "$install_dir"printf '%s\n' 'Canvas Capture requires Chrome 157.0.8080.0 or newer with Canvas Draw Element enabled.'-printf '%s\n' 'Open chrome://extensions manually, then click Reload or choose Load unpacked for this directory.'+printf '%s\n' 'Open chrome://extensions, then click Reload or choose Load unpacked for this directory.'diff --git a/.agents/skills/install-canvas-capture-browser/SKILL.md b/.agents/skills/install-canvas-capture-browser/SKILL.mdindex 0b9eac4eaf..68b603b0e0 100644--- a/.agents/skills/install-canvas-capture-browser/SKILL.md+++ b/.agents/skills/install-canvas-capture-browser/SKILL.md@@ -33,7 +33,12 @@ and video encoding configuration before allowing recording.'/Users/jonathanburger/Applications/Recorder Chrome.app/Contents/MacOS/Google Chrome for Testing' \--user-data-dir='/Users/jonathanburger/Library/Application Support/Remotion Canvas Capture' \--enable-features=CanvasDrawElement \- --enable-blink-features=CanvasDrawElement \--no-first-run \--no-default-browser-check```++ `--enable-features=CanvasDrawElement` is equivalent to enabling+ `chrome://flags/#canvas-draw-element` and restarting Chrome; either method is+ sufficient. Do not add `--enable-blink-features=CanvasDrawElement`: this+ developer override directly changes Blink's state and triggers Chrome's+ unsupported-command-line warning, even when the feature is supported.diff --git a/bun.lock b/bun.lockindex fb8ec105a0..d580634c52 100644--- a/bun.lock+++ b/bun.lock@@ -239,6 +239,7 @@"version": "4.0.535","dependencies": {"@remotion/design": "workspace:*",+ "@remotion/studio-shared": "workspace:*","mediabunny": "catalog:","react": "catalog:","react-dom": "catalog:",@@ -423,6 +424,7 @@"@remotion/paths": "workspace:*","@remotion/player": "workspace:*","@remotion/shapes": "workspace:*",+ "@remotion/studio-shared": "workspace:*","@remotion/timeline-utils": "workspace:*","@remotion/whisper-webgpu": "workspace:*","@vercel/remix": "2.16.7",diff --git a/packages/canvas-capture-extension/README.md b/packages/canvas-capture-extension/README.mdindex 70b37bf74b..aabe596993 100644--- a/packages/canvas-capture-extension/README.md+++ b/packages/canvas-capture-extension/README.md@@ -32,7 +32,6 @@ Launch it with a dedicated profile and the HTML-in-canvas feature enabled:'/Users/jonathanburger/Applications/Recorder Chrome.app/Contents/MacOS/Google Chrome for Testing' \--user-data-dir='/Users/jonathanburger/Library/Application Support/Remotion Canvas Capture' \--enable-features=CanvasDrawElement \- --enable-blink-features=CanvasDrawElement \--no-first-run \--no-default-browser-check```@@ -72,6 +71,24 @@ files change.The development extension is separate from the manually loaded productionextension, so its path and extension ID remain stable across worktrees.+To test a local handoff destination, set `CANVAS_CAPTURE_HANDOFF_ORIGIN` when+running `bun run dev`, for example `http://localhost:3000`. Production builds+always open `https://www.remotion.dev`.++## Opening a recording in Remotion++The extension stores the recording locally and opens `/new` or `/convert`+with a single-use transfer token and the extension ID in the URL fragment.+The destination page connects directly to the extension through+`externally_connectable` messaging. The extension checks the page origin,+destination path, tab ID, and token before sending the recording in chunks.+The page acknowledges receipt before the stored recording is deleted.++Transfer tokens expire after 10 minutes. Interrupted transfers can be retried+from the same destination tab until the token expires; expired recordings are+removed when the extension next starts or opens another recording. No receiver+content script or persistent host access is required.+## Build and installThe extension exposes `setup_shot`, `get_shot`, and `save_recording` to WebMCP-awarediff --git a/packages/canvas-capture-extension/README.public.md b/packages/canvas-capture-extension/README.public.mdindex 005736050d..f7d63a86b5 100644--- a/packages/canvas-capture-extension/README.public.md+++ b/packages/canvas-capture-extension/README.public.md@@ -8,7 +8,7 @@ HTML-in-canvas implementation.Canvas Capture requires Chrome 157.0.8080.0 or newer with Canvas Draw Element enabled.-Older Chrome versions cannot load the extension. In a supported Chrome version,+Chrome 155 and newer can install the extension and display the browser setup requirements. In a supported Chrome version,open `chrome://flags/#canvas-draw-element`, enable Canvas Draw Element, and restartChrome. The recorder shows a setup warning if the required APIs are unavailable;this does not necessarily mean the flag is disabled.diff --git a/packages/canvas-capture-extension/package.json b/packages/canvas-capture-extension/package.jsonindex 7e1686ba57..07f0963ea9 100644--- a/packages/canvas-capture-extension/package.json+++ b/packages/canvas-capture-extension/package.json@@ -11,6 +11,7 @@"make": "bunx --bun wxt build"},"dependencies": {+ "@remotion/studio-shared": "workspace:*","@remotion/design": "workspace:*","mediabunny": "catalog:","react": "catalog:",diff --git a/packages/canvas-capture-extension/src/background.ts b/packages/canvas-capture-extension/src/background.tsindex c87451f9d5..f5796dc6ba 100644--- a/packages/canvas-capture-extension/src/background.ts+++ b/packages/canvas-capture-extension/src/background.ts@@ -1,5 +1,6 @@import {browser} from 'wxt/browser';import {canvasSetupUrl} from './browser-requirements';+import {startCaptureHandoff} from './handoff-server';import {captureControllerMessageType,openCaptureSetupMessageType,@@ -7,6 +8,7 @@ import {} from './messages';export const startBackground = () => {+ startCaptureHandoff();browser.action.onClicked.addListener(async (tab) => {if (tab.id === undefined) {return;@@ -72,19 +74,5 @@ export const startBackground = () => {.create({url: canvasSetupUrl, active: true}).then(() => ({opened: true}));}-- if (- message.type !== 'remotion-canvas-capture-open' ||- !('captureId' in message) ||- typeof message.captureId !== 'string' ||- !('destination' in message) ||- (message.destination !== 'convert' && message.destination !== 'new')- ) {- return;- }-- const url = new URL(`https://www.remotion.dev/${message.destination}`);- url.searchParams.set('canvas-capture', message.captureId);- return browser.tabs.create({url: url.toString()});});};diff --git a/packages/canvas-capture-extension/src/entrypoints/receiver.content.ts b/packages/canvas-capture-extension/src/entrypoints/receiver.content.tsdeleted file mode 100644index 567d073c6a..0000000000--- a/packages/canvas-capture-extension/src/entrypoints/receiver.content.ts+++ /dev/null@@ -1,13 +0,0 @@-import {defineContentScript} from 'wxt/utils/define-content-script';-import {startReceiver} from '../receiver';--export default defineContentScript({- matches: [- 'https://remotion.dev/convert*',- 'https://www.remotion.dev/convert*',- 'https://remotion.dev/new*',- 'https://www.remotion.dev/new*',- ],- runAt: 'document_start',- main: startReceiver,-});diff --git a/packages/canvas-capture-extension/src/handoff-server.ts b/packages/canvas-capture-extension/src/handoff-server.tsnew file mode 100644index 0000000000..60fc18fed0--- /dev/null+++ b/packages/canvas-capture-extension/src/handoff-server.ts@@ -0,0 +1,244 @@+import {+ canvasCapturePortName,+ type CanvasCaptureResponse,+} from '@remotion/studio-shared/canvas-capture-handoff';+import {browser, type Browser} from 'wxt/browser';+import {+ getChunkKey,+ getMetadataKey,+ getStoredCapture,+ removeExpiredCaptures,+ removeStoredCapture,+ type StoredCaptureMetadata,+} from './handoff';++const handoffOrigin = import.meta.env.CANVAS_CAPTURE_HANDOFF_ORIGIN as string;++export const startCaptureHandoff = () => {+ const transfers = new Map<string, Browser.runtime.Port>();+ const completing = new Set<string>();+ removeExpiredCaptures().catch(() => undefined);++ browser.runtime.onMessage.addListener((message, sender) => {+ if (+ sender.id !== browser.runtime.id ||+ typeof message !== 'object' ||+ message === null ||+ message.type !== 'remotion-canvas-capture-open' ||+ typeof message.captureId !== 'string'+ ) {+ return;+ }++ return (async () => {+ await removeExpiredCaptures();+ const metadata = await getStoredCapture(message.captureId);+ if (+ !metadata ||+ metadata.expiresAt <= Date.now() ||+ metadata.tabId !== null+ ) {+ throw new Error(+ 'The canvas capture has expired or was already opened.',+ );+ }++ // Bind the token before the destination can establish a connection.+ const tab = await browser.tabs.create({+ url: 'about:blank',+ active: false,+ });+ if (tab.id === undefined) {+ throw new Error('Could not open the canvas capture.');+ }++ try {+ await browser.storage.local.set({+ [getMetadataKey(message.captureId)]: {...metadata, tabId: tab.id},+ });+ const url = new URL(`/${metadata.destination}`, handoffOrigin);+ url.hash = new URLSearchParams({+ 'canvas-capture': message.captureId,+ 'canvas-capture-extension': browser.runtime.id,+ }).toString();+ await browser.tabs.update(tab.id, {url: url.toString(), active: true});+ } catch (error) {+ await browser.tabs.remove(tab.id).catch(() => undefined);+ throw error;+ }+ })();+ });++ browser.runtime.onConnectExternal.addListener((port) => {+ const {sender} = port;+ if (+ port.name !== canvasCapturePortName ||+ !sender?.url ||+ sender.tab?.id === undefined ||+ sender.frameId !== 0+ ) {+ port.disconnect();+ return;+ }++ let senderUrl: URL;+ try {+ senderUrl = new URL(sender.url);+ } catch {+ port.disconnect();+ return;+ }++ if (+ ![+ handoffOrigin,+ 'https://remotion.dev',+ 'https://www.remotion.dev',+ ].includes(senderUrl.origin)+ ) {+ port.disconnect();+ return;+ }++ let captureId: string | null = null;+ let metadata: StoredCaptureMetadata | null = null;+ let nextChunk = 0;+ let busy = false;+ let disconnected = false;+ const send = (message: CanvasCaptureResponse) => {+ if (!disconnected) {+ port.postMessage(message);+ }+ };++ port.onDisconnect.addListener(() => {+ disconnected = true;+ if (captureId && transfers.get(captureId) === port) {+ transfers.delete(captureId);+ }+ });++ port.onMessage.addListener((message: unknown) => {+ const receive = async () => {+ if (+ busy ||+ disconnected ||+ typeof message !== 'object' ||+ message === null ||+ !('type' in message) ||+ !('captureId' in message) ||+ typeof message.captureId !== 'string'+ ) {+ throw new Error('Invalid canvas capture request.');+ }++ busy = true;+ if (captureId === null) {+ if (+ message.type !== 'start' ||+ !/^[0-9a-f-]{36}$/.test(message.captureId) ||+ completing.has(message.captureId)+ ) {+ throw new Error('Invalid canvas capture token.');+ }++ const stored = await getStoredCapture(message.captureId);+ if (!stored || stored.expiresAt <= Date.now()) {+ if (stored) {+ await removeStoredCapture(message.captureId, stored.chunks);+ }++ throw new Error(+ 'The canvas capture has expired. Open the recording from the extension again.',+ );+ }++ const parameters = new URLSearchParams(senderUrl.hash.slice(1));+ if (+ stored.tabId !== sender.tab?.id ||+ (senderUrl.pathname !== `/${stored.destination}` &&+ senderUrl.pathname !== `/${stored.destination}/`) ||+ parameters.get('canvas-capture') !== message.captureId ||+ parameters.get('canvas-capture-extension') !== browser.runtime.id+ ) {+ throw new Error('This page cannot receive that canvas capture.');+ }++ if (disconnected || completing.has(message.captureId)) {+ return;+ }++ captureId = message.captureId;+ metadata = stored;+ // React may reconnect the same destination while an effect is remounted.+ transfers.get(captureId)?.disconnect();+ transfers.set(captureId, port);+ send({+ type: 'start',+ captureId,+ filename: stored.filename,+ mimeType: stored.mimeType,+ size: stored.size,+ chunks: stored.chunks,+ });+ return;+ }++ if (+ !metadata ||+ message.captureId !== captureId ||+ transfers.get(captureId) !== port ||+ metadata.expiresAt <= Date.now()+ ) {+ throw new Error(+ 'The canvas capture transfer is no longer available.',+ );+ }++ if (+ message.type === 'chunk' &&+ 'index' in message &&+ message.index === nextChunk &&+ nextChunk < metadata.chunks+ ) {+ const key = getChunkKey(captureId, nextChunk);+ const stored = await browser.storage.local.get(key);+ const data = stored[key];+ if (typeof data !== 'string') {+ throw new Error('The canvas capture is missing a recording chunk.');+ }++ send({type: 'chunk', captureId, index: nextChunk, data});+ nextChunk++;+ return;+ }++ if (message.type === 'complete' && nextChunk === metadata.chunks) {+ completing.add(captureId);+ await browser.storage.local.set({+ [getMetadataKey(captureId)]: {...metadata, expiresAt: 0},+ });+ await removeStoredCapture(captureId, metadata.chunks);+ send({type: 'complete', captureId});+ transfers.delete(captureId);+ completing.delete(captureId);+ return;+ }++ throw new Error('Unexpected canvas capture request.');+ };++ receive()+ .catch((error) => {+ send({+ type: 'error',+ message: error instanceof Error ? error.message : String(error),+ });+ port.disconnect();+ })+ .finally(() => {+ busy = false;+ });+ });+ });+};diff --git a/packages/canvas-capture-extension/src/handoff.ts b/packages/canvas-capture-extension/src/handoff.tsindex 67d25ce5b2..cb28c7872b 100644--- a/packages/canvas-capture-extension/src/handoff.ts+++ b/packages/canvas-capture-extension/src/handoff.ts@@ -1,19 +1,82 @@+import {canvasCaptureChunkSize} from '@remotion/studio-shared/canvas-capture-handoff';import {browser} from 'wxt/browser';-const STORAGE_PREFIX = 'remotion-canvas-capture:';-const CHUNK_SIZE = 1024 * 1024;+export const captureStoragePrefix = 'remotion-canvas-capture:';+export const captureLifetime = 10 * 60 * 1000;-type StoredCaptureMetadata = {+export type StoredCaptureMetadata = {readonly filename: string;readonly mimeType: string;readonly chunks: number;+ readonly size: number;+ readonly destination: CaptureHandoffDestination;+ readonly expiresAt: number;+ readonly tabId: number | null;};-const getMetadataKey = (captureId: string) =>- `${STORAGE_PREFIX}${captureId}:metadata`;+export const getMetadataKey = (captureId: string) =>+ `${captureStoragePrefix}${captureId}:metadata`;-const getChunkKey = (captureId: string, index: number) =>- `${STORAGE_PREFIX}${captureId}:chunk:${index}`;+export const getChunkKey = (captureId: string, index: number) =>+ `${captureStoragePrefix}${captureId}:chunk:${index}`;++export const getStoredCapture = async (+ captureId: string,+): Promise<StoredCaptureMetadata | null> => {+ const key = getMetadataKey(captureId);+ const stored = await browser.storage.local.get(key);+ const metadata = stored[key] as Partial<StoredCaptureMetadata> | undefined;+ if (+ !metadata ||+ typeof metadata.filename !== 'string' ||+ typeof metadata.mimeType !== 'string' ||+ typeof metadata.size !== 'number' ||+ !Number.isSafeInteger(metadata.size) ||+ metadata.size < 0 ||+ metadata.chunks !== Math.ceil(metadata.size / canvasCaptureChunkSize) ||+ (metadata.destination !== 'new' && metadata.destination !== 'convert') ||+ typeof metadata.expiresAt !== 'number' ||+ !Number.isFinite(metadata.expiresAt) ||+ (metadata.tabId !== null && !Number.isSafeInteger(metadata.tabId))+ ) {+ return null;+ }++ return metadata as StoredCaptureMetadata;+};++export const removeStoredCapture = async (+ captureId: string,+ chunks: number,+) => {+ await browser.storage.local.remove([+ getMetadataKey(captureId),+ ...Array.from({length: chunks}, (_, index) =>+ getChunkKey(captureId, index),+ ),+ ]);+};++export const removeExpiredCaptures = async () => {+ const keys = await browser.storage.local.getKeys();+ const metadataKeys = keys.filter(+ (key) => key.startsWith(captureStoragePrefix) && key.endsWith(':metadata'),+ );+ const metadata = await browser.storage.local.get(metadataKeys);+ const expiredPrefixes = metadataKeys+ .filter((key) => {+ const value = metadata[key] as Partial<StoredCaptureMetadata> | undefined;+ return (+ typeof value?.expiresAt !== 'number' || value.expiresAt <= Date.now()+ );+ })+ .map((key) => key.slice(0, -'metadata'.length));+ await browser.storage.local.remove(+ keys.filter((key) =>+ expiredPrefixes.some((prefix) => key.startsWith(prefix)),+ ),+ );+};const toBase64 = (bytes: Uint8Array) => {let binary = '';@@ -35,34 +98,40 @@ export const openCaptureInRemotion = async (destination: CaptureHandoffDestination,) => {const captureId = crypto.randomUUID();- const chunkCount = Math.ceil(file.size / CHUNK_SIZE);+ const chunkCount = Math.ceil(file.size / canvasCaptureChunkSize);const storedKeys: string[] = [];try {+ const metadata: StoredCaptureMetadata = {+ filename: file.name,+ mimeType: file.type,+ chunks: chunkCount,+ size: file.size,+ destination,+ expiresAt: Date.now() + captureLifetime,+ tabId: null,+ };+ const metadataKey = getMetadataKey(captureId);+ await browser.storage.local.set({[metadataKey]: metadata});+ storedKeys.push(metadataKey);+for (let index = 0; index < chunkCount; index++) {const key = getChunkKey(captureId, index);const bytes = new Uint8Array(await file- .slice(index * CHUNK_SIZE, (index + 1) * CHUNK_SIZE)+ .slice(+ index * canvasCaptureChunkSize,+ (index + 1) * canvasCaptureChunkSize,+ ).arrayBuffer(),);await browser.storage.local.set({[key]: toBase64(bytes)});storedKeys.push(key);}- const metadata: StoredCaptureMetadata = {- filename: file.name,- mimeType: file.type,- chunks: chunkCount,- };- const metadataKey = getMetadataKey(captureId);- await browser.storage.local.set({[metadataKey]: metadata});- storedKeys.push(metadataKey);-await browser.runtime.sendMessage({type: 'remotion-canvas-capture-open',captureId,- destination,});} catch (error) {await browser.storage.local.remove(storedKeys).catch(() => undefined);diff --git a/packages/canvas-capture-extension/src/receiver.ts b/packages/canvas-capture-extension/src/receiver.tsdeleted file mode 100644index 086f26eb8a..0000000000--- a/packages/canvas-capture-extension/src/receiver.ts+++ /dev/null@@ -1,114 +0,0 @@-import {browser} from 'wxt/browser';--export const startReceiver = () => {- const STORAGE_PREFIX = 'remotion-canvas-capture:';- const MESSAGE_PREFIX = 'remotion-canvas-capture';-- type StoredCaptureMetadata = {- readonly filename: string;- readonly mimeType: string;- readonly chunks: number;- };-- const captureId = new URL(window.location.href).searchParams.get(- 'canvas-capture',- );- let isDelivering = false;-- const getMetadataKey = (id: string) => `${STORAGE_PREFIX}${id}:metadata`;- const getChunkKey = (id: string, index: number) =>- `${STORAGE_PREFIX}${id}:chunk:${index}`;-- const removeCaptureParameter = () => {- const url = new URL(window.location.href);- url.searchParams.delete('canvas-capture');- window.history.replaceState(- null,- '',- `${url.pathname}${url.search}${url.hash}`,- );- };-- const deliverCapture = async (id: string) => {- const metadataKey = getMetadataKey(id);- const storedMetadata = await browser.storage.local.get(metadataKey);- const metadata = storedMetadata[metadataKey] as- | StoredCaptureMetadata- | undefined;-- if (- !metadata ||- typeof metadata.filename !== 'string' ||- typeof metadata.mimeType !== 'string' ||- !Number.isSafeInteger(metadata.chunks) ||- metadata.chunks < 0- ) {- throw new Error('The canvas capture could not be found.');- }-- window.postMessage(- {- type: `${MESSAGE_PREFIX}-start`,- captureId: id,- filename: metadata.filename,- mimeType: metadata.mimeType,- chunks: metadata.chunks,- },- window.location.origin,- );-- for (let index = 0; index < metadata.chunks; index++) {- const key = getChunkKey(id, index);- const storedChunk = await browser.storage.local.get(key);- const chunk = storedChunk[key];- if (typeof chunk !== 'string') {- throw new Error(`Canvas capture chunk ${index + 1} is missing.`);- }-- window.postMessage(- {- type: `${MESSAGE_PREFIX}-chunk`,- captureId: id,- index,- data: chunk,- },- window.location.origin,- );- await browser.storage.local.remove(key);- }-- window.postMessage(- {type: `${MESSAGE_PREFIX}-complete`, captureId: id},- window.location.origin,- );- await browser.storage.local.remove(metadataKey);- removeCaptureParameter();- };-- if (captureId) {- window.addEventListener('message', (event) => {- if (- isDelivering ||- event.origin !== window.location.origin ||- typeof event.data !== 'object' ||- event.data === null ||- event.data.type !== `${MESSAGE_PREFIX}-ready` ||- event.data.captureId !== captureId- ) {- return;- }-- isDelivering = true;- deliverCapture(captureId).catch((error) => {- window.postMessage(- {- type: `${MESSAGE_PREFIX}-error`,- captureId,- message: error instanceof Error ? error.message : String(error),- },- window.location.origin,- );- });- });- }-};diff --git a/packages/canvas-capture-extension/wxt.config.ts b/packages/canvas-capture-extension/wxt.config.tsindex bc1d40ed6f..b0b6720232 100644--- a/packages/canvas-capture-extension/wxt.config.ts+++ b/packages/canvas-capture-extension/wxt.config.ts@@ -6,6 +6,10 @@ import {minimumChromeVersion} from './src/browser-requirements';const homeDirectory = homedir();const isDevelopment = process.env.npm_lifecycle_event === 'dev';+const handoffOrigin =+ isDevelopment && process.env.CANVAS_CAPTURE_HANDOFF_ORIGIN+ ? new URL(process.env.CANVAS_CAPTURE_HANDOFF_ORIGIN).origin+ : 'https://www.remotion.dev';export default defineConfig({srcDir: 'src',@@ -19,6 +23,12 @@ export default defineConfig({): 'dist',outDirTemplate: '.',+ vite: () => ({+ define: {+ 'import.meta.env.CANVAS_CAPTURE_HANDOFF_ORIGIN':+ JSON.stringify(handoffOrigin),+ },+ }),manifest: {name: 'Remotion Canvas Capture',description: `Record an area or webpage as MP4 or WebM. Requires Chrome ${minimumChromeVersion}+ and Canvas Draw Element enabled.`,@@ -26,6 +36,20 @@ export default defineConfig({// Allow older Chrome versions to install and show the recording requirements.minimum_chrome_version: '155',permissions: ['activeTab', 'scripting', 'storage', 'unlimitedStorage'],+ externally_connectable: {+ matches: [+ 'https://remotion.dev/new*',+ 'https://remotion.dev/convert*',+ 'https://www.remotion.dev/new*',+ 'https://www.remotion.dev/convert*',+ ...(isDevelopment && handoffOrigin !== 'https://www.remotion.dev'+ ? [+ `${new URL(handoffOrigin).protocol}//${new URL(handoffOrigin).hostname}/new*`,+ `${new URL(handoffOrigin).protocol}//${new URL(handoffOrigin).hostname}/convert*`,+ ]+ : []),+ ],+ },icons: {16: 'icons/icon-16.png',32: 'icons/icon-32.png',diff --git a/packages/convert/app/components/Main.tsx b/packages/convert/app/components/Main.tsxindex 57b343fc2d..f240501cac 100644--- a/packages/convert/app/components/Main.tsx+++ b/packages/convert/app/components/Main.tsx@@ -18,11 +18,16 @@ export const Main: React.FC<{const [src, setSrc] = useState<Source | null>(() => {return url.has('url') ? {type: 'url', url: url.get('url') as string} : null;});- useCanvasCapture(setSrc);+ const captureError = useCanvasCapture(setSrc);return (<TitleProvider routeAction={routeAction}><div className="font-sans min-h-screen">+ {captureError ? (+ <div role="alert" className="p-4 text-red-500">+ {captureError}+ </div>+ ) : null}{src ? (<FileAvailablekey={src.type === 'url' ? src.url : src.file.name}diff --git a/packages/convert/app/lib/use-canvas-capture.ts b/packages/convert/app/lib/use-canvas-capture.tsindex 6b42aa6ab0..11b58041d5 100644--- a/packages/convert/app/lib/use-canvas-capture.ts+++ b/packages/convert/app/lib/use-canvas-capture.ts@@ -1,97 +1,26 @@-import {useEffect} from 'react';+import {receiveCanvasCapture} from '@remotion/studio-shared/canvas-capture-handoff';+import {useEffect, useState} from 'react';import type {Source} from './convert-state';-const MESSAGE_PREFIX = 'remotion-canvas-capture';--type IncomingCapture = {- readonly captureId: string;- readonly filename: string;- readonly mimeType: string;- readonly chunks: Array<ArrayBuffer | null>;-};--const decodeBase64 = (value: string) => {- const binary = atob(value);- const buffer = new ArrayBuffer(binary.length);- const bytes = new Uint8Array(buffer);- for (let index = 0; index < binary.length; index++) {- bytes[index] = binary.charCodeAt(index);- }-- return buffer;-};-export const useCanvasCapture = (setSrc: React.Dispatch<React.SetStateAction<Source | null>>,) => {+ const [error, setError] = useState<string | null>(null);useEffect(() => {- const captureId = new URL(window.location.href).searchParams.get(- 'canvas-capture',- );- if (!captureId) {- return;- }-- let incoming: IncomingCapture | null = null;-- const onMessage = (event: MessageEvent) => {- if (- event.source !== window ||- event.origin !== window.location.origin ||- typeof event.data !== 'object' ||- event.data === null ||- event.data.captureId !== captureId- ) {- return;- }-- if (- event.data.type === `${MESSAGE_PREFIX}-start` &&- typeof event.data.filename === 'string' &&- typeof event.data.mimeType === 'string' &&- Number.isSafeInteger(event.data.chunks) &&- event.data.chunks >= 0- ) {- incoming = {- captureId,- filename: event.data.filename,- mimeType: event.data.mimeType,- chunks: Array.from({length: event.data.chunks}, () => null),- };- return;- }-- if (- event.data.type === `${MESSAGE_PREFIX}-chunk` &&- incoming &&- Number.isSafeInteger(event.data.index) &&- event.data.index >= 0 &&- event.data.index < incoming.chunks.length &&- typeof event.data.data === 'string'- ) {- incoming.chunks[event.data.index] = decodeBase64(event.data.data);- return;- }-- if (- event.data.type === `${MESSAGE_PREFIX}-complete` &&- incoming &&- incoming.chunks.every((chunk) => chunk !== null)- ) {- const file = new File(incoming.chunks, incoming.filename, {- type: incoming.mimeType,- });+ const controller = new AbortController();+ receiveCanvasCapture({+ handoffWindow: window,+ signal: controller.signal,+ onCapture: (file) => {setSrc({type: 'file', file});- incoming = null;+ },+ }).catch((err) => {+ if (!controller.signal.aborted) {+ setError(err instanceof Error ? err.message : String(err));}- };-- window.addEventListener('message', onMessage);- window.postMessage(- {type: `${MESSAGE_PREFIX}-ready`, captureId},- window.location.origin,- );+ });- return () => window.removeEventListener('message', onMessage);+ return () => controller.abort();}, [setSrc]);+ return error;};diff --git a/packages/convert/package.json b/packages/convert/package.jsonindex bc4f1939c8..58c515b4e5 100644--- a/packages/convert/package.json+++ b/packages/convert/package.json@@ -13,6 +13,7 @@"lint": "bun check && eslint --cache --cache-location ./node_modules/.cache/eslint app"},"dependencies": {+ "@remotion/studio-shared": "workspace:*","@mediabunny/mp3-encoder": "catalog:","@mediabunny/aac-encoder": "catalog:","@mediabunny/flac-encoder": "catalog:",diff --git a/packages/convert/tsconfig.json b/packages/convert/tsconfig.jsonindex 00e73ec276..41ca6f9574 100644--- a/packages/convert/tsconfig.json+++ b/packages/convert/tsconfig.json@@ -38,6 +38,9 @@"noEmit": true},"references": [+ {+ "path": "../studio-shared"+ },{"path": "../design"}diff --git a/packages/docs/docs/canvas-capture/privacy.mdx b/packages/docs/docs/canvas-capture/privacy.mdxindex 137c77f185..0a89aeb7bb 100644--- a/packages/docs/docs/canvas-capture/privacy.mdx+++ b/packages/docs/docs/canvas-capture/privacy.mdx@@ -22,9 +22,9 @@ Recording and video encoding take place locally in your browser. The extension h## Opening a recording in Remotion-When you choose to open a recording in Remotion, the extension temporarily stores the recording and its metadata in local extension storage, opens `remotion.dev/new` or `remotion.dev/convert`, and transfers the recording to that page in your browser.+When you choose to open a recording in Remotion, the extension temporarily stores the recording and its metadata in local extension storage and opens `remotion.dev/new` or `remotion.dev/convert`. That page requests the recording directly from the extension using a single-use transfer token. The transfer takes place locally in your browser.-The extension removes the stored recording data as it is delivered. If delivery is interrupted, some local data may remain until you clear the extension's storage or uninstall it. Use of the Remotion website is also subject to the applicable [Remotion Privacy Policy](/docs/privacy).+The extension removes the stored recording after the page acknowledges receipt. Transfer tokens expire after 10 minutes. If delivery is interrupted, local data may remain until the extension next starts or opens another recording after expiry, or until you clear its storage or uninstall it. Use of the Remotion website is also subject to the applicable [Remotion Privacy Policy](/docs/privacy).## How the data is useddiff --git a/packages/studio-shared/bundle.ts b/packages/studio-shared/bundle.tsindex 6451c47238..e4800941c6 100644--- a/packages/studio-shared/bundle.ts+++ b/packages/studio-shared/bundle.ts@@ -7,6 +7,10 @@ await buildPackage({},external: 'dependencies',entrypoints: [+ {+ path: 'src/canvas-capture-handoff.ts',+ target: 'browser',+ },{path: 'src/index.ts',target: 'browser',diff --git a/packages/studio-shared/package.json b/packages/studio-shared/package.jsonindex 25efecb3db..5dcf913c36 100644--- a/packages/studio-shared/package.json+++ b/packages/studio-shared/package.json@@ -69,7 +69,13 @@"module": "./dist/esm/parse-spring-easing-config.mjs","import": "./dist/esm/parse-spring-easing-config.mjs"},- "./package.json": "./package.json"+ "./package.json": "./package.json",+ "./canvas-capture-handoff": {+ "types": "./dist/canvas-capture-handoff.d.ts",+ "require": "./dist/canvas-capture-handoff.js",+ "module": "./dist/esm/canvas-capture-handoff.mjs",+ "import": "./dist/esm/canvas-capture-handoff.mjs"+ }},"typesVersions": {">=1.0": {@@ -87,6 +93,9 @@],"parse-spring-easing-config": ["./dist/parse-spring-easing-config.d.ts"+ ],+ "canvas-capture-handoff": [+ "./dist/canvas-capture-handoff.d.ts"]}}diff --git a/packages/studio-shared/src/canvas-capture-handoff.ts b/packages/studio-shared/src/canvas-capture-handoff.tsnew file mode 100644index 0000000000..dfa17df8c7--- /dev/null+++ b/packages/studio-shared/src/canvas-capture-handoff.ts@@ -0,0 +1,279 @@+export const canvasCapturePortName = 'remotion-canvas-capture';+export const canvasCaptureChunkSize = 1024 * 1024;++export type CanvasCaptureRequest =+ | {type: 'start'; captureId: string}+ | {type: 'chunk'; captureId: string; index: number}+ | {type: 'complete'; captureId: string};++export type CanvasCaptureResponse =+ | {+ type: 'start';+ captureId: string;+ filename: string;+ mimeType: string;+ size: number;+ chunks: number;+ }+ | {type: 'chunk'; captureId: string; index: number; data: string}+ | {type: 'complete'; captureId: string}+ | {type: 'error'; message: string};++type CapturePort = {+ postMessage: (message: CanvasCaptureRequest) => void;+ disconnect: () => void;+ onMessage: {+ addListener: (listener: (message: unknown) => void) => void;+ removeListener: (listener: (message: unknown) => void) => void;+ };+ onDisconnect: {+ addListener: (listener: () => void) => void;+ removeListener: (listener: () => void) => void;+ };+};++type CaptureRuntime = {+ connect: (extensionId: string, options: {name: string}) => CapturePort;+ lastError: {message: string | undefined} | undefined;+};++export const receiveCanvasCapture = async ({+ handoffWindow,+ signal,+ onCapture,+}: {+ handoffWindow: Window;+ signal: AbortSignal;+ onCapture: (file: File) => void | Promise<void>;+}): Promise<void> => {+ const parameters = new URLSearchParams(handoffWindow.location.hash.slice(1));+ const captureId = parameters.get('canvas-capture');+ if (!captureId) {+ return;+ }++ const extensionId = parameters.get('canvas-capture-extension');+ const runtime = (+ handoffWindow as Window & {+ chrome: {runtime: CaptureRuntime | undefined} | undefined;+ }+ ).chrome?.runtime;+ if (!extensionId || !/^[a-p]{32}$/.test(extensionId) || !runtime?.connect) {+ throw new Error(+ 'The Canvas Capture extension is unavailable. Open the recording from the extension again.',+ );+ }++ if (signal.aborted) {+ return;+ }++ const captureRuntime = runtime;+ const port = runtime.connect(extensionId, {name: canvasCapturePortName});+ await new Promise<void>((resolve, reject) => {+ let settled = false;+ let timeout: ReturnType<typeof setTimeout> | null = null;+ let metadata: Extract<CanvasCaptureResponse, {type: 'start'}> | null = null;+ const chunks: ArrayBuffer[] = [];+ let awaitingCompletion = false;+ let cleanup: (() => void) | null = null;++ const finish = (error: Error | null) => {+ if (settled) {+ return;+ }++ settled = true;+ if (timeout !== null) {+ clearTimeout(timeout);+ }++ cleanup?.();+ port.disconnect();+ if (error) {+ reject(error);+ } else {+ resolve();+ }+ };++ const send = (message: CanvasCaptureRequest) => {+ if (timeout !== null) {+ clearTimeout(timeout);+ }++ timeout = setTimeout(() => {+ finish(+ new Error(+ 'Canvas Capture transfer timed out. Open the recording from the extension again.',+ ),+ );+ }, 30_000);+ port.postMessage(message);+ };++ const acceptFile = async () => {+ if (!metadata || signal.aborted) {+ return;+ }++ const file = new File(chunks, metadata.filename, {+ type: metadata.mimeType,+ });+ await onCapture(file);+ if (!signal.aborted) {+ awaitingCompletion = true;+ send({type: 'complete', captureId});+ }+ };++ const handleMessage = async (message: unknown) => {+ if (settled) {+ return;+ }++ if (timeout !== null) {+ clearTimeout(timeout);+ timeout = null;+ }++ if (+ typeof message !== 'object' ||+ message === null ||+ !('type' in message)+ ) {+ throw new Error('Invalid Canvas Capture response.');+ }++ if (+ message.type === 'error' &&+ 'message' in message &&+ typeof message.message === 'string'+ ) {+ throw new Error(message.message);+ }++ if (!('captureId' in message) || message.captureId !== captureId) {+ throw new Error(+ 'Canvas Capture transfer did not match the requested recording.',+ );+ }++ if (+ message.type === 'start' &&+ metadata === null &&+ 'filename' in message &&+ typeof message.filename === 'string' &&+ 'mimeType' in message &&+ typeof message.mimeType === 'string' &&+ 'size' in message &&+ typeof message.size === 'number' &&+ Number.isSafeInteger(message.size) &&+ message.size >= 0 &&+ 'chunks' in message &&+ message.chunks === Math.ceil(message.size / canvasCaptureChunkSize)+ ) {+ metadata = message as Extract<CanvasCaptureResponse, {type: 'start'}>;+ if (metadata.chunks === 0) {+ await acceptFile();+ } else {+ send({type: 'chunk', captureId, index: 0});+ }++ return;+ }++ if (+ message.type === 'chunk' &&+ metadata &&+ !awaitingCompletion &&+ 'index' in message &&+ message.index === chunks.length &&+ chunks.length < metadata.chunks &&+ 'data' in message &&+ typeof message.data === 'string' &&+ message.data.length <= 4 * Math.ceil(canvasCaptureChunkSize / 3)+ ) {+ const binary = atob(message.data);+ const expectedSize = Math.min(+ canvasCaptureChunkSize,+ metadata.size - chunks.length * canvasCaptureChunkSize,+ );+ if (binary.length !== expectedSize) {+ throw new Error(+ 'Canvas Capture received an incomplete recording chunk.',+ );+ }++ const buffer = new ArrayBuffer(binary.length);+ const bytes = new Uint8Array(buffer);+ for (let index = 0; index < binary.length; index++) {+ bytes[index] = binary.charCodeAt(index);+ }++ chunks.push(buffer);+ if (chunks.length === metadata.chunks) {+ await acceptFile();+ } else {+ send({type: 'chunk', captureId, index: chunks.length});+ }++ return;+ }++ if (message.type === 'complete' && awaitingCompletion) {+ const url = new URL(handoffWindow.location.href);+ const hash = new URLSearchParams(url.hash.slice(1));+ if (hash.get('canvas-capture') === captureId) {+ hash.delete('canvas-capture');+ hash.delete('canvas-capture-extension');+ url.hash = hash.toString();+ handoffWindow.history.replaceState(+ null,+ '',+ `${url.pathname}${url.search}${url.hash}`,+ );+ }++ finish(null);+ return;+ }++ throw new Error('Unexpected Canvas Capture response.');+ };++ function onMessage(message: unknown) {+ handleMessage(message).catch((error) =>+ finish(error instanceof Error ? error : new Error(String(error))),+ );+ }++ function onDisconnect() {+ finish(+ new Error(+ captureRuntime.lastError?.message ??+ 'Canvas Capture disconnected before the transfer completed. Open the recording from the extension again.',+ ),+ );+ }++ function onAbort() {+ finish(null);+ }++ cleanup = () => {+ port.onMessage.removeListener(onMessage);+ port.onDisconnect.removeListener(onDisconnect);+ signal.removeEventListener('abort', onAbort);+ };++ port.onMessage.addListener(onMessage);+ port.onDisconnect.addListener(onDisconnect);+ signal.addEventListener('abort', onAbort, {once: true});+ if (signal.aborted) {+ onAbort();+ } else {+ send({type: 'start', captureId});+ }+ });+};diff --git a/packages/studio/src/components/CanvasCaptureDropHandler.tsx b/packages/studio/src/components/CanvasCaptureDropHandler.tsxindex 8cf5437c03..f1e4ef4287 100644--- a/packages/studio/src/components/CanvasCaptureDropHandler.tsx+++ b/packages/studio/src/components/CanvasCaptureDropHandler.tsx@@ -1,16 +1,9 @@+import {receiveCanvasCapture} from '@remotion/studio-shared/canvas-capture-handoff';import {useCallback, useContext, useEffect, type FC} from 'react';import {SetSelectedModalContext} from '../state/modals';import {handleCanvasCaptureDrop} from './canvas-capture-drop';import {isFileDragEvent} from './drop-handler-data';--const canvasCaptureMessagePrefix = 'remotion-canvas-capture';--type IncomingCanvasCapture = {- readonly captureId: string;- readonly filename: string;- readonly mimeType: string;- readonly chunks: Array<ArrayBuffer | null>;-};+import {showNotification} from './Notifications/NotificationCenter';export const CanvasCaptureDropHandler: FC<{readonly readOnlyStudio: boolean;@@ -67,80 +60,31 @@ export const CanvasCaptureDropHandler: FC<{window.remotion_browserStudio && window.parent !== window? window.parent: window;- const captureId = new URL(handoffWindow.location.href).searchParams.get(- 'canvas-capture',- );- if (!captureId) {- return;- }-- let incoming: IncomingCanvasCapture | null = null;- const onMessage = async (event: MessageEvent) => {- if (- event.source !== handoffWindow ||- event.origin !== handoffWindow.location.origin ||- typeof event.data !== 'object' ||- event.data === null ||- event.data.captureId !== captureId- ) {- return;- }-- if (- event.data.type === `${canvasCaptureMessagePrefix}-start` &&- typeof event.data.filename === 'string' &&- typeof event.data.mimeType === 'string' &&- Number.isSafeInteger(event.data.chunks) &&- event.data.chunks >= 0- ) {- incoming = {- captureId,- filename: event.data.filename,- mimeType: event.data.mimeType,- chunks: Array.from({length: event.data.chunks}, () => null),- };- return;- }-- if (- event.data.type === `${canvasCaptureMessagePrefix}-chunk` &&- incoming &&- Number.isSafeInteger(event.data.index) &&- event.data.index >= 0 &&- event.data.index < incoming.chunks.length &&- typeof event.data.data === 'string'- ) {- const binary = atob(event.data.data);- const buffer = new ArrayBuffer(binary.length);- const bytes = new Uint8Array(buffer);- for (let index = 0; index < binary.length; index++) {- bytes[index] = binary.charCodeAt(index);- }-- incoming.chunks[event.data.index] = buffer;- return;- }-- if (- event.data.type === `${canvasCaptureMessagePrefix}-complete` &&- incoming &&- incoming.chunks.every((chunk) => chunk !== null)- ) {- const file = new File(incoming.chunks, incoming.filename, {- type: incoming.mimeType,+ const controller = new AbortController();+ receiveCanvasCapture({+ handoffWindow,+ signal: controller.signal,+ onCapture: async (file) => {+ const imported = await handleCanvasCaptureDrop({+ files: [file],+ setSelectedModal,});- incoming = null;- await handleCanvasCaptureDrop({files: [file], setSelectedModal});+ if (!imported) {+ throw new Error(+ 'The received file is not a Canvas Capture recording.',+ );+ }+ },+ }).catch((error) => {+ if (!controller.signal.aborted) {+ showNotification(+ error instanceof Error ? error.message : String(error),+ 5000,+ );}- };-- handoffWindow.addEventListener('message', onMessage);- handoffWindow.postMessage(- {type: `${canvasCaptureMessagePrefix}-ready`, captureId},- handoffWindow.location.origin,- );+ });- return () => handoffWindow.removeEventListener('message', onMessage);+ return () => controller.abort();}, [readOnlyStudio, setSelectedModal]);return null;