/** * SHARED SPACE (src/space/): a space on nobody's own object, over synthetic people on the open host. The membership * matrix is test/shared-space-gate.test.ts; here, the flows: founding (keys from each member's own object), records * (each its adder's own, re-wrapped never re-contented), bytes counted to who added them in their own tally, media at * the door by signed single-use URL, members added by the owner, the epoch moved by the owner, leaving, ownership * passing on, Keep them, the owner deleting, a link that names nobody, an account's erase, a membership bound to its * database, and the sweeps. */ import { env, runDurableObjectAlarm, runInDurableObject, SELF } from "cloudflare:test"; import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; import type { Business } from "../src/business.ts"; import { LEAVE_MS } from "../src/space/space.ts"; import { fakes, open } from "./calling.ts"; import { accept, found, inSpace, kept, linkParts, opaque, person, record, upload, wrap, type Person, type SpaceView } from "./shared_space_people.ts"; vi.setConfig({ testTimeout: 180_000 }); beforeEach(() => { fakes(); }); afterEach(() => { vi.restoreAllMocks(); }); type Obj = { store: { meta(k: string): string | null; setMeta(k: string, v: string): void } }; function inPerson(p: Person, run: (sql: SqlStorage, instance: Obj) => T | Promise): Promise { return runInDurableObject(env.BUSINESS.get(env.BUSINESS.idFromName(p.slug)), (instance: Business, state) => run(state.storage.sql, instance as unknown as Obj)); } /** What a person's space tally says they added to shared spaces, and their own media count. */ async function counted(p: Person): Promise<{ shared: number; media: number }> { return inPerson(p, (sql, o) => ({ shared: sql.exec<{ n: number | null }>("SELECT SUM(bytes) AS n FROM space_bytes").one().n ?? 0, media: Number(o.store.meta("media_bytes") ?? "0") })); } async function circle(count: number): Promise { const people: Person[] = []; for (let i = 0; i < count; i++) people.push(await person()); for (let i = 0; i < count; i++) for (let j = i + 1; j < count; j++) await accept(people[i]!, people[j]!); return people; } async function alarm(space: string): Promise { await runDurableObjectAlarm(env.SPACES.get(env.SPACES.idFromName(space))); } const recordBytes = (r: Record): number => String(r.body).length + String(r.sig).length + 400; describe("a shared space", () => { it("is founded on its own object with each member's keys from their own object, and holds only wraps and sealed text", async () => { const [a, b, c] = await circle(3); const z = await person(); await accept(z, b!); const { space, id } = await found(a!, [b!, c!]); expect(space).toMatch(/^[A-Za-z0-9_-]{22}$/); for (const p of [a!, b!, c!]) expect((await p.ask<{ spaces: { space: string }[] }>("GET", "/v1/spaces")).body.spaces.map((s) => s.space)).toContain(space); const read = await b!.ask("GET", `/v1/spaces/${space}`); expect(read.status).toBe(200); expect(read.body.epoch).toBe(1); expect(read.body.unwrapped).toEqual([]); const byId = Object.fromEntries(read.body.members.map((m) => [m.member, m])); expect(byId[id[a!.number]!]).toMatchObject({ role: "owner", key: a!.key, sign: a!.sign, number: a!.number }); expect(byId[id[c!.number]!]).toMatchObject({ role: "add", key: c!.key, number: c!.number }); // A member's records: b adds an album; a reads it by cursor, its adder a member id, never a number. const album = record("alb-goa", "album", "alb-goa", [], 1); expect((await b!.ask("POST", `/v1/spaces/${space}/records`, { epoch: 1, records: [album] })).status).toBe(200); const list = await a!.ask<{ records: { id: string; adder: string; body: string }[]; next: number }>("GET", `/v1/spaces/${space}/records`); expect(list.body.records.map((r) => [r.id, r.adder, r.body])).toEqual([["alb-goa", id[b!.number], album.body]]); expect((await a!.ask<{ records: unknown[] }>("GET", `/v1/spaces/${space}/records?after=${list.body.next}`)).body.records).toEqual([]); expect(await kept(space)).toContain(String(album.body)); const personal = await inPerson(a!, (sql) => JSON.stringify(sql.exec("SELECT * FROM space_in").toArray())); expect(personal).not.toContain(String(album.body)); }); it("shows a member another's number only when that person is already theirs", async () => { const [a, b] = await circle(2); const c = await person(); await accept(a!, c); const { space, id } = await found(a!, [b!, c]); const seen = await b!.ask("GET", `/v1/spaces/${space}`); const cAsSeen = seen.body.members.find((m) => m.member === id[c.number])!; expect(cAsSeen.number).toBeUndefined(); expect(seen.body.members.find((m) => m.member === id[a!.number])!.number).toBe(a!.number); }); it("refuses founding with someone who is not the founder's person, or whose phone posted no key", async () => { const [a] = await circle(1); const z = await person(); expect((await a!.ask("POST", "/v1/spaces", { members: [z.number] })).status).toBe(403); expect((await z.ask<{ spaces: unknown[] }>("GET", "/v1/spaces")).body.spaces).toEqual([]); expect((await a!.ask<{ spaces: unknown[] }>("GET", "/v1/spaces")).body.spaces, "the founder's own object let go of it too").toEqual([]); }); it("counts each photo and record to whoever added it, in their own tally; serves bytes at the door; refunds on delete", async () => { const [a, b] = await circle(2); const { space } = await found(a!, [b!]); const { file, bytes } = await upload(b!, space, 5000); expect(await counted(b!)).toEqual({ shared: 5000, media: 0 }); expect((await counted(a!)).shared).toBe(0); const item = record("it-1", "item", "alb", [file], 1); expect((await b!.ask("POST", `/v1/spaces/${space}/records`, { epoch: 1, records: [item] })).status).toBe(200); expect((await counted(b!)).shared).toBe(5000 + recordBytes(item)); const urls = await a!.ask<{ urls: Record }>("POST", `/v1/spaces/${space}/media`, { files: [file, "x".repeat(22)] }); expect(Object.keys(urls.body.urls)).toEqual([file]); const url = urls.body.urls[file]!; expect(new Uint8Array(await (await SELF.fetch(url)).arrayBuffer())).toEqual(bytes); const part = await SELF.fetch(url, { headers: { range: "bytes=10-19" } }); expect(part.status).toBe(206); expect(new Uint8Array(await part.arrayBuffer())).toEqual(bytes.slice(10, 20)); const other = await upload(b!, space, 100); expect((await SELF.fetch(url.replace(file, other.file))).status).toBe(403); expect((await SELF.fetch(url, { method: "PUT", body: new Uint8Array(10), headers: { "content-length": "10" } })).status).toBe(403); // The owner deletes b's photo: the bytes go and b is refunded, file and record alike. expect((await a!.ask("POST", `/v1/spaces/${space}/records/delete`, { ids: ["it-1"] })).status).toBe(200); expect((await counted(b!)).shared).toBe(100); expect(await env.MEDIA.head(`spaces/${space}/${file}`)).toBeNull(); expect((await SELF.fetch(url)).status).toBe(404); }); it("a write URL is single-use: a second PUT, or one after its row is gone, writes nothing; bytes with no row are swept", async () => { const [a] = await circle(1); const { space } = await found(a!, []); const { file, url } = await upload(a!, space, 300); const again = await SELF.fetch(url, { method: "PUT", body: new Uint8Array(300), headers: { "content-length": "300" } }); expect(again.status).toBe(409); expect((await a!.ask("POST", `/v1/spaces/${space}/records`, { epoch: 1, records: [record("r", "item", "x", [file], 1)] })).status).toBe(200); expect((await a!.ask("POST", `/v1/spaces/${space}/records/delete`, { ids: ["r"] })).status).toBe(200); expect((await counted(a!)).shared).toBe(0); const reused = await SELF.fetch(url, { method: "PUT", body: new Uint8Array(300), headers: { "content-length": "300" } }); expect(reused.status, "upload, commit, delete, PUT again: refused").toBe(409); expect(await env.MEDIA.head(`spaces/${space}/${file}`)).toBeNull(); // Bytes under the prefix that no row names go at the sweep. await env.MEDIA.put(`spaces/${space}/${opaque(16)}`, new Uint8Array(10)); await inSpace(space, (_sql, instance) => instance.sweepOrphansNow()); expect((await env.MEDIA.list({ prefix: `spaces/${space}/` })).objects).toEqual([]); }); it("refuses an upload that would not fit the adder's space, and a PUT of another length", async () => { const [a, b] = await circle(2); const { space } = await found(a!, [b!]); await inPerson(b!, (_sql, o) => o.store.setMeta("media_cap", "1000")); const full = await b!.ask<{ code: string }>("POST", `/v1/spaces/${space}/upload`, { epoch: 1, size: 2000 }); expect(full.status).toBe(413); expect(full.body.code).toBe("space_full"); const granted = await a!.ask<{ url: string }>("POST", `/v1/spaces/${space}/upload`, { epoch: 1, size: 100 }); expect((await SELF.fetch(granted.body.url, { method: "PUT", body: new Uint8Array(99), headers: { "content-length": "99" } })).status).toBe(400); }); it("an upload never committed is swept after an hour and refunded", async () => { const [a] = await circle(1); const { space } = await found(a!, []); const { file } = await upload(a!, space, 700); expect((await counted(a!)).shared).toBe(700); await inSpace(space, (sql) => sql.exec("UPDATE file SET at = ?", Date.now() - 2 * 3_600_000)); await alarm(space); expect((await counted(a!)).shared).toBe(0); expect(await env.MEDIA.head(`spaces/${space}/${file}`)).toBeNull(); }); it("only the owner removes and moves the epoch; records are re-wrapped, never re-contented; no byte moves", async () => { const [a, b, c] = await circle(3); const { space, id } = await found(a!, [b!, c!]); const { file } = await upload(c!, space, 300); const item = record("it-c", "item", "alb", [file], 1); const mine = record("it-b", "item", "alb", [], 1); expect((await c!.ask("POST", `/v1/spaces/${space}/records`, { epoch: 1, records: [item] })).status).toBe(200); expect((await b!.ask("POST", `/v1/spaces/${space}/records`, { epoch: 1, records: [mine] })).status).toBe(200); // Nobody but its adder changes a record's content, the owner included. expect((await a!.ask("POST", `/v1/spaces/${space}/records`, { epoch: 1, records: [{ ...item, body: `r1:${opaque(90)}` }] })).status).toBe(403); expect((await b!.ask("POST", `/v1/spaces/${space}/epoch`, { epoch: 2, remove: [id[c!.number]], wraps: { [id[a!.number]!]: wrap(), [id[b!.number]!]: wrap() } })).status).toBe(403); expect((await a!.ask("POST", `/v1/spaces/${space}/epoch`, { epoch: 2, remove: [id[c!.number]], wraps: { [id[a!.number]!]: wrap() } })).status).toBe(400); const moved = await a!.ask<{ epoch: number; stale: number }>("POST", `/v1/spaces/${space}/epoch`, { epoch: 2, remove: [id[c!.number]], wraps: { [id[a!.number]!]: wrap(), [id[b!.number]!]: wrap() } }); expect(moved.status, JSON.stringify(moved.body)).toBe(200); expect(moved.body).toMatchObject({ epoch: 2, stale: 2 }); expect((await c!.ask("GET", `/v1/spaces/${space}`)).status).toBe(404); expect((await c!.ask<{ spaces: { space: string }[] }>("GET", "/v1/spaces")).body.spaces.map((s) => s.space)).not.toContain(space); // b re-wraps its own; b may not re-wrap c's; the owner does; the content stays as it was. expect((await b!.ask("POST", `/v1/spaces/${space}/records/rewrap`, { epoch: 2, records: [{ id: "it-b", key: `g1:2:${opaque(60)}` }] })).status).toBe(200); expect((await b!.ask("POST", `/v1/spaces/${space}/records/rewrap`, { epoch: 2, records: [{ id: "it-c", key: `g1:2:${opaque(60)}` }] })).status).toBe(403); expect((await a!.ask("POST", `/v1/spaces/${space}/records/rewrap`, { epoch: 2, records: [{ id: "it-c", key: `g1:1:${opaque(60)}` }] })).status).toBe(409); const rewrapped = await a!.ask<{ left: number }>("POST", `/v1/spaces/${space}/records/rewrap`, { epoch: 2, records: [{ id: "it-c", key: `g1:2:${opaque(60)}` }] }); expect(rewrapped.body.left).toBe(0); const list = await a!.ask<{ records: { id: string; body: string; sig: string; adder: string; epoch: number }[] }>("GET", `/v1/spaces/${space}/records`); const c1 = list.body.records.find((r) => r.id === "it-c")!; expect(c1).toMatchObject({ body: item.body, sig: item.sig, adder: id[c!.number], epoch: 2 }); const read = await a!.ask<{ wraps: Record; left: { member: string }[] }>("GET", `/v1/spaces/${space}`); expect(Object.keys(read.body.wraps)).toEqual(["2"]); expect(read.body.left.map((l) => l.member)).toEqual([id[c!.number]]); // Thirty days on, c's photos leave and c is refunded. expect((await counted(c!)).shared).toBe(300 + recordBytes(item)); await inSpace(space, (sql) => sql.exec("UPDATE member SET left_at = ? WHERE id = ?", Date.now() - LEAVE_MS - 1000, id[c!.number])); await alarm(space); expect((await counted(c!)).shared).toBe(0); expect(await env.MEDIA.head(`spaces/${space}/${file}`)).toBeNull(); }); it("only the owner adds members, each one of the owner's people, keys from their own object; the owner hands them the key", async () => { const [a, b, c] = await circle(3); const z = await person(); await accept(z, b!); const { space, id } = await found(a!, [b!]); expect((await b!.ask<{ code: string }>("POST", `/v1/spaces/${space}/members`, { numbers: [c!.number] })).body.code).toBe("owner_only"); expect((await a!.ask("POST", `/v1/spaces/${space}/members`, { numbers: [z.number] })).status).toBe(403); const added = await a!.ask("POST", `/v1/spaces/${space}/members`, { numbers: [c!.number] }); expect(added.status, JSON.stringify(added.body)).toBe(200); const cId = added.body.members.find((m) => m.number === c!.number)!.member; expect(added.body.members.find((m) => m.member === cId)!.key).toBe(c!.key); expect(added.body.unwrapped).toEqual([cId]); expect((await a!.ask("POST", `/v1/spaces/${space}/wraps`, { epoch: 1, wraps: { [cId]: wrap() } })).status).toBe(200); expect((await a!.ask("POST", `/v1/spaces/${space}/wraps`, { epoch: 1, wraps: { [id[b!.number]!]: wrap() } })).status, "b holds the key already").toBe(409); expect((await c!.ask("GET", `/v1/spaces/${space}`)).status).toBe(200); expect((await c!.ask<{ spaces: { space: string }[] }>("GET", "/v1/spaces")).body.spaces.map((s) => s.space)).toContain(space); }); it("binds a membership to its database: someone else holding the number later opens nothing", async () => { const [a, b] = await circle(2); const { space, id } = await found(a!, [b!]); expect((await b!.ask("GET", `/v1/spaces/${space}`)).status).toBe(200); // As if the number now belonged to another database: the member row's database is no longer this caller's. await inSpace(space, (sql) => sql.exec("UPDATE member SET database = ? WHERE id = ?", crypto.randomUUID(), id[b!.number])); expect((await b!.ask("GET", `/v1/spaces/${space}`)).status).toBe(404); }); it("survives its founder leaving: the longest member becomes owner, the epoch is due, nothing is added until it moves; the last one out ends it", async () => { const [a, b, c] = await circle(3); const { space, id } = await found(a!, [b!, c!]); const { file } = await upload(b!, space, 200); expect((await b!.ask("POST", `/v1/spaces/${space}/records`, { epoch: 1, records: [record("i", "item", "x", [file], 1)] })).status).toBe(200); expect((await a!.ask("POST", `/v1/spaces/${space}/leave`, {})).status).toBe(200); const read = await b!.ask<{ rekey_due: boolean; members: { member: string; role: string }[] }>("GET", `/v1/spaces/${space}`); expect(read.body.rekey_due).toBe(true); expect(read.body.members.find((m) => m.member === id[b!.number])?.role).toBe("owner"); expect((await a!.ask("GET", `/v1/spaces/${space}`)).status).toBe(404); expect((await c!.ask<{ code: string }>("POST", `/v1/spaces/${space}/upload`, { epoch: 1, size: 10 })).body.code).toBe("rekey_due"); expect((await c!.ask<{ code: string }>("POST", `/v1/spaces/${space}/epoch`, { epoch: 2, wraps: {} })).body.code).toBe("owner_only"); expect((await b!.ask("POST", `/v1/spaces/${space}/epoch`, { epoch: 2, wraps: { [id[b!.number]!]: wrap(), [id[c!.number]!]: wrap() } })).status).toBe(200); expect((await c!.ask("POST", `/v1/spaces/${space}/records`, { epoch: 2, records: [record("j", "item", "x", [], 2)] })).status).toBe(200); expect((await b!.ask("POST", `/v1/spaces/${space}/leave`, {})).status).toBe(200); expect((await c!.ask("POST", `/v1/spaces/${space}/leave`, {})).status).toBe(200); expect((await c!.ask("GET", `/v1/spaces/${space}`)).status).toBe(404); await inSpace(space, (sql) => sql.exec("UPDATE meta SET v = ? WHERE k = 'ending_at'", String(Date.now() - LEAVE_MS - 1000))); await alarm(space); expect(await env.MEDIA.head(`spaces/${space}/${file}`)).toBeNull(); expect(await inSpace(space, (sql) => sql.exec("SELECT name FROM sqlite_master WHERE type = 'table' AND name = 'meta'").toArray().length)).toBe(0); expect((await counted(b!)).shared, "every adder refunded at the erase").toBe(0); }); it("survives a member's account erase: told by their database, treated as leaving", async () => { const [a, b] = await circle(2); const { space, id } = await found(a!, [b!]); await runInDurableObject(env.BUSINESS.get(env.BUSINESS.idFromName(a!.slug)), (instance: Business) => (instance as unknown as { leaveSpaces(): Promise }).leaveSpaces()); const read = await b!.ask<{ members: { member: string; role: string }[]; left: { member: string }[]; rekey_due: boolean }>("GET", `/v1/spaces/${space}`); expect(read.status).toBe(200); expect(read.body.members.map((m) => [m.member, m.role])).toEqual([[id[b!.number], "owner"]]); expect(read.body.left.map((l) => l.member)).toEqual([id[a!.number]]); expect(read.body.rekey_due).toBe(true); expect((await a!.ask<{ spaces: unknown[] }>("GET", "/v1/spaces")).body.spaces).toEqual([]); }); it("a link opens one album to its holder with no member, number or name in it; it stops with its maker and when not wrapped again", async () => { const [a, b] = await circle(2); const { space, id } = await found(a!, [b!]); const one = await upload(b!, space, 64); const two = await upload(b!, space, 64); expect((await b!.ask("POST", `/v1/spaces/${space}/records`, { epoch: 1, records: [record("alb-1", "album", "alb-1", [], 1), record("p-1", "item", "alb-1", [one.file], 1), record("p-2", "item", "alb-2", [two.file], 1)] })).status).toBe(200); const link = await linkParts(); const make = (l: typeof link, who: Person) => who.ask("POST", `/v1/spaces/${space}/links`, { epoch: 1, link: l.id, album: "alb-1", public: l.public, auth_hash: l.hash, wrap: wrap(), days: 30 }); expect((await make(link, b!)).status, "only the owner makes a link").toBe(403); expect((await make(link, a!)).status).toBe(200); const auth = { authorization: `Bearer ${link.auth}` }; const read = await open<{ records: { id: string }[]; wraps: Record }>("POST", `/v1/space-link/${space}/${link.id}`, {}, auth); expect(read.status, JSON.stringify(read.body)).toBe(200); expect(read.body.records.map((r) => r.id).sort()).toEqual(["alb-1", "p-1"]); const text = JSON.stringify(read.body); for (const secret of [a!.number, b!.number, id[a!.number]!, id[b!.number]!, "adder", "sig"]) expect(text.includes(secret), `the link view carries ${secret}`).toBe(false); const media = await open<{ urls: Record }>("POST", `/v1/space-link/${space}/${link.id}/media`, { files: [one.file, two.file] }, auth); expect(Object.keys(media.body.urls)).toEqual([one.file]); expect((await open("POST", `/v1/space-link/${space}/${link.id}`, {}, { authorization: `Bearer ${opaque(32)}` })).status).toBe(404); // An epoch move that does not wrap the link again stops it. expect((await a!.ask("POST", `/v1/spaces/${space}/epoch`, { epoch: 2, wraps: { [id[a!.number]!]: wrap(), [id[b!.number]!]: wrap() } })).status).toBe(200); expect((await open("POST", `/v1/space-link/${space}/${link.id}`, {}, auth)).status).toBe(404); // A link stops with its maker. const third = await linkParts(); expect((await a!.ask("POST", `/v1/spaces/${space}/links`, { epoch: 2, link: third.id, album: "alb-1", public: third.public, auth_hash: third.hash, wrap: wrap(), days: 7 })).status).toBe(200); expect((await open("POST", `/v1/space-link/${space}/${third.id}`, {}, { authorization: `Bearer ${third.auth}` })).status).toBe(200); expect((await a!.ask("POST", `/v1/spaces/${space}/leave`, {})).status).toBe(200); expect((await open("POST", `/v1/space-link/${space}/${third.id}`, {}, { authorization: `Bearer ${third.auth}` })).status).toBe(404); }); it("Keep them: a departing member's photos move to whoever keeps them, the bytes counted to the keeper, nothing uploaded again", async () => { const [a, b, c] = await circle(3); const { space, id } = await found(a!, [b!, c!]); const { file } = await upload(c!, space, 900); const item = record("c-1", "item", "x", [file], 1); expect((await c!.ask("POST", `/v1/spaces/${space}/records`, { epoch: 1, records: [item] })).status).toBe(200); expect((await c!.ask("POST", `/v1/spaces/${space}/leave`, {})).status).toBe(200); expect((await b!.ask("POST", `/v1/spaces/${space}/keep`, { member: id[a!.number] })).status, "a has not left").toBe(404); const kept = await b!.ask<{ records: number; bytes: number }>("POST", `/v1/spaces/${space}/keep`, { member: id[c!.number] }); expect(kept.body).toMatchObject({ records: 1, bytes: 900 + recordBytes(item) }); expect((await counted(b!)).shared).toBe(900 + recordBytes(item)); expect((await counted(c!)).shared).toBe(0); await inSpace(space, (sql) => sql.exec("UPDATE member SET left_at = ? WHERE id = ?", Date.now() - LEAVE_MS - 1000, id[c!.number])); await alarm(space); const list = await a!.ask<{ records: { id: string; adder: string; signer: string; signer_key: string }[] }>("GET", `/v1/spaces/${space}/records`); // The keeper holds it now; who signed it, and the key they signed with, stay, so phones still verify it. expect(list.body.records).toEqual([expect.objectContaining({ id: "c-1", adder: id[b!.number], signer: id[c!.number], signer_key: c!.sign })]); expect(await env.MEDIA.head(`spaces/${space}/${file}`)).not.toBeNull(); }); it("the owner deletes it: members still read and save for thirty days, nothing changes, then it is erased and every adder refunded", async () => { const [a, b] = await circle(2); const { space, id } = await found(a!, [b!]); const { file } = await upload(b!, space, 400); expect((await b!.ask("POST", `/v1/spaces/${space}/records`, { epoch: 1, records: [record("b-1", "item", "x", [file], 1)] })).status).toBe(200); expect((await b!.ask("POST", `/v1/spaces/${space}/delete`, {})).status, "only the owner deletes").toBe(403); expect((await a!.ask("POST", `/v1/spaces/${space}/delete`, {})).status).toBe(200); expect((await b!.ask<{ deleted: { by: string } | null }>("GET", `/v1/spaces/${space}`)).body.deleted?.by).toBe(id[a!.number]); expect(Object.keys((await b!.ask<{ urls: Record }>("POST", `/v1/spaces/${space}/media`, { files: [file] })).body.urls)).toEqual([file]); expect((await b!.ask<{ code: string }>("POST", `/v1/spaces/${space}/records`, { epoch: 1, records: [record("b-2", "item", "x", [], 1)] })).body.code).toBe("space_deleted"); expect((await counted(b!)).shared).toBeGreaterThan(400); await inSpace(space, (sql) => sql.exec("UPDATE meta SET v = ? WHERE k = 'deleted_at'", String(Date.now() - LEAVE_MS - 1000))); await alarm(space); expect((await counted(b!)).shared).toBe(0); expect(await env.MEDIA.head(`spaces/${space}/${file}`)).toBeNull(); expect((await b!.ask("GET", `/v1/spaces/${space}`)).status).toBe(404); expect((await b!.ask<{ spaces: unknown[] }>("GET", "/v1/spaces")).body.spaces).toEqual([]); }); it("a refund the person's object does not take is kept and tried again until it does", async () => { const [a, b] = await circle(2); const { space } = await found(a!, [b!]); const { file } = await upload(b!, space, 500); await inSpace(space, (sql) => sql.exec("UPDATE member SET slug = ? WHERE number = ?", "p-no-such-object", b!.number)); // The file goes uncommitted at the hour: the refund cannot land at the wrong slug, and waits in the outbox. await inSpace(space, (sql) => sql.exec("UPDATE file SET at = ? WHERE id = ?", Date.now() - 2 * 3_600_000, file)); await alarm(space); expect(await inSpace(space, (sql) => sql.exec<{ n: number }>("SELECT COUNT(*) AS n FROM outbox WHERE kind = 'refund'").one().n)).toBe(1); await inSpace(space, (sql) => { sql.exec("UPDATE outbox SET slug = ?, next_at = 0", b!.slug); }); await alarm(space); expect(await inSpace(space, (sql) => sql.exec<{ n: number }>("SELECT COUNT(*) AS n FROM outbox").one().n)).toBe(0); expect((await counted(b!)).shared).toBe(0); }); it("two members putting one new id at once: one lands, the other is refused and refunded; nothing is kept under the wrong adder", async () => { const [a, b] = await circle(2); const { space, id } = await found(a!, [b!]); const fa = await upload(a!, space, 1000); const fb = await upload(b!, space, 2000); const ra = record("same", "item", "x", [fa.file], 1); const rb = record("same", "item", "x", [fb.file], 1); const [pa, pb] = await Promise.all([a!.ask("POST", `/v1/spaces/${space}/records`, { epoch: 1, records: [ra] }), b!.ask("POST", `/v1/spaces/${space}/records`, { epoch: 1, records: [rb] })]); expect([pa.status, pb.status].filter((x) => x === 200)).toHaveLength(1); expect([403, 409]).toContain(pa.status === 200 ? pb.status : pa.status); const [winner, loser, winRecord, loseFile] = pa.status === 200 ? [a!, b!, ra, fb] : [b!, a!, rb, fa]; const list = await a!.ask<{ records: { id: string; adder: string; body: string; files: string[] }[] }>("GET", `/v1/spaces/${space}/records`); expect(list.body.records).toEqual([expect.objectContaining({ id: "same", adder: id[winner.number], body: winRecord.body })]); // The loser's own file is still theirs to use or lose (swept at the hour); only its bytes are counted to them. expect((await counted(loser)).shared).toBe(loseFile.bytes.length); expect((await counted(winner)).shared).toBe((winner === a ? 1000 : 2000) + recordBytes(winRecord)); }); it("refuses to take in a member whose phone posted no signing key", async () => { const [a] = await circle(1); const c = await person(); await accept(a!, c); await inPerson(c, (sql) => sql.exec("DELETE FROM send_sign_key")); expect((await a!.ask<{ code: string }>("POST", "/v1/spaces", { members: [c.number] })).body.code).toBe("share_key_not_yet"); }); it("a telling-out that arrives late, after the person was added again, does not take the space off their list", async () => { const [a, c] = await circle(2); const { space, id } = await found(a!, [c!]); const first = await inSpace(space, (sql) => sql.exec<{ serial: number }>("SELECT serial FROM member WHERE id = ?", id[c!.number]).one().serial); expect((await a!.ask("POST", `/v1/spaces/${space}/epoch`, { epoch: 2, remove: [id[c!.number]], wraps: { [id[a!.number]!]: wrap() } })).status).toBe(200); expect((await a!.ask("POST", `/v1/spaces/${space}/members`, { numbers: [c!.number] })).status).toBe(200); expect((await c!.ask<{ spaces: { space: string }[] }>("GET", "/v1/spaces")).body.spaces.map((x) => x.space)).toContain(space); // The first membership's telling-out, late: let go. await runInDurableObject(env.BUSINESS.get(env.BUSINESS.idFromName(c!.slug)), (instance: Business) => (instance as unknown as { spaceLeft(s: string, serial: number): Promise }).spaceLeft(space, first)); expect((await c!.ask<{ spaces: { space: string }[] }>("GET", "/v1/spaces")).body.spaces.map((x) => x.space)).toContain(space); }); it("a read of an id nobody founded writes nothing", async () => { const [a] = await circle(1); const id = opaque(16); expect((await a!.ask("GET", `/v1/spaces/${id}`)).status).toBe(404); expect(await inSpace(id, (sql) => sql.exec("SELECT name FROM sqlite_master WHERE type = 'table'").toArray().length)).toBe(0); expect((await open("GET", `/v1/spaces/${id}`)).status, "no bearer: sign in").toBe(401); }); });