sync-vault-adapter.ts

22.9 KB · raw

1// Production adapter that backs `runSyncInitiator` with the live vault.2//3// The coordinator (sync-coordinator.ts) never decrypts vault data; it4// only moves opaque base64 entry blobs and metadata. This adapter is the5// boundary where vault plaintext meets the sync layer — entries leave the6// vault as encrypted envelopes here, and incoming envelopes are decrypted7// here before being merged via `applyMergedRemoteEntries`.8//9// Envelope cipher: AES-GCM with a PER-ENTRY key derived as10//   HKDF-SHA256(ikm = syncMasterKey, salt = "", info = entryId + "\x00" + "sync-entry-v1")11// (random 12B nonce, aad = "peach-sync-entry-v1"). Binding the key to the12// entry id means a ciphertext minted for one entry slot cannot be replayed13// into another: decryptEntryOrNull rejects any envelope whose decrypted14// entry.id does not match the map key it arrived under. Both sides hold the15// same syncMasterKey (same vault) so keys match without prior negotiation. The16// Noise KK reconnect session encrypts the transport on top — the envelope is17// belt-and-braces so a transport-layer leak doesn't expose plaintext entries.18//19// Device-manifest exchange (v2 brief §4.3) is plumbed here. Any admitted20// mesh peer may issue one — see applyVerifiedPeerManifest for why the issuer21// is not restricted by device type or first-pair topology, and for what the22// Noise-authenticated static key gates. docs/mesh-vouching-authority.md is the23// end-to-end trace.2425import { HKDF } from "@stablelib/hkdf";26import { SHA256 } from "@stablelib/sha256";27import type { SyncVaultAdapter } from "./sync-coordinator";28import { getOrCreateDeviceId } from "./device-identity";29import {30  computeVaultId,31  deriveSyncIdentityKeypair,32  deriveSyncSigningKeypair,33  hexToPubkey,34  pubkeyToHex,35} from "../shared/sync-identity";36import {37  buildSignedDeviceManifest,38  verifyDeviceManifest,39} from "../shared/device-manifest";40import { constantTimeEqualHex } from "../shared/constant-time";41import {42  applyMergedRemoteEntries,43  getDeletedEntries,44  getRootKeyHex,45  getEntries,46  getEntryById,47  getVaultVersion,48  isUnlocked,49} from "./vault";50import {51  findPairedDeviceById,52  findPairedDeviceByPubkey,53  isDeviceRevoked,54  listDeviceRevocations,55  listPairedDevices,56  mergeDeviceRevocations,57  removePairedDeviceById,58  upsertPairedDevice,59} from "./paired-devices";60import {61  removePendingVouchedDevice,62} from "./pending-vouched-devices";63import {64  bytesToHex as rendezvousBytesToHex,65  deriveMeshRendezvousSecret,66  normalizeRelayUrl,67} from "../shared/rendezvous";68import { recordSyncAlerts } from "./sync-alerts";69import { SYNC_LIMITS, clampSyncTimestamp } from "../shared/sync-limits";70import type { VaultEntry } from "../shared/types";71import type {72  ManifestDeviceEntry,73  PairedDevice,74  SignedDeviceManifest,75} from "../shared/sync-types";7677// Each entry uses a unique AES-GCM key: HKDF(masterKey, info = entryId + "\x00" + "sync-entry-v1").78// The info binding prevents a ciphertext from one entry slot being replayed into another.79const ENTRY_KEY_INFO_SUFFIX = "sync-entry-v1";80const ENTRY_AAD = "peach-sync-entry-v1";8182export class VaultLockedError extends Error {83  constructor() {84    super("vault_locked");85    this.name = "VaultLockedError";86  }87}8889export function createSyncVaultAdapter(90  context: { deviceName?: string } = {},91): SyncVaultAdapter {92  return {93    async computeVaultId() {94      const master = requireMasterKey();95      return computeVaultId(master);96    },9798    async getOurDeviceId() {99      return getOrCreateDeviceId();100    },101102    async getLocalVersion() {103      return getVaultVersion();104    },105106    async buildEntryManifest() {107      requireUnlocked();108      const manifest: Record<string, number> = {};109      for (const entry of getEntries()) {110        manifest[entry.id] = entry.modifiedAt;111      }112      return manifest;113    },114115    async buildTombstoneManifest() {116      // KNOWN LIMITATION: tombstones accumulate without bound. Every deleted117      // entry leaves a {id, deletedAt} record that persists indefinitely and is118      // sent in every sync session, so a long-lived vault's manifest grows with119      // total deletions, not live entries. Acceptable for now (records are tiny120      // and the trash-retention purge eventually splices the entry array).121      // TODO(tombstone-gc): prune tombstones older than N months once every paired device122      // Algorithm: (1) After SYNC_DONE, record the peer-ack timestamp per tombstone.123      // (2) Once ALL paired devices have ack-ed a tombstone, splice it from the124      // deleted-entries array. (3) Gate on all-devices to prevent resurrection125      // from an offline peer that still holds the entry.126      requireUnlocked();127      const manifest: Record<string, number> = {};128      for (const entry of getDeletedEntries()) {129        if (typeof entry.deletedAt === "number") {130          manifest[entry.id] = entry.deletedAt;131        }132      }133      return manifest;134    },135136    async getEncryptedEntries(entryIds) {137      requireUnlocked();138      const masterKey = requireMasterKey();139      const out: Record<string, string> = {};140      for (const id of entryIds) {141        const entry = getEntryById(id);142        if (!entry) continue;143        const key = await deriveEntryKey(masterKey, id);144        out[id] = await encryptEntry(key, entry);145      }146      return out;147    },148149    async applyEntries(entries) {150      requireUnlocked();151      const entryList = Object.entries(entries);152      // MV-3: bound the batch before any per-entry crypto work.153      if (entryList.length > SYNC_LIMITS.MAX_ENTRY_COUNT) {154        throw new Error(155          `sync entry count ${entryList.length} exceeds limit ${SYNC_LIMITS.MAX_ENTRY_COUNT}`,156        );157      }158      const masterKey = requireMasterKey();159      const decrypted: VaultEntry[] = [];160      for (const [id, envelope] of entryList) {161        // MV-3: per-entry ceiling, checked on the (base64) envelope before162        // decrypting. Base64 inflates by 4/3, so allow that factor.163        if (envelope.length > (SYNC_LIMITS.MAX_ENTRY_PLAINTEXT_BYTES * 4) / 3 + 64) {164          continue; // oversized envelope — skip, never decrypt165        }166        const key = await deriveEntryKey(masterKey, id);167        const entry = await decryptEntryOrNull(key, envelope);168        if (!entry) continue;169        // MV-3: defense in depth — re-measure the decrypted plaintext.170        if (JSON.stringify(entry).length > SYNC_LIMITS.MAX_ENTRY_PLAINTEXT_BYTES) {171          continue;172        }173        // The map key is the authority on id — refuse mismatched envelopes174        // so a swapped envelope can't poison a different entry slot.175        if (entry.id !== id) continue;176        decrypted.push(entry);177      }178      if (decrypted.length > 0) {179        await applyMergedRemoteEntries(decrypted, {}, context);180      }181    },182183    async applyTombstones(tombstones) {184      requireUnlocked();185      const tombstoneList = Object.entries(tombstones);186      // MV-3: bound the tombstone batch before processing.187      if (tombstoneList.length > SYNC_LIMITS.MAX_TOMBSTONE_COUNT) {188        throw new Error(189          `sync tombstone count ${tombstoneList.length} exceeds limit ${SYNC_LIMITS.MAX_TOMBSTONE_COUNT}`,190        );191      }192      const cleaned: Record<string, number> = {};193      for (const [id, ts] of tombstoneList) {194        if (typeof ts === "number" && Number.isFinite(ts) && ts > 0) {195          // HV-1c: clamp before the value participates in any comparison.196          // vault.ts clamps again defensively; clamping here keeps the197          // invariant local to the boundary where peer data enters.198          cleaned[id] = clampSyncTimestamp(ts);199        }200      }201      if (Object.keys(cleaned).length > 0) {202        await applyMergedRemoteEntries([], cleaned, context);203      }204    },205206    async buildOutgoingDeviceManifest() {207      requireUnlocked();208      const masterKey = requireMasterKey();209      const issuerDeviceId = await getOrCreateDeviceId();210      const signing = await deriveSyncSigningKeypair(masterKey, issuerDeviceId);211      const revoked = await listDeviceRevocations();212      const revokedIds = new Set(revoked.map((r) => r.deviceId));213      const devices = (await listPairedDevices())214        .filter((d) => !revokedIds.has(d.deviceId))215        .map(toManifestEntry)216        .filter((d): d is ManifestDeviceEntry => d !== null);217      return buildSignedDeviceManifest(218        issuerDeviceId,219        devices,220        signing.privateKey,221        { revoked },222      );223    },224225    async applyIncomingDeviceManifest(manifest, authenticatedRemoteStaticPublicKey) {226      requireUnlocked();227      // ponytail: temporary mesh-propagation diagnostic, strip before save228      console.info("[Peach diag] applyIncomingDeviceManifest: issuerDeviceId=" + manifest?.body?.issuerDeviceId + " devices=" + (manifest?.body?.devices ?? []).map((d) => d.deviceId).join(",") + " revoked=" + (manifest?.body?.revoked ?? []).length);229      try {230        await applyVerifiedPeerManifest(231          manifest,232          authenticatedRemoteStaticPublicKey,233        );234      } catch (diagError) {235        console.info("[Peach diag] applyVerifiedPeerManifest threw:", diagError);236      }237      const all = await listPairedDevices();238      console.info("[Peach diag] post-manifest paired-devices:", all.map((d) => d.deviceId + "/" + d.trustSource).join(","));239    },240  };241}242243function toManifestEntry(device: PairedDevice): ManifestDeviceEntry | null {244  if (245    !device.deviceId ||246    !device.deviceName ||247    !device.deviceType ||248    !device.longTermPublicKeyHex ||249    !/^[0-9a-f]{64}$/.test(device.longTermPublicKeyHex) ||250    !device.signingPublicKeyHex ||251    !/^[0-9a-f]{64}$/.test(device.signingPublicKeyHex)252  ) {253    return null;254  }255  return {256    deviceId: device.deviceId,257    deviceName: device.deviceName,258    deviceType: device.deviceType,259    longTermPublicKeyHex: device.longTermPublicKeyHex,260    signingPublicKeyHex: device.signingPublicKeyHex,261    wsPort: device.wsPort,262    relayUrl: device.relayUrl,263    pairedAt: device.pairedAt,264  };265}266267/**268 * Apply a device manifest issued by a peer we pair with directly.269 *270 * The issuer used to be required to be an "extension", on the assumption that271 * the extension was the mesh's trust anchor. It is not: the device a fresh272 * install joins through is the one holding the peer list to hand over.273 *274 * The issuer must already be admitted locally as either direct or vouched.275 * That is the decentralisation boundary: an unknown key has no session and no276 * authority, while every authenticated member can propagate the same signed277 * pool without the original hub online. A v3 entry is admitted only when it278 * carries a valid relay route; both endpoints independently derive the same279 * pair-only capability from their vault root and public keys.280 */281async function applyVerifiedPeerManifest(282  manifest: SignedDeviceManifest,283  authenticatedRemoteStaticPublicKey: Uint8Array,284): Promise<void> {285  const issuerId = manifest?.body?.issuerDeviceId;286  if (typeof issuerId !== "string" || !issuerId) return;287288  if (authenticatedRemoteStaticPublicKey.length !== 32) return;289  const authenticatedPubkeyHex = pubkeyToHex(authenticatedRemoteStaticPublicKey);290  const issuer = await findPairedDeviceByPubkey(authenticatedPubkeyHex);291  if (292    !issuer ||293    issuer.deviceId !== issuerId ||294    (295      issuer.trustSource !== "direct" &&296      issuer.trustSource !== "vouched"297    ) ||298    !issuer.signingPublicKeyHex ||299    !/^[0-9a-f]{64}$/.test(issuer.signingPublicKeyHex)300  ) {301    return;302  }303304  let body: Awaited<ReturnType<typeof verifyDeviceManifest>>;305  try {306    body = await verifyDeviceManifest(307      manifest,308      hexToPubkey(issuer.signingPublicKeyHex),309    );310  } catch {311    // Stored key may be stale (older builds persisted the key derived at312    // first-pair and never refreshed it). The signing keypair is deterministic313    // from (masterKey, deviceId) on both sides, so retry once with the locally314    // re-derived pubkey. A genuinely forged signature throws here and is315    // silently rejected — only a stale-but-correct key survives the retry.316    const masterForIssuer = requireMasterKey();317    try {318      const derived = await deriveSyncSigningKeypair(319        masterForIssuer,320        issuer.deviceId,321      );322      body = await verifyDeviceManifest(manifest, derived.publicKeyRaw);323    } catch {324      return;325    } finally {326      masterForIssuer.fill(0);327    }328  }329  if (body.issuerDeviceId !== issuer.deviceId) return;330331  const ourDeviceId = await getOrCreateDeviceId();332  const masterKey = requireMasterKey();333  const localKeys = deriveSyncIdentityKeypair(masterKey, ourDeviceId);334335  try {336    // Revocations are absorbed BEFORE any vouching, so a manifest that both337    // revokes and re-vouches the same device in one payload cannot race itself.338    // A peer may not revoke US — that would let one compromised device sever the339    // whole mesh — so our own id is filtered out first.340    const newlyRevoked = await mergeDeviceRevocations(341      body.revoked.filter((r) => r.deviceId !== ourDeviceId),342    );343    for (const deviceId of newlyRevoked) {344      await removePairedDeviceById(deviceId);345      await removePendingVouchedDevice(deviceId);346      void recordSyncAlerts([347        {348          type: "DEVICE_REVOKED",349          entryId: "",350          entryTitle: deviceId,351          deviceName: issuer.deviceName ?? "paired device",352          timestamp: Date.now(),353        },354      ]);355    }356357    for (const entry of body.devices) {358      if (entry.deviceId === ourDeviceId || entry.deviceId === issuer.deviceId) {359        // ponytail: temporary mesh-propagation diagnostic, strip before save360        console.info("[Peach diag] skip entry (self or issuer):", entry.deviceId);361        continue;362      }363      // Terminal: no manifest re-admits a revoked device. Matched on the key as364      // well as the id, because the id is the issuer's to choose — checking only365      // the id let a revoked key walk back in under a fresh one. The check sits366      // ahead of the existing-device lookup so it also refuses rotating a device367      // we still trust onto a revoked key.368      if (await isDeviceRevoked(entry.deviceId, entry.longTermPublicKeyHex)) {369        // ponytail: temporary mesh-propagation diagnostic, strip before save370        console.info("[Peach diag] skip entry (revoked):", entry.deviceId, "longTerm=" + entry.longTermPublicKeyHex?.slice(0, 12) + "...", "hasRelay=" + !!entry.relayUrl);371        continue;372      }373      const existing = await findPairedDeviceById(entry.deviceId);374      const meshRoute = deriveManifestMeshRoute(375        masterKey,376        localKeys.publicKey,377        entry,378      );379      // ponytail: temporary mesh-propagation diagnostic, strip before save380      if (existing) {381        console.info("[Peach diag] skip entry (existing):", entry.deviceId, "trustSource=" + existing.trustSource);382      } else if (!meshRoute) {383        console.info("[Peach diag] skip entry (no mesh route):", entry.deviceId, "hasRelay=" + !!entry.relayUrl);384      } else {385        console.info("[Peach diag] admit entry:", entry.deviceId, "relay=" + meshRoute.relayUrl);386      }387388      // A v3 manifest from an admitted, KK-authenticated issuer proves389      // same-vault membership and carries enough route material for the two390      // introduced endpoints to derive their own capability. Admit it391      // immediately so a six-device vault converges without keeping the392      // original pairing hub online.393      if (!existing) {394        if (!meshRoute) continue;395        await upsertPairedDevice({396          deviceId: entry.deviceId,397          deviceName: entry.deviceName,398          deviceType: entry.deviceType,399          longTermPublicKeyHex: entry.longTermPublicKeyHex.toLowerCase(),400          signingPublicKeyHex: entry.signingPublicKeyHex.toLowerCase(),401          wsPort: entry.wsPort,402          rendezvousSecretHex: meshRoute.rendezvousSecretHex,403          relayUrl: meshRoute.relayUrl,404          pairedAt: entry.pairedAt,405          trustSource: "vouched",406        });407        await removePendingVouchedDevice(entry.deviceId);408        continue;409      }410411      // MV-8d: a key changing under a stable deviceId is legitimate after a412      // reinstall, but it is exactly what a graph-poisoning attack looks like —413      // signal the user either way, durably (the alert queue survives a closed414      // popup) and live (the broadcast updates an open one).415      if (416        existing.longTermPublicKeyHex &&417        !constantTimeEqualHex(418          existing.longTermPublicKeyHex,419          entry.longTermPublicKeyHex,420        )421      ) {422        // S5: name the device from the LOCAL record, never from the manifest.423        // The issuer is a third party here (its own entry is skipped above), so424        // `entry.deviceName` is an unverified claim about someone else — an425        // attacker who could put it on screen could make its own key rotation426        // read as a rotation on a device the user trusts more.427        const knownName = existing.deviceName ?? entry.deviceName;428        notifyPopup({429          type: "DEVICE_KEY_ROTATED",430          payload: { deviceName: knownName, deviceId: entry.deviceId },431        });432        void recordSyncAlerts([433          {434            type: "DEVICE_KEY_ROTATED",435            entryId: "",436            entryTitle: knownName,437            deviceName: knownName,438            timestamp: Date.now(),439          },440        ]);441      }442443      // Existing device — update in place as before. The name is deliberately444      // NOT taken from the manifest: a device's name is set by that device at445      // pairing, and letting a third-party issuer rewrite it is the rename-then-446      // impersonate half of S5. Self-renames never arrive here anyway.447      await upsertPairedDevice({448        ...existing,449        deviceId: entry.deviceId,450        deviceName: existing.deviceName ?? entry.deviceName,451        deviceType: entry.deviceType,452        longTermPublicKeyHex: entry.longTermPublicKeyHex.toLowerCase(),453        signingPublicKeyHex: entry.signingPublicKeyHex.toLowerCase(),454        pairedAt: existing.pairedAt ?? entry.pairedAt,455        trustSource: existing.trustSource ?? "direct",456        wsPort: existing.wsPort ?? entry.wsPort,457        rendezvousSecretHex:458          existing.trustSource === "vouched" && meshRoute459            ? meshRoute.rendezvousSecretHex460            : existing.rendezvousSecretHex,461        relayUrl:462          existing.trustSource === "vouched" && meshRoute463            ? meshRoute.relayUrl464            : existing.relayUrl,465        lastSyncedAt: existing.lastSyncedAt,466      });467    }468  } finally {469    masterKey.fill(0);470    localKeys.secretKey.fill(0);471  }472}473474function deriveManifestMeshRoute(475  masterKey: Uint8Array,476  localPublicKey: Uint8Array,477  entry: ManifestDeviceEntry,478): { rendezvousSecretHex: string; relayUrl: string } | null {479  try {480    if (!entry.relayUrl) return null;481    const relayUrl = normalizeRelayUrl(entry.relayUrl);482    const secret = deriveMeshRendezvousSecret(483      masterKey,484      localPublicKey,485      hexToPubkey(entry.longTermPublicKeyHex),486    );487    try {488      return {489        rendezvousSecretHex: rendezvousBytesToHex(secret),490        relayUrl,491      };492    } finally {493      secret.fill(0);494    }495  } catch {496    return null;497  }498}499500function notifyPopup(msg: { type: string; payload?: unknown }): void {501  try {502    void chrome.runtime.sendMessage(msg).catch(() => undefined);503  } catch {504    /* popup closed — the durable sync-alert queue remains authoritative */505  }506}507508function requireUnlocked(): void {509  if (!isUnlocked()) throw new VaultLockedError();510}511512// Sync derives everything — vault_id, the Noise static key, the Ed25519513// manifest signing key, and the per-entry envelope keys — from the vault's514// stable root key, NOT the password-derived key. This keeps paired devices'515// identities and envelope keys constant across a master-password change on516// either side (SEV-2-B); two paired devices with independently-rotated517// passwords still share this key and can decrypt each other's entries.518function requireMasterKey(): Uint8Array {519  if (!isUnlocked()) throw new VaultLockedError();520  const hex = getRootKeyHex();521  if (!hex) throw new VaultLockedError();522  return hexToBytes(hex);523}524525async function deriveEntryKey(masterKey: Uint8Array, entryId: string): Promise<CryptoKey> {526  // Null-byte separator (HKDF hardening): entryId cannot contain \x00, so this527  // makes the (entryId, suffix) boundary unambiguous regardless of future id528  // formats. Coordinated wire change — peach-android VaultSyncAdapter derives529  // the identical info; the two MUST stay byte-for-byte in lockstep.530  const info = new TextEncoder().encode(`${entryId}\x00${ENTRY_KEY_INFO_SUFFIX}`);531  const raw = new HKDF(SHA256, masterKey, new Uint8Array(0), info).expand(32);532  return crypto.subtle.importKey(533    "raw",534    raw.buffer as ArrayBuffer,535    { name: "AES-GCM" },536    false,537    ["encrypt", "decrypt"],538  );539}540541async function encryptEntry(key: CryptoKey, entry: VaultEntry): Promise<string> {542  const plaintext = new TextEncoder().encode(JSON.stringify(entry));543  const nonce = crypto.getRandomValues(new Uint8Array(12));544  const aad = new TextEncoder().encode(ENTRY_AAD);545  const ct = await crypto.subtle.encrypt(546    {547      name: "AES-GCM",548      iv: nonce.buffer as ArrayBuffer,549      additionalData: aad.buffer as ArrayBuffer,550      tagLength: 128,551    },552    key,553    plaintext.buffer as ArrayBuffer,554  );555  const ctBytes = new Uint8Array(ct);556  const envelope = new Uint8Array(nonce.length + ctBytes.length);557  envelope.set(nonce, 0);558  envelope.set(ctBytes, nonce.length);559  return bytesToBase64(envelope);560}561562async function decryptEntryOrNull(key: CryptoKey, envelopeB64: string): Promise<VaultEntry | null> {563  try {564    const bytes = base64ToBytes(envelopeB64);565    if (bytes.length < 12 + 16) return null;566    const nonce = bytes.subarray(0, 12);567    const ct = bytes.subarray(12);568    const aad = new TextEncoder().encode(ENTRY_AAD);569    const pt = await crypto.subtle.decrypt(570      {571        name: "AES-GCM",572        iv: nonce.buffer.slice(nonce.byteOffset, nonce.byteOffset + nonce.byteLength) as ArrayBuffer,573        additionalData: aad.buffer as ArrayBuffer,574        tagLength: 128,575      },576      key,577      ct.buffer.slice(ct.byteOffset, ct.byteOffset + ct.byteLength) as ArrayBuffer,578    );579    const json = new TextDecoder().decode(pt);580    const parsed = JSON.parse(json);581    if (!parsed || typeof parsed !== "object" || typeof parsed.id !== "string") return null;582    return parsed as VaultEntry;583  } catch {584    return null;585  }586}587588function hexToBytes(hex: string): Uint8Array {589  if (hex.length % 2 !== 0) throw new Error("hex length must be even");590  const out = new Uint8Array(hex.length / 2);591  for (let i = 0; i < out.length; i++) {592    out[i] = parseInt(hex.slice(i * 2, i * 2 + 2), 16);593  }594  return out;595}596597function bytesToBase64(bytes: Uint8Array): string {598  let bin = "";599  for (let i = 0; i < bytes.length; i++) bin += String.fromCharCode(bytes[i]);600  return btoa(bin);601}602603function base64ToBytes(b64: string): Uint8Array {604  const bin = atob(b64);605  const out = new Uint8Array(bin.length);606  for (let i = 0; i < bin.length; i++) out[i] = bin.charCodeAt(i);607  return out;608}