Skip to content

Open source CapCut alternative.

TypeScript

feat(site): serve shared media from the edge, on tokens we can withdraw

David Le852a53f8d9ba
diff --git a/site/src/cut/server/cloud/httpRange.test.ts b/site/src/cut/server/cloud/httpRange.test.ts
new file mode 100644
index 00000000..255d0594
--- /dev/null
+++ b/site/src/cut/server/cloud/httpRange.test.ts
@@ -0,0 +1,55 @@
+import { describe, expect, test } from "bun:test";
+import { parseRange } from "./httpRange";
+
+const SIZE = 1000;
+
+describe("parseRange", () => {
+ test("no header means the whole object", () => {
+ expect(parseRange(null, SIZE)).toBe(null);
+ expect(parseRange(undefined, SIZE)).toBe(null);
+ expect(parseRange("", SIZE)).toBe(null);
+ });
+
+ test("a closed range is inclusive at both ends", () => {
+ expect(parseRange("bytes=0-99", SIZE)).toEqual({ start: 0, end: 99 });
+ expect(parseRange("bytes=100-199", SIZE)).toEqual({ start: 100, end: 199 });
+ });
+
+ test("an open range runs to the last byte", () => {
+ expect(parseRange("bytes=0-", SIZE)).toEqual({ start: 0, end: 999 });
+ expect(parseRange("bytes=500-", SIZE)).toEqual({ start: 500, end: 999 });
+ });
+
+ test("a suffix range counts back from the end", () => {
+ expect(parseRange("bytes=-500", SIZE)).toEqual({ start: 500, end: 999 });
+ // Asking for more than exists yields the whole object, not a negative start.
+ expect(parseRange("bytes=-5000", SIZE)).toEqual({ start: 0, end: 999 });
+ });
+
+ test("an end past the object clamps instead of overrunning", () => {
+ expect(parseRange("bytes=900-5000", SIZE)).toEqual({ start: 900, end: 999 });
+ });
+
+ test("the last single byte is reachable", () => {
+ expect(parseRange("bytes=999-999", SIZE)).toEqual({ start: 999, end: 999 });
+ expect(parseRange("bytes=-1", SIZE)).toEqual({ start: 999, end: 999 });
+ });
+
+ test("unsatisfiable ranges are refused rather than coerced", () => {
+ expect(parseRange("bytes=1000-", SIZE)).toBe("invalid"); // starts past the end
+ expect(parseRange("bytes=200-100", SIZE)).toBe("invalid"); // backwards
+ expect(parseRange("bytes=-0", SIZE)).toBe("invalid"); // empty suffix
+ expect(parseRange("bytes=-", SIZE)).toBe("invalid");
+ expect(parseRange("bytes=0-99", 0)).toBe("invalid"); // empty object
+ });
+
+ test("shapes we do not serve are refused, not guessed at", () => {
+ expect(parseRange("bytes=0-99, 200-299", SIZE)).toBe("invalid"); // multi-range
+ expect(parseRange("items=0-99", SIZE)).toBe("invalid"); // wrong unit
+ expect(parseRange("bytes=abc-def", SIZE)).toBe("invalid");
+ });
+
+ test("surrounding whitespace is tolerated", () => {
+ expect(parseRange(" bytes=0-99 ", SIZE)).toEqual({ start: 0, end: 99 });
+ });
+});
diff --git a/site/src/cut/server/cloud/httpRange.ts b/site/src/cut/server/cloud/httpRange.ts
new file mode 100644
index 00000000..26933838
--- /dev/null
+++ b/site/src/cut/server/cloud/httpRange.ts
@@ -0,0 +1,38 @@
+/** Byte-range parsing for media delivery. Lives here rather than beside the
+ * edge handler that uses it (worker/cf/media.ts) so it sits inside the site's
+ * program and can be tested; the Worker's bundler pulls it in. */
+
+export type ParsedRange = { start: number; end: number };
+
+/**
+ * Parse a `Range` header against a known object size. Returns null when the
+ * request is for the whole object, and "invalid" when the range cannot be
+ * satisfied — the caller answers 416 for that, rather than quietly serving
+ * something else.
+ *
+ * Only single ranges are handled. Multi-range requests ask for a multipart
+ * response no media element sends, so they read as unsatisfiable.
+ */
+export function parseRange(
+ header: string | null | undefined,
+ size: number
+): ParsedRange | null | "invalid" {
+ if (!header) return null;
+ const m = /^bytes=(\d*)-(\d*)$/.exec(header.trim());
+ if (!m) return "invalid";
+ const [, rawStart, rawEnd] = m;
+ if (rawStart === "" && rawEnd === "") return "invalid";
+ if (size <= 0) return "invalid";
+ // A suffix range ("bytes=-500") asks for the last N bytes, clamped to the
+ // object when it asks for more than exists.
+ if (rawStart === "") {
+ const wanted = Number(rawEnd);
+ if (wanted <= 0) return "invalid";
+ return { start: Math.max(0, size - wanted), end: size - 1 };
+ }
+ const start = Number(rawStart);
+ if (start >= size) return "invalid";
+ const end = rawEnd === "" ? size - 1 : Math.min(Number(rawEnd), size - 1);
+ if (start > end) return "invalid";
+ return { start, end };
+}
diff --git a/site/src/cut/server/cloud/mediaCdn.ts b/site/src/cut/server/cloud/mediaCdn.ts
new file mode 100644
index 00000000..99291b74
--- /dev/null
+++ b/site/src/cut/server/cloud/mediaCdn.ts
@@ -0,0 +1,61 @@
+// Shared media through Cloudflare's edge.
+//
+// A presigned R2 URL points at the S3 API endpoint, which Cloudflare does not
+// cache, and its signature is a bearer credential nothing can withdraw — R2
+// validates it by arithmetic, with no record that the URL was ever issued. A
+// shared link is exactly where both hurt: many viewers pull the same objects,
+// and unsharing has to mean something.
+//
+// So shared media is served from our own hostname instead, by a Worker holding
+// a private R2 binding (worker/cf/media.ts). Tokens are ours, so they are
+// short — unsharing takes effect within one token's life — and the Worker
+// keys its cache on the object path alone, so a token that rotates every few
+// minutes still collapses onto one cached copy per object.
+//
+// Without the two variables set, this is inert and callers presign R2 as
+// before: the mode is a deployment's choice, not a fork in the code.
+import { createHmac, timingSafeEqual } from "node:crypto";
+
+/** Token lifetime. Short on purpose — it is the revocation window, and the
+ * Worker's cache key ignores the token, so shortening it costs no cache hits.
+ * The client re-mints ahead of expiry (lib/mediaLinks.ts). */
+export const MEDIA_TOKEN_TTL_SECONDS = 5 * 60;
+
+function config(): { base: string; secret: string } | null {
+ const base = process.env.CUT_MEDIA_BASE_URL;
+ const secret = process.env.CUT_MEDIA_SIGNING_SECRET;
+ if (!base || !secret) return null;
+ return { base: base.replace(/\/+$/, ""), secret };
+}
+
+/** Whether shared media rides the edge Worker on this deployment. */
+export const mediaCdnEnabled = () => config() != null;
+
+/** The signature over one object and expiry. Both sides derive it the same
+ * way; the Worker holds the same secret and never calls back here. */
+export function mediaSignature(secret: string, key: string, expires: number): string {
+ return createHmac("sha256", secret).update(`${key}\n${expires}`).digest("base64url");
+}
+
+/** An edge URL for one R2 key, or null when the CDN is not configured. */
+export function mediaCdnUrl(key: string): string | null {
+ const cfg = config();
+ if (!cfg) return null;
+ const expires = Math.floor(Date.now() / 1000) + MEDIA_TOKEN_TTL_SECONDS;
+ const sig = mediaSignature(cfg.secret, key, expires);
+ // The key's slashes are path separators on the edge host, so each segment is
+ // encoded on its own.
+ const path = key.split("/").map(encodeURIComponent).join("/");
+ return `${cfg.base}/${path}?e=${expires}&s=${sig}`;
+}
+
+/** Verify a token the way the Worker does. Kept beside the minting so the two
+ * can never drift; used by the tests. */
+export function mediaTokenValid(key: string, expires: number, sig: string): boolean {
+ const cfg = config();
+ if (!cfg) return false;
+ if (!Number.isFinite(expires) || expires * 1000 < Date.now()) return false;
+ const expected = Buffer.from(mediaSignature(cfg.secret, key, expires));
+ const given = Buffer.from(sig);
+ return expected.length === given.length && timingSafeEqual(expected, given);
+}
diff --git a/site/src/cut/worker/cf/media.ts b/site/src/cut/worker/cf/media.ts
new file mode 100644
index 00000000..4f186435
--- /dev/null
+++ b/site/src/cut/worker/cf/media.ts
@@ -0,0 +1,175 @@
+// 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).
+//
+// 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.
+//
+// This file is compiled by wrangler, not the site's tsconfig — workers globals
+// are typed loosely on purpose.
+import { parseRange } from "../../server/cloud/httpRange";
+
+type R2Range = { offset: number; length?: number };
+type R2Object = {
+ body: ReadableStream | null;
+ size: number;
+ httpEtag: string;
+ httpMetadata?: { contentType?: string };
+ writeHttpMetadata(headers: Headers): void;
+};
+type R2Bucket = {
+ get(key: string, opts?: { range?: R2Range }): Promise<R2Object | null>;
+ head(key: string): Promise<R2Object | null>;
+};
+
+export type MediaEnv = {
+ CUT_MEDIA: R2Bucket;
+ CUT_MEDIA_SIGNING_SECRET: string;
+};
+
+/** Cloudflare refuses to cache past this on Free/Pro/Business plans; a larger
+ * object streams from R2 on every request instead of failing. */
+const MAX_CACHEABLE_BYTES = 512 * 1024 * 1024;
+/** How long the edge keeps an object. Media is immutable once written — a new
+ * 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;
+
+const encoder = new TextEncoder();
+
+async function signatureFor(secret: string, key: string, expires: number): Promise<string> {
+ const cryptoKey = await crypto.subtle.importKey(
+ "raw",
+ encoder.encode(secret),
+ { name: "HMAC", hash: "SHA-256" },
+ false,
+ ["sign"]
+ );
+ const mac = await crypto.subtle.sign("HMAC", cryptoKey, encoder.encode(`${key}\n${expires}`));
+ // 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(/=+$/, "");
+}
+
+/** 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;
+ let diff = 0;
+ for (let i = 0; i < a.length; i++) diff |= a.charCodeAt(i) ^ b.charCodeAt(i);
+ return diff === 0;
+}
+
+function baseHeaders(object: R2Object): 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`);
+ return headers;
+}
+
+export async function serveMedia(
+ request: Request,
+ env: MediaEnv,
+ ctx: { waitUntil(p: Promise<unknown>): void }
+): Promise<Response> {
+ if (request.method !== "GET" && request.method !== "HEAD") {
+ return new Response("Method not allowed.", { status: 405, headers: { Allow: "GET, HEAD" } });
+ }
+ const url = new URL(request.url);
+ const key = decodeURIComponent(url.pathname.replace(/^\/+/, ""));
+ const expires = Number(url.searchParams.get("e"));
+ const sig = url.searchParams.get("s") ?? "";
+ if (!key || !sig || !Number.isFinite(expires)) return new Response("Not found.", { status: 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 new Response("Link expired.", { status: 403 });
+ if (!env.CUT_MEDIA_SIGNING_SECRET) return new Response("Not configured.", { status: 500 });
+ if (!sameSignature(sig, await signatureFor(env.CUT_MEDIA_SIGNING_SECRET, key, expires))) {
+ return new Response("Forbidden.", { status: 403 });
+ }
+
+ // The cache key is the object, never the token: tokens rotate every few
+ // minutes and every viewer holds a different one, so keying on the full URL
+ // would mean a miss per viewer per rotation. The stored entry is the whole
+ // object; a Range on the lookup is what makes the cache answer 206 from it.
+ const cacheUrl = `${url.origin}/${url.pathname.replace(/^\/+/, "")}`;
+ const storeKey = new Request(cacheUrl, { method: "GET" });
+ const rangeHeader = request.headers.get("range");
+ const lookupKey = rangeHeader
+ ? new Request(cacheUrl, { method: "GET", headers: { Range: rangeHeader } })
+ : storeKey;
+ const cache = caches.default;
+ const hit = await cache.match(lookupKey);
+ if (hit) return hit;
+
+ const head = await env.CUT_MEDIA.head(key);
+ if (!head) return new Response("Not found.", { status: 404 });
+
+ const range = parseRange(rangeHeader, head.size);
+ if (range === "invalid") {
+ return new Response("Range not satisfiable.", {
+ status: 416,
+ headers: { "Content-Range": `bytes */${head.size}` },
+ });
+ }
+
+ // Beyond the cacheable ceiling, stream the asked-for bytes straight through
+ // and skip the cache — putting it would fail, and buffering it to try would
+ // be worse than the miss.
+ if (head.size > MAX_CACHEABLE_BYTES) {
+ const object = await env.CUT_MEDIA.get(
+ key,
+ range ? { range: { offset: range.start, length: range.end - range.start + 1 } } : undefined
+ );
+ if (!object) return new Response("Not found.", { status: 404 });
+ const headers = baseHeaders(object);
+ headers.set("Cache-Control", "public, max-age=3600");
+ if (range) {
+ headers.set("Content-Range", `bytes ${range.start}-${range.end}/${head.size}`);
+ headers.set("Content-Length", String(range.end - range.start + 1));
+ return new Response(object.body, { status: 206, headers });
+ }
+ headers.set("Content-Length", String(head.size));
+ return new Response(object.body, { status: 200, headers });
+ }
+
+ // Warm the cache with the whole object, streamed. cache.put refuses a 206,
+ // so the entry is always the full 200 — which is what lets later range
+ // requests be answered from it.
+ const warm = async () => {
+ const whole = await env.CUT_MEDIA.get(key);
+ if (!whole || !whole.body) return;
+ const headers = baseHeaders(whole);
+ headers.set("Content-Length", String(whole.size));
+ await cache.put(storeKey, new Response(whole.body, { status: 200, headers }));
+ };
+
+ if (range) {
+ // Serve the asked-for bytes from R2 directly and warm in the background.
+ // Reading the whole object to slice it here would risk the Worker's memory
+ // ceiling on exactly the large files that most need the cache.
+ const part = await env.CUT_MEDIA.get(key, {
+ range: { offset: range.start, length: range.end - range.start + 1 },
+ });
+ if (!part) return new Response("Not found.", { status: 404 });
+ const headers = baseHeaders(part);
+ headers.set("Content-Range", `bytes ${range.start}-${range.end}/${head.size}`);
+ headers.set("Content-Length", String(range.end - range.start + 1));
+ ctx.waitUntil(warm());
+ return new Response(part.body, { status: 206, headers });
+ }
+
+ const object = await env.CUT_MEDIA.get(key);
+ if (!object || !object.body) return new Response("Not found.", { status: 404 });
+ const headers = baseHeaders(object);
+ headers.set("Content-Length", String(object.size));
+ const full = new Response(object.body, { status: 200, headers });
+ ctx.waitUntil(cache.put(storeKey, full.clone()));
+ return full;
+}