# Remote Web access

Every HTTP, SSE and WebSocket request carries the per-start instance token or a paired device's credential, even on loopback. Either means the active profile's one owner. No relay, no accounts.

## Access modes

| Mode | Bind | Browser reaches | Protection besides the token |
| --- | --- | --- | --- |
| Same machine | `127.0.0.1` | Loopback URL | Host and Origin checks |
| Trusted LAN or encrypted VPN | Explicit `web.host`, often `0.0.0.0` | Direct address | Non-empty exact origins, Host checks, HTTPS or an encrypted network |
| SSH tunnel | `127.0.0.1` | Local forwarded port | SSH encrypts transport |
| Public owner domain | `127.0.0.1` behind a same-host proxy | Owner-managed HTTPS URL | Exact origin and Host, trusted loopback proxy, HTTPS |

### Who a valid token is

- **Principal**: `owner/install/<16hex>` from `openprogram/runtime/permissions/authority.py`, with the owner tier's fixed capabilities
- **Scope**: The active profile or state directory: `owner.json` lives there, so each profile has its own owner
- **Proves**: Authorization as the owner, not which person is at the browser
- **Channel speakers**: Telegram, Discord and other channels keep speaker attribution and the restricted `paired` tier; a channel turn never makes someone the Web owner
- **Stored**: No Web user table, passwords, memberships, roles or per-project ACL

| Excluded | Instead |
| --- | --- |
| Web accounts, signup, invitations, user sessions | One owner principal per profile or state instance |
| RBAC, groups, tenant or workspace roles, project permissions | The Web UI is one full-capability administrative interface |
| OAuth, OIDC, SSO, identity-aware proxy, Tailscale identity | May add a control; never replace the token |
| Built-in TLS, ACME, certificate storage and renewal | The owner runs nginx, Caddy, a VPN or SSH |
| Public relay, hosted tunnel, rendezvous, share URL | No outbound registration for reachability; another device pairs directly with the server it can reach ([Paired devices](#paired-devices)) |
| Authentication off, `--insecure` | Always on, including loopback |
| Long-lived token in a query, `localStorage` or public HTML | Fragment bootstrap and HttpOnly cookie only |
| Reading stored provider credentials as plaintext | Replace only |

## Threats on loopback

| Caller | What it can do | Control |
| --- | --- | --- |
| Arbitrary Web page | Send some HTTP to localhost; WebSocket escapes the same-origin read rule | Token plus exact Origin and Host before any action |
| DNS-rebinding page | Resolve a hostile name to loopback and present a foreign Host | Fail-closed Host validation |
| Local process, other OS account | Omit `Origin`, as `curl` and native clients do | Bearer token; missing Origin conveys no trust |
| LAN peer after external bind | Connect to every route and `/ws` | Mandatory token, exact origins, Host validation, protected transport |
| Reverse-proxy client | Present a public Host while the backend stays loopback | Explicit public origin, narrowly trusted loopback proxy |

### Invariants

- Before authentication: no protected state, session data, file bytes, secret metadata, SSE event or WebSocket frame leaves, and no action runs.
- A missing `Origin` never establishes trust. It is allowed only after valid Bearer authentication, or on a safe cookie request.
- The token complements Host and Origin checks; cookies keep CSRF controls.
- A non-loopback bind with incomplete origins fails before listening.
- No route returns a stored secret, or the token after initial entry.

## Token and credentials

| Aspect | Rule |
| --- | --- |
| Value | `secrets.token_bytes(32)`, shown as 43 characters of unpadded base64url; new on every Web process start |
| One process | Exclusive owner-only lock `<state-dir>/web.lock`; a second process fails without touching the first's token |
| Files | `web/token` written atomically before the listener is ready; `web/access.json` holds exactly `version`, `bind_host`, `port`, `effective_origins`, `token_fingerprint`; both owner-only, hardened by `restrict_to_user()` |
| Never from | Configuration, a command-line argument, an environment variable |
| Never in | Server logs, exception messages, access logs, telemetry, Web responses. Logs carry only `sha256:<first 12 hex of sha256(raw bytes)>` |
| Compare | Decode to exactly 32 bytes, then `hmac.compare_digest` |

**Startup failure and cleanup**

- The write follows the temp-file, `os.replace` and permission pattern of `openprogram/extensions/mcp/token_storage.py`.
- Startup fails if the lock cannot be taken or the token file cannot be created and read back safely.
- `read_active_web_access()` returns `ActiveWebAccess` only for a valid snapshot whose fingerprint matches the live token file.
- On bind failure or shutdown, the process removes the token only while holding the lock with its own token in the file, and `access.json` only when the fingerprint is its own.
- Stale unlocked files are replaced atomically by the next process.

### Credential forms

| Client | Credential | Rule |
| --- | --- | --- |
| Browser HTTP, SSE, WebSocket | Cookie `openprogram_owner_<16hex>` = `base64url(HMAC-SHA256(raw_token, "openprogram-web-cookie-v1"))` | `HttpOnly`, `SameSite=Strict`, `Path=/`, no `Domain`, session lifetime; `Secure` when the effective scheme is HTTPS |
| Native HTTP, SSE, WebSocket | `Authorization: Bearer <token>` | Header only; a token in a query is ignored |
| Paired browser | Cookie `openprogram_device_<16hex>` = `opd1.<device id>.<secret>` | Same attributes as the owner cookie, plus `Max-Age` of 400 days; the server forgets the device after 30 idle days |
| Paired native client | `Authorization: Bearer opd1.…` | Same Bearer rules as the owner token |

- The profile-specific name keeps simultaneous profile servers from overwriting each other's cookie: cookies are not port-scoped.
- The owner cookie has no database row. It is recomputed from the token, so a restart invalidates it. A device credential is checked against `web/devices.json` and survives restarts.
- Except on bootstrap, any `Authorization` header selects the Bearer path: a bad one returns `401` and never falls back to a valid cookie.

### Browser sign-in

1. **CLI** `open /#token=…`
2. **Browser** `GET /` without the fragment; gets the public shell
3. **Browser** token into memory, `history.replaceState()`
4. **Browser** `POST /api/auth/bootstrap`
5. **Web server** `204`, `Set-Cookie: HttpOnly`
6. **Browser** HTTP, SSE, WebSocket with the cookie

The fragment never appears in an HTTP request, proxy log, Referer or route. `apps/web/lib/net/auth/owner-auth-bootstrap.ts` mounts the application only after the exchange and uses no Web Storage.

**`POST /api/auth/bootstrap` contract**

- `POST` only, with a valid exact Origin and valid Host.
- `Content-Type: application/json`, body at most 256 bytes, exactly `{"token":"<43-character base64url>"}`. Unknown keys, duplicate keys, bad base64url and other lengths are rejected.
- Any `Authorization` header, a missing token or a wrong token: the same `401`.
- Success: `204` and the cookie. Always `Cache-Control: no-store`; the token is never in a response.

### Sign-in link for another device

```
openprogram web auth-url --base-url https://agent.example.com
```

1. Compare worker PID and port files, `access.json` and the listening process: send a fresh nonce to `GET /api/auth/challenge` and check the HMAC proof locally. The token is never sent to the probed port.
2. Read the live token file and print one fragment URL to the terminal, never to application logs.

`--base-url` must be an effective origin frozen in `access.json`, with no path, query, fragment or user information. HTTP passes only for exact `localhost` on a loopback listener or an IP in the ranges under [Plaintext HTTP](#http-ranges).

### Paired devices

The owner token changes on every start, which suits this computer's own App and CLI: they read it from the state directory. A phone or a second computer cannot, so it pairs once and keeps a credential of its own.

1. **Computer** `openprogram web pair`: `POST /api/auth/pairings` mints a code; the CLI prints `<origin>/#pair=<code>` and its QR code
2. **Other device** opens the link; the fragment leaves the address bar before any request
3. **Other device** `POST /api/auth/pair {"code"}`
4. **Web server** spends the code; a browser (it sends `Origin`) gets the device cookie with `204`, a native client gets `{"device_id","token"}`
5. **Other device** every later request, across restarts, until revoked or idle 30 days

| Part | Rule | Why |
| --- | --- | --- |
| Pairing code | 32 random bytes; single use; 10 minutes; held only in the worker's memory, at most 16 pending | A link that leaks into a chat or a screenshot is worthless soon after; a restart drops them all |
| Device credential | `opd1.<16hex id>.<32-byte secret>`; only `sha256(secret)` is stored, owner-only, in `<state>/web/devices.json` | The file never holds a usable secret; the id lets one device be listed and revoked |
| Authority | The same single owner as the instance token; the device id goes on the request as `device_id` | A paired device can run tools as the owner anyway, so narrower scopes would not be a real boundary |
| Lifetime | Valid while used; forgotten after 30 idle days; `last_used` written at most hourly | A lost phone that is never opened again stops working on its own |
| Revoke | `DELETE /api/auth/devices/{device_id}` or `openprogram web devices revoke <id>`; its open WebSockets close with `4401` | Revoking takes effect on the connection the device is already holding |
| Reachability | Unchanged: the link names an effective origin; with only loopback origins the CLI explains how to configure LAN, VPN or a proxy | Pairing proves who; it does not make an unreachable server reachable |
| Spent link | A browser that is already paired and opens an old link signs in with its cookie and says nothing | Reopening a bookmarked link is not an error |

Routes: `GET /api/auth/devices`, `PATCH` and `DELETE /api/auth/devices/{device_id}`, `POST /api/auth/pairings` in `openprogram/interfaces/server/routes/identity/devices.py`; registry in `openprogram/interfaces/server/device_access.py`.

**Why pairing, and why this shape**

| Peer | How another device signs in | Taken |
| --- | --- | --- |
| [T3 Code](https://github.com/pingdotgg/t3code) | `t3 pair` prints a QR of a one-time link with the secret in the fragment; the device keeps a session listed and revocable under Sharing & access; unused 30 days, it pairs again. LAN, Tailscale HTTPS, SSH, or its hosted T3 Connect relay | Fragment link, one-time code, 30-day idle expiry, revoke list. Not the hosted relay or scoped grants |
| DSH Mobile (DeepSeek Harness plugin) | QR, link or key pairing; device tokens go only to their exact origin; private LAN CA pinned; Tailscale Funnel or tunnels for remote; Web Push for the home-screen PWA | Credential bound to one origin (host-only cookie). LAN TLS and push are later steps |
| pi remote extensions | QR to a LAN or tailnet WebSocket, or a self-hosted end-to-end encrypted relay | Confirms LAN and tailnet as the default routes |
| Claude Code Remote Control, Codex remote control | The vendor's service relays between the computer and the phone | Not taken: OpenProgram runs no service |

## Request handling

One ASGI middleware, `OwnerAuthMiddleware`, runs before route dispatch for HTTP and WebSocket. No application route interprets authentication itself.

| Order | Check | On failure |
| --- | --- | --- |
| 1 | Immediate peer, effective scheme, one valid `Host`; `request_origin` must be effective. `Origin` and `Sec-Fetch-Site` when present. | `403 request_origin_rejected` |
| 2 | Public, challenge and bootstrap routes answer here | Their own rule, below |
| 3 | Bearer if an `Authorization` header exists, else cookie | `401 authentication_required`, `WWW-Authenticate: Bearer realm="OpenProgram"` |
| 4 | Cookie on an unsafe method or WebSocket must have `Origin` | `403 request_origin_rejected` |
| 5 | Attach `owner_authority(principal)`, then route, SSE generator or `websocket.accept` |  |

WebSocket failures are HTTP upgrade denials, never an accepted socket then a close frame. Malformed or revision-mismatched challenge: `400 invalid_challenge`. HTTP carrying `x-openprogram-ui-check`: `409 ui_verification_active`. Invalid non-loopback startup configuration: no listener.

### Reachable without the owner credential

| Route | Guard or content |
| --- | --- |
| Application shell, static assets | `GET` and `HEAD`; no token, secret, session id or user data in the HTML |
| `GET`/`HEAD /docs`, `/docs/**` | Prebuilt site only: `docs/_site` in a checkout, `openprogram/interfaces/server/_frontend/docs` in a package (the wheel must include its `index.html`). No source scan or build on a request; staleness checks run only when a source worker registers routes. |
| `POST /api/auth/bootstrap` | Its own body-token check |
| `POST /api/auth/pair` | A single-use pairing code in the body |
| `GET /api/auth/challenge` | Listener proof, below; grants nothing |
| `GET /healthz` | Only `{"status":"ok"}`; details are behind authentication at `/api/diagnostics` |
| `POST /hooks/<id>` | Scheduler webhook, guarded by the task's own key |
| `GET /application-assets/…` | Sandboxed module imports with `Origin: null`; reads one immutable UI tree; Host still checked |
| Office host | Served by the `office_editor` application while enabled; WebSocket refused |

All pass step 1, except the Office host, which `office_editor` checks. Everything else needs a credential: routes, raw files, providers, diagnostics, SSE, WebSocket.

**Listener challenge and session check**

- Input: `nonce` of 32 bytes as 43-character base64url, optional `revision` of 40 lowercase hex that must equal the served revision.
- Output: exactly `200 {"proof":"<43-character base64url>"}`, where the proof is `HMAC-SHA256(raw_token, "openprogram-web-challenge-v1\0" + nonce + "\0" + revision)`.
- No credential is sent, and no token or diagnostics are returned.
- `GET /api/auth/session` after sign-in: `204` means the cookie matches the live worker. On `401` the desktop shell exchanges a fresh in-memory token and repeats bootstrap instead of reconnecting with a stale cookie.

**Response headers**

| Response | Headers |
| --- | --- |
| Static shell | `Content-Security-Policy` with `object-src 'none'`, `base-uri 'none'`, `frame-ancestors 'none'`, scripts from same origin plus generated hashes (no third-party scripts, no `unsafe-eval`); `X-Frame-Options: DENY`; `Referrer-Policy: no-referrer`; `X-Content-Type-Options: nosniff` |
| `/docs/*.raw.html` | Same, but frameable by the same origin: `SAMEORIGIN`, `frame-ancestors 'self'` |
| Bootstrap, challenge, failures, protected API, credential status, SSE | `Cache-Control: no-store` |
| Content-addressed static assets | Long-lived cache |

### Origin by request form

| Request | Credential | `Origin` |
| --- | --- | --- |
| Cookie, unsafe HTTP | Required | Must equal `request_origin`; missing rejected |
| Cookie, WebSocket | Required before accept | Must equal `request_origin`; missing rejected |
| Cookie, safe HTTP or SSE | Required | If present, must equal `request_origin`; navigation may omit it |
| Bearer HTTP, SSE, WebSocket | Required (before accept on WebSocket) | May be omitted; if present, must be `request_origin` or, with a valid token, another effective origin |
| Listener challenge | None; bounded nonce and revision | May be omitted; if present, must equal `request_origin` |
| Bootstrap | Token in the body | Must equal `request_origin` |

The Bearer allowance exists because the Node TUI reaches loopback by IP while presenting the canonical origin. Safe methods are `GET`, `HEAD` and `OPTIONS`, and change no state. `Sec-Fetch-Site: cross-site` is always rejected. CORS headers control reading a response and are not authentication.

**How origins are computed**

- `web.host` and `web.allowed_origins` come from the active profile's `<state-dir>/config.json`. `web.host` defaults to `127.0.0.1` and is needed only for direct LAN or VPN access.
- An entry is only `scheme://host[:port]`, `http` or `https`. Invalid: wildcards, paths, queries, fragments, user information, opaque origins, malformed IPv6, unspecified and multicast literals (so `0.0.0.0` and `::`).
- DNS names are IDNA- and case-normalized, IPv6 is bracketed, default ports are removed.
- `effective_origins` = configured origins + on a loopback listener, `http://localhost:<port>` and the literal actually bound. A non-loopback listener gets no implicit origin. A request's `Host` is never promoted into the set.
- `Host` must be one valid authority: duplicate, comma-joined, user-information, unspecified and multicast forms are rejected.
- `request_origin` = scheme + parsed `Host`, with `ws` as `http` and `wss` as `https`. This one comparison covers exact origin and DNS rebinding.

### Plaintext HTTP

| Accepted | Range |
| --- | --- |
| DNS | Only exact `localhost` on a loopback listener |
| IPv4 | `127.0.0.0/8`, `10.0.0.0/8`, `172.16.0.0/12`, `192.168.0.0/16`, `169.254.0.0/16`, `100.64.0.0/10` |
| IPv6 | `::1/128`, `fc00::/7`, `fe80::/10`; no zone identifiers |

Everything else needs HTTPS. An explicit list, not `is_private`: that property includes reserved addresses and excludes RFC 6598. Every non-loopback HTTP origin logs a startup warning, because an observer can read the credential. `100.64.0.0/10` is for encrypted overlays such as Tailscale; the address alone does not prove encryption, so the owner is responsible for that.

## Deployment recipes

### SSH tunnel

```
ssh -N -L 18100:127.0.0.1:18100 owner@remote-host
# on the remote host, once the tunnel is up
openprogram web auth-url --base-url http://127.0.0.1:18100
```

A different local port needs that exact `http://localhost:<port>` or loopback-literal origin in `allowed_origins` first.

### Direct LAN or VPN

```
{
  "web": {
    "host": "0.0.0.0",
    "allowed_origins": ["http://192.168.1.20:18100"]
  }
}
```

### Same-host HTTPS proxy

```
{
  "web": {
    "host": "127.0.0.1",
    "allowed_origins": ["https://agent.example.com"]
  }
}
```

| Party | Rule |
| --- | --- |
| OpenProgram | Starts Uvicorn with `proxy_headers=False`. Never trusts `X-Forwarded-For`. Trusts `X-Forwarded-Proto` only from a raw loopback peer, one value, `http` or `https`; any other value is rejected, and it is ignored from other peers. |
| Proxy | Preserves the public Host, overwrites the scheme, supports WebSocket Upgrade, disables SSE buffering |
| Missing scheme header | A DNS or public-IP origin stays HTTP and is refused with `403`, so no insecure owner cookie can be set |

**nginx**

```
map $http_upgrade $connection_upgrade {
    default upgrade;
    ''      close;
}

server {
    listen 443 ssl;
    server_name agent.example.com;

    # ssl_certificate and ssl_certificate_key are owner-managed.

    location / {
        proxy_pass http://127.0.0.1:18100;
        proxy_http_version 1.1;
        proxy_set_header Host $http_host;
        proxy_set_header X-Forwarded-Proto $scheme;
        proxy_set_header Forwarded "";
        proxy_set_header X-Forwarded-Host "";
        proxy_set_header X-Forwarded-For "";
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection $connection_upgrade;
        proxy_buffering off;
        proxy_read_timeout 3600s;
    }
}
```

**Caddy**

```
agent.example.com {
    reverse_proxy 127.0.0.1:18100
}
```

Certificates are Caddy's job because the owner chose Caddy; OpenProgram does not call its APIs.

## Stored secrets

Owner authentication authorizes replacing and using a secret, never reading it.

|  | Config or environment key | Provider credential |
| --- | --- | --- |
| Read | `GET /api/config/key/{env_var}`: `{"has_value":false,"masked":""}` or `{"has_value":true,"masked":"sk-…abc4"}`; undeclared name `404` | `GET /api/providers/{provider}/credentials`: each row's metadata with `key_tail`, the last four characters; no value or full key |
| Preserve | Omit the name from `api_keys` | Rename, turn off, reorder and the strategy neither take nor change the key |
| Replace | `POST /api/config` `{"api_keys":{"ENV_VAR":"new"}}`, one or more keys; `200 {"saved":true}` | `POST /api/providers/{provider}/credentials/{cid}/replace` `{"api_key":"new"}`, checked first; `200 {"ok":true,"credential":…,"check":…}`; `400` for a rejected key or a sign-in; `404` if absent |
| Check | Not offered | `POST /api/providers/{provider}/credentials/check-key` `{"api_key":"new","replace"?:cid}` stores nothing and answers `{"ok":true,"check":…}`; the add or replace after it reuses the check |
| Delete | `DELETE /api/config/key/{env_var}`, no body, idempotent; removes the stored key; `204`. A variable set in the Worker's environment is not touched and still supplies its key. | `DELETE /api/providers/{provider}/credentials/{cid}` removes that one credential; `200 {"ok":true}`; `404` if absent; `409` naming the variable for an environment key |
| Reveal | A `reveal` query: `404` | No route reads a stored key |

| Rule | Detail |
| --- | --- |
| `400`, nothing changed | Unknown fields, unknown names, `null`, empty, non-printable or non-ASCII values, any displayed mask. Also a key validation definitively rejects; a transient or offline `unknown` result still saves. |
| Mask | Values of 12 or more characters with ASCII visible parts: first 3, `…`, last 4, hiding at least 5. Otherwise a fixed `••••••••`, so short lengths stay hidden. |
| Frontend | No reveal button, request or plaintext response field in provider detail, API-key settings or account manager |
| MCP servers | `MCPServerConfig.to_storage_dict()` keeps full values for the file; `to_response_dict()` masks every `env` and `headers` value, bearer token and OAuth client secret as `{has_value, masked}` on `/api/mcp/servers`, `/api/mcp/servers/{name}`, `/api/mcp/catalog`, `/api/mcp/catalog/diff`. `PATCH /api/mcp/servers/{name}`: omitted preserves, new value replaces, explicit empty deletes; persisted after the restart succeeds. `mcp_servers.json` is `0600` through temp file, `fsync` and `os.replace`. |
| Project-file reveal | Unrelated file-navigation action under normal authentication; not a credential path |

## Startup

Validate configuration, generate and secure the token, write and check `access.json`, compute the fingerprint, then listen.

| Logged | Startup error |
| --- | --- |
| Bind address and whether it is loopback | Malformed origin |
| Effective origins | Non-loopback bind without an origin |
| Whether loopback-proxy scheme handling is active | Unsafe public HTTP origin |
| Token fingerprint, never the token | Unsafe token file |
| Warning for non-loopback HTTP | Occupied Web-process lock |

## Implementation status

| Status | Items |
| --- | --- |
| Implemented | Everything above, except the items below |
| Not started | Web Push for paired phones; the desktop App opening another computer's server as its own window. Settings → Devices (one list with paired phones, Add device with a pairing QR, rename, revoke, Same Wi-Fi and Anywhere) is in place: [Remote OpenProgram machines](https://fzkuji.github.io/OpenProgram/docs/reference/design/integrations/remote-openprogram.html#ways-in) |
| Partial | Browser-driven audit that no exported asset or navigation path embeds dynamic data; server-side tests cover responses and rendered HTML |
| Partial | nginx and Caddy HTTPS, WebSocket and SSE smoke deployments; a real-listener origin matrix covers `X-Forwarded-Proto` and `X-Forwarded-Host` |

**Where each part lives and what tests it**

| Part | Code and tests |
| --- | --- |
| Default bind, lifespan | `_web_config()` and `create_app()` in `openprogram/interfaces/server/server.py` |
| Owner principal, tiers | `openprogram/runtime/permissions/authority.py`; `tests/unit/providers/auth/test_authority_scope.py` |
| Token, lock, cookie | `OwnerAuthState` in `openprogram/interfaces/server/owner_auth.py`; `test_process_token_is_owner_only_locked_and_replaced_after_release` |
| Origins | `canonicalize_origin()`, `resolve_effective_origins()` in `openprogram/host/security/backend_endpoint.py`; parameterized owner-auth tests |
| Middleware | `OwnerAuthMiddleware`; owner-auth tests for HTTP mutation and pre-accept WebSocket |
| Bootstrap | `apps/web/lib/net/auth/owner-auth-bootstrap.ts`, `OwnerAuthBoundary`; `apps/web/scripts/settings/check-owner-auth-bootstrap.mjs`, TypeScript check, production build |
| Paired devices | `device_access.py`, `routes/identity/devices.py`, `openprogram/interfaces/cli/commands/services/web_devices.py`; `tests/component/webui/owner_auth/test_device_pairing.py`, `apps/web/tests/access/owner-auth-bootstrap.test.mjs` |
| `auth-url` | `openprogram/interfaces/cli/commands/services/web.py`, `build_owner_auth_url()`; `tests/unit/webui/test_web_auth_url.py` |
| Secrets | `openprogram/host/security/credential_mask.py`, `credential_secrets`; `tests/component/programs/mcp/test_mcp_secret_non_retrievability.py`, `apps/web/scripts/settings/check-secret-non-retrieval.mjs` |
| Internal clients | `resolve_backend_endpoint()` returns a challenge-verified `BackendEndpoint`, so the token is read only after proof; used by `openprogram/interfaces/cli/ink.py` and `openprogram/interfaces/cli/commands/capabilities/mcp.py`. The Node client sends Bearer only to backend URLs: `apps/cli/src/utils/backend.ts`, `apps/cli/tests/startup/backendAuth.test.ts` |
| Startup report | `start_server()`; `test_startup_logs_warn_about_plaintext_http_for_remote_origins` |
| Real listener | `tests/component/webui/owner_auth/test_web_owner_auth_listener.py`: real Uvicorn socket, HTTP, SSE, pre-accept WebSocket denial, bind-failure cleanup, wire-level rotation, two-profile cookies, reverse-proxy origins, token-leak sweep over bodies, headers, logs and rendered pages |

**Acceptance behaviours**

1. Loopback HTTP, SSE and WebSocket without a credential fail.
2. A correct Bearer token works without `Origin`; a wrong one gets the same `401` and does nothing.
3. Bootstrap clears the fragment before other fetches, accepts only the bounded JSON, sends no token in URL, query or Referer, derives the specified cookie, rejects a body token with `Authorization`, then opens HTTP, SSE and WebSocket.
4. Cookie unsafe HTTP and WebSocket reject missing, opaque, cross-site and unlisted origins before action or accept.
5. Foreign, duplicate, comma-joined, unspecified and multicast Hosts are rejected on loopback, direct bind and proxy; HTTP/WS and HTTPS/WSS give the same origin pairs.
6. Default loopback accepts only its implicit origins; another SSH local port is rejected until configured.
7. A non-loopback bind without valid origins refuses startup; the listed HTTP ranges pass with warnings; unspecified, multicast, documentation, benchmarking, reserved and global literals are rejected for HTTP.
8. Uvicorn proxy rewriting is off; forwarded scheme is honoured only from a raw loopback peer; forged `X-Forwarded-For` changes nothing; public bootstrap without HTTPS fails; direct WS and Caddy WSS give the expected origin.
9. A second process for one state directory cannot change the live token or snapshot; bind failure removes only the failing process's files.
10. Restart rotates the token and invalidates the old Bearer and cookie.
11. A malformed `Authorization` header never falls back to a cookie.
12. Static assets and `/healthz` contain no token, session, filesystem or credential data or diagnostics.
13. Headers reject framing; protected responses are `no-store`; `401` advertises the Bearer realm.
14. Docs read without authentication from prebuilt files in checkouts and packages, with no scan or build; Host still applies; unsafe methods and private APIs are excluded.
15. Reveal returns `410` and `404`; replace, preserve and delete follow the exact schemas; 8–11-character values use the fixed mask; masks are never accepted; frontend types have no reveal or full-secret field.
16. nginx and Caddy carry authenticated HTTP, SSE and WebSocket over HTTPS with a loopback backend.
17. Channel messages keep `paired` and gain no owner authority.
18. Two profile servers on one hostname and different ports have distinct cookies and authenticate independently.
19. The ownership probe checks PID, port and snapshot, sends only a fresh nonce, validates the versioned proof, optionally binds the revision, disables ambient HTTP proxies and never sends or logs the token. Foreign listeners and stale or mismatched snapshot, port, proof or revision are not the owner server.

**Open-source survey**

Systems in OpenProgram's design corpus plus others with relevant Web deployment, authentication, proxy or secret handling. Not exhaustive.

| System | Design | Taken | Rejected or not applicable |
| --- | --- | --- | --- |
| [OpenClaw](https://github.com/openclaw/openclaw) | Loopback-first gateway, authenticated non-loopback, explicit origins, SSH and proxy guidance, Host and trusted-proxy controls ([remote](https://github.com/openclaw/openclaw/blob/main/docs/gateway/remote.md), [security](https://github.com/openclaw/openclaw/blob/main/docs/gateway/security/index.md), [Control UI](https://github.com/openclaw/openclaw/blob/main/docs/web/control-ui.md)) | Exact origins, fragment bootstrap, SSH and proxy patterns, proxy trust limits | External identity replacing the token |
| [Jupyter Server](https://github.com/jupyter-server/jupyter_server) | Notebook 4.3 made generated tokens the default and handed them to the opened browser; now token or cookie, HTTPS for public use, XSRF and WebSocket Origin checks ([changelog](https://github.com/jupyter/notebook/blob/4.x/docs/source/changelog.rst), [security](https://github.com/jupyter-server/jupyter_server/blob/main/docs/source/operators/security.rst), [public server](https://github.com/jupyter-server/jupyter_server/blob/main/docs/source/operators/public-server.rst)). The closest single-owner experience; a precedent for the experience, not identical threats. | Automatic token entry, cookie transition | Query tokens (fragment instead), password mode |
| [Hermes Agent](https://github.com/NousResearch/Hermes-Agent) | Loopback default; non-loopback needs a password or OAuth provider and fails without one; `--insecure` deprecated; single-use [WS ticket](https://github.com/NousResearch/hermes-agent/blob/main/hermes_cli/dashboard_auth/ws_tickets.py); redacted listings with an authenticated [reveal route](https://github.com/NousResearch/hermes-agent/blob/main/hermes_cli/web_server.py#L7663-L7696) ([dashboard](https://github.com/NousResearch/hermes-agent/blob/main/website/docs/user-guide/features/web-dashboard.md#when-the-gate-engages)) | External fail-closed behaviour, redacted secret views | Provider accounts, second WS ticket, reveal |
| [Agent Zero](https://github.com/agent0ai/agent-zero) | Optional single login, session cookie, CSRF and WS Origin checks, reverse proxies, built-in tunnels, masked [settings](https://github.com/agent0ai/agent-zero/blob/main/helpers/settings.py) ([install](https://github.com/agent0ai/agent-zero/blob/main/docs/setup/installation.md), [VPS](https://github.com/agent0ai/agent-zero/blob/main/docs/setup/vps-deployment.md)) | Cookie, CSRF, Origin and WS checks together; masked-only updates | Optional authentication, built-in public tunnels |
| [OpenHands](https://github.com/OpenHands/OpenHands) | Session API key across HTTP and WS; SSH and nginx [self-hosting](https://github.com/OpenHands/OpenHands/blob/main/docs/SELF_HOSTING.md); other editions add accounts | Common HTTP and WS key, loopback backend | Token in public HTML or browser storage, plaintext secret retrieval |
| [opencode](https://github.com/sst/opencode) | Loopback default, optional Basic auth, CORS origins, short-lived [PTY ticket](https://github.com/sst/opencode/blob/dev/packages/core/src/pty/ticket.ts) ([server](https://github.com/sst/opencode/blob/dev/packages/web/src/content/docs/server.mdx), [network](https://github.com/sst/opencode/blob/dev/packages/opencode/src/cli/network.ts)) | Loopback default | Optional authentication; second ticket, since the HttpOnly cookie already avoids WS query credentials |
| [Open WebUI](https://github.com/open-webui/open-webui) | Multi-user roles; [nginx](https://github.com/open-webui/docs/blob/main/docs/reference/https/nginx.md) and [Caddy](https://github.com/open-webui/docs/blob/main/docs/reference/https/caddy.md) guidance for HTTPS, Upgrade, SSE buffering | Proxy mechanics | Signup, accounts, JWT sessions, groups, RBAC |
| [Dify](https://github.com/langgenius/dify) | Workspace and account roles; [credential responses](https://github.com/langgenius/dify/blob/main/api/core/entities/provider_configuration.py) obfuscated with hidden-value updates | Masked-only responses, explicit replacement | Tenant and role layers |
| [LibreChat](https://github.com/danny-avila/LibreChat) | Registration, admins, role access, JWT ([authentication](https://github.com/LibreChat-AI/librechat.ai/blob/main/content/docs/features/authentication.mdx), [nginx](https://github.com/LibreChat-AI/librechat.ai/blob/main/content/docs/remote/nginx.mdx)). Shows what real multi-user design needs. | Proxy details | Identity data model |
| [AnythingLLM](https://github.com/Mintplex-Labs/anything-llm) | Separate single- and multi-user modes; single-user [bypasses auth](https://github.com/Mintplex-Labs/anything-llm/blob/master/server/utils/middleware/validatedRequest.js) without a password; multi-user adds [role checks](https://github.com/Mintplex-Labs/anything-llm/blob/master/server/utils/middleware/multiUserProtected.js) | Single-owner concept | Optional authentication |
| [AutoGen Studio](https://github.com/microsoft/autogen/tree/main/python/packages/autogen-studio) | Loopback default; [default auth](https://github.com/microsoft/autogen/blob/main/python/packages/autogen-studio/autogenstudio/web/auth/manager.py) is none; optional OAuth or JWT; research prototype | Loopback default | Query or `localStorage` credentials, post-accept WS auth, optional auth |
| [Codex CLI](https://github.com/openai/codex) | `codex app-server` over stdio and experimental WebSocket; enrollment and pairing ([app-server](https://github.com/openai/codex/blob/main/codex-rs/app-server/README.md)); no owner-hosted browser UI | None | Service-mediated remote control: OpenProgram runs no relay |
| [WeClaw](https://github.com/fastclaw-ai/weclaw/blob/main/README.md) | HTTP API on `127.0.0.1:18011` by default, listen address changeable; no owner browser UI contract | None | Not a remote-Web precedent |
| [SWE-agent](https://github.com/SWE-agent/SWE-agent) | Command-line agent; [documentation](https://github.com/SWE-agent/SWE-agent/tree/main/docs) shows no owner Web UI | None | Not applicable |
| [pi-mono](https://github.com/badlogic/pi-mono/tree/main/packages/coding-agent) | TUI, [SDK](https://github.com/badlogic/pi-mono/blob/main/packages/coding-agent/docs/sdk.md), [RPC mode](https://github.com/badlogic/pi-mono/blob/main/packages/coding-agent/docs/rpc.md); no remote Web server contract | None | Not applicable |
| [pi-ai](https://github.com/badlogic/pi-mono/tree/main/packages/ai) | Provider transport library | None | Not applicable |

### Three kinds of remote identity

| Kind | Examples | OpenProgram |
| --- | --- | --- |
| Instance credential | Jupyter, OpenClaw, OpenHands | Used: one root secret in two transport forms, one bootstrap, one set of checks; no WebSocket ticket, session database or OAuth flow |
| Application accounts | Open WebUI, Dify, LibreChat, multi-user AnythingLLM | Rejected: state and policy the product does not need |
| Device pairing | T3 Code, DSH Mobile, OpenClaw paired devices | Used: a one-time code buys one revocable device credential on the server the device already reaches |
| Managed remote control | Hosted tunnels, relays | Rejected: needs a service OpenProgram does not run |

[Permission model](https://fzkuji.github.io/OpenProgram/docs/reference/design/runtime/security/sandbox-architecture.html) · [Speaker identity](https://fzkuji.github.io/OpenProgram/docs/reference/design/memory/speaker-identity.html) · [MCP server](https://fzkuji.github.io/OpenProgram/docs/reference/design/integrations/extensions/mcp-server.html)
