Skip to content

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.

fix(server): harden Server Edition sign-in (security audit S1–S8)

reviewc98bfcca4686
diff --git a/CLAUDE.md b/CLAUDE.md
index 87d438f59..24ef59f59 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -206,7 +206,8 @@ The codebase is split by Electron process boundary — keep code on the correct
(`src/shared/rpc.ts`) that a browser-side `window.nodeTerminal` shim
(`src/renderer/bridge/`) consumes. Boots the same core services via
`ServerPlatform` (`src/server/platform-server.ts`). Single-user auth
- (scrypt + httpOnly cookie + Origin check). `npm run server:dev` to try;
+ (scrypt + httpOnly cookie + Origin check; the rules a refactor must keep are under
+ **Server Edition sign-in** below). `npm run server:dev` to try;
docs/SERVER.md for details. `src/server` must not import electron or
`src/main` (enforced by `src/server/no-electron.test.ts`). **Phase 3a** also
serves fs/git/commit handlers (editor/diff/source-control now work in the
@@ -250,6 +251,36 @@ PTY output flows main → renderer over per-session channels (`pty:data:<session
input flows renderer → main over `pty:write`. node-pty is kept **external** in the bundle
(`externalizeDepsPlugin` in `electron.vite.config.ts`) because it's a native module.
+### Server Edition sign-in (security audit 2026-10)
+
+The browser edition is reachable by anyone who can reach its login page, so its auth layer carries
+rules that look like over-engineering and are not. Each was a measured finding; tests pin each
+(`src/server/http-auth.test.ts`, `auth.test.ts`, `ws.test.ts`, `proxy-trust.test.ts`).
+- **A login attempt reserves its rate-limit slot BEFORE the body is read** (`Auth.beginLoginAttempt`,
+ settled exactly once as success / failure / abandoned), and the budget counts attempts in flight.
+ Checked-before-body + charged-after-verify let 60 of 60 held-body guesses through. The lock is per
+ CLIENT (5 → 1 min, doubling to 1 h) with a global ceiling (50 per 5 min, in-flight included) as the
+ backstop; one global counter let a stranger lock the owner out. The client key is
+ `client-address.ts`: the TCP peer, or — only when the peer is loopback/private/CGNAT/ULA or in the
+ trust nets — the LAST `X-Forwarded-For` entry, never an earlier one (the caller wrote those).
+- **Password verification is the async `crypto.scrypt` behind a 2-slot FIFO gate.** There is no
+ synchronous verify on purpose: a `scryptSync` per guess froze every terminal's WebSocket.
+- **Every `POST /auth/*` and the WS upgrade pass ONE same-origin rule** (`src/server/origin.ts`).
+ A new auth POST route goes under `/auth/` or it skips the check.
+- **Sign-out is server-side.** `/auth/logout` deletes the presented session, `/auth/logout-all`
+ deletes all (signed-in callers only), and `ws.ts` closes a cookie socket (4401) when its session is
+ revoked (`Auth.onSessionsRevoked`) or found expired on a heartbeat. The browser UI is
+ Settings → Sign-in, Server Edition only (`nav.ts` `browserOnly`).
+- **Header trust from loopback needs the proxy secret.** On loopback every local process is "the
+ proxy", so `resolveConfig` turns header trust OFF (and the boot says what to set) when the nets
+ cover loopback and `NODETERM_TRUST_PROXY_SECRET` is unset, and `proxyAuthDecision` refuses a
+ loopback peer without a secret whatever the config. The secret is env-only (argv is world-readable)
+ and never logged.
+- **`NODETERM_PUBLIC_ORIGIN`** forces `Secure` + HSTS; without it `Secure` follows
+ `X-Forwarded-Proto` and the first non-loopback `Host` logs a warning. Every response refuses framing
+ by HTTP header (the app CSP is a `<meta>`, where `frame-ancestors` is ignored), and the served
+ `connect-src` is `'self'` (same-origin ws/wss, CSP3; Chrome-verified).
+
## Key abstraction: TerminalTransport
This is the load-bearing design decision. The renderer depends only on the
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md
index a7c234025..dd79a1806 100644
--- a/CONTRIBUTING.md
+++ b/CONTRIBUTING.md
@@ -883,6 +883,13 @@ ANSWER) into "the ControlMaster is down" (a NON-answer, session still running).
the debt down and settle it later (`core/pending-remote-kills.ts`). Silently dropping it is the one
option that is never available.
+**Server Edition sign-in rules are load-bearing** (security audit 2026-10; see CLAUDE.md →
+Server Edition sign-in). A login attempt reserves its rate-limit slot before its body is read and
+verifies with the async scrypt behind a 2-slot gate — never `scryptSync`, which stalls every
+terminal. A new auth POST lives under `/auth/` so the shared same-origin check (`src/server/origin.ts`)
+covers it. Header trust from a loopback peer needs `NODETERM_TRUST_PROXY_SECRET`, which is read from
+the environment only and never logged.
+
**A Server Edition agent owns only nodes it freshly opened in this server run.** The
creator ledger is process-local and must never be rebuilt from `.nodeterm/project.json`, titles,
hook history, or a surviving tmux name: all are writable or stale. A restart therefore clears
diff --git a/docs/SERVER.md b/docs/SERVER.md
index d295e3c48..ac53842c3 100644
--- a/docs/SERVER.md
+++ b/docs/SERVER.md
@@ -46,6 +46,9 @@ NODETERM_SERVER_PASSWORD='choose-a-strong-one' npm run server:start
When `NODETERM_SERVER_PASSWORD` is set **and** no password is configured yet, the
server writes the scrypt hash on boot and skips the setup URL entirely — go straight
to `/login`. It is ignored once a password already exists (it never overwrites).
+Use at least 8 characters, the same rule the setup form enforces. A shorter value is
+still used (an existing deployment must keep booting), but the boot prints a loud
+`✖ NODETERM_SERVER_PASSWORD is shorter than 8 characters` line.
### Manual build + run
@@ -69,6 +72,8 @@ Precedence: **CLI flag > environment variable > default.**
| — | `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. |
+| — | `NODETERM_TRUST_PROXY_SECRET` | — | Shared secret your proxy sends as `X-Nodeterm-Proxy-Secret` (at least 32 printable characters). **Required** when the trusted nets include loopback. Environment only: a command-line flag is refused, because argv is readable by every local user. |
+| `--public-origin <url>` | `NODETERM_PUBLIC_ORIGIN` | — | The https origin you open in the browser, e.g. `https://term.example.com`. Forces the `Secure` cookie flag, sends HSTS, and lets that `Origin` pass the same-origin checks when the proxy rewrites `Host`. See [TLS](#tls-reverse-proxy). |
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
@@ -246,18 +251,53 @@ Single-user auth. There is one password; sessions are per-browser.
- **Password hashing:** scrypt (`N=16384, r=8, p=1`, 32-byte key, per-password random
salt), stored as `auth.json` (mode `0600`) in the data dir. Login comparison is
constant-time (`crypto.timingSafeEqual`). The app never stores the plaintext.
+- **Password verification** runs the asynchronous scrypt, at most two at a time (a FIFO
+ gate), so a burst of login attempts never stalls the event loop that carries every
+ terminal's WebSocket.
- **Session cookie:** on successful login the server sets `nt_session=<random>` with
- `HttpOnly; SameSite=Strict; Path=/` (and `Secure` when served over HTTPS). Sessions
+ `HttpOnly; SameSite=Strict; Path=/`, plus `Secure` when `NODETERM_PUBLIC_ORIGIN` is set
+ or the proxy sends `X-Forwarded-Proto: https` (see [TLS](#tls-reverse-proxy)). Sessions
are persisted (`sessions.json`, mode `0600`) with a 30-day TTL and swept lazily.
- `revokeAll()` exists to drop every session but is only wired programmatically in
- Phase 2 (no logout-everywhere UI yet; `/auth/logout` clears the current cookie).
-- **Origin check on WS upgrade:** the WebSocket endpoint requires a valid session
- cookie **and**, when the browser sends an `Origin` header, that its host matches the
- request `Host`. A malformed Origin is rejected (never throws). This blocks
- cross-site WebSocket hijacking. (Non-browser clients without an Origin still must
- present a valid cookie.)
-- **Login rate limit / lockout:** 5 failed password attempts trip a 60-second lockout
- (further attempts get `429 too_many_attempts`); a success resets the counter.
+- **Signing out:** `POST /auth/logout` deletes the presented session on the server, so a
+ copy of the cookie stops working too (it used to clear only the browser's cookie and
+ leave the session valid for 30 days). `POST /auth/logout-all` ("Sign out everywhere")
+ deletes every session; it needs a signed-in caller. Both are in the browser UI under
+ **Settings → Application → Sign-in** (Server Edition only). An open WebSocket remembers
+ the session it was opened with and is closed (code `4401`) the moment that session is
+ signed out, and on the next heartbeat (≤ 30 s) after it expires. A socket opened through
+ proxy header trust is bound to the proxy's identity, not to a cookie, and stays open.
+- **Same-origin checks:** the WebSocket upgrade and every `POST /auth/*` (login, logout,
+ logout-all, setup) refuse a request whose `Origin` is not this server: its host must
+ equal the request `Host`, or the `Origin` must equal `NODETERM_PUBLIC_ORIGIN`.
+ `Origin: null` and a malformed Origin are refused. A request with no `Origin` is a
+ non-browser client (browsers always send one on a POST and on a WebSocket handshake)
+ and is allowed — unless it says `Sec-Fetch-Site: cross-site` or `same-site`. A refused
+ auth POST is answered `403 cross_origin` and is not charged to the lockout. So a page
+ the owner visits can neither post the login form (to lock them out) nor sign them out.
+- **Login rate limit / lockout**, per client:
+ - A login attempt reserves a slot **before** its body is read, and the budget counts
+ attempts in flight as well as failures. (It used to be checked before the body and
+ charged after verification, so requests whose bodies were held back all passed it: 60
+ of 60 were verified in the audit's repro.) A body that does not arrive within 10 s is
+ abandoned and its slot released without a charge.
+ - 5 failures (or attempts still in flight) lock **that client** for 1 minute; each
+ further lock doubles, up to 1 hour. A success resets the client; a client quiet for an
+ hour after its last lock is forgotten. Refusals are `429 too_many_attempts` with a
+ `Retry-After` header (a browser gets the sign-in page with the wait in minutes).
+ - A **global ceiling** of 50 failures plus attempts in flight per 5-minute sliding window,
+ across all clients, is the backstop against a guesser with many addresses. Its cost:
+ under a sustained distributed attack it refuses the owner too, until the window drains.
+ - **Who is a client:** the TCP peer, except when the peer is a forwarder — loopback, a
+ private, CGNAT, link-local or ULA address, or inside `NODETERM_TRUST_PROXY_NETS` — in which
+ case it is the **last** `X-Forwarded-For` entry (the one your proxy appended; the entries
+ to its left were written by whoever called the proxy). IPv6 clients are grouped by their
+ /64. Consequences: a process that reaches the server from a forwarder address (a local
+ user, another container on the network) can pick the bucket it is charged to — the
+ global ceiling still applies to it; and behind two proxies (a CDN in front of your
+ proxy) clients are grouped by the CDN's edge address.
+- **No framing:** every response carries `X-Frame-Options: DENY` and
+ `Content-Security-Policy: frame-ancestors 'none'` (the app's own CSP is a `<meta>` tag, where
+ `frame-ancestors` is ignored), plus `X-Content-Type-Options: nosniff`.
- **Auth gate:** every route except the login/setup pages and their POST handlers
requires a valid session — HTML navigations redirect to `/login`, API/WS get `401`.
@@ -278,35 +318,91 @@ NODETERM_TRUST_PROXY_HEADER=Tailscale-User-Login node out/server/main.cjs
NODETERM_TRUST_PROXY_HEADER=X-Forwarded-User node out/server/main.cjs
```
-A request is trusted only when **both** hold:
+A request is trusted only when **all** of these 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**.
+ `NODETERM_TRUST_PROXY_NETS=10.0.0.0/8`;
+2. it carries the configured header with a **non-empty value**;
+3. when `NODETERM_TRUST_PROXY_SECRET` is set, it carries
+ `X-Nodeterm-Proxy-Secret` equal to it (compared in constant time; never logged).
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.
+boundary is the trust statement, and on **loopback that boundary holds every local
+process**: every Unix account on the host, every container on the host network, every
+sandboxed agent is "from the trusted networks". So:
+
+- **Loopback nets need the secret.** If the trusted nets include loopback (127.0.0.0/8 or
+ `::1`, including the default and anything wider such as `0.0.0.0/0`) and no secret is set,
+ header trust stays **OFF**: the server still boots with password sign-in, and the boot
+ prints a `✖ Proxy header trust is OFF` error naming what to set. A loopback peer is never
+ header-trusted without the secret, whatever the configuration.
+- **Other nets work without it, but get a warning:** every host that can reach the server
+ from those networks — other containers on the same network, the Docker host's bridge
+ address — counts as your proxy. Set the secret there too.
+
+To turn it on, generate a secret (`openssl rand -hex 32`), give it to the server through the
+environment (a `--trust-proxy-secret` flag is refused: argv is readable by every local user),
+and have the proxy send it on **every** request, WebSocket upgrades included:
+
+```nginx
+# nginx
+proxy_set_header X-Nodeterm-Proxy-Secret "<secret>";
+```
+
+```caddy
+# Caddy (inside reverse_proxy)
+header_up X-Nodeterm-Proxy-Secret "<secret>"
+```
+
+```yaml
+# Traefik (a headers middleware attached to the router)
+http:
+ middlewares:
+ nodeterm-secret:
+ headers:
+ customRequestHeaders:
+ X-Nodeterm-Proxy-Secret: "<secret>"
+```
+
+The proxy must also **strip/overwrite** the identity header on incoming client requests
+(Cloudflare Access, Tailscale and oauth2-proxy all do). A request that comes from a trusted
+address with the identity header but without the right secret is treated as signed out,
+and the server logs (at most once a minute, without any header value) that the secret was
+missing. A typo'd nets entry, a secret shorter than 32 characters, a secret with spaces, or
+a secret without a header all fail the boot rather than silently changing who is trusted;
+setting nets without a header is likewise refused.
+
+> **Upgrading a deployment that already uses header trust on loopback** (the default nets):
+> after this change header trust is off until you set `NODETERM_TRUST_PROXY_SECRET` and the
+> proxy header. Users then see the password page; sign in with the password, or set the
+> secret.
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.
+prints a `⚠️ Proxy header trust ENABLED` line naming the header, the networks and
+whether a secret is required — verify it matches what you meant to trust.
### TLS (reverse proxy)
The server speaks **plain HTTP** by design. For anything beyond `localhost`, run it
bound to loopback and put a TLS-terminating reverse proxy (nginx, Caddy, Cloudflare
-Tunnel, a VPN, etc.) in front. The `Secure` cookie flag is set automatically when the
-proxy forwards HTTPS (detected via `X-Forwarded-Proto` / the request being TLS).
-`--insecure-http` only exists as an explicit, eyes-open escape hatch for trusted
-private networks — prefer the proxy.
+Tunnel, a VPN, etc.) in front, and tell the server the address you open in the browser:
+
+```bash
+NODETERM_PUBLIC_ORIGIN=https://term.example.com node out/server/main.cjs
+```
+
+With it, the session cookie is **always** `Secure` and every response carries
+`Strict-Transport-Security: max-age=31536000`; an `Origin` equal to it also passes the
+same-origin checks when the proxy rewrites `Host`. It must be an `https` origin with no path
+(anything else fails the boot). Without it the server behaves as before — `Secure` is set only
+when the proxy sends `X-Forwarded-Proto: https`, and no HSTS is sent — and it logs one warning
+the first time a request arrives for a non-loopback `Host`, because a proxy that does not send
+that header silently loses `Secure`. `--insecure-http` only exists as an explicit, eyes-open
+escape hatch for trusted private networks — prefer the proxy.
### Docker / Dokploy
@@ -323,9 +419,10 @@ docker run -d -p 8443:8443 \
```
On Dokploy specifically: create an app from this repo (Dockerfile build), attach a volume at
-`/data`, set `NODETERM_SERVER_PASSWORD`, and point a domain at container port `8443` — Traefik
-terminates TLS and forwards `X-Forwarded-Proto`, so the session cookie gets its `Secure` flag
-and the clipboard runs in a secure context.
+`/data`, set `NODETERM_SERVER_PASSWORD` and `NODETERM_PUBLIC_ORIGIN=https://<your domain>`, and
+point a domain at container port `8443` — Traefik terminates TLS (and forwards
+`X-Forwarded-Proto`), so the session cookie gets its `Secure` flag and the clipboard runs in a
+secure context.
Things the image decides for you (see the Dockerfile comments for the full why):
@@ -349,9 +446,16 @@ under the container user's home, so consider a volume there too if you rely on t
The inline login/setup pages carry a strict CSP. The built `index.html` ships with a
`default-src 'self'` marker that the server **rewrites** at serve time to
-`default-src 'self'; connect-src 'self' ws: wss:;` so the browser can open the
-WebSocket. If that marker is ever missing, the server logs a loud warning (the WS
-would otherwise be blocked) — rebuild the renderer or update the rewrite.
+`default-src 'self'; connect-src 'self';` so the browser can open the WebSocket: CSP3
+matches a same-origin `ws:`/`wss:` URL against `'self'`, and the bridge only ever opens
+`/ws` on the page's own host. (It used to be `connect-src 'self' ws: wss:`, i.e. a socket to
+any host — harmless without an XSS, an exfiltration channel with one.) Verified with headless
+Chrome 153 against `http`/`ws` and `https`/`wss`: the same-origin socket opens, a
+cross-origin one is blocked. Firefox and Safari follow the same CSP3 rule but were not run;
+a browser too old to apply it would block the WebSocket and show the reconnect overlay. If
+that marker is ever missing, the server logs a loud warning (the WS would otherwise be
+blocked) — rebuild the renderer or update the rewrite. Framing is refused by HTTP header on
+every response (see [Security model](#security-model)).
### Dictation
diff --git a/src/renderer/components/settings/SettingsIcons.tsx b/src/renderer/components/settings/SettingsIcons.tsx
index 0bef94828..25f150d02 100644
--- a/src/renderer/components/settings/SettingsIcons.tsx
+++ b/src/renderer/components/settings/SettingsIcons.tsx
@@ -148,6 +148,8 @@ const PATHS: Record<StaticSettingsSectionId, React.JSX.Element> = {
),
updates: <path d="M8 2.6v7M5 6.6 8 9.6l3-3M3.6 12.6h8.8" />,
privacy: <path d="M8 2.4 12.4 4.2V8c0 3-2 4.8-4.4 5.6C5.6 12.8 3.6 11 3.6 8V4.2Z" />,
+ // A door with an arrow leaving it (sign out).
+ 'sign-in': <path d="M9.5 3H4a1 1 0 0 0-1 1v8a1 1 0 0 0 1 1h5.5M7.5 8h6M11.5 6l2 2-2 2" />,
// A tiny bug (the debug section).
debug: (
<>
diff --git a/src/renderer/components/settings/SettingsPage.tsx b/src/renderer/components/settings/SettingsPage.tsx
index fc6b7cf08..623813106 100644
--- a/src/renderer/components/settings/SettingsPage.tsx
+++ b/src/renderer/components/settings/SettingsPage.tsx
@@ -32,6 +32,8 @@ import { LiveLinksSection } from './sections/LiveLinksSection'
import { SshSection } from './sections/SshSection'
import { UpdatesSection } from './sections/UpdatesSection'
import { PrivacySection } from './sections/PrivacySection'
+import { SignInSection } from './sections/SignInSection'
+import { isBrowserRuntime } from '@renderer/bridge/runtime'
import { DebugSection } from './sections/DebugSection'
import { GitHubIssuesSection } from './sections/GitHubIssuesSection'
import { ModelGatewaySection } from './sections/ModelGatewaySection'
@@ -184,6 +186,11 @@ export function SettingsPage({
<SettingsSectionBoundary title="Privacy" visible={active === 'privacy'}>
<PrivacySection isActive={active === 'privacy'} />
</SettingsSectionBoundary>
+ {isBrowserRuntime() && (
+ <SettingsSectionBoundary title="Sign-in" visible={active === 'sign-in'}>
+ <SignInSection isActive={active === 'sign-in'} />
+ </SettingsSectionBoundary>
+ )}
<SettingsSectionBoundary title="Debug" visible={active === 'debug'}>
<DebugSection isActive={active === 'debug'} />
</SettingsSectionBoundary>
diff --git a/src/renderer/components/settings/SettingsSidebar.tsx b/src/renderer/components/settings/SettingsSidebar.tsx
index 42cc9aa4e..cc82edea0 100644
--- a/src/renderer/components/settings/SettingsSidebar.tsx
+++ b/src/renderer/components/settings/SettingsSidebar.tsx
@@ -5,6 +5,7 @@ import { visibleSettingsGroups, type SettingsGroup, type SettingsSectionId } fro
import { matchesQuery } from './search'
import { SectionIcon } from './SettingsIcons'
import { ProjectGlyph } from '../ProjectGlyph'
+import { isBrowserRuntime } from '@renderer/bridge/runtime'
const isMac = /Mac/i.test(navigator.platform || navigator.userAgent)
@@ -28,7 +29,7 @@ export function SettingsSidebar({
}): React.JSX.Element {
const hasQuery = query.trim() !== ''
const GROUPS = useMemo(
- () => [...visibleSettingsGroups(isMac), ...(extraGroups ?? [])],
+ () => [...visibleSettingsGroups(isMac, isBrowserRuntime()), ...(extraGroups ?? [])],
[extraGroups]
)
return (
diff --git a/src/renderer/components/settings/nav.test.ts b/src/renderer/components/settings/nav.test.ts
index fa58bcfc1..a6b0ae728 100644
--- a/src/renderer/components/settings/nav.test.ts
+++ b/src/renderer/components/settings/nav.test.ts
@@ -2,10 +2,10 @@ import { describe, it, expect } from 'vitest'
import { SETTINGS_GROUPS, allSectionIds, FIRST_SECTION_ID, visibleSettingsGroups, projectsSettingsGroup } from './nav'
describe('SETTINGS_GROUPS', () => {
- it('lists exactly 26 sections with no duplicates', () => {
+ it('lists exactly 27 sections with no duplicates', () => {
const ids = allSectionIds()
- expect(ids).toHaveLength(26)
- expect(new Set(ids).size).toBe(26)
+ expect(ids).toHaveLength(27)
+ expect(new Set(ids).size).toBe(27)
})
it('starts at a section that exists in the groups', () => {
expect(allSectionIds()).toContain(FIRST_SECTION_ID)
@@ -13,11 +13,19 @@ describe('SETTINGS_GROUPS', () => {
it('hides mac-only sections off macOS, keeps them on', () => {
const off = visibleSettingsGroups(false).flatMap((g) => g.sections.map((s) => s.id))
expect(off).not.toContain('notch')
- expect(off).toHaveLength(25)
- expect(visibleSettingsGroups(true)).toEqual(SETTINGS_GROUPS)
+ expect(off).toHaveLength(25) // notch and the browser-only sign-in are both out
+ expect(visibleSettingsGroups(true, true)).toEqual(SETTINGS_GROUPS)
// No group is left empty by the filter.
expect(visibleSettingsGroups(false).every((g) => g.sections.length > 0)).toBe(true)
})
+ it('shows the Sign-in section only in a browser tab (the Server Edition)', () => {
+ const ids = (isMac: boolean, isBrowser: boolean): string[] =>
+ visibleSettingsGroups(isMac, isBrowser).flatMap((g) => g.sections.map((s) => s.id))
+ expect(ids(true, false)).not.toContain('sign-in')
+ expect(ids(false, false)).not.toContain('sign-in')
+ expect(ids(false, true)).toContain('sign-in')
+ expect(ids(true, true)).toContain('sign-in')
+ })
})
describe('Live links section', () => {
diff --git a/src/renderer/components/settings/nav.ts b/src/renderer/components/settings/nav.ts
index b6db6b458..5eb6ac2f9 100644
--- a/src/renderer/components/settings/nav.ts
+++ b/src/renderer/components/settings/nav.ts
@@ -27,6 +27,7 @@ export type SettingsSectionId =
| 'ssh'
| 'updates'
| 'privacy'
+ | 'sign-in'
| 'debug'
| `project-${string}`
@@ -42,6 +43,8 @@ export interface SettingsSectionRef {
title: string
/** Only meaningful on macOS (the notch capsule) — hidden elsewhere by `visibleSettingsGroups`. */
macOnly?: boolean
+ /** Only meaningful in a browser tab (the Server Edition's sign-in session) — hidden under Electron. */
+ browserOnly?: boolean
/** Project-section rows only (`project-${string}` ids): the project's own color/icon, so the
* sidebar can render its `ProjectGlyph` beside the title instead of the generic folder glyph
* every project section used to share. Absent on every static section. */
@@ -111,6 +114,7 @@ export const SETTINGS_GROUPS: SettingsGroup[] = [
{ id: 'license', title: 'License' },
{ id: 'updates', title: 'Updates' },
{ id: 'privacy', title: 'Privacy' },
+ { id: 'sign-in', title: 'Sign-in', browserOnly: true },
{ id: 'debug', title: 'Debug' }
]
}
@@ -124,14 +128,14 @@ export function allSectionIds(): SettingsSectionId[] {
/**
* The groups as the sidebar should render them for this platform: a mac-only section is dropped
- * entirely off macOS (an empty group would be dropped too, though none exists today). Pure — the
- * caller passes the platform so this stays testable.
+ * entirely off macOS, a browser-only one under Electron (an empty group would be dropped too,
+ * though none exists today). Pure — the caller passes the platform so this stays testable.
*/
-export function visibleSettingsGroups(isMac: boolean): SettingsGroup[] {
- if (isMac) return SETTINGS_GROUPS
- return SETTINGS_GROUPS.map((g) => ({ ...g, sections: g.sections.filter((s) => !s.macOnly) })).filter(
- (g) => g.sections.length > 0
- )
+export function visibleSettingsGroups(isMac: boolean, isBrowser = false): SettingsGroup[] {
+ return SETTINGS_GROUPS.map((g) => ({
+ ...g,
+ sections: g.sections.filter((s) => (isMac || !s.macOnly) && (isBrowser || !s.browserOnly))
+ })).filter((g) => g.sections.length > 0)
}
/**
diff --git a/src/renderer/components/settings/sections/SignInSection.test.tsx b/src/renderer/components/settings/sections/SignInSection.test.tsx
new file mode 100644
index 000000000..75096ddfe
--- /dev/null
+++ b/src/renderer/components/settings/sections/SignInSection.test.tsx
@@ -0,0 +1,60 @@
+// @vitest-environment jsdom
+//
+// Settings → Sign-in (Server Edition only, security audit 2026-10 S3): "Sign out" ends this
+// browser's session on the server; "Sign out everywhere" is confirmed, then ends every session.
+import { act } from 'react'
+import { createRoot, type Root } from 'react-dom/client'
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+import { resetDialogStack } from '../../dialog-stack'
+import { SignInSection } from './SignInSection'
+
+;(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true
+
+let host: HTMLDivElement
+let root: Root
+const fetchMock = vi.fn(async () => ({ type: 'opaqueredirect', ok: false, status: 0 }) as Response)
+const assign = vi.fn()
+
+beforeEach(() => {
+ resetDialogStack()
+ fetchMock.mockClear()
+ assign.mockClear()
+ vi.stubGlobal('fetch', fetchMock)
+ Object.defineProperty(window, 'location', { value: { assign }, configurable: true, writable: true })
+ host = document.createElement('div')
+ document.body.appendChild(host)
+ root = createRoot(host)
+ act(() => root.render(<SignInSection isActive />))
+})
+afterEach(() => {
+ act(() => root.unmount())
+ host.remove()
+ vi.unstubAllGlobals()
+})
+
+const button = (label: string): HTMLButtonElement => {
+ const b = [...document.querySelectorAll('button')].find((x) => x.textContent === label)
+ if (!b) throw new Error(`no button "${label}"`)
+ return b as HTMLButtonElement
+}
+
+describe('SignInSection', () => {
+ it('Sign out posts /auth/logout and goes to the sign-in page', async () => {
+ await act(async () => button('Sign out').click())
+ expect(fetchMock).toHaveBeenCalledWith('/auth/logout', expect.objectContaining({ method: 'POST' }))
+ expect(assign).toHaveBeenCalledWith('/login')
+ })
+
+ it('Sign out everywhere asks first; cancel sends nothing, confirm posts /auth/logout-all', async () => {
+ await act(async () => button('Sign out everywhere').click())
+ expect(fetchMock).not.toHaveBeenCalled()
+ expect(document.body.textContent).toMatch(/Sign out every browser\?/)
+ await act(async () => button('Cancel').click())
+ expect(fetchMock).not.toHaveBeenCalled()
+ await act(async () => button('Sign out everywhere').click())
+ const confirm = [...document.querySelectorAll('button')].filter((x) => x.textContent === 'Sign out everywhere').pop()!
+ await act(async () => confirm.click())
+ expect(fetchMock).toHaveBeenCalledWith('/auth/logout-all', expect.objectContaining({ method: 'POST' }))
+ expect(assign).toHaveBeenCalledWith('/login')
+ })
+})
diff --git a/src/renderer/components/settings/sections/SignInSection.tsx b/src/renderer/components/settings/sections/SignInSection.tsx
new file mode 100644
index 000000000..870b89fd0
--- /dev/null
+++ b/src/renderer/components/settings/sections/SignInSection.tsx
@@ -0,0 +1,82 @@
+import { useState } from 'react'
+import { SettingsSection } from '../SettingsSection'
+import { SearchableRow } from '../SearchableRow'
+import { FieldRow } from '../FieldRow'
+import { Button } from '@renderer/ui/Button'
+import { ConfirmDialog } from '../../ConfirmDialog'
+import { signOutBrowser, type SignOutScope } from '../../../lib/browserSignOut'
+
+// Server Edition only (the section is not listed under Electron — see nav.ts `browserOnly`).
+const ROWS = {
+ signOut: {
+ title: 'Sign out of this browser',
+ keywords: ['sign out', 'log out', 'logout', 'session', 'password', 'browser']
+ },
+ signOutEverywhere: {
+ title: 'Sign out everywhere',
+ keywords: ['sign out', 'log out', 'logout', 'everywhere', 'all', 'sessions', 'revoke', 'browser', 'stolen']
+ }
+}
+const ENTRIES = Object.values(ROWS)
+
+export function SignInSection({ isActive }: { isActive: boolean }): React.JSX.Element {
+ const [busy, setBusy] = useState<SignOutScope | null>(null)
+ const [error, setError] = useState<string | null>(null)
+ const [confirming, setConfirming] = useState(false)
+
+ const run = async (scope: SignOutScope): Promise<void> => {
+ setBusy(scope)
+ setError(null)
+ const r = await signOutBrowser(scope, {
+ fetch: (...a) => window.fetch(...a),
+ assign: (url) => window.location.assign(url)
+ })
+ if (!r.ok) {
+ setError(r.error)
+ setBusy(null)
+ }
+ }
+
+ return (
+ <SettingsSection id="sign-in" title="Sign-in" isActive={isActive} searchEntries={ENTRIES}>
+ <SearchableRow {...ROWS.signOut}>
+ <FieldRow
+ label="Sign out of this browser"
+ description="Ends this browser's session on the server, so a copy of its cookie stops working too. If you signed in through your proxy's single sign-on, sign out there as well."
+ control={
+ <Button onClick={() => void run('this')} disabled={busy !== null}>
+ {busy === 'this' ? 'Signing out…' : 'Sign out'}
+ </Button>
+ }
+ />
+ </SearchableRow>
+ <SearchableRow {...ROWS.signOutEverywhere}>
+ <FieldRow
+ label="Sign out everywhere"
+ description="Ends every browser session on this server, this one included. Every open tab is disconnected and has to sign in again with the password. Use it if a device was lost or a session may have been copied."
+ control={
+ <Button onClick={() => setConfirming(true)} disabled={busy !== null}>
+ {busy === 'everywhere' ? 'Signing out…' : 'Sign out everywhere'}
+ </Button>
+ }
+ />
+ </SearchableRow>
+ {error ? (
+ <p role="alert" className="mt-2 text-[13px] text-danger">
+ {error}
+ </p>
+ ) : null}
+ {confirming ? (
+ <ConfirmDialog
+ message="Sign out every browser? Every open tab on this server is disconnected and has to sign in again with the password. Running terminals keep running."
+ confirmLabel="Sign out everywhere"
+ onConfirm={() => {
+ setConfirming(false)
+ void run('everywhere')
+ }}
+ onCancel={() => setConfirming(false)}
+ />
+ ) : null}
+ </SettingsSection>
+ )
+}
diff --git a/src/renderer/lib/browserSignOut.test.ts b/src/renderer/lib/browserSignOut.test.ts
new file mode 100644
index 000000000..571e4e9fb
--- /dev/null
+++ b/src/renderer/lib/browserSignOut.test.ts
@@ -0,0 +1,42 @@
+import { describe, it, expect, vi } from 'vitest'
+import { signOutBrowser, SIGN_OUT_PATH } from './browserSignOut'
+
+const res = (init: Partial<Response>): Response => ({ ok: false, status: 0, type: 'basic', ...init }) as Response
+
+describe('signOutBrowser', () => {
+ it('posts to the right route, same-origin, without following the redirect, then goes to /login', async () => {
+ for (const scope of ['this', 'everywhere'] as const) {
+ const fetch = vi.fn(async () => res({ type: 'opaqueredirect' }))
+ const assign = vi.fn()
+ expect(await signOutBrowser(scope, { fetch: fetch as unknown as typeof globalThis.fetch, assign })).toEqual({ ok: true })
+ expect(fetch).toHaveBeenCalledWith(SIGN_OUT_PATH[scope], {
+ method: 'POST',
+ credentials: 'same-origin',
+ redirect: 'manual'
+ })
+ expect(assign).toHaveBeenCalledWith('/login')
+ }
+ expect(SIGN_OUT_PATH).toEqual({ this: '/auth/logout', everywhere: '/auth/logout-all' })
+ })
+
+ it('a session already gone (401) still lands on the sign-in page', async () => {
+ const assign = vi.fn()
+ const r = await signOutBrowser('everywhere', { fetch: (async () => res({ status: 401 })) as unknown as typeof fetch, assign })
+ expect(r).toEqual({ ok: true })
+ expect(assign).toHaveBeenCalledWith('/login')
+ })
+
+ it('a refusal or a network failure stays on the page and says nothing was signed out', async () => {
+ const assign = vi.fn()
+ const refused = await signOutBrowser('everywhere', { fetch: (async () => res({ status: 403 })) as unknown as typeof fetch, assign })
+ expect(refused).toEqual({ ok: false, error: expect.stringMatching(/HTTP 403.*Nothing was signed out/) })
+ const down = await signOutBrowser('this', {
+ fetch: (async () => {
+ throw new TypeError('network')
+ }) as unknown as typeof fetch,
+ assign
+ })
+ expect(down).toEqual({ ok: false, error: expect.stringMatching(/Nothing was signed out/) })
+ expect(assign).not.toHaveBeenCalled()
+ })
+})
diff --git a/src/renderer/lib/browserSignOut.ts b/src/renderer/lib/browserSignOut.ts
new file mode 100644
index 000000000..70c4e5935
--- /dev/null
+++ b/src/renderer/lib/browserSignOut.ts
@@ -0,0 +1,46 @@
+// Sign out of the Server Edition from the browser (security audit 2026-10, S3).
+//
+// Server Edition only: the page is served by the server it signs out of, so this is a plain POST
+// to that server's own /auth routes — no `window.nodeTerminal` member, nothing for Electron or a
+// relay tab (neither has a browser session to end). The POST carries the page's Origin, which the
+// server's same-origin check requires (src/server/origin.ts).
+//
+// - `this`: /auth/logout — deletes THIS browser's session on the server.
+// - `everywhere`: /auth/logout-all — deletes every session; every other open tab's connection is
+// closed by the server and lands on the sign-in page.
+
+export type SignOutScope = 'this' | 'everywhere'
+
+export interface SignOutDeps {
+ fetch: typeof fetch
+ /** Navigate the page (window.location.assign). */
+ assign: (url: string) => void
+}
+
+export type SignOutResult = { ok: true } | { ok: false; error: string }
+
+export const SIGN_OUT_PATH: Record<SignOutScope, string> = {
+ this: '/auth/logout',
+ everywhere: '/auth/logout-all'
+}
+
+export async function signOutBrowser(scope: SignOutScope, deps: SignOutDeps): Promise<SignOutResult> {
+ let res: Response
+ try {
+ // `manual`: the server answers 303 → /login, and following it inside fetch would only fetch
+ // the login page into nothing. An opaque redirect IS the success answer.
+ res = await deps.fetch(SIGN_OUT_PATH[scope], { method: 'POST', credentials: 'same-origin', redirect: 'manual' })
+ } catch {
+ return { ok: false, error: 'Could not reach the server. Nothing was signed out.' }
+ }
+ if (res.type === 'opaqueredirect' || res.ok || (res.status >= 300 && res.status < 400)) {
+ deps.assign('/login')
+ return { ok: true }
+ }
+ if (res.status === 401) {
+ // The session was already gone (signed out elsewhere, or expired): the sign-in page is next anyway.
+ deps.assign('/login')
+ return { ok: true }
+ }
+ return { ok: false, error: `The server refused to sign out (HTTP ${res.status}). Nothing was signed out.` }
+}
diff --git a/src/server/auth-boot-messages.test.ts b/src/server/auth-boot-messages.test.ts
new file mode 100644
index 000000000..bb2d75b44
--- /dev/null
+++ b/src/server/auth-boot-messages.test.ts
@@ -0,0 +1,45 @@
+import { describe, it, expect } from 'vitest'
+import { authBootMessages } from './auth-boot-messages'
+import { resolveConfig } from './config'
+import { parseTrustedNets } from './proxy-trust'
+
+describe('authBootMessages', () => {
+ it('says nothing for a plain password deployment', () => {
+ expect(authBootMessages(resolveConfig({}, []))).toEqual({ errors: [], notices: [] })
+ expect(authBootMessages(resolveConfig({ NODETERM_SERVER_PASSWORD: 'long-enough' }, []))).toEqual({
+ errors: [],
+ notices: []
+ })
+ })
+
+ it('S2: refused header trust is an ERROR line naming the env var, the header and the proxy setting', () => {
+ const m = authBootMessages(resolveConfig({ NODETERM_TRUST_PROXY_HEADER: 'X-Forwarded-User' }, []))
+ expect(m.errors).toHaveLength(1)
+ expect(m.errors[0]).toMatch(/Proxy header trust is OFF/)
+ expect(m.errors[0]).toMatch(/NODETERM_TRUST_PROXY_SECRET=<secret>/)
+ expect(m.errors[0]).toMatch(/X-Nodeterm-Proxy-Secret: <secret>/)
+ expect(m.errors[0]).toMatch(/openssl rand -hex 32/)
+ expect(m.notices).toEqual([])
+ })
+
+ it('header trust with a secret is announced; without one (non-loopback nets) it warns about every host on the nets', () => {
+ const secret = 'z'.repeat(40)
+ const withSecret = authBootMessages({
+ trustProxy: { header: 'X-U', nets: parseTrustedNets('127.0.0.1'), secret }
+ })
+ expect(withSecret.notices[0]).toMatch(/ENABLED/)
+ expect(withSecret.notices[0]).not.toContain(secret)
+ const bare = authBootMessages({ trustProxy: { header: 'X-U', nets: parseTrustedNets('10.0.0.0/8') } })
+ expect(bare.notices[0]).toMatch(/without a secret/)
+ expect(bare.notices[0]).toMatch(/NODETERM_TRUST_PROXY_SECRET/)
+ })
+
+ it('S8: a seeded password under 8 characters is an error line, never a refusal, never echoed', () => {
+ const config = resolveConfig({ NODETERM_SERVER_PASSWORD: 'hunter2' }, [])
+ expect(config.passwordSeed).toBe('hunter2') // still used
+ const m = authBootMessages(config)
+ expect(m.errors).toHaveLength(1)
+ expect(m.errors[0]).toMatch(/shorter than 8/)
+ expect(m.errors[0]).not.toContain('hunter2')
+ })
+})
diff --git a/src/server/auth-boot-messages.ts b/src/server/auth-boot-messages.ts
new file mode 100644
index 000000000..69ca874be
--- /dev/null
+++ b/src/server/auth-boot-messages.ts
@@ -0,0 +1,56 @@
+// What the boot prints about the sign-in configuration. Pure (config in, lines out) so the exact
+// wording — which is the operator's only chance to notice a misconfiguration — is pinned by tests.
+import type { ServerConfig } from './config'
+import { describeTrustedNets } from './proxy-trust'
+import { MIN_PASSWORD_LENGTH, passwordTooShort } from './auth'
+
+export interface AuthBootMessages {
+ /** console.error — something the operator asked for is OFF, or unsafe. */
+ errors: string[]
+ /** console.log — loud, but working as configured. */
+ notices: string[]
+}
+
+export function authBootMessages(
+ config: Pick<ServerConfig, 'trustProxy' | 'trustProxyRefused' | 'passwordSeed'>
+): AuthBootMessages {
+ const errors: string[] = []
+ const notices: string[] = []
+
+ // S2: header trust on loopback nets with no secret was refused — say exactly what to set.
+ if (config.trustProxyRefused) errors.push(`✖ ${config.trustProxyRefused}`)
+
+ if (config.trustProxy) {
+ const nets = describeTrustedNets(config.trustProxy.nets)
+ const header = config.trustProxy.header
+ if (config.trustProxy.secret) {
+ notices.push(
+ `⚠️ Proxy header trust ENABLED: requests from [${nets}] carrying a non-empty "${header}" header ` +
+ `AND the X-Nodeterm-Proxy-Secret header are authenticated WITHOUT a password. Ensure your proxy ` +
+ `strips/overwrites "${header}" on client requests and sends the secret on every request.`
+ )
+ } else {
+ // Non-loopback nets without a secret keep working (an existing deployment must not break), but
+ // every host that can reach this server from those nets is "the proxy" — other containers on
+ // the same network, the Docker host's bridge address.
+ notices.push(
+ `⚠️ Proxy header trust ENABLED without a secret: requests from [${nets}] carrying a non-empty ` +
+ `"${header}" header are authenticated WITHOUT a password. EVERY host that can reach this server ` +
+ `from those networks counts as your proxy — other containers on the same network, the Docker ` +
+ `host. Set NODETERM_TRUST_PROXY_SECRET and have the proxy send it as X-Nodeterm-Proxy-Secret.`
+ )
+ }
+ }
+
+ // S8: the setup form refuses a password shorter than 8; the env seed used to skip that rule.
+ // Warn, never refuse: an existing deployment with a short seeded password must still boot.
+ if (config.passwordSeed !== undefined && passwordTooShort(config.passwordSeed)) {
+ errors.push(
+ `✖ NODETERM_SERVER_PASSWORD is shorter than ${MIN_PASSWORD_LENGTH} characters. It is still used, but ` +
+ `the setup form would refuse it: anyone who can reach the login page can guess a short password. ` +
+ `Choose a longer one (if a password already exists, delete auth.json in the data directory and ` +
+ `restart to re-seed it).`
+ )
+ }
+ return { errors, notices }
+}
diff --git a/src/server/auth.test.ts b/src/server/auth.test.ts
index 48a0146f9..efdc5a652 100644
--- a/src/server/auth.test.ts
+++ b/src/server/auth.test.ts
@@ -2,25 +2,53 @@ import { describe, it, expect, beforeEach, vi, afterEach } from 'vitest'
import fs from 'fs'
import os from 'os'
import path from 'path'
-import { Auth } from './auth'
+import {
+ Auth,
+ LOCKOUT_MS,
+ MAX_LOCKOUT_MS,
+ MAX_FAILURES,
+ GLOBAL_MAX_ATTEMPTS,
+ GLOBAL_WINDOW_MS,
+ CLIENT_MEMORY_MS,
+ MAX_TRACKED_CLIENTS,
+ passwordTooShort,
+ type LoginGate
+} from './auth'
let dir: string
beforeEach(() => { dir = fs.mkdtempSync(path.join(os.tmpdir(), 'nt-auth-')) })
afterEach(() => { fs.rmSync(dir, { recursive: true, force: true }); vi.useRealTimers() })
describe('Auth', () => {
- it('is unconfigured until a password is set; then verifies only the right one', () => {
+ it('is unconfigured until a password is set; then verifies only the right one', async () => {
const a = new Auth(dir)
expect(a.isConfigured()).toBe(false)
- expect(a.verifyPassword('anything')).toBe(false)
+ expect(await a.verifyPasswordAsync('anything')).toBe(false)
a.setPassword('correct horse')
expect(a.isConfigured()).toBe(true)
- expect(a.verifyPassword('correct horse')).toBe(true)
- expect(a.verifyPassword('wrong')).toBe(false)
+ expect(await a.verifyPasswordAsync('correct horse')).toBe(true)
+ expect(await a.verifyPasswordAsync('wrong')).toBe(false)
// survives process restart (re-read from disk)
- expect(new Auth(dir).verifyPassword('correct horse')).toBe(true)
+ expect(await new Auth(dir).verifyPasswordAsync('correct horse')).toBe(true)
})
+ it('verifies OFF the event loop and at most two at a time (S1)', async () => {
+ // A synchronous scrypt per login froze every terminal's WebSocket for ~35 ms per guess, and a
+ // burst of held requests froze the whole server. The event loop must stay free while verifying,
+ // and the libuv pool must not be flooded (two at a time, the live-link gate's number).
+ const a = new Auth(dir)
+ a.setPassword('correct horse')
+ let ticks = 0
+ const timer = setInterval(() => ticks++, 1)
+ const running: Promise<boolean>[] = []
+ for (let i = 0; i < 6; i++) running.push(a.verifyPasswordAsync(i === 5 ? 'correct horse' : `w${i}`))
+ expect(a._scryptInFlightForTest()).toBeLessThanOrEqual(2)
+ const results = await Promise.all(running)
+ clearInterval(timer)
+ expect(results).toEqual([false, false, false, false, false, true])
+ expect(ticks).toBeGreaterThan(5) // the loop kept turning while six scrypts ran
+ }, 30_000)
+
it('setup token is single-use and timing-safe-compared', () => {
const a = new Auth(dir)
const tok = a.setupToken()
@@ -45,15 +73,147 @@ describe('Auth', () => {
expect(a.validateSession(t2)).toBe(false)
})
- it('locks out after 5 consecutive failures for 60s; success resets', () => {
+ it('revokeSession deletes exactly the presented token, and listeners hear every revoke (S3)', () => {
+ const a = new Auth(dir)
+ const heard: number[] = []
+ const off = a.onSessionsRevoked(() => heard.push(1))
+ const t1 = a.createSession()
+ const t2 = a.createSession()
+ expect(a.revokeSession(t1)).toBe(true)
+ expect(a.validateSession(t1)).toBe(false)
+ expect(a.validateSession(t2)).toBe(true)
+ expect(new Auth(dir).validateSession(t1)).toBe(false) // gone from disk, not only memory
+ expect(a.revokeSession(t1)).toBe(false) // already gone: nothing to announce
+ expect(a.revokeSession('constructor')).toBe(false) // not an own key
+ expect(heard).toHaveLength(1)
+ a.revokeAll()
+ expect(heard).toHaveLength(2)
+ off()
+ a.revokeAll()
+ expect(heard).toHaveLength(2)
+ })
+
+ it('password rule: at least 8 characters, one definition for setup and the boot seed (S8)', () => {
+ expect(passwordTooShort('1234567')).toBe(true)
+ expect(passwordTooShort('12345678')).toBe(false)
+ })
+})
+
+/** Reserve, then settle as `outcome`. */
+function attempt(a: Auth, client: string, outcome: 'success' | 'failure' | 'abandoned'): LoginGate {
+ const g = a.beginLoginAttempt(client)
+ if (g.ok) g.finish(outcome)
+ return g
+}
+
+describe('login rate limit (S1 + S4)', () => {
+ it('a client is locked after MAX_FAILURES failures; success resets it', () => {
+ vi.useFakeTimers()
+ const a = new Auth(dir)
+ for (let i = 0; i < MAX_FAILURES; i++) expect(attempt(a, 'v4:1.1.1.1', 'failure').ok).toBe(true)
+ const locked = a.beginLoginAttempt('v4:1.1.1.1')
+ expect(locked.ok).toBe(false)
+ if (!locked.ok) {
+ expect(locked.scope).toBe('client')
+ expect(locked.retryAfterMs).toBeGreaterThan(LOCKOUT_MS - 1000)
+ expect(locked.retryAfterMs).toBeLessThanOrEqual(LOCKOUT_MS)
+ }
+ vi.advanceTimersByTime(LOCKOUT_MS + 1)
+ expect(attempt(a, 'v4:1.1.1.1', 'failure').ok).toBe(true)
+ expect(attempt(a, 'v4:1.1.1.1', 'success').ok).toBe(true)
+ for (let i = 0; i < MAX_FAILURES; i++) expect(attempt(a, 'v4:1.1.1.1', 'failure').ok).toBe(true)
+ expect(a.beginLoginAttempt('v4:1.1.1.1').ok).toBe(false)
+ })
+
+ it('S4: one client locking itself out does not lock out anyone else', () => {
+ const a = new Auth(dir)
+ for (let i = 0; i < MAX_FAILURES; i++) attempt(a, 'v4:6.6.6.6', 'failure')
+ expect(a.beginLoginAttempt('v4:6.6.6.6').ok).toBe(false)
+ // The owner, from their own address, still gets in.
+ expect(attempt(a, 'v4:1.2.3.4', 'success').ok).toBe(true)
+ })
+
+ it('S1: the budget counts attempts IN FLIGHT — held request bodies cannot all pass the gate', () => {
+ // The old gate was checked before the body was read and charged only after verification, so
+ // sixty requests whose bodies were held back all passed it with the counter still at zero.
+ const a = new Auth(dir)
+ const held: LoginGate[] = []
+ for (let i = 0; i < 60; i++) held.push(a.beginLoginAttempt('v4:6.6.6.6'))
+ expect(held.filter((g) => g.ok)).toHaveLength(MAX_FAILURES)
+ // Abandoned (no body ever came) releases the slot without charging a failure.
+ for (const g of held) if (g.ok) g.finish('abandoned')
+ expect(held.filter((g) => g.ok).length).toBe(MAX_FAILURES)
+ expect(a.beginLoginAttempt('v4:6.6.6.6').ok).toBe(true)
+ })
+
+ it('finish is idempotent: settling twice charges once', () => {
+ const a = new Auth(dir)
+ const g = a.beginLoginAttempt('v4:1.1.1.1')
+ if (!g.ok) throw new Error('refused')
+ g.finish('failure')
+ g.finish('failure')
+ g.finish('success') // a late second settle must not reset either
+ for (let i = 0; i < MAX_FAILURES - 1; i++) expect(attempt(a, 'v4:1.1.1.1', 'failure').ok).toBe(true)
+ expect(a.beginLoginAttempt('v4:1.1.1.1').ok).toBe(false)
+ })
+
+ it('lockouts back off exponentially per client, capped, and are forgotten after a quiet hour', () => {
+ vi.useFakeTimers()
+ const a = new Auth(dir)
+ const lockOnce = (): number => {
+ for (let i = 0; i < MAX_FAILURES; i++) expect(attempt(a, 'v4:6.6.6.6', 'failure').ok).toBe(true)
+ const g = a.beginLoginAttempt('v4:6.6.6.6')
+ if (g.ok) throw new Error('not locked')
+ return g.retryAfterMs
+ }
+ const waits: number[] = []
+ for (let n = 0; n < 9; n++) {
+ const w = lockOnce()
+ waits.push(w)
+ vi.advanceTimersByTime(w + 1)
+ }
+ expect(waits.slice(0, 4)).toEqual([LOCKOUT_MS, 2 * LOCKOUT_MS, 4 * LOCKOUT_MS, 8 * LOCKOUT_MS])
+ expect(Math.max(...waits)).toBe(MAX_LOCKOUT_MS)
+ // A quiet hour after the last lock ended: back to the first step.
+ vi.advanceTimersByTime(CLIENT_MEMORY_MS + 1)
+ expect(lockOnce()).toBe(LOCKOUT_MS)
+ })
+
+ it('a global ceiling across all clients is the backstop for a distributed guesser', () => {
vi.useFakeTimers()
const a = new Auth(dir)
- for (let i = 0; i < 5; i++) { expect(a.loginAllowed()).toBe(true); a.recordLoginFailure() }
- expect(a.loginAllowed()).toBe(false)
- vi.advanceTimersByTime(61_000)
- expect(a.loginAllowed()).toBe(true)
- a.recordLoginFailure(); a.recordLoginSuccess()
- for (let i = 0; i < 5; i++) { expect(a.loginAllowed()).toBe(true); a.recordLoginFailure() }
- expect(a.loginAllowed()).toBe(false)
+ let n = 0
+ // Each client stays under its own budget; together they reach the ceiling.
+ while (n < GLOBAL_MAX_ATTEMPTS) {
+ expect(attempt(a, `v4:10.0.${Math.floor(n / 4)}.1`, 'failure').ok).toBe(true)
+ n++
+ }
+ const refused = a.beginLoginAttempt('v4:1.2.3.4')
+ expect(refused.ok).toBe(false)
+ if (!refused.ok) {
+ expect(refused.scope).toBe('global')
+ expect(refused.retryAfterMs).toBeLessThanOrEqual(GLOBAL_WINDOW_MS)
+ }
+ // It is a sliding window: once the failures age out, everyone can sign in again.
+ vi.advanceTimersByTime(GLOBAL_WINDOW_MS + 1)
+ expect(attempt(a, 'v4:1.2.3.4', 'success').ok).toBe(true)
+ })
+
+ it('the global ceiling also counts attempts in flight (S1 across many clients)', () => {
+ const a = new Auth(dir)
+ const held: LoginGate[] = []
+ for (let i = 0; i < 400; i++) held.push(a.beginLoginAttempt(`v4:10.1.${i}.1`))
+ expect(held.filter((g) => g.ok)).toHaveLength(GLOBAL_MAX_ATTEMPTS)
+ for (const g of held) if (g.ok) g.finish('abandoned')
+ expect(a.beginLoginAttempt('v4:1.2.3.4').ok).toBe(true)
+ })
+
+ it('tracks a bounded number of clients', () => {
+ const a = new Auth(dir)
+ for (let i = 0; i < MAX_TRACKED_CLIENTS + 500; i++) {
+ const g = a.beginLoginAttempt(`v4:k${i}`)
+ if (g.ok) g.finish('abandoned')
+ }
+ expect(a._trackedClientsForTest()).toBeLessThanOrEqual(MAX_TRACKED_CLIENTS)
})
})
diff --git a/src/server/auth.ts b/src/server/auth.ts
index a2db8d08c..f216b7fb2 100644
--- a/src/server/auth.ts
+++ b/src/server/auth.ts
@@ -9,8 +9,95 @@ const SCRYPT_P = 1
const SCRYPT_KEYLEN = 32
export const SESSION_TTL_MS = 30 * 24 * 60 * 60 * 1000
+
+/** The one password-length rule: the setup form refuses below it, the boot seed warns below it. */
+export const MIN_PASSWORD_LENGTH = 8
+export function passwordTooShort(password: string): boolean {
+ return password.length < MIN_PASSWORD_LENGTH
+}
+
+// ---- Login rate limit (security audit 2026-10, S1 + S4) -------------------------------------
+//
+// S1: the old gate was CHECKED before the request body was read and CHARGED after the password
+// was verified, so N requests whose bodies were held back all passed it with the counter at zero
+// (measured: 60 of 60 verified). Now an attempt RESERVES a slot synchronously before the body is
+// read, and the budget counts reserved slots plus failures — so at most MAX_FAILURES attempts per
+// client can ever be outstanding or failed before the lock, however they are timed.
+//
+// S4: one global counter let anyone lock the owner out with five wrong passwords a minute. The
+// lock is per CLIENT now (an address, see client-address.ts), with exponential backoff, and a much
+// higher global ceiling across all clients stays as the backstop against a guesser with many
+// addresses. The ceiling also counts in-flight attempts, or the S1 race would reopen across
+// clients. Its cost, stated: under a sustained distributed attack the ceiling refuses the owner
+// too, for as long as the attack keeps the window full.
+
+/** First lock a client earns; each further lock doubles it, up to MAX_LOCKOUT_MS. */
export const LOCKOUT_MS = 60_000
-const MAX_FAILURES = 5
+export const MAX_LOCKOUT_MS = 60 * 60_000
+/** Failures (plus attempts still in flight) a client may have before it is locked. */
+export const MAX_FAILURES = 5
+/** The global backstop: failures within the window plus every attempt in flight, all clients. */
+export const GLOBAL_WINDOW_MS = 5 * 60_000
+export const GLOBAL_MAX_ATTEMPTS = 50
+/** A client quiet this long after its last attempt or lock is forgotten (backoff starts over). */
+export const CLIENT_MEMORY_MS = 60 * 60_000
+/** Bounded memory: past this many tracked clients, the least recently seen are forgotten. */
+export const MAX_TRACKED_CLIENTS = 10_000
+/** Concurrent scrypt verifications (each is ~16 MiB and a libuv pool thread) — the live-link
+ * service gates its own scrypt at the same number (core/watch-link/service.ts SCRYPT_SLOTS). */
+export const SCRYPT_SLOTS = 2
+
+export type LoginOutcome = 'success' | 'failure' | 'abandoned'
+/** A reserved login attempt (settle it exactly once), or a refusal and when to come back. */
+export type LoginGate =
+ | { ok: true; finish(outcome: LoginOutcome): void }
+ | { ok: false; retryAfterMs: number; scope: 'client' | 'global' }
+
+interface ClientState {
+ failures: number
+ inFlight: number
+ lockedUntil: number
+ /** How many locks this client has earned in a row — the backoff exponent. */
+ level: number
+ lastSeen: number
+}
+
+/** A FIFO gate: at most `slots` tasks run at once, the rest wait in order. Same shape as the
+ * live-link service's `createFifoGate` (core/watch-link/service.ts). */
+function fifoGate(slots: number): { run<T>(task: () => Promise<T>): Promise<T>; active(): number } {
+ let active = 0
+ const waiting: (() => void)[] = []
+ const release = (): void => {
+ const next = waiting.shift()
+ if (next) next()
+ else active--
+ }
+ return {
+ active: () => active,
+ run: <T>(task: () => Promise<T>): Promise<T> =>
+ new Promise<T>((resolve, reject) => {
+ const go = (): void => {
+ let p: Promise<T>
+ try {
+ p = Promise.resolve(task())
+ } catch (err) {
+ p = Promise.reject(err)
+ }
+ p.then(resolve, reject).finally(release)
+ }
+ if (active < slots) {
+ active++
+ go()
+ } else waiting.push(go)
+ })
+ }
+}
+
+function scryptAsync(password: string, salt: Buffer, keylen: number, opts: crypto.ScryptOptions): Promise<Buffer> {
+ return new Promise((resolve, reject) =>
+ crypto.scrypt(password, salt, keylen, opts, (err, key) => (err ? reject(err) : resolve(key)))
+ )
+}
interface AuthFile {
salt: string
@@ -33,9 +120,13 @@ export class Auth {
private setupTokenValue: string | null = null
private sessions: SessionMap | null = null
+ private revokeListeners = new Set<() => void>()
- private failures = 0
- private lockedUntil = 0
+ private clients = new Map<string, ClientState>()
+ /** Times of recent failures, all clients (pruned to GLOBAL_WINDOW_MS). */
+ private globalFailures: number[] = []
+ private globalInFlight = 0
+ private scryptGate = fifoGate(SCRYPT_SLOTS)
constructor(dataDir: string) {
this.authPath = path.join(dataDir, 'auth.json')
@@ -73,20 +164,28 @@ export class Auth {
fs.writeFileSync(this.authPath, JSON.stringify(data, null, 2), { mode: 0o600 })
}
- verifyPassword(password: string): boolean {
+ /**
+ * Verify a password with the ASYNC scrypt, through a FIFO gate of SCRYPT_SLOTS. The old
+ * `scryptSync` ran on the one event loop that carries every terminal's WebSocket, so each guess
+ * froze the whole server for its duration (S1). There is deliberately no synchronous variant.
+ */
+ async verifyPasswordAsync(password: string): Promise<boolean> {
const auth = this.readAuth()
if (!auth) return false
const salt = Buffer.from(auth.salt, 'hex')
const stored = Buffer.from(auth.hash, 'hex')
- const computed = crypto.scryptSync(password, salt, stored.length, {
- N: auth.N,
- r: auth.r,
- p: auth.p
- })
+ const computed = await this.scryptGate.run(() =>
+ scryptAsync(password, salt, stored.length, { N: auth.N, r: auth.r, p: auth.p })
+ )
if (computed.length !== stored.length) return false
return crypto.timingSafeEqual(computed, stored)
}
+ /** Test seam: scrypt runs currently holding a gate slot. */
+ _scryptInFlightForTest(): number {
+ return this.scryptGate.active()
+ }
+
// ---- Setup token -------------------------------------------------------
setupToken(): string {
@@ -154,27 +253,122 @@ export class Auth {
return Object.prototype.hasOwnProperty.call(sessions, token)
}
+ /** Sign out ONE session: the token the caller presented (S3). True when it existed. */
+ revokeSession(token: string): boolean {
+ const sessions = this.loadSessions()
+ if (!Object.prototype.hasOwnProperty.call(sessions, token)) return false
+ delete sessions[token]
+ this.persistSessions()
+ this.announceRevoke()
+ return true
+ }
+
+ /** Sign out everywhere: every session of every browser (S3). */
revokeAll(): void {
this.sessions = {}
this.persistSessions()
+ this.announceRevoke()
}
- // ---- Rate limiting -----------------------------------------------------
+ /** Hear every revoke — the WebSocket layer closes the sockets whose session is gone. */
+ onSessionsRevoked(listener: () => void): () => void {
+ this.revokeListeners.add(listener)
+ return () => this.revokeListeners.delete(listener)
+ }
- loginAllowed(): boolean {
- return Date.now() >= this.lockedUntil
+ private announceRevoke(): void {
+ for (const listener of [...this.revokeListeners]) {
+ try {
+ listener()
+ } catch {
+ /* a listener's failure must not undo the revoke */
+ }
+ }
}
- recordLoginFailure(): void {
- this.failures += 1
- if (this.failures >= MAX_FAILURES) {
- this.lockedUntil = Date.now() + LOCKOUT_MS
- this.failures = 0
+ // ---- Rate limiting (S1 + S4, see the block at the top of this file) -----
+
+ /**
+ * Reserve a login attempt for `client` (a key from client-address.ts) BEFORE the request body is
+ * read. Refused when the client is locked or has MAX_FAILURES failures + attempts in flight, or
+ * when the global window is full. A reservation must be settled exactly once: `success` resets
+ * the client, `failure` charges it (and may lock it), `abandoned` (no body, a read error) only
+ * releases the slot.
+ */
+ beginLoginAttempt(client: string, now = Date.now()): LoginGate {
+ this.pruneGlobal(now)
+ const state = this.clientState(client, now)
+ if (now < state.lockedUntil) {
+ return { ok: false, retryAfterMs: state.lockedUntil - now, scope: 'client' }
}
+ if (state.failures + state.inFlight >= MAX_FAILURES) {
+ // Every slot is held by an attempt still in flight; one of them settling frees it.
+ return { ok: false, retryAfterMs: 1000, scope: 'client' }
+ }
+ if (this.globalFailures.length + this.globalInFlight >= GLOBAL_MAX_ATTEMPTS) {
+ const oldest = this.globalFailures[0]
+ return {
+ ok: false,
+ retryAfterMs: oldest !== undefined ? Math.max(1000, oldest + GLOBAL_WINDOW_MS - now) : 1000,
+ scope: 'global'
+ }
+ }
+ state.inFlight++
+ state.lastSeen = now
+ this.globalInFlight++
+ let settled = false
+ return {
+ ok: true,
+ finish: (outcome: LoginOutcome): void => {
+ if (settled) return
+ settled = true
+ const at = Date.now()
+ state.inFlight--
+ this.globalInFlight--
+ state.lastSeen = at
+ if (outcome === 'success') {
+ state.failures = 0
+ state.level = 0
+ state.lockedUntil = 0
+ } else if (outcome === 'failure') {
+ state.failures++
+ this.globalFailures.push(at)
+ if (state.failures >= MAX_FAILURES) {
+ state.lockedUntil = at + Math.min(LOCKOUT_MS * 2 ** state.level, MAX_LOCKOUT_MS)
+ state.level++
+ state.failures = 0
+ }
+ }
+ }
+ }
+ }
+
+ /** Test seam: how many clients are tracked. */
+ _trackedClientsForTest(): number {
+ return this.clients.size
}
- recordLoginSuccess(): void {
- this.failures = 0
- this.lockedUntil = 0
+ private pruneGlobal(now: number): void {
+ const cutoff = now - GLOBAL_WINDOW_MS
+ let drop = 0
+ while (drop < this.globalFailures.length && this.globalFailures[drop] <= cutoff) drop++
+ if (drop > 0) this.globalFailures.splice(0, drop)
+ }
+
+ /** The client's state, forgotten first when it has been quiet long enough; moved to the end of
+ * the map (most recently seen) so the oldest are evicted first when the map is full. */
+ private clientState(client: string, now: number): ClientState {
+ let state = this.clients.get(client)
+ if (state && state.inFlight === 0 && now - Math.max(state.lastSeen, state.lockedUntil) > CLIENT_MEMORY_MS) {
+ state = undefined
+ }
+ this.clients.delete(client)
+ if (!state) state = { failures: 0, inFlight: 0, lockedUntil: 0, level: 0, lastSeen: now }
+ this.clients.set(client, state)
+ while (this.clients.size > MAX_TRACKED_CLIENTS) {
+ const oldest = this.clients.keys().next().value as string
+ this.clients.delete(oldest)
+ }
+ return state
}
}
diff --git a/src/server/client-address.test.ts b/src/server/client-address.test.ts
new file mode 100644
index 000000000..2e7b8f889
--- /dev/null
+++ b/src/server/client-address.test.ts
@@ -0,0 +1,45 @@
+import { describe, it, expect } from 'vitest'
+import { loginClientKey } from './client-address'
+import { parseTrustedNets } from './proxy-trust'
+
+describe('loginClientKey (S4: which client a login attempt is charged to)', () => {
+ it('a public peer is the client, and its X-Forwarded-For is ignored (a client can write anything there)', () => {
+ expect(loginClientKey('203.0.113.9', undefined)).toBe('v4:203.0.113.9')
+ expect(loginClientKey('203.0.113.9', '198.51.100.1')).toBe('v4:203.0.113.9')
+ expect(loginClientKey('::ffff:203.0.113.9', undefined)).toBe('v4:203.0.113.9')
+ })
+
+ it('behind a forwarder (loopback, private, CGNAT, ULA) the client is the LAST X-Forwarded-For entry', () => {
+ for (const proxy of ['127.0.0.1', '::1', '10.0.1.7', '172.18.0.2', '192.168.1.1', '100.100.1.1', 'fd7a:115c::1']) {
+ expect(loginClientKey(proxy, '198.51.100.1')).toBe('v4:198.51.100.1')
+ }
+ // Only the entry the proxy appended counts: the left ones came from whoever called the proxy.
+ expect(loginClientKey('127.0.0.1', '1.1.1.1, 2.2.2.2, 198.51.100.1')).toBe('v4:198.51.100.1')
+ // Ports and brackets, as some proxies write them.
+ expect(loginClientKey('127.0.0.1', '198.51.100.1:51234')).toBe('v4:198.51.100.1')
+ expect(loginClientKey('127.0.0.1', '[2001:db8:1:2:3:4:5:6]:443')).toBe('v6:20010db800010002/64')
+ })
+
+ it('no (or garbage) X-Forwarded-For from a forwarder → the forwarder itself', () => {
+ expect(loginClientKey('127.0.0.1', undefined)).toBe('v4:127.0.0.1')
+ expect(loginClientKey('127.0.0.1', ' ')).toBe('v4:127.0.0.1')
+ expect(loginClientKey('127.0.0.1', 'not-an-ip')).toBe('v4:127.0.0.1')
+ })
+
+ it('IPv6 clients are keyed by their /64', () => {
+ expect(loginClientKey('2001:db8:1:2::9', undefined)).toBe('v6:20010db800010002/64')
+ expect(loginClientKey('2001:db8:1:2:ffff::1', undefined)).toBe('v6:20010db800010002/64')
+ expect(loginClientKey('2001:db8:1:3::9', undefined)).not.toBe(loginClientKey('2001:db8:1:2::9', undefined))
+ })
+
+ it('a header-trust net counts as a forwarder even when it is public', () => {
+ const trust = { header: 'X-U', nets: parseTrustedNets('203.0.113.0/24') }
+ expect(loginClientKey('203.0.113.9', '198.51.100.1', trust)).toBe('v4:198.51.100.1')
+ expect(loginClientKey('198.51.100.7', '1.2.3.4', trust)).toBe('v4:198.51.100.7')
+ })
+
+ it('an unreadable peer shares one bucket rather than escaping the limit', () => {
+ expect(loginClientKey(undefined, '198.51.100.1')).toBe('unknown')
+ expect(loginClientKey('garbage', undefined)).toBe('unknown')
+ })
+})
diff --git a/src/server/client-address.ts b/src/server/client-address.ts
new file mode 100644
index 000000000..779880f60
--- /dev/null
+++ b/src/server/client-address.ts
@@ -0,0 +1,64 @@
+// Which CLIENT a login attempt is charged to (security audit 2026-10, S4).
+//
+// The login lockout used to be one global counter, so a stranger's five wrong passwords locked the
+// owner out too. It is per client now (auth.ts), and a client is an address — which, behind the
+// reverse proxy the Server Edition is documented to run behind, is NOT the TCP peer: every request
+// arrives from the proxy, and keying on the peer would make the per-client lock global again.
+//
+// The rule, kept deliberately small:
+// - When the TCP peer is a FORWARDER — loopback, a private / CGNAT / link-local / ULA address (a
+// same-host nginx, a Docker network's Traefik, a Tailscale proxy), or inside the header-trust
+// nets — the client is the LAST `X-Forwarded-For` entry: the one that forwarder appended. Only
+// that one: every entry to its left was written by whoever sent the request to the proxy, i.e.
+// possibly the attacker.
+// - Any other peer is the client itself, and `X-Forwarded-For` is ignored.
+// - IPv6 clients are keyed by their /64 (one subscriber's allocation), IPv4 by the address.
+//
+// What it costs, stated: a process that can reach the server FROM a forwarder address (a local
+// user, a container on the same network) can choose the bucket it is charged to — evading its own
+// per-client lock (the global ceiling still applies) or locking a chosen address's bucket. A chain
+// of two proxies (a CDN in front of the local proxy) buckets clients by the CDN's edge address.
+// Neither reopens S1: the budget per bucket and the global ceiling still hold.
+import { isTrustedAddress, parsePeerAddress, parseTrustedNets, type TrustProxyConfig } from './proxy-trust'
+
+const FORWARDER_NETS = parseTrustedNets(
+ '127.0.0.0/8, ::1/128, 10.0.0.0/8, 172.16.0.0/12, 192.168.0.0/16, 100.64.0.0/10, 169.254.0.0/16, fc00::/7, fe80::/10'
+)
+
+function keyOf(bytes: Uint8Array): string {
+ if (bytes.length === 4) return `v4:${Array.from(bytes).join('.')}`
+ let hex = ''
+ for (let i = 0; i < 8; i++) hex += bytes[i].toString(16).padStart(2, '0')
+ return `v6:${hex}/64`
+}
+
+/** One `X-Forwarded-For` entry → an address, tolerating a port (`1.2.3.4:5678`, `[::1]:80`). */
+function entryAddress(entry: string): Uint8Array | null {
+ const e = entry.trim()
+ const bracketed = /^\[([^\]]+)\](?::\d+)?$/.exec(e)
+ if (bracketed) return parsePeerAddress(bracketed[1])
+ const v4WithPort = /^(\d{1,3}(?:\.\d{1,3}){3}):\d+$/.exec(e)
+ if (v4WithPort) return parsePeerAddress(v4WithPort[1])
+ return parsePeerAddress(e)
+}
+
+/**
+ * The rate-limit key of the client behind this request (see the header). `peer` is the TCP peer
+ * address, `forwardedFor` the raw `X-Forwarded-For` header.
+ */
+export function loginClientKey(
+ peer: string | undefined,
+ forwardedFor: string | string[] | undefined,
+ trust?: TrustProxyConfig
+): string {
+ const peerBytes = parsePeerAddress(peer)
+ if (!peerBytes) return 'unknown'
+ const forwarder =
+ isTrustedAddress(peer, FORWARDER_NETS) || (trust !== undefined && isTrustedAddress(peer, trust.nets))
+ if (forwarder && typeof forwardedFor === 'string' && forwardedFor.trim() !== '') {
+ const entries = forwardedFor.split(',')
+ const last = entryAddress(entries[entries.length - 1])
+ if (last) return keyOf(last)
+ }
+ return keyOf(peerBytes)
+}
diff --git a/src/server/config.test.ts b/src/server/config.test.ts
index ae88c348d..580664bd1 100644
--- a/src/server/config.test.ts
+++ b/src/server/config.test.ts
@@ -3,6 +3,8 @@ import os from 'os'
import path from 'path'
import { resolveConfig, resolveDataDir } from './config'
+const SECRET = 'f'.repeat(16) + '0123456789abcdef'.repeat(2)
+
describe('resolveConfig', () => {
it('has safe defaults', () => {
const c = resolveConfig({}, [])
@@ -58,10 +60,69 @@ describe('resolveConfig', () => {
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' }, [])
+ it('proxy trust: header via env, nets default to loopback (needs the secret, see S2 below)', () => {
+ const c = resolveConfig(
+ { NODETERM_TRUST_PROXY_HEADER: 'Cf-Access-Authenticated-User-Email', NODETERM_TRUST_PROXY_SECRET: SECRET },
+ []
+ )
expect(c.trustProxy?.header).toBe('Cf-Access-Authenticated-User-Email')
expect(c.trustProxy?.nets.length).toBeGreaterThan(0)
+ expect(c.trustProxy?.secret).toBe(SECRET)
+ expect(c.trustProxyRefused).toBeUndefined()
+ })
+
+ // S2 (security audit 2026-10): on loopback every local process is "the proxy".
+ it('proxy trust S2: loopback nets with no secret → header trust OFF, boot still succeeds, with the fix spelled out', () => {
+ for (const nets of ['', '127.0.0.1', '10.0.0.0/8, ::1', '0.0.0.0/0']) {
+ const c = resolveConfig(
+ { NODETERM_TRUST_PROXY_HEADER: 'X-Forwarded-User', NODETERM_TRUST_PROXY_NETS: nets },
+ []
+ )
+ expect(c.trustProxy).toBeUndefined()
+ expect(c.trustProxyRefused).toMatch(/NODETERM_TRUST_PROXY_SECRET=/)
+ expect(c.trustProxyRefused).toMatch(/X-Nodeterm-Proxy-Secret/)
+ expect(c.trustProxyRefused).toMatch(/every local process/i)
+ }
+ // Non-loopback nets keep working without a secret (the boot warns, see index.ts).
+ const far = resolveConfig(
+ { NODETERM_TRUST_PROXY_HEADER: 'X-Forwarded-User', NODETERM_TRUST_PROXY_NETS: '10.0.0.0/8' },
+ []
+ )
+ expect(far.trustProxy?.secret).toBeUndefined()
+ expect(far.trustProxyRefused).toBeUndefined()
+ })
+
+ it('proxy trust S2: the secret is env-only, long enough, header-safe, and needs the header', () => {
+ // A secret on argv is readable by every local user (/proc/<pid>/cmdline).
+ expect(() =>
+ resolveConfig({ NODETERM_TRUST_PROXY_HEADER: 'X-U' }, ['--trust-proxy-secret', SECRET])
+ ).toThrow(/environment/i)
+ expect(() =>
+ resolveConfig({ NODETERM_TRUST_PROXY_HEADER: 'X-U', NODETERM_TRUST_PROXY_SECRET: 'short' }, [])
+ ).toThrow(/at least 32/)
+ expect(() =>
+ resolveConfig({ NODETERM_TRUST_PROXY_HEADER: 'X-U', NODETERM_TRUST_PROXY_SECRET: `${SECRET} x` }, [])
+ ).toThrow(/printable/)
+ expect(() => resolveConfig({ NODETERM_TRUST_PROXY_SECRET: SECRET }, [])).toThrow(/TRUST_PROXY_HEADER/)
+ // The refusal never echoes the value.
+ try {
+ resolveConfig({ NODETERM_TRUST_PROXY_HEADER: 'X-U', NODETERM_TRUST_PROXY_SECRET: 'tooshort-value' }, [])
+ } catch (e) {
+ expect(String(e)).not.toContain('tooshort-value')
+ }
+ })
+
+ it('public origin (S5): https origin only, normalized; anything else fails the boot', () => {
+ expect(resolveConfig({}, []).publicOrigin).toBeUndefined()
+ expect(resolveConfig({ NODETERM_PUBLIC_ORIGIN: 'https://term.example.com/' }, []).publicOrigin).toBe(
+ 'https://term.example.com'
+ )
+ expect(resolveConfig({}, ['--public-origin', 'https://Term.Example.com:8443']).publicOrigin).toBe(
+ 'https://term.example.com:8443'
+ )
+ for (const bad of ['http://term.example.com', 'term.example.com', 'https://term.example.com/app', 'https://u:[email protected]', 'https://x.com/?a=1']) {
+ expect(() => resolveConfig({ NODETERM_PUBLIC_ORIGIN: bad }, [])).toThrow(/NODETERM_PUBLIC_ORIGIN/)
+ }
})
it('proxy trust: argv overrides env; custom nets parsed', () => {
diff --git a/src/server/config.ts b/src/server/config.ts
index 5e909c957..c0e5928ce 100644
--- a/src/server/config.ts
+++ b/src/server/config.ts
@@ -1,6 +1,13 @@
import os from 'os'
import path from 'path'
-import { parseTrustedNets, DEFAULT_TRUSTED_NETS_SPEC, type TrustProxyConfig } from './proxy-trust'
+import {
+ parseTrustedNets,
+ describeTrustedNets,
+ netsCoverLoopback,
+ DEFAULT_TRUSTED_NETS_SPEC,
+ MIN_PROXY_SECRET_LENGTH,
+ type TrustProxyConfig
+} from './proxy-trust'
import type { RelayTransport } from '../core/relay/relay-socket'
/**
@@ -56,6 +63,21 @@ export type ServerConfig = {
* Absent = feature off (default). See src/server/proxy-trust.ts and docs/SERVER.md.
*/
trustProxy?: TrustProxyConfig
+ /**
+ * Set when header trust was configured but refused (S2): the trusted nets include loopback and no
+ * `NODETERM_TRUST_PROXY_SECRET` is set, so every local process would count as the proxy. Header
+ * trust is then OFF (`trustProxy` undefined, password sign-in still works) and the boot prints
+ * this message, which names exactly what to set in the proxy and the environment.
+ */
+ trustProxyRefused?: string
+ /**
+ * The public https origin the server is reached at (`NODETERM_PUBLIC_ORIGIN`, e.g.
+ * `https://term.example.com`), normalized to its origin. When set, the session cookie is always
+ * `Secure`, every response carries HSTS, and an `Origin` equal to it passes the same-origin checks
+ * even when the proxy rewrites `Host`. Unset = the old behaviour (`Secure` follows
+ * `X-Forwarded-Proto`), with a one-time warning when a non-loopback Host arrives.
+ */
+ publicOrigin?: string
/**
* TEST ONLY: an in-process relay transport for each hosted-team listener, in place of the real
* WebSocket to the relay. Passed straight to `createHostedService`'s `transport`.
@@ -97,6 +119,49 @@ function parseArgv(argv: string[]): Record<string, string | boolean> {
return out
}
+/**
+ * The boot error for header trust on loopback nets with no secret (S2). Exported for the tests and
+ * the docs; it must name exactly what to set, because the operator's next step is to set it.
+ */
+export function trustProxyRefusedMessage(nets: string): string {
+ return [
+ `Proxy header trust is OFF: NODETERM_TRUST_PROXY_HEADER is set, but the trusted networks [${nets}] include loopback and NODETERM_TRUST_PROXY_SECRET is not set.`,
+ `On loopback every local process and every local user counts as "your proxy", so the header alone would sign any of them in as the owner, without a password. Password sign-in still works.`,
+ `To turn header trust on:`,
+ ` 1. Generate a secret: openssl rand -hex 32`,
+ ` 2. Give it to nodeterm-server: NODETERM_TRUST_PROXY_SECRET=<secret> (environment only — never a command-line flag)`,
+ ` 3. Make the proxy send it on every request, WebSocket upgrades included: X-Nodeterm-Proxy-Secret: <secret>`,
+ ` nginx: proxy_set_header X-Nodeterm-Proxy-Secret "<secret>";`,
+ ` Caddy: header_up X-Nodeterm-Proxy-Secret "<secret>"`,
+ ` Traefik: a headers middleware with customRequestHeaders.X-Nodeterm-Proxy-Secret`,
+ `See "Reverse-proxy SSO" in docs/SERVER.md.`
+ ].join('\n')
+}
+
+/** Validate `NODETERM_PUBLIC_ORIGIN` into a normalized https origin. Throws (never echoing more than
+ * the value the operator typed) on anything that is not exactly an https origin. */
+function parsePublicOrigin(value: string): string {
+ let url: URL
+ try {
+ url = new URL(value)
+ } catch {
+ throw new Error(`NODETERM_PUBLIC_ORIGIN must be an https origin such as https://term.example.com (got "${value}").`)
+ }
+ if (
+ url.protocol !== 'https:' ||
+ url.username !== '' ||
+ url.password !== '' ||
+ (url.pathname !== '/' && url.pathname !== '') ||
+ url.search !== '' ||
+ url.hash !== ''
+ ) {
+ throw new Error(
+ `NODETERM_PUBLIC_ORIGIN must be an https origin with no path, query or credentials, such as https://term.example.com (got "${value}").`
+ )
+ }
+ return url.origin
+}
+
function isLoopback(host: string): boolean {
return host === '127.0.0.1' || host === 'localhost' || host === '::1'
}
@@ -166,13 +231,44 @@ export function resolveConfig(env: NodeJS.ProcessEnv, argv: string[]): ServerCon
// 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', '')
+ // The proxy secret is ENVIRONMENT ONLY: a command line is readable by every local user, which is
+ // exactly who the secret keeps out. A flag is refused rather than ignored, so it is not mistaken
+ // for working. Neither refusal ever echoes the value.
+ if (args['trust-proxy-secret'] !== undefined) {
+ throw new Error(
+ `--trust-proxy-secret is not accepted: a command line is readable by every local user. Pass the secret through the environment as NODETERM_TRUST_PROXY_SECRET instead.`
+ )
+ }
+ const trustSecret = env.NODETERM_TRUST_PROXY_SECRET ?? ''
+ if (trustSecret !== '') {
+ if (trustHeader === '') {
+ throw new Error(
+ `NODETERM_TRUST_PROXY_SECRET is set but no trust header is configured. Set NODETERM_TRUST_PROXY_HEADER (or --trust-proxy-header) too, or unset the secret.`
+ )
+ }
+ if (trustSecret.length < MIN_PROXY_SECRET_LENGTH) {
+ throw new Error(
+ `NODETERM_TRUST_PROXY_SECRET must be at least ${MIN_PROXY_SECRET_LENGTH} characters (header trust is not rate-limited, so every request is a guess). Generate one with: openssl rand -hex 32`
+ )
+ }
+ if (!/^[\x21-\x7e]+$/.test(trustSecret)) {
+ throw new Error(
+ `NODETERM_TRUST_PROXY_SECRET must be printable ASCII with no spaces (it travels as a request header). Generate one with: openssl rand -hex 32`
+ )
+ }
+ }
let trustProxy: TrustProxyConfig | undefined
+ let trustProxyRefused: string | 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)
+ const nets = parseTrustedNets(trustNetsSpec || DEFAULT_TRUSTED_NETS_SPEC)
+ if (trustSecret === '' && netsCoverLoopback(nets)) {
+ // Fail CLOSED, not loud: the server still boots with password sign-in, and the boot prints
+ // what to set. Refusing the boot would take down a deployment that worked yesterday.
+ trustProxyRefused = trustProxyRefusedMessage(describeTrustedNets(nets))
+ } else {
+ trustProxy = { header: trustHeader, nets, ...(trustSecret !== '' ? { secret: trustSecret } : {}) }
}
} else if (trustNetsSpec !== '') {
throw new Error(
@@ -182,6 +278,9 @@ export function resolveConfig(env: NodeJS.ProcessEnv, argv: string[]): ServerCon
)
}
+ const publicOriginRaw = pick('public-origin', 'NODETERM_PUBLIC_ORIGIN', '')
+ const publicOrigin = publicOriginRaw !== '' ? parsePublicOrigin(publicOriginRaw) : undefined
+
return {
port,
host,
@@ -190,6 +289,8 @@ export function resolveConfig(env: NodeJS.ProcessEnv, argv: string[]): ServerCon
insecureHttp,
passwordSeed,
trustProxy,
+ ...(trustProxyRefused !== undefined ? { trustProxyRefused } : {}),
+ ...(publicOrigin !== undefined ? { publicOrigin } : {}),
headless,
canvasControl
}
diff --git a/src/server/download.test.ts b/src/server/download.test.ts
index 230cb4fc6..be5a1ec25 100644
--- a/src/server/download.test.ts
+++ b/src/server/download.test.ts
@@ -119,6 +119,19 @@ describe('GET /download', () => {
expect(body.length).toBeGreaterThan(20)
})
+ it('a folder whose name starts with "-" is archived as a name, never parsed as a tar option (S7)', async () => {
+ const cookie = await login()
+ const odd = path.join(dir, '--transform=s.a.b.')
+ fs.mkdirSync(odd)
+ fs.writeFileSync(path.join(odd, 'a.txt'), 'a')
+ const token = tickets.issue(odd, true)
+ const res = await fetch(`${base}/download?t=${token}`, { headers: { cookie } })
+ // Without `--`, GNU tar took the name as an option, had no file operand left, and failed (500).
+ expect(res.status).toBe(200)
+ const body = new Uint8Array(await res.arrayBuffer())
+ expect([body[0], body[1]]).toEqual([0x1f, 0x8b])
+ })
+
it('rejects a non-GET method', async () => {
const cookie = await login()
const token = tickets.issue(path.join(dir, 'notes.md'), false)
diff --git a/src/server/download.ts b/src/server/download.ts
index 6d78d0090..336a28dd3 100644
--- a/src/server/download.ts
+++ b/src/server/download.ts
@@ -107,7 +107,9 @@ export async function handleDownload(
function streamTarball(res: http.ServerResponse, dirPath: string): void {
const parent = path.dirname(dirPath)
const base = path.basename(dirPath)
- const child = spawn('tar', ['-czf', '-', '-C', parent, base], { stdio: ['ignore', 'pipe', 'ignore'] })
+ // `--` before the name (security audit 2026-10, S7): a folder called `--transform=…` or
+ // `--checkpoint-action=…` — committed in a cloned repository, say — was parsed by tar as an option.
+ const child = spawn('tar', ['-czf', '-', '-C', parent, '--', base], { stdio: ['ignore', 'pipe', 'ignore'] })
let started = false
const fail = (): void => {
if (started || res.headersSent) res.destroy()
diff --git a/src/server/http-auth.test.ts b/src/server/http-auth.test.ts
new file mode 100644
index 000000000..d63724851
--- /dev/null
+++ b/src/server/http-auth.test.ts
@@ -0,0 +1,268 @@
+// Regression tests for the Server Edition auth findings of the 2026-10 security audit (S1, S3, S4,
+// S5, S6). Each one ports a repro from the audit against the real handler on a loopback port.
+import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest'
+import http from 'http'
+import fs from 'fs'
+import os from 'os'
+import path from 'path'
+import { Auth, MAX_FAILURES } from './auth'
+import { createHttpHandler, SESSION_COOKIE, type HttpHandlerOpts } from './http'
+
+const REAL = 'correct-horse-battery'
+let dir: string, rendererDir: string, auth: Auth
+let servers: http.Server[] = []
+
+beforeEach(() => {
+ dir = fs.mkdtempSync(path.join(os.tmpdir(), 'nt-http-auth-'))
+ rendererDir = path.join(dir, 'renderer')
+ fs.mkdirSync(rendererDir)
+ fs.writeFileSync(
+ path.join(rendererDir, 'index.html'),
+ `<meta http-equiv="Content-Security-Policy" content="default-src 'self'; style-src 'self'" /><div id="root"></div>`
+ )
+ auth = new Auth(dir)
+ auth.setPassword(REAL)
+ servers = []
+})
+afterEach(async () => {
+ for (const s of servers) {
+ s.closeAllConnections()
+ await new Promise((r) => s.close(r))
+ }
+ fs.rmSync(dir, { recursive: true, force: true })
+ vi.restoreAllMocks()
+})
+
+async function serve(extra: Partial<HttpHandlerOpts> = {}): Promise<number> {
+ const srv = http.createServer(createHttpHandler({ auth, rendererDir, ...extra }))
+ servers.push(srv)
+ await new Promise<void>((r) => srv.listen(0, '127.0.0.1', r))
+ return (srv.address() as { port: number }).port
+}
+
+interface Res {
+ status: number
+ headers: http.IncomingHttpHeaders
+ body: string
+}
+
+/** A raw request (fetch hides Set-Cookie attributes and refuses to set Host/Origin freely). With
+ * `bodyDelayMs`, the headers go out first and the body later — the S1 hold. */
+function request(
+ port: number,
+ method: string,
+ p: string,
+ headers: Record<string, string> = {},
+ body?: string,
+ bodyDelayMs = 0
+): Promise<Res> {
+ return new Promise((resolve, reject) => {
+ const h: Record<string, string> = { ...headers }
+ if (body !== undefined) {
+ h['content-type'] = 'application/x-www-form-urlencoded'
+ h['content-length'] = String(Buffer.byteLength(body))
+ }
+ const r = http.request({ host: '127.0.0.1', port, path: p, method, headers: h }, (res) => {
+ const chunks: Buffer[] = []
+ res.on('data', (c: Buffer) => chunks.push(c))
+ res.on('end', () =>
+ resolve({ status: res.statusCode ?? 0, headers: res.headers, body: Buffer.concat(chunks).toString('utf8') })
+ )
+ })
+ r.on('error', reject)
+ if (bodyDelayMs > 0) {
+ r.flushHeaders()
+ setTimeout(() => r.end(body), bodyDelayMs)
+ } else r.end(body)
+ })
+}
+
+const login = (port: number, password: string, headers: Record<string, string> = {}, delay = 0): Promise<Res> =>
+ request(port, 'POST', '/auth/login', headers, `password=${encodeURIComponent(password)}`, delay)
+
+function cookieOf(res: Res): string {
+ const raw = (res.headers['set-cookie'] ?? [])[0] ?? ''
+ return raw.split(';')[0]
+}
+
+describe('S1: login lockout cannot be bypassed by holding request bodies', () => {
+ it('60 concurrent guesses with held bodies: at most MAX_FAILURES are verified', async () => {
+ const port = await serve()
+ const N = 60
+ const guesses = Array.from({ length: N }, (_, i) => (i === N - 1 ? REAL : `guess-${i}`))
+ const results = await Promise.all(guesses.map((g) => login(port, g, {}, 200)))
+ const verified = results.filter((r) => r.status === 303).length
+ const refused = results.filter((r) => r.status === 429).length
+ // Was: 60 verified, 0 refused — and the right password, last, got a session.
+ expect(verified).toBeLessThanOrEqual(MAX_FAILURES)
+ expect(refused).toBeGreaterThanOrEqual(N - MAX_FAILURES)
+ expect(results[N - 1].status).toBe(429)
+ }, 60_000)
+
+ it('the slot is taken BEFORE the body is read: held bodies refuse the next attempt at once', async () => {
+ const port = await serve()
+ const c = { 'x-forwarded-for': '203.0.113.66' }
+ // Five attempts whose bodies are still on their way...
+ const held = Array.from({ length: MAX_FAILURES }, (_, i) => login(port, `held${i}`, c, 1500))
+ await new Promise((r) => setTimeout(r, 300))
+ // ...already hold this client's whole budget: a sixth, body and all, is refused right now.
+ const sixth = await login(port, REAL, c)
+ expect(sixth.status).toBe(429)
+ expect((await Promise.all(held)).map((r) => r.status)).toEqual(Array(MAX_FAILURES).fill(303))
+ }, 30_000)
+
+ it('an attempt whose body never makes it releases its slot without charging a failure', async () => {
+ const port = await serve()
+ const huge = 'password=' + 'x'.repeat(20 * 1024) // over the 10 KB form cap → 400
+ for (let i = 0; i < MAX_FAILURES + 2; i++) {
+ // The server destroys an oversized body's socket, so the client sees a 400 or a hang-up.
+ const status = await request(port, 'POST', '/auth/login', {}, huge).then((r) => r.status, () => 400)
+ expect(status).toBe(400)
+ }
+ expect((await login(port, REAL)).status).toBe(303)
+ })
+
+ it('a refusal says when to come back (Retry-After), and a browser gets a page, not JSON', async () => {
+ const port = await serve()
+ for (let i = 0; i < MAX_FAILURES; i++) await login(port, `bad${i}`)
+ const json = await login(port, REAL)
+ expect(json.status).toBe(429)
+ expect(Number(json.headers['retry-after'])).toBeGreaterThan(0)
+ expect(JSON.parse(json.body)).toEqual({ error: 'too_many_attempts' })
+ const page = await login(port, REAL, { accept: 'text/html' })
+ expect(page.status).toBe(429)
+ expect(page.headers['content-type']).toContain('text/html')
+ expect(page.body).toMatch(/Too many attempts/)
+ })
+})
+
+describe('S4: a stranger cannot lock the owner out', () => {
+ it('five bad passwords from one client do not refuse another client', async () => {
+ const port = await serve()
+ // Behind a same-host proxy every request comes from loopback; the proxy names the client.
+ for (let i = 0; i < MAX_FAILURES; i++) await login(port, `bad${i}`, { 'x-forwarded-for': '203.0.113.66' })
+ expect((await login(port, REAL, { 'x-forwarded-for': '203.0.113.66' })).status).toBe(429)
+ const owner = await login(port, REAL, { 'x-forwarded-for': '198.51.100.7' })
+ expect(owner.status).toBe(303)
+ expect(cookieOf(owner)).toContain(`${SESSION_COOKIE}=`)
+ })
+
+ it('auth POSTs refuse a cross-site Origin (a page the owner visits cannot post the login form)', async () => {
+ const port = await serve({ publicOrigin: 'https://term.example.com' })
+ const host = `127.0.0.1:${port}`
+ for (const route of ['/auth/login', '/auth/logout', '/auth/logout-all', '/auth/setup']) {
+ expect((await request(port, 'POST', route, { origin: 'https://evil.example' }, 'password=x')).status).toBe(403)
+ expect((await request(port, 'POST', route, { origin: 'null' }, 'password=x')).status).toBe(403)
+ // No Origin, but the browser says the request is cross-site.
+ expect((await request(port, 'POST', route, { 'sec-fetch-site': 'cross-site' }, 'password=x')).status).toBe(403)
+ }
+ // Same origin by Host, or the configured public origin (a proxy that rewrites Host), passes.
+ expect((await login(port, REAL, { origin: `http://${host}` })).status).toBe(303)
+ expect((await login(port, REAL, { origin: 'https://term.example.com', host: 'internal:8443' })).status).toBe(303)
+ // A non-browser client (no Origin, no fetch metadata) still signs in.
+ expect((await login(port, REAL)).status).toBe(303)
+ // A refused cross-site post is not charged to the lockout.
+ for (let i = 0; i < MAX_FAILURES + 3; i++) {
+ await request(port, 'POST', '/auth/login', { origin: 'https://evil.example' }, 'password=x')
+ }
+ expect((await login(port, REAL)).status).toBe(303)
+ })
+})
+
+describe('S3: signing out ends the session on the server', () => {
+ it('/auth/logout deletes the presented token: the same cookie no longer works', async () => {
+ const port = await serve()
+ const cookie = cookieOf(await login(port, REAL))
+ expect((await request(port, 'GET', '/', { cookie, accept: 'application/json' })).status).toBe(200)
+ const out = await request(port, 'POST', '/auth/logout', { cookie })
+ expect(out.status).toBe(303)
+ expect(out.headers['set-cookie']?.[0]).toContain('Max-Age=0')
+ // Was 200: the token lived on in sessions.json for its whole 30-day TTL.
+ expect((await request(port, 'GET', '/', { cookie, accept: 'application/json' })).status).toBe(401)
+ })
+
+ it('/auth/logout-all signs out every browser, and needs a signed-in caller', async () => {
+ const port = await serve()
+ const a = cookieOf(await login(port, REAL))
+ const b = cookieOf(await login(port, REAL))
+ // Unauthenticated callers cannot sign everyone out.
+ expect((await request(port, 'POST', '/auth/logout-all', { accept: 'application/json' })).status).toBe(401)
+ expect((await request(port, 'GET', '/', { cookie: b, accept: 'application/json' })).status).toBe(200)
+ const out = await request(port, 'POST', '/auth/logout-all', { cookie: a })
+ expect(out.status).toBe(303)
+ expect(out.headers.location).toBe('/login')
+ for (const c of [a, b]) {
+ expect((await request(port, 'GET', '/', { cookie: c, accept: 'application/json' })).status).toBe(401)
+ }
+ })
+})
+
+describe('S5: Secure and HSTS', () => {
+ it('without NODETERM_PUBLIC_ORIGIN: Secure follows X-Forwarded-Proto, no HSTS (unchanged)', async () => {
+ const port = await serve()
+ const plain = await login(port, REAL)
+ expect(plain.headers['set-cookie']?.[0]).not.toContain('Secure')
+ expect(plain.headers['strict-transport-security']).toBeUndefined()
+ const viaProxy = await login(port, REAL, { 'x-forwarded-proto': 'https' })
+ expect(viaProxy.headers['set-cookie']?.[0]).toContain('Secure')
+ })
+
+ it('with NODETERM_PUBLIC_ORIGIN: every cookie is Secure and every response sends HSTS', async () => {
+ const port = await serve({ publicOrigin: 'https://term.example.com' })
+ const res = await login(port, REAL)
+ expect(res.headers['set-cookie']?.[0]).toContain('Secure')
+ expect(res.headers['strict-transport-security']).toBe('max-age=31536000')
+ const cookie = cookieOf(res)
+ const out = await request(port, 'POST', '/auth/logout', { cookie })
+ expect(out.headers['set-cookie']?.[0]).toContain('Secure')
+ for (const r of [
+ await request(port, 'GET', '/login'),
+ await request(port, 'GET', '/x.json'),
+ await request(port, 'GET', '/', { cookie: cookieOf(await login(port, REAL)) })
+ ]) {
+ expect(r.headers['strict-transport-security']).toBe('max-age=31536000')
+ }
+ })
+
+ it('warns once when a non-loopback Host arrives without NODETERM_PUBLIC_ORIGIN', async () => {
+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {})
+ const port = await serve()
+ await request(port, 'GET', '/login', { host: 'localhost:8443' })
+ await request(port, 'GET', '/login', { host: '127.0.0.1:8443' })
+ await request(port, 'GET', '/login', { host: '[::1]:8443' })
+ expect(warn).not.toHaveBeenCalled()
+ await request(port, 'GET', '/login', { host: 'term.example.com' })
+ await request(port, 'GET', '/login', { host: 'term.example.com' })
+ expect(warn).toHaveBeenCalledTimes(1)
+ expect(String(warn.mock.calls[0][0])).toMatch(/NODETERM_PUBLIC_ORIGIN=https:\/\/term\.example\.com/)
+ // Configured: never warns.
+ warn.mockClear()
+ const port2 = await serve({ publicOrigin: 'https://term.example.com' })
+ await request(port2, 'GET', '/login', { host: 'term.example.com' })
+ expect(warn).not.toHaveBeenCalled()
+ })
+})
+
+describe('S6: no framing, anywhere', () => {
+ it('every response says DENY / frame-ancestors none — app, login, setup, errors', async () => {
+ const port = await serve()
+ const cookie = cookieOf(await login(port, REAL))
+ const responses = [
+ await request(port, 'GET', '/', { cookie }),
+ await request(port, 'GET', '/login'),
+ await request(port, 'GET', '/setup'),
+ await request(port, 'GET', '/x.json'),
+ await request(port, 'POST', '/auth/login', {}, 'password=nope')
+ ]
+ for (const r of responses) {
+ expect(r.headers['x-frame-options']).toBe('DENY')
+ expect(String(r.headers['content-security-policy'])).toContain("frame-ancestors 'none'")
+ expect(r.headers['x-content-type-options']).toBe('nosniff')
+ }
+ // The login page keeps its own strict policy, with frame-ancestors added — one header.
+ const page = responses[1]
+ expect(page.headers['content-security-policy']).toBe(
+ "default-src 'none'; style-src 'unsafe-inline'; form-action 'self'; frame-ancestors 'none'"
+ )
+ })
+})
diff --git a/src/server/http.test.ts b/src/server/http.test.ts
index d391a682a..aebd87dd4 100644
--- a/src/server/http.test.ts
+++ b/src/server/http.test.ts
@@ -12,7 +12,8 @@ import {
_resetStaticCacheForTest,
SESSION_COOKIE
} from './http'
-import { parseTrustedNets } from './proxy-trust'
+import { parseTrustedNets, PROXY_SECRET_HEADER } from './proxy-trust'
+import { MAX_FAILURES } from './auth'
let dir: string, rendererDir: string, server: http.Server, base: string, auth: Auth
@@ -98,7 +99,9 @@ describe('http layer', () => {
it('serves static with CSP rewrite on index.html and blocks traversal', async () => {
const cookie = await setupAndLogin()
const html = await (await fetch(`${base}/`, { headers: { cookie } })).text()
- expect(html).toContain(`connect-src 'self' ws: wss:`)
+ // S6: same-origin only — a same-origin ws:/wss: URL is covered by 'self' (CSP3).
+ expect(html).toContain(`connect-src 'self';`)
+ expect(html).not.toContain('ws: wss:')
const js = await fetch(`${base}/app.js`, { headers: { cookie } })
expect(js.headers.get('content-type')).toContain('javascript')
const evil = await fetch(`${base}/..%2f..%2fauth.json`, { headers: { cookie } })
@@ -232,7 +235,7 @@ describe('http layer', () => {
)
const res = await rawGet('/', { cookie, 'accept-encoding': 'gzip' })
expect(res.headers['content-encoding']).toBe('gzip')
- expect(zlib.gunzipSync(res.body).toString('utf8')).toContain(`connect-src 'self' ws: wss:`)
+ expect(zlib.gunzipSync(res.body).toString('utf8')).toContain(`connect-src 'self';`)
})
it('re-compresses after the file changes on disk (a rebuild must not serve stale bytes)', async () => {
@@ -259,13 +262,15 @@ describe('http layer', () => {
describe('http layer with proxy header trust', () => {
const HDR = 'Cf-Access-Authenticated-User-Email'
+ const SECRET = 'q'.repeat(48)
+ const SEC = { [PROXY_SECRET_HEADER]: SECRET }
- function trustedServer(netsSpec: string): Promise<{ srv: http.Server; url: string }> {
+ function trustedServer(netsSpec: string, secret: string | undefined = SECRET): Promise<{ srv: http.Server; url: string }> {
const srv = http.createServer(
createHttpHandler({
auth,
rendererDir,
- trustProxy: { header: HDR, nets: parseTrustedNets(netsSpec) }
+ trustProxy: { header: HDR, nets: parseTrustedNets(netsSpec), ...(secret ? { secret } : {}) }
})
)
return new Promise((r) =>
@@ -275,19 +280,19 @@ describe('http layer with proxy header trust', () => {
)
}
- it('trusted peer + header: serves the app with no cookie; /login and /setup redirect home', async () => {
+ it('trusted peer + header + secret: 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]' } })
+ const home = await fetch(`${url}/`, { headers: { ...SEC, [HDR]: '[email protected]' } })
expect(home.status).toBe(200)
const login = await fetch(`${url}/login`, {
- headers: { [HDR]: '[email protected]' },
+ headers: { ...SEC, [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]' },
+ headers: { ...SEC, [HDR]: '[email protected]' },
redirect: 'manual'
})
expect(setup.status).toBe(302)
@@ -297,17 +302,40 @@ describe('http layer with proxy header trust', () => {
}
})
+ it('S2: from loopback, the header WITHOUT the secret is not an identity (any local process could send it)', async () => {
+ const { srv, url } = await trustedServer('127.0.0.0/8')
+ const { srv: srvNoSecret, url: urlNoSecret } = await trustedServer('127.0.0.0/8', undefined)
+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {})
+ try {
+ // The audit's repro: no cookie, just the header from a local process → was 200.
+ expect((await fetch(`${url}/x.json`, { headers: { [HDR]: 'anyone' }, redirect: 'manual' })).status).toBe(401)
+ expect(
+ (await fetch(`${url}/x.json`, { headers: { [HDR]: 'anyone', [PROXY_SECRET_HEADER]: 'guess' }, redirect: 'manual' }))
+ .status
+ ).toBe(401)
+ // A config with loopback nets and no secret at all trusts no loopback peer.
+ expect((await fetch(`${urlNoSecret}/x.json`, { headers: { [HDR]: 'anyone' }, redirect: 'manual' })).status).toBe(401)
+ // The refusal is logged, without the value of any header.
+ expect(warn.mock.calls.flat().join(' ')).not.toContain('anyone')
+ expect(warn.mock.calls.flat().join(' ')).not.toContain('guess')
+ } finally {
+ warn.mockRestore()
+ await new Promise((r) => srv.close(r))
+ await new Promise((r) => srvNoSecret.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: SEC, redirect: 'manual' })).status).toBe(401)
expect(
- (await fetch(`${url}/x.json`, { headers: { [HDR]: ' ' }, redirect: 'manual' })).status
+ (await fetch(`${url}/x.json`, { headers: { ...SEC, [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' }))
+ (await fetch(`${urlFar}/x.json`, { headers: { ...SEC, [HDR]: '[email protected]' }, redirect: 'manual' }))
.status
).toBe(401)
// Password/cookie auth still works beside proxy trust.
diff --git a/src/server/http.ts b/src/server/http.ts
index d1325c30d..f7f2a6819 100644
--- a/src/server/http.ts
+++ b/src/server/http.ts
@@ -7,14 +7,19 @@ import http from 'http'
import fs from 'fs'
import path from 'path'
import zlib from 'zlib'
-import type { Auth } from './auth'
-import { proxyAuthAllowed, type TrustProxyConfig } from './proxy-trust'
+import { passwordTooShort, type Auth } from './auth'
+import { noteProxyRefusal, proxyAuthDecision, type TrustProxyConfig } from './proxy-trust'
+import { loginClientKey } from './client-address'
+import { sameOriginRequest } from './origin'
import { handleDownload } from './download'
import type { DownloadTickets } from '../core/download-tickets'
export const SESSION_COOKIE = 'nt_session'
const MAX_BODY_BYTES = 10 * 1024 // 10KB POST body cap
+/** A form body that has not arrived by now is abandoned. Login attempts hold a rate-limit slot
+ * while their body is read (S1), so a client that never sends one must not hold it for long. */
+export const FORM_BODY_TIMEOUT_MS = 10_000
const CONTENT_TYPES: Record<string, string> = {
'.html': 'text/html; charset=utf-8',
@@ -29,7 +34,15 @@ const CONTENT_TYPES: Record<string, string> = {
}
// CSP served with the inline login/setup pages (no app assets, no connections).
-const PAGE_CSP = "default-src 'none'; style-src 'unsafe-inline'; form-action 'self'"
+const PAGE_CSP = "default-src 'none'; style-src 'unsafe-inline'; form-action 'self'; frame-ancestors 'none'"
+
+/** Sent on EVERY response (S6). The app's own CSP is a `<meta>`, where `frame-ancestors` is
+ * ignored, so framing has to be refused by HTTP header; a second CSP header only adds a
+ * restriction (browsers enforce each policy). The login/setup pages send PAGE_CSP instead,
+ * which carries the same directive. */
+const FRAME_CSP = "frame-ancestors 'none'"
+/** HSTS when NODETERM_PUBLIC_ORIGIN says the server is reached over https (S5). */
+const HSTS = 'max-age=31536000'
/** Types worth compressing. Everything else (png, woff2) is already compressed — running it
* through gzip only burns CPU and usually grows the payload. */
@@ -54,6 +67,12 @@ export interface HttpHandlerOpts {
/** Ticket store backing `GET /download` (Explorer file downloads). Omitted in tests that don't
* exercise it — the route then simply doesn't exist. */
downloadTickets?: DownloadTickets
+ /**
+ * NODETERM_PUBLIC_ORIGIN (an https origin, normalized). When set the session cookie is always
+ * `Secure`, every response carries HSTS, and an `Origin` equal to it passes the same-origin check
+ * even when the proxy rewrites `Host`. See config.ts.
+ */
+ publicOrigin?: string
}
/** Parse the `nt_session=` value out of a Cookie header. Exported for the WS upgrade (Task 5). */
@@ -73,18 +92,46 @@ function isHtmlNavigation(req: http.IncomingMessage): boolean {
return typeof accept === 'string' && accept.includes('text/html')
}
-function cookieAttributes(req: http.IncomingMessage): string {
+/**
+ * `Secure` is ALWAYS set when the operator declared an https public origin. Without one it follows
+ * `X-Forwarded-Proto` as before (S5): a client can only use that header against itself, but a
+ * proxy that does not send it silently loses `Secure` — hence the boot/first-request warning.
+ */
+function cookieAttributes(req: http.IncomingMessage, publicOrigin: string | undefined): string {
let attrs = `HttpOnly; SameSite=Strict; Path=/`
- if (req.headers['x-forwarded-proto'] === 'https') attrs += '; Secure'
+ if (publicOrigin !== undefined || req.headers['x-forwarded-proto'] === 'https') attrs += '; Secure'
return attrs
}
-function setSessionCookie(req: http.IncomingMessage, res: http.ServerResponse, token: string): void {
- res.setHeader('Set-Cookie', `${SESSION_COOKIE}=${token}; ${cookieAttributes(req)}`)
+function setSessionCookie(
+ req: http.IncomingMessage,
+ res: http.ServerResponse,
+ token: string,
+ publicOrigin: string | undefined
+): void {
+ res.setHeader('Set-Cookie', `${SESSION_COOKIE}=${token}; ${cookieAttributes(req, publicOrigin)}`)
+}
+
+function clearSessionCookie(
+ req: http.IncomingMessage,
+ res: http.ServerResponse,
+ publicOrigin: string | undefined
+): void {
+ res.setHeader('Set-Cookie', `${SESSION_COOKIE}=; Max-Age=0; ${cookieAttributes(req, publicOrigin)}`)
+}
+
+/** Is this `Host` header one of this machine's loopback names (no warning needed for it)? */
+function isLoopbackHost(host: string | undefined): boolean {
+ if (!host) return true
+ let name = host.toLowerCase()
+ if (name.startsWith('[')) name = name.slice(1, name.indexOf(']') === -1 ? undefined : name.indexOf(']'))
+ else if (name.lastIndexOf(':') !== -1 && name.indexOf(':') === name.lastIndexOf(':')) name = name.slice(0, name.lastIndexOf(':'))
+ return name === 'localhost' || name.endsWith('.localhost') || name === '::1' || /^127(\.\d{1,3}){3}$/.test(name)
}
-function clearSessionCookie(req: http.IncomingMessage, res: http.ServerResponse): void {
- res.setHeader('Set-Cookie', `${SESSION_COOKIE}=; Max-Age=0; ${cookieAttributes(req)}`)
+/** A `Host` value safe to print: hostname characters only, capped. */
+function printableHost(host: string): string {
+ return host.replace(/[^A-Za-z0-9.:\-[\]]/g, '').slice(0, 100)
}
function redirect(res: http.ServerResponse, status: number, location: string): void {
@@ -98,8 +145,9 @@ function sendJson(res: http.ServerResponse, status: number, body: unknown): void
res.end(s)
}
-function sendPage(res: http.ServerResponse, status: number, html: string): void {
+function sendPage(res: http.ServerResponse, status: number, html: string, extra: http.OutgoingHttpHeaders = {}): void {
res.writeHead(status, {
+ ...extra,
'Content-Type': 'text/html; charset=utf-8',
'Content-Security-Policy': PAGE_CSP,
'X-Content-Type-Options': 'nosniff'
@@ -107,29 +155,45 @@ function sendPage(res: http.ServerResponse, status: number, html: string): void
res.end(html)
}
-/** Read a form-encoded POST body (capped) and decode into URLSearchParams. */
+/** Read a form-encoded POST body (capped, and abandoned after FORM_BODY_TIMEOUT_MS) and decode
+ * into URLSearchParams. */
function readForm(req: http.IncomingMessage): Promise<URLSearchParams> {
return new Promise((resolve, reject) => {
const chunks: Buffer[] = []
let size = 0
let aborted = false
+ const abort = (err: Error): void => {
+ if (aborted) return
+ aborted = true
+ clearTimeout(timer)
+ reject(err)
+ req.destroy()
+ }
+ const timer = setTimeout(() => abort(new Error('body timeout')), FORM_BODY_TIMEOUT_MS)
+ if (timer.unref) timer.unref()
req.on('data', (chunk: Buffer) => {
if (aborted) return
size += chunk.length
if (size > MAX_BODY_BYTES) {
- aborted = true
- reject(new Error('body too large'))
- req.destroy()
+ abort(new Error('body too large'))
return
}
chunks.push(chunk)
})
req.on('end', () => {
if (aborted) return
+ clearTimeout(timer)
resolve(new URLSearchParams(Buffer.concat(chunks).toString('utf8')))
})
req.on('error', (err) => {
- if (!aborted) reject(err)
+ if (aborted) return
+ aborted = true
+ clearTimeout(timer)
+ reject(err)
+ })
+ // A client that hangs up before the body is complete fires neither 'end' nor 'error'.
+ req.on('close', () => {
+ if (!aborted && !req.complete) abort(new Error('client closed'))
})
})
}
@@ -155,8 +219,13 @@ const H1_STYLE = 'margin:0 0 4px;font-size:18px;font-weight:600'
const SUB_STYLE = 'margin:0 0 16px;font-size:13px;color:#9aa0a6'
const ERR_STYLE = 'margin:0 0 12px;font-size:13px;color:#f26d6d'
-function loginPage(hasError: boolean): string {
- const errLine = hasError ? `<p style="${ERR_STYLE}">Wrong password. Try again.</p>` : ''
+function loginPage(error: 'wrong' | { retryAfterMs: number } | null): string {
+ const errLine =
+ error === 'wrong'
+ ? `<p style="${ERR_STYLE}">Wrong password. Try again.</p>`
+ : error !== null
+ ? `<p style="${ERR_STYLE}">Too many attempts. Try again in ${Math.max(1, Math.ceil(error.retryAfterMs / 60_000))} minute${Math.ceil(error.retryAfterMs / 60_000) > 1 ? 's' : ''}.</p>`
+ : ''
return `<!doctype html><html><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>Sign in — nodeterm</title></head><body style="${PAGE_STYLE}"><form method="post" action="/auth/login" style="${CARD_STYLE}"><h1 style="${H1_STYLE}">nodeterm</h1><p style="${SUB_STYLE}">Sign in to continue</p>${errLine}<input style="${INPUT_STYLE}" type="password" name="password" placeholder="Password" autofocus autocomplete="current-password"><button style="${BUTTON_STYLE}" type="submit">Sign in</button></form></body></html>`
}
@@ -330,7 +399,9 @@ async function serveStatic(
const identity = async (): Promise<Buffer> => {
const raw = await fs.promises.readFile(filePath)
- // CSP rewrite ONLY on index.html: relax connect-src so the WS client can connect.
+ // CSP rewrite ONLY on index.html: give the WS client a connect-src. `'self'` covers a
+ // same-origin ws:/wss: URL (CSP3 matches ws↔http and wss↔https for 'self'), which is the only
+ // socket the bridge opens — `ws: wss:` allowed a socket to ANY host (S6).
if (!isIndex) return raw
const html = raw.toString('utf8')
const marker = "default-src 'self';"
@@ -339,11 +410,11 @@ async function serveStatic(
// would block the ws:/wss: WebSocket with no visible error — make sure an
// operator sees this in the server logs.
console.warn(
- "[nodeterm-server] index.html CSP did not contain the expected `default-src 'self';` marker — the ws: connect-src rewrite did not apply; the browser will block the WebSocket. Rebuild the renderer or update the rewrite."
+ "[nodeterm-server] index.html CSP did not contain the expected `default-src 'self';` marker — the connect-src rewrite did not apply; the browser will block the WebSocket. Rebuild the renderer or update the rewrite."
)
return raw
}
- return Buffer.from(html.replace(marker, "default-src 'self'; connect-src 'self' ws: wss:;"))
+ return Buffer.from(html.replace(marker, "default-src 'self'; connect-src 'self';"))
}
const enc =
@@ -373,7 +444,8 @@ async function serveStatic(
export function createHttpHandler(
opts: HttpHandlerOpts
): (req: http.IncomingMessage, res: http.ServerResponse) => void {
- const { auth, rendererDir, trustProxy, downloadTickets } = opts
+ const { auth, rendererDir, trustProxy, downloadTickets, publicOrigin } = opts
+ let warnedNoPublicOrigin = false
return function handler(req: http.IncomingMessage, res: http.ServerResponse): void {
void handle(req, res).catch(() => {
@@ -382,13 +454,39 @@ export function createHttpHandler(
})
}
+ /** A refused login: 429 with Retry-After — a page for a browser, JSON otherwise. */
+ function sendTooMany(req: http.IncomingMessage, res: http.ServerResponse, retryAfterMs: number): void {
+ const retryAfter = String(Math.max(1, Math.ceil(retryAfterMs / 1000)))
+ if (isHtmlNavigation(req)) {
+ sendPage(res, 429, loginPage({ retryAfterMs }), { 'Retry-After': retryAfter })
+ return
+ }
+ res.writeHead(429, { 'Content-Type': 'application/json; charset=utf-8', 'Retry-After': retryAfter })
+ res.end(JSON.stringify({ error: 'too_many_attempts' }))
+ }
+
async function handle(req: http.IncomingMessage, res: http.ServerResponse): Promise<void> {
const url = new URL(req.url || '/', 'http://x')
const pathname = url.pathname
const method = req.method || 'GET'
- const proxyAuthed =
- trustProxy !== undefined && proxyAuthAllowed(trustProxy, req.headers, req.socket.remoteAddress)
+ // Every response, before any route can answer (S6, S5).
+ res.setHeader('X-Frame-Options', 'DENY')
+ res.setHeader('Content-Security-Policy', FRAME_CSP)
+ res.setHeader('X-Content-Type-Options', 'nosniff')
+ if (publicOrigin !== undefined) res.setHeader('Strict-Transport-Security', HSTS)
+ else if (!warnedNoPublicOrigin && !isLoopbackHost(req.headers['host'])) {
+ warnedNoPublicOrigin = true
+ const host = printableHost(req.headers['host'] ?? '')
+ console.warn(
+ `[nodeterm-server] requests are arriving for "${host}" but NODETERM_PUBLIC_ORIGIN is not set: the session cookie is marked Secure only when your proxy sends X-Forwarded-Proto: https, and no HSTS header is sent. Set NODETERM_PUBLIC_ORIGIN=https://${host} (the address you open in the browser). See docs/SERVER.md.`
+ )
+ }
+
+ const decision =
+ trustProxy !== undefined ? proxyAuthDecision(trustProxy, req.headers, req.socket.remoteAddress) : 'none'
+ noteProxyRefusal(decision)
+ const proxyAuthed = decision === 'trusted'
// A proxy-authed caller has no use for the password pages — send them home.
if (proxyAuthed && method === 'GET' && (pathname === '/login' || pathname === '/setup')) {
@@ -396,6 +494,14 @@ export function createHttpHandler(
return
}
+ // Every auth POST changes who is signed in, so a cross-site page must not be able to send one
+ // (login CSRF, forced logout, and — before S4 — locking the owner out from a page they visit).
+ // Refused BEFORE any rate-limit slot is taken, so a refused post costs the lockout nothing.
+ if (method === 'POST' && pathname.startsWith('/auth/') && !sameOriginRequest(req.headers, publicOrigin)) {
+ sendJson(res, 403, { error: 'cross_origin' })
+ return
+ }
+
// ---- Public auth routes (no session required) --------------------------
if (pathname === '/setup' && method === 'GET') {
@@ -420,7 +526,7 @@ export function createHttpHandler(
redirect(res, 302, '/setup')
return
}
- sendPage(res, 200, loginPage(url.searchParams.has('error')))
+ sendPage(res, 200, loginPage(url.searchParams.has('error') ? 'wrong' : null))
return
}
@@ -440,51 +546,82 @@ export function createHttpHandler(
}
const token = form.get('token') || ''
const password = form.get('password') || ''
- if (password.length < 8 || !auth.consumeSetupToken(token)) {
+ if (passwordTooShort(password) || !auth.consumeSetupToken(token)) {
sendJson(res, 403, { error: 'invalid_setup' })
return
}
auth.setPassword(password)
const session = auth.createSession()
- setSessionCookie(req, res, session)
+ setSessionCookie(req, res, session, publicOrigin)
redirect(res, 303, '/')
return
}
if (pathname === '/auth/login' && method === 'POST') {
- if (!auth.loginAllowed()) {
- sendJson(res, 429, { error: 'too_many_attempts' })
+ // Reserve the attempt BEFORE reading the body (S1): the old check-then-read-then-charge let
+ // every request whose body was held back pass the gate while the counter was still zero.
+ const gate = auth.beginLoginAttempt(
+ loginClientKey(req.socket.remoteAddress, req.headers['x-forwarded-for'], trustProxy)
+ )
+ if (!gate.ok) {
+ sendTooMany(req, res, gate.retryAfterMs)
return
}
let form: URLSearchParams
try {
form = await readForm(req)
} catch {
+ gate.finish('abandoned')
sendJson(res, 400, { error: 'bad_request' })
return
}
const password = form.get('password') || ''
- if (auth.verifyPassword(password)) {
- auth.recordLoginSuccess()
+ let ok: boolean
+ try {
+ ok = await auth.verifyPasswordAsync(password)
+ } catch (err) {
+ gate.finish('abandoned')
+ throw err
+ }
+ if (ok) {
+ gate.finish('success')
const session = auth.createSession()
- setSessionCookie(req, res, session)
+ setSessionCookie(req, res, session, publicOrigin)
redirect(res, 303, '/')
return
}
- auth.recordLoginFailure()
+ gate.finish('failure')
redirect(res, 303, '/login?error=1')
return
}
if (pathname === '/auth/logout' && method === 'POST') {
- clearSessionCookie(req, res)
+ // Sign out THIS browser: the token it presented is deleted on the server (S3), so a copy of
+ // the cookie stops working too — clearing the cookie alone left it valid for 30 days.
+ const presented = sessionTokenFromCookie(req.headers['cookie'])
+ if (presented) auth.revokeSession(presented)
+ clearSessionCookie(req, res, publicOrigin)
+ redirect(res, 303, '/login')
+ return
+ }
+
+ const token = sessionTokenFromCookie(req.headers['cookie'])
+
+ if (pathname === '/auth/logout-all' && method === 'POST') {
+ // Sign out EVERY browser (S3). Only a signed-in caller may, or anyone could log the owner out.
+ if (!proxyAuthed && !auth.validateSession(token)) {
+ if (isHtmlNavigation(req)) redirect(res, 303, '/login')
+ else sendJson(res, 401, { error: 'unauthorized' })
+ return
+ }
+ auth.revokeAll()
+ clearSessionCookie(req, res, publicOrigin)
redirect(res, 303, '/login')
return
}
// ---- Everything else requires a valid session --------------------------
- const token = sessionTokenFromCookie(req.headers['cookie'])
if (!proxyAuthed && !auth.validateSession(token)) {
if (isHtmlNavigation(req)) redirect(res, 302, '/login')
else sendJson(res, 401, { error: 'unauthorized' })
diff --git a/src/server/index.ts b/src/server/index.ts
index 8a2498c26..c47415a96 100644
--- a/src/server/index.ts
+++ b/src/server/index.ts
@@ -10,7 +10,7 @@ import { ServerPlatform } from './platform-server'
import { Auth } from './auth'
import { createHttpHandler } from './http'
import { attachWsServer } from './ws'
-import { describeTrustedNets } from './proxy-trust'
+import { authBootMessages } from './auth-boot-messages'
import type { ServerConfig } from './config'
import { initPlatform } from '../core/platform'
@@ -232,15 +232,13 @@ 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.`
- )
+ // Loud on purpose: these lines are the operator's one chance to notice a sign-in
+ // misconfiguration (header trust refused for want of a secret, nets wider than the proxy's own
+ // subnet, a short seeded password). See auth-boot-messages.ts.
+ {
+ const { errors, notices } = authBootMessages(config)
+ for (const line of errors) console.error(line)
+ for (const line of notices) console.log(line)
}
if (!config.headless && !auth.isConfigured()) {
// No password set yet: print the one-time setup URL so the operator can bootstrap.
@@ -1234,6 +1232,7 @@ export async function startServer(
auth,
rendererDir: config.rendererDir,
trustProxy: config.trustProxy,
+ publicOrigin: config.publicOrigin,
downloadTickets
})
)
@@ -1243,7 +1242,8 @@ export async function startServer(
platform,
auth,
onClientGone: dropUiClient,
- trustProxy: config.trustProxy
+ trustProxy: config.trustProxy,
+ publicOrigin: config.publicOrigin
})
await new Promise<void>((resolve, reject) => {
diff --git a/src/server/origin.ts b/src/server/origin.ts
new file mode 100644
index 000000000..67196226e
--- /dev/null
+++ b/src/server/origin.ts
@@ -0,0 +1,30 @@
+// Same-origin checks for the Server Edition's state-changing entry points: the auth POSTs
+// (/auth/login, /auth/logout, /auth/logout-all, /auth/setup) and the WebSocket upgrade.
+//
+// One rule for both, so they cannot drift (security audit 2026-10, S4):
+// - An `Origin` header, when present, must name this server: its host equals the request's `Host`
+// (what the WebSocket check has always required — so any deployment whose app works passes it),
+// or it equals NODETERM_PUBLIC_ORIGIN when that is set (a proxy that rewrites `Host`).
+// `Origin: null` (sandboxed frames, opaque redirects) and a malformed value are refused.
+// - No `Origin`: browsers always send one on a POST and on a WebSocket handshake, so its absence
+// means a non-browser client (curl, a script, the tests), which a cross-site page cannot be.
+// The one exception is a browser that says so itself: `Sec-Fetch-Site: cross-site` or
+// `same-site` is refused. Absent fetch metadata is allowed — older browsers do not send it.
+import type http from 'http'
+
+export function sameOriginRequest(headers: http.IncomingHttpHeaders, publicOrigin?: string): boolean {
+ const origin = headers['origin']
+ if (typeof origin === 'string' && origin.length > 0) {
+ if (origin === 'null') return false
+ let url: URL
+ try {
+ url = new URL(origin)
+ } catch {
+ return false
+ }
+ if (publicOrigin !== undefined && url.origin === publicOrigin) return true
+ return url.host === headers['host']
+ }
+ const site = headers['sec-fetch-site']
+ return !(site === 'cross-site' || site === 'same-site')
+}
diff --git a/src/server/proxy-trust.test.ts b/src/server/proxy-trust.test.ts
index dc59138b1..25cd723d4 100644
--- a/src/server/proxy-trust.test.ts
+++ b/src/server/proxy-trust.test.ts
@@ -5,6 +5,9 @@ import {
proxyAuthAllowed,
describeTrustedNets,
DEFAULT_TRUSTED_NETS_SPEC,
+ PROXY_SECRET_HEADER,
+ netsCoverLoopback,
+ proxyAuthDecision,
type TrustProxyConfig
} from './proxy-trust'
@@ -69,30 +72,35 @@ describe('isTrustedAddress', () => {
})
describe('proxyAuthAllowed', () => {
+ // Loopback nets carry a secret (a loopback config without one is refused at boot AND here —
+ // see the S2 block below), so the plain trusted-peer cases run with the secret header present.
+ const SECRET = 's'.repeat(40)
const trust: TrustProxyConfig = {
header: 'Cf-Access-Authenticated-User-Email',
- nets: parseTrustedNets('127.0.0.0/8')
+ nets: parseTrustedNets('127.0.0.0/8'),
+ secret: SECRET
}
+ const sec = { [PROXY_SECRET_HEADER]: SECRET }
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')
+ proxyAuthAllowed(trust, { ...sec, '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, { ...sec }, '127.0.0.1')).toBe(false)
expect(
- proxyAuthAllowed(trust, { 'cf-access-authenticated-user-email': '' }, '127.0.0.1')
+ proxyAuthAllowed(trust, { ...sec, 'cf-access-authenticated-user-email': '' }, '127.0.0.1')
).toBe(false)
expect(
- proxyAuthAllowed(trust, { 'cf-access-authenticated-user-email': ' ' }, '127.0.0.1')
+ proxyAuthAllowed(trust, { ...sec, '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')
+ proxyAuthAllowed(trust, { ...sec, 'cf-access-authenticated-user-email': '[email protected]' }, '10.0.0.5')
).toBe(false)
})
@@ -100,7 +108,7 @@ describe('proxyAuthAllowed', () => {
expect(
proxyAuthAllowed(
trust,
- { 'cf-access-authenticated-user-email': ['[email protected]', '[email protected]'] as unknown as string },
+ { ...sec, 'cf-access-authenticated-user-email': ['[email protected]', '[email protected]'] as unknown as string },
'127.0.0.1'
)
).toBe(false)
@@ -115,3 +123,58 @@ describe('describeTrustedNets', () => {
expect(describeTrustedNets(parseTrustedNets('::1'))).toBe('0:0:0:0:0:0:0:1/128')
})
})
+
+// S2 (security audit 2026-10): on loopback every local process — every Unix account, container on
+// the host network, sandboxed agent — is "a peer in the trusted nets", so the identity header alone
+// made any of them the server's owner. A shared secret the proxy adds is what tells them apart.
+describe('proxy secret (S2)', () => {
+ const HDR = 'X-Forwarded-User'
+ const SECRET = 'a1b2c3d4'.repeat(5)
+
+ it('netsCoverLoopback: true for any net that holds a loopback address, IPv4 or IPv6', () => {
+ expect(netsCoverLoopback(parseTrustedNets(DEFAULT_TRUSTED_NETS_SPEC))).toBe(true)
+ expect(netsCoverLoopback(parseTrustedNets('127.0.0.1'))).toBe(true)
+ expect(netsCoverLoopback(parseTrustedNets('127.9.0.0/16'))).toBe(true)
+ expect(netsCoverLoopback(parseTrustedNets('::1'))).toBe(true)
+ // Wider nets that CONTAIN loopback count too — 0.0.0.0/0 trusts every local process as well.
+ expect(netsCoverLoopback(parseTrustedNets('0.0.0.0/0'))).toBe(true)
+ expect(netsCoverLoopback(parseTrustedNets('96.0.0.0/3'))).toBe(true)
+ expect(netsCoverLoopback(parseTrustedNets('::/0'))).toBe(true)
+ expect(netsCoverLoopback(parseTrustedNets('10.0.0.0/8, 192.168.0.0/16'))).toBe(false)
+ expect(netsCoverLoopback(parseTrustedNets('128.0.0.0/1'))).toBe(false)
+ expect(netsCoverLoopback(parseTrustedNets('fd00::/8, ::2'))).toBe(false)
+ })
+
+ it('with a secret: the header counts only when X-Nodeterm-Proxy-Secret matches exactly', () => {
+ const trust: TrustProxyConfig = { header: HDR, nets: parseTrustedNets('10.0.0.0/8'), secret: SECRET }
+ const id = { 'x-forwarded-user': 'dev' }
+ expect(proxyAuthDecision(trust, { ...id, [PROXY_SECRET_HEADER]: SECRET }, '10.1.2.3')).toBe('trusted')
+ expect(proxyAuthDecision(trust, { ...id }, '10.1.2.3')).toBe('bad-secret')
+ expect(proxyAuthDecision(trust, { ...id, [PROXY_SECRET_HEADER]: SECRET + 'x' }, '10.1.2.3')).toBe('bad-secret')
+ expect(proxyAuthDecision(trust, { ...id, [PROXY_SECRET_HEADER]: SECRET.slice(1) }, '10.1.2.3')).toBe('bad-secret')
+ expect(proxyAuthDecision(trust, { ...id, [PROXY_SECRET_HEADER]: '' }, '10.1.2.3')).toBe('bad-secret')
+ // A repeated header is ambiguous: refused, like a repeated identity header.
+ expect(
+ proxyAuthDecision(trust, { ...id, [PROXY_SECRET_HEADER]: [SECRET, SECRET] as unknown as string }, '10.1.2.3')
+ ).toBe('bad-secret')
+ // The secret alone, with no identity, is not an identity.
+ expect(proxyAuthDecision(trust, { [PROXY_SECRET_HEADER]: SECRET }, '10.1.2.3')).toBe('none')
+ // Outside the nets the secret means nothing either.
+ expect(proxyAuthDecision(trust, { ...id, [PROXY_SECRET_HEADER]: SECRET }, '11.0.0.1')).toBe('none')
+ expect(proxyAuthAllowed(trust, { ...id, [PROXY_SECRET_HEADER]: SECRET }, '10.1.2.3')).toBe(true)
+ expect(proxyAuthAllowed(trust, { ...id }, '10.1.2.3')).toBe(false)
+ })
+
+ it('without a secret: a LOOPBACK peer is never header-trusted, whatever the nets say', () => {
+ // resolveConfig already turns header trust off for loopback nets with no secret; this is the
+ // same rule at the decision point, so a config built any other way cannot reopen the hole.
+ const wide: TrustProxyConfig = { header: HDR, nets: parseTrustedNets('0.0.0.0/0, ::/0') }
+ const id = { 'x-forwarded-user': 'dev' }
+ expect(proxyAuthDecision(wide, id, '127.0.0.1')).toBe('loopback-needs-secret')
+ expect(proxyAuthDecision(wide, id, '::ffff:127.0.0.1')).toBe('loopback-needs-secret')
+ expect(proxyAuthDecision(wide, id, '::1')).toBe('loopback-needs-secret')
+ expect(proxyAuthAllowed(wide, id, '127.0.0.1')).toBe(false)
+ // A non-loopback peer in the nets keeps today's behaviour (header alone) — the boot warns.
+ expect(proxyAuthDecision(wide, id, '10.0.0.7')).toBe('trusted')
+ })
+})
diff --git a/src/server/proxy-trust.ts b/src/server/proxy-trust.ts
index 21497de2d..02b3b861b 100644
--- a/src/server/proxy-trust.ts
+++ b/src/server/proxy-trust.ts
@@ -4,10 +4,20 @@
// 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.
+// the configured header with a non-empty value AND — when a proxy secret is configured —
+// the `X-Nodeterm-Proxy-Secret` header equal to it. The identity header's CONTENT is
+// deliberately not validated (no JWT verification).
+//
+// Why the secret (security audit 2026-10, S2): the trusted-network boundary is a statement
+// about WHO can be the TCP peer, and on loopback the answer is "every process on this host" —
+// every Unix account, every container on the host network, every sandboxed agent. With the
+// default loopback nets the header alone made any of them the server's owner. So a peer on
+// loopback is never header-trusted without the secret: `resolveConfig` turns header trust OFF
+// for loopback nets with no secret (and says so at boot), and `proxyAuthDecision` refuses a
+// loopback peer without one, so a config built any other way cannot reopen it.
+//
// Everything here is pure (no node:http import) so it unit-tests without sockets.
+import crypto from 'crypto'
export interface TrustedNet {
/** 4 bytes (IPv4) or 16 bytes (IPv6). */
@@ -19,11 +29,24 @@ export interface TrustProxyConfig {
/** Header name asserting the authenticated identity, e.g. Cf-Access-Authenticated-User-Email. */
header: string
nets: TrustedNet[]
+ /**
+ * The shared secret the proxy sends in {@link PROXY_SECRET_HEADER} on every request (HTTP and the
+ * WebSocket upgrade). Set from `NODETERM_TRUST_PROXY_SECRET` only — never a CLI flag, because argv
+ * is readable by every local user. Never logged. Required when the nets cover loopback.
+ */
+ secret?: string
}
/** Default trusted networks: loopback only — the recommended same-host proxy deployment. */
export const DEFAULT_TRUSTED_NETS_SPEC = '127.0.0.0/8, ::1/128'
+/** The request header the proxy carries the shared secret in (lower-case: Node's header map). */
+export const PROXY_SECRET_HEADER = 'x-nodeterm-proxy-secret'
+
+/** A secret shorter than this is refused at boot: every request is a guess and nothing rate-limits
+ * header trust, so the secret has to be long enough not to be guessable. */
+export const MIN_PROXY_SECRET_LENGTH = 32
+
function parseIPv4(s: string): Uint8Array | null {
const parts = s.split('.')
if (parts.length !== 4) return null
@@ -130,6 +153,51 @@ export function describeTrustedNets(nets: TrustedNet[]): string {
.join(', ')
}
+const LOOPBACK_V4: TrustedNet = { bytes: new Uint8Array([127, 0, 0, 0]), prefix: 8 }
+const LOOPBACK_V6 = (() => {
+ const b = new Uint8Array(16)
+ b[15] = 1
+ return b
+})()
+
+/**
+ * Does any of these nets hold a loopback address (127.0.0.0/8 or ::1)? A net that merely CONTAINS
+ * loopback (0.0.0.0/0, ::/0) counts: it trusts every local process just the same.
+ */
+export function netsCoverLoopback(nets: TrustedNet[]): boolean {
+ return nets.some((net) => {
+ if (net.bytes.length === 4) {
+ // Two IPv4 prefixes overlap iff they agree on the shorter prefix's bits.
+ const shorter = Math.min(net.prefix, LOOPBACK_V4.prefix)
+ return matchesNet(LOOPBACK_V4.bytes, { bytes: net.bytes, prefix: shorter })
+ }
+ return matchesNet(LOOPBACK_V6, net)
+ })
+}
+
+/** Is this peer address a loopback address (127.0.0.0/8, ::1, or ::ffff:127.x)? */
+export function isLoopbackAddress(addr: string | undefined): boolean {
+ if (!addr) return false
+ const parsed = parseAddress(addr)
+ if (!parsed) return false
+ const norm = normalize(parsed)
+ return norm.length === 4 ? norm[0] === 127 : matchesNet(norm, { bytes: LOOPBACK_V6, prefix: 128 })
+}
+
+/** Parse a peer address into bytes, an IPv4-mapped IPv6 address collapsed to IPv4. Null on garbage. */
+export function parsePeerAddress(addr: string | undefined): Uint8Array | null {
+ if (!addr) return null
+ const parsed = parseAddress(addr)
+ return parsed ? normalize(parsed) : null
+}
+
+/** Constant-time equality of two strings (hash first, so the lengths do not leak either). */
+function secretMatches(candidate: string, secret: string): boolean {
+ const a = crypto.createHash('sha256').update(candidate, 'utf8').digest()
+ const b = crypto.createHash('sha256').update(secret, 'utf8').digest()
+ return crypto.timingSafeEqual(a, b)
+}
+
/** 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
@@ -140,16 +208,66 @@ export function isTrustedAddress(addr: string | undefined, nets: TrustedNet[]):
}
/**
- * 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.
+ * Why a request is or is not header-trusted:
+ * - `trusted`: trusted peer, identity header present, and the secret (when configured) matches;
+ * - `none`: not a header-trust request at all (peer outside the nets, or no identity header);
+ * - `bad-secret`: a trusted peer sent the identity header but not the configured secret — the
+ * case worth a (throttled, value-free) log line, since it usually means the proxy is missing
+ * its `X-Nodeterm-Proxy-Secret` setting;
+ * - `loopback-needs-secret`: a loopback peer, and no secret is configured at all (see the header).
+ * Every answer but `trusted` falls through to the normal cookie/login path.
+ */
+export type ProxyAuthDecision = 'trusted' | 'none' | 'bad-secret' | 'loopback-needs-secret'
+
+/**
+ * The one auth decision. `headers` is Node's lowercased header map; a repeated header (array
+ * value) is ambiguous and rejected — fail closed.
*/
+export function proxyAuthDecision(
+ trust: TrustProxyConfig,
+ headers: Record<string, string | string[] | undefined>,
+ remoteAddress: string | undefined
+): ProxyAuthDecision {
+ if (!isTrustedAddress(remoteAddress, trust.nets)) return 'none'
+ const value = headers[trust.header.toLowerCase()]
+ if (typeof value !== 'string' || value.trim() === '') return 'none'
+ if (trust.secret === undefined || trust.secret === '') {
+ return isLoopbackAddress(remoteAddress) ? 'loopback-needs-secret' : 'trusted'
+ }
+ const presented = headers[PROXY_SECRET_HEADER]
+ if (typeof presented !== 'string' || !secretMatches(presented, trust.secret)) return 'bad-secret'
+ return 'trusted'
+}
+
+/** {@link proxyAuthDecision} as a yes/no. */
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() !== ''
+ return proxyAuthDecision(trust, headers, remoteAddress) === 'trusted'
+}
+
+const REFUSED_LOG_EVERY_MS = 60_000
+let lastRefusedLog = 0
+
+/**
+ * Log — at most once a minute, and never with any header VALUE — that a trusted peer sent the
+ * identity header but header trust was refused. Without it an operator whose proxy forgot the
+ * secret only sees the login page and no reason.
+ */
+export function noteProxyRefusal(decision: ProxyAuthDecision, now = Date.now()): void {
+ if (decision !== 'bad-secret' && decision !== 'loopback-needs-secret') return
+ if (now - lastRefusedLog < REFUSED_LOG_EVERY_MS) return
+ lastRefusedLog = now
+ console.warn(
+ decision === 'bad-secret'
+ ? `[nodeterm-server] a request from a trusted proxy address carried the identity header but no matching ${PROXY_SECRET_HEADER} header; it was treated as signed out. Check that your proxy sends the secret on every request, WebSocket upgrades included.`
+ : `[nodeterm-server] a loopback request carried the identity header, but header trust from loopback needs NODETERM_TRUST_PROXY_SECRET; it was treated as signed out.`
+ )
+}
+
+/** Test seam: forget when the refusal line was last logged. */
+export function _resetProxyRefusalLogForTest(): void {
+ lastRefusedLog = 0
}
diff --git a/src/server/ws.test.ts b/src/server/ws.test.ts
index 35f2f2102..cab60f052 100644
--- a/src/server/ws.test.ts
+++ b/src/server/ws.test.ts
@@ -1,4 +1,4 @@
-import { describe, it, expect, beforeEach, afterEach } from 'vitest'
+import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest'
import http from 'http'
import fs from 'fs'
import os from 'os'
@@ -6,9 +6,9 @@ import path from 'path'
import WebSocket from 'ws'
import { Auth } from './auth'
import { ServerPlatform } from './platform-server'
-import { attachWsServer, WS_MAX_PAYLOAD } from './ws'
+import { attachWsServer, WS_MAX_PAYLOAD, WS_CLOSE_SIGNED_OUT } from './ws'
import { SESSION_COOKIE } from './http'
-import { parseTrustedNets } from './proxy-trust'
+import { parseTrustedNets, PROXY_SECRET_HEADER } from './proxy-trust'
import { initPlatform, resetPlatformForTests } from '../core/platform'
import { presenceHub } from '../core/presence/hub'
import { IPC } from '../shared/ipc'
@@ -201,14 +201,15 @@ 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 () => {
+ it('proxy header trust: upgrade allowed via trusted header + secret, still origin-checked (S2)', async () => {
const HDR = 'Tailscale-User-Login'
- const mk = async (netsSpec: string): Promise<{ srv: http.Server; p: number }> => {
+ const SECRET = 'w'.repeat(40)
+ const mk = async (netsSpec: string, secret?: 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) }
+ trustProxy: { header: HDR, nets: parseTrustedNets(netsSpec), ...(secret ? { secret } : {}) }
})
await new Promise<void>((r) => srv.listen(0, '127.0.0.1', r))
return { srv, p: (srv.address() as { port: number }).port }
@@ -221,28 +222,143 @@ describe('ws endpoint', () => {
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')
+ const { srv, p: pTrusted } = await mk('127.0.0.0/8', SECRET)
+ const { srv: srvBare, p: pBare } = await mk('127.0.0.0/8')
+ const { srv: srvFar, p: pFar } = await mk('10.0.0.0/8', SECRET)
+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {})
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}` })
+ const sec = { [PROXY_SECRET_HEADER]: SECRET }
+ // No cookie, trusted peer + header + secret → accepted (same-host Origin passes the origin check).
+ const ok = await dial(pTrusted, { ...sec, [HDR]: 'dev@corp', origin: `http://127.0.0.1:${pTrusted}` })
expect(ok.readyState).toBe(WebSocket.OPEN)
+ // S2, the audit's repro: a local process with the header and no secret → was accepted as OWNER.
+ await expect(dial(pTrusted, { [HDR]: 'x' })).rejects.toThrow()
+ await expect(dial(pTrusted, { [HDR]: 'x', [PROXY_SECRET_HEADER]: 'nope' })).rejects.toThrow()
+ await expect(dial(pBare, { [HDR]: 'x' })).rejects.toThrow()
// Cross-site Origin is still rejected even when proxy-authed.
await expect(
- dial(pTrusted, { [HDR]: 'dev@corp', origin: 'https://evil.example.com' })
+ dial(pTrusted, { ...sec, [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()
+ await expect(dial(pFar, { ...sec, [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)
+ expect(warn.mock.calls.flat().join(' ')).not.toContain('nope')
for (const ws of sockets) ws.terminate()
sockets = []
await until(() => presenceHub.peers().length === 0, 'trust-test peers drain')
} finally {
+ warn.mockRestore()
await new Promise((r) => srv.close(r))
+ await new Promise((r) => srvBare.close(r))
await new Promise((r) => srvFar.close(r))
}
+ }, 30_000)
+
+ it('NODETERM_PUBLIC_ORIGIN: an Origin equal to it passes even when the proxy rewrote Host', async () => {
+ const srv = http.createServer((_q, s2) => { s2.statusCode = 404; s2.end() })
+ attachWsServer(srv, { platform, auth, publicOrigin: 'https://term.example.com' })
+ await new Promise<void>((r) => srv.listen(0, '127.0.0.1', r))
+ const p2 = (srv.address() as { port: number }).port
+ const dial = (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)
+ })
+ try {
+ const ok = await dial({ cookie, origin: 'https://term.example.com' })
+ expect(ok.readyState).toBe(WebSocket.OPEN)
+ await expect(dial({ cookie, origin: 'https://evil.example.com' })).rejects.toThrow()
+ for (const ws of sockets) ws.terminate()
+ sockets = []
+ await until(() => presenceHub.peers().length === 0, 'public-origin peers drain')
+ } finally {
+ await new Promise((r) => srv.close(r))
+ }
+ }, 30_000)
+
+ // S3: an open WebSocket was authenticated once, at upgrade, and never again.
+ describe('signing out closes the sockets riding on that session (S3)', () => {
+ const closeCode = (ws: WebSocket): Promise<number> =>
+ new Promise((resolve) => ws.on('close', (code) => resolve(code)))
+
+ it('/auth/logout of one session closes exactly its sockets, and nothing it sends after reaches dispatch', async () => {
+ const casts: unknown[] = []
+ platform.on('fire', (v: unknown) => casts.push(v))
+ const other = `${SESSION_COOKIE}=${auth.createSession()}`
+ const mine = await connect({ cookie })
+ const theirs = await connect({ cookie: other })
+ const closed = closeCode(mine)
+ auth.revokeSession(cookie.split('=')[1])
+ mine.send(JSON.stringify({ t: 'cast', method: 'fire', args: ['after-revoke'] }))
+ expect(await closed).toBe(WS_CLOSE_SIGNED_OUT)
+ expect(casts).toEqual([])
+ expect(theirs.readyState).toBe(WebSocket.OPEN)
+ // And it cannot come back with the same cookie.
+ await expect(connect({ cookie })).rejects.toThrow()
+ }, 30_000)
+
+ it('sign out everywhere closes every cookie socket; a proxy-authenticated one stays (its identity is the proxy)', async () => {
+ const SECRET = 'v'.repeat(40)
+ const HDR = 'X-Forwarded-User'
+ const srv = http.createServer((_q, s2) => { s2.statusCode = 404; s2.end() })
+ attachWsServer(srv, {
+ platform,
+ auth,
+ trustProxy: { header: HDR, nets: parseTrustedNets('127.0.0.0/8'), secret: SECRET }
+ })
+ await new Promise<void>((r) => srv.listen(0, '127.0.0.1', r))
+ const p2 = (srv.address() as { port: number }).port
+ try {
+ const viaProxy = await new Promise<WebSocket>((resolve, reject) => {
+ // It carries a cookie too: the socket is bound to the proxy's identity, not to that cookie.
+ const ws = new WebSocket(`ws://127.0.0.1:${p2}/ws`, {
+ headers: { [HDR]: 'dev', [PROXY_SECRET_HEADER]: SECRET, cookie: `${SESSION_COOKIE}=${auth.createSession()}` }
+ })
+ sockets.push(ws)
+ ws.on('open', () => resolve(ws))
+ ws.on('error', reject)
+ })
+ const a = await connect({ cookie })
+ const b = await connect({ cookie: `${SESSION_COOKIE}=${auth.createSession()}` })
+ const codes = Promise.all([closeCode(a), closeCode(b)])
+ auth.revokeAll()
+ expect(await codes).toEqual([WS_CLOSE_SIGNED_OUT, WS_CLOSE_SIGNED_OUT])
+ expect(viaProxy.readyState).toBe(WebSocket.OPEN)
+ for (const ws of sockets) ws.terminate()
+ sockets = []
+ await until(() => presenceHub.peers().length === 0, 'peers drain')
+ } finally {
+ await new Promise((r) => srv.close(r))
+ }
+ }, 30_000)
+
+ it('a session that EXPIRES is noticed by the heartbeat (expiry announces nothing)', async () => {
+ const hbServer = http.createServer((_q, s) => { s.statusCode = 404; s.end() })
+ attachWsServer(hbServer, { platform, auth, heartbeatMs: 50 })
+ await new Promise<void>((r) => hbServer.listen(0, '127.0.0.1', r))
+ const hbPort = (hbServer.address() as { port: number }).port
+ try {
+ const ws = new WebSocket(`ws://127.0.0.1:${hbPort}/ws`, { headers: { cookie } })
+ sockets.push(ws)
+ await new Promise<void>((res, rej) => {
+ ws.on('open', () => res())
+ ws.on('error', rej)
+ })
+ const closed = closeCode(ws)
+ // Only Date moves: the heartbeat's real timer keeps running.
+ vi.useFakeTimers({ toFake: ['Date'] })
+ vi.setSystemTime(Date.now() + 31 * 24 * 60 * 60 * 1000)
+ expect(await closed).toBe(WS_CLOSE_SIGNED_OUT)
+ } finally {
+ vi.useRealTimers()
+ await until(() => presenceHub.peers().length === 0, 'expired peer drains')
+ await new Promise((r) => hbServer.close(r))
+ }
+ }, 30_000)
})
it('heartbeat: terminates a socket that never answers a ping, dropping its presence peer', async () => {
diff --git a/src/server/ws.ts b/src/server/ws.ts
index cb4acc612..a9e306614 100644
--- a/src/server/ws.ts
+++ b/src/server/ws.ts
@@ -17,7 +17,8 @@ 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 { noteProxyRefusal, proxyAuthDecision, type TrustProxyConfig } from './proxy-trust'
+import { sameOriginRequest } from './origin'
import { parseRpcMessage } from '../shared/rpc'
import { presenceHub } from '../core/presence/hub'
import { WS_CLIENT_FRAME_MAX } from '../shared/ws-frame'
@@ -54,6 +55,13 @@ export const WS_HEARTBEAT_MS = 30_000
*/
export const WS_MAX_PAYLOAD = WS_CLIENT_FRAME_MAX
+/**
+ * Close code for a socket whose session was signed out (S3): `/auth/logout`, "Sign out everywhere",
+ * or the session's 30-day TTL running out. An application code (4000–4999) so it cannot be
+ * mistaken for a network drop in a log.
+ */
+export const WS_CLOSE_SIGNED_OUT = 4401
+
export interface WsServerOpts {
platform: ServerPlatform
auth: Auth
@@ -69,43 +77,61 @@ export interface WsServerOpts {
heartbeatMs?: number
/** Reverse-proxy SSO trust (issue #29) — same object the HTTP handler gets. */
trustProxy?: TrustProxyConfig
+ /** NODETERM_PUBLIC_ORIGIN — an `Origin` equal to it passes the same-origin check (see origin.ts). */
+ publicOrigin?: string
}
/**
- * 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).
+ * Decide whether an upgrade request is allowed. Allowed only when the request is authenticated — a
+ * valid session cookie OR reverse-proxy header trust (issue #29; with the proxy secret when one is
+ * configured, S2) — AND it passes the same-origin check (origin.ts; the cross-site WS hijacking
+ * check applies to both auth paths). A malformed Origin is a rejection (never throws).
+ *
+ * Returns the session token the socket rides on when it was authenticated by its cookie — the
+ * socket is closed when that session is signed out or expires (S3). A proxy-authenticated socket
+ * carries no token: its identity is the proxy's, not a cookie's.
*/
function upgradeAllowed(
req: http.IncomingMessage,
auth: Auth,
- trustProxy?: TrustProxyConfig
-): boolean {
+ trustProxy: TrustProxyConfig | undefined,
+ publicOrigin: string | undefined
+): { ok: false } | { ok: true; token: string | null } {
const token = sessionTokenFromCookie(req.headers['cookie'])
- const proxyAuthed =
- trustProxy !== undefined && proxyAuthAllowed(trustProxy, req.headers, req.socket.remoteAddress)
- if (!proxyAuthed && !auth.validateSession(token)) return false
-
- const origin = req.headers['origin']
- if (typeof origin === 'string' && origin.length > 0) {
- let originHost: string
- try {
- originHost = new URL(origin).host
- } catch {
- // Malformed Origin → reject, don't throw.
- return false
- }
- if (originHost !== req.headers['host']) return false
- }
- return true
+ const decision =
+ trustProxy !== undefined ? proxyAuthDecision(trustProxy, req.headers, req.socket.remoteAddress) : 'none'
+ noteProxyRefusal(decision)
+ const proxyAuthed = decision === 'trusted'
+ if (!proxyAuthed && !auth.validateSession(token)) return { ok: false }
+ if (!sameOriginRequest(req.headers, publicOrigin)) return { ok: false }
+ return { ok: true, token: proxyAuthed || token === undefined ? null : token }
}
export function attachWsServer(server: http.Server, opts: WsServerOpts): WebSocketServer {
- const { platform, auth, onClientGone, heartbeatMs = WS_HEARTBEAT_MS, trustProxy } = opts
+ const { platform, auth, onClientGone, heartbeatMs = WS_HEARTBEAT_MS, trustProxy, publicOrigin } = opts
const wss = new WebSocketServer({ noServer: true, maxPayload: WS_MAX_PAYLOAD })
+ // The session each cookie-authenticated socket rides on (S3). A socket used to be checked once at
+ // upgrade and never again, so signing out — or the session expiring — left an open tab fully
+ // connected. Now a revoke closes the affected sockets at once, and the heartbeat re-checks the
+ // rest every round (that is what catches the 30-day expiry, which emits nothing).
+ const tokenOf = new Map<WebSocket, string>()
+ const signedOut = new WeakSet<WebSocket>()
+ const endIfSignedOut = (ws: WebSocket): boolean => {
+ const token = tokenOf.get(ws)
+ if (token === undefined || auth.validateSession(token)) return false
+ tokenOf.delete(ws)
+ // Drop anything it sends from here on — the close handshake can take a moment, and a frame
+ // that arrives in it must not reach dispatch.
+ signedOut.add(ws)
+ ws.close(WS_CLOSE_SIGNED_OUT, 'signed out')
+ return true
+ }
+ const offRevoke = auth.onSessionsRevoked(() => {
+ for (const ws of [...tokenOf.keys()]) endIfSignedOut(ws)
+ })
+ server.on('close', () => offRevoke())
+
// The one teardown for a connection that is GONE — whether by a clean 'close', or because its sink
// proved dead (the registry evicted it after consecutive throwing sends and called this back).
// Order matches 'close': leave the hub, hand the pty layer its subscriber back, detach the sink.
@@ -134,6 +160,7 @@ export function attachWsServer(server: http.Server, opts: WsServerOpts): WebSock
const alive = new WeakSet<WebSocket>()
const heartbeat = setInterval(() => {
for (const ws of wss.clients) {
+ if (endIfSignedOut(ws)) continue
if (!alive.has(ws)) {
ws.terminate()
continue
@@ -152,7 +179,8 @@ export function attachWsServer(server: http.Server, opts: WsServerOpts): WebSock
const pathname = new URL(req.url || '/', 'http://x').pathname
if (pathname !== '/ws') return
- if (!upgradeAllowed(req, auth, trustProxy)) {
+ const allowed = upgradeAllowed(req, auth, trustProxy, publicOrigin)
+ if (!allowed.ok) {
// 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', () => {})
@@ -162,6 +190,9 @@ export function attachWsServer(server: http.Server, opts: WsServerOpts): WebSock
}
wss.handleUpgrade(req, socket, head, (ws) => {
+ if (allowed.token !== null) tokenOf.set(ws, allowed.token)
+ // Signed out between the upgrade check and now: never attach it.
+ if (endIfSignedOut(ws)) return
wss.emit('connection', ws, req)
})
})
@@ -188,6 +219,7 @@ export function attachWsServer(server: http.Server, opts: WsServerOpts): WebSock
presenceHub.join(uiId, 'browser')
ws.on('message', (data: unknown, isBinary: boolean) => {
+ if (signedOut.has(ws)) return
// Any inbound frame proves the peer is there, pong or not.
alive.add(ws)
// Binary client→server frames are ignored in Phase 2 (pty input rides JSON casts).
@@ -215,7 +247,10 @@ export function attachWsServer(server: http.Server, opts: WsServerOpts): WebSock
console.warn('[nodeterm-server] ws socket error', (e && e.code) || e)
})
- ws.on('close', () => teardown(uiId))
+ ws.on('close', () => {
+ tokenOf.delete(ws)
+ teardown(uiId)
+ })
})
return wss
}