diff --git a/packages/desktop/CHANGELOG.md b/packages/desktop/CHANGELOG.md index e8421c03cc..3264b1e2b1 100644 --- a/packages/desktop/CHANGELOG.md +++ b/packages/desktop/CHANGELOG.md @@ -1,6 +1,19 @@ # 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 +- **desktop**: show the workspace and switch only on the person's say-so + + + ## v0.35.0 (2026-11-24) ### Features 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/__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/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 7510219aa3..7a66e3ed79 100644 --- a/packages/desktop/openadapt_desktop/config.py +++ b/packages/desktop/openadapt_desktop/config.py @@ -34,6 +34,9 @@ "phi_mode": "phi_mode", "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", } @@ -199,13 +202,31 @@ def settings_customise_sources( default=60, description="Seconds between needs-attention count polls (never < 30).", ) - runner_enabled: bool = Field( + allow_local_pairing: bool = Field( default=False, description=( - "Enable the outbound hosted runner for admitted dispatches. " - "Off by default." + "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." + ), + ) + paired_workspace_id: str = Field( + default="", + description=( + "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 97f81f4fd4..5d580f8f60 100644 --- a/packages/desktop/openadapt_desktop/dispatch.py +++ b/packages/desktop/openadapt_desktop/dispatch.py @@ -44,6 +44,7 @@ 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 @@ -375,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, - "connect_uri": self.connect_uri, + **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, @@ -5918,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) @@ -5935,30 +5935,10 @@ 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) - def connect_uri(self, **params: Any) -> dict: - """Handle only a validated ``openadapt://connect`` pairing URI.""" - from openadapt_desktop.auth.pairing import connect_uri - - uri = params.get("uri") - if not isinstance(uri, str): - raise ValueError("uri is required") - result = connect_uri(uri) - 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_sync(self._sync_state_now()) - return result - def _authoring_service(self) -> Any: if self.services.authoring is None: from openadapt_desktop.authoring_runner import AuthoringRunner @@ -6018,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 new file mode 100644 index 0000000000..a8a0102478 --- /dev/null +++ b/packages/desktop/openadapt_desktop/pairing_confirm.py @@ -0,0 +1,416 @@ +"""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. If a second, different +link arrives while one is waiting, Desktop drops both rather than swap the +question the person is reading. A link that arrives after that asks a fresh +question, marked as coming right after two links; nothing can tell it from the +person's own link, which is why Switch names the workspace by id and account. +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 + +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 + +#: 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 + + 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. + + 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 + # Until when a new question is marked as following two links. + self._conflict_until = 0.0 + + 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 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) + 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() + self._conflict_until = time.monotonic() + PAIRING_CONFIRM_TTL_S + 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"], + "host": host, + "destination_kind": request.get("destination_kind"), + "expires_at": time.monotonic() + PAIRING_CONFIRM_TTL_S, + "after_conflict": time.monotonic() < self._conflict_until, + } + 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, + "after_conflict": pending.get("after_conflict") is True, + **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 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. + """ + 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 = "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. + 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, + # Kept to recognize a repeat delivery of this link, never shown. + "pairing": pending["pairing"], + "host": pending["host"], + "after_conflict": pending.get("after_conflict") is True, + } + 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() + 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", + "request_id": pending["request_id"], + "host": review["host"], + "workspace": review["workspace"], + "account": review["account"], + "same_workspace": same, + "same_name": same_name, + "after_conflict": pending.get("after_conflict") is True, + **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/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/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-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/src/App.pairingConfirm.test.tsx b/packages/desktop/src/App.pairingConfirm.test.tsx new file mode 100644 index 0000000000..a87be2ef84 --- /dev/null +++ b/packages/desktop/src/App.pairingConfirm.test.tsx @@ -0,0 +1,186 @@ +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 +// 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, EVT, engineInvoke, engineTry, onEngineEvent } 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("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" })); + 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(); +}); + +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("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("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 }; + 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 817fa6f089..b155da542c 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,12 @@ import { deliverAttentionNotification } from "./lib/attentionNotification"; import { Qualification } from "./screens/Qualification"; import { clearLocalSession, rememberLocalSession } from "./localSession"; import { ItemApprovalDialog } from "./ui/ItemApproval"; +import { + PairingConfirm, + PairingSwitch, + type PairingPrompt, + type PairingSwitchPrompt, +} from "./ui/PairingConfirm"; import { ShadowModeIndicator, ShadowPromptBanner, @@ -91,10 +98,13 @@ type Route = | { name: "portal" } | { name: "settings" }; -type PairingState = { - status: "connecting" | "connected" | "error"; - error?: string; -}; +type PairingState = + | PairingPrompt + | PairingSwitchPrompt + | { + status: "connecting" | "connected" | "declined" | "kept" | "error" | "idle"; + error?: string; + }; const NAV: { route: "tasks" | "needs" | "results"; @@ -501,6 +511,18 @@ 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" || + pairingStatus?.status === "pending_switch" + ) { + setPairing(pairingStatus); + } setAtRest( await engineTry(CMD.AT_REST_STATUS, {}, null), ); @@ -555,9 +577,16 @@ 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 === "kept" || + state.status === "idle" + ? null + : state, + ); + if (state?.status === "connected") { void engineTry( CMD.GET_AUTH_STATUS, {}, @@ -586,7 +615,50 @@ 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?.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" || + 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(/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(/after you allow it/); + }); + + 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. Your connection stays as it is unless you then choose Switch.", + ); + }); + + 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\. Your connection stays/); + }); + + 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"); + }); +}); + +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 (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 , with account and ID", () => { + const onSwitch = vi.fn(); + const onKeep = vi.fn(); + render(); + 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 (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("marks a question that comes right after two different links", () => { + expect(switchQuestion({ ...switchPrompt, after_conflict: true })).toContain( + "Two different connect links arrived a moment ago.", + ); + expect(pairingQuestion({ ...prompt, after_conflict: true })).toContain( + "Continue only if you just opened your own link again.", + ); + expect(pairingQuestion(prompt)).not.toMatch(/arrived a moment ago/); + }); + + 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/); + 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 new file mode 100644 index 0000000000..6fa98f0f7a --- /dev/null +++ b/packages/desktop/src/ui/PairingConfirm.tsx @@ -0,0 +1,178 @@ +// 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. 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. A question that comes right after that is +// marked, because it may not be the person's own link. +// +// 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"; + request_id: string; + host: string; + workspace?: string | null; + account?: string | null; + already_paired?: boolean; + current_host?: string | null; + after_conflict?: boolean; +}; + +/** Said on a question that arrives right after two different links. */ +export const AFTER_CONFLICT = + " Two different connect links arrived a moment ago. Continue only if you just opened your own link again."; + +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 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)}. 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}.` + + replaces + + (prompt.after_conflict ? AFTER_CONFLICT : "") + + " 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)} + + + + +
+ ); +} + +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; + same_name?: boolean; + after_conflict?: 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 ${named(prompt.workspace)}${account} on ${hostLabel(prompt.host)}.`; + const warning = prompt.after_conflict ? AFTER_CONFLICT : ""; + if (!prompt.already_paired) { + return `${target}${warning} Switch only if this is the workspace you meant.`; + } + 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}${warning} 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 ${named(prompt.current_workspace)}` + : "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/conftest.py b/packages/desktop/tests/conftest.py index 4c7f000d83..f37a9fe804 100644 --- a/packages/desktop/tests/conftest.py +++ b/packages/desktop/tests/conftest.py @@ -158,6 +158,17 @@ def _isolated_flow_at_rest(tmp_path_factory, monkeypatch): monkeypatch.setenv("OPENADAPT_HOME", str(tmp_path_factory.mktemp("openadapt-home"))) +@pytest.fixture(autouse=True) +def _isolated_desktop_config(tmp_path_factory, monkeypatch): + """Keep tests from reading or writing the developer's ~/.openadapt/config.toml. + + Sign-in, sign-out and Switch persist ``[hosted]`` keys; a test that wants a + specific file still sets ``OPENADAPT_CONFIG_TOML`` itself. + """ + path = tmp_path_factory.mktemp("desktop-config") / "config.toml" + monkeypatch.setenv("OPENADAPT_CONFIG_TOML", str(path)) + + @pytest.fixture(autouse=True) def no_usage_stats_or_update_check(monkeypatch): """Keep the suite from sending usage stats or asking GitHub for releases. diff --git a/packages/desktop/tests/test_engine/test_approval_mode.py b/packages/desktop/tests/test_engine/test_approval_mode.py index 680e893811..45e2d90e23 100644 --- a/packages/desktop/tests/test_engine/test_approval_mode.py +++ b/packages/desktop/tests/test_engine/test_approval_mode.py @@ -231,7 +231,16 @@ def _run(disp, member: str) -> dict: def test_desktop_has_no_command_that_turns_the_switch_on(task) -> None: disp, _db, _config, _digest = task - commands = {name for name in disp._handlers if "approval" in name or "switch" in name} + # ``pairing_switch`` is the only exception: it switches this computer's + # Cloud connection after a connect link, and never touches approval mode + # (see test_pairing_switch_cannot_change_approval_mode). Every other new + # command with "approval" or "switch" in its name must be added here. + not_approval_mode = {"pairing_switch"} + commands = { + name + for name in disp._handlers + if ("approval" in name or "switch" in name) and name not in not_approval_mode + } # The item-approval pair answers one save a running item waits on # (``each_item``), as does a stop card's save approval; none reads or # writes a switch record. @@ -242,8 +251,29 @@ def test_desktop_has_no_command_that_turns_the_switch_on(task) -> None: "answer_item_approval", "answer_stop_approval", } - source = Path(__file__).resolve().parents[2] / "openadapt_desktop" / "dispatch.py" - assert "accept_switch" not in source.read_text() + package = Path(__file__).resolve().parents[2] / "openadapt_desktop" + assert "accept_switch" not in (package / "dispatch.py").read_text() + + +def test_pairing_switch_cannot_change_approval_mode(task) -> None: + disp, _db, config, digest = task + from openadapt_desktop.pairing_confirm import PairingConfirmation + + # It is the connect-link confirmation's Switch, nothing else. + handler = disp._handlers["pairing_switch"] + assert handler.__func__ is PairingConfirmation.switch + source = ( + Path(__file__).resolve().parents[2] / "openadapt_desktop" / "pairing_confirm.py" + ).read_text() + for name in ("approval_mode", "accept_switch", "turn_off", "read_switch"): + assert name not in source + + # With a switch on in Cloud, a refused pairing_switch leaves it as it was. + accept_switch(config.data_dir, "wf-note", _envelope(digest)) + before = disp.dispatch("get_approval_mode", {"workflow_id": "wf-note"}) + with pytest.raises(RuntimeError, match="isn't waiting"): + disp.dispatch("pairing_switch", {"request_id": "anything", "workflow_id": "wf-note"}) + assert disp.dispatch("get_approval_mode", {"workflow_id": "wf-note"}) == before def test_no_switch_reads_off_and_has_nothing_to_turn_off(task) -> None: @@ -254,7 +284,7 @@ def test_no_switch_reads_off_and_has_nothing_to_turn_off(task) -> None: # The card shows no switch for a task that has none on this computer. assert mode["visible"] is False assert mode["can_turn_off"] is False - assert mode["blockers"][-len(NOT_BUILT):] == list(NOT_BUILT) + assert mode["blockers"][-len(NOT_BUILT) :] == list(NOT_BUILT) refused = disp.dispatch("turn_off_approval_mode", {"workflow_id": "wf-note"}) assert refused["ok"] is False assert "no switch" in refused["error"] @@ -321,15 +351,19 @@ def test_a_closed_switch_stays_closed_until_cloud_sends_a_new_one(task) -> None: accept_switch(config.data_dir, "wf-note", _envelope(digest)) turn_off(config.data_dir, "wf-note") view = read_switch( - config.data_dir, "wf-note", - bundle_dir=config.data_dir / "bundles" / "wf-note", runner_id=RUNNER, + config.data_dir, + "wf-note", + bundle_dir=config.data_dir / "bundles" / "wf-note", + runner_id=RUNNER, ) assert view["state"] == "off" accept_switch(config.data_dir, "wf-note", _envelope(digest, switch_id="sw-2")) view = read_switch( - config.data_dir, "wf-note", - bundle_dir=config.data_dir / "bundles" / "wf-note", runner_id=RUNNER, + config.data_dir, + "wf-note", + bundle_dir=config.data_dir / "bundles" / "wf-note", + runner_id=RUNNER, ) assert view["state"] == "on" assert view["switch_id"] == "sw-2" @@ -344,7 +378,8 @@ def test_a_switch_for_another_version_or_runner_never_reads_on(task) -> None: assert mode["off_reason"] == "version_changed" accept_switch( - config.data_dir, "wf-note", + config.data_dir, + "wf-note", _envelope(digest, runner_id="runner-other", switch_id="sw-b"), ) mode = disp.dispatch("get_approval_mode", {"workflow_id": "wf-note"}) @@ -370,8 +405,10 @@ def test_a_tampered_or_missing_log_reads_off(task) -> None: log = config.data_dir / "approval_mode" / "wf-note" / "switch.log" log.write_text(log.read_text().replace('"opened"', '"opened" ')) view = read_switch( - config.data_dir, "wf-note", - bundle_dir=config.data_dir / "bundles" / "wf-note", runner_id=RUNNER, + config.data_dir, + "wf-note", + bundle_dir=config.data_dir / "bundles" / "wf-note", + runner_id=RUNNER, ) assert view["state"] == "off" assert view["off_reason"] == "uncertain_result" @@ -380,16 +417,20 @@ def test_a_tampered_or_missing_log_reads_off(task) -> None: result = turn_off(config.data_dir, "wf-note") assert result["logged"] is False view = read_switch( - config.data_dir, "wf-note", - bundle_dir=config.data_dir / "bundles" / "wf-note", runner_id=RUNNER, + config.data_dir, + "wf-note", + bundle_dir=config.data_dir / "bundles" / "wf-note", + runner_id=RUNNER, ) assert view["state"] == "off" assert view["off_reason"] == "turned_off" log.unlink() view = read_switch( - config.data_dir, "wf-note", - bundle_dir=config.data_dir / "bundles" / "wf-note", runner_id=RUNNER, + config.data_dir, + "wf-note", + bundle_dir=config.data_dir / "bundles" / "wf-note", + runner_id=RUNNER, ) assert view["state"] == "off" @@ -400,8 +441,10 @@ def test_an_unfinished_item_in_the_log_reads_off(task) -> None: log = switch_api.SwitchLog(config.data_dir / "approval_mode" / "wf-note" / "switch.log") log.append("item_started", run_ref=HEX) view = read_switch( - config.data_dir, "wf-note", - bundle_dir=config.data_dir / "bundles" / "wf-note", runner_id=RUNNER, + config.data_dir, + "wf-note", + bundle_dir=config.data_dir / "bundles" / "wf-note", + runner_id=RUNNER, ) assert view["state"] == "off" assert view["off_reason"] == "uncertain_result" @@ -424,14 +467,10 @@ def test_a_switch_from_cloud_is_validated_before_it_is_stored(task) -> None: def test_requirements_come_from_flow_and_are_not_confirmed_here(task) -> None: disp, _db, config, digest = task # A task with no switch here doesn't pay for reading its requirements. - hidden = disp.dispatch( - "get_approval_mode", {"workflow_id": "wf-note", "requirements": True} - ) + hidden = disp.dispatch("get_approval_mode", {"workflow_id": "wf-note", "requirements": True}) assert "requirements" not in hidden accept_switch(config.data_dir, "wf-note", _envelope(digest)) - mode = disp.dispatch( - "get_approval_mode", {"workflow_id": "wf-note", "requirements": True} - ) + mode = disp.dispatch("get_approval_mode", {"workflow_id": "wf-note", "requirements": True}) requirements = mode["requirements"] if not requirements["available"]: pytest.skip(f"Flow couldn't read the test workflow: {requirements['reason']}") @@ -595,8 +634,9 @@ def test_an_item_held_for_approval_offers_no_rerun(task) -> None: held = { "mode": "problems_only", "channel": "desktop_run_it_list_with_header", - "item_checks": _checks(["channel", "record_key_not_recent"], - failed={"record_key_not_recent": "seen_recently"}), + "item_checks": _checks( + ["channel", "record_key_not_recent"], failed={"record_key_not_recent": "seen_recently"} + ), "pre_checks": [], "post_checks": [], "decision": "approval_required", @@ -668,8 +708,13 @@ def test_control_a_bound_no_person_item_counts_when_the_switch_is_on_here(switch @pytest.mark.parametrize( - "transaction", ["RECONCILIATION_REQUIRED", "HALTED_BEFORE_EFFECT", "COMPLETED_UNVERIFIED", - "NOT_A_REAL_OUTCOME"] + "transaction", + [ + "RECONCILIATION_REQUIRED", + "HALTED_BEFORE_EFFECT", + "COMPLETED_UNVERIFIED", + "NOT_A_REAL_OUTCOME", + ], ) def test_attack_inconsistent_verified_pair_never_closes_an_item(task, transaction: str) -> None: """Execution VERIFIED with a transaction outcome that disagrees. @@ -710,9 +755,7 @@ def test_attack_inconsistent_pair_under_the_switch_never_reads_confirmed(switch_ needs_person=True, counts_toward_problems=True, switch_off_reason="uncertain_result", - post_checks=_checks( - ["verified", "whole_run_clean"], failed={"verified": "not_verified"} - ), + post_checks=_checks(["verified", "whole_run_clean"], failed={"verified": "not_verified"}), ) disp.services._flow_bridge = _Bridge( [_report(transaction="RECONCILIATION_REQUIRED", execution="VERIFIED", approval=block)] @@ -911,8 +954,10 @@ def test_attack_cloud_cannot_reopen_a_switch_turned_off_here(task) -> None: accept_switch(config.data_dir, "wf-note", _envelope(digest)) view = read_switch( - config.data_dir, "wf-note", - bundle_dir=config.data_dir / "bundles" / "wf-note", runner_id=RUNNER, + config.data_dir, + "wf-note", + bundle_dir=config.data_dir / "bundles" / "wf-note", + runner_id=RUNNER, ) assert view["state"] == "off" assert view["off_reason"] == "turned_off" @@ -929,8 +974,10 @@ def test_attack_an_archived_closed_switch_cannot_return(task) -> None: with pytest.raises(SwitchApprovalError): accept_switch(config.data_dir, "wf-note", _envelope(digest, switch_id="sw-1")) view = read_switch( - config.data_dir, "wf-note", - bundle_dir=config.data_dir / "bundles" / "wf-note", runner_id=RUNNER, + config.data_dir, + "wf-note", + bundle_dir=config.data_dir / "bundles" / "wf-note", + runner_id=RUNNER, ) assert view["switch_id"] == "sw-3" @@ -951,8 +998,10 @@ def test_attack_resending_the_same_switch_keeps_its_log(task) -> None: assert log.state().open_items == [HEX] view = read_switch( - config.data_dir, "wf-note", - bundle_dir=config.data_dir / "bundles" / "wf-note", runner_id=RUNNER, + config.data_dir, + "wf-note", + bundle_dir=config.data_dir / "bundles" / "wf-note", + runner_id=RUNNER, ) assert view["state"] == "off" assert view["off_reason"] == "uncertain_result" @@ -1018,9 +1067,7 @@ def disk_full(*_a, **_k): assert result["moved_aside"] is True # What Flow's gate reads before every save: a missing log means off. with pytest.raises(switch_api.SwitchLogError): - switch_api.SwitchLog( - config.data_dir / "approval_mode" / "wf-note" / "switch.log" - ).state() + switch_api.SwitchLog(config.data_dir / "approval_mode" / "wf-note" / "switch.log").state() assert result["mode"]["state"] == "off" assert result["mode"]["off_reason"] == "turned_off" # And the same switch can't come back. 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 d8463418c9..a2ce0566fe 100644 --- a/packages/desktop/tests/test_engine/test_dispatch.py +++ b/packages/desktop/tests/test_engine/test_dispatch.py @@ -16,6 +16,107 @@ 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" +) +_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( outcome: str, @@ -2464,52 +2565,451 @@ 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( - self, deps, monkeypatch, tmp_path + 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") + + monkeypatch.setattr(httpx, "post", _no_network) + monkeypatch.setattr(httpx, "get", _no_network) + 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 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 fake_keyring._store == keychain_before + + 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 + + with pytest.raises(RuntimeError, match="Review the connect request"): + disp.dispatch("pairing_allow", {"request_id": "not-the-shown-one"}) + with pytest.raises(RuntimeError, match="Review the connect request"): + disp.dispatch("pairing_allow", {}) + 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 - 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")) + _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) + + 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 - def _connect(exact_uri: str) -> dict: - received.append(exact_uri) - return { - "authenticated": True, - "host": "https://app.openadapt.ai", - "paired": True, - } + 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"]}) - 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 ( - "pairing_state", - { - "status": "connected", - "host": "https://app.openadapt.ai", - }, - ) in events + 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_connect_uri_returns_the_canonical_authenticated_host( - self, deps, monkeypatch, tmp_path + 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 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 - monkeypatch.setenv("OPENADAPT_CONFIG_TOML", str(tmp_path / "config.toml")) + _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.pairing_confirm 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_claim_and_stages_nothing( + self, deps, fake_keyring, monkeypatch + ) -> None: + from openadapt_desktop.auth.store import load_credential + + 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"]}) + + # The same link delivered again keeps the Switch question as it is. + assert disp.dispatch("connect_uri", {"uri": _CONNECT_URI}) == question + assert "abort" not in cloud.calls + + other = _CONNECT_URI.replace(_PAIRING_SECRET, "oap_" + "B" * 43) + with pytest.raises(RuntimeError, match="Two different connect links arrived"): + disp.dispatch("connect_uri", {"uri": other}) + + assert cloud.calls[-1] == "abort" + assert events[-1][1]["status"] == "error" + assert "Nothing changed" in events[-1][1]["error"] + assert disp.dispatch("pairing_status", {}) == {"status": "idle"} + assert load_credential("https://app.openadapt.ai")["token"] == _CURRENT_TOKEN + with pytest.raises(RuntimeError, match="isn't waiting"): + disp.dispatch("pairing_switch", {"request_id": question["request_id"]}) + + 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 + # The link's workspace is "Northside Clinic" too, folded differently. + disp.config.paired_workspace_name = " northside CLINIC " + 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 + # A different workspace wearing the current one's name is flagged. + assert question["same_name"] is True + + def test_same_name_is_not_flagged_for_the_same_or_an_unrelated_workspace( + self, deps, monkeypatch + ) -> None: + disp, _db, _events = deps + _store_current_credential() + cloud = _FakeCloud(identity=_IDENTITY) + cloud.install(monkeypatch) + + disp.config.paired_workspace_id = _IDENTITY["workspace"]["id"] + disp.config.paired_workspace_name = "Northside Clinic" + prompt = disp.dispatch("connect_uri", {"uri": _CONNECT_URI}) + same = disp.dispatch("pairing_allow", {"request_id": prompt["request_id"]}) + assert (same["same_workspace"], same["same_name"]) == (True, False) + disp.dispatch("pairing_keep", {}) + + disp.config.paired_workspace_id = _CURRENT_WORKSPACE_ID + disp.config.paired_workspace_name = "Current Clinic" + other = _CONNECT_URI.replace(_PAIRING_SECRET, "oap_" + "B" * 43) + prompt = disp.dispatch("connect_uri", {"uri": other}) + unrelated = disp.dispatch("pairing_allow", {"request_id": prompt["request_id"]}) + assert (unrelated["same_workspace"], unrelated["same_name"]) == (False, False) + + def test_a_repeat_delivery_keeps_the_shown_request_and_a_new_link_drops_both( + self, deps + ) -> None: + disp, _db, events = deps + first = disp.dispatch("connect_uri", {"uri": _CONNECT_URI}) + again = disp.dispatch("connect_uri", {"uri": _CONNECT_URI}) + assert again["request_id"] == first["request_id"] + + # A different link never takes the place of the question on screen. + other = _CONNECT_URI.replace(_PAIRING_SECRET, "oap_" + "B" * 43) + with pytest.raises(RuntimeError, match="Two different connect links arrived"): + disp.dispatch("connect_uri", {"uri": other}) + assert events[-1][1] == { + "status": "error", + "error": "Two different connect links arrived. Nothing changed. " + "Open the link you created again.", + } + assert disp.dispatch("pairing_status", {}) == {"status": "idle"} + with pytest.raises(RuntimeError, match="isn't waiting"): + disp.dispatch("pairing_allow", {"request_id": first["request_id"]}) + + # Opening the person's own link again starts a fresh question, + # marked as following two links. + fresh = disp.dispatch("connect_uri", {"uri": _CONNECT_URI}) + assert fresh["status"] == "pending_confirm" + assert fresh["request_id"] != first["request_id"] + assert fresh["after_conflict"] is True + assert first["after_conflict"] is False + + def test_a_link_fired_twice_after_a_conflict_is_marked_through_switch( + self, deps, monkeypatch + ) -> None: + """A, then B (both dropped), then B again: a new question, never a quiet one.""" + disp, _db, _events = deps + cloud = _FakeCloud(identity=_IDENTITY) + cloud.install(monkeypatch) + disp.dispatch("connect_uri", {"uri": _CONNECT_URI}) + other = _CONNECT_URI.replace(_PAIRING_SECRET, "oap_" + "B" * 43) + with pytest.raises(RuntimeError, match="Two different connect links arrived"): + disp.dispatch("connect_uri", {"uri": other}) + + again = disp.dispatch("connect_uri", {"uri": other}) + + assert disp.dispatch("pairing_status", {}) == again + assert again["after_conflict"] is True + question = disp.dispatch("pairing_allow", {"request_id": again["request_id"]}) + assert question["after_conflict"] is True + + def test_an_expired_request_does_not_block_a_new_link(self, deps, monkeypatch) -> None: + import openadapt_desktop.pairing_confirm as confirm_module + + disp, _db, _events = deps + disp.dispatch("connect_uri", {"uri": _CONNECT_URI}) + now = confirm_module.time.monotonic() monkeypatch.setattr( - "openadapt_desktop.auth.pairing.connect_uri", - lambda _uri: { - "authenticated": True, - "host": "HTTPS://Customer.Example:443/pairing", - "paired": True, - }, + confirm_module.time, + "monotonic", + lambda: now + confirm_module.PAIRING_CONFIRM_TTL_S + 1, ) + other = _CONNECT_URI.replace(_PAIRING_SECRET, "oap_" + "B" * 43) + assert disp.dispatch("connect_uri", {"uri": other})["status"] == "pending_confirm" - result = disp.dispatch("connect_uri", {"uri": "openadapt://connect"}) + def test_sign_in_and_sign_out_forget_the_recorded_workspace( + self, deps, fake_keyring, monkeypatch, tmp_path + ) -> None: + """A later Switch question can't offer to keep a workspace that's gone.""" + import tomllib - assert result["host"] == "https://customer.example" - assert disp.config.hosted_host == "https://customer.example" + 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" + cred = { + "kind": "ingest_token", + "token": "oai_ingest_signed_in", + "refresh_token": None, + "org_id": "org_other", + "host": "https://app.openadapt.ai", + "expires_at": None, + } + monkeypatch.setattr("openadapt_desktop.auth.login", lambda host, prefer: cred) + monkeypatch.setattr( + "openadapt_desktop.auth.paste.PasteTokenProvider.login", lambda self, token=None: cred + ) + + def _recorded() -> None: + disp.config.paired_workspace_id = _CURRENT_WORKSPACE_ID + disp.config.paired_workspace_name = "Current Clinic" + + def _forgotten() -> bool: + hosted = tomllib.loads(toml_path.read_text())["hosted"] + return ( + disp.config.paired_workspace_id == "" + and disp.config.paired_workspace_name == "" + and hosted["paired_workspace_id"] == "" + and hosted["paired_workspace_name"] == "" + ) + + for command, params in ( + ("login_browser", {}), + ("login_paste", {"token": "t"}), + ("logout", {}), + ): + _recorded() + result = disp.dispatch(command, params) + assert toml_path.exists(), (command, result) + assert _forgotten(), command + + 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.pairing_confirm as dispatch_module + + disp, _db, _events = deps + claims: list[tuple] = [] + monkeypatch.setattr( + "openadapt_desktop.auth.pairing.claim_for_review", + 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 == [] + + 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 +3017,28 @@ 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: + # 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_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: + 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: 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..60a138218a 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.dispatch_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 @@ -71,3 +73,53 @@ 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() + 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 ("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() + 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 = 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 = 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("): + 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 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" }, diff --git a/packages/flow/docs/design/DECOMPOSITION.md b/packages/flow/docs/design/DECOMPOSITION.md index 723c7e6158..bc8e021c6e 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` | 6501 | | `packages/capture/openadapt_capture/recorder.py` | 4836 | | `packages/flow/openadapt_flow/interactive_recorder.py` | 4808 | | `packages/flow/openadapt_flow/runtime/durable/attended.py` | 4368 |