From ef1b33345686fdbb0cff323bdaa4b9a9d6da57c9 Mon Sep 17 00:00:00 2001 From: abrichr Date: Sun, 29 Nov 2026 21:13:06 -0500 Subject: [PATCH 1/9] fix(desktop): ask before a connect link pairs this computer An openadapt://connect link used to redeem its pairing code as soon as the operating system delivered it. Anyone can create a pairing code and put it in a link, so one click could move a Desktop to another Cloud workspace. A connect link now only stages the request in the engine. The window shows the target host, says when the link would replace the current pairing (also on the same host, since that can still be another workspace), and redeems nothing until the person clicks Allow. Allow carries the request id the window showed, so a second link that arrives before the click can't be allowed by it. The staged code stays in engine memory, expires after ten minutes, and is used at most once. Cloud has no way to look up a code without redeeming it, so the dialog says the workspace isn't known yet. The engine now refuses connect links for a Cloud server on this computer unless the developer setting allow_local_pairing is on (env OPENADAPT_ALLOW_LOCAL_PAIRING or config.toml). Links for app.openadapt.ai are unchanged; every other host was already refused. The main window no longer has shell execute or spawn permission on the engine sidecar. Rust starts the sidecar itself and no frontend code used the shell plugin. --- packages/desktop/openadapt_desktop/config.py | 11 + .../desktop/openadapt_desktop/dispatch.py | 163 +++++++++++++- .../src-tauri/capabilities/default.json | 24 +- packages/desktop/src-tauri/src/pairing.rs | 81 +++++-- .../desktop/src/App.pairingConfirm.test.tsx | 84 +++++++ packages/desktop/src/App.tsx | 57 ++++- packages/desktop/src/lib/engine.ts | 4 + .../desktop/src/ui/PairingConfirm.test.tsx | 58 +++++ packages/desktop/src/ui/PairingConfirm.tsx | 78 +++++++ .../tests/test_engine/test_dispatch.py | 205 +++++++++++++++--- .../tests/test_pairing_protocol_boundary.py | 34 +++ 11 files changed, 709 insertions(+), 90 deletions(-) create mode 100644 packages/desktop/src/App.pairingConfirm.test.tsx create mode 100644 packages/desktop/src/ui/PairingConfirm.test.tsx create mode 100644 packages/desktop/src/ui/PairingConfirm.tsx diff --git a/packages/desktop/openadapt_desktop/config.py b/packages/desktop/openadapt_desktop/config.py index 7510219aa3..d9ec080b19 100644 --- a/packages/desktop/openadapt_desktop/config.py +++ b/packages/desktop/openadapt_desktop/config.py @@ -34,6 +34,7 @@ "phi_mode": "phi_mode", "poll_interval_s": "poll_interval_s", "runner_enabled": "runner_enabled", + "allow_local_pairing": "allow_local_pairing", } @@ -199,6 +200,16 @@ def settings_customise_sources( default=60, description="Seconds between needs-attention count polls (never < 30).", ) + allow_local_pairing: bool = Field( + default=False, + description=( + "Developer setting: accept openadapt://connect links that name a " + "Cloud server on this computer (localhost). Off by default, so a " + "connect link can only name app.openadapt.ai. Set it with " + "OPENADAPT_ALLOW_LOCAL_PAIRING or allow_local_pairing in the " + "[hosted] table of config.toml; a link or the window can't turn it on." + ), + ) runner_enabled: bool = Field( default=False, description=( diff --git a/packages/desktop/openadapt_desktop/dispatch.py b/packages/desktop/openadapt_desktop/dispatch.py index 97f81f4fd4..6adcb5ce13 100644 --- a/packages/desktop/openadapt_desktop/dispatch.py +++ b/packages/desktop/openadapt_desktop/dispatch.py @@ -92,6 +92,10 @@ def _noop_emit(event: str, data: dict) -> None: """Default event sink -- drops events when no emitter is wired.""" +#: How long a staged ``openadapt://connect`` request waits for Allow. +PAIRING_CONFIRM_TTL_S = 600.0 + + def _canonical_hosted_origin(value: Any) -> str: """Return a safe hosted origin or raise before any credential is sent.""" @@ -276,6 +280,10 @@ def __init__( self._shadow: Any = None self._shadow_resumed = False self.services.live_tap_provider = self._shadow_live_tap + # The one ``openadapt://connect`` request waiting for Allow. Memory + # only: the one-use pairing code never reaches disk, the window or a + # log, and a restart drops it. + self._pending_connect: dict[str, Any] | None = None self._handlers: dict[str, Callable[..., dict | None]] = {} self._register() from openadapt_desktop.coach import empty_coach @@ -376,6 +384,11 @@ def _register(self) -> None: "login_browser": self.login_browser, "login_paste": self.login_paste, "connect_uri": self.connect_uri, + # A connect link only stages a request; nothing is redeemed until + # the person clicks Allow in the window (window wire only). + "pairing_status": self.pairing_status, + "pairing_allow": self.pairing_allow, + "pairing_deny": self.pairing_deny, "claim_runner_uri": self.claim_runner_uri, "authoring_allow": self.authoring_allow, "authoring_deny": self.authoring_deny, @@ -5941,24 +5954,160 @@ def login_paste(self, **params: Any) -> dict: return self._auth_status(cred) def connect_uri(self, **params: Any) -> dict: - """Handle only a validated ``openadapt://connect`` pairing URI.""" - from openadapt_desktop.auth.pairing import connect_uri + """Stage a validated ``openadapt://connect`` link for an in-app Allow. + + Nothing is redeemed here: no request goes to Cloud, the keychain and + ``hosted_host`` are untouched. Anyone can make a pairing code and put + it in a link, so the person must see the target and click Allow + (:meth:`pairing_allow`) before the code is spent. This mirrors the + Allow that runner links already require. + """ + from openadapt_desktop.auth.pairing import PairingError, parse_connect_uri uri = params.get("uri") if not isinstance(uri, str): raise ValueError("uri is required") - result = connect_uri(uri) + try: + request = parse_connect_uri(uri) + host = _canonical_hosted_origin(request["host"]) + if not self._pairing_host_allowed(host): + raise PairingError( + "This connect link names a Cloud server on this computer. " + "Desktop only accepts links for app.openadapt.ai unless the " + "developer setting allow_local_pairing is on. Nothing changed." + ) + except (PairingError, ValueError) as exc: + self.emit("pairing_state", {"status": "error", "error": str(exc)}) + raise + pending = self._pending_connect + if ( + pending is not None + and not self._pending_connect_expired(pending) + and pending["pairing"] == request["pairing"] + and pending["host"] == host + ): + # The same link delivered twice (launch and single-instance can + # both deliver it): keep the request the window is showing. + prompt = self._pairing_prompt(pending) + else: + self._pending_connect = { + "request_id": uuid.uuid4().hex, + "pairing": request["pairing"], + "host": host, + "destination_kind": request.get("destination_kind"), + "expires_at": time.monotonic() + PAIRING_CONFIRM_TTL_S, + } + prompt = self._pairing_prompt(self._pending_connect) + self.emit("pairing_state", prompt) + return prompt + + def _pairing_host_allowed(self, host: str) -> bool: + """Production Cloud always; this computer only with the developer setting.""" + from openadapt_desktop.auth.store import DEFAULT_HOST, canonical_host_origin + + if host == canonical_host_origin(DEFAULT_HOST): + return True + hostname = urlsplit(host).hostname + return hostname in {"localhost", "127.0.0.1", "::1"} and ( + self.config.allow_local_pairing is True + ) + + @staticmethod + def _pending_connect_expired(pending: dict[str, Any]) -> bool: + return time.monotonic() >= float(pending["expires_at"]) + + def _pairing_prompt(self, pending: dict[str, Any]) -> dict[str, Any]: + """What the window shows. Never carries the pairing code.""" + from openadapt_desktop.auth.store import active_credential, canonical_host_origin + + try: + current = active_credential() + current_host = ( + canonical_host_origin(str(current.get("host") or "")) if current else None + ) + already_paired = current is not None + except Exception: # noqa: BLE001 - an unreadable keychain must not hide the warning + current_host = None + already_paired = True + return { + "status": "pending_confirm", + "request_id": pending["request_id"], + "host": pending["host"], + # Cloud has no way to look up a pairing code without redeeming it, + # so Desktop can't name the workspace or account before Allow. + "workspace": None, + "account": None, + "already_paired": already_paired, + "current_host": current_host or None, + "expires_in_s": max(0, int(float(pending["expires_at"]) - time.monotonic())), + } + + def pairing_status(self, **params: Any) -> dict: + """Return the connect request waiting for Allow, or ``idle``.""" + pending = self._pending_connect + if pending is None: + return {"status": "idle"} + if self._pending_connect_expired(pending): + self._pending_connect = None + return {"status": "idle"} + return self._pairing_prompt(pending) + + def pairing_allow(self, **params: Any) -> dict: + """Redeem the staged connect request the person allowed in the window. + + ``request_id`` must name the request the window showed, so a second + link that arrives before the click can't be allowed by it. + """ + from openadapt_desktop.auth.pairing import PairingError, claim_pairing + + pending = self._pending_connect + if pending is None or self._pending_connect_expired(pending): + self._pending_connect = None + message = ( + "That connect request isn't waiting any more. Nothing changed. " + "Create a new connection from Cloud settings." + ) + self.emit("pairing_state", {"status": "error", "error": message}) + raise PairingError(message) + if params.get("request_id") != pending["request_id"]: + message = ( + "A different connect link arrived. Review it before you allow it. Nothing changed." + ) + self.emit("pairing_state", self._pairing_prompt(pending)) + raise PairingError(message) + # One use: the code is spent or refused below, never offered again. + self._pending_connect = None + self.emit("pairing_state", {"status": "connecting", "host": pending["host"]}) + try: + result = claim_pairing( + pending["host"], + pending["pairing"], + destination_kind=pending.get("destination_kind"), + ) + except PairingError as exc: + self.emit("pairing_state", {"status": "error", "error": str(exc)}) + raise + except Exception: + self.emit( + "pairing_state", + {"status": "error", "error": "The secure connection could not be completed."}, + ) + raise host = _canonical_hosted_origin(result["host"]) result = {**result, "host": host} self.config.hosted_host = host self._persist_config_key("hosted_host", host) - self.emit( - "pairing_state", - {"status": "connected", "host": host}, - ) + self.emit("pairing_state", {"status": "connected", "host": host}) self._emit_sync(self._sync_state_now()) return result + def pairing_deny(self, **params: Any) -> dict: + """Drop the staged connect request. Nothing was redeemed.""" + self._pending_connect = None + state = {"status": "declined"} + self.emit("pairing_state", state) + return state + def _authoring_service(self) -> Any: if self.services.authoring is None: from openadapt_desktop.authoring_runner import AuthoringRunner diff --git a/packages/desktop/src-tauri/capabilities/default.json b/packages/desktop/src-tauri/capabilities/default.json index 7aede268a4..0dc53a5b62 100644 --- a/packages/desktop/src-tauri/capabilities/default.json +++ b/packages/desktop/src-tauri/capabilities/default.json @@ -1,7 +1,7 @@ { "$schema": "../gen/schemas/desktop-schema.json", "identifier": "default", - "description": "Core permissions for the OpenAdapt Desktop shell: run the engine sidecar, receive engine events, show notifications, and (only in a build with an update feed) self-update.", + "description": "Core permissions for the OpenAdapt Desktop window: receive engine events, show and focus the window, show notifications, and (only in a build with an update feed) self-update. The window gets no shell permission: Rust starts the engine sidecar (sidecar.rs), so the webview can't run or spawn it.", "windows": ["main"], "permissions": [ "core:default", @@ -10,26 +10,6 @@ "core:window:allow-hide", "core:window:allow-set-focus", "notification:default", - "updater:default", - { - "identifier": "shell:allow-execute", - "allow": [ - { - "name": "binaries/openadapt-engine", - "sidecar": true, - "args": true - } - ] - }, - { - "identifier": "shell:allow-spawn", - "allow": [ - { - "name": "binaries/openadapt-engine", - "sidecar": true, - "args": true - } - ] - } + "updater:default" ] } diff --git a/packages/desktop/src-tauri/src/pairing.rs b/packages/desktop/src-tauri/src/pairing.rs index febbea241c..ef23ed62ca 100644 --- a/packages/desktop/src-tauri/src/pairing.rs +++ b/packages/desktop/src-tauri/src/pairing.rs @@ -9,6 +9,13 @@ //! //! Connect is not widened to accept runner fields, and runner is not widened //! to accept connect fields. +//! +//! `connect_uri` only stages the request in the engine. Anyone can mint a +//! pairing code and wrap it in a link, so nothing is redeemed, and no +//! credential or Cloud host changes, until the person clicks Allow in the +//! window (`pairing_allow`, which the window sends with the request id it +//! showed). The engine also enforces the host allowlist: production always, +//! this computer only behind the developer setting. use std::collections::{HashMap, HashSet}; use std::error::Error; @@ -88,40 +95,35 @@ fn route_urls( } }; - // Keep only a non-secret in-memory fingerprint. Initial delivery and the - // single-instance event can otherwise race and consume the one-use code - // twice. - let fingerprint = fingerprint(&action.uri); - { - let mut handled = state.handled.lock().unwrap(); - if handled.contains(&fingerprint) { - return; - } - if handled.len() >= MAX_RECENT_LINKS { - handled.clear(); - } - handled.insert(fingerprint); + // Runner links claim at once, so keep a non-secret in-memory fingerprint: + // initial delivery and the single-instance event can otherwise race and + // consume the one-use bind token twice. Connect links redeem nothing here + // (the engine keeps one staged request and folds a repeat into it), so a + // link the person dismissed with "Not now" can be opened again. + if action.command == "claim_runner_uri" && !first_delivery(&state, &action.uri) { + return; } let event = status_event(action.command); - let connecting = if action.command == "claim_runner_uri" { - "claiming" - } else { - "connecting" - }; - emit_state(&app, event, connecting, None); + if action.command == "claim_runner_uri" { + emit_state(&app, event, "claiming", None); + } tauri::async_runtime::spawn(async move { let result = engine .send_command(action.command, json!({ "uri": action.uri })) .await; match result { Ok(data) => { - let connected = if action.command == "claim_runner_uri" { - "bound" + let payload = if action.command == "claim_runner_uri" { + json!({ "status": "bound", "data": data }) } else { - "connected" + // The engine's own answer: a request waiting for Allow. + // Never "connected": nothing has been redeemed yet. Bring + // the window forward so the person sees the question. + crate::window::show_main(&app); + data }; - let _ = app.emit(event, json!({ "status": connected, "data": data })); + let _ = app.emit(event, payload); } Err(error) => { eprintln!("[pairing] connection failed: {error}"); @@ -131,6 +133,19 @@ fn route_urls( }); } +fn first_delivery(state: &PairingLinkState, uri: &str) -> bool { + let fingerprint = fingerprint(uri); + let mut handled = state.handled.lock().unwrap(); + if handled.contains(&fingerprint) { + return false; + } + if handled.len() >= MAX_RECENT_LINKS { + handled.clear(); + } + handled.insert(fingerprint); + true +} + fn status_event(command: &str) -> &'static str { if command == "claim_runner_uri" { "engine://authoring_state" @@ -450,6 +465,26 @@ mod tests { assert!(validate_destination("http://app.openadapt.ai", None).is_err()); } + #[test] + fn runner_links_are_claimed_once() { + let state = PairingLinkState::default(); + let runner = runner_uri(); + assert!(first_delivery(&state, &runner)); + assert!(!first_delivery(&state, &runner)); + } + + #[test] + fn connect_links_go_to_the_staging_action_only() { + // `connect_uri` stages; the redeem verb is never reachable from a link. + let url = parse(&format!( + "openadapt://connect?pairing={SECRET}&host=https%3A%2F%2Fapp.openadapt.ai" + )); + let action = action_for_url(&url).unwrap(); + assert_eq!(action.command, "connect_uri"); + assert_ne!(action.command, "pairing_allow"); + assert_eq!(status_event(action.command), "engine://pairing_state"); + } + #[test] fn multiple_urls_are_rejected_as_ambiguous() { let url = parse(&format!( diff --git a/packages/desktop/src/App.pairingConfirm.test.tsx b/packages/desktop/src/App.pairingConfirm.test.tsx new file mode 100644 index 0000000000..7c5e732fe0 --- /dev/null +++ b/packages/desktop/src/App.pairingConfirm.test.tsx @@ -0,0 +1,84 @@ +import { cleanup, fireEvent, render, screen, waitFor } from "@testing-library/react"; +import { afterEach, expect, it, vi } from "vitest"; + +// A connect link opened at launch is staged before the window listens, so the +// window asks the engine on mount. Nothing is redeemed until Allow, and Allow +// carries the request id the dialog showed. + +vi.mock("./lib/engine", async (importOriginal) => { + const actual = await importOriginal(); + return { + ...actual, + engineTry: vi.fn(), + engineInvoke: vi.fn(async () => ({})), + onEngineEvent: vi.fn(() => Promise.resolve(() => {})), + sidecarRunning: vi.fn(async () => true), + }; +}); + +vi.mock("./screens/Welcome", () => ({ + Welcome: () =>
Welcome screen
, +})); + +import App from "./App"; +import { CMD, engineInvoke, engineTry } from "./lib/engine"; + +afterEach(() => { + cleanup(); + vi.clearAllMocks(); +}); + +function engineWithPendingLink() { + vi.mocked(engineTry).mockImplementation(async (command, _params, fallback) => { + if (command === CMD.GET_AUTH_STATUS) return { authenticated: true }; + if (command === CMD.GET_WORKFLOWS) return []; + if (command === CMD.GET_FIRST_WORKFLOW_STATE) return { ok: true, state: null }; + if (command === CMD.GET_NEEDS_ATTENTION) { + return { count: 0, open_halts: 0, failed_runs: 0 }; + } + if (command === CMD.GET_SYNC_STATE) return { state: "synced", queued: 0 }; + if (command === CMD.PAIRING_STATUS) { + return { + status: "pending_confirm", + request_id: "req-42", + host: "https://app.openadapt.ai", + workspace: null, + account: null, + already_paired: true, + current_host: "https://app.openadapt.ai", + }; + } + return fallback ?? null; + }); +} + +function sent(command: string): boolean { + return [ + ...vi.mocked(engineTry).mock.calls, + ...vi.mocked(engineInvoke).mock.calls, + ].some(([name]) => name === command); +} + +it("asks before connecting and says it replaces the current pairing", async () => { + engineWithPendingLink(); + render(); + const dialog = await screen.findByRole("alertdialog"); + expect(dialog.textContent).toContain("app.openadapt.ai"); + expect(dialog.textContent).toContain("Allowing replaces that connection."); + expect(sent(CMD.PAIRING_ALLOW)).toBe(false); + + fireEvent.click(screen.getByRole("button", { name: "Allow" })); + await waitFor(() => + expect(engineInvoke).toHaveBeenCalledWith(CMD.PAIRING_ALLOW, { request_id: "req-42" }), + ); +}); + +it("Not now redeems nothing", async () => { + engineWithPendingLink(); + render(); + await screen.findByRole("alertdialog"); + fireEvent.click(screen.getByRole("button", { name: "Not now" })); + await waitFor(() => expect(sent(CMD.PAIRING_DENY)).toBe(true)); + expect(sent(CMD.PAIRING_ALLOW)).toBe(false); + expect(screen.queryByRole("alertdialog")).toBeNull(); +}); diff --git a/packages/desktop/src/App.tsx b/packages/desktop/src/App.tsx index 817fa6f089..7c4403bab8 100644 --- a/packages/desktop/src/App.tsx +++ b/packages/desktop/src/App.tsx @@ -8,6 +8,7 @@ import { useCallback, useEffect, useRef, useState } from "react"; import { CMD, EVT, + engineInvoke, engineTry, onEngineEvent, onShadowPauseToggleRequested, @@ -48,6 +49,7 @@ import { deliverAttentionNotification } from "./lib/attentionNotification"; import { Qualification } from "./screens/Qualification"; import { clearLocalSession, rememberLocalSession } from "./localSession"; import { ItemApprovalDialog } from "./ui/ItemApproval"; +import { PairingConfirm, type PairingPrompt } from "./ui/PairingConfirm"; import { ShadowModeIndicator, ShadowPromptBanner, @@ -91,10 +93,12 @@ type Route = | { name: "portal" } | { name: "settings" }; -type PairingState = { - status: "connecting" | "connected" | "error"; - error?: string; -}; +type PairingState = + | PairingPrompt + | { + status: "connecting" | "connected" | "declined" | "error" | "idle"; + error?: string; + }; const NAV: { route: "tasks" | "needs" | "results"; @@ -501,6 +505,15 @@ export default function App() { if (authoringStatus?.status && authoringStatus.status !== "idle") { setAuthoring(authoringStatus); } + // A link opened at launch can be staged before this window listens. + const pairingStatus = await engineTry( + CMD.PAIRING_STATUS, + {}, + { status: "idle" }, + ); + if (pairingStatus?.status === "pending_confirm") { + setPairing(pairingStatus); + } setAtRest( await engineTry(CMD.AT_REST_STATUS, {}, null), ); @@ -555,9 +568,13 @@ export default function App() { onEngineEvent(EVT.ATTENTION_NOTIFICATION, (payload: unknown) => { void deliverAttentionNotification(payload); }), - onEngineEvent(EVT.PAIRING_STATE, (state: PairingState) => { - setPairing(state); - if (state.status === "connected") { + onEngineEvent(EVT.PAIRING_STATE, (state: PairingState | null) => { + setPairing( + !state?.status || state.status === "declined" || state.status === "idle" + ? null + : state, + ); + if (state?.status === "connected") { void engineTry( CMD.GET_AUTH_STATUS, {}, @@ -586,7 +603,31 @@ export default function App() { // eslint-disable-next-line react-hooks/exhaustive-deps }, []); - const pairingNotice = pairing ? ( + const pairingNotice = pairing?.status === "pending_confirm" ? ( + { + setPairing({ status: "connecting" }); + // The engine reports connected or the error on pairing_state. This + // only covers an engine that never answered. + engineInvoke(CMD.PAIRING_ALLOW, { request_id: requestId }).catch( + (error: unknown) => + setPairing((current) => + current?.status === "connecting" + ? { status: "error", error: String(error) } + : current, + ), + ); + }} + onDeny={() => { + setPairing(null); + void engineTry(CMD.PAIRING_DENY, {}, null); + }} + /> + ) : pairing && + (pairing.status === "connecting" || + pairing.status === "connected" || + pairing.status === "error") ? (
{ + it("names the target host and says the workspace isn't known yet", () => { + const text = pairingQuestion(prompt); + expect(text).toContain("app.openadapt.ai"); + expect(text).toMatch(/can't show which workspace/); + expect(text).not.toMatch(/replaces/); + }); + + it("names the workspace and account when the engine reports them", () => { + const text = pairingQuestion({ ...prompt, workspace: "Clinic A", account: "pat" }); + expect(text).toContain("(workspace Clinic A, account pat)"); + expect(text).not.toMatch(/can't show/); + }); + + it("says the link replaces the current pairing, even on the same host", () => { + const text = pairingQuestion({ + ...prompt, + already_paired: true, + current_host: "https://app.openadapt.ai", + }); + expect(text).toContain( + "This computer is already connected to app.openadapt.ai. Allowing replaces that connection.", + ); + }); + + it("warns about replacing even when the current host is unknown", () => { + const text = pairingQuestion({ ...prompt, already_paired: true }); + expect(text).toMatch(/already connected to OpenAdapt Cloud\. Allowing replaces/); + }); + + it("sends Allow with the request id it showed, and Not now without one", () => { + const onAllow = vi.fn(); + const onDeny = vi.fn(); + render(); + expect(screen.getByRole("alertdialog")).toBeTruthy(); + fireEvent.click(screen.getByRole("button", { name: "Not now" })); + expect(onDeny).toHaveBeenCalledTimes(1); + expect(onAllow).not.toHaveBeenCalled(); + fireEvent.click(screen.getByRole("button", { name: "Allow" })); + expect(onAllow).toHaveBeenCalledWith("req-1"); + }); +}); diff --git a/packages/desktop/src/ui/PairingConfirm.tsx b/packages/desktop/src/ui/PairingConfirm.tsx new file mode 100644 index 0000000000..2add44bcb3 --- /dev/null +++ b/packages/desktop/src/ui/PairingConfirm.tsx @@ -0,0 +1,78 @@ +// The question an `openadapt://connect` link asks before anything happens. +// +// Anyone can create a pairing code and put it in a link, so a link never +// connects this computer by itself: the engine only stages it, and nothing is +// redeemed, and no credential or Cloud address changes, until the person +// clicks Allow here. Allow sends back the request id this dialog showed, so a +// second link that arrives before the click can't be allowed by it. +// +// Cloud can't look up a pairing code without redeeming it, so the workspace +// and account are named only when the engine reports them. + +export type PairingPrompt = { + status: "pending_confirm"; + request_id: string; + host: string; + workspace?: string | null; + account?: string | null; + already_paired?: boolean; + current_host?: string | null; +}; + +function hostLabel(origin: string): string { + try { + const url = new URL(origin); + return url.host || origin; + } catch { + return origin; + } +} + +export function pairingQuestion(prompt: PairingPrompt): string { + const target = hostLabel(prompt.host); + const named = [ + prompt.workspace ? `workspace ${prompt.workspace}` : null, + prompt.account ? `account ${prompt.account}` : null, + ].filter(Boolean); + const who = named.length + ? ` (${named.join(", ")})` + : ". OpenAdapt can't show which workspace this link belongs to until you allow it"; + const replaces = prompt.already_paired + ? prompt.current_host + ? ` This computer is already connected to ${hostLabel(prompt.current_host)}. Allowing replaces that connection.` + : " This computer is already connected to OpenAdapt Cloud. Allowing replaces that connection." + : ""; + return ( + `Connect this computer to OpenAdapt Cloud at ${target}${who}.` + + replaces + + " Only allow a link you just created yourself." + ); +} + +export function PairingConfirm({ + prompt, + onAllow, + onDeny, +}: { + prompt: PairingPrompt; + onAllow: (requestId: string) => void; + onDeny: () => void; +}) { + return ( +
+ {pairingQuestion(prompt)} + + + + +
+ ); +} diff --git a/packages/desktop/tests/test_engine/test_dispatch.py b/packages/desktop/tests/test_engine/test_dispatch.py index d8463418c9..810758e4e8 100644 --- a/packages/desktop/tests/test_engine/test_dispatch.py +++ b/packages/desktop/tests/test_engine/test_dispatch.py @@ -16,6 +16,11 @@ from openadapt_desktop.flow_bridge import FlowBridge from openadapt_desktop.macos_permissions import control_permission_guidance +_PAIRING_SECRET = "oap_" + "A" * 43 +_CONNECT_URI = ( + "openadapt://connect?pairing=" + _PAIRING_SECRET + "&host=https%3A%2F%2Fapp.openadapt.ai" +) + def _precise_report( outcome: str, @@ -2464,52 +2469,184 @@ def test_get_auth_status_refuses_credential_for_other_configured_host( "host": "https://customer.example", } - def test_connect_uri_forwards_one_exact_string_and_emits_safe_state( + def test_connect_link_without_allow_redeems_nothing( + self, deps, fake_keyring, monkeypatch, tmp_path + ) -> None: + """A link alone never reaches Cloud, the keychain or the config.""" + import httpx + + disp, _db, events = deps + toml_path = tmp_path / "config.toml" + monkeypatch.setenv("OPENADAPT_CONFIG_TOML", str(toml_path)) + disp.config.hosted_host = "https://app.openadapt.ai" + + def _no_network(*_args, **_kwargs): + raise AssertionError("a connect link must not reach Cloud before Allow") + + claims: list[tuple] = [] + monkeypatch.setattr(httpx, "post", _no_network) + monkeypatch.setattr(httpx, "get", _no_network) + monkeypatch.setattr( + "openadapt_desktop.auth.pairing.claim_pairing", + lambda *args, **kwargs: claims.append((args, kwargs)), + ) + keychain_before = dict(fake_keyring._store) + + prompt = disp.dispatch("connect_uri", {"uri": _CONNECT_URI}) + + assert prompt["status"] == "pending_confirm" + assert prompt["host"] == "https://app.openadapt.ai" + assert prompt["already_paired"] is False + assert claims == [] + assert fake_keyring._store == keychain_before + assert not toml_path.exists() + assert disp.config.hosted_host == "https://app.openadapt.ai" + assert ("pairing_state", prompt) in events + # The one-use code never leaves the engine. + assert _PAIRING_SECRET not in json.dumps(prompt) + assert all(_PAIRING_SECRET not in json.dumps(data) for _e, data in events) + + assert disp.dispatch("pairing_deny", {}) == {"status": "declined"} + assert disp.dispatch("pairing_status", {}) == {"status": "idle"} + with pytest.raises(RuntimeError, match="isn't waiting"): + disp.dispatch("pairing_allow", {"request_id": prompt["request_id"]}) + assert claims == [] + assert fake_keyring._store == keychain_before + + def test_allow_redeems_exactly_the_request_the_window_showed( self, deps, monkeypatch, tmp_path ) -> None: disp, _db, events = deps - uri = "openadapt://connect?pairing=oap_" + "A" * 43 + "&host=https%3A%2F%2Fapp.openadapt.ai" - received: list[str] = [] monkeypatch.setenv("OPENADAPT_CONFIG_TOML", str(tmp_path / "config.toml")) + claims: list[tuple] = [] - def _connect(exact_uri: str) -> dict: - received.append(exact_uri) - return { - "authenticated": True, - "host": "https://app.openadapt.ai", - "paired": True, - } + def _claim(host, secret, code_verifier=None, destination_kind=None): + claims.append((host, secret, destination_kind)) + return {"authenticated": True, "host": host, "paired": True} + + monkeypatch.setattr("openadapt_desktop.auth.pairing.claim_pairing", _claim) + prompt = disp.dispatch("connect_uri", {"uri": _CONNECT_URI}) + assert disp.dispatch("pairing_status", {}) == prompt + + with pytest.raises(RuntimeError, match="different connect link"): + disp.dispatch("pairing_allow", {"request_id": "not-the-shown-one"}) + with pytest.raises(RuntimeError, match="different connect link"): + disp.dispatch("pairing_allow", {}) + assert claims == [] + + result = disp.dispatch("pairing_allow", {"request_id": prompt["request_id"]}) - monkeypatch.setattr("openadapt_desktop.auth.pairing.connect_uri", _connect) - result = disp.dispatch("connect_uri", {"uri": uri}) assert result["paired"] is True - assert received == [uri] + assert claims == [("https://app.openadapt.ai", _PAIRING_SECRET, None)] + assert disp.config.hosted_host == "https://app.openadapt.ai" assert ( "pairing_state", - { - "status": "connected", - "host": "https://app.openadapt.ai", - }, + {"status": "connected", "host": "https://app.openadapt.ai"}, ) in events + # One use: a second Allow can't spend the code again. + with pytest.raises(RuntimeError, match="isn't waiting"): + disp.dispatch("pairing_allow", {"request_id": prompt["request_id"]}) + assert len(claims) == 1 - def test_connect_uri_returns_the_canonical_authenticated_host( - self, deps, monkeypatch, tmp_path + def test_a_repeat_delivery_keeps_the_shown_request_and_a_new_link_replaces_it( + self, deps ) -> None: disp, _db, _events = deps - monkeypatch.setenv("OPENADAPT_CONFIG_TOML", str(tmp_path / "config.toml")) + first = disp.dispatch("connect_uri", {"uri": _CONNECT_URI}) + again = disp.dispatch("connect_uri", {"uri": _CONNECT_URI}) + assert again["request_id"] == first["request_id"] + + other = _CONNECT_URI.replace(_PAIRING_SECRET, "oap_" + "B" * 43) + replaced = disp.dispatch("connect_uri", {"uri": other}) + assert replaced["request_id"] != first["request_id"] + with pytest.raises(RuntimeError, match="different connect link"): + disp.dispatch("pairing_allow", {"request_id": first["request_id"]}) + + def test_prompt_warns_when_it_would_replace_the_current_pairing( + self, deps, fake_keyring + ) -> None: + from openadapt_desktop.auth.provider import Credential + from openadapt_desktop.auth.store import store_credential + + disp, _db, _events = deps + credential: Credential = { + "kind": "ingest_token", + "token": "oai_ingest_current", + "refresh_token": None, + "org_id": None, + "host": "https://app.openadapt.ai", + "expires_at": None, + } + store_credential(credential) + + prompt = disp.dispatch("connect_uri", {"uri": _CONNECT_URI}) + + # Same host can still be a different workspace, so warn every time. + assert prompt["already_paired"] is True + assert prompt["current_host"] == "https://app.openadapt.ai" + assert prompt["workspace"] is None + assert prompt["account"] is None + + def test_prompt_warns_when_the_keychain_cannot_be_read(self, deps, monkeypatch) -> None: + disp, _db, _events = deps + + def _locked(): + raise RuntimeError("keychain locked") + + monkeypatch.setattr("openadapt_desktop.auth.store.active_credential", _locked) + prompt = disp.dispatch("connect_uri", {"uri": _CONNECT_URI}) + assert prompt["already_paired"] is True + + def test_expired_request_cannot_be_allowed(self, deps, monkeypatch) -> None: + import openadapt_desktop.dispatch as dispatch_module + + disp, _db, _events = deps + claims: list[tuple] = [] monkeypatch.setattr( - "openadapt_desktop.auth.pairing.connect_uri", - lambda _uri: { - "authenticated": True, - "host": "HTTPS://Customer.Example:443/pairing", - "paired": True, - }, + "openadapt_desktop.auth.pairing.claim_pairing", + lambda *args, **kwargs: claims.append(args), ) + prompt = disp.dispatch("connect_uri", {"uri": _CONNECT_URI}) + now = dispatch_module.time.monotonic() + monkeypatch.setattr( + dispatch_module.time, + "monotonic", + lambda: now + dispatch_module.PAIRING_CONFIRM_TTL_S + 1, + ) + assert disp.dispatch("pairing_status", {}) == {"status": "idle"} + with pytest.raises(RuntimeError, match="isn't waiting"): + disp.dispatch("pairing_allow", {"request_id": prompt["request_id"]}) + assert claims == [] - result = disp.dispatch("connect_uri", {"uri": "openadapt://connect"}) - - assert result["host"] == "https://customer.example" - assert disp.config.hosted_host == "https://customer.example" + def test_local_cloud_links_need_the_developer_setting(self, deps) -> None: + disp, _db, events = deps + local = ( + "openadapt://connect?pairing=" + + _PAIRING_SECRET + + "&host=http%3A%2F%2Flocalhost%3A3000&destination_kind=local" + ) + disp.config.allow_local_pairing = False + with pytest.raises(RuntimeError, match="allow_local_pairing"): + disp.dispatch("connect_uri", {"uri": local}) + assert disp.dispatch("pairing_status", {}) == {"status": "idle"} + assert events[-1][1]["status"] == "error" + + disp.config.allow_local_pairing = True + prompt = disp.dispatch("connect_uri", {"uri": local}) + assert prompt["host"] == "http://localhost:3000" + + def test_connect_links_outside_the_allowlist_are_refused(self, deps) -> None: + disp, _db, _events = deps + disp.config.allow_local_pairing = True + for host in ( + "https%3A%2F%2Fcustomer.example", + "https%3A%2F%2Fapp.openadapt.ai.evil.example", + "http%3A%2F%2Fapp.openadapt.ai", + ): + uri = f"openadapt://connect?pairing={_PAIRING_SECRET}&host={host}" + with pytest.raises(RuntimeError): + disp.dispatch("connect_uri", {"uri": uri}) + assert disp.dispatch("pairing_status", {}) == {"status": "idle"} def test_connect_uri_requires_a_single_string_parameter(self, deps) -> None: disp, _db, _events = deps @@ -2517,6 +2654,14 @@ def test_connect_uri_requires_a_single_string_parameter(self, deps) -> None: with pytest.raises(ValueError, match="uri is required"): disp.dispatch("connect_uri", params) + def test_pairing_allow_is_served_on_the_window_wire_only(self) -> None: + from openadapt_desktop import socket_server + + for name in ("pairing_allow", "pairing_deny", "connect_uri"): + assert name not in socket_server._TRAY_COMMANDS + assert name not in socket_server._LOCAL_AGENT_COMMANDS + assert name not in socket_server._SETUP_AGENT_COMMANDS + class TestConfigCommands: def test_get_config(self, deps) -> None: diff --git a/packages/desktop/tests/test_pairing_protocol_boundary.py b/packages/desktop/tests/test_pairing_protocol_boundary.py index fe1f549f27..ff66cd958b 100644 --- a/packages/desktop/tests/test_pairing_protocol_boundary.py +++ b/packages/desktop/tests/test_pairing_protocol_boundary.py @@ -71,3 +71,37 @@ def test_python_runner_bind_is_parse_only() -> None: assert '"allow"' in authoring assert "win_agent" in authoring assert "from openadapt_flow.backends.win_agent" not in authoring + + +def test_a_connect_link_only_stages_and_allow_is_not_reachable_from_a_link() -> None: + pairing = (ROOT / "src-tauri/src/pairing.rs").read_text() + dispatch = (ROOT / "openadapt_desktop/dispatch.py").read_text() + # The deep link reaches only the staging verb; Allow comes from the window. + assert '"pairing_allow"' not in pairing.split("#[cfg(test)]", 1)[0] + assert '"pairing_allow": self.pairing_allow' in dispatch + stage = dispatch.split(" def connect_uri(", 1)[1].split("\n def ", 1)[0] + assert "import connect_uri" not in stage + for redeem in ("claim_pairing", "httpx", "_persist_config_key"): + assert redeem not in stage + assert "hosted_host =" not in stage + + +def test_the_window_gets_no_shell_permission() -> None: + # Rust starts the engine sidecar (sidecar.rs); the webview never runs it. + for path in (ROOT / "src-tauri/capabilities").glob("*.json"): + permissions = json.loads(path.read_text())["permissions"] + identifiers = { + item if isinstance(item, str) else item["identifier"] for item in permissions + } + assert not {i for i in identifiers if i.startswith("shell:")}, path.name + package = json.loads((ROOT / "package.json").read_text()) + assert "@tauri-apps/plugin-shell" not in package.get("dependencies", {}) + frontend = [ + path + for path in (ROOT / "src").rglob("*") + if path.suffix in {".ts", ".tsx"} and path.is_file() + ] + for path in frontend: + text = path.read_text(encoding="utf-8") + assert "plugin-shell" not in text, path + assert "plugin:shell" not in text, path From 3cb9a49b40e1a658a4860708053a4c1c89c22710 Mon Sep 17 00:00:00 2001 From: abrichr Date: Sun, 29 Nov 2026 21:14:07 -0500 Subject: [PATCH 2/9] chore(desktop): release 0.35.1 --- packages/desktop/CHANGELOG.md | 12 ++++++++++++ packages/desktop/openadapt_desktop/__init__.py | 2 +- packages/desktop/package-lock.json | 4 ++-- packages/desktop/package.json | 2 +- packages/desktop/pyproject.toml | 2 +- packages/desktop/src-tauri/Cargo.lock | 2 +- packages/desktop/src-tauri/Cargo.toml | 2 +- packages/desktop/src-tauri/tauri.conf.json | 2 +- packages/desktop/uv.lock | 2 +- 9 files changed, 21 insertions(+), 9 deletions(-) diff --git a/packages/desktop/CHANGELOG.md b/packages/desktop/CHANGELOG.md index e8421c03cc..31ad0ae68a 100644 --- a/packages/desktop/CHANGELOG.md +++ b/packages/desktop/CHANGELOG.md @@ -1,6 +1,18 @@ # CHANGELOG +## v0.35.1 (2026-11-29) + +### Features + +- **flow**: support general on-screen read-back and graded VERIFIED floors + +### Bug Fixes + +- **desktop**: ask before a connect link pairs this computer + + + ## v0.35.0 (2026-11-24) ### Features diff --git a/packages/desktop/openadapt_desktop/__init__.py b/packages/desktop/openadapt_desktop/__init__.py index 574a1e8b9f..42da48fdd5 100644 --- a/packages/desktop/openadapt_desktop/__init__.py +++ b/packages/desktop/openadapt_desktop/__init__.py @@ -21,4 +21,4 @@ +-- backends/ Storage backend plugins """ -__version__ = "0.35.0" +__version__ = "0.35.1" diff --git a/packages/desktop/package-lock.json b/packages/desktop/package-lock.json index 7c5eba7609..2e624f89d4 100644 --- a/packages/desktop/package-lock.json +++ b/packages/desktop/package-lock.json @@ -1,12 +1,12 @@ { "name": "openadapt-desktop", - "version": "0.35.0", + "version": "0.35.1", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "openadapt-desktop", - "version": "0.35.0", + "version": "0.35.1", "dependencies": { "@tauri-apps/api": "^2", "@tauri-apps/plugin-notification": "^2", diff --git a/packages/desktop/package.json b/packages/desktop/package.json index 86b4c496ca..021f46c543 100644 --- a/packages/desktop/package.json +++ b/packages/desktop/package.json @@ -1,6 +1,6 @@ { "name": "openadapt-desktop", - "version": "0.35.0", + "version": "0.35.1", "description": "Installed companion for OpenAdapt authoring, teaching, and local pairing", "private": true, "type": "module", diff --git a/packages/desktop/pyproject.toml b/packages/desktop/pyproject.toml index ca8eb3f38a..3a829046fd 100644 --- a/packages/desktop/pyproject.toml +++ b/packages/desktop/pyproject.toml @@ -4,7 +4,7 @@ build-backend = "hatchling.build" [project] name = "openadapt-desktop" -version = "0.35.0" +version = "0.35.1" description = "The OpenAdapt desktop app and local engine: record a data-entry task, run it on a list, and check each saved record" readme = "README.md" requires-python = ">=3.11" diff --git a/packages/desktop/src-tauri/Cargo.lock b/packages/desktop/src-tauri/Cargo.lock index 91b42bb5d5..8dd40ce78d 100644 --- a/packages/desktop/src-tauri/Cargo.lock +++ b/packages/desktop/src-tauri/Cargo.lock @@ -2513,7 +2513,7 @@ dependencies = [ [[package]] name = "openadapt-desktop" -version = "0.35.0" +version = "0.35.1" dependencies = [ "hex", "reqwest", diff --git a/packages/desktop/src-tauri/Cargo.toml b/packages/desktop/src-tauri/Cargo.toml index 847814b00a..76072810eb 100644 --- a/packages/desktop/src-tauri/Cargo.toml +++ b/packages/desktop/src-tauri/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "openadapt-desktop" -version = "0.35.0" +version = "0.35.1" description = "Installed companion for OpenAdapt authoring, teaching, and local pairing" authors = ["OpenAdapt AI"] license = "MIT" diff --git a/packages/desktop/src-tauri/tauri.conf.json b/packages/desktop/src-tauri/tauri.conf.json index 6efcb55544..9f42a42503 100644 --- a/packages/desktop/src-tauri/tauri.conf.json +++ b/packages/desktop/src-tauri/tauri.conf.json @@ -1,7 +1,7 @@ { "$schema": "https://raw.githubusercontent.com/nicoverbruggen/tauri-v2-schema/main/schema.json", "productName": "OpenAdapt Desktop", - "version": "0.35.0", + "version": "0.35.1", "identifier": "ai.openadapt.desktop", "build": { "frontendDist": "../dist", diff --git a/packages/desktop/uv.lock b/packages/desktop/uv.lock index 819f4a2cb4..249bdaf4a6 100644 --- a/packages/desktop/uv.lock +++ b/packages/desktop/uv.lock @@ -1172,7 +1172,7 @@ wheels = [ [[package]] name = "openadapt-desktop" -version = "0.35.0" +version = "0.35.1" source = { editable = "." } dependencies = [ { name = "cryptography" }, From 7bb9d2ca6b3dd66754e77901bf1e50707fc84ecc Mon Sep 17 00:00:00 2001 From: abrichr Date: Sun, 29 Nov 2026 21:20:55 -0500 Subject: [PATCH 3/9] test(desktop): cover live connect links and window-only Allow Test the dialog for a link that arrives while the app is open, that the loopback socket can't send Allow, and that the window can't turn on local pairing. Drop an unused countdown field from the prompt and update the installer doc. --- .../docs/RELEASE_CANDIDATE_INSTALLERS.md | 5 ++- .../desktop/openadapt_desktop/dispatch.py | 1 - .../desktop/src/App.pairingConfirm.test.tsx | 39 ++++++++++++++++++- .../tests/test_engine/test_dispatch.py | 15 +++++-- 4 files changed, 51 insertions(+), 9 deletions(-) diff --git a/packages/desktop/docs/RELEASE_CANDIDATE_INSTALLERS.md b/packages/desktop/docs/RELEASE_CANDIDATE_INSTALLERS.md index 650758b471..5c5faf9bc0 100644 --- a/packages/desktop/docs/RELEASE_CANDIDATE_INSTALLERS.md +++ b/packages/desktop/docs/RELEASE_CANDIDATE_INSTALLERS.md @@ -6,8 +6,9 @@ OpenAdapt Desktop native packages are **unadmitted candidates** for the installed authoring, teaching, and local-pairing companion. They bundle and start the Python sidecar, connect the Tauri/React cockpit to it over local JSON-lines IPC, and register the `openadapt://` operating-system handler. The handler accepts -only the fixed `openadapt://connect` action and forwards it to the sidecar's -strict, transactional pairing flow. +only the fixed `openadapt://connect` action and forwards it to the sidecar, +which redeems nothing until the person clicks Allow in the window; then the +strict, transactional pairing flow runs. The canonical compiler and governed runtime remain in `openadapt-flow`. Each native installer freezes the exact `openadapt-flow[browser,console]==2.4.1` diff --git a/packages/desktop/openadapt_desktop/dispatch.py b/packages/desktop/openadapt_desktop/dispatch.py index 6adcb5ce13..0f1237ad06 100644 --- a/packages/desktop/openadapt_desktop/dispatch.py +++ b/packages/desktop/openadapt_desktop/dispatch.py @@ -6039,7 +6039,6 @@ def _pairing_prompt(self, pending: dict[str, Any]) -> dict[str, Any]: "account": None, "already_paired": already_paired, "current_host": current_host or None, - "expires_in_s": max(0, int(float(pending["expires_at"]) - time.monotonic())), } def pairing_status(self, **params: Any) -> dict: diff --git a/packages/desktop/src/App.pairingConfirm.test.tsx b/packages/desktop/src/App.pairingConfirm.test.tsx index 7c5e732fe0..9c92bc30c8 100644 --- a/packages/desktop/src/App.pairingConfirm.test.tsx +++ b/packages/desktop/src/App.pairingConfirm.test.tsx @@ -1,4 +1,4 @@ -import { cleanup, fireEvent, render, screen, waitFor } from "@testing-library/react"; +import { act, cleanup, fireEvent, render, screen, waitFor } from "@testing-library/react"; import { afterEach, expect, it, vi } from "vitest"; // A connect link opened at launch is staged before the window listens, so the @@ -21,7 +21,7 @@ vi.mock("./screens/Welcome", () => ({ })); import App from "./App"; -import { CMD, engineInvoke, engineTry } from "./lib/engine"; +import { CMD, EVT, engineInvoke, engineTry, onEngineEvent } from "./lib/engine"; afterEach(() => { cleanup(); @@ -82,3 +82,38 @@ it("Not now redeems nothing", async () => { expect(sent(CMD.PAIRING_ALLOW)).toBe(false); expect(screen.queryByRole("alertdialog")).toBeNull(); }); + +it("shows a link that arrives while the app is open, and clears on declined", async () => { + vi.mocked(engineTry).mockImplementation(async (command, _params, fallback) => { + if (command === CMD.GET_AUTH_STATUS) return { authenticated: true }; + if (command === CMD.GET_WORKFLOWS) return []; + if (command === CMD.GET_FIRST_WORKFLOW_STATE) return { ok: true, state: null }; + if (command === CMD.PAIRING_STATUS) return { status: "idle" }; + return fallback ?? null; + }); + const handlers = new Map void>(); + vi.mocked(onEngineEvent).mockImplementation(((event: string, handler: (p: unknown) => void) => { + handlers.set(event, handler); + return Promise.resolve(() => {}); + }) as typeof onEngineEvent); + + render(); + await waitFor(() => expect(handlers.has(EVT.PAIRING_STATE)).toBe(true)); + expect(screen.queryByRole("alertdialog")).toBeNull(); + + act(() => + handlers.get(EVT.PAIRING_STATE)?.({ + status: "pending_confirm", + request_id: "req-7", + host: "https://app.openadapt.ai", + already_paired: false, + }), + ); + const dialog = await screen.findByRole("alertdialog"); + expect(dialog.textContent).toContain("app.openadapt.ai"); + expect(dialog.textContent).not.toContain("replaces"); + expect(sent(CMD.PAIRING_ALLOW)).toBe(false); + + act(() => handlers.get(EVT.PAIRING_STATE)?.({ status: "declined" })); + await waitFor(() => expect(screen.queryByRole("alertdialog")).toBeNull()); +}); diff --git a/packages/desktop/tests/test_engine/test_dispatch.py b/packages/desktop/tests/test_engine/test_dispatch.py index 810758e4e8..3ee47ee7dc 100644 --- a/packages/desktop/tests/test_engine/test_dispatch.py +++ b/packages/desktop/tests/test_engine/test_dispatch.py @@ -2655,12 +2655,19 @@ def test_connect_uri_requires_a_single_string_parameter(self, deps) -> None: disp.dispatch("connect_uri", params) def test_pairing_allow_is_served_on_the_window_wire_only(self) -> None: + # The loopback socket (tray and local agents) refuses any command + # outside _SOCKET_COMMANDS, so only the window can say Allow. from openadapt_desktop import socket_server - for name in ("pairing_allow", "pairing_deny", "connect_uri"): - assert name not in socket_server._TRAY_COMMANDS - assert name not in socket_server._LOCAL_AGENT_COMMANDS - assert name not in socket_server._SETUP_AGENT_COMMANDS + for name in ("pairing_allow", "pairing_deny", "pairing_status", "connect_uri"): + assert name not in socket_server._SOCKET_COMMANDS + + def test_the_local_pairing_setting_cannot_be_set_from_the_window(self, deps) -> None: + disp, _db, _e = deps + disp.config.allow_local_pairing = False + result = disp.dispatch("set_config", {"key": "allow_local_pairing", "value": True}) + assert result["ok"] is False + assert disp.config.allow_local_pairing is False class TestConfigCommands: From 94696ce1a736ea0077d24ea727f1edd9361a4e67 Mon Sep 17 00:00:00 2001 From: abrichr Date: Sun, 29 Nov 2026 21:50:39 -0500 Subject: [PATCH 4/9] fix(desktop): show the workspace and switch only on the person's say-so Allow on a connect link no longer makes the new connection active. An attacker's code for their own workspace also names app.openadapt.ai, so the host alone can't tell the person anything. Allow now claims the code and checks the new credential without writing it to the keychain or changing the Cloud host. The window then names the workspace and account Cloud reported and the current workspace, with "Switch to " and "Keep ". Only Switch stages and commits the credential (the existing rollback path). Keep, a 90-second timeout, a new link or a restart revokes or drops it; Cloud also revokes a claim nobody confirms within two minutes. Workspaces are compared by id, since whoever makes the code chooses the name. If Cloud's answer names no workspace, Desktop revokes the claim, keeps its current connection and shows an error. Desktop asks for the names with include_identity in the claim request; Cloud doesn't send them yet, so until it does every connect link ends with that error. Signing in from Desktop is unaffected. --- .../desktop/openadapt_desktop/auth/pairing.py | 250 ++++++++++++++- packages/desktop/openadapt_desktop/config.py | 18 +- .../desktop/openadapt_desktop/dispatch.py | 174 ++++++++-- .../desktop/src/App.pairingConfirm.test.tsx | 31 +- packages/desktop/src/App.tsx | 39 ++- packages/desktop/src/lib/engine.ts | 2 + .../desktop/src/ui/PairingConfirm.test.tsx | 64 +++- packages/desktop/src/ui/PairingConfirm.tsx | 76 ++++- .../tests/test_engine/test_auth_pairing.py | 162 ++++++++++ .../tests/test_engine/test_dispatch.py | 296 ++++++++++++++++-- .../tests/test_pairing_protocol_boundary.py | 20 +- 11 files changed, 1048 insertions(+), 84 deletions(-) diff --git a/packages/desktop/openadapt_desktop/auth/pairing.py b/packages/desktop/openadapt_desktop/auth/pairing.py index bc4f91099c..a9621a3e9c 100644 --- a/packages/desktop/openadapt_desktop/auth/pairing.py +++ b/packages/desktop/openadapt_desktop/auth/pairing.py @@ -46,6 +46,14 @@ ALLOWED_FIELDS = frozenset({"pairing", "host", "destination_kind"}) ALLOWED_DESTINATIONS = frozenset({"openadapt-managed", "local"}) API_TIMEOUT_S = 8.0 +#: A reviewed claim must be switched to well before Cloud revokes a claim that +#: was never confirmed (two minutes after the claim). +REVIEW_TTL_S = 90.0 +#: Asks Cloud to name the workspace and account in the claim response. A Cloud +#: that doesn't know the field ignores it and answers with the usual keys. +IDENTITY_REQUEST_FIELD = "include_identity" +_IDENTITY_KEYS = frozenset({"workspace", "account"}) +_NAME_MAX = 120 class PairingError(RuntimeError): @@ -512,8 +520,14 @@ def _canonical_uuid(value: Any) -> str: return canonical -def _validated_claim(body: Any, headers: Any) -> tuple[str, str, float]: - """Validate the complete Cloud 201 response before staging its bearer.""" +def _validated_claim( + body: Any, headers: Any, *, allow_identity: bool = False +) -> tuple[str, str, float]: + """Validate the complete Cloud 201 response before staging its bearer. + + ``allow_identity`` additionally accepts the optional ``workspace`` and + ``account`` blocks a review claim asks for (:func:`claim_for_review`). + """ expected = { "paired", "pairing_id", @@ -521,7 +535,14 @@ def _validated_claim(body: Any, headers: Any) -> tuple[str, str, float]: "ingest_token", "credential", } - if not isinstance(body, dict) or set(body) != expected or body.get("paired") is not True: + keys = set(body) if isinstance(body, dict) else set() + extra = keys - expected + if ( + not isinstance(body, dict) + or not expected <= keys + or (extra and not (allow_identity and extra <= _IDENTITY_KEYS)) + or body.get("paired") is not True + ): raise PairingError("Pairing response did not match the credential contract") pairing_id = _canonical_uuid(body.get("pairing_id")) _canonical_uuid(body.get("ingest_token_id")) @@ -552,3 +573,226 @@ def _claim_abort_coordinates(body: Any) -> tuple[str, str] | None: except PairingError: return None return pairing_id, cast(str, body["ingest_token"]) + + +# -------------------------------------------------------------------------- +# Two-phase pairing for ``openadapt://connect`` links. +# +# Anyone can create a pairing code in their own workspace and put it in a link, +# and the host is app.openadapt.ai either way. So a link pairing is claimed and +# checked first (:func:`claim_for_review`), with nothing written to the +# keychain, and becomes this computer's connection only when the person picks +# Switch after seeing the workspace Cloud named (:func:`switch_reviewed`). +# Keep, a timeout or a restart discards it (:func:`discard_reviewed`); Cloud +# also revokes a claim nobody confirmed. + + +def _clean_name(value: Any) -> str | None: + """A display string from Cloud: no control characters, bounded length.""" + if not isinstance(value, str): + return None + cleaned = re.sub(r"[\x00-\x1f\x7f-\x9f\u200b-\u200f\u202a-\u202e\u2066-\u2069]", "", value) + cleaned = " ".join(cleaned.split())[:_NAME_MAX] + return cleaned or None + + +def claim_identity(body: Any) -> tuple[dict[str, str] | None, dict[str, str] | None]: + """Read the optional ``workspace`` and ``account`` blocks of a claim. + + A workspace counts only with both a canonical UUID ``id`` and a ``name``: + whoever made the code chooses the name, so Desktop compares by id. + """ + workspace: dict[str, str] | None = None + account: dict[str, str] | None = None + raw_workspace = body.get("workspace") if isinstance(body, dict) else None + if isinstance(raw_workspace, dict): + name = _clean_name(raw_workspace.get("name")) + try: + workspace_id = _canonical_uuid(raw_workspace.get("id")) + except PairingError: + workspace_id = None + if name and workspace_id: + workspace = {"id": workspace_id, "name": name} + raw_account = body.get("account") if isinstance(body, dict) else None + if isinstance(raw_account, dict): + email = _clean_name(raw_account.get("email")) + if email and "@" in email: + account = {"email": email} + return workspace, account + + +def _check_new_credential(host: str, token: str, expiry: float) -> str | None: + """Validate a just-claimed bearer; return a failure message or None.""" + try: + validation = httpx.get( + f"{host}/api/needs-attention/count", + headers={"Authorization": f"Bearer {token}"}, + timeout=API_TIMEOUT_S, + follow_redirects=False, + ) + except httpx.HTTPError: + return "Cloud could not verify the new credential." + if not 200 <= validation.status_code < 300: + return f"Cloud could not verify the new credential ({validation.status_code})." + try: + lifetime = parse_credential_lifetime( + validation.json(), + headers=validation.headers, + require_headers=True, + require_fresh=True, + require_no_store=True, + ) + except (AttributeError, TypeError, ValueError, CredentialContractError): + return "Cloud returned an incomplete credential lifetime contract." + if lifetime["expires_at_timestamp"] != expiry: + return "Cloud returned a different credential deadline during validation." + return None + + +def claim_for_review( + host: str, + pairing_secret: str, + destination_kind: str | None = None, + *, + now: float, +) -> dict[str, Any]: + """Claim and check one link's pairing code without making it active. + + Nothing is written to the keychain and no stage record is created, so a + crash or restart leaves the current connection exactly as it was. The + returned review holds the new bearer in memory only. + + Args: + host: The Cloud origin, re-validated here. + pairing_secret: The one-use ``oap_`` secret from the link. + destination_kind: The link's destination kind. + now: The caller's monotonic clock, for the review deadline. + + Returns: + A review for :func:`switch_reviewed` or :func:`discard_reviewed`. + + Raises: + PairingError: On any failure. A claimed code is revoked first. + """ + if not PAIRING_SECRET_RE.fullmatch(str(pairing_secret)): + raise PairingError("Pairing code is malformed") + host = _validate_destination(host, destination_kind) + if not secure_store_available(): + raise PairingError( + "Secure pairing needs an unlocked operating-system keychain. " + "Unlock it, then create a new connection from Cloud settings." + ) + try: + unfinished = load_pairing_stage() + except RuntimeError as exc: + raise PairingError( + "Desktop could not read pairing recovery state from the keychain" + ) from exc + if unfinished is not None: + # Recovery would promote that earlier connection without a Switch, so + # a link never runs it. Signing in from Desktop finishes it. + raise PairingError( + "Desktop has an unfinished earlier connection. Sign in from Desktop " + "to finish it, then open the link again. Nothing changed." + ) + + device_name = _safe_device_name() + try: + claim = httpx.post( + f"{host}/api/local-bridge/pairings/claim", + json={ + "pairing_secret": pairing_secret, + "device_name": device_name, + IDENTITY_REQUEST_FIELD: True, + }, + timeout=API_TIMEOUT_S, + follow_redirects=False, + ) + except httpx.HTTPError as exc: + raise PairingError("Could not reach OpenAdapt Cloud") from exc + if claim.status_code == 410: + raise PairingError("Pairing code expired, was cancelled, or was already used") + if claim.status_code >= 400: + raise PairingError(f"Pairing failed ({claim.status_code})") + if claim.status_code != 201: + raise PairingError("Pairing response used an unexpected success status") + try: + body = claim.json() + except (AttributeError, TypeError, ValueError) as exc: + raise PairingError("Pairing response was not valid JSON") from exc + try: + token, pairing_id, expiry = _validated_claim(body, claim.headers, allow_identity=True) + except PairingError: + rollback = _claim_abort_coordinates(body) + if rollback: + _abort_claim(host, rollback[0], rollback[1]) + raise + problem = _check_new_credential(host, token, expiry) + if problem is not None: + _abort_claim(host, pairing_id, token) + raise PairingError(f"{problem} Your previous Desktop connection is unchanged.") + workspace, account = claim_identity(body) + return { + "host": host, + "pairing_id": pairing_id, + "token": token, + "expires_at": expiry, + "device_name": device_name, + "workspace": workspace, + "account": account, + "deadline": now + REVIEW_TTL_S, + } + + +def discard_reviewed(review: dict[str, Any]) -> bool: + """Revoke a reviewed claim the person didn't switch to.""" + return _abort_claim(review["host"], review["pairing_id"], review["token"]) + + +def switch_reviewed(review: dict[str, Any], *, now: float) -> dict[str, Any]: + """Make a reviewed claim this computer's connection. + + Runs the same stage, validate, commit and confirm path as every other + pairing, so a failure rolls back to the connection Desktop had. + """ + if now >= float(review["deadline"]): + discard_reviewed(review) + raise PairingError( + "That connection waited too long and was cancelled. Nothing changed. " + "Create a new connection from Cloud settings." + ) + host = review["host"] + previous = snapshot_pairing_canonical(host) + if previous is None: + discard_reviewed(review) + raise PairingError( + "Desktop could not safely snapshot the current keychain connection. Nothing changed." + ) + credential: Credential = { + "kind": "ingest_token", + "token": review["token"], + "refresh_token": None, + "org_id": None, + "host": host, + "expires_at": review["expires_at"], + } + if not stage_pairing_credential( + review["pairing_id"], credential, previous, review["device_name"] + ): + discard_reviewed(review) + raise PairingError( + "Desktop could not durably stage the new credential. " + "Your previous Desktop connection is unchanged." + ) + try: + stage = load_pairing_stage() + except RuntimeError as exc: + raise PairingError( + "Desktop staged the credential but could not read it back; " + "the prior connection remains available for recovery." + ) from exc + if stage is None: + raise PairingError( + "Desktop could not recover the newly staged credential from the keychain" + ) + return _finish_staged_pairing(stage) diff --git a/packages/desktop/openadapt_desktop/config.py b/packages/desktop/openadapt_desktop/config.py index d9ec080b19..7a66e3ed79 100644 --- a/packages/desktop/openadapt_desktop/config.py +++ b/packages/desktop/openadapt_desktop/config.py @@ -35,6 +35,8 @@ "poll_interval_s": "poll_interval_s", "runner_enabled": "runner_enabled", "allow_local_pairing": "allow_local_pairing", + "paired_workspace_id": "paired_workspace_id", + "paired_workspace_name": "paired_workspace_name", } @@ -210,13 +212,21 @@ def settings_customise_sources( "[hosted] table of config.toml; a link or the window can't turn it on." ), ) - runner_enabled: bool = Field( - default=False, + paired_workspace_id: str = Field( + default="", description=( - "Enable the outbound hosted runner for admitted dispatches. " - "Off by default." + "Cloud workspace id this computer switched to from a connect link. " + "Display only; Cloud decides what the credential can reach." ), ) + paired_workspace_name: str = Field( + default="", + description="Cloud workspace name shown with paired_workspace_id.", + ) + runner_enabled: bool = Field( + default=False, + description=("Enable the outbound hosted runner for admitted dispatches. Off by default."), + ) # --- Mobile attended-decision portal (openadapt_desktop/portal) --- # The portal is loopback-only by default. Publishing it to a phone requires diff --git a/packages/desktop/openadapt_desktop/dispatch.py b/packages/desktop/openadapt_desktop/dispatch.py index 0f1237ad06..1cd66e7adf 100644 --- a/packages/desktop/openadapt_desktop/dispatch.py +++ b/packages/desktop/openadapt_desktop/dispatch.py @@ -92,8 +92,9 @@ def _noop_emit(event: str, data: dict) -> None: """Default event sink -- drops events when no emitter is wired.""" -#: How long a staged ``openadapt://connect`` request waits for Allow. -PAIRING_CONFIRM_TTL_S = 600.0 +#: How long a staged ``openadapt://connect`` request waits for Allow. Cloud's +#: pairing codes last five minutes. +PAIRING_CONFIRM_TTL_S = 300.0 def _canonical_hosted_origin(value: Any) -> str: @@ -284,6 +285,9 @@ def __init__( # only: the one-use pairing code never reaches disk, the window or a # log, and a restart drops it. self._pending_connect: dict[str, Any] | None = None + # A claimed link waiting for Switch or Keep: the new bearer, in memory + # only. Keep, a timeout or a restart discards it. + self._pending_switch: dict[str, Any] | None = None self._handlers: dict[str, Callable[..., dict | None]] = {} self._register() from openadapt_desktop.coach import empty_coach @@ -388,6 +392,8 @@ def _register(self) -> None: # the person clicks Allow in the window (window wire only). "pairing_status": self.pairing_status, "pairing_allow": self.pairing_allow, + "pairing_switch": self.pairing_switch, + "pairing_keep": self.pairing_keep, "pairing_deny": self.pairing_deny, "claim_runner_uri": self.claim_runner_uri, "authoring_allow": self.authoring_allow, @@ -5990,6 +5996,8 @@ def connect_uri(self, **params: Any) -> dict: # both deliver it): keep the request the window is showing. prompt = self._pairing_prompt(pending) else: + # A new link replaces any connection still waiting for Switch. + self._discard_pending_switch() self._pending_connect = { "request_id": uuid.uuid4().hex, "pairing": request["pairing"], @@ -6017,32 +6025,25 @@ def _pending_connect_expired(pending: dict[str, Any]) -> bool: return time.monotonic() >= float(pending["expires_at"]) def _pairing_prompt(self, pending: dict[str, Any]) -> dict[str, Any]: - """What the window shows. Never carries the pairing code.""" - from openadapt_desktop.auth.store import active_credential, canonical_host_origin - - try: - current = active_credential() - current_host = ( - canonical_host_origin(str(current.get("host") or "")) if current else None - ) - already_paired = current is not None - except Exception: # noqa: BLE001 - an unreadable keychain must not hide the warning - current_host = None - already_paired = True + """The Allow question. Never carries the pairing code.""" return { "status": "pending_confirm", "request_id": pending["request_id"], "host": pending["host"], - # Cloud has no way to look up a pairing code without redeeming it, - # so Desktop can't name the workspace or account before Allow. + # Cloud names the workspace only once the code is claimed, which + # needs Allow. The Switch question after it shows the name. "workspace": None, "account": None, - "already_paired": already_paired, - "current_host": current_host or None, + **self._current_pairing(), } def pairing_status(self, **params: Any) -> dict: - """Return the connect request waiting for Allow, or ``idle``.""" + """Return the connect question waiting in the window, or ``idle``.""" + switch = self._pending_switch + if switch is not None: + if time.monotonic() < float(switch["review"]["deadline"]): + return self._switch_prompt(switch) + self._discard_pending_switch() pending = self._pending_connect if pending is None: return {"status": "idle"} @@ -6052,12 +6053,18 @@ def pairing_status(self, **params: Any) -> dict: return self._pairing_prompt(pending) def pairing_allow(self, **params: Any) -> dict: - """Redeem the staged connect request the person allowed in the window. + """Claim the connect request the person allowed, for review only. ``request_id`` must name the request the window showed, so a second - link that arrives before the click can't be allowed by it. + link that arrives before the click can't be allowed by it. The claim + is checked but not made active: the window then shows the workspace + Cloud named, and only :meth:`pairing_switch` changes the connection. """ - from openadapt_desktop.auth.pairing import PairingError, claim_pairing + from openadapt_desktop.auth.pairing import ( + PairingError, + claim_for_review, + discard_reviewed, + ) pending = self._pending_connect if pending is None or self._pending_connect_expired(pending): @@ -6076,13 +6083,115 @@ def pairing_allow(self, **params: Any) -> dict: raise PairingError(message) # One use: the code is spent or refused below, never offered again. self._pending_connect = None + self._discard_pending_switch() self.emit("pairing_state", {"status": "connecting", "host": pending["host"]}) try: - result = claim_pairing( + review = claim_for_review( pending["host"], pending["pairing"], destination_kind=pending.get("destination_kind"), + now=time.monotonic(), + ) + except PairingError as exc: + self.emit("pairing_state", {"status": "error", "error": str(exc)}) + raise + except Exception: + self.emit( + "pairing_state", + {"status": "error", "error": "The secure connection could not be completed."}, + ) + raise + if review["workspace"] is None: + # Without a workspace Cloud vouches for, Switch would be a guess. + discard_reviewed(review) + message = ( + "OpenAdapt Cloud didn't say which workspace this link belongs to, " + "so Desktop cancelled it and kept its current connection. " + "Nothing changed." + ) + self.emit("pairing_state", {"status": "error", "error": message}) + raise PairingError(message) + self._pending_switch = {"request_id": uuid.uuid4().hex, "review": review} + prompt = self._switch_prompt(self._pending_switch) + self.emit("pairing_state", prompt) + return prompt + + def _current_pairing(self) -> dict[str, Any]: + """What this computer is connected to now, as far as Desktop knows.""" + from openadapt_desktop.auth.store import active_credential, canonical_host_origin + + try: + current = active_credential() + host = canonical_host_origin(str(current.get("host") or "")) if current else None + paired = current is not None + except Exception: # noqa: BLE001 - an unreadable keychain must not hide the warning + host, paired = None, True + workspace = None + if paired and self.config.paired_workspace_id and self.config.paired_workspace_name: + workspace = { + "id": self.config.paired_workspace_id, + "name": self.config.paired_workspace_name, + } + return { + "already_paired": paired, + "current_host": host or None, + "current_workspace": workspace, + } + + def _switch_prompt(self, pending: dict[str, Any]) -> dict[str, Any]: + """The Switch or Keep question. Never carries the bearer.""" + review = pending["review"] + current = self._current_pairing() + same = ( + current["current_workspace"] is not None + and current["current_workspace"]["id"] == review["workspace"]["id"] + ) + return { + "status": "pending_switch", + "request_id": pending["request_id"], + "host": review["host"], + "workspace": review["workspace"], + "account": review["account"], + "same_workspace": same, + **current, + } + + def _discard_pending_switch(self) -> bool | None: + """Revoke a reviewed claim nobody switched to. None if there was none.""" + from openadapt_desktop.auth.pairing import discard_reviewed + + pending = self._pending_switch + self._pending_switch = None + if pending is None: + return None + try: + return discard_reviewed(pending["review"]) + except Exception: # noqa: BLE001 - Cloud also revokes an unconfirmed claim + return False + + def pairing_switch(self, **params: Any) -> dict: + """Make the reviewed claim the window showed this computer's connection.""" + from openadapt_desktop.auth.pairing import PairingError, switch_reviewed + + pending = self._pending_switch + if pending is None or time.monotonic() >= float(pending["review"]["deadline"]): + self._discard_pending_switch() + message = ( + "That connection isn't waiting any more, so Desktop kept its current " + "connection. Nothing changed." + ) + self.emit("pairing_state", {"status": "error", "error": message}) + raise PairingError(message) + if params.get("request_id") != pending["request_id"]: + self.emit("pairing_state", self._switch_prompt(pending)) + raise PairingError( + "Review the connection on screen before you switch. Nothing changed." ) + self._pending_switch = None + review = pending["review"] + self.emit("pairing_state", {"status": "connecting", "host": review["host"]}) + try: + result = switch_reviewed(review, now=time.monotonic()) except PairingError as exc: self.emit("pairing_state", {"status": "error", "error": str(exc)}) raise @@ -6093,13 +6202,28 @@ def pairing_allow(self, **params: Any) -> dict: ) raise host = _canonical_hosted_origin(result["host"]) - result = {**result, "host": host} + workspace = review["workspace"] + result = {**result, "host": host, "workspace": workspace} self.config.hosted_host = host + self.config.paired_workspace_id = workspace["id"] + self.config.paired_workspace_name = workspace["name"] self._persist_config_key("hosted_host", host) - self.emit("pairing_state", {"status": "connected", "host": host}) + self._persist_config_key("paired_workspace_id", workspace["id"]) + self._persist_config_key("paired_workspace_name", workspace["name"]) + self.emit( + "pairing_state", + {"status": "connected", "host": host, "workspace": workspace}, + ) self._emit_sync(self._sync_state_now()) return result + def pairing_keep(self, **params: Any) -> dict: + """Keep the current connection and revoke the reviewed claim.""" + revoked = self._discard_pending_switch() + state = {"status": "kept", "revoked": revoked is True} + self.emit("pairing_state", state) + return state + def pairing_deny(self, **params: Any) -> dict: """Drop the staged connect request. Nothing was redeemed.""" self._pending_connect = None diff --git a/packages/desktop/src/App.pairingConfirm.test.tsx b/packages/desktop/src/App.pairingConfirm.test.tsx index 9c92bc30c8..d7569e545c 100644 --- a/packages/desktop/src/App.pairingConfirm.test.tsx +++ b/packages/desktop/src/App.pairingConfirm.test.tsx @@ -64,7 +64,7 @@ it("asks before connecting and says it replaces the current pairing", async () = render(); const dialog = await screen.findByRole("alertdialog"); expect(dialog.textContent).toContain("app.openadapt.ai"); - expect(dialog.textContent).toContain("Allowing replaces that connection."); + expect(dialog.textContent).toContain("Your connection stays as it is unless you then choose Switch."); expect(sent(CMD.PAIRING_ALLOW)).toBe(false); fireEvent.click(screen.getByRole("button", { name: "Allow" })); @@ -111,9 +111,36 @@ it("shows a link that arrives while the app is open, and clears on declined", as ); const dialog = await screen.findByRole("alertdialog"); expect(dialog.textContent).toContain("app.openadapt.ai"); - expect(dialog.textContent).not.toContain("replaces"); + expect(dialog.textContent).not.toContain("already connected"); expect(sent(CMD.PAIRING_ALLOW)).toBe(false); act(() => handlers.get(EVT.PAIRING_STATE)?.({ status: "declined" })); await waitFor(() => expect(screen.queryByRole("alertdialog")).toBeNull()); }); + +it("after Allow, only Switch makes the new workspace active; Keep discards it", async () => { + vi.mocked(engineTry).mockImplementation(async (command, _params, fallback) => { + if (command === CMD.GET_AUTH_STATUS) return { authenticated: true }; + if (command === CMD.GET_WORKFLOWS) return []; + if (command === CMD.GET_FIRST_WORKFLOW_STATE) return { ok: true, state: null }; + if (command === CMD.PAIRING_STATUS) { + return { + status: "pending_switch", + request_id: "sw-9", + host: "https://app.openadapt.ai", + workspace: { id: "6f9d2c1e-0b7a-4c3e-9a51-2d8f4b6e7a10", name: "Northside Clinic" }, + account: null, + already_paired: true, + current_workspace: null, + }; + } + return fallback ?? null; + }); + render(); + const dialog = await screen.findByRole("alertdialog"); + expect(dialog.textContent).toContain("Northside Clinic"); + fireEvent.click(screen.getByRole("button", { name: "Keep current connection" })); + await waitFor(() => expect(sent(CMD.PAIRING_KEEP)).toBe(true)); + expect(sent(CMD.PAIRING_SWITCH)).toBe(false); + expect(screen.queryByRole("alertdialog")).toBeNull(); +}); diff --git a/packages/desktop/src/App.tsx b/packages/desktop/src/App.tsx index 7c4403bab8..b155da542c 100644 --- a/packages/desktop/src/App.tsx +++ b/packages/desktop/src/App.tsx @@ -49,7 +49,12 @@ import { deliverAttentionNotification } from "./lib/attentionNotification"; import { Qualification } from "./screens/Qualification"; import { clearLocalSession, rememberLocalSession } from "./localSession"; import { ItemApprovalDialog } from "./ui/ItemApproval"; -import { PairingConfirm, type PairingPrompt } from "./ui/PairingConfirm"; +import { + PairingConfirm, + PairingSwitch, + type PairingPrompt, + type PairingSwitchPrompt, +} from "./ui/PairingConfirm"; import { ShadowModeIndicator, ShadowPromptBanner, @@ -95,8 +100,9 @@ type Route = type PairingState = | PairingPrompt + | PairingSwitchPrompt | { - status: "connecting" | "connected" | "declined" | "error" | "idle"; + status: "connecting" | "connected" | "declined" | "kept" | "error" | "idle"; error?: string; }; @@ -511,7 +517,10 @@ export default function App() { {}, { status: "idle" }, ); - if (pairingStatus?.status === "pending_confirm") { + if ( + pairingStatus?.status === "pending_confirm" || + pairingStatus?.status === "pending_switch" + ) { setPairing(pairingStatus); } setAtRest( @@ -570,7 +579,10 @@ export default function App() { }), onEngineEvent(EVT.PAIRING_STATE, (state: PairingState | null) => { setPairing( - !state?.status || state.status === "declined" || state.status === "idle" + !state?.status || + state.status === "declined" || + state.status === "kept" || + state.status === "idle" ? null : state, ); @@ -624,6 +636,25 @@ export default function App() { void engineTry(CMD.PAIRING_DENY, {}, null); }} /> + ) : pairing?.status === "pending_switch" ? ( + { + setPairing({ status: "connecting" }); + engineInvoke(CMD.PAIRING_SWITCH, { request_id: requestId }).catch( + (error: unknown) => + setPairing((current) => + current?.status === "connecting" + ? { status: "error", error: String(error) } + : current, + ), + ); + }} + onKeep={() => { + setPairing(null); + void engineTry(CMD.PAIRING_KEEP, {}, null); + }} + /> ) : pairing && (pairing.status === "connecting" || pairing.status === "connected" || diff --git a/packages/desktop/src/lib/engine.ts b/packages/desktop/src/lib/engine.ts index 143e7a411a..5df2265257 100644 --- a/packages/desktop/src/lib/engine.ts +++ b/packages/desktop/src/lib/engine.ts @@ -105,6 +105,8 @@ export const CMD = { // An openadapt://connect link only stages a request; Allow redeems it. PAIRING_STATUS: "pairing_status", PAIRING_ALLOW: "pairing_allow", + PAIRING_SWITCH: "pairing_switch", + PAIRING_KEEP: "pairing_keep", PAIRING_DENY: "pairing_deny", AUTHORING_ALLOW: "authoring_allow", AUTHORING_DENY: "authoring_deny", diff --git a/packages/desktop/src/ui/PairingConfirm.test.tsx b/packages/desktop/src/ui/PairingConfirm.test.tsx index aacdc08e77..91c3d4c3b6 100644 --- a/packages/desktop/src/ui/PairingConfirm.test.tsx +++ b/packages/desktop/src/ui/PairingConfirm.test.tsx @@ -1,6 +1,14 @@ import { cleanup, fireEvent, render, screen } from "@testing-library/react"; import { afterEach, describe, expect, it, vi } from "vitest"; -import { PairingConfirm, pairingQuestion, type PairingPrompt } from "./PairingConfirm"; +import { + PairingConfirm, + PairingSwitch, + keepLabel, + pairingQuestion, + switchQuestion, + type PairingPrompt, + type PairingSwitchPrompt, +} from "./PairingConfirm"; afterEach(cleanup); @@ -18,30 +26,30 @@ describe("PairingConfirm", () => { it("names the target host and says the workspace isn't known yet", () => { const text = pairingQuestion(prompt); expect(text).toContain("app.openadapt.ai"); - expect(text).toMatch(/can't show which workspace/); - expect(text).not.toMatch(/replaces/); + expect(text).toMatch(/shows which workspace this link belongs to after you allow it/); + expect(text).not.toMatch(/already connected/); }); it("names the workspace and account when the engine reports them", () => { const text = pairingQuestion({ ...prompt, workspace: "Clinic A", account: "pat" }); expect(text).toContain("(workspace Clinic A, account pat)"); - expect(text).not.toMatch(/can't show/); + expect(text).not.toMatch(/after you allow it/); }); - it("says the link replaces the current pairing, even on the same host", () => { + it("says the current pairing stays unless the person switches, even on the same host", () => { const text = pairingQuestion({ ...prompt, already_paired: true, current_host: "https://app.openadapt.ai", }); expect(text).toContain( - "This computer is already connected to app.openadapt.ai. Allowing replaces that connection.", + "This computer is already connected to app.openadapt.ai. Your connection stays as it is unless you then choose Switch.", ); }); - it("warns about replacing even when the current host is unknown", () => { + it("says the computer is paired even when the current host is unknown", () => { const text = pairingQuestion({ ...prompt, already_paired: true }); - expect(text).toMatch(/already connected to OpenAdapt Cloud\. Allowing replaces/); + expect(text).toMatch(/already connected to OpenAdapt Cloud\. Your connection stays/); }); it("sends Allow with the request id it showed, and Not now without one", () => { @@ -56,3 +64,43 @@ describe("PairingConfirm", () => { expect(onAllow).toHaveBeenCalledWith("req-1"); }); }); + +const switchPrompt: PairingSwitchPrompt = { + status: "pending_switch", + request_id: "sw-1", + host: "https://app.openadapt.ai", + workspace: { id: "6f9d2c1e-0b7a-4c3e-9a51-2d8f4b6e7a10", name: "Northside Clinic" }, + account: { email: "pat@example.com" }, + same_workspace: false, + already_paired: true, + current_host: "https://app.openadapt.ai", + current_workspace: { id: "11111111-2222-4333-8444-555555555555", name: "Current Clinic" }, +}; + +describe("PairingSwitch", () => { + it("names the new and the current workspace and the account", () => { + const text = switchQuestion(switchPrompt); + expect(text).toContain("workspace Northside Clinic as pat@example.com on app.openadapt.ai"); + expect(text).toContain("connected to Current Clinic. Switching replaces that connection."); + }); + + it("labels the buttons Switch to and Keep ", () => { + const onSwitch = vi.fn(); + const onKeep = vi.fn(); + render(); + fireEvent.click(screen.getByRole("button", { name: "Keep Current Clinic" })); + expect(onKeep).toHaveBeenCalledTimes(1); + expect(onSwitch).not.toHaveBeenCalled(); + fireEvent.click(screen.getByRole("button", { name: "Switch to Northside Clinic" })); + expect(onSwitch).toHaveBeenCalledWith("sw-1"); + }); + + it("says when the current workspace wasn't recorded, and when nothing is paired", () => { + const unknown = { ...switchPrompt, current_workspace: null }; + expect(switchQuestion(unknown)).toMatch(/workspace OpenAdapt didn't record/); + expect(keepLabel(unknown)).toBe("Keep current connection"); + const fresh = { ...switchPrompt, already_paired: false, current_workspace: null }; + expect(keepLabel(fresh)).toBe("Don't connect"); + expect(switchQuestion(fresh)).not.toMatch(/replaces/); + }); +}); diff --git a/packages/desktop/src/ui/PairingConfirm.tsx b/packages/desktop/src/ui/PairingConfirm.tsx index 2add44bcb3..bb289a45f0 100644 --- a/packages/desktop/src/ui/PairingConfirm.tsx +++ b/packages/desktop/src/ui/PairingConfirm.tsx @@ -6,8 +6,11 @@ // clicks Allow here. Allow sends back the request id this dialog showed, so a // second link that arrives before the click can't be allowed by it. // -// Cloud can't look up a pairing code without redeeming it, so the workspace -// and account are named only when the engine reports them. +// Cloud can't look up a pairing code without redeeming it, so the first +// question names only the host. After Allow, the engine claims and checks the +// code without making it active, and the second question (PairingSwitch) +// names the workspace and account Cloud reported. Only Switch changes this +// computer's connection; Keep, a timeout or a restart discards the new one. export type PairingPrompt = { status: "pending_confirm"; @@ -36,11 +39,11 @@ export function pairingQuestion(prompt: PairingPrompt): string { ].filter(Boolean); const who = named.length ? ` (${named.join(", ")})` - : ". OpenAdapt can't show which workspace this link belongs to until you allow it"; + : ". OpenAdapt shows which workspace this link belongs to after you allow it"; const replaces = prompt.already_paired ? prompt.current_host - ? ` This computer is already connected to ${hostLabel(prompt.current_host)}. Allowing replaces that connection.` - : " This computer is already connected to OpenAdapt Cloud. Allowing replaces that connection." + ? ` This computer is already connected to ${hostLabel(prompt.current_host)}. Your connection stays as it is unless you then choose Switch.` + : " This computer is already connected to OpenAdapt Cloud. Your connection stays as it is unless you then choose Switch." : ""; return ( `Connect this computer to OpenAdapt Cloud at ${target}${who}.` + @@ -76,3 +79,66 @@ export function PairingConfirm({
); } + +export type Workspace = { id: string; name: string }; + +export type PairingSwitchPrompt = { + status: "pending_switch"; + request_id: string; + host: string; + workspace: Workspace; + account?: { email: string } | null; + same_workspace?: boolean; + already_paired?: boolean; + current_host?: string | null; + current_workspace?: Workspace | null; +}; + +export function switchQuestion(prompt: PairingSwitchPrompt): string { + const account = prompt.account?.email ? ` as ${prompt.account.email}` : ""; + const target = `This link connects this computer to the workspace ${prompt.workspace.name}${account} on ${hostLabel(prompt.host)}.`; + if (!prompt.already_paired) { + return `${target} Switch only if this is the workspace you meant.`; + } + const current = prompt.current_workspace + ? prompt.same_workspace + ? ` This computer already uses ${prompt.current_workspace.name}; switching replaces its connection.` + : ` This computer is connected to ${prompt.current_workspace.name}. Switching replaces that connection.` + : " This computer is already connected to a workspace OpenAdapt didn't record. Switching replaces that connection."; + return `${target}${current} Switch only if this is the workspace you meant.`; +} + +export function keepLabel(prompt: PairingSwitchPrompt): string { + if (!prompt.already_paired) return "Don't connect"; + return prompt.current_workspace + ? `Keep ${prompt.current_workspace.name}` + : "Keep current connection"; +} + +export function PairingSwitch({ + prompt, + onSwitch, + onKeep, +}: { + prompt: PairingSwitchPrompt; + onSwitch: (requestId: string) => void; + onKeep: () => void; +}) { + return ( +
+ {switchQuestion(prompt)} + + + + +
+ ); +} diff --git a/packages/desktop/tests/test_engine/test_auth_pairing.py b/packages/desktop/tests/test_engine/test_auth_pairing.py index b1e86b4c79..508ca77f42 100644 --- a/packages/desktop/tests/test_engine/test_auth_pairing.py +++ b/packages/desktop/tests/test_engine/test_auth_pairing.py @@ -547,3 +547,165 @@ def _post(url, **kwargs): pairing.claim_pairing(HOST, SECRET) assert endpoints == ["claim", "abort"] assert store.load_credential(HOST) is None + + +# ---------------------------------------------------------------- two-phase +WORKSPACE_ID = "6f9d2c1e-0b7a-4c3e-9a51-2d8f4b6e7a10" + + +class _FakeCloud: + """Claim, validate and abort endpoints, recording every call.""" + + def __init__(self, *, identity: dict | None = None, abort_ok: bool = True) -> None: + self.pairing_id = str(uuid4()) + self.identity = identity or {} + self.abort_ok = abort_ok + self.calls: list[str] = [] + self.claim_body: dict | None = None + + def post(self, url, *, json, headers=None, **kwargs): + if url.endswith("/claim"): + self.calls.append("claim") + self.claim_body = json + response = _claim_response(self.pairing_id) + response._body.update(self.identity) + return response + if url.endswith("/abort"): + self.calls.append("abort") + assert json == {"pairing_id": self.pairing_id} + assert headers == {"Authorization": f"Bearer {TOKEN}"} + return _Response(200 if self.abort_ok else 409, {"revoked": self.abort_ok}) + assert url.endswith("/confirm") + self.calls.append("confirm") + return _Response(200, {"connected": True}) + + def get(self, url, *, headers, **kwargs): + self.calls.append("validate") + assert headers == {"Authorization": f"Bearer {TOKEN}"} + return _validation_response() + + +def _install(monkeypatch, cloud: _FakeCloud) -> None: + monkeypatch.setattr(pairing, "secure_store_available", lambda: True) + monkeypatch.setattr(pairing, "_safe_device_name", lambda: "test-device") + monkeypatch.setattr(pairing.httpx, "post", cloud.post) + monkeypatch.setattr(pairing.httpx, "get", cloud.get) + + +def _identity() -> dict: + return { + "workspace": {"id": WORKSPACE_ID, "name": "Northside Clinic"}, + "account": {"email": "pat@example.com"}, + } + + +def test_review_claim_checks_the_code_and_writes_nothing(monkeypatch, fake_keyring) -> None: + store.store_credential(_credential(HOST, OLD_TOKEN)) + before = dict(fake_keyring._store) + cloud = _FakeCloud(identity=_identity()) + _install(monkeypatch, cloud) + + review = pairing.claim_for_review(HOST, SECRET, now=100.0) + + assert cloud.calls == ["claim", "validate"] + assert cloud.claim_body == { + "pairing_secret": SECRET, + "device_name": "test-device", + "include_identity": True, + } + assert review["workspace"] == {"id": WORKSPACE_ID, "name": "Northside Clinic"} + assert review["account"] == {"email": "pat@example.com"} + assert review["deadline"] == 100.0 + pairing.REVIEW_TTL_S + assert fake_keyring._store == before + assert store.load_pairing_stage() is None + assert store.load_credential(HOST)["token"] == OLD_TOKEN + + +def test_review_claim_without_identity_names_no_workspace(monkeypatch) -> None: + cloud = _FakeCloud() + _install(monkeypatch, cloud) + review = pairing.claim_for_review(HOST, SECRET, now=0.0) + assert review["workspace"] is None + assert review["account"] is None + + +def test_review_identity_needs_an_id_and_strips_control_characters() -> None: + workspace, account = pairing.claim_identity( + { + "workspace": {"id": WORKSPACE_ID, "name": "Acme‮\x00 Clinic\n"}, + "account": {"email": "no-at-sign"}, + } + ) + assert workspace == {"id": WORKSPACE_ID, "name": "Acme Clinic"} + assert account is None + assert pairing.claim_identity({"workspace": {"name": "Acme"}}) == (None, None) + assert pairing.claim_identity({"workspace": {"id": "x", "name": "Acme"}}) == (None, None) + + +def test_review_claim_refuses_extra_keys_beyond_identity(monkeypatch) -> None: + cloud = _FakeCloud(identity={"admin": True}) + _install(monkeypatch, cloud) + with pytest.raises(pairing.PairingError, match="credential contract"): + pairing.claim_for_review(HOST, SECRET, now=0.0) + assert cloud.calls == ["claim", "abort"] + + +def test_review_claim_never_runs_recovery_of_an_unfinished_stage(monkeypatch, fake_keyring) -> None: + store.store_credential(_credential(HOST, OLD_TOKEN)) + previous = store.snapshot_pairing_canonical(HOST) + assert store.stage_pairing_credential( + str(uuid4()), _credential(HOST, OTHER_TOKEN), previous, "test-device" + ) + before = dict(fake_keyring._store) + cloud = _FakeCloud(identity=_identity()) + _install(monkeypatch, cloud) + + with pytest.raises(pairing.PairingError, match="unfinished earlier connection"): + pairing.claim_for_review(HOST, SECRET, now=0.0) + + assert cloud.calls == [] + assert fake_keyring._store == before + + +def test_switch_makes_the_reviewed_claim_active(monkeypatch) -> None: + store.store_credential(_credential(HOST, OLD_TOKEN)) + cloud = _FakeCloud(identity=_identity()) + _install(monkeypatch, cloud) + review = pairing.claim_for_review(HOST, SECRET, now=0.0) + + result = pairing.switch_reviewed(review, now=1.0) + + assert result["authenticated"] is True + assert store.load_credential(HOST) == _credential(HOST, TOKEN, EXPIRES_TS) + assert store.load_pairing_stage() is None + assert cloud.calls == ["claim", "validate", "validate", "confirm"] + + +def test_switch_after_the_deadline_revokes_and_changes_nothing(monkeypatch, fake_keyring) -> None: + store.store_credential(_credential(HOST, OLD_TOKEN)) + cloud = _FakeCloud(identity=_identity()) + _install(monkeypatch, cloud) + review = pairing.claim_for_review(HOST, SECRET, now=0.0) + before = dict(fake_keyring._store) + + with pytest.raises(pairing.PairingError, match="waited too long"): + pairing.switch_reviewed(review, now=pairing.REVIEW_TTL_S) + + assert cloud.calls[-1] == "abort" + assert fake_keyring._store == before + assert store.load_pairing_stage() is None + + +def test_discard_revokes_the_reviewed_claim(monkeypatch, fake_keyring) -> None: + cloud = _FakeCloud(identity=_identity()) + _install(monkeypatch, cloud) + review = pairing.claim_for_review(HOST, SECRET, now=0.0) + before = dict(fake_keyring._store) + assert pairing.discard_reviewed(review) is True + assert cloud.calls[-1] == "abort" + assert fake_keyring._store == before + + +def test_review_deadline_is_well_inside_clouds_claim_grace() -> None: + # Cloud revokes a claim that isn't confirmed within two minutes. + assert pairing.REVIEW_TTL_S <= 90.0 diff --git a/packages/desktop/tests/test_engine/test_dispatch.py b/packages/desktop/tests/test_engine/test_dispatch.py index 3ee47ee7dc..1491bdb52f 100644 --- a/packages/desktop/tests/test_engine/test_dispatch.py +++ b/packages/desktop/tests/test_engine/test_dispatch.py @@ -20,6 +20,102 @@ _CONNECT_URI = ( "openadapt://connect?pairing=" + _PAIRING_SECRET + "&host=https%3A%2F%2Fapp.openadapt.ai" ) +_NEW_TOKEN = "oai_ingest_" + "N" * 43 +_CURRENT_TOKEN = "oai_ingest_" + "C" * 43 +_CURRENT_WORKSPACE_ID = "11111111-2222-4333-8444-555555555555" +_IDENTITY = { + "workspace": {"id": "6f9d2c1e-0b7a-4c3e-9a51-2d8f4b6e7a10", "name": "Northside Clinic"}, + "account": {"email": "pat@example.com"}, +} + + +def _credential_lifetime() -> dict: + return { + "expires_at": "2026-10-26T12:00:00+00:00", + "expires_in_days": 90, + "expiring_soon": False, + "legacy_non_expiring": False, + "warning_days": 14, + } + + +class _CloudResponse: + def __init__(self, status_code: int, body: dict, headers: dict | None = None) -> None: + self.status_code = status_code + self._body = body + self.headers = headers or {} + + def json(self) -> dict: + return self._body + + +class _FakeCloud: + """Cloud's claim, validate, abort and confirm routes for the real pairing code.""" + + def __init__(self, *, identity: dict | None = None) -> None: + import uuid + + self.pairing_id = str(uuid.uuid4()) + self.identity = identity or {} + self.calls: list[str] = [] + + def install(self, monkeypatch) -> None: + from openadapt_desktop.auth import pairing + + monkeypatch.setattr(pairing, "secure_store_available", lambda: True) + monkeypatch.setattr(pairing, "_safe_device_name", lambda: "test-device") + monkeypatch.setattr(pairing.httpx, "post", self.post) + monkeypatch.setattr(pairing.httpx, "get", self.get) + + def post(self, url, *, json, headers=None, **kwargs): + import uuid + + if url.endswith("/claim"): + self.calls.append("claim") + return _CloudResponse( + 201, + { + "paired": True, + "pairing_id": self.pairing_id, + "ingest_token_id": str(uuid.uuid4()), + "ingest_token": _NEW_TOKEN, + "credential": _credential_lifetime(), + **self.identity, + }, + {"cache-control": "no-store", "referrer-policy": "no-referrer"}, + ) + if url.endswith("/abort"): + self.calls.append("abort") + return _CloudResponse(200, {"revoked": True}) + self.calls.append("confirm") + return _CloudResponse(200, {"connected": True}) + + def get(self, url, *, headers, **kwargs): + self.calls.append("validate") + return _CloudResponse( + 200, + {"count": 0, "credential": _credential_lifetime()}, + { + "cache-control": "no-store", + "x-openadapt-credential-warning-days": "14", + "x-openadapt-credential-expires-in-days": "90", + }, + ) + + +def _store_current_credential() -> None: + from openadapt_desktop.auth.store import store_credential + + store_credential( + { + "kind": "ingest_token", + "token": _CURRENT_TOKEN, + "refresh_token": None, + "org_id": None, + "host": "https://app.openadapt.ai", + "expires_at": None, + } + ) def _precise_report( @@ -2483,13 +2579,8 @@ def test_connect_link_without_allow_redeems_nothing( def _no_network(*_args, **_kwargs): raise AssertionError("a connect link must not reach Cloud before Allow") - claims: list[tuple] = [] monkeypatch.setattr(httpx, "post", _no_network) monkeypatch.setattr(httpx, "get", _no_network) - monkeypatch.setattr( - "openadapt_desktop.auth.pairing.claim_pairing", - lambda *args, **kwargs: claims.append((args, kwargs)), - ) keychain_before = dict(fake_keyring._store) prompt = disp.dispatch("connect_uri", {"uri": _CONNECT_URI}) @@ -2497,7 +2588,6 @@ def _no_network(*_args, **_kwargs): assert prompt["status"] == "pending_confirm" assert prompt["host"] == "https://app.openadapt.ai" assert prompt["already_paired"] is False - assert claims == [] assert fake_keyring._store == keychain_before assert not toml_path.exists() assert disp.config.hosted_host == "https://app.openadapt.ai" @@ -2510,21 +2600,12 @@ def _no_network(*_args, **_kwargs): assert disp.dispatch("pairing_status", {}) == {"status": "idle"} with pytest.raises(RuntimeError, match="isn't waiting"): disp.dispatch("pairing_allow", {"request_id": prompt["request_id"]}) - assert claims == [] assert fake_keyring._store == keychain_before - def test_allow_redeems_exactly_the_request_the_window_showed( - self, deps, monkeypatch, tmp_path - ) -> None: - disp, _db, events = deps - monkeypatch.setenv("OPENADAPT_CONFIG_TOML", str(tmp_path / "config.toml")) - claims: list[tuple] = [] - - def _claim(host, secret, code_verifier=None, destination_kind=None): - claims.append((host, secret, destination_kind)) - return {"authenticated": True, "host": host, "paired": True} - - monkeypatch.setattr("openadapt_desktop.auth.pairing.claim_pairing", _claim) + def test_allow_needs_the_request_the_window_showed(self, deps, monkeypatch) -> None: + disp, _db, _events = deps + cloud = _FakeCloud(identity=_IDENTITY) + cloud.install(monkeypatch) prompt = disp.dispatch("connect_uri", {"uri": _CONNECT_URI}) assert disp.dispatch("pairing_status", {}) == prompt @@ -2532,21 +2613,167 @@ def _claim(host, secret, code_verifier=None, destination_kind=None): disp.dispatch("pairing_allow", {"request_id": "not-the-shown-one"}) with pytest.raises(RuntimeError, match="different connect link"): disp.dispatch("pairing_allow", {}) - assert claims == [] + assert cloud.calls == [] + + disp.dispatch("pairing_allow", {"request_id": prompt["request_id"]}) + assert cloud.calls == ["claim", "validate"] + # One use: a second Allow can't spend the code again. + with pytest.raises(RuntimeError, match="isn't waiting"): + disp.dispatch("pairing_allow", {"request_id": prompt["request_id"]}) + assert cloud.calls.count("claim") == 1 + + def test_already_paired_desktop_keeps_its_credential_until_switch( + self, deps, fake_keyring, monkeypatch, tmp_path + ) -> None: + from openadapt_desktop.auth.store import load_credential, load_pairing_stage + + disp, _db, events = deps + monkeypatch.setenv("OPENADAPT_CONFIG_TOML", str(tmp_path / "config.toml")) + _store_current_credential() + disp.config.paired_workspace_id = _CURRENT_WORKSPACE_ID + disp.config.paired_workspace_name = "Current Clinic" + cloud = _FakeCloud(identity=_IDENTITY) + cloud.install(monkeypatch) + prompt = disp.dispatch("connect_uri", {"uri": _CONNECT_URI}) + keychain_before = dict(fake_keyring._store) - result = disp.dispatch("pairing_allow", {"request_id": prompt["request_id"]}) + question = disp.dispatch("pairing_allow", {"request_id": prompt["request_id"]}) + + assert question["status"] == "pending_switch" + assert question["workspace"] == _IDENTITY["workspace"] + assert question["account"] == _IDENTITY["account"] + assert question["already_paired"] is True + assert question["current_workspace"] == { + "id": _CURRENT_WORKSPACE_ID, + "name": "Current Clinic", + } + assert question["same_workspace"] is False + assert _NEW_TOKEN not in json.dumps(question) + assert all(_NEW_TOKEN not in json.dumps(data) for _e, data in events) + # Claimed and checked, but nothing on this computer changed. + assert fake_keyring._store == keychain_before + assert load_credential("https://app.openadapt.ai")["token"] == _CURRENT_TOKEN + assert load_pairing_stage() is None + assert disp.dispatch("pairing_status", {}) == question + + with pytest.raises(RuntimeError, match="Review the connection"): + disp.dispatch("pairing_switch", {"request_id": "other"}) + assert load_credential("https://app.openadapt.ai")["token"] == _CURRENT_TOKEN + + result = disp.dispatch("pairing_switch", {"request_id": question["request_id"]}) assert result["paired"] is True - assert claims == [("https://app.openadapt.ai", _PAIRING_SECRET, None)] - assert disp.config.hosted_host == "https://app.openadapt.ai" - assert ( - "pairing_state", - {"status": "connected", "host": "https://app.openadapt.ai"}, - ) in events - # One use: a second Allow can't spend the code again. + assert load_credential("https://app.openadapt.ai")["token"] == _NEW_TOKEN + assert disp.config.paired_workspace_id == _IDENTITY["workspace"]["id"] + assert disp.config.paired_workspace_name == "Northside Clinic" + assert cloud.calls == ["claim", "validate", "validate", "confirm"] + assert events[-2][1]["status"] == "connected" + + def test_keep_discards_the_new_credential(self, deps, fake_keyring, monkeypatch) -> None: + from openadapt_desktop.auth.store import load_credential, load_pairing_stage + + disp, _db, _events = deps + _store_current_credential() + cloud = _FakeCloud(identity=_IDENTITY) + cloud.install(monkeypatch) + prompt = disp.dispatch("connect_uri", {"uri": _CONNECT_URI}) + question = disp.dispatch("pairing_allow", {"request_id": prompt["request_id"]}) + keychain_before = dict(fake_keyring._store) + + assert disp.dispatch("pairing_keep", {}) == {"status": "kept", "revoked": True} + + assert cloud.calls[-1] == "abort" + assert fake_keyring._store == keychain_before + assert load_credential("https://app.openadapt.ai")["token"] == _CURRENT_TOKEN + assert load_pairing_stage() is None + assert disp.dispatch("pairing_status", {}) == {"status": "idle"} with pytest.raises(RuntimeError, match="isn't waiting"): + disp.dispatch("pairing_switch", {"request_id": question["request_id"]}) + + def test_a_claim_that_names_no_workspace_does_not_switch( + self, deps, fake_keyring, monkeypatch + ) -> None: + from openadapt_desktop.auth.store import load_credential, load_pairing_stage + + disp, _db, events = deps + _store_current_credential() + cloud = _FakeCloud() # today's Cloud: no workspace or account + cloud.install(monkeypatch) + prompt = disp.dispatch("connect_uri", {"uri": _CONNECT_URI}) + keychain_before = dict(fake_keyring._store) + + with pytest.raises(RuntimeError, match="didn't say which workspace"): disp.dispatch("pairing_allow", {"request_id": prompt["request_id"]}) - assert len(claims) == 1 + + assert cloud.calls == ["claim", "validate", "abort"] + assert fake_keyring._store == keychain_before + assert load_credential("https://app.openadapt.ai")["token"] == _CURRENT_TOKEN + assert load_pairing_stage() is None + assert events[-1][1]["status"] == "error" + assert disp.dispatch("pairing_status", {}) == {"status": "idle"} + + def test_a_restart_during_review_leaves_the_current_connection( + self, deps, fake_keyring, monkeypatch + ) -> None: + from openadapt_desktop.auth.store import load_pairing_stage + + disp, _db, _events = deps + _store_current_credential() + cloud = _FakeCloud(identity=_IDENTITY) + cloud.install(monkeypatch) + prompt = disp.dispatch("connect_uri", {"uri": _CONNECT_URI}) + disp.dispatch("pairing_allow", {"request_id": prompt["request_id"]}) + keychain_before = dict(fake_keyring._store) + + restarted = EngineDispatcher(disp.config, services=disp.services, emit=lambda e, d: None) + + assert restarted.dispatch("pairing_status", {}) == {"status": "idle"} + assert fake_keyring._store == keychain_before + assert load_pairing_stage() is None + + def test_switch_after_the_review_deadline_keeps_the_current_connection( + self, deps, fake_keyring, monkeypatch + ) -> None: + import openadapt_desktop.dispatch as dispatch_module + from openadapt_desktop.auth.pairing import REVIEW_TTL_S + + disp, _db, _events = deps + _store_current_credential() + cloud = _FakeCloud(identity=_IDENTITY) + cloud.install(monkeypatch) + prompt = disp.dispatch("connect_uri", {"uri": _CONNECT_URI}) + question = disp.dispatch("pairing_allow", {"request_id": prompt["request_id"]}) + keychain_before = dict(fake_keyring._store) + now = dispatch_module.time.monotonic() + monkeypatch.setattr(dispatch_module.time, "monotonic", lambda: now + REVIEW_TTL_S + 1) + + with pytest.raises(RuntimeError, match="isn't waiting"): + disp.dispatch("pairing_switch", {"request_id": question["request_id"]}) + + assert cloud.calls[-1] == "abort" + assert fake_keyring._store == keychain_before + + def test_a_new_link_during_review_revokes_the_reviewed_claim(self, deps, monkeypatch) -> None: + disp, _db, _events = deps + cloud = _FakeCloud(identity=_IDENTITY) + cloud.install(monkeypatch) + prompt = disp.dispatch("connect_uri", {"uri": _CONNECT_URI}) + disp.dispatch("pairing_allow", {"request_id": prompt["request_id"]}) + + other = _CONNECT_URI.replace(_PAIRING_SECRET, "oap_" + "B" * 43) + assert disp.dispatch("connect_uri", {"uri": other})["status"] == "pending_confirm" + assert cloud.calls[-1] == "abort" + + def test_same_workspace_is_matched_by_id_not_name(self, deps, monkeypatch) -> None: + disp, _db, _events = deps + _store_current_credential() + disp.config.paired_workspace_id = _CURRENT_WORKSPACE_ID + disp.config.paired_workspace_name = "Northside Clinic" # same name as the link's + cloud = _FakeCloud(identity=_IDENTITY) + cloud.install(monkeypatch) + prompt = disp.dispatch("connect_uri", {"uri": _CONNECT_URI}) + question = disp.dispatch("pairing_allow", {"request_id": prompt["request_id"]}) + assert question["same_workspace"] is False def test_a_repeat_delivery_keeps_the_shown_request_and_a_new_link_replaces_it( self, deps @@ -2603,7 +2830,7 @@ def test_expired_request_cannot_be_allowed(self, deps, monkeypatch) -> None: disp, _db, _events = deps claims: list[tuple] = [] monkeypatch.setattr( - "openadapt_desktop.auth.pairing.claim_pairing", + "openadapt_desktop.auth.pairing.claim_for_review", lambda *args, **kwargs: claims.append(args), ) prompt = disp.dispatch("connect_uri", {"uri": _CONNECT_URI}) @@ -2659,7 +2886,14 @@ def test_pairing_allow_is_served_on_the_window_wire_only(self) -> None: # outside _SOCKET_COMMANDS, so only the window can say Allow. from openadapt_desktop import socket_server - for name in ("pairing_allow", "pairing_deny", "pairing_status", "connect_uri"): + for name in ( + "pairing_allow", + "pairing_switch", + "pairing_keep", + "pairing_deny", + "pairing_status", + "connect_uri", + ): assert name not in socket_server._SOCKET_COMMANDS def test_the_local_pairing_setting_cannot_be_set_from_the_window(self, deps) -> None: diff --git a/packages/desktop/tests/test_pairing_protocol_boundary.py b/packages/desktop/tests/test_pairing_protocol_boundary.py index ff66cd958b..e1b0d5b5ff 100644 --- a/packages/desktop/tests/test_pairing_protocol_boundary.py +++ b/packages/desktop/tests/test_pairing_protocol_boundary.py @@ -77,8 +77,24 @@ def test_a_connect_link_only_stages_and_allow_is_not_reachable_from_a_link() -> pairing = (ROOT / "src-tauri/src/pairing.rs").read_text() dispatch = (ROOT / "openadapt_desktop/dispatch.py").read_text() # The deep link reaches only the staging verb; Allow comes from the window. - assert '"pairing_allow"' not in pairing.split("#[cfg(test)]", 1)[0] - assert '"pairing_allow": self.pairing_allow' in dispatch + shell = pairing.split("#[cfg(test)]", 1)[0] + for verb in ("pairing_allow", "pairing_switch", "pairing_keep"): + assert f'"{verb}"' not in shell + assert f'"{verb}": self.{verb}' in dispatch + # A link's claim is reviewed before it can become the connection: the + # review phase never stages, commits or recovers a keychain credential. + python_pairing = (ROOT / "openadapt_desktop/auth/pairing.py").read_text() + review = python_pairing.split("def claim_for_review(", 1)[1].split("\ndef ", 1)[0] + for write in ( + "stage_pairing_credential(", + "commit_pairing_stage(", + "recover_pending_pairing(", + "_finish_staged_pairing(", + ): + assert write not in review + allow = dispatch.split(" def pairing_allow(", 1)[1].split("\n def ", 1)[0] + for write in ("claim_pairing(", "switch_reviewed(", "_persist_config_key", "hosted_host ="): + assert write not in allow stage = dispatch.split(" def connect_uri(", 1)[1].split("\n def ", 1)[0] assert "import connect_uri" not in stage for redeem in ("claim_pairing", "httpx", "_persist_config_key"): From bf7950577b43def130730b7feb5c24927b279ce8 Mon Sep 17 00:00:00 2001 From: abrichr Date: Sun, 29 Nov 2026 21:50:56 -0500 Subject: [PATCH 5/9] docs(desktop): list the workspace switch in the 0.35.1 changelog --- packages/desktop/CHANGELOG.md | 1 + 1 file changed, 1 insertion(+) diff --git a/packages/desktop/CHANGELOG.md b/packages/desktop/CHANGELOG.md index 31ad0ae68a..3264b1e2b1 100644 --- a/packages/desktop/CHANGELOG.md +++ b/packages/desktop/CHANGELOG.md @@ -10,6 +10,7 @@ ### Bug Fixes - **desktop**: ask before a connect link pairs this computer +- **desktop**: show the workspace and switch only on the person's say-so From ef43ba4d1815abca558131467959ba68db6ade82 Mon Sep 17 00:00:00 2001 From: abrichr Date: Sun, 29 Nov 2026 21:54:36 -0500 Subject: [PATCH 6/9] refactor(desktop): move connect-link confirmation out of dispatch.py The Allow and Switch/Keep steps for openadapt:// connect links now live in openadapt_desktop/pairing_confirm.py, one class that holds the staged link and the reviewed claim. dispatch.py registers its handlers in one line, as it does for Chrome profiles, and drops to 6502 lines; its size budget drops to match. --- .../desktop/openadapt_desktop/dispatch.py | 294 +-------------- .../openadapt_desktop/pairing_confirm.py | 349 ++++++++++++++++++ .../tests/test_engine/test_dispatch.py | 4 +- .../tests/test_pairing_protocol_boundary.py | 20 +- packages/flow/docs/design/DECOMPOSITION.md | 2 +- 5 files changed, 365 insertions(+), 304 deletions(-) create mode 100644 packages/desktop/openadapt_desktop/pairing_confirm.py diff --git a/packages/desktop/openadapt_desktop/dispatch.py b/packages/desktop/openadapt_desktop/dispatch.py index 1cd66e7adf..8d3e8c2260 100644 --- a/packages/desktop/openadapt_desktop/dispatch.py +++ b/packages/desktop/openadapt_desktop/dispatch.py @@ -47,6 +47,7 @@ from openadapt_desktop.chrome_profile import dispatch_handlers as chrome_profile_handlers from openadapt_desktop.config import EngineConfig from openadapt_desktop.macos_permissions import control_permission_guidance +from openadapt_desktop.pairing_confirm import dispatch_handlers as pairing_confirm_handlers from openadapt_desktop.private_fs import ensure_private_dir EmitFn = Callable[[str, dict], None] @@ -92,11 +93,6 @@ def _noop_emit(event: str, data: dict) -> None: """Default event sink -- drops events when no emitter is wired.""" -#: How long a staged ``openadapt://connect`` request waits for Allow. Cloud's -#: pairing codes last five minutes. -PAIRING_CONFIRM_TTL_S = 300.0 - - def _canonical_hosted_origin(value: Any) -> str: """Return a safe hosted origin or raise before any credential is sent.""" @@ -281,13 +277,6 @@ def __init__( self._shadow: Any = None self._shadow_resumed = False self.services.live_tap_provider = self._shadow_live_tap - # The one ``openadapt://connect`` request waiting for Allow. Memory - # only: the one-use pairing code never reaches disk, the window or a - # log, and a restart drops it. - self._pending_connect: dict[str, Any] | None = None - # A claimed link waiting for Switch or Keep: the new bearer, in memory - # only. Keep, a timeout or a restart discards it. - self._pending_switch: dict[str, Any] | None = None self._handlers: dict[str, Callable[..., dict | None]] = {} self._register() from openadapt_desktop.coach import empty_coach @@ -387,14 +376,7 @@ def _register(self) -> None: # auth (both providers live in engine.auth -- spec 3a) "login_browser": self.login_browser, "login_paste": self.login_paste, - "connect_uri": self.connect_uri, - # A connect link only stages a request; nothing is redeemed until - # the person clicks Allow in the window (window wire only). - "pairing_status": self.pairing_status, - "pairing_allow": self.pairing_allow, - "pairing_switch": self.pairing_switch, - "pairing_keep": self.pairing_keep, - "pairing_deny": self.pairing_deny, + **pairing_confirm_handlers(self), # connect links; Allow is window wire only "claim_runner_uri": self.claim_runner_uri, "authoring_allow": self.authoring_allow, "authoring_deny": self.authoring_deny, @@ -5959,278 +5941,6 @@ def login_paste(self, **params: Any) -> dict: self._emit_sync(self._sync_state_now()) return self._auth_status(cred) - def connect_uri(self, **params: Any) -> dict: - """Stage a validated ``openadapt://connect`` link for an in-app Allow. - - Nothing is redeemed here: no request goes to Cloud, the keychain and - ``hosted_host`` are untouched. Anyone can make a pairing code and put - it in a link, so the person must see the target and click Allow - (:meth:`pairing_allow`) before the code is spent. This mirrors the - Allow that runner links already require. - """ - from openadapt_desktop.auth.pairing import PairingError, parse_connect_uri - - uri = params.get("uri") - if not isinstance(uri, str): - raise ValueError("uri is required") - try: - request = parse_connect_uri(uri) - host = _canonical_hosted_origin(request["host"]) - if not self._pairing_host_allowed(host): - raise PairingError( - "This connect link names a Cloud server on this computer. " - "Desktop only accepts links for app.openadapt.ai unless the " - "developer setting allow_local_pairing is on. Nothing changed." - ) - except (PairingError, ValueError) as exc: - self.emit("pairing_state", {"status": "error", "error": str(exc)}) - raise - pending = self._pending_connect - if ( - pending is not None - and not self._pending_connect_expired(pending) - and pending["pairing"] == request["pairing"] - and pending["host"] == host - ): - # The same link delivered twice (launch and single-instance can - # both deliver it): keep the request the window is showing. - prompt = self._pairing_prompt(pending) - else: - # A new link replaces any connection still waiting for Switch. - self._discard_pending_switch() - self._pending_connect = { - "request_id": uuid.uuid4().hex, - "pairing": request["pairing"], - "host": host, - "destination_kind": request.get("destination_kind"), - "expires_at": time.monotonic() + PAIRING_CONFIRM_TTL_S, - } - prompt = self._pairing_prompt(self._pending_connect) - self.emit("pairing_state", prompt) - return prompt - - def _pairing_host_allowed(self, host: str) -> bool: - """Production Cloud always; this computer only with the developer setting.""" - from openadapt_desktop.auth.store import DEFAULT_HOST, canonical_host_origin - - if host == canonical_host_origin(DEFAULT_HOST): - return True - hostname = urlsplit(host).hostname - return hostname in {"localhost", "127.0.0.1", "::1"} and ( - self.config.allow_local_pairing is True - ) - - @staticmethod - def _pending_connect_expired(pending: dict[str, Any]) -> bool: - return time.monotonic() >= float(pending["expires_at"]) - - def _pairing_prompt(self, pending: dict[str, Any]) -> dict[str, Any]: - """The Allow question. Never carries the pairing code.""" - return { - "status": "pending_confirm", - "request_id": pending["request_id"], - "host": pending["host"], - # Cloud names the workspace only once the code is claimed, which - # needs Allow. The Switch question after it shows the name. - "workspace": None, - "account": None, - **self._current_pairing(), - } - - def pairing_status(self, **params: Any) -> dict: - """Return the connect question waiting in the window, or ``idle``.""" - switch = self._pending_switch - if switch is not None: - if time.monotonic() < float(switch["review"]["deadline"]): - return self._switch_prompt(switch) - self._discard_pending_switch() - pending = self._pending_connect - if pending is None: - return {"status": "idle"} - if self._pending_connect_expired(pending): - self._pending_connect = None - return {"status": "idle"} - return self._pairing_prompt(pending) - - def pairing_allow(self, **params: Any) -> dict: - """Claim the connect request the person allowed, for review only. - - ``request_id`` must name the request the window showed, so a second - link that arrives before the click can't be allowed by it. The claim - is checked but not made active: the window then shows the workspace - Cloud named, and only :meth:`pairing_switch` changes the connection. - """ - from openadapt_desktop.auth.pairing import ( - PairingError, - claim_for_review, - discard_reviewed, - ) - - pending = self._pending_connect - if pending is None or self._pending_connect_expired(pending): - self._pending_connect = None - message = ( - "That connect request isn't waiting any more. Nothing changed. " - "Create a new connection from Cloud settings." - ) - self.emit("pairing_state", {"status": "error", "error": message}) - raise PairingError(message) - if params.get("request_id") != pending["request_id"]: - message = ( - "A different connect link arrived. Review it before you allow it. Nothing changed." - ) - self.emit("pairing_state", self._pairing_prompt(pending)) - raise PairingError(message) - # One use: the code is spent or refused below, never offered again. - self._pending_connect = None - self._discard_pending_switch() - self.emit("pairing_state", {"status": "connecting", "host": pending["host"]}) - try: - review = claim_for_review( - pending["host"], - pending["pairing"], - destination_kind=pending.get("destination_kind"), - now=time.monotonic(), - ) - except PairingError as exc: - self.emit("pairing_state", {"status": "error", "error": str(exc)}) - raise - except Exception: - self.emit( - "pairing_state", - {"status": "error", "error": "The secure connection could not be completed."}, - ) - raise - if review["workspace"] is None: - # Without a workspace Cloud vouches for, Switch would be a guess. - discard_reviewed(review) - message = ( - "OpenAdapt Cloud didn't say which workspace this link belongs to, " - "so Desktop cancelled it and kept its current connection. " - "Nothing changed." - ) - self.emit("pairing_state", {"status": "error", "error": message}) - raise PairingError(message) - self._pending_switch = {"request_id": uuid.uuid4().hex, "review": review} - prompt = self._switch_prompt(self._pending_switch) - self.emit("pairing_state", prompt) - return prompt - - def _current_pairing(self) -> dict[str, Any]: - """What this computer is connected to now, as far as Desktop knows.""" - from openadapt_desktop.auth.store import active_credential, canonical_host_origin - - try: - current = active_credential() - host = canonical_host_origin(str(current.get("host") or "")) if current else None - paired = current is not None - except Exception: # noqa: BLE001 - an unreadable keychain must not hide the warning - host, paired = None, True - workspace = None - if paired and self.config.paired_workspace_id and self.config.paired_workspace_name: - workspace = { - "id": self.config.paired_workspace_id, - "name": self.config.paired_workspace_name, - } - return { - "already_paired": paired, - "current_host": host or None, - "current_workspace": workspace, - } - - def _switch_prompt(self, pending: dict[str, Any]) -> dict[str, Any]: - """The Switch or Keep question. Never carries the bearer.""" - review = pending["review"] - current = self._current_pairing() - same = ( - current["current_workspace"] is not None - and current["current_workspace"]["id"] == review["workspace"]["id"] - ) - return { - "status": "pending_switch", - "request_id": pending["request_id"], - "host": review["host"], - "workspace": review["workspace"], - "account": review["account"], - "same_workspace": same, - **current, - } - - def _discard_pending_switch(self) -> bool | None: - """Revoke a reviewed claim nobody switched to. None if there was none.""" - from openadapt_desktop.auth.pairing import discard_reviewed - - pending = self._pending_switch - self._pending_switch = None - if pending is None: - return None - try: - return discard_reviewed(pending["review"]) - except Exception: # noqa: BLE001 - Cloud also revokes an unconfirmed claim - return False - - def pairing_switch(self, **params: Any) -> dict: - """Make the reviewed claim the window showed this computer's connection.""" - from openadapt_desktop.auth.pairing import PairingError, switch_reviewed - - pending = self._pending_switch - if pending is None or time.monotonic() >= float(pending["review"]["deadline"]): - self._discard_pending_switch() - message = ( - "That connection isn't waiting any more, so Desktop kept its current " - "connection. Nothing changed." - ) - self.emit("pairing_state", {"status": "error", "error": message}) - raise PairingError(message) - if params.get("request_id") != pending["request_id"]: - self.emit("pairing_state", self._switch_prompt(pending)) - raise PairingError( - "Review the connection on screen before you switch. Nothing changed." - ) - self._pending_switch = None - review = pending["review"] - self.emit("pairing_state", {"status": "connecting", "host": review["host"]}) - try: - result = switch_reviewed(review, now=time.monotonic()) - except PairingError as exc: - self.emit("pairing_state", {"status": "error", "error": str(exc)}) - raise - except Exception: - self.emit( - "pairing_state", - {"status": "error", "error": "The secure connection could not be completed."}, - ) - raise - host = _canonical_hosted_origin(result["host"]) - workspace = review["workspace"] - result = {**result, "host": host, "workspace": workspace} - self.config.hosted_host = host - self.config.paired_workspace_id = workspace["id"] - self.config.paired_workspace_name = workspace["name"] - self._persist_config_key("hosted_host", host) - self._persist_config_key("paired_workspace_id", workspace["id"]) - self._persist_config_key("paired_workspace_name", workspace["name"]) - self.emit( - "pairing_state", - {"status": "connected", "host": host, "workspace": workspace}, - ) - self._emit_sync(self._sync_state_now()) - return result - - def pairing_keep(self, **params: Any) -> dict: - """Keep the current connection and revoke the reviewed claim.""" - revoked = self._discard_pending_switch() - state = {"status": "kept", "revoked": revoked is True} - self.emit("pairing_state", state) - return state - - def pairing_deny(self, **params: Any) -> dict: - """Drop the staged connect request. Nothing was redeemed.""" - self._pending_connect = None - state = {"status": "declined"} - self.emit("pairing_state", state) - return state - def _authoring_service(self) -> Any: if self.services.authoring is None: from openadapt_desktop.authoring_runner import AuthoringRunner diff --git a/packages/desktop/openadapt_desktop/pairing_confirm.py b/packages/desktop/openadapt_desktop/pairing_confirm.py new file mode 100644 index 0000000000..3ea01bdb67 --- /dev/null +++ b/packages/desktop/openadapt_desktop/pairing_confirm.py @@ -0,0 +1,349 @@ +"""Ask before an ``openadapt://connect`` link pairs this computer. + +Anyone can create a pairing code in their own Cloud workspace and put it in a +link, and the host is app.openadapt.ai either way. So a link changes nothing +on its own: + +1. :meth:`PairingConfirmation.connect_uri` stages the link in memory and the + window asks Allow or Not now. Nothing reaches Cloud. +2. :meth:`PairingConfirmation.allow` claims the code and checks the new + credential without making it active, then the window names the workspace + and account Cloud reported: Switch or Keep. +3. Only :meth:`PairingConfirmation.switch` makes it this computer's + connection. Keep, a timeout, a new link or a restart discards it. + +Every answer carries the request id the window showed. These commands are +served on the window wire only: the loopback socket refuses them. +""" + +from __future__ import annotations + +import time +import uuid +from typing import Any, Callable +from urllib.parse import urlsplit + +from openadapt_desktop.config import EngineConfig + +#: How long a staged ``openadapt://connect`` request waits for Allow. Cloud's +#: pairing codes last five minutes. +PAIRING_CONFIRM_TTL_S = 300.0 + + +def _canonical_hosted_origin(value: Any) -> str: + from openadapt_desktop.dispatch import _canonical_hosted_origin as canonical + + return canonical(value) + + +class PairingConfirmation: + """The one link waiting for Allow and the one claim waiting for Switch. + + Both live in memory only: the pairing code and the new bearer never reach + disk, the window or a log, and a restart drops them. + """ + + def __init__( + self, + config: EngineConfig, + *, + emit: Callable[[str, dict], None], + persist: Callable[[str, Any], None], + after_connect: Callable[[], None], + ) -> None: + self.config = config + self._emit = emit + self._persist = persist + self._after_connect = after_connect + self._pending_connect: dict[str, Any] | None = None + self._pending_switch: dict[str, Any] | None = None + + def connect_uri(self, **params: Any) -> dict: + """Stage a validated ``openadapt://connect`` link for an in-app Allow. + + Nothing is redeemed here: no request goes to Cloud, the keychain and + ``hosted_host`` are untouched. Anyone can make a pairing code and put + it in a link, so the person must see the target and click Allow + (:meth:`allow`) before the code is spent. This mirrors the + Allow that runner links already require. + """ + from openadapt_desktop.auth.pairing import PairingError, parse_connect_uri + + uri = params.get("uri") + if not isinstance(uri, str): + raise ValueError("uri is required") + try: + request = parse_connect_uri(uri) + host = _canonical_hosted_origin(request["host"]) + if not self._pairing_host_allowed(host): + raise PairingError( + "This connect link names a Cloud server on this computer. " + "Desktop only accepts links for app.openadapt.ai unless the " + "developer setting allow_local_pairing is on. Nothing changed." + ) + except (PairingError, ValueError) as exc: + self._emit("pairing_state", {"status": "error", "error": str(exc)}) + raise + pending = self._pending_connect + if ( + pending is not None + and not self._pending_connect_expired(pending) + and pending["pairing"] == request["pairing"] + and pending["host"] == host + ): + # The same link delivered twice (launch and single-instance can + # both deliver it): keep the request the window is showing. + prompt = self._pairing_prompt(pending) + else: + # A new link replaces any connection still waiting for Switch. + self._discard_pending_switch() + self._pending_connect = { + "request_id": uuid.uuid4().hex, + "pairing": request["pairing"], + "host": host, + "destination_kind": request.get("destination_kind"), + "expires_at": time.monotonic() + PAIRING_CONFIRM_TTL_S, + } + prompt = self._pairing_prompt(self._pending_connect) + self._emit("pairing_state", prompt) + return prompt + + def _pairing_host_allowed(self, host: str) -> bool: + """Production Cloud always; this computer only with the developer setting.""" + from openadapt_desktop.auth.store import DEFAULT_HOST, canonical_host_origin + + if host == canonical_host_origin(DEFAULT_HOST): + return True + hostname = urlsplit(host).hostname + return hostname in {"localhost", "127.0.0.1", "::1"} and ( + self.config.allow_local_pairing is True + ) + + @staticmethod + def _pending_connect_expired(pending: dict[str, Any]) -> bool: + return time.monotonic() >= float(pending["expires_at"]) + + def _pairing_prompt(self, pending: dict[str, Any]) -> dict[str, Any]: + """The Allow question. Never carries the pairing code.""" + return { + "status": "pending_confirm", + "request_id": pending["request_id"], + "host": pending["host"], + # Cloud names the workspace only once the code is claimed, which + # needs Allow. The Switch question after it shows the name. + "workspace": None, + "account": None, + **self._current_pairing(), + } + + def status(self, **params: Any) -> dict: + """Return the connect question waiting in the window, or ``idle``.""" + switch = self._pending_switch + if switch is not None: + if time.monotonic() < float(switch["review"]["deadline"]): + return self._switch_prompt(switch) + self._discard_pending_switch() + pending = self._pending_connect + if pending is None: + return {"status": "idle"} + if self._pending_connect_expired(pending): + self._pending_connect = None + return {"status": "idle"} + return self._pairing_prompt(pending) + + def allow(self, **params: Any) -> dict: + """Claim the connect request the person allowed, for review only. + + ``request_id`` must name the request the window showed, so a second + link that arrives before the click can't be allowed by it. The claim + is checked but not made active: the window then shows the workspace + Cloud named, and only :meth:`switch` changes the connection. + """ + from openadapt_desktop.auth.pairing import ( + PairingError, + claim_for_review, + discard_reviewed, + ) + + pending = self._pending_connect + if pending is None or self._pending_connect_expired(pending): + self._pending_connect = None + message = ( + "That connect request isn't waiting any more. Nothing changed. " + "Create a new connection from Cloud settings." + ) + self._emit("pairing_state", {"status": "error", "error": message}) + raise PairingError(message) + if params.get("request_id") != pending["request_id"]: + message = ( + "A different connect link arrived. Review it before you allow it. Nothing changed." + ) + self._emit("pairing_state", self._pairing_prompt(pending)) + raise PairingError(message) + # One use: the code is spent or refused below, never offered again. + self._pending_connect = None + self._discard_pending_switch() + self._emit("pairing_state", {"status": "connecting", "host": pending["host"]}) + try: + review = claim_for_review( + pending["host"], + pending["pairing"], + destination_kind=pending.get("destination_kind"), + now=time.monotonic(), + ) + except PairingError as exc: + self._emit("pairing_state", {"status": "error", "error": str(exc)}) + raise + except Exception: + self._emit( + "pairing_state", + {"status": "error", "error": "The secure connection could not be completed."}, + ) + raise + if review["workspace"] is None: + # Without a workspace Cloud vouches for, Switch would be a guess. + discard_reviewed(review) + message = ( + "OpenAdapt Cloud didn't say which workspace this link belongs to, " + "so Desktop cancelled it and kept its current connection. " + "Nothing changed." + ) + self._emit("pairing_state", {"status": "error", "error": message}) + raise PairingError(message) + self._pending_switch = {"request_id": uuid.uuid4().hex, "review": review} + prompt = self._switch_prompt(self._pending_switch) + self._emit("pairing_state", prompt) + return prompt + + def _current_pairing(self) -> dict[str, Any]: + """What this computer is connected to now, as far as Desktop knows.""" + from openadapt_desktop.auth.store import active_credential, canonical_host_origin + + try: + current = active_credential() + host = canonical_host_origin(str(current.get("host") or "")) if current else None + paired = current is not None + except Exception: # noqa: BLE001 - an unreadable keychain must not hide the warning + host, paired = None, True + workspace = None + if paired and self.config.paired_workspace_id and self.config.paired_workspace_name: + workspace = { + "id": self.config.paired_workspace_id, + "name": self.config.paired_workspace_name, + } + return { + "already_paired": paired, + "current_host": host or None, + "current_workspace": workspace, + } + + def _switch_prompt(self, pending: dict[str, Any]) -> dict[str, Any]: + """The Switch or Keep question. Never carries the bearer.""" + review = pending["review"] + current = self._current_pairing() + same = ( + current["current_workspace"] is not None + and current["current_workspace"]["id"] == review["workspace"]["id"] + ) + return { + "status": "pending_switch", + "request_id": pending["request_id"], + "host": review["host"], + "workspace": review["workspace"], + "account": review["account"], + "same_workspace": same, + **current, + } + + def _discard_pending_switch(self) -> bool | None: + """Revoke a reviewed claim nobody switched to. None if there was none.""" + from openadapt_desktop.auth.pairing import discard_reviewed + + pending = self._pending_switch + self._pending_switch = None + if pending is None: + return None + try: + return discard_reviewed(pending["review"]) + except Exception: # noqa: BLE001 - Cloud also revokes an unconfirmed claim + return False + + def switch(self, **params: Any) -> dict: + """Make the reviewed claim the window showed this computer's connection.""" + from openadapt_desktop.auth.pairing import PairingError, switch_reviewed + + pending = self._pending_switch + if pending is None or time.monotonic() >= float(pending["review"]["deadline"]): + self._discard_pending_switch() + message = ( + "That connection isn't waiting any more, so Desktop kept its current " + "connection. Nothing changed." + ) + self._emit("pairing_state", {"status": "error", "error": message}) + raise PairingError(message) + if params.get("request_id") != pending["request_id"]: + self._emit("pairing_state", self._switch_prompt(pending)) + raise PairingError( + "Review the connection on screen before you switch. Nothing changed." + ) + self._pending_switch = None + review = pending["review"] + self._emit("pairing_state", {"status": "connecting", "host": review["host"]}) + try: + result = switch_reviewed(review, now=time.monotonic()) + except PairingError as exc: + self._emit("pairing_state", {"status": "error", "error": str(exc)}) + raise + except Exception: + self._emit( + "pairing_state", + {"status": "error", "error": "The secure connection could not be completed."}, + ) + raise + host = _canonical_hosted_origin(result["host"]) + workspace = review["workspace"] + result = {**result, "host": host, "workspace": workspace} + self.config.hosted_host = host + self.config.paired_workspace_id = workspace["id"] + self.config.paired_workspace_name = workspace["name"] + self._persist("hosted_host", host) + self._persist("paired_workspace_id", workspace["id"]) + self._persist("paired_workspace_name", workspace["name"]) + self._emit( + "pairing_state", + {"status": "connected", "host": host, "workspace": workspace}, + ) + self._after_connect() + return result + + def keep(self, **params: Any) -> dict: + """Keep the current connection and revoke the reviewed claim.""" + revoked = self._discard_pending_switch() + state = {"status": "kept", "revoked": revoked is True} + self._emit("pairing_state", state) + return state + + def deny(self, **params: Any) -> dict: + """Drop the staged connect request. Nothing was redeemed.""" + self._pending_connect = None + state = {"status": "declined"} + self._emit("pairing_state", state) + return state + + +def dispatch_handlers(dispatcher: Any) -> dict[str, Callable[..., dict]]: + """The connect-link commands, bound to one dispatcher's config and events.""" + confirmation = PairingConfirmation( + dispatcher.config, + emit=lambda event, data: dispatcher.emit(event, data), + persist=dispatcher._persist_config_key, + after_connect=lambda: dispatcher._emit_sync(dispatcher._sync_state_now()), + ) + return { + "connect_uri": confirmation.connect_uri, + "pairing_status": confirmation.status, + "pairing_allow": confirmation.allow, + "pairing_switch": confirmation.switch, + "pairing_keep": confirmation.keep, + "pairing_deny": confirmation.deny, + } diff --git a/packages/desktop/tests/test_engine/test_dispatch.py b/packages/desktop/tests/test_engine/test_dispatch.py index 1491bdb52f..e32bacbafe 100644 --- a/packages/desktop/tests/test_engine/test_dispatch.py +++ b/packages/desktop/tests/test_engine/test_dispatch.py @@ -2734,7 +2734,7 @@ def test_a_restart_during_review_leaves_the_current_connection( def test_switch_after_the_review_deadline_keeps_the_current_connection( self, deps, fake_keyring, monkeypatch ) -> None: - import openadapt_desktop.dispatch as dispatch_module + import openadapt_desktop.pairing_confirm as dispatch_module from openadapt_desktop.auth.pairing import REVIEW_TTL_S disp, _db, _events = deps @@ -2825,7 +2825,7 @@ def _locked(): assert prompt["already_paired"] is True def test_expired_request_cannot_be_allowed(self, deps, monkeypatch) -> None: - import openadapt_desktop.dispatch as dispatch_module + import openadapt_desktop.pairing_confirm as dispatch_module disp, _db, _events = deps claims: list[tuple] = [] diff --git a/packages/desktop/tests/test_pairing_protocol_boundary.py b/packages/desktop/tests/test_pairing_protocol_boundary.py index e1b0d5b5ff..7f3169ca7a 100644 --- a/packages/desktop/tests/test_pairing_protocol_boundary.py +++ b/packages/desktop/tests/test_pairing_protocol_boundary.py @@ -35,7 +35,9 @@ def test_python_pairing_action_has_no_shell_or_navigation_escape_hatch() -> None pairing = (ROOT / "openadapt_desktop/auth/pairing.py").read_text() store = (ROOT / "openadapt_desktop/auth/store.py").read_text() dispatch = (ROOT / "openadapt_desktop/dispatch.py").read_text() - assert '"connect_uri": self.connect_uri' in dispatch + confirm = (ROOT / "openadapt_desktop/pairing_confirm.py").read_text() + assert "**pairing_confirm_handlers(self)" in dispatch + assert '"connect_uri": confirmation.connect_uri' in confirm assert '"claim_runner_uri": self.claim_runner_uri' in dispatch assert "subprocess" not in pairing assert "shell=" not in pairing @@ -75,12 +77,12 @@ def test_python_runner_bind_is_parse_only() -> None: def test_a_connect_link_only_stages_and_allow_is_not_reachable_from_a_link() -> None: pairing = (ROOT / "src-tauri/src/pairing.rs").read_text() - dispatch = (ROOT / "openadapt_desktop/dispatch.py").read_text() + confirm = (ROOT / "openadapt_desktop/pairing_confirm.py").read_text() # The deep link reaches only the staging verb; Allow comes from the window. shell = pairing.split("#[cfg(test)]", 1)[0] - for verb in ("pairing_allow", "pairing_switch", "pairing_keep"): - assert f'"{verb}"' not in shell - assert f'"{verb}": self.{verb}' in dispatch + for verb in ("allow", "switch", "keep"): + assert f'"pairing_{verb}"' not in shell + assert f'"pairing_{verb}": confirmation.{verb}' in confirm # A link's claim is reviewed before it can become the connection: the # review phase never stages, commits or recovers a keychain credential. python_pairing = (ROOT / "openadapt_desktop/auth/pairing.py").read_text() @@ -92,12 +94,12 @@ def test_a_connect_link_only_stages_and_allow_is_not_reachable_from_a_link() -> "_finish_staged_pairing(", ): assert write not in review - allow = dispatch.split(" def pairing_allow(", 1)[1].split("\n def ", 1)[0] - for write in ("claim_pairing(", "switch_reviewed(", "_persist_config_key", "hosted_host ="): + allow = confirm.split(" def allow(", 1)[1].split("\n def ", 1)[0] + for write in ("claim_pairing(", "switch_reviewed(", "_persist(", "hosted_host ="): assert write not in allow - stage = dispatch.split(" def connect_uri(", 1)[1].split("\n def ", 1)[0] + stage = confirm.split(" def connect_uri(", 1)[1].split("\n def ", 1)[0] assert "import connect_uri" not in stage - for redeem in ("claim_pairing", "httpx", "_persist_config_key"): + for redeem in ("claim_pairing", "httpx", "_persist("): assert redeem not in stage assert "hosted_host =" not in stage diff --git a/packages/flow/docs/design/DECOMPOSITION.md b/packages/flow/docs/design/DECOMPOSITION.md index 723c7e6158..c986a6eb31 100644 --- a/packages/flow/docs/design/DECOMPOSITION.md +++ b/packages/flow/docs/design/DECOMPOSITION.md @@ -613,7 +613,7 @@ The encryption-at-rest default lowered `__main__.py`: the `at-rest` command, `-- | `packages/flow/openadapt_flow/__main__.py` | 14237 | | `packages/flow/openadapt_flow/qualification/__init__.py` | 4891 | | `packages/flow/openadapt_flow/ir.py` | 6829 | -| `packages/desktop/openadapt_desktop/dispatch.py` | 6524 | +| `packages/desktop/openadapt_desktop/dispatch.py` | 6502 | | `packages/capture/openadapt_capture/recorder.py` | 4836 | | `packages/flow/openadapt_flow/interactive_recorder.py` | 4808 | | `packages/flow/openadapt_flow/runtime/durable/attended.py` | 4368 | From 871296bdf6f769faa15ce1155f1743da96410aaa Mon Sep 17 00:00:00 2001 From: abrichr Date: Sun, 29 Nov 2026 23:33:44 -0500 Subject: [PATCH 7/9] fix(desktop): tell same-name workspaces apart and refuse a second link Whoever creates a pairing code picks its workspace name, so the Switch question could read the same for the person's own workspace and for a different one named like it. - When the link's workspace has a different id but the current workspace's name (NFKC, case and whitespace folded), say "This is a different workspace that is also named ". - Both buttons carry a short workspace id, and Switch carries the account email, so the two can't read alike. - A second, different connect link no longer replaces the question on screen. Desktop drops both requests, revokes any reviewed claim and says "Two different connect links arrived. Nothing changed." - Sign-in and sign-out forget the workspace a connect link recorded, so a later dialog can't offer to keep a stale workspace. --- .../desktop/openadapt_desktop/dispatch.py | 11 +- .../openadapt_desktop/pairing_confirm.py | 95 +++++++++--- .../desktop/src/App.pairingConfirm.test.tsx | 40 +++++ .../desktop/src/ui/PairingConfirm.test.tsx | 55 ++++++- packages/desktop/src/ui/PairingConfirm.tsx | 45 ++++-- .../tests/test_engine/test_dispatch.py | 138 ++++++++++++++++-- .../tests/test_pairing_protocol_boundary.py | 2 +- packages/flow/docs/design/DECOMPOSITION.md | 2 +- 8 files changed, 334 insertions(+), 54 deletions(-) diff --git a/packages/desktop/openadapt_desktop/dispatch.py b/packages/desktop/openadapt_desktop/dispatch.py index 8d3e8c2260..5d580f8f60 100644 --- a/packages/desktop/openadapt_desktop/dispatch.py +++ b/packages/desktop/openadapt_desktop/dispatch.py @@ -44,10 +44,10 @@ from loguru import logger +from openadapt_desktop import pairing_confirm from openadapt_desktop.chrome_profile import dispatch_handlers as chrome_profile_handlers from openadapt_desktop.config import EngineConfig from openadapt_desktop.macos_permissions import control_permission_guidance -from openadapt_desktop.pairing_confirm import dispatch_handlers as pairing_confirm_handlers from openadapt_desktop.private_fs import ensure_private_dir EmitFn = Callable[[str, dict], None] @@ -376,7 +376,7 @@ def _register(self) -> None: # auth (both providers live in engine.auth -- spec 3a) "login_browser": self.login_browser, "login_paste": self.login_paste, - **pairing_confirm_handlers(self), # connect links; Allow is window wire only + **pairing_confirm.dispatch_handlers(self), # connect links; Allow is window wire only "claim_runner_uri": self.claim_runner_uri, "authoring_allow": self.authoring_allow, "authoring_deny": self.authoring_deny, @@ -5919,8 +5919,7 @@ def login_browser(self, **params: Any) -> dict: raise ValueError("Authenticated host did not match the requested host") except Exception as exc: return {"authenticated": False, "error": str(exc)} - self.config.hosted_host = host - self._persist_config_key("hosted_host", host) + pairing_confirm.record_sign_in(self, host) self._emit_sync(self._sync_state_now()) return self._auth_status(cred) @@ -5936,8 +5935,7 @@ def login_paste(self, **params: Any) -> dict: raise ValueError("Authenticated host did not match the requested host") except Exception as exc: return {"authenticated": False, "error": str(exc)} - self.config.hosted_host = host - self._persist_config_key("hosted_host", host) + pairing_confirm.record_sign_in(self, host) self._emit_sync(self._sync_state_now()) return self._auth_status(cred) @@ -6000,6 +5998,7 @@ def logout(self, **params: Any) -> dict: if not canonical_host_origin(stored_host): return {"authenticated": False, "error": "Hosted origin is invalid"} clear_credential(stored_host) + pairing_confirm.forget_paired_workspace(self) self._emit_sync(self._sync_state_now()) return {"authenticated": False} diff --git a/packages/desktop/openadapt_desktop/pairing_confirm.py b/packages/desktop/openadapt_desktop/pairing_confirm.py index 3ea01bdb67..65f7ee884f 100644 --- a/packages/desktop/openadapt_desktop/pairing_confirm.py +++ b/packages/desktop/openadapt_desktop/pairing_confirm.py @@ -12,13 +12,16 @@ 3. Only :meth:`PairingConfirmation.switch` makes it this computer's connection. Keep, a timeout, a new link or a restart discards it. -Every answer carries the request id the window showed. These commands are -served on the window wire only: the loopback socket refuses them. +Every answer carries the request id the window showed. If a second, different +link arrives while one is waiting, Desktop drops both rather than swap the +question the person is reading. These commands are served on the window wire +only: the loopback socket refuses them. """ from __future__ import annotations import time +import unicodedata import uuid from typing import Any, Callable from urllib.parse import urlsplit @@ -29,6 +32,16 @@ #: pairing codes last five minutes. PAIRING_CONFIRM_TTL_S = 300.0 +#: What the window says when two different links arrive while one waits. +TWO_LINKS_MESSAGE = ( + "Two different connect links arrived. Nothing changed. Open the link you created again." +) +#: The same, once the first link's code was already spent by Allow. +TWO_LINKS_AFTER_ALLOW_MESSAGE = ( + "Two different connect links arrived. Nothing changed. Create a new connection " + "in Cloud settings and open that link." +) + def _canonical_hosted_origin(value: Any) -> str: from openadapt_desktop.dispatch import _canonical_hosted_origin as canonical @@ -36,6 +49,29 @@ def _canonical_hosted_origin(value: Any) -> str: return canonical(value) +def _comparable_name(name: str) -> str: + """Fold a workspace name the way a person would read it.""" + return " ".join(unicodedata.normalize("NFKC", name).casefold().split()) + + +def forget_paired_workspace(dispatcher: Any) -> None: + """Forget the workspace a connect link recorded. + + Called on sign-in and sign-out, which can change the workspace without a + connect link, so a later Switch question can't name a stale workspace. + """ + for key in ("paired_workspace_id", "paired_workspace_name"): + setattr(dispatcher.config, key, "") + dispatcher._persist_config_key(key, "") + + +def record_sign_in(dispatcher: Any, host: str) -> None: + """Record the Cloud host a sign-in chose, and forget the old workspace.""" + dispatcher.config.hosted_host = host + dispatcher._persist_config_key("hosted_host", host) + forget_paired_workspace(dispatcher) + + class PairingConfirmation: """The one link waiting for Allow and the one claim waiting for Switch. @@ -85,18 +121,29 @@ def connect_uri(self, **params: Any) -> dict: self._emit("pairing_state", {"status": "error", "error": str(exc)}) raise pending = self._pending_connect - if ( - pending is not None - and not self._pending_connect_expired(pending) - and pending["pairing"] == request["pairing"] - and pending["host"] == host - ): + if pending is not None and self._pending_connect_expired(pending): + pending = self._pending_connect = None + switch = self._pending_switch + if switch is not None and time.monotonic() >= float(switch["review"]["deadline"]): + self._discard_pending_switch() + switch = None + same_link = {"pairing": request["pairing"], "host": host} + if pending is not None and same_link == {k: pending[k] for k in same_link}: # The same link delivered twice (launch and single-instance can # both deliver it): keep the request the window is showing. prompt = self._pairing_prompt(pending) - else: - # A new link replaces any connection still waiting for Switch. + elif switch is not None and same_link == {k: switch[k] for k in same_link}: + prompt = self._switch_prompt(switch) + elif pending is not None or switch is not None: + # A different link while one waits: swapping the question in + # place would let a second link ride on the person's click, so + # drop both and ask them to start again. + self._pending_connect = None self._discard_pending_switch() + message = TWO_LINKS_MESSAGE if switch is None else TWO_LINKS_AFTER_ALLOW_MESSAGE + self._emit("pairing_state", {"status": "error", "error": message}) + raise PairingError(message) + else: self._pending_connect = { "request_id": uuid.uuid4().hex, "pairing": request["pairing"], @@ -154,8 +201,8 @@ def status(self, **params: Any) -> dict: def allow(self, **params: Any) -> dict: """Claim the connect request the person allowed, for review only. - ``request_id`` must name the request the window showed, so a second - link that arrives before the click can't be allowed by it. The claim + ``request_id`` must name the request the window showed, so a click + on an earlier question can't allow a later one. The claim is checked but not made active: the window then shows the workspace Cloud named, and only :meth:`switch` changes the connection. """ @@ -175,9 +222,7 @@ def allow(self, **params: Any) -> dict: self._emit("pairing_state", {"status": "error", "error": message}) raise PairingError(message) if params.get("request_id") != pending["request_id"]: - message = ( - "A different connect link arrived. Review it before you allow it. Nothing changed." - ) + message = "Review the connect request on screen before you allow it. Nothing changed." self._emit("pairing_state", self._pairing_prompt(pending)) raise PairingError(message) # One use: the code is spent or refused below, never offered again. @@ -210,7 +255,13 @@ def allow(self, **params: Any) -> dict: ) self._emit("pairing_state", {"status": "error", "error": message}) raise PairingError(message) - self._pending_switch = {"request_id": uuid.uuid4().hex, "review": review} + self._pending_switch = { + "request_id": uuid.uuid4().hex, + "review": review, + # Kept to recognize a repeat delivery of this link, never shown. + "pairing": pending["pairing"], + "host": pending["host"], + } prompt = self._switch_prompt(self._pending_switch) self._emit("pairing_state", prompt) return prompt @@ -241,9 +292,14 @@ def _switch_prompt(self, pending: dict[str, Any]) -> dict[str, Any]: """The Switch or Keep question. Never carries the bearer.""" review = pending["review"] current = self._current_pairing() - same = ( - current["current_workspace"] is not None - and current["current_workspace"]["id"] == review["workspace"]["id"] + known = current["current_workspace"] + same = known is not None and known["id"] == review["workspace"]["id"] + # Whoever creates a code picks its workspace name, so a different + # workspace can carry the current one's name. Say so outright. + same_name = ( + known is not None + and not same + and _comparable_name(known["name"]) == _comparable_name(review["workspace"]["name"]) ) return { "status": "pending_switch", @@ -252,6 +308,7 @@ def _switch_prompt(self, pending: dict[str, Any]) -> dict[str, Any]: "workspace": review["workspace"], "account": review["account"], "same_workspace": same, + "same_name": same_name, **current, } diff --git a/packages/desktop/src/App.pairingConfirm.test.tsx b/packages/desktop/src/App.pairingConfirm.test.tsx index d7569e545c..a87be2ef84 100644 --- a/packages/desktop/src/App.pairingConfirm.test.tsx +++ b/packages/desktop/src/App.pairingConfirm.test.tsx @@ -118,6 +118,46 @@ it("shows a link that arrives while the app is open, and clears on declined", as await waitFor(() => expect(screen.queryByRole("alertdialog")).toBeNull()); }); +it("a second, different link replaces the question with an error, not a new Allow", async () => { + vi.mocked(engineTry).mockImplementation(async (command, _params, fallback) => { + if (command === CMD.GET_AUTH_STATUS) return { authenticated: true }; + if (command === CMD.GET_WORKFLOWS) return []; + if (command === CMD.GET_FIRST_WORKFLOW_STATE) return { ok: true, state: null }; + if (command === CMD.PAIRING_STATUS) return { status: "idle" }; + return fallback ?? null; + }); + const handlers = new Map void>(); + vi.mocked(onEngineEvent).mockImplementation(((event: string, handler: (p: unknown) => void) => { + handlers.set(event, handler); + return Promise.resolve(() => {}); + }) as typeof onEngineEvent); + + render(); + await waitFor(() => expect(handlers.has(EVT.PAIRING_STATE)).toBe(true)); + act(() => + handlers.get(EVT.PAIRING_STATE)?.({ + status: "pending_confirm", + request_id: "req-7", + host: "https://app.openadapt.ai", + already_paired: true, + }), + ); + await screen.findByRole("alertdialog"); + + // The engine drops both requests and reports it on pairing_state. + act(() => + handlers.get(EVT.PAIRING_STATE)?.({ + status: "error", + error: + "Two different connect links arrived. Nothing changed. Open the link you created again.", + }), + ); + await waitFor(() => expect(screen.queryByRole("alertdialog")).toBeNull()); + expect(screen.getByRole("alert").textContent).toContain("Two different connect links arrived."); + expect(screen.queryByRole("button", { name: "Allow" })).toBeNull(); + expect(sent(CMD.PAIRING_ALLOW)).toBe(false); +}); + it("after Allow, only Switch makes the new workspace active; Keep discards it", async () => { vi.mocked(engineTry).mockImplementation(async (command, _params, fallback) => { if (command === CMD.GET_AUTH_STATUS) return { authenticated: true }; diff --git a/packages/desktop/src/ui/PairingConfirm.test.tsx b/packages/desktop/src/ui/PairingConfirm.test.tsx index 91c3d4c3b6..329f4bd10b 100644 --- a/packages/desktop/src/ui/PairingConfirm.test.tsx +++ b/packages/desktop/src/ui/PairingConfirm.test.tsx @@ -5,6 +5,8 @@ import { PairingSwitch, keepLabel, pairingQuestion, + shortId, + switchLabel, switchQuestion, type PairingPrompt, type PairingSwitchPrompt, @@ -80,21 +82,64 @@ const switchPrompt: PairingSwitchPrompt = { describe("PairingSwitch", () => { it("names the new and the current workspace and the account", () => { const text = switchQuestion(switchPrompt); - expect(text).toContain("workspace Northside Clinic as pat@example.com on app.openadapt.ai"); - expect(text).toContain("connected to Current Clinic. Switching replaces that connection."); + expect(text).toContain( + "workspace Northside Clinic (ID 6f9d2c1e) as pat@example.com on app.openadapt.ai", + ); + expect(text).toContain( + "connected to Current Clinic (ID 11111111). Switching replaces that connection.", + ); + expect(text).not.toMatch(/also named/); }); - it("labels the buttons Switch to and Keep ", () => { + it("labels the buttons Switch to and Keep , with account and ID", () => { const onSwitch = vi.fn(); const onKeep = vi.fn(); render(); - fireEvent.click(screen.getByRole("button", { name: "Keep Current Clinic" })); + fireEvent.click(screen.getByRole("button", { name: "Keep Current Clinic (ID 11111111)" })); expect(onKeep).toHaveBeenCalledTimes(1); expect(onSwitch).not.toHaveBeenCalled(); - fireEvent.click(screen.getByRole("button", { name: "Switch to Northside Clinic" })); + fireEvent.click( + screen.getByRole("button", { + name: "Switch to Northside Clinic (pat@example.com, ID 6f9d2c1e)", + }), + ); expect(onSwitch).toHaveBeenCalledWith("sw-1"); }); + it("says outright when a different workspace has the current one's name", () => { + // Whoever creates a code picks its workspace name, so "Acme" can be anyone's. + const lookalike: PairingSwitchPrompt = { + ...switchPrompt, + workspace: { id: "22222222-3333-4444-8555-666666666666", name: "Acme" }, + account: { email: "ops@example.com" }, + current_workspace: { id: "11111111-2222-4333-8444-555555555555", name: "Acme" }, + same_workspace: false, + same_name: true, + }; + const text = switchQuestion(lookalike); + expect(text).toContain("This is a different workspace that is also named Acme."); + expect(text).toContain("connected to Acme (ID 11111111)"); + expect(text).toContain("workspace Acme (ID 22222222) as ops@example.com"); + // The two buttons can't read alike. + expect(switchLabel(lookalike)).toBe("Switch to Acme (ops@example.com, ID 22222222)"); + expect(keepLabel(lookalike)).toBe("Keep Acme (ID 11111111)"); + expect(switchLabel(lookalike)).not.toBe(keepLabel(lookalike).replace("Keep", "Switch to")); + + // The genuinely same workspace reads differently and shows the same ID. + const same = { + ...lookalike, + workspace: lookalike.current_workspace!, + same_workspace: true, + same_name: false, + }; + expect(switchQuestion(same)).toContain("already uses Acme (ID 11111111)"); + expect(switchQuestion(same)).not.toMatch(/different workspace/); + }); + + it("shortens a workspace ID to its first 8 characters", () => { + expect(shortId("6f9d2c1e-0b7a-4c3e-9a51-2d8f4b6e7a10")).toBe("6f9d2c1e"); + }); + it("says when the current workspace wasn't recorded, and when nothing is paired", () => { const unknown = { ...switchPrompt, current_workspace: null }; expect(switchQuestion(unknown)).toMatch(/workspace OpenAdapt didn't record/); diff --git a/packages/desktop/src/ui/PairingConfirm.tsx b/packages/desktop/src/ui/PairingConfirm.tsx index bb289a45f0..774f3a2194 100644 --- a/packages/desktop/src/ui/PairingConfirm.tsx +++ b/packages/desktop/src/ui/PairingConfirm.tsx @@ -3,14 +3,18 @@ // Anyone can create a pairing code and put it in a link, so a link never // connects this computer by itself: the engine only stages it, and nothing is // redeemed, and no credential or Cloud address changes, until the person -// clicks Allow here. Allow sends back the request id this dialog showed, so a -// second link that arrives before the click can't be allowed by it. +// clicks Allow here. If a second, different link arrives while this question +// is waiting, the engine drops both and the window shows an error instead of +// swapping the question in place. // // Cloud can't look up a pairing code without redeeming it, so the first // question names only the host. After Allow, the engine claims and checks the // code without making it active, and the second question (PairingSwitch) // names the workspace and account Cloud reported. Only Switch changes this // computer's connection; Keep, a timeout or a restart discards the new one. +// Whoever creates a code picks its workspace name, so the buttons also carry +// a short workspace ID, and a different workspace with the current one's +// name is called out. export type PairingPrompt = { status: "pending_confirm"; @@ -89,29 +93,50 @@ export type PairingSwitchPrompt = { workspace: Workspace; account?: { email: string } | null; same_workspace?: boolean; + same_name?: boolean; already_paired?: boolean; current_host?: string | null; current_workspace?: Workspace | null; }; +/** The first 8 characters of a workspace ID, enough to tell two apart. */ +export function shortId(id: string): string { + return id.replace(/-/g, "").slice(0, 8); +} + +function named(workspace: Workspace): string { + return `${workspace.name} (ID ${shortId(workspace.id)})`; +} + export function switchQuestion(prompt: PairingSwitchPrompt): string { const account = prompt.account?.email ? ` as ${prompt.account.email}` : ""; - const target = `This link connects this computer to the workspace ${prompt.workspace.name}${account} on ${hostLabel(prompt.host)}.`; + const target = `This link connects this computer to the workspace ${named(prompt.workspace)}${account} on ${hostLabel(prompt.host)}.`; if (!prompt.already_paired) { return `${target} Switch only if this is the workspace you meant.`; } - const current = prompt.current_workspace - ? prompt.same_workspace - ? ` This computer already uses ${prompt.current_workspace.name}; switching replaces its connection.` - : ` This computer is connected to ${prompt.current_workspace.name}. Switching replaces that connection.` - : " This computer is already connected to a workspace OpenAdapt didn't record. Switching replaces that connection."; + const known = prompt.current_workspace; + const current = !known + ? " This computer is already connected to a workspace OpenAdapt didn't record. Switching replaces that connection." + : prompt.same_workspace + ? ` This computer already uses ${named(known)}; switching replaces its connection.` + : prompt.same_name + ? ` This is a different workspace that is also named ${prompt.workspace.name}. This computer is connected to ${named(known)}. Switching replaces that connection.` + : ` This computer is connected to ${named(known)}. Switching replaces that connection.`; return `${target}${current} Switch only if this is the workspace you meant.`; } +export function switchLabel(prompt: PairingSwitchPrompt): string { + const details = [ + prompt.account?.email || null, + `ID ${shortId(prompt.workspace.id)}`, + ].filter(Boolean); + return `Switch to ${prompt.workspace.name} (${details.join(", ")})`; +} + export function keepLabel(prompt: PairingSwitchPrompt): string { if (!prompt.already_paired) return "Don't connect"; return prompt.current_workspace - ? `Keep ${prompt.current_workspace.name}` + ? `Keep ${named(prompt.current_workspace)}` : "Keep current connection"; } @@ -133,7 +158,7 @@ export function PairingSwitch({ {switchQuestion(prompt)}