254 lines · 10.8 KB · TypeScriptRaw
/** * Cotton to Cotton messages' tests' world: phones signed up on the open host * with synthetic numbers, each holding an X25519 chat key made in the test, * and sealing as the phone's core does (cotton-core chat/seal.rs, `c1:`): the * Worker under test only ever carries the boxes. The fake APNs and FCM are * Calling's (test/calling.ts). */import { SELF } from "cloudflare:test";import { expect, vi } from "vitest";import { bearer, OPEN, open, signUp } from "./calling.ts";type Body = Record<string, unknown>;const INFO = new TextEncoder().encode("cotton-chat-v1");export function b64url(bytes: Uint8Array): string { return btoa(String.fromCharCode(...bytes)).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");}export function unb64url(text: string): Uint8Array { const padded = text.replace(/-/g, "+").replace(/_/g, "/"); return Uint8Array.from(atob(padded + "=".repeat((4 - (padded.length % 4)) % 4)), (c) => c.charCodeAt(0));}function cat(...parts: Uint8Array[]): Uint8Array { const out = new Uint8Array(parts.reduce((n, p) => n + p.length, 0)); let at = 0; for (const p of parts) { out.set(p, at); at += p.length; } return out;}export interface Pair { privateKey: CryptoKey; publicRaw: Uint8Array;}async function x25519(): Promise<Pair> { const pair = (await crypto.subtle.generateKey({ name: "X25519" }, true, ["deriveBits"])) as CryptoKeyPair; return { privateKey: pair.privateKey, publicRaw: new Uint8Array((await crypto.subtle.exportKey("raw", pair.publicKey)) as ArrayBuffer) };}async function dh(privateKey: CryptoKey, publicRaw: Uint8Array): Promise<Uint8Array> { const pub = await crypto.subtle.importKey("raw", publicRaw, { name: "X25519" }, false, []); return new Uint8Array(await crypto.subtle.deriveBits({ name: "X25519", public: pub } as unknown as SubtleCryptoDeriveKeyAlgorithm, privateKey, 256));}async function aesKey(ikm: Uint8Array, salt: Uint8Array, use: "encrypt" | "decrypt"): Promise<CryptoKey> { const base = await crypto.subtle.importKey("raw", ikm, "HKDF", false, ["deriveKey"]); return crypto.subtle.deriveKey({ name: "HKDF", hash: "SHA-256", salt, info: INFO }, base, { name: "AES-GCM", length: 256 }, false, [use]);}/** Open a `c1:` box with a device's key pair: the payload's text, or null. */export async function openBox(key: Pair, box: string): Promise<string | null> { try { const body = unb64url(box.slice(3)); const eph = body.slice(0, 32); const sender = body.slice(32, 64); const nonce = body.slice(64, 76); const ct = body.slice(76); const ikm = cat(await dh(key.privateKey, eph), await dh(key.privateKey, sender)); const aes = await aesKey(ikm, cat(eph, sender, key.publicRaw), "decrypt"); const plain = await crypto.subtle.decrypt({ name: "AES-GCM", iv: nonce, additionalData: cat(INFO, sender, key.publicRaw) }, aes, ct); return new TextDecoder().decode(plain); } catch { return null; }}/** A device key pair from its private scalar and public half, as the vectors give them. */export async function pairOf(secret: string, publicKey: string): Promise<Pair> { const privateKey = await crypto.subtle.importKey("jwk", { kty: "OKP", crv: "X25519", d: secret, x: publicKey }, { name: "X25519" }, false, ["deriveBits"]); return { privateKey, publicRaw: unb64url(publicKey) };}/** A phone: its sign-in, its chat key and the number it is on. */export class ChatPhone { readonly number: string; readonly device: string; readonly credential: string; readonly key: Pair; constructor(number: string, device: string, credential: string, key: Pair) { this.number = number; this.device = device; this.credential = credential; this.key = key; } get publicKey(): string { return b64url(this.key.publicRaw); } /** Seal a payload for one device's public key, as the phone's core does. */ async seal(recipient: string, payload: unknown): Promise<string> { const r = unb64url(recipient); const eph = await x25519(); const ikm = cat(await dh(eph.privateKey, r), await dh(this.key.privateKey, r)); const key = await aesKey(ikm, cat(eph.publicRaw, this.key.publicRaw, r), "encrypt"); const nonce = crypto.getRandomValues(new Uint8Array(12)); const ct = new Uint8Array(await crypto.subtle.encrypt({ name: "AES-GCM", iv: nonce, additionalData: cat(INFO, this.key.publicRaw, r) }, key, new TextEncoder().encode(JSON.stringify(payload)))); return `c1:${b64url(cat(eph.publicRaw, this.key.publicRaw, nonce, ct))}`; } /** Open a box sealed for this phone: the payload, or null. */ async open(box: string): Promise<Body | null> { const plain = await openBox(this.key, box); return plain === null ? null : (JSON.parse(plain) as Body); } async keysFor(number: string): Promise<{ devices: Sealable[]; own: Sealable[] }> { const res = await open<{ devices: Sealable[]; own: Sealable[] }>("GET", `/v1/chat/keys?number=${encodeURIComponent(number)}`, undefined, bearer(this.credential)); expect(res.status, JSON.stringify(res.body)).toBe(200); return res.body; } /** Write to a number: every one of their devices and this person's own other devices get a box. */ async write(to: string, text: string, id: string = crypto.randomUUID(), kind = "message"): Promise<{ status: number; body: Body }> { const keys = await this.keysFor(to); const payload = kind === "message" ? { v: 1, id, kind, from: this.number, to, body: text } : { v: 1, id, kind, from: this.number, to, state: text }; const boxes: Record<string, string> = {}; for (const k of [...keys.devices, ...keys.own]) boxes[k.device] = await this.seal(k.key, payload); return open("POST", "/v1/chat/send", { to, id, kind, boxes }, bearer(this.credential)); } /** Say one thing in a group: each member's devices get a box naming the group, and this person's own other devices a copy. */ async writeGroup(group: string, members: string[], text: string, id: string = crypto.randomUUID(), kind = "message"): Promise<{ status: number; body: Body }> { const res = await open<{ peers: Record<string, { device: string; key: string }[]>; own: { device: string; key: string }[] }>("POST", "/v1/chat/keys", { numbers: members }, bearer(this.credential)); expect(res.status, JSON.stringify(res.body)).toBe(200); const to: Record<string, Record<string, string>> = {}; for (const member of members) { to[member] = {}; for (const k of res.body.peers[member]!) to[member]![k.device] = await this.seal(k.key, { v: 1, id, kind, from: this.number, to: member, body: text, group }); } const own: Record<string, string> = {}; for (const k of res.body.own) own[k.device] = await this.seal(k.key, { v: 1, id, kind, from: this.number, to: this.number, body: text, group }); return open("POST", "/v1/chat/group/send", { id, kind, group, to, own: Object.keys(own).length ? own : undefined }, bearer(this.credential)); } /** This owner's phone says who is in a group (none: they left it). */ async joinGroup(group: string, members: string[]): Promise<{ status: number; body: Body }> { return open("POST", "/v1/chat/group", { group, members }, bearer(this.credential)); } async inbox(): Promise<Item[]> { const res = await open<{ items: Item[] }>("GET", "/v1/chat/inbox", undefined, bearer(this.credential)); expect(res.status, JSON.stringify(res.body)).toBe(200); return res.body.items; } async ack(items: Item[]): Promise<void> { const res = await open("POST", "/v1/chat/ack", { items: items.map((i) => ({ id: i.id, kind: i.kind })) }, bearer(this.credential)); expect(res.status).toBe(200); } async say(what: "accept" | "refuse" | "block" | "unblock", number: string): Promise<void> { const res = await open("POST", `/v1/chat/${what}`, { number }, bearer(this.credential)); expect(res.status, JSON.stringify(res.body)).toBe(200); } /** A socket ticket, asked for with the device's credential (the core's POST). */ async ticket(): Promise<string> { const res = await open<{ ticket: string }>("POST", "/v1/chat/socket", {}, bearer(this.credential)); expect(res.status, JSON.stringify(res.body)).toBe(200); return res.body.ticket; } /** The socket, opened with a fresh ticket as the app opens it. */ async socket(): Promise<ChatSocket> { const res = await SELF.fetch(`${OPEN}/v1/chat/socket`, { headers: { upgrade: "websocket", authorization: `Bearer ${await this.ticket()}` } }); expect(res.status).toBe(101); const ws = res.webSocket!; ws.accept(); return new ChatSocket(ws); }}/** A device as a keys lookup answers it; `c2` when it speaks c2 (src/chat/chat.ts `ChatKey`). */export interface Sealable { device: string; key: string; c2?: { identity: string; signing: string; sig: string };}export interface Item { id: string; kind: string; peer: string; out: boolean; request: boolean; box: string; at: number; group?: string | null;}export class ChatSocket { frames: Body[] = []; closed = false; readonly ws: WebSocket; constructor(ws: WebSocket) { this.ws = ws; ws.addEventListener("message", (event) => this.frames.push(JSON.parse(String(event.data)) as Body)); ws.addEventListener("close", () => { this.closed = true; }); } items(): Item[] { return this.frames.filter((f) => f.t === "envelope").map((f) => f.item as Item); } async next(count = 1): Promise<Item[]> { await vi.waitFor(() => { if (this.items().length < count) throw new Error(`${this.items().length} of ${count} envelopes`); }, { timeout: 3000, interval: 10 }); return this.items(); } send(frame: Body): void { this.ws.send(JSON.stringify(frame)); }}/** A phone signed in on a number, its chat key published (and its alert token, when given). */export async function chatPhone(number: string, device: string, push?: { platform: "ios" | "android"; token: string }): Promise<ChatPhone> { const credential = await signUp(number, device); const key = await x25519(); const phone = new ChatPhone(number, device, credential, key); const body: Body = { publicKey: phone.publicKey }; if (push) Object.assign(body, push, push.platform === "ios" ? { topic: "com.cottondb.messages.dev", sandbox: true } : {}); const res = await open("POST", "/v1/chat/device", body, bearer(credential)); expect(res.status, JSON.stringify(res.body)).toBe(200); return phone;}/** Let an object-to-object hop finish when nothing will come of it. */export async function settle(): Promise<void> { await new Promise((resolve) => setTimeout(resolve, 150));}/** Wait until a phone's inbox holds `count` items. */export async function arrived(phone: ChatPhone, count = 1): Promise<Item[]> { let items: Item[] = []; await vi.waitFor(async () => { items = await phone.inbox(); if (items.length < count) throw new Error(`${items.length} of ${count} held`); }, { timeout: 3000, interval: 20 }); return items;}