Skip to content

Open source CapCut alternative.

TypeScript

fix(site): serve cloud media through the edge Worker

David Lea8e35b44d9c5
diff --git a/site/.env.example b/site/.env.example
index 2c57b70a..f67ad5d1 100644
--- a/site/.env.example
+++ b/site/.env.example
@@ -60,10 +60,9 @@ R2_SECRET_ACCESS_KEY="replace-with-r2-secret-access-key"
# worker by hand; it polls on its own).
CUT_RENDER_WAKE_SECRET="replace-with-wake-secret"
-# Shared-media edge delivery. Holding this secret is what turns it on: a shared
-# project's media is then served from the Cut Worker's R2 binding — cached at
-# the edge, and revocable, because the token is ours and lives only minutes.
-# Must match the Worker's own CUT_MEDIA_SIGNING_SECRET (openssl rand -hex 32).
-# The hostname is code, in src/cut/lib/hosts.ts. Leave unset (local dev) to
-# presign R2 directly instead.
+# Cloud-media delivery. Required wherever cloud projects are served: every byte
+# the browser reads goes through the Cut Worker's R2 binding, addressed by a
+# token signed with this. Without it, media reads answer 500. Must match the
+# Worker's own CUT_MEDIA_SIGNING_SECRET (openssl rand -hex 32); the hostname is
+# code, in src/cut/lib/hosts.ts.
CUT_MEDIA_SIGNING_SECRET="replace-with-media-signing-secret"
diff --git a/site/src/app/cut/s/[token]/card/[ext]/route.ts b/site/src/app/cut/s/[token]/card/[ext]/route.ts
index 8f007ada..678bfbf7 100644
--- a/site/src/app/cut/s/[token]/card/[ext]/route.ts
+++ b/site/src/app/cut/s/[token]/card/[ext]/route.ts
@@ -1,6 +1,7 @@
import { resolveShare } from "@/cut/server/cloud/sharedView";
import {
CARD_CACHE_SECONDS,
+ CARD_STALE_SECONDS,
cardUrl,
placeholderCard,
shareProjectName,
@@ -29,7 +30,9 @@ export async function GET(
const target = { userId: view.share.userId, projectId: view.share.projectId };
const cacheable = view.share.access === "public";
const headers: Record<string, string> = cacheable
- ? { "Cache-Control": `public, s-maxage=${CARD_CACHE_SECONDS}, stale-while-revalidate=86400` }
+ ? {
+ "Cache-Control": `public, s-maxage=${CARD_CACHE_SECONDS}, stale-while-revalidate=${CARD_STALE_SECONDS}`,
+ }
: { "Cache-Control": "private, no-store" };
if (ext === "gif" || ext === "jpg") {
diff --git a/site/src/cut/lib/mediaLinks.ts b/site/src/cut/lib/mediaLinks.ts
index ac348907..09ab2015 100644
--- a/site/src/cut/lib/mediaLinks.ts
+++ b/site/src/cut/lib/mediaLinks.ts
@@ -29,7 +29,7 @@ import { mediaUrl } from "./types";
/** Re-mint this far ahead of expiry, as a share of the whole lifetime, so a
* five-minute token and a one-day one are both refreshed in good time. */
const REFRESH_LEAD_FRACTION = 1 / 3;
-const MAX_REFRESH_LEAD_MS = 60 * 60 * 1000; // a day-long URL needn't lead by more
+const MAX_REFRESH_LEAD_MS = 20 * 60 * 1000; // …and a long-lived one needn't by more
const MIN_REFRESH_LEAD_MS = 20_000; // …nor a short one by less
const FORCED_GAP_MS = 15_000; // min gap between failure-driven re-mints
const ELEMENT_RETRIES = 3;
@@ -109,11 +109,10 @@ function refreshSignedUrls(force = false): Promise<void> {
return refreshing;
}
-/** A URL whose access expires and can be re-minted: a presigned R2 URL, or an
- * edge media token (`?e=<expiry>&s=<signature>`). Both heal by re-minting the
- * batch; anything else does not. */
+/** A URL whose access expires and can be re-minted: an edge media token
+ * (`?e=<expiry>&s=<signature>`). It heals by re-minting the batch; anything
+ * else does not. */
function isExpiringUrl(src: string): boolean {
- if (src.includes("X-Amz-Signature=")) return true;
try {
const params = new URL(src, window.location.origin).searchParams;
return params.has("e") && params.has("s");
diff --git a/site/src/cut/server/cloud/jobs.ts b/site/src/cut/server/cloud/jobs.ts
index 209d1e27..bdd38045 100644
--- a/site/src/cut/server/cloud/jobs.ts
+++ b/site/src/cut/server/cloud/jobs.ts
@@ -6,7 +6,8 @@ import { prisma } from "@/lib/prisma";
import { EXPORT_QUOTA_MARGIN, renderJobCheck } from "./limits";
import { wakeRenderWorker } from "./wake";
import { getProject } from "./projects";
-import { overlayKey, presignGet, presignPut } from "./r2";
+import { mediaObjectUrl } from "./mediaCdn";
+import { overlayKey, presignPut } from "./r2";
import { quotaCheck } from "./usage";
import { caught, err, redirect } from "./util";
@@ -188,7 +189,9 @@ export const jobsCloud = {
if (!row || row.state !== "done" || !row.outputKey) {
return new Response("Export not ready.", { status: 404 });
}
- return redirect(await presignGet(row.outputKey, row.outName ?? undefined));
+ return redirect(
+ mediaObjectUrl(row.outputKey, row.outName ? { downloadName: row.outName } : undefined)
+ );
} catch (e) {
return caught(e, "Export not ready.");
}
diff --git a/site/src/cut/server/cloud/library.ts b/site/src/cut/server/cloud/library.ts
index a751ebfe..52c0aa61 100644
--- a/site/src/cut/server/cloud/library.ts
+++ b/site/src/cut/server/cloud/library.ts
@@ -14,8 +14,9 @@ import type {
import type { StoredAsset } from "@/cut/lib/types";
import type { Prisma } from "@/generated/prisma/client";
import { prisma } from "@/lib/prisma";
+import { mediaObjectUrl } from "./mediaCdn";
import { getProject, takenMediaNames } from "./projects";
-import { copy, del, head, libraryKey, presignGet, presignPut, projectMediaKey } from "./r2";
+import { copy, del, head, libraryKey, presignPut, projectMediaKey } from "./r2";
import { addUsage, quotaCheck } from "./usage";
import { caught, decodeFileParam, dedupeName, err, redirect, safeFileName, typeOf } from "./util";
@@ -401,7 +402,7 @@ export const libraryCloud = {
async serveMedia(userId: string, file: string) {
try {
- return redirect(await presignGet(libraryKey(userId, decodeFileParam(file))));
+ return redirect(mediaObjectUrl(libraryKey(userId, decodeFileParam(file))));
} catch (e) {
return caught(e, "Bad request.", 400);
}
diff --git a/site/src/cut/server/cloud/media.ts b/site/src/cut/server/cloud/media.ts
index 6032354f..9bf5ec6e 100644
--- a/site/src/cut/server/cloud/media.ts
+++ b/site/src/cut/server/cloud/media.ts
@@ -3,8 +3,9 @@
// step. Small images (AI generations, stock tiles) still ride through the
// server like the engine's importImage.
import { prisma } from "@/lib/prisma";
+import { mediaObjectUrl, mediaUrlLifetime } from "./mediaCdn";
import { getProject, takenMediaNames } from "./projects";
-import { head, presignGet, presignGetLifetime, presignPut, projectMediaKey, putObject } from "./r2";
+import { head, presignPut, projectMediaKey, putObject } from "./r2";
import { addUsage, quotaCheck } from "./usage";
import { caught, dedupeName, err, safeFileName } from "./util";
@@ -123,16 +124,37 @@ export const mediaCloud = {
};
if (!Array.isArray(items)) return err("items is required.", 400);
if (items.length > PRESIGN_GET_BATCH_MAX) return err("Too many items.", 400);
- const urls = await Promise.all(
- items
- .filter((i) => typeof i.projectId === "string" && typeof i.fileName === "string")
- .map(async (i) => ({
+ const wanted = items.filter(
+ (i) => typeof i.projectId === "string" && typeof i.fileName === "string"
+ );
+ // One query for the whole batch, not one per file. It carries the version
+ // each URL needs — a filename freed by a delete can be handed out again,
+ // and the edge would serve the old object under it — and it is also how a
+ // file that no longer exists is left out instead of minted for.
+ const rows = await prisma.cutMediaObject.findMany({
+ where: {
+ userId,
+ kind: "media",
+ projectId: { in: [...new Set(wanted.map((i) => i.projectId!))] },
+ },
+ select: { projectId: true, fileName: true, updatedAt: true },
+ });
+ const versions = new Map(
+ rows.map((r) => [`${r.projectId}/${r.fileName}`, String(r.updatedAt.getTime())])
+ );
+ const urls = wanted.flatMap((i) => {
+ const fileName = safeFileName(i.fileName!);
+ const version = versions.get(`${i.projectId}/${fileName}`);
+ if (!version) return [];
+ return [
+ {
projectId: i.projectId!,
fileName: i.fileName!,
- url: await presignGet(projectMediaKey(userId, i.projectId!, safeFileName(i.fileName!))),
- }))
- );
- return Response.json({ urls, expiresIn: presignGetLifetime() });
+ url: mediaObjectUrl(projectMediaKey(userId, i.projectId!, fileName), { version }),
+ },
+ ];
+ });
+ return Response.json({ urls, expiresIn: mediaUrlLifetime() });
} catch (e) {
return caught(e, "Could not sign the media URLs.");
}
diff --git a/site/src/cut/server/cloud/mediaCdn.test.ts b/site/src/cut/server/cloud/mediaCdn.test.ts
new file mode 100644
index 00000000..f6ad4ddc
--- /dev/null
+++ b/site/src/cut/server/cloud/mediaCdn.test.ts
@@ -0,0 +1,118 @@
+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 SECRET = "test-media-signing-secret";
+
+/** The Worker's verifier, transcribed from worker/cf/media.ts. It runs on
+ * WebCrypto rather than node:crypto, so the two implementations only agree if
+ * the signed payload and its encoding match exactly — which is what this pins:
+ * a drift between them 403s every cloud media read. */
+async function workerSignature(
+ secret: string,
+ key: string,
+ expires: number,
+ downloadName: string,
+ version: string
+): 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(`${key}\n${expires}\n${downloadName}\n${version}`)
+ );
+ let binary = "";
+ for (const byte of new Uint8Array(mac)) binary += String.fromCharCode(byte);
+ return btoa(binary).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
+}
+
+const KEY = "cut/user1/projects/p1/media/clip.mp4";
+
+describe("signer and verifier agree", () => {
+ test("across every field combination a URL can carry", async () => {
+ const expires = 1_750_000_000;
+ const cases: [string, string][] = [
+ ["", ""], // plain read
+ ["export.mp4", ""], // download
+ ["", "1750000000000"], // versioned
+ ["My Cut.mp4", "1750000000000"], // both
+ ["夏の動画.mp4", "42"], // non-ASCII download name
+ ];
+ for (const [name, version] of cases) {
+ expect(mediaSignature(SECRET, KEY, expires, name, version)).toBe(
+ await workerSignature(SECRET, KEY, expires, name, version)
+ );
+ }
+ });
+
+ test("a differing field changes the signature", () => {
+ const at = 1_750_000_000;
+ const base = mediaSignature(SECRET, KEY, at, "", "");
+ expect(mediaSignature(SECRET, KEY, at, "a.mp4", "")).not.toBe(base);
+ expect(mediaSignature(SECRET, KEY, at, "", "2")).not.toBe(base);
+ // The name and version fields cannot be slid past each other: a name that
+ // ends where the version begins must not sign the same as the reverse.
+ expect(mediaSignature(SECRET, KEY, at, "a", "b")).not.toBe(
+ mediaSignature(SECRET, KEY, at, "", "a\nb")
+ );
+ });
+});
+
+describe("tokens are stable inside a window", () => {
+ test("two mints of one object return the identical URL", () => {
+ expect(mediaObjectUrl(KEY)).toBe(mediaObjectUrl(KEY));
+ });
+
+ test("a version reaches the query and changes the URL", () => {
+ const a = new URL(mediaObjectUrl(KEY, { version: "1" }));
+ expect(a.searchParams.get("v")).toBe("1");
+ expect(mediaObjectUrl(KEY, { version: "2" })).not.toBe(mediaObjectUrl(KEY, { version: "1" }));
+ });
+
+ test("a download name reaches the query, sanitized", () => {
+ const url = new URL(mediaObjectUrl(KEY, { downloadName: 'a"b\nc.mp4' }));
+ expect(url.searchParams.get("d")).toBe("abc.mp4");
+ });
+
+ test("the lifetime clears docCache's ten-minute link-reuse floor", () => {
+ // Below it, a stored media-links batch could never be reused and every
+ // cloud project would open on origin URLs (lib/docCache.ts).
+ expect(mediaUrlLifetime()).toBeGreaterThan(10 * 60);
+ });
+
+ test("a longer minimum lifetime still lands on a window boundary", () => {
+ const day = 24 * 60 * 60;
+ const a = mediaObjectUrl(KEY, { minLifetimeSeconds: day });
+ expect(a).toBe(mediaObjectUrl(KEY, { minLifetimeSeconds: day }));
+ expect(Number(new URL(a).searchParams.get("e"))).toBeGreaterThan(
+ Math.floor(Date.now() / 1000) + day
+ );
+ });
+});
+
+describe("download names", () => {
+ test("quotes and newlines come out", () => {
+ expect(mediaDownloadName('a"b\r\nc')).toBe("abc");
+ });
+
+ test("a non-ASCII name gets both header forms", () => {
+ const header = contentDisposition("夏の動画.mp4");
+ // filename= must be a ByteString; the real name rides filename*.
+ expect(header).toContain('filename="____.mp4"');
+ expect(header).toContain("filename*=UTF-8''%E5%A4%8F");
+ for (const ch of header) expect(ch.charCodeAt(0)).toBeLessThan(256);
+ });
+
+ test("a name with nothing ASCII left still names a file", () => {
+ expect(contentDisposition("動画")).toContain('filename="__"');
+ });
+});
diff --git a/site/src/cut/server/cloud/mediaCdn.ts b/site/src/cut/server/cloud/mediaCdn.ts
index b7688b51..8397b8bf 100644
--- a/site/src/cut/server/cloud/mediaCdn.ts
+++ b/site/src/cut/server/cloud/mediaCdn.ts
@@ -1,59 +1,107 @@
-// Shared media through Cloudflare's edge.
+// Cloud 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.
+// Every byte the browser reads out of a cloud project comes through the media
+// Worker (worker/cf/media.ts): a private R2 binding addressed by a signed token
+// this module mints. The Worker sets CORS headers itself, which is what Cut
+// needs — the preview, the filmstrips and the AI pipeline all read pixels or
+// bytes back, so they load with crossOrigin="anonymous" (lib/mediaCors.ts), and
+// a response without those headers fails to load rather than degrading.
//
-// 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.
+// Tokens are minted on window boundaries rather than at the instant of the
+// request, so every mint inside a window yields the identical URL. That is what
+// lets a project re-mint its whole batch without disturbing playback: the store
+// compares URLs to decide what changed, and a decoder keyed on a URL that
+// rotated would be torn down and rebuilt mid-edit.
//
-// The hostname is code (lib/hosts.ts); the signing secret is the only part
-// that belongs in the environment, and holding it is what turns this on. A
-// deployment without it presigns R2 as before.
-import { createHmac, timingSafeEqual } from "node:crypto";
+// An object rewritten in place — a preview proxy, a share card, a media filename
+// freed by a delete and handed out again — carries a `version` that joins the
+// edge cache key, so new bytes are a new cache entry instead of a wait for the
+// old one to lapse.
+//
+// The hostname is code (lib/hosts.ts); the secret is the only part that lives in
+// the environment, and the Worker must hold the identical value.
+import { createHmac } from "node:crypto";
import { CUT_MEDIA_ORIGIN } from "@/cut/lib/hosts";
+import { mediaDownloadName } from "./mediaName";
-/** 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;
+/** Tokens are minted on boundaries of this window, so every mint inside one
+ * produces the same URL. */
+const TOKEN_WINDOW_SECONDS = 60 * 60;
-/** The signing secret, when this deployment has one. */
-const signingSecret = () => process.env.CUT_MEDIA_SIGNING_SECRET || null;
+/** How long past its window a token keeps working. This is the floor on any
+ * token's life and the revocation window — unsharing takes effect within this
+ * plus the window the token was minted in. It also has to clear docCache's
+ * link-reuse floor (lib/docCache.ts), or a stored batch could never be reused
+ * and every cloud project would open on origin URLs. */
+const TOKEN_GRACE_SECONDS = 60 * 60;
-/** Whether shared media rides the edge Worker on this deployment. */
-export const mediaCdnEnabled = () => signingSecret() != null;
+/** A deployment without the signing secret cannot serve cloud media at all.
+ * Carried as its own type so routes answer with a server error in their own
+ * words instead of echoing this message — which names an environment variable —
+ * to whoever asked, including anonymous share viewers. */
+export class MediaNotConfiguredError extends Error {
+ constructor() {
+ super("CUT_MEDIA_SIGNING_SECRET is not set — cloud media cannot be served");
+ }
+}
-/** 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");
+function signingSecret(): string {
+ const secret = process.env.CUT_MEDIA_SIGNING_SECRET;
+ if (!secret) throw new MediaNotConfiguredError();
+ return secret;
}
-/** An edge URL for one R2 key, or null when this deployment has no secret. */
-export function mediaCdnUrl(key: string): string | null {
- const secret = signingSecret();
- if (!secret) return null;
- const expires = Math.floor(Date.now() / 1000) + MEDIA_TOKEN_TTL_SECONDS;
- const sig = mediaSignature(secret, key, expires);
+/** The expiry every token minted in the current window carries. `minLifetime`
+ * raises it for a URL that outlives the page that minted it — a crawler holding
+ * a share card — and still lands on a window boundary, so those URLs stay stable
+ * and cacheable too. */
+function tokenExpiry(minLifetimeSeconds = TOKEN_GRACE_SECONDS, at = Date.now()): number {
+ const windowMs = TOKEN_WINDOW_SECONDS * 1000;
+ const windowEnd = Math.ceil(at / windowMs) * windowMs;
+ return Math.floor(windowEnd / 1000) + Math.max(TOKEN_GRACE_SECONDS, minLifetimeSeconds);
+}
+
+/** Seconds the tokens minted right now stay good for, so a client re-mints
+ * ahead of expiry rather than after a 403. */
+export const mediaUrlLifetime = (): number => tokenExpiry() - Math.floor(Date.now() / 1000);
+
+/** 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
+ * derive this the same way; the Worker holds the same secret and never calls
+ * back here. */
+export function mediaSignature(
+ secret: string,
+ key: string,
+ expires: number,
+ downloadName = "",
+ version = ""
+): string {
+ return createHmac("sha256", secret)
+ .update(`${key}\n${expires}\n${downloadName}\n${version}`)
+ .digest("base64url");
+}
+
+/** The browser-facing URL for one R2 object.
+ *
+ * `downloadName` makes it an attachment download under that filename.
+ * `version` must change whenever the object's bytes do, for any key written
+ * more than once. `minLifetimeSeconds` widens the token for a URL that outlives
+ * its page; everything a live page reads leaves it alone, since the token's life
+ * is the revocation window. */
+export function mediaObjectUrl(
+ key: string,
+ opts?: { downloadName?: string; version?: string; minLifetimeSeconds?: number }
+): string {
+ const expires = tokenExpiry(opts?.minLifetimeSeconds);
+ const name = opts?.downloadName ? mediaDownloadName(opts.downloadName) : "";
+ const version = opts?.version ?? "";
+ const sig = mediaSignature(signingSecret(), key, expires, name, version);
// 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 `${CUT_MEDIA_ORIGIN}/${path}?e=${expires}&s=${sig}`;
-}
-
-/** Verify a token the way the Worker does. Kept beside the minting so the two
- * can never drift. */
-export function mediaTokenValid(key: string, expires: number, sig: string): boolean {
- const secret = signingSecret();
- if (!secret) return false;
- if (!Number.isFinite(expires) || expires * 1000 < Date.now()) return false;
- const expected = Buffer.from(mediaSignature(secret, key, expires));
- const given = Buffer.from(sig);
- return expected.length === given.length && timingSafeEqual(expected, given);
+ const query = new URLSearchParams({ e: String(expires), s: sig });
+ if (version) query.set("v", version);
+ if (name) query.set("d", name);
+ return `${CUT_MEDIA_ORIGIN}/${path}?${query.toString()}`;
}
diff --git a/site/src/cut/server/cloud/mediaName.ts b/site/src/cut/server/cloud/mediaName.ts
new file mode 100644
index 00000000..bfee76bc
--- /dev/null
+++ b/site/src/cut/server/cloud/mediaName.ts
@@ -0,0 +1,25 @@
+// The download filename carried by a media token.
+//
+// Lives here because both sides need the identical rule: the hosted API signs
+// the sanitized name (mediaCdn.ts) and the edge Worker sanitizes what arrives
+// before checking the signature (worker/cf/media.ts, whose bundler pulls this
+// in). Two copies that drift by one character would 403 every download.
+
+/** A download filename with the characters that would break the signature's
+ * framing or the header it lands in taken out: quotes, and the newlines that
+ * both separate signature fields and terminate a header. */
+export const mediaDownloadName = (name: string): string => name.replace(/["\r\n]/g, "");
+
+/** `Content-Disposition` for an attachment under `name`.
+ *
+ * A header value is a ByteString, so a name with non-ASCII in it cannot go in
+ * `filename=` at all — workerd refuses the code points, and a browser that did
+ * receive them would guess an encoding. RFC 6266 answers this with both forms:
+ * `filename=` carries an ASCII-folded name for anything old, and `filename*=`
+ * carries the real one percent-encoded as UTF-8, which every current browser
+ * prefers. */
+export function contentDisposition(name: string): string {
+ const safe = mediaDownloadName(name);
+ const ascii = safe.replace(/[^\x20-\x7E]/g, "_") || "download";
+ return `attachment; filename="${ascii}"; filename*=UTF-8''${encodeURIComponent(safe)}`;
+}
diff --git a/site/src/cut/server/cloud/projects.ts b/site/src/cut/server/cloud/projects.ts
index dd84d313..0ebce54d 100644
--- a/site/src/cut/server/cloud/projects.ts
+++ b/site/src/cut/server/cloud/projects.ts
@@ -3,12 +3,8 @@
import { normalizeAspect, type ProjectDoc, type ProjectFolder, type ProjectSummary } from "@/cut/lib/types";
import type { Prisma } from "@/generated/prisma/client";
import { prisma } from "@/lib/prisma";
-import {
- del,
- presignGet,
- projectExportKey,
- projectMediaKey,
-} from "./r2";
+import { mediaObjectUrl } from "./mediaCdn";
+import { del, projectExportKey, projectMediaKey } from "./r2";
import { addUsage } from "./usage";
import { caught, decodeFileParam, err, redirect } from "./util";
@@ -323,7 +319,17 @@ export const projectsCloud = {
async serveMedia(userId: string, id: string, file: string) {
try {
- return redirect(await presignGet(projectMediaKey(userId, id, decodeFileParam(file))));
+ const fileName = decodeFileParam(file);
+ const row = await prisma.cutMediaObject.findFirst({
+ where: { userId, projectId: id, kind: "media", fileName },
+ select: { updatedAt: true },
+ });
+ if (!row) return err("Not found.", 404);
+ return redirect(
+ mediaObjectUrl(projectMediaKey(userId, id, fileName), {
+ version: String(row.updatedAt.getTime()),
+ })
+ );
} catch (e) {
return caught(e, "Bad request.", 400);
}
@@ -362,7 +368,7 @@ export const projectsCloud = {
try {
const fileName = decodeFileParam(file);
const key = projectExportKey(userId, id, fileName);
- return redirect(await presignGet(key, download ? fileName : undefined));
+ return redirect(mediaObjectUrl(key, download ? { downloadName: fileName } : undefined));
} catch (e) {
return caught(e, "Bad request.", 400);
}
@@ -391,7 +397,12 @@ export const projectsCloud = {
try {
const row = await getProject(userId, id);
if (!row?.previewKey) return new Response("Not found.", { status: 404 });
- return redirect(await presignGet(row.previewKey));
+ // One fixed key that every re-render overwrites, so the version is what
+ // stops the edge serving the pre-edit proxy: the row's updatedAt moves
+ // whenever the project that produced it did.
+ return redirect(
+ mediaObjectUrl(row.previewKey, { version: String(row.updatedAt.getTime()) })
+ );
} catch (e) {
return caught(e, "Bad request.", 400);
}
diff --git a/site/src/cut/server/cloud/r2.ts b/site/src/cut/server/cloud/r2.ts
index 1438c794..0b3450d6 100644
--- a/site/src/cut/server/cloud/r2.ts
+++ b/site/src/cut/server/cloud/r2.ts
@@ -15,10 +15,6 @@ import { getSignedUrl } from "@aws-sdk/s3-request-presigner";
const R2_BUCKET = "donkey-cut";
const PUT_EXPIRY_SECONDS = 60 * 60; // 1h — the client uploads right after presigning
-// 24h from the signing window's start (see signingWindowStart) — hydrated
-// asset URLs live a session. Clients should refresh against
-// presignGetLifetime(), which subtracts the elapsed part of the window.
-export const GET_EXPIRY_SECONDS = 24 * 60 * 60;
export class R2NotConfiguredError extends Error {
constructor() {
@@ -78,48 +74,19 @@ export function presignPut(key: string, mime: string): Promise<string> {
);
}
-/** Signatures are minted on window boundaries rather than at the current
- * instant, so the same object presigns to the same URL for everyone asking
- * within the window. A signature that changed per request made every media
- * URL unique, which meant the browser cache (and any cache in front of it)
- * could never reuse a byte — worst on a shared link, where many viewers pull
- * the same objects and one viewer re-pulls them on every reload. */
-const SIGNING_WINDOW_SECONDS = 60 * 60; // 1h
-
-/** Start of the signing window `at` falls in. Exported for the callers that
- * need to tell a client how long a URL stays good. */
-export function signingWindowStart(at: number = Date.now()): Date {
- const ms = SIGNING_WINDOW_SECONDS * 1000;
- return new Date(Math.floor(at / ms) * ms);
-}
-
-/** Seconds a URL minted now is still valid for: the tail of its window plus
- * the expiry. Shorter than GET_EXPIRY_SECONDS, and it is what clients should
- * refresh against. */
-export function presignGetLifetime(at: number = Date.now()): number {
- const elapsed = (at - signingWindowStart(at).getTime()) / 1000;
- return Math.round(GET_EXPIRY_SECONDS - elapsed);
-}
-
-export function presignGet(key: string, downloadName?: string): Promise<string> {
- return getSignedUrl(
- r2(),
- new GetObjectCommand({
- Bucket: R2_BUCKET,
- Key: key,
- ...(downloadName
- ? { ResponseContentDisposition: `attachment; filename="${downloadName.replace(/"/g, "")}"` }
- : {}),
- }),
- { expiresIn: GET_EXPIRY_SECONDS, signingDate: signingWindowStart() }
- );
-}
/** Object size/type, or null when the object does not exist. */
-export async function head(key: string): Promise<{ bytes: number; mime: string } | null> {
+export async function head(
+ key: string
+): Promise<{ bytes: number; mime: string; etag: string } | null> {
try {
const res = await r2().send(new HeadObjectCommand({ Bucket: R2_BUCKET, Key: key }));
- return { bytes: Number(res.ContentLength ?? 0), mime: res.ContentType ?? "" };
+ return {
+ bytes: Number(res.ContentLength ?? 0),
+ mime: res.ContentType ?? "",
+ // Quoted on the wire, and the quotes would need escaping in a URL.
+ etag: (res.ETag ?? "").replace(/[^\w]/g, ""),
+ };
} catch (e) {
if (e instanceof R2NotConfiguredError) throw e;
return null;
diff --git a/site/src/cut/server/cloud/shareCache.ts b/site/src/cut/server/cloud/shareCache.ts
index 88a336a2..fa6ce3f7 100644
--- a/site/src/cut/server/cloud/shareCache.ts
+++ b/site/src/cut/server/cloud/shareCache.ts
@@ -60,9 +60,9 @@ export function shareCacheHeaders(
};
}
-/** Headers for a redirect to a signed media URL. The signature is minted in
- * fixed windows (see r2.ts), so the redirect is reusable until the window
- * turns over; keep it well inside that window. */
+/** Headers for a redirect to a signed media URL. The token is minted in fixed
+ * windows (see mediaCdn.ts), so the redirect is reusable until the window turns
+ * over; keep it well inside that window. */
export function shareRedirectHeaders(
share: Pick<ShareRow, "access">,
ttlSeconds: number
diff --git a/site/src/cut/server/cloud/shareCard.tsx b/site/src/cut/server/cloud/shareCard.tsx
index 328d2ccb..685abaca 100644
--- a/site/src/cut/server/cloud/shareCard.tsx
+++ b/site/src/cut/server/cloud/shareCard.tsx
@@ -11,7 +11,8 @@
// also draws the placeholder: the project's name on Cut's own backdrop.
import { ImageResponse } from "next/og";
import { prisma } from "@/lib/prisma";
-import { head, presignGet, projectCardKey } from "./r2";
+import { MediaNotConfiguredError, mediaObjectUrl } from "./mediaCdn";
+import { head, projectCardKey } from "./r2";
export type CardKind = "gif" | "jpg";
@@ -21,6 +22,10 @@ const CARD_HEIGHT = 630;
/** A card URL names its version, so a crawler holding one can be handed the
* edge copy for as long as the signature behind it lives. */
export const CARD_CACHE_SECONDS = 45 * 60;
+/** How long past that a crawler may be served the cached redirect while it
+ * revalidates behind the request. A token in that redirect has to outlast the
+ * whole window, or the card unfurls broken hours after it was minted. */
+export const CARD_STALE_SECONDS = 24 * 60 * 60;
export interface ShareCardTarget {
userId: string;
@@ -36,9 +41,18 @@ export async function cardUrl(
): Promise<string | null> {
try {
const key = projectCardKey(target.userId, target.projectId, kind);
- if (!(await head(key))) return null;
- return await presignGet(key);
- } catch {
+ const object = await head(key);
+ if (!object) return null;
+ // The card lives on a fixed key that every re-render overwrites, so its
+ // ETag is what keeps the edge from serving the previous one.
+ return mediaObjectUrl(key, {
+ version: object.etag,
+ minLifetimeSeconds: CARD_CACHE_SECONDS + CARD_STALE_SECONDS,
+ });
+ } catch (e) {
+ // A card that isn't there yet is ordinary — the caller draws a placeholder.
+ // A deployment with no signing secret is not, and must not hide behind it.
+ if (e instanceof MediaNotConfiguredError) throw e;
return null;
}
}
diff --git a/site/src/cut/server/cloud/sharedView.ts b/site/src/cut/server/cloud/sharedView.ts
index ae3a9426..41877e24 100644
--- a/site/src/cut/server/cloud/sharedView.ts
+++ b/site/src/cut/server/cloud/sharedView.ts
@@ -7,31 +7,18 @@
import type { ProjectDoc, StoredAsset } from "@/cut/lib/types";
import { auth } from "@/lib/auth";
import { prisma } from "@/lib/prisma";
-import { MEDIA_TOKEN_TTL_SECONDS, mediaCdnEnabled, mediaCdnUrl } from "./mediaCdn";
-import { presignGet, presignGetLifetime, projectMediaKey } from "./r2";
+import { mediaObjectUrl, mediaUrlLifetime } from "./mediaCdn";
+import { projectMediaKey } from "./r2";
import { normalizeEmails, normalizeFeatures, type ShareFeatures } from "./share";
import { shareCacheHeaders, shareRedirectHeaders } from "./shareCache";
import { caught, decodeFileParam, err, redirect } from "./util";
const PRESIGN_GET_BATCH_MAX = 500;
-/** How long a media redirect may be reused. It has to stay inside the life of
- * the URL it carries, or the edge would keep handing out a dead link. */
+/** How long a media redirect may be reused. Tokens are minted on window
+ * boundaries, so the redirect is reusable until the window turns over; this
+ * keeps it well inside that. */
const MEDIA_REDIRECT_TTL = 15 * 60;
-/** A viewer-facing URL for one of the owner's objects: the edge Worker when
- * this deployment has it configured, a presigned R2 URL otherwise. */
-const sharedMediaUrl = (key: string): Promise<string> =>
- Promise.resolve(mediaCdnUrl(key) ?? presignGet(key));
-
-/** Redirect lifetime that matches whichever URL kind was minted. */
-const mediaRedirectTtl = () =>
- mediaCdnEnabled() ? Math.floor(MEDIA_TOKEN_TTL_SECONDS / 5) : MEDIA_REDIRECT_TTL;
-
-/** What the client is told a media batch is good for, so it re-mints ahead of
- * expiry rather than after a 403. */
-const mediaUrlLifetime = () =>
- mediaCdnEnabled() ? MEDIA_TOKEN_TTL_SECONDS : presignGetLifetime();
-
export type ShareRow = NonNullable<
Awaited<ReturnType<typeof prisma.cutProjectShare.findUnique>>
>;
@@ -164,8 +151,8 @@ export const sharedView = {
const allowed = await allowedFileNames(view.share, view.features);
if (!allowed.has(fileName)) return err("Media not found.", 404);
return redirect(
- await sharedMediaUrl(projectMediaKey(view.share.userId, id, fileName)),
- shareRedirectHeaders(view.share, mediaRedirectTtl())
+ mediaObjectUrl(projectMediaKey(view.share.userId, id, fileName)),
+ shareRedirectHeaders(view.share, MEDIA_REDIRECT_TTL)
);
} catch (e) {
return caught(e, "Bad request.", 400);
@@ -190,12 +177,10 @@ export const sharedView = {
typeof i.fileName === "string" &&
allowed.has(i.fileName)
)
- .map(async (i) => ({
+ .map((i) => ({
projectId: i.projectId!,
fileName: i.fileName!,
- url: await sharedMediaUrl(
- projectMediaKey(view.share.userId, i.projectId!, i.fileName!)
- ),
+ url: mediaObjectUrl(projectMediaKey(view.share.userId, i.projectId!, i.fileName!)),
}))
);
return Response.json({ urls, expiresIn: mediaUrlLifetime() });
@@ -227,8 +212,8 @@ export const sharedView = {
const row = await ownerProject(view.share);
if (!row?.previewKey) return new Response("Not found.", { status: 404 });
return redirect(
- await sharedMediaUrl(row.previewKey),
- shareRedirectHeaders(view.share, mediaRedirectTtl())
+ mediaObjectUrl(row.previewKey),
+ shareRedirectHeaders(view.share, MEDIA_REDIRECT_TTL)
);
} catch (e) {
return caught(e, "Bad request.", 400);
diff --git a/site/src/cut/server/cloud/util.ts b/site/src/cut/server/cloud/util.ts
index db23e81f..28a3ce15 100644
--- a/site/src/cut/server/cloud/util.ts
+++ b/site/src/cut/server/cloud/util.ts
@@ -1,13 +1,21 @@
import path from "node:path";
+import { MediaNotConfiguredError } from "./mediaCdn";
import { R2NotConfiguredError } from "./r2";
export const err = (message: string, status: number) =>
Response.json({ error: message }, { status });
-export const caught = (e: unknown, fallback: string, status = 500) =>
- e instanceof R2NotConfiguredError
- ? err(e.message, 500)
- : err(e instanceof Error ? e.message : fallback, status);
+export const caught = (e: unknown, fallback: string, status = 500) => {
+ if (e instanceof R2NotConfiguredError) return err(e.message, 500);
+ // The real reason belongs in the server's logs, not in a response an
+ // anonymous share viewer reads: it names the environment variable to set.
+ // 5xx also keeps the client's retry — a 4xx reads as "stop asking".
+ if (e instanceof MediaNotConfiguredError) {
+ console.error(e.message);
+ return err("Cloud media is unavailable.", 500);
+ }
+ return err(e instanceof Error ? e.message : fallback, status);
+};
export const redirect = (url: string, headers: Record<string, string> = {}) =>
new Response(null, { status: 302, headers: { Location: url, ...headers } });
diff --git a/site/src/cut/worker/cf/media.ts b/site/src/cut/worker/cf/media.ts
index e7f65d13..6341c974 100644
--- a/site/src/cut/worker/cf/media.ts
+++ b/site/src/cut/worker/cf/media.ts
@@ -12,6 +12,7 @@
// This file is compiled by wrangler, not the site's tsconfig — workers globals
// are typed loosely on purpose.
import { parseRange } from "../../server/cloud/httpRange";
+import { contentDisposition, mediaDownloadName } from "../../server/cloud/mediaName";
type R2Range = { offset: number; length?: number };
type R2Object = {
@@ -41,7 +42,13 @@ const EDGE_TTL_SECONDS = 7 * 24 * 60 * 60;
const encoder = new TextEncoder();
-async function signatureFor(secret: string, key: string, expires: number): Promise<string> {
+async function signatureFor(
+ secret: string,
+ key: string,
+ expires: number,
+ downloadName: string,
+ version: string
+): Promise<string> {
const cryptoKey = await crypto.subtle.importKey(
"raw",
encoder.encode(secret),
@@ -49,7 +56,11 @@ async function signatureFor(secret: string, key: string, expires: number): Promi
false,
["sign"]
);
- const mac = await crypto.subtle.sign("HMAC", cryptoKey, encoder.encode(`${key}\n${expires}`));
+ const mac = await crypto.subtle.sign(
+ "HMAC",
+ cryptoKey,
+ encoder.encode(`${key}\n${expires}\n${downloadName}\n${version}`)
+ );
// base64url, matching node's digest("base64url") on the signing side.
let binary = "";
for (const byte of new Uint8Array(mac)) binary += String.fromCharCode(byte);
@@ -76,9 +87,21 @@ function sameSignature(a: string, b: string): boolean {
// URL is already full access, and no credentials ride these requests.
const CORS_HEADERS: Record<string, string> = {
"Access-Control-Allow-Origin": "*",
- "Access-Control-Expose-Headers": "Content-Length, Content-Range, Accept-Ranges, ETag",
+ "Access-Control-Expose-Headers":
+ "Content-Length, Content-Range, Accept-Ranges, ETag, Content-Disposition",
};
+/** An attachment download is the same bytes with one more header, so the cached
+ * entry stays the plain object and the header goes on the way out — the cache key
+ * ignores the download name, and a stored Content-Disposition would otherwise
+ * leak onto every later inline read of that object. */
+function asDownload(res: Response, downloadName: string): Response {
+ if (!downloadName) return res;
+ const out = new Response(res.body, res);
+ out.headers.set("Content-Disposition", contentDisposition(downloadName));
+ return out;
+}
+
function baseHeaders(object: R2Object): Headers {
const headers = new Headers();
object.writeHttpMetadata(headers);
@@ -117,23 +140,43 @@ export async function serveMedia(
});
}
const url = new URL(request.url);
- const key = decodeURIComponent(url.pathname.replace(/^\/+/, ""));
+ // 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);
- if (!sameSignature(sig, await signatureFor(env.CUT_MEDIA_SIGNING_SECRET, key, expires))) {
- return refuse("Forbidden.", 403);
- }
+ const expected = await signatureFor(
+ env.CUT_MEDIA_SIGNING_SECRET,
+ key,
+ expires,
+ downloadName,
+ version
+ );
+ if (!sameSignature(sig, expected)) return refuse("Forbidden.", 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
+ // 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
+ // a miss per viewer per rotation. The version is what a rewritten object
+ // 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.
- const cacheUrl = `${url.origin}/${url.pathname.replace(/^\/+/, "")}`;
+ const cacheUrl =
+ `${url.origin}/${url.pathname.replace(/^\/+/, "")}` + (version ? `?v=${version}` : "");
const storeKey = new Request(cacheUrl, { method: "GET" });
const rangeHeader = request.headers.get("range");
const lookupKey = rangeHeader
@@ -141,7 +184,7 @@ export async function serveMedia(
: storeKey;
const cache = caches.default;
const hit = await cache.match(lookupKey);
- if (hit) return hit;
+ if (hit) return asDownload(hit, downloadName);
// The size is only needed to resolve a range; a whole-object request skips
// this and reads it off the object it is already fetching.
@@ -180,7 +223,7 @@ export async function serveMedia(
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());
- return new Response(part.body, { status: 206, headers });
+ return asDownload(new Response(part.body, { status: 206, headers }), downloadName);
}
const object = await env.CUT_MEDIA.get(key);
@@ -191,5 +234,5 @@ export async function serveMedia(
// Past Cloudflare's ceiling the put would fail, so it is not attempted;
// those objects stream from R2 every time rather than breaking.
if (object.size <= MAX_CACHEABLE_BYTES) ctx.waitUntil(cache.put(storeKey, full.clone()));
- return full;
+ return asDownload(full, downloadName);
}
diff --git a/site/src/types/bun-test.d.ts b/site/src/types/bun-test.d.ts
index f2a633c8..8fc9f464 100644
--- a/site/src/types/bun-test.d.ts
+++ b/site/src/types/bun-test.d.ts
@@ -12,8 +12,11 @@ declare module "bun:test" {
toBe(expected: unknown): void;
toEqual(expected: unknown): void;
toBeCloseTo(expected: number, precision?: number): void;
+ toBeGreaterThan(expected: number): void;
toBeGreaterThanOrEqual(expected: number): void;
+ toBeLessThan(expected: number): void;
toBeLessThanOrEqual(expected: number): void;
+ toContain(expected: string): void;
toBeUndefined(): void;
toHaveLength(expected: number): void;
toBeTruthy(): void;