🎥 Make videos programmatically with React
`@remotion/studio-server`: Contain Element writes inside the project (#9925)
Igor Samokhovetsabbb487b6190
diff --git a/packages/studio-server/src/preview-server/routes/insert-element.ts b/packages/studio-server/src/preview-server/routes/insert-element.tsindex 510dd0629b..91cd722d81 100644--- a/packages/studio-server/src/preview-server/routes/insert-element.ts+++ b/packages/studio-server/src/preview-server/routes/insert-element.ts@@ -20,6 +20,7 @@ import {suppressUndoStackInvalidation,} from '../undo-stack';import {warnAboutPrettierOnce} from './log-updates/log-update';+import {getSafeElementInstallPaths} from './safe-element-install-path';import {withSourceFileWriteQueue} from './source-file-write-queue';const validatePosition = (@@ -34,14 +35,6 @@ const validatePosition = (}};-const isInside = ({child, parent}: {child: string; parent: string}) => {- const relative = path.relative(parent, child);- return (- relative === '' ||- (!relative.startsWith('..') && !path.isAbsolute(relative))- );-};-const withoutTsxExtension = (fileName: string) => {return fileName.replace(/\.tsx$/, '');};@@ -175,13 +168,15 @@ export const insertElementHandler: ApiHandler<);}- const elementFileName = path.resolve(- path.dirname(location.fileName),- derivedElementFileName,- );- if (!isInside({child: elementFileName, parent: remotionRoot})) {- throw new Error('Element file must stay inside the Remotion project');- }+ const safePaths = await getSafeElementInstallPaths({+ compositionFileName: location.fileName,+ elementFileName: path.resolve(+ path.dirname(location.fileName),+ derivedElementFileName,+ ),+ remotionRoot,+ });+ const {elementFileName} = safePaths;const elementFileExists = existsSync(elementFileName);const existingElementSource = elementFileExists@@ -198,7 +193,7 @@ export const insertElementHandler: ApiHandler<type: 'file-conflict',conflict: {filePath: path- .relative(remotionRoot, elementFileName)+ .relative(safePaths.remotionRoot, elementFileName).split(path.sep).join('/'),existingSource: existingElementSource,@@ -236,6 +231,19 @@ export const insertElementHandler: ApiHandler<},});+ const finalSafePaths = await getSafeElementInstallPaths({+ compositionFileName: inserted.fileName,+ elementFileName,+ remotionRoot,+ });+ if (+ finalSafePaths.compositionFileName !== safePaths.compositionFileName+ ) {+ throw new Error(+ 'Composition source changed during Element installation',+ );+ }+pushTransactionToUndoStack({snapshots: [...(shouldWriteElementFilediff --git a/packages/studio-server/src/preview-server/routes/safe-element-install-path.ts b/packages/studio-server/src/preview-server/routes/safe-element-install-path.tsnew file mode 100644index 0000000000..b0d74278b2--- /dev/null+++ b/packages/studio-server/src/preview-server/routes/safe-element-install-path.ts@@ -0,0 +1,82 @@+import {lstat, realpath} from 'node:fs/promises';+import path from 'node:path';++const isInside = ({child, parent}: {child: string; parent: string}) => {+ const relative = path.relative(parent, child);+ return (+ relative === '' ||+ (!relative.startsWith('..') && !path.isAbsolute(relative))+ );+};++const assertInsideProject = ({+ fileName,+ remotionRoot,+}: {+ fileName: string;+ remotionRoot: string;+}) => {+ if (!isInside({child: fileName, parent: remotionRoot})) {+ throw new Error(+ 'Element installation must stay inside the Remotion project',+ );+ }+};++const getCanonicalProjectRoot = async (remotionRoot: string) => {+ return realpath(remotionRoot);+};++export const getSafeElementInstallPaths = async ({+ compositionFileName,+ elementFileName,+ remotionRoot,+}: {+ compositionFileName: string;+ elementFileName: string;+ remotionRoot: string;+}) => {+ const canonicalRoot = await getCanonicalProjectRoot(remotionRoot);+ const canonicalCompositionFile = await realpath(compositionFileName);+ assertInsideProject({+ fileName: canonicalCompositionFile,+ remotionRoot: canonicalRoot,+ });++ // The Element directory already exists because it is the composition file's+ // directory. Resolving it before appending the file name prevents writes+ // through a directory symlink that leaves the project.+ const canonicalElementDirectory = await realpath(+ path.dirname(elementFileName),+ );+ assertInsideProject({+ fileName: canonicalElementDirectory,+ remotionRoot: canonicalRoot,+ });++ const canonicalElementFile = path.join(+ canonicalElementDirectory,+ path.basename(elementFileName),+ );++ try {+ const elementStats = await lstat(canonicalElementFile);+ if (elementStats.isSymbolicLink()) {+ throw new Error('Element source file must not be a symbolic link');+ }++ if (!elementStats.isFile()) {+ throw new Error('Element source path must be a file');+ }+ } catch (error) {+ if ((error as NodeJS.ErrnoException).code !== 'ENOENT') {+ throw error;+ }+ }++ return {+ compositionFileName: canonicalCompositionFile,+ elementFileName: canonicalElementFile,+ remotionRoot: canonicalRoot,+ };+};diff --git a/packages/studio-server/src/test/insert-element.test.ts b/packages/studio-server/src/test/insert-element.test.tsindex 8c6abcb910..6220c9c66b 100644--- a/packages/studio-server/src/test/insert-element.test.ts+++ b/packages/studio-server/src/test/insert-element.test.ts@@ -4,6 +4,7 @@ import {mkdtempSync,readFileSync,rmSync,+ symlinkSync,writeFileSync,} from 'node:fs';import {tmpdir} from 'node:os';@@ -53,6 +54,9 @@ const element = {const makeFixture = () => {const remotionRoot = mkdtempSync(path.join(tmpdir(), 'remotion-element-'));+ const outsideRoot = mkdtempSync(+ path.join(tmpdir(), 'remotion-element-outside-'),+ );const compositionFile = path.join(remotionRoot, 'Root.tsx');const elementFile = path.join(remotionRoot, 'lower-third.element.tsx');writeFileSync(compositionFile, compositionSource);@@ -103,9 +107,16 @@ const makeFixture = () => {cleanupLiveEvents();cleanupFileWatcher();rmSync(remotionRoot, {force: true, recursive: true});+ rmSync(outsideRoot, {force: true, recursive: true});};- return {callHandler, cleanup, compositionFile, elementFile};+ return {+ callHandler,+ cleanup,+ compositionFile,+ elementFile,+ outsideRoot,+ };};test('creates a new Element file without an overwrite conflict', async () => {@@ -170,6 +181,53 @@ test('returns a structured conflict without changing the project', async () => {}});+test('rejects an Element source symlink that escapes the project', async () => {+ const fixture = makeFixture();+ try {+ const outsideElement = path.join(+ fixture.outsideRoot,+ 'lower-third.element.tsx',+ );+ writeFileSync(outsideElement, existingElementSource);+ symlinkSync(outsideElement, fixture.elementFile);++ const response = await fixture.callHandler(true);++ expect(response).toMatchObject({+ success: false,+ type: 'error',+ reason: 'Element source file must not be a symbolic link',+ });+ expect(readFileSync(outsideElement, 'utf-8')).toBe(existingElementSource);+ expect(readFileSync(fixture.compositionFile, 'utf-8')).toBe(+ compositionSource,+ );+ } finally {+ fixture.cleanup();+ }+});++test('rejects a composition source symlink that escapes the project', async () => {+ const fixture = makeFixture();+ try {+ const outsideComposition = path.join(fixture.outsideRoot, 'Root.tsx');+ writeFileSync(outsideComposition, compositionSource);+ rmSync(fixture.compositionFile);+ symlinkSync(outsideComposition, fixture.compositionFile);++ const response = await fixture.callHandler(false);++ expect(response).toMatchObject({+ success: false,+ type: 'error',+ reason: 'Element installation must stay inside the Remotion project',+ });+ expect(readFileSync(outsideComposition, 'utf-8')).toBe(compositionSource);+ } finally {+ fixture.cleanup();+ }+});+test('overwrites conflicting source and undo restores both files', async () => {const fixture = makeFixture();try {