Cotton code
75 lines · 3.6 KB · TypeScriptRaw
/** * The one `c1:` box the Worker makes (20 Nov 2026): who is * calling, sealed for each rung phone's own chat key, so the ring push can * name the caller at once without Apple or Google reading who it is. * * The box is the phone's own scheme (cotton-core chat/seal.rs): X25519 with * an ephemeral key and a "sender" key, HKDF-SHA256, AES-256-GCM, info * `cotton-chat-v1`. The Worker has no lasting chat key and needs none: its * sender key is a second fresh key per box, so the box authenticates nothing * by itself. What vouches for it is the channel: only this Worker can push * through Cotton's APNs and FCM credentials, and the phone opens it only to * name the ring, then joins and hears the caller's number from its own * object. The Worker already knows who calls whom (it routes the ring); the * box only keeps that from the push services. */const INFO = new TextEncoder().encode("cotton-chat-v1");function b64url(bytes: Uint8Array): string {  return btoa(String.fromCharCode(...bytes)).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");}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;}async function pair(): Promise<{ privateKey: CryptoKey; publicRaw: Uint8Array }> {  const made = (await crypto.subtle.generateKey({ name: "X25519" }, false, ["deriveBits"])) as CryptoKeyPair;  return { privateKey: made.privateKey, publicRaw: new Uint8Array((await crypto.subtle.exportKey("raw", made.publicKey)) as ArrayBuffer) };}async function dh(privateKey: CryptoKey, publicRaw: Uint8Array): Promise<Uint8Array> {  const peer = await crypto.subtle.importKey("raw", publicRaw, { name: "X25519" }, false, []);  const bits = new Uint8Array(await crypto.subtle.deriveBits({ name: "X25519", public: peer } as unknown as SubtleCryptoDeriveKeyAlgorithm, privateKey, 256));  if (bits.every((b) => b === 0)) throw new Error("a small-order key");  return bits;}/** `payload` sealed as a `c1:` box for one device's public key (base64url); null when the key is not one. */export async function sealFor(recipientPublic: string, payload: unknown): Promise<string | null> {  try {    const r = unb64url(recipientPublic);    if (r.length !== 32) return null;    const eph = await pair();    const sender = await pair();    const ikm = cat(await dh(eph.privateKey, r), await dh(sender.privateKey, r));    const base = await crypto.subtle.importKey("raw", ikm, "HKDF", false, ["deriveKey"]);    const key = await crypto.subtle.deriveKey({ name: "HKDF", hash: "SHA-256", salt: cat(eph.publicRaw, sender.publicRaw, r), info: INFO }, base, { name: "AES-GCM", length: 256 }, false, ["encrypt"]);    const nonce = crypto.getRandomValues(new Uint8Array(12));    const ct = new Uint8Array(await crypto.subtle.encrypt({ name: "AES-GCM", iv: nonce, additionalData: cat(INFO, sender.publicRaw, r) }, key, new TextEncoder().encode(JSON.stringify(payload))));    return `c1:${b64url(cat(eph.publicRaw, sender.publicRaw, nonce, ct))}`;  } catch {    return null;  }}/** What a ring's box says: the room it is for, who is calling, and whether it is video. */export interface RingHint {  v: 1;  ring: string;  from: string;  video: boolean;  /** The Cotton group the call was placed from: the ring names the group. */  group?: string;}