feat(web-tabs): open dashboard URLs as tabs beside agent sessions

Adds a "Web / URL" section to the Run dropdown. A saved URL renders as a tab in
the same strip as Claude/Codex/Gemini sessions, with the same Alt+1..9 numbering,
so Codeman is one mission control instead of Codeman plus a pile of browser tabs.

A webview is NOT a sixth SessionMode: no PTY, no tmux, no respawn, no idle
detection. It is a separate resource sharing only the tab strip and the main
content area, the same call that keeps Docker and remote-SSH as case overlays.

Dashboards are proxied through Codeman's own origin, because a direct iframe
fails three ways at once in the shipped deployment: prod serves HTTPS behind
tailscale serve, so http:// targets are hard-blocked as mixed content (with no
override at all on iOS Safari); Grafana/Portainer-class dashboards send
X-Frame-Options: DENY; and our own default-src 'self' CSP blocks cross-origin
frames. Proxying dissolves all three and leaves the production CSP byte-for-byte
unchanged, since /webview/... is already covered by 'self'. A useful side effect:
the fetch happens server-side, so a tailnet-only dashboard is reachable from a
phone that is not on the tailnet.

The proxy is not an API surface. It authenticates on a 192-bit capability in the
path (memory-only, rolling TTL, bound to the minting user, revoked on edit or
delete) and is correspondingly exempt from the cookie and Origin checks, because
a sandboxed iframe is opaque-origin: it sends no SameSite=lax cookie and its
writes arrive with Origin: null. The Host allowlist is never bypassed. A second
Referer-keyed form of the exemption exists for root-absolute assets and is fenced
to safe methods on non-/api, non-/ws, non-/q paths.

Iframes omit allow-same-origin unless a URL is explicitly marked trusted, since a
proxied page is served from Codeman's own origin and could otherwise read this
document and drive the agent-spawning API. Authorization and codeman_session are
stripped upstream in BOTH modes, so CODEMAN_PASSWORD cannot leak into a dashboard.

Two things only a real browser reveals, both presenting as the dashboard's own
"Failed to fetch" while the page itself renders fine:

- Runtime-built root-absolute URLs (fetch('/api/data')) escape <base href> and
  land on Codeman's root. Widening the Referer fallback into /api would trade
  security for it, so an injected shim patches fetch/XHR/WebSocket/EventSource
  inside the frame instead, removing the class rather than the guard.
- An opaque-origin document CORS-checks every request, including to the host it
  was served from. Script/css/img loads are not CORS-checked, which is why the
  page renders while its API calls die. The proxy now emits CORS headers and
  answers preflights itself. registerSecurityHeaders answered every OPTIONS with
  a bare 204 before routing, carrying no ACAO for Origin: null, so that
  short-circuit now exempts a valid capability.

Neither is reproducible with curl, which does not enforce CORS.

Also fixes a pre-existing bug found on the way: .toolbar has backdrop-filter,
making it a stacking context that trapped .run-mode-menu's z-index:1000, so
.welcome-overlay painted over the whole Run menu. With no session open, every
item in it (Claude Code included) was unclickable.

Verified end to end against a real tailnet dashboard: live data, WebSocket push,
no failed requests, and switching tabs does not reload the frame. 98 new tests
cover the pure rewrite helpers, the CORS helper, the shim's rewrite logic, route
CRUD, and every edge of the auth exemption.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
This commit is contained in:
Codeman maintainer
2026-07-27 17:06:36 +02:00
parent ea4c935d51
commit b34fcaf928
26 changed files with 3316 additions and 18 deletions
+79 -3
View File
@@ -22,6 +22,8 @@ import {
import { getHookSecret, HOOK_SECRET_HEADER } from '../../config/hook-secret.js';
import { isMultiUserMode } from '../../config/multiuser.js';
import { findUser, setPassword, touchLastLogin, verifyPassword } from '../../user-store.js';
import { webviewCapabilities } from '../../webview-capabilities.js';
import { capabilityFromProxyPath, capabilityFromReferer } from '../webview-proxy.js';
import { ApiErrorCode, createErrorResponse, type AuthUser } from '../../types.js';
// Request-scoped identity (multi-user). Single-user leaves it undefined and the
@@ -120,6 +122,49 @@ function isPasswordChangeExempt(req: FastifyRequest): boolean {
return !url.startsWith('/api/');
}
/**
* Whether this request carries a VALID web-tab proxy capability.
*
* Requests under `/webview/<cap>/` cannot authenticate the normal way. The iframe
* rendering a dashboard is sandboxed without `allow-same-origin`, so it runs in an
* opaque origin: every request it makes is cross-site, meaning the `SameSite=lax`
* `codeman_session` cookie is never attached, and non-GET requests and WebSocket
* upgrades arrive with `Origin: null`. Both the cookie check and the CSRF Origin
* guard would therefore reject a perfectly legitimate dashboard asset load.
*
* The capability in the path is the credential instead: 192 bits of entropy, held
* in memory only (a restart invalidates it), rolling TTL, bound to the user who
* minted it through an already-authenticated `POST /api/webviews/:id/open`, and
* granting nothing but "relay bytes to this one saved URL".
*
* The exemption is deliberately narrow: it requires the capability to RESOLVE, so
* a bare `/webview/anything` reaches nothing, and a `/webviewfoo` path does not
* match the prefix at all. The Host allowlist is NOT bypassed, so DNS-rebinding
* protection still applies to these requests.
*/
function hasValidWebviewCapability(req: FastifyRequest): boolean {
const url = (req.url ?? '').split('?')[0];
const fromPath = capabilityFromProxyPath(url);
if (fromPath) return webviewCapabilities.resolve(fromPath) !== undefined;
// Referer form: a dashboard subresource requested with a ROOT-ABSOLUTE URL, which
// lands on Codeman's root and is relayed by the 404 fallback. Without this the
// asset would be rejected here, before the fallback ever runs.
//
// This is the only exemption decided by a header the request itself supplies, so
// it is fenced in hard: safe methods only, and never for Codeman's own functional
// surfaces. Without those fences a page could present a webview Referer and skip
// auth on /api. It is not a privilege escalation even so, holding a live
// capability already implies an authenticated `POST /api/webviews/:id/open`, but
// the exemption should stay no wider than the problem it solves.
if (req.method !== 'GET' && req.method !== 'HEAD') return false;
if (url.startsWith('/api/') || url.startsWith('/ws/') || url.startsWith('/q/')) return false;
const fromReferer = capabilityFromReferer(typeof req.headers.referer === 'string' ? req.headers.referer : undefined);
return !!fromReferer && webviewCapabilities.resolve(fromReferer) !== undefined;
}
/**
* Register HTTP Basic Auth middleware with session cookies and rate limiting.
* Only active when CODEMAN_PASSWORD is set.
@@ -211,6 +256,12 @@ export function registerAuthMiddleware(app: FastifyInstance, https: boolean): Au
return;
}
// Web-tab proxy, authenticated by the capability in the path, not the cookie.
if (hasValidWebviewCapability(req)) {
done();
return;
}
const clientIp = req.ip;
// Check session cookie first (avoids re-sending credentials on every request)
@@ -341,6 +392,12 @@ function registerMultiUserAuthHook(
// QR redemption path — handled by the route itself.
if (req.url?.startsWith('/q/')) return;
// Web-tab proxy, authenticated by the capability in the path, not the cookie.
// `req.authUser` stays undefined here on purpose: the proxy handler enforces
// ownership against the identity BOUND TO THE CAPABILITY, which is stricter
// than re-deriving it from a request that carries no credentials.
if (hasValidWebviewCapability(req)) return;
const clientIp = req.ip;
// 1. Cookie session (carries identity + mustChangePassword snapshot).
@@ -466,7 +523,17 @@ export function registerHostGuard(app: FastifyInstance, getPolicy: () => HostPol
reply.code(403).send('Forbidden: host not allowed');
return;
}
if (!SAFE_HTTP_METHODS.has(req.method) && !isAllowedRequestOrigin(req.headers.origin, policy)) {
// The Host allowlist above is NEVER bypassed. The Origin (CSRF) check is,
// but only for a request carrying a valid web-tab capability: a sandboxed
// dashboard is opaque-origin, so its form posts and uploads arrive with
// `Origin: null`, which this guard rejects by design. The capability is the
// credential in that case, and it is unguessable, see
// hasValidWebviewCapability.
if (
!SAFE_HTTP_METHODS.has(req.method) &&
!isAllowedRequestOrigin(req.headers.origin, policy) &&
!hasValidWebviewCapability(req)
) {
reply.code(403).send('Forbidden: cross-site request blocked');
return;
}
@@ -521,8 +588,17 @@ export function registerSecurityHeaders(app: FastifyInstance, https: boolean): v
}
}
// Handle CORS preflight
if (req.method === 'OPTIONS') {
// Handle CORS preflight.
//
// EXCEPT for the web-tab proxy, which must answer its own preflight. A
// sandboxed dashboard iframe is opaque-origin, so it sends `Origin: null`;
// the CORS block above only emits headers for localhost origins, so a bare
// 204 from here carries no `Access-Control-Allow-Origin` and the browser
// rejects the preflight. Every dashboard fetch then fails with an opaque
// net::ERR_FAILED while the page itself renders fine (script/css/img loads
// are not CORS-checked). Falling through lets the proxy route reply with the
// right headers.
if (req.method === 'OPTIONS' && !hasValidWebviewCapability(req)) {
reply.code(204).send();
done();
return;