entry.ts

5.9 KB · raw

1import { setupMessageHandler, setRestoreReady } from "./messages";2import { setupAutoLock } from "./alarms";3import { setupSyncAlarm } from "./sync-alarm";4import { setupPasskeyProxy } from "./passkey";5import { setupCommands } from "./commands";6import { setupClipboardClearAlarm } from "./clipboard";7import { applyStorageHardening, restoreFromSession, isUnlocked, lock } from "./vault";8import { ensureSettingsLoaded } from "./vault";9import { denyAllPendingPasskeyRequests } from "./passkey";10import {11  hydratePersistedSyncState,12  setSyncDialTargetSelector,13  setSyncRunner,14  triggerSyncIfReachable,15} from "./sync-trigger";16import { productionSyncRunner, abortSyncRunnerSessions } from "./sync-runner";17import {18  drainAndRefreshLockedSyncSpool,19  refreshLockedSyncSpool,20} from "./sync-vault-adapter";21import { clearLockedSyncPrivateKey } from "./locked-sync-spool";22import { setLockedSyncHooks } from "./vault";23import { repairPairedRevocationOverlaps } from "./paired-devices";24import {25  requestMeshRelayReconcile,26  setupMeshRelayListener,27  abortMeshRelaySessions,28  selectProductionDialTargets,29} from "./mesh-relay-listener";30import { hardenExtensionStorage } from "./storage-access";31import { recordInstalledVersion } from "../shared/release-notes";3233chrome.runtime.onInstalled.addListener((details) => { void recordInstalledVersion(details); });3435// The chrome.idle.onStateChanged listener lives in ./alarms (the architectural36// home for auto-lock timing). Keeping it in only one place avoids drift.3738// Lock-on-close via port disconnect. The popup opens a nonce'd port39// ("popup-<uuid>"); when that port disconnects (popup closed), lock if40// lockOnClose is enabled. Previously also declared in the never-bundled41// index.ts (deleted in LV-5) — this is now the single registration.42//43// LV-5: the lock port name carries a per-popup-open random suffix. Another44// extension cannot open ports INTO this extension (onConnectExternal is not45// registered), so the nonce is defense-in-depth — a port named exactly46// "popup" from anything that isn't our popup no longer reliably triggers47// deny-all + lock once the legacy window closes.48const POPUP_PORT_PREFIX = "popup-";4950chrome.runtime.onConnect.addListener((port) => {51  if (!port.name.startsWith(POPUP_PORT_PREFIX)) return;52  const senderUrl = port.sender?.url;53  const extensionOrigin = new URL(chrome.runtime.getURL("")).origin;54  if (port.sender?.tab || !senderUrl || new URL(senderUrl).origin !== extensionOrigin) return;55  port.onDisconnect.addListener(async () => {56    await denyAllPendingPasskeyRequests();57    const s = await ensureSettingsLoaded();58    if (!isUnlocked() || s.lockOnClose !== true) return;59    await lock();60  });61});6263export function start(): void {64  // PB-26-203: establish the storage trust boundary first, then decide65  // whether the session escrow may operate, then restore. The composed66  // promise is handed to the message layer as a gate; the handler itself is67  // still registered synchronously below (MV3 requirement).68  const hardening = hardenExtensionStorage();69  setLockedSyncHooks({70    refresh: refreshLockedSyncSpool,71    // The mesh relay dependency list covers storage reads only; lock and unlock72    // change in-memory vault state, so they reconcile through these hooks.73    afterUnlock: () => drainAndRefreshLockedSyncSpool().finally(requestMeshRelayReconcile),74    onLock: () => requestMeshRelayReconcile(),75    onDecoy: () => {76      void clearLockedSyncPrivateKey();77      abortMeshRelaySessions();78      abortSyncRunnerSessions();79    },80  });81  // MV3: the chrome.runtime.onMessage listener MUST be registered during the82  // worker's initial SYNCHRONOUS evaluation. If registration is deferred behind83  // an await, a popup/content message that wakes a cold worker is dispatched84  // before the listener exists → "receiving end does not exist", and the popup85  // misreads the failed HAS_VAULT as "no vault" and shows onboarding.86  //87  // So: kick off session-restore, hand its promise to the message layer as a88  // gate, and register the handler synchronously. Unlock-dependent handlers89  // await the gate (see handleMessage), which preserves the SEV-3-B fix — no90  // spurious lock screen — without delaying listener registration.91  const restored = hardening92    .then((h) => applyStorageHardening(h.sessionEscrowAvailable))93    .then(() => restoreFromSession());94  setRestoreReady(restored);95  setupMessageHandler();96  void setupAutoLock();97  setupCommands();98  // HV-2: clipboard auto-clear backstop must survive worker eviction; the99  // listener has to be registered during initial synchronous evaluation so100  // a cold worker woken BY the alarm still handles it.101  setupClipboardClearAlarm();102  void setupPasskeyProxy();103  // Wire the sync production runner into the dispatcher. Without this104  // `triggerSyncIfReachable` is a no-op (the runner slot starts null) — the105  // pairing/transport/coordinator stack ships dormant until this assignment.106  setSyncRunner(productionSyncRunner);107  setSyncDialTargetSelector(selectProductionDialTargets);108  setupMeshRelayListener();109  // 10-minute background sync. Must be registered during initial synchronous110  // evaluation for the same reason as the clipboard alarm: a cold worker111  // woken BY the sync alarm needs the listener already attached. Setup is112  // idempotent — calling it after a SW revival is safe.113  setupSyncAlarm();114  // First dial without waiting for the alarm tick. The runner is wired and115  // the vault is unlocked enough that listPairedDevices works — the in-flight116  // guard inside triggerSyncIfReachable handles the case where another path117  // (e.g. a fresh pairing completing on the same wake) is already running.118  void restored119    .then(() => requestMeshRelayReconcile())120    .then(() => repairPairedRevocationOverlaps())121    .then(() => hydratePersistedSyncState())122    .then(() => triggerSyncIfReachable({ reason: "startup" }))123    .catch(() => undefined);124}125126start();