Cotton code
89 lines · 4.4 KB · TypeScriptRaw
/** * A shared space's signed media URLs (SHARED SPACE, 26 Nov 2026): the front Worker answers a space's bytes straight * from R2 (as STREAM AT THE DOOR does a film's), never through any person's object nor the space's own. The token is * the whole grant: HMAC-SHA256, by a key of its own derived from STREAM_SIGNING_KEY (HKDF-SHA256, info * `cotton-space-media-v1`: a film's stream token and a space's media token are signed by different keys), over * *   space-v1 \n <op> \n <space id> \n <file id> \n <size or -> \n <expiry seconds> * * so it reaches one file of one space, for one act (`r` read, `w` write), until it expires. A write's size is signed * in, and the door takes no other length. Only the space's gate mints one, and only for a member or a live link. */import type { Env } from "../env.ts";import { refuse } from "../http.ts";export const MEDIA_PATH = /^\/v1\/space-media\/([A-Za-z0-9_-]+)\/([A-Za-z0-9_-]{22})\/([A-Za-z0-9_-]{22})$/;/** How long a read URL lives: short, so one minted before a removal dies soon after it. */export const READ_LIFE_MS = 15 * 60 * 1000;/** How long an upload URL lives; an upload not committed by then is swept and refunded. */export const WRITE_LIFE_MS = 60 * 60 * 1000;export type Op = "r" | "w";/** Where a space's file lies in the MEDIA bucket: under the space, never under a person. */export function fileAt(space: string, file: string): string {  return `spaces/${space}/${file}`;}async function signingKey(env: Env): Promise<CryptoKey> {  const secret = env.STREAM_SIGNING_KEY;  if (!secret) refuse(503, "no_stream_key", "this Worker has no STREAM_SIGNING_KEY");  const root = await crypto.subtle.importKey("raw", new TextEncoder().encode(secret), "HKDF", false, ["deriveKey"]);  return crypto.subtle.deriveKey(    { name: "HKDF", hash: "SHA-256", salt: new Uint8Array(32), info: new TextEncoder().encode("cotton-space-media-v1") },    root,    { name: "HMAC", hash: "SHA-256", length: 256 },    false,    ["sign", "verify"],  );}function message(op: Op, space: string, file: string, size: number | null, expires: number): Uint8Array {  return new TextEncoder().encode(`space-v1\n${op}\n${space}\n${file}\n${size ?? "-"}\n${expires}`);}export function b64url(bytes: Uint8Array): string {  let s = "";  for (const b of bytes) s += String.fromCharCode(b);  return btoa(s).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");}function unb64url(text: string): Uint8Array | null {  try {    return Uint8Array.from(atob(text.replace(/-/g, "+").replace(/_/g, "/")), (c) => c.charCodeAt(0));  } catch {    return null;  }}/** A token: op byte, expiry (8 bytes), size (8 bytes, or all ones for none), then the 32-byte HMAC. */export async function mint(env: Env, op: Op, space: string, file: string, size: number | null, expires: number): Promise<string> {  const mac = new Uint8Array(await crypto.subtle.sign("HMAC", await signingKey(env), message(op, space, file, size, expires)));  const bytes = new Uint8Array(1 + 8 + 8 + 32);  const view = new DataView(bytes.buffer);  bytes[0] = op === "w" ? 0x77 : 0x72;  view.setBigUint64(1, BigInt(expires));  view.setBigUint64(9, size === null ? 0xffffffffffffffffn : BigInt(size));  bytes.set(mac, 17);  return b64url(bytes);}/** The URL path a token rides in. */export function mediaPath(token: string, space: string, file: string): string {  return `/v1/space-media/${token}/${space}/${file}`;}/** The token's act and signed size, when it is genuine, unexpired and for this file; a 403 otherwise. */export async function admit(env: Env, token: string, space: string, file: string, now = Date.now()): Promise<{ op: Op; size: number | null }> {  const bytes = unb64url(token);  if (!bytes || bytes.length !== 49 || (bytes[0] !== 0x72 && bytes[0] !== 0x77)) refuse(403, "bad_media_token", "this media URL is not one Cotton made");  const op: Op = bytes[0] === 0x77 ? "w" : "r";  const view = new DataView(bytes.buffer);  const expires = Number(view.getBigUint64(1));  const rawSize = view.getBigUint64(9);  const size = rawSize === 0xffffffffffffffffn ? null : Number(rawSize);  const genuine = await crypto.subtle.verify("HMAC", await signingKey(env), bytes.slice(17), message(op, space, file, size, expires));  if (!genuine) refuse(403, "bad_media_token", "this media URL is not one Cotton made, or not for this file");  if (expires * 1000 <= now) refuse(403, "media_expired", "this media URL has expired; ask for a new one");  return { op, size };}