Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 13 additions & 0 deletions packages/desktop/CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -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
Expand Down
5 changes: 3 additions & 2 deletions packages/desktop/docs/RELEASE_CANDIDATE_INSTALLERS.md
Original file line number Diff line number Diff line change
Expand Up @@ -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`
Expand Down
2 changes: 1 addition & 1 deletion packages/desktop/openadapt_desktop/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,4 +21,4 @@
+-- backends/ Storage backend plugins
"""

__version__ = "0.35.0"
__version__ = "0.35.1"
250 changes: 247 additions & 3 deletions packages/desktop/openadapt_desktop/auth/pairing.py
Original file line number Diff line number Diff line change
Expand Up @@ -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):
Expand Down Expand Up @@ -512,16 +520,29 @@ 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",
"ingest_token_id",
"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"))
Expand Down Expand Up @@ -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)
27 changes: 24 additions & 3 deletions packages/desktop/openadapt_desktop/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -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",
}


Expand Down Expand Up @@ -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
Expand Down
Loading
Loading