Cotton code
141 lines · 7.3 KB · TypeScriptRaw
/** * Synthetic people and spaces for the shared-space tests (test/shared-space.test.ts, test/shared-space-gate.test.ts, * test/shared-space-switch.test.ts). The phones' half (minting epoch and record keys, wrapping them, sealing bodies, * signing, sealing files) is cotton-core's; here the objects are handed what those phones would post: opaque `w1:` * wraps, `g1:` keys, `r1:` bodies, `s1:` signatures and f1-shaped bytes. */import { env, runInDurableObject, SELF } from "cloudflare:test";import { expect } from "vitest";import type { Space } from "../src/space/space.ts";import { bearer, OPEN, open } from "./calling.ts";import { chatPhone, type ChatPhone } from "./chat.ts";type Body = Record<string, unknown>;let n = 0;const number = (): string => `+91900007${String(1000 + ++n).padStart(4, "0")}`;export interface Person {  phone: ChatPhone;  slug: string;  number: string;  key: string;  sign: string;  /** The private half of `sign` (Ed25519): what the person's phone signs roster statements with. */  signing: CryptoKey;  credential: string;  ask<T = Body>(method: string, path: string, body?: unknown): Promise<{ status: number; body: T }>;}export function b64url(bytes: Uint8Array): string {  let s = "";  for (const b of bytes) s += String.fromCharCode(b);  return btoa(s).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");}export const opaque = (bytes: number): string => b64url(crypto.getRandomValues(new Uint8Array(bytes)));export const wrap = (): string => `w1:${opaque(80)}`;/** A record as a phone posts it: its key wrapped at `epoch`, its body sealed, its adder's signature. */export function record(id: string, kind: string, album: string, files: string[], epoch: number): Body {  return { id, kind, album, files, key: `g1:${epoch}:${opaque(60)}`, body: `r1:${opaque(90)}`, sig: `s1:${opaque(64)}` };}/** * A roster statement as a phone posts it (`t1:` body `.` signature). The space checks only its chain (space, seq, * prev); the phones verify the signature, so the test's is opaque. */export function statement(space: string, seq: number, prev: string, extra: Body = {}): string {  const body = JSON.stringify({ v: 1, space, seq, prev, kind: "add", ...extra });  return `t1:${b64url(new TextEncoder().encode(body))}.${opaque(64)}`;}/** * A roster statement as `who`'s phone signs it (AUDIT FIX B1: the space verifies it): `by` their member id, signed * with their signing key over "cotton-space-roster-v1\n" + body JSON (cotton-core `seal::shared_roster::sign`). */export async function signed(who: Person, by: string, space: string, seq: number, prev: string, extra: Body = {}): Promise<string> {  const json = JSON.stringify({ v: 1, space, seq, prev, kind: "add", by, ...extra });  const sig = new Uint8Array(await crypto.subtle.sign({ name: "Ed25519" }, who.signing, new TextEncoder().encode(`cotton-space-roster-v1\n${json}`)));  return `t1:${b64url(new TextEncoder().encode(json))}.${b64url(sig)}`;}/** The hash the next statement names: hex SHA-256 of the last statement's text. */export async function hashOf(text: string): Promise<string> {  const digest = await crypto.subtle.digest("SHA-256", new TextEncoder().encode(text));  return [...new Uint8Array(digest)].map((b) => b.toString(16).padStart(2, "0")).join("");}/** A signed-in person whose phone has posted its sharing and signing keys. */export async function person(): Promise<Person> {  const phone = await chatPhone(number(), `space-dev-${n}`);  const slug = (await env.DIRECTORY.get(env.DIRECTORY.idFromName("directory")).lookup(phone.number))!;  const pair = (await crypto.subtle.generateKey({ name: "Ed25519" }, true, ["sign", "verify"])) as CryptoKeyPair;  const sign = b64url(new Uint8Array((await crypto.subtle.exportKey("raw", pair.publicKey)) as ArrayBuffer));  const p: Person = { phone, slug, number: phone.number, key: opaque(32), sign, signing: pair.privateKey, credential: phone.credential, ask: <T = Body>(method: string, path: string, body?: unknown) => open<T>(method, path, body, bearer(phone.credential)) };  const posted = await p.ask("POST", "/v1/send/key", { key: p.key, sign: p.sign });  expect(posted.status, JSON.stringify(posted.body)).toBe(200);  return p;}export async function accept(x: Person, y: Person): Promise<void> {  await x.phone.say("accept", y.number);  await y.phone.say("accept", x.number);}export interface SpaceView {  space: string;  epoch: number;  members: { member: string; number?: string; key: string; sign: string | null; role: string; you: boolean }[];  unwrapped: string[];}/** A space founded by `founder` with `members`, its first key handed out (epoch 1); its id and each person's member id. */export async function found(founder: Person, members: Person[], extra: Body = {}): Promise<{ space: string; id: Record<string, string> }> {  const res = await founder.ask<SpaceView>("POST", "/v1/spaces", { members: members.map((p) => p.number), ...extra });  expect(res.status, JSON.stringify(res.body)).toBe(200);  const space = res.body.space;  const id: Record<string, string> = {};  for (const m of res.body.members) id[m.number!] = m.member;  const first = await founder.ask("POST", `/v1/spaces/${space}/epoch`, { epoch: 1, wraps: Object.fromEntries(res.body.members.map((m) => [m.member, wrap()])) });  expect(first.status, JSON.stringify(first.body)).toBe(200);  return { space, id };}/** A file uploaded to a space by `who`: its id, the bytes, and the write URL it used. */export async function upload(who: Person, space: string, size = 4096, epoch = 1): Promise<{ file: string; bytes: Uint8Array; url: string }> {  const granted = await who.ask<{ file: string; url: string }>("POST", `/v1/spaces/${space}/upload`, { epoch, size });  expect(granted.status, JSON.stringify(granted.body)).toBe(200);  const bytes = crypto.getRandomValues(new Uint8Array(size));  const put = await SELF.fetch(granted.body.url, { method: "PUT", body: bytes, headers: { "content-length": String(size) } });  expect(put.status, await put.clone().text()).toBe(200);  return { file: granted.body.file, bytes, url: granted.body.url };}export function spaceStub(space: string) {  return env.SPACES.get(env.SPACES.idFromName(space));}/** Run SQL in a space's object. */export function inSpace<T>(space: string, run: (sql: SqlStorage, instance: Space) => T | Promise<T>): Promise<T> {  return runInDurableObject(spaceStub(space), (instance: Space, state) => run(state.storage.sql, instance));}/** Everything a space's object keeps, as one string. */export function kept(space: string): Promise<string> {  return inSpace(space, (sql) => {    const tables = sql.exec<{ name: string }>("SELECT name FROM sqlite_master WHERE type = 'table' AND name NOT LIKE '\\_%' ESCAPE '\\' AND name NOT LIKE 'sqlite%'").toArray();    return JSON.stringify(Object.fromEntries(tables.map((t) => [t.name, sql.exec(`SELECT * FROM ${t.name}`).toArray()])));  });}/** A link's secret parts as a phone would make them (the test stands in for the HKDF): auth token, its hash, public key. */export async function linkParts(): Promise<{ id: string; auth: string; hash: string; public: string }> {  const auth = opaque(32);  const digest = await crypto.subtle.digest("SHA-256", new TextEncoder().encode(auth));  const hash = [...new Uint8Array(digest)].map((b) => b.toString(16).padStart(2, "0")).join("");  return { id: opaque(12), auth, hash, public: opaque(32) };}export { OPEN };