Open source CapCut alternative.
TypeScript
feat(cut): sign a whole media tree for one HLS ladder [rebuild]
David Le9f52fd7b07af
diff --git a/site/src/cut/server/cloud/mediaCdn.test.ts b/site/src/cut/server/cloud/mediaCdn.test.tsindex f6ad4ddc..66204550 100644--- a/site/src/cut/server/cloud/mediaCdn.test.ts+++ b/site/src/cut/server/cloud/mediaCdn.test.ts@@ -3,7 +3,14 @@ import { describe, expect, test } from "bun:test";import { contentDisposition, mediaDownloadName } from "./mediaName";process.env.CUT_MEDIA_SIGNING_SECRET = "test-media-signing-secret";-const { mediaObjectUrl, mediaSignature, mediaUrlLifetime } = await import("./mediaCdn");+const {+ MEDIA_TREE_PREFIX,+ mediaObjectUrl,+ mediaSignature,+ mediaTreeSignature,+ mediaTreeUrl,+ mediaUrlLifetime,+} = await import("./mediaCdn");const SECRET = "test-media-signing-secret";@@ -99,6 +106,92 @@ describe("tokens are stable inside a window", () => {});});+/** The Worker's tree verifier, transcribed from worker/cf/media.ts for the same+ * reason as the object one above. */+async function workerTreeSignature(+ secret: string,+ prefix: string,+ expires: number+): Promise<string> {+ const cryptoKey = await crypto.subtle.importKey(+ "raw",+ new TextEncoder().encode(secret),+ { name: "HMAC", hash: "SHA-256" },+ false,+ ["sign"]+ );+ const mac = await crypto.subtle.sign(+ "HMAC",+ cryptoKey,+ new TextEncoder().encode(`tree\n${prefix}\n${expires}`)+ );+ let binary = "";+ for (const byte of new Uint8Array(mac)) binary += String.fromCharCode(byte);+ return btoa(binary).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");+}++const PREFIX = "cut/user1/projects/p1/hls/v1abc";++describe("tree tokens", () => {+ test("signer and verifier agree", async () => {+ const expires = 1_750_000_000;+ expect(mediaTreeSignature(SECRET, PREFIX, expires)).toBe(+ await workerTreeSignature(SECRET, PREFIX, expires)+ );+ });++ test("a tree signature is not an object signature", () => {+ const at = 1_750_000_000;+ // Framing them differently is what stops a token minted for a whole prefix+ // from being replayed as one for the single object at that path.+ expect(mediaTreeSignature(SECRET, PREFIX, at)).not.toBe(+ mediaSignature(SECRET, PREFIX, at, "", "")+ );+ });++ test("the URL carries the depth the Worker needs to recover the prefix", () => {+ const url = new URL(mediaTreeUrl(PREFIX, "master.m3u8"));+ const segments = url.pathname.replace(/^\/+/, "").split("/");+ expect(segments[0]).toBe(MEDIA_TREE_PREFIX);+ const depth = Number(segments[2]);+ expect(depth).toBe(PREFIX.split("/").length);+ expect(segments.slice(4, 4 + depth).join("/")).toBe(PREFIX);+ expect(segments.slice(4 + depth).join("/")).toBe("master.m3u8");+ });++ test("a relative hop from the playlist keeps the token", () => {+ // This is the whole reason the token is in the path: a player resolves+ // "720p/seg00001.ts" against the master's URL, and everything before the+ // last slash — token included — comes along.+ const master = mediaTreeUrl(PREFIX, "master.m3u8");+ const variant = new URL("720p/index.m3u8", master);+ const segment = new URL("seg00001.ts", variant);+ const token = new URL(master).pathname.split("/").slice(0, 5).join("/");+ expect(segment.pathname.startsWith(token)).toBe(true);+ expect(segment.pathname.endsWith(`${PREFIX}/720p/seg00001.ts`)).toBe(true);+ });++ test("no query string, so nothing is lost on that hop", () => {+ expect(new URL(mediaTreeUrl(PREFIX, "master.m3u8")).search).toBe("");+ });++ test("the hold is bounded, so a token is never an open-ended grant", () => {+ const week = 7 * 24 * 60 * 60;+ const expires = Number(+ new URL(mediaTreeUrl(PREFIX, "master.m3u8", { holdSeconds: week })).pathname.split("/")[2]+ );+ expect(expires).toBeLessThan(Math.floor(Date.now() / 1000) + week);+ });++ test("a long cut still gets a token that outlasts watching it", () => {+ const twoHours = 2 * 60 * 60;+ const expires = Number(+ new URL(mediaTreeUrl(PREFIX, "master.m3u8", { holdSeconds: twoHours })).pathname.split("/")[2]+ );+ expect(expires).toBeGreaterThan(Math.floor(Date.now() / 1000) + twoHours);+ });+});+describe("download names", () => {test("quotes and newlines come out", () => {expect(mediaDownloadName('a"b\r\nc')).toBe("abc");diff --git a/site/src/cut/server/cloud/mediaCdn.ts b/site/src/cut/server/cloud/mediaCdn.tsindex 8397b8bf..ea29a861 100644--- a/site/src/cut/server/cloud/mediaCdn.ts+++ b/site/src/cut/server/cloud/mediaCdn.ts@@ -65,6 +65,11 @@ function tokenExpiry(minLifetimeSeconds = TOKEN_GRACE_SECONDS, at = Date.now()):* ahead of expiry rather than after a 403. */export const mediaUrlLifetime = (): number => tokenExpiry() - Math.floor(Date.now() / 1000);+/** The longest a tree token may live. A tree token is the revocation window for+ * everything under its prefix, so a very long cut does not get to hold one+ * open indefinitely. */+const TREE_MAX_LIFETIME_SECONDS = 24 * 60 * 60;+/** The signature over one object, its expiry, and the download name and version* it carries — both empty when absent, so the framing is one rule. Signing them* is what keeps either from being edited into a URL after the fact. Both sides@@ -105,3 +110,53 @@ export function mediaObjectUrl(if (name) query.set("d", name);return `${CUT_MEDIA_ORIGIN}/${path}?${query.toString()}`;}++// --- Tree tokens: one signature over a whole prefix ---+//+// An HLS ladder is hundreds of objects that the player discovers on its own:+// the master playlist names variant playlists, and each variant names its+// segments, all as RELATIVE URIs. Relative resolution keeps path segments and+// drops the query string, so the per-object token above cannot survive the hop+// from a playlist to the segments it references — the player would ask for+// every segment unsigned.+//+// So a tree token rides in the PATH instead: /_t/<expires>/<depth>/<sig>/<key>.+// A playlist fetched through that path resolves its relative children under the+// same four segments, and the whole ladder plays on one signature.+//+// `depth` is how many leading segments of the key the signature covers, which+// is what lets the Worker recover the prefix from a URL it has never seen+// before. The framing is distinct from the object signature's, so neither kind+// of token can be replayed as the other.++/** Marks the token path. Leading underscore keeps it clear of the key space,+ * which is always rooted at `cut/`. */+export const MEDIA_TREE_PREFIX = "_t";++export function mediaTreeSignature(secret: string, prefix: string, expires: number): string {+ return createHmac("sha256", secret).update(`tree\n${prefix}\n${expires}`).digest("base64url");+}++/**+ * A URL for `filePath` under the signed `prefix`, where everything else under+ * that prefix is reachable by relative resolution from it.+ *+ * `holdSeconds` is how long the token must stay good — pass the cut's duration+ * and the token outlives a straight-through watch, so playback never dies on a+ * 403 halfway. It is the revocation window too, which is why it is bounded.+ */+export function mediaTreeUrl(+ prefix: string,+ filePath: string,+ opts?: { holdSeconds?: number }+): string {+ const clean = prefix.replace(/^\/+|\/+$/g, "");+ const hold = Math.min(opts?.holdSeconds ?? 0, TREE_MAX_LIFETIME_SECONDS);+ const expires = tokenExpiry(hold);+ const sig = mediaTreeSignature(signingSecret(), clean, expires);+ const depth = clean.split("/").length;+ const encode = (p: string) => p.split("/").map(encodeURIComponent).join("/");+ return `${CUT_MEDIA_ORIGIN}/${MEDIA_TREE_PREFIX}/${expires}/${depth}/${encodeURIComponent(+ sig+ )}/${encode(clean)}/${encode(filePath.replace(/^\/+/, ""))}`;+}diff --git a/site/src/cut/server/cloud/r2.ts b/site/src/cut/server/cloud/r2.tsindex 0b3450d6..2c73d771 100644--- a/site/src/cut/server/cloud/r2.ts+++ b/site/src/cut/server/cloud/r2.ts@@ -46,6 +46,15 @@ export const projectExportKey = (userId: string, projectId: string, fileName: st`cut/${userId}/projects/${projectId}/exports/${fileName}`;export const projectPreviewKey = (userId: string, projectId: string) =>`cut/${userId}/projects/${projectId}/preview.mp4`;+/** Root of one HLS ladder. The doc version is a path segment rather than a+ * query parameter because a player reaches segments by relative URI: a version+ * that lived in the query would be dropped on the first hop out of a playlist,+ * and a re-rendered ladder would then be served the previous cut's segments out+ * of the edge cache. A new version is a new tree, and the old one is swept. */+export const projectHlsPrefix = (userId: string, projectId: string, version: string) =>+ `cut/${userId}/projects/${projectId}/hls/${version}`;+export const projectHlsRoot = (userId: string, projectId: string) =>+ `cut/${userId}/projects/${projectId}/hls/`;/** The link-preview card's artifacts. Fixed keys, rewritten by each card* render: the public URL carries the doc version, so freshness rides the URL* and R2 keeps one copy instead of one per edit. */@@ -109,6 +118,53 @@ export async function getObject(key: string): Promise<{ bytes: Buffer; mime: str}}+/**+ * Delete everything under `prefix`, paging until the listing is empty.+ *+ * Deleting a tree cannot be "list once, then delete": an HLS ladder for a long+ * cut runs to tens of thousands of objects, and a single capped listing would+ * leave the remainder behind with nothing left pointing at it. Returns how many+ * objects went.+ */+export async function deletePrefix(prefix: string): Promise<number> {+ let removed = 0;+ // Bounded so a listing that somehow never drains cannot spin forever; each+ // pass removes up to 1000, so this is far above any real ladder.+ for (let pass = 0; pass < 1000; pass++) {+ const keys = await listUnder(prefix, 1000);+ if (keys.length === 0) return removed;+ await del(keys);+ removed += keys.length;+ // A delete that silently removed nothing would otherwise loop on the same+ // page: del swallows its own failures, so treat no progress as done.+ if (keys.length < 1000) return removed;+ }+ return removed;+}++/** Every key under `prefix`, up to `limit`. Callers deleting a whole tree+ * should use deletePrefix, which pages instead of truncating. */+export async function listUnder(prefix: string, limit = 10_000): Promise<string[]> {+ const out: string[] = [];+ let token: string | undefined;+ do {+ const res = await r2().send(+ new ListObjectsV2Command({+ Bucket: R2_BUCKET,+ Prefix: prefix,+ ContinuationToken: token,+ MaxKeys: 1000,+ })+ );+ for (const o of res.Contents ?? []) {+ if (o.Key) out.push(o.Key);+ if (out.length >= limit) return out;+ }+ token = res.IsTruncated ? res.NextContinuationToken : undefined;+ } while (token);+ return out;+}+/** Keys under `prefix` last written before `before`, paged to `limit` objects.* For prefix sweeps of objects no database row tracks. */export async function listOlderThan(diff --git a/site/src/cut/worker/cf/media.ts b/site/src/cut/worker/cf/media.tsindex 6341c974..67a64221 100644--- a/site/src/cut/worker/cf/media.ts+++ b/site/src/cut/worker/cf/media.ts@@ -1,13 +1,18 @@-// The shared-media edge handler: serves one R2 object per request from-// Cloudflare's cache, gated by a short-lived token the hosted API mints-// (server/cloud/mediaCdn.ts holds the matching signer).+// The shared-media edge handler: serves R2 objects from Cloudflare's cache,+// gated by a short-lived token the hosted API mints (server/cloud/mediaCdn.ts+// holds the matching signer).//// Two things make this worth a Worker rather than a presigned R2 URL. The// bucket stays private — this binding is the only way in, so access is a// decision we make per request instead of arithmetic R2 does alone. And the-// cache key drops the query string, so every viewer and every re-mint of a-// rotating token collapse onto one cached copy per object; without that, a-// short token lifetime would mean a cache miss on every request.+// cache key is the object, never the token, so every viewer and every re-mint+// of a rotating token collapse onto one cached copy; without that, a short+// token lifetime would mean a cache miss on every request.+//+// Tokens come in two shapes. An object token names one key. A tree token names+// a prefix and rides in the path so that an HLS player, which follows relative+// URIs out of a playlist, keeps its authorization across the hop to the+// segments — a query string would not survive it.//// This file is compiled by wrangler, not the site's tsconfig — workers globals// are typed loosely on purpose.@@ -39,16 +44,14 @@ const MAX_CACHEABLE_BYTES = 512 * 1024 * 1024;* upload is a new key — so this is long and the token, not the cache, is what* bounds access. */const EDGE_TTL_SECONDS = 7 * 24 * 60 * 60;+/** How long a playlist may be held. Short, because a ladder rewrites its master+ * as later rungs finish — long enough to absorb a crowd opening one link, short+ * enough that the finished ladder reaches them. */+const PLAYLIST_TTL_SECONDS = 60;const encoder = new TextEncoder();-async function signatureFor(- secret: string,- key: string,- expires: number,- downloadName: string,- version: string-): Promise<string> {+async function hmac(secret: string, message: string): Promise<string> {const cryptoKey = await crypto.subtle.importKey("raw",encoder.encode(secret),@@ -56,17 +59,30 @@ async function signatureFor(false,["sign"]);- const mac = await crypto.subtle.sign(- "HMAC",- cryptoKey,- encoder.encode(`${key}\n${expires}\n${downloadName}\n${version}`)- );+ const mac = await crypto.subtle.sign("HMAC", cryptoKey, encoder.encode(message));// base64url, matching node's digest("base64url") on the signing side.let binary = "";for (const byte of new Uint8Array(mac)) binary += String.fromCharCode(byte);return btoa(binary).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");}+const signatureFor = (+ secret: string,+ key: string,+ expires: number,+ downloadName: string,+ version: string+): Promise<string> => hmac(secret, `${key}\n${expires}\n${downloadName}\n${version}`);++/** The tree-token signature — see mediaCdn.ts for why an HLS ladder needs a+ * token that survives relative URI resolution. Framed differently from the+ * object signature so neither can stand in for the other. */+const treeSignatureFor = (secret: string, prefix: string, expires: number): Promise<string> =>+ hmac(secret, `tree\n${prefix}\n${expires}`);++/** Marks a tree-token path: /_t/<expires>/<depth>/<sig>/<key…>. */+const TREE_PREFIX = "_t";+/** Constant-time compare, so a wrong signature leaks nothing through timing. */function sameSignature(a: string, b: string): boolean {if (a.length !== b.length) return false;@@ -102,12 +118,26 @@ function asDownload(res: Response, downloadName: string): Response {return out;}-function baseHeaders(object: R2Object): Headers {+function baseHeaders(object: R2Object, key: string): Headers {const headers = new Headers();object.writeHttpMetadata(headers);headers.set("etag", object.httpEtag);headers.set("Accept-Ranges", "bytes");- headers.set("Cache-Control", `public, max-age=${EDGE_TTL_SECONDS}, immutable`);+ // Media is immutable — a new upload is a new key — so it is cached hard and+ // the token, not the cache, is what bounds access.+ //+ // An HLS playlist is the exception, and the only one: a ladder publishes its+ // low rungs first and then REWRITES master.m3u8 in place to add the rest.+ // Cached as immutable, the first version would be pinned at the edge for a+ // week and the later rungs would never be listed to anyone — a 4K share+ // silently capped at 720p. Playlists are a few hundred bytes, so a short life+ // costs nothing; the segments they name are where caching earns its keep.+ headers.set(+ "Cache-Control",+ key.endsWith(".m3u8")+ ? `public, max-age=${PLAYLIST_TTL_SECONDS}`+ : `public, max-age=${EDGE_TTL_SECONDS}, immutable`+ );for (const [k, v] of Object.entries(CORS_HEADERS)) headers.set(k, v);return headers;}@@ -115,6 +145,95 @@ function baseHeaders(object: R2Object): Headers {const refuse = (body: string, status: number) =>new Response(body, { status, headers: CORS_HEADERS });+/** What a valid token resolves to: the R2 key it grants, plus the two+ * presentation fields an object token may carry. */+interface Granted {+ key: string;+ downloadName: string;+ version: string;+}++/** A stray percent is a malformed request, not a fault: decoding throws, and an+ * uncaught throw here is a Cloudflare exception page counted against this+ * Worker's error rate instead of the 404 it should be. */+function decodePath(segments: string[]): string | null {+ try {+ return segments.map(decodeURIComponent).join("/");+ } catch {+ return null;+ }+}++/**+ * Decide whether this URL may read an object, and which one.+ *+ * Two token shapes reach here. An object token addresses exactly one key and+ * carries its expiry and signature in the query string. A tree token addresses+ * anything under a signed prefix and rides in the path, because an HLS player+ * follows relative URIs out of a playlist and a query string does not survive+ * that hop (mediaCdn.ts explains the choice).+ */+async function authorize(url: URL, env: MediaEnv): Promise<Granted | Response> {+ const segments = url.pathname.replace(/^\/+/, "").split("/");+ if (!env.CUT_MEDIA_SIGNING_SECRET) return refuse("Not configured.", 500);++ if (segments[0] === TREE_PREFIX) {+ // /_t/<expires>/<depth>/<sig>/<key…>+ const expires = Number(segments[1]);+ const depth = Number(segments[2]);+ const sig = segments[3] ? decodeURIComponent(segments[3]) : "";+ const rest = segments.slice(4);+ if (+ !sig ||+ !Number.isFinite(expires) ||+ !Number.isInteger(depth) ||+ depth < 1 ||+ depth > rest.length+ ) {+ return refuse("Not found.", 404);+ }+ if (expires * 1000 < Date.now()) return refuse("Link expired.", 403);+ let decoded: string[];+ try {+ decoded = rest.map(decodeURIComponent);+ } catch {+ return refuse("Not found.", 404);+ }+ // The signature covers the prefix, and the key is the prefix plus whatever+ // the playlist pointed at — so a `..` that climbed back out of the tree+ // would still verify. Checked on the DECODED segments: `%2e%2e` reaches the+ // key as `..` and would walk straight past a check on the raw path.+ if (decoded.slice(depth).some((s) => s === ".." || s === ".")) {+ return refuse("Not found.", 404);+ }+ const prefix = decoded.slice(0, depth).join("/");+ const expected = await treeSignatureFor(env.CUT_MEDIA_SIGNING_SECRET, prefix, expires);+ if (!sameSignature(sig, expected)) return refuse("Forbidden.", 403);+ return { key: decoded.join("/"), downloadName: "", version: "" };+ }++ const key = decodePath(segments);+ const expires = Number(url.searchParams.get("e"));+ const sig = url.searchParams.get("s") ?? "";+ // Both are signed, so neither can be edited in after the fact. The name is+ // sanitized by the same rule that signed it, so the two agree by construction.+ const downloadName = mediaDownloadName(url.searchParams.get("d") ?? "");+ const version = url.searchParams.get("v") ?? "";+ if (!key || !sig || !Number.isFinite(expires)) return refuse("Not found.", 404);+ // Expiry first: an expired token is the ordinary case once a share is+ // revoked, and it costs nothing to answer.+ if (expires * 1000 < Date.now()) return refuse("Link expired.", 403);+ const expected = await signatureFor(+ env.CUT_MEDIA_SIGNING_SECRET,+ key,+ expires,+ downloadName,+ version+ );+ if (!sameSignature(sig, expected)) return refuse("Forbidden.", 403);+ return { key, downloadName, version };+}+export async function serveMedia(request: Request,env: MediaEnv,@@ -140,34 +259,9 @@ export async function serveMedia(});}const url = new URL(request.url);- // A stray percent in the path is a malformed request, not a fault: decoding it- // throws, and an uncaught throw here is a Cloudflare exception page against- // this Worker's error rate instead of the 404 it should be.- let key: string;- try {- key = decodeURIComponent(url.pathname.replace(/^\/+/, ""));- } catch {- return refuse("Not found.", 404);- }- const expires = Number(url.searchParams.get("e"));- const sig = url.searchParams.get("s") ?? "";- // Both are signed, so neither can be edited in after the fact. The name is- // sanitized by the same rule that signed it, so the two agree by construction.- const downloadName = mediaDownloadName(url.searchParams.get("d") ?? "");- const version = url.searchParams.get("v") ?? "";- if (!key || !sig || !Number.isFinite(expires)) return refuse("Not found.", 404);- // Expiry first: an expired token is the ordinary case once a share is- // revoked, and it costs nothing to answer.- if (expires * 1000 < Date.now()) return refuse("Link expired.", 403);- if (!env.CUT_MEDIA_SIGNING_SECRET) return refuse("Not configured.", 500);- const expected = await signatureFor(- env.CUT_MEDIA_SIGNING_SECRET,- key,- expires,- downloadName,- version- );- if (!sameSignature(sig, expected)) return refuse("Forbidden.", 403);+ const allowed = await authorize(url, env);+ if (allowed instanceof Response) return allowed;+ const { key, downloadName, version } = allowed;// The cache key is the object and its version, never the token: tokens rotate// and every viewer holds a different one, so keying on the full URL would mean@@ -175,8 +269,13 @@ export async function serveMedia(// changes — without it, a fixed key like a project's preview proxy would serve// its pre-edit bytes for the whole edge TTL. The stored entry is the whole// object; a Range on the lookup is what makes the cache answer 206 from it.+ // Built from the resolved key rather than the request path: a tree token+ // carries its expiry and signature in the path, and those rotate, so keying+ // on the path as it arrived would give every mint its own cache entry and+ // undo the collapse this whole scheme exists for.const cacheUrl =- `${url.origin}/${url.pathname.replace(/^\/+/, "")}` + (version ? `?v=${version}` : "");+ `${url.origin}/${key.split("/").map(encodeURIComponent).join("/")}` ++ (version ? `?v=${version}` : "");const storeKey = new Request(cacheUrl, { method: "GET" });const rangeHeader = request.headers.get("range");const lookupKey = rangeHeader@@ -206,7 +305,7 @@ export async function serveMedia(const warm = async () => {const whole = await env.CUT_MEDIA.get(key);if (!whole || !whole.body) return;- const headers = baseHeaders(whole);+ const headers = baseHeaders(whole, key);headers.set("Content-Length", String(whole.size));await cache.put(storeKey, new Response(whole.body, { status: 200, headers }));};@@ -219,7 +318,7 @@ export async function serveMedia(range: { offset: range.start, length: range.end - range.start + 1 },});if (!part) return refuse("Not found.", 404);- const headers = baseHeaders(part);+ const headers = baseHeaders(part, key);headers.set("Content-Range", `bytes ${range.start}-${range.end}/${size}`);headers.set("Content-Length", String(range.end - range.start + 1));if (size <= MAX_CACHEABLE_BYTES) ctx.waitUntil(warm());@@ -228,7 +327,7 @@ export async function serveMedia(const object = await env.CUT_MEDIA.get(key);if (!object || !object.body) return refuse("Not found.", 404);- const headers = baseHeaders(object);+ const headers = baseHeaders(object, key);headers.set("Content-Length", String(object.size));const full = new Response(object.body, { status: 200, headers });// Past Cloudflare's ceiling the put would fail, so it is not attempted;