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 93 }94}959697function 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;115116117118119const 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}125126127128129130export 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 145 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}178179180181182183184185186187188189190export 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}226227228229230231232233234export 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 294 295 296 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 315 316 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 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 362 363 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}378379380381382383384async 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 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 435 436 437 438 439 const { vaultId } = await createVaultFromRootKey(password, rootKeyHex);440 createdVault = true;441 return { vaultId };442 },443 async applyLicense(license) {444 445 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 487 488 489 490 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 498 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 516 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 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 545 546 547 548 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 557 558 await storageRemove(INITIAL_SYNC_PENDING_DEVICE_KEY).catch(() => undefined);559 } else {560 561 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}587588589590591592593async 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}599600601602603604605606607608609610function 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}650651652653654655656657function 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}682683684685686687688689690691692export 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 704 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}753754755756757758759760async function storeAdoptedDevice(paired: PairedDevice): Promise<void> {761 const secret = paired.rendezvousSecretHex;762 const pub = { ...paired };763 delete pub.rendezvousSecretHex;764 765 766 await upsertPairedDeviceAndClearRevocation(pub);767 768 769 770 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}