diff --git a/CHANGELOG.md b/CHANGELOG.md index 7aa84d47..d0bdbd8c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,6 +5,7 @@ assigned at release. ## Unreleased +- Added: per-device person messaging credentials. `POST /api/v1/workspaces/{id}/messaging/identity/credential` now mints each signed-in device its own 12 hour Relaycast device token for the person's agent (`POST /v1/agents/{name}/device-tokens`, workspace key) instead of handing out the agent's shared token, and answers with `device` (`{id, name, kind}`, derived from the server-side session only, with the name as Relaycast returns it; an answer naming another device id or kind is `502`) and `expiresAt`. Tokens are stored encrypted in `person_device_credentials` (migration 0081), probed on every serve, re-minted inside one hour of expiry or when refused, and revoked at Relaycast when their sign-in ends (on sign-out, which waits at most 5 seconds for Relaycast, else by a sweep on messaging requests; the expiry is the backstop). Device rows are deleted with their sign-in; a removed member's tokens end with the person agent. An optional body `{"refusedTokenSha256": "<64 lowercase hex>"}` forces a re-mint when it matches the stored token, at most once per device per 30 seconds (`429 rate_limited` inside the window; `Retry-After` is sent but clients must not depend on it, the hosted route sends none). A null or absent value changes nothing and other keys are ignored; only invalid JSON, a non-object body or a malformed hash (uppercase included) is `400 invalid_request`. A device revoked while its sign-in still authenticates answers `403 device_revoked` (no Control route produces this today; it matches the hosted service). A sign-in or membership that ends mid-mint answers `401` for a bearer device (`403` for the web device) and the minted token is revoked upstream. Mints take the same per-person lock as identity registration, recovery and member revocation, and re-check the sign-in and membership after the token is saved. A relay node token minted with a device token ends with that device token, so clients mint it again after a renewal. Desktop handoff tokens get `403 handoff_not_exchanged` / `403 handoff_not_capable`. Against a Relaycast without the device-token route (its exact `404 not_found` "Route not found" answer, agent confirmed) the shared token is served in the old shape and the fallback is logged. See docs/identity.md, "Person messaging credential". - 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` reports whether Amp returned more than the first 100 threads. - 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..786f9309 100644 --- a/docs/identity.md +++ b/docs/identity.md @@ -1411,6 +1411,112 @@ capability scope: Membership is checked live on every request and mint, so removing a person from an organization takes effect on their next request. +### Person messaging credential + +`POST /api/v1/workspaces/{id}/messaging/identity/credential` (scope +`cli:auth` or the browser session) hands the caller a Relaycast token for the +person's own human agent. Each signed-in device gets its own device token for +that one agent, minted with the workspace key +(`POST /v1/agents/{name}/device-tokens`). The agent's shared token never +leaves Control while Relaycast serves device tokens. + +- The device comes from the server-side session only; the client cannot name + it (device fields in the body are ignored). The browser session (the `/cloud` + cookie) is the device `{id: "web", name: "web", kind: "web"}`, bound to no + sign-in. A bearer is its + own sign-in's device: kind `desktop` when the session carries a Desktop host + name (the handoff consent or an enrollment key exchange), otherwise `cli`. + The name is that host name with control and bidirectional formatting + characters removed, cut to 80 UTF-16 units on a grapheme boundary, or the + kind when empty. The id is `-`: lowercase `[a-z0-9-]`, at most 64 characters, never + Relaycast's reserved `unknown` or `direct`. The session id survives a token + refresh, so a refreshed sign-in keeps its device and token. +- Every mint asks for a 12 hour TTL (`ttl_seconds: 43200`) and sends the + expected `agent_id`; an answer naming another agent, or another device id + or kind, is refused. Relaycast cleans the device name it records (control + characters to spaces, whitespace collapsed, trimmed, at most 80 + characters), so the name stored and served is the one in its answer. The + stored expiry is the earlier of Relaycast's `expires_at` and now + 12 hours. +- The answer is + `{identity: {name, agentId, token, relaycastUrl, device: {id, name, kind}, expiresAt}}`. + A stored token is served again while it is more than one hour from expiry + and Relaycast still accepts it (`GET /v1/agent` with the token, on every + request, never cached). A refused token is re-minted. While Relaycast is + unreachable the stored token is served as long as it is unexpired. A probe + answered `403 device_token_forbidden` is a `502`, never a re-mint. +- The request body is optional and read the same way as on the hosted + service, so one client works against both. No body, a JSON object without + `refusedTokenSha256`, or `"refusedTokenSha256": null` changes nothing; + other keys are ignored. A client that saw its token refused may send + `{"refusedTokenSha256": "<64 lowercase hex>"}`, the SHA-256 of that token. + When it matches the stored token (compared in constant time; neither the + hash nor the token is logged) the stored token is dropped without a probe + and a new one minted, at most once per device every 30 seconds, measured + from the stored token's `minted_at` by the database clock so every replica + agrees. Inside that window the answer is `429 rate_limited`. Control also + sends `Retry-After` (seconds), but clients must not depend on it: the + hosted route sends none. A hash that does not match takes the normal path + (probe, no forced mint). A body that is not JSON or not an object, or a + `refusedTokenSha256` that is not 64 lowercase hex (uppercase included), is + `400 invalid_request`. The shared-token fallback below ignores the field. +- A device row revoked while its sign-in still authenticates answers + `403 device_revoked`; sign in again for a new device. No Control route + leaves a row in that state today; the answer exists so clients handle the + same code as on the hosted service. The web device is bound to no sign-in, + so a new browser request mints it again. +- Mints, sweeps of revoked device tokens, the person agent's registration, + takeover and recovery, and member revocation take the same per-person + advisory lock, so a mint never interleaves with a recovery or a removal. + After a minted token is saved, the mint re-checks in the same transaction + that the sign-in is live and the person is still a member; if not, the row + is revoked and the token revoked upstream (or left to the sweep). A sign-in + row deleted while the mint was in flight leaves the token recorded with no + sign-in, already revoked, for the same upstream revoke. +- A device token is never presented to Relaycast's token rotation, recovery + or upgrade routes; recovery uses the workspace key and the shared token. + Relaycast refuses device tokens there with `403 device_token_forbidden`, + which Control treats as an error, never as a refused token to re-mint. +- A relay node token minted with a device token ends when that device token + is revoked, renewed or expires, or when the person agent is taken over. A + client mints its node token again after it receives a renewed device token. +- A mint refused with `404 agent_not_found` or `409 agent_identity_conflict` + recovers the person agent once (the same recovery as a refused shared + token, which ends every device token of the agent) and mints again. Any + other refusal, including `400` and `409 not_a_person_agent`, answers + `502 upstream_unavailable`. +- Tokens are stored encrypted in `person_device_credentials` (migration + 0082), one row per workspace, person and device. A device row is deleted + with its sign-in row. Ending a sign-in (sign-out, workspace switch, + revoke-all, API token or Desktop credential revocation) revokes its rows in + the same transaction; revoke-all also revokes the web row. Relaycast is told + with `DELETE /v1/agents/{name}/device-tokens/{device}` (a `404` means + already gone) right after sign-out, which waits at most 5 seconds for it, + and by a bounded sweep on every messaging request until it confirms. A + token Relaycast never hears about still ends at its 12 hour expiry. +- Removing a membership deletes the person's sign-in rows, and with them + their device rows. Their device tokens end because member revocation + deletes the person agent at Relaycast, not by per-device revokes. +- A bearer sign-in that ends while its token is being minted answers `401`, + including when the membership is removed (the sign-in goes with it). The + web device is bound to no sign-in, so for it a membership removed during + the mint answers `403`. Either way the minted token is revoked upstream at + once, or by the sweep if that fails. +- A Desktop browser handoff token never holds a messaging credential: before + its PKCE exchange it answers `403 handoff_not_exchanged`, after it + `403 handoff_not_capable`. The session the exchange issues is the device. +- A Relaycast release without device tokens is detected only by its own + missing-route answer to the mint (`404` with code `not_found` and message + `Route not found`) while a workspace-key lookup still finds the person's + agent under the expected id. Control then answers with the shared person + token in the old shape (`{name, agentId, token, relaycastUrl}`, no `device` + or `expiresAt`) and logs + `[selfhost-api] messaging device credential fallback: Relaycast has no device-token route` + with `workspaceId` and `deviceKind`. Any other answer is not a missing + route. + +Gate-only installs answer `403 gate_only` instead (below). + ### Gate-only installs (relaygate) On a gate-only install, relaygate is the only public way into Relaycast and diff --git a/migrations/0082_person_device_credentials.sql b/migrations/0082_person_device_credentials.sql new file mode 100644 index 00000000..f303450e --- /dev/null +++ b/migrations/0082_person_device_credentials.sql @@ -0,0 +1,44 @@ +-- Per-device person messaging credentials (docs/identity.md, "Person messaging credential"): each signed-in +-- device of a person gets its own device-scoped Relaycast token for the person's human agent, minted with the +-- workspace key. One row per (workspace, person, device); the token is encrypted with the keyring like +-- person_identities.token_ciphertext. A row is served only while it is not revoked, still names the person's +-- current agent on the workspace's current Relaycast workspace, and is outside the renewal margin of expires_at. +CREATE TABLE IF NOT EXISTS person_device_credentials ( + id uuid PRIMARY KEY, + workspace_id uuid NOT NULL REFERENCES workspaces(id) ON DELETE CASCADE, + user_id uuid NOT NULL REFERENCES users(id) ON DELETE CASCADE, + -- Derived server-side: `web` for the browser session, otherwise `-<8 hex of the sign-in>`. + device_id text NOT NULL, + device_name text NOT NULL, + device_kind text NOT NULL CHECK (device_kind IN ('desktop', 'cli', 'web')), + -- The sign-in session the token belongs to; NULL for the web device. Session rows are never deleted by the + -- application (sign-out sets revoked_at), so the cascade only fires with the user, membership or workspace. + session_id uuid REFERENCES token_sessions(id) ON DELETE CASCADE, + relaycast_workspace_id text NOT NULL, + -- The person agent the token was minted for; agent_name is the path segment the upstream revoke addresses. + agent_name text NOT NULL, + agent_remote_id text NOT NULL, + token_ciphertext text NOT NULL, + expires_at timestamptz NOT NULL, + -- When the stored token was minted. A client report of a refused token forces at most one mint per device per + -- 30 seconds, decided against this column so every replica agrees. + minted_at timestamptz NOT NULL DEFAULT now(), + -- Set in the same transaction that ends the sign-in session, removes the member or abandons a mint. + revoked_at timestamptz, + -- Set once Relaycast confirmed the device token is gone (revoked, or 404), or when the agent itself was deleted. + upstream_revoked_at timestamptz, + created_at timestamptz NOT NULL DEFAULT now(), + updated_at timestamptz NOT NULL DEFAULT now(), + UNIQUE (workspace_id, user_id, device_id) +); + +-- Ending a sign-in session revokes the live rows bound to it. +CREATE INDEX IF NOT EXISTS person_device_credentials_live_session_idx + ON person_device_credentials (session_id) + WHERE revoked_at IS NULL; + +-- The upstream revocation sweep reads revoked rows Relaycast has not confirmed yet, least recently tried first +-- (a failed attempt moves updated_at), so one unreachable Relaycast workspace cannot hold up the rest. +CREATE INDEX IF NOT EXISTS person_device_credentials_upstream_pending_idx + ON person_device_credentials (updated_at) + WHERE revoked_at IS NOT NULL AND upstream_revoked_at IS NULL; diff --git a/scripts/cloud-import-verify/schema-manifest.json b/scripts/cloud-import-verify/schema-manifest.json index f7abf9b5..eb5d9fbd 100644 --- a/scripts/cloud-import-verify/schema-manifest.json +++ b/scripts/cloud-import-verify/schema-manifest.json @@ -83,7 +83,8 @@ {"name":"0078_events_shim_claim_leases.sql","sha256":"1729204ca96b4196d16369b039b72c70b43ae6036c955d06e89f2f168d6d4b7a"}, {"name":"0079_hosted_relay_gate.sql","sha256":"c9b201ff87a00dc9bf06cb304e46673556e47153343a68edf8d557029b988af1"}, {"name":"0080_staff_read_grants_year_cap.sql","sha256":"86d678003039015d447a4d3461830082d0a3bf03a578ece20526ccf763e4f562"}, - {"name":"0081_cursor_cloud_identity.sql","sha256":"4b8bd4a7e758708db798f953fe50b0f225ca1db17e841a490ce363940c4a949c"} + {"name":"0081_cursor_cloud_identity.sql","sha256":"4b8bd4a7e758708db798f953fe50b0f225ca1db17e841a490ce363940c4a949c"}, + {"name":"0082_person_device_credentials.sql","sha256":"e1dfd45b9ec6f157fcddabb4a51b81d04ab3af8e7539f6f31cd8dc8b2dcb271d"} ], "required":[ {"kind":"column","name":"public.admin_audit_events.action","definition":{"collation":"pg_catalog.default","default":null,"generated":"","identity":"","not_null":true,"position":6,"type":"text"}}, @@ -794,6 +795,23 @@ {"kind":"column","name":"public.password_setup_tokens.id","definition":{"collation":null,"default":null,"generated":"","identity":"","not_null":true,"position":1,"type":"uuid"}}, {"kind":"column","name":"public.password_setup_tokens.invite_token_hash","definition":{"collation":"pg_catalog.default","default":null,"generated":"","identity":"","not_null":false,"position":4,"type":"text"}}, {"kind":"column","name":"public.password_setup_tokens.token_hash","definition":{"collation":"pg_catalog.default","default":null,"generated":"","identity":"","not_null":true,"position":3,"type":"text"}}, + {"kind":"column","name":"public.person_device_credentials.agent_name","definition":{"collation":"pg_catalog.default","default":null,"generated":"","identity":"","not_null":true,"position":9,"type":"text"}}, + {"kind":"column","name":"public.person_device_credentials.agent_remote_id","definition":{"collation":"pg_catalog.default","default":null,"generated":"","identity":"","not_null":true,"position":10,"type":"text"}}, + {"kind":"column","name":"public.person_device_credentials.created_at","definition":{"collation":null,"default":"now()","generated":"","identity":"","not_null":true,"position":16,"type":"timestamp with time zone"}}, + {"kind":"column","name":"public.person_device_credentials.device_id","definition":{"collation":"pg_catalog.default","default":null,"generated":"","identity":"","not_null":true,"position":4,"type":"text"}}, + {"kind":"column","name":"public.person_device_credentials.device_kind","definition":{"collation":"pg_catalog.default","default":null,"generated":"","identity":"","not_null":true,"position":6,"type":"text"}}, + {"kind":"column","name":"public.person_device_credentials.device_name","definition":{"collation":"pg_catalog.default","default":null,"generated":"","identity":"","not_null":true,"position":5,"type":"text"}}, + {"kind":"column","name":"public.person_device_credentials.expires_at","definition":{"collation":null,"default":null,"generated":"","identity":"","not_null":true,"position":12,"type":"timestamp with time zone"}}, + {"kind":"column","name":"public.person_device_credentials.id","definition":{"collation":null,"default":null,"generated":"","identity":"","not_null":true,"position":1,"type":"uuid"}}, + {"kind":"column","name":"public.person_device_credentials.minted_at","definition":{"collation":null,"default":"now()","generated":"","identity":"","not_null":true,"position":13,"type":"timestamp with time zone"}}, + {"kind":"column","name":"public.person_device_credentials.relaycast_workspace_id","definition":{"collation":"pg_catalog.default","default":null,"generated":"","identity":"","not_null":true,"position":8,"type":"text"}}, + {"kind":"column","name":"public.person_device_credentials.revoked_at","definition":{"collation":null,"default":null,"generated":"","identity":"","not_null":false,"position":14,"type":"timestamp with time zone"}}, + {"kind":"column","name":"public.person_device_credentials.session_id","definition":{"collation":null,"default":null,"generated":"","identity":"","not_null":false,"position":7,"type":"uuid"}}, + {"kind":"column","name":"public.person_device_credentials.token_ciphertext","definition":{"collation":"pg_catalog.default","default":null,"generated":"","identity":"","not_null":true,"position":11,"type":"text"}}, + {"kind":"column","name":"public.person_device_credentials.updated_at","definition":{"collation":null,"default":"now()","generated":"","identity":"","not_null":true,"position":17,"type":"timestamp with time zone"}}, + {"kind":"column","name":"public.person_device_credentials.upstream_revoked_at","definition":{"collation":null,"default":null,"generated":"","identity":"","not_null":false,"position":15,"type":"timestamp with time zone"}}, + {"kind":"column","name":"public.person_device_credentials.user_id","definition":{"collation":null,"default":null,"generated":"","identity":"","not_null":true,"position":3,"type":"uuid"}}, + {"kind":"column","name":"public.person_device_credentials.workspace_id","definition":{"collation":null,"default":null,"generated":"","identity":"","not_null":true,"position":2,"type":"uuid"}}, {"kind":"column","name":"public.person_identities.agent_name","definition":{"collation":"pg_catalog.default","default":null,"generated":"","identity":"","not_null":true,"position":4,"type":"text"}}, {"kind":"column","name":"public.person_identities.agent_remote_id","definition":{"collation":"pg_catalog.default","default":null,"generated":"","identity":"","not_null":true,"position":5,"type":"text"}}, {"kind":"column","name":"public.person_identities.created_at","definition":{"collation":null,"default":"now()","generated":"","identity":"","not_null":true,"position":7,"type":"timestamp with time zone"}}, @@ -1579,6 +1597,12 @@ {"kind":"constraint","name":"public.password_setup_tokens.password_setup_tokens_email_normalized","definition":{"deferrable":false,"deferred":false,"definition":"CHECK ((email = lower(email)))","no_inherit":false,"triggers":[],"type":"c","validated":true}}, {"kind":"constraint","name":"public.password_setup_tokens.password_setup_tokens_pkey","definition":{"deferrable":false,"deferred":false,"definition":"PRIMARY KEY (id)","no_inherit":true,"triggers":[],"type":"p","validated":true}}, {"kind":"constraint","name":"public.password_setup_tokens.password_setup_tokens_token_hash_key","definition":{"deferrable":false,"deferred":false,"definition":"UNIQUE (token_hash)","no_inherit":true,"triggers":[],"type":"u","validated":true}}, + {"kind":"constraint","name":"public.person_device_credentials.person_device_credentials_device_kind_check","definition":{"deferrable":false,"deferred":false,"definition":"CHECK ((device_kind = ANY (ARRAY['desktop'::text, 'cli'::text, 'web'::text])))","no_inherit":false,"triggers":[],"type":"c","validated":true}}, + {"kind":"constraint","name":"public.person_device_credentials.person_device_credentials_pkey","definition":{"deferrable":false,"deferred":false,"definition":"PRIMARY KEY (id)","no_inherit":true,"triggers":[],"type":"p","validated":true}}, + {"kind":"constraint","name":"public.person_device_credentials.person_device_credentials_session_id_fkey","definition":{"deferrable":false,"deferred":false,"definition":"FOREIGN KEY (session_id) REFERENCES token_sessions(id) ON DELETE CASCADE","no_inherit":true,"triggers":[{"deferrable":false,"deferred":false,"enabled":"O","function":"pg_catalog.RI_FKey_check_ins","table":"public.person_device_credentials","type":5},{"deferrable":false,"deferred":false,"enabled":"O","function":"pg_catalog.RI_FKey_check_upd","table":"public.person_device_credentials","type":17},{"deferrable":false,"deferred":false,"enabled":"O","function":"pg_catalog.RI_FKey_cascade_del","table":"public.token_sessions","type":9},{"deferrable":false,"deferred":false,"enabled":"O","function":"pg_catalog.RI_FKey_noaction_upd","table":"public.token_sessions","type":17}],"type":"f","validated":true}}, + {"kind":"constraint","name":"public.person_device_credentials.person_device_credentials_user_id_fkey","definition":{"deferrable":false,"deferred":false,"definition":"FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE","no_inherit":true,"triggers":[{"deferrable":false,"deferred":false,"enabled":"O","function":"pg_catalog.RI_FKey_check_ins","table":"public.person_device_credentials","type":5},{"deferrable":false,"deferred":false,"enabled":"O","function":"pg_catalog.RI_FKey_check_upd","table":"public.person_device_credentials","type":17},{"deferrable":false,"deferred":false,"enabled":"O","function":"pg_catalog.RI_FKey_cascade_del","table":"public.users","type":9},{"deferrable":false,"deferred":false,"enabled":"O","function":"pg_catalog.RI_FKey_noaction_upd","table":"public.users","type":17}],"type":"f","validated":true}}, + {"kind":"constraint","name":"public.person_device_credentials.person_device_credentials_workspace_id_fkey","definition":{"deferrable":false,"deferred":false,"definition":"FOREIGN KEY (workspace_id) REFERENCES workspaces(id) ON DELETE CASCADE","no_inherit":true,"triggers":[{"deferrable":false,"deferred":false,"enabled":"O","function":"pg_catalog.RI_FKey_check_ins","table":"public.person_device_credentials","type":5},{"deferrable":false,"deferred":false,"enabled":"O","function":"pg_catalog.RI_FKey_check_upd","table":"public.person_device_credentials","type":17},{"deferrable":false,"deferred":false,"enabled":"O","function":"pg_catalog.RI_FKey_cascade_del","table":"public.workspaces","type":9},{"deferrable":false,"deferred":false,"enabled":"O","function":"pg_catalog.RI_FKey_noaction_upd","table":"public.workspaces","type":17}],"type":"f","validated":true}}, + {"kind":"constraint","name":"public.person_device_credentials.person_device_credentials_workspace_id_user_id_device_id_key","definition":{"deferrable":false,"deferred":false,"definition":"UNIQUE (workspace_id, user_id, device_id)","no_inherit":true,"triggers":[],"type":"u","validated":true}}, {"kind":"constraint","name":"public.person_identities.person_identities_pkey","definition":{"deferrable":false,"deferred":false,"definition":"PRIMARY KEY (id)","no_inherit":true,"triggers":[],"type":"p","validated":true}}, {"kind":"constraint","name":"public.person_identities.person_identities_user_id_fkey","definition":{"deferrable":false,"deferred":false,"definition":"FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE","no_inherit":true,"triggers":[{"deferrable":false,"deferred":false,"enabled":"O","function":"pg_catalog.RI_FKey_check_ins","table":"public.person_identities","type":5},{"deferrable":false,"deferred":false,"enabled":"O","function":"pg_catalog.RI_FKey_check_upd","table":"public.person_identities","type":17},{"deferrable":false,"deferred":false,"enabled":"O","function":"pg_catalog.RI_FKey_cascade_del","table":"public.users","type":9},{"deferrable":false,"deferred":false,"enabled":"O","function":"pg_catalog.RI_FKey_noaction_upd","table":"public.users","type":17}],"type":"f","validated":true}}, {"kind":"constraint","name":"public.person_identities.person_identities_workspace_id_agent_name_key","definition":{"deferrable":false,"deferred":false,"definition":"UNIQUE (workspace_id, agent_name)","no_inherit":true,"triggers":[],"type":"u","validated":true}}, @@ -1949,6 +1973,10 @@ {"kind":"index","name":"public.password_setup_tokens.password_setup_tokens_email_idx","definition":{"definition":"CREATE INDEX password_setup_tokens_email_idx ON public.password_setup_tokens USING btree (email) WHERE (consumed_at IS NULL)","live":true,"nulls_not_distinct":false,"primary":false,"ready":true,"unique":false,"valid":true}}, {"kind":"index","name":"public.password_setup_tokens.password_setup_tokens_pkey","definition":{"definition":"CREATE UNIQUE INDEX password_setup_tokens_pkey ON public.password_setup_tokens USING btree (id)","live":true,"nulls_not_distinct":false,"primary":true,"ready":true,"unique":true,"valid":true}}, {"kind":"index","name":"public.password_setup_tokens.password_setup_tokens_token_hash_key","definition":{"definition":"CREATE UNIQUE INDEX password_setup_tokens_token_hash_key ON public.password_setup_tokens USING btree (token_hash)","live":true,"nulls_not_distinct":false,"primary":false,"ready":true,"unique":true,"valid":true}}, + {"kind":"index","name":"public.person_device_credentials.person_device_credentials_live_session_idx","definition":{"definition":"CREATE INDEX person_device_credentials_live_session_idx ON public.person_device_credentials USING btree (session_id) WHERE (revoked_at IS NULL)","live":true,"nulls_not_distinct":false,"primary":false,"ready":true,"unique":false,"valid":true}}, + {"kind":"index","name":"public.person_device_credentials.person_device_credentials_pkey","definition":{"definition":"CREATE UNIQUE INDEX person_device_credentials_pkey ON public.person_device_credentials USING btree (id)","live":true,"nulls_not_distinct":false,"primary":true,"ready":true,"unique":true,"valid":true}}, + {"kind":"index","name":"public.person_device_credentials.person_device_credentials_upstream_pending_idx","definition":{"definition":"CREATE INDEX person_device_credentials_upstream_pending_idx ON public.person_device_credentials USING btree (updated_at) WHERE ((revoked_at IS NOT NULL) AND (upstream_revoked_at IS NULL))","live":true,"nulls_not_distinct":false,"primary":false,"ready":true,"unique":false,"valid":true}}, + {"kind":"index","name":"public.person_device_credentials.person_device_credentials_workspace_id_user_id_device_id_key","definition":{"definition":"CREATE UNIQUE INDEX person_device_credentials_workspace_id_user_id_device_id_key ON public.person_device_credentials USING btree (workspace_id, user_id, device_id)","live":true,"nulls_not_distinct":false,"primary":false,"ready":true,"unique":true,"valid":true}}, {"kind":"index","name":"public.person_identities.person_identities_pkey","definition":{"definition":"CREATE UNIQUE INDEX person_identities_pkey ON public.person_identities USING btree (id)","live":true,"nulls_not_distinct":false,"primary":true,"ready":true,"unique":true,"valid":true}}, {"kind":"index","name":"public.person_identities.person_identities_workspace_id_agent_name_key","definition":{"definition":"CREATE UNIQUE INDEX person_identities_workspace_id_agent_name_key ON public.person_identities USING btree (workspace_id, agent_name)","live":true,"nulls_not_distinct":false,"primary":false,"ready":true,"unique":true,"valid":true}}, {"kind":"index","name":"public.person_identities.person_identities_workspace_id_user_id_key","definition":{"definition":"CREATE UNIQUE INDEX person_identities_workspace_id_user_id_key ON public.person_identities USING btree (workspace_id, user_id)","live":true,"nulls_not_distinct":false,"primary":false,"ready":true,"unique":true,"valid":true}}, @@ -2121,6 +2149,7 @@ {"kind":"table","name":"public.password_registrations","definition":{"force_row_security":false,"kind":"r","row_security":false}}, {"kind":"table","name":"public.password_reset_tokens","definition":{"force_row_security":false,"kind":"r","row_security":false}}, {"kind":"table","name":"public.password_setup_tokens","definition":{"force_row_security":false,"kind":"r","row_security":false}}, + {"kind":"table","name":"public.person_device_credentials","definition":{"force_row_security":false,"kind":"r","row_security":false}}, {"kind":"table","name":"public.person_identities","definition":{"force_row_security":false,"kind":"r","row_security":false}}, {"kind":"table","name":"public.person_messages","definition":{"force_row_security":false,"kind":"r","row_security":false}}, {"kind":"table","name":"public.person_revocations","definition":{"force_row_security":false,"kind":"r","row_security":false}}, @@ -2168,5 +2197,5 @@ "optional":{ }, - "sha256":"a84f62943bd06f7c9879f13a303ffedbc4e702f64b3a4294ac8d87eeade8bbd5" + "sha256":"f5c0ed2360f83251115103a0c4f86b4045abf2bc199cdeaed76bdeb70b56d73d" } diff --git a/src/admin/api-tokens.ts b/src/admin/api-tokens.ts index fb042eb2..bda525d5 100644 --- a/src/admin/api-tokens.ts +++ b/src/admin/api-tokens.ts @@ -3,7 +3,7 @@ import type { Database, SqlExecutor } from "../database.js"; import { hashSecret, opaqueToken } from "../crypto.js"; import { normalizedOrigin } from "../auth/introspect.js"; import { normalizeEmailAddress } from "../identity/config.js"; -import { NODE_ID_PATTERN } from "../store.js"; +import { NODE_ID_PATTERN, revokeSessionDeviceCredentials } from "../store.js"; import { lockIdentity, lockOrganization } from "../tenancy.js"; import { iso, recordAudit, type AuditActor } from "./audit.js"; @@ -1155,6 +1155,7 @@ export class ApiTokenStore { RETURNING id`, [input.tokenId], ); + await revokeSessionDeviceCredentials(tx, sessions.rows.map((row) => row.id)); target = `${input.tokenId} (desktop-enrollment: user ${revoked.user_id}) sessions=${sessions.rows.length}`; } if (input.reason) target = `${target} reason=${input.reason}`; diff --git a/src/app.ts b/src/app.ts index 9162f29e..ff5d1883 100644 --- a/src/app.ts +++ b/src/app.ts @@ -96,6 +96,7 @@ import { } from "./admin/staff-read-grants.js"; import type { TelemetryModule } from "./telemetry/module.js"; import { identityErrorResponse, type IdentityModule } from "./identity/routes.js"; +import { SIGN_OUT_REVOKE_TIMEOUT_MS, sweepDeviceRevocations } from "./messaging/device-credentials.js"; import { revokeRemovedMember, type MessagingDeps } from "./messaging/identity.js"; import { createMessagingHandler, MessagingHttpError } from "./messaging/routes.js"; import { isBindingOwnedIdentity } from "./messaging/binding-identities.js"; @@ -483,7 +484,8 @@ export function createApp(input: { now?: () => Date; /** Test hooks for claim leases and crash injection. Production leaves this unset. */ messaging?: Pick; + "claimLeaseMs" | "beforeDispatch" | "afterUpstream" | "afterRemoteRegister" | "afterIdentityStaged" | "beforeMembershipRecheck" + | "beforeDeviceSave" | "afterDeviceMint" | "signOutRevokeTimeoutMs" | "warn">; }): AppHandler { const { config, store, admin, telemetry, identity } = input; const features = input.features ?? NO_FEATURES; @@ -2182,6 +2184,11 @@ setTimeout(poll,${Math.max(1, started.intervalSeconds) * 1_000}); : bearer(request); if (!token) throw new HttpError(400, "invalid_request", "token is required"); if (!await store.revoke(token)) throw new HttpError(404, "token_not_found", "Token not found"); + // Best effort and bounded: the ended sign-in's device token is revoked + // at Relaycast now when it can be; otherwise the messaging sweep and the + // token's own expiry end it. + const signal = AbortSignal.timeout(messagingDeps.signOutRevokeTimeoutMs ?? SIGN_OUT_REVOKE_TIMEOUT_MS); + await sweepDeviceRevocations(messagingDeps, undefined, { signal }).catch(() => undefined); json(response, 200, { revoked: true }, true); return; } diff --git a/src/auth/desktop-mcp-credentials.ts b/src/auth/desktop-mcp-credentials.ts index d8bc28fe..23086583 100644 --- a/src/auth/desktop-mcp-credentials.ts +++ b/src/auth/desktop-mcp-credentials.ts @@ -1,7 +1,7 @@ import { randomUUID } from "node:crypto"; import type { Database, SqlExecutor } from "../database.js"; import { hashSecret, opaqueToken } from "../crypto.js"; -import type { Principal } from "../store.js"; +import { revokeSessionDeviceCredentials, type Principal } from "../store.js"; /** * Desktop-provider MCP credentials, ported from Cloud's @@ -301,6 +301,7 @@ export class DesktopMcpCredentials { WHERE id = $1 AND revoked_at IS NULL`, [tokenId.toLowerCase()], ); + await revokeSessionDeviceCredentials(tx, [tokenId.toLowerCase()]); }); } diff --git a/src/control-tables.ts b/src/control-tables.ts index 90a1a19a..9a1fc213 100644 --- a/src/control-tables.ts +++ b/src/control-tables.ts @@ -71,6 +71,7 @@ export const CONTROL_TABLES: readonly string[] = [ "password_registrations", "password_reset_tokens", "password_setup_tokens", + "person_device_credentials", "person_identities", "person_messages", "person_revocations", diff --git a/src/messaging/device-credentials.ts b/src/messaging/device-credentials.ts new file mode 100644 index 00000000..9c7d7bac --- /dev/null +++ b/src/messaging/device-credentials.ts @@ -0,0 +1,592 @@ +import { createHash, randomUUID, timingSafeEqual } from "node:crypto"; +import { decryptSecret, encryptSecret } from "../crypto.js"; +import type { SqlExecutor } from "../database.js"; +import type { Principal } from "../store.js"; +import { MessagingHttpError } from "./http.js"; +import { + client, + isMember, + personLockKey, + recoverPersonIdentity, + slug, + withLock, + type MessagingDeps, + type PersonAccess, + type PersonIdentity, +} from "./identity.js"; +import { RelaycastCallError, type DeviceTokenDevice } from "./relaycast.js"; + +/** Lifetime asked for every device token; Relaycast accepts 60..2592000 seconds. */ +export const DEVICE_TOKEN_TTL_SECONDS = 12 * 60 * 60; +/** A stored device token this close to its expiry is re-minted instead of served. */ +export const DEVICE_TOKEN_RENEW_MARGIN_MS = 60 * 60 * 1000; +/** A client report of a refused token forces at most one mint per device in this window. */ +export const FORCED_MINT_INTERVAL_SECONDS = 30; +/** Upstream device-token revocations attempted per sweep. */ +const SWEEP_BATCH = 10; +const MAX_DEVICE_NAME_UNITS = 80; +const MAX_DEVICE_ID_SLUG = 32; +/** Relaycast's device id rule. */ +const DEVICE_ID = /^[a-z0-9-]{1,64}$/; +/** Device ids Relaycast reserves for its own bookkeeping. */ +const RESERVED_DEVICE_IDS = new Set(["unknown", "direct"]); + +/** The browser session's device. It is bound to no sign-in session. */ +export const WEB_DEVICE: DeviceTokenDevice = { id: "web", name: "web", kind: "web" }; + +export type DeviceCredential = + | { kind: "device"; identity: PersonIdentity; device: DeviceTokenDevice; token: string; expiresAt: Date } + /** Relaycast has no device-token route: the person's shared token, without a device. */ + | { kind: "shared"; identity: PersonIdentity }; + +type DeviceRow = { + id: string; + device_name: string; + session_id: string | null; + relaycast_workspace_id: string; + agent_name: string; + agent_remote_id: string; + token_ciphertext: string; + expires_at: Date | string; + revoked_at: Date | string | null; + /** Whole seconds until a forced mint is allowed again, by the database clock; 0 or less when it is allowed. */ + forced_mint_wait: number; +}; + +/** A device token with the device as Relaycast recorded it (its cleaned name). */ +type StoredToken = { token: string; expiresAt: Date; device: DeviceTokenDevice }; + +/** Bound on the upstream device-token revokes a sign-out waits for. */ +export const SIGN_OUT_REVOKE_TIMEOUT_MS = 5_000; + +const REFUSED_TOKEN_SHA256 = /^[0-9a-f]{64}$/; + +/** 429 for a forced mint inside FORCED_MINT_INTERVAL_SECONDS; the route sends Retry-After. */ +export class DeviceMintRateLimited extends MessagingHttpError { + constructor(readonly retryAfterSeconds: number) { + super(429, "rate_limited", "A new credential was issued for this device moments ago. Try again shortly."); + this.name = "DeviceMintRateLimited"; + } +} + +function deviceRevoked(): MessagingHttpError { + return new MessagingHttpError(403, "device_revoked", "This device's messaging credential was revoked. Sign in again."); +} + +/** + * The optional credential request body, read the same way as the hosted + * route so one client works against both: no body, or a JSON object whose + * optional `refusedTokenSha256` is the 64 lowercase hex SHA-256 of the token + * the client saw refused (absent or null: no report). Other keys are ignored; + * the device never comes from the body. Invalid JSON, a non-object body or a + * malformed hash is 400 invalid_request. + */ +export function parseCredentialRequest(raw: string): { refusedTokenSha256: string | null } { + if (!raw.trim()) return { refusedTokenSha256: null }; + let parsed: unknown; + try { + parsed = JSON.parse(raw); + } catch { + throw new MessagingHttpError(400, "invalid_request", "Body must be valid JSON"); + } + if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) { + throw new MessagingHttpError(400, "invalid_request", "Body must be a JSON object"); + } + const value = (parsed as Record).refusedTokenSha256; + if (value === undefined || value === null) return { refusedTokenSha256: null }; + if (typeof value !== "string" || !REFUSED_TOKEN_SHA256.test(value)) { + throw new MessagingHttpError( + 400, + "invalid_request", + "refusedTokenSha256 must be the 64 lowercase hex SHA-256 of the refused token", + ); + } + return { refusedTokenSha256: value }; +} + +/** Constant-time comparison of sha256(token) with a reported hex digest. */ +function tokenHashMatches(token: string, reportedSha256: string): boolean { + const actual = Buffer.from(createHash("sha256").update(token).digest("hex"), "utf8"); + const reported = Buffer.from(reportedSha256, "utf8"); + return actual.length === reported.length && timingSafeEqual(actual, reported); +} + +export function isValidDeviceId(id: string): boolean { + return DEVICE_ID.test(id) && !RESERVED_DEVICE_IDS.has(id); +} + +/** + * The display name of a sign-in's device: the host name recorded on the + * session row with control and bidirectional formatting characters removed, + * cut to at most 80 UTF-16 units on a grapheme boundary. Empty falls back to + * the kind. + */ +export function deviceName(hostName: string | null | undefined, kind: DeviceTokenDevice["kind"]): string { + const cleaned = (hostName ?? "").replace(/[\p{Cc}\u202A-\u202E\u2066-\u2069]/gu, "").trim(); + let cut = ""; + for (const { segment } of new Intl.Segmenter(undefined, { granularity: "grapheme" }).segment(cleaned)) { + if (cut.length + segment.length > MAX_DEVICE_NAME_UNITS) break; + cut += segment; + } + return cut.trim() || kind; +} + +/** + * `-`. The + * hash suffix keeps two sign-ins on hosts with the same name apart and keeps + * the id off Relaycast's reserved ids. + */ +export function deviceId(name: string, kind: DeviceTokenDevice["kind"], signInId: string): string { + const base = slug(name).slice(0, MAX_DEVICE_ID_SLUG).replace(/-+$/, "") || kind; + const id = `${base}-${createHash("sha256").update(signInId).digest("hex").slice(0, 8)}`; + if (!isValidDeviceId(id)) throw new Error("derived device id is outside Relaycast's device id rule"); + return id; +} + +/** + * The device a messaging credential request speaks for, derived from the + * server-side session only. A cookie request is the web device; a bearer is + * its own sign-in's device, bound to that session row. + */ +export function personDevice( + principal: Pick, + viaCookie: boolean, +): { device: DeviceTokenDevice; signInId: string | null } { + if (viaCookie) return { device: WEB_DEVICE, signInId: null }; + const kind = principal.desktopHostName ? "desktop" : "cli"; + const name = deviceName(principal.desktopHostName, kind); + return { device: { id: deviceId(name, kind, principal.sessionId), name, kind }, signInId: principal.sessionId }; +} + +/** Stored expiry: the earlier of Relaycast's expiry and the TTL asked for. */ +export function deviceTokenExpiry(upstream: string | null, now: Date, ttlSeconds = DEVICE_TOKEN_TTL_SECONDS): Date { + const asked = new Date(now.getTime() + ttlSeconds * 1000); + if (upstream === null) return asked; + const reported = new Date(upstream); + if (Number.isNaN(reported.getTime())) return asked; + return reported.getTime() < asked.getTime() ? reported : asked; +} + +function errorMessage(body: string): string | null { + try { + const parsed: unknown = body ? JSON.parse(body) : null; + if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) return null; + const outer = parsed as Record; + const nested = outer.error; + if (nested && typeof nested === "object" && !Array.isArray(nested)) { + const message = (nested as Record).message; + return typeof message === "string" ? message : null; + } + return typeof outer.message === "string" ? outer.message : null; + } catch { + return null; + } +} + +/** + * True only when Relaycast plainly has no device-token route (a release + * before device tokens): the mint answered 404 with code `not_found` and the + * message `Route not found`, and a workspace-key lookup still finds the + * person's agent under the expected id. Any other answer, a lookup failure, or + * a missing or replaced agent is not a missing route. + */ +export async function isMissingDeviceTokenRoute( + error: unknown, + findAgent: () => Promise<{ id: string } | null>, + expectedAgentId: string, +): Promise { + if (!(error instanceof RelaycastCallError)) return false; + if (error.status !== 404 || error.code !== "not_found" || errorMessage(error.body) !== "Route not found") return false; + try { + const agent = await findAgent(); + return agent !== null && agent.id === expectedAgentId; + } catch { + return false; + } +} + +/** Mint refusals that mean the person agent itself is gone or was replaced. */ +function isIdentityRefusal(error: unknown): boolean { + return error instanceof RelaycastCallError + && ((error.status === 404 && error.code === "agent_not_found") + || (error.status === 409 && error.code === "agent_identity_conflict")); +} + +function nowOf(deps: MessagingDeps): Date { + return deps.now?.() ?? new Date(); +} + +async function readDeviceRow(executor: SqlExecutor, access: PersonAccess, deviceIdValue: string): Promise { + const result = await executor.query( + `SELECT id, device_name, session_id, relaycast_workspace_id, agent_name, agent_remote_id, token_ciphertext, expires_at, revoked_at, + CEIL(EXTRACT(EPOCH FROM minted_at + interval '${FORCED_MINT_INTERVAL_SECONDS} seconds' - now()))::int + AS forced_mint_wait + FROM person_device_credentials + WHERE workspace_id = $1 AND user_id = $2 AND device_id = $3`, + [access.workspaceId, access.user.userId, deviceIdValue], + ); + return result.rows[0] ?? null; +} + +function usableRow( + row: DeviceRow | null, + identity: PersonIdentity, + device: DeviceTokenDevice, + signInId: string | null, + now: Date, + deps: MessagingDeps, +): StoredToken | null { + if (!row || row.revoked_at !== null) return null; + if (row.relaycast_workspace_id !== identity.relaycastWorkspaceId) return null; + if (row.agent_remote_id !== identity.agentId || row.agent_name !== identity.name) return null; + if (row.session_id !== signInId) return null; + const expiresAt = new Date(row.expires_at); + if (expiresAt.getTime() - now.getTime() <= DEVICE_TOKEN_RENEW_MARGIN_MS) return null; + return { + token: decryptSecret(row.token_ciphertext, deps.keyring), + expiresAt, + device: { ...device, name: row.device_name }, + }; +} + +/** + * Whether a stored token may be served. A refusal (401/403) or a token that + * now acts as another agent is dropped. An unreachable or failing Relaycast + * did not refuse it, so it is served: callers only probe rows outside the + * renew margin, which are unexpired. Nothing is cached between requests. + * `device_token_forbidden` says the route does not take device tokens at + * all, not that this token was refused, so it is an error and never a reason + * to mint again. + */ +async function probeServes(deps: MessagingDeps, token: string, identity: PersonIdentity): Promise { + try { + const agent = await client(deps).authenticatedAgent(token); + return agent.id === identity.agentId; + } catch (error) { + if (error instanceof RelaycastCallError && error.status === 403 && error.code === "device_token_forbidden") { + throw new MessagingHttpError(502, "upstream_unavailable", "The relay is not reachable right now. Try again shortly."); + } + return !(error instanceof RelaycastCallError && (error.status === 401 || error.status === 403)); + } +} + +/** + * Locks the sign-in's session row FOR SHARE before the device row is written, + * the order a sign-out takes them in (session row, then its device rows). A + * concurrent sign-out then waits for this transaction and its device-row + * revoke sees the row stored here. False when the session row is gone: + * removing a membership deletes the person's session rows, and that can + * commit while the Relaycast mint is in flight. + */ +async function lockSession(tx: SqlExecutor, signInId: string): Promise { + const result = await tx.query("SELECT 1 FROM token_sessions WHERE id = $1 FOR SHARE", [signInId]); + return result.rows.length === 1; +} + +async function sessionLive(tx: SqlExecutor, signInId: string): Promise { + const result = await tx.query( + `SELECT 1 FROM token_sessions + WHERE id = $1 AND revoked_at IS NULL AND refresh_token_expires_at > now() + FOR SHARE`, + [signInId], + ); + return result.rows.length === 1; +} + +async function storeRow( + tx: SqlExecutor, + deps: MessagingDeps, + input: { + access: PersonAccess; + identity: PersonIdentity; + device: DeviceTokenDevice; + signInId: string | null; + token: string; + expiresAt: Date; + /** Saves the row already revoked, pending the upstream revoke. */ + revoked: boolean; + }, +): Promise { + const stored = await tx.query<{ id: string }>( + `INSERT INTO person_device_credentials + (id, workspace_id, user_id, device_id, device_name, device_kind, session_id, relaycast_workspace_id, + agent_name, agent_remote_id, token_ciphertext, expires_at, minted_at, revoked_at, upstream_revoked_at) + VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, now(), CASE WHEN $13::boolean THEN now() END, NULL) + ON CONFLICT (workspace_id, user_id, device_id) DO UPDATE + SET device_name = EXCLUDED.device_name, + device_kind = EXCLUDED.device_kind, + session_id = EXCLUDED.session_id, + relaycast_workspace_id = EXCLUDED.relaycast_workspace_id, + agent_name = EXCLUDED.agent_name, + agent_remote_id = EXCLUDED.agent_remote_id, + token_ciphertext = EXCLUDED.token_ciphertext, + expires_at = EXCLUDED.expires_at, + minted_at = now(), + revoked_at = EXCLUDED.revoked_at, + upstream_revoked_at = NULL, + updated_at = now() + RETURNING id`, + [ + randomUUID(), + input.access.workspaceId, + input.access.user.userId, + input.device.id, + input.device.name, + input.device.kind, + input.signInId, + input.identity.relaycastWorkspaceId, + input.identity.name, + input.identity.agentId, + encryptSecret(input.token, deps.keyring.active), + input.expiresAt, + input.revoked, + ], + ); + return stored.rows[0]!.id; +} + +type MintOutcome = + | { kind: "served"; stored: StoredToken } + | { kind: "rate_limited"; retryAfterSeconds: number } + | { kind: "device_revoked" } + | { kind: "refused"; status: 401 | 403; rowId: string }; + +/** A row revoked while its own sign-in still authenticates: the device was revoked, not the sign-in. */ +function revokedForSignIn(row: DeviceRow | null, signInId: string | null): boolean { + return row !== null && row.revoked_at !== null && signInId !== null && row.session_id === signInId; +} + +/** + * Mints under the person lock (personLockKey), the lock the person identity's + * registration, takeover, recovery and member revocation take, so a mint + * never interleaves with a recovery that expires or a removal that revokes + * device rows. Like the identity code, the Relaycast call runs inside it. + * Locks are taken in the order person lock, session row, device row; a + * sign-out takes session row, then device rows. + * + * `forced` is a client report of the refused stored token `droppedToken`: + * it re-mints at most once per FORCED_MINT_INTERVAL_SECONDS per device, by + * the row's minted_at against the database clock. + */ +async function mintUnderLock( + deps: MessagingDeps, + access: PersonAccess, + identity: PersonIdentity, + device: DeviceTokenDevice, + signInId: string | null, + droppedToken: string | null, + forced: boolean, +): Promise { + const relaycast = client(deps); + const outcome = await withLock( + deps.database, + personLockKey(access.workspaceId, access.user.userId), + async (tx) => { + const row = await readDeviceRow(tx, access, device.id); + if (revokedForSignIn(row, signInId)) return { kind: "device_revoked" }; + // Another request may have minted while this one waited for the lock. + const again = usableRow(row, identity, device, signInId, nowOf(deps), deps); + if (again && again.token !== droppedToken) return { kind: "served", stored: again }; + if (forced && again && row && row.forced_mint_wait > 0) { + return { kind: "rate_limited", retryAfterSeconds: row.forced_mint_wait }; + } + const issued = await relaycast.issueDeviceToken(access.relaycastApiKey, identity.name, { + expectedAgentId: identity.agentId, + device, + ttlSeconds: DEVICE_TOKEN_TTL_SECONDS, + }); + const stored: StoredToken = { + token: issued.token, + expiresAt: deviceTokenExpiry(issued.expiresAt, nowOf(deps)), + device: issued.device, + }; + if (deps.beforeDeviceSave) await deps.beforeDeviceSave(tx); + // A refused token stays recorded, revoked and with no session, so the + // sweep retries the upstream revoke if the immediate one fails. + const recordRevoked = () => storeRow(tx, deps, { access, identity, signInId: null, revoked: true, ...stored }); + if (signInId && !(await lockSession(tx, signInId))) { + return { kind: "refused", status: 401, rowId: await recordRevoked() }; + } + const rowId = await storeRow(tx, deps, { access, identity, signInId, revoked: false, ...stored }); + if (deps.afterDeviceMint) await deps.afterDeviceMint(tx); + // Checked after the save: a sign-out or member removal that commits + // before this point is seen here, one that comes later waits for this + // transaction and revokes or deletes the saved row. + const refusal = signInId && !(await sessionLive(tx, signInId)) + ? 401 as const + : !(await isMember(tx, access.organizationId, access.user.userId)) ? 403 as const : null; + if (refusal === null) return { kind: "served", stored }; + const revoked = await tx.query<{ id: string }>( + "UPDATE person_device_credentials SET revoked_at = now(), updated_at = now() WHERE id = $1 RETURNING id", + [rowId], + ); + // A deleted session row takes its device rows with it. + return { kind: "refused", status: refusal, rowId: revoked.rows[0]?.id ?? await recordRevoked() }; + }, + ); + if (outcome.kind === "served") return outcome.stored; + if (outcome.kind === "rate_limited") throw new DeviceMintRateLimited(outcome.retryAfterSeconds); + if (outcome.kind === "device_revoked") throw deviceRevoked(); + try { + await relaycast.revokeDeviceToken(access.relaycastApiKey, identity.name, device.id); + await deps.database.query( + `UPDATE person_device_credentials SET upstream_revoked_at = now(), updated_at = now() + WHERE id = $1 AND revoked_at IS NOT NULL AND upstream_revoked_at IS NULL`, + [outcome.rowId], + ); + } catch { + // The revoked row stays pending for sweepDeviceRevocations. + } + if (outcome.status === 401) { + throw new MessagingHttpError(401, "unauthorized", "The sign-in ended before the credential was issued"); + } + throw new MessagingHttpError(403, "forbidden", "Organization membership ended before the credential was issued"); +} + +/** + * This device's own Relaycast token for the person agent `identity`: the + * stored one while it is usable and not refused upstream, otherwise a fresh + * mint bound to the sign-in session. The shared person token comes back only + * when Relaycast has no device-token route (isMissingDeviceTokenRoute). + * + * `options.refusedTokenSha256` is the client's report of a refused token. When + * it matches the stored token (constant-time) that token is dropped without a + * probe and re-minted, at most once per FORCED_MINT_INTERVAL_SECONDS per + * device (DeviceMintRateLimited inside it). A hash that does not match takes + * the normal path. A device row revoked while its sign-in still authenticates + * answers 403 device_revoked. + */ +export async function ensureDeviceCredential( + deps: MessagingDeps, + access: PersonAccess, + identity: PersonIdentity, + device: DeviceTokenDevice, + signInId: string | null, + options: { refusedTokenSha256?: string | null } = {}, +): Promise { + if (!isValidDeviceId(device.id)) throw new Error("device id is outside Relaycast's device id rule"); + let current = identity; + let droppedToken: string | null = null; + let forced = false; + const row = await readDeviceRow(deps.database, access, device.id); + if (revokedForSignIn(row, signInId)) throw deviceRevoked(); + const stored = usableRow(row, current, device, signInId, nowOf(deps), deps); + if (stored) { + forced = options.refusedTokenSha256 ? tokenHashMatches(stored.token, options.refusedTokenSha256) : false; + if (!forced && await probeServes(deps, stored.token, current)) { + return { kind: "device", identity: current, ...stored }; + } + droppedToken = stored.token; + } + let recovered = false; + for (;;) { + try { + const minted = await mintUnderLock(deps, access, current, device, signInId, droppedToken, forced); + return { kind: "device", identity: current, ...minted }; + } catch (error) { + if (!(error instanceof RelaycastCallError)) throw error; + if (!recovered && isIdentityRefusal(error)) { + recovered = true; + try { + current = await recoverPersonIdentity(deps, access, current); + } catch (recoveryError) { + if (recoveryError instanceof RelaycastCallError) { + throw new MessagingHttpError(502, "upstream_unavailable", "The relay is not reachable right now. Try again shortly."); + } + throw recoveryError; + } + continue; + } + const agentName = current.name; + const missingRoute = await isMissingDeviceTokenRoute( + error, + () => client(deps).getAgent(access.relaycastApiKey, agentName), + current.agentId, + ); + if (missingRoute) { + (deps.warn ?? defaultWarn)("messaging device credential fallback: Relaycast has no device-token route", { + workspaceId: access.workspaceId, + deviceKind: device.kind, + }); + return { kind: "shared", identity: current }; + } + throw new MessagingHttpError(502, "upstream_unavailable", "The relay is not reachable right now. Try again shortly."); + } + } +} + +function defaultWarn(message: string, fields: Record): void { + console.warn(`[selfhost-api] ${message}`, fields); +} + +/** + * Sends the upstream revoke for device rows revoked locally (ended sign-ins, + * refused mints) that Relaycast has not confirmed yet. Bounded per call; a + * failed row is retried on a later call after the others. `options.signal` + * bounds the upstream calls; an aborted call leaves its row pending like any + * other failure. + */ +export async function sweepDeviceRevocations( + deps: MessagingDeps, + organizationId?: string, + options: { signal?: AbortSignal } = {}, +): Promise { + const rows = await deps.database.query<{ + id: string; + workspace_id: string; + user_id: string; + device_id: string; + agent_name: string; + row_relaycast_workspace_id: string; + relaycast_workspace_id: string; + relaycast_api_key_ciphertext: string; + }>( + `SELECT device.id, device.workspace_id, device.user_id, device.device_id, device.agent_name, + device.relaycast_workspace_id AS row_relaycast_workspace_id, + workspace.relaycast_workspace_id, workspace.relaycast_api_key_ciphertext + FROM person_device_credentials device + JOIN workspaces workspace ON workspace.id = device.workspace_id + WHERE device.revoked_at IS NOT NULL AND device.upstream_revoked_at IS NULL + AND workspace.relaycast_api_key_ciphertext IS NOT NULL + AND ($1::uuid IS NULL OR workspace.organization_id = $1) + ORDER BY device.updated_at + LIMIT ${SWEEP_BATCH}`, + [organizationId ?? null], + ); + if (rows.rows.length === 0) return; + const relaycast = client(deps); + for (const row of rows.rows) { + if (options.signal?.aborted) return; + try { + await withLock(deps.database, personLockKey(row.workspace_id, row.user_id), async (tx) => { + // A mint may have replaced the row with a live token since it was read. + const pending = await tx.query( + `SELECT 1 FROM person_device_credentials + WHERE id = $1 AND revoked_at IS NOT NULL AND upstream_revoked_at IS NULL`, + [row.id], + ); + if (pending.rows.length === 0) return; + // The workspace key only reaches the workspace's current Relaycast + // workspace; a token minted on an earlier one runs out at its expiry. + if (row.row_relaycast_workspace_id === row.relaycast_workspace_id) { + await relaycast.revokeDeviceToken( + decryptSecret(row.relaycast_api_key_ciphertext, deps.keyring), + row.agent_name, + row.device_id, + options.signal, + ); + } + await tx.query( + "UPDATE person_device_credentials SET upstream_revoked_at = now(), updated_at = now() WHERE id = $1", + [row.id], + ); + }); + } catch { + // Moves the row behind the others; it stays pending for a later sweep. + await deps.database.query( + "UPDATE person_device_credentials SET updated_at = now() WHERE id = $1 AND upstream_revoked_at IS NULL", + [row.id], + ).catch(() => undefined); + } + } +} diff --git a/src/messaging/identity.ts b/src/messaging/identity.ts index 689da8a7..4a90a780 100644 --- a/src/messaging/identity.ts +++ b/src/messaging/identity.ts @@ -57,11 +57,34 @@ export type MessagingDeps = { beforeMembershipRecheck?: (tx: SqlExecutor) => Promise | void; beforeDispatch?: () => Promise | void; afterUpstream?: () => Promise | void; + /** + * Runs inside the device-credential lock after Relaycast minted a device + * token and before the session row is locked and the token row saved. + */ + beforeDeviceSave?: (tx: SqlExecutor) => Promise | void; + /** + * Runs inside the device-credential lock after the minted token row is + * saved and before the session and membership re-check. + */ + afterDeviceMint?: (tx: SqlExecutor) => Promise | void; + /** Tests shorten the bound on the upstream revokes a sign-out waits for. */ + signOutRevokeTimeoutMs?: number; + /** Server-side warning sink; defaults to console.warn. Never given a token or a device name. */ + warn?: (message: string, fields: Record) => void; +}; + +/** The workspace and person a messaging credential is issued for. */ +export type PersonAccess = { + workspaceId: string; + organizationId: string; + relaycastWorkspaceId: string; + relaycastApiKey: string; + user: PersonUser; }; type Relaycast = ReturnType; -function slug(value: string): string { +export function slug(value: string): string { return value .toLowerCase() .normalize("NFKD") @@ -97,7 +120,16 @@ function ownerOf(workspaceId: string, user: PersonUser): PersonOwner { }; } -async function withLock(database: Database, key: string, run: (tx: SqlExecutor) => Promise): Promise { +/** + * The per-person advisory lock key. Identity creation, recovery (takeover), + * membership-removal revocation and every device-token mint and revoke for + * one person in one workspace take this one lock, so they serialize. + */ +export function personLockKey(workspaceId: string, userId: string): string { + return `${workspaceId}:${userId}`; +} + +export async function withLock(database: Database, key: string, run: (tx: SqlExecutor) => Promise): Promise { return database.transaction(async (tx) => { await tx.query("SELECT pg_advisory_xact_lock(hashtext($1), hashtext($2))", ["selfhost-person", key]); return run(tx); @@ -124,7 +156,7 @@ function usable(row: IdentityRow | null, relaycastWorkspaceId: string, keyring: }; } -async function isMember(executor: SqlExecutor, organizationId: string, userId: string): Promise { +export async function isMember(executor: SqlExecutor, organizationId: string, userId: string): Promise { const result = await executor.query<{ present: boolean }>( `SELECT true AS present FROM organization_memberships @@ -159,7 +191,7 @@ async function saveIdentity( ); } -function client(deps: MessagingDeps): Relaycast { +export function client(deps: MessagingDeps): Relaycast { return createRelaycastClient({ internalOrigin: deps.relaycastUrl, fetchImpl: deps.fetchImpl }); } @@ -240,6 +272,14 @@ async function persistRecovery( identity, keyring: deps.keyring, }); + // A takeover revokes every device token of the agent upstream, so the + // person's stored device tokens are expired here and re-minted, not served. + await executor.query( + `UPDATE person_device_credentials + SET expires_at = LEAST(expires_at, now()), updated_at = now() + WHERE workspace_id = $1 AND user_id = $2`, + [access.workspaceId, access.user.userId], + ); return identity; } @@ -248,7 +288,7 @@ export async function ensurePersonIdentity( access: { workspaceId: string; organizationId: string; relaycastWorkspaceId: string; relaycastApiKey: string; user: PersonUser }, ): Promise { const relaycast = client(deps); - const outcome = await withLock(deps.database, `${access.workspaceId}:${access.user.userId}`, async (tx) => { + const outcome = await withLock(deps.database, personLockKey(access.workspaceId, access.user.userId), async (tx) => { if (!(await isMember(tx, access.organizationId, access.user.userId))) { throw new MessagingHttpError(403, "forbidden", "Organization membership is required"); } @@ -281,8 +321,15 @@ export async function ensurePersonIdentity( return outcome.identity!; } +/** + * A 401/403 that refuses the presented token. `device_token_forbidden` is + * not one: it means a device token reached a route that only takes the + * agent's own token, an error to surface, never a reason to recover. + */ export function isRefusedToken(error: unknown): boolean { - return error instanceof RelaycastCallError && (error.status === 401 || error.status === 403); + return error instanceof RelaycastCallError + && (error.status === 401 || error.status === 403) + && error.code !== "device_token_forbidden"; } export async function recoverPersonIdentity( @@ -291,7 +338,7 @@ export async function recoverPersonIdentity( refused: PersonIdentity, ): Promise { const relaycast = client(deps); - return withLock(deps.database, `${access.workspaceId}:${access.user.userId}`, async (tx) => { + return withLock(deps.database, personLockKey(access.workspaceId, access.user.userId), async (tx) => { const current = usable(await readRow(tx, access.workspaceId, access.user.userId), access.relaycastWorkspaceId, deps.keyring); if (current && current.token !== refused.token) return current; const remote = await relaycast.getAgent(access.relaycastApiKey, refused.name); @@ -340,6 +387,17 @@ async function queueRevocation(executor: SqlExecutor, target: RevocationTarget): WHERE workspace_id = $1 AND user_id = $2 AND agent_remote_id = $3`, [target.workspaceId, target.userId, target.agentRemoteId], ); + // Deleting the agent upstream ends its device tokens with it. Rows minted for + // another agent id stay pending for the upstream device-token sweep. + await executor.query( + `UPDATE person_device_credentials + SET revoked_at = COALESCE(revoked_at, now()), + upstream_revoked_at = CASE WHEN agent_remote_id = $3 THEN COALESCE(upstream_revoked_at, now()) + ELSE upstream_revoked_at END, + updated_at = now() + WHERE workspace_id = $1 AND user_id = $2`, + [target.workspaceId, target.userId, target.agentRemoteId], + ); } /** Membership removal retires the human credential. Session sign-out does not. */ @@ -361,7 +419,9 @@ export async function revokeRemovedMember(deps: MessagingDeps, organizationId: s ); for (const row of rows.rows) { const relaycastApiKey = decryptSecret(row.relaycast_api_key_ciphertext, deps.keyring); - await deps.database.transaction(async (tx) => { + // Under the person lock: a device-token mint in flight commits its row + // first, and this revocation then revokes it. + await withLock(deps.database, personLockKey(row.workspace_id, userId), async (tx) => { await queueRevocation(tx, { workspaceId: row.workspace_id, userId, diff --git a/src/messaging/relaycast.ts b/src/messaging/relaycast.ts index f94f0548..68d09128 100644 --- a/src/messaging/relaycast.ts +++ b/src/messaging/relaycast.ts @@ -22,6 +22,12 @@ export class RelaycastCallError extends Error { export type RegisteredAgent = { id: string; name: string; token: string }; +/** The device a person agent's device token is stamped with. */ +export type DeviceTokenDevice = { id: string; name: string; kind: "desktop" | "cli" | "web" }; + +/** `expiresAt` is the upstream ISO expiry, or null when it reported none. */ +export type IssuedDeviceToken = { token: string; agentId: string; device: DeviceTokenDevice; expiresAt: string | null }; + export type HostedDelivery = { delivery_id: string; message_id: string; @@ -378,6 +384,56 @@ export function createRelaycastClient(input: { await call("DELETE", `/v1/agents/${encodeURIComponent(name)}`, workspaceKey, undefined, undefined, true); }, + /** + * Mints a device-scoped token for a person agent with the workspace key. + * The token acts as the agent, and Relaycast stamps what it sends with + * the device. `ttlSeconds` is always sent: an omitted TTL means a token + * that never expires. The answer must name the agent and the device id and + * kind that were asked for. Relaycast cleans the device name, so the + * returned device carries the name from the answer when it has one. + */ + async issueDeviceToken( + workspaceKey: string, + name: string, + input: { expectedAgentId: string; device: DeviceTokenDevice; ttlSeconds: number }, + ): Promise { + const data = record(await labeled("issue_device_token", () => call( + "POST", + `/v1/agents/${encodeURIComponent(name)}/device-tokens`, + workspaceKey, + { + agent_id: input.expectedAgentId, + device: { id: input.device.id, name: input.device.name, kind: input.device.kind }, + ttl_seconds: input.ttlSeconds, + }, + ))); + const token = text(data?.token); + const agentId = text(data?.agent_id); + const answered = record(data?.device); + if (!token || agentId !== input.expectedAgentId + || text(answered?.id) !== input.device.id || text(answered?.kind) !== input.device.kind) { + throw new RelaycastCallError(502, "", false); + } + const device: DeviceTokenDevice = { ...input.device, name: text(answered?.name) ?? input.device.name }; + return { token, agentId, device, expiresAt: text(data?.expires_at) }; + }, + + /** + * Revokes one device's token of an agent; a device with no token (404) is + * already done. `signal` aborts the request (a caller's deadline). + */ + async revokeDeviceToken(workspaceKey: string, name: string, deviceId: string, signal?: AbortSignal): Promise { + await labeled("revoke_device_token", () => call( + "DELETE", + `/v1/agents/${encodeURIComponent(name)}/device-tokens/${encodeURIComponent(deviceId)}`, + workspaceKey, + undefined, + undefined, + true, + signal, + )); + }, + async sendDirectMessage(input: { token: string; to: string; diff --git a/src/messaging/routes.ts b/src/messaging/routes.ts index d02240be..ba7ee99a 100644 --- a/src/messaging/routes.ts +++ b/src/messaging/routes.ts @@ -17,6 +17,14 @@ import { type PersonIdentity, type SendClaim, } from "./identity.js"; +import { + DeviceMintRateLimited, + ensureDeviceCredential, + type DeviceCredential, + parseCredentialRequest, + personDevice, + sweepDeviceRevocations, +} from "./device-credentials.js"; import { MessagingHttpError, SEND_UNCERTAIN_MESSAGE, SendAbandoned } from "./http.js"; import { createRelaycastClient, RelaycastCallError } from "./relaycast.js"; @@ -260,6 +268,7 @@ export function createMessagingHandler(input: MessagingDeps & { throw new MessagingHttpError(403, "csrf_rejected", "Cross-origin messaging write refused"); } await sweepRevocations(deps, access.workspace.organizationId); + await sweepDeviceRevocations(deps, access.workspace.organizationId); const person = accessInput(access); if (people && method === "GET") { @@ -311,14 +320,45 @@ export function createMessagingHandler(input: MessagingDeps & { }, true); return true; } + // A Desktop browser handoff token, exchanged or not, is never a device: + // only the session its PKCE exchange issues may hold a messaging token. + if (access.principal.pendingHandoff) { + throw new MessagingHttpError(403, "handoff_not_exchanged", "Exchange the sign-in handoff first"); + } + if (access.principal.handoff) { + throw new MessagingHttpError( + 403, + "handoff_not_capable", + "This sign-in handoff cannot hold a messaging credential; use the session issued by POST /api/v1/auth/desktop/session", + ); + } + // Optional `{"refusedTokenSha256": ...}`: the client saw that token refused. + const { refusedTokenSha256 } = parseCredentialRequest(await requestBody(request)); + const { device, signInId } = personDevice(access.principal, !bearerToken); const identity = await ensurePersonIdentity(deps, person); + let issued: DeviceCredential; + try { + issued = await ensureDeviceCredential(deps, person, identity, device, signInId, { refusedTokenSha256 }); + } catch (error) { + if (error instanceof DeviceMintRateLimited) response.setHeader("retry-after", String(error.retryAfterSeconds)); + throw error; + } helpers.json(response, 200, { - identity: { - name: identity.name, - agentId: identity.agentId, - token: identity.token, - relaycastUrl: publicOrigin, - }, + identity: issued.kind === "device" + ? { + name: issued.identity.name, + agentId: issued.identity.agentId, + token: issued.token, + relaycastUrl: publicOrigin, + device: issued.device, + expiresAt: issued.expiresAt.toISOString(), + } + : { + name: issued.identity.name, + agentId: issued.identity.agentId, + token: issued.identity.token, + relaycastUrl: publicOrigin, + }, }, true); return true; } diff --git a/src/store.ts b/src/store.ts index c962072b..3ab1c2f1 100644 --- a/src/store.ts +++ b/src/store.ts @@ -228,6 +228,21 @@ type TokenContextRow = { desktop_host_name: string | null; }; +/** + * Ends the per-device messaging credentials bound to sign-in sessions that + * were just revoked. Call it in the transaction that revokes the sessions; + * the messaging sweep sends the upstream revoke later. + */ +export async function revokeSessionDeviceCredentials(executor: SqlExecutor, sessionIds: string[]): Promise { + if (sessionIds.length === 0) return; + await executor.query( + `UPDATE person_device_credentials + SET revoked_at = now(), upstream_revoked_at = NULL, updated_at = now() + WHERE session_id = ANY($1::uuid[]) AND revoked_at IS NULL`, + [sessionIds], + ); +} + function cleanName(value: string, field: string): string { const cleaned = value.replace(/[\p{C}]/gu, " ").trim().slice(0, 120); if (!cleaned) throw new Error(`${field} is required`); @@ -2027,6 +2042,7 @@ export class ControlPlaneStore { WHERE id = $1`, [input.sessionId], ); + await revokeSessionDeviceCredentials(tx, [input.sessionId]); await tx.query( "UPDATE users SET last_organization_id = $2, last_workspace_id = $3, updated_at = now() WHERE id = $1", [input.userId, organizationId, input.workspaceId], @@ -2128,14 +2144,17 @@ export class ControlPlaneStore { async revoke(token: string): Promise { const hash = hashSecret(token); - const result = await this.database.query<{ id: string }>( - `UPDATE token_sessions AS s - SET revoked_at = now(), revoked_reason = 'user_requested', updated_at = now() - WHERE (access_token_hash = $1 OR refresh_token_hash = $1) AND revoked_at IS NULL - RETURNING id`, - [hash], - ); - return result.rows.length === 1; + return this.database.transaction(async (tx) => { + const result = await tx.query<{ id: string }>( + `UPDATE token_sessions AS s + SET revoked_at = now(), revoked_reason = 'user_requested', updated_at = now() + WHERE (access_token_hash = $1 OR refresh_token_hash = $1) AND revoked_at IS NULL + RETURNING id`, + [hash], + ); + await revokeSessionDeviceCredentials(tx, result.rows.map((row) => row.id)); + return result.rows.length === 1; + }); } /** @@ -2163,6 +2182,15 @@ export class ControlPlaneStore { RETURNING id`, [userId, reason], ); + await revokeSessionDeviceCredentials(executor, sessions.rows.map((row) => row.id)); + // The web device is shared by all of the person's browser sessions, so it + // has no session binding; ending every session ends it too. + await executor.query( + `UPDATE person_device_credentials + SET revoked_at = now(), upstream_revoked_at = NULL, updated_at = now() + WHERE user_id = $1 AND session_id IS NULL AND revoked_at IS NULL`, + [userId], + ); // Desktop relay identity tokens let the MCP endpoint act as the person's // Desktop agents. They are deleted (the table has no revoked state), so // this server stops using them; Desktop syncs them again after the diff --git a/test/messaging.test.ts b/test/messaging.test.ts index da148ab9..95e1a06e 100644 --- a/test/messaging.test.ts +++ b/test/messaging.test.ts @@ -303,7 +303,9 @@ function createRelay(state: RelayState) { return; } - sendJson(response, 404, { error: { code: "not_found", message: "missing" } }); + // Relaycast answers routes it does not have with this exact body; the + // device-token mint falls back to the shared person token only on it. + sendJson(response, 404, { error: { code: "not_found", message: "Route not found" } }); }); } diff --git a/test/person-device-credentials.test.ts b/test/person-device-credentials.test.ts new file mode 100644 index 00000000..3c350b69 --- /dev/null +++ b/test/person-device-credentials.test.ts @@ -0,0 +1,1126 @@ +import assert from "node:assert/strict"; +import { createHash, randomUUID } from "node:crypto"; +import { createServer, type IncomingMessage, type Server, type ServerResponse } from "node:http"; +import test from "node:test"; +import { createApp } from "../src/app.js"; +import type { SelfhostConfig } from "../src/config.js"; +import { hashSecret } from "../src/crypto.js"; +import type { SqlExecutor } from "../src/database.js"; +import { + DEVICE_TOKEN_TTL_SECONDS, + deviceId, + deviceName, + deviceTokenExpiry, + isMissingDeviceTokenRoute, + isValidDeviceId, +} from "../src/messaging/device-credentials.js"; +import { RelaycastCallError } from "../src/messaging/relaycast.js"; +import { migrate } from "../src/migrations.js"; +import { ControlPlaneStore } from "../src/store.js"; +import { close, listen, PGliteDatabase } from "./support/harness.js"; + +/** + * A Relaycast with person agents, their workspace-key routes and per-device + * tokens. A device token acts as its agent at GET /v1/agent until it is + * revoked, replaced by a newer mint for the same device, or the agent is + * taken over. Unknown routes answer Relaycast's own "Route not found" 404. + */ +type Agent = { id: string; name: string; token: string; metadata: Record }; +type DeviceToken = { token: string; device: Record }; +type Answer = { status: number; body: unknown }; + +type RelayState = { + agents: Map; + /** Live tokens (agent and device) to the agent name they act as. */ + tokenOwner: Map; + /** `${agentName}\n${deviceId}` to that device's live token. */ + deviceTokens: Map; + registerCalls: number; + takeoverCalls: number; + probeCalls: number; + /** Every device-token mint request body, in order. */ + mints: Array>; + /** The device id of every device-token DELETE, in order. */ + deviceDeletes: string[]; + /** Answers for the next mints, used before the normal behaviour. */ + mintAnswers: Answer[]; + /** `undefined` answers now + ttl_seconds; a string or null is sent as `expires_at`. */ + mintExpiresAt: string | null | undefined; + /** Device-token DELETEs to fail with a 500 before they succeed. */ + deleteFailures: number; + /** GET /v1/agent drops the connection. */ + probeDown: boolean; + /** Answers for the next GET /v1/agent calls, used before the normal behaviour. */ + probeAnswers: Answer[]; + /** Relaycast issues device tokens in two shapes; Control must not depend on either. */ + deviceTokenPrefix: "at_live_dv_" | "ar_ad_"; + /** Every device token issued, in order. */ + issuedTokens: string[]; + /** Device-token DELETEs are accepted and never answered. */ + deleteHangs: boolean; +}; + +function relayState(): RelayState { + return { + agents: new Map(), + tokenOwner: new Map(), + deviceTokens: new Map(), + registerCalls: 0, + takeoverCalls: 0, + probeCalls: 0, + mints: [], + deviceDeletes: [], + mintAnswers: [], + mintExpiresAt: undefined, + deleteFailures: 0, + probeDown: false, + probeAnswers: [], + deviceTokenPrefix: "at_live_dv_", + issuedTokens: [], + deleteHangs: false, + }; +} + +/** Whether `value` carries any device token the relay issued. */ +function mentionsIssuedToken(state: RelayState, value: unknown): boolean { + const serialized = typeof value === "string" ? value : JSON.stringify(value); + return state.issuedTokens.some((token) => serialized.includes(token)); +} + +/** Relaycast's device name cleaning: control characters to spaces, whitespace collapsed, trimmed, at most 80. */ +function relayCleanName(name: unknown): string { + return String(name).replace(/\p{Cc}/gu, " ").replace(/\s+/g, " ").trim().slice(0, 80); +} + +async function readBody(request: IncomingMessage): Promise { + const chunks: Buffer[] = []; + for await (const chunk of request) chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk)); + return Buffer.concat(chunks).toString("utf8"); +} + +function bearer(request: IncomingMessage): string { + const header = request.headers.authorization ?? ""; + return header.startsWith("Bearer ") ? header.slice("Bearer ".length) : ""; +} + +function sendJson(response: ServerResponse, status: number, body: unknown): void { + response.writeHead(status, { "content-type": "application/json" }); + response.end(JSON.stringify(body)); +} + +const ROUTE_NOT_FOUND = { error: { code: "not_found", message: "Route not found" } }; + +function dropDeviceTokens(state: RelayState, agentName: string): void { + for (const [key, entry] of state.deviceTokens) { + if (key.startsWith(`${agentName}\n`)) { + state.tokenOwner.delete(entry.token); + state.deviceTokens.delete(key); + } + } +} + +function createRelay(state: RelayState) { + return createServer(async (request, response) => { + const url = new URL(request.url ?? "/", "http://relaycast.internal"); + const raw = await readBody(request); + const parsed = raw ? JSON.parse(raw) as Record : {}; + const token = bearer(request); + const mint = /^\/v1\/agents\/([^/]+)\/device-tokens$/.exec(url.pathname); + const revoke = /^\/v1\/agents\/([^/]+)\/device-tokens\/([^/]+)$/.exec(url.pathname); + const agentPath = /^\/v1\/agents\/([^/]+)(\/takeover|\/revoke-token)?$/.exec(url.pathname); + + if (request.method === "POST" && url.pathname === "/v1/agents") { + state.registerCalls += 1; + const name = String(parsed.name); + if (state.agents.has(name)) { + sendJson(response, 409, { error: { code: "agent_already_exists", message: "name taken" } }); + return; + } + const metadata = parsed.metadata && typeof parsed.metadata === "object" ? parsed.metadata as Record : {}; + const agent = { id: `ag_${state.registerCalls}`, name, token: `ar_ag_${state.registerCalls}`, metadata }; + state.agents.set(name, agent); + state.tokenOwner.set(agent.token, name); + sendJson(response, 201, { data: { id: agent.id, name: agent.name, token: agent.token } }); + return; + } + + if (request.method === "GET" && url.pathname === "/v1/agent") { + state.probeCalls += 1; + if (state.probeDown) { + response.socket?.destroy(); + return; + } + const probeAnswer = state.probeAnswers.shift(); + if (probeAnswer) { + sendJson(response, probeAnswer.status, probeAnswer.body); + return; + } + const owner = state.tokenOwner.get(token); + const agent = owner ? state.agents.get(owner) : undefined; + if (!agent) { + sendJson(response, 401, { error: { code: "unauthorized", message: "invalid token" } }); + return; + } + sendJson(response, 200, { data: { id: agent.id, name: agent.name, type: "human", channels: [] } }); + return; + } + + if (request.method === "POST" && mint) { + state.mints.push(parsed); + const answer = state.mintAnswers.shift(); + if (answer) { + sendJson(response, answer.status, answer.body); + return; + } + const agent = state.agents.get(decodeURIComponent(mint[1]!)); + if (!agent) { + sendJson(response, 404, { error: { code: "agent_not_found", message: "Agent not found" } }); + return; + } + if (parsed.agent_id !== agent.id) { + sendJson(response, 409, { error: { code: "agent_identity_conflict", message: "Agent id does not match" } }); + return; + } + const asked = parsed.device as Record; + if (asked.id === "direct" || asked.id === "unknown") { + sendJson(response, 400, { error: { code: "invalid_request", message: "Reserved device id" } }); + return; + } + const device = { id: asked.id, name: relayCleanName(asked.name), kind: asked.kind }; + const key = `${agent.name}\n${String(device.id)}`; + const previous = state.deviceTokens.get(key); + if (previous) state.tokenOwner.delete(previous.token); + const issued = `${state.deviceTokenPrefix}${state.mints.length}`; + state.issuedTokens.push(issued); + state.deviceTokens.set(key, { token: issued, device }); + state.tokenOwner.set(issued, agent.name); + const expiresAt = state.mintExpiresAt === undefined + ? new Date(Date.now() + Number(parsed.ttl_seconds) * 1000).toISOString() + : state.mintExpiresAt; + sendJson(response, 201, { data: { agent_id: agent.id, device, token: issued, expires_at: expiresAt } }); + return; + } + + if (request.method === "DELETE" && revoke) { + const deviceIdValue = decodeURIComponent(revoke[2]!); + state.deviceDeletes.push(deviceIdValue); + // Left open; the harness closes every connection at the end of the test. + if (state.deleteHangs) return; + if (state.deleteFailures > 0) { + state.deleteFailures -= 1; + sendJson(response, 500, { error: { code: "unavailable", message: "try later" } }); + return; + } + const key = `${decodeURIComponent(revoke[1]!)}\n${deviceIdValue}`; + const entry = state.deviceTokens.get(key); + if (!entry) { + sendJson(response, 404, { error: { code: "not_found", message: "Device token not found" } }); + return; + } + state.tokenOwner.delete(entry.token); + state.deviceTokens.delete(key); + sendJson(response, 200, { data: { ok: true } }); + return; + } + + if (agentPath) { + const name = decodeURIComponent(agentPath[1]!); + const agent = state.agents.get(name); + if (request.method === "GET" && !agentPath[2]) { + if (!agent) { + sendJson(response, 404, { error: { code: "agent_not_found", message: "Agent not found" } }); + return; + } + sendJson(response, 200, { data: { id: agent.id, name: agent.name, metadata: agent.metadata } }); + return; + } + if (request.method === "POST" && agentPath[2] === "/takeover") { + state.takeoverCalls += 1; + if (!agent || agent.id !== parsed.expected_agent_id) { + sendJson(response, 409, { error: { code: "agent_identity_conflict", message: "conflict" } }); + return; + } + state.tokenOwner.delete(agent.token); + dropDeviceTokens(state, agent.name); + agent.token = `ar_ag_takeover_${state.takeoverCalls}`; + state.tokenOwner.set(agent.token, agent.name); + sendJson(response, 200, { data: { agent_id: agent.id, name: agent.name, token: agent.token } }); + return; + } + if (request.method === "POST" && agentPath[2] === "/revoke-token") { + if (agent) state.tokenOwner.delete(agent.token); + sendJson(response, agent ? 200 : 404, agent ? { data: { ok: true } } : { error: { code: "agent_not_found", message: "Agent not found" } }); + return; + } + if (request.method === "DELETE" && !agentPath[2]) { + if (agent) { + state.tokenOwner.delete(agent.token); + dropDeviceTokens(state, agent.name); + state.agents.delete(name); + } + sendJson(response, 200, { data: { ok: true } }); + return; + } + } + + sendJson(response, 404, ROUTE_NOT_FOUND); + }); +} + +async function jsonRequest( + baseUrl: string, + path: string, + options: { method?: string; token?: string; cookie?: string; body?: unknown; rawBody?: string } = {}, +): Promise<{ status: number; body: Record; headers: Headers }> { + const headers: Record = {}; + const method = options.method ?? "GET"; + if (options.token) headers.authorization = `Bearer ${options.token}`; + if (options.cookie) headers.cookie = options.cookie; + if (options.cookie && method !== "GET") headers.origin = "https://control.internal.example"; + const payload = options.rawBody ?? (options.body !== undefined ? JSON.stringify(options.body) : undefined); + // Cookie writes must declare JSON (the CSRF guard), with or without a body. + const cookieWrite = Boolean(options.cookie) && method !== "GET"; + if (payload !== undefined || cookieWrite) headers["content-type"] = "application/json"; + const response = await fetch(`${baseUrl}${path}`, { + method, + headers, + ...(payload !== undefined ? { body: payload } : {}), + }); + const text = await response.text(); + return { status: response.status, body: text ? JSON.parse(text) as Record : {}, headers: response.headers }; +} + +type Hooks = { + beforeDeviceSave?: (tx: SqlExecutor) => Promise | void; + afterDeviceMint?: (tx: SqlExecutor) => Promise | void; +}; +type SignIn = { accessToken: string; refreshToken: string; sessionId: string }; + +async function harness( + t: { after: (fn: () => Promise) => void }, + options?: { config?: Partial; signOutRevokeTimeoutMs?: number }, +) { + const state = relayState(); + const hooks: Hooks = {}; + const warnings: Array<{ message: string; fields: Record }> = []; + const relaycast = createRelay(state); + const relaycastOrigin = await listen(relaycast); + const database = new PGliteDatabase(); + let control: Server | undefined; + t.after(async () => { + if (control) await close(control); + await close(relaycast); + await database.close(); + }); + await migrate(database); + const config: SelfhostConfig = { + databaseUrl: "unused-in-test", + publicBaseUrl: "https://control.internal.example", + relaycastUrl: relaycastOrigin, + relaycastPublicUrl: "https://cast.selfhosted.example", + relayhistoryUrl: "http://relayhistory.invalid", + relayhistoryPublicUrl: "https://history.selfhosted.example", + sessionReadApi: { url: "http://relayhistory.invalid", publicUrl: "https://history.selfhosted.example", secret: "session-read-secret-".repeat(2) }, + bootstrapToken: "bootstrap-token-that-is-at-least-32-bytes", + encryptionKeyring: { active: { id: "test-key", key: Buffer.alloc(32, 7) } }, + internalServiceToken: "service-token-that-is-at-least-32-bytes", + oauthRedirectUrl: "https://control.internal.example/api/v1/integrations/oauth/callback", + dashboardUrl: "https://control.internal.example/", + port: 3000, + host: "127.0.0.1", + ...options?.config, + }; + const store = new ControlPlaneStore(database, config.encryptionKeyring, 0); + control = createServer(createApp({ + config, + store, + messaging: { + beforeDeviceSave: (tx) => hooks.beforeDeviceSave?.(tx), + afterDeviceMint: (tx) => hooks.afterDeviceMint?.(tx), + ...(options?.signOutRevokeTimeoutMs !== undefined ? { signOutRevokeTimeoutMs: options.signOutRevokeTimeoutMs } : {}), + warn: (message, fields) => { warnings.push({ message, fields }); }, + }, + })); + const origin = await listen(control); + const org = await jsonRequest(origin, "/api/v1/organizations", { + method: "POST", + token: config.bootstrapToken, + body: { name: "Tenant", ownerEmail: "owner@example.test", ownerName: "Owner" }, + }); + assert.equal(org.status, 201); + const workspace = await jsonRequest(origin, `/api/v1/organizations/${org.body.id}/workspaces`, { + method: "POST", + token: config.bootstrapToken, + body: { name: "Primary", relaycastWorkspaceId: "rc-first", relaycastApiKey: "rk_live_first" }, + }); + assert.equal(workspace.status, 201); + const workspaceId = workspace.body.id as string; + const userId = org.body.owner.id as string; + + async function signIn(forUser = userId): Promise { + const started = await jsonRequest(origin, "/api/v1/auth/device/start", { + method: "POST", + body: { client_name: "device-credential-test" }, + }); + assert.equal(started.status, 201); + const approved = await jsonRequest(origin, "/api/v1/auth/device/approve", { + method: "POST", + token: config.bootstrapToken, + body: { action: "approve", user_code: started.body.user_code, user_id: forUser, workspace_id: workspaceId }, + }); + assert.equal(approved.status, 200); + const issued = await jsonRequest(origin, "/api/v1/auth/device/token", { + method: "POST", + body: { device_code: started.body.device_code }, + }); + assert.equal(issued.status, 200); + const accessToken = issued.body.access_token as string; + return { + accessToken, + refreshToken: issued.body.refresh_token as string, + sessionId: await sessionOf(accessToken), + }; + } + + async function sessionOf(accessToken: string): Promise { + const found = await database.query<{ id: string }>( + "SELECT id FROM token_sessions WHERE access_token_hash = $1", + [hashSecret(accessToken)], + ); + assert.equal(found.rows.length, 1); + return found.rows[0]!.id; + } + + function credential(auth: { token: string } | { cookie: string }, body?: { json: unknown } | { raw: string }) { + const cloud = "cookie" in auth; + return jsonRequest( + origin, + `${cloud ? "/cloud" : ""}/api/v1/workspaces/${workspaceId}/messaging/identity/credential`, + { + method: "POST", + ...auth, + ...(body && "json" in body ? { body: body.json } : {}), + ...(body && "raw" in body ? { rawBody: body.raw } : {}), + }, + ); + } + + async function deviceRows() { + return (await database.query<{ + device_id: string; + device_name: string; + device_kind: string; + session_id: string | null; + agent_remote_id: string; + token_ciphertext: string; + expired: boolean; + revoked: boolean; + upstream_revoked: boolean; + }>( + `SELECT device_id, device_name, device_kind, session_id, agent_remote_id, token_ciphertext, + expires_at <= now() AS expired, revoked_at IS NOT NULL AS revoked, + upstream_revoked_at IS NOT NULL AS upstream_revoked + FROM person_device_credentials ORDER BY created_at`, + )).rows; + } + + return { + state, hooks, warnings, origin, config, database, store, workspaceId, userId, + orgId: org.body.id as string, signIn, sessionOf, credential, deviceRows, + }; +} + +/** Whether Relaycast still accepts `token` as its agent. */ +async function relayAccepts(relaycastUrl: string, token: string): Promise { + const response = await fetch(`${relaycastUrl}/v1/agent`, { headers: { authorization: `Bearer ${token}` } }); + await response.text(); + return response.status === 200; +} + +test("a browser session gets the web device and each bearer sign-in its own device token for one agent", async (t) => { + const fx = await harness(t); + const first = await fx.signIn(); + const second = await fx.signIn(); + + const web = await fx.credential({ cookie: `agent_relay_session=${first.accessToken}` }); + assert.equal(web.status, 200); + assert.deepEqual(web.body.identity.device, { id: "web", name: "web", kind: "web" }); + + const one = await fx.credential({ token: first.accessToken }); + const two = await fx.credential({ token: second.accessToken }); + assert.equal(one.status, 200); + assert.equal(two.status, 200); + assert.equal(one.body.identity.device.kind, "cli"); + assert.equal(one.body.identity.device.id, deviceId("cli", "cli", first.sessionId)); + assert.equal(two.body.identity.device.id, deviceId("cli", "cli", second.sessionId)); + assert.notEqual(one.body.identity.device.id, two.body.identity.device.id); + assert.notEqual(one.body.identity.token, two.body.identity.token); + assert.notEqual(one.body.identity.token, web.body.identity.token); + // One person agent behind all three devices; no device gets the shared agent token. + assert.equal(fx.state.registerCalls, 1); + for (const answer of [web, one, two]) { + assert.equal(answer.body.identity.agentId, "ag_1"); + assert.equal(answer.body.identity.name, one.body.identity.name); + assert.notEqual(answer.body.identity.token, "ar_ag_1"); + assert.equal(answer.body.identity.relaycastUrl, "https://cast.selfhosted.example"); + assert.equal(typeof answer.body.identity.expiresAt, "string"); + } + // Every mint names the agent, the device and the TTL. + assert.equal(fx.state.mints.length, 3); + for (const body of fx.state.mints) { + assert.equal(body.agent_id, "ag_1"); + assert.equal(body.ttl_seconds, DEVICE_TOKEN_TTL_SECONDS); + } + assert.deepEqual(fx.state.mints[1]!.device, one.body.identity.device); + + const rows = await fx.deviceRows(); + assert.equal(rows.length, 3); + assert.deepEqual(rows.map((row) => row.session_id), [null, first.sessionId, second.sessionId]); + for (const row of rows) assert.equal(mentionsIssuedToken(fx.state, row.token_ciphertext), false); +}); + +test("a stored device token is reused until the renew margin, and a refresh keeps the device", async (t) => { + const fx = await harness(t); + const signIn = await fx.signIn(); + const minted = await fx.credential({ token: signIn.accessToken }); + assert.equal(minted.status, 200); + const again = await fx.credential({ token: signIn.accessToken }); + assert.equal(again.body.identity.token, minted.body.identity.token); + assert.equal(again.body.identity.expiresAt, minted.body.identity.expiresAt); + assert.equal(fx.state.mints.length, 1); + // The stored token is probed on every serve; nothing is cached. + assert.equal(fx.state.probeCalls, 1); + assert.equal((await fx.credential({ token: signIn.accessToken })).status, 200); + assert.equal(fx.state.probeCalls, 2); + + const refreshed = await jsonRequest(fx.origin, "/api/v1/auth/token/refresh", { + method: "POST", + body: { refreshToken: signIn.refreshToken }, + }); + assert.equal(refreshed.status, 200); + assert.equal(await fx.sessionOf(refreshed.body.accessToken as string), signIn.sessionId); + const afterRefresh = await fx.credential({ token: refreshed.body.accessToken as string }); + assert.equal(afterRefresh.status, 200); + assert.equal(afterRefresh.body.identity.device.id, minted.body.identity.device.id); + assert.equal(afterRefresh.body.identity.token, minted.body.identity.token); + assert.equal(fx.state.mints.length, 1); + + await fx.database.query("UPDATE person_device_credentials SET expires_at = now() + interval '30 minutes'"); + const renewed = await fx.credential({ token: refreshed.body.accessToken as string }); + assert.equal(renewed.status, 200); + assert.equal(fx.state.mints.length, 2); + assert.notEqual(renewed.body.identity.token, minted.body.identity.token); + assert.equal(renewed.body.identity.device.id, minted.body.identity.device.id); + assert.equal((await fx.deviceRows()).length, 1); +}); + +test("the device comes from the session row, a client-sent device is ignored, and the name Relaycast returns is served", async (t) => { + const fx = await harness(t); + const signIn = await fx.signIn(); + // Relaycast collapses the runs of spaces that Control's own cleaning keeps. + const hostName = "Ada's MacBook Pro"; + await fx.database.query("UPDATE token_sessions SET desktop_host_name = $2 WHERE id = $1", [signIn.sessionId, hostName]); + const answer = await fx.credential({ token: signIn.accessToken }, { + json: { device: { id: "unknown", name: "Evil", kind: "web" }, name: "Evil", deviceId: "direct" }, + }); + assert.equal(answer.status, 200); + const expected = { id: deviceId(hostName, "desktop", signIn.sessionId), name: "Ada's MacBook Pro", kind: "desktop" }; + assert.deepEqual(answer.body.identity.device, expected); + assert.match(answer.body.identity.device.id as string, /^ada-s-macbook-pro-[0-9a-f]{8}$/); + // The mint asked for the session's device, not the body's. + assert.equal(fx.state.mints.length, 1); + assert.deepEqual(fx.state.mints[0]!.device, { ...expected, name: hostName }); + const [row] = await fx.deviceRows(); + assert.equal(row!.device_name, "Ada's MacBook Pro"); + assert.equal(row!.device_kind, "desktop"); + // A stored token is served with the stored, returned name. + const again = await fx.credential({ token: signIn.accessToken }); + assert.equal(again.status, 200); + assert.equal(fx.state.mints.length, 1); + assert.deepEqual(again.body.identity.device, expected); +}); + +test("device names are cut on a grapheme boundary and stripped of control and bidi characters", () => { + assert.equal(deviceName("a".repeat(79) + "\u{1F44D}", "desktop"), "a".repeat(79)); + const accented = "é".repeat(41); + const cutAccents = deviceName(accented, "desktop"); + assert.equal(cutAccents.length, 80); + assert.equal(cutAccents, "é".repeat(40)); + const family = "\u{1F468}\u200D\u{1F469}\u200D\u{1F467}\u200D\u{1F466}"; + assert.equal(family.length, 11); + assert.equal(deviceName(family.repeat(8), "desktop"), family.repeat(7)); + assert.equal(deviceName("Ada\u0000\u202E Box\u2066", "desktop"), "Ada Box"); + assert.equal(deviceName(" \u0007 ", "desktop"), "desktop"); + assert.equal(deviceName(null, "cli"), "cli"); + for (const name of [deviceName(family.repeat(8), "desktop"), cutAccents]) { + assert.equal(/[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(? { + for (const id of ["web", "cli-0a1b2c3d", "a".repeat(64)]) assert.equal(isValidDeviceId(id), true, id); + for (const id of ["unknown", "direct", "", "A", "a_b", "a b", "a".repeat(65)]) assert.equal(isValidDeviceId(id), false, id); + for (const name of ["unknown", "direct", "Unknown", "DIRECT"]) { + const id = deviceId(name, "cli", "session-1"); + assert.equal(isValidDeviceId(id), true, id); + assert.notEqual(id, "unknown"); + assert.notEqual(id, "direct"); + } + assert.match(deviceId("\u{1F600}\u{1F600}", "desktop", "session-1"), /^desktop-[0-9a-f]{8}$/); + assert.equal(deviceId("x".repeat(200), "cli", "session-1").length <= 64, true); + assert.notEqual(deviceId("host", "desktop", "session-1"), deviceId("host", "desktop", "session-2")); +}); + +test("the stored expiry is the earlier of Relaycast's and the TTL asked for", async (t) => { + const now = new Date("2026-11-19T12:00:00.000Z"); + const asked = new Date(now.getTime() + DEVICE_TOKEN_TTL_SECONDS * 1000); + assert.equal(deviceTokenExpiry("2026-11-19T14:00:00.000Z", now).toISOString(), "2026-11-19T14:00:00.000Z"); + assert.equal(deviceTokenExpiry("2026-12-19T12:00:00.000Z", now).toISOString(), asked.toISOString()); + assert.equal(deviceTokenExpiry(null, now).toISOString(), asked.toISOString()); + assert.equal(deviceTokenExpiry("not a date", now).toISOString(), asked.toISOString()); + + const fx = await harness(t); + const signIn = await fx.signIn(); + const early = new Date(Date.now() + 2 * 60 * 60 * 1000).toISOString(); + fx.state.mintExpiresAt = early; + const shortLived = await fx.credential({ token: signIn.accessToken }); + assert.equal(shortLived.status, 200); + assert.equal(shortLived.body.identity.expiresAt, early); + + const other = await fx.signIn(); + fx.state.mintExpiresAt = null; + const before = Date.now(); + const unreported = await fx.credential({ token: other.accessToken }); + assert.equal(unreported.status, 200); + const expiresAt = Date.parse(unreported.body.identity.expiresAt as string); + assert.equal(expiresAt >= before + DEVICE_TOKEN_TTL_SECONDS * 1000, true); + assert.equal(expiresAt <= Date.now() + DEVICE_TOKEN_TTL_SECONDS * 1000, true); +}); + +test("a refused stored token is re-minted and an unreachable probe serves the unexpired stored token", async (t) => { + const fx = await harness(t); + const signIn = await fx.signIn(); + const minted = await fx.credential({ token: signIn.accessToken }); + assert.equal(minted.status, 200); + + fx.state.probeDown = true; + const served = await fx.credential({ token: signIn.accessToken }); + assert.equal(served.status, 200); + assert.equal(served.body.identity.token, minted.body.identity.token); + assert.equal(fx.state.mints.length, 1); + fx.state.probeDown = false; + + fx.state.tokenOwner.delete(minted.body.identity.token as string); + const reminted = await fx.credential({ token: signIn.accessToken }); + assert.equal(reminted.status, 200); + assert.equal(fx.state.mints.length, 2); + assert.notEqual(reminted.body.identity.token, minted.body.identity.token); + assert.equal(await relayAccepts(fx.config.relaycastUrl, reminted.body.identity.token as string), true); +}); + +function sha256Hex(value: string): string { + return createHash("sha256").update(value).digest("hex"); +} + +test("a reported refused token that matches the stored one is re-minted without a probe", async (t) => { + const fx = await harness(t); + // The other upstream token shape; nothing in Control reads the prefix. + fx.state.deviceTokenPrefix = "ar_ad_"; + const signIn = await fx.signIn(); + const minted = await fx.credential({ token: signIn.accessToken }); + assert.equal(minted.status, 200); + assert.match(minted.body.identity.token as string, /^ar_ad_/); + // Outside the 30 second window of the first mint. + await fx.database.query("UPDATE person_device_credentials SET minted_at = now() - interval '1 minute'"); + const probes = fx.state.probeCalls; + + const reminted = await fx.credential({ token: signIn.accessToken }, { + json: { refusedTokenSha256: sha256Hex(minted.body.identity.token as string) }, + }); + assert.equal(reminted.status, 200); + assert.equal(fx.state.mints.length, 2); + assert.equal(fx.state.probeCalls, probes); + assert.notEqual(reminted.body.identity.token, minted.body.identity.token); + assert.equal(reminted.body.identity.device.id, minted.body.identity.device.id); + assert.equal(await relayAccepts(fx.config.relaycastUrl, reminted.body.identity.token as string), true); + assert.equal(await relayAccepts(fx.config.relaycastUrl, minted.body.identity.token as string), false); + assert.equal((await fx.deviceRows()).length, 1); +}); + +test("a second reported refusal of a device token within 30 seconds of its mint gets 429 with Retry-After", async (t) => { + const fx = await harness(t); + const signIn = await fx.signIn(); + const minted = await fx.credential({ token: signIn.accessToken }); + assert.equal(minted.status, 200); + + const limited = await fx.credential({ token: signIn.accessToken }, { + json: { refusedTokenSha256: sha256Hex(minted.body.identity.token as string) }, + }); + assert.equal(limited.status, 429); + assert.equal(limited.body.error, "rate_limited"); + const retryAfter = Number(limited.headers.get("retry-after")); + assert.equal(Number.isInteger(retryAfter) && retryAfter >= 1 && retryAfter <= 30, true, String(retryAfter)); + assert.equal(mentionsIssuedToken(fx.state, limited.body), false); + assert.equal(fx.state.mints.length, 1); + + // Once the window has passed the report re-mints; reporting the new token at once is limited again. + await fx.database.query("UPDATE person_device_credentials SET minted_at = now() - interval '31 seconds'"); + const reminted = await fx.credential({ token: signIn.accessToken }, { + json: { refusedTokenSha256: sha256Hex(minted.body.identity.token as string) }, + }); + assert.equal(reminted.status, 200); + assert.equal(fx.state.mints.length, 2); + const again = await fx.credential({ token: signIn.accessToken }, { + json: { refusedTokenSha256: sha256Hex(reminted.body.identity.token as string) }, + }); + assert.equal(again.status, 429); + assert.equal(fx.state.mints.length, 2); + + // The window is per device: another sign-in of the same person is not limited. + const other = await fx.signIn(); + const otherMinted = await fx.credential({ token: other.accessToken }); + assert.equal(otherMinted.status, 200); + assert.equal(fx.state.mints.length, 3); +}); + +test("a reported refused token that does not match the stored one takes the normal path", async (t) => { + const fx = await harness(t); + const signIn = await fx.signIn(); + const minted = await fx.credential({ token: signIn.accessToken }); + assert.equal(minted.status, 200); + const probes = fx.state.probeCalls; + + const served = await fx.credential({ token: signIn.accessToken }, { json: { refusedTokenSha256: sha256Hex("at_live_dv_stale") } }); + assert.equal(served.status, 200); + assert.equal(served.body.identity.token, minted.body.identity.token); + assert.equal(fx.state.mints.length, 1); + assert.equal(fx.state.probeCalls, probes + 1); + + // A stored token Relaycast refuses is still dropped by the probe, without the 30 second limit. + fx.state.tokenOwner.delete(minted.body.identity.token as string); + const reminted = await fx.credential({ token: signIn.accessToken }, { json: { refusedTokenSha256: sha256Hex("at_live_dv_stale") } }); + assert.equal(reminted.status, 200); + assert.equal(fx.state.mints.length, 2); + assert.notEqual(reminted.body.identity.token, minted.body.identity.token); +}); + +test("a malformed credential request body is refused with 400 before anything is registered or minted", async (t) => { + const fx = await harness(t); + const signIn = await fx.signIn(); + const hash = sha256Hex("at_live_dv_1"); + for (const raw of [ + "not json", + "[]", + "null", + "\"text\"", + "42", + JSON.stringify({ refusedTokenSha256: hash.toUpperCase() }), + JSON.stringify({ refusedTokenSha256: hash.slice(1) }), + JSON.stringify({ refusedTokenSha256: `${hash}0` }), + JSON.stringify({ refusedTokenSha256: "" }), + JSON.stringify({ refusedTokenSha256: 42 }), + JSON.stringify({ refusedTokenSha256: [hash] }), + ]) { + const refused = await fx.credential({ token: signIn.accessToken }, { raw }); + assert.equal(refused.status, 400, raw); + assert.equal(refused.body.error, "invalid_request", raw); + } + assert.equal(fx.state.registerCalls, 0); + assert.equal(fx.state.mints.length, 0); + assert.equal((await fx.deviceRows()).length, 0); +}); + +test("no body, an empty object, a null report or unknown keys leave the credential request unchanged", async (t) => { + const fx = await harness(t); + const signIn = await fx.signIn(); + const minted = await fx.credential({ token: signIn.accessToken }); + assert.equal(minted.status, 200); + const bodies = [ + { raw: "" }, + { raw: " \n" }, + { json: {} }, + { json: { refusedTokenSha256: null } }, + { json: { refused: true, client: "test" } }, + ]; + for (const body of bodies) { + const served = await fx.credential({ token: signIn.accessToken }, body); + assert.equal(served.status, 200, JSON.stringify(body)); + assert.equal(served.body.identity.token, minted.body.identity.token); + } + assert.equal(fx.state.mints.length, 1); + assert.equal(fx.state.probeCalls, bodies.length); +}); + +test("a device revoked while its sign-in still authenticates answers 403 device_revoked", async (t) => { + const fx = await harness(t); + const signIn = await fx.signIn(); + const minted = await fx.credential({ token: signIn.accessToken }); + assert.equal(minted.status, 200); + await fx.database.query("UPDATE person_device_credentials SET revoked_at = now() WHERE session_id = $1", [signIn.sessionId]); + + const revoked = await fx.credential({ token: signIn.accessToken }); + assert.equal(revoked.status, 403); + assert.equal(revoked.body.error, "device_revoked"); + const reported = await fx.credential({ token: signIn.accessToken }, { + json: { refusedTokenSha256: sha256Hex(minted.body.identity.token as string) }, + }); + assert.equal(reported.status, 403); + assert.equal(reported.body.error, "device_revoked"); + assert.equal(mentionsIssuedToken(fx.state, [revoked.body, reported.body]), false); + assert.equal(fx.state.mints.length, 1); + + // The web device is bound to no sign-in: a revoked web row is minted again for the browser session. + const web = await fx.credential({ cookie: `agent_relay_session=${signIn.accessToken}` }); + assert.equal(web.status, 200); + await fx.database.query("UPDATE person_device_credentials SET revoked_at = now() WHERE device_id = 'web'"); + const webAgain = await fx.credential({ cookie: `agent_relay_session=${signIn.accessToken}` }); + assert.equal(webAgain.status, 200); + assert.notEqual(webAgain.body.identity.token, web.body.identity.token); +}); + +test("a probe answered device_token_forbidden is an upstream error, never a re-mint", async (t) => { + const fx = await harness(t); + const signIn = await fx.signIn(); + const minted = await fx.credential({ token: signIn.accessToken }); + assert.equal(minted.status, 200); + fx.state.probeAnswers.push({ + status: 403, + body: { error: { code: "device_token_forbidden", message: "Device tokens cannot use this route" } }, + }); + const failed = await fx.credential({ token: signIn.accessToken }); + assert.equal(failed.status, 502); + assert.equal(failed.body.error, "upstream_unavailable"); + assert.equal(fx.state.mints.length, 1); + const [row] = await fx.deviceRows(); + assert.equal(row!.revoked, false); +}); + +test("Desktop handoff tokens never hold a messaging credential", async (t) => { + const fx = await harness(t); + const handoff = await fx.store.issueDesktopHandoff({ + userId: fx.userId, + organizationId: fx.orgId, + workspaceId: fx.workspaceId, + codeChallenge: "c".repeat(43), + consentedHostName: "Studio", + }); + const pending = await fx.credential({ token: handoff.accessToken }); + assert.equal(pending.status, 403); + assert.equal(pending.body.error, "handoff_not_exchanged"); + + const exchanged = await fx.store.exchangeDesktopHandoff(handoff.accessToken, () => true); + assert(exchanged); + const spent = await fx.credential({ token: handoff.accessToken }); + assert.equal(spent.status, 403); + assert.equal(spent.body.error, "handoff_not_capable"); + assert.equal(fx.state.mints.length, 0); + assert.equal(JSON.stringify([pending.body, spent.body]).includes("ar_ag_"), false); + + const session = await fx.credential({ token: exchanged.accessToken }); + assert.equal(session.status, 200); + assert.equal(session.body.identity.device.kind, "desktop"); + assert.equal(session.body.identity.device.name, "Studio"); + assert.equal(session.body.identity.device.id, deviceId("Studio", "desktop", exchanged.sessionId)); +}); + +test("the shared-token fallback needs Relaycast's exact missing-route answer and the expected agent", async () => { + const routeMissing = JSON.stringify(ROUTE_NOT_FOUND); + const agent = async () => ({ id: "ag_1" }); + assert.equal(await isMissingDeviceTokenRoute(new RelaycastCallError(404, routeMissing), agent, "ag_1"), true); + assert.equal( + await isMissingDeviceTokenRoute( + new RelaycastCallError(404, JSON.stringify({ error: "not_found", message: "Route not found" })), + agent, + "ag_1", + ), + true, + ); + const refused: Array<[string, unknown, () => Promise<{ id: string } | null>]> = [ + ["other message", new RelaycastCallError(404, JSON.stringify({ error: { code: "not_found", message: "Agent not found" } })), agent], + ["other code", new RelaycastCallError(404, JSON.stringify({ error: { code: "agent_not_found", message: "Route not found" } })), agent], + ["no body", new RelaycastCallError(404, ""), agent], + ["not JSON", new RelaycastCallError(404, "Route not found"), agent], + ["405", new RelaycastCallError(405, routeMissing), agent], + ["500", new RelaycastCallError(500, routeMissing, true), agent], + ["transport", new RelaycastCallError(0, "", true), agent], + ["agent missing", new RelaycastCallError(404, routeMissing), async () => null], + ["agent replaced", new RelaycastCallError(404, routeMissing), async () => ({ id: "ag_2" })], + ["lookup failed", new RelaycastCallError(404, routeMissing), async () => { throw new RelaycastCallError(0, "", true); }], + ["not a Relaycast answer", new Error("Route not found"), agent], + ]; + for (const [label, error, findAgent] of refused) { + assert.equal(await isMissingDeviceTokenRoute(error, findAgent, "ag_1"), false, label); + } +}); + +test("a Relaycast without device tokens serves the shared token and logs the fallback", async (t) => { + const fx = await harness(t); + const signIn = await fx.signIn(); + fx.state.mintAnswers.push({ status: 404, body: ROUTE_NOT_FOUND }); + // A reported refused-token hash plays no part in the fallback. + const shared = await fx.credential({ token: signIn.accessToken }, { json: { refusedTokenSha256: sha256Hex("ar_ag_1") } }); + assert.equal(shared.status, 200); + assert.equal(shared.body.identity.token, "ar_ag_1"); + assert.equal(shared.body.identity.agentId, "ag_1"); + assert.equal("device" in shared.body.identity, false); + assert.equal("expiresAt" in shared.body.identity, false); + assert.equal(fx.warnings.length, 1); + assert.match(fx.warnings[0]!.message, /device credential fallback/); + assert.deepEqual(fx.warnings[0]!.fields, { workspaceId: fx.workspaceId, deviceKind: "cli" }); + assert.equal(JSON.stringify(fx.warnings).includes("ar_ag_"), false); + assert.equal((await fx.deviceRows()).length, 0); + + // Any other refusal of the mint is an upstream failure, never the shared token. + for (const answer of [ + { status: 404, body: { error: { code: "not_found", message: "Not here" } } }, + { status: 405, body: ROUTE_NOT_FOUND }, + { status: 500, body: { error: { code: "internal", message: "boom" } } }, + { status: 400, body: { error: { code: "invalid_request", message: "bad device" } } }, + { status: 409, body: { error: { code: "not_a_person_agent", message: "not a person" } } }, + ]) { + fx.state.mintAnswers.push(answer); + const failed = await fx.credential({ token: signIn.accessToken }); + assert.equal(failed.status, 502, JSON.stringify(answer)); + assert.equal(failed.body.error, "upstream_unavailable"); + assert.equal(JSON.stringify(failed.body).includes("ar_ag_"), false); + } + assert.equal(fx.warnings.length, 1); +}); + +test("a mint answer naming another agent is refused", async (t) => { + const fx = await harness(t); + const signIn = await fx.signIn(); + fx.state.mintAnswers.push({ + status: 201, + body: { data: { agent_id: "ag_other", device: {}, token: "at_live_dv_foreign", expires_at: null } }, + }); + const refused = await fx.credential({ token: signIn.accessToken }); + assert.equal(refused.status, 502); + assert.equal(refused.body.error, "upstream_unavailable"); + assert.equal(JSON.stringify(refused.body).includes("at_live_dv_foreign"), false); + assert.equal((await fx.deviceRows()).length, 0); +}); + +test("a mint answer naming another device id or kind is refused", async (t) => { + const fx = await harness(t); + const signIn = await fx.signIn(); + const asked = { id: deviceId("cli", "cli", signIn.sessionId), name: "cli", kind: "cli" }; + for (const device of [{ ...asked, id: "other-device" }, { ...asked, kind: "desktop" }, { name: "cli" }]) { + fx.state.mintAnswers.push({ + status: 201, + body: { data: { agent_id: "ag_1", device, token: "ar_ad_foreign", expires_at: null } }, + }); + const refused = await fx.credential({ token: signIn.accessToken }); + assert.equal(refused.status, 502, JSON.stringify(device)); + assert.equal(refused.body.error, "upstream_unavailable"); + assert.equal(JSON.stringify(refused.body).includes("ar_ad_foreign"), false); + } + assert.equal((await fx.deviceRows()).length, 0); +}); + +test("an identity refusal of the mint recovers the person agent once and expires stored device tokens", async (t) => { + for (const refusal of [ + { status: 409, body: { error: { code: "agent_identity_conflict", message: "conflict" } } }, + { status: 404, body: { error: { code: "agent_not_found", message: "Agent not found" } } }, + ]) { + const fx = await harness(t); + const first = await fx.signIn(); + const second = await fx.signIn(); + const stored = await fx.credential({ token: first.accessToken }); + assert.equal(stored.status, 200); + + fx.state.mintAnswers.push(refusal); + const recovered = await fx.credential({ token: second.accessToken }); + assert.equal(recovered.status, 200, refusal.body.error.code); + assert.equal(fx.state.takeoverCalls, 1); + assert.equal(fx.state.mints.length, 3); + assert.equal(recovered.body.identity.agentId, "ag_1"); + // The takeover ended every device token of the agent; the stored one is expired, not served. + const firstRow = (await fx.deviceRows()).find((row) => row.session_id === first.sessionId); + assert.equal(firstRow!.expired, true); + const reminted = await fx.credential({ token: first.accessToken }); + assert.equal(reminted.status, 200); + assert.notEqual(reminted.body.identity.token, stored.body.identity.token); + assert.equal(fx.state.mints.length, 4); + + // A second refusal after the one recovery is an upstream failure. + const third = await fx.signIn(); + fx.state.mintAnswers.push(refusal, refusal); + const failed = await fx.credential({ token: third.accessToken }); + assert.equal(failed.status, 502); + assert.equal(fx.state.takeoverCalls, 2); + } +}); + +test("ending a sign-in revokes its device token, retried by the sweep after an upstream failure", async (t) => { + const fx = await harness(t); + const ended = await fx.signIn(); + const other = await fx.signIn(); + const minted = await fx.credential({ token: ended.accessToken }); + assert.equal(minted.status, 200); + const kept = await fx.credential({ token: other.accessToken }); + assert.equal(kept.status, 200); + + fx.state.deleteFailures = 1; + const signOut = await jsonRequest(fx.origin, "/api/v1/auth/token/revoke", { + method: "POST", + body: { token: ended.accessToken }, + }); + assert.equal(signOut.status, 200); + assert.deepEqual(fx.state.deviceDeletes, [minted.body.identity.device.id]); + let row = (await fx.deviceRows()).find((candidate) => candidate.session_id === ended.sessionId)!; + assert.equal(row.revoked, true); + assert.equal(row.upstream_revoked, false); + assert.equal(await relayAccepts(fx.config.relaycastUrl, minted.body.identity.token as string), true); + + const people = await jsonRequest(fx.origin, `/api/v1/workspaces/${fx.workspaceId}/messaging/people`, { token: other.accessToken }); + assert.equal(people.status, 200); + assert.deepEqual(fx.state.deviceDeletes, [minted.body.identity.device.id, minted.body.identity.device.id]); + row = (await fx.deviceRows()).find((candidate) => candidate.session_id === ended.sessionId)!; + assert.equal(row.upstream_revoked, true); + assert.equal(await relayAccepts(fx.config.relaycastUrl, minted.body.identity.token as string), false); + + // The other sign-in's device is untouched. + const live = (await fx.deviceRows()).find((candidate) => candidate.session_id === other.sessionId)!; + assert.equal(live.revoked, false); + assert.equal(await relayAccepts(fx.config.relaycastUrl, kept.body.identity.token as string), true); + assert.equal(fx.state.deviceDeletes.length, 2); +}); + +test("a sign-in that ends while its device token is minted gets 401 and the token is revoked upstream", async (t) => { + const fx = await harness(t); + const signIn = await fx.signIn(); + fx.hooks.afterDeviceMint = async (tx) => { + fx.hooks.afterDeviceMint = undefined; + // The token is saved before the session is checked. + const saved = await tx.query("SELECT 1 FROM person_device_credentials WHERE session_id = $1 AND revoked_at IS NULL", [signIn.sessionId]); + assert.equal(saved.rows.length, 1); + await tx.query("UPDATE token_sessions SET revoked_at = now() WHERE id = $1", [signIn.sessionId]); + }; + const refused = await fx.credential({ token: signIn.accessToken }); + assert.equal(refused.status, 401); + assert.equal(refused.body.error, "unauthorized"); + assert.equal(mentionsIssuedToken(fx.state, refused.body), false); + assert.equal(fx.state.mints.length, 1); + assert.equal(fx.state.deviceDeletes.length, 1); + assert.equal(await relayAccepts(fx.config.relaycastUrl, fx.state.issuedTokens[0]!), false); + const [row] = await fx.deviceRows(); + assert.equal(row!.revoked, true); + assert.equal(row!.upstream_revoked, true); +}); + +test("a sign-in row deleted while its device token is minted gets 401 and the token is recorded revoked and revoked upstream", async (t) => { + const fx = await harness(t); + const signIn = await fx.signIn(); + // PGlite runs a transaction on its only connection, so the delete that + // would come from another connection runs on the mint's transaction, + // after the mint and before the session row is locked. + fx.hooks.beforeDeviceSave = async (tx) => { + fx.hooks.beforeDeviceSave = undefined; + await tx.query("DELETE FROM token_sessions WHERE id = $1", [signIn.sessionId]); + }; + const refused = await fx.credential({ token: signIn.accessToken }); + assert.equal(refused.status, 401); + assert.equal(refused.body.error, "unauthorized"); + assert.equal(mentionsIssuedToken(fx.state, refused.body), false); + assert.equal(fx.state.mints.length, 1); + assert.equal(fx.state.deviceDeletes.length, 1); + assert.equal(await relayAccepts(fx.config.relaycastUrl, fx.state.issuedTokens[0]!), false); + const rows = await fx.deviceRows(); + assert.equal(rows.length, 1); + assert.equal(rows[0]!.session_id, null); + assert.equal(rows[0]!.revoked, true); + assert.equal(rows[0]!.upstream_revoked, true); +}); + +test("a membership that ends while a bearer device token is minted gets 401, since its sign-in goes with it, and the token is revoked upstream", async (t) => { + const fx = await harness(t); + const signIn = await fx.signIn(); + fx.hooks.afterDeviceMint = async (tx) => { + fx.hooks.afterDeviceMint = undefined; + // The token is saved before the session and membership are checked. + const saved = await tx.query("SELECT 1 FROM person_device_credentials WHERE session_id = $1 AND revoked_at IS NULL", [signIn.sessionId]); + assert.equal(saved.rows.length, 1); + // Removing the membership deletes the person's sign-ins and, with them, the saved row. + await tx.query("DELETE FROM organization_memberships WHERE user_id = $1", [fx.userId]); + }; + const refused = await fx.credential({ token: signIn.accessToken }); + assert.equal(refused.status, 401); + assert.equal(refused.body.error, "unauthorized"); + assert.equal(mentionsIssuedToken(fx.state, refused.body), false); + assert.equal(fx.state.deviceDeletes.length, 1); + assert.equal(await relayAccepts(fx.config.relaycastUrl, fx.state.issuedTokens[0]!), false); + const rows = await fx.deviceRows(); + assert.equal(rows.length, 1); + assert.equal(rows[0]!.session_id, null); + assert.equal(rows[0]!.revoked, true); + assert.equal(rows[0]!.upstream_revoked, true); +}); + +test("a membership that ends while the web device token is minted gets 403 and the token is revoked upstream", async (t) => { + const fx = await harness(t); + const signIn = await fx.signIn(); + fx.hooks.afterDeviceMint = async (tx) => { + fx.hooks.afterDeviceMint = undefined; + // The web row is bound to no sign-in, so the membership re-check is its only guard. + const saved = await tx.query("SELECT 1 FROM person_device_credentials WHERE device_id = 'web' AND revoked_at IS NULL"); + assert.equal(saved.rows.length, 1); + await tx.query("DELETE FROM organization_memberships WHERE user_id = $1", [fx.userId]); + }; + const refused = await fx.credential({ cookie: `agent_relay_session=${signIn.accessToken}` }); + assert.equal(refused.status, 403); + assert.equal(refused.body.error, "forbidden"); + assert.equal(mentionsIssuedToken(fx.state, refused.body), false); + assert.deepEqual(fx.state.deviceDeletes, ["web"]); + assert.equal(await relayAccepts(fx.config.relaycastUrl, fx.state.issuedTokens[0]!), false); + const [row] = await fx.deviceRows(); + assert.equal(row!.revoked, true); + assert.equal(row!.upstream_revoked, true); +}); + +test("sign-out answers 200 when Relaycast never answers the device-token revoke", async (t) => { + const fx = await harness(t, { signOutRevokeTimeoutMs: 50 }); + const signIn = await fx.signIn(); + const minted = await fx.credential({ token: signIn.accessToken }); + assert.equal(minted.status, 200); + + fx.state.deleteHangs = true; + const signOut = await jsonRequest(fx.origin, "/api/v1/auth/token/revoke", { + method: "POST", + body: { token: signIn.accessToken }, + }); + assert.equal(signOut.status, 200); + assert.deepEqual(fx.state.deviceDeletes, [minted.body.identity.device.id]); + // The aborted revoke leaves the row pending for the sweep. + const [row] = await fx.deviceRows(); + assert.equal(row!.revoked, true); + assert.equal(row!.upstream_revoked, false); +}); + +test("a gate-only install mints no device token", async (t) => { + const fx = await harness(t, { config: { relaygatePublicUrl: "https://gate.selfhosted.example" } }); + const signIn = await fx.signIn(); + const withheld = await fx.credential({ token: signIn.accessToken }); + assert.equal(withheld.status, 403); + assert.equal(withheld.body.error, "gate_only"); + // The body is not read on a gate-only install. + const withBody = await fx.credential({ token: signIn.accessToken }, { raw: "not json" }); + assert.equal(withBody.status, 403); + assert.equal(withBody.body.error, "gate_only"); + assert.equal(fx.state.registerCalls, 0); + assert.equal(fx.state.mints.length, 0); + assert.equal((await fx.deviceRows()).length, 0); +}); + +test("the device kind column accepts only desktop, cli and web", async (t) => { + const fx = await harness(t); + const insert = (kind: string) => fx.database.query( + `INSERT INTO person_device_credentials + (id, workspace_id, user_id, device_id, device_name, device_kind, session_id, relaycast_workspace_id, + agent_name, agent_remote_id, token_ciphertext, expires_at) + VALUES ($1, $2, $3, $4, 'name', $5, NULL, 'rc-first', 'agent', 'ag_1', 'ciphertext', now() + interval '1 hour')`, + [randomUUID(), fx.workspaceId, fx.userId, `device-${kind}`, kind], + ); + await insert("web"); + await assert.rejects(insert("phone")); +});