Skip to content

🎥 Make videos programmatically with React

`@remotion/studio-protocol`: Confirm license key installation in Studio (#10106)

Jonny Burger432aae85d729
diff --git a/packages/example/e2e/studio-protocol.test.mts b/packages/example/e2e/studio-protocol.test.mts
index 6976d0efce..24b469418a 100644
--- a/packages/example/e2e/studio-protocol.test.mts
+++ b/packages/example/e2e/studio-protocol.test.mts
@@ -127,9 +127,10 @@ export const MyComponent = () => {
response.writeHead(200, {'Content-Type': 'text/html'});
response.end(`<!doctype html>
<button id="install">Install in Studio</button>
+ <button id="license">Configure license in Studio</button>
<p id="status"></p>
<script type="module">
- import {createElementPayload, installInStudio} from '/protocol.js';
+ import {createElementPayload, installInStudio, StudioProtocolInternals} from '/protocol.js';
const payload = createElementPayload({
displayName: 'Protocol Element',
slug: 'protocol-element',
@@ -139,9 +140,17 @@ export const MyComponent = () => {
durationInFrames: 30,
});
document.querySelector('#install').onclick = async () => {
+ document.querySelector('#status').textContent = '';
const result = await installInStudio({payload});
document.querySelector('#status').textContent = JSON.stringify(result);
};
+ document.querySelector('#license').onclick = async () => {
+ document.querySelector('#status').textContent = '';
+ const result = await StudioProtocolInternals.setLicenseKeyInStudio({
+ licenseKey: 'rm_pub_${'a'.repeat(48)}',
+ });
+ document.querySelector('#status').textContent = JSON.stringify(result);
+ };
</script>`);
});
await new Promise<void>((resolve) =>
@@ -233,6 +242,26 @@ export const MyComponent = () => {
);
expect(compositionSource).toContain('ProtocolElement');
expect(compositionSource).toContain('protocol-element.element');
+
+ await studioPage.bringToFront();
+ await studioPage.mouse.click(500, 300);
+ await senderPage.bringToFront();
+ await senderPage
+ .getByRole('button', {name: 'Configure license in Studio'})
+ .click();
+ await senderPage.waitForFunction(
+ () => document.querySelector('#status')?.textContent !== '',
+ );
+ expect(await senderPage.locator('#status').textContent()).toContain(
+ 'awaiting-confirmation',
+ );
+
+ await studioPage.bringToFront();
+ const licenseDialog = studioPage.getByRole('dialog');
+ await expect(licenseDialog.getByText('Configure License')).toBeVisible();
+ await expect(
+ licenseDialog.getByRole('textbox', {name: 'Public license key'}),
+ ).toHaveValue(`rm_pub_${'a'.repeat(48)}`);
} catch (error) {
throw new Error(`${String(error)}\nTemporary Studio logs:\n${studioLogs}`);
} finally {
diff --git a/packages/studio-protocol/src/set-license-key-in-studio.ts b/packages/studio-protocol/src/set-license-key-in-studio.ts
index 65ec6568a4..6b3794a12f 100644
--- a/packages/studio-protocol/src/set-license-key-in-studio.ts
+++ b/packages/studio-protocol/src/set-license-key-in-studio.ts
@@ -28,7 +28,7 @@ export type SetLicenseKeyInStudioErrorCode =
export type SetLicenseKeyInStudioResult =
| {
readonly success: true;
- readonly status: 'license-key-set';
+ readonly status: 'awaiting-confirmation';
readonly target: {
readonly projectName: string | null;
readonly studioOrigin: string;
@@ -221,11 +221,11 @@ export const setLicenseKeyInStudioWithDependencies = async (
isRecord(result) &&
result.protocol === 'remotion-studio-protocol' &&
result.protocolVersion === 1 &&
- result.status === 'license-key-set'
+ result.status === 'awaiting-confirmation'
) {
return {
success: true,
- status: 'license-key-set',
+ status: 'awaiting-confirmation',
target: {
projectName: selected.descriptor.projectName,
studioOrigin: selected.origin,
diff --git a/packages/studio-protocol/src/test/set-license-key-in-studio.test.ts b/packages/studio-protocol/src/test/set-license-key-in-studio.test.ts
index 181c328240..0e21b65443 100644
--- a/packages/studio-protocol/src/test/set-license-key-in-studio.test.ts
+++ b/packages/studio-protocol/src/test/set-license-key-in-studio.test.ts
@@ -53,7 +53,7 @@ const dependencies = {
ports: [3000, 3001],
};
-test('sets the key in the most recently focused Studio project', async () => {
+test('requests confirmation in the most recently focused Studio project', async () => {
const requests: Array<{
readonly options?: RequestInit;
readonly url: string;
@@ -89,7 +89,7 @@ test('sets the key in the most recently focused Studio project', async () => {
jsonResponse({
protocol: 'remotion-studio-protocol',
protocolVersion: 1,
- status: 'license-key-set',
+ status: 'awaiting-confirmation',
}),
);
};
@@ -101,7 +101,7 @@ test('sets the key in the most recently focused Studio project', async () => {
}),
).toEqual({
success: true,
- status: 'license-key-set',
+ status: 'awaiting-confirmation',
target: {
projectName: 'Focused project',
studioOrigin: 'http://localhost:3001',
diff --git a/packages/studio-server/src/preview-server/studio-protocol/handle-license-key.ts b/packages/studio-server/src/preview-server/studio-protocol/handle-license-key.ts
index bd0eb876ca..796549fd36 100644
--- a/packages/studio-server/src/preview-server/studio-protocol/handle-license-key.ts
+++ b/packages/studio-server/src/preview-server/studio-protocol/handle-license-key.ts
@@ -2,14 +2,16 @@ import type {IncomingMessage, ServerResponse} from 'node:http';
import {StudioProtocolInternals} from '@remotion/studio-protocol';
import {z} from 'zod';
import {consumeStudioProtocolTarget} from '../element-install-state';
+import type {LiveEventsServer} from '../live-events';
import {parseRequestBody, RequestBodyTooLargeError} from '../parse-body';
-import {setPublicLicenseKeyInConfigFile} from '../routes/update-public-license';
import {
getAllowedLicenseKeyOrigin,
setStudioProtocolCorsHeaders,
} from './origin-policy';
import {writeStudioProtocolError} from './protocol-response';
+type FocusStudioTab = (studioUrl: string) => void;
+
const studioProtocolLicenseKeyRequestSchema = z.object({
operation: z.literal('set-license-key'),
protocol: z.literal('remotion-studio-protocol'),
@@ -22,10 +24,14 @@ const MAX_STUDIO_PROTOCOL_LICENSE_KEY_BODY_SIZE = 4096;
export const handleStudioProtocolLicenseKey = async ({
configFile,
+ focusStudioTab,
+ liveEventsServer,
request,
response,
}: {
readonly configFile: string | null;
+ readonly focusStudioTab: FocusStudioTab;
+ readonly liveEventsServer: LiveEventsServer;
readonly request: IncomingMessage;
readonly response: ServerResponse;
}): Promise<void> => {
@@ -127,27 +133,28 @@ export const handleStudioProtocolLicenseKey = async ({
return;
}
- try {
- setPublicLicenseKeyInConfigFile({
- configFile,
- publicLicenseKey: parsedRequest.data.licenseKey,
- });
- } catch {
+ const delivered = liveEventsServer.sendEventToClientId(target.clientId, {
+ type: 'license-key-install-request',
+ licenseKey: parsedRequest.data.licenseKey,
+ });
+ if (!delivered) {
writeStudioProtocolError({
- code: 'config-write-failed',
- message: 'Could not update the Remotion config file.',
+ code: 'target-expired',
+ message: 'The selected Remotion Studio tab is no longer connected.',
response,
- status: 500,
+ status: 409,
});
return;
}
+ focusStudioTab(target.studioUrl);
+
response.writeHead(200, {'Content-Type': 'application/json'});
response.end(
JSON.stringify({
protocol: 'remotion-studio-protocol',
protocolVersion: 1,
- status: 'license-key-set',
+ status: 'awaiting-confirmation',
}),
);
};
diff --git a/packages/studio-server/src/routes.ts b/packages/studio-server/src/routes.ts
index a0da7f068a..0382e1af13 100644
--- a/packages/studio-server/src/routes.ts
+++ b/packages/studio-server/src/routes.ts
@@ -462,7 +462,15 @@ export const handleRoutes = ({
}
if (url.pathname === '/api/studio-protocol/license-key') {
- return handleStudioProtocolLicenseKey({configFile, request, response});
+ return handleStudioProtocolLicenseKey({
+ configFile,
+ focusStudioTab: (studioUrl) => {
+ focusBrowserTab({url: studioUrl}).catch(() => undefined);
+ },
+ liveEventsServer,
+ request,
+ response,
+ });
}
return handleStudioProtocolInstall({
diff --git a/packages/studio-server/src/test/studio-protocol-routes.test.ts b/packages/studio-server/src/test/studio-protocol-routes.test.ts
index 11af104211..be6d0ff8e4 100644
--- a/packages/studio-server/src/test/studio-protocol-routes.test.ts
+++ b/packages/studio-server/src/test/studio-protocol-routes.test.ts
@@ -6,10 +6,6 @@ import {tmpdir} from 'node:os';
import path from 'node:path';
import {createElementPayload} from '@remotion/studio-protocol';
import type {EventSourceEvent} from '@remotion/studio-shared';
-import {
- createFileWatcherRegistry,
- setFileWatcherRegistry,
-} from '../file-watcher';
import {
clearElementInstallStateForTests,
updateElementInstallTarget,
@@ -351,8 +347,10 @@ test('discovers an exact Studio target and delivers one install request over HTT
}
});
-test('sets a public license key in the focused Studio project over HTTP', async () => {
+test('opens a license key confirmation in the focused Studio project over HTTP', async () => {
clearElementInstallStateForTests();
+ const deliveredEvents: EventSourceEvent[] = [];
+ const focusedUrls: string[] = [];
const directory = mkdtempSync(
path.join(tmpdir(), 'remotion-license-protocol-'),
);
@@ -366,7 +364,6 @@ test('sets a public license key in the focused Studio project over HTTP', async
'',
].join('\n'),
);
- const unsetRegistry = setFileWatcherRegistry(createFileWatcherRegistry());
const liveEventsServer: LiveEventsServer = {
addNewClientListener: () => () => undefined,
closeConnections: () => Promise.resolve(),
@@ -387,7 +384,14 @@ test('sets a public license key in the focused Studio project over HTTP', async
studioUrl: 'http://localhost:3000',
});
},
- sendEventToClientId: () => false,
+ sendEventToClientId: (clientId, event) => {
+ if (clientId !== 'focused-studio-tab') {
+ return false;
+ }
+
+ deliveredEvents.push(event);
+ return true;
+ },
};
const server = createServer((request, response) => {
const {pathname} = new URL(request.url ?? '/', 'http://localhost');
@@ -413,6 +417,8 @@ test('sets a public license key in the focused Studio project over HTTP', async
handleStudioProtocolLicenseKey({
configFile: loadedConfigFile,
+ focusStudioTab: (studioUrl) => focusedUrls.push(studioUrl),
+ liveEventsServer,
request,
response,
}).catch((error) => response.destroy(error));
@@ -498,15 +504,16 @@ test('sets a public license key in the focused Studio project over HTTP', async
expect(await response.json()).toEqual({
protocol: 'remotion-studio-protocol',
protocolVersion: 1,
- status: 'license-key-set',
+ status: 'awaiting-confirmation',
});
- expect(readFileSync(configFile, 'utf8')).toBe(
- [
- "import {Config} from '@remotion/cli/config';",
- `Config.setPublicLicenseKey('${validLicenseKey}');`,
- '',
- ].join('\n'),
- );
+ expect(readFileSync(configFile, 'utf8')).toContain('rm_pub_old');
+ expect(deliveredEvents).toEqual([
+ {
+ type: 'license-key-install-request',
+ licenseKey: validLicenseKey,
+ },
+ ]);
+ expect(focusedUrls).toEqual(['http://localhost:3000']);
const replay = await fetch(`${origin}/api/studio-protocol/license-key`, {
method: 'POST',
@@ -521,6 +528,8 @@ test('sets a public license key in the focused Studio project over HTTP', async
status: 'error',
error: {code: 'target-expired'},
});
+ expect(deliveredEvents).toHaveLength(1);
+ expect(focusedUrls).toHaveLength(1);
const noConfigDiscovery = await fetch(`${origin}/api/studio-protocol`, {
headers: {Origin: 'https://www.remotion.pro'},
@@ -555,7 +564,6 @@ test('sets a public license key in the focused Studio project over HTTP', async
await new Promise<void>((resolve, reject) => {
server.close((error) => (error ? reject(error) : resolve()));
});
- unsetRegistry();
rmSync(directory, {recursive: true, force: true});
clearElementInstallStateForTests();
}
diff --git a/packages/studio-shared/src/event-source-event.ts b/packages/studio-shared/src/event-source-event.ts
index 27976e7a77..15d4e021c8 100644
--- a/packages/studio-shared/src/event-source-event.ts
+++ b/packages/studio-shared/src/event-source-event.ts
@@ -87,6 +87,10 @@ export type EventSourceEvent =
type: 'element-install-request';
request: ElementInstallRequest;
}
+ | {
+ type: 'license-key-install-request';
+ licenseKey: string;
+ }
| {
type: 'visual-control-values-changed';
values: Array<{
diff --git a/packages/studio/src/components/Modals.tsx b/packages/studio/src/components/Modals.tsx
index 0fbe723f1e..f7f7945fae 100644
--- a/packages/studio/src/components/Modals.tsx
+++ b/packages/studio/src/components/Modals.tsx
@@ -1,4 +1,4 @@
-import React, {useContext} from 'react';
+import React, {useContext, useEffect} from 'react';
import ReactDOM from 'react-dom';
import {StudioServerConnectionCtx} from '../helpers/client-id';
import {getStudioAskAIEnabled} from '../helpers/studio-runtime-config';
@@ -30,11 +30,26 @@ import {UpdateModal} from './UpdateModal/UpdateModal';
export const Modals: React.FC<{
readonly readOnlyStudio: boolean;
}> = ({readOnlyStudio}) => {
- const {selectedModal: modalContextType} = useContext(ModalsContext);
+ const {selectedModal: modalContextType, setSelectedModal} =
+ useContext(ModalsContext);
const {currentZIndex} = useZIndex();
- const canRender =
- useContext(StudioServerConnectionCtx).previewServerState.type ===
- 'connected';
+ const {previewServerState, subscribeToEvent} = useContext(
+ StudioServerConnectionCtx,
+ );
+ const canRender = previewServerState.type === 'connected';
+
+ useEffect(() => {
+ return subscribeToEvent('license-key-install-request', (event) => {
+ if (event.type !== 'license-key-install-request') {
+ return;
+ }
+
+ setSelectedModal({
+ type: 'configure-license',
+ initialPublicLicenseKey: event.licenseKey,
+ });
+ });
+ }, [setSelectedModal, subscribeToEvent]);
return ReactDOM.createPortal(
<>
@@ -85,6 +100,7 @@ export const Modals: React.FC<{
)}
{modalContextType && modalContextType.type === 'configure-license' && (
<ConfigureLicenseModal
+ key={modalContextType.initialPublicLicenseKey}
initialPublicLicenseKey={modalContextType.initialPublicLicenseKey}
/>
)}