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
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
181 changes: 181 additions & 0 deletions docs/identity.md
Original file line number Diff line number Diff line change
Expand Up @@ -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=<path>` (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=<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": "<time>", "opensAt": "<time>", "setBy": "<who>"}` opens or
changes the window. `opensAt` defaults to now; `closesAt` must be in the
future and at most 90 days after `opensAt`; `setBy` (1-120 characters) names
who made the change, since the bootstrap bearer names no person. An unknown
organization is 404; one with no members is `409 organization_empty`.
Audited as `installation.cloud_bridge.organization_set`.
- `DELETE` on the same path removes the window (`204`; 404 when there is
none). Audited as `installation.cloud_bridge.organization_removed`.

List an organization only after its import has been applied and verified, as
part of the same operator step.

### Operations

- Cloud must end the Cloud session it vouches for when it signs the
assertion, so the person is not signed in to both.
- A reverse proxy in front of a separate dashboard host must route
`/cloud/api/v1/auth/cloud-bridge/start` and
`/cloud/api/v1/auth/cloud-bridge/consume` to this service and pass
`Set-Cookie` on the consume response.

**Removal.** The bridge is a migration tool. Once the last organization's
window has closed, set `SELFHOST_CLOUD_BRIDGE_ENABLED=false`. Its routes,
tables (`cloud_bridge_organizations`, `cloud_bridge_assertions`) and settings
can be deleted in a later release.

## Invites

Owners and admins invite people by email from Settings → Members. The API
Expand Down
5 changes: 5 additions & 0 deletions docs/repository-guide.md
Original file line number Diff line number Diff line change
Expand Up @@ -163,6 +163,11 @@ is explicit. History is served only by the sessions pipeline: see
| `SELFHOST_OIDC_ISSUER` / `SELFHOST_OIDC_CLIENT_ID` / `SELFHOST_OIDC_CLIENT_SECRET[_FILE]` | Optional OpenID Connect sign-in (Google Workspace, Okta, Entra ID, Keycloak...). Authorization code + PKCE. See [docs/identity.md](identity.md) |
| `SELFHOST_OIDC_ALLOWED_DOMAINS` / `SELFHOST_OIDC_DISPLAY_NAME` / `SELFHOST_OIDC_SCOPES` / `SELFHOST_OIDC_REDIRECT_URL` | Optional OIDC refinements: email domains allowed to sign in, button label, scopes (default `openid email profile`), and a fixed redirect URI (default `<site>/login/oidc/callback`) |
| `SELFHOST_MICROSOFT_CLIENT_ID` / `SELFHOST_MICROSOFT_CLIENT_SECRET[_FILE]` / `SELFHOST_MICROSOFT_TENANT` / `SELFHOST_MICROSOFT_REDIRECT_URL` | Optional "Continue with Microsoft" sign-in for personal Microsoft accounts (Outlook.com, Hotmail) and Entra ID work or school accounts. Client ID and secret are set together; tenant `common` (default), `consumers`, `organizations` or a tenant ID; redirect URI default `<site>/login/microsoft/callback`. Works beside `SELFHOST_OIDC_*`. See [docs/identity.md](identity.md#microsoft-accounts-outlookcom-hotmail-and-entra-id) |
| `SELFHOST_CLOUD_BRIDGE_ENABLED` | Optional, default off (`true`/`false`, anything else fails start-up). Turns on the session bridge for organizations moved from Agent Relay Cloud ([docs/identity.md](identity.md#session-bridge-for-organizations-moved-from-agent-relay-cloud)); off, no other bridge variable is read and the bridge routes answer 404 |
| `SELFHOST_CLOUD_BRIDGE_ISSUER` / `SELFHOST_CLOUD_BRIDGE_AUDIENCE` | Required when the bridge is enabled. The exact `iss` and (string) `aud` Cloud signs |
| `SELFHOST_CLOUD_BRIDGE_HANDOFF_URL` | Required when the bridge is enabled. Cloud's handoff page; https (http only on localhost), no query or fragment. Its origin is the only `Origin` the consume route accepts |
| `SELFHOST_CLOUD_BRIDGE_PUBLIC_KEYS[_FILE]` | Required when the bridge is enabled. A JWKS (`{"keys":[...]}`) of 1-4 public Ed25519 keys (`kty` `OKP`, `crv` `Ed25519`), each with a unique `kid` and no private `d` member |
| `SELFHOST_CLOUD_BRIDGE_MAX_AUTH_AGE_SECONDS` | Optional, default `2592000` (30 days), at most `7776000` (90 days). The oldest Cloud sign-in (`auth_time`) the bridge accepts |
| `SELFHOST_SMTP_HOST` / `_PORT` / `_SECURITY` / `_USERNAME` / `_PASSWORD[_FILE]`, `SELFHOST_EMAIL_FROM` | Optional SMTP for invite emails and sign-in links |
| `SELFHOST_EMAIL_LOGIN` | Optional `true`: email sign-in links (requires SMTP) |
| `SELFHOST_SIGNIN_METHODS` | Optional comma list of `email_link` and `password`. `email_link` requires SMTP; `password` does not (without SMTP only its emailed register and reset are off, answering 404 `email_not_configured`). Default: `email_link` when `SELFHOST_EMAIL_LOGIN=true`. Unlisted methods answer 404 `signin_method_disabled`. Failed password sign-ins lock per account and client (5 free, then 30 s doubling to 15 min) and per account across all clients (50 in an hour locks it for 15 min and mails the owner, at most once a day). See [docs/identity.md](identity.md#email-and-password-optional) and [Lockout](identity.md#lockout) |
Expand Down
29 changes: 29 additions & 0 deletions migrations/0083_cloud_bridge.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
-- Session bridge for organizations moved from Agent Relay Cloud
-- (docs/identity.md). Cloud signs a short-lived assertion for a browser that
-- holds a live Cloud session; Control turns it into its own browser session,
-- but only for an organization the operator has listed here, for a bounded
-- window, after its import was applied and verified.

-- One bridge window per organization. set_by is the operator-declared label
-- of who opened or last changed the window: the bootstrap credential that
-- writes these rows carries no person identity of its own.
CREATE TABLE IF NOT EXISTS cloud_bridge_organizations (
organization_id uuid PRIMARY KEY REFERENCES organizations(id) ON DELETE CASCADE,
opens_at timestamptz NOT NULL DEFAULT now(),
closes_at timestamptz NOT NULL,
set_by text NOT NULL,
created_at timestamptz NOT NULL DEFAULT now(),
updated_at timestamptz NOT NULL DEFAULT now(),
CHECK (closes_at > opens_at)
);

-- Spent assertion ids. An assertion is single use: its jti is inserted
-- before the sign-in and a second insert of the same jti is a replay. Rows
-- are kept until shortly after the assertion could no longer verify anyway,
-- then swept.
CREATE TABLE IF NOT EXISTS cloud_bridge_assertions (
jti text PRIMARY KEY,
expires_at timestamptz NOT NULL
);
CREATE INDEX IF NOT EXISTS cloud_bridge_assertions_expires_at
ON cloud_bridge_assertions (expires_at);
Loading
Loading