Cotton code
145 lines · 7.4 KB · TypeScriptRaw
/** * SEALED AT ARRIVAL (e2e rulings R2, 15 Nov 2026): what the * object writes into a sealed table itself (an assistant's MCP write, a pull * it fetched, a lookup it filled) is sealed the moment it arrives, to the * person's arrival public key: an X25519 key each of their devices derives * from the data key, whose public half the object holds in the `seal_key` * row `arrival`. The object never holds a key that opens what it sealed, and * never falls back to clear: with no arrival key held, the write is refused. * *     sealed_enc  "s1:" the sealed columns under a fresh DEK, as a device seals them *     dek_enc     "a1:" the w1 wrap of (DEK || table "\n" id) to the arrival key, its "w1:" dropped *     seal_v      0: no table key wraps it yet; a device's sweep seals it again under one * * The core's twin is crates/cotton-core/src/seal/arrival.rs; both answer * crates/cotton-conformance/vectors/seal/arrival.json byte for byte. */import { bodyAad, bucket, DEK_ENC, SEAL_V, SEALED_ENC, SealError, type SealSpec } from "./seal.ts";type Data = Record<string, unknown>;export const ARRIVAL_PREFIX = "a1:";export const ARRIVAL_ROW = "arrival";export const ARRIVAL_V = 0;const WRAP_INFO = "cotton-vault-wrap-v1";const utf8 = new TextEncoder();/** A PKCS#8 X25519 private key is this prefix and the 32 secret bytes (RFC 8410). */const X25519_PKCS8 = Uint8Array.from([0x30, 0x2e, 0x02, 0x01, 0x00, 0x30, 0x05, 0x06, 0x03, 0x2b, 0x65, 0x6e, 0x04, 0x22, 0x04, 0x20]);function b64url(bytes: Uint8Array): string {  let s = "";  for (const b of bytes) s += String.fromCharCode(b);  return btoa(s).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");}/** A base64url key of 32 bytes, or null. */export function keyFromText(text: unknown): Uint8Array | null {  if (typeof text !== "string" || !/^[A-Za-z0-9_-]{43}$/.test(text)) return null;  const b64 = text.replace(/-/g, "+").replace(/_/g, "/") + "=";  try {    const bytes = Uint8Array.from(atob(b64), (c) => c.charCodeAt(0));    return bytes.length === 32 ? bytes : null;  } catch {    return null;  }}function concat(...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;}/** Canonical JSON (the core's canonical_json): object keys sorted at every depth, no whitespace. */function canonical(value: unknown): string {  if (Array.isArray(value)) return `[${value.map(canonical).join(",")}]`;  if (value && typeof value === "object") {    const keys = Object.keys(value as Data).sort((a, b) => (a < b ? -1 : a > b ? 1 : 0));    return `{${keys.map((k) => `${JSON.stringify(k)}:${canonical((value as Data)[k])}`).join(",")}}`;  }  return JSON.stringify(value ?? null);}async function gcmSeal(key: Uint8Array, nonce: Uint8Array, plain: Uint8Array, aad: Uint8Array): Promise<Uint8Array> {  const k = await crypto.subtle.importKey("raw", key, "AES-GCM", false, ["encrypt"]);  return concat(nonce, new Uint8Array(await crypto.subtle.encrypt({ name: "AES-GCM", iv: nonce, additionalData: aad }, k, plain)));}/** The w1 wrap (cotton-core vault/wrap.rs `wrap_with`) of `plain` to `recipientPub`, with the ephemeral secret and nonce given. */export async function wrapWith(ephemeral: Uint8Array, nonce: Uint8Array, recipientPub: Uint8Array, plain: Uint8Array): Promise<string> {  const pkcs8 = concat(X25519_PKCS8, ephemeral);  const secret = await crypto.subtle.importKey("pkcs8", pkcs8, { name: "X25519" }, true, ["deriveBits"]);  // Typed by the shape read, not the Workers' global JsonWebKey: the scripts' typecheck (node types) holds no such name.  const jwk = (await crypto.subtle.exportKey("jwk", secret)) as { x?: string };  const ephemeralPub = keyFromText(jwk.x);  if (!ephemeralPub) throw new SealError("seal_bad_input", "the ephemeral key has no public half");  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 Parameters<typeof crypto.subtle.deriveBits>[0], secret, 256));  if (shared.every((b) => b === 0)) throw new SealError("seal_bad_input", "the arrival key is not a usable X25519 key");  const ikm = await crypto.subtle.importKey("raw", shared, "HKDF", false, ["deriveBits"]);  const key = new Uint8Array(await crypto.subtle.deriveBits({ name: "HKDF", hash: "SHA-256", salt: concat(ephemeralPub, recipientPub), info: utf8.encode(WRAP_INFO) }, ikm, 256));  const sealed = await gcmSeal(key, nonce, plain, recipientPub);  return b64url(concat(ephemeralPub, sealed));}/** The randomness one arrival seal takes. */export interface ArrivalRandom {  dek: Uint8Array;  bodyNonce: Uint8Array;  ephemeral: Uint8Array;  wrapNonce: Uint8Array;}function fresh(): ArrivalRandom {  const r = (n: number) => crypto.getRandomValues(new Uint8Array(n));  return { dek: r(32), bodyNonce: r(12), ephemeral: r(32), wrapNonce: r(12) };}/** * `data` (a row's columns, plaintext) as the object stores it sealed at * arrival to `arrivalPub`: its clear columns (`id` and the block's `clear`) * as they are, every other column inside the blob. A column the sealer * writes is refused by name. */export async function sealAtArrival(arrivalPub: Uint8Array, databaseId: string, table: string, id: string, spec: SealSpec, data: Data, random: ArrivalRandom = fresh()): Promise<Data> {  const clear: Data = {};  const sealed: Data = {};  for (const [k, v] of Object.entries(data)) {    if (k === SEALED_ENC || k === DEK_ENC || k === SEAL_V) throw new SealError("seal_column_clash", `${k} is written by the sealer`);    if (k === "id" || spec.clear.includes(k)) clear[k] = v;    else sealed[k] = v;  }  const text = utf8.encode(canonical(sealed));  const padded = new Uint8Array(bucket(text.length)).fill(0x20);  padded.set(text);  const body = await gcmSeal(random.dek, random.bodyNonce, padded, utf8.encode(bodyAad(databaseId, table, id)));  const wrapped = await wrapWith(random.ephemeral, random.wrapNonce, arrivalPub, concat(random.dek, utf8.encode(`${table}\n${id}`)));  return { ...clear, [SEALED_ENC]: `s1:${b64url(body)}`, [DEK_ENC]: `${ARRIVAL_PREFIX}${wrapped}`, [SEAL_V]: ARRIVAL_V };}/** Is this stored row one the object sealed at arrival? */export function isArrivalRow(data: Data): boolean {  return typeof data[DEK_ENC] === "string" && (data[DEK_ENC] as string).startsWith(ARRIVAL_PREFIX);}/** * A password's value saved over MCP, sealed to the arrival key (keys DECISIONS.md S3, 25 Nov 2026): the payload as * the one sealed column `payload` of an arrival row of VALUE_TABLE bound to the secret's id, stored as * `a2:<sealed_enc>|<dek_enc>`. The object cannot open it; the owner's device opens it (cotton-core * `seal::arrival::open_arrival_value`) and moves it under the vault key through /v1/secret/rewrap. */export const VALUE_PREFIX = "a2:";export const VALUE_TABLE = "secret_value";export async function sealValueAtArrival(arrivalPub: Uint8Array, databaseId: string, id: string, payload: string, random: ArrivalRandom = fresh()): Promise<string> {  const row = await sealAtArrival(arrivalPub, databaseId, VALUE_TABLE, id, { clear: [], blind: [], blind_exact: [] }, { payload }, random);  return `${VALUE_PREFIX}${String(row[SEALED_ENC])}|${String(row[DEK_ENC])}`;}export function isArrivalValue(sealed: unknown): boolean {  return typeof sealed === "string" && sealed.startsWith(VALUE_PREFIX);}