relay-adoption-bg.ts

28.1 KB · raw

1import { generateKeyPair } from "@stablelib/x25519";2import {3  createPairingInvitation,4  pairingInvitationUrl,5  parsePairingInvitation,6} from "../shared/pairing-invitation";7import {8  openRelayPairingSocket,9  type PairingSocket,10} from "../shared/pairing-dial";11import {12  noiseNKResponder,13  type NoiseNKSession,14} from "../shared/noise-js";15import {16  grantAdoption,17  isAdoptDeviceManifestFrame,18  isAdoptRequest,19  isAdoptSnapshotApplied,20  receiveFrame,21  receiveVaultSnapshot,22  sendFrame,23  sendVaultSnapshot,24  type AdoptionSourceDeps,25} from "../shared/vault-adopt";26import {27  grantAdoptionV2,28  isAdoptRequestV2,29  requestAdoptionV2,30  type AdoptionV2ReceiverDeps,31  type AdoptionV2SourceDeps,32} from "../shared/adoption-protocol";33import {34  derivePairingSAS,35  type PairingTransport,36} from "../shared/pairing-handshake";37import type { PairedDevice } from "../shared/sync-types";38import {39  bytesToHex,40  deriveRendezvousSecret,41  generatePairingRendezvousToken,42} from "../shared/rendezvous";43import {44  buildLocalIdentity,45  getDeviceName,46  getLocalPairingIdentity,47  preparePreVaultIdentity,48  readPreVaultIdentity,49  rotatePreVaultIdentity,50  rotateDeviceId,51} from "./device-identity";52import {53  browserGenerationIo,54  isPostReset,55  onDirectV2PairingEstablished,56} from "./sync-generation";57import {58  hasAdoptionIdentityConflict,59  markLastSyncedAt,60  rotatePairedDeviceIdentity,61  upsertPairedDeviceAndClearRevocation,62} from "./paired-devices";63import { getSyncSettings, relayInForce } from "./sync-settings";64import { activateLicense, getLicenseKey, isProUser } from "./license";65import { createVaultFromRootKey, exportDuressSlotForAdoption, getRootKeyHex, installAdoptedDuressSlot, isUnlocked, rollbackAdoptedVault } from "./vault";66import { deferAutoLockForOperation } from "./alarms";67import { computeVaultId } from "../shared/sync-identity";68import { INITIAL_SYNC_PENDING_DEVICE_KEY } from "../shared/initial-sync";69import { storageRemove, storageSet } from "../shared/storage";70import {71  persistPendingAdoptionHolder,72  persistPendingAdoptionIdentity,73  readPendingAdoptionHolder,74  removePendingAdoptionHolder,75  completePendingAdoptionIdentity,76} from "./pending-adoption-holder";77import { isValidPairSecret, setPairSecret } from "./pair-secrets";78import { createSyncVaultAdapter } from "./sync-vault-adapter";79import { triggerSyncIfReachable } from "./sync-trigger";80import { schedulePostAdoptionSync } from "./sync-alarm";81import type { LocalIdentity } from "../shared/pairing-handshake";8283const SOURCE_WINDOW_MS = 5 * 60 * 1000;8485function push(type: string, payload: unknown): void {86  try {87    const maybe = chrome.runtime.sendMessage({ type, payload }) as unknown;88    if (maybe && typeof (maybe as Promise<unknown>).catch === "function") {89      (maybe as Promise<unknown>).catch(() => undefined);90    }91  } catch {92    // The popup may have closed. The pending approval fails closed on cleanup.93  }94}9596/** Race a promise against a wall-clock deadline; rejects with "timeout". */97function withTimeout<T>(promise: Promise<T>, ms: number): Promise<T> {98  return new Promise<T>((resolve, reject) => {99    const timer = setTimeout(() => reject(new Error("timeout")), ms);100    promise.then(101      (value) => {102        clearTimeout(timer);103        resolve(value);104      },105      (error) => {106        clearTimeout(timer);107        reject(error);108      },109    );110  });111}112113let inFlight = false;114let activeSocket: PairingSocket | null = null;115// Outstanding source-side SAS confirmations, keyed by id. A map (vs the116// receiver's single slot) makes a stale decision from a previous source117// session impossible to land on the current one even if both run on the118// same background worker.119const pendingSourceSasConfirmation = new Map<string, { resolve: (ok: boolean) => void }>();120const pendingReceiverSasConfirmation = new Map<string, { sas: string; resolve: (ok: boolean) => void }>();121122export function isRelayAdoptionSourceInFlight(): boolean {123  return inFlight;124}125126/**127 * Occupy the non-buffering room before returning the invitation to the UI.128 * All long-term key material remains in the background service worker.129 */130export async function startRelayAdoptionSource(): Promise<{131  invitation: string;132}> {133  if (inFlight) throw new Error("adoption_source_in_progress");134  if (!isUnlocked()) throw new Error("vault_locked");135  inFlight = true;136  const releaseAutoLock = deferAutoLockForOperation(SOURCE_WINDOW_MS);137138  let local: Awaited<ReturnType<typeof getLocalPairingIdentity>> | null = null;139  try {140    const settings = await getSyncSettings();141    const relayUrl = relayInForce(settings);142    local = await getLocalPairingIdentity();143    const token = generatePairingRendezvousToken();144    // Source side has the vault — caller checked isUnlocked — so the phone145    // can read the invitation and know it should receive the vault.146    const encoded = createPairingInvitation(relayUrl, token, "populated", bytesToHex(local.publicKey));147    const invitation = parsePairingInvitation(encoded);148    if (!invitation) throw new Error("invitation_generation_failed");149150    const socket = await openRelayPairingSocket(pairingInvitationUrl(invitation));151    activeSocket = socket;152    const readyLocal = local;153    void runSourceSession(154      socket,155      token,156      relayUrl,157      readyLocal,158    ).finally(() => {159      readyLocal.privateKey.fill(0);160      readyLocal.publicKey.fill(0);161      clearState();162      releaseAutoLock();163    });164    return { invitation: encoded };165  } catch (error) {166    local?.privateKey.fill(0);167    local?.publicKey.fill(0);168    clearState();169    releaseAutoLock();170    throw error;171  }172}173174export function cancelRelayAdoptionSource(): void {175  activeSocket?.close();176  clearState();177}178179/**180 * Onboarding pairing request — the empty extension shows a QR and the populated181 * phone scans it. The invitation carries `vaultStatus: "empty"`, which the182 * phone reads to switch into source mode and `grantAdoption` over the183 * established Noise channel. The receiver's `runReceiverSession` accepts the184 * root key and creates a local vault wrapped with the popup-supplied password.185 *186 * `password` is the local-only password the user picked on the "Set a password187 * for this device" screen; it wraps the adopted root key at rest and has no188 * relationship to the source device's password.189 */190export async function startRelayAdoptionReceiver(191  password: string,192): Promise<{ invitation: string }> {193  if (inFlight) throw new Error("adoption_receiver_in_progress");194  if (typeof password !== "string" || password.length === 0) {195    throw new Error("ADOPT_INVALID_PASSWORD");196  }197  inFlight = true;198  try {199    await preparePreVaultIdentity(password);200    const settings = await getSyncSettings();201    const relayUrl = relayInForce(settings);202    const token = generatePairingRendezvousToken();203    const ephemeral = generateKeyPair();204    const encoded = createPairingInvitation(relayUrl, token, "empty", bytesToHex(ephemeral.publicKey));205    const invitation = parsePairingInvitation(encoded);206    if (!invitation) throw new Error("invitation_generation_failed");207    const socket = await openRelayPairingSocket(pairingInvitationUrl(invitation));208    activeSocket = socket;209    void runReceiverSession(210      socket,211      token,212      relayUrl,213      password,214      ephemeral,215    ).finally(() => {216      ephemeral.secretKey.fill(0);217      ephemeral.publicKey.fill(0);218      clearState();219    });220    return { invitation: encoded };221  } catch (error) {222    clearState();223    throw error;224  }225}226227/**228 * Resolves the source-side SAS confirmation by id. Called by the message229 * handler when the popup taps Confirm/Cancel on the source's SAS screen.230 * Returns true if the id matched an in-flight confirmation. Unknown ids231 * (already resolved, timed out, or never existed) are a no-op so a late232 * popup click cannot crash anything.233 */234export function resolveSourceSasConfirmation(id: string, ok: boolean): boolean {235  const pending = pendingSourceSasConfirmation.get(id);236  if (!pending) return false;237  pendingSourceSasConfirmation.delete(id);238  pending.resolve(ok);239  return true;240}241242export function resolveReceiverSasConfirmation(id: string, sas: string, ok: boolean): boolean {243  const pending = pendingReceiverSasConfirmation.get(id);244  if (!pending) return false;245  pendingReceiverSasConfirmation.delete(id);246  pending.resolve(ok && constantTimeEqual(pending.sas, sas));247  return true;248}249250async function runSourceSession(251  socket: PairingSocket,252  expectedToken: string,253  relayUrl: string,254  local: Awaited<ReturnType<typeof getLocalPairingIdentity>>,255): Promise<void> {256  const timeout = setTimeout(() => socket.close(), SOURCE_WINDOW_MS);257  let noise: NoiseNKSession | undefined;258  try {259    const hello = decodeJson<{ type?: unknown; token?: unknown }>(260      await socket.receive(),261    );262    if (hello.type !== "PEACH_HELLO" || typeof hello.token !== "string" ||263        !constantTimeEqual(hello.token, expectedToken)) {264      throw new Error("invalid_invitation");265    }266    socket.send(encodeJson({267      type: "PEACH_HELLO_ACK",268      ephemeralPublicKeyHex: bytesToHex(local.publicKey),269    }));270271    const session = await noiseNKResponder(272      local.privateKey,273      local.publicKey,274      async (bytes) => socket.send(bytes),275      () => socket.receive(),276    );277    noise = session;278    const channel: PairingTransport = {279      async send(plaintext) { socket.send(session.encrypt(plaintext)); },280      async receive() { return session.decrypt(await socket.receive()); },281    };282    const request = await receiveFrame(channel);283    if (!isAdoptRequest(request) && !isAdoptRequestV2(request)) {284      throw new Error("expected_ADOPT_REQUEST");285    }286287    const sourceDeps = buildSourceSessionDeps({288      identity: local.identity,289      rendezvousSecretHex: bytesToHex(deriveRendezvousSecret(session.handshakeHash)),290      relayUrl,291      sas: derivePairingSAS(session.handshakeHash),292    });293    // §11.6: after a secure reset a v1 peer is repair-required, exactly as an294    // outdated sync peer is. Refused before any grant. A new ADOPT_REJECT295    // reason is not an option — §10.3 freezes the set to the two v1 peers296    // already understand — so the refusal is local and the peer simply fails.297    if (isAdoptRequest(request) && (await isPostReset(browserGenerationIo))) {298      push("ADOPTION_SOURCE_RESULT", {299        status: "error",300        error: "peer_protocol_outdated",301      });302      return;303    }304    const device = isAdoptRequestV2(request)305      ? await grantAdoptionV2(channel, request, sourceDeps)306      : await grantAdoption(channel, request, sourceDeps);307    if (!device) {308      push("ADOPTION_SOURCE_RESULT", {309        status: "error",310        error: "adoption_rejected",311      });312      return;313    }314    // If the receiver advertised inline-snapshot support, send the vault now315    // over the same authenticated channel. Best-effort: any failure leaves the316    // receiver to fall back to the sync pipeline triggered below.317    if (request.snapshot_capable === true) {318      try {319        const adapter = createSyncVaultAdapter();320        const entryManifest = await adapter.buildEntryManifest();321        const entryIds = Object.keys(entryManifest);322        const entries =323          entryIds.length > 0 ? await adapter.getEncryptedEntries(entryIds) : {};324        const tombstones = await adapter.buildTombstoneManifest();325        let duressSlot: string | null = null;326        try {327          duressSlot = await exportDuressSlotForAdoption();328        } catch {329          // Duress omission must not fail the whole snapshot.330        }331        await sendVaultSnapshot(channel, entries, tombstones, duressSlot);332333        const applied = await withTimeout(receiveFrame(channel), 15_000);334        if (isAdoptSnapshotApplied(applied)) {335          console.info(336            `[Peach] snapshot applied by receiver: ${applied.entries_received} entries, ${applied.tombstones_received} tombstones`,337          );338        }339340        if (adapter.buildOutgoingDeviceManifest) {341          const manifest = await adapter.buildOutgoingDeviceManifest();342          if (manifest) {343            await sendFrame(channel, { type: "ADOPT_DEVICE_MANIFEST", manifest });344            await withTimeout(receiveFrame(channel), 5_000).catch(() => undefined);345          }346        }347      } catch (snapshotError) {348        if (349          snapshotError instanceof Error &&350          snapshotError.message === "ADOPT_SNAPSHOT_DURESS_FRAME_TOO_LARGE"351        ) {352          throw snapshotError;353        }354        console.info(355          "[Peach] inline snapshot send failed (receiver will use sync pipeline):",356          snapshotError,357        );358      }359    }360    push("ADOPTION_SOURCE_RESULT", { status: "complete" });361    // The Android receiver starts its relay listener as soon as its source362    // record is durable. Immediate best-effort trigger; alarm-based retries363    // cover MV3 service-worker death (setTimeout does not survive it).364    void triggerSyncIfReachable({ reason: "manual", force: true });365    schedulePostAdoptionSync();366  } catch (error) {367    push("ADOPTION_SOURCE_RESULT", {368      status: "error",369      error: error instanceof Error ? error.message : "adoption_failed",370    });371  } finally {372    clearTimeout(timeout);373    noise?.close();374    socket.close();375    pendingSourceSasConfirmation.clear();376  }377}378379/**380 * Browser receives the vault from the phone. The protocol is the mirror of381 * the source side: phone is the Noise initiator and the source of truth for382 * the SAS gate, browser is the responder that creates the vault locally.383 */384async function runReceiverSession(385  socket: PairingSocket,386  expectedToken: string,387  relayUrl: string,388  password: string,389  invitationEphemeral: { secretKey: Uint8Array; publicKey: Uint8Array },390): Promise<void> {391  const timeout = setTimeout(() => socket.close(), SOURCE_WINDOW_MS);392  // The invitation binds the responder static so the initiator can verify the ACK.393  const ephemeral = invitationEphemeral;394  const ephemeralPrivate = ephemeral.secretKey;395  const ephemeralPublic = ephemeral.publicKey;396  let noise: NoiseNKSession | undefined;397  let createdVault = false;398  let protocolError: string | undefined;399  try {400    const hello = decodeJson<{ type?: unknown; token?: unknown }>(401      await socket.receive(),402    );403    if (hello.type !== "PEACH_HELLO" || typeof hello.token !== "string" ||404        !constantTimeEqual(hello.token, expectedToken)) {405      throw new Error("invalid_invitation");406    }407    socket.send(encodeJson({408      type: "PEACH_HELLO_ACK",409      ephemeralPublicKeyHex: bytesToHex(ephemeralPublic),410    }));411412    const session = await noiseNKResponder(413      ephemeralPrivate,414      ephemeralPublic,415      async (bytes) => socket.send(bytes),416      () => socket.receive(),417    );418    noise = session;419    const channel: PairingTransport = {420      async send(plaintext) { socket.send(session.encrypt(plaintext)); },421      async receive() { return session.decrypt(await socket.receive()); },422    };423424    const deviceName = await getDeviceName();425426    const receiverDeps: AdoptionV2ReceiverDeps = {427      deviceName,428      async confirmSas() {429        const sas = derivePairingSAS(session.handshakeHash);430        const id = crypto.randomUUID();431        return waitForReceiverSasConfirmation(id, sas);432      },433      async createVaultFromRootKey(rootKeyHex) {434        // Direct call, not chrome.runtime.sendMessage — a service worker435        // calling sendMessage does not reach its own listener (returns436        // undefined), and the receiver already lives in the same SW context437        // as the vault module. Round-tripping through the message bus was438        // the root cause of "create_vault_no_response".439        const { vaultId } = await createVaultFromRootKey(password, rootKeyHex);440        createdVault = true;441        return { vaultId };442      },443      async applyLicense(license) {444        // Direct call, not chrome.runtime.sendMessage — same sendMessage-to-self445        // issue as createVaultFromRootKey. SW can't reach its own listener.446        await applyTransferredLicense(license);447      },448      async license() {449        return (await isProUser()) ? (await getLicenseKey()) ?? undefined : undefined;450      },451      async rotateLocalIdentity() {452        return await rotatePreVaultIdentity(password);453      },454      async hasSourceIdentityCollision(source) {455        return hasAdoptionIdentityConflict(source.device_id, source.long_term_public_key_hex);456      },457      pairState: {458        rendezvousSecretHex: bytesToHex(deriveRendezvousSecret(session.handshakeHash)),459        relayUrl,460      },461      onError(error) {462        protocolError = error;463      },464      async localIdentity() {465        return await readPreVaultIdentity(password);466      },467      async validateSource() {},468      async upsertPairedDeviceAndClearRevocation(paired: PairedDevice) {469        await storeAdoptedDevice(paired);470      },471    };472    const adoptionResult = await requestAdoptionV2(channel, receiverDeps);473474    if (!adoptionResult) {475      if (createdVault) {476        await rollbackAdoptedVault();477        createdVault = false;478      }479      push("ADOPTION_SOURCE_RESULT", {480        status: "error",481        error: protocolError ?? "adoption_rejected",482      });483      return;484    }485    const { device, snapshotCapable } = adoptionResult;486    // The pairing channel is still open and authenticated — try to pull the487    // vault snapshot inline so the popup transitions immediately instead of488    // waiting on a second sync round. Skip the wait entirely when the source489    // did not echo snapshot_capable: true (pre-C source, or explicit opt-out);490    // fall through to the existing sync pipeline below.491    let snapshotApplied = false;492    if (snapshotCapable) try {493      const snapshot = await withTimeout(receiveVaultSnapshot(channel), 30_000);494      const adapter = createSyncVaultAdapter();495      await adapter.applyEntries(snapshot.entries);496      await adapter.applyTombstones(snapshot.tombstones);497      // Duress install is isolated: a failure here must NOT demote an498      // otherwise-successful entry snapshot to the sync fallback.499      if (snapshot.duressSlot) {500        try {501          await installAdoptedDuressSlot(snapshot.duressSlot);502        } catch (duressError) {503          console.info(504            "[Peach] adopted duress slot install failed (non-fatal):",505            duressError,506          );507        }508      }509      await sendFrame(channel, {510        type: "ADOPT_SNAPSHOT_APPLIED",511        entries_received: Object.keys(snapshot.entries).length,512        tombstones_received: Object.keys(snapshot.tombstones).length,513      });514515      // Optional device graph. Non-fatal and isolated so a manifest timeout or516      // unsupported source cannot demote an otherwise-successful entry snapshot.517      try {518        const manifestFrame = await withTimeout(receiveFrame(channel), 5_000);519        if (520          isAdoptDeviceManifestFrame(manifestFrame) &&521          adapter.applyIncomingDeviceManifest &&522          typeof device.longTermPublicKeyHex === "string" &&523          /^[0-9a-f]{64}$/.test(device.longTermPublicKeyHex)524        ) {525          await adapter.applyIncomingDeviceManifest(526            manifestFrame.manifest,527            hexToBytes(device.longTermPublicKeyHex),528          );529          await sendFrame(channel, { type: "ADOPT_DEVICE_MANIFEST_APPLIED" });530        }531      } catch {532        // The graph arrives via incremental sync instead.533      }534535      await markLastSyncedAt(device.deviceId, Date.now());536      snapshotApplied = true;537    } catch (snapshotError) {538      console.info(539        "[Peach] inline snapshot failed, falling back to sync pipeline:",540        snapshotError,541      );542    }543544    // Adoption has committed identity and vault-key material, but entries have545    // not necessarily crossed yet. Persist the exact source row before telling546    // the popup pairing is complete so a popup close/reopen cannot reveal the547    // temporarily empty receiver vault. The popup clears this only after that548    // row records a successful sync.549    await storageSet(INITIAL_SYNC_PENDING_DEVICE_KEY, device.deviceId).catch(550      () => undefined,551    );552    push("ADOPTION_SOURCE_RESULT", { status: "complete" });553    createdVault = false;554555    if (snapshotApplied) {556      // The snapshot populated the vault and marked the source synced, so the557      // pending marker's job is done — clear it instead of making the popup wait.558      await storageRemove(INITIAL_SYNC_PENDING_DEVICE_KEY).catch(() => undefined);559    } else {560      // Fallback: the existing sync pipeline fills the vault. Immediate561      // best-effort trigger plus alarm-based retries that survive SW death.562      void triggerSyncIfReachable({ reason: "manual", force: true });563      schedulePostAdoptionSync();564    }565  } catch (error) {566    if (createdVault) {567      try {568        await rollbackAdoptedVault();569        createdVault = false;570      } catch (rollbackError) {571        console.error("[Peach] rollback failed:", rollbackError);572      }573    }574    console.error("[Peach] receiver session failed:", error);575    push("ADOPTION_SOURCE_RESULT", {576      status: "error",577      error: error instanceof Error ? error.message : "adoption_failed",578    });579  } finally {580    clearTimeout(timeout);581    noise?.close();582    socket.close();583    ephemeralPrivate.fill(0);584    ephemeralPublic.fill(0);585  }586}587588/**589 * A transferred entitlement is committed only when activation succeeds and590 * the stored value can immediately be re-read as Pro. activateLicense returns591 * a normal Free result for invalid input, so callers must not ignore it.592 */593async function applyTransferredLicense(license: string): Promise<void> {594  const activated = await activateLicense(license);595  if (!activated.valid || activated.plan !== "pro" || !(await isProUser())) {596    throw new Error("license_transfer_failed");597  }598}599600/**601 * Push the SAS to the popup, then block until the popup responds via the602 * `SOURCE_SAS_DECISION` message or the timeout fires. Returns false on603 * timeout or cancel so the adoption aborts before any vault state changes.604 *605 * The pending deferred MUST be installed before the push: a popup-side606 * auto-approver (test mocks, future automation) can synchronously resolve607 * the deferred the moment it sees the SAS push, and a missing slot would608 * drop that approval on the floor.609 */610function waitForReceiverSasConfirmation(611  id: string,612  sas: string,613): Promise<boolean> {614  return new Promise<boolean>((resolve) => {615    const timer = setTimeout(() => {616      pendingReceiverSasConfirmation.delete(id);617      resolve(false);618    }, SOURCE_WINDOW_MS);619    pendingReceiverSasConfirmation.set(id, { sas, resolve: (ok) => {620      clearTimeout(timer);621      resolve(ok);622    } });623    push("ADOPTION_SOURCE_SAS", { id, sas, displayOnly: false });624  });625}626627function waitForSourceSasConfirmation(628  id: string,629  request: { device_name: string },630  sas: string,631): Promise<boolean> {632  return new Promise<boolean>((resolve) => {633    const timer = setTimeout(() => {634      pendingSourceSasConfirmation.delete(id);635      resolve(false);636    }, SOURCE_WINDOW_MS);637    pendingSourceSasConfirmation.set(id, {638      resolve: (ok) => {639        clearTimeout(timer);640        resolve(ok);641      },642    });643    push("ADOPTION_SOURCE_SAS", {644      id,645      sas,646      receiverDeviceName: request.device_name,647    });648  });649}650651/**652 * Opening Add Device in an unlocked extension is the source-side authorization.653 * Announce the SAS for comparison, then let the scanning device's explicit654 * confirmation be the single commit gate. grantAdoption still refuses to send655 * the root key until the receiver returns ADOPT_CONFIRM(true).656 */657function requestConsent(658  request: { device_name: string },659  sas: string,660  id: string,661): Promise<boolean> {662  return waitForSourceSasConfirmation(id, request, sas);663}664665function clearState(): void {666  activeSocket = null;667  inFlight = false;668  pendingSourceSasConfirmation.clear();669  pendingReceiverSasConfirmation.clear();670}671672function constantTimeEqual(a: string, b: string): boolean {673  if (a.length !== b.length) return false;674  let diff = 0;675  for (let i = 0; i < a.length; i++) diff |= a.charCodeAt(i) ^ b.charCodeAt(i);676  return diff === 0;677}678679function encodeJson(value: unknown): Uint8Array {680  return new TextEncoder().encode(JSON.stringify(value));681}682683/**684 * Bind a source session's callbacks to the live session facts.685 *686 * Extracted from the session function so §10.5 can be proven: the test dirties687 * every member and asserts each one reaches its sink. TypeScript already688 * requires the *non-optional* members of the union, but the optional ones --689 * `persistPendingHolder` above all, which is ordering guarantee §10.4.1 -- would690 * silently disappear from an inline literal. This is where that is caught.691 */692export function buildSourceSessionDeps(input: {693  identity: LocalIdentity;694  rendezvousSecretHex: string;695  relayUrl: string | undefined;696  sas: string;697}): AdoptionSourceDeps & AdoptionV2SourceDeps {698  const { identity, rendezvousSecretHex, relayUrl, sas } = input;699  return {700    sourceIdentity: identity,701    pairState: { rendezvousSecretHex, relayUrl },702    async rootKeyHex() {703      // grantAdoption calls this only after local password approval and the704      // receiver's encrypted ADOPT_CONFIRM(true).705      const value = getRootKeyHex();706      if (!value) throw new Error("vault_locked");707      return value;708    },709    async vaultId() {710      const value = getRootKeyHex();711      if (!value) throw new Error("vault_locked");712      const bytes = hexToBytes(value);713      try {714        return await computeVaultId(bytes);715      } finally {716        bytes.fill(0);717      }718    },719    async license() {720      return (await isProUser()) ? ((await getLicenseKey()) ?? undefined) : undefined;721    },722    async applyLicense(license) {723      await applyTransferredLicense(license);724    },725    onConsent: (adoptRequest) => requestConsent(adoptRequest, sas, crypto.randomUUID()),726    persistPendingHolder: persistPendingAdoptionHolder,727    clearPendingHolder: async (adoptRequest) => {728      const current = await readPendingAdoptionHolder();729      if (current?.request.device_id === adoptRequest.device_id) {730        await removePendingAdoptionHolder();731      }732    },733    async upsertPairedDevice(paired) {734      await storeAdoptedDevice(paired);735    },736    hasDeviceIdentityCollision: async (device) =>737      hasAdoptionIdentityConflict(device.deviceId, device.longTermPublicKeyHex ?? ""),738    rotateSourceIdentity: async () => {739      await rotatePairedDeviceIdentity(() => getLocalPairingIdentity({ existingOnly: true }), rotateDeviceId);740      return await buildLocalIdentity();741    },742    persistPendingIdentity: persistPendingAdoptionIdentity,743    async completePendingIdentity(paired: PairedDevice) {744      await completePendingAdoptionIdentity(paired);745    },746    snapshotCapable: () => true,747  };748}749750function decodeJson<T>(value: Uint8Array): T {751  return JSON.parse(new TextDecoder().decode(value)) as T;752}753754/**755 * PB-26-213: an adopted device's secret bypasses the public registry into756 * the encrypted pair-secret record. The registry row stays secretless; when757 * the vault is somehow locked here the row still lands and the next unlock758 * cannot recover this secret — re-pair is the fail-closed path.759 */760async function storeAdoptedDevice(paired: PairedDevice): Promise<void> {761  const secret = paired.rendezvousSecretHex;762  const pub = { ...paired };763  delete pub.rendezvousSecretHex;764  // Validate, persist, and clear the terminal tombstone under one registry765  // mutation so a concurrent revoke cannot recreate or lose the tombstone.766  await upsertPairedDeviceAndClearRevocation(pub);767  // §11.3 REPAIRING → V2_ACTIVE. Anything adopted here is a direct pairing: it768  // came from a grant, not from a manifest vouch, and on a device that has769  // reset it can only be v2 — the post-reset source refuses v1 at the first770  // frame. A device that never reset is untouched by this.771  await onDirectV2PairingEstablished(browserGenerationIo, true);772  if (!isValidPairSecret(secret)) return;773  const masterKeyHex = getRootKeyHex();774  if (!masterKeyHex) return;775  const masterKey = hexToBytes(masterKeyHex);776  try {777    await setPairSecret(paired.deviceId, secret, masterKey);778  } finally {779    masterKey.fill(0);780  }781}782783function hexToBytes(hex: string): Uint8Array {784  const out = new Uint8Array(hex.length / 2);785  for (let i = 0; i < out.length; i++) {786    out[i] = Number.parseInt(hex.slice(i * 2, i * 2 + 2), 16);787  }788  return out;789}