Cotton code
294 lines · 18.4 KB · TypeScriptRaw
import { env, runInDurableObject, SELF } from "cloudflare:test";import { describe, expect, it } from "vitest";import { rangeOf, STREAM_LIFE_MS, streamToken } from "../src/media.ts";import { ADMIN, DATABASE_ID, http, mint, OWNER_PHONE, personalObject } from "./personal.ts";const bytes = (s: string) => new TextEncoder().encode(s);async function put(slug: string, key: string, auth: string, body: Uint8Array, type: string): Promise<void> {  const res = await SELF.fetch(`https://example.test/b/${slug}/v1/media/${key}`, {    method: "PUT",    headers: { authorization: `Bearer ${auth}`, "content-type": type, "content-length": String(body.length) },    body,  });  expect(res.status, await res.text()).toBe(201);}/** * RULE (owner, 4 Nov 2026): films play in Apple's player, streamed and kept on the phone: an HLS folder per film, * fetched by AVPlayer with a signed URL and no bearer, Range answered, playlists never rewritten. */describe("a film streamed by a signed URL", () => {  const SLUG = "stream-personal";  const FOLDER = `${DATABASE_ID}/films/film-1/`;  const MASTER = `${FOLDER}master.m3u8`;  const MASTER_TEXT = "#EXTM3U\n#EXT-X-INDEPENDENT-SEGMENTS\n#EXT-X-STREAM-INF:BANDWIDTH=1000\nv0/index.m3u8\n";  const SEGMENT = bytes("0123456789abcdef");  let owner = "";  let credential = "";  let url = "";  it("mints a URL for the owner's film, good for twelve hours", async () => {    ({ owner, credential } = await personalObject(SLUG));    await put(SLUG, MASTER, credential, bytes(MASTER_TEXT), "application/vnd.apple.mpegurl");    await put(SLUG, `${FOLDER}v0/index.m3u8`, credential, bytes("#EXTM3U\n#EXT-X-MAP:URI=\"init.mp4\"\n#EXTINF:6,\nseg0.m4s\n#EXT-X-ENDLIST\n"), "application/vnd.apple.mpegurl");    await put(SLUG, `${FOLDER}v0/init.mp4`, credential, bytes("init"), "video/mp4");    await put(SLUG, `${FOLDER}v0/seg0.m4s`, credential, SEGMENT, "video/iso.segment");    await put(SLUG, `${FOLDER}sub-en.vtt`, credential, bytes("WEBVTT\n"), "text/vtt");    await put(SLUG, `${DATABASE_ID}/films/film-2/master.m3u8`, credential, bytes(MASTER_TEXT), "application/vnd.apple.mpegurl");    await put(SLUG, `${DATABASE_ID}/photos/p.jpg`, credential, bytes("jpeg"), "image/jpeg");    // The phone mints (cotton-client MEDIA_STREAM, its device credential); an assistant's token is refused a film's    // folder, a kind the owner's devices seal (AVATAR SEAL 4).    const byToken = await http<{ code: string }>(SLUG, "POST", "/v1/media/stream", { key: MASTER }, { authorization: `Bearer ${owner}` });    expect([byToken.status, byToken.body.code]).toEqual([403, "sealed_kind"]);    for (const auth of [credential]) {      // Each URL is minted between its own request's before and after: it lives twelve hours from then.      const before = Date.now();      const res = await http<{ url: string; expires_at: string }>(SLUG, "POST", "/v1/media/stream", { key: MASTER }, { authorization: `Bearer ${auth}` });      const after = Date.now();      expect(res.status, JSON.stringify(res.body)).toBe(200);      expect(res.body.url).toMatch(new RegExp(`^https://example\\.test/b/${SLUG}/v1/stream/[A-Za-z0-9_-]{55}/${MASTER}$`));      const expires = Date.parse(res.body.expires_at);      expect(expires - before).toBeGreaterThan(STREAM_LIFE_MS - 5000);      expect(expires - after).toBeLessThanOrEqual(STREAM_LIFE_MS);      url = res.body.url;    }  });  it("refuses a mint to anyone but the owner, for a key that is no film's, and for a film not there", async () => {    const reader = await mint(SLUG, credential, "reader", ["read"]);    expect((await http(SLUG, "POST", "/v1/media/stream", { key: MASTER })).status).toBe(403);    expect((await http(SLUG, "POST", "/v1/media/stream", { key: MASTER }, { authorization: `Bearer ${reader}` })).status).toBe(403);    expect((await http(SLUG, "POST", "/v1/media/stream", { key: `${DATABASE_ID}/photos/p.jpg` }, { authorization: `Bearer ${credential}` })).body).toMatchObject({ code: "not_streamable" });    expect((await http(SLUG, "POST", "/v1/media/stream", { key: `${DATABASE_ID}/films/film-9/master.m3u8` }, { authorization: `Bearer ${credential}` })).status).toBe(404);    expect((await http(SLUG, "POST", "/v1/media/stream", { key: `00000000-0000-4000-8000-000000000000/films/film-1/master.m3u8` }, { authorization: `Bearer ${credential}` })).status).toBe(404);  });  it("serves the folder with no bearer, each file as the player expects it, relative URIs resolving under the token", async () => {    const master = await SELF.fetch(url);    expect(master.status).toBe(200);    expect(master.headers.get("content-type")).toBe("application/vnd.apple.mpegurl");    expect(master.headers.get("cache-control")).toBe("private");    expect(master.headers.get("accept-ranges")).toBe("bytes");    expect(await master.text(), "a playlist is never rewritten").toBe(MASTER_TEXT);    const variant = new URL("v0/index.m3u8", url);    expect((await SELF.fetch(variant)).headers.get("content-type")).toBe("application/vnd.apple.mpegurl");    expect((await SELF.fetch(new URL("init.mp4", variant))).headers.get("content-type")).toBe("video/mp4");    expect((await SELF.fetch(new URL("../sub-en.vtt", variant))).headers.get("content-type")).toBe("text/vtt; charset=utf-8");    const segment = await SELF.fetch(new URL("seg0.m4s", variant));    expect(segment.headers.get("content-type")).toBe("video/iso.segment");    expect(new Uint8Array(await segment.arrayBuffer())).toEqual(SEGMENT);  });  // RULE (Android Cinemas, 15 Nov 2026): a cast receiver, a web page on the TV, reads the stream across origins: every  // stream answer is readable by any origin (the signed URL is the whole grant) and a Range read's preflight is answered.  it("opens the stream to a cast receiver's origin, its Range preflight answered", async () => {    const res = await SELF.fetch(url, { headers: { origin: "https://www.gstatic.com", range: "bytes=0-3" } });    expect(res.status).toBe(206);    expect(res.headers.get("access-control-allow-origin")).toBe("*");    expect(res.headers.get("access-control-expose-headers")).toContain("content-range");    await res.arrayBuffer();    const preflight = await SELF.fetch(url, { method: "OPTIONS", headers: { origin: "https://www.gstatic.com", "access-control-request-method": "GET", "access-control-request-headers": "range" } });    expect(preflight.status).toBe(204);    expect([preflight.headers.get("access-control-allow-origin"), preflight.headers.get("access-control-allow-headers")]).toEqual(["*", "range"]);    const forged = await SELF.fetch(url.replace(/stream\/[^/]+\//, "stream/forged/"), { method: "OPTIONS" });    expect(forged.status, "a preflight admits nothing: the GET is still refused").toBe(204);    expect((await SELF.fetch(url.replace(/stream\/[^/]+\//, "stream/forged/"))).status).toBe(403);  });  it("answers a Range with 206 and the bytes asked, and past the end with 416", async () => {    const segment = new URL("v0/seg0.m4s", url);    const part = await SELF.fetch(segment, { headers: { range: "bytes=2-5" } });    expect(part.status).toBe(206);    expect(part.headers.get("content-range")).toBe(`bytes 2-5/${SEGMENT.length}`);    expect(part.headers.get("content-length")).toBe("4");    expect(await part.text()).toBe("2345");    const tail = await SELF.fetch(segment, { headers: { range: "bytes=-3" } });    expect([tail.status, tail.headers.get("content-range"), await tail.text()]).toEqual([206, `bytes 13-15/${SEGMENT.length}`, "def"]);    const open = await SELF.fetch(segment, { headers: { range: "bytes=10-" } });    expect([open.status, await open.text()]).toEqual([206, "abcdef"]);    const past = await SELF.fetch(segment, { headers: { range: "bytes=99-" } });    expect([past.status, past.headers.get("content-range")]).toEqual([416, `bytes */${SEGMENT.length}`]);    await past.arrayBuffer();  });  it("refuses a forged token, an expired one, a key outside its film, and answers 404 for a file not there", async () => {    const base = url.slice(0, url.indexOf("/v1/stream/"));    const tokenOf = url.slice(base.length + "/v1/stream/".length).split("/")[0]!;    const at = (t: string, key: string) => `${base}/v1/stream/${t}/${key}`;    const forged = (tokenOf[0] === "A" ? "B" : "A") + tokenOf.slice(1);    for (const [t, key, code] of [      [forged, MASTER, "bad_stream_token"],      ["not-a-token", MASTER, "bad_stream_token"],      [tokenOf, `${DATABASE_ID}/films/film-2/master.m3u8`, "bad_stream_token"],      [tokenOf, `${DATABASE_ID}/photos/p.jpg`, "outside_stream"],      [await streamToken(env, FOLDER, Math.floor(Date.now() / 1000) - 1), MASTER, "stream_expired"],      [await streamToken(env, FOLDER, Math.floor(Date.now() / 1000) - 1, SLUG), MASTER, "stream_expired"],      // A slug-bound token is good for its own account only.      [await streamToken(env, FOLDER, Math.floor(Date.now() / 1000) + 600, "another-slug"), MASTER, "bad_stream_token"],    ] as const) {      const res = await SELF.fetch(at(t, key));      expect(res.status, `${code} ${key}`).toBe(403);      expect(((await res.json()) as { code: string }).code).toBe(code);    }    const missing = await SELF.fetch(at(tokenOf, `${FOLDER}v0/seg9.m4s`));    expect(missing.status).toBe(404);    await missing.arrayBuffer();    expect((await SELF.fetch(url, { method: "POST" })).status).toBe(405);  });  // STREAM AT THE DOOR (coordinator, 26 Nov 2026): a slug-bound URL is answered by the front Worker from the bucket,  // never in the object's queue: with the object's own stream route broken, the film still plays; an older token (not  // slug-bound) still goes to the object.  it("answers a slug-bound stream at the front Worker, never entering the object", async () => {    await runInDurableObject(env.BUSINESS.get(env.BUSINESS.idFromName(SLUG)), (instance) => {      (instance as unknown as { stream: () => never }).stream = () => {        throw new Error("the object was entered");      };    });    const master = await SELF.fetch(url);    expect([master.status, await master.text()]).toEqual([200, MASTER_TEXT]);    const ranged = await SELF.fetch(new URL("v0/seg0.m4s", url), { headers: { range: "bytes=0-3" } });    expect([ranged.status, await ranged.text()]).toEqual([206, "0123"]);    const base = url.slice(0, url.indexOf("/v1/stream/"));    const old = await SELF.fetch(`${base}/v1/stream/${await streamToken(env, FOLDER, Math.floor(Date.now() / 1000) + 600)}/${MASTER}`);    expect(old.status, "an old token goes to the object, broken here").toBe(500);    await old.arrayBuffer();    await runInDurableObject(env.BUSINESS.get(env.BUSINESS.idFromName(SLUG)), (instance) => {      delete (instance as unknown as { stream?: unknown }).stream;    });  });  it("answers a Range on the owner's own media route too", async () => {    const res = await SELF.fetch(`https://example.test/b/${SLUG}/v1/media/${FOLDER}v0/seg0.m4s`, { headers: { authorization: `Bearer ${credential}`, range: "bytes=0-3" } });    expect(res.status).toBe(206);    expect(res.headers.get("content-range")).toBe(`bytes 0-3/${SEGMENT.length}`);    expect(res.headers.get("accept-ranges")).toBe("bytes");    expect(await res.text()).toBe("0123");    const whole = await SELF.fetch(`https://example.test/b/${SLUG}/v1/media/${FOLDER}v0/seg0.m4s`, { headers: { authorization: `Bearer ${credential}` } });    expect([whole.status, whole.headers.get("content-length")]).toEqual([200, String(SEGMENT.length)]);    await whole.arrayBuffer();  });  it("streams on the open host, where the key's database names the object", async () => {    const entered = await SELF.fetch("https://cottondb.com/v1/admin/directory", {      method: "POST",      headers: { ...ADMIN, "content-type": "application/json" },      body: JSON.stringify({ database_id: DATABASE_ID, slug: SLUG, phone: OWNER_PHONE }),    });    expect(entered.status, await entered.text()).toBe(200);    const minted = await SELF.fetch("https://cottondb.com/v1/media/stream", {      method: "POST",      headers: { authorization: `Bearer ${credential}`, "content-type": "application/json" },      body: JSON.stringify({ key: MASTER }),    });    const { url: open } = (await minted.json()) as { url: string };    expect(open).toMatch(/^https:\/\/cottondb\.com\/v1\/stream\//);    const res = await SELF.fetch(open);    expect([res.status, await res.text()]).toEqual([200, MASTER_TEXT]);    const unknown = await SELF.fetch(open.replace(DATABASE_ID, "00000000-0000-4000-8000-000000000000"));    expect(unknown.status).toBe(404);    await unknown.arrayBuffer();  });});describe("a Range header", () => {  it("reads one range of a size, whole for none or several, unsatisfiable past the end", () => {    expect(rangeOf(null, 10)).toBeNull();    expect(rangeOf("bytes=0-1", 10)).toEqual({ offset: 0, length: 2 });    expect(rangeOf("bytes=5-", 10)).toEqual({ offset: 5, length: 5 });    expect(rangeOf("bytes=8-100", 10)).toEqual({ offset: 8, length: 2 });    expect(rangeOf("bytes=-4", 10)).toEqual({ offset: 6, length: 4 });    expect(rangeOf("bytes=-40", 10)).toEqual({ offset: 0, length: 10 });    expect(rangeOf("bytes=0-1,4-5", 10)).toBeNull();    expect(rangeOf("bytes=5-2", 10)).toBeNull();    expect(rangeOf("items=0-1", 10)).toBeNull();    expect(rangeOf("bytes=10-", 10)).toBe("unsatisfiable");    expect(rangeOf("bytes=-0", 10)).toBe("unsatisfiable");  });});/** RULE (owner, 4 Nov 2026): a book streams by a signed URL for its one key, so the reader or a background download on the phone fetches it with no bearer. */describe("a book streamed by a signed URL", () => {  const SLUG = "stream-books";  const BOOK = `${DATABASE_ID}/books/${"ab".repeat(32)}.epub`;  const OTHER = `${DATABASE_ID}/books/${"cd".repeat(32)}.pdf`;  const BOOK_BYTES = bytes("an invented book's bytes");  it("signs one book key, serves it with its type and Range, and nothing else with that token", async () => {    const { credential: device } = await personalObject(SLUG);    await put(SLUG, BOOK, device, BOOK_BYTES, "application/epub+zip");    await put(SLUG, OTHER, device, bytes("another invented book"), "application/pdf");    const minted = await http<{ url: string }>(SLUG, "POST", "/v1/media/stream", { key: BOOK }, { authorization: `Bearer ${device}` });    expect(minted.status, JSON.stringify(minted.body)).toBe(200);    const url = minted.body.url;    expect(url).toMatch(new RegExp(`/v1/stream/[A-Za-z0-9_-]{55}/${BOOK}$`));    const whole = await SELF.fetch(url);    expect([whole.status, whole.headers.get("content-type")]).toEqual([200, "application/epub+zip"]);    expect(new Uint8Array(await whole.arrayBuffer())).toEqual(BOOK_BYTES);    const part = await SELF.fetch(url, { headers: { range: "bytes=0-1" } });    expect([part.status, await part.text()]).toEqual([206, "an"]);    const token = url.split("/v1/stream/")[1]!.split("/")[0]!;    const base = url.slice(0, url.indexOf("/v1/stream/"));    const other = await SELF.fetch(`${base}/v1/stream/${token}/${OTHER}`);    expect(other.status, "a book's token reaches that book alone").toBe(403);    expect(((await other.json()) as { code: string }).code).toBe("bad_stream_token");    expect((await http(SLUG, "POST", "/v1/media/stream", { key: `${DATABASE_ID}/books/${"ef".repeat(32)}.pdf` }, { authorization: `Bearer ${device}` })).status, "a book not there").toBe(404);  });});/** RULE (Music definition, 4 Nov 2026): a song streams by a signed URL for its one key, as a book does, so the player or a background download fetches it with no bearer. */describe("a song streamed by a signed URL", () => {  const SLUG = "stream-songs";  const SONG = `${DATABASE_ID}/music/${"ab".repeat(32)}.flac`;  const OTHER = `${DATABASE_ID}/music/${"cd".repeat(32)}.mp3`;  const SONG_BYTES = bytes("fLaC an invented song");  it("signs one song key, serves it with its type and Range, and nothing else with that token", async () => {    const { credential: device } = await personalObject(SLUG);    await put(SLUG, SONG, device, SONG_BYTES, "audio/flac");    await put(SLUG, OTHER, device, bytes("another invented song"), "audio/mpeg");    const minted = await http<{ url: string }>(SLUG, "POST", "/v1/media/stream", { key: SONG }, { authorization: `Bearer ${device}` });    expect(minted.status, JSON.stringify(minted.body)).toBe(200);    const url = minted.body.url;    const whole = await SELF.fetch(url);    expect([whole.status, whole.headers.get("content-type")]).toEqual([200, "audio/flac"]);    expect(new Uint8Array(await whole.arrayBuffer())).toEqual(SONG_BYTES);    const part = await SELF.fetch(url, { headers: { range: "bytes=0-3" } });    expect([part.status, await part.text()]).toEqual([206, "fLaC"]);    const token = url.split("/v1/stream/")[1]!.split("/")[0]!;    const base = url.slice(0, url.indexOf("/v1/stream/"));    expect((await SELF.fetch(`${base}/v1/stream/${token}/${OTHER}`)).status, "a song's token reaches that song alone").toBe(403);  });});/** RULE (Cinemas definition, 5 Nov 2026): a film the phone plays as it is streams whole, `<database id>/films/<id>/whole.<ext>`, by the same signed URL and Range as an HLS folder. */describe("a whole film streamed by a signed URL", () => {  const SLUG = "stream-whole-film";  const WHOLE = `${DATABASE_ID}/films/f-whole/whole.mp4`;  const BODY = bytes("ftypisom an invented whole film");  it("signs the film's folder, serves the file as video/mp4, and answers a Range with 206", async () => {    const { credential: device } = await personalObject(SLUG);    await put(SLUG, WHOLE, device, BODY, "video/mp4");    const res = await http<{ url: string }>(SLUG, "POST", "/v1/media/stream", { key: WHOLE }, { authorization: `Bearer ${device}` });    expect(res.status, JSON.stringify(res.body)).toBe(200);    const whole = await SELF.fetch(res.body.url);    expect(whole.status).toBe(200);    expect(whole.headers.get("content-type")).toBe("video/mp4");    expect(whole.headers.get("accept-ranges")).toBe("bytes");    const ranged = await SELF.fetch(res.body.url, { headers: { range: "bytes=4-7" } });    expect(ranged.status).toBe(206);    expect(ranged.headers.get("content-range")).toBe(`bytes 4-7/${BODY.length}`);    expect(await ranged.text()).toBe("isom");    const token = res.body.url.split("/v1/stream/")[1]!.split("/")[0]!;    const mov = `${DATABASE_ID}/films/f-whole/whole.mov`;    await put(SLUG, mov, device, BODY, "video/quicktime");    const sibling = await SELF.fetch(`https://example.test/b/${SLUG}/v1/stream/${token}/${mov}`);    expect(sibling.status, "the token reaches the film's folder").toBe(200);    expect(sibling.headers.get("content-type")).toBe("video/quicktime");  });});