175 lines · 10.6 KB · TypeScriptRaw
/** * RULE (R6): a person's files are sealed on their device before they leave it, and the object * stores and serves those bytes exactly as they came. It draws none at a size, reads no book's package from one, and * labels every stream of one as a sealed file, never as the type its key's extension names. Every byte here is * invented: an f1 head and noise. */import { env, runInDurableObject, SELF } from "cloudflare:test";import { describe, expect, it, vi } from "vitest";import type { Business } from "../src/business.ts";import { PART_MIN_BYTES, SEALED_FILE_TYPE } from "../src/media.ts";import { DATABASE_ID, http, personalObject, BOOKS_OPEN } from "./personal.ts";/** Bytes as a device's seal makes them: the f1 magic, then what no one can read. */function sealedBytes(length: number, seed: number): Uint8Array { const out = new Uint8Array(length); let x = seed; for (let i = 0; i < length; i++) { x = (x * 1103515245 + 12345) >>> 0; out[i] = x >>> 24; } out.set(new TextEncoder().encode("CTF1"), 0); return out;}async function media(slug: string, method: string, key: string, auth: string, body?: Uint8Array, type = SEALED_FILE_TYPE, query = "", headers: Record<string, string> = {}): Promise<Response> { return SELF.fetch(`https://example.test/b/${slug}/v1/media/${key}${query}`, { method, headers: { authorization: `Bearer ${auth}`, ...(body ? { "content-type": type, "content-length": String(body.length) } : {}), ...headers }, body, });}const digest = async (bytes: Uint8Array) => [...new Uint8Array(await crypto.subtle.digest("SHA-256", bytes))].map((b) => b.toString(16).padStart(2, "0")).join("");const hex = (n: number) => n.toString(16).padStart(2, "0").repeat(32);describe("a file sealed on the person's device", () => { const SLUG = "media-sealed"; const KEYS = { picture: `${DATABASE_ID}/photos/${hex(1)}.jpg`, thumbnail: `${DATABASE_ID}/photos/${hex(1)}.t256.jpg`, book: `${DATABASE_ID}/books/${hex(2)}.epub`, song: `${DATABASE_ID}/music/${hex(3)}.mp3`, film: `${DATABASE_ID}/films/film-sealed/whole.mp4`, }; let device = ""; it("is stored under a picture's, a book's, a song's and a film's key, and comes back byte for byte", async () => { // The device's device lays and reads these: an assistant's token writes no sealed kind and reads none outside a window (AVATAR SEAL 4). ({ credential: device } = await personalObject(SLUG)); for (const [i, key] of Object.values(KEYS).entries()) { const bytes = sealedBytes(1000 + i * 77, i + 1); const put = await media(SLUG, "PUT", key, device, bytes); expect(put.status, `${key}: ${await put.clone().text()}`).toBe(201); const got = await media(SLUG, "GET", key, device); expect(got.status).toBe(200); expect(got.headers.get("content-type"), key).toBe(SEALED_FILE_TYPE); expect(new Uint8Array(await got.arrayBuffer()), key).toEqual(bytes); const stored = await env.MEDIA.get(`${SLUG}/${key.slice(DATABASE_ID.length + 1)}`); expect(new Uint8Array(await stored!.arrayBuffer()), `${key}: the bucket holds what came`).toEqual(bytes); } }); it("answers a range of it untouched, as a film's seek asks", async () => { const whole = new Uint8Array(await (await media(SLUG, "GET", KEYS.film, device)).arrayBuffer()); const res = await media(SLUG, "GET", KEYS.film, device, undefined, SEALED_FILE_TYPE, "", { range: "bytes=11-500" }); expect(res.status).toBe(206); expect(res.headers.get("content-range")).toBe(`bytes 11-500/${whole.length}`); expect(new Uint8Array(await res.arrayBuffer())).toEqual(whole.slice(11, 501)); }); // PLAYER START (26 Nov 2026): a range is read from R2 in one read, and says the same as the long way at every edge. it("answers every shape of range as it did, from one read", async () => { const whole = new Uint8Array(await (await media(SLUG, "GET", KEYS.film, device)).arrayBuffer()); const n = whole.length; const cases: [string, number, number | null, number, number][] = [ ["bytes=0-1048575", 206, 0, 0, n], [`bytes=${n - 10}-${n + 500}`, 206, n - 10, n - 10, n], ["bytes=100-", 206, 100, 100, n], ["bytes=-20", 206, n - 20, n - 20, n], [`bytes=${n}-`, 416, null, 0, 0], ["bytes=junk", 200, null, 0, n], ]; for (const [range, status, from, sliceFrom, sliceTo] of cases) { const res = await media(SLUG, "GET", KEYS.film, device, undefined, SEALED_FILE_TYPE, "", { range }); expect(res.status, range).toBe(status); const body = new Uint8Array(await res.arrayBuffer()); if (status === 416) { expect(res.headers.get("content-range"), range).toBe(`bytes */${n}`); continue; } expect(body, range).toEqual(whole.slice(sliceFrom, sliceTo)); expect(res.headers.get("content-length"), range).toBe(String(sliceTo - sliceFrom)); if (from !== null) expect(res.headers.get("content-range"), range).toBe(`bytes ${from}-${sliceTo - 1}/${n}`); expect(res.headers.get("content-type"), range).toBe(SEALED_FILE_TYPE); expect(res.headers.get("etag"), range).toBeTruthy(); } const missing = await media(SLUG, "GET", `${DATABASE_ID}/films/none/whole.mp4`, device, undefined, SEALED_FILE_TYPE, "", { range: "bytes=0-10" }); expect(missing.status).toBe(404); }); it("is never drawn at a size, even under a picture's or a thumbnail's key", async () => { for (const key of [KEYS.picture, KEYS.thumbnail]) { const res = await media(SLUG, "GET", key, device, undefined, SEALED_FILE_TYPE, "?width=256"); expect(res.status, key).toBe(400); expect(await res.json()).toMatchObject({ code: "sealed_file" }); } }); it("streams by a signed URL as it is stored, labelled sealed rather than as its extension's type", async () => { for (const key of [KEYS.book, KEYS.song, KEYS.film]) { const minted = await http<{ url: string }>(SLUG, "POST", "/v1/media/stream", { key }, { authorization: `Bearer ${device}` }); expect(minted.status, JSON.stringify(minted.body)).toBe(200); const res = await SELF.fetch(minted.body.url); expect(res.status).toBe(200); expect(res.headers.get("content-type"), key).toBe(SEALED_FILE_TYPE); const held = new Uint8Array(await (await media(SLUG, "GET", key, device)).arrayBuffer()); expect(new Uint8Array(await res.arrayBuffer()), key).toEqual(held); } }); it("goes up in parts above one request's limit and is put together byte for byte", async () => { const key = `${DATABASE_ID}/films/film-sealed-big/whole.mp4`; const bytes = sealedBytes(PART_MIN_BYTES + 4321, 9); const start = await media(SLUG, "POST", key, device, new TextEncoder().encode(JSON.stringify({ size: bytes.length, content_type: SEALED_FILE_TYPE })), "application/json", "?uploads"); expect(start.status, await start.clone().text()).toBe(201); const { upload } = (await start.json()) as { upload: string }; const parts: { part: number; etag: string }[] = []; for (const [i, part] of [bytes.slice(0, PART_MIN_BYTES), bytes.slice(PART_MIN_BYTES)].entries()) { const res = await media(SLUG, "PUT", key, device, part, "application/octet-stream", `?upload=${encodeURIComponent(upload)}&part=${i + 1}`); expect(res.status, await res.clone().text()).toBe(200); parts.push((await res.json()) as { part: number; etag: string }); } const done = await media(SLUG, "POST", key, device, new TextEncoder().encode(JSON.stringify({ parts })), "application/json", `?upload=${encodeURIComponent(upload)}`); expect(done.status, await done.clone().text()).toBe(201); const got = await media(SLUG, "GET", key, device); expect(got.headers.get("content-type")).toBe(SEALED_FILE_TYPE); expect(await digest(new Uint8Array(await got.arrayBuffer()))).toBe(await digest(bytes)); }, 120_000); it("is never read for a book's package: the book is marked sealed once and its columns stay the device's", async () => { const { credential } = await personalObject("media-sealed-book", BOOKS_OPEN); const key = `${DATABASE_ID}/books/${hex(4)}.epub`; const put = await media("media-sealed-book", "PUT", key, credential, sealedBytes(2048, 4)); expect(put.status, await put.clone().text()).toBe(201); const made = await http<{ made?: { id: string } }>("media-sealed-book", "POST", "/v1/act", { act: "create", args: { table: "book", data: { title: "A Sealed Book", file: key, status: "want_to_read" } } }, { authorization: `Bearer ${credential}` }); expect(made.status, JSON.stringify(made.body)).toBe(200); const stub = env.BUSINESS.get(env.BUSINESS.idFromName("media-sealed-book")); await vi.waitFor(async () => { const seen = await runInDurableObject(stub, (_i, state) => state.storage.sql.exec<{ outcome: string }>("SELECT outcome FROM book_file_seen").toArray()); expect(seen.map((s) => s.outcome)).toEqual(["sealed"]); }, { timeout: 10_000, interval: 100 }); const again = await runInDurableObject(stub, (instance: Business) => instance.bookFilePass(Date.now() + 2 * 60 * 60 * 1000)); expect(again, "read once for its file: never again").toMatchObject({ filled: 0, sealed: 0, unreadable: 0 }); });});/** RULE (owner, 18 Nov 2026): a landing started again asks once which files are stored sealed, and a clear copy still counts as to be sent. */describe("asking which files are stored sealed", () => { it("names what is absent or only in the clear, and says it answered that question", async () => { const SLUG = "media-sealed-missing"; // Asked by the owner's device (the Mac's seal-files, a phone's landing): an assistant's token is refused (AVATAR SEAL 3). const { credential, owner } = await personalObject(SLUG); const key = (name: string) => `${DATABASE_ID}/films/film-held/video/${name}.m4s`; expect((await media(SLUG, "PUT", key("sealed"), credential, sealedBytes(64, 1))).status).toBe(201); expect((await media(SLUG, "PUT", key("clear"), credential, sealedBytes(64, 2), "video/iso.segment")).status).toBe(201); const keys = [key("sealed"), key("clear"), key("absent")]; const asked = await http<{ missing: string[]; sealed?: boolean }>(SLUG, "POST", "/v1/media/missing", { keys, sealed: true }, { authorization: `Bearer ${credential}` }); expect(asked.body).toEqual({ missing: [key("clear"), key("absent")], sealed: true }); const plain = await http<{ missing: string[]; sealed?: boolean }>(SLUG, "POST", "/v1/media/missing", { keys }, { authorization: `Bearer ${credential}` }); expect(plain.body).toEqual({ missing: [key("absent")] }); const byToken = await http<{ code: string }>(SLUG, "POST", "/v1/media/missing", { keys, sealed: true }, { authorization: `Bearer ${owner}` }); expect([byToken.status, byToken.body.code]).toEqual([403, "sealed_kind"]); });});