194 lines · 12.1 KB · TypeScriptRaw
/** * Space for photos and files (assets/design/shared/SPACE.md, 23 Nov 2026): 2 GB free, 1 GB to both for each friend * counted after 14 days of use, 2 TB at most, a full space refusing new files only. Behind SPACE_RULES, off by * default (the test pool binds none): each test throws it for its own invented accounts by the admin's mode. */import { env, runInDurableObject, SELF } from "cloudflare:test";import { describe, expect, it } from "vitest";import type { Business } from "../src/business.ts";import { allowance, dayCounted, FREE_BYTES, FRIEND_BYTES, GB, MOST_BYTES, SPACE_FULL_WORDS } from "../src/space.ts";import { ADMIN, http } from "./personal.ts";const OPEN = "https://cottondb.com";const PNG = Uint8Array.from(atob("iVBORw0KGgoAAAANSUhEUgAAACAAAAAYCAIAAAAUMWhjAAAAJElEQVR4nGM4EaBBU8QwasGoBaMWjFowasGoBaMWjFowNCwAAOj5wC7/fbJHAAAAAElFTkSuQmCC"), (c) => c.charCodeAt(0));type Space = { mode: string; bytes: number; allowance: number; free: number; friends: number; counting: { days: number; of: number }; bought: number; floor: number };async function open<T = Record<string, unknown>>(method: string, path: string, body?: unknown, headers: Record<string, string> = {}): Promise<{ status: number; body: T }> { const res = await SELF.fetch(`${OPEN}${path}`, { method, headers: { "content-type": "application/json", ...headers }, body: body === undefined ? undefined : JSON.stringify(body) }); const text = await res.text(); return { status: res.status, body: (text ? JSON.parse(text) : null) as T };}let ips = 40;/** An invented number's whole sign-in on the open host: its own personal database. */async function signUp(phone: string): Promise<{ slug: string; auth: Record<string, string> }> { ips += 1; const ip = { "cf-connecting-ip": `198.51.100.${ips}` }; const code = await open<{ challenge_id: string; database_id: string }>("POST", "/v1/code", { phone, device_id: "phone-1" }, ip); expect(code.status, JSON.stringify(code.body)).toBe(200); const signed = await open<{ credential: string }>("POST", "/v1/sign-in", { database_id: code.body.database_id, challenge_id: code.body.challenge_id, code: "123456", device_id: "phone-1" }, ip); expect(signed.status, JSON.stringify(signed.body)).toBe(200); return { slug: `p-${code.body.database_id}`, auth: { authorization: `Bearer ${signed.body.credential}` } };}const object = (slug: string) => env.BUSINESS.get(env.BUSINESS.idFromName(slug));/** The object's meta, set in place (a test's stand-in for months of use). */function meta(slug: string, values: Record<string, string | null>): Promise<void> { return runInDurableObject(object(slug), (instance: Business) => { const store = (instance as unknown as { store: { setMeta(k: string, v: string | null): void } }).store; for (const [k, v] of Object.entries(values)) store.setMeta(k, v); });}const mode = (slug: string, m: string | null) => http<Space>(slug, "POST", "/v1/admin/space/mode", { mode: m }, ADMIN);const spaceOf = async (a: { auth: Record<string, string> }) => (await open<Space>("GET", "/v1/space", undefined, a.auth)).body;const putPng = (slug: string, auth: Record<string, string>, key: string) => SELF.fetch(`https://example.test/b/${slug}/v1/media/${slug.slice(2)}/${key}`, { method: "PUT", headers: { ...auth, "content-type": "image/png", "content-length": String(PNG.length) }, body: PNG });describe("the space rules' sums", () => { it("are 2 GB free, 1 GB a friend, never above 2 TB, never below what was held", () => { expect(GB).toBe(1024 ** 3); expect(allowance(0, 0, 0)).toBe(FREE_BYTES); expect(allowance(3, 0, 0)).toBe(FREE_BYTES + 3 * FRIEND_BYTES); expect(allowance(5000, 0, 0)).toBe(MOST_BYTES); expect(allowance(0, 10 * GB, 0)).toBe(10 * GB); expect(allowance(0, 0, 7 * GB)).toBe(7 * GB); expect(allowance(0, 0, 3 * MOST_BYTES)).toBe(3 * MOST_BYTES); }); it("count a day once, and stop at 14", () => { expect(dayCounted(null, 0, "2026-11-23")).toBe(1); expect(dayCounted("2026-11-23", 1, "2026-11-23")).toBeNull(); expect(dayCounted("2026-11-23", 1, "2026-11-24")).toBe(2); expect(dayCounted("2026-11-23", 14, "2026-11-24")).toBeNull(); });});describe("space for photos and files", { timeout: 90_000 }, () => { it("is today's with the switch off: the 50 GB cap, no day counted, nothing said on a pass", async () => { const a = await signUp("+15550170001"); const s = await spaceOf(a); expect(s).toMatchObject({ mode: "off", allowance: 50 * GB, friends: 0, counting: { days: 0, of: 14 } }); const pass = await open<{ space?: unknown }>("GET", "/v1/sync?since=0", undefined, a.auth); expect(pass.status).toBe(200); expect(pass.body.space).toBeUndefined(); expect((await spaceOf(a)).counting.days).toBe(0); expect((await open("POST", "/v1/space/invited-by", { number: "+15550170002" }, a.auth)).status).toBe(409); }); it("holds 2 GB on a new account; full, a file is refused in plain words while words still write and sync", async () => { const a = await signUp("+15550170011"); expect((await mode(a.slug, "on")).body).toMatchObject({ mode: "on", allowance: FREE_BYTES, floor: 0 }); expect((await putPng(a.slug, a.auth, "photos/one.png")).status).toBe(201); // Nearly full: what is held stands just short of 2 GB. await meta(a.slug, { media_bytes: String(FREE_BYTES - 10) }); const refused = await putPng(a.slug, a.auth, "photos/two.png"); expect(refused.status).toBe(413); expect(await refused.json()).toMatchObject({ code: "space_full", message: SPACE_FULL_WORDS }); // Writing is never refused for file space. const note = await http(a.slug, "POST", "/v1/admin/import", { rows: [{ table: "note", data: { title: "still written" } }] }, ADMIN); expect(note.status, JSON.stringify(note.body)).toBe(200); const pass = await open<{ space?: { bytes: number; allowance: number; used: number } }>("GET", "/v1/sync?since=0", undefined, a.auth); expect(pass.status).toBe(200); expect(pass.body.space).toMatchObject({ allowance: FREE_BYTES }); expect(pass.body.space!.used).toBeGreaterThanOrEqual(0.99); // The file already kept still reads. const kept = await SELF.fetch(`https://example.test/b/${a.slug}/v1/media/${a.slug.slice(2)}/photos/one.png`, { headers: a.auth }); expect(kept.status).toBe(200); }); it("takes nothing from an account that held more when the rules came on, and leaves room for what was bought", async () => { const a = await signUp("+15550170021"); await meta(a.slug, { media_bytes: String(7 * GB) }); expect((await mode(a.slug, "on")).body).toMatchObject({ allowance: 7 * GB, floor: 7 * GB, free: 0 }); expect((await putPng(a.slug, a.auth, "photos/after.png")).status).toBe(413); expect((await http<Space>(a.slug, "POST", "/v1/admin/space/bought", { bytes: 10 * GB }, ADMIN)).body).toMatchObject({ allowance: 10 * GB, bought: 10 * GB }); expect((await putPng(a.slug, a.auth, "photos/after.png")).status).toBe(201); expect((await http(a.slug, "POST", "/v1/admin/space/bought", { bytes: 3 * MOST_BYTES }, ADMIN)).status).toBe(400); }); it("adds 1 GB to both once the friend named who invited them has used an app on 14 separate days", async () => { const asha = await signUp("+15550170031"); const bimal = await signUp("+15550170032"); await mode(asha.slug, "on"); await mode(bimal.slug, "on"); // Bimal, the newer account, names Asha; never himself, never twice. expect((await open("POST", "/v1/space/invited-by", { number: "+15550170032" }, bimal.auth)).status).toBe(400); const named = await open("POST", "/v1/space/invited-by", { number: "+15550170031" }, bimal.auth); expect(named).toMatchObject({ status: 200, body: { ok: true } }); expect((await open("POST", "/v1/space/invited-by", { number: "+15550170031" }, bimal.auth)).status).toBe(409); expect((await spaceOf(asha)).friends).toBe(0); // Thirteen days are in; today's pass is the fourteenth. await meta(bimal.slug, { space_days: "13", space_day_last: "2026-01-01" }); await open("GET", "/v1/sync?since=0", undefined, bimal.auth); expect((await spaceOf(bimal)).counting.days).toBe(14); expect(await spaceOf(asha)).toMatchObject({ friends: 1, allowance: FREE_BYTES + FRIEND_BYTES }); expect(await spaceOf(bimal)).toMatchObject({ friends: 1, allowance: FREE_BYTES + FRIEND_BYTES }); // Another pass the same day changes nothing. await open("GET", "/v1/sync?since=0", undefined, bimal.auth); expect((await spaceOf(asha)).friends).toBe(1); }); it("answers the same whether the number named is on Cotton, newer, or nobody's, and takes it as the one naming (ROUTES-AUDIT 6)", async () => { const older = await signUp("+15550170061"); const one = await signUp("+15550170062"); const two = await signUp("+15550170063"); const three = await signUp("+15550170064"); const newer = await signUp("+15550170065"); for (const a of [older, one, two, three, newer]) await mode(a.slug, "on"); const answers = await Promise.all([ open("POST", "/v1/space/invited-by", { number: "+15550170061" }, one.auth), // on Cotton, older open("POST", "/v1/space/invited-by", { number: "+15550170065" }, two.auth), // on Cotton, newer open("POST", "/v1/space/invited-by", { number: "+15550179999" }, three.auth), // nobody's ]); for (const a of answers) expect(a).toEqual(answers[0]); expect(answers[0]).toMatchObject({ status: 200, body: { ok: true } }); // Each is its one naming: a second answers the same refusal for all three. const again = await Promise.all([one, two, three].map((a) => open<{ code: string }>("POST", "/v1/space/invited-by", { number: "+15550170061" }, a.auth))); expect(again.map((a) => [a.status, a.body.code])).toEqual([[409, "already_named"], [409, "already_named"], [409, "already_named"]]); }); it("counts a friend who had their 14 days before naming who invited them, at the naming", async () => { const asha = await signUp("+15550170041"); const chitra = await signUp("+15550170042"); await mode(asha.slug, "count"); await mode(chitra.slug, "count"); await meta(chitra.slug, { space_days: "13", space_day_last: "2026-01-01" }); await open("GET", "/v1/sync?since=0", undefined, chitra.auth); const named = await open("POST", "/v1/space/invited-by", { number: "+15550170041" }, chitra.auth); expect(named).toMatchObject({ status: 200, body: { ok: true } }); // Counted under `count`, though the cap is still today's. expect(await spaceOf(asha)).toMatchObject({ mode: "count", friends: 1, allowance: 50 * GB }); }); it("names as referrer whoever waited first for a number that joins through Comms", async () => { const asha = await signUp("+15550170051"); const dev = await signUp("+15550170052"); const newcomer = "+15550170053"; await runInDurableObject(env.DIRECTORY.get(env.DIRECTORY.idFromName("directory")), async (instance) => { const d = instance as unknown as { keyOf(p: string): Promise<string>; sql: SqlStorage }; const key = await d.keyOf(newcomer); d.sql.exec("INSERT INTO waiting (key, slug, ticket, at) VALUES (?, ?, 't-dev', ?)", key, dev.slug, Date.now() - 1000); d.sql.exec("INSERT INTO waiting (key, slug, ticket, at) VALUES (?, ?, 't-asha', ?)", key, asha.slug, Date.now() - 5000); }); const joiner = await signUp(newcomer); await runInDurableObject(env.DIRECTORY.get(env.DIRECTORY.idFromName("directory")), async (instance) => { const d = instance as unknown as { joined(slug: string, phone: string, counting: boolean): Promise<unknown>; sql: SqlStorage }; await d.joined(joiner.slug, newcomer, true); const row = d.sql.exec<{ referrer: string }>("SELECT referrer FROM referral WHERE friend = ?", joiner.slug).toArray()[0]; expect(row?.referrer).toBe(asha.slug); }); }); it("is set per account only by the admin, and read only by the owner", async () => { const a = await signUp("+15550170061"); expect((await http(a.slug, "POST", "/v1/admin/space/mode", { mode: "on" }, a.auth)).status).toBe(403); expect((await mode(a.slug, "sideways")).status).toBe(400); expect((await mode(a.slug, null)).body).toMatchObject({ mode: "off" }); expect((await open("GET", "/v1/space")).status).toBeGreaterThanOrEqual(400); });});