relay-adoption-bg.test.ts

48.2 KB · raw

1import { beforeEach, describe, expect, it, vi } from "vitest";2import { padSyncFrame } from "../shared/sync-padding";34const mocks = vi.hoisted(() => ({5  openSocket: vi.fn(),6  getLocalIdentity: vi.fn(),7  getDeviceName: vi.fn(),8  getRootKeyHex: vi.fn(),9  upsert: vi.fn(),10  clearRevocation: vi.fn(),11  hasIdentityConflict: vi.fn(),12  rotateDeviceId: vi.fn(),13  rotatePairedDeviceIdentity: vi.fn(async (_load: unknown, rotate: () => Promise<string>) => rotate()),14  setPairSecret: vi.fn(),15  pushes: [] as Array<{ type: string; payload: unknown }>,16  triggerSync: vi.fn(),17  createVault: vi.fn(),18  activateLicense: vi.fn(),19  isProUser: vi.fn(),20  getLicenseKey: vi.fn(),21  localIdentity: vi.fn(),22  rollbackVault: vi.fn(),23  createSyncAdapter: vi.fn(),24  __applyIncomingDeviceManifest: vi.fn(),25  releaseAutoLock: vi.fn(),26  deferAutoLock: vi.fn(),27  storage: new Map<string, string>(),28  storageSet: vi.fn(),29  storageGet: vi.fn(),30  storageRemove: vi.fn(),31  sasDecisions: [] as Array<{ id: string; ok: boolean }>,32  isPostReset: vi.fn(),33  markRepair: vi.fn(),34}));3536vi.mock("../shared/pairing-dial", () => ({37  openRelayPairingSocket: mocks.openSocket,38}));3940vi.mock("../shared/noise-js", () => ({41  noiseNKResponder: vi.fn(async () => ({42    handshakeHash: new Uint8Array(32).fill(7),43    encrypt: (bytes: Uint8Array) => bytes,44    decrypt: (bytes: Uint8Array) => bytes,45    close: vi.fn(),46  })),47}));4849vi.mock("../shared/rendezvous", async (importOriginal) => {50  const actual = await importOriginal<typeof import("../shared/rendezvous")>();51  return {52    ...actual,53    generatePairingRendezvousToken: () => "AAECAwQFBgcICQoLDA0ODw",54  };55});565758vi.mock("./device-identity", () => ({59  getLocalPairingIdentity: async () => ({60    identity: {61      deviceId: "test-device",62      deviceName: "Test",63      deviceType: "extension",64      longTermPublicKeyHex: "aa".repeat(32),65      vaultId: "bb".repeat(32),66    },67    privateKey: new Uint8Array(32).fill(7),68    publicKey: new Uint8Array(32).fill(8),69  }),70  getDeviceName: mocks.getDeviceName,71  buildLocalIdentity: mocks.localIdentity,72  preparePreVaultIdentity: vi.fn(async () => undefined),73  readPreVaultIdentity: mocks.localIdentity,74  rotatePreVaultIdentity: mocks.localIdentity,75  rotateDeviceId: mocks.rotateDeviceId,76}));7778vi.mock("./sync-settings", async (importOriginal) => ({79  ...(await importOriginal<typeof import("./sync-settings")>()),80  getSyncSettings: async () => ({81    mode: "public" as const,82    relayUrl: "wss://relay.peachpasswords.com",83  }),84}));8586vi.mock("./license", () => ({87  isProUser: mocks.isProUser,88  getLicenseKey: mocks.getLicenseKey,89  activateLicense: mocks.activateLicense,90}));9192vi.mock("./vault", () => ({93  isUnlocked: vi.fn(() => true),94  getRootKeyHex: mocks.getRootKeyHex,95  createVaultFromRootKey: mocks.createVault,96  rollbackAdoptedVault: mocks.rollbackVault,97  exportDuressSlotForAdoption: vi.fn(async () => null),98  installAdoptedDuressSlot: vi.fn(async () => undefined),99}));100101vi.mock("../shared/sync-identity", async (importOriginal) => {102  // Partial mock: the manifest test needs the REAL deriveSyncSigningKeypair /103  // pubkeyToHex to build a verifiable signed manifest (2026-08-04: this test104  // was orphaned inside the rendezvous mock factory and never ran; the mock105  // below had since lost the real exports).106  const actual = await importOriginal<typeof import("../shared/sync-identity")>();107  return {108    ...actual,109    computeVaultId: vi.fn(async () => "b".repeat(64)),110  };111});112113vi.mock("../shared/storage", () => ({114  storageSet: mocks.storageSet,115  storageGet: mocks.storageGet,116  storageRemove: mocks.storageRemove,117  storageClear: vi.fn(async () => mocks.storage.clear()),118}));119const chromeStorage = {120  local: {121    get: async (key: string) => ({ [key]: await mocks.storageGet(key) }),122    set: async (items: Record<string, string>) => {123      for (const [key, value] of Object.entries(items)) await mocks.storageSet(key, value);124    },125    remove: async (key: string) => mocks.storageRemove(key),126    clear: async () => mocks.storage.clear(),127  },128};129vi.mock("./paired-devices", () => ({130  upsertPairedDevice: mocks.upsert,131  upsertPairedDeviceAndClearRevocation: mocks.upsert,132  clearDeviceRevocation: mocks.clearRevocation,133  hasAdoptionIdentityConflict: mocks.hasIdentityConflict,134  rotatePairedDeviceIdentity: mocks.rotatePairedDeviceIdentity,135}));136137vi.mock("./pair-secrets", () => ({138  setPairSecret: mocks.setPairSecret,139  isValidPairSecret: (value: unknown): value is string =>140    typeof value === "string" && /^[0-9a-f]{64}$/.test(value),141}));142143vi.mock("./sync-trigger", () => ({144  triggerSyncIfReachable: mocks.triggerSync,145}));146147vi.mock("./sync-generation", () => ({148  browserGenerationIo: {},149  isPostReset: mocks.isPostReset,150  onDirectV2PairingEstablished: mocks.markRepair,151}));152153vi.mock("./alarms", () => ({154  deferAutoLockForOperation: mocks.deferAutoLock,155}));156157vi.mock("./sync-vault-adapter", () => ({158  createSyncVaultAdapter: mocks.createSyncAdapter,159}));160161import {162  cancelRelayAdoptionSource,163  startRelayAdoptionSource,164} from "./relay-adoption-bg";165166const encode = (value: unknown) =>167  new TextEncoder().encode(JSON.stringify(value));168169function adoptionV2Frames(options: {170  rootKeyHex: string;171  vaultId: string;172  deviceId?: string;173  deviceName?: string;174  longTermPublicKeyHex?: string;175  signingPublicKeyHex?: string;176  license?: string;177  snapshotCapable?: boolean;178}): unknown[] {179  const license = options.license ?? "PPK-test";180  return [181    { type: "ADOPT_CONFIRM_REQUIRED" },182    {183      type: "ADOPT_PREPARE",184      device_id: options.deviceId ?? "phone-source-id",185      device_name: options.deviceName ?? "June's phone",186      device_type: "android",187      long_term_public_key_hex: options.longTermPublicKeyHex ?? "99".repeat(32),188      signing_public_key_hex: options.signingPublicKeyHex ?? "aa".repeat(32),189      vault_id: options.vaultId,190      relay_url: "wss://relay.peachpasswords.com",191      license,192      snapshot_capable: options.snapshotCapable,193    },194    {195      type: "ADOPT_GRANT",196      root_key_hex: options.rootKeyHex,197      vault_id: options.vaultId,198      license,199    },200    { type: "ADOPT_COMPLETE" },201  ];202}203204function socketWithFrames(205  frames: unknown[],206  options: { closeOnEmpty?: boolean } = {},207) {208  const queue = frames.map((frame) => {209    const encoded = encode(frame);210    // PB-26-604: snapshot frames are bucket-padded before Noise.211    return (frame as { type?: string }).type === "ADOPT_SNAPSHOT"212      ? padSyncFrame(encoded)213      : encoded;214  });215  return {216    send: vi.fn(),217    receive: vi.fn(async () => {218      const next = queue.shift();219      if (!next) {220        // A real peer closes the channel once it runs out of frames; model221        // that so the receiver's post-ADOPT_APPLIED snapshot read rejects fast222        // and falls back to the sync pipeline instead of hanging on a timeout.223        if (options.closeOnEmpty) throw new Error("socket_closed");224        return new Promise<Uint8Array>(() => undefined);225      }226      return next;227    }),228    close: vi.fn(),229    closedBeforeFrame: vi.fn(() => false),230  };231}232233async function waitForPush(type: string): Promise<void> {234  await vi.waitFor(() => {235    expect(mocks.pushes.some((message) => message.type === type)).toBe(true);236  });237}238239beforeEach(() => {240  mocks.pushes.length = 0;241  mocks.sasDecisions.length = 0;242  mocks.openSocket.mockReset();243  mocks.getLocalIdentity.mockReset();244  mocks.getRootKeyHex.mockReset();245  mocks.upsert.mockReset();246  mocks.clearRevocation.mockReset();247  mocks.clearRevocation.mockResolvedValue(undefined);248  mocks.hasIdentityConflict.mockReset();249  mocks.hasIdentityConflict.mockResolvedValue(false);250  mocks.rotateDeviceId.mockReset();251  mocks.rotateDeviceId.mockResolvedValue(undefined);252  mocks.setPairSecret.mockReset();253  mocks.triggerSync.mockReset();254  mocks.triggerSync.mockResolvedValue(undefined);255  mocks.isPostReset.mockReset();256  mocks.isPostReset.mockResolvedValue(false);257  mocks.markRepair.mockReset();258  mocks.markRepair.mockResolvedValue(undefined);259  mocks.releaseAutoLock.mockReset();260  mocks.deferAutoLock.mockReset();261  mocks.deferAutoLock.mockReturnValue(mocks.releaseAutoLock);262  mocks.storage.clear();263  mocks.storageSet.mockReset();264  mocks.storageSet.mockImplementation(async (key: string, value: string) => {265    mocks.storage.set(key, value);266  });267  mocks.storageGet.mockReset();268  mocks.storageGet.mockImplementation(async (key: string) => mocks.storage.get(key) ?? null);269  mocks.storageRemove.mockReset();270  mocks.storageRemove.mockImplementation(async (key: string) => {271    mocks.storage.delete(key);272  });273  mocks.isProUser.mockReset();274  mocks.isProUser.mockResolvedValue(true);275  mocks.getLicenseKey.mockReset();276  mocks.getLicenseKey.mockResolvedValue("PPK-source");277  mocks.getLocalIdentity.mockResolvedValue({278    identity: {279      deviceId: "browser-source",280      deviceName: "June's Browser",281      deviceType: "extension",282      longTermPublicKeyHex: "a".repeat(64),283      vaultId: "b".repeat(64),284    },285    privateKey: new Uint8Array(32).fill(1),286    publicKey: new Uint8Array(32).fill(2),287  });288  mocks.getRootKeyHex.mockReturnValue("c".repeat(64));289  mocks.upsert.mockResolvedValue(undefined);290  mocks.setPairSecret.mockResolvedValue(undefined);291  const applyIncomingDeviceManifest = vi.fn(async () => undefined);292    mocks.__applyIncomingDeviceManifest = applyIncomingDeviceManifest;293    mocks.createSyncAdapter.mockReturnValue({294      buildEntryManifest: vi.fn(async () => ({})),295      getEncryptedEntries: vi.fn(async () => ({})),296      buildTombstoneManifest: vi.fn(async () => ({})),297      applyEntries: vi.fn(async () => undefined),298      applyTombstones: vi.fn(async () => undefined),299      buildOutgoingDeviceManifest: vi.fn(async () => null),300      applyIncomingDeviceManifest,301    });302  Object.defineProperty(globalThis, "chrome", {303    configurable: true,304    value: {305    runtime: {306      async sendMessage(message: { type: string; payload: unknown }) {307        mocks.pushes.push(message);308        // The source flow waits for the popup to send SOURCE_SAS_DECISION before309        // forwarding the root key. The receiver test overrides this mock and310        // resolves the decision itself; the source tests rely on this default311        // auto-approver so the happy-path test reaches the ADOPT_IDENTITY frame.312        if (message.type === "ADOPTION_SOURCE_SAS") {313          const p = message.payload as { id?: string; sas?: string; displayOnly?: boolean };314          if (typeof p?.id === "string" && typeof p.sas === "string") {315            if (p.displayOnly === false) {316              const { resolveReceiverSasConfirmation } = await import("./relay-adoption-bg");317              resolveReceiverSasConfirmation(p.id, p.sas, true);318            } else {319              const { resolveSourceSasConfirmation } = await import("./relay-adoption-bg");320              mocks.sasDecisions.push({ id: p.id, ok: true });321              resolveSourceSasConfirmation(p.id, true);322            }323          }324        }325        return Promise.resolve();326      },327    },328    },329  });330});331332describe("relay adoption source background boundary", () => {333  it("shows the SAS and waits for the popup's single confirmation", async () => {334    const socket = socketWithFrames([335      {336        type: "PEACH_HELLO",337        token: "AAECAwQFBgcICQoLDA0ODw",338      },339      {340        type: "ADOPT_REQUEST",341        device_id: "request-only-label",342        device_name: "June's phone",343        device_type: "android",344      },345      { type: "ADOPT_CONFIRM", confirmed: true },346      {347        type: "ADOPT_IDENTITY",348        device_id: "android-receiver",349        device_name: "June's phone",350        device_type: "android",351        long_term_public_key_hex: "d".repeat(64),352      },353      { type: "ADOPT_APPLIED" },354    ]);355    mocks.openSocket.mockResolvedValue(socket);356357    const { resolveSourceSasConfirmation } = await import("./relay-adoption-bg");358    const sasIds: string[] = [];359    Object.defineProperty(globalThis, "chrome", {360      configurable: true,361      value: {362        storage: chromeStorage,363        runtime: {364          async sendMessage(message: { type: string; payload: unknown }) {365            mocks.pushes.push(message);366            if (message.type === "ADOPTION_SOURCE_SAS") {367              const p = message.payload as { id?: string };368              if (typeof p?.id === "string") {369                // Hold the SAS gate open until the test explicitly approves370                // it — this proves the source flow waits for the popup.371                sasIds.push(p.id);372              }373              return Promise.resolve();374            }375            return Promise.resolve();376          },377        },378      },379    });380    void resolveSourceSasConfirmation; // imported for the post-approval call below381382    const started = await startRelayAdoptionSource();383    expect(started.invitation).toMatch(/^peach-pair-v2:/);384    expect(mocks.deferAutoLock).toHaveBeenCalledWith(5 * 60 * 1000);385    await waitForPush("ADOPTION_SOURCE_SAS");386    // The adoption must NOT be complete yet — the popup's SAS decision is the387    // prerequisite for forwarding the root key.388    await vi.waitFor(() => {389      expect(mocks.sasDecisions.length).toBe(0);390    });391    expect(mocks.getRootKeyHex).not.toHaveBeenCalled();392    expect(mocks.upsert).not.toHaveBeenCalled();393394    // Approve the SAS; the adoption should now proceed and complete.395    const id = sasIds[0];396    expect(typeof id).toBe("string");397    resolveSourceSasConfirmation(id, true);398    mocks.sasDecisions.push({ id, ok: true });399400    await waitForPush("ADOPTION_SOURCE_RESULT");401402    await vi.waitFor(() => expect(mocks.releaseAutoLock).toHaveBeenCalled());403404    expect(mocks.getRootKeyHex).toHaveBeenCalled();405    expect(mocks.upsert).toHaveBeenCalledWith(expect.objectContaining({406      deviceId: "android-receiver",407      relayUrl: "wss://relay.peachpasswords.com",408    }));409    // PB-26-213: the registry row stays secretless; the secret bypasses it410    // into the encrypted pair-secret record.411    const sourceRow = mocks.upsert.mock.calls[0]?.[0] as Record<string, unknown>;412    expect(sourceRow.rendezvousSecretHex).toBeUndefined();413    expect(mocks.setPairSecret).toHaveBeenCalledWith(414      "android-receiver",415      expect.stringMatching(/^[0-9a-f]{64}$/),416      expect.any(Uint8Array),417    );418    expect(mocks.pushes).toContainEqual({419      type: "ADOPTION_SOURCE_RESULT",420      payload: { status: "complete" },421    });422    expect(mocks.triggerSync).toHaveBeenCalledWith({423      reason: "manual",424      force: true,425    });426    const sentTypes = socket.send.mock.calls427      .map(([bytes]) => {428        try {429          return JSON.parse(new TextDecoder().decode(bytes as Uint8Array)).type;430        } catch {431          return undefined;432        }433      });434    expect(sentTypes).toContain("ADOPT_COMPLETE");435  });436437  it("refuses a v1 request without granting once this device has reset", async () => {438    const socket = socketWithFrames([439      { type: "PEACH_HELLO", token: "AAECAwQFBgcICQoLDA0ODw" },440      {441        type: "ADOPT_REQUEST",442        device_id: "legacy-label",443        device_name: "Old phone",444        device_type: "android",445      },446    ]);447    mocks.openSocket.mockResolvedValue(socket);448    mocks.isPostReset.mockResolvedValue(true);449450    await startRelayAdoptionSource();451    await waitForPush("ADOPTION_SOURCE_RESULT");452453    expect(mocks.pushes).toContainEqual({454      type: "ADOPTION_SOURCE_RESULT",455      payload: { status: "error", error: "peer_protocol_outdated" },456    });457    expect(mocks.getRootKeyHex).not.toHaveBeenCalled();458    expect(mocks.upsert).not.toHaveBeenCalled();459    const sentTypes = socket.send.mock.calls.map(([bytes]) => {460      try {461        return JSON.parse(new TextDecoder().decode(bytes as Uint8Array)).type;462      } catch {463        return undefined;464      }465    });466    expect(sentTypes).not.toContain("ADOPT_GRANT");467  });468469  it("still runs the v1 transcript before a reset", async () => {470    const socket = socketWithFrames([471      { type: "PEACH_HELLO", token: "AAECAwQFBgcICQoLDA0ODw" },472      {473        type: "ADOPT_REQUEST",474        device_id: "legacy-label",475        device_name: "Old phone",476        device_type: "android",477      },478      { type: "ADOPT_CONFIRM", confirmed: true },479      {480        type: "ADOPT_IDENTITY",481        device_id: "android-receiver",482        device_name: "Old phone",483        device_type: "android",484        long_term_public_key_hex: "d".repeat(64),485      },486      { type: "ADOPT_APPLIED" },487    ]);488    mocks.openSocket.mockResolvedValue(socket);489    mocks.isPostReset.mockResolvedValue(false);490491    await startRelayAdoptionSource();492    await waitForPush("ADOPTION_SOURCE_RESULT");493494    // Non-ejectable, not withdrawn: the v1 path is unchanged until the reset.495    expect(mocks.getRootKeyHex).toHaveBeenCalled();496    expect(mocks.pushes).not.toContainEqual({497      type: "ADOPTION_SOURCE_RESULT",498      payload: { status: "error", error: "peer_protocol_outdated" },499    });500  });501502  it("fails adoption without sending snapshot frames when duress is oversized", async () => {503    const socket = socketWithFrames([504      { type: "PEACH_HELLO", token: "AAECAwQFBgcICQoLDA0ODw" },505      {506        type: "ADOPT_REQUEST",507        device_id: "request-only-label",508        device_name: "June's phone",509        device_type: "android",510        snapshot_capable: true,511      },512      { type: "ADOPT_CONFIRM", confirmed: true },513      {514        type: "ADOPT_IDENTITY",515        device_id: "android-receiver",516        device_name: "June's phone",517        device_type: "android",518        long_term_public_key_hex: "d".repeat(64),519      },520      { type: "ADOPT_APPLIED" },521    ]);522    mocks.openSocket.mockResolvedValue(socket);523    const { exportDuressSlotForAdoption } = await import("./vault");524    vi.mocked(exportDuressSlotForAdoption).mockResolvedValueOnce(525      "x".repeat(768 * 1024),526    );527528    await startRelayAdoptionSource();529    await waitForPush("ADOPTION_SOURCE_RESULT");530531    expect(mocks.pushes).toContainEqual({532      type: "ADOPTION_SOURCE_RESULT",533      payload: {534        status: "error",535        error: "ADOPT_SNAPSHOT_DURESS_FRAME_TOO_LARGE",536      },537    });538    expect(mocks.pushes).not.toContainEqual(expect.objectContaining({539      type: "ADOPTION_SOURCE_RESULT",540      payload: expect.objectContaining({ status: "complete" }),541    }));542    const sentTypes = socket.send.mock.calls.map(([bytes]) =>543      JSON.parse(new TextDecoder().decode(bytes as Uint8Array)).type,544    );545    expect(sentTypes).not.toContain("ADOPT_SNAPSHOT");546    expect(mocks.triggerSync).not.toHaveBeenCalled();547  });548549  it("sends no snapshot frames and completes via sync fallback when the vault exceeds the inline budget", async () => {550    // PB-26-206: an over-budget snapshot is never partially sent or silently551    // truncated — the source completes adoption and the sync pipeline carries552    // the entries instead.553    const socket = socketWithFrames([554      { type: "PEACH_HELLO", token: "AAECAwQFBgcICQoLDA0ODw" },555      {556        type: "ADOPT_REQUEST",557        device_id: "request-only-label",558        device_name: "June's phone",559        device_type: "android",560        snapshot_capable: true,561      },562      { type: "ADOPT_CONFIRM", confirmed: true },563      {564        type: "ADOPT_IDENTITY",565        device_id: "android-receiver",566        device_name: "June's phone",567        device_type: "android",568        long_term_public_key_hex: "d".repeat(64),569      },570      { type: "ADOPT_APPLIED" },571      // The receiver's ADOPT_SNAPSHOT_APPLIED ack never arrives (nothing is572      // sent); the source must not hang on it — withTimeout resolves the wait573      // via the sync fallback path below.574      { type: "ADOPT_SNAPSHOT_APPLIED", entries_received: 0, tombstones_received: 0 },575    ]);576    mocks.openSocket.mockResolvedValue(socket);577    // 16 envelopes of ~674 KiB ≈ 10.8 MiB > 10 MiB aggregate budget.578    const envelope = "c".repeat(690_000);579    const entries: Record<string, string> = {};580    for (let i = 0; i < 16; i++) entries[`big-${i}`] = envelope;581    mocks.createSyncAdapter.mockReturnValue({582      buildEntryManifest: vi.fn(async () => Object.fromEntries(583        Object.keys(entries).map((id) => [id, 1]),584      )),585      getEncryptedEntries: vi.fn(async () => entries),586      buildTombstoneManifest: vi.fn(async () => ({})),587      applyEntries: vi.fn(async () => undefined),588      applyTombstones: vi.fn(async () => undefined),589      buildOutgoingDeviceManifest: vi.fn(async () => null),590      applyIncomingDeviceManifest: vi.fn(async () => undefined),591    });592593    await startRelayAdoptionSource();594    await waitForPush("ADOPTION_SOURCE_RESULT");595596    expect(mocks.pushes).toContainEqual({597      type: "ADOPTION_SOURCE_RESULT",598      payload: expect.objectContaining({ status: "complete" }),599    });600    const sentTypes = socket.send.mock.calls.map(([bytes]) =>601      JSON.parse(new TextDecoder().decode(bytes as Uint8Array)).type,602    );603    expect(sentTypes).not.toContain("ADOPT_SNAPSHOT");604    // Sync fallback ran so the entries still reach the receiver.605    expect(mocks.triggerSync).toHaveBeenCalledWith({ reason: "manual", force: true });606  });607608  it("fails closed when the popup rejects the SAS", async () => {609    const socket = socketWithFrames([610      {611        type: "PEACH_HELLO",612        token: "AAECAwQFBgcICQoLDA0ODw",613      },614      {615        type: "ADOPT_REQUEST",616        device_id: "request-only-label",617        device_name: "New phone",618        device_type: "android",619      },620      { type: "ADOPT_CONFIRM", confirmed: false },621    ]);622    mocks.openSocket.mockResolvedValue(socket);623624    const { resolveSourceSasConfirmation } = await import("./relay-adoption-bg");625    let pendingId: string | undefined;626    Object.defineProperty(globalThis, "chrome", {627      configurable: true,628      value: {629        runtime: {630          sendMessage(message: { type: string; payload: unknown }) {631            mocks.pushes.push(message);632            if (message.type === "ADOPTION_SOURCE_SAS") {633              const p = message.payload as { id?: string };634              if (typeof p?.id === "string") pendingId = p.id;635            }636            return Promise.resolve();637          },638        },639      },640    });641642    await startRelayAdoptionSource();643    await waitForPush("ADOPTION_SOURCE_SAS");644    expect(typeof pendingId).toBe("string");645    resolveSourceSasConfirmation(pendingId!, false);646    mocks.sasDecisions.push({ id: pendingId!, ok: false });647648    await waitForPush("ADOPTION_SOURCE_RESULT");649650    expect(mocks.getRootKeyHex).not.toHaveBeenCalled();651    expect(mocks.upsert).not.toHaveBeenCalled();652    expect(mocks.pushes).toContainEqual({653      type: "ADOPTION_SOURCE_RESULT",654      payload: { status: "error", error: "adoption_rejected" },655    });656  });657658  it("rejects before reading the root key when neither peer has Pro", async () => {659    const socket = socketWithFrames([660      {661        type: "PEACH_HELLO",662        token: "AAECAwQFBgcICQoLDA0ODw",663      },664      {665        type: "ADOPT_REQUEST",666        device_id: "free-receiver",667        device_name: "Free phone",668        device_type: "android",669      },670      { type: "ADOPT_CONFIRM", confirmed: true },671    ]);672    mocks.isProUser.mockResolvedValue(false);673    mocks.getLicenseKey.mockResolvedValue(undefined);674    mocks.openSocket.mockResolvedValue(socket);675676    await startRelayAdoptionSource();677    await waitForPush("ADOPTION_SOURCE_RESULT");678679    expect(mocks.getRootKeyHex).not.toHaveBeenCalled();680    expect(mocks.upsert).not.toHaveBeenCalled();681    expect(mocks.pushes).toContainEqual({682      type: "ADOPTION_SOURCE_RESULT",683      payload: { status: "error", error: "ADOPT_PRO_REQUIRED" },684    });685    const sentFrames = socket.send.mock.calls.flatMap(([bytes]) => {686      try {687        return [JSON.parse(new TextDecoder().decode(bytes as Uint8Array))];688      } catch {689        return [];690      }691    });692    expect(sentFrames).toContainEqual({693      type: "ADOPT_REJECT",694      reason: "ADOPT_PRO_REQUIRED",695    });696  });697698  it("fails closed when the user never answers the SAS", async () => {699    // vi.useFakeTimers is unsafe with the live noise/socket mocks (they700    // schedule real work), so we hold the SAS gate open by never resolving701    // the deferred and then cancel the session. clearState must drop the702    // pending SAS so it doesn't pin the relay room open for the next run.703    const socket = socketWithFrames([]);704    mocks.openSocket.mockResolvedValue(socket);705706    Object.defineProperty(globalThis, "chrome", {707      value: {708        storage: chromeStorage,709        runtime: {710          sendMessage(message: { type: string; payload: unknown }) {711            mocks.pushes.push(message);712            return Promise.resolve();713          },714        },715      },716    });717718    await startRelayAdoptionSource();719    cancelRelayAdoptionSource();720721    expect(socket.close).toHaveBeenCalled();722    expect(mocks.getRootKeyHex).not.toHaveBeenCalled();723    expect(mocks.upsert).not.toHaveBeenCalled();724  });725726  it("cancelling the source screen closes the room without reading the root", async () => {727    const socket = socketWithFrames([]);728    mocks.openSocket.mockResolvedValue(socket);729730    await startRelayAdoptionSource();731    cancelRelayAdoptionSource();732733    expect(socket.close).toHaveBeenCalled();734    expect(mocks.getRootKeyHex).not.toHaveBeenCalled();735    expect(mocks.upsert).not.toHaveBeenCalled();736  });737});738739describe("relay adoption receiver background", () => {740  beforeEach(async () => {741    // The receiver session runs in the background via `void runReceiverSession`;742    // it doesn't get awaited by the caller and can leave `inFlight` set if the743    // socket fixture didn't deliver PEACH_HELLO. Reset explicitly so each test744    // starts from a clean state.745    const { cancelRelayAdoptionSource } = await import("./relay-adoption-bg");746    cancelRelayAdoptionSource();747    mocks.pushes.length = 0;748    mocks.openSocket.mockReset();749    mocks.getDeviceName.mockReset();750    mocks.getDeviceName.mockResolvedValue("Receiver Browser");751    mocks.createVault.mockReset();752    mocks.createVault.mockResolvedValue({ vaultId: "ee".repeat(32) });753    mocks.activateLicense.mockReset();754    mocks.activateLicense.mockResolvedValue({ valid: true, plan: "pro" });755    mocks.isProUser.mockReset();756    mocks.isProUser.mockResolvedValue(true);757    mocks.getLicenseKey.mockReset();758    mocks.getLicenseKey.mockResolvedValue(undefined);759    mocks.localIdentity.mockReset();760    mocks.localIdentity.mockResolvedValue({761      deviceId: "receiver-id",762      deviceName: "Receiver Browser",763      deviceType: "extension",764      longTermPublicKeyHex: "11".repeat(32),765      signingPublicKeyHex: "22".repeat(32),766    });767    mocks.rollbackVault.mockReset();768    mocks.rollbackVault.mockResolvedValue(undefined);769    mocks.storageSet.mockReset();770    mocks.storageSet.mockImplementation(async (key: string, value: string) => {771      mocks.storage.set(key, value);772    });773    mocks.upsert.mockReset();774    mocks.upsert.mockResolvedValue(undefined);775    mocks.setPairSecret.mockReset();776    mocks.setPairSecret.mockResolvedValue(undefined);777    mocks.triggerSync.mockReset();778    mocks.triggerSync.mockResolvedValue(undefined);779    mocks.openSocket.mockResolvedValue(socketWithFrames([]));780    Object.defineProperty(globalThis, "chrome", {781      value: {782        storage: chromeStorage,783        runtime: {784          async sendMessage(message: { type: string; payload?: unknown }) {785            mocks.pushes.push({ type: message.type, payload: message.payload });786            if (message.type === "ADOPTION_SOURCE_SAS") {787              const p = message.payload as { id?: string; sas?: string; displayOnly?: boolean };788              if (p.displayOnly === false && typeof p.id === "string" && typeof p.sas === "string") {789                const { resolveReceiverSasConfirmation } = await import("./relay-adoption-bg");790                resolveReceiverSasConfirmation(p.id, p.sas, true);791              }792            }793            return { ok: true };794          },795          onMessage: {796            addListener() { /* no-op */ },797            removeListener() { /* no-op */ },798          },799        },800      },801    });802  });803804  it("opens a relay socket and returns an empty invitation", async () => {805    const { startRelayAdoptionReceiver } = await import("./relay-adoption-bg");806    const started = await startRelayAdoptionReceiver("receiver-password");807    expect(started.invitation).toMatch(/^peach-pair-v2:/);808    // The QR carries vault:"empty" so the phone knows to act as source.809    const decoded = decodeInvitation(started.invitation);810    expect(decoded?.vault).toBe("empty");811    expect(mocks.openSocket).toHaveBeenCalled();812  });813814  it("rejects an empty password", async () => {815    const { startRelayAdoptionReceiver } = await import("./relay-adoption-bg");816    await expect(startRelayAdoptionReceiver("")).rejects.toThrow("ADOPT_INVALID_PASSWORD");817  });818819  it("surfaces the Pro-required rejection without creating a vault", async () => {820    mocks.openSocket.mockResolvedValue(socketWithFrames([821      { type: "PEACH_HELLO", token: "AAECAwQFBgcICQoLDA0ODw" },822      { type: "ADOPT_CONFIRM_REQUIRED" },823      { type: "ADOPT_REJECT", reason: "ADOPT_PRO_REQUIRED" },824    ]));825826    const { startRelayAdoptionReceiver } = await import("./relay-adoption-bg");827    await startRelayAdoptionReceiver("receiver-password");828    await waitForPush("ADOPTION_SOURCE_RESULT");829830    expect(mocks.createVault).not.toHaveBeenCalled();831    expect(mocks.rollbackVault).not.toHaveBeenCalled();832    expect(mocks.pushes).toContainEqual({833      type: "ADOPTION_SOURCE_RESULT",834      payload: { status: "error", error: "ADOPT_PRO_REQUIRED" },835    });836  });837838  it("the receiver wires requestAdoption, not grantAdoption", async () => {839    // The receiver's protocol position is the opposite of the source side:840    // it sends ADOPT_REQUEST, the phone returns ADOPT_GRANT with the root key.841    // Assert this by watching what lands on socket.send: the receiver's842    // outbound ADOPT_* traffic is ADOPT_REQUEST + ADOPT_CONFIRM + ADOPT_IDENTITY843    // + ADOPT_APPLIED. ADOPT_GRANT only ever belongs to the source side.844    const rootKeyHex = "f0".repeat(32);845    const vaultId = "b".repeat(64);846    const socket = socketWithFrames([847      { type: "PEACH_HELLO", token: "AAECAwQFBgcICQoLDA0ODw" },848      ...adoptionV2Frames({ rootKeyHex, vaultId }),849    ], { closeOnEmpty: true });850    mocks.openSocket.mockResolvedValue(socket);851    mocks.createVault.mockResolvedValue({ vaultId });852853    const { startRelayAdoptionReceiver } = await import("./relay-adoption-bg");854    Object.defineProperty(globalThis, "chrome", {855      value: {856        storage: chromeStorage,857        runtime: {858          async sendMessage(message: { type: string; payload?: unknown }) {859            mocks.pushes.push({ type: message.type, payload: message.payload });860            if (message.type === "ADOPTION_SOURCE_SAS") {861              const p = message.payload as { id?: string; sas?: string; displayOnly?: boolean };862              if (p.displayOnly === false && typeof p.id === "string" && typeof p.sas === "string") {863                const { resolveReceiverSasConfirmation } = await import("./relay-adoption-bg");864                resolveReceiverSasConfirmation(p.id, p.sas, true);865              }866            }867            return { ok: true };868          },869          onMessage: { addListener: () => undefined, removeListener: () => undefined },870        },871      },872    });873    await startRelayAdoptionReceiver("receiver-password");874    await waitForPush("ADOPTION_SOURCE_RESULT");875876    const sentTypes = (socket.send as unknown as { mock: { calls: unknown[][] } })877      .mock.calls878      .map(([bytes]) => {879        try {880          return JSON.parse(new TextDecoder().decode(bytes as Uint8Array)).type;881        } catch {882          return undefined;883        }884      });885    // ADOPT_REQUEST is the first adoption-protocol frame out of this side;886    // ADOPT_GRANT is the source side's frame and must never appear here.887    expect(sentTypes).toContain("ADOPT_REQUEST_V2");888    expect(sentTypes).not.toContain("ADOPT_GRANT");889  });890891  it("completes the handshake end-to-end: vault created → paired", async () => {892    // Wire the receiver's noise mock and SAS gate together so the full893    // requestAdoption protocol runs against an in-memory phone that sends894    // PEACH_HELLO, then ADOPT_CONFIRM(true), ADOPT_GRANT, ADOPT_COMPLETE.895    // The mocked noise is pass-through (encrypt = decrypt = identity), so896    // frames land as ordinary JSON.897    const rootKeyHex = "f0".repeat(32);898    // computeVaultId and createVaultFromRootKey both return "b".repeat(64);899    // the grant's vault_id is set to the same so the protocol proceeds.900    const vaultId = "b".repeat(64);901    const frames = [902      { type: "PEACH_HELLO", token: "AAECAwQFBgcICQoLDA0ODw" },903      ...adoptionV2Frames({ rootKeyHex, vaultId }),904    ];905    mocks.createVault.mockResolvedValue({ vaultId });906    mocks.openSocket.mockResolvedValue(socketWithFrames(frames, { closeOnEmpty: true }));907908    // Replace the chrome.runtime mock for this one test and approve the displayed SAS.909    Object.defineProperty(globalThis, "chrome", {910      value: {911        storage: chromeStorage,912        runtime: {913          async sendMessage(message: { type: string; payload?: unknown }) {914            mocks.pushes.push({ type: message.type, payload: message.payload });915            if (message.type === "ADOPTION_SOURCE_SAS") {916              const p = message.payload as { id?: string; sas?: string; displayOnly?: boolean };917              if (p.displayOnly === false && typeof p.id === "string" && typeof p.sas === "string") {918                const { resolveReceiverSasConfirmation } = await import("./relay-adoption-bg");919                resolveReceiverSasConfirmation(p.id, p.sas, true);920              }921            }922            return { ok: true };923          },924          onMessage: {925            addListener: () => undefined,926            removeListener: () => undefined,927          },928        },929      },930    });931932    const { startRelayAdoptionReceiver } = await import("./relay-adoption-bg");933    await startRelayAdoptionReceiver("receiver-password");934935    await waitForPush("ADOPTION_SOURCE_RESULT");936937    // The receiver displays its locally derived SAS and requires confirmation.938    expect(mocks.pushes).toContainEqual({939      type: "ADOPTION_SOURCE_SAS",940      payload: expect.objectContaining({941        sas: expect.stringMatching(/^\d{8}$/),942        displayOnly: false,943      }),944    });945946    // The vault module was called directly with the popup-supplied password947    // and the root key granted by the phone.948    expect(mocks.createVault).toHaveBeenCalledWith("receiver-password", rootKeyHex);949950    // License activation, identity derivation, and pairing persistence all951    // call their modules directly from the service worker.952    expect(mocks.activateLicense).toHaveBeenCalledWith("PPK-test");953    expect(mocks.isProUser).toHaveBeenCalled();954    expect(mocks.localIdentity).toHaveBeenCalled();955    expect(mocks.upsert).toHaveBeenCalledWith(expect.objectContaining({956      deviceId: "phone-source-id",957    }));958    const receiverRow = mocks.upsert.mock.calls[0]?.[0] as Record<string, unknown>;959    expect(receiverRow.rendezvousSecretHex).toBeUndefined();960    expect(mocks.setPairSecret).toHaveBeenCalledWith(961      "phone-source-id",962      expect.stringMatching(/^[0-9a-f]{64}$/),963      expect.any(Uint8Array),964    );965    expect(mocks.storageSet).toHaveBeenCalledWith(966      "peach_initial_sync_pending_device_id",967      "phone-source-id",968    );969    expect(mocks.rollbackVault).not.toHaveBeenCalled();970971    // The terminal state is "complete" — the popup can transition to success.972    expect(mocks.pushes).toContainEqual({973      type: "ADOPTION_SOURCE_RESULT",974      payload: { status: "complete" },975    });976  });977978  it("rolls back and refuses completion when a carried Pro license is not activated", async () => {979    const rootKeyHex = "f0".repeat(32);980    const vaultId = "b".repeat(64);981    mocks.createVault.mockResolvedValue({ vaultId });982    mocks.activateLicense.mockResolvedValue({ valid: false, plan: "free" });983    mocks.isProUser.mockResolvedValue(false);984    mocks.openSocket.mockResolvedValue(socketWithFrames([985      { type: "PEACH_HELLO", token: "AAECAwQFBgcICQoLDA0ODw" },986      ...adoptionV2Frames({ rootKeyHex, vaultId, license: "PPK-invalid" }),987    ]));988989    const { startRelayAdoptionReceiver } = await import("./relay-adoption-bg");990    await startRelayAdoptionReceiver("receiver-password");991    await waitForPush("ADOPTION_SOURCE_RESULT");992993    expect(mocks.rollbackVault).toHaveBeenCalledOnce();994    expect(mocks.localIdentity).toHaveBeenCalled();995    expect(mocks.upsert).not.toHaveBeenCalled();996    expect(mocks.pushes).toContainEqual(expect.objectContaining({997      type: "ADOPTION_SOURCE_RESULT",998      payload: expect.objectContaining({999        status: "error",1000        error: "license_transfer_failed",1001      }),1002    }));1003  });10041005  it("rolls back a newly created vault when a later adoption step fails", async () => {1006    const rootKeyHex = "f0".repeat(32);1007    const vaultId = "b".repeat(64);1008    mocks.createVault.mockResolvedValue({ vaultId });1009    mocks.upsert.mockRejectedValue(new Error("pair_persist_failed"));1010    mocks.openSocket.mockResolvedValue(socketWithFrames([1011      { type: "PEACH_HELLO", token: "AAECAwQFBgcICQoLDA0ODw" },1012      ...adoptionV2Frames({ rootKeyHex, vaultId }),1013    ]));10141015    const { startRelayAdoptionReceiver } = await import("./relay-adoption-bg");1016    await startRelayAdoptionReceiver("receiver-password");1017    await waitForPush("ADOPTION_SOURCE_RESULT");10181019    expect(mocks.rollbackVault).toHaveBeenCalledOnce();1020    expect(mocks.upsert).toHaveBeenCalledOnce();1021    expect(mocks.pushes).toContainEqual(expect.objectContaining({1022      type: "ADOPTION_SOURCE_RESULT",1023      payload: expect.objectContaining({ status: "error", error: "pair_persist_failed" }),1024    }));1025  });10261027  it("skips inline snapshot wait when grant lacks snapshot_capable and falls through to sync", async () => {1028    // The source's ADOPT_GRANT does not echo snapshot_capable (pre-C source).1029    // The receiver should skip the 30-second inline snapshot wait entirely1030    // and fall through to the sync pipeline — no receiveVaultSnapshot call.1031    const rootKeyHex = "f0".repeat(32);1032    const vaultId = "b".repeat(64);1033    mocks.createVault.mockResolvedValue({ vaultId });1034    mocks.openSocket.mockResolvedValue(socketWithFrames([1035      { type: "PEACH_HELLO", token: "AAECAwQFBgcICQoLDA0ODw" },1036      ...adoptionV2Frames({1037        rootKeyHex,1038        vaultId,1039        deviceId: "old-phone-id",1040        deviceName: "Old phone",1041      }),1042    ], { closeOnEmpty: true }));10431044    const { startRelayAdoptionReceiver } = await import("./relay-adoption-bg");1045    await startRelayAdoptionReceiver("receiver-password");1046    await waitForPush("ADOPTION_SOURCE_RESULT");10471048    // Sync fallback ran immediately (no 30s wait).1049    expect(mocks.triggerSync).toHaveBeenCalledWith({ reason: "manual", force: true });1050    // Adoption completed successfully.1051    expect(mocks.pushes).toContainEqual(expect.objectContaining({1052      type: "ADOPTION_SOURCE_RESULT",1053      payload: expect.objectContaining({ status: "complete" }),1054    }));1055    // The initial sync pending marker was set (not cleared — no snapshot applied).1056    expect(mocks.storageSet).toHaveBeenCalledWith(1057      "peach_initial_sync_pending_device_id",1058      "old-phone-id",1059    );1060  });10611062  it("applies the source's device manifest after the snapshot, then acks", async () => {1063    // Mesh propagation: a 3rd browser that completes an adoption with a1064    // snapshot-capable source must also receive the source's signed device1065    // manifest and forward it to the sync adapter before the receiver1066    // resolves. The relay stays an opaque forwarder, so the whole path1067    // lives in `relay-adoption-bg.ts` and `sync-vault-adapter.ts`.1068    const rootKeyHex = "f0".repeat(32);1069    const vaultId = "b".repeat(64);1070    const longTermPubkeyHex = "99".repeat(32);1071    const { buildSignedDeviceManifest } = await import("../shared/device-manifest");1072    const { deriveSyncSigningKeypair } = await import(1073      "../shared/legacy-identity-derivation.test-support"1074    );1075    const { pubkeyToHex } = await import("../shared/sync-identity");1076    const issuerKp = await deriveSyncSigningKeypair(1077      new Uint8Array(32).fill(0x55),1078      "phone-source-id",1079    );1080    const manifest = await buildSignedDeviceManifest(1081      "phone-source-id",1082      [1083        {1084          deviceId: "peer-b",1085          deviceName: "Pool B",1086          deviceType: "extension",1087          longTermPublicKeyHex: "11".repeat(32),1088          signingPublicKeyHex: "22".repeat(32),1089          wsPort: 49152,1090          relayUrl: "wss://relay.peachpasswords.com",1091          pairedAt: 1,1092        },1093      ],1094      issuerKp.privateKey,1095    );1096    const socket = socketWithFrames([1097      { type: "PEACH_HELLO", token: "AAECAwQFBgcICQoLDA0ODw" },1098      ...adoptionV2Frames({1099        rootKeyHex,1100        vaultId,1101        longTermPublicKeyHex: longTermPubkeyHex,1102        signingPublicKeyHex: pubkeyToHex(issuerKp.publicKeyRaw),1103        snapshotCapable: true,1104      }),1105      // Current protocol: the snapshot arrives as ADOPT_SNAPSHOT chunk frames1106      // after the handshake; one empty chunk ends the phase.1107      { type: "ADOPT_SNAPSHOT", chunk_index: 0, chunk_count: 1, entries: {}, tombstones: {} },1108      { type: "ADOPT_DEVICE_MANIFEST", manifest },1109    ], { closeOnEmpty: true });1110    mocks.createVault.mockResolvedValue({ vaultId });1111    mocks.openSocket.mockResolvedValue(socket);1112    mocks.__applyIncomingDeviceManifest.mockClear();11131114    const { startRelayAdoptionReceiver } = await import("./relay-adoption-bg");1115    await startRelayAdoptionReceiver("receiver-password");1116    await waitForPush("ADOPTION_SOURCE_RESULT");11171118    expect(mocks.__applyIncomingDeviceManifest).toHaveBeenCalledTimes(1);1119    const [forwarded, pubkey] = mocks.__applyIncomingDeviceManifest.mock.calls[0];1120    expect(forwarded).toEqual(manifest);1121    expect(pubkey).toBeInstanceOf(Uint8Array);1122    expect(pubkey.length).toBe(32);1123    // The receiver must NOT have sent ADOPT_DEVICE_MANIFEST_APPLIED if the1124    // adapter path was skipped (the ack only follows a real apply).1125    const sentTypes = (socket.send as unknown as { mock: { calls: unknown[][] } })1126      .mock.calls1127      .map(([bytes]) => {1128        try {1129          return JSON.parse(new TextDecoder().decode(bytes as Uint8Array)).type;1130        } catch {1131          return undefined;1132        }1133      });1134    expect(sentTypes).toContain("ADOPT_DEVICE_MANIFEST_APPLIED");1135    // And the source's ADOPT_DEVICE_MANIFEST frame must have been consumed.1136    expect(sentTypes).not.toContain("ADOPT_DEVICE_MANIFEST");1137  });11381139  it("does not call applyIncomingDeviceManifest when the source omits the manifest frame", async () => {1140    // The source is snapshot-capable but does not send an ADOPT_DEVICE_MANIFEST1141    // frame. The receiver should commit the snapshot, send ADOPT_SNAPSHOT_APPLIED,1142    // and quietly time out the optional 5s wait without acking a manifest1143    // or invoking the adapter path.1144    const rootKeyHex = "f0".repeat(32);1145    const vaultId = "b".repeat(64);1146    const longTermPubkeyHex = "99".repeat(32);1147    const socket = socketWithFrames([1148      { type: "PEACH_HELLO", token: "AAECAwQFBgcICQoLDA0ODw" },1149      ...adoptionV2Frames({1150        rootKeyHex,1151        vaultId,1152        longTermPublicKeyHex: longTermPubkeyHex,1153        snapshotCapable: true,1154      }),1155      // Current protocol: one empty ADOPT_SNAPSHOT chunk ends the snapshot1156      // phase; then NO ADOPT_DEVICE_MANIFEST follow-up.1157      { type: "ADOPT_SNAPSHOT", chunk_index: 0, chunk_count: 1, entries: {}, tombstones: {} },1158    ], { closeOnEmpty: true });1159    mocks.createVault.mockResolvedValue({ vaultId });1160    mocks.openSocket.mockResolvedValue(socket);1161    mocks.__applyIncomingDeviceManifest.mockClear();11621163    const { startRelayAdoptionReceiver } = await import("./relay-adoption-bg");1164    await startRelayAdoptionReceiver("receiver-password");1165    await waitForPush("ADOPTION_SOURCE_RESULT");11661167    expect(mocks.__applyIncomingDeviceManifest).not.toHaveBeenCalled();1168    const sentTypes = (socket.send as unknown as { mock: { calls: unknown[][] } })1169      .mock.calls1170      .map(([bytes]) => {1171        try {1172          return JSON.parse(new TextDecoder().decode(bytes as Uint8Array)).type;1173        } catch {1174          return undefined;1175        }1176      });1177    expect(sentTypes).toContain("ADOPT_SNAPSHOT_APPLIED");1178    expect(sentTypes).not.toContain("ADOPT_DEVICE_MANIFEST_APPLIED");1179  });1180});11811182function decodeInvitation(encoded: string): { vault?: string } | null {1183  // Mirrors parsePairingInvitation's payload structure without pulling the1184  // module in: the receiver test only needs to assert the embedded status.1185  const at = encoded.indexOf(":");1186  if (at < 0) return null;1187  const b64 = encoded.slice(at + 1).replace(/-/g, "+").replace(/_/g, "/");1188  try {1189    const json = Buffer.from(b64, "base64").toString("utf8");1190    return JSON.parse(json) as { vault?: string };1191  } catch {1192    return null;1193  }1194}11951196describe("§10.5 adoption adapter coverage", () => {1197  const identity = {1198    deviceId: "source-id",1199    deviceName: "Source",1200    deviceType: "extension" as const,1201    longTermPublicKeyHex: "a".repeat(64),1202    vaultId: "b".repeat(64),1203  };1204  const device = {1205    deviceId: "receiver-id",1206    deviceName: "Phone",1207    deviceType: "android" as const,1208    longTermPublicKeyHex: "d".repeat(64),1209    pairedAt: 1,1210  };12111212  async function build() {1213    const { buildSourceSessionDeps } = await import("./relay-adoption-bg");1214    return buildSourceSessionDeps({1215      identity,1216      rendezvousSecretHex: "cc".repeat(32),1217      relayUrl: "wss://relay.test",1218      sas: "12345678",1219    });1220  }12211222  it("carries every member of the union, including the optional ones", async () => {1223    const deps = await build();12241225    // The compile-time guarantee covers only the non-optional members. An1226    // inline literal could silently drop `persistPendingHolder`, which is1227    // ordering guarantee §10.4.1: no root before a listable holder.1228    expect(Object.keys(deps).sort()).toEqual(1229      [1230        "applyLicense",1231        "clearPendingHolder",1232        "completePendingIdentity",1233        "hasDeviceIdentityCollision",1234        "license",1235        "onConsent",1236        "pairState",1237        "persistPendingHolder",1238        "persistPendingIdentity",1239        "rootKeyHex",1240        "rotateSourceIdentity",1241        "snapshotCapable",1242        "sourceIdentity",1243        "upsertPairedDevice",1244        "vaultId",1245      ].sort(),1246    );1247  });12481249  it("forwards every callback to its sink", async () => {1250    mocks.activateLicense.mockResolvedValue({ valid: true, plan: "pro" });1251    const deps = await build();12521253    // Session facts are bound, not forwarded.1254    expect(deps.sourceIdentity).toEqual(identity);1255    expect(deps.pairState).toEqual({1256      rendezvousSecretHex: "cc".repeat(32),1257      relayUrl: "wss://relay.test",1258    });1259    expect(deps.snapshotCapable()).toBe(true);12601261    expect(await deps.rootKeyHex()).toBe("c".repeat(64));1262    expect(await deps.vaultId()).toBe("b".repeat(64));1263    expect(await deps.license()).toBe("PPK-source");1264    await deps.applyLicense("PPK-transferred");1265    expect(mocks.activateLicense).toHaveBeenCalledWith("PPK-transferred");12661267    await deps.upsertPairedDevice(device);1268    expect(mocks.upsert).toHaveBeenCalledWith(expect.objectContaining({ deviceId: "receiver-id" }));12691270    expect(await deps.hasDeviceIdentityCollision(device)).toBe(false);1271    expect(mocks.hasIdentityConflict).toHaveBeenCalledWith("receiver-id", "d".repeat(64));12721273    await deps.rotateSourceIdentity();1274    expect(mocks.rotatePairedDeviceIdentity).toHaveBeenCalledWith(expect.any(Function), mocks.rotateDeviceId);1275    expect(mocks.rotateDeviceId).toHaveBeenCalled();12761277    // §10.4.1: the pending holder is durable before any root-bearing frame.1278    // They are optional on the v1 interface, which is exactly why they need1279    // asserting here: an inline literal could omit them and still typecheck.1280    expect(deps.persistPendingHolder).toBeDefined();1281    expect(deps.clearPendingHolder).toBeDefined();1282    await deps.persistPendingHolder?.({1283      type: "ADOPT_REQUEST",1284      device_id: "receiver-id",1285      device_name: "Phone",1286      device_type: "android",1287    } as never);1288    expect(mocks.storage.has("peach_pending_adoption_holder_v1")).toBe(true);12891290    await deps.persistPendingIdentity(device as never, 1);1291    expect(mocks.storage.has("peach_pending_adoption_identity_v2")).toBe(true);1292    await deps.completePendingIdentity(device as never);12931294    await deps.clearPendingHolder?.(1295      { device_name: "Phone", device_id: "receiver-id" } as never,1296      device as never,1297    );1298    expect(mocks.storage.has("peach_pending_adoption_holder_v1")).toBe(false);12991300    expect(await deps.onConsent({} as never)).toBe(true);1301  });1302});