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
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)
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.
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
CLIopen /#token=…
BrowserGET / without the fragment; gets the public shell
Browsertoken into memory, history.replaceState()
BrowserPOST /api/auth/bootstrap
Web server204, Set-Cookie: HttpOnly
BrowserHTTP, 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
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.
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.
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.
Computeropenprogram web pair: POST /api/auth/pairings mints a code; the CLI prints <origin>/#pair=<code> and its QR code
Other deviceopens the link; the fragment leaves the address bar before any request
Other devicePOST /api/auth/pair {"code"}
Web serverspends the code; a browser (it sends Origin) gets the device cookie with 204, a native client gets {"device_id","token"}
Other deviceevery 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.
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
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'
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.
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.
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
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
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
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
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
Loopback HTTP, SSE and WebSocket without a credential fail.
A correct Bearer token works without Origin; a wrong one gets the same 401 and does nothing.
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.
Cookie unsafe HTTP and WebSocket reject missing, opaque, cross-site and unlisted origins before action or accept.
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.
Default loopback accepts only its implicit origins; another SSH local port is rejected until configured.
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.
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.
A second process for one state directory cannot change the live token or snapshot; bind failure removes only the failing process's files.
Restart rotates the token and invalidates the old Bearer and cookie.
A malformed Authorization header never falls back to a cookie.
Static assets and /healthz contain no token, session, filesystem or credential data or diagnostics.
Headers reject framing; protected responses are no-store; 401 advertises the Bearer realm.
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.
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.
nginx and Caddy carry authenticated HTTP, SSE and WebSocket over HTTPS with a loopback backend.
Channel messages keep paired and gain no owner authority.
Two profile servers on one hostname and different ports have distinct cookies and authenticate independently.
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.
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, security, public server). The closest single-owner experience; a precedent for the experience, not identical threats.
Loopback default; non-loopback needs a password or OAuth provider and fails without one; --insecure deprecated; single-use WS ticket; redacted listings with an authenticated reveal route (dashboard)