Cotton code
249 lines · 17.5 KB · TypeScriptRaw
/** * Secrets between people (src/send/secrets.ts; assets/design/keys/CONTRACT.md "The Worker", row 14), over * synthetic people's objects on the open host. The boxes are opaque made-up text: the objects never open them. * A share goes only between people who accepted each other; to anyone else it is answered the same and never * held. A value open is counted on the giver's list; a take back, a drop and the end of `until` leave nothing. */import { env, runInDurableObject } from "cloudflare:test";import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";import { SCHEMA as HANDOVER_SCHEMA } from "../src/handover.ts";import { NOTE_BOX_MAX, NOTES_MAX, VALUE_MAX } from "../src/send/secrets.ts";import { bearer, fakes, open } from "./calling.ts";import { chatPhone, type ChatPhone } from "./chat.ts";vi.setConfig({ testTimeout: 300_000 });let n = 0;const number = (): string => `+91900008${String(1000 + ++n).padStart(4, "0")}`;const id = (s: string): string => `${s}${"0".repeat(Math.max(0, 32 - s.length))}`.slice(0, 32);const box = (s: string): string => `p1:${btoa(s).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "")}`;const week = () => Date.now() + 7 * 86_400_000;beforeEach(() => {  fakes();});afterEach(() => {  vi.restoreAllMocks();});type Out = { share: string; to: string; delivered_at: number; opens: number; last_open: number | null; until: number | null; state: string };type In = { share: string; from: string; card: string; until: number | null; may_copy: boolean };const call = <T = Record<string, unknown>>(p: ChatPhone, method: string, path: string, body?: unknown) => open<T>(method, path, body, bearer(p.credential));const outOf = async (p: ChatPhone) => (await call<{ shares: Out[] }>(p, "GET", "/v1/secret/share/out")).body.shares;const inOf = async (p: ChatPhone) => (await call<{ shares: In[] }>(p, "GET", "/v1/secret/share/in")).body.shares;const objectOf = async (p: ChatPhone) => env.BUSINESS.get(env.BUSINESS.idFromName((await env.DIRECTORY.get(env.DIRECTORY.idFromName("directory")).lookup(p.number))!));async function connected(): Promise<{ giver: ChatPhone; holder: ChatPhone }> {  const giver = await chatPhone(number(), `dev-${n}`);  const holder = await chatPhone(number(), `dev-${n}`);  await giver.say("accept", holder.number);  await holder.say("accept", giver.number);  return { giver, holder };}function give(from: ChatPhone, to: ChatPhone | string, share: string, extra: Record<string, unknown> = {}) {  return call(from, "POST", "/v1/secret/share", { to: typeof to === "string" ? to : to.number, share, card: box(`card ${share}`), value: box(`value ${share} v1`), version: 1, until: week(), may_copy: true, ...extra });}describe("secrets between people", () => {  it("keeps the giver's own sealed notes, each key once, within its limits", async () => {    const { giver, holder } = await connected();    expect((await call(giver, "PUT", "/v1/secret/note", { key: "share:abc", box: box("who holds it") })).body).toEqual({ ok: true });    expect((await call(giver, "PUT", "/v1/secret/note", { key: "pin:Ab-12", box: box("a pinned key") })).status).toBe(200);    expect((await call(giver, "PUT", "/v1/secret/note", { key: "share:abc", box: box("who holds it now") })).status).toBe(200);    expect((await call<{ notes: { key: string; box: string }[] }>(giver, "GET", "/v1/secret/note")).body.notes).toEqual([      { key: "pin:Ab-12", box: box("a pinned key") },      { key: "share:abc", box: box("who holds it now") },    ]);    // Each person's notes are their own.    expect((await call<{ notes: unknown[] }>(holder, "GET", "/v1/secret/note")).body.notes).toEqual([]);    expect((await call(giver, "PUT", "/v1/secret/note", { key: "x".repeat(81), box: box("long key") })).status).toBe(400);    expect((await call(giver, "PUT", "/v1/secret/note", { key: "share:open", box: "not sealed" })).status).toBe(400);    expect((await call(giver, "PUT", "/v1/secret/note", { key: "share:big", box: `p1:${"A".repeat(NOTE_BOX_MAX)}` })).status).toBe(413);    await runInDurableObject(await objectOf(giver), (_i, state) => {      for (let i = 0; i < NOTES_MAX - 2; i++) state.storage.sql.exec("INSERT INTO secret_note (key, box, at) VALUES (?, 'p1:x', 0)", `share:filler-${i}`);    });    expect((await call(giver, "PUT", "/v1/secret/note", { key: "share:one-more", box: box("over") })).status).toBe(413);    expect((await call(giver, "PUT", "/v1/secret/note", { key: "share:abc", box: box("replacing is fine") })).status).toBe(200);    // A signed-out caller, and no device at all, are refused.    expect((await open("GET", "/v1/secret/note")).status).toBe(401);  });  it("gives a share to one of this person's people: the card, one counted open, a newer value, then taken back from both", async () => {    const { giver, holder } = await connected();    const share = id("share-garden-wifi");    const until = week();    expect((await give(giver, holder, share, { until })).body).toEqual({ ok: true });    await vi.waitFor(async () => expect(await inOf(holder)).toHaveLength(1), { timeout: 5000, interval: 50 });    expect(await inOf(holder)).toEqual([{ share, from: giver.number, card: box(`card ${share}`), until, may_copy: true }]);    const given = await outOf(giver);    expect(given).toMatchObject([{ share, to: holder.number, opens: 0, last_open: null, until, state: "live" }]);    expect(given[0]!.delivered_at).toBeGreaterThan(Date.now() - 60_000);    // The same id twice is the phone's error.    expect((await give(giver, holder, share)).status).toBe(409);    // Reveal: the value box, and one open on the giver's list.    expect((await call(holder, "POST", "/v1/secret/share/value", { share })).body).toEqual({ value: box(`value ${share} v1`), version: 1 });    await vi.waitFor(async () => expect((await outOf(giver))[0]!.opens).toBe(1), { timeout: 5000, interval: 50 });    expect((await outOf(giver))[0]!.last_open).toBeGreaterThan(Date.now() - 60_000);    await call(holder, "POST", "/v1/secret/share/value", { share });    await vi.waitFor(async () => expect((await outOf(giver))[0]!.opens).toBe(2), { timeout: 5000, interval: 50 });    // The giver changes the value: the holder's next open is the newer one; an older version never overwrites it.    expect((await call(giver, "POST", "/v1/secret/share/update", { share, value: box("value v2"), version: 2 })).body).toEqual({ ok: true });    await vi.waitFor(async () => expect((await call(holder, "POST", "/v1/secret/share/value", { share })).body).toEqual({ value: box("value v2"), version: 2 }), { timeout: 5000, interval: 50 });    await call(giver, "POST", "/v1/secret/share/update", { share, value: box("value v1 again"), version: 1 });    await new Promise((r) => setTimeout(r, 300));    expect((await call<{ version: number }>(holder, "POST", "/v1/secret/share/value", { share })).body.version).toBe(2);    // Taken back: gone from the holder before the call is answered, and the giver's list says so.    expect((await call(giver, "POST", "/v1/secret/share/take", { share })).body).toEqual({ ok: true });    expect(await inOf(holder)).toEqual([]);    expect((await call(holder, "POST", "/v1/secret/share/value", { share })).body).toMatchObject({ code: "share_gone" });    expect((await outOf(giver))[0]!.state).toBe("taken");    expect((await call(giver, "POST", "/v1/secret/share/update", { share, value: box("too late"), version: 3 })).status).toBe(404);    // Nothing of a box is left on the holder's object.    await runInDurableObject(await objectOf(holder), (_i, state) => expect(state.storage.sql.exec("SELECT count(*) AS n FROM secret_held").one().n).toBe(0));  });  it("AUDIT D: a delivery that waited (the holder was frozen) is never handed over once the share was taken back", async () => {    const { giver, holder } = await connected();    const share = id("waited");    expect((await give(giver, holder, share)).status).toBe(200);    expect((await call(giver, "POST", "/v1/secret/share/take", { share })).body).toEqual({ ok: true });    expect(await inOf(holder)).toEqual([]);    // The delivery as the queue would hold it, had the holder's account been frozen when it was given; then due now.    const delivery = { from: giver.number, share, card: box(`card ${share}`), value: box(`value ${share} v1`), version: 1, until: week(), may_copy: true };    await runInDurableObject(await objectOf(giver), async (instance, state) => {      state.storage.sql.exec(HANDOVER_SCHEMA);      state.storage.sql.exec("INSERT INTO handover_retry (kind, to_number, delivery, tries, next_at, first_at) VALUES ('secret', ?, ?, 1, 0, ?)", holder.number, JSON.stringify(delivery), Date.now());      await (instance as unknown as { retryHandovers(): Promise<void> }).retryHandovers();    });    expect(await inOf(holder)).toEqual([]);    await runInDurableObject(await objectOf(holder), (_i, state) => expect(state.storage.sql.exec("SELECT count(*) AS n FROM secret_held").one().n).toBe(0));  });  it("AUDIT D: a take-back the holder's object could not take yet (frozen) is told again on the alarm, and lands", async () => {    const { giver, holder } = await connected();    const share = id("retake");    expect((await give(giver, holder, share)).status).toBe(200);    await vi.waitFor(async () => expect(await inOf(holder)).toHaveLength(1), { timeout: 5000, interval: 50 });    // The take as it stands after the holder's object answered "frozen, try again": taken here, kept in the queue.    await runInDurableObject(await objectOf(giver), async (instance, state) => {      state.storage.sql.exec("UPDATE secret_out SET state = 'taken' WHERE share = ?", share);      state.storage.sql.exec(HANDOVER_SCHEMA);      state.storage.sql.exec("INSERT INTO handover_retry (kind, to_number, delivery, tries, next_at, first_at) VALUES ('secret_take', ?, ?, 1, 0, ?)", holder.number, JSON.stringify({ from: giver.number, share }), Date.now());      await (instance as unknown as { retryHandovers(): Promise<void> }).retryHandovers();      expect(state.storage.sql.exec("SELECT count(*) AS n FROM handover_retry").one().n).toBe(0);    });    expect(await inOf(holder)).toEqual([]);    expect((await call(holder, "POST", "/v1/secret/share/value", { share })).body).toMatchObject({ code: "share_gone" });  });  it("answers a share to a stranger, a blocked person or nobody the same, and holds none of them", async () => {    const { giver, holder } = await connected();    const stranger = await chatPhone(number(), `dev-${n}`);    // The stranger accepted the giver; the giver never accepted them.    await stranger.say("accept", giver.number);    expect((await give(giver, stranger, id("share-stranger"))).body).toEqual({ ok: true });    expect((await give(giver, "+919000089999", id("share-nobody"))).body).toEqual({ ok: true });    expect((await give(stranger, giver, id("share-from-stranger"))).body).toEqual({ ok: true });    await holder.say("block", giver.number);    expect((await give(giver, holder, id("share-blocked"))).body).toEqual({ ok: true });    await new Promise((r) => setTimeout(r, 500));    expect(await inOf(stranger)).toEqual([]);    expect(await inOf(holder)).toEqual([]);    expect(await inOf(giver)).toEqual([]);    // The giver's own list shows each as given: it never says who could not be reached.    expect((await outOf(giver)).map((o) => [o.share, o.state])).toEqual([      [id("share-stranger"), "live"],      [id("share-nobody"), "live"],      [id("share-blocked"), "live"],    ]);    // Malformed is the phone's error, said by name.    expect((await give(giver, holder, "short")).status).toBe(400);    expect((await give(giver, holder, id("share-plain"), { value: "plain words" })).status).toBe(400);    expect((await give(giver, holder, id("share-big"), { value: `p1:${"A".repeat(VALUE_MAX)}` })).status).toBe(413);    expect((await give(giver, holder, id("share-past"), { until: Date.now() - 1000 })).status).toBe(400);    expect((await give(giver, giver, id("share-self"))).status).toBe(400);  });  it("lets a share end at its until on both objects, and the holder drop one", async () => {    const { giver, holder } = await connected();    const ending = id("share-ending");    const dropped = id("share-dropped");    await give(giver, holder, ending);    await give(giver, holder, dropped, { until: null, may_copy: false });    await vi.waitFor(async () => expect(await inOf(holder)).toHaveLength(2), { timeout: 5000, interval: 50 });    expect((await inOf(holder)).find((s) => s.share === dropped)).toMatchObject({ until: null, may_copy: false });    // The week passes.    for (const p of [giver, holder]) {      await runInDurableObject(await objectOf(p), (_i, state) => {        state.storage.sql.exec("UPDATE secret_held SET until = ? WHERE share = ?", Date.now() - 1000, ending);        state.storage.sql.exec("UPDATE secret_out SET until = ? WHERE share = ?", Date.now() - 1000, ending);      });    }    expect((await call(holder, "POST", "/v1/secret/share/value", { share: ending })).body).toMatchObject({ code: "share_gone" });    expect((await inOf(holder)).map((s) => s.share)).toEqual([dropped]);    expect((await outOf(giver)).find((o) => o.share === ending)!.state).toBe("expired");    // The holder lets one go.    expect((await call(holder, "POST", "/v1/secret/share/drop", { share: dropped })).body).toEqual({ ok: true });    expect(await inOf(holder)).toEqual([]);    expect((await call(holder, "POST", "/v1/secret/share/value", { share: dropped })).status).toBe(404);  });  it("carries an ask to one of this person's people, who answers it", async () => {    const { giver, holder } = await connected();    const ask = id("ask-wifi-please");    expect((await call(holder, "POST", "/v1/secret/ask", { to: giver.number, ask, box: box("the wifi, please") })).body).toEqual({ ok: true });    type Ask = { ask: string; from: string; box: string; state: string; at: number };    await vi.waitFor(async () => expect((await call<{ asks: Ask[] }>(giver, "GET", "/v1/secret/ask/in")).body.asks).toHaveLength(1), { timeout: 5000, interval: 50 });    expect((await call<{ asks: Ask[] }>(giver, "GET", "/v1/secret/ask/in")).body.asks).toMatchObject([{ ask, from: holder.number, box: box("the wifi, please"), state: "waiting" }]);    expect((await call(giver, "POST", "/v1/secret/ask/answer", { ask, state: "no" })).body).toEqual({ ok: true });    expect((await call<{ asks: Ask[] }>(giver, "GET", "/v1/secret/ask/in")).body.asks[0]!.state).toBe("no");    expect((await call(giver, "POST", "/v1/secret/ask/answer", { ask, state: "maybe" })).status).toBe(400);    expect((await call(giver, "POST", "/v1/secret/ask/answer", { ask: id("ask-unknown"), state: "no" })).status).toBe(404);  });  // ASK ON PERSON (the Android Secrets walk, 26 Nov 2026: Withdraw was refused, the route was never served).  it("lists the asks this person sent, takes a waiting one back on both objects, and hears an answer", async () => {    const { giver, holder } = await connected();    type Ask = { ask: string; state: string };    const outOfAsks = async (p: ChatPhone) => (await call<{ asks: (Ask & { to: string })[] }>(p, "GET", "/v1/secret/ask/out")).body.asks;    const inOfAsks = async (p: ChatPhone) => (await call<{ asks: Ask[] }>(p, "GET", "/v1/secret/ask/in")).body.asks;    const first = id("ask-door-code");    const second = id("ask-wifi-again");    await call(holder, "POST", "/v1/secret/ask", { to: giver.number, ask: first, box: box("the door code") });    await call(holder, "POST", "/v1/secret/ask", { to: giver.number, ask: second, box: box("the wifi") });    expect(await outOfAsks(holder)).toMatchObject([{ ask: first, to: giver.number, state: "waiting" }, { ask: second, to: giver.number, state: "waiting" }]);    await vi.waitFor(async () => expect(await inOfAsks(giver)).toHaveLength(2), { timeout: 5000, interval: 50 });    expect((await call(holder, "POST", "/v1/secret/ask/withdraw", { ask: first })).body).toEqual({ ok: true });    expect((await outOfAsks(holder)).find((a) => a.ask === first)!.state).toBe("withdrawn");    await vi.waitFor(async () => expect((await inOfAsks(giver)).find((a) => a.ask === first)!.state).toBe("withdrawn"), { timeout: 5000, interval: 50 });    expect((await call(giver, "POST", "/v1/secret/ask/answer", { ask: first, state: "no" })).status).toBe(404);    expect((await call(giver, "POST", "/v1/secret/ask/answer", { ask: second, state: "no" })).body).toEqual({ ok: true });    await vi.waitFor(async () => expect((await outOfAsks(holder)).find((a) => a.ask === second)!.state).toBe("no"), { timeout: 5000, interval: 50 });    // An answered ask stays answered; one never sent is not there.    expect((await call(holder, "POST", "/v1/secret/ask/withdraw", { ask: second })).body).toEqual({ ok: true });    expect((await outOfAsks(holder)).find((a) => a.ask === second)!.state).toBe("no");    expect((await call(holder, "POST", "/v1/secret/ask/withdraw", { ask: id("ask-never-sent") })).status).toBe(404);    // The giver's own asks are their own.    expect(await outOfAsks(giver)).toEqual([]);  });  it("never holds a stranger's ask", async () => {    const { giver } = await connected();    type Ask = { ask: string };    const ask = id("ask-wifi-please");    const stranger = await chatPhone(number(), `dev-${n}`);    await stranger.say("accept", giver.number);    expect((await call(stranger, "POST", "/v1/secret/ask", { to: giver.number, ask: id("ask-stranger"), box: box("give me yours") })).body).toEqual({ ok: true });    await new Promise((r) => setTimeout(r, 500));    expect((await call<{ asks: Ask[] }>(giver, "GET", "/v1/secret/ask/in")).body.asks.map((a) => a.ask)).not.toContain(id("ask-stranger"));    expect(ask).toHaveLength(32);  });});