From 69c1691c256d14d3085f9911d7ae579baeaae587 Mon Sep 17 00:00:00 2001 From: layered-control-agent-host Date: Fri, 20 Nov 2026 13:05:39 +0000 Subject: [PATCH] feat(identity): session bridge for organizations moved from Agent Relay Cloud Off by default (SELFHOST_CLOUD_BRIDGE_ENABLED); while off its routes answer 404 and no other bridge setting is read. Cloud signs a short-lived, single-use Ed25519 assertion for a browser with a live Cloud session and posts it to /cloud/api/v1/auth/cloud-bridge/consume. This service verifies it against operator-configured public keys and issues its own browser session for the existing user (matched by id, never email) in an organization the operator listed with a time-boxed window. It accepts no Cloud token or cookie, creates no user, membership or workspace, and exchanges no Desktop, MCP or API credential. - migration 0083: cloud_bridge_organizations (per-organization window) and cloud_bridge_assertions (spent assertion ids) - start route keeps the nonce and next path in an encrypted attempt cookie; consume requires the handoff page's exact Origin, the nonce, a verified assertion, an open window, membership, a recent enough Cloud sign-in and no sign-out here since that sign-in - operator routes under /api/v1/installation/cloud-bridge/organizations (bootstrap bearer), audited - every acceptance and verified refusal is audited; refusals log an internal reason and never the assertion, nonce or cookie - verifier schema manifest refreshed for 0083 Co-Authored-By: Claude --- CHANGELOG.md | 1 + docs/identity.md | 181 ++++ docs/repository-guide.md | 5 + migrations/0083_cloud_bridge.sql | 29 + openapi.yaml | 151 ++++ .../cloud-import-verify/schema-manifest.json | 22 +- src/control-tables.ts | 2 + src/identity/attempt-cookie.ts | 33 +- src/identity/cloud-bridge.ts | 312 +++++++ src/identity/config.ts | 34 + src/identity/routes.ts | 284 +++++- src/identity/store.ts | 274 ++++++ test/cloud-bridge-verifier.test.ts | 350 ++++++++ test/cloud-bridge.test.ts | 811 ++++++++++++++++++ test/fixtures/cloud-bridge-contract.json | 28 + 15 files changed, 2501 insertions(+), 16 deletions(-) create mode 100644 migrations/0083_cloud_bridge.sql create mode 100644 src/identity/cloud-bridge.ts create mode 100644 test/cloud-bridge-verifier.test.ts create mode 100644 test/cloud-bridge.test.ts create mode 100644 test/fixtures/cloud-bridge-contract.json diff --git a/CHANGELOG.md b/CHANGELOG.md index edd8e962..291bbb06 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,6 +5,7 @@ assigned at release. ## Unreleased +- Added: a session bridge for organizations moved from Agent Relay Cloud (migration 0083; docs/identity.md). Off by default (`SELFHOST_CLOUD_BRIDGE_ENABLED`); while off its routes answer 404. Cloud signs a short-lived, single-use Ed25519 assertion for a browser with a live Cloud session and posts it to `/cloud/api/v1/auth/cloud-bridge/consume`; this deployment verifies it against `SELFHOST_CLOUD_BRIDGE_PUBLIC_KEYS` and issues its own browser session for the existing user (matched by id, never email) in an organization the operator listed with a time-boxed window (`/api/v1/installation/cloud-bridge/organizations`, bootstrap bearer only). It creates nothing, accepts no Cloud token, and is refused after the person signs out here. - Fixed: MCP repository-filtered session summaries apply the first 200 characters of a repo-only filter in the session directory before pagination, while still accepting a 512-character repo value and verifying the full returned repository URL. This requires a sessions read API whose session directory list applies `projectContains` as a case-insensitive substring of project ID, catalog project key or recorded repository URL (directory migration `20261105034000` or later). Exact verification can still produce a short or empty page with a cursor. Relay agent listings now link an exact roster agent ID to its already-synced Desktop native session when the agent has no validated Relaycast session declaration. The optional session join is failure-open: the roster still returns a null session ID and attribution with `session_unavailable_reason` set to `enrichment_failed` or `ambiguous_sync`; an independently recorded metadata session kind is preserved. No migration. - Changed: MCP `list_amp_threads` now returns `{ threads, truncated }` instead of a bare thread array. Clients that parse the old array must read the `threads` field; `truncated` truthfully reports whether Amp returned more than the first 100 threads by requesting one lookahead row. - Changed: MCP `list_relay_agents` now returns the first at most 100 matching agents in relay order and adds `total_matching` and `truncated`; it previously returned the whole matching roster. diff --git a/docs/identity.md b/docs/identity.md index 20c62178..40fb3a41 100644 --- a/docs/identity.md +++ b/docs/identity.md @@ -1274,6 +1274,187 @@ and leaves no user row. Personal and self-serve organizations need `RELAYCAST_INTERNAL_SECRET` to create their Relaycast workspace; without it they answer `503 not_ready`. +## Session bridge for organizations moved from Agent Relay Cloud + +When an organization moves from Agent Relay Cloud to this deployment, its +people still sign in to Cloud out of habit. The session bridge lets a browser +that holds a live Cloud session continue here without signing in again: +Cloud signs a short-lived, single-use assertion naming the person, and this +deployment verifies it and issues its own browser session. This deployment +never validates a Cloud session or a Cloud token; it only trusts the +assertion's signature, under keys the operator configured. + +It is off by default (`SELFHOST_CLOUD_BRIDGE_ENABLED`). While it is off, +every route below answers 404 like an unknown route. + +### Flow + +1. `GET /cloud/api/v1/auth/cloud-bridge/start?next=` (also served as + `/api/v1/auth/cloud-bridge/start`). This deployment makes a 32-byte random + nonce, stores `{nonce, next}` in the encrypted HttpOnly attempt cookie + `agent_relay_cloud_bridge` (Path `/cloud/api/v1/auth/cloud-bridge/consume`, + 5 minutes, `SameSite=None; Secure`) and redirects to + `SELFHOST_CLOUD_BRIDGE_HANDOFF_URL?nonce=`. Only the nonce goes to + Cloud. `next` must be a same-site path; anything else becomes `/`. +2. Cloud's handoff page, for a person with a live Cloud session, signs an + assertion for that nonce and auto-posts a form to + `POST /cloud/api/v1/auth/cloud-bridge/consume` with the single field + `assertion`. It must post to the `/cloud` form of the path: the attempt + cookie is only sent there. +3. This deployment checks the request and the assertion, spends it, signs the + person in, sets the usual session cookie (Path `/cloud`), clears the attempt + cookie and answers `303` to `next` (checked again as a same-site path). + +The consume request is a cross-site form post by design, so it is exempt from +this deployment's same-origin rule for its own forms. Instead its `Origin` +header must equal the origin of `SELFHOST_CLOUD_BRIDGE_HANDOFF_URL` exactly; a +missing header, `null` or any other value is refused before the assertion is +read. A handoff page served with `Referrer-Policy: no-referrer` makes +browsers send `Origin: null` on its form post, and the bridge then refuses +every sign-in: Cloud's handoff page must use a policy that keeps the origin +(for example `strict-origin-when-cross-origin`). The attempt cookie is +`SameSite=None` because a `Lax` cookie is not sent on a cross-site POST. + +### The assertion + +A compact JWS signed with Ed25519, verified with Node's own crypto. + +| Part | Rule | +| --- | --- | +| `alg` (header) | Exactly `EdDSA` | +| `typ` (header) | Exactly `cloud-bridge+jwt` | +| `kid` (header) | Required; one of the configured keys (Cloud uses the RFC 7638 thumbprint; it is compared as opaque text) | +| `crit` (header) | Refused when present | +| `iss` | Exactly `SELFHOST_CLOUD_BRIDGE_ISSUER` | +| `aud` | A string exactly equal to `SELFHOST_CLOUD_BRIDGE_AUDIENCE` (an array is refused) | +| `sub` | Required. The Cloud user id, which the import keeps as the user's id here. The only identity key: the account is never matched by email | +| `org_id` | Required. The organization being bridged into | +| `workspace_id` | Optional. Used when it names a workspace of that organization; otherwise ignored | +| `auth_time` | Required. When the person signed in to Cloud (seconds) | +| `auth_method` | Optional. Recorded in the audit row only | +| `use` | Exactly `browser` | +| `nonce` | Required. Must equal the nonce in this browser's attempt cookie | +| `jti` | Required, opaque, at most 128 characters. Single use | +| `iat`, `exp` | Required. `exp - iat` at most 120 seconds; `iat` not more than 30 seconds in the future; `exp` not more than 30 seconds in the past | +| `nbf` | Optional. Refused when more than 30 seconds in the future | +| `email` | Ignored | + +The whole assertion is capped at 4 KiB. The signature is verified before any +claim is judged. + +### What it never does + +- It creates nothing: no user, organization, membership, workspace or + invitation. The person, the organization's bridge window and the membership + must already exist. An invite or an auto-join domain that matches the + person's email does not help, and neither do the admin-email rules. +- It accepts no Cloud token or Cloud session cookie. +- It exchanges no Desktop credential, MCP OAuth grant or API token. Desktop + completes its normal browser sign-in on the bridged browser session. + +### Checks and refusals + +In order, after the assertion verified: the user exists (by `sub`), the +organization has an open bridge window, the user is a member, `auth_time` is +not older than `SELFHOST_CLOUD_BRIDGE_MAX_AUTH_AGE_SECONDS` (nor in the +future beyond the skew), and the person has not signed out here since. Then +the workspace is chosen: the `workspace_id` claim when it is the +organization's, else the person's last used workspace there, else the oldest. +The session is labelled "Browser sign-in (moved from Cloud)" and audited as +`auth.cloud_bridge.accepted` (target: `jti` and `authMethod`). The assertion's +`jti` is spent before these checks, so a refused assertion cannot be retried. + +**Signed out since.** Cloud cannot end its own session server-side, so a kept +copy of it could otherwise bridge again. Signing out of this deployment (or a +password reset or operator session removal) ends bridging for every Cloud +sign-in made before it; a new Cloud sign-in can still bridge while the +organization's window is open. Precisely: any session of the person ended at +or after `auth_time` refuses the assertion, except a session ended by a +workspace switch or by removing one Desktop MCP provider, which are not +sign-outs. + +Refusals are HTML pages with a link to `/login`. They are never cached and +always clear the attempt cookie. The page's `x-error-code` header carries the +code: + +| Code | Status | When | +| --- | --- | --- | +| `cloud_bridge_invalid` | 400 | Anything wrong with the request or the assertion: Origin, missing or expired attempt cookie, nonce mismatch, header, signature, claims, lifetime, replay | +| `cloud_bridge_user_unknown` | 403 | No user here has the `sub` id | +| `cloud_bridge_org_not_moved` | 403 | The organization has no open bridge window | +| `cloud_bridge_not_member` | 403 | The user is not a member of the organization | +| `cloud_bridge_auth_too_old` | 403 | The Cloud sign-in is older than the maximum age | +| `cloud_bridge_signed_out` | 403 | The person signed out here after that Cloud sign-in | + +A `503 not_ready` page means the installation or the organization's workspace +is not set up yet. + +Every refusal writes one log line, `cloud bridge refused`, with an internal +`reason`: `origin`, `attempt_missing`, `malformed`, `wrong_type`, `wrong_alg`, +`unknown_kid`, `bad_signature`, `wrong_issuer`, `wrong_audience`, `expired`, +`not_yet_valid`, `lifetime_too_long`, `wrong_use`, `nonce_mismatch`, +`replayed`, `user_unknown`, `org_not_moved`, `not_member`, `auth_too_old` or +`signed_out`. The line names the `kid` when it is plain base64url text, and +`sub`, `orgId` and `jti` only once the signature verified. It never holds the +assertion, any part of it, the nonce or the cookie. When the signature +verified and the organization exists here, the refusal is also audited in it +as `auth.cloud_bridge.refused` with the reason. + +**Rate limits.** Per source address: 30 starts and 30 consumes per 5 +minutes. Once the signature verified: 10 per person (`sub`) and 1,200 per +organization per 10 minutes. Over a limit, the browser gets the usual +"Too many attempts" page (429). + +### Configuration + +| Variable | | +| --- | --- | +| `SELFHOST_CLOUD_BRIDGE_ENABLED` | `true` or `false` (default); anything else fails start-up | +| `SELFHOST_CLOUD_BRIDGE_ISSUER` | Required when enabled. The exact `iss` | +| `SELFHOST_CLOUD_BRIDGE_AUDIENCE` | Required when enabled. The exact `aud` | +| `SELFHOST_CLOUD_BRIDGE_HANDOFF_URL` | Required when enabled. https (http only on localhost), no query or fragment | +| `SELFHOST_CLOUD_BRIDGE_PUBLIC_KEYS[_FILE]` | Required when enabled. JWKS with 1-4 Ed25519 public keys (`kty` `OKP`, `crv` `Ed25519`), unique `kid`s, no `d` member | +| `SELFHOST_CLOUD_BRIDGE_MAX_AUTH_AGE_SECONDS` | Optional, default `2592000` (30 days), at most `7776000` (90 days) | + +**Key rotation.** Change `SELFHOST_CLOUD_BRIDGE_PUBLIC_KEYS` and restart. It +holds up to 4 keys, so the old and new key can be listed together while +Cloud switches over; remove the old one afterwards. + +### Operator routes + +Bootstrap bearer only, like the +[installation settings](#installation-settings-kill-switches); 404 while the +bridge is off. + +- `GET /api/v1/installation/cloud-bridge/organizations` lists + `{organizations: [{organizationId, opensAt, closesAt, setBy, updatedAt}]}`. +- `PUT /api/v1/installation/cloud-bridge/organizations/{organizationId}` with + `{"closesAt": "