diff --git a/AGENTS.md b/AGENTS.md index 03cd434c4..e6130cf52 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -69,6 +69,9 @@ Shared foundations in `lib/omp/`: `lib/hosts/hub.ts` for a remote one). - `auth-gateway.ts` — shared, idle-killed `omp auth-gateway stdio` child: omp's own credentials and models behind JSON-line gateway requests. +- `auth-broker.ts` — idle-stopped `omp auth-broker serve` child of the web + server (started on the first forwarded request, stopped after 5 minutes with + none in flight): `brokerFetch`, `abortBrokerRequests`. --- @@ -100,8 +103,9 @@ app/api/ events/route.ts GET multiplexed SSE | POST subscribe/unsubscribe channels events/link/route.ts GET WebSocket upgrade: the browser link (lib/browser-link.ts), bound to the request's web session; gated like every API route, 426 without an upgrade transport-metrics/route.ts GET { now } (the SSE clock probe) | POST { samples } → /omp-web/transport-metrics.jsonl - hosts/route.ts GET hosts (this machine first) | POST { label } → token once + login command | PATCH { id, label?, allowAgentStart? } (`local`: label only, empty resets to "This machine") | DELETE ?id= revoke (registry first, then close the link); 503 if hosts.json is unreadable + hosts/route.ts GET hosts (this machine first) | POST { label } → token once + login command | PATCH { id, label?, allowAgentStart?, shareCredentials? } (`local`: label only, empty resets to "This machine"; `shareCredentials` on `local` is 400) | DELETE ?id= revoke (registry first, then close the link); 503 if hosts.json is unreadable hosts/link/route.ts GET WebSocket upgrade (the `ompweb host` daemon; bearer checked before the upgrade, skipped by the `proxy.ts` gate) | POST 426 for pre-WebSocket daemons + hosts/broker/[...path]/route.ts allow-listed forwarding of an omp auth broker's endpoints for a host with `shareCredentials`; authenticated by the host token, outside the password gate (`proxy.ts` `UNGATED`); see "Remote hosts → Shared credentials" notifications/devices/route.ts GET VAPID key + subscribed | PUT { deviceId, prefs, subscription? } notifications/presence/route.ts POST { clientId, deviceId, visible, sessionId, seq } notifications/test/route.ts POST { deviceId } send a test push (502 on push-service refusal) @@ -148,6 +152,7 @@ lib/ hub.ts main side: the link's upgrade and `websocket` handler (`handleLinkUpgrade`, `hostLinkSocket`), `RemoteHost`, `getHost`, `listHosts`, adoption of live children (`reattach`/`adopt`), orphans, `freezeHostLinks`, `hosts` change events daemon.ts daemon side: `runHostDaemon` (reconnect, buffering, op dispatch, hello with each child's `{sessionId, cwd, pending}`; follows a `host.json` url or token change when a dial fails; loopback redials at most 3 s apart) pending-requests.ts daemon side: `PendingRequests`, a channel's still-open blocking requests and current session id for the hello + daemon-broker.ts daemon side: the loopback forwarder that gives a sharing host's omp processes `OMP_AUTH_BROKER_URL`/`OMP_AUTH_BROKER_TOKEN` (`credentialsEnv`); forwards to the link's server with the link's host token registry.ts `/omp-web/hosts.json`: create/update/revoke, token hashing and lookup; the `local` record (`rotateLocalHostToken`, `customLocalLabel`) session-index.ts sessions and projects across hosts, cached per host; `hostForSessionId`, `sessionSpawnTarget`, `invalidateLocalSessionLists` update-types.ts shared per-host software status and operation contract @@ -449,10 +454,12 @@ The table is static imports, not a runtime glob, so `bun build --compile` (`scri v6 (uploads: hub → daemon binary frames, `upload_ack`, `uploadStart`/ `uploadAbort`/`uploadAttach`) keeps v4 and v5. v7 adds multi-server joins, host-owned lifecycle, callback routing and channel/list discovery: - `MIN_LINK_PROTOCOL_VERSION` is 4 and `LINK_PROTOCOL_VERSION` 7 (literal + `MIN_LINK_PROTOCOL_VERSION` is 4 and `LINK_PROTOCOL_VERSION` 9 (literal one-liners: the deploy script parses them with `sed`); a v4 daemon gets no `part`, whole lines and no unacked window (`link.sender.parts`); a v4/v5 - daemon gets 426 for uploads. Main keeps at least N-1, and + daemon gets 426 for uploads. v8 (host pool) adds `capacity` reports, `creationId` + and `preparePoolProject`; v9 adds `open.launch.shareCredentials` (see "Shared + credentials" below). Main keeps at least N-1, and dropping one is an explicit decision (a hello outside the range gets close 4426 with `{"serverVersion":N}`, a pre-WebSocket daemon's POST gets 426). Once the WebSocket experiments end, the first version @@ -520,11 +527,48 @@ The table is static imports, not a runtime glob, so `bun build --compile` (`scri session resumes after its host's hello (`resumeOnHostLink`, `lib/session-resume.ts`), once, after the orphan's exit. - **Proxy exclusion.** The `proxy.ts` gate lets exactly `/api/hosts/link` through - (the `UNGATED` pattern names that path, no subpaths): the daemon has no + (the `UNGATED` pattern names that path, no subpaths) and the prefix + `/api/hosts/broker/v1/` (below): the daemon has no session cookie, so it authenticates with its bearer token instead. The hub verifies the `Authorization: Bearer ` header before the upgrade (401 unknown token, 503 unreadable `hosts.json` or frozen server). Keep - `/api/hosts` itself behind the proxy. + `/api/hosts` itself behind the proxy. `/api/hosts/broker/v1/` is the second + ungated path (the `UNGATED` pattern names that prefix; anything else under + `/api/hosts/broker/` stays gated): the daemon authenticates there with its + host token too. A reverse proxy must pass it without its own authentication, + without response buffering (the snapshot stream stays open) and without + redirects. +- **Shared credentials** (`docs/specs/2026-11-10-shared-credentials-design.md`). + A linked host's `shareCredentials` (default off; `local` never has it) makes the + omp processes its daemon spawns use the credentials of the server machine + through `omp auth-broker serve`; ompweb still never reads `agent.db`. + - **Route.** `app/api/hosts/broker/[...path]/route.ts` checks the host token + before reading a body (401 unknown token, 403 `local` or sharing off, 503 + unreadable `hosts.json` or no broker), then forwards only an allow-list of + broker endpoints (snapshot, its stream, health, `refresh`, `disable`, + `block`, `blocks`, usage), body at most 1 MiB, with a handful of request + and response headers. Everything else answers 404, `POST /v1/credential` + included: a host cannot upload a credential. It turns the idle timeout off + after authenticating. Turning sharing off or revoking the host calls + `abortBrokerRequests` for it and later requests get 403 or 401. + - **Daemon.** `open.launch.shareCredentials` (link v9) makes the daemon start omp + with the loopback forwarder's URL and a secret it generates at each start. The + host token never enters an omp environment: the forwarder adds the link's + current token to each request, sends it to that link's server and refuses + redirects. + - **No fallback.** The hub answers 426 `host_upgrade_required` for a sharing + host on a v4–v8 daemon, and the daemon refuses to spawn on an omp older than + 15.13.1. Starting a session is refused; it never uses the host's own stored + logins. Joining a running session is never refused. + - **Which server decides.** The server whose `open` starts a process decides + its credentials, an advisor replacement included (`withCredentials` in + `lib/hosts/daemon-channels.ts`); a server that joins a running process does + not change them. The resume manifest keeps the server URL + (`launch.credentialsServer`). A launch whose link is no longer in `host.json` + is refused with 409 `credentials_link_gone`, on resume as on a new start. + - **Scope.** The host can read current access tokens and stored API keys; + refresh tokens stay on the server. Not shared: `models.yml` custom providers, + environment-variable API keys, omp settings. - **Remote paths never reach `allowFileRoot`** or any other main-side filesystem check: they mean nothing on main. `startNewRpcSession` calls `allowFileRoot` and the local session-list invalidation only for the local @@ -1556,6 +1600,7 @@ during the wait. ### Auth and model config - Auth flows go through RPC commands (`get_login_providers`, `login`, `get_logout_accounts`, `logout`) against the omp child process; credentials live in omp's `agent.db` (SQLite) which omp-web never touches directly. `/api/auth/accounts/[provider]` lists stored accounts and removes one by `credentialId`; omp without those commands reports `supported: false` and the UI falls back to the read-only `omp usage` account list. +- Linked hosts with `shareCredentials` read this machine's credentials through `lib/omp/auth-broker.ts`, the `omp auth-broker serve` child (the token comes from `omp auth-broker token` and stays in the server process; a refused token stops the child and the next request starts a new one). The broker reloads the store on every snapshot, so a login or logout in Settings reaches every omp process a sharing host starts afterwards; a running process picks it up the next time it is used (omp stops listening for updates after 20 seconds without activity and resumes on its next use) and keeps the access tokens and API keys it has already loaded until it ends. - The Models panel reads and writes `models.yml` in the omp agent directory (`~/.omp/agent/models.yml`, `.yaml` fallback). - API-key status endpoints must never return the raw key. diff --git a/CHANGELOG.md b/CHANGELOG.md index fc2526cef..319b4683d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -8,6 +8,7 @@ All notable changes to **omp-web** (`@kahme247/ompweb`) are documented in this f ### Added +- **Hosts can use the server's provider logins.** **Settings → Hosts** has a per-host toggle, **Use this server's provider logins**, off by default; turning it on asks for confirmation. Sessions started on that host then use the logins stored on the ompweb server instead of the host's own, through `omp auth-broker serve` on the server and a loopback forwarder in the host daemon. The host token never enters an omp process's environment, and OAuth refresh tokens never leave the server machine; the host can read current access tokens and stored API keys. Starting a session on a sharing host needs a daemon on link protocol v9 and omp 15.13.1 or newer, and is refused otherwise rather than falling back to the host's own logins. Custom providers in `models.yml`, environment-variable API keys and omp settings are not shared. A reverse proxy must let `/api/hosts/broker/` through without its own authentication, response buffering or redirects. - **Windows hosts can be pool workers and accept local maintenance controls.** `ompweb host status`, `drain` and `resume` now work on Windows through a named pipe with a random name and a per-start token, kept in `/omp-web/host-control.json`; requests without the current token are refused. Windows hosts also report CPU busy time and available memory, so pools can place sessions on them. Windows reports no load average, so CPU pressure there comes from busy time alone. - **Archive and restore sessions on linked hosts.** Archiving now works for sessions on any linked machine, not only this one. The Archived Sessions browser lists every host's archive, shows which host each session is on, and restores it on that host. A host that is offline or runs an older ompweb host is named in the browser instead of hiding its archive silently. Restore rejects a session ID already active on any registered host, so every registered host must be online to restore, even an archive on this machine; the browser names the offline host that blocks it. A per-session claim stops web-server processes that share one agent directory from restoring the same session together; it does not coordinate separate web servers that share a daemon. A restore on another host keeps running when the web server stops waiting for it (after 30 s, or when the link drops), so the session stays claimed until that host's daemon process confirms it stopped: restoring the same ID again, on any host, is refused until then instead of creating a second active copy. Only the daemon process that took the restore can confirm that, so if the daemon was replaced, restarted or shut down meanwhile, or its host was unregistered, the session stays blocked: there is no timeout and no automatic clearing, and recovery is manual (see AGENTS.md). A restored session's attachments and other files are put back before the session becomes visible, so a file attached from another tab at that moment can no longer fail the restore or block retrying it. Restore streams archives with fixed 256 MiB compressed and expanded limits and rejects unsupported session IDs before consuming the archive. - **Several web apps can share one host daemon and the same live sessions.** Link additional servers with `ompweb host login --add --url ` (token from stdin). Prompts, tool progress, results and dialogs stay synchronized, and restarting one web app leaves the other connected to the same omp process. Link protocol v7 moves session startup, idle cleanup and interrupted-run recovery into the host; older links remain supported without sharing their processes. Schedule the first daemon upgrade while its host is quiescent. diff --git a/DESIGN.md b/DESIGN.md index 1b2dbc9a2..6c5a71620 100644 --- a/DESIGN.md +++ b/DESIGN.md @@ -99,8 +99,11 @@ with their open blocking requests replayed. A direct spawn path would tie every run to the web server's lifetime, which is why none exists. The CLI boundary above holds on every machine: a remote machine runs its own -installed `omp`, its own `~/.omp/agent` and its own credentials. ompweb only -routes. `RpcProcess` takes its byte pipe (`RpcTransport`) from the host, so the +installed `omp`, its own `~/.omp/agent` and its own credentials, unless sharing is +turned on for that host (Settings → Hosts): then its sessions use the server's +provider logins through `omp auth-broker serve`, and the host never gets a +refresh token. ompweb only routes. `RpcProcess` takes its byte pipe +(`RpcTransport`) from the host, so the session wrapper, event streams, notifications and queue handle frames without knowing where omp runs. Session routes address a session by id; the owning host resolves the file path, so a remote path never reaches the serving diff --git a/README.md b/README.md index feb3b997c..95d520b58 100644 --- a/README.md +++ b/README.md @@ -183,6 +183,8 @@ restart, without signing out of Windows. Forward WebSocket upgrades on `/api/events/link` (browsers) and `/api/hosts/link` (hosts); without the upgrade, a browser falls back to server-sent events after a few seconds. In nginx that means `proxy_http_version 1.1;`, `proxy_set_header Upgrade $http_upgrade;`, `proxy_set_header Connection "upgrade";`, and a `proxy_read_timeout` well above 30 s. +Hosts that [use the server's provider logins](#use-the-servers-provider-logins-on-a-host) also call `/api/hosts/broker/`, authenticated by their host token. That path must reach ompweb without the proxy's own authentication (a proxy login page or `auth_request` would block the daemon), without response buffering (it carries a long-lived event stream; in nginx, `proxy_buffering off;`) and without redirects. + ### Two services: the web server and the local daemon ompweb runs this machine's `omp` sessions through a small daemon, `ompweb host`, @@ -480,7 +482,8 @@ host (KDE Plasma, and most Wayland/X11 desktops). ## Run sessions on another machine One ompweb can start and watch omp sessions on other machines. Each machine keeps -its own `omp` install, `~/.omp/agent` directory, sessions, and credentials; +its own `omp` install, `~/.omp/agent` directory, sessions, and credentials (unless you +[share the server's provider logins](#use-the-servers-provider-logins-on-a-host)); ompweb only routes. The remote machine needs `omp` and either Node 24 (for `npx`) or the [single binary](#single-binary), and must be able to reach the ompweb server over HTTP(S). It dials out, so it can sit behind NAT. @@ -550,7 +553,7 @@ everything else on it: they resume when it wakes, and the link returns then. A docked or no-sleep setup keeps running with the lid closed. Revoking a host in Settings closes its link and the daemon stops its omp processes. -A reverse proxy must forward the upgrade on `/api/hosts/link`; see [Behind a reverse proxy](#behind-a-reverse-proxy). +A reverse proxy must forward the upgrade on `/api/hosts/link`. For hosts that share the server's logins it must also pass `/api/hosts/broker/` without the proxy's own authentication and without response buffering; see [Behind a reverse proxy](#behind-a-reverse-proxy). Update ompweb on the server before its hosts: a host from before this version shows **needs upgrade** until it is updated. @@ -602,6 +605,21 @@ Notes: is switched on for it in Settings → Hosts. An agent running on a remote host always asks before it starts or messages a session on this machine. +### Use the server's provider logins on a host + +By default a host uses its own omp logins. Turn on **Use this server's provider logins** for a host in **Settings → Hosts** and the sessions started there use the logins stored on the ompweb server instead, so you log in to a provider once. The setting is per host and off by default; turning it on asks for confirmation. This machine does not have it, because it already uses the server's logins. + +- **What is shared:** the provider logins stored on the server (OAuth logins and stored API keys). The server runs `omp auth-broker serve` for this and starts it on the first request; it stops after 5 minutes without one. +- **When a change reaches a host:** every omp process started after a login or logout on the server uses it. A running process picks it up the next time it is used, because omp stops listening for updates after 20 seconds without activity and resumes on its next use. A running process keeps the access tokens and API keys it has already loaded until it ends. +- **What is not shared:** custom providers in `models.yml`, API keys set through environment variables (a host's own environment keys still apply there), and omp settings. +- **Requirements:** the server's own `omp` must provide `omp auth-broker`. The host's daemon must speak link protocol 9 and its `omp` must be 15.13.1 or newer; otherwise starting a session on that host is refused with a message naming what to update. It never falls back to the host's own stored logins. Joining a session that is already running is not refused. The setting applies to omp processes started after you change it. +- **What the host can read:** the current access token of every OAuth login and every stored API key, in full. A process running as the daemon's user can do the same. OAuth refresh tokens never leave the server machine, and the host cannot add or replace a login. It can mark a login disabled or rate-limited for every machine. +- **Turning it off:** turning sharing off, or revoking the host, aborts the host's open requests to the server and refuses later ones. Access tokens the host already read stay valid until they expire, and API keys until you rotate them at the provider. +- **Dependence on the server:** a running session asks the server whenever an access token needs a refresh, so it fails to authenticate once its token expires while the server is unreachable. An `omp` you run yourself in the host's terminal is unaffected. +- **Troubleshooting:** when sessions on a sharing host fail at startup, check the server log for `[omp-web] broker` lines and that the reverse proxy lets `/api/hosts/broker/` through. + +The host token is not put in an omp process's environment. The daemon listens on a loopback port with a secret it generates at each start, gives omp that address and secret, and forwards the requests to the server with the host token. + ### Keep a host running as a service These run the [single binary](#single-binary) in host mode. On Linux and Windows a diff --git a/app/api/hosts/broker/[...path]/route.ts b/app/api/hosts/broker/[...path]/route.ts new file mode 100644 index 000000000..3717104bd --- /dev/null +++ b/app/api/hosts/broker/[...path]/route.ts @@ -0,0 +1,107 @@ +import { readBodyWithinLimit, RequestBodyTooLargeError } from "@/lib/bounded-form-data"; +import { hostForToken, HostRegistryUnreadableError, LOCAL_HOST_ID, type HostRecord } from "@/lib/hosts/registry"; +import { AuthBrokerUnavailableError, brokerFetch } from "@/lib/omp/auth-broker"; + +// A linked host's daemon forwards omp's auth-broker calls here (lib/omp/auth-broker.ts runs the broker). proxy.ts does +// not gate the /v1/ paths: the host's bearer token is checked before anything else is read. + +const MAX_BODY_BYTES = 1024 * 1024; +const noStore = { "cache-control": "no-store" }; +const fail = (error: string, status: number) => Response.json({ error }, { status, headers: noStore }); + +// Anything not listed is 404, including POST /v1/credential: a host cannot add or replace a credential. +const ALLOWED: readonly (readonly [method: string, path: RegExp])[] = [ + ["GET", /^\/v1\/(?:healthz|snapshot|snapshot\/stream|credentials\/disabled|usage|usage\/history|usage\/clients)$/], + ["POST", /^\/v1\/credential\/\d+\/(?:refresh|disable|block)$/], + ["DELETE", /^\/v1\/credential\/\d+\/blocks?$/], + ["POST", /^\/v1\/usage\/(?:observed|stale)$/], +]; +const REQUEST_HEADERS = ["content-type", "accept", "if-none-match", "omp-auth-broker-capabilities"]; +const RESPONSE_HEADERS = ["content-type", "etag", "cache-control", "vary"]; +// A path the allow-list has not vetted reaches the log only as plain `/v1/` text. +const PLAIN_PATH = /^\/v1\/[A-Za-z0-9/_-]*$/; + +/** Never a token, a query, a body or an error message: a broker failure names only its class. */ +function log(hostId: string, method: string, path: string, status: number, reason?: string) { + console.log(`[omp-web] broker ${hostId} ${method} ${path} ${status}${reason ? ` ${reason}` : ""}`); +} + +function only(source: Headers, names: readonly string[]): Headers { + const picked = new Headers(); + for (const name of names) { + const value = source.get(name); + if (value !== null) picked.set(name, value); + } + return picked; +} + +/** The sharing host the bearer token names, or the refusal to answer with (a 403 is logged; a 401 has no host to name). */ +function admit(request: Request, path: string): HostRecord | Response { + const header = request.headers.get("authorization"); + const token = header?.startsWith("Bearer ") ? header.slice("Bearer ".length).trim() : ""; + let host: HostRecord | null; + try { + host = token ? hostForToken(token) : null; + } catch (error) { + if (!(error instanceof HostRegistryUnreadableError)) throw error; + // Never 401: a daemon told its token is unknown stops every omp child. + return fail("The host registry cannot be read", 503); + } + if (!host) return fail("Unknown host token", 401); + // `local` is refused by id: a hand-edited hosts.json can give its record the flag. + if (host.id === LOCAL_HOST_ID || !host.shareCredentials) { + log(host.id, request.method, PLAIN_PATH.test(path) ? path : "-", 403); + return fail("Credential sharing is off for this host", 403); + } + return host; +} + +async function forward(request: Request, { params, disableIdleTimeout }: { params: Promise<{ path: string[] }>; disableIdleTimeout: () => void }) { + const path = `/${(await params).path.join("/")}`; + const first = admit(request, path); + if (first instanceof Response) return first; + if (!ALLOWED.some(([method, allowed]) => method === request.method && allowed.test(path))) { + log(first.id, request.method, PLAIN_PATH.test(path) ? path : "-", 404); + return fail("Not found", 404); + } + + // Public to proxy.ts, so Bun's idle timeout is still on: the snapshot stream and the long poll stay open without traffic. + disableIdleTimeout(); + let body: ArrayBuffer | undefined; + if (request.method !== "GET") { + try { + body = (await readBodyWithinLimit(request, MAX_BODY_BYTES)).buffer; + } catch (error) { + if (error instanceof RequestBodyTooLargeError) return fail("Request body is too large", 413); + throw error; + } + } + + // The body can take as long as the sender likes, and no request of this host is abortable (abortBrokerRequests) until + // brokerFetch registers it: a host revoked or switched off meanwhile must not get through. No await from here to that call. + const host = admit(request, path); + if (host instanceof Response) return host; + + let upstream: Response; + try { + upstream = await brokerFetch(host.id, path + new URL(request.url).search, { + method: request.method, + headers: only(request.headers, REQUEST_HEADERS), + body, + signal: request.signal, + }); + } catch (error) { + const unavailable = error instanceof AuthBrokerUnavailableError; + const reason = unavailable ? (error.reason ?? "fetch_failed") + // The host disconnected, or abortBrokerRequests cut it off. + : request.signal.aborted || (error instanceof Error && error.name === "AbortError") ? "aborted" : "fetch_failed"; + log(host.id, request.method, path, unavailable ? 503 : 502, reason); + return unavailable ? fail("The auth broker is unavailable", 503) : fail("The auth broker request failed", 502); + } + log(host.id, request.method, path, upstream.status); + return new Response(upstream.body, { status: upstream.status, headers: only(upstream.headers, RESPONSE_HEADERS) }); +} + +export const GET = forward; +export const POST = forward; +export const DELETE = forward; diff --git a/app/api/hosts/route.ts b/app/api/hosts/route.ts index 66c89c096..fba3b2e20 100644 --- a/app/api/hosts/route.ts +++ b/app/api/hosts/route.ts @@ -1,6 +1,7 @@ import { closeHostLink, hostsSnapshot, listHosts, notifyHostsChange } from "@/lib/hosts/hub"; import { loadPools, savePools, type HostPool } from "@/lib/hosts/pools"; import { createHost, HostRegistryUnreadableError, readHosts, revokeHost, UnknownHostError, updateHost } from "@/lib/hosts/registry"; +import { abortBrokerRequests } from "@/lib/omp/auth-broker"; import { isRecord } from "@/lib/type-guards"; const MAX_LABEL_LENGTH = 100; @@ -125,14 +126,17 @@ export async function PATCH(req: Request) { if (!body || typeof body.id !== "string" || !body.id) return fail("id is required", 400); const isLocal = body.id === "local"; if (isLocal && body.allowAgentStart !== undefined) return fail("This machine's agent-start setting cannot be changed", 400); + if (isLocal && body.shareCredentials !== undefined) return fail("This machine's credential sharing cannot be changed", 400); // An empty name resets this machine to its default name. const label = isLocal && typeof body.label === "string" && !body.label.trim() ? "" : parseLabel(body.label); if (label === null) return fail(`label must be a non-empty string of at most ${MAX_LABEL_LENGTH} characters`, 400); - const { allowAgentStart } = body; + const { allowAgentStart, shareCredentials } = body; if (allowAgentStart !== undefined && typeof allowAgentStart !== "boolean") return fail("allowAgentStart must be a boolean", 400); - if (label === undefined && allowAgentStart === undefined) return fail("Nothing to update", 400); + if (shareCredentials !== undefined && typeof shareCredentials !== "boolean") return fail("shareCredentials must be a boolean", 400); + if (label === undefined && allowAgentStart === undefined && shareCredentials === undefined) return fail("Nothing to update", 400); try { - updateHost(body.id, { label, allowAgentStart }); + updateHost(body.id, { label, allowAgentStart, shareCredentials }); + if (shareCredentials === false) abortBrokerRequests(body.id); notifyHostsChange(); return Response.json({ host: hostsSnapshot().hosts.find((h) => h.id === body.id) }, { headers: noStore }); } catch (error) { @@ -148,6 +152,7 @@ export async function DELETE(req: Request) { // Registry first: with the record gone a daemon that redials gets 401 instead of reconnecting. if (!revokeHost(id)) return fail("Unknown host", 404); closeHostLink(id); + abortBrokerRequests(id); notifyHostsChange(); return Response.json({ ok: true }, { headers: noStore }); } catch (error) { diff --git a/bin/omp-web-host.test.mjs b/bin/omp-web-host.test.mjs index 478b84815..3e3aa4864 100644 --- a/bin/omp-web-host.test.mjs +++ b/bin/omp-web-host.test.mjs @@ -145,7 +145,7 @@ test("status/drain/resume consume the real CLI daemon endpoint and SIGTERM remov const frame = JSON.parse(line); if (frame.type === "hello") { hellos += 1; - ws.send(JSON.stringify({ type: "welcome", v: 8, hostId: "cli-fixture" })); + ws.send(JSON.stringify({ type: "welcome", v: 9, hostId: "cli-fixture" })); } else if (typeof frame.seq === "number") ws.send(JSON.stringify({ type: "ack", ack: frame.seq })); } }, @@ -164,7 +164,7 @@ test("status/drain/resume consume the real CLI daemon endpoint and SIGTERM remov status = JSON.parse((await hostCommand(f.env, "status")).stdout); } assert.equal(status.pid, daemon.child.pid, "the launcher must not leave a wrapper PID"); - assert.equal(status.protocol, 8); + assert.equal(status.protocol, 9); assert.equal(status.drained, false); assert.equal(hellos, 1); assert.equal(JSON.stringify(status).includes("private-cli-fixture-token"), false); diff --git a/components/HostsConfig.test.mjs b/components/HostsConfig.test.mjs index 65b1ffe6d..f34834c9a 100644 --- a/components/HostsConfig.test.mjs +++ b/components/HostsConfig.test.mjs @@ -396,3 +396,35 @@ test("resident-session blocking stays readable with a disabled daemon update and assert.ok(screen.getByRole("button", { name: "Update ompweb host" }).disabled); assert.equal(screen.getByRole("button", { name: "Update omp runtime" }).disabled, false); }); + +test("sharing credentials is confirmed before it is turned on, and turned off at once", async (t) => { + const patches = []; + mockHostRequests(t, async (url, init) => { + if (String(url).includes("/updates")) return Response.json(updateInfo()); + patches.push(JSON.parse(init?.body ?? "null")); + return Response.json({}); + }); + const user = userEvent.setup(); + await showHosts([ + hostRow(), + hostRow({ id: "h1", label: "Laptop", allowAgentStart: false, shareCredentials: false }), + hostRow({ id: "h2", label: "Desk", allowAgentStart: false, shareCredentials: true }), + ]); + const localRow = (await screen.findByRole("button", { name: "Rename This machine" })).closest("li"); + assert.equal(within(localRow).queryByRole("switch", { name: /provider logins/ }), null); + + await user.click(screen.getByRole("switch", { name: "Use this server's provider logins on Laptop" })); + const dialog = await screen.findByRole("dialog", { name: "Share credentials with Laptop?" }); + assert.deepEqual(patches, []); + await user.click(within(dialog).getByRole("button", { name: "Cancel" })); + await waitFor(() => assert.equal(screen.queryByRole("dialog"), null)); + assert.deepEqual(patches, []); + + await user.click(screen.getByRole("switch", { name: "Use this server's provider logins on Laptop" })); + await user.click(within(await screen.findByRole("dialog")).getByRole("button", { name: "Share" })); + await waitFor(() => assert.deepEqual(patches, [{ id: "h1", shareCredentials: true }])); + + await user.click(screen.getByRole("switch", { name: "Use this server's provider logins on Desk" })); + await waitFor(() => assert.deepEqual(patches.at(-1), { id: "h2", shareCredentials: false })); + assert.equal(screen.queryByRole("dialog"), null); +}); diff --git a/components/HostsConfig.tsx b/components/HostsConfig.tsx index 49735fd5f..af07ef1c1 100644 --- a/components/HostsConfig.tsx +++ b/components/HostsConfig.tsx @@ -111,7 +111,7 @@ function HostDialog({ dialog, onClose }: { dialog: NonNullable; onClose ); } -function HostCard({ host, onRename, onRevoke }: { host: HostRow; onRename: () => void; onRevoke: () => void }) { +function HostCard({ host, onRename, onRevoke, onShare }: { host: HostRow; onRename: () => void; onRevoke: () => void; onShare: () => void }) { const { t } = useI18n(); const name = hostName(t, host); const linked = "allowAgentStart" in host ? host : null; @@ -150,6 +150,16 @@ function HostCard({ host, onRename, onRevoke }: { host: HostRow; onRename: () => /> )} + {linked && ( +
+ {t("hostsConfig.shareCredentials")} + { if (shareCredentials) onShare(); else void call("PATCH", "/api/hosts", { id: host.id, shareCredentials }).catch(failure); }} + /> +
+ )} @@ -169,8 +179,22 @@ export function HostsConfig() { const { hosts, failed: loadFailed } = useHostRows(); const [dialog, setDialog] = useState(null); const [revoking, setRevoking] = useState(null); + const [sharing, setSharing] = useState(null); const [busy, setBusy] = useState(false); + const share = async () => { + if (!sharing) return; + setBusy(true); + try { + await call("PATCH", "/api/hosts", { id: sharing.id, shareCredentials: true }); + setSharing(null); + } catch (error) { + failure(error); + } finally { + setBusy(false); + } + }; + const revoke = async () => { if (!revoking) return; setBusy(true); @@ -202,7 +226,7 @@ export function HostsConfig() { ) : (
    {hosts.map((host) => ( - setDialog({ kind: "rename", host })} onRevoke={() => setRevoking(host)} /> + setDialog({ kind: "rename", host })} onRevoke={() => setRevoking(host)} onShare={() => setSharing(host)} /> ))} {hosts.length === 1 &&
  • {t("hostsConfig.empty")}
  • }
@@ -219,6 +243,16 @@ export function HostsConfig() { busy={busy} onConfirm={() => void revoke()} /> + { if (!open) setSharing(null); }} + title={t("hostsConfig.shareCredentialsTitle", { name: sharing?.label ?? "" })} + description={t("hostsConfig.shareCredentialsDescription", { name: sharing?.label ?? "" })} + confirmLabel={t("hostsConfig.shareCredentialsConfirm")} + cancelLabel={t("hostsConfig.cancel")} + busy={busy} + onConfirm={() => void share()} + /> ); } diff --git a/docs/plans/2026-11-11-shared-credentials.md b/docs/plans/2026-11-11-shared-credentials.md new file mode 100644 index 000000000..a9df40e0c --- /dev/null +++ b/docs/plans/2026-11-11-shared-credentials.md @@ -0,0 +1,329 @@ +# Shared provider credentials for linked hosts — implementation plan + +> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking. + +**Goal:** a linked host with sharing turned on runs its omp sessions with the web server machine's provider logins, through omp's own auth broker. + +**Architecture:** the web server runs `omp auth-broker serve` on loopback as an idle-stopped child and exposes an allow-listed forwarding route that authenticates the host token. The host daemon runs a loopback forwarder with a per-run secret and starts omp with `OMP_AUTH_BROKER_URL`/`OMP_AUTH_BROKER_TOKEN` pointing at it, so the host token never enters a child environment. A per-host registry flag and link protocol v9 decide which spawns get it. + +**Tech Stack:** TypeScript; server on Bun; daemon modules on Node through `jiti`; tests `bun test --parallel`. + +**Spec:** `docs/specs/2026-11-10-shared-credentials-design.md` (C1–C7). Read it first. + +**Base:** the branch contains `feat/transparent-host-pool` (merged at `0425e39b`), which owns link protocol 8. Line numbers in this plan predate that merge, so locate code by the names given. + +## Global Constraints + +- `LINK_PROTOCOL_VERSION = 9`, `MIN_LINK_PROTOCOL_VERSION = 4` (literal one-line exports: the deploy script `sed`s them). +- Daemon-loaded files (`lib/hosts/daemon*.ts`, `host.ts`, `host-resume.ts`, `local-host.ts`, `link-protocol.ts`, the new `lib/hosts/daemon-broker.ts`, and their `lib/` imports): relative imports only, no `Bun` global. +- ompweb never imports `@oh-my-pi/*` and never reads `agent.db`. +- A host with sharing on never runs a session with its own stored logins: every failure path refuses, none falls back. +- Minimum omp on a sharing host: `15.13.1`. +- The broker child binds `127.0.0.1` only. Ready timeout 60 s; idle stop 5 min after the last forwarded request ends; stop is SIGTERM, then SIGKILL after 5 s. +- Request bodies on both forwarders: at most 1 MiB (`1_048_576` bytes), else 413. +- Forwarded request headers: `content-type`, `accept`, `if-none-match`, `omp-auth-broker-capabilities`. Forwarded response headers: `content-type`, `etag`, `cache-control`, `vary`. Nothing else in either direction. +- Never log a token, a secret or a body. The host token never appears in an omp child's environment or arguments. +- Existing suites must pass. Update fixtures only where they pin the server's own protocol version as 8; never weaken an assertion. +- Commit titles follow the log (`feat(hosts): …`, `docs(hosts): …`). Commit and push after every task. +- No production service or daemon is touched. Task 8 uses throwaway home directories and a free port. + +## Review Focus + +1. Sharing is turned off, or the host is revoked, while that host has a snapshot stream open → the stream ends at once, not at its next reconnect. (Task 3) +2. `omp auth-broker token --regenerate` is run while the broker child is up → one request answers 503, the next starts a new child with the new token. (Task 2) +3. Two sessions start on a host in the same instant, before its forwarder listens → both get the same port and secret from one listener. (Task 5) +4. The host's saved server URL has a path prefix or a trailing slash (`https://example.com/ompweb/`) → requests reach `/api/hosts/broker/...` with no doubled slash. (Task 5) +5. A sharing session resumed after a daemon restart keeps the shared credentials; it must never come back on the host's own logins. (Task 6) + +--- + +### Task 1: `shareCredentials` on the host record + +**Files:** +- Modify: `lib/hosts/registry.ts` (`HostRecord`, `parseHostRecord`, `createHost`, `updateHost`) +- Modify: `app/api/hosts/route.ts` (`PATCH`) +- Modify: `lib/hosts/hub.ts` (`LinkedHostRow`, `listHosts`) +- Test: `lib/hosts/registry.test.mjs`, `lib/hosts/hosts-route.test.mjs` + +**Interfaces:** +- Produces: `HostRecord.shareCredentials: boolean`; `updateHost(id: string, updates: { label?: string; allowAgentStart?: boolean; shareCredentials?: boolean }): HostRecord`; `LinkedHostRow.shareCredentials: boolean`. + +- [ ] **Step 1: Write the failing tests** + +`registry.test.mjs`: +- a `hosts.json` record without the field loads with `shareCredentials === false`; +- `createHost("x").host.shareCredentials === false`; +- `updateHost(id, { shareCredentials: true })`, then `loadHosts()` → `true`; +- `updateHost("local", { shareCredentials: true })` throws `ReservedHostError`. + +`hosts-route.test.mjs`: +- `PATCH { id, shareCredentials: true }` → 200, `body.host.shareCredentials === true`; +- `PATCH { id, shareCredentials: "yes" }` → 400, `error === "shareCredentials must be a boolean"`; +- `PATCH { id: "local", shareCredentials: true }` → 400, `error === "This machine's credential sharing cannot be changed"`. + +- [ ] **Step 2: Run** `bun test --parallel lib/hosts/registry.test.mjs lib/hosts/hosts-route.test.mjs` — expected: the new tests fail. +- [ ] **Step 3: Implement.** `parseHostRecord` reads `r.shareCredentials === true`; `createHost` writes `false`; `updateHost` mirrors `allowAgentStart`, including the `local` refusal; `PATCH` mirrors the `allowAgentStart` validation and counts the field in the "Nothing to update" check; `listHosts` copies the field. +- [ ] **Step 4: Run** the same command — expected: pass. +- [ ] **Step 5: Commit** `feat(hosts): add a per-host credential sharing setting`, push. + +--- + +### Task 2: broker child on the web server + +**Files:** +- Create: `lib/omp/auth-broker.ts` +- Test: `lib/omp/auth-broker.test.mjs` +- Reference: `lib/omp/auth-gateway.ts` (same state-on-`globalThis`, environment and exit-hook pattern) + +**Interfaces:** +- Produces: + +```ts +export const AUTH_BROKER_TIMINGS = { readyMs: 60_000, idleMs: 300_000, killMs: 5_000 }; // mutable: tests shorten them +export class AuthBrokerUnavailableError extends Error {} +/** Fetch `path` (starts with "/v1/", query included) from the broker child on behalf of `hostId`. */ +export function brokerFetch(hostId: string, path: string, init: { method: string; headers: Headers; body?: ArrayBuffer; signal: AbortSignal }): Promise; +/** Abort every open broker request of this host, streams included. */ +export function abortBrokerRequests(hostId: string): void; +export function disposeAuthBroker(): void; +``` + +Behaviour the signature does not fix: +- Start: `omp auth-broker token` (stdout, trimmed; empty is a start failure), then `omp auth-broker serve --bind=127.0.0.1:0`. Ready is the first stdout line that parses as JSON with `message === "auth-broker listening"` and a `url` starting with `http://127.0.0.1:`. Concurrent first calls share one start. +- `brokerFetch` sets `authorization: Bearer ` itself, fetches with `proxy: false`, and aborts when `init.signal` or the host's own controller aborts. +- A request is in flight until its response body ends, errors or is cancelled. The idle timer runs only at zero in flight. +- Upstream 401 → stop the child and throw `AuthBrokerUnavailableError`. A start failure, a ready timeout and a child that exits mid-start throw it too. + +- [ ] **Step 1: Write the failing tests.** Use a fake `omp` through `OMP_WEB_OMP_BIN`: a Node script (with the `.cmd` wrapper on Windows, as `lib/hosts/link-integration.test.mjs` does) that prints `tok-N` for `auth-broker token` (N from a counter file) and, for `auth-broker serve`, appends a line to a starts file, listens on port 0, prints the listening line, answers `GET /v1/echo` with the received `authorization` header, `GET /v1/stream` with one chunk and then stays open, and `GET /v1/deny` with 401. + - `starts once for concurrent calls`: no starts-file line before the first call; two parallel `brokerFetch("h1", "/v1/echo")` → one line; both bodies equal `Bearer tok-1`. + - `stays up while a stream is open, stops when idle`: `idleMs = 50`; with `/v1/stream` open, the child is alive after 200 ms; after cancelling the body, it exits within 1 s. + - `aborts only the named host`: streams open for `h1` and `h2`; `abortBrokerRequests("h1")` → `h1`'s reader rejects, `h2`'s reads on. + - `restarts after the broker refuses its token`: `/v1/deny` rejects with `AuthBrokerUnavailableError`; the next `/v1/echo` body is `Bearer tok-2` and the starts file has two lines. + - `restarts after the child exits`: kill the child; the next call answers 200. +- [ ] **Step 2: Run** `bun test --parallel lib/omp/auth-broker.test.mjs` — expected: fail, module not found. +- [ ] **Step 3: Implement** `lib/omp/auth-broker.ts`. +- [ ] **Step 4: Run** the same command — expected: pass. +- [ ] **Step 5: Commit** `feat(auth): run omp's auth broker as an idle-stopped child`, push. + +--- + +### Task 3: forwarding route and gate + +**Files:** +- Create: `app/api/hosts/broker/[...path]/route.ts` +- Modify: `server/routes.ts` (import and `"hosts/broker/[...path]"` entry) +- Modify: `proxy.ts` (`UNGATED` and its comment) +- Modify: `app/api/hosts/route.ts` (`PATCH`, `DELETE`) +- Test: `lib/hosts/broker-route.test.mjs`, `lib/web-auth.test.mjs`, `lib/hosts/hosts-route.test.mjs` + +**Interfaces:** +- Consumes: `brokerFetch`, `abortBrokerRequests`, `AuthBrokerUnavailableError` (Task 2); `hostForToken`, `HostRegistryUnreadableError`, `LOCAL_HOST_ID`, `HostRecord.shareCredentials` (Task 1); the handler context `{ params, disableIdleTimeout }` (`server/routes.ts`). +- Produces: `GET`, `POST`, `DELETE` on `/api/hosts/broker/`. + +The allow-list, exact: + +```ts +const ALLOWED: readonly (readonly [method: string, path: RegExp])[] = [ + ["GET", /^\/v1\/(?:healthz|snapshot|snapshot\/stream|credentials\/disabled|usage|usage\/history|usage\/clients)$/], + ["POST", /^\/v1\/credential\/\d+\/(?:refresh|disable|block)$/], + ["DELETE", /^\/v1\/credential\/\d+\/blocks?$/], + ["POST", /^\/v1\/usage\/(?:observed|stale)$/], +]; +``` + +Order of checks, each answering JSON `{ error }` with `cache-control: no-store`: +1. Bearer token missing or unknown → 401 `Unknown host token`; `HostRegistryUnreadableError` → 503. +2. Host is `local` or has `shareCredentials` false → 403 `Credential sharing is off for this host`. +3. `"/" + params.path.join("/")` with the request method not in `ALLOWED` → 404. +4. `disableIdleTimeout()`. +5. Body over 1 MiB → 413 (read it for `POST` and `DELETE`: omp's single-block delete carries a JSON body). +6. `brokerFetch(host.id, path + url.search, …)` with `signal: request.signal`; `AuthBrokerUnavailableError` → 503; any other failure → 502. +7. Log `[omp-web] broker ` (no query). + +`UNGATED` gains the alternative `api\/hosts\/broker\/` (a prefix; `/api/hosts/broker` itself and `/api/hosts/brokerx` stay gated). + +`PATCH` with `shareCredentials === false` and `DELETE` call `abortBrokerRequests(id)` after the registry write. + +- [ ] **Step 1: Write the failing tests.** `broker-route.test.mjs` mocks `@/lib/omp/auth-broker` so `brokerFetch` records its arguments and returns a canned `Response`: + - no header and an unknown token → 401, `brokerFetch` not called; + - known token, sharing off → 403; the `local` record's token → 403; + - unreadable `hosts.json` → 503; + - `GET v1/snapshot?wait=30000` → `brokerFetch` gets `("", "/v1/snapshot?wait=30000", …)`; + - `POST v1/credential`, `GET v1/credential/1/refresh`, `GET v1/credentials/check`, `GET v2/snapshot`, `POST v1/credential/x/refresh` → 404 each; + - request headers `cookie`, `x-forwarded-for`, `authorization` are not in the forwarded `Headers`; the four allowed ones are; + - upstream headers `set-cookie` and `x-other` are not in the answer; the four allowed ones are; the upstream status is kept; + - a 1 MiB + 1 byte `POST v1/usage/observed` → 413; + - `brokerFetch` rejecting with `AuthBrokerUnavailableError` → 503; with `new Error("x")` → 502; + - `disableIdleTimeout` is called once for an accepted request and never for a 401. + + `web-auth.test.mjs`: with a password set and no cookie, `proxy()` returns `"public"` for `/api/hosts/broker/v1/healthz` and a 401 `Response` for `/api/hosts/broker` and `/api/hosts/brokerx/v1/healthz`. + + `hosts-route.test.mjs`: `PATCH { shareCredentials: false }` and `DELETE` call `abortBrokerRequests` with the host id; `PATCH { shareCredentials: true }` does not. +- [ ] **Step 2: Run** `bun test --parallel lib/hosts/broker-route.test.mjs lib/web-auth.test.mjs lib/hosts/hosts-route.test.mjs server/routes.test.ts` — expected: the new tests fail. +- [ ] **Step 3: Implement** the route, the table entry, the gate and the two aborts. +- [ ] **Step 4: Run** the same command — expected: pass. +- [ ] **Step 5: Commit** `feat(hosts): forward allow-listed auth-broker requests for sharing hosts`, push. + +--- + +### Task 4: link protocol v9 and the hub's flag + +**Files:** +- Modify: `lib/hosts/link-protocol.ts` (`LINK_PROTOCOL_VERSION`), plus a new constant +- Modify: `lib/hosts/host.ts` (`SpawnRequest`) +- Modify: `lib/hosts/hub.ts` (`RemoteHost.spawnRpc`) +- Test: `lib/hosts/hub-v7.test.mjs`; fixtures that pin the server's version as 8 + +**Interfaces:** +- Consumes: `HostRecord.shareCredentials` (Task 1). +- Produces: + +```ts +export const LINK_PROTOCOL_VERSION = 9; +export const SHARED_CREDENTIALS_SINCE_VERSION = 9; +// SpawnRequest gains: +/** Hub → daemon (v9): run this process with the opening server's provider logins. */ +shareCredentials?: true; +/** Daemon only: the server URL whose link supplies the credentials. Never trusted from the wire. */ +credentialsServer?: string; +``` + +`spawnRpc`, before it sends anything: read the host's record with `loadHosts()`. If sharing is on and the link's `hostVersion` is below 9, throw `new HostOpError(426, "host_upgrade_required", "Update ompweb on