Skip to content

Open source CapCut alternative.

TypeScript

refactor(site): the media hostname is code, not an env var

David Lec51da2f608f1
diff --git a/site/.env.example b/site/.env.example
index d8307aa8..dafa1b50 100644
--- a/site/.env.example
+++ b/site/.env.example
@@ -60,10 +60,10 @@ R2_SECRET_ACCESS_KEY="replace-with-r2-secret-access-key"
CUT_RENDER_WAKE_URL="replace-with-worker-wake-url"
CUT_RENDER_WAKE_SECRET="replace-with-wake-secret"
-# Shared-media edge delivery. With both set, a shared project's media is served
-# from this host by the Cut Worker's R2 binding — cached at the edge, and
-# revocable, because the token is ours and lives only minutes. The secret must
-# match the Worker's CUT_MEDIA_SIGNING_SECRET. Leave unset (local dev) to
+# 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.
-CUT_MEDIA_BASE_URL="https://media.donkeycut.com"
CUT_MEDIA_SIGNING_SECRET="replace-with-media-signing-secret"
diff --git a/site/src/cut/lib/hosts.ts b/site/src/cut/lib/hosts.ts
index 6b771a0e..ba653af3 100644
--- a/site/src/cut/lib/hosts.ts
+++ b/site/src/cut/lib/hosts.ts
@@ -11,6 +11,12 @@ export const DONKEYCUT_HOSTS = new Set(["donkeycut.com", "www.donkeycut.com"]);
export const DONKEYCUT_CANONICAL = "https://donkeycut.com";
+// Shared media is served from its own hostname by the Cut Worker's R2 binding
+// (src/cut/worker/cf/media.ts), never by this app. The Worker claims it as a
+// custom domain in wrangler.jsonc; change that route and this together.
+export const CUT_MEDIA_HOST = "media.donkeycut.com";
+export const CUT_MEDIA_ORIGIN = `https://${CUT_MEDIA_HOST}`;
+
function hostname(host: string | null | undefined): string {
return host ? host.split(":")[0] : "";
}
diff --git a/site/src/cut/server/cloud/mediaCdn.ts b/site/src/cut/server/cloud/mediaCdn.ts
index 99291b74..b7688b51 100644
--- a/site/src/cut/server/cloud/mediaCdn.ts
+++ b/site/src/cut/server/cloud/mediaCdn.ts
@@ -12,24 +12,22 @@
// 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.
+// 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";
+import { CUT_MEDIA_ORIGIN } from "@/cut/lib/hosts";
/** 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 };
-}
+/** The signing secret, when this deployment has one. */
+const signingSecret = () => process.env.CUT_MEDIA_SIGNING_SECRET || null;
/** Whether shared media rides the edge Worker on this deployment. */
-export const mediaCdnEnabled = () => config() != null;
+export const mediaCdnEnabled = () => signingSecret() != 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. */
@@ -37,25 +35,25 @@ export function mediaSignature(secret: string, key: string, expires: number): st
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. */
+/** An edge URL for one R2 key, or null when this deployment has no secret. */
export function mediaCdnUrl(key: string): string | null {
- const cfg = config();
- if (!cfg) return null;
+ const secret = signingSecret();
+ if (!secret) return null;
const expires = Math.floor(Date.now() / 1000) + MEDIA_TOKEN_TTL_SECONDS;
- const sig = mediaSignature(cfg.secret, key, expires);
+ const sig = mediaSignature(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}`;
+ 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; used by the tests. */
+ * can never drift. */
export function mediaTokenValid(key: string, expires: number, sig: string): boolean {
- const cfg = config();
- if (!cfg) return false;
+ const secret = signingSecret();
+ if (!secret) return false;
if (!Number.isFinite(expires) || expires * 1000 < Date.now()) return false;
- const expected = Buffer.from(mediaSignature(cfg.secret, key, expires));
+ const expected = Buffer.from(mediaSignature(secret, key, expires));
const given = Buffer.from(sig);
return expected.length === given.length && timingSafeEqual(expected, given);
}
diff --git a/site/src/cut/worker/README.md b/site/src/cut/worker/README.md
index f0b9083a..809430c8 100644
--- a/site/src/cut/worker/README.md
+++ b/site/src/cut/worker/README.md
@@ -97,16 +97,20 @@ stream straight through, uncached.
One-time setup:
1. The zone must be on Cloudflare — the Cache API is a no-op on `workers.dev`,
- so `routes` has to be a real hostname. `wrangler.jsonc` claims
- `media.donkeycut.com` as a custom domain and sets `CUT_MEDIA_HOST` to match;
- change both together, or comment both out to leave the feature off.
-2. Worker secret: `npx wrangler secret put CUT_MEDIA_SIGNING_SECRET -c
- src/cut/worker/wrangler.jsonc` (any long random string).
-3. On the hosted site (Vercel env): `CUT_MEDIA_BASE_URL` = `https://` + that
- hostname, and `CUT_MEDIA_SIGNING_SECRET` = the same string.
-
-Without those two site variables the hosted API presigns R2 exactly as before,
-so local dev and an un-migrated deployment both keep working.
+ so the route has to be a real hostname. `wrangler.jsonc` claims
+ `media.donkeycut.com` as a custom domain and wrangler creates the DNS record
+ and certificate on deploy; a pre-existing CNAME on that name blocks it. The
+ handler matches `CUT_MEDIA_HOST` in `../lib/hosts.ts`, so the two names move
+ together.
+2. Generate the secret once: `openssl rand -hex 32`.
+3. Worker secret: `npx wrangler secret put CUT_MEDIA_SIGNING_SECRET -c
+ src/cut/worker/wrangler.jsonc`, pasting that value.
+4. On the hosted site (Vercel env): `CUT_MEDIA_SIGNING_SECRET`, the same value.
+ Holding it is what switches the feature on.
+
+The two sides must carry the same string — a mismatch fails every request's
+signature check. Without the site variable the hosted API presigns R2 exactly
+as before, so local dev and an un-migrated deployment both keep working.
## Copy queue
diff --git a/site/src/cut/worker/cf/worker.ts b/site/src/cut/worker/cf/worker.ts
index c397a97f..c6e4f51d 100644
--- a/site/src/cut/worker/cf/worker.ts
+++ b/site/src/cut/worker/cf/worker.ts
@@ -6,6 +6,7 @@
// This file is compiled by wrangler, not the site's tsconfig — workers
// globals are typed loosely on purpose.
import { Container, getContainer } from "@cloudflare/containers";
+import { CUT_MEDIA_HOST } from "../../lib/hosts";
import { serveMedia, type MediaEnv } from "./media";
type WorkerEnv = MediaEnv & {
@@ -17,8 +18,6 @@ type WorkerEnv = MediaEnv & {
CUT_WAKE_SECRET: string;
CUT_COPY_EXECUTE_URL: string;
CUT_COPY_EXECUTE_SECRET: string;
- /** Hostname the shared-media routes arrive on. */
- CUT_MEDIA_HOST: string;
};
// Minimal shapes for the queue consumer — this file stays off workers-types
@@ -58,9 +57,7 @@ export default {
// Shared media arrives on its own hostname (see wrangler.jsonc routes) and
// is the only public traffic this Worker takes. Matching on the host keeps
// it clear of the container's control endpoints below.
- if (env.CUT_MEDIA_HOST && url.hostname === env.CUT_MEDIA_HOST) {
- return serveMedia(request, env, ctx);
- }
+ if (url.hostname === CUT_MEDIA_HOST) return serveMedia(request, env, ctx);
if (request.method === "POST" && url.pathname === "/wake") {
// Starting the container bills CPU, so the wake is not public: callers
// present the shared secret the hosted API holds.
diff --git a/site/src/cut/worker/wrangler.jsonc b/site/src/cut/worker/wrangler.jsonc
index e8212d25..74e80fb2 100644
--- a/site/src/cut/worker/wrangler.jsonc
+++ b/site/src/cut/worker/wrangler.jsonc
@@ -27,12 +27,11 @@
},
// Shared media is served from the edge (cf/media.ts) with the bucket kept
// private: this binding is the only way in. The Cache API is inert on
- // workers.dev, so the route has to be a real hostname on the zone — set
- // CUT_MEDIA_HOST to the same name. Comment both out to leave the feature off;
- // the hosted API then presigns R2 exactly as before.
+ // workers.dev, so the route has to be a real hostname on the zone; it must
+ // match CUT_MEDIA_HOST in ../../lib/hosts.ts, which is what the handler
+ // matches on. Wrangler creates the DNS record and certificate on deploy.
"r2_buckets": [{ "binding": "CUT_MEDIA", "bucket_name": "donkey-cut" }],
"routes": [{ "pattern": "media.donkeycut.com", "custom_domain": true }],
- "vars": { "CUT_MEDIA_HOST": "media.donkeycut.com" },
"migrations": [{ "tag": "v1", "new_sqlite_classes": ["CutRenderWorker"] }],
// Share-copy jobs drain serially: one message per batch, one batch in
// flight, so a burst of copy requests can't stampede R2 or the database.