diff --git a/CHANGELOG.md b/CHANGELOG.md index 291bbb0..0d11169 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,6 +5,7 @@ assigned at release. ## Unreleased +- Added: optional `SELFHOST_ROUTED_SITE_URL` (an https origin) for a deployment reached through an edge router on another site origin. When a request carries exactly one `x-original-host` header naming that origin's host, the Desktop/CLI sign-in answers (browser handoff `api_url`, desktop session, workspace switch, device start `verification_uri`, device and enrollment token `api_url`, and refresh `apiUrl`) name it instead of the Host-selected origin, so a Desktop that signed in through that site accepts them. The header only selects the configured value and is never echoed; emailed links, OIDC redirect URIs, the MCP endpoint URL, cookies and browser origin checks are unchanged. The router must overwrite `x-original-host`. Unset: unchanged. No migration. - Added: a session bridge for organizations moved from Agent Relay Cloud (migration 0083; docs/identity.md). Off by default (`SELFHOST_CLOUD_BRIDGE_ENABLED`); while off its routes answer 404. Cloud signs a short-lived, single-use Ed25519 assertion for a browser with a live Cloud session and posts it to `/cloud/api/v1/auth/cloud-bridge/consume`; this deployment verifies it against `SELFHOST_CLOUD_BRIDGE_PUBLIC_KEYS` and issues its own browser session for the existing user (matched by id, never email) in an organization the operator listed with a time-boxed window (`/api/v1/installation/cloud-bridge/organizations`, bootstrap bearer only). It creates nothing, accepts no Cloud token, and is refused after the person signs out here. - Fixed: MCP repository-filtered session summaries apply the first 200 characters of a repo-only filter in the session directory before pagination, while still accepting a 512-character repo value and verifying the full returned repository URL. This requires a sessions read API whose session directory list applies `projectContains` as a case-insensitive substring of project ID, catalog project key or recorded repository URL (directory migration `20261105034000` or later). Exact verification can still produce a short or empty page with a cursor. Relay agent listings now link an exact roster agent ID to its already-synced Desktop native session when the agent has no validated Relaycast session declaration. The optional session join is failure-open: the roster still returns a null session ID and attribution with `session_unavailable_reason` set to `enrichment_failed` or `ambiguous_sync`; an independently recorded metadata session kind is preserved. No migration. - Changed: MCP `list_amp_threads` now returns `{ threads, truncated }` instead of a bare thread array. Clients that parse the old array must read the `threads` field; `truncated` truthfully reports whether Amp returned more than the first 100 threads by requesting one lookahead row. diff --git a/docs/repository-guide.md b/docs/repository-guide.md index f313ff3..e3bd5f0 100644 --- a/docs/repository-guide.md +++ b/docs/repository-guide.md @@ -157,6 +157,7 @@ is explicit. History is served only by the sessions pipeline: see | `SELFHOST_FLOWS_RUNTIME_ENV_URL` | Origin serving that internal route, default `http://127.0.0.1:$PORT` (this process) | | `SELFHOST_OAUTH_REDIRECT_URL` | Optional. OAuth redirect URI registered in each provider OAuth app. Default `$SELFHOST_PUBLIC_URL/api/v1/integrations/oauth/callback` | | `SELFHOST_DASHBOARD_URL` | Optional dashboard origin. Link shown on the OAuth result page (default `$SELFHOST_PUBLIC_URL/`) and, when https, `runUrl` on mirrored flow runs | +| `SELFHOST_ROUTED_SITE_URL` | Optional https origin of a third site whose edge router forwards `/cloud/...` here and overwrites `x-original-host` with that site's host. When one such header names this origin's host, the Desktop/CLI sign-in answers (`api_url`, `apiUrl`, `verification_uri`) name it instead of the Host-selected origin. Unset: unchanged. See [Desktop sign-in through an edge router](#desktop-sign-in-through-an-edge-router) | | `SELFHOST_BOOTSTRAP_ORG_NAME` / `SELFHOST_BOOTSTRAP_ADMIN_EMAIL` | Optional, set together (or the org name with `SELFHOST_ADMIN_EMAILS`). First-boot bootstrap: creates the organization with this admin as owner and a default workspace bound to a new Relaycast workspace. Idempotent. See [docs/identity.md](identity.md) | | `SELFHOST_BOOTSTRAP_ADMIN_NAME` / `SELFHOST_BOOTSTRAP_WORKSPACE_NAME` | Optional display name for the admin (default: the email's local part) and the workspace name (default `Default`) | | `RELAYCAST_INTERNAL_SECRET` | Optional (`_FILE` supported), at least 32 bytes, equal to Relaycast's own internal secret. Lets the bootstrap create the default workspace through Relaycast's `POST /internal/workspaces` | @@ -527,6 +528,48 @@ Self-host has no Desktop-authority grant: approving a named host records nothing beyond the session itself. A session is bound to one workspace, so a `workspace` parameter naming another is refused (403). +### Desktop sign-in through an edge router + +Some deployments are reached through an edge router on a third site origin +that forwards `/cloud/...` here. Those requests arrive with this +service's own Host, so the rule above would name the API or dashboard origin, +and a Desktop that signed in through `` would refuse the answer. Set +`SELFHOST_ROUTED_SITE_URL` to that site's https origin (no path, query, +fragment or credentials). + +The rule: when the request carries exactly one `x-original-host` header whose +value, trimmed and lower-cased, equals the host of `SELFHOST_ROUTED_SITE_URL`, +these answers name `SELFHOST_ROUTED_SITE_URL` instead of the Host-selected +origin: + +- the browser handoff's loopback redirect `api_url` (`GET`/`POST /cloud/api/v1/cli/login`; + the redirect target itself is still the loopback `redirect_uri`) +- `apiUrl` from `POST /cloud/api/v1/auth/desktop/session` +- `apiUrl` from `POST /cloud/api/v1/auth/desktop/workspaces` +- `verification_uri` and `verification_uri_complete` from `POST /cloud/api/v1/auth/device/start` +- `api_url` from `POST /cloud/api/v1/auth/device/token` +- `api_url` from `POST /cloud/api/v1/auth/enrollment/token` +- `apiUrl` from `POST /cloud/api/v1/auth/token/refresh` + +A repeated header or one naming any other host falls back to the +Host-selected origin. Nothing else uses the setting: emailed sign-in and +password links carry one-time tokens and keep the Host-selected origin, OIDC +redirect URIs are registered per origin, the MCP endpoint URL is unchanged, +and browser origin checks and cookies are unchanged. A browser sign-in page +reached through that router is therefore not covered by this setting: the +Desktop consent form, like every cookie-authenticated write, still admits +only the API and dashboard origins, so a consent posted from the routed site +is refused. The device and enrollment-key sign-ins and every session-bearer +call are covered. + +The header only selects a configured value and is never echoed. A caller that +reaches the service directly and sends the header itself only receives the +operator-configured public origin in its own response; that origin scopes no +cookie, is never the target of a redirect this service sends and is not +stored. The router must +overwrite `x-original-host` with its own site's host rather than pass a +client's copy through. + ### Desktop enrollment keys (no browser) For managed rollouts an organization owner or admin mints a one-time key per diff --git a/openapi.yaml b/openapi.yaml index 648f82a..4bd9d25 100644 --- a/openapi.yaml +++ b/openapi.yaml @@ -1533,7 +1533,8 @@ paths: handoff access token bound to the challenge and redirects (307) to the loopback redirect_uri with state, access_token, access_token_expires_at and api_url (/cloud: the dashboard or - public origin the request arrived on). No + public origin the request arrived on, or SELFHOST_ROUTED_SITE_URL + through its edge router). No refresh token is placed in the URL. With desktop_host_name, a consent page asks the person to approve "Agent Relay Desktop on " first; its Approve posts the same parameters back (303 on approval). @@ -1623,7 +1624,7 @@ paths: accessTokenExpiresAt: { type: string, format: date-time } refreshToken: { type: string } refreshTokenExpiresAt: { type: string, format: date-time } - apiUrl: { type: string, description: "/cloud (the dashboard or public origin the request arrived on)" } + apiUrl: { type: string, description: "/cloud (the dashboard or public origin the request arrived on, or SELFHOST_ROUTED_SITE_URL through its edge router)" } tokenType: { type: string, enum: [Bearer] } "400": description: Missing codeVerifier @@ -9975,7 +9976,7 @@ components: api_url: type: string format: uri - description: "`/cloud`, as hosted Cloud returns; Desktop requires it. is SELFHOST_DASHBOARD_URL's origin when the request arrived on the dashboard host, otherwise SELFHOST_PUBLIC_URL." + description: "`/cloud`, as hosted Cloud returns; Desktop requires it. is SELFHOST_ROUTED_SITE_URL when set and the request carries one x-original-host header naming its host, else SELFHOST_DASHBOARD_URL's origin when the request arrived on the dashboard host, otherwise SELFHOST_PUBLIC_URL." DeviceLookup: type: object required: [user_code, client_name, desktop_host_name, status, expires_at, current_workspace_id, workspaces] @@ -10030,7 +10031,7 @@ components: apiUrl: type: string format: uri - description: "`/cloud` (the dashboard or public origin the request arrived on)" + description: "`/cloud` (the dashboard or public origin the request arrived on, or SELFHOST_ROUTED_SITE_URL through its edge router)" CloudBridgeOrganization: type: object required: [organizationId, opensAt, closesAt, setBy, updatedAt] diff --git a/src/app.ts b/src/app.ts index 9162f29..d32861d 100644 --- a/src/app.ts +++ b/src/app.ts @@ -588,6 +588,17 @@ export function createApp(input: { // api_url == /cloud, so sign-in answers name the origin the // request arrived on. Only these configured origins are ever echoed, so a // forged Host header cannot point a client elsewhere. + // + // A third origin (SELFHOST_ROUTED_SITE_URL, docs/repository-guide.md): an edge + // router on another site origin forwards /cloud/... here, so those + // requests arrive with this service's own Host, and the router sets + // x-original-host to its site's host. That header only selects among + // configured values; nothing from it is echoed. It is honoured without proof + // from the router because the origin goes back only to the caller that sent + // the header, is an operator-configured public value, scopes no cookie, is + // never the target of a redirect sent here and is not stored. That is also + // why only the Desktop/CLI API answers use apiSiteBaseUrl: emailed links, + // OIDC redirect URIs and the MCP endpoint URL keep the Host-selected origin. const siteBases = new Map([ [new URL(config.dashboardUrl).host.toLowerCase(), new URL(config.dashboardUrl).origin], [new URL(config.publicBaseUrl).host.toLowerCase(), config.publicBaseUrl.replace(/\/+$/, "")], @@ -596,6 +607,16 @@ export function createApp(input: { const host = typeof request.headers.host === "string" ? request.headers.host.trim().toLowerCase() : ""; return siteBases.get(host) ?? config.publicBaseUrl.replace(/\/+$/, ""); } + const routedSiteOrigin = config.routedSiteOrigin ?? null; + const routedSiteHost = routedSiteOrigin ? new URL(routedSiteOrigin).host.toLowerCase() : null; + function apiSiteBaseUrl(request: IncomingMessage): string { + if (routedSiteOrigin && routedSiteHost) { + // One header, one value: Node joins repeats with ", ", which never matches. + const forwarded = request.headers["x-original-host"]; + if (typeof forwarded === "string" && forwarded.trim().toLowerCase() === routedSiteHost) return routedSiteOrigin; + } + return siteBaseUrl(request); + } // Hosted MCP (shared-sessions facade): reads, team activity, capabilities. const amp = input.amp?.config.enabled ? input.amp : null; const providerProbes: ProviderProbes = input.providerProbes ?? {}; @@ -1651,7 +1672,7 @@ setTimeout(poll,${Math.max(1, started.intervalSeconds) * 1_000}); ...(consentedHostName ? { consentedHostName } : {}), }); response.writeHead(status, { - location: handoffCallbackUrl(login, issued, `${siteBaseUrl(request)}/cloud`), + location: handoffCallbackUrl(login, issued, `${apiSiteBaseUrl(request)}/cloud`), "cache-control": "no-store", "referrer-policy": "no-referrer", }); @@ -1746,7 +1767,7 @@ setTimeout(poll,${Math.max(1, started.intervalSeconds) * 1_000}); accessTokenExpiresAt: issued.accessTokenExpiresAt, refreshToken: issued.refreshToken, refreshTokenExpiresAt: issued.refreshTokenExpiresAt, - apiUrl: `${siteBaseUrl(request)}/cloud`, + apiUrl: `${apiSiteBaseUrl(request)}/cloud`, tokenType: "Bearer", }, true); return; @@ -1901,7 +1922,7 @@ setTimeout(poll,${Math.max(1, started.intervalSeconds) * 1_000}); accessTokenExpiresAt: issued.accessTokenExpiresAt, refreshToken: issued.refreshToken, refreshTokenExpiresAt: issued.refreshTokenExpiresAt, - apiUrl: `${siteBaseUrl(request)}/cloud`, + apiUrl: `${apiSiteBaseUrl(request)}/cloud`, tokenType: "Bearer", workspace: { id: target.id, @@ -1933,7 +1954,7 @@ setTimeout(poll,${Math.max(1, started.intervalSeconds) * 1_000}); // Under /cloud/api so it reaches this service on a shared dashboard // origin too (the ingress sends only /cloud/api and /login here). A GET // redirects to the dashboard's approval page. - const verification = `${siteBaseUrl(request)}/cloud/api/v1/auth/device/approve`; + const verification = `${apiSiteBaseUrl(request)}/cloud/api/v1/auth/device/approve`; json(response, 201, { device_code: started.deviceCode, user_code: started.userCode, @@ -2074,7 +2095,7 @@ setTimeout(poll,${Math.max(1, started.intervalSeconds) * 1_000}); scope: result.tokens.scopes.join(" "), // Hosted Cloud's shape: the API base is the site's /cloud mount, and // Desktop refuses a sign-in whose api_url is anything else. - api_url: `${siteBaseUrl(request)}/cloud`, + api_url: `${apiSiteBaseUrl(request)}/cloud`, }, true); return; } @@ -2134,7 +2155,7 @@ setTimeout(poll,${Math.max(1, started.intervalSeconds) * 1_000}); access_token_expires_at: result.tokens.accessTokenExpiresAt, refresh_token_expires_at: result.tokens.refreshTokenExpiresAt, scope: result.tokens.scopes.join(" "), - api_url: `${siteBaseUrl(request)}/cloud`, + api_url: `${apiSiteBaseUrl(request)}/cloud`, // Workspace policy (docs/workspace-policy.md): whether this session is // managed (the key carries admin policy consent), the revision to // compare a cached policy against, and the document itself so the @@ -2170,7 +2191,7 @@ setTimeout(poll,${Math.max(1, started.intervalSeconds) * 1_000}); refreshToken: issued.refreshToken, refreshTokenExpiresAt: issued.refreshTokenExpiresAt, tokenType: "Bearer", - apiUrl: `${siteBaseUrl(request)}/cloud`, + apiUrl: `${apiSiteBaseUrl(request)}/cloud`, }, true); return; } diff --git a/src/config.ts b/src/config.ts index 9c7062e..4d8028d 100644 --- a/src/config.ts +++ b/src/config.ts @@ -20,6 +20,13 @@ export type SelfhostConfig = { githubApp?: GithubAppConfig | null; databaseUrl: string; publicBaseUrl: string; + /** + * SELFHOST_ROUTED_SITE_URL: a third site origin whose edge router forwards + * /cloud/... here and sets x-original-host. Desktop/CLI sign-in + * answers name it when that header matches; null (unset) keeps the + * Host-selected origin everywhere. + */ + routedSiteOrigin?: string | null; relaycastUrl: string; relaycastPublicUrl: string; /** @@ -357,6 +364,31 @@ export function serviceUrl(env: Env, name: string): string { return value.replace(/\/+$/, ""); } +// Optional third site origin (an edge router's site that forwards /cloud +// here). https only: Desktop is told to call it as its API base. +function loadRoutedSiteOrigin(env: Env): string | null { + const name = "SELFHOST_ROUTED_SITE_URL"; + const value = env[name]?.trim(); + if (!value) return null; + let url: URL; + try { + url = new URL(value); + } catch { + throw new Error(`${name} must be an https origin without credentials, path, query, or fragment`); + } + if ( + url.protocol !== "https:" || + url.username || + url.password || + url.search || + url.hash || + (url.pathname !== "" && url.pathname !== "/") + ) { + throw new Error(`${name} must be an https origin without credentials, path, query, or fragment`); + } + return url.origin; +} + function publicServiceUrl(env: Env, name: string): string { const value = required(env, name); const maxOriginLength = 253 + "https://".length + ":65535".length; @@ -502,6 +534,7 @@ export function loadConfig(env: Env = process.env): SelfhostConfig { return { databaseUrl: loadDatabaseUrl(env), publicBaseUrl: serviceUrl(env, "SELFHOST_PUBLIC_URL"), + routedSiteOrigin: loadRoutedSiteOrigin(env), relaycastUrl: serviceUrl(env, "RELAYCAST_URL"), relaycastPublicUrl: publicServiceUrl(env, "RELAYCAST_PUBLIC_URL"), relayhistoryUrl: sessionReadApi.url, diff --git a/test/config.test.ts b/test/config.test.ts index 97bac2b..a07cda4 100644 --- a/test/config.test.ts +++ b/test/config.test.ts @@ -54,6 +54,20 @@ test("SELFHOST_RELAYGATE_PUBLIC_URL is optional and must be a public https origi } }); +test("SELFHOST_ROUTED_SITE_URL is optional and must be an https origin", () => { + assert.equal(loadConfig(completeEnv).routedSiteOrigin, null); + assert.equal(loadConfig({ ...completeEnv, SELFHOST_ROUTED_SITE_URL: " " }).routedSiteOrigin, null); + assert.equal(loadConfig({ ...completeEnv, SELFHOST_ROUTED_SITE_URL: "https://site.example.test" }).routedSiteOrigin, + "https://site.example.test"); + assert.equal(loadConfig({ ...completeEnv, SELFHOST_ROUTED_SITE_URL: " https://Site.Example.Test/ " }).routedSiteOrigin, + "https://site.example.test"); + for (const bad of ["http://site.example.test", "https://site.example.test/cloud", "https://site.example.test/?a=1", + "https://site.example.test/#top", "https://u:p@site.example.test", "not a url"]) { + assert.throws(() => loadConfig({ ...completeEnv, SELFHOST_ROUTED_SITE_URL: bad }), + /SELFHOST_ROUTED_SITE_URL must be an https origin without credentials, path, query, or fragment/, bad); + } +}); + test("SELFHOST_DEFAULT_SHARING_MODE is optional and one of all, new or selected", () => { const unset = loadConfig(completeEnv); assert.equal(unset.defaultSharingMode, undefined); diff --git a/test/desktop-site-origin.test.ts b/test/desktop-site-origin.test.ts index 001a1a8..c257057 100644 --- a/test/desktop-site-origin.test.ts +++ b/test/desktop-site-origin.test.ts @@ -26,7 +26,14 @@ type Raw = { status: number; headers: Record; + }, ): Promise { const target = new URL(origin); const payload = options.body === undefined ? undefined : JSON.stringify(options.body); @@ -37,6 +44,7 @@ function raw( path, method: options.method ?? "GET", headers: { + ...options.headers, host: options.host, ...(options.token ? { authorization: `Bearer ${options.token}` } : {}), ...(options.cookie ? { cookie: options.cookie } : {}), @@ -62,7 +70,7 @@ function raw( }); } -async function setup(t: test.TestContext) { +async function setup(t: test.TestContext, overrides: Partial = {}) { const database = new PGliteDatabase(); await migrate(database); const control = createServer(); @@ -82,6 +90,7 @@ async function setup(t: test.TestContext) { dashboardUrl: `${DASHBOARD_SITE}/`, port: 0, host: "127.0.0.1", + ...overrides, }; const store = new ControlPlaneStore(database, KEYRING, 0); control.on("request", createApp({ config, store })); @@ -217,3 +226,189 @@ test("an unconfigured Host header falls back to SELFHOST_PUBLIC_URL, never the H assert.equal(tokens.body.api_url, `${API_SITE}/cloud`); assert(!tokens.text.includes("evil.example")); }); + +// SELFHOST_ROUTED_SITE_URL: an edge router on a third site origin forwards +// /cloud/... here, so the request carries this service's own Host and +// the router's x-original-host. Only the Desktop/CLI API answers follow it, +// and only for one header value equal to the configured origin's host. +const ROUTED_SITE = "https://site.proof.test"; +const ROUTED = { routedSiteOrigin: ROUTED_SITE }; +const ROUTER = { "x-original-host": new URL(ROUTED_SITE).host }; + +type SignIn = { + callbackApiUrl: string | null; + exchangeApiUrl: unknown; + refreshApiUrl: unknown; + verificationUri: unknown; + verificationUriComplete: unknown; + deviceApiUrl: unknown; + /** The device flow's session (cli:auth). */ + accessToken: string; + /** The browser flow's exchanged Desktop session (desktop:workspaces). */ + desktopAccessToken: string; + /** Every answer's headers and body, for "never echoed" checks. */ + seen: string; +}; + +/** Both Desktop sign-in flows and a refresh on `host`, each answer request carrying `headers`. */ +async function signIn( + origin: string, + ownerId: string, + workspaceId: string, + host: string, + headers: Record = {}, +): Promise { + const session = await browserSession(origin, host, ownerId, workspaceId); + const handoff = await raw(origin, loginPath(), { host, cookie: session, headers }); + assert.equal(handoff.status, 307); + const callback = new URL(String(handoff.headers.location)); + // The redirect target is the stored loopback URI whatever the header says. + assert.equal(`${callback.origin}${callback.pathname}`, "http://127.0.0.1:5123/callback/STATE1"); + const exchanged = await raw(origin, "/cloud/api/v1/auth/desktop/session", { + host, + method: "POST", + token: callback.searchParams.get("access_token")!, + body: { codeVerifier: VERIFIER }, + headers, + }); + assert.equal(exchanged.status, 200); + const refreshed = await raw(origin, "/cloud/api/v1/auth/token/refresh", { + host, + method: "POST", + body: { refreshToken: exchanged.body.refreshToken }, + headers, + }); + assert.equal(refreshed.status, 200); + const started = await raw(origin, "/cloud/api/v1/auth/device/start", { + host, + method: "POST", + body: { client_name: "Agent Relay Desktop" }, + headers, + }); + assert.equal(started.status, 201); + await approve(origin, started.body.user_code, ownerId, workspaceId); + const tokens = await raw(origin, "/cloud/api/v1/auth/device/token", { + host, + method: "POST", + body: { device_code: started.body.device_code }, + headers, + }); + assert.equal(tokens.status, 200); + return { + callbackApiUrl: callback.searchParams.get("api_url"), + exchangeApiUrl: exchanged.body.apiUrl, + refreshApiUrl: refreshed.body.apiUrl, + verificationUri: started.body.verification_uri, + verificationUriComplete: started.body.verification_uri_complete, + deviceApiUrl: tokens.body.api_url, + accessToken: tokens.body.access_token, + // The refresh above rotated the exchanged pair; this is the live one. + desktopAccessToken: refreshed.body.accessToken, + seen: [handoff, exchanged, refreshed, started, tokens] + .map((answer) => `${JSON.stringify(answer.headers)}\n${answer.text}`) + .join("\n"), + }; +} + +function assertAnswersName(answers: SignIn, site: string, label: string) { + assert.equal(answers.callbackApiUrl, `${site}/cloud`, label); + assert.equal(answers.exchangeApiUrl, `${site}/cloud`, label); + assert.equal(answers.refreshApiUrl, `${site}/cloud`, label); + assert.equal(answers.verificationUri, `${site}/cloud/api/v1/auth/device/approve`, label); + assert(String(answers.verificationUriComplete).startsWith(`${site}/cloud/api/v1/auth/device/approve?user_code=`), label); + assert.equal(answers.deviceApiUrl, `${site}/cloud`, label); +} + +test("a Desktop signing in through the edge router gets the routed site in every sign-in answer", async (t) => { + const { origin, ownerId, workspaceId } = await setup(t, ROUTED); + const answers = await signIn(origin, ownerId, workspaceId, new URL(API_SITE).host, ROUTER); + assertAnswersName(answers, ROUTED_SITE, "through the router"); +}); + +for (const site of [DASHBOARD_SITE, API_SITE]) { + test(`with a routed site configured, a Desktop signing in directly through ${site} still gets ${site}`, async (t) => { + const { origin, ownerId, workspaceId } = await setup(t, ROUTED); + const answers = await signIn(origin, ownerId, workspaceId, new URL(site).host); + assertAnswersName(answers, site, "no header"); + assert(!answers.seen.includes("site.proof.test")); + }); +} + +test("only one x-original-host value equal to the routed host selects it, and the header is never echoed", async (t) => { + const { origin, ownerId, workspaceId } = await setup(t, ROUTED); + const host = new URL(API_SITE).host; + const matching = await signIn(origin, ownerId, workspaceId, host, { "x-original-host": " SITE.Proof.TEST " }); + assertAnswersName(matching, ROUTED_SITE, "case variant with spaces"); + for (const value of [ + "evil.example", + "site.proof.test, evil.example", + ["site.proof.test", "evil.example"], + ["site.proof.test", "site.proof.test"], + ]) { + const label = JSON.stringify(value); + const answers = await signIn(origin, ownerId, workspaceId, host, { "x-original-host": value }); + assertAnswersName(answers, API_SITE, label); + assert(!answers.seen.includes("evil.example"), label); + } +}); + +test("without a routed site configured, x-original-host changes nothing", async (t) => { + const { origin, ownerId, workspaceId } = await setup(t); + const answers = await signIn(origin, ownerId, workspaceId, new URL(API_SITE).host, ROUTER); + assertAnswersName(answers, API_SITE, "routed site unset"); + assert(!answers.seen.includes("site.proof.test")); +}); + +test("the MCP endpoint URL keeps the Host-selected origin through the edge router", async (t) => { + const { origin, ownerId, workspaceId } = await setup(t, ROUTED); + const host = new URL(API_SITE).host; + const { accessToken } = await signIn(origin, ownerId, workspaceId, host, ROUTER); + const described = await raw(origin, "/api/v1/mcp/shared-sessions", { + host, + method: "POST", + token: accessToken, + headers: { ...ROUTER, accept: "application/json, text/event-stream" }, + body: { jsonrpc: "2.0", id: 1, method: "tools/call", params: { name: "describe_capabilities", arguments: {} } }, + }); + assert.equal(described.status, 200); + assert.equal(described.body.result.structuredContent.endpoint.url, `${API_SITE}/api/v1/mcp/shared-sessions`); + assert(!described.text.includes("site.proof.test")); +}); + +test("a Desktop workspace switch through the edge router gets the routed site, and the Host-selected site without the header", async (t) => { + const { origin, ownerId, workspaceId } = await setup(t, ROUTED); + const host = new URL(API_SITE).host; + // Each switch answers with a fresh pair and retires the one that asked. + let { desktopAccessToken: token } = await signIn(origin, ownerId, workspaceId, host); + for (const [headers, site] of [[ROUTER, ROUTED_SITE], [{}, API_SITE]] as const) { + const switched = await raw(origin, "/cloud/api/v1/auth/desktop/workspaces", { + host, + method: "POST", + token, + body: { workspaceId }, + headers, + }); + assert.equal(switched.status, 200, switched.text); + assert.equal(switched.body.apiUrl, `${site}/cloud`); + token = switched.body.accessToken; + } +}); + +test("an enrollment key exchange through the edge router gets the routed site, and the Host-selected site without the header", async (t) => { + const { origin, ownerId, workspaceId } = await setup(t, ROUTED); + const host = new URL(API_SITE).host; + // Member self-mint from the owner's device session: a single-use sh_ek_ key per exchange. + const { accessToken } = await signIn(origin, ownerId, workspaceId, host); + for (const [headers, site] of [[ROUTER, ROUTED_SITE], [{}, API_SITE]] as const) { + const minted = await raw(origin, "/api/v1/me/enrollment-keys", { host, method: "POST", token: accessToken, body: {} }); + assert.equal(minted.status, 201, minted.text); + const exchanged = await raw(origin, "/api/v1/auth/enrollment/token", { + host, + method: "POST", + body: { enrollment_key: minted.body.accessToken, client_name: "Agent Relay Desktop", desktop_host_name: "build-01" }, + headers, + }); + assert.equal(exchanged.status, 200, exchanged.text); + assert.equal(exchanged.body.api_url, `${site}/cloud`); + } +});