Cotton code
530 lines · 31.3 KB · TypeScriptRaw
/** * A new device approved from one already signed in, with no code (owner, * 17 Nov 2026; src/approval.ts). Every number, device and name is invented. */import { env, runInDurableObject, SELF } from "cloudflare:test";import { describe, expect, it } from "vitest";import { ADMIT_SECONDS, ANSWER_FLOOR_MS, ASK_TTL_SECONDS, askCommit, Asks, askSas, ASKS_PER_HOUR, CLAIM_SECONDS, claimStatement, NOBODY, WRONG_TRIES } from "../src/approval.ts";import type { Directory } from "../src/directory.ts";import { ADMIN } from "./personal.ts";const OPEN = "https://cottondb.com";type Body = Record<string, unknown>;async function open<T = Body>(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 = 0;function network(): Record<string, string> {  ips += 1;  return { "cf-connecting-ip": `203.0.113.${ips}` };}const bearer = (token: string): Record<string, string> => ({ authorization: `Bearer ${token}` });function b64u(bytes: ArrayBuffer | Uint8Array): string {  let s = "";  for (const b of new Uint8Array(bytes)) s += String.fromCharCode(b);  return btoa(s).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");}interface Device {  id: string;  /** Its X25519 vault key's public half (any 32 bytes here: the Worker only relays it). */  vaultKey: string;  /** The nonce it commits to before an approver's exists. */  nonce: string;  sign(text: string): Promise<string>;}const random32 = (): string => b64u(crypto.getRandomValues(new Uint8Array(32)));async function device(): Promise<Device> {  const pair = (await crypto.subtle.generateKey({ name: "Ed25519" }, true, ["sign", "verify"])) as CryptoKeyPair;  const id = b64u((await crypto.subtle.exportKey("raw", pair.publicKey)) as ArrayBuffer);  return { id, vaultKey: random32(), nonce: random32(), sign: async (text) => b64u(await crypto.subtle.sign({ name: "Ed25519" }, pair.privateKey, new TextEncoder().encode(text))) };}/** A number signed in on one device by code: its credential and database. */async function signedIn(phone: string, deviceId = "phone-signed-in"): Promise<{ credential: string; databaseId: string }> {  const ip = network();  const code = await open<{ challenge_id: string; database_id: string }>("POST", "/v1/code", { phone, device_id: deviceId }, 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: deviceId }, ip);  expect(signed.status, JSON.stringify(signed.body)).toBe(200);  return { credential: signed.body.credential, databaseId: code.body.database_id };}interface AskAnswer {  ask_id: string;  expires_in: number;  poll_seconds: number;}async function askBody(phone: string, asking: Device, name = "Pixel walk"): Promise<Body> {  return { phone, device_id: asking.id, device_name: name, vault_key: asking.vaultKey, commit: await askCommit(asking.id, asking.vaultKey, asking.nonce) };}async function ask(phone: string, asking: Device, name = "Pixel walk"): Promise<AskAnswer> {  const asked = await open<AskAnswer>("POST", "/v1/approval/ask", await askBody(phone, asking, name), network());  expect(asked.status, JSON.stringify(asked.body)).toBe(200);  return asked.body;}const poll = (askId: string) => open<{ state: string; nonce_b?: string; challenge?: string }>("POST", "/v1/approval/poll", { ask_id: askId });interface Seen {  ask_id: string;  device_id: string;  device_name: string | null;  device_kind?: string | null;  vault_key: string | null;  commit: string;  nonce_b: string | null;  reveal: string | null;  asked_at: number;  expires_at: number;}const approvals = (credential: string) => open<{ now: number; asks: Seen[]; holds: boolean }>("GET", "/v1/approvals", undefined, bearer(credential));/** * The exchange before Approve: the approver sets its nonce, the asking device * sees it on a poll and reveals its own. Answers the code each side works out. */async function compare(credential: string, askId: string, asking: Device): Promise<{ asking: string; approving: string }> {  const nonceB = random32();  const set = await open<{ nonce_b: string }>("POST", "/v1/approvals/nonce", { ask_id: askId, nonce: nonceB }, bearer(credential));  expect(set.status, JSON.stringify(set.body)).toBe(200);  const polled = await poll(askId);  expect(polled.body).toEqual({ state: "waiting", nonce_b: nonceB });  const revealed = await open("POST", "/v1/approval/reveal", { ask_id: askId, nonce: asking.nonce }, network());  expect(revealed.status, JSON.stringify(revealed.body)).toBe(200);  const seen = (await approvals(credential)).body.asks.find((a) => a.ask_id === askId)!;  expect(await askCommit(seen.device_id, seen.vault_key, seen.reveal!)).toBe(seen.commit);  return {    asking: await askSas(asking.id, asking.vaultKey, asking.nonce, polled.body.nonce_b!),    approving: await askSas(seen.device_id, seen.vault_key, seen.reveal!, seen.nonce_b!),  };}async function claim(askId: string, signer: Device, challenge: string) {  return open<{ credential?: string; database_id?: string; host?: string; code?: string; person?: Body }>("POST", "/v1/approval/claim", { ask_id: askId, sig: await signer.sign(claimStatement(askId, challenge)) }, network());}describe("approving a new device from one already signed in", () => {  it("shows the ask with the name and its keys, both sides work out the same code, and Approve grants the new device its own credential once", async () => {    const phone = "+919000004001";    const me = await signedIn(phone);    const pixel = await device();    const asked = await ask(phone, pixel);    expect(Object.keys(asked).sort()).toEqual(["ask_id", "expires_in", "poll_seconds"]);    expect(asked.expires_in).toBe(ASK_TTL_SECONDS);    const seen = await approvals(me.credential);    expect(seen.status, JSON.stringify(seen.body)).toBe(200);    expect(seen.body.asks).toHaveLength(1);    expect(seen.body.asks[0]).toMatchObject({ ask_id: asked.ask_id, device_id: pixel.id, device_name: "Pixel walk", vault_key: pixel.vaultKey, nonce_b: null, reveal: null });    expect(seen.body.asks[0]!.expires_at - seen.body.asks[0]!.asked_at).toBe(ASK_TTL_SECONDS);    expect((await poll(asked.ask_id)).body).toEqual({ state: "waiting" });    // Approve before the codes were compared lets nobody in.    const blind = await open<{ code: string }>("POST", "/v1/approvals/approve", { ask_id: asked.ask_id }, bearer(me.credential));    expect([blind.status, blind.body.code]).toEqual([409, "not_compared"]);    const codes = await compare(me.credential, asked.ask_id, pixel);    expect(codes.asking).toMatch(/^\d{6}$/);    expect(codes.approving).toBe(codes.asking);    expect((await open("POST", "/v1/approvals/approve", { ask_id: asked.ask_id }, bearer(me.credential))).status).toBe(200);    const approved = await poll(asked.ask_id);    expect(approved.body.state).toBe("approved");    const challenge = approved.body.challenge!;    expect(challenge.length).toBeGreaterThan(20);    const claimed = await claim(asked.ask_id, pixel, challenge);    expect(claimed.status, JSON.stringify(claimed.body)).toBe(200);    expect(claimed.body.database_id).toBe(me.databaseId);    expect(claimed.body.host).toBe(OPEN);    expect(claimed.body.credential!.startsWith(`ctd_${me.databaseId}_`)).toBe(true);    expect(claimed.body.credential).not.toBe(me.credential);    const mine = await open<{ person: { phone: string } }>("GET", "/v1/me", undefined, bearer(claimed.body.credential!));    expect(mine.status).toBe(200);    expect(mine.body.person.phone).toBe(phone);    // Reuse: the ask is spent.    const again = await claim(asked.ask_id, pixel, challenge);    expect(again.status).toBe(410);    expect(again.body.code).toBe("ask_used");    expect((await poll(asked.ask_id)).body).toEqual({ state: "used" });    // And it is no longer shown.    expect((await open<{ asks: unknown[] }>("GET", "/v1/approvals", undefined, bearer(me.credential))).body.asks).toEqual([]);  });  it("Refuse ends the ask: the asking device is told, and nothing can be claimed", async () => {    const phone = "+919000004002";    const me = await signedIn(phone);    const pixel = await device();    const asked = await ask(phone, pixel);    expect((await open("POST", "/v1/approvals/refuse", { ask_id: asked.ask_id }, bearer(me.credential))).status).toBe(200);    expect((await poll(asked.ask_id)).body).toEqual({ state: "refused" });    const claimed = await claim(asked.ask_id, pixel, "any");    expect(claimed.status).toBe(409);    expect(claimed.body.code).toBe("not_approved");    // Decided once: approving after Refuse is refused.    const late = await open<{ code: string }>("POST", "/v1/approvals/approve", { ask_id: asked.ask_id }, bearer(me.credential));    expect(late.status).toBe(409);    expect(late.body.code).toBe("ask_decided");  });  it("a claim signed by any key but the asking device's is refused and spends nothing", async () => {    const phone = "+919000004003";    const me = await signedIn(phone);    const pixel = await device();    const thief = await device();    const asked = await ask(phone, pixel);    await compare(me.credential, asked.ask_id, pixel);    await open("POST", "/v1/approvals/approve", { ask_id: asked.ask_id }, bearer(me.credential));    const challenge = (await poll(asked.ask_id)).body.challenge!;    const stolen = await claim(asked.ask_id, thief, challenge);    expect(stolen.status).toBe(401);    expect(stolen.body.code).toBe("wrong_device");    expect(stolen.body.credential).toBeUndefined();    // A signature over another challenge is no good either.    expect((await claim(asked.ask_id, pixel, "not-the-challenge")).body.code).toBe("wrong_device");    const mine = await claim(asked.ask_id, pixel, challenge);    expect(mine.status, JSON.stringify(mine.body)).toBe(200);    expect(mine.body.credential).toBeTruthy();  });  it("no admin token, MCP token or stranger approves; a device never approves its own ask", async () => {    const phone = "+919000004004";    const pixel = await device();    // The asking device itself signed in by code earlier, under the same device key.    const me = await signedIn(phone, pixel.id);    const asked = await ask(phone, pixel);    const own = await open<{ code: string }>("POST", "/v1/approvals/approve", { ask_id: asked.ask_id }, bearer(me.credential));    expect(own.status).toBe(403);    expect(own.body.code).toBe("own_ask");    expect((await open<{ asks: unknown[] }>("GET", "/v1/approvals", undefined, bearer(me.credential))).body.asks).toEqual([]);    const admin = await SELF.fetch(`https://cottondb.com/b/p-${me.databaseId}/v1/approvals/approve`, { method: "POST", headers: { "content-type": "application/json", authorization: `Bearer ${ADMIN}` }, body: JSON.stringify({ ask_id: asked.ask_id }) });    // The admin token is no device's: the object sees no credential at this door and answers it as it answers    // a stranger, as a database that does not exist would (STRANGER ROUTES, 24 Nov 2026).    expect(admin.status).toBe(401);    expect(((await admin.json()) as Body).code).toBe("not_signed_in");    const nobody = await open<{ code: string }>("POST", "/v1/approvals/approve", { ask_id: asked.ask_id });    expect(nobody.status).toBe(401);    // Another number's signed-in device cannot see or decide it.    const other = await signedIn("+919000004005");    expect((await open<{ asks: unknown[] }>("GET", "/v1/approvals", undefined, bearer(other.credential))).body.asks).toEqual([]);    const cross = await open<{ code: string }>("POST", "/v1/approvals/approve", { ask_id: asked.ask_id }, bearer(other.credential));    expect(cross.status).toBe(404);    expect((await poll(asked.ask_id)).body).toEqual({ state: "waiting" });  });});describe("nothing leaks to the asking device", () => {  it("until a person taps, answers alike and in one timing class for a number not on Cotton, one with no device and one with a phone open, and makes no database", async () => {    const open_ = "+919000004101";    const watching = await signedIn(open_);    const quiet = "+919000004102";    // On Cotton, but every device signed out.    const q = await signedIn(quiet);    await open("POST", "/v1/sign-out", {}, bearer(q.credential));    const stranger = "+919000004103";    const timed = async <T,>(call: () => Promise<{ status: number; body: T }>) => {      const started = Date.now();      const answer = await call();      return { ...answer, ms: Date.now() - started };    };    const seen: unknown[][] = [];    const askIds: string[] = [];    for (const phone of [open_, quiet, stranger]) {      const pixel = await device();      const asked = await timed(async () => open<Body>("POST", "/v1/approval/ask", await askBody(phone, pixel), network()));      expect(asked.status).toBe(200);      const askId = asked.body.ask_id as string;      askIds.push(askId);      expect(askId).toMatch(/^cta_[A-Za-z0-9_-]{32}$/);      if (phone === open_) {        // The owner's phone is open and its card shows the ask, as the core draws it before anyone taps: it looks, it sets nothing.        const card = await approvals(watching.credential);        expect(card.body.asks.map((a) => [a.ask_id, a.nonce_b])).toEqual([[askId, null]]);      }      const early = await timed(() => open<{ code: string }>("POST", "/v1/approval/reveal", { ask_id: askId, nonce: pixel.nonce }, network()));      const polled = await timed(() => poll(askId));      const claimed = await timed(() => claim(askId, pixel, "none"));      const answers = [asked, early, polled, claimed];      for (const a of answers) expect(a.ms, "every answer is held to the floor").toBeGreaterThanOrEqual(ANSWER_FLOOR_MS);      seen.push([        [asked.status, Object.keys(asked.body).sort(), asked.body.expires_in, asked.body.poll_seconds],        [early.status, early.body],        [polled.status, polled.body],        [claimed.status, claimed.body],      ]);    }    expect(seen[0]).toEqual([      [200, ["ask_id", "expires_in", "poll_seconds"], ASK_TTL_SECONDS, 3],      [409, { code: "too_early", message: "No device has opened this sign-in ask yet." }],      [200, { state: "waiting" }],      [409, { code: "not_approved", message: "That sign-in has not been approved." }],    ]);    expect(seen[1]).toEqual(seen[0]);    expect(seen[2]).toEqual(seen[0]);    const dir = env.DIRECTORY.get(env.DIRECTORY.idFromName("directory"));    // The same timing class: every ask is held by an object, a number on no database by NOBODY, and none is made.    const routes = await runInDurableObject(dir, (_instance: Directory, state) =>      askIds.map((id) => state.storage.sql.exec<{ slug: string | null }>("SELECT slug FROM approval_route WHERE id = ?", id).toArray()[0]?.slug ?? null),    );    expect(routes.every((slug) => typeof slug === "string" && slug.length > 0)).toBe(true);    expect(routes[2]).toBe(NOBODY);    expect(await runInDurableObject(dir, (instance: Directory) => instance.lookup(stranger))).toBeNull();    // NOBODY's ask expires as a person's does.    await runInDurableObject(env.BUSINESS.get(env.BUSINESS.idFromName(NOBODY)), async (_i, state) => {      const asks = new Asks(state.storage.sql);      const late = Math.floor(Date.now() / 1000) + ASK_TTL_SECONDS + 1;      expect(asks.state(askIds[2]!, late)).toEqual({ state: "expired" });    });  });  it("limits asks per number the same whether or not the number is on Cotton, and per network", async () => {    const known = "+919000004201";    await signedIn(known);    for (const phone of [known, "+919000004202"]) {      for (let i = 0; i < ASKS_PER_HOUR; i += 1) await ask(phone, await device());      const over = await open<{ code: string }>("POST", "/v1/approval/ask", await askBody(phone, await device()), network());      expect([over.status, over.body.code]).toEqual([429, "too_many_asks"]);    }  });  it("refuses a device id that is not a key, before anything", async () => {    const res = await open<{ code: string }>("POST", "/v1/approval/ask", { phone: "+919000004301", device_id: "phone-1" }, network());    expect([res.status, res.body.code]).toEqual([400, "bad_device"]);    // An app from before the codes were compared on both screens is told to update, or to send a code.    const old = await open<{ code: string }>("POST", "/v1/approval/ask", { phone: "+919000004301", device_id: (await device()).id }, network());    expect([old.status, old.body.code]).toEqual([400, "update_app"]);    const unknown = await poll("cta_" + "x".repeat(32));    expect([unknown.status]).toEqual([404]);  });});describe("an ask's clock", () => {  it("expires: no approval, no claim, and its poll says so", async () => {    const slug = "approval-clock-1";    const stub = env.BUSINESS.get(env.BUSINESS.idFromName(slug));    const pixel = await device();    await runInDurableObject(stub, async (_i, state) => {      const asks = new Asks(state.storage.sql);      const t = 1_800_000_000;      asks.add({ id: "cta_clock1", phone: "+919000004401", deviceId: pixel.id, deviceName: "Pixel", vaultKey: null, commit: "c", createdAt: t, expiresAt: t + ASK_TTL_SECONDS });      expect(asks.state("cta_clock1", t + ASK_TTL_SECONDS)).toEqual({ state: "waiting" });      expect(asks.state("cta_clock1", t + ASK_TTL_SECONDS + 1)).toEqual({ state: "expired" });      expect(asks.waiting("+919000004401", "other", t + ASK_TTL_SECONDS + 1)).toEqual([]);      expect((await asks.decide("cta_clock1", "+919000004401", "other", "approved", t + ASK_TTL_SECONDS + 1))?.code).toBe("ask_expired");    });  });  it("an approval late in the ask leaves the device a minute to claim, and no more", async () => {    const stub = env.BUSINESS.get(env.BUSINESS.idFromName("approval-clock-2"));    const pixel = await device();    await runInDurableObject(stub, async (_i, state) => {      const asks = new Asks(state.storage.sql);      const t = 1_800_000_000;      asks.add({ id: "cta_clock2", phone: "+919000004402", deviceId: pixel.id, deviceName: null, vaultKey: null, commit: await askCommit(pixel.id, null, pixel.nonce), createdAt: t, expiresAt: t + ASK_TTL_SECONDS });      const late = t + ASK_TTL_SECONDS - 5;      asks.nonce("cta_clock2", "+919000004402", "other", random32(), late);      expect(await asks.reveal("cta_clock2", pixel.nonce, late)).toBeNull();      expect(await asks.decide("cta_clock2", "+919000004402", "other", "approved", late)).toBeNull();      const { challenge } = asks.state("cta_clock2", late + CLAIM_SECONDS) as { challenge: string };      expect(asks.state("cta_clock2", late + CLAIM_SECONDS + 1)).toEqual({ state: "expired" });      const sig = await pixel.sign(claimStatement("cta_clock2", challenge));      const tooLate = await asks.claim("cta_clock2", sig, late + CLAIM_SECONDS + 1);      expect("refused" in tooLate && tooLate.refused.code).toBe("ask_expired");      const inTime = await asks.claim("cta_clock2", sig, late + CLAIM_SECONDS);      expect(inTime).toEqual({ phone: "+919000004402", deviceId: pixel.id });    });  });});describe("the code is not the server's", () => {  it("a reveal that does not hash to the commit is refused, the first nonce and reveal stand, and a swapped key changes the code", async () => {    const phone = "+919000004501";    const me = await signedIn(phone);    const pixel = await device();    const asked = await ask(phone, pixel);    const first = random32();    expect((await open<{ nonce_b: string }>("POST", "/v1/approvals/nonce", { ask_id: asked.ask_id, nonce: first }, bearer(me.credential))).body.nonce_b).toBe(first);    // A second approver's nonce (another signed-in device) does not replace the first.    expect((await open<{ nonce_b: string }>("POST", "/v1/approvals/nonce", { ask_id: asked.ask_id, nonce: random32() }, bearer(me.credential))).body.nonce_b).toBe(first);    const wrong = await open<{ code: string }>("POST", "/v1/approval/reveal", { ask_id: asked.ask_id, nonce: random32() }, network());    expect([wrong.status, wrong.body.code]).toEqual([400, "wrong_reveal"]);    expect((await open("POST", "/v1/approval/reveal", { ask_id: asked.ask_id, nonce: pixel.nonce }, network())).status).toBe(200);    // Saying it again is fine; saying another is not.    expect((await open("POST", "/v1/approval/reveal", { ask_id: asked.ask_id, nonce: pixel.nonce }, network())).status).toBe(200);    const other = await open<{ code: string }>("POST", "/v1/approval/reveal", { ask_id: asked.ask_id, nonce: random32() }, network());    expect(other.body.code).toBe("already_revealed");    const honest = await askSas(pixel.id, pixel.vaultKey, pixel.nonce, first);    expect(await askSas(pixel.id, random32(), pixel.nonce, first)).not.toBe(honest);    expect(await askSas((await device()).id, pixel.vaultKey, pixel.nonce, first)).not.toBe(honest);    expect(await askSas(pixel.id, pixel.vaultKey, pixel.nonce, random32())).not.toBe(honest);  });  it("the asking device's own nonce cannot be set by the asking device as approver", async () => {    const phone = "+919000004502";    const pixel = await device();    const me = await signedIn(phone, pixel.id);    const asked = await ask(phone, pixel);    const own = await open<{ code: string }>("POST", "/v1/approvals/nonce", { ask_id: asked.ask_id, nonce: random32() }, bearer(me.credential));    expect([own.status, own.body.code]).toEqual([403, "own_ask"]);  });});describe("wrong codes are counted by the object", () => {  it("three wrong codes across every signed-in device of the number refuse the ask", async () => {    const phone = "+919000004601";    const one = await signedIn(phone, "phone-one");    const two = await signedIn(phone, "phone-two");    const pixel = await device();    const asked = await ask(phone, pixel);    const wrong = (credential: string) => open<{ left?: number; ended?: boolean; code?: string }>("POST", "/v1/approvals/wrong", { ask_id: asked.ask_id }, bearer(credential));    // Before the codes are on both screens there is nothing to get wrong.    expect([(await wrong(one.credential)).status, (await wrong(one.credential)).body.code]).toEqual([409, "not_compared"]);    await compare(one.credential, asked.ask_id, pixel);    expect((await wrong(one.credential)).body).toEqual({ left: WRONG_TRIES - 1, ended: false });    // Another device of the number (or the same app after a restart) counts on from there.    expect((await wrong(two.credential)).body).toEqual({ left: WRONG_TRIES - 2, ended: false });    expect((await wrong(one.credential)).body).toEqual({ left: 0, ended: true });    expect((await poll(asked.ask_id)).body).toEqual({ state: "refused", why: "wrong" });    const late = await open<{ code: string }>("POST", "/v1/approvals/approve", { ask_id: asked.ask_id }, bearer(two.credential));    expect([late.status, late.body.code]).toEqual([409, "ask_decided"]);    expect((await wrong(two.credential)).body.code).toBe("ask_decided");  });  it("a stranger's device, an MCP token or the admin cannot count against an ask", async () => {    const phone = "+919000004602";    await signedIn(phone, "phone-one");    const other = await signedIn("+919000004603");    const asked = await ask(phone, await device());    const cross = await open<{ code: string }>("POST", "/v1/approvals/wrong", { ask_id: asked.ask_id }, bearer(other.credential));    expect([cross.status, cross.body.code]).toEqual([404, "no_such_ask"]);    expect((await open("POST", "/v1/approvals/wrong", { ask_id: asked.ask_id })).status).toBe(401);  });});describe("no device into the vault on a tap", () => {  it("admits a wrap only for the key an ask named, revealed and approved by that approver, lately", async () => {    const stub = env.BUSINESS.get(env.BUSINESS.idFromName("approval-admit-1"));    const pixel = await device();    await runInDurableObject(stub, async (_i, state) => {      const asks = new Asks(state.storage.sql);      const t = 1_800_000_000;      const phone = "+919000004701";      asks.add({ id: "cta_admit1", phone, deviceId: pixel.id, deviceName: null, vaultKey: pixel.vaultKey, commit: await askCommit(pixel.id, pixel.vaultKey, pixel.nonce), createdAt: t, expiresAt: t + ASK_TTL_SECONDS });      expect(asks.admitted(pixel.id, pixel.vaultKey, "approver", t), "waiting").toBe(false);      asks.nonce("cta_admit1", phone, "approver", random32(), t);      expect(await asks.reveal("cta_admit1", pixel.nonce, t)).toBeNull();      expect(asks.admitted(pixel.id, pixel.vaultKey, "approver", t), "compared, not approved").toBe(false);      expect(await asks.decide("cta_admit1", phone, "approver", "approved", t)).toBeNull();      expect(asks.admitted(pixel.id, pixel.vaultKey, "approver", t)).toBe(true);      expect(asks.admitted(pixel.id, random32(), "approver", t), "another key").toBe(false);      expect(asks.admitted(pixel.id, pixel.vaultKey, "someone-else", t), "another approver").toBe(false);      expect(asks.admitted(pixel.id, pixel.vaultKey, "approver", t + ADMIT_SECONDS + 1), "too late").toBe(false);    });  });});/** A signed-in device's own vault row, with a wrap (synthetic): it can open the person's data. */async function holdTheKey(credential: string, deviceId: string): Promise<void> {  const made = await open("POST", "/v1/act", { act: "create", args: { table: "vault_key", id: `vault-key-${deviceId}`, data: { device_id: deviceId, public_key: random32(), wrapped_vmk: "w1:SYNTHETIC-holder", vmk_version: 1 } } }, bearer(credential));  expect(made.status, JSON.stringify(made.body)).toBe(200);}describe("getting in on a new device (assets/design/shared/GETTING-IN.md)", () => {  it("a second ask from the same device replaces the first: the first expires, is shown to nobody, and cannot be approved or claimed", async () => {    const phone = "+919000004801";    const me = await signedIn(phone);    const mac = await device();    const first = await ask(phone, mac, "mac-c");    const second = await ask(phone, { ...mac, nonce: random32() }, "mac-c");    expect((await poll(first.ask_id)).body).toEqual({ state: "expired" });    expect((await poll(second.ask_id)).body).toEqual({ state: "waiting" });    expect((await approvals(me.credential)).body.asks.map((a) => a.ask_id)).toEqual([second.ask_id]);    const late = await open<{ code: string }>("POST", "/v1/approvals/approve", { ask_id: first.ask_id, scanned: mac.nonce }, bearer(me.credential));    expect([late.status, late.body.code]).toEqual([410, "ask_expired"]);    // Another device's ask stands beside it.    const pixel = await device();    const third = await ask(phone, pixel);    expect((await approvals(me.credential)).body.asks.map((a) => a.ask_id).sort()).toEqual([second.ask_id, third.ask_id].sort());  });  it("the scanned code approves with no digits compared: only the nonce the ask committed to, once", async () => {    const phone = "+919000004802";    const me = await signedIn(phone);    const mac = await device();    const asked = await open<AskAnswer>("POST", "/v1/approval/ask", { ...(await askBody(phone, mac, "mac-c")), device_kind: "mac" }, network());    expect(asked.status).toBe(200);    const seen = (await approvals(me.credential)).body.asks[0]!;    expect(seen.device_kind).toBe("mac");    // A code from another device (or made up) is refused and spends nothing.    const forged = await open<{ code: string }>("POST", "/v1/approvals/approve", { ask_id: asked.body.ask_id, scanned: random32() }, bearer(me.credential));    expect([forged.status, forged.body.code]).toEqual([409, "wrong_scan"]);    const junk = await open<{ code: string }>("POST", "/v1/approvals/approve", { ask_id: asked.body.ask_id, scanned: "nope" }, bearer(me.credential));    expect([junk.status, junk.body.code]).toEqual([400, "bad_scan"]);    expect((await poll(asked.body.ask_id)).body).toEqual({ state: "waiting" });    expect((await open("POST", "/v1/approvals/approve", { ask_id: asked.body.ask_id, scanned: mac.nonce }, bearer(me.credential))).status).toBe(200);    const approved = await poll(asked.body.ask_id);    expect(approved.body.state).toBe("approved");    // The approval admits that device's key for the vault wrap, as a compared one does.    const admitted = await runInDurableObject(env.BUSINESS.get(env.BUSINESS.idFromName(`p-${me.databaseId}`)), async (_i, state) => new Asks(state.storage.sql).admitted(mac.id, mac.vaultKey, "phone-signed-in", Math.floor(Date.now() / 1000)));    expect(admitted).toBe(true);    // Replay: approving again is refused; claiming twice is refused.    const again = await open<{ code: string }>("POST", "/v1/approvals/approve", { ask_id: asked.body.ask_id, scanned: mac.nonce }, bearer(me.credential));    expect([again.status, again.body.code]).toEqual([409, "ask_decided"]);    expect((await claim(asked.body.ask_id, mac, approved.body.challenge!)).status).toBe(200);    expect((await claim(asked.body.ask_id, mac, approved.body.challenge!)).body.code).toBe("ask_used");  });  it("a scanned code must agree with digits already revealed", async () => {    const phone = "+919000004803";    const me = await signedIn(phone);    const pixel = await device();    const asked = await ask(phone, pixel);    await compare(me.credential, asked.ask_id, pixel);    const other = await open<{ code: string }>("POST", "/v1/approvals/approve", { ask_id: asked.ask_id, scanned: random32() }, bearer(me.credential));    expect([other.status, other.body.code]).toEqual([409, "wrong_scan"]);    expect((await open("POST", "/v1/approvals/approve", { ask_id: asked.ask_id, scanned: pixel.nonce }, bearer(me.credential))).status).toBe(200);  });  it("a device that cannot open the data itself cannot open, approve or be told it may: only one that holds the key lets another in", async () => {    const phone = "+919000004804";    const holder = await signedIn(phone, "phone-holder");    const locked = await signedIn(phone, "phone-locked");    await holdTheKey(holder.credential, "phone-holder");    const mac = await device();    const asked = await ask(phone, mac, "mac-c");    const lockedSees = await approvals(locked.credential);    expect(lockedSees.body.holds).toBe(false);    expect((await approvals(holder.credential)).body.holds).toBe(true);    const opened = await open<{ code: string }>("POST", "/v1/approvals/nonce", { ask_id: asked.ask_id, nonce: random32() }, bearer(locked.credential));    expect([opened.status, opened.body.code]).toEqual([403, "approver_locked"]);    const approved = await open<{ code: string }>("POST", "/v1/approvals/approve", { ask_id: asked.ask_id, scanned: mac.nonce }, bearer(locked.credential));    expect([approved.status, approved.body.code]).toEqual([403, "approver_locked"]);    expect((await poll(asked.ask_id)).body).toEqual({ state: "waiting" });    // Refuse stays open to it: saying no lets nobody in.    expect((await open("POST", "/v1/approvals/approve", { ask_id: asked.ask_id, scanned: mac.nonce }, bearer(holder.credential))).status).toBe(200);  });  it("an unknown device kind is dropped, not refused", async () => {    const phone = "+919000004805";    const me = await signedIn(phone);    const asked = await open<AskAnswer>("POST", "/v1/approval/ask", { ...(await askBody(phone, await device())), device_kind: "toaster" }, network());    expect(asked.status).toBe(200);    expect((await approvals(me.credential)).body.asks[0]!.device_kind).toBeNull();  });});