Cotton code
114 lines · 6.4 KB · TypeScriptRaw
/** * A phone's half of sealing, for tests: seal a row as seal-core does * (`seal::row`), make its blind tokens, and build and sign an unlock grant * (`seal::grant::build_grant_with`). Every key is made by the caller or is * seal-core's grant vector; every row is synthetic. */import vector from "../../../crates/cotton-conformance/vectors/seal/grant.json";import { bucket, blindKey, bodyAad, cellTexts, dekAad, exactToken, tableKey, textTokens } from "../src/seal.ts";import { tableFileRoot } from "../src/table_files.ts";import { fromBase64Url, toBase64Url } from "../src/vault.ts";import { unlockStatement } from "../src/window.ts";import { DATABASE_ID } from "./personal.ts";const DEFAULT_DATABASE_ID = DATABASE_ID;const utf8 = new TextEncoder();export const hex = (h: string): Uint8Array => Uint8Array.from(h.match(/../g)!.map((b) => parseInt(b, 16)));/** The grant vector's person key: its public half the phone publishes (`publishPersonKey`), its seed what signs. */export const PERSON_PUBLIC_KEY = vector.person_public_key;export const PERSON_SEED = hex(vector.person_seed_hex);const X25519_PKCS8 = hex("302e020100300506032b656e04220420");const ED25519_PKCS8 = hex("302e020100300506032b657004220420");async function okp(prefix: Uint8Array, secret: Uint8Array, name: "X25519" | "Ed25519", uses: string[]): Promise<{ key: CryptoKey; pub: Uint8Array }> {  const pkcs8 = new Uint8Array(48);  pkcs8.set(prefix);  pkcs8.set(secret, 16);  const key = await crypto.subtle.importKey("pkcs8", pkcs8, { name }, true, uses as Parameters<typeof crypto.subtle.importKey>[4]);  const jwk = (await crypto.subtle.exportKey("jwk", key)) as JsonWebKey;  return { key, pub: fromBase64Url(jwk.x!) };}/** `vault::wrap::wrap_with`. */async function wrapWith(recipientPub: Uint8Array, plain: Uint8Array): Promise<string> {  const eph = await okp(X25519_PKCS8, crypto.getRandomValues(new Uint8Array(32)), "X25519", ["deriveBits"]);  const nonce = crypto.getRandomValues(new Uint8Array(12));  const peer = await crypto.subtle.importKey("raw", recipientPub, { name: "X25519" }, false, []);  const shared = new Uint8Array(await crypto.subtle.deriveBits({ name: "X25519", public: peer } as unknown as SubtleCryptoDeriveKeyAlgorithm, eph.key, 256));  const salt = new Uint8Array(64);  salt.set(eph.pub);  salt.set(recipientPub, 32);  const ikm = await crypto.subtle.importKey("raw", shared, "HKDF", false, ["deriveBits"]);  const k = await crypto.subtle.importKey("raw", await crypto.subtle.deriveBits({ name: "HKDF", hash: "SHA-256", salt, info: utf8.encode("cotton-vault-wrap-v1") }, ikm, 256), "AES-GCM", false, ["encrypt"]);  const body = new Uint8Array(await crypto.subtle.encrypt({ name: "AES-GCM", iv: nonce, additionalData: recipientPub }, k, plain));  const out = new Uint8Array(32 + 12 + body.length);  out.set(eph.pub);  out.set(nonce, 32);  out.set(body, 44);  return `w1:${toBase64Url(out)}`;}function canonical(v: unknown): string {  if (v && typeof v === "object" && !Array.isArray(v)) {    const o = v as Record<string, unknown>;    return `{${Object.keys(o).sort().map((k) => `${JSON.stringify(k)}:${canonical(o[k])}`).join(",")}}`;  }  return JSON.stringify(v);}/** The `unlock_allow` args for a request: TK for every version up to each table's seal_v and BK, wrapped to worker_pub, signed by the vector's person key. */export async function grantFor(o: { dk: Uint8Array; requestId: string; tokenId: string; tables: [string, number][]; minutes: number; workerPub: string; databaseId?: string }): Promise<Record<string, unknown>> {  const DATABASE_ID = o.databaseId ?? DEFAULT_DATABASE_ID;  const keys: Record<string, Record<string, string>> = {};  const blind: Record<string, string> = {};  for (const [t, v] of o.tables) {    keys[t] = {};    for (let n = 1; n <= v; n++) keys[t]![String(n)] = toBase64Url(await tableKey(o.dk, DATABASE_ID, t, n));    blind[t] = toBase64Url(await blindKey(o.dk, DATABASE_ID, t));  }  const files = keys.message ? { files: { message: toBase64Url(await tableFileRoot(o.dk, DATABASE_ID, "message")) } } : {};  const bundle = canonical({ request_id: o.requestId, token_id: o.tokenId, keys, blind, ...files });  const wrapped = await wrapWith(fromBase64Url(o.workerPub), utf8.encode(bundle));  const tables = o.tables.map(([t]) => t).sort();  const person = await okp(ED25519_PKCS8, PERSON_SEED, "Ed25519", ["sign"]);  const statement = await unlockStatement(DATABASE_ID, o.requestId, o.tokenId, tables, o.minutes, wrapped);  const sig = toBase64Url(new Uint8Array(await crypto.subtle.sign({ name: "Ed25519" }, person.key, utf8.encode(statement))));  return { request_id: o.requestId, tables, minutes: o.minutes, wrapped, signer: toBase64Url(person.pub).slice(0, 8), sig };}async function gcm(key: Uint8Array, plain: Uint8Array, aad: string): Promise<string> {  const nonce = crypto.getRandomValues(new Uint8Array(12));  const k = await crypto.subtle.importKey("raw", key, "AES-GCM", false, ["encrypt"]);  const body = new Uint8Array(await crypto.subtle.encrypt({ name: "AES-GCM", iv: nonce, additionalData: utf8.encode(aad) }, k, plain));  const out = new Uint8Array(12 + body.length);  out.set(nonce);  out.set(body, 12);  return toBase64Url(out);}/** A row's sealed columns as a phone seals them: one padded blob under a fresh DEK, the DEK under TK(t, v). */export async function sealRow(dk: Uint8Array, table: string, id: string, v: number, sealed: Record<string, unknown>): Promise<Record<string, unknown>> {  const text = canonical(sealed);  const padded = text + " ".repeat(bucket(utf8.encode(text).length) - utf8.encode(text).length);  const dek = crypto.getRandomValues(new Uint8Array(32));  return {    sealed_enc: `s1:${await gcm(dek, utf8.encode(padded), bodyAad(DATABASE_ID, table, id))}`,    dek_enc: `d1:${await gcm(await tableKey(dk, DATABASE_ID, table, v), dek, dekAad(DATABASE_ID, table, id, v))}`,    seal_v: v,  };}/** A row's blind tokens as a phone makes them (`seal::blind::row_tokens`). */export async function rowTokens(dk: Uint8Array, table: string, spec: { blind?: string[]; blind_exact?: string[] }, row: Record<string, unknown>): Promise<string[]> {  const bk = await blindKey(dk, DATABASE_ID, table);  const out = new Set<string>();  for (const c of spec.blind ?? []) for (const text of cellTexts(row[c])) for (const t of await textTokens(bk, c, text)) out.add(t);  for (const c of spec.blind_exact ?? []) for (const text of cellTexts(row[c])) {    const t = await exactToken(bk, c, text);    if (t) out.add(t);  }  return [...out];}