diff --git a/README.md b/README.md index be77ddc..884181e 100644 --- a/README.md +++ b/README.md @@ -86,6 +86,10 @@ The Deploy workflow attempts a staging update after every `dev` push. The `stagi Use the guarded production wrapper for the first protocol-3 cutover and any later compatibility-contract change. It validates the protocol-3 device map, published extension, canary credential, immutable source snapshot, Worker provenance, and deployment evidence. Follow the [production rollout runbook](docs/unattended-production-rollout.md). +For protocol changes, deploy Smart Compliance Platform's matching protocol fork +before promoting the Understudy release to `master` and submitting the store +build. Follow the [extension release order](apps/extension/RUNBOOK.md#release-a-protocol-change). + ## Preserve attended proof history The completed attended design and production proof remain in Git at Understudy `master@797d0e489df2772d0f5d597141982547861881bb` and Metamind `master@0814deb`. Attended mode remains compatible in the current extension and API. diff --git a/apps/backend/src/dashboard/pages.ts b/apps/backend/src/dashboard/pages.ts index 70e3426..a81d212 100644 --- a/apps/backend/src/dashboard/pages.ts +++ b/apps/backend/src/dashboard/pages.ts @@ -52,8 +52,8 @@ for (const button of document.querySelectorAll("[data-copy]")) { }); } const countdown = document.querySelector("[data-expires]"); +const expiresAt = Number(countdown?.getAttribute("data-expires")); if (countdown) { - const expiresAt = Number(countdown.getAttribute("data-expires")); const tick = () => { const left = Math.max(0, Math.floor((expiresAt - Date.now()) / 1000)); countdown.textContent = left > 0 @@ -69,15 +69,46 @@ if (pairing) { const extensionId = pairing.getAttribute("data-extension-id"); const status = document.getElementById("pairing-status"); pairing.removeAttribute("data-offer"); - if (offer && extensionId && globalThis.chrome?.runtime?.sendMessage) { + if (offer && extensionId && status && globalThis.chrome?.runtime?.sendMessage) { + const failure = "The extension did not accept the offer. Confirm it is installed, then generate a new offer."; + const showReply = (reply, confirmationId) => { + if (chrome.runtime.lastError) { + status.textContent = failure; + return; + } + if (reply?.status === "confirmation_pending" || reply?.status === "pairing") { + const id = confirmationId ?? reply.confirmationId; + if (typeof id !== "string") { + status.textContent = failure; + return; + } + status.textContent = reply.status === "confirmation_pending" + ? "Open the Understudy side panel to confirm pairing." + : "Pairing this browser…"; + setTimeout(() => chrome.runtime.sendMessage( + extensionId, + { type: "understudy_pair_status", confirmationId: id }, + (next) => showReply(next, id), + ), 1_000); + return; + } + status.textContent = reply?.ok !== true + ? failure + : reply.status === "closing_previous_sessions" + ? "Pairing saved. The previous service’s sessions are closing." + : "This browser is paired. You can close this page."; + }; + // Store builds with the two-field offer schema accept this first message. + const message = { type: "understudy_pair_offer", offer }; chrome.runtime.sendMessage( extensionId, - { type: "understudy_pair_offer", offer }, + message, (reply) => { - if (!status) return; - status.textContent = chrome.runtime.lastError || reply?.ok !== true - ? "The extension did not accept the offer. Confirm it is installed, then generate a new offer." - : "This browser is paired. You can close this page."; + if (reply?.status === "expiry_required") { + chrome.runtime.sendMessage(extensionId, { ...message, expiresAt }, showReply); + } else { + showReply(reply); + } }, ); } else if (status) { diff --git a/apps/extension/README.md b/apps/extension/README.md index ba7dae5..10abf13 100644 --- a/apps/extension/README.md +++ b/apps/extension/README.md @@ -58,20 +58,24 @@ pnpm --filter @understudy/extension build:store pnpm --filter @understudy/extension zip:store ``` -`test:e2e` launches local Chrome with the store build. It verifies bounded +`test:e2e` validates the store manifest and launches local Chrome with the internal E2E build. It verifies bounded semantic capture on a 10,000-element document, offscreen find, inspect, pagination, same-process and OOPIF frames, shadow DOM, structured deltas, and stale refs. It also verifies that worker eviction expires refs and cursors. -Load `.output/chrome-mv3/` for internal testing, `.output/chrome-mv3-staging/` for hosted staging, or `.output/chrome-mv3-store/` for store acceptance. The staging build has the stable extension ID `ebpcldlibljfjhcfknagjcdmhggeknfc` and connects only to `https://staging.understudy.proofof.tech`. The store build connects only to `https://understudy.proofof.tech` and has no pinned key. +Load `.output/chrome-mv3/` for internal testing, `.output/chrome-mv3-staging/` for hosted staging, or `.output/chrome-mv3-store/` for store acceptance. The staging build has the stable extension ID `ebpcldlibljfjhcfknagjcdmhggeknfc` and connects only to `https://staging.understudy.proofof.tech`. The store build omits a pinned key and connects to Understudy at `https://understudy.proofof.tech` and Smart Compliance Platform (SCP) at `https://browser.nomixhq.com`. `store-release.json` records the manually submitted or published Chrome Web Store artifact for ID `lbmbdjjaodgipnleaggclnobbijpadee`. Production deployment requires `status: "published"` and normalized build contents equal to that record. ZIP timestamps and compression do not affect this gate. ## Pair a browser -Sign in at `https://understudy.proofof.tech/dashboard` and select **Pair this browser**. The CSRF-protected POST mints an opaque single-use offer. The dashboard sends it directly to the installed extension with `chrome.runtime.sendMessage`; the offer never enters a URL, browser history, or referrer. +For Understudy, sign in at `https://understudy.proofof.tech/dashboard` and select **Pair this browser**. The CSRF-protected POST creates a single-use offer. The dashboard sends it directly to the installed extension with `chrome.runtime.sendMessage` and keeps it out of the URL. -The extension accepts only the exact sender page `https://understudy.proofof.tech/dashboard/pair`, an exact two-field schema, and a 43-character base64url offer. Re-pairing a live installation rotates the existing device credential without releasing its assignments. A locally detected revocation omits its dead credential. If a browser was revoked while offline and still submits that credential, pairing returns a fresh device identity and the extension durably fences and discards stale local ownership before activating it, including across service-worker restarts. A different Chrome profile creates a separate browser. +For SCP, create an offer in the SCP console and open its pairing link in the Chrome profile you want to enroll. SCP's API creates the offer. The gateway serves `https://browser.nomixhq.com/dashboard/pair`, which removes the offer fragment from the current history entry with `history.replaceState` on load before sending the offer to the extension. The fragment stays out of the HTTP request. Chrome may briefly record it in history before the page runs. The offer expires after 10 minutes and is single-use. + +The extension accepts the exact `/dashboard/pair` page at any service origin compiled into the build. It ignores a fragment and refuses sender URLs with a query string. It requires the two-field message schema and a 43-character base64url offer. The sender page determines where the extension claims the offer, and the extension saves that origin with the profile for future connections. + +Re-pairing with the same service rotates the existing device credential without releasing its assignments. Pairing with a different service creates a device there while the extension releases any old assignments. A locally detected revocation omits its dead credential. If a browser was revoked while offline and still submits that credential, pairing returns a fresh device identity and the extension durably fences and discards stale local ownership before activating it, including across service-worker restarts. A different Chrome profile creates a separate browser. An empty default origin policy is valid, but the device cannot accept a session until configured. diff --git a/apps/extension/RUNBOOK.md b/apps/extension/RUNBOOK.md index a5de37a..1212b4e 100644 --- a/apps/extension/RUNBOOK.md +++ b/apps/extension/RUNBOOK.md @@ -21,10 +21,21 @@ pnpm --filter @understudy/extension build:store pnpm --filter @understudy/extension zip:store ``` -`test:e2e` uses local Chrome and the existing `ws` package. It loads the store -build, configures hosting through the side panel, and exercises bounded +`test:e2e` validates the store manifest and loads the internal E2E build in local Chrome. +It configures hosting through the side panel and exercises bounded semantic discovery across large pages, frames, and shadow DOM. +## Release a protocol change + +1. Merge the Understudy protocol change to `dev`. +2. Deploy the matching protocol fork to the hosted Smart Compliance Platform + (SCP) browser gateway. +3. Promote Understudy's release commit from `dev` to `master`. +4. Submit the store ZIP for that commit and record it once Chrome Web Store + publishes it. Follow [the store submission procedure](WEBSTORE.md). + +Expect `master`’s Deploy run to fail at `verify:store-release` until you promote the store record to `published`. + ## Verify semantic discovery 1. Confirm `device_hello` advertises `semantic-elements-v1` before enabling the @@ -53,8 +64,10 @@ semantic discovery across large pages, frames, and shadow DOM. 1. Build with `pnpm --filter @understudy/extension build:store`. 2. Open `chrome://extensions`, enable Developer mode, and choose Load unpacked. 3. Select `apps/extension/.output/chrome-mv3-store/`. -4. Confirm the manifest requests only the expected debugger, storage, alarms, - side-panel, and canonical-host permissions. +4. Confirm the manifest requests the expected debugger, storage, alarms, and + side-panel permissions. Check that both host permissions and external + message matches contain exactly `https://understudy.proofof.tech/*` and + `https://browser.nomixhq.com/*`. Do not use WXT development mode for release acceptance. @@ -67,7 +80,9 @@ Use the pinned staging build to test hosted changes before store submission: 3. Load `apps/extension/.output/chrome-mv3-staging/` through `chrome://extensions`. 4. Confirm Chrome reports extension ID `ebpcldlibljfjhcfknagjcdmhggeknfc`. 5. Sign in at `https://staging.understudy.proofof.tech/dashboard` and pair the browser. -6. Reject pairing messages from production, loopback, query-bearing, fragment-bearing, and trailing-slash sender URLs. +6. Confirm the extension rejects pairing messages from either production host + and from loopback. On staging, verify that a fragment on the exact pairing + page is accepted and that a query or trailing slash is refused. 7. Verify hosted control, OAuth, Model Context Protocol (MCP), dashboard, privacy, and side-panel links remain on staging. The staging extension retains internal controls and broad host permissions. Do not submit it to the Chrome Web Store. @@ -85,9 +100,17 @@ The staging extension retains internal controls and broad host permissions. Do n acknowledges the new version, then become available without re-pairing. 6. Remove an origin used by a controlled tab. The backend must fence the lease, terminalize the session, and push the narrower policy immediately. -7. Replay or alter the pairing offer and try it from another origin. Each must - fail. Pairing the same installation again must rotate its credential rather - than leave a live predecessor. +7. Replay or alter the pairing offer and try it from an unlisted origin. Each + must fail. Re-pair with Understudy and verify that the device credential + rotates and the previous credential stops working. + +## Verify SCP pairing + +1. In the SCP console, create a pairing offer. Open the link in the Chrome + profile with the store extension installed. +2. Confirm the gateway page at `https://browser.nomixhq.com/dashboard/pair` + removes the fragment from the current history entry and pairs the extension. +3. Restart Chrome and verify that the same device reconnects to the SCP gateway. ## Exercise lifecycle convergence diff --git a/apps/extension/WEBSTORE.md b/apps/extension/WEBSTORE.md index 09019e5..466303f 100644 --- a/apps/extension/WEBSTORE.md +++ b/apps/extension/WEBSTORE.md @@ -15,7 +15,10 @@ curl --fail --silent --show-error https://understudy.proofof.tech/privacy >/dev/ Confirm `manifest.json` is at the archive root. Distribution is unlisted, free, all regions, category Productivity → Tools. -Submit the exact ZIP built from the final clean `dev` release commit. Record that commit and the raw ZIP SHA-256 outside Git while review is pending. Do not reuse an artifact built before the deployment and staging changes. +For a protocol change, submit after SCP's matching protocol fork is live and +the release commit has reached `master`. Follow [the protocol release order](RUNBOOK.md#release-a-protocol-change). +Submit the exact ZIP built from the final clean `dev` release commit. Record +that commit and the raw ZIP SHA-256 outside Git while review is pending. After Chrome Web Store reports the item as published, return to the exact source commit and record the published artifact: @@ -26,7 +29,12 @@ pnpm --filter @understudy/extension record:store-release -- \ pnpm --filter @understudy/extension verify:store-release ``` -Run the recorder from a clean checkout of the exact submitted commit and replace `source_commit_sha` with that checkout's full `HEAD`. The recorder rejects a dirty tree, a different commit, or an abbreviated SHA. Commit the resulting `store-release.json` separately on `dev`, then promote `dev` to `master`. Never set `published` while the item remains in review. +Run the recorder from a clean checkout of the exact submitted commit and replace +`source_commit_sha` with that checkout's full `HEAD`. The recorder rejects a dirty +tree, a different commit, or an abbreviated SHA. Commit the resulting +`store-release.json` separately on `dev` and promote the marker to `master`. +The production deployment gate requires the published marker and the matching +build contents. ## Listing copy @@ -40,9 +48,9 @@ can operate controlled tabs on exact origins you allow. ```text UNDERSTUDY IS BETA SOFTWARE. -Understudy pairs a dedicated Chrome profile with the hosted Understudy service. An AI client you authorize can open and operate extension-owned tabs only on exact website origins you allow. +Understudy pairs a dedicated Chrome profile with the hosted Understudy service or the Smart Compliance Platform gateway. An AI client you authorize can open and operate extension-owned tabs only on exact website origins you allow. -Pairing is approved directly between the Understudy dashboard and the installed extension. The side panel shows device and policy state, controlled-window inventory, connection recovery, an emergency stop, and a local troubleshooting log. +Pair from your service's dashboard. The side panel shows device and policy state, controlled-window inventory, connection recovery, an emergency stop, and a local troubleshooting log. Understudy does not choose tasks or approve actions. Your connected AI client selects bounded semantic page elements and requests actions. Element references are opaque and checked again before use; the extension does not expose selectors or automatically redirect an action to a changed target. You control pairing, allowed origins, API or OAuth connections, and device revocation. @@ -72,9 +80,9 @@ Pair Chrome with Understudy so an AI client the user authorizes can operate exte - `alarms`: provide a Manifest V3 wake-up backstop for connection recovery, policy/inventory reconciliation, and exact controlled-window cleanup. - `sidePanel`: pair, show connection and policy state, and stop hosting. -- `https://understudy.proofof.tech/*`: receive direct one-time pairing offers, - request short-lived connect tickets, and exchange validated control/session - frames over HTTPS and WSS. +- `https://understudy.proofof.tech/*` and `https://browser.nomixhq.com/*` allow + the extension to receive pairing offers, request short-lived connect tickets, + and exchange control and session frames with the service that paired the profile. The package requests neither `tabs` nor `activeTab`. Select **No remote code**: all executable code is bundled; remote commands are validated data, not code. diff --git a/apps/extension/scripts/e2e.mjs b/apps/extension/scripts/e2e.mjs index 2f38c5f..2b8b7e1 100644 --- a/apps/extension/scripts/e2e.mjs +++ b/apps/extension/scripts/e2e.mjs @@ -5,6 +5,7 @@ import { tmpdir } from "node:os"; import path from "node:path"; import process from "node:process"; import WebSocket, { WebSocketServer } from "ws"; +import { validateStoreManifest } from "./store-release.mjs"; class CdpClient { static connect(url) { @@ -53,7 +54,8 @@ const storeManifest = JSON.parse( await readFile(path.join(storeExtensionDir, "manifest.json"), "utf8"), ); const manifest = JSON.parse(await readFile(path.join(extensionDir, "manifest.json"), "utf8")); -if (storeManifest.version !== "0.2.0" || manifest.version !== "0.2.0") { +validateStoreManifest(storeManifest, "0.2.0"); +if (manifest.version !== "0.2.0") { throw new Error("unexpected extension build version"); } diff --git a/apps/extension/scripts/store-release.integration.mjs b/apps/extension/scripts/store-release.integration.mjs index d96d6e3..7bc0c39 100644 --- a/apps/extension/scripts/store-release.integration.mjs +++ b/apps/extension/scripts/store-release.integration.mjs @@ -137,13 +137,14 @@ function run(command, args, cwd) { } function storeManifest() { + const matches = ["https://understudy.proofof.tech/*", "https://browser.nomixhq.com/*"]; return { name: "Understudy Beta", version: "0.2.0", homepage_url: "https://understudy.proofof.tech/dashboard", - host_permissions: ["https://understudy.proofof.tech/*"], + host_permissions: [...matches], externally_connectable: { - matches: ["https://understudy.proofof.tech/*"], + matches: [...matches], }, }; } diff --git a/apps/extension/scripts/store-release.mjs b/apps/extension/scripts/store-release.mjs index faecffe..4fa457a 100644 --- a/apps/extension/scripts/store-release.mjs +++ b/apps/extension/scripts/store-release.mjs @@ -20,6 +20,10 @@ const targets = JSON.parse( ); const EXTENSION_ID = targets.production.extensionId; const PRODUCTION_ORIGIN = targets.production.origin; +const STORE_MATCHES = [ + PRODUCTION_ORIGIN, + ...targets.production.additionalServiceOrigins, +].map((origin) => `${origin}/*`); const SHA256_PATTERN = /^[0-9a-f]{64}$/; const COMMIT_PATTERN = /^[0-9a-f]{40}$/; @@ -86,16 +90,21 @@ export function validateStoreManifest(manifest, expectedVersion, allowLegacyPair if (manifest.homepage_url !== `${PRODUCTION_ORIGIN}/dashboard`) { throw new Error("store manifest homepage is not production"); } - const externalMatches = manifest.externally_connectable?.matches; - const legacyPairing = allowLegacyPairing && externalMatches === undefined; - if ( - JSON.stringify(manifest.host_permissions) !== - JSON.stringify([`${PRODUCTION_ORIGIN}/*`]) || - (!legacyPairing && - JSON.stringify(externalMatches) !== JSON.stringify([`${PRODUCTION_ORIGIN}/*`])) - ) { - throw new Error("store manifest network origins are not production-only"); + const hostMatches = JSON.stringify(manifest.host_permissions); + const externalMatches = JSON.stringify(manifest.externally_connectable?.matches); + const expectedMatches = JSON.stringify(STORE_MATCHES); + if (hostMatches === expectedMatches && externalMatches === expectedMatches) return; + + if (allowLegacyPairing && expectedVersion === "0.1.2") { + const legacyMatches = JSON.stringify([`${PRODUCTION_ORIGIN}/*`]); + if ( + hostMatches === legacyMatches && + (externalMatches === undefined || externalMatches === legacyMatches) + ) { + return; + } } + throw new Error("store manifest network origins do not match the store allowlist"); } export async function verifyStoreRelease({ @@ -111,11 +120,7 @@ export async function verifyStoreRelease({ allowInReview, ); const manifest = JSON.parse(await readFile(join(directory, "manifest.json"), "utf8")); - validateStoreManifest( - manifest, - release.version, - allowInReview && release.version === "0.1.2", - ); + validateStoreManifest(manifest, release.version, allowInReview); const directoryDigest = await contentDigest(directory); if (directoryDigest !== release.contentSha256) { throw new Error("store build content does not match the recorded release"); diff --git a/apps/extension/scripts/store-release.test.mjs b/apps/extension/scripts/store-release.test.mjs index bf3c3cf..c0c488f 100644 --- a/apps/extension/scripts/store-release.test.mjs +++ b/apps/extension/scripts/store-release.test.mjs @@ -44,6 +44,30 @@ describe("store release gate", () => { expect(() => validateStoreManifest(manifest, "0.2.0")).toThrow(/pinned/); }); + it.each(["host_permissions", "externally_connectable"])("requires the exact store allowlist in %s", (field) => { + for (const matches of [ + ["https://understudy.proofof.tech/*"], + ["https://browser.nomixhq.com/*"], + [...storeManifest().host_permissions, "https://staging.understudy.proofof.tech/*"], + [""], + ]) { + const manifest = storeManifest(); + manifest[field] = field === "host_permissions" ? matches : { matches }; + expect(() => validateStoreManifest(manifest, "0.2.0", true)).toThrow(/network origins/); + } + }); + + it("preserves opt-in verification of the 0.1.2 pairing manifest", () => { + const manifest = { + ...storeManifest(), + version: "0.1.2", + host_permissions: ["https://understudy.proofof.tech/*"], + externally_connectable: undefined, + }; + expect(() => validateStoreManifest(manifest, "0.1.2", true)).not.toThrow(); + expect(() => validateStoreManifest(manifest, "0.1.2")).toThrow(/network origins/); + }); + it("rejects unsafe, duplicate, and symlinked store entries", async () => { expect(() => validateZipEntries(["../manifest.json"])).toThrow(/unsafe/); expect(() => validateZipEntries(["manifest.json", "manifest.json"])).toThrow( @@ -63,13 +87,14 @@ async function temporaryDirectory() { } function storeManifest() { + const matches = ["https://understudy.proofof.tech/*", "https://browser.nomixhq.com/*"]; return { name: "Understudy Beta", version: "0.2.0", homepage_url: "https://understudy.proofof.tech/dashboard", - host_permissions: ["https://understudy.proofof.tech/*"], + host_permissions: [...matches], externally_connectable: { - matches: ["https://understudy.proofof.tech/*"], + matches: [...matches], }, }; } diff --git a/apps/extension/scripts/verify-build-target.mjs b/apps/extension/scripts/verify-build-target.mjs index dd83bc1..75270b4 100644 --- a/apps/extension/scripts/verify-build-target.mjs +++ b/apps/extension/scripts/verify-build-target.mjs @@ -31,9 +31,13 @@ try { throw new Error("staging manifest identity, authority, or pinned key is invalid"); } const bundledSource = await readBundleSource(directory); + const productionOrigins = [ + targets.production.origin, + ...targets.production.additionalServiceOrigins, + ]; if ( !bundledSource.includes(STAGING_ORIGIN) || - bundledSource.includes(targets.production.origin) + productionOrigins.some((origin) => bundledSource.includes(origin)) ) { throw new Error("staging bundle is not pinned exclusively to the staging origin"); } diff --git a/apps/extension/src/core/background-pairing.test.ts b/apps/extension/src/core/background-pairing.test.ts new file mode 100644 index 0000000..2a9a709 --- /dev/null +++ b/apps/extension/src/core/background-pairing.test.ts @@ -0,0 +1,400 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; +import { PAIRING_CLAIM_KEY } from "./pairing-client"; +import type { PanelMsg, StateMsg, SwMsg } from "../messaging"; + +const UNDERSTUDY = "https://understudy.proofof.tech"; +const SCP = "https://browser.nomixhq.com"; +const OFFER = "A".repeat(43); +const DEVICE_ID = "00000000-0000-4000-8000-000000000001"; +const CREDENTIAL = `udt_v2_${"B".repeat(43)}`; + +const profile = vi.hoisted(() => ({ + start: vi.fn(async () => {}), + publicConfig: vi.fn<() => StateMsg["profileConfig"]>(), + currentStatus: vi.fn(() => "disabled"), + blockedReason: vi.fn<() => StateMsg["profileStatusReason"] | null>(), + stagedServiceOrigin: vi.fn<() => string | null>(), + pairingCredential: vi.fn<() => Promise>(), + configurePaired: vi.fn(async () => {}), + persistedPairingTransition: vi.fn<() => Promise<"active" | "staged" | null>>(), + stopAll: vi.fn(async () => {}), + sessions: { assignments: () => [] }, +})); + +vi.mock("./profile-client", () => ({ + ProfileClient: class { + constructor() { return profile; } + }, +})); +vi.mock("./delete-obsolete-database", () => ({ + deleteObsoleteDatabase: async () => {}, +})); + +type ExternalReply = { + ok?: boolean; + status?: string; + confirmationId?: string; +}; +type ExternalListener = ( + message: unknown, + sender: { url: string }, + sendResponse: (reply: ExternalReply) => void, +) => boolean; + +function storageArea(values: Record) { + return { + get: vi.fn(async (key: string) => ({ [key]: values[key] })), + set: vi.fn(async (next: Record) => { + Object.assign(values, next); + }), + remove: vi.fn(async (keys: string | string[]) => { + for (const key of Array.isArray(keys) ? keys : [keys]) delete values[key]; + }), + }; +} + +function persistedProfile(serviceOrigin: string): NonNullable { + return { serviceOrigin, deviceId: DEVICE_ID, unattendedEnabled: true, originPolicy: [], policyVersion: 1 }; +} + +function priorClaim(serviceOrigin: string) { + return { + version: 4, + active: { + serviceOrigin, + offer: "C".repeat(43), + claimId: "D".repeat(43), + phase: "dispatched", + previousCredential: null, + }, + queued: null, + stopRequested: false, + }; +} + +async function boot( + local: Record = {}, + claimResponse = async (url: string) => Response.json({ + ...persistedProfile(new URL(url).origin), + deviceCredential: CREDENTIAL, + }), +) { + const localArea = storageArea(local); + const external = vi.fn<(listener: ExternalListener) => void>(); + const panelMessage = vi.fn<(listener: (message: PanelMsg) => void) => void>(); + const panel = { + name: "panel", + onMessage: { addListener: panelMessage }, + onDisconnect: { addListener: vi.fn() }, + postMessage: vi.fn<(message: SwMsg) => void>(), + }; + const connect = vi.fn<(listener: (port: typeof panel) => void) => void>(); + const unusedEvent = { addListener: vi.fn() }; + vi.stubGlobal("browser", { + storage: { local: localArea, session: storageArea({}) }, + alarms: { onAlarm: unusedEvent, create: vi.fn(async () => {}) }, + debugger: { onEvent: unusedEvent, onDetach: unusedEvent }, + tabs: { onCreated: unusedEvent }, + runtime: { onConnect: { addListener: connect }, onMessageExternal: { addListener: external } }, + sidePanel: { setPanelBehavior: vi.fn(async () => {}) }, + }); + const fetchClaim = vi.fn(claimResponse); + vi.stubGlobal("fetch", fetchClaim); + vi.stubGlobal("__UNDERSTUDY_STORE__", true); + vi.stubGlobal("__UNDERSTUDY_ORIGIN_PINNED__", true); + vi.stubGlobal("defineBackground", (entry: { main: () => void }) => entry); + const entry = (await import("../entrypoints/background")).default as { main: () => void }; + entry.main(); + connect.mock.calls[0]?.[0](panel); + const externalListener = external.mock.calls[0]?.[0]; + const sendPanel = panelMessage.mock.calls[0]?.[0]; + if (externalListener === undefined || sendPanel === undefined) { + throw new Error("pairing listeners were not registered"); + } + const externalMessage = (origin: string, message: unknown) => new Promise((resolve) => { + externalListener(message, { url: `${origin}/dashboard/pair` }, resolve); + }); + return { + fetchClaim, + local, + sendPanel, + offer: (origin: string, expiresAt?: number, offer = OFFER) => externalMessage(origin, { + type: "understudy_pair_offer", + offer, + ...(expiresAt === undefined ? {} : { expiresAt }), + }), + status: (origin: string, confirmationId: string) => externalMessage(origin, { + type: "understudy_pair_status", + confirmationId, + }), + state: () => panel.postMessage.mock.calls + .map(([message]) => message) + .filter((message): message is StateMsg => message.type === "state") + .at(-1), + }; +} + +function pendingId(reply: ExternalReply): string { + expect(reply.status).toBe("confirmation_pending"); + if (reply.confirmationId === undefined) throw new Error("confirmation ID is missing"); + return reply.confirmationId; +} + +beforeEach(() => { + vi.resetModules(); + vi.resetAllMocks(); + vi.useFakeTimers(); + profile.publicConfig.mockReturnValue(null); + profile.blockedReason.mockReturnValue(null); + profile.stagedServiceOrigin.mockReturnValue(null); + profile.pairingCredential.mockResolvedValue(undefined); + profile.persistedPairingTransition.mockResolvedValue(null); +}); + +afterEach(() => { + vi.useRealTimers(); + vi.unstubAllGlobals(); +}); + +describe("external pairing and side-panel consent", () => { + it("holds a change of service until the panel confirms the displayed offer", async () => { + // #given + profile.publicConfig.mockReturnValue(persistedProfile(SCP)); + const browser = await boot(); + const expiresAt = Date.now() + 60_000; + + // #when + const id = pendingId(await browser.offer(UNDERSTUDY, expiresAt)); + + // #then + expect(browser.state()?.pairingConfirmation).toEqual({ + id, + serviceHost: "understudy.proofof.tech", + replacesHost: "browser.nomixhq.com", + }); + expect(browser.local[PAIRING_CLAIM_KEY]).toBeUndefined(); + expect(browser.fetchClaim).not.toHaveBeenCalled(); + expect(await browser.status(SCP, id)).toEqual({ ok: false }); + browser.sendPanel({ type: "confirmPairing", confirmationId: id }); + await vi.waitFor(async () => + expect(await browser.status(UNDERSTUDY, id)).toEqual({ ok: true }), + ); + expect(browser.fetchClaim.mock.calls.map(([url]) => url)).toEqual([ + `${UNDERSTUDY}/v1/pairing/claim`, + ]); + }); + + it.each(["unpaired", "revoked"] as const)( + "requires consent for an SCP offer on a %s profile", + async (kind) => { + // #given + if (kind === "revoked") { + profile.publicConfig.mockReturnValue(persistedProfile(SCP)); + profile.blockedReason.mockReturnValue("credential_revoked"); + } + const browser = await boot(); + + // #when + pendingId(await browser.offer(SCP, Date.now() + 60_000)); + + // #then + expect(browser.fetchClaim).not.toHaveBeenCalled(); + }, + ); + + it.each([ + [null, UNDERSTUDY], + [UNDERSTUDY, UNDERSTUDY], + [SCP, SCP], + ])("redeems a legacy offer from %s's permitted service %s without a prompt", async (origin, offerOrigin) => { + // #given + if (origin !== null) profile.publicConfig.mockReturnValue(persistedProfile(origin)); + const browser = await boot(); + + // #when + const reply = await browser.offer(offerOrigin); + + // #then + expect(reply).toEqual({ ok: true }); + expect(browser.state()?.pairingConfirmation).toBeUndefined(); + }); + + it("asks the dashboard for the original expiry before displaying a legacy switch offer", async () => { + // #given + profile.publicConfig.mockReturnValue(persistedProfile(SCP)); + const browser = await boot(); + + // #when + const reply = await browser.offer(UNDERSTUDY); + + // #then + expect(reply).toEqual({ status: "expiry_required" }); + expect(browser.state()?.pairingConfirmation).toBeUndefined(); + expect(browser.fetchClaim).not.toHaveBeenCalled(); + }); + + it.each(["cancel", "expire"] as const)( + "drops a held offer on %s and rejects a late confirmation", + async (action) => { + // #given + const browser = await boot(); + const deadline = Date.now() + 1_000; + const id = pendingId(await browser.offer(SCP, deadline)); + + // #when + if (action === "cancel") browser.sendPanel({ type: "cancelPairing", confirmationId: id }); + else await vi.advanceTimersByTimeAsync(1_000); + browser.sendPanel({ type: "confirmPairing", confirmationId: id }); + + // #then + expect(await browser.status(SCP, id)).toEqual({ ok: false }); + expect(browser.state()?.pairingConfirmation).toBeUndefined(); + expect(browser.fetchClaim).not.toHaveBeenCalled(); + }, + ); + + it("does not let a stale panel click confirm a replacement offer", async () => { + // #given + const browser = await boot(); + const deadline = Date.now() + 60_000; + const staleId = pendingId(await browser.offer(SCP, deadline)); + const replacementId = pendingId(await browser.offer(SCP, deadline, "E".repeat(43))); + + // #when + browser.sendPanel({ type: "confirmPairing", confirmationId: staleId }); + + // #then + expect(browser.fetchClaim).not.toHaveBeenCalled(); + expect(browser.state()?.pairingConfirmation?.id).toBe(replacementId); + }); + + it("requires a fresh offer if the pairing to replace changed while consent was pending", async () => { + // #given + profile.publicConfig.mockReturnValue(persistedProfile(UNDERSTUDY)); + const browser = await boot(); + const id = pendingId(await browser.offer(SCP, Date.now() + 60_000)); + profile.publicConfig.mockReturnValue({ + ...persistedProfile(UNDERSTUDY), + deviceId: "00000000-0000-4000-8000-000000000002", + }); + + // #when + browser.sendPanel({ type: "confirmPairing", confirmationId: id }); + + // #then + expect(await browser.status(SCP, id)).toEqual({ ok: false }); + expect(browser.fetchClaim).not.toHaveBeenCalled(); + }); + + it("keeps a repeated offer's original hold deadline", async () => { + // #given + const browser = await boot(); + const id = pendingId(await browser.offer(SCP, Date.now() + 1_000)); + + // #when + expect(pendingId(await browser.offer(SCP, Date.now() + 60_000))).toBe(id); + await vi.advanceTimersByTimeAsync(1_000); + + // #then + expect(await browser.status(SCP, id)).toEqual({ ok: false }); + }); + + it("keeps a local Stop All in force until a held offer is confirmed", async () => { + // #given + profile.publicConfig.mockReturnValue(persistedProfile(UNDERSTUDY)); + let finishStop!: () => void; + profile.stopAll.mockImplementationOnce(() => new Promise((resolve) => { finishStop = resolve; })); + const browser = await boot(); + browser.sendPanel({ type: "stopAll" }); + await vi.waitFor(() => expect(profile.stopAll).toHaveBeenCalledOnce()); + + // #when + const id = pendingId(await browser.offer(UNDERSTUDY, Date.now() + 60_000)); + + // #then + expect(browser.state()?.profileConfig?.unattendedEnabled).toBe(false); + expect(browser.fetchClaim).not.toHaveBeenCalled(); + browser.sendPanel({ type: "confirmPairing", confirmationId: id }); + finishStop(); + await vi.waitFor(async () => + expect(await browser.status(UNDERSTUDY, id)).toEqual({ ok: true }), + ); + }); + + it.each([SCP, UNDERSTUDY])( + "keeps a failed claim only when the queued offer is for the same service (%s)", + async (offerOrigin) => { + // #given + profile.publicConfig.mockReturnValue(persistedProfile(offerOrigin)); + const original = priorClaim(UNDERSTUDY); + const browser = await boot( + { [PAIRING_CLAIM_KEY]: original }, + async (url) => new URL(url).origin === UNDERSTUDY + ? new Response(null, { status: 409 }) + : Response.json({ ...persistedProfile(SCP), deviceCredential: CREDENTIAL }), + ); + + // #when + const reply = await browser.offer(offerOrigin); + + // #then + if (offerOrigin === SCP) { + expect(reply).toEqual({ ok: true }); + expect(browser.local[PAIRING_CLAIM_KEY]).toBeUndefined(); + } else { + expect(reply).toEqual({ ok: false }); + expect(browser.local[PAIRING_CLAIM_KEY]).toMatchObject({ + active: original.active, + queued: { serviceOrigin: UNDERSTUDY, offer: OFFER }, + }); + } + }, + ); + + it("advances to a different service's queued claim during worker recovery", async () => { + // #given + const pending = { + ...priorClaim(UNDERSTUDY), + queued: { serviceOrigin: SCP, offer: OFFER, claimId: "E".repeat(43) }, + }; + const browser = await boot( + { [PAIRING_CLAIM_KEY]: pending }, + async (url) => new URL(url).origin === UNDERSTUDY + ? new Response(null, { status: 409 }) + : Response.json({ ...persistedProfile(SCP), deviceCredential: CREDENTIAL }), + ); + + // #when + await vi.waitFor(() => expect(browser.local[PAIRING_CLAIM_KEY]).toBeUndefined()); + + // #then + expect(browser.fetchClaim.mock.calls.map(([url]) => url)).toEqual([ + `${UNDERSTUDY}/v1/pairing/claim`, + `${SCP}/v1/pairing/claim`, + ]); + }); + + it("reports a saved pairing while cleanup is pending and preserves the dispatched claim", async () => { + // #given + profile.publicConfig.mockReturnValue(persistedProfile(UNDERSTUDY)); + profile.configurePaired.mockRejectedValueOnce(new Error("profile is staged")); + profile.persistedPairingTransition.mockImplementationOnce(async () => { + profile.stagedServiceOrigin.mockReturnValue(SCP); + return "staged"; + }); + const browser = await boot(); + const id = pendingId(await browser.offer(SCP, Date.now() + 60_000)); + + // #when + browser.sendPanel({ type: "confirmPairing", confirmationId: id }); + + // #then + await vi.waitFor(async () => + expect(await browser.status(SCP, id)).toEqual({ ok: true, status: "closing_previous_sessions" }), + ); + expect(browser.state()?.pairing).toEqual({ phase: "success", closingPreviousSessions: true }); + expect(browser.local[PAIRING_CLAIM_KEY]).toMatchObject({ + active: { serviceOrigin: SCP, offer: OFFER, phase: "dispatched" }, + }); + }); +}); diff --git a/apps/extension/src/core/external-pairing.test.ts b/apps/extension/src/core/external-pairing.test.ts index 70f1f84..bf62214 100644 --- a/apps/extension/src/core/external-pairing.test.ts +++ b/apps/extension/src/core/external-pairing.test.ts @@ -1,33 +1,50 @@ import { describe, expect, it } from "vitest"; -import { externalPairingOffer } from "./external-pairing"; +import { pairingManagementUrl } from "../service-origin"; +import { externalPairingOffer, externalPairingStatusRequest } from "./external-pairing"; const OFFER = "A".repeat(43); describe("externalPairingOffer", () => { - it("accepts only the canonical pairing page and exact message schema", () => { + it.each([ + ["https://understudy.proofof.tech", ""], + ["https://browser.nomixhq.com", ""], + ["https://browser.nomixhq.com", `#${OFFER}`], + ])("accepts the exact pairing page at %s with suffix %s", (serviceOrigin, suffix) => { expect( externalPairingOffer( { type: "understudy_pair_offer", offer: OFFER }, - { url: "https://understudy.proofof.tech/dashboard/pair" }, + { url: `${serviceOrigin}/dashboard/pair${suffix}` }, ), - ).toBe(OFFER); + ).toEqual({ offer: OFFER, serviceOrigin }); }); - it("accepts staging only when the build supplies the staging origin", () => { - expect( - externalPairingOffer( - { type: "understudy_pair_offer", offer: OFFER }, - { url: "https://staging.understudy.proofof.tech/dashboard/pair" }, - "https://staging.understudy.proofof.tech", - ), - ).toBe(OFFER); + it("accepts only staging when the build supplies the staging origin", () => { + const staging = "https://staging.understudy.proofof.tech"; expect( externalPairingOffer( { type: "understudy_pair_offer", offer: OFFER }, - { url: "https://understudy.proofof.tech/dashboard/pair" }, - "https://staging.understudy.proofof.tech", + { url: `${staging}/dashboard/pair` }, + [staging], ), - ).toBeNull(); + ).toEqual({ offer: OFFER, serviceOrigin: staging }); + for (const origin of ["https://understudy.proofof.tech", "https://browser.nomixhq.com"]) { + expect( + externalPairingOffer( + { type: "understudy_pair_offer", offer: OFFER }, + { url: `${origin}/dashboard/pair` }, + [staging], + ), + ).toBeNull(); + } + }); + + it("passes through the dashboard's absolute offer expiry", () => { + const serviceOrigin = "https://browser.nomixhq.com"; + const expiresAt = 1_234_567_890_123; + expect(externalPairingOffer( + { type: "understudy_pair_offer", offer: OFFER, expiresAt }, + { url: `${serviceOrigin}/dashboard/pair` }, + )).toEqual({ offer: OFFER, serviceOrigin, expiresAt }); }); it.each([ @@ -35,7 +52,9 @@ describe("externalPairingOffer", () => { "http://understudy.proofof.tech/dashboard/pair", "https://understudy.proofof.tech/dashboard/pair/", "https://understudy.proofof.tech/dashboard/pair?offer=secret", - "https://understudy.proofof.tech/dashboard/pair#fragment", + "https://browser.nomixhq.com/dashboard", + "https://browser.nomixhq.com/dashboard/pair?#fragment", + "https://staging.understudy.proofof.tech/dashboard/pair", "https://evil.example/dashboard/pair", ])("rejects sender URL %s", (url) => { expect( @@ -52,6 +71,9 @@ describe("externalPairingOffer", () => { { type: "understudy_pair_offer", offer: "short" }, { type: "other", offer: OFFER }, { type: "understudy_pair_offer", offer: OFFER, extra: true }, + { type: "understudy_pair_offer", offer: OFFER, expiresAt: "1234567890123" }, + { type: "understudy_pair_offer", offer: OFFER, expiresAt: Infinity }, + { type: "understudy_pair_offer", offer: OFFER, expiresAt: 1234567890123, extra: true }, ])("rejects malformed messages", (message) => { expect( externalPairingOffer(message, { @@ -60,3 +82,23 @@ describe("externalPairingOffer", () => { ).toBeNull(); }); }); + +describe("externalPairingStatusRequest", () => { + it("accepts a status request only from a permitted pairing page", () => { + const serviceOrigin = "https://browser.nomixhq.com"; + const message = { type: "understudy_pair_status", confirmationId: OFFER }; + expect(externalPairingStatusRequest(message, { url: `${serviceOrigin}/dashboard/pair` })) + .toEqual({ serviceOrigin, confirmationId: OFFER }); + expect(externalPairingStatusRequest(message, { url: `${serviceOrigin}/dashboard` })) + .toBeNull(); + }); +}); + +describe("pairingManagementUrl", () => { + it.each([ + ["https://understudy.proofof.tech", "https://understudy.proofof.tech/dashboard"], + ["https://browser.nomixhq.com", "https://browser.nomixhq.com/dashboard/pair"], + ])("links the paired profile at %s to its service's management page", (origin, url) => { + expect(pairingManagementUrl(origin)).toBe(url); + }); +}); diff --git a/apps/extension/src/core/external-pairing.ts b/apps/extension/src/core/external-pairing.ts index 3b795a2..7445ec7 100644 --- a/apps/extension/src/core/external-pairing.ts +++ b/apps/extension/src/core/external-pairing.ts @@ -1,27 +1,79 @@ -import { SERVICE_ORIGIN } from "../service-origin"; +import { PAIRING_PAGE_PATH, SERVICE_ORIGINS } from "../service-origin"; +import type { PairingOffer } from "./pairing-client"; + +const PAIRING_CODE = /^[A-Za-z0-9_-]{43}$/; + +interface ExternalPairingOffer extends PairingOffer { + expiresAt?: number; +} + +export interface ExternalPairingStatusRequest { + confirmationId: string; + serviceOrigin: string; +} export function externalPairingOffer( message: unknown, sender: { url?: string }, - serviceOrigin: string = SERVICE_ORIGIN, -): string | null { + serviceOrigins: readonly string[] = SERVICE_ORIGINS, +): ExternalPairingOffer | null { + const record = messageRecord(message); if ( - typeof sender.url !== "string" || - sender.url !== `${serviceOrigin}/dashboard/pair` + record === null || + record.type !== "understudy_pair_offer" || + typeof record.offer !== "string" || + !PAIRING_CODE.test(record.offer) ) { return null; } - if (typeof message !== "object" || message === null || Array.isArray(message)) { + const serviceOrigin = pairingPageOrigin(sender, serviceOrigins); + if (serviceOrigin === undefined) return null; + const keyCount = Object.keys(record).length; + if (!Object.hasOwn(record, "expiresAt")) { + return keyCount === 2 ? { offer: record.offer, serviceOrigin } : null; + } + if ( + keyCount !== 3 || + typeof record.expiresAt !== "number" || + !Number.isSafeInteger(record.expiresAt) || + record.expiresAt <= 0 + ) { return null; } - const record = message as Record; + return { offer: record.offer, serviceOrigin, expiresAt: record.expiresAt }; +} + +export function externalPairingStatusRequest( + message: unknown, + sender: { url?: string }, +): ExternalPairingStatusRequest | null { + const record = messageRecord(message); if ( + record === null || Object.keys(record).length !== 2 || - record.type !== "understudy_pair_offer" || - typeof record.offer !== "string" || - !/^[A-Za-z0-9_-]{43}$/.test(record.offer) + record.type !== "understudy_pair_status" || + typeof record.confirmationId !== "string" || + !PAIRING_CODE.test(record.confirmationId) ) { return null; } - return record.offer; + const serviceOrigin = pairingPageOrigin(sender, SERVICE_ORIGINS); + return serviceOrigin === undefined + ? null + : { confirmationId: record.confirmationId, serviceOrigin }; +} + +function pairingPageOrigin( + sender: { url?: string }, + serviceOrigins: readonly string[], +): string | undefined { + if (typeof sender.url !== "string") return undefined; + const [pageUrl] = sender.url.split("#", 1); + return serviceOrigins.find((origin) => pageUrl === `${origin}${PAIRING_PAGE_PATH}`); +} + +function messageRecord(message: unknown): Record | null { + return typeof message === "object" && message !== null && !Array.isArray(message) + ? message as Record + : null; } diff --git a/apps/extension/src/core/pairing-client.test.ts b/apps/extension/src/core/pairing-client.test.ts index fd0d692..21d8e0e 100644 --- a/apps/extension/src/core/pairing-client.test.ts +++ b/apps/extension/src/core/pairing-client.test.ts @@ -17,6 +17,8 @@ const OFFER = "a".repeat(43); const PREVIOUS_CREDENTIAL = `udt_v2_${"b".repeat(43)}`; const RECOVERED_CREDENTIAL = `udt_v2_${"e".repeat(43)}`; const CLAIM_ID = "d".repeat(43); +const SCP_ORIGIN = "https://browser.nomixhq.com"; +const UNDERSTUDY_OFFER = { offer: OFFER, serviceOrigin: DEFAULT_SERVICE_ORIGIN }; const VALID_BODY = { serviceOrigin: "https://understudy.proofof.tech", deviceId: "00000000-0000-4000-8000-000000000001", @@ -65,6 +67,7 @@ describe("redeemPairingOffer", () => { `${DEFAULT_SERVICE_ORIGIN}/v1/pairing/claim`, expect.objectContaining({ method: "POST", + redirect: "error", body: JSON.stringify({ offer: OFFER, claimId: CLAIM_ID, @@ -75,6 +78,29 @@ describe("redeemPairingOffer", () => { expect(result).toEqual(VALID_BODY); }); + it("redeems an SCP offer at the SCP claim endpoint", async () => { + const body = { ...VALID_BODY, serviceOrigin: SCP_ORIGIN }; + const fetchMock = stubFetch(200, body); + + await expect(redeemPairingOffer(OFFER, undefined, SCP_ORIGIN, CLAIM_ID)) + .resolves.toEqual(body); + expect(fetchMock).toHaveBeenCalledWith( + "https://browser.nomixhq.com/v1/pairing/claim", + expect.objectContaining({ + method: "POST", + body: JSON.stringify({ offer: OFFER, claimId: CLAIM_ID }), + }), + ); + }); + + it("refuses to send an offer to an unlisted service origin", async () => { + const fetchMock = stubFetch(200, VALID_BODY); + + await expect(redeemPairingOffer(OFFER, PREVIOUS_CREDENTIAL, "https://other.example")) + .rejects.toThrow(PairingError); + expect(fetchMock).not.toHaveBeenCalled(); + }); + it("rejects malformed offers and credentials before any network call", async () => { const fetchMock = stubFetch(200, VALID_BODY); await expect(redeemPairingOffer("short")).rejects.toThrow(PairingError); @@ -102,10 +128,13 @@ describe("redeemPairingOffer", () => { await expect(redeemPairingOffer(OFFER)).rejects.toThrow(/unreadable reply/); }); - it("rejects a pairing response from a different service authority", async () => { + it.each([ + "https://staging.understudy.proofof.tech", + SCP_ORIGIN, + ])("rejects a pairing response claiming a different service authority %s", async (serviceOrigin) => { stubFetch(200, { ...VALID_BODY, - serviceOrigin: "https://staging.understudy.proofof.tech", + serviceOrigin, }); await expect(redeemPairingOffer(OFFER)).rejects.toThrow( @@ -142,16 +171,39 @@ describe("PairingClaimCoordinator", () => { expect(values[PAIRING_CLAIM_KEY]).toBeUndefined(); }); + it("removes a durable claim with an unlisted origin before resolving its proof", async () => { + const { values, storage } = storageFixture({ + [PAIRING_CLAIM_KEY]: { + version: 4, + active: { + ...UNDERSTUDY_OFFER, + serviceOrigin: "https://other.example", + claimId: CLAIM_ID, + phase: "preparing", + previousCredential: null, + }, + queued: null, + stopRequested: false, + }, + }); + const getCredential = vi.fn(async () => PREVIOUS_CREDENTIAL); + + await expect(new PairingClaimCoordinator(storage).next(null, getCredential)) + .resolves.toBeNull(); + expect(getCredential).not.toHaveBeenCalled(); + expect(values[PAIRING_CLAIM_KEY]).toBeUndefined(); + }); + it("persists an offer before resolving its credential proof", async () => { const { values, storage } = storageFixture(); const coordinator = new PairingClaimCoordinator(storage); - await coordinator.request(OFFER); + await coordinator.request(UNDERSTUDY_OFFER); expect(values[PAIRING_CLAIM_KEY]).toEqual({ - version: 3, + version: 4, active: expect.objectContaining({ - offer: OFFER, + ...UNDERSTUDY_OFFER, phase: "preparing", previousCredential: null, }), @@ -160,7 +212,7 @@ describe("PairingClaimCoordinator", () => { }); await expect( - coordinator.next(OFFER, () => Promise.resolve(PREVIOUS_CREDENTIAL)), + coordinator.next(UNDERSTUDY_OFFER, () => Promise.resolve(PREVIOUS_CREDENTIAL)), ).resolves.toEqual( expect.objectContaining({ offer: OFFER, @@ -192,7 +244,7 @@ describe("PairingClaimCoordinator", () => { }; const coordinator = new PairingClaimCoordinator(storage); - const claiming = coordinator.request(OFFER); + const claiming = coordinator.request(UNDERSTUDY_OFFER); await vi.waitFor(() => expect(storage.set).toHaveBeenCalledOnce()); const clearing = coordinator.cancel(); releaseSet(); @@ -205,8 +257,8 @@ describe("PairingClaimCoordinator", () => { const { values, storage } = storageFixture(); const coordinator = new PairingClaimCoordinator(storage); - await coordinator.request(OFFER); - await coordinator.next(OFFER, () => Promise.resolve(PREVIOUS_CREDENTIAL)); + await coordinator.request(UNDERSTUDY_OFFER); + await coordinator.next(UNDERSTUDY_OFFER, () => Promise.resolve(PREVIOUS_CREDENTIAL)); await coordinator.cancel(); expect(values[PAIRING_CLAIM_KEY]).toBeUndefined(); @@ -225,15 +277,15 @@ describe("PairingClaimCoordinator", () => { const restarted = new PairingClaimCoordinator(storage); await expect( - restarted.next(OFFER, () => Promise.resolve(PREVIOUS_CREDENTIAL)), + restarted.next(UNDERSTUDY_OFFER, () => Promise.resolve(PREVIOUS_CREDENTIAL)), ).resolves.toEqual({ - offer: OFFER, + ...UNDERSTUDY_OFFER, claimId: CLAIM_ID, previousCredential: PREVIOUS_CREDENTIAL, }); expect(values[PAIRING_CLAIM_KEY]).toEqual( expect.objectContaining({ - version: 3, + version: 4, active: expect.objectContaining({ claimId: CLAIM_ID, phase: "ready", @@ -243,11 +295,46 @@ describe("PairingClaimCoordinator", () => { ); }); + it("recovers a version-3 active and queued offer at the original build origin", async () => { + const queuedOffer = "f".repeat(43); + const queuedClaimId = "g".repeat(43); + const { storage } = storageFixture({ + [PAIRING_CLAIM_KEY]: { + version: 3, + active: { + offer: OFFER, + claimId: CLAIM_ID, + phase: "dispatched", + previousCredential: PREVIOUS_CREDENTIAL, + }, + queued: { offer: queuedOffer, claimId: queuedClaimId }, + stopRequested: false, + }, + }); + const restarted = new PairingClaimCoordinator(storage); + const claim = await restarted.next(null, async () => RECOVERED_CREDENTIAL); + expect(claim).toEqual({ + ...UNDERSTUDY_OFFER, + claimId: CLAIM_ID, + previousCredential: PREVIOUS_CREDENTIAL, + }); + if (claim === null) throw new Error("claim not recovered"); + + await restarted.complete(claim); + + await expect(restarted.next(null, async () => RECOVERED_CREDENTIAL)).resolves.toEqual({ + offer: queuedOffer, + serviceOrigin: DEFAULT_SERVICE_ORIGIN, + claimId: queuedClaimId, + previousCredential: RECOVERED_CREDENTIAL, + }); + }); + it("preserves a dispatched claim through Stop All and replays its exact proof", async () => { const { values, storage } = storageFixture(); const coordinator = new PairingClaimCoordinator(storage); - await coordinator.request(OFFER); - const original = await coordinator.next(OFFER, () => + await coordinator.request(UNDERSTUDY_OFFER); + const original = await coordinator.next(UNDERSTUDY_OFFER, () => Promise.resolve(PREVIOUS_CREDENTIAL), ); if (original === null) throw new Error("claim not prepared"); @@ -271,15 +358,15 @@ describe("PairingClaimCoordinator", () => { it("does not let a duplicate dispatched offer undo Stop All", async () => { const { storage } = storageFixture(); const coordinator = new PairingClaimCoordinator(storage); - await coordinator.request(OFFER); - const original = await coordinator.next(OFFER, () => + await coordinator.request(UNDERSTUDY_OFFER); + const original = await coordinator.next(UNDERSTUDY_OFFER, () => Promise.resolve(PREVIOUS_CREDENTIAL), ); if (original === null) throw new Error("claim not prepared"); await coordinator.markDispatched(original); await coordinator.cancel(); - await coordinator.request(OFFER); + await coordinator.request(UNDERSTUDY_OFFER); await expect(coordinator.disposition(original)).resolves.toEqual({ allowHosting: false, @@ -291,14 +378,14 @@ describe("PairingClaimCoordinator", () => { it("recovers a dispatched rotation before proving a queued offer", async () => { const { values, storage } = storageFixture(); const coordinator = new PairingClaimCoordinator(storage); - await coordinator.request(OFFER); - const original = await coordinator.next(OFFER, () => + await coordinator.request(UNDERSTUDY_OFFER); + const original = await coordinator.next(UNDERSTUDY_OFFER, () => Promise.resolve(PREVIOUS_CREDENTIAL), ); if (original === null) throw new Error("claim not prepared"); await coordinator.markDispatched(original); - const nextOffer = "f".repeat(43); + const nextOffer = { ...UNDERSTUDY_OFFER, offer: "f".repeat(43) }; await coordinator.request(nextOffer); await expect(coordinator.disposition(original)).resolves.toEqual({ @@ -314,7 +401,7 @@ describe("PairingClaimCoordinator", () => { phase: "dispatched", previousCredential: PREVIOUS_CREDENTIAL, }), - queued: expect.objectContaining({ offer: nextOffer }), + queued: expect.objectContaining(nextOffer), }), ); @@ -324,28 +411,61 @@ describe("PairingClaimCoordinator", () => { ); expect(promoted).toEqual( expect.objectContaining({ - offer: nextOffer, + ...nextOffer, previousCredential: RECOVERED_CREDENTIAL, }), ); }); + it("preserves the origin and retry identity of separate claims for identical offers", async () => { + const { storage } = storageFixture(); + const coordinator = new PairingClaimCoordinator(storage); + await coordinator.request(UNDERSTUDY_OFFER); + const dispatched = await coordinator.next(UNDERSTUDY_OFFER, async () => PREVIOUS_CREDENTIAL); + if (dispatched === null) throw new Error("claim not prepared"); + await coordinator.markDispatched(dispatched); + + const scpOffer = { offer: OFFER, serviceOrigin: SCP_ORIGIN }; + await coordinator.request(scpOffer); + const restarted = new PairingClaimCoordinator(storage); + const getCredential = vi.fn(async (_origin: string) => undefined); + await expect(restarted.next(scpOffer, getCredential)).resolves.toEqual(dispatched); + expect(getCredential).not.toHaveBeenCalled(); + await restarted.complete(dispatched); + + const promoted = await restarted.next(scpOffer, getCredential); + expect(promoted).toEqual({ + ...scpOffer, + claimId: expect.stringMatching(/^[A-Za-z0-9_-]{43}$/), + previousCredential: undefined, + }); + expect(getCredential).toHaveBeenCalledWith(SCP_ORIGIN); + if (promoted === null) throw new Error("queued claim not prepared"); + expect(promoted.claimId).not.toBe(dispatched.claimId); + await restarted.markDispatched(promoted); + + const recovered = new PairingClaimCoordinator(storage); + await expect(recovered.next(null, getCredential)).resolves.toEqual(promoted); + expect(getCredential).toHaveBeenCalledOnce(); + }); + it("does not let an obsolete completion remove a replacement", async () => { const { storage } = storageFixture(); const coordinator = new PairingClaimCoordinator(storage); - await coordinator.request(OFFER); - const obsolete = await coordinator.next(OFFER, () => + await coordinator.request(UNDERSTUDY_OFFER); + const obsolete = await coordinator.next(UNDERSTUDY_OFFER, () => Promise.resolve(PREVIOUS_CREDENTIAL), ); if (obsolete === null) throw new Error("claim not prepared"); - await coordinator.request("f".repeat(43)); + const replacement = { ...UNDERSTUDY_OFFER, offer: "f".repeat(43) }; + await coordinator.request(replacement); await expect(coordinator.complete(obsolete)).resolves.toBe(false); await expect( - coordinator.next("f".repeat(43), () => Promise.resolve(RECOVERED_CREDENTIAL)), + coordinator.next(replacement, () => Promise.resolve(RECOVERED_CREDENTIAL)), ).resolves.toEqual( expect.objectContaining({ - offer: "f".repeat(43), + ...replacement, previousCredential: RECOVERED_CREDENTIAL, }), ); @@ -354,10 +474,10 @@ describe("PairingClaimCoordinator", () => { it("does not let a stale scheduler consume the newest queued offer", async () => { const { storage } = storageFixture(); const coordinator = new PairingClaimCoordinator(storage); - const staleOffer = "f".repeat(43); - const latestOffer = "e".repeat(43); - await coordinator.request(OFFER); - const dispatched = await coordinator.next(OFFER, () => + const staleOffer = { ...UNDERSTUDY_OFFER, offer: "f".repeat(43) }; + const latestOffer = { ...UNDERSTUDY_OFFER, offer: "e".repeat(43) }; + await coordinator.request(UNDERSTUDY_OFFER); + const dispatched = await coordinator.next(UNDERSTUDY_OFFER, () => Promise.resolve(PREVIOUS_CREDENTIAL), ); if (dispatched === null) throw new Error("claim not prepared"); @@ -376,7 +496,7 @@ describe("PairingClaimCoordinator", () => { coordinator.next(latestOffer, () => Promise.resolve(RECOVERED_CREDENTIAL)), ).resolves.toEqual( expect.objectContaining({ - offer: latestOffer, + ...latestOffer, previousCredential: RECOVERED_CREDENTIAL, }), ); diff --git a/apps/extension/src/core/pairing-client.ts b/apps/extension/src/core/pairing-client.ts index cd1880c..0407152 100644 --- a/apps/extension/src/core/pairing-client.ts +++ b/apps/extension/src/core/pairing-client.ts @@ -11,7 +11,7 @@ import { readBoundedJson, withRequestDeadline, } from "./request-deadline"; -import { SERVICE_ORIGIN } from "../service-origin"; +import { SERVICE_ORIGIN, isServiceOrigin } from "../service-origin"; export const DEFAULT_SERVICE_ORIGIN = SERVICE_ORIGIN; export const PAIRING_CLAIM_KEY = "understudy:pairingClaim"; @@ -24,9 +24,16 @@ interface PairingClaimStorage { remove(key: string): Promise; } -export interface PairingClaim { +export interface PairingOffer { offer: string; + serviceOrigin: string; +} + +interface PairingClaimIdentity extends PairingOffer { claimId: string; +} + +export interface PairingClaim extends PairingClaimIdentity { previousCredential: string | undefined; } @@ -36,14 +43,9 @@ interface PairingIntent extends PairingClaim { phase: PairingClaimPhase; } -interface QueuedPairingIntent { - offer: string; - claimId: string; -} - interface PairingIntentState { active: PairingIntent; - queued: QueuedPairingIntent | null; + queued: PairingClaimIdentity | null; stopRequested: boolean; } @@ -58,7 +60,7 @@ export class PairingClaimCoordinator { constructor(private readonly storage: PairingClaimStorage) {} - request(offer: string): Promise { + request(offer: PairingOffer): Promise { return this.exclusive(async () => { const stored = await loadPairingState(this.storage); if (stored === null) { @@ -69,16 +71,16 @@ export class PairingClaimCoordinator { }); return; } - if (stored.active.offer === offer) { + if (samePairingOffer(stored.active, offer)) { return; } if (stored.active.phase === "dispatched") { await putPairingState(this.storage, { active: stored.active, queued: - stored.queued?.offer === offer + stored.queued !== null && samePairingOffer(stored.queued, offer) ? stored.queued - : { offer, claimId: createPairingClaimId() }, + : { ...offer, claimId: createPairingClaimId() }, stopRequested: false, }); return; @@ -92,8 +94,8 @@ export class PairingClaimCoordinator { } next( - targetOffer: string | null, - getCurrentCredential: () => Promise, + targetOffer: PairingOffer | null, + getCurrentCredential: (serviceOrigin: string) => Promise, ): Promise { return this.exclusive(async () => { const stored = await loadPairingState(this.storage); @@ -101,7 +103,7 @@ export class PairingClaimCoordinator { if ( targetOffer !== null && stored.active.phase !== "dispatched" && - stored.active.offer !== targetOffer + !samePairingOffer(stored.active, targetOffer) ) { return null; } @@ -112,7 +114,7 @@ export class PairingClaimCoordinator { ...stored, active: { ...stored.active, - previousCredential: await getCurrentCredential(), + previousCredential: await getCurrentCredential(stored.active.serviceOrigin), phase: "ready", }, }; @@ -158,19 +160,7 @@ export class PairingClaimCoordinator { if (stored === null || !samePairingClaim(stored.active, expected)) { return false; } - if (stored.queued === null) { - await this.storage.remove(PAIRING_CLAIM_KEY); - } else { - await putPairingState(this.storage, { - active: { - ...stored.queued, - previousCredential: undefined, - phase: "preparing", - }, - queued: null, - stopRequested: false, - }); - } + await this.finishActive(stored); return true; }); } @@ -179,6 +169,23 @@ export class PairingClaimCoordinator { return this.complete(expected); } + rejectBeforeDifferentService(expected: PairingClaim): Promise { + return this.exclusive(async () => { + const stored = await loadPairingState(this.storage); + if ( + stored === null || + stored.active.phase !== "dispatched" || + !samePairingClaim(stored.active, expected) || + stored.queued === null || + stored.queued.serviceOrigin === expected.serviceOrigin + ) { + return false; + } + await this.finishActive(stored); + return true; + }); + } + cancel(): Promise { return this.exclusive(async () => { const stored = await loadPairingState(this.storage); @@ -194,6 +201,22 @@ export class PairingClaimCoordinator { }); } + private async finishActive(stored: PairingIntentState): Promise { + if (stored.queued === null) { + await this.storage.remove(PAIRING_CLAIM_KEY); + } else { + await putPairingState(this.storage, { + active: { + ...stored.queued, + previousCredential: undefined, + phase: "preparing", + }, + queued: null, + stopRequested: false, + }); + } + } + private exclusive(operation: () => Promise): Promise { const result = this.operationTail.then(operation, operation); this.operationTail = result.then( @@ -245,7 +268,7 @@ async function putPairingState( ): Promise { await storage.set({ [PAIRING_CLAIM_KEY]: { - version: 3, + version: 4, active: serializePairingIntent(state.active), queued: state.queued, stopRequested: state.stopRequested, @@ -265,9 +288,13 @@ function parsePairingState(value: unknown): PairingIntentState | null { credentialResolved?: unknown; previousCredential?: unknown; }; - if (candidate.version === 3) { - const active = parsePairingIntent(candidate.active); - const queued = parseQueuedPairingIntent(candidate.queued); + if (candidate.version === 3 || candidate.version === 4) { + const legacyOrigin = candidate.version === 3 ? DEFAULT_SERVICE_ORIGIN : undefined; + const active = parsePairingIntent(candidate.active, legacyOrigin); + const queued = + candidate.queued === null + ? null + : parsePairingClaimIdentity(candidate.queued, legacyOrigin); if ( active === null || queued === undefined || @@ -302,6 +329,7 @@ function parseLegacyPairingState(candidate: { active: { offer: candidate.offer as string, claimId: candidate.claimId as string, + serviceOrigin: DEFAULT_SERVICE_ORIGIN, previousCredential: nullableCredential(candidate.previousCredential), phase: credentialResolved ? "ready" : "preparing", }, @@ -310,17 +338,14 @@ function parseLegacyPairingState(candidate: { }; } -function parsePairingIntent(value: unknown): PairingIntent | null { - if (typeof value !== "object" || value === null) return null; +function parsePairingIntent(value: unknown, legacyOrigin?: string): PairingIntent | null { + const identity = parsePairingClaimIdentity(value, legacyOrigin); + if (identity === undefined) return null; const candidate = value as { - offer?: unknown; - claimId?: unknown; previousCredential?: unknown; phase?: unknown; }; if ( - !validOffer(candidate.offer) || - !validClaimId(candidate.claimId) || !validPreviousCredential(candidate.previousCredential) || (candidate.phase !== "preparing" && candidate.phase !== "ready" && @@ -330,34 +355,42 @@ function parsePairingIntent(value: unknown): PairingIntent | null { return null; } return { - offer: candidate.offer as string, - claimId: candidate.claimId as string, + ...identity, previousCredential: nullableCredential(candidate.previousCredential), phase: candidate.phase, }; } -function parseQueuedPairingIntent(value: unknown): QueuedPairingIntent | null | undefined { - if (value === null) return null; +function parsePairingClaimIdentity( + value: unknown, + legacyOrigin?: string, +): PairingClaimIdentity | undefined { if (typeof value !== "object" || value === null) return undefined; - const candidate = value as { offer?: unknown; claimId?: unknown }; - return validOffer(candidate.offer) && validClaimId(candidate.claimId) - ? { offer: candidate.offer as string, claimId: candidate.claimId as string } - : undefined; + const candidate = value as { offer?: unknown; claimId?: unknown; serviceOrigin?: unknown }; + const serviceOrigin = legacyOrigin ?? candidate.serviceOrigin; + if ( + !validOffer(candidate.offer) || + !validClaimId(candidate.claimId) || + !isServiceOrigin(serviceOrigin) + ) { + return undefined; + } + return { offer: candidate.offer, claimId: candidate.claimId, serviceOrigin }; } function serializePairingIntent(intent: PairingIntent): Record { return { offer: intent.offer, claimId: intent.claimId, + serviceOrigin: intent.serviceOrigin, previousCredential: intent.previousCredential ?? null, phase: intent.phase, }; } -function newPairingIntent(offer: string): PairingIntent { +function newPairingIntent(offer: PairingOffer): PairingIntent { return { - offer, + ...offer, claimId: createPairingClaimId(), previousCredential: undefined, phase: "preparing", @@ -387,13 +420,18 @@ function toPairingClaim(intent: PairingIntent): PairingClaim { return { offer: intent.offer, claimId: intent.claimId, + serviceOrigin: intent.serviceOrigin, previousCredential: intent.previousCredential, }; } +export function samePairingOffer(left: PairingOffer, right: PairingOffer): boolean { + return left.offer === right.offer && left.serviceOrigin === right.serviceOrigin; +} + function samePairingClaim(left: PairingClaim, right: PairingClaim): boolean { return ( - left.offer === right.offer && + samePairingOffer(left, right) && left.claimId === right.claimId && left.previousCredential === right.previousCredential ); @@ -443,11 +481,15 @@ export async function redeemPairingOffer( if (!/^[A-Za-z0-9_-]{43}$/.test(claimId)) { throw new PairingError("The browser pairing attempt is invalid. Generate a new offer."); } + if (!isServiceOrigin(serviceOrigin)) { + throw new PairingError("The pairing service origin is not allowed in this build."); + } let response: Response; try { response = await withRequestDeadline(PAIRING_REQUEST_TIMEOUT_MS, (signal) => fetch(new URL("/v1/pairing/claim", serviceOrigin).toString(), { method: "POST", + redirect: "error", headers: { "content-type": "application/json" }, body: JSON.stringify({ offer, diff --git a/apps/extension/src/core/profile-client.test.ts b/apps/extension/src/core/profile-client.test.ts index 1039b8c..04fa4e7 100644 --- a/apps/extension/src/core/profile-client.test.ts +++ b/apps/extension/src/core/profile-client.test.ts @@ -11,6 +11,9 @@ const CONFIG: ProfileConfig = { policyVersion: 1, }; const EPOCH = "browser-epoch-1"; +const UNDERSTUDY_ORIGIN = "https://understudy.proofof.tech"; +const SCP_ORIGIN = "https://browser.nomixhq.com"; +const STORE_SERVICE_ORIGINS = [UNDERSTUDY_ORIGIN, SCP_ORIGIN]; type Listener = (event: Event & { code?: number; data?: unknown }) => void; @@ -224,7 +227,7 @@ describe("ProfileClient generation fencing", () => { deviceId: CONFIG.deviceId, policyVersion: 1, }); - await expect(client.pairingCredential()).resolves.toBe(CONFIG.deviceCredential); + await expect(client.pairingCredential(CONFIG.serviceOrigin)).resolves.toBe(CONFIG.deviceCredential); expect(fixture.local.policyVersion).toBe(1); }); @@ -671,8 +674,8 @@ describe("ProfileClient generation fencing", () => { }), ); await expect( - client.pairingTransitionPersisted(replacement), - ).resolves.toBe(true); + client.persistedPairingTransition(replacement), + ).resolves.toBe("active"); }); it("discards a stale revoked identity before activating its fresh device", async () => { @@ -875,7 +878,7 @@ describe("ProfileClient generation fencing", () => { expect(fixture.local.unattendedEnabled).toBe(false); expect(fixture.local["understudy:credentialRevoked"]).toBe(true); - await expect(client.pairingCredential()).resolves.toBeUndefined(); + await expect(client.pairingCredential(CONFIG.serviceOrigin)).resolves.toBeUndefined(); expect(fetchMock).toHaveBeenCalledOnce(); }); @@ -888,7 +891,7 @@ describe("ProfileClient generation fencing", () => { expect(client.currentStatus()).toBe("error"); expect(fixture.local["understudy:credentialRevoked"]).toBe(true); - await expect(client.pairingCredential()).resolves.toBeUndefined(); + await expect(client.pairingCredential(CONFIG.serviceOrigin)).resolves.toBeUndefined(); }); it("releases a provision that finishes after Stop All without acknowledging provision", async () => { @@ -1108,7 +1111,7 @@ describe("ProfileClient generation fencing", () => { await vi.waitFor(() => expect(sessionSocket.closeCount).toBe(1)); await vi.waitFor(() => expect(client.sessions.assignments()).toEqual([])); expect(fixture.local["understudy:credentialRevoked"]).toBe(true); - await expect(client.pairingCredential()).resolves.toBeUndefined(); + await expect(client.pairingCredential(CONFIG.serviceOrigin)).resolves.toBeUndefined(); }); }); @@ -1129,11 +1132,11 @@ describe("ProfileClient startup cleanup", () => { expect(client.currentStatus()).toBe("disabled"); }); - it("rejects configuration outside a build-pinned service origin", () => { + it("rejects configuration outside the build-pinned service origins", () => { const fixture = installBrowser(); const client = new ProfileClient( undefined, - "https://understudy.proofof.tech", + STORE_SERVICE_ORIGINS, ); expect(() => client.configure(CONFIG)).toThrow( @@ -1142,7 +1145,7 @@ describe("ProfileClient startup cleanup", () => { expect(fixture.localArea.set).not.toHaveBeenCalled(); }); - it("discards a persisted profile outside a build-pinned service origin", async () => { + it("discards a persisted profile outside the build-pinned service origins", async () => { const fixture = installBrowser({ local: persistedConfig(CONFIG), session: { "understudy:browserEpoch": EPOCH }, @@ -1151,7 +1154,7 @@ describe("ProfileClient startup cleanup", () => { vi.stubGlobal("fetch", fetchMock); const client = new ProfileClient( undefined, - "https://understudy.proofof.tech", + STORE_SERVICE_ORIGINS, ); await client.start(); @@ -1164,6 +1167,39 @@ describe("ProfileClient startup cleanup", () => { expect(FakeWebSocket.instances).toHaveLength(0); }); + it("restores an SCP profile and connects through its stored service origin", async () => { + installBrowser({ + local: persistedConfig({ ...CONFIG, serviceOrigin: SCP_ORIGIN }), + session: { "understudy:browserEpoch": EPOCH }, + }); + const fetchMock = vi.fn(async () => ticketResponse()); + vi.stubGlobal("fetch", fetchMock); + const client = new ProfileClient(undefined, STORE_SERVICE_ORIGINS); + + await client.start(); + + expect(client.publicConfig()).toMatchObject({ serviceOrigin: SCP_ORIGIN }); + expect(fetchMock).toHaveBeenCalledOnce(); + expect(fetchMock).toHaveBeenCalledWith( + "https://browser.nomixhq.com/v1/device/connect-ticket", + expect.objectContaining({ method: "POST", redirect: "error" }), + ); + expect(FakeWebSocket.instances[0]?.url).toMatch( + /^wss:\/\/browser\.nomixhq\.com\/agents\/device\/device\?ticket=/, + ); + }); + + it("offers the current credential as pairing proof only at its own service origin", async () => { + installBrowser({ + local: persistedConfig({ ...CONFIG, serviceOrigin: UNDERSTUDY_ORIGIN }), + }); + const client = new ProfileClient(undefined, STORE_SERVICE_ORIGINS); + + await expect(client.pairingCredential(UNDERSTUDY_ORIGIN)) + .resolves.toBe(CONFIG.deviceCredential); + await expect(client.pairingCredential(SCP_ORIGIN)).resolves.toBeUndefined(); + }); + it("retains and resends a closure until the backend acknowledges its exact fence", async () => { const closure = { sessionId: "session-closed", @@ -1216,6 +1252,70 @@ describe("ProfileClient startup cleanup", () => { await vi.waitFor(() => expect(client.currentStatus()).toBe("disabled")); }); + it("sends an orphaned window's closure to the previous service before switching", async () => { + // #given + const closure = { + sessionId: "session-orphaned", + leaseId: "lease-orphaned", + leaseEpoch: 1, + browserEpoch: EPOCH, + }; + const fixture = installBrowser({ + local: persistedConfig({ + ...CONFIG, + serviceOrigin: UNDERSTUDY_ORIGIN, + unattendedEnabled: false, + }), + session: { + "understudy:browserEpoch": EPOCH, + "understudy:assignments": { + version: 4, + assignments: [], + ownedWindows: [{ ...closure, tabId: 7, windowId: 3 }], + closedOutbox: [], + vacatedLeases: [], + }, + }, + }); + fixture.removeWindow.mockRejectedValue(new Error("window still exists")); + vi.stubGlobal("fetch", vi.fn(async () => ticketResponse())); + const client = new ProfileClient(undefined, STORE_SERVICE_ORIGINS); + await client.start(); + expect(client.sessions.assignments()).toEqual([]); + expect(client.sessions.closureOutbox()).toEqual([]); + expect(client.sessions.ownedWindows()).toHaveLength(1); + + // #when + const replacement = { + ...CONFIG, + serviceOrigin: SCP_ORIGIN, + deviceCredential: "new-credential", + }; + await expect(client.configurePaired(replacement, undefined)).rejects.toThrow( + "paired profile configuration was superseded", + ); + + // #then + await expect(client.persistedPairingTransition(replacement)).resolves.toBe("staged"); + await expect(client.persistedPairingTransition({ + ...replacement, + deviceCredential: "unrelated-credential", + })).resolves.toBeNull(); + expect(fixture.local.serviceOrigin).toBe(UNDERSTUDY_ORIGIN); + const cleanup = FakeWebSocket.instances.at(-1); + expect(cleanup?.url).toMatch(/^wss:\/\/understudy\.proofof\.tech\//); + fixture.removeWindow.mockResolvedValue(undefined); + cleanup?.open(); + await vi.waitFor(() => + expect(cleanup?.sent).toContainEqual({ type: "closed", ...closure }), + ); + cleanup?.message({ type: "closed_ack", ...closure }); + await vi.waitFor(() => + expect(FakeWebSocket.instances.at(-1)?.url).toMatch(/^wss:\/\/browser\.nomixhq\.com\//), + ); + expect(fixture.local.serviceOrigin).toBe(SCP_ORIGIN); + }); + it("settles old-epoch closures before registering a new Chrome epoch", async () => { const oldAssignment = { sessionId: "session-old-epoch", @@ -1503,7 +1603,7 @@ describe("ProfileClient startup cleanup", () => { expect(client.sessions.closureOutbox()).toEqual([]); expect(fetchMock).not.toHaveBeenCalled(); expect(client.currentStatus()).toBe("error"); - await expect(client.pairingCredential()).resolves.toBeUndefined(); + await expect(client.pairingCredential(CONFIG.serviceOrigin)).resolves.toBeUndefined(); }); it("resumes a crash-fenced identity replacement only after local ownership closes", async () => { @@ -1519,6 +1619,7 @@ describe("ProfileClient startup cleanup", () => { }; const replacement: ProfileConfig = { ...CONFIG, + serviceOrigin: SCP_ORIGIN, deviceId: "00000000-0000-4000-8000-000000000002", deviceCredential: "fresh-credential", }; @@ -1544,7 +1645,7 @@ describe("ProfileClient startup cleanup", () => { async (_input: RequestInfo | URL, _init?: RequestInit) => ticketResponse(), ); vi.stubGlobal("fetch", fetchMock); - const client = new ProfileClient(); + const client = new ProfileClient(undefined, STORE_SERVICE_ORIGINS); await client.start(); expect(fetchMock).not.toHaveBeenCalled(); @@ -1556,6 +1657,7 @@ describe("ProfileClient startup cleanup", () => { expect(client.sessions.assignments()).toEqual([]); expect(client.sessions.ownedWindows()).toEqual([]); expect(fetchMock).toHaveBeenCalledOnce(); + expect(fetchMock.mock.calls[0]?.[0]).toBe("https://browser.nomixhq.com/v1/device/connect-ticket"); expect(fetchMock.mock.calls[0]?.[1]?.headers).toEqual({ authorization: "Bearer fresh-credential", "content-type": "application/json", @@ -1672,7 +1774,7 @@ describe("ProfileClient startup cleanup", () => { windowId: 3, }; const fixture = installBrowser({ - local: persistedConfig(CONFIG), + local: persistedConfig({ ...CONFIG, serviceOrigin: UNDERSTUDY_ORIGIN }), session: { "understudy:browserEpoch": EPOCH, "understudy:assignments": [assignment], @@ -1683,18 +1785,18 @@ describe("ProfileClient startup cleanup", () => { ticketResponse(), ); vi.stubGlobal("fetch", fetchMock); - const client = new ProfileClient(); + const client = new ProfileClient(undefined, STORE_SERVICE_ORIGINS); await client.start(); fixture.removeWindow.mockResolvedValue(undefined); const replacement: ProfileConfig = { ...CONFIG, - serviceOrigin: "https://new.example", + serviceOrigin: SCP_ORIGIN, deviceCredential: "new-credential", }; await client.configure(replacement); - expect(fixture.local.serviceOrigin).toBe(CONFIG.serviceOrigin); + expect(fixture.local.serviceOrigin).toBe(UNDERSTUDY_ORIGIN); expect(fixture.local.unattendedEnabled).toBe(false); expect(fixture.local["understudy:stagedProfile"]).toEqual(replacement); expect(FakeWebSocket.instances).toHaveLength(2); @@ -1740,9 +1842,9 @@ describe("ProfileClient startup cleanup", () => { ).toEqual([]); expect(fetchMock.mock.calls.map(([url]) => url)).toEqual([ - "https://old.example/v1/device/connect-ticket", - "https://old.example/v1/device/connect-ticket", - "https://new.example/v1/device/connect-ticket", + "https://understudy.proofof.tech/v1/device/connect-ticket", + "https://understudy.proofof.tech/v1/device/connect-ticket", + "https://browser.nomixhq.com/v1/device/connect-ticket", ]); expect(fixture.local.serviceOrigin).toBe(replacement.serviceOrigin); expect(fixture.local.unattendedEnabled).toBe(true); diff --git a/apps/extension/src/core/profile-client.ts b/apps/extension/src/core/profile-client.ts index 8932acc..7ce0b1c 100644 --- a/apps/extension/src/core/profile-client.ts +++ b/apps/extension/src/core/profile-client.ts @@ -96,7 +96,7 @@ export class ProfileClient { constructor( private readonly onStatus?: (status: ProfileStatus) => void, - private readonly requiredServiceOrigin?: string, + private readonly allowedServiceOrigins?: readonly string[], ) { this.sessions = new SessionManager( () => this.requiredConfig().serviceOrigin, @@ -197,12 +197,19 @@ export class ProfileClient { }; } - async pairingCredential(): Promise { + async pairingCredential(serviceOrigin: string): Promise { await this.ensureInitialized(); - return this.credentialRevoked ? undefined : this.config?.deviceCredential; + if (this.credentialRevoked || this.config?.serviceOrigin !== serviceOrigin) { + return undefined; + } + return this.config.deviceCredential; + } + + stagedServiceOrigin(): string | null { + return this.stagedConfig?.serviceOrigin ?? null; } - async pairingTransitionPersisted(expected: ProfileConfig): Promise { + async persistedPairingTransition(expected: ProfileConfig): Promise<"active" | "staged" | null> { await this.ensureInitialized(); await this.configWriteTail; const stored = await browser.storage.local.get([ @@ -210,15 +217,15 @@ export class ProfileClient { STAGED_CONFIG_KEY, CREDENTIAL_REVOKED_KEY, ]); - if ( - stored[STAGED_CONFIG_KEY] !== null && - stored[STAGED_CONFIG_KEY] !== undefined - ) { - return false; - } - let active: ProfileConfig; + const staged = stored[STAGED_CONFIG_KEY]; try { - active = normalizeProfileConfig({ + const normalized = normalizeProfileConfig(expected); + if (staged !== null && staged !== undefined) { + return sameProfileConfig(normalizeProfileConfig(staged), normalized) + ? "staged" + : null; + } + const active = normalizeProfileConfig({ serviceOrigin: stored.serviceOrigin, unattendedEnabled: stored.unattendedEnabled, deviceId: stored.deviceId, @@ -226,13 +233,12 @@ export class ProfileClient { originPolicy: stored.originPolicy, policyVersion: stored.policyVersion, }); + return stored[CREDENTIAL_REVOKED_KEY] !== true && samePairingAuthority(active, normalized) + ? "active" + : null; } catch { - return false; + return null; } - return ( - stored[CREDENTIAL_REVOKED_KEY] !== true && - samePairingAuthority(active, normalizeProfileConfig(expected)) - ); } configure(config: ProfileConfig): Promise { @@ -245,7 +251,9 @@ export class ProfileClient { ): Promise { const discardPrevious = previousCredential !== undefined && - this.config?.deviceCredential === previousCredential && + this.config !== null && + this.config.serviceOrigin === config.serviceOrigin && + this.config.deviceCredential === previousCredential && this.config.deviceId !== config.deviceId; return this.configureWithTransition(config, discardPrevious, true); } @@ -331,7 +339,8 @@ export class ProfileClient { (current.unattendedEnabled || this.sessions.assignments().length > 0 || this.sessions.closureOutbox().length > 0 || - this.sessions.vacatedLeases().length > 0); + this.sessions.vacatedLeases().length > 0 || + this.sessions.pendingCleanup()); if (current !== null && rotatesCurrentDevice) { if ( @@ -524,6 +533,7 @@ export class ProfileClient { new URL("/v1/device/connect-ticket", config.serviceOrigin).toString(), { method: "POST", + redirect: "error", headers: { authorization: `Bearer ${config.deviceCredential}`, "content-type": "application/json", @@ -1096,7 +1106,8 @@ export class ProfileClient { current.unattendedEnabled || this.sessions.assignments().length > 0 || this.sessions.closureOutbox().length > 0 || - this.sessions.vacatedLeases().length > 0; + this.sessions.vacatedLeases().length > 0 || + this.sessions.pendingCleanup(); return ownsOldWork ? "release" : null; } @@ -1184,9 +1195,6 @@ export class ProfileClient { } catch { active = null; } - if (active !== null && stored.policyVersion === undefined) { - await browser.storage.local.set({ policyVersion: active.policyVersion }); - } let staged: ProfileConfig | null; try { staged = @@ -1198,10 +1206,8 @@ export class ProfileClient { staged = null; } if ( - this.requiredServiceOrigin !== undefined && stored.serviceOrigin !== undefined && - (active === null || - active.serviceOrigin !== this.requiredServiceOrigin) + !this.allowsServiceOrigin(active) ) { await browser.storage.local.remove([...PROFILE_STATE_KEYS]); return { @@ -1212,15 +1218,16 @@ export class ProfileClient { }; } if ( - this.requiredServiceOrigin !== undefined && stored[STAGED_CONFIG_KEY] !== null && stored[STAGED_CONFIG_KEY] !== undefined && - (staged === null || - staged.serviceOrigin !== this.requiredServiceOrigin) + !this.allowsServiceOrigin(staged) ) { staged = null; await browser.storage.local.remove(STAGED_CONFIG_KEY); } + if (active !== null && stored.policyVersion === undefined) { + await browser.storage.local.set({ policyVersion: active.policyVersion }); + } return { active, staged, @@ -1282,14 +1289,18 @@ export class ProfileClient { } private assertServiceOrigin(config: ProfileConfig): void { - if ( - this.requiredServiceOrigin !== undefined && - config.serviceOrigin !== this.requiredServiceOrigin - ) { + if (!this.allowsServiceOrigin(config)) { throw new Error("profile service origin is not allowed in this build"); } } + private allowsServiceOrigin(config: ProfileConfig | null): boolean { + return ( + this.allowedServiceOrigins === undefined || + (config !== null && this.allowedServiceOrigins.includes(config.serviceOrigin)) + ); + } + private pairedTransitionCommitted( expected: ProfileConfig, generation: number, diff --git a/apps/extension/src/entrypoints/background.ts b/apps/extension/src/entrypoints/background.ts index ff228ab..fe39023 100644 --- a/apps/extension/src/entrypoints/background.ts +++ b/apps/extension/src/entrypoints/background.ts @@ -19,13 +19,19 @@ import { resolveAttendedTransition } from "../core/attended-switch"; import { sendIfPeerCurrent } from "../core/peer-binding"; import { routeCommand } from "../core/router"; import { RetryableStartupGate } from "../core/startup-gate"; -import { externalPairingOffer } from "../core/external-pairing"; import { - DEFAULT_SERVICE_ORIGIN, + externalPairingOffer, + externalPairingStatusRequest, + type ExternalPairingStatusRequest, +} from "../core/external-pairing"; +import { + createPairingClaimId, PairingError, PairingClaimCoordinator, type PairingClaim, + type PairingOffer, redeemPairingOffer, + samePairingOffer, } from "../core/pairing-client"; import { ReconnectingWs } from "../core/ws-client"; import { deleteObsoleteDatabase } from "../core/delete-obsolete-database"; @@ -44,6 +50,7 @@ import type { SwMsg, WsStatus, } from "../messaging"; +import { SERVICE_ORIGIN, SERVICE_ORIGINS } from "../service-origin"; import { controlledTabInfo } from "../tabs"; // Attended URLs can contain a legacy extension token. Keep them in @@ -55,6 +62,21 @@ const ATTACHED_TAB_KEY = "understudy:attachedTabId"; const ATTACHMENT_ID_KEY = "understudy:attachmentId"; const BACKSTOP_ALARM = "ws-backstop"; const LOG_CAP = 50; +const PAIRING_OFFER_TTL_MS = 10 * 60_000; + +type PairingReply = { ok: false } | { ok: true; status?: "closing_previous_sessions" }; +type ExternalPairingReply = + | PairingReply + | { status: "expiry_required" | "pairing" } + | { status: "confirmation_pending"; confirmationId: string }; + +interface HeldPairing { + id: string; + offer: PairingOffer; + expiresAt: number; + timer: ReturnType; + replaces: { serviceOrigin: string; deviceId: string } | null; +} // ── Module-scope singletons — rebuilt on every SW wake ─────────────────────── // WXT re-runs main() when the service worker is revived, so these are re-created @@ -79,6 +101,10 @@ let wsIsolationFailed = false; let wsSwitchRequest = 0; let wsSwitchTail: Promise = Promise.resolve(); let pairingTail: Promise = Promise.resolve(); +let pairingRecovery: Promise = Promise.resolve(); +let scheduledPairing: { serviceOrigin: string; request: number } | null = null; +let heldPairing: HeldPairing | null = null; +let confirmedPairing: { id: string; serviceOrigin: string; reply?: PairingReply } | null = null; let session: CdpSession | null = null; let attachedTitle: string | undefined; @@ -87,6 +113,7 @@ let attachmentId: string | null = null; let pairingState: StateMsg["pairing"]; let hostingStopRequested = false; let hostingStopRequest = 0; +let lastStopAllRequest = 0; interface AttendedRuntime { dedupe: WriteDedupe; @@ -115,7 +142,7 @@ let attendedWritesBlocked = false; let attendedTerminal = false; const profileClient = new ProfileClient( () => broadcastState(), - __UNDERSTUDY_ORIGIN_PINNED__ ? DEFAULT_SERVICE_ORIGIN : undefined, + __UNDERSTUDY_ORIGIN_PINNED__ ? SERVICE_ORIGINS : undefined, ); const pairingClaims = new PairingClaimCoordinator(browser.storage.local); @@ -156,18 +183,14 @@ export default defineBackground({ const pairingRecoveryRequest = ++hostingStopRequest; if (__UNDERSTUDY_STORE__) { fireAndForget("store startup", () => storeRuntimeGate.wait()); - fireAndForget("pairing recovery", async () => { - await storeRuntimeGate.wait(); - await recoverPendingPairing(pairingRecoveryRequest); - }); } else { fireAndForget("ensureConnection", ensureConnection); fireAndForget("reconcileAttachment", reconcileAttachment); fireAndForget("profileClient", () => profileClient.start()); - fireAndForget("pairing recovery", () => - recoverPendingPairing(pairingRecoveryRequest), - ); } + pairingRecovery = (__UNDERSTUDY_STORE__ ? storeRuntimeGate.wait() : Promise.resolve()) + .then(() => recoverPendingPairing(pairingRecoveryRequest)); + fireAndForget("pairing recovery", () => pairingRecovery); }, }); @@ -983,23 +1006,132 @@ async function setWsUrl(url: string): Promise { function onExternalMessage( message: unknown, sender: Browser.runtime.MessageSender, - sendResponse: (response: { ok: boolean }) => void, + sendResponse: (response: ExternalPairingReply) => void, ): true { const offer = externalPairingOffer(message, sender); if (offer === null) { - sendResponse({ ok: false }); + const status = externalPairingStatusRequest(message, sender); + sendResponse(status === null ? { ok: false } : externalPairingStatus(status)); return true; } - const request = ++hostingStopRequest; - hostingStopRequested = false; - const redemption = schedulePairing(offer, request); - void redemption.then( - (paired) => sendResponse({ ok: paired }), + const { expiresAt, ...pairingOffer } = offer; + void receivePairingOffer(pairingOffer, expiresAt).then( + sendResponse, () => sendResponse({ ok: false }), ); return true; } +async function receivePairingOffer( + offer: PairingOffer, + expiresAt: number | undefined, +): Promise { + const stopAtReceipt = lastStopAllRequest; + // Recovery can change the controlling service before the offer is classified. + try { + await pairingRecovery; + } catch { + if (__UNDERSTUDY_STORE__) await storeRuntimeGate.wait(); + else await profileClient.start(); + } + const now = Date.now(); + if ( + stopAtReceipt !== lastStopAllRequest || + (expiresAt !== undefined && expiresAt <= now) + ) { + return { ok: false }; + } + const pending = heldPairing; + if (pending !== null && samePairingOffer(pending.offer, offer)) { + return pending.expiresAt > now + ? { status: "confirmation_pending", confirmationId: pending.id } + : { ok: false }; + } + const profile = profileClient.publicConfig(); + const stagedOrigin = profileClient.stagedServiceOrigin(); + if ( + hostingStopRequested || + (scheduledPairing !== null && scheduledPairing.serviceOrigin !== offer.serviceOrigin) || + (stagedOrigin !== null && stagedOrigin !== offer.serviceOrigin) || + offer.serviceOrigin !== (profile?.serviceOrigin ?? SERVICE_ORIGIN) || + (offer.serviceOrigin !== SERVICE_ORIGIN && profileClient.blockedReason() === "credential_revoked") + ) { + if (expiresAt === undefined) return { status: "expiry_required" }; + clearHeldPairing(); + const id = createPairingClaimId(); + const deadline = Math.min(expiresAt, now + PAIRING_OFFER_TTL_MS); + const timer = setTimeout(() => { + if (heldPairing?.id !== id) return; + clearHeldPairing(); + broadcastState(); + }, deadline - now); + heldPairing = { + id, + offer, + expiresAt: deadline, + timer, + replaces: profile === null + ? null + : { serviceOrigin: profile.serviceOrigin, deviceId: profile.deviceId }, + }; + broadcastState(); + return { status: "confirmation_pending", confirmationId: id }; + } + return schedulePairing(offer, ++hostingStopRequest); +} + +function externalPairingStatus({ + confirmationId, + serviceOrigin, +}: ExternalPairingStatusRequest): ExternalPairingReply { + const pending = heldPairing; + if (pending?.id === confirmationId && pending.offer.serviceOrigin === serviceOrigin) { + return pending.expiresAt > Date.now() + ? { status: "confirmation_pending", confirmationId } + : { ok: false }; + } + if (confirmedPairing?.id === confirmationId && confirmedPairing.serviceOrigin === serviceOrigin) { + return confirmedPairing.reply ?? { status: "pairing" }; + } + return { ok: false }; +} + +function clearHeldPairing(): void { + if (heldPairing === null) return; + clearTimeout(heldPairing.timer); + heldPairing = null; +} + +function decidePairing(confirmationId: string, confirm: boolean): void { + const pending = heldPairing; + if (pending?.id !== confirmationId) return; + clearHeldPairing(); + const current = profileClient.publicConfig(); + if ( + !confirm || + pending.expiresAt <= Date.now() || + pending.replaces?.serviceOrigin !== current?.serviceOrigin || + pending.replaces?.deviceId !== current?.deviceId + ) { + broadcastState(); + return; + } + const confirmation: NonNullable = { + id: pending.id, + serviceOrigin: pending.offer.serviceOrigin, + }; + confirmedPairing = confirmation; + hostingStopRequested = false; + void schedulePairing(pending.offer, ++hostingStopRequest).then( + (reply) => { + confirmation.reply = reply; + }, + () => { + confirmation.reply = { ok: false }; + }, + ); +} + function onConnect(port: Browser.runtime.Port): void { if (port.name !== "panel") return; ports.add(port); @@ -1017,9 +1149,15 @@ function handlePanelMsg(msg: PanelMsg, port: Browser.runtime.Port): void { pushState(port); return; } + if (msg.type === "confirmPairing" || msg.type === "cancelPairing") { + decidePairing(msg.confirmationId, msg.type === "confirmPairing"); + return; + } if (msg.type === "stopAll") { const request = ++hostingStopRequest; + lastStopAllRequest = request; hostingStopRequested = true; + clearHeldPairing(); pairingState = undefined; const stopping = pairingClaims.cancel().then(() => __UNDERSTUDY_STORE__ @@ -1071,19 +1209,21 @@ function handlePanelMsg(msg: PanelMsg, port: Browser.runtime.Port): void { } } -// The dashboard offer is redeemed only after Chrome verifies the external sender. -function schedulePairing(offer: string, request: number): Promise { +function schedulePairing(offer: PairingOffer, request: number): Promise { + scheduledPairing = { serviceOrigin: offer.serviceOrigin, request }; pairingState = { phase: "pairing" }; broadcastState(); const queued = pairingClaims.request(offer); - const redemption = pairingTail.then(async () => { + const redemption = pairingTail.then(async (): Promise => { try { await queued; - if (request !== hostingStopRequest) return false; + if (request !== hostingStopRequest) return { ok: false }; return await pairDevice(offer, request); } catch (cause) { reportPairingFailure(cause, request); - return false; + return { ok: false }; + } finally { + if (scheduledPairing?.request === request) scheduledPairing = null; } }); pairingTail = redemption.then( @@ -1094,25 +1234,25 @@ function schedulePairing(offer: string, request: number): Promise { } async function pairDevice( - targetOffer: string | null, + targetOffer: PairingOffer | null, request: number, -): Promise { +): Promise { for (;;) { let claim: PairingClaim | null = null; try { - claim = await pairingClaims.next(targetOffer, async () => { + claim = await pairingClaims.next(targetOffer, async (serviceOrigin) => { if (__UNDERSTUDY_STORE__) await storeRuntimeGate.wait(); - return profileClient.pairingCredential(); + return profileClient.pairingCredential(serviceOrigin); }); - if (claim === null) return false; + if (claim === null) return { ok: false }; if (!(await pairingClaims.markDispatched(claim))) { - if (request !== hostingStopRequest) return false; + if (request !== hostingStopRequest) return { ok: false }; continue; } const result = await redeemPairingOffer( claim.offer, claim.previousCredential, - DEFAULT_SERVICE_ORIGIN, + claim.serviceOrigin, claim.claimId, ); const disposition = await pairingClaims.disposition(claim); @@ -1128,15 +1268,16 @@ async function pairDevice( originPolicy: result.originPolicy, policyVersion: result.policyVersion, }; + let transition: "active" | "staged" = "active"; try { await profileClient.configurePaired( recoveredConfig, claim.previousCredential, ); } catch (cause) { - if (!(await profileClient.pairingTransitionPersisted(recoveredConfig))) { - throw cause; - } + const persisted = await profileClient.persistedPairingTransition(recoveredConfig); + if (persisted === null) throw cause; + transition = persisted; } const committedDisposition = await pairingClaims.disposition(claim); if (committedDisposition === null) { @@ -1144,33 +1285,34 @@ async function pairDevice( } if (!committedDisposition.allowHosting) { await profileClient.stopAll(); + } else if (transition === "staged") { + // The dispatched claim recovers the pairing if cleanup cannot promote the staged profile. + return request === hostingStopRequest && + (targetOffer === null || samePairingOffer(claim, targetOffer)) + ? reportPairingSuccess(true) + : { ok: false }; } if (!(await pairingClaims.complete(claim))) { throw new Error("pairing intent changed before durable completion"); } } catch (cause) { - if (cause instanceof PairingError && cause.status === 404 && claim !== null) { - await pairingClaims.reject(claim).catch(() => {}); - if ( - claim.offer !== targetOffer && - request === hostingStopRequest - ) { - continue; + let advance = false; + if (claim !== null) { + if (cause instanceof PairingError && cause.status === 404) { + const rejected = await pairingClaims.reject(claim).catch(() => false); + advance = rejected && (targetOffer === null || !samePairingOffer(claim, targetOffer)); + } else { + advance = await pairingClaims.rejectBeforeDifferentService(claim).catch(() => false); } } + if (advance && request === hostingStopRequest) continue; if (targetOffer !== null) reportPairingFailure(cause, request); - return false; + return { ok: false }; } - if (request !== hostingStopRequest) return false; + if (request !== hostingStopRequest) return { ok: false }; if (targetOffer === null) continue; - if (claim.offer === targetOffer) { - pairingState = { phase: "success" }; - log("paired with account; unattended hosting enabled"); - broadcastState(); - return true; - } - if (request !== hostingStopRequest) return false; + if (samePairingOffer(claim, targetOffer)) return reportPairingSuccess(); } } @@ -1185,6 +1327,17 @@ async function recoverPendingPairing(request: number): Promise { if (request === hostingStopRequest) broadcastState(); } +function reportPairingSuccess(closingPreviousSessions = false): PairingReply { + pairingState = closingPreviousSessions + ? { phase: "success", closingPreviousSessions: true } + : { phase: "success" }; + log(closingPreviousSessions + ? "Pairing saved while the previous service’s sessions close." + : "Paired with account."); + broadcastState(); + return closingPreviousSessions ? { ok: true, status: "closing_previous_sessions" } : { ok: true }; +} + function reportPairingFailure(cause: unknown, request: number): void { if (request !== hostingStopRequest) return; pairingState = { @@ -1210,6 +1363,11 @@ function buildAttached(): AttachedTab | null { function buildState(): StateMsg { const blockedReason = profileClient.blockedReason(); const profileConfig = profileClient.publicConfig(); + const pending = heldPairing !== null && heldPairing.expiresAt > Date.now() ? heldPairing : null; + const pairing: StateMsg["pairing"] = pairingState?.closingPreviousSessions && + profileClient.stagedServiceOrigin() === null + ? { phase: "success" } + : pairingState; return { type: "state", wsStatus, @@ -1221,7 +1379,14 @@ function buildState(): StateMsg { hostingStopRequested && profileConfig !== null ? { ...profileConfig, unattendedEnabled: false } : profileConfig, - ...(pairingState === undefined ? {} : { pairing: pairingState }), + ...(pairing === undefined ? {} : { pairing }), + ...(pending === null ? {} : { + pairingConfirmation: { + id: pending.id, + serviceHost: new URL(pending.offer.serviceOrigin).host, + replacesHost: pending.replaces === null ? null : new URL(pending.replaces.serviceOrigin).host, + }, + }), ...(blockedReason === null ? {} : { profileStatusReason: blockedReason }), logs: [...logBuffer], }; diff --git a/apps/extension/src/entrypoints/sidepanel/App.tsx b/apps/extension/src/entrypoints/sidepanel/App.tsx index 09d8f45..997be22 100644 --- a/apps/extension/src/entrypoints/sidepanel/App.tsx +++ b/apps/extension/src/entrypoints/sidepanel/App.tsx @@ -9,7 +9,7 @@ import type { ProfileBlockReason, SwMsg, } from "../../messaging"; -import { DASHBOARD_URL, PRIVACY_URL } from "../../service-origin"; +import { DASHBOARD_URL, pairingManagementUrl, PRIVACY_URL } from "../../service-origin"; const SUPPORT_URL = "https://github.com/ProofOfTechOrg/understudy/issues"; const RECONNECT_DELAY_MS = 500; @@ -72,9 +72,12 @@ export function App(): ReactElement { }, []); const pairing = swState?.pairing; + const confirmation = swState?.pairingConfirmation; const isLoading = swState === null; const isPairing = pairing?.phase === "pairing"; const profileConfig = swState?.profileConfig ?? null; + const serviceHost = profileConfig === null ? null : new URL(profileConfig.serviceOrigin).host; + const pairingUrl = profileConfig === null ? DASHBOARD_URL : pairingManagementUrl(profileConfig.serviceOrigin); const controlledTabs = swState?.controlledTabs ?? 0; const isPaired = profileConfig !== null; const status = deriveHostStatus(swState); @@ -83,8 +86,9 @@ export function App(): ReactElement { (profileConfig?.unattendedEnabled === true || controlledTabs > 0); const pairingNotice = pairingNoticeFor( pairing ?? null, - swState?.profileStatus, + status, swState?.profileStatusReason, + serviceHost, ); const stopHosting = (): void => { @@ -131,13 +135,40 @@ export function App(): ReactElement {

{isPaired ? "Replace pairing" : "Pair this browser"}

-

- Use the dashboard to send a one-time offer directly to this extension. - Pairing credentials never appear in a URL or require transcription. -

+ {confirmation === undefined ? null : ( +
+

+ Allow {confirmation.serviceHost} to control this browser? + {confirmation.replacesHost === null ? null : ( + <> This replaces the pairing with {confirmation.replacesHost}. + )} +

+
+ + +
+
+ )} +

Send a one-time pairing offer from your service’s dashboard.

@@ -145,8 +176,8 @@ export function App(): ReactElement {

- Re-pairing rotates this installation’s credential. Only exact origins - allowed in your dashboard can be operated. + Re-pairing with your current service rotates this installation’s credential. + The extension operates on the origins your service allows.

@@ -158,6 +189,9 @@ export function App(): ReactElement {