Skip to content

🎥 Make videos programmatically with React

`template-vibe-code`: Validate file names client-side and protect the entry point

Jonny Burger67ca2d8ee7aa
diff --git a/packages/template-vibe-code/src/app/api/project/route.ts b/packages/template-vibe-code/src/app/api/project/route.ts
index d7fe810e76..7cc39e540e 100644
--- a/packages/template-vibe-code/src/app/api/project/route.ts
+++ b/packages/template-vibe-code/src/app/api/project/route.ts
@@ -1,9 +1,6 @@
import { NextResponse } from "next/server";
-import {
- isAllowedProjectPath,
- readProjectFiles,
- writeProjectFiles,
-} from "@/server/project-files";
+import { isAllowedProjectPath } from "@/lib/project-paths";
+import { readProjectFiles, writeProjectFiles } from "@/server/project-files";
// Saving writes to src/remotion on disk, which only makes sense while
// developing locally. Deployed instances keep edits in memory.
diff --git a/packages/template-vibe-code/src/app/page.tsx b/packages/template-vibe-code/src/app/page.tsx
index f3788a6a86..eca16319d2 100644
--- a/packages/template-vibe-code/src/app/page.tsx
+++ b/packages/template-vibe-code/src/app/page.tsx
@@ -1,5 +1,6 @@
import { Editor } from "@/editor/Editor";
-import { PROJECT_ENTRY_POINT, readProjectFiles } from "@/server/project-files";
+import { PROJECT_ENTRY_POINT } from "@/lib/project-paths";
+import { readProjectFiles } from "@/server/project-files";
// Always read the project fresh from disk so edits made outside the browser
// show up after a reload.
diff --git a/packages/template-vibe-code/src/editor/Editor.tsx b/packages/template-vibe-code/src/editor/Editor.tsx
index 0a7737c407..4b97193db6 100644
--- a/packages/template-vibe-code/src/editor/Editor.tsx
+++ b/packages/template-vibe-code/src/editor/Editor.tsx
@@ -209,6 +209,7 @@ export const Editor: React.FC<{
const actions = useEditorActions({
context: {
state,
+ entryPoint,
host,
layers,
compositions,
@@ -260,6 +261,7 @@ export const Editor: React.FC<{
const value: EditorContextValue = {
state,
dispatch,
+ entryPoint,
canSave,
host,
hostError,
diff --git a/packages/template-vibe-code/src/editor/components/SidebarPanel.tsx b/packages/template-vibe-code/src/editor/components/SidebarPanel.tsx
index 963b8a30ec..f5c40872e2 100644
--- a/packages/template-vibe-code/src/editor/components/SidebarPanel.tsx
+++ b/packages/template-vibe-code/src/editor/components/SidebarPanel.tsx
@@ -17,6 +17,7 @@ import {
} from "@/components/ui/context-menu";
import { Input } from "@/components/ui/input";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
+import { PROJECT_DIR } from "@/lib/project-paths";
import { cn } from "@/lib/utils";
import type { CompositionInfo } from "../model/compositions";
import { getFileName, sortFilePaths } from "../model/project";
@@ -149,10 +150,10 @@ const FileRow: React.FC<{
readonly filePath: string;
readonly active: boolean;
}> = ({ filePath, active }) => {
- const { actions, state } = useEditor();
+ const { actions, entryPoint } = useEditor();
const [renaming, setRenaming] = useState(false);
- const isEntry =
- Object.keys(state.files).length > 1 && /index\.tsx?$/.test(filePath);
+ // The entry point calls registerRoot(); without it nothing compiles.
+ const isEntry = filePath === entryPoint;
if (renaming) {
return (
@@ -177,7 +178,11 @@ const FileRow: React.FC<{
type="button"
aria-pressed={active}
onClick={() => actions.openFile(filePath)}
- onDoubleClick={() => setRenaming(true)}
+ onDoubleClick={() => {
+ if (!isEntry) {
+ setRenaming(true);
+ }
+ }}
className={cn(
"flex w-full items-center gap-2 px-3 py-1.5 text-left text-xs outline-none",
active
@@ -199,7 +204,7 @@ const FileRow: React.FC<{
</button>
</ContextMenuTrigger>
<ContextMenuContent>
- <ContextMenuItem onSelect={() => setRenaming(true)}>
+ <ContextMenuItem disabled={isEntry} onSelect={() => setRenaming(true)}>
Rename
</ContextMenuItem>
<ContextMenuSeparator />
@@ -219,8 +224,6 @@ export const SidebarPanel: React.FC = () => {
const { state, dispatch, actions, compositions, activeComposition } =
useEditor();
const [creating, setCreating] = useState<"composition" | "file" | null>(null);
- const directory =
- Object.keys(state.files)[0]?.split("/").slice(0, -1).join("/") ?? "src";
return (
<Tabs
@@ -289,23 +292,11 @@ export const SidebarPanel: React.FC = () => {
<TabsContent value="files" className="min-h-0 overflow-y-auto py-1">
{creating === "file" ? (
<InlineInput
- placeholder={`${directory}/NewComponent.tsx`}
- initialValue={`${directory}/`}
+ placeholder={`${PROJECT_DIR}/NewComponent.tsx`}
+ initialValue={`${PROJECT_DIR}/`}
onSubmit={(filePath) => {
setCreating(null);
- const componentName = getFileName(filePath).replace(/\.\w+$/, "");
- actions.createFile(
- filePath,
- /\.tsx$/.test(filePath)
- ? `import React from "react";
-import { AbsoluteFill } from "remotion";
-
-export const ${componentName}: React.FC = () => {
- return <AbsoluteFill />;
-};
-`
- : "",
- );
+ actions.createFile(filePath);
}}
onCancel={() => setCreating(null)}
/>
diff --git a/packages/template-vibe-code/src/editor/hooks/use-editor-actions.ts b/packages/template-vibe-code/src/editor/hooks/use-editor-actions.ts
index e39b084f8c..37032bef80 100644
--- a/packages/template-vibe-code/src/editor/hooks/use-editor-actions.ts
+++ b/packages/template-vibe-code/src/editor/hooks/use-editor-actions.ts
@@ -36,7 +36,8 @@ import type {
import type { CompositionInfo } from "../model/compositions";
import { formatSource } from "../model/format";
import { areSiblingNodes, type Layer } from "../model/layers";
-import { toCodemodProject } from "../model/project";
+import { getFileName, toCodemodProject } from "../model/project";
+import { resolveProjectPathInput } from "@/lib/project-paths";
import type { PlaybackStore } from "./use-playback";
import { getErrorMessage } from "./use-preview-host";
import type {
@@ -49,6 +50,7 @@ const zoomLevels = [0.1, 0.25, 0.5, 0.75, 1, 1.5, 2, 3, 4];
type ActionContext = {
state: EditorState;
+ entryPoint: string;
host: PreviewHost | null;
layers: Layer[];
compositions: CompositionInfo[];
@@ -168,12 +170,31 @@ export const useEditorActions = ({
coalesceKey: `edit:${filePath}`,
});
},
- createFile: (filePath: string, contents: string) => {
+ // File names are validated with the same rules as /api/project, so a
+ // single bad name cannot make every later save fail.
+ createFile: (input: string) => {
+ const resolved = resolveProjectPathInput(input);
+ if (resolved.error !== null) {
+ notifyError(new Error(resolved.error));
+ return;
+ }
+
+ const filePath = resolved.path;
if (filePath in ref.current.state.files) {
notifyError(new Error(`${filePath} already exists.`));
return;
}
+ const componentName = getFileName(filePath).replace(/\.\w+$/, "");
+ const contents = /\.(tsx|jsx)$/.test(filePath)
+ ? `import React from "react";
+import { AbsoluteFill } from "remotion";
+
+export const ${componentName}: React.FC = () => {
+ return <AbsoluteFill />;
+};
+`
+ : "";
dispatch({
type: "set-files",
files: { ...ref.current.state.files, [filePath]: contents },
@@ -182,12 +203,37 @@ export const useEditorActions = ({
dispatch({ type: "open-file", filePath });
},
deleteFile: (filePath: string) => {
+ if (filePath === ref.current.entryPoint) {
+ notifyError(
+ new Error(`${filePath} is the entry point and cannot be deleted.`),
+ );
+ return;
+ }
+
const files = { ...ref.current.state.files };
delete files[filePath];
dispatch({ type: "set-files", files, coalesceKey: null });
},
- renameFile: (filePath: string, nextPath: string) => {
+ renameFile: (filePath: string, input: string) => {
+ if (filePath === ref.current.entryPoint) {
+ notifyError(
+ new Error(`${filePath} is the entry point and cannot be renamed.`),
+ );
+ return;
+ }
+
+ const resolved = resolveProjectPathInput(input);
+ if (resolved.error !== null) {
+ notifyError(new Error(resolved.error));
+ return;
+ }
+
+ const nextPath = resolved.path;
const { files } = ref.current.state;
+ if (nextPath === filePath) {
+ return;
+ }
+
if (nextPath in files) {
notifyError(new Error(`${nextPath} already exists.`));
return;
diff --git a/packages/template-vibe-code/src/editor/state/editor-context.tsx b/packages/template-vibe-code/src/editor/state/editor-context.tsx
index b2b39e2755..f03d4e2333 100644
--- a/packages/template-vibe-code/src/editor/state/editor-context.tsx
+++ b/packages/template-vibe-code/src/editor/state/editor-context.tsx
@@ -13,6 +13,8 @@ import type { EditorAction, EditorState } from "./editor-store";
export type EditorContextValue = {
state: EditorState;
dispatch: React.Dispatch<EditorAction>;
+ /** The file that calls registerRoot(); it cannot be renamed or deleted. */
+ entryPoint: string;
canSave: boolean;
host: PreviewHost | null;
hostError: string | null;
diff --git a/packages/template-vibe-code/src/lib/project-paths.ts b/packages/template-vibe-code/src/lib/project-paths.ts
new file mode 100644
index 0000000000..272649dc5f
--- /dev/null
+++ b/packages/template-vibe-code/src/lib/project-paths.ts
@@ -0,0 +1,75 @@
+// Path rules for the Remotion project that the editor edits. This module is
+// shared by the browser (validating new file names) and the server (guarding
+// what /api/project may read and write), so it must not use Node.js APIs.
+
+export const PROJECT_DIR = "src/remotion";
+export const PROJECT_ENTRY_POINT = `${PROJECT_DIR}/index.ts`;
+export const PROJECT_FILE_EXTENSIONS = [
+ ".ts",
+ ".tsx",
+ ".js",
+ ".jsx",
+ ".css",
+ ".json",
+];
+
+export const isAllowedProjectPath = (filePath: string): boolean => {
+ if (filePath.includes("\\") || filePath.includes("\0")) {
+ return false;
+ }
+
+ const segments = filePath.split("/");
+ const projectSegments = PROJECT_DIR.split("/");
+ if (
+ segments.length <= projectSegments.length ||
+ projectSegments.some((segment, index) => segments[index] !== segment) ||
+ segments.some(
+ (segment) => segment === "" || segment === "." || segment === "..",
+ )
+ ) {
+ return false;
+ }
+
+ const fileName = segments[segments.length - 1];
+ const dot = fileName.lastIndexOf(".");
+ return dot > 0 && PROJECT_FILE_EXTENSIONS.includes(fileName.slice(dot));
+};
+
+/**
+ * Turns a file name typed by the user into a project path: relative names
+ * are placed inside the project folder and a missing extension defaults to
+ * `.tsx`. Returns an error message for paths the server would reject.
+ */
+export const resolveProjectPathInput = (
+ input: string,
+): { path: string; error: null } | { path: null; error: string } => {
+ let path = input.trim().replace(/^(\.\/)+/, "");
+ if (path === "" || path === PROJECT_DIR || path === `${PROJECT_DIR}/`) {
+ return { path: null, error: "Enter a file name." };
+ }
+
+ const outsideError = {
+ path: null,
+ error: `Files must be inside ${PROJECT_DIR} and end with ${PROJECT_FILE_EXTENSIONS.join(", ")}.`,
+ };
+ if (!path.startsWith(`${PROJECT_DIR}/`)) {
+ // Absolute paths and paths under another top-level folder are mistakes
+ // rather than names to place inside the project.
+ if (path.startsWith("/") || path === "src" || path.startsWith("src/")) {
+ return outsideError;
+ }
+
+ path = `${PROJECT_DIR}/${path}`;
+ }
+
+ const fileName = path.split("/").at(-1) ?? "";
+ if (!fileName.includes(".")) {
+ path = `${path}.tsx`;
+ }
+
+ if (!isAllowedProjectPath(path)) {
+ return outsideError;
+ }
+
+ return { path, error: null };
+};
diff --git a/packages/template-vibe-code/src/server/project-files.ts b/packages/template-vibe-code/src/server/project-files.ts
index 37d28b0b17..661920187b 100644
--- a/packages/template-vibe-code/src/server/project-files.ts
+++ b/packages/template-vibe-code/src/server/project-files.ts
@@ -1,42 +1,15 @@
import { promises as fs } from "node:fs";
import path from "node:path";
+import { isAllowedProjectPath, PROJECT_DIR } from "@/lib/project-paths";
// The Remotion project that is loaded into the editor lives in src/remotion.
// It is a regular Remotion project: `npx remotion studio` and
// `npx remotion render` work on the same files.
-export const PROJECT_DIR = "src/remotion";
-export const PROJECT_ENTRY_POINT = `${PROJECT_DIR}/index.ts`;
-
+//
// Keeping the folder literal lets Next.js trace only these files into the
// server bundle instead of the whole project.
const projectRoot = path.join(process.cwd(), "src", "remotion");
-const allowedExtensions = new Set([
- ".ts",
- ".tsx",
- ".js",
- ".jsx",
- ".css",
- ".json",
-]);
-
-export const isAllowedProjectPath = (filePath: string) => {
- if (filePath.includes("\\") || filePath.includes("\0")) {
- return false;
- }
-
- const normalized = path.posix.normalize(filePath);
- if (
- normalized !== filePath ||
- !normalized.startsWith(`${PROJECT_DIR}/`) ||
- normalized.split("/").some((segment) => segment === "..")
- ) {
- return false;
- }
-
- return allowedExtensions.has(path.posix.extname(normalized));
-};
-
const resolveProjectPath = (filePath: string) => {
if (!isAllowedProjectPath(filePath)) {
throw new Error(`Refusing to access "${filePath}" outside ${PROJECT_DIR}`);