Skip to content

Open source CapCut alternative.

TypeScript

feat(site): scope Cut engine data per Donkey account [rebuild]

David Le5d206247a269
diff --git a/docs/guides/cut/README.md b/docs/guides/cut/README.md
index 51f74485..4e722c28 100644
--- a/docs/guides/cut/README.md
+++ b/docs/guides/cut/README.md
@@ -1,6 +1,6 @@
# Cut
-Cut (publicly "Donkey Cut") is a standalone, free video editor. Its product domain is `donkeycut.com` — a marketing landing at `/` and the editor at `/app/…` — while the legacy `cut.donkeyuse.com` keeps serving the editor at its root, unchanged. Both hosts serve only the client bundle — every page is client-rendered — and the page does all real work against the Cut engine: a local server the Donkey Mac app ships and supervises on the user's own Mac. The engine uses local disk, the app's bundled ffmpeg, on-device speech, and the user's own Claude/Codex CLI logins. Editing is account-free. The signed-in features are AI generation — images, video, and voiceovers — and the assistant's Gemini models: the page posts to Donkey's hosted inference routes with the user's Donkey session and credits. On `cut.donkeyuse.com` the auth cookie rides the registrable domain; `donkeycut.com` is a different registrable domain, so it signs in through an apex one-time-token handoff (`/cut-auth`) that sets a host-only cookie there. Generated media lands back in the project through the engine like any other file; Gemini chat turns, including their editor tool calls, run entirely in the page.
+Cut (publicly "Donkey Cut") is a standalone, free video editor. Its product domain is `donkeycut.com` — a marketing landing at `/` and the editor at `/app/…` — while the legacy `cut.donkeyuse.com` keeps serving the editor at its root, unchanged. Both hosts serve only the client bundle — every page is client-rendered — and the page does all real work against the Cut engine: a local server the Donkey Mac app ships and supervises on the user's own Mac. The engine uses local disk, the app's bundled ffmpeg, on-device speech, and the user's own Claude/Codex CLI logins. Using the app requires a Donkey sign-in, and every engine request carries the signed-in account id: each account's projects and library live in that account's own folder on the Mac, so accounts sharing a machine don't see each other's work. AI generation — images, video, and voiceovers — and the assistant's Gemini models additionally spend credits: the page posts to Donkey's hosted inference routes with the user's session and credits. On `cut.donkeyuse.com` the auth cookie rides the registrable domain; `donkeycut.com` is a different registrable domain, so it signs in through an apex one-time-token handoff (`/cut-auth`) that sets a host-only cookie there. Generated media lands back in the project through the engine like any other file; Gemini chat turns, including their editor tool calls, run entirely in the page.
**The one rule:** Cut's server side runs only on the user's Mac. On a hosted deploy every Cut API answers 404 before any handler runs, so the unauthenticated routes are unreachable there and nothing can execute off-Mac — the engine has no path to Donkey's production models; the page reaches them only through Donkey's own authenticated inference APIs. Don't wrap Cut's API routes in the Donkey auth helper, reach for Prisma, or bill against credits to "harden" them; local-only is the design for everything the engine does.
@@ -26,9 +26,11 @@ The client probes the engine's health endpoint (dedicated port first, dev server
Every Cut API route is a framework-free handler (web-standard request in, response out) registered once in a route table (`matchCutRoute`), namespaced under `/api/cut/*` to keep it clear of Donkey's own APIs. Both surfaces dispatch through that one table: the packaged engine mounts it directly, and the Next dev server reaches it through a single optional-catch-all route (`/api/cut/[[...slug]]`). They are the same router — static-over-dynamic precedence, HEAD, and 405s behave identically, and there is nowhere for the two to drift. The hosted 404 is applied once, in that shared dispatch.
+The shared dispatch also binds each request to the account id the page sends, and every project and library path builds on that account's folder — only the health probe runs outside a scope. A request without an id is refused before any handler runs. The engine has no way to verify the id (it never talks to the hosted backend), so this separates accounts that share a Mac; it is not protection against a hostile local user, who owns the disk anyway. Data written before scoping existed is adopted by the first account that connects.
+
## The engine
-The engine is a single compiled binary built from the site's Cut code and version-locked to the app: the app's dev run script and release packaging build and bundle it automatically (no separate step), and the app stamps its own release version into the engine's environment, so updates ride app releases. The Donkey app spawns it at launch — regardless of sign-in, since Cut is free and standalone — restarts it with backoff if it dies, and stops it on quit. The engine's lifetime is tied to the app process: the engine watches the pid that spawned it and exits when that process is gone, and at launch the app replaces an engine on the port stamped with a different version, so engine fixes always ship with the app update. An engine matching the app's version (another instance) or a developer-run "dev" engine is left alone. Its data lives under the user's Application Support; its logs under the user's Logs folder.
+The engine is a single compiled binary built from the site's Cut code and version-locked to the app: the app's dev run script and release packaging build and bundle it automatically (no separate step), and the app stamps its own release version into the engine's environment, so updates ride app releases. The Donkey app spawns it at launch — regardless of sign-in, since Cut is free and standalone — restarts it with backoff if it dies, and stops it on quit. The engine's lifetime is tied to the app process: the engine watches the pid that spawned it and exits when that process is gone, and at launch the app replaces an engine on the port stamped with a different version, so engine fixes always ship with the app update. An engine matching the app's version (another instance) or a developer-run "dev" engine is left alone. Its data lives under the user's Application Support, one folder per Donkey account; its logs under the user's Logs folder.
Because a GUI-spawned process inherits a bare PATH, the engine rebuilds it: tools shipped beside the engine binary first (they version with the app), then the app's bundled tools (bundled tool always wins), then the user's login-shell PATH and common install dirs. That is how it finds the speech tool, ffmpeg, and the user's `claude` and `codex`.
@@ -36,7 +38,7 @@ Because a GUI-spawned process inherits a bare PATH, the engine rebuilds it: tool
| Concern | Donkey | Cut |
| --- | --- | --- |
-| Sign-in | Required account | None for editing; AI generation and Gemini chat need one |
+| Sign-in | Required account | Required account; data is per-account on the Mac |
| Billing | Credits | Free; AI generation and Gemini chat spend credits |
| Storage | Database | Local disk |
| Model access | Hosted routes | CLI logins; AI generation and Gemini chat use Donkey's hosted routes (signed in) |
diff --git a/site/.gitignore b/site/.gitignore
index 7c8e197a..52c1261e 100644
--- a/site/.gitignore
+++ b/site/.gitignore
@@ -43,7 +43,9 @@ next-env.d.ts
/src/generated/prisma
-# Cut (video editor) local runtime data — per-project media/exports + shared library
+# Cut (video editor) local runtime data — per-user projects/library (plus
+# pre-scoping roots kept until a first sign-in adopts them)
+/users/
/projects/
/library/
diff --git a/site/scripts/eval-scene-live.ts b/site/scripts/eval-scene-live.ts
index f5e8dcce..7eeb2140 100644
--- a/site/scripts/eval-scene-live.ts
+++ b/site/scripts/eval-scene-live.ts
@@ -81,7 +81,7 @@ async function main(): Promise<void> {
if (ACTION === "fresh") {
const name = arg("--name") ?? `eval ${new Date().toISOString().slice(0, 16)}`;
- const res = await fetch(`${BASE}/api/cut/projects`, {
+ const res = await fetch(`${BASE}/api/cut/projects?u=donkey-dev-auth-bypass`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ name }),
diff --git a/site/src/cut/components/RequireSession.tsx b/site/src/cut/components/RequireSession.tsx
index 20930407..371cf383 100644
--- a/site/src/cut/components/RequireSession.tsx
+++ b/site/src/cut/components/RequireSession.tsx
@@ -3,6 +3,7 @@
import { useEffect, type ReactNode } from "react";
import { signInHrefFor } from "@/app/_components/landing/useAppEntryHref";
+import { setEngineUser } from "@/cut/lib/api";
import { DONKEYCUT_CANONICAL } from "@/cut/lib/hosts";
import { authClient } from "@/lib/auth-client";
import { useCutBase } from "@/cut/lib/nav";
@@ -10,9 +11,14 @@ import { useCutBase } from "@/cut/lib/nav";
// Session gate for the whole Cut app surface. The landing CTAs already route
// signed-out clicks through /sign-in (useAppEntryHref); this covers direct
// navigation to an app URL the same way, sending the visitor to sign-in with
-// the URL they wanted as the post-auth callback. While the session is still
-// resolving the app renders normally, so signed-in users (the common case) see
-// no gate at all.
+// the URL they wanted as the post-auth callback.
+//
+// The app renders only once the session is known: every engine URL carries
+// the account id (the engine keeps each account's data separate), so a
+// component rendered earlier would build unscoped media URLs. Holding
+// children until the id is bound makes that impossible; the session check is
+// a fast same-origin cookie read, and the ConnectGate's own connect flow
+// covers the moment visually.
//
// The legacy host (base "") has no /sign-in of its own — donkeycut.com owns
// auth — so its URLs redirect to the canonical host, mapped onto the same app
@@ -34,6 +40,7 @@ export function RequireSession({ children }: { children: ReactNode }) {
);
}, [signedOut, base]);
- if (signedOut) return null;
+ if (!session) return null;
+ setEngineUser(session.user.id);
return <>{children}</>;
}
diff --git a/site/src/cut/engine/serve.ts b/site/src/cut/engine/serve.ts
index 775b1c8e..7459435e 100644
--- a/site/src/cut/engine/serve.ts
+++ b/site/src/cut/engine/serve.ts
@@ -2,7 +2,7 @@ import { createServer, type IncomingMessage, type ServerResponse } from "node:ht
import { Readable } from "node:stream";
import { allowedOrigin, corsHeaders, preflightHeaders } from "../server/cors";
-import { matchCutRoute } from "../server/http/routes";
+import { matchCutRoute, runCutRoute } from "../server/http/routes";
import { ensureToolPath, resolveOnPath } from "../server/tool-path";
import { enginePort } from "./config";
@@ -132,7 +132,7 @@ async function start() {
void (async () => {
try {
const webReq = toWebRequest(req, aborter.signal);
- const webRes = await match.handler(webReq, match.params);
+ const webRes = await runCutRoute(webReq, match);
await writeResponse(webRes, res, cors, match.head);
} catch (err) {
if (!res.headersSent) {
diff --git a/site/src/cut/lib/api.ts b/site/src/cut/lib/api.ts
index ed5049aa..c3c48f3e 100644
--- a/site/src/cut/lib/api.ts
+++ b/site/src/cut/lib/api.ts
@@ -133,13 +133,30 @@ export function engineOrigin(): string {
return resolvedOrigin ?? "";
}
+// The signed-in Donkey account, set by RequireSession before the app renders.
+// Every engine URL carries it (the `u` param) — headers can't, because media
+// loads as plain <video>/<img> src — and the engine keeps each account's
+// projects and library in that user's own folder. The engine refuses data
+// requests without it, so a scope-less URL fails visibly instead of showing
+// another account's data.
+let engineUser: string | null = null;
+
+export function setEngineUser(id: string) {
+ engineUser = id;
+}
+
+const scopedPath = (path: string) =>
+ engineUser
+ ? `${path}${path.includes("?") ? "&" : "?"}u=${encodeURIComponent(engineUser)}`
+ : path;
+
/** Absolute-or-relative URL for an engine API path. */
-export const apiUrl = (path: string) => `${engineOrigin()}${path}`;
+export const apiUrl = (path: string) => `${engineOrigin()}${scopedPath(path)}`;
/** fetch() against the engine, resolving it first. */
export async function apiFetch(path: string, init?: RequestInit) {
const base = await engineReady();
- return fetch(`${base}${path}`, init);
+ return fetch(`${base}${scopedPath(path)}`, init);
}
/** JSON body of an engine reply. A reply that never reached a handler is plain
diff --git a/site/src/cut/server/http/next.ts b/site/src/cut/server/http/next.ts
index dee4b3dd..c5d5d2d9 100644
--- a/site/src/cut/server/http/next.ts
+++ b/site/src/cut/server/http/next.ts
@@ -1,6 +1,6 @@
import { hostedApiBlock } from "../local-only";
import { ensureToolPath } from "../tool-path";
-import { matchCutRoute } from "./routes";
+import { matchCutRoute, runCutRoute } from "./routes";
/**
* The Cut API surface as a Next route handler. A single optional-catch-all route
@@ -27,7 +27,7 @@ export async function cutCatchAll(req: Request): Promise<Response> {
});
}
- const res = await match.handler(req, match.params);
+ const res = await runCutRoute(req, match);
// A HEAD reply carries the GET headers but no body.
if (match.head && res.body) {
void res.body.cancel();
diff --git a/site/src/cut/server/http/routes.ts b/site/src/cut/server/http/routes.ts
index 7a2d2557..de7a590f 100644
--- a/site/src/cut/server/http/routes.ts
+++ b/site/src/cut/server/http/routes.ts
@@ -1,3 +1,4 @@
+import { adoptLegacyData, isValidCutUser, runWithCutUser } from "../userScope";
import { aiApi } from "./ai";
import { engineApi } from "./engine";
import { exportApi } from "./export";
@@ -11,6 +12,9 @@ interface CutRoute {
method: "GET" | "POST" | "PUT" | "DELETE";
path: string; // ":name" segments bind params
handler: TableHandler;
+ /** Health is the one route outside a user scope: probes and the app's
+ * supervisor hit it with no session in hand. */
+ scoped?: false;
}
/**
@@ -19,7 +23,7 @@ interface CutRoute {
* catch-all route and the packaged engine — so the two surfaces cannot drift.
*/
export const CUT_ROUTES: CutRoute[] = [
- { method: "GET", path: "/api/cut/engine/health", handler: () => engineApi.health() },
+ { method: "GET", path: "/api/cut/engine/health", handler: () => engineApi.health(), scoped: false },
{ method: "GET", path: "/api/cut/projects", handler: () => projectsApi.list() },
{ method: "POST", path: "/api/cut/projects", handler: (req) => projectsApi.create(req) },
@@ -87,9 +91,32 @@ export const CUT_ROUTES: CutRoute[] = [
];
export type RouteMatch =
- | { handler: TableHandler; params: Record<string, string>; head: boolean }
+ | { handler: TableHandler; params: Record<string, string>; head: boolean; scoped: boolean }
| { methodNotAllowed: string[] };
+/**
+ * Run a matched route inside the requesting user's data scope. The page
+ * appends the signed-in account id to every engine URL (api.ts); binding it
+ * here — the one dispatch both mounts share — means every handler, and every
+ * path built during it, is per-user by construction. A request without a
+ * valid id never reaches a handler.
+ */
+export async function runCutRoute(
+ req: Request,
+ match: { handler: TableHandler; params: Record<string, string>; scoped: boolean }
+): Promise<Response> {
+ if (!match.scoped) return match.handler(req, match.params);
+ const user = new URL(req.url).searchParams.get("u");
+ if (!user || !isValidCutUser(user)) {
+ return new Response(
+ JSON.stringify({ error: "This page is out of date with the Donkey app — reload the tab." }),
+ { status: 400, headers: { "Content-Type": "application/json" } }
+ );
+ }
+ await adoptLegacyData(user);
+ return runWithCutUser(user, () => match.handler(req, match.params));
+}
+
/** Bind a pattern against path segments. Returns the bound params and a
* specificity score (count of literal segment matches) so more-literal paths
* win, or null when the shape doesn't match. Params bind RAW (percent-encoded),
@@ -132,7 +159,14 @@ export function matchCutRoute(method: string, pathname: string): RouteMatch | nu
const chosen = matches.filter((m) => m.score === top);
const hit = chosen.find((m) => m.route.method === wanted);
- if (hit) return { handler: hit.route.handler, params: hit.params, head: method === "HEAD" };
+ if (hit) {
+ return {
+ handler: hit.route.handler,
+ params: hit.params,
+ head: method === "HEAD",
+ scoped: hit.route.scoped !== false,
+ };
+ }
// Path matched but this method has no handler → 405, as Next returns.
const allow = new Set<string>(chosen.map((m) => m.route.method));
diff --git a/site/src/cut/server/library.ts b/site/src/cut/server/library.ts
index aa4c6e38..6f1b58ad 100644
--- a/site/src/cut/server/library.ts
+++ b/site/src/cut/server/library.ts
@@ -1,15 +1,15 @@
import { spawn } from "node:child_process";
import { copyFile, mkdir, readFile, rm, writeFile } from "node:fs/promises";
import path from "node:path";
-import { cutDataRoot } from "./dataDir";
import { assertLocalRuntime } from "./local-only";
import { mediaPath as projectMediaPath, readProject } from "./projects";
+import { cutUserRoot } from "./userScope";
import { exists, uniqueName, writeJsonAtomic } from "./util";
-/** The shared library: reusable media that lives outside any project. */
-export const LIBRARY_ROOT = path.join(cutDataRoot(), "library");
-const LIB_MEDIA = path.join(LIBRARY_ROOT, "media");
-const INDEX = path.join(LIBRARY_ROOT, "library.json");
+/** The user's library: reusable media that lives outside any project. */
+const libraryRoot = () => path.join(cutUserRoot(), "library");
+const libMedia = () => path.join(libraryRoot(), "media");
+const indexPath = () => path.join(libraryRoot(), "library.json");
/** Where a URL-imported asset came from, kept as notes on the asset. */
export interface LibrarySource {
@@ -98,36 +98,36 @@ export function libMediaPath(fileName: string) {
assertLocalRuntime();
const safe = path.basename(fileName);
if (!safe || safe.startsWith(".")) throw new Error("Invalid file name.");
- return path.join(LIB_MEDIA, safe);
+ return path.join(libMedia(), safe);
}
async function readIndex(): Promise<LibraryIndex> {
assertLocalRuntime();
let raw: string;
try {
- raw = await readFile(INDEX, "utf8");
+ raw = await readFile(indexPath(), "utf8");
} catch {
return { assets: [] };
}
try {
return JSON.parse(raw) as LibraryIndex;
} catch (err) {
- console.error(`Corrupt library index ${INDEX}:`, err);
+ console.error(`Corrupt library index ${indexPath()}:`, err);
}
try {
- const idx = JSON.parse(await readFile(`${INDEX}.bak`, "utf8")) as LibraryIndex;
+ const idx = JSON.parse(await readFile(`${indexPath()}.bak`, "utf8")) as LibraryIndex;
await writeIndex(idx);
return idx;
} catch (err) {
- console.error(`Could not recover ${INDEX} from backup:`, err);
+ console.error(`Could not recover ${indexPath()} from backup:`, err);
return { assets: [] };
}
}
async function writeIndex(idx: LibraryIndex) {
assertLocalRuntime();
- await mkdir(LIB_MEDIA, { recursive: true });
- await writeJsonAtomic(INDEX, idx);
+ await mkdir(libMedia(), { recursive: true });
+ await writeJsonAtomic(indexPath(), idx);
}
// Serialize read-modify-write cycles on the shared index. Without this, moving
@@ -239,7 +239,7 @@ export async function register(
/** Upload a file straight into the library. */
export async function addUpload(file: File): Promise<LibraryAsset> {
if (!typeOf(file.name)) throw new Error("Unsupported file type.");
- await mkdir(LIB_MEDIA, { recursive: true });
+ await mkdir(libMedia(), { recursive: true });
const fileName = await freeName(file.name);
await writeFile(libMediaPath(fileName), Buffer.from(await file.arrayBuffer()));
return register(fileName, file.name);
@@ -253,7 +253,7 @@ export async function addFromProject(
): Promise<LibraryAsset> {
const src = projectMediaPath(projectId, fileName);
if (!(await exists(src))) throw new Error("Media file not found in project.");
- await mkdir(LIB_MEDIA, { recursive: true });
+ await mkdir(libMedia(), { recursive: true });
const dest = await freeName(fileName);
await copyFile(src, libMediaPath(dest));
return register(dest, name || fileName);
@@ -266,7 +266,7 @@ export async function addDownloaded(
source?: LibrarySource
): Promise<LibraryAsset> {
if (!typeOf(srcPath)) throw new Error("Unsupported file type.");
- await mkdir(LIB_MEDIA, { recursive: true });
+ await mkdir(libMedia(), { recursive: true });
const dest = await freeName(path.basename(srcPath));
await copyFile(srcPath, libMediaPath(dest));
return register(dest, name || path.basename(srcPath), source);
@@ -377,7 +377,7 @@ export async function saveTemplate(projectId: string, input: TemplateInput): Pro
if (!input.media?.length && !input.texts?.length && !input.cues?.length) {
throw new Error("Nothing to save.");
}
- await mkdir(LIB_MEDIA, { recursive: true });
+ await mkdir(libMedia(), { recursive: true });
const media: TemplateMedia[] = [];
for (const m of input.media) {
const src = projectMediaPath(projectId, m.fileName);
@@ -435,7 +435,7 @@ export async function addMediaToTemplate(
): Promise<LibraryTemplate> {
const src = projectMediaPath(projectId, input.media.fileName);
if (!(await exists(src))) throw new Error("Media file not found in project.");
- await mkdir(LIB_MEDIA, { recursive: true });
+ await mkdir(libMedia(), { recursive: true });
const dest = await freeName(input.media.fileName);
await copyFile(src, libMediaPath(dest));
try {
diff --git a/site/src/cut/server/projects.ts b/site/src/cut/server/projects.ts
index 67d8a52f..495d549f 100644
--- a/site/src/cut/server/projects.ts
+++ b/site/src/cut/server/projects.ts
@@ -1,23 +1,23 @@
import { cp, mkdir, readdir, readFile, rm, stat, writeFile } from "node:fs/promises";
import path from "node:path";
import type { ProjectDoc, ProjectFolder, ProjectSummary } from "@/cut/lib/types";
-import { cutDataRoot } from "./dataDir";
import { assertLocalRuntime } from "./local-only";
+import { cutUserRoot } from "./userScope";
import { exists, uniqueName, writeJsonAtomic } from "./util";
-/** All projects live here; each project is one folder holding project.json,
- * its raw media files, and its exports. */
-export const PROJECTS_ROOT = path.join(cutDataRoot(), "projects");
+/** The requesting user's projects live here; each project is one folder
+ * holding project.json, its raw media files, and its exports. */
+const projectsRoot = () => path.join(cutUserRoot(), "projects");
// Project folders are grouping metadata only; it lives beside the project dirs
// as a plain file, so the project-dir scan (which requires ID_RE) skips it.
-const FOLDERS_INDEX = path.join(PROJECTS_ROOT, "folders.json");
+const foldersIndex = () => path.join(projectsRoot(), "folders.json");
const ID_RE = /^[a-z0-9][a-z0-9-]{2,40}$/;
export function projectDir(id: string) {
assertLocalRuntime();
if (!ID_RE.test(id)) throw new Error("Invalid project id.");
- return path.join(PROJECTS_ROOT, id);
+ return path.join(projectsRoot(), id);
}
export const mediaDir = (id: string) => path.join(projectDir(id), "media");
@@ -185,7 +185,7 @@ async function summarize(id: string, doc: ProjectDoc): Promise<ProjectSummary> {
async function readFolders(): Promise<ProjectFolder[]> {
try {
- const raw = JSON.parse(await readFile(FOLDERS_INDEX, "utf8")) as { folders?: ProjectFolder[] };
+ const raw = JSON.parse(await readFile(foldersIndex(), "utf8")) as { folders?: ProjectFolder[] };
return Array.isArray(raw.folders) ? raw.folders : [];
} catch {
return [];
@@ -193,8 +193,8 @@ async function readFolders(): Promise<ProjectFolder[]> {
}
async function writeFolders(folders: ProjectFolder[]) {
- await mkdir(PROJECTS_ROOT, { recursive: true });
- await writeJsonAtomic(FOLDERS_INDEX, { folders });
+ await mkdir(projectsRoot(), { recursive: true });
+ await writeJsonAtomic(foldersIndex(), { folders });
}
export async function listProjectFolders(): Promise<ProjectFolder[]> {
@@ -227,7 +227,7 @@ export async function renameProjectFolder(id: string, name: string): Promise<Pro
export async function deleteProjectFolder(id: string) {
await writeFolders((await readFolders()).filter((f) => f.id !== id));
// Projects in the folder fall back to ungrouped rather than disappearing.
- const entries = await readdir(PROJECTS_ROOT, { withFileTypes: true }).catch(() => []);
+ const entries = await readdir(projectsRoot(), { withFileTypes: true }).catch(() => []);
await Promise.all(
entries
.filter((e) => e.isDirectory() && ID_RE.test(e.name))
@@ -268,8 +268,8 @@ export async function duplicateProject(id: string): Promise<ProjectSummary> {
export async function listProjects(): Promise<ProjectSummary[]> {
assertLocalRuntime();
- await mkdir(PROJECTS_ROOT, { recursive: true });
- const entries = await readdir(PROJECTS_ROOT, { withFileTypes: true });
+ await mkdir(projectsRoot(), { recursive: true });
+ const entries = await readdir(projectsRoot(), { withFileTypes: true });
const names = entries
.filter((e) => e.isDirectory() && ID_RE.test(e.name))
.map((e) => e.name);
diff --git a/site/src/cut/server/userScope.ts b/site/src/cut/server/userScope.ts
new file mode 100644
index 00000000..19ff32e2
--- /dev/null
+++ b/site/src/cut/server/userScope.ts
@@ -0,0 +1,58 @@
+import { AsyncLocalStorage } from "node:async_hooks";
+import { mkdir, rename } from "node:fs/promises";
+import path from "node:path";
+import { cutDataRoot } from "./dataDir";
+import { exists } from "./util";
+
+/**
+ * Every data route runs inside a signed-in user's scope: the page sends the
+ * Donkey account id with each engine request (the `u` query param api.ts
+ * appends), the dispatcher binds it here, and all project/library paths hang
+ * off users/<id> under the data root. The engine cannot verify the id — it
+ * never talks to the hosted backend — so this is per-account separation on a
+ * shared Mac, not protection against a hostile local user.
+ */
+const scope = new AsyncLocalStorage<string>();
+
+// Donkey account ids are URL-safe tokens; anything else is refused before it
+// can become a filesystem path.
+const USER_ID_RE = /^[A-Za-z0-9_-]{1,64}$/;
+
+export const isValidCutUser = (id: string) => USER_ID_RE.test(id);
+
+export function runWithCutUser<T>(id: string, fn: () => T): T {
+ if (!isValidCutUser(id)) throw new Error("Invalid user id.");
+ return scope.run(id, fn);
+}
+
+/** The current request's per-user data root. Path helpers build on this, so a
+ * path outside a user scope is impossible by construction. */
+export function cutUserRoot(): string {
+ const id = scope.getStore();
+ if (!id) throw new Error("No user scope bound to this request.");
+ return path.join(cutDataRoot(), "users", id);
+}
+
+// Data written before user scoping lived directly under the data root. The
+// first account to connect adopts it — the same single owner who could see it
+// before — by moving those folders into its own scope.
+const LEGACY_DIRS = ["projects", "library"];
+let adopting: Promise<void> | null = null;
+
+export function adoptLegacyData(id: string): Promise<void> {
+ adopting ??= (async () => {
+ const root = cutDataRoot();
+ for (const dir of LEGACY_DIRS) {
+ const from = path.join(root, dir);
+ if (!(await exists(from))) continue;
+ const to = path.join(root, "users", id, dir);
+ if (await exists(to)) continue;
+ await mkdir(path.dirname(to), { recursive: true });
+ await rename(from, to);
+ }
+ })().catch((err) => {
+ adopting = null; // retry on the next request instead of pinning the failure
+ throw err;
+ });
+ return adopting;
+}