Cotton code
87 lines · 5.6 KB · TypeScriptRaw
/** * A test's stand-in for a phone's arrival key (e2e rulings R2): a fixed * synthetic X25519 secret, its public half to hand the object, and a device's * opening of a file the object sealed at arrival (src/arrival_file.ts), so a * test can say what bytes were kept without the object ever opening them. */const SECRET = new Uint8Array(32).fill(0x2a);const X25519_PKCS8 = Uint8Array.from([0x30, 0x2e, 0x02, 0x01, 0x00, 0x30, 0x05, 0x06, 0x03, 0x2b, 0x65, 0x6e, 0x04, 0x22, 0x04, 0x20]);const utf8 = new TextEncoder();const fromB64url = (s: string): Uint8Array => Uint8Array.from(atob(s.replace(/-/g, "+").replace(/_/g, "/") + "=".repeat((4 - (s.length % 4)) % 4)), (c) => c.charCodeAt(0));async function secretKey(): Promise<CryptoKey> {  const pkcs8 = new Uint8Array(X25519_PKCS8.length + 32);  pkcs8.set(X25519_PKCS8);  pkcs8.set(SECRET, X25519_PKCS8.length);  return crypto.subtle.importKey("pkcs8", pkcs8, { name: "X25519" }, true, ["deriveBits"]);}/** The arrival public key, base64url: what a test hands the object as a phone would (`seal_key` row `arrival`). */export async function arrivalPub(): Promise<string> {  return ((await crypto.subtle.exportKey("jwk", await secretKey())) as JsonWebKey).x!;}/** A file the object sealed at arrival for `objectKey`, opened as a device holding the arrival secret opens it. */export async function openArrivalFile(stored: Uint8Array, objectKey: string): Promise<Uint8Array> {  if (new TextDecoder().decode(stored.subarray(0, 4)) !== "CTA1") throw new Error("not an arrival file");  const n = new DataView(stored.buffer, stored.byteOffset).getUint16(4, false);  const wrap = fromB64url(new TextDecoder().decode(stored.subarray(6, 6 + n)));  const ephemeral = wrap.subarray(0, 32);  const recipient = fromB64url(await arrivalPub());  const peer = await crypto.subtle.importKey("raw", ephemeral, { name: "X25519" }, false, []);  const shared = new Uint8Array(await crypto.subtle.deriveBits({ name: "X25519", public: peer } as unknown as SubtleCryptoDeriveKeyAlgorithm, await secretKey(), 256));  const salt = new Uint8Array(64);  salt.set(ephemeral);  salt.set(recipient, 32);  const ikm = await crypto.subtle.importKey("raw", shared, "HKDF", false, ["deriveBits"]);  const kek = new Uint8Array(await crypto.subtle.deriveBits({ name: "HKDF", hash: "SHA-256", salt, info: utf8.encode("cotton-vault-wrap-v1") }, ikm, 256));  const kekKey = await crypto.subtle.importKey("raw", kek, "AES-GCM", false, ["decrypt"]);  const bound = new Uint8Array(await crypto.subtle.decrypt({ name: "AES-GCM", iv: wrap.subarray(32, 44), additionalData: recipient }, kekKey, wrap.subarray(44)));  if (new TextDecoder().decode(bound.subarray(32)) !== `f1\n${objectKey}`) throw new Error("the wrap names another file");  const fk = await crypto.subtle.importKey("raw", bound.subarray(0, 32), "AES-GCM", false, ["decrypt"]);  const inner = stored.subarray(6 + n);  if (new TextDecoder().decode(inner.subarray(0, 4)) !== "CTF1") throw new Error("no f1 file inside");  const prefix = inner.subarray(4, 11);  const parts: Uint8Array[] = [];  const sealedPart = 64 * 1024 + 16;  const body = inner.subarray(11);  const count = Math.max(1, Math.ceil(body.length / sealedPart));  for (let i = 0; i < count; i++) {    const iv = new Uint8Array(12);    iv.set(prefix);    new DataView(iv.buffer).setUint32(7, i, false);    iv[11] = i === count - 1 ? 1 : 0;    parts.push(new Uint8Array(await crypto.subtle.decrypt({ name: "AES-GCM", iv, additionalData: utf8.encode(`f1|${objectKey}`) }, fk, body.subarray(i * sealedPart, (i + 1) * sealedPart))));  }  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;}/** A row the object sealed at arrival (src/arrival.ts), opened as a device holding the arrival secret opens it: its sealed columns. */export async function openArrivalRow(data: Record<string, unknown>, aad: string, table: string, id: string): Promise<Record<string, unknown>> {  const dek = String(data.dek_enc);  if (!dek.startsWith("a1:")) throw new Error("not sealed at arrival");  const wrap = fromB64url(dek.slice(3));  const ephemeral = wrap.subarray(0, 32);  const recipient = fromB64url(await arrivalPub());  const peer = await crypto.subtle.importKey("raw", ephemeral, { name: "X25519" }, false, []);  const shared = new Uint8Array(await crypto.subtle.deriveBits({ name: "X25519", public: peer } as unknown as SubtleCryptoDeriveKeyAlgorithm, await secretKey(), 256));  const salt = new Uint8Array(64);  salt.set(ephemeral);  salt.set(recipient, 32);  const ikm = await crypto.subtle.importKey("raw", shared, "HKDF", false, ["deriveBits"]);  const kek = new Uint8Array(await crypto.subtle.deriveBits({ name: "HKDF", hash: "SHA-256", salt, info: utf8.encode("cotton-vault-wrap-v1") }, ikm, 256));  const kekKey = await crypto.subtle.importKey("raw", kek, "AES-GCM", false, ["decrypt"]);  const bound = new Uint8Array(await crypto.subtle.decrypt({ name: "AES-GCM", iv: wrap.subarray(32, 44), additionalData: recipient }, kekKey, wrap.subarray(44)));  if (new TextDecoder().decode(bound.subarray(32)) !== `${table}\n${id}`) throw new Error("the wrap names another row");  const rowKey = await crypto.subtle.importKey("raw", bound.subarray(0, 32), "AES-GCM", false, ["decrypt"]);  const body = fromB64url(String(data.sealed_enc).replace(/^s1:/, ""));  const plain = await crypto.subtle.decrypt({ name: "AES-GCM", iv: body.subarray(0, 12), additionalData: utf8.encode(aad) }, rowKey, body.subarray(12));  return JSON.parse(new TextDecoder().decode(plain).trimEnd()) as Record<string, unknown>;}