Node-based terminal manager for AI coding agents — tmux-backed terminals and parallel agent sessions as draggable nodes on an infinite pan/zoom canvas. macOS, Linux, and a browser Server Edition.
TypeScript adhdagent-orchestrationai-agentscanvasclaude-codecodexcoding-agentsdeveloper-toolselectrongeminilinuxmacosmultiplexeropencodeparallel-agentsterminalterminal-emulatorterminal-multiplexertmuxworkspace-manager
feat(server): reverse-proxy SSO header trust (#29, Option B)
enesffff0fb4bede
diff --git a/docs/SERVER.md b/docs/SERVER.mdindex 3e5547c1a..de3c47bde 100644--- a/docs/SERVER.md+++ b/docs/SERVER.md@@ -67,6 +67,8 @@ Precedence: **CLI flag > environment variable > default.**| `--renderer-dir <path>` | `NODETERM_RENDERER_DIR` | `out/renderer` (resolved from cwd) | Directory of the built renderer (`index.html` + hashed assets). || `--insecure-http` | — | off | Acknowledge serving plain HTTP directly on a non-loopback interface (see below). || — | `NODETERM_SERVER_PASSWORD` | — | Seed the password headlessly on first boot (see above). |+| `--trust-proxy-header <name>` | `NODETERM_TRUST_PROXY_HEADER` | — (off) | Reverse-proxy SSO trust: identity header asserted by your proxy (see [Reverse-proxy SSO](#reverse-proxy-sso-header-trust)). |+| `--trust-proxy-nets <list>` | `NODETERM_TRUST_PROXY_NETS` | `127.0.0.0/8, ::1/128` | Comma-separated IPs/CIDRs (IPv4+IPv6) whose requests may use the trust header. Only meaningful with the header set. |Binding a **non-loopback** host (anything other than `127.0.0.1` / `localhost` /`::1`) **without** `--insecure-http` is refused at startup — plain HTTP on a public@@ -95,6 +97,44 @@ Single-user auth. There is one password; sessions are per-browser.- **Auth gate:** every route except the login/setup pages and their POST handlersrequires a valid session — HTML navigations redirect to `/login`, API/WS get `401`.+### Reverse-proxy SSO (header trust)++Deployments that front the server with an SSO reverse proxy (Cloudflare Access,+Tailscale, oauth2-proxy, Authelia…) already authenticate every request before it+reaches nodeterm, and the proxy asserts the identity in a request header. Setting+`NODETERM_TRUST_PROXY_HEADER` makes such requests count as authenticated — no+password, setup token, or session cookie needed:++```bash+# Cloudflare Access+NODETERM_TRUST_PROXY_HEADER=Cf-Access-Authenticated-User-Email node out/server/main.cjs+# Tailscale (tailscale serve / funnel with identity headers)+NODETERM_TRUST_PROXY_HEADER=Tailscale-User-Login node out/server/main.cjs+# oauth2-proxy / Authelia / most others+NODETERM_TRUST_PROXY_HEADER=X-Forwarded-User node out/server/main.cjs+```++A request is trusted only when **both** hold:++1. its **TCP peer address** is inside `NODETERM_TRUST_PROXY_NETS` (default:+ loopback only — the same-host proxy deployment). If your proxy reaches the+ container over a private network, list it explicitly, e.g.+ `NODETERM_TRUST_PROXY_NETS=127.0.0.1,10.0.0.0/8`;+2. it carries the configured header with a **non-empty value**.++The header **content is not validated** (no JWT verification) — the trusted-network+boundary is the trust statement. That makes two things non-negotiable: only the+proxy may be reachable from the trusted networks, and the proxy must+**strip/overwrite** the header on incoming client requests (Cloudflare Access,+Tailscale and oauth2-proxy all do). A typo'd nets entry fails the boot rather than+silently changing who is trusted; setting nets without a header is likewise refused.++Everything else stays intact: password/cookie auth keeps working beside it (e.g.+for loopback ops access), the WS upgrade still enforces the same-host Origin check,+and a proxy-authed visit to `/login` or `/setup` just redirects home. The boot log+prints a `⚠️ Proxy header trust ENABLED` line naming the header and networks —+verify it matches what you meant to trust.+### TLS (reverse proxy)The server speaks **plain HTTP** by design. For anything beyond `localhost`, run itdiff --git a/src/server/config.test.ts b/src/server/config.test.tsindex 60ee6490c..7e50eff0c 100644--- a/src/server/config.test.ts+++ b/src/server/config.test.ts@@ -25,4 +25,34 @@ describe('resolveConfig', () => {expect(() => resolveConfig({ NODETERM_HOST: '0.0.0.0' }, [])).toThrow(/insecure-http|reverse proxy/i)expect(() => resolveConfig({ NODETERM_HOST: '0.0.0.0' }, ['--insecure-http'])).not.toThrow()})++ it('proxy trust: off by default', () => {+ expect(resolveConfig({}, []).trustProxy).toBeUndefined()+ })++ it('proxy trust: header via env, nets default to loopback', () => {+ const c = resolveConfig({ NODETERM_TRUST_PROXY_HEADER: 'Cf-Access-Authenticated-User-Email' }, [])+ expect(c.trustProxy?.header).toBe('Cf-Access-Authenticated-User-Email')+ expect(c.trustProxy?.nets.length).toBeGreaterThan(0)+ })++ it('proxy trust: argv overrides env; custom nets parsed', () => {+ const c = resolveConfig({ NODETERM_TRUST_PROXY_HEADER: 'X-Env' }, [+ '--trust-proxy-header',+ 'Tailscale-User-Login',+ '--trust-proxy-nets',+ '10.0.0.0/8'+ ])+ expect(c.trustProxy?.header).toBe('Tailscale-User-Login')+ expect(c.trustProxy?.nets).toHaveLength(1)+ })++ it('proxy trust: invalid nets or nets-without-header fail the boot', () => {+ expect(() =>+ resolveConfig({ NODETERM_TRUST_PROXY_HEADER: 'X-U', NODETERM_TRUST_PROXY_NETS: 'nope' }, [])+ ).toThrow(/nope/)+ expect(() => resolveConfig({ NODETERM_TRUST_PROXY_NETS: '10.0.0.0/8' }, [])).toThrow(+ /TRUST_PROXY_HEADER/i+ )+ })})diff --git a/src/server/config.ts b/src/server/config.tsindex 781c4e766..5094fb8b2 100644--- a/src/server/config.ts+++ b/src/server/config.ts@@ -1,5 +1,6 @@import os from 'os'import path from 'path'+import { parseTrustedNets, DEFAULT_TRUSTED_NETS_SPEC, type TrustProxyConfig } from './proxy-trust'/*** Fully-resolved server configuration. Produced by {@link resolveConfig} from the@@ -21,6 +22,12 @@ export type ServerConfig = {* every subsequent agent session on the machine.*/installHooks?: boolean+ /**+ * Reverse-proxy SSO trust (issue #29): requests whose TCP peer is inside `nets` and+ * which carry `header` (non-empty) are authenticated without a session cookie.+ * Absent = feature off (default). See src/server/proxy-trust.ts and docs/SERVER.md.+ */+ trustProxy?: TrustProxyConfig}/**@@ -85,5 +92,24 @@ export function resolveConfig(env: NodeJS.ProcessEnv, argv: string[]): ServerCon)}- return { port, host, dataDir, rendererDir, insecureHttp, passwordSeed }+ // Reverse-proxy SSO trust. `pick` with an empty default so "unset" and "" coincide.+ const trustHeader = pick('trust-proxy-header', 'NODETERM_TRUST_PROXY_HEADER', '')+ const trustNetsSpec = pick('trust-proxy-nets', 'NODETERM_TRUST_PROXY_NETS', '')+ let trustProxy: TrustProxyConfig | undefined+ if (trustHeader !== '') {+ // parseTrustedNets throws on a typo — a bad trust config must fail the boot, not+ // silently change who is trusted.+ trustProxy = {+ header: trustHeader,+ nets: parseTrustedNets(trustNetsSpec || DEFAULT_TRUSTED_NETS_SPEC)+ }+ } else if (trustNetsSpec !== '') {+ throw new Error(+ `--trust-proxy-nets / NODETERM_TRUST_PROXY_NETS is set but no trust header is configured. ` ++ `Set NODETERM_TRUST_PROXY_HEADER (or --trust-proxy-header) to the identity header your ` ++ `reverse proxy asserts (e.g. Cf-Access-Authenticated-User-Email), or unset the nets.`+ )+ }++ return { port, host, dataDir, rendererDir, insecureHttp, passwordSeed, trustProxy }}diff --git a/src/server/http.test.ts b/src/server/http.test.tsindex a2789e289..d08521ce5 100644--- a/src/server/http.test.ts+++ b/src/server/http.test.ts@@ -5,6 +5,7 @@ import os from 'os'import path from 'path'import { Auth } from './auth'import { createHttpHandler, sessionTokenFromCookie, SESSION_COOKIE } from './http'+import { parseTrustedNets } from './proxy-trust'let dir: string, rendererDir: string, server: http.Server, base: string, auth: Auth@@ -123,3 +124,67 @@ describe('http layer', () => {expect(sessionTokenFromCookie(undefined)).toBeUndefined()})})++describe('http layer with proxy header trust', () => {+ const HDR = 'Cf-Access-Authenticated-User-Email'++ function trustedServer(netsSpec: string): Promise<{ srv: http.Server; url: string }> {+ const srv = http.createServer(+ createHttpHandler({+ auth,+ rendererDir,+ trustProxy: { header: HDR, nets: parseTrustedNets(netsSpec) }+ })+ )+ return new Promise((r) =>+ srv.listen(0, '127.0.0.1', () =>+ r({ srv, url: `http://127.0.0.1:${(srv.address() as { port: number }).port}` })+ )+ )+ }++ it('trusted peer + header: serves the app with no cookie; /login and /setup redirect home', async () => {+ const { srv, url } = await trustedServer('127.0.0.0/8')+ try {+ const home = await fetch(`${url}/`, { headers: { [HDR]: '[email protected]' } })+ expect(home.status).toBe(200)+ const login = await fetch(`${url}/login`, {+ headers: { [HDR]: '[email protected]' },+ redirect: 'manual'+ })+ expect(login.status).toBe(302)+ expect(login.headers.get('location')).toBe('/')+ const setup = await fetch(`${url}/setup`, {+ headers: { [HDR]: '[email protected]' },+ redirect: 'manual'+ })+ expect(setup.status).toBe(302)+ expect(setup.headers.get('location')).toBe('/')+ } finally {+ await new Promise((r) => srv.close(r))+ }+ })++ it('missing/empty header, or a peer outside the nets, falls through to normal auth', async () => {+ const { srv, url } = await trustedServer('127.0.0.0/8')+ const { srv: srvFar, url: urlFar } = await trustedServer('10.0.0.0/8')+ try {+ expect((await fetch(`${url}/x.json`, { redirect: 'manual' })).status).toBe(401)+ expect(+ (await fetch(`${url}/x.json`, { headers: { [HDR]: ' ' }, redirect: 'manual' })).status+ ).toBe(401)+ // Loopback peer, but the trusted nets exclude loopback → the header means nothing.+ expect(+ (await fetch(`${urlFar}/x.json`, { headers: { [HDR]: '[email protected]' }, redirect: 'manual' }))+ .status+ ).toBe(401)+ // Password/cookie auth still works beside proxy trust.+ const cookie = await setupAndLogin()+ const viaCookie = await fetch(`${urlFar}/`, { headers: { cookie } })+ expect(viaCookie.status).toBe(200)+ } finally {+ await new Promise((r) => srv.close(r))+ await new Promise((r) => srvFar.close(r))+ }+ })+})diff --git a/src/server/http.ts b/src/server/http.tsindex 54c78aaac..a772336dd 100644--- a/src/server/http.ts+++ b/src/server/http.ts@@ -7,6 +7,7 @@ import http from 'http'import fs from 'fs'import path from 'path'import type { Auth } from './auth'+import { proxyAuthAllowed, type TrustProxyConfig } from './proxy-trust'export const SESSION_COOKIE = 'nt_session'@@ -30,6 +31,13 @@ const PAGE_CSP = "default-src 'none'; style-src 'unsafe-inline'; form-action 'seexport interface HttpHandlerOpts {auth: AuthrendererDir: string+ /**+ * Reverse-proxy SSO trust (issue #29): when set, a request whose TCP peer is inside the+ * trusted nets and which carries the header (non-empty) is authenticated without a+ * session cookie. Never *blocks* anything — a request that doesn't qualify simply falls+ * through to the normal cookie/login path.+ */+ trustProxy?: TrustProxyConfig}/** Parse the `nt_session=` value out of a Cookie header. Exported for the WS upgrade (Task 5). */@@ -215,7 +223,7 @@ function serveStatic(export function createHttpHandler(opts: HttpHandlerOpts): (req: http.IncomingMessage, res: http.ServerResponse) => void {- const { auth, rendererDir } = opts+ const { auth, rendererDir, trustProxy } = optsreturn function handler(req: http.IncomingMessage, res: http.ServerResponse): void {void handle(req, res).catch(() => {@@ -229,6 +237,15 @@ export function createHttpHandler(const pathname = url.pathnameconst method = req.method || 'GET'+ const proxyAuthed =+ trustProxy !== undefined && proxyAuthAllowed(trustProxy, req.headers, req.socket.remoteAddress)++ // A proxy-authed caller has no use for the password pages — send them home.+ if (proxyAuthed && method === 'GET' && (pathname === '/login' || pathname === '/setup')) {+ redirect(res, 302, '/')+ return+ }+// ---- Public auth routes (no session required) --------------------------if (pathname === '/setup' && method === 'GET') {@@ -318,7 +335,7 @@ export function createHttpHandler(// ---- Everything else requires a valid session --------------------------const token = sessionTokenFromCookie(req.headers['cookie'])- if (!auth.validateSession(token)) {+ if (!proxyAuthed && !auth.validateSession(token)) {if (isHtmlNavigation(req)) redirect(res, 302, '/login')else sendJson(res, 401, { error: 'unauthorized' })returndiff --git a/src/server/index.ts b/src/server/index.tsindex bd42aedf7..4c1b89a6f 100644--- a/src/server/index.ts+++ b/src/server/index.ts@@ -6,6 +6,7 @@ import { ServerPlatform } from './platform-server'import { Auth } from './auth'import { createHttpHandler } from './http'import { attachWsServer } from './ws'+import { describeTrustedNets } from './proxy-trust'import type { ServerConfig } from './config'import { initPlatform } from '../core/platform'@@ -89,6 +90,16 @@ export async function startServer(const auth = new Auth(config.dataDir)if (config.passwordSeed && !auth.isConfigured()) auth.setPassword(config.passwordSeed)+ if (config.trustProxy) {+ // Loud on purpose: this line is the operator's one chance to notice a trust+ // misconfiguration (wrong header name, or nets wider than the proxy's own subnet).+ console.log(+ `⚠️ Proxy header trust ENABLED: requests from [${describeTrustedNets(config.trustProxy.nets)}] ` ++ `carrying a non-empty "${config.trustProxy.header}" header are authenticated WITHOUT a ` ++ `password. Ensure ONLY your SSO reverse proxy can reach this server from those networks, ` ++ `and that it strips/overwrites this header on client requests.`+ )+ }if (!auth.isConfigured()) {// No password set yet: print the one-time setup URL so the operator can bootstrap.console.log(`Setup: http://${config.host}:${config.port}/setup?token=${auth.setupToken()}`)@@ -278,10 +289,17 @@ export async function startServer(}await hookServer.start()- const server = http.createServer(createHttpHandler({ auth, rendererDir: config.rendererDir }))+ const server = http.createServer(+ createHttpHandler({ auth, rendererDir: config.rendererDir, trustProxy: config.trustProxy })+ )// A closed browser tab is the NORMAL way to leave the Server Edition and sends no `pty:kill`,// so the WS close hook is what unsubscribes that client from the sessions it was watching.- attachWsServer(server, { platform, auth, onClientGone: (uiId) => ptyManager.dropClient(uiId) })+ attachWsServer(server, {+ platform,+ auth,+ onClientGone: (uiId) => ptyManager.dropClient(uiId),+ trustProxy: config.trustProxy+ })await new Promise<void>((resolve, reject) => {server.once('error', reject)diff --git a/src/server/proxy-trust.test.ts b/src/server/proxy-trust.test.tsnew file mode 100644index 000000000..dc59138b1--- /dev/null+++ b/src/server/proxy-trust.test.ts@@ -0,0 +1,117 @@+import { describe, it, expect } from 'vitest'+import {+ parseTrustedNets,+ isTrustedAddress,+ proxyAuthAllowed,+ describeTrustedNets,+ DEFAULT_TRUSTED_NETS_SPEC,+ type TrustProxyConfig+} from './proxy-trust'++describe('parseTrustedNets', () => {+ it('parses IPv4 addresses and CIDRs', () => {+ const nets = parseTrustedNets('127.0.0.1, 10.0.0.0/8')+ expect(nets).toHaveLength(2)+ expect(isTrustedAddress('127.0.0.1', nets)).toBe(true)+ expect(isTrustedAddress('10.20.30.40', nets)).toBe(true)+ expect(isTrustedAddress('11.0.0.1', nets)).toBe(false)+ })++ it('parses IPv6 addresses and CIDRs', () => {+ const nets = parseTrustedNets('::1, fd00::/8')+ expect(isTrustedAddress('::1', nets)).toBe(true)+ expect(isTrustedAddress('fd12:3456::1', nets)).toBe(true)+ expect(isTrustedAddress('fe80::1', nets)).toBe(false)+ })++ it('throws on an unparseable entry (fail closed at boot)', () => {+ expect(() => parseTrustedNets('10.0.0.0/8, not-an-ip')).toThrow(/not-an-ip/)+ expect(() => parseTrustedNets('10.0.0.0/33')).toThrow(/10\.0\.0\.0\/33/)+ expect(() => parseTrustedNets('::1/129')).toThrow(/::1\/129/)+ expect(() => parseTrustedNets('')).toThrow(/empty/i)+ expect(() => parseTrustedNets(' , ')).toThrow(/empty/i)+ })++ it('default spec covers loopback only', () => {+ const nets = parseTrustedNets(DEFAULT_TRUSTED_NETS_SPEC)+ expect(isTrustedAddress('127.0.0.1', nets)).toBe(true)+ expect(isTrustedAddress('127.255.255.254', nets)).toBe(true)+ expect(isTrustedAddress('::1', nets)).toBe(true)+ expect(isTrustedAddress('10.0.0.1', nets)).toBe(false)+ expect(isTrustedAddress('fd00::1', nets)).toBe(false)+ })+})++describe('isTrustedAddress', () => {+ it('normalizes IPv4-mapped IPv6 peers (::ffff:a.b.c.d) against IPv4 nets', () => {+ const nets = parseTrustedNets('127.0.0.0/8')+ expect(isTrustedAddress('::ffff:127.0.0.1', nets)).toBe(true)+ expect(isTrustedAddress('::ffff:10.0.0.1', nets)).toBe(false)+ })++ it('respects non-octet-aligned prefixes', () => {+ const nets = parseTrustedNets('192.168.4.0/22')+ expect(isTrustedAddress('192.168.7.255', nets)).toBe(true)+ expect(isTrustedAddress('192.168.8.0', nets)).toBe(false)+ })++ it('rejects garbage or missing peer addresses', () => {+ const nets = parseTrustedNets('127.0.0.0/8')+ expect(isTrustedAddress(undefined, nets)).toBe(false)+ expect(isTrustedAddress('', nets)).toBe(false)+ expect(isTrustedAddress('bogus', nets)).toBe(false)+ })++ it('an IPv4 peer never matches an IPv6 net and vice versa', () => {+ expect(isTrustedAddress('127.0.0.1', parseTrustedNets('::1'))).toBe(false)+ expect(isTrustedAddress('::1', parseTrustedNets('127.0.0.0/8'))).toBe(false)+ })+})++describe('proxyAuthAllowed', () => {+ const trust: TrustProxyConfig = {+ header: 'Cf-Access-Authenticated-User-Email',+ nets: parseTrustedNets('127.0.0.0/8')+ }++ it('allows a trusted peer carrying a non-empty header (case-insensitive name)', () => {+ expect(+ proxyAuthAllowed(trust, { 'cf-access-authenticated-user-email': '[email protected]' }, '127.0.0.1')+ ).toBe(true)+ })++ it('rejects when the header is missing or empty', () => {+ expect(proxyAuthAllowed(trust, {}, '127.0.0.1')).toBe(false)+ expect(+ proxyAuthAllowed(trust, { 'cf-access-authenticated-user-email': '' }, '127.0.0.1')+ ).toBe(false)+ expect(+ proxyAuthAllowed(trust, { 'cf-access-authenticated-user-email': ' ' }, '127.0.0.1')+ ).toBe(false)+ })++ it('rejects a peer outside the trusted nets even with the header', () => {+ expect(+ proxyAuthAllowed(trust, { 'cf-access-authenticated-user-email': '[email protected]' }, '10.0.0.5')+ ).toBe(false)+ })++ it('rejects a repeated header (array value) — ambiguous, so fail closed', () => {+ expect(+ proxyAuthAllowed(+ trust,+ { 'cf-access-authenticated-user-email': ['[email protected]', '[email protected]'] as unknown as string },+ '127.0.0.1'+ )+ ).toBe(false)+ })+})++describe('describeTrustedNets', () => {+ it('round-trips both families readably', () => {+ expect(describeTrustedNets(parseTrustedNets('127.0.0.0/8, 10.1.2.3'))).toBe(+ '127.0.0.0/8, 10.1.2.3/32'+ )+ expect(describeTrustedNets(parseTrustedNets('::1'))).toBe('0:0:0:0:0:0:0:1/128')+ })+})diff --git a/src/server/proxy-trust.ts b/src/server/proxy-trust.tsnew file mode 100644index 000000000..21497de2d--- /dev/null+++ b/src/server/proxy-trust.ts@@ -0,0 +1,155 @@+// Reverse-proxy SSO header trust (issue #29, Option B).+//+// A deployment that fronts the Server Edition with an SSO reverse proxy (Cloudflare+// Access, Tailscale, oauth2-proxy…) already authenticates every request; the proxy+// asserts the identity in a request header. When configured, a request is treated as+// authenticated iff its TCP peer address is inside the trusted networks AND it carries+// the configured header with a non-empty value. The header CONTENT is deliberately not+// validated (no JWT verification): the trusted-network boundary is the trust statement —+// only the proxy can be the TCP peer, and the proxy owns setting/stripping the header.+// Everything here is pure (no node:http import) so it unit-tests without sockets.++export interface TrustedNet {+ /** 4 bytes (IPv4) or 16 bytes (IPv6). */+ bytes: Uint8Array+ prefix: number+}++export interface TrustProxyConfig {+ /** Header name asserting the authenticated identity, e.g. Cf-Access-Authenticated-User-Email. */+ header: string+ nets: TrustedNet[]+}++/** Default trusted networks: loopback only — the recommended same-host proxy deployment. */+export const DEFAULT_TRUSTED_NETS_SPEC = '127.0.0.0/8, ::1/128'++function parseIPv4(s: string): Uint8Array | null {+ const parts = s.split('.')+ if (parts.length !== 4) return null+ const out = new Uint8Array(4)+ for (let i = 0; i < 4; i++) {+ if (!/^\d{1,3}$/.test(parts[i])) return null+ const n = Number(parts[i])+ if (n > 255) return null+ out[i] = n+ }+ return out+}++function parseIPv6(s: string): Uint8Array | null {+ // Handle a trailing IPv4 tail (::ffff:1.2.3.4) by converting it to two hex groups.+ const v4Tail = s.match(/^(.*:)(\d+\.\d+\.\d+\.\d+)$/)+ if (v4Tail) {+ const v4 = parseIPv4(v4Tail[2])+ if (!v4) return null+ const hi = ((v4[0] << 8) | v4[1]).toString(16)+ const lo = ((v4[2] << 8) | v4[3]).toString(16)+ s = v4Tail[1] + hi + ':' + lo+ }+ const halves = s.split('::')+ if (halves.length > 2) return null+ const groups = (part: string): string[] => (part === '' ? [] : part.split(':'))+ const head = groups(halves[0])+ const tail = halves.length === 2 ? groups(halves[1]) : []+ const missing = 8 - head.length - tail.length+ if (halves.length === 2 ? missing < 1 : missing !== 0) return null+ const all = [...head, ...Array(halves.length === 2 ? missing : 0).fill('0'), ...tail]+ const out = new Uint8Array(16)+ for (let i = 0; i < 8; i++) {+ if (!/^[0-9a-fA-F]{1,4}$/.test(all[i])) return null+ const n = parseInt(all[i], 16)+ out[i * 2] = n >> 8+ out[i * 2 + 1] = n & 0xff+ }+ return out+}++function parseAddress(s: string): Uint8Array | null {+ return s.includes(':') ? parseIPv6(s) : parseIPv4(s)+}++/**+ * Parse a comma-separated list of IPs / CIDRs (IPv4 + IPv6) into trusted nets.+ * Throws on any unparseable entry: a typo in the trust config must fail the boot,+ * not silently narrow (or widen) trust.+ */+export function parseTrustedNets(spec: string): TrustedNet[] {+ const entries = spec+ .split(',')+ .map((e) => e.trim())+ .filter((e) => e !== '')+ if (entries.length === 0) throw new Error('trusted-nets list is empty')+ return entries.map((entry) => {+ const slash = entry.indexOf('/')+ const addrPart = slash === -1 ? entry : entry.slice(0, slash)+ const bytes = parseAddress(addrPart)+ if (!bytes) throw new Error(`unparseable trusted-net entry "${entry}"`)+ const maxPrefix = bytes.length * 8+ let prefix = maxPrefix+ if (slash !== -1) {+ const p = entry.slice(slash + 1)+ if (!/^\d{1,3}$/.test(p) || Number(p) > maxPrefix) {+ throw new Error(`unparseable trusted-net entry "${entry}"`)+ }+ prefix = Number(p)+ }+ return { bytes, prefix }+ })+}++/** Collapse an IPv4-mapped IPv6 address (::ffff:a.b.c.d) to its 4-byte IPv4 form. */+function normalize(bytes: Uint8Array): Uint8Array {+ if (bytes.length !== 16) return bytes+ for (let i = 0; i < 10; i++) if (bytes[i] !== 0) return bytes+ if (bytes[10] !== 0xff || bytes[11] !== 0xff) return bytes+ return bytes.slice(12)+}++function matchesNet(addr: Uint8Array, net: TrustedNet): boolean {+ if (addr.length !== net.bytes.length) return false+ const fullBytes = net.prefix >> 3+ for (let i = 0; i < fullBytes; i++) if (addr[i] !== net.bytes[i]) return false+ const rem = net.prefix & 7+ if (rem === 0) return true+ const mask = (0xff << (8 - rem)) & 0xff+ return (addr[fullBytes] & mask) === (net.bytes[fullBytes] & mask)+}++/** Human-readable form of the parsed nets for the boot-time warning log. */+export function describeTrustedNets(nets: TrustedNet[]): string {+ return nets+ .map((net) => {+ if (net.bytes.length === 4) return `${Array.from(net.bytes).join('.')}/${net.prefix}`+ const groups: string[] = []+ for (let i = 0; i < 16; i += 2) {+ groups.push(((net.bytes[i] << 8) | net.bytes[i + 1]).toString(16))+ }+ return `${groups.join(':')}/${net.prefix}`+ })+ .join(', ')+}++/** Is this socket peer address inside any of the trusted nets? Garbage/missing → false. */+export function isTrustedAddress(addr: string | undefined, nets: TrustedNet[]): boolean {+ if (!addr) return false+ const parsed = parseAddress(addr)+ if (!parsed) return false+ const norm = normalize(parsed)+ return nets.some((net) => matchesNet(norm, net))+}++/**+ * The one auth decision: trusted peer + configured header present with a non-empty value.+ * `headers` is Node's lowercased header map; a repeated header (array value) is ambiguous+ * and rejected — fail closed.+ */+export function proxyAuthAllowed(+ trust: TrustProxyConfig,+ headers: Record<string, string | string[] | undefined>,+ remoteAddress: string | undefined+): boolean {+ if (!isTrustedAddress(remoteAddress, trust.nets)) return false+ const value = headers[trust.header.toLowerCase()]+ return typeof value === 'string' && value.trim() !== ''+}diff --git a/src/server/ws.test.ts b/src/server/ws.test.tsindex 25fc26088..5aec6217b 100644--- a/src/server/ws.test.ts+++ b/src/server/ws.test.ts@@ -8,6 +8,7 @@ import { Auth } from './auth'import { ServerPlatform } from './platform-server'import { attachWsServer, WS_MAX_PAYLOAD } from './ws'import { SESSION_COOKIE } from './http'+import { parseTrustedNets } from './proxy-trust'import { initPlatform, resetPlatformForTests } from '../core/platform'import { presenceHub } from '../core/presence/hub'import { IPC } from '../shared/ipc'@@ -191,6 +192,50 @@ describe('ws endpoint', () => {expect(gone).toEqual([1]) // the uiId this socket attached as})+ it('proxy header trust: upgrade allowed via trusted header, still origin-checked', async () => {+ const HDR = 'Tailscale-User-Login'+ const mk = async (netsSpec: string): Promise<{ srv: http.Server; p: number }> => {+ const srv = http.createServer((_q, s2) => { s2.statusCode = 404; s2.end() })+ attachWsServer(srv, {+ platform,+ auth,+ trustProxy: { header: HDR, nets: parseTrustedNets(netsSpec) }+ })+ await new Promise<void>((r) => srv.listen(0, '127.0.0.1', r))+ return { srv, p: (srv.address() as { port: number }).port }+ }+ const dial = (p2: number, headers: Record<string, string>): Promise<WebSocket> =>+ new Promise((resolve, reject) => {+ const ws = new WebSocket(`ws://127.0.0.1:${p2}/ws`, { headers })+ sockets.push(ws)+ ws.on('open', () => resolve(ws))+ ws.on('error', reject)+ })++ const { srv, p: pTrusted } = await mk('127.0.0.0/8')+ const { srv: srvFar, p: pFar } = await mk('10.0.0.0/8')+ try {+ // No cookie, trusted peer + header → accepted (same-host Origin passes the origin check).+ const ok = await dial(pTrusted, { [HDR]: 'dev@corp', origin: `http://127.0.0.1:${pTrusted}` })+ expect(ok.readyState).toBe(WebSocket.OPEN)+ // Cross-site Origin is still rejected even when proxy-authed.+ await expect(+ dial(pTrusted, { [HDR]: 'dev@corp', origin: 'https://evil.example.com' })+ ).rejects.toThrow()+ // Header without cookie from a peer outside the trusted nets → rejected.+ await expect(dial(pFar, { [HDR]: 'dev@corp' })).rejects.toThrow()+ // Cookie still works on a trust-enabled server.+ const viaCookie = await dial(pFar, { cookie })+ expect(viaCookie.readyState).toBe(WebSocket.OPEN)+ for (const ws of sockets) ws.terminate()+ sockets = []+ await until(() => presenceHub.peers().length === 0, 'trust-test peers drain')+ } finally {+ await new Promise((r) => srv.close(r))+ await new Promise((r) => srvFar.close(r))+ }+ })+it('heartbeat: terminates a socket that never answers a ping, dropping its presence peer', async () => {// Its own listener, so the heartbeat can run at test speed (production: WS_HEARTBEAT_MS).const hbServer = http.createServer((_q, s) => { s.statusCode = 404; s.end() })diff --git a/src/server/ws.ts b/src/server/ws.tsindex e7612792b..a8fb4c70d 100644--- a/src/server/ws.ts+++ b/src/server/ws.ts@@ -17,6 +17,7 @@ import { WebSocketServer, type WebSocket } from 'ws'import type { Auth } from './auth'import type { ServerPlatform } from './platform-server'import { sessionTokenFromCookie } from './http'+import { proxyAuthAllowed, type TrustProxyConfig } from './proxy-trust'import { parseRpcMessage } from '../shared/rpc'import { presenceHub } from '../core/presence/hub'@@ -65,16 +66,26 @@ export interface WsServerOpts {onClientGone?: (uiId: number) => void/** TEST ONLY: shorten the heartbeat period. Production always uses WS_HEARTBEAT_MS. */heartbeatMs?: number+ /** Reverse-proxy SSO trust (issue #29) — same object the HTTP handler gets. */+ trustProxy?: TrustProxyConfig}/**- * Decide whether an upgrade request is allowed. Returns true only when the- * session cookie validates AND, if an Origin header is present, its host matches- * the Host header. A malformed Origin URL is treated as a rejection (never throws).+ * Decide whether an upgrade request is allowed. Returns true only when the request is+ * authenticated — a valid session cookie OR reverse-proxy header trust (issue #29) —+ * AND, if an Origin header is present, its host matches the Host header (the cross-site+ * WS hijacking check applies to both auth paths). A malformed Origin URL is treated as a+ * rejection (never throws).*/-function upgradeAllowed(req: http.IncomingMessage, auth: Auth): boolean {+function upgradeAllowed(+ req: http.IncomingMessage,+ auth: Auth,+ trustProxy?: TrustProxyConfig+): boolean {const token = sessionTokenFromCookie(req.headers['cookie'])- if (!auth.validateSession(token)) return false+ const proxyAuthed =+ trustProxy !== undefined && proxyAuthAllowed(trustProxy, req.headers, req.socket.remoteAddress)+ if (!proxyAuthed && !auth.validateSession(token)) return falseconst origin = req.headers['origin']if (typeof origin === 'string' && origin.length > 0) {@@ -91,7 +102,7 @@ function upgradeAllowed(req: http.IncomingMessage, auth: Auth): boolean {}export function attachWsServer(server: http.Server, opts: WsServerOpts): void {- const { platform, auth, onClientGone, heartbeatMs = WS_HEARTBEAT_MS } = opts+ const { platform, auth, onClientGone, heartbeatMs = WS_HEARTBEAT_MS, trustProxy } = optsconst wss = new WebSocketServer({ noServer: true, maxPayload: WS_MAX_PAYLOAD })// The one teardown for a connection that is GONE — whether by a clean 'close', or because its sink@@ -140,7 +151,7 @@ export function attachWsServer(server: http.Server, opts: WsServerOpts): void {const pathname = new URL(req.url || '/', 'http://x').pathnameif (pathname !== '/ws') return- if (!upgradeAllowed(req, auth)) {+ if (!upgradeAllowed(req, auth, trustProxy)) {// Guard the raw socket: writing to an already-dead peer emits 'error', and an// unhandled 'error' on a socket (EventEmitter) throws → crashes the process.socket.on('error', () => {})