Cotton code
214 lines · 11.3 KB · TypeScriptRaw
/** * The c2 box's half on the Worker (assets/design/chat/SEALING.md): a device publishes its Olm * record and one-time keys beside its chat key, a sender claims one key per device it starts a session with (the * fallback key once they run out), a device that stops saying c2 loses what it published, a made-up device answers a * c2 record and keys a phone cannot tell from a real one's, and a c2 box travels as a c1 box does. The Worker opens * nothing: the signatures and the ratchet are the phone's (cotton-core chat/ratchet.rs). Every number is synthetic. */import { describe, expect, it, vi } from "vitest";import vectors from "../../../crates/cotton-core/src/chat/ratchet_vectors.json";import { bearer, fakes, open } from "./calling.ts";import { arrived, b64url, chatPhone, unb64url, type ChatPhone } from "./chat.ts";import { CLAIMS_PER_HOUR, PREKEYS_MAX, signerOf } from "../src/chat/chat.ts";import { apnsBody } from "../src/chat/push.ts";vi.setConfig({ testTimeout: 30_000 });let n = 0;const number = (): string => `+91900002${String(1000 + ++n).padStart(4, "0")}`;const hex = (text: string): Uint8Array => Uint8Array.from(text.match(/../g)!.map((b) => parseInt(b, 16)));const toHex = (bytes: Uint8Array): string => [...bytes].map((b) => b.toString(16).padStart(2, "0")).join("");const cat = (...parts: Uint8Array[]): Uint8Array => {  const out = new Uint8Array(parts.reduce((s, p) => s + p.length, 0));  let at = 0;  for (const p of parts) {    out.set(p, at);    at += p.length;  }  return out;};const DEVICE = new TextEncoder().encode("cotton-chat-c2-device");const PREKEY = new TextEncoder().encode("cotton-chat-c2-prekey");/** A key-shaped string: 32 bytes of `fill`, base64url. */const key = (fill: number): string => b64url(new Uint8Array(32).fill(fill));/** A signature-shaped string: 64 bytes. */const sig = (fill: number): string => b64url(new Uint8Array(64).fill(fill));const prekeys = (from: number, count: number) => Array.from({ length: count }, (_, i) => ({ key: key((from + i) % 250), sig: sig(1) }));/** A phone that says it speaks c2: its record, its fallback key and `count` one-time keys. */async function c2Phone(at: string, device: string, count = 3, first = 10): Promise<ChatPhone> {  const phone = await chatPhone(at, device);  const res = await open<{ prekeys: number }>("POST", "/v1/chat/device", { publicKey: phone.publicKey, c2: { identity: key(first), signing: key(first + 1), sig: sig(2), fallback: { key: key(200), sig: sig(3) }, prekeys: prekeys(first + 2, count) } }, bearer(phone.credential));  expect(res.status, JSON.stringify(res.body)).toBe(200);  expect(res.body.prekeys).toBe(count);  return phone;}async function claim(phone: ChatPhone, at: string, devices: string[]): Promise<{ status: number; body: { prekeys: Record<string, { key: string; sig: string; fallback?: boolean }> } }> {  return open("POST", "/v1/chat/prekeys/claim", { number: at, devices }, bearer(phone.credential));}async function inboxPrekeys(phone: ChatPhone): Promise<number | undefined> {  const res = await open<{ prekeys?: number }>("GET", "/v1/chat/inbox", undefined, bearer(phone.credential));  return res.body.prekeys;}describe("a c2 device's keys", () => {  it("publishes its record beside its chat key, and a sender sees it", async () => {    fakes();    const a = await chatPhone(number(), "a-phone");    const b = await c2Phone(number(), "b-phone");    // Real keys go only between people who accepted each other (src/chat/gate.ts).    await b.say("accept", a.number);    await a.say("accept", b.number);    const keys = await a.keysFor(b.number);    expect(keys.devices).toHaveLength(1);    expect(keys.devices[0]).toMatchObject({ key: b.publicKey, c2: { identity: key(10), signing: key(11), sig: sig(2) } });    // A c1 phone's devices carry no record.    expect((await b.keysFor(a.number)).devices[0]).not.toHaveProperty("c2");    expect(await inboxPrekeys(b)).toBe(3);    expect(await inboxPrekeys(a)).toBeUndefined();  });  it("hands each one-time key out once, then its fallback key", async () => {    fakes();    const a = await chatPhone(number(), "a-phone");    const b = await c2Phone(number(), "b-phone", 2);    await b.say("accept", a.number);    const handle = (await a.keysFor(b.number)).devices[0]!.device;    const first = await claim(a, b.number, [handle]);    const second = await claim(a, b.number, [handle]);    expect(first.status).toBe(200);    expect(first.body.prekeys[handle]!.key).not.toBe(second.body.prekeys[handle]!.key);    expect(await inboxPrekeys(b)).toBe(0);    const third = await claim(a, b.number, [handle]);    expect(third.body.prekeys[handle]).toEqual({ key: key(200), sig: sig(3), fallback: true });    // Topped up, the shelf hands out one-time keys again.    const topped = await open<{ prekeys: number }>("POST", "/v1/chat/prekeys", { prekeys: prekeys(50, 4) }, bearer(b.credential));    expect(topped.body.prekeys).toBe(4);    expect((await claim(a, b.number, [handle])).body.prekeys[handle]!.fallback).toBeUndefined();  });  it("claims for this person's own other phones from their own object, never for the asking phone", async () => {    fakes();    const at = number();    const one = await c2Phone(at, "one", 2, 10);    const two = await c2Phone(at, "two", 2, 60);    const own = (await one.keysFor(at)).own;    expect(own).toHaveLength(1);    expect(own[0]!.c2!.identity).toBe(key(60));    const claimed = await claim(one, at, [own[0]!.device]);    expect(Object.keys(claimed.body.prekeys)).toEqual([own[0]!.device]);    expect(await inboxPrekeys(two)).toBe(1);    expect(await inboxPrekeys(one)).toBe(2);  });  it("keeps a hundred one-time keys at most, the newest", async () => {    fakes();    const b = await c2Phone(number(), "b-phone", 90);    const res = await open<{ prekeys: number }>("POST", "/v1/chat/prekeys", { prekeys: prekeys(100, 40) }, bearer(b.credential));    expect(res.body.prekeys).toBe(PREKEYS_MAX);  });  it("forgets what a device published once it registers without c2, or with a new chat key", async () => {    fakes();    const a = await chatPhone(number(), "a-phone");    const b = await c2Phone(number(), "b-phone");    await b.say("accept", a.number);    const again = await open("POST", "/v1/chat/device", { publicKey: b.publicKey }, bearer(b.credential));    expect(again.status).toBe(200);    expect((await a.keysFor(b.number)).devices[0]).not.toHaveProperty("c2");    expect(await inboxPrekeys(b)).toBeUndefined();    // A device that never said c2 may not publish keys.    const refused = await open<{ code: string }>("POST", "/v1/chat/prekeys", { prekeys: prekeys(1, 1) }, bearer(a.credential));    expect(refused.status).toBe(409);  });  it("refuses a record or a key that is not shaped as one", async () => {    fakes();    const b = await chatPhone(number(), "b-phone");    for (const c2 of [{ identity: "x", signing: key(1), sig: sig(1) }, { identity: key(1), signing: key(1), sig: "short" }, { identity: key(1), signing: key(2), sig: sig(1), prekeys: [{ key: key(3) }] }]) {      const res = await open("POST", "/v1/chat/device", { publicKey: b.publicKey, c2 }, bearer(b.credential));      expect(res.status, JSON.stringify(c2)).toBe(400);    }  });  it("limits how many keys one phone claims in an hour", async () => {    fakes();    const a = await chatPhone(number(), "a-phone");    const b = await c2Phone(number(), "b-phone", 1);    await b.say("accept", a.number);    const handle = (await a.keysFor(b.number)).devices[0]!.device;    const many = Array.from({ length: 16 }, () => handle);    let status = 200;    for (let i = 0; i <= CLAIMS_PER_HOUR / 16 && status === 200; i++) status = (await claim(a, b.number, many)).status;    expect(status).toBe(429);  });});describe("a number nobody holds", () => {  it("answers every asking account the same made-up devices, so two accounts comparing learn nothing (ROUTES-AUDIT 6)", async () => {    fakes();    const a = await chatPhone(number(), "a-phone");    const b = await chatPhone(number(), "b-phone");    // Five: each is one of the hour's new numbers for both accounts (src/chat/gate.ts).    for (let n = 0; n < 5; n++) {      const nobody = number();      expect((await a.keysFor(nobody)).devices).toEqual((await b.keysFor(nobody)).devices);    }  });  it("answers a c2 record and fresh one-time keys, each truly signed, as a phone's would be", async () => {    fakes();    const a = await chatPhone(number(), "a-phone");    const nobody = number();    const keys = await a.keysFor(nobody);    const fake = keys.devices[0]!;    expect(fake.c2).toBeDefined();    // The same each time it is asked.    expect((await a.keysFor(nobody)).devices[0]).toEqual(fake);    const signing = await crypto.subtle.importKey("raw", unb64url(fake.c2!.signing), { name: "Ed25519" }, false, ["verify"]);    expect(await crypto.subtle.verify({ name: "Ed25519" }, signing, unb64url(fake.c2!.sig), cat(DEVICE, unb64url(fake.key), unb64url(fake.c2!.identity)))).toBe(true);    const one = (await claim(a, nobody, [fake.device])).body.prekeys[fake.device]!;    const two = (await claim(a, nobody, [fake.device])).body.prekeys[fake.device]!;    expect(one.key).not.toBe(two.key);    for (const p of [one, two]) {      expect(p.fallback).toBeUndefined();      expect(await crypto.subtle.verify({ name: "Ed25519" }, signing, unb64url(p.sig), cat(PREKEY, unb64url(fake.c2!.identity), unb64url(p.key)))).toBe(true);    }  });});describe("the c2 box", () => {  it("travels as a c1 box does, and an iPhone's alert carries it with the envelope's outside", async () => {    fakes();    const a = await chatPhone(number(), "a-phone");    const b = await c2Phone(number(), "b-phone");    await b.say("accept", a.number);    const handle = (await a.keysFor(b.number)).devices[0]!.device;    const box = `c2:${b64url(new Uint8Array(120).fill(7))}`;    const sent = await open("POST", "/v1/chat/send", { to: b.number, id: crypto.randomUUID(), kind: "message", boxes: { [handle]: box } }, bearer(a.credential));    expect(sent.status, JSON.stringify(sent.body)).toBe(200);    expect((await arrived(b))[0]!.box).toBe(box);    // An iPhone's alert carries a c2 box with the envelope's outside, for the core's read-only peek; a c1 box alone.    const alerted = apnsBody({ kind: "message", request: false, box, id: "m1", peer: a.number, out: false, at: 5, group: null });    expect(alerted).toMatchObject({ box, item: { id: "m1", kind: "message", peer: a.number, out: false, at: 5, group: null } });    expect(apnsBody({ kind: "message", request: false, box: "c1:abc", id: "m2", peer: a.number })).toEqual(expect.not.objectContaining({ item: expect.anything() }));    expect(apnsBody({ kind: "message", request: true, box })).not.toHaveProperty("box");    const bad = await open("POST", "/v1/chat/send", { to: b.number, id: crypto.randomUUID(), kind: "message", boxes: { [handle]: "c3:abc" } }, bearer(a.credential));    expect(bad.status).toBe(400);  });});describe("the signatures, two implementations", () => {  it("signs a record and a one-time key byte for byte as the core's vectors say", async () => {    const v = vectors.record;    const signer = await signerOf(hex(v.signingSeed));    expect(toHex(signer.publicRaw)).toBe(v.signing);    expect(toHex(await signer.sign(cat(DEVICE, hex(v.chatKey), hex(v.identity))))).toBe(v.deviceSig);    expect(toHex(await signer.sign(cat(PREKEY, hex(v.identity), hex(v.prekey))))).toBe(v.prekeySig);  });});