import { env, runInDurableObject, SELF } from "cloudflare:test"; import { describe, expect, it, vi } from "vitest"; import type { Business } from "../src/business.ts"; import { ADMIN, answer, DATABASE_ID, http, mint, PERSONAL_TABLES, personalObject, FILMS_OPEN } from "./personal.ts"; // ROOM, not a hang: every test here makes a fresh personal object and writes media through it. Light // work, but on the box at load ~90 these took 30-62 s each run alone, and the full suite timed out // "a film erased takes its folder" at vitest's 5 s default (coordinator, 22 Nov 2026). vi.setConfig({ testTimeout: 120_000 }); const BYTES = (n: number, fill = 1): Uint8Array => new Uint8Array(n).fill(fill); async function media(slug: string, method: string, key: string, auth: string | null, body?: Uint8Array, query = ""): Promise { return SELF.fetch(`https://example.test/b/${slug}/v1/media/${key}${query}`, { method, headers: { ...(auth ? { authorization: `Bearer ${auth}` } : {}), ...(body ? { "content-type": "application/octet-stream", "content-length": String(body.length) } : {}) }, body, }); } async function putAll(slug: string, credential: string, files: Record): Promise { for (const [key, size] of Object.entries(files)) { const res = await media(slug, "PUT", key, credential, BYTES(size)); expect(res.status, await res.clone().text()).toBe(201); } } async function missing(slug: string, credential: string, keys: string[]): Promise { const res = await http<{ missing: string[] }>(slug, "POST", "/v1/media/missing", { keys }, { authorization: `Bearer ${credential}` }); expect(res.status, JSON.stringify(res.body)).toBe(200); return res.body.missing; } function usage(slug: string): Promise { const object = env.BUSINESS.get(env.BUSINESS.idFromName(slug)); return runInDurableObject(object, (instance: Business) => Number((instance as unknown as { store: { meta(key: string): string | null } }).store.meta("media_bytes") ?? "0")); } /** A film's HLS folder as the film import lays it, with its record's `file` the master. */ function filmFiles(id: string): Record { const folder = `${DATABASE_ID}/films/${id}/`; return { [`${folder}video/init.mp4`]: 30, [`${folder}video/seg-0.m4s`]: 400, [`${folder}poster.jpg`]: 50, [`${folder}master.m3u8`]: 20 }; } async function act(slug: string, credential: string, name: string, args: Record): Promise<{ made?: { id: string } }> { const res = await http<{ made?: { id: string } }>(slug, "POST", "/v1/act", { act: name, args }, { authorization: `Bearer ${credential}` }); expect(res.status, JSON.stringify(res.body)).toBe(200); return res.body; } /** RULE (owner, 4 Nov 2026): a film removed takes its media with it; nothing the owner bins stays in R2 for ever. */ describe("deleting the owner's media", () => { const SLUG = "media-delete"; let credential = ""; let owner = ""; it("deletes one key and takes its bytes off the object's media", async () => { ({ credential, owner } = await personalObject(SLUG, FILMS_OPEN)); const photo = `${DATABASE_ID}/photos/${"ab".repeat(32)}.jpg`; await putAll(SLUG, credential, { [photo]: 700 }); const before = await usage(SLUG); const res = await media(SLUG, "DELETE", photo, credential); expect(res.status, await res.clone().text()).toBe(200); expect(await res.json()).toEqual({ deleted: 1, bytes: 700 }); expect(await usage(SLUG)).toBe(before - 700); expect((await media(SLUG, "GET", photo, credential)).status).toBe(404); expect((await media(SLUG, "DELETE", photo, credential)).status, "nothing there is 404").toBe(404); // AVATAR SEAL 3 (3): a token neither deletes a person's sealed file nor overwrites one, nor asks whether one is held. const code = async (r: Response): Promise<[number, string]> => [r.status, ((await r.json()) as { code: string }).code]; await putAll(SLUG, credential, { [photo]: 700 }); expect(await code(await media(SLUG, "DELETE", photo, owner))).toEqual([403, "sealed_kind"]); expect(await code(await media(SLUG, "DELETE", `${DATABASE_ID}/photos/sub/`, owner, undefined, "?prefix=1"))).toEqual([403, "sealed_kind"]); expect(await code(await media(SLUG, "PUT", photo, owner, BYTES(700)))).toEqual([403, "sealed_kind"]); expect(await code(await media(SLUG, "POST", photo, owner, new TextEncoder().encode(JSON.stringify({ size: 700 })), "?uploads"))).toEqual([403, "sealed_kind"]); const asked = await http<{ code: string }>(SLUG, "POST", "/v1/media/missing", { keys: [photo] }, { authorization: `Bearer ${owner}` }); expect([asked.status, asked.body.code]).toEqual([403, "sealed_kind"]); expect(await missing(SLUG, credential, [photo]), "the refused acts left it").toEqual([]); // A file of no sealed kind is the token's as before. const doc = `${DATABASE_ID}/documents/${"cd".repeat(32)}.pdf`; expect((await media(SLUG, "PUT", doc, owner, BYTES(10))).status).toBe(201); expect((await media(SLUG, "DELETE", doc, owner)).status).toBe(200); }); it("deletes everything under a folder at least two deep, and nothing beside it", async () => { const one = filmFiles("film-one"); const two = filmFiles("film-two"); await putAll(SLUG, credential, { ...one, ...two }); const before = await usage(SLUG); const res = await media(SLUG, "DELETE", `${DATABASE_ID}/films/film-one/`, credential, undefined, "?prefix=1"); expect(res.status, await res.clone().text()).toBe(200); expect(await res.json()).toEqual({ deleted: 4, bytes: 500 }); expect(await usage(SLUG)).toBe(before - 500); expect((await missing(SLUG, credential, [...Object.keys(one), ...Object.keys(two)])).sort()).toEqual(Object.keys(one).sort()); expect((await media(SLUG, "DELETE", `${DATABASE_ID}/films/film-one/`, credential, undefined, "?prefix=1")).status, "an empty folder is 404").toBe(404); }); it("refuses a kind's whole folder, the database's, a folder without its slash, another database's and anyone but the owner", async () => { const two = `${DATABASE_ID}/films/film-two/`; const code = async (r: Response): Promise<[number, string]> => [r.status, ((await r.json()) as { code: string }).code]; expect(await code(await media(SLUG, "DELETE", `${DATABASE_ID}/films/`, credential, undefined, "?prefix=1"))).toEqual([400, "bad_key"]); expect(await code(await media(SLUG, "DELETE", `${DATABASE_ID}/`, credential, undefined, "?prefix=1")), "the database's own folder names no media").toEqual([404, "not_found"]); expect(await code(await media(SLUG, "DELETE", `${DATABASE_ID}/films/film-two`, credential, undefined, "?prefix=1"))).toEqual([400, "bad_key"]); expect(await code(await media(SLUG, "DELETE", two, credential))).toEqual([400, "bad_key"]); expect(await code(await media(SLUG, "DELETE", `00000000-0000-4000-8000-000000000000/films/film-two/`, credential, undefined, "?prefix=1"))).toEqual([404, "not_found"]); const reader = await mint(SLUG, credential, "reader", ["read"]); expect(await code(await media(SLUG, "DELETE", two, reader, undefined, "?prefix=1"))).toEqual([403, "owner_only"]); expect(await code(await media(SLUG, "DELETE", two, null, undefined, "?prefix=1"))).toEqual([403, "owner_only"]); expect(await missing(SLUG, credential, Object.keys(filmFiles("film-two"))), "the refused deletes left the folder").toEqual([]); }); }); /** RULE (owner, 4 Nov 2026): when a film is erased for good the object deletes its folder itself, so the owner never runs a script for it. */ describe("a film erased takes its folder", () => { it("goes with a film erased, stays while another live film plays from it, and stays on a plain delete (a phone's Bin)", async () => { const slug = "film-erase"; const { credential } = await personalObject(slug, FILMS_OPEN); const files = { ...filmFiles("erased"), ...filmFiles("shared") }; await putAll(slug, credential, files); const folder = (id: string): string => `${DATABASE_ID}/films/${id}/`; const make = async (file: string): Promise => (await act(slug, credential, "create", { table: "film", data: { title: "Synthetic", kind: "film", status: "want_to_watch", file, poster: `${file.replace(/master\.m3u8$/, "")}poster.jpg` } })).made!.id; const erased = await make(`${folder("erased")}master.m3u8`); const first = await make(`${folder("shared")}master.m3u8`); const second = await make(`${folder("shared")}master.m3u8`); const before = await usage(slug); // A phone puts a film in its Bin as a plain delete, and Undo there brings it back: nothing is dropped. await act(slug, credential, "delete", { table: "film", id: erased }); expect(await missing(slug, credential, Object.keys(filmFiles("erased"))), "a film in a phone's Bin keeps its folder").toEqual([]); expect(await usage(slug)).toBe(before); // The Bin emptied: the phone's erase ends a film for good, and its folder goes once no live film names it. await act(slug, credential, "delete", { table: "film", id: first, erase: "bin" }); expect(await missing(slug, credential, Object.keys(filmFiles("shared"))), "another film still plays from the folder").toEqual([]); await act(slug, credential, "delete", { table: "film", id: second, erase: "bin" }); expect((await missing(slug, credential, Object.keys(filmFiles("shared")))).sort()).toEqual(Object.keys(filmFiles("shared")).sort()); }); // RULE (CINEMAS DEV PROOF, 26 Nov 2026): the phone sends its Bin as a plain delete and its emptied Bin as an erase of // that same row: the erase finds the tombstone, which kept the film's keys, and the folder goes; Undo's create takes // the tombstone back with the folder whole. it("goes when the phone's emptied Bin erases a film its Bin already deleted, and Undo before that keeps it", async () => { const slug = "film-bin-then-erase"; const { credential } = await personalObject(slug, FILMS_OPEN); await putAll(slug, credential, filmFiles("binned")); const file = `${DATABASE_ID}/films/binned/master.m3u8`; const data = { title: "Proof Ferry", kind: "film", status: "want_to_watch", file }; const film = (await act(slug, credential, "create", { table: "film", data })).made!.id; await act(slug, credential, "delete", { table: "film", id: film }); // Undo on the phone: the row goes again whole, as a create over its tombstone. await act(slug, credential, "create", { table: "film", id: film, data }); expect(await missing(slug, credential, Object.keys(filmFiles("binned"))), "undone, the film keeps its folder").toEqual([]); await act(slug, credential, "delete", { table: "film", id: film }); expect(await missing(slug, credential, Object.keys(filmFiles("binned"))), "in the Bin again, still kept").toEqual([]); await act(slug, credential, "delete", { table: "film", id: film, erase: "bin" }); expect((await missing(slug, credential, Object.keys(filmFiles("binned")))).sort(), "the emptied Bin takes the folder").toEqual(Object.keys(filmFiles("binned")).sort()); await expect(act(slug, credential, "delete", { table: "film", id: film, erase: "bin" }), "erased once, the row is no longer there").rejects.toThrow(/no_such_record/); }); it("stays while an episode in another film table plays from it (a film moved under a series)", async () => { const slug = "film-moved"; const { credential } = await personalObject(slug, FILMS_OPEN); await putAll(slug, credential, filmFiles("moved")); const file = `${DATABASE_ID}/films/moved/master.m3u8`; const film = (await act(slug, credential, "create", { table: "film", data: { title: "Marshwatchers", kind: "film", status: "want_to_watch", file } })).made!.id; const series = (await act(slug, credential, "create", { table: "film", data: { title: "Lowmarsh", kind: "series", status: "watching" } })).made!.id; const season = (await act(slug, credential, "create", { table: "film_season", data: { film: series, number: 3, title: "Season 3" } })).made!.id; await act(slug, credential, "create", { table: "film_episode", data: { season, series, number: 1, title: "Marshwatchers", file } }); await act(slug, credential, "delete", { table: "film", id: film, erase: "bin" }); expect(await missing(slug, credential, Object.keys(filmFiles("moved"))), "the episode still plays from the folder").toEqual([]); }); it("AUDIT C 3: an assistant's key never deletes a file, one by one or by folder", async () => { const slug = "film-key-delete"; const { credential } = await personalObject(slug, FILMS_OPEN); // A file of no sealed kind (a film's are refused to every key already: AVATAR SEAL 4). const files = { [`${DATABASE_ID}/notes/kept/a.bin`]: 20, [`${DATABASE_ID}/notes/kept/b.bin`]: 20 }; await putAll(slug, credential, files); // A key with an allow list never reaches a device route; an assistant's OAuth connection made before allows (live, // KEY_DEFAULT today: "owner" scope, no list) does, and is refused here. The connection is planted on a full key. const listed = await mint(slug, credential, "a narrowed key", ["owner"], undefined, undefined, { read: ["note"], write: ["note"] }); const connector = await mint(slug, credential, "Claude", ["owner"]); await runInDurableObject(env.BUSINESS.get(env.BUSINESS.idFromName(slug)), (instance) => { (instance as unknown as { ctx: { storage: { sql: { exec(q: string, ...a: unknown[]): unknown } } } }).ctx.storage.sql.exec("UPDATE rows SET data = json_set(data, '$.connection_id', 'invented-connection') WHERE table_id = 'mcp_token' AND json_extract(data, '$.name') = 'Claude'"); }); for (const path of [`/v1/media/${encodeURIComponent(Object.keys(files)[0]!)}`, `/v1/media/${encodeURIComponent(`${DATABASE_ID}/notes/kept/`)}?prefix=1`]) { const byList = await http<{ code: string }>(slug, "DELETE", path, undefined, { authorization: `Bearer ${listed}` }); expect(byList.status, path).toBe(403); const byConnector = await http<{ code: string }>(slug, "DELETE", path, undefined, { authorization: `Bearer ${connector}` }); expect([byConnector.status, byConnector.body.code], path).toEqual([403, "owner_device_only"]); } expect(await missing(slug, credential, Object.keys(files))).toEqual([]); }); it("stays while a film waits in the bin, and goes when empty_bin erases it", async () => { const slug = "film-bin"; const { credential, owner } = await personalObject(slug, FILMS_OPEN); // A film table that keeps a bin, as a table with a `deleted_at` column does. const film = PERSONAL_TABLES.find((t) => t.id === "film")!; const binned = { ...film, seal: null, columns: [...(film.columns as Record[]), { key: "deleted_at", label: "Deleted", type: "datetime" }] }; const installed = await http(slug, "POST", "/v1/admin/definitions/tables", { tables: [binned] }, ADMIN); expect(installed.status, JSON.stringify(installed.body)).toBe(200); await putAll(slug, credential, filmFiles("in-bin")); const file = `${DATABASE_ID}/films/in-bin/master.m3u8`; // The stream is the object's to name (`file` is readonly to an assistant): the owner's own write lays it. const made = (await act(slug, owner, "create", { table: "film", data: { title: "Synthetic", file } })).made!; await answer(slug, owner, "delete_record", { table: "film", id: made.id }); expect(await missing(slug, credential, Object.keys(filmFiles("in-bin"))), "a film in the bin keeps its folder").toEqual([]); // An assistant erases only what has sat in the Bin 30 days (AUDIT C 3): this one is put back in time. expect(await answer(slug, owner, "empty_bin", { table: "film" })).toMatchObject({ erased: 0 }); await runInDurableObject(env.BUSINESS.get(env.BUSINESS.idFromName(slug)), (instance) => { (instance as unknown as { ctx: { storage: { sql: { exec(q: string, ...a: unknown[]): unknown } } } }).ctx.storage.sql.exec("UPDATE rows SET data = json_set(data, '$.deleted_at', '2026-01-01T00:00:00.000Z') WHERE table_id = 'film' AND id = ?", made.id); }); expect(await answer(slug, owner, "empty_bin", { table: "film" })).toMatchObject({ erased: 1, tables: { film: 1 } }); expect((await missing(slug, credential, Object.keys(filmFiles("in-bin")))).sort()).toEqual(Object.keys(filmFiles("in-bin")).sort()); }); });