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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ assigned at release.

## Unreleased

- Added: 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.
Expand Down
43 changes: 43 additions & 0 deletions docs/repository-guide.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 `<site>/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` |
Expand Down Expand Up @@ -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 `<site>/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 `<site>` 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
Expand Down
9 changes: 5 additions & 4 deletions openapi.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -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 (<site>/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 <host>" first;
its Approve posts the same parameters back (303 on approval).
Expand Down Expand Up @@ -1623,7 +1624,7 @@ paths:
accessTokenExpiresAt: { type: string, format: date-time }
refreshToken: { type: string }
refreshTokenExpiresAt: { type: string, format: date-time }
apiUrl: { type: string, description: "<site>/cloud (the dashboard or public origin the request arrived on)" }
apiUrl: { type: string, description: "<site>/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
Expand Down Expand Up @@ -9975,7 +9976,7 @@ components:
api_url:
type: string
format: uri
description: "`<site>/cloud`, as hosted Cloud returns; Desktop requires it. <site> is SELFHOST_DASHBOARD_URL's origin when the request arrived on the dashboard host, otherwise SELFHOST_PUBLIC_URL."
description: "`<site>/cloud`, as hosted Cloud returns; Desktop requires it. <site> 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]
Expand Down Expand Up @@ -10030,7 +10031,7 @@ components:
apiUrl:
type: string
format: uri
description: "`<site>/cloud` (the dashboard or public origin the request arrived on)"
description: "`<site>/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]
Expand Down
35 changes: 28 additions & 7 deletions src/app.ts
Original file line number Diff line number Diff line change
Expand Up @@ -588,6 +588,17 @@ export function createApp(input: {
// api_url == <its site>/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 <site>/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<string, string>([
[new URL(config.dashboardUrl).host.toLowerCase(), new URL(config.dashboardUrl).origin],
[new URL(config.publicBaseUrl).host.toLowerCase(), config.publicBaseUrl.replace(/\/+$/, "")],
Expand All @@ -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 ?? {};
Expand Down Expand Up @@ -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",
});
Expand Down Expand Up @@ -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;
Expand Down Expand Up @@ -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,
Expand Down Expand Up @@ -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,
Expand Down Expand Up @@ -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;
}
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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;
}
Expand Down
33 changes: 33 additions & 0 deletions src/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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
* <site>/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;
/**
Expand Down Expand Up @@ -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;
Expand Down Expand Up @@ -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,
Expand Down
14 changes: 14 additions & 0 deletions test/config.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down
Loading
Loading