Files
Codeman/src/webview-capabilities.ts
T
Codeman maintainer b34fcaf928 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>
2026-07-27 17:06:36 +02:00

117 lines
4.5 KiB
TypeScript

/**
* @fileoverview Capability tokens for the web-tab proxy.
*
* The proxy cannot authenticate on Codeman's session cookie. A sandboxed iframe
* (no `allow-same-origin`) runs in an OPAQUE origin, so every request it makes is
* cross-site: the `SameSite=lax` `codeman_session` cookie is not sent, and its
* non-GET requests and WebSocket upgrades arrive with `Origin: null`, which the
* host guard rejects by design.
*
* So `/webview/:cap/*` authenticates on an unguessable capability minted by an
* already-authenticated `POST /api/webviews/:id/open`. Properties that make this
* safe to exempt from the cookie/Origin checks:
*
* - 128 bits of `randomBytes` entropy, base64url, never derived from anything.
* - Held in memory only. A restart invalidates every outstanding capability.
* - Rolling TTL: refreshed on use, expired after inactivity.
* - Bound to the minting user, so multi-user ownership survives the exemption.
* - Grants exactly one thing: relaying bytes to that one saved URL. It reaches no
* session, no file, no API surface.
*/
import { randomBytes } from 'node:crypto';
import { StaleExpirationMap } from './utils/index.js';
import { MAX_WEBVIEW_CAPABILITIES, WEBVIEW_CAPABILITY_TTL_MS } from './config/webview-limits.js';
export interface WebviewCapabilityRecord {
webviewId: string;
/** Username that minted it (multi-user); undefined in single-user mode. */
owner?: string;
createdAt: number;
}
export class WebviewCapabilityStore {
private readonly capabilities: StaleExpirationMap<string, WebviewCapabilityRecord>;
/** Reverse index so re-opening a webview reuses its capability instead of leaking one per click. */
private readonly byWebview = new Map<string, string>();
constructor(ttlMs: number = WEBVIEW_CAPABILITY_TTL_MS) {
this.capabilities = new StaleExpirationMap<string, WebviewCapabilityRecord>({
ttlMs,
refreshOnGet: true,
onExpire: (_token, record) => {
const current = this.byWebview.get(record.webviewId);
if (current !== undefined) this.byWebview.delete(record.webviewId);
},
});
}
/** Mint (or reuse) a capability for a webview. Returns the token. */
mint(webviewId: string, owner?: string): string {
const existing = this.byWebview.get(webviewId);
if (existing) {
const record = this.capabilities.get(existing);
// Reuse only while the record is live AND still belongs to the same identity.
if (record && record.owner === owner) return existing;
this.capabilities.delete(existing);
this.byWebview.delete(webviewId);
}
// Bound growth: a client that never reuses tokens must not grow this forever.
if (this.capabilities.size >= MAX_WEBVIEW_CAPABILITIES) this.capabilities.cleanup();
const token = randomBytes(24).toString('base64url');
this.capabilities.set(token, { webviewId, owner, createdAt: Date.now() });
this.byWebview.set(webviewId, token);
return token;
}
/** Resolve a capability, refreshing its TTL. Returns undefined when unknown or expired. */
resolve(token: string): WebviewCapabilityRecord | undefined {
if (!token) return undefined;
return this.capabilities.get(token);
}
/** Revoke every capability for a webview (called on delete/edit). */
revokeWebview(webviewId: string): void {
const token = this.byWebview.get(webviewId);
if (token) {
this.capabilities.delete(token);
this.byWebview.delete(webviewId);
}
}
/** Revoke every capability minted by a user (called on logout / user deletion). */
revokeOwner(owner: string): void {
for (const [webviewId, token] of [...this.byWebview]) {
const record = this.capabilities.peek(token);
if (record?.owner === owner) {
this.capabilities.delete(token);
this.byWebview.delete(webviewId);
}
}
}
get size(): number {
return this.capabilities.size;
}
dispose(): void {
this.capabilities.dispose();
this.byWebview.clear();
}
}
/**
* Process-wide capability store.
*
* A singleton rather than an injected dependency because two unrelated layers must
* agree on it: the proxy routes that mint and consume capabilities, and the auth
* middleware, which has to recognize a valid capability to know that a
* `/webview/...` request is legitimately exempt from the cookie and Origin checks.
* Threading a store through the auth middleware's construction just to answer that
* one question would be worse. The map's cleanup timer is `unref`'d, so holding
* this at module scope does not keep the process alive.
*/
export const webviewCapabilities = new WebviewCapabilityStore();