/** * Auth plugin for remote dsh Web access with front-end login/register. * * Responsibilities: * - Refuse to start with `--host 0.0.0.0` unless credentials can be managed. * - Serve a login/register page at `/login`. * - Provide session management (signed cookies; expiry configurable in the settings tab, default 14 days). * - Protect every registered route by wrapping the webserver's registration. * - Bridge dsh 0.1.2's native browser authentication: mint the native * `dsh-auth-*` cookie for callers our session layer already trusts, so a * `dsh_sid` session (or a genuine loopback request) clears the upstream * `isAuthenticated` fence without exposing the launch-token URL flow. * - Provide a `webAuth` service that downstream transport layers can use. * * Wire-level enforcement: * The plugin wraps `ctx.webServer.register` to inject a session check into * every registered route (except `/login` and `/api/auth/*`). The * `connection` row must inject `webAuth` so it activates after this plugin. * * Trust model (dsh 0.1.2): * Upstream now runs its own browser auth (`browser-auth.ts`): the `/api` * fence is `trust fence (403) + native-cookie check (401)` with NO loopback * exemption, and `index.html` is gated the same way. A valid `dsh_sid` * session — or a genuine loopback request (loopback peer address *and* * loopback `Host`, see `isTrustedOrigin`) — passes our wrapper, and the * wrapper mints the native cookie on the fly (a 200 bounce document * with a meta refresh for page navigations, a single 303 for * non-navigation GET/HEAD) so the very next request satisfies upstream. * The bind * address alone is not a trust signal: binding to 127.0.0.1 behind a * reverse proxy still serves remote clients, whose forwarded `Host` names * the public domain. */ import type { Context } from '@deepseek-ai/cordis' import z from '@deepseek-ai/schemastery' import { createHash, createHmac } from 'node:crypto' import type { IncomingMessage, ServerResponse } from 'node:http' import type { WebResourceRoute, WebServer, WebRoute, WebUpgradeRoute } from '@deepseek-ai/dsh-host-webserver' import { credentialKey } from '@deepseek-ai/dsh-credentials' import { isValidSessionMaxAgeDays, SESSION_MAX_AGE_CHOICES } from './session-limits.ts' import { WEB_STARTUP_SERVICE } from './startup.ts' import { LOGIN_PAGE_HTML } from './login-page.ts' import { issueSlider, parseSliderTheme, verifySlider } from './slider/index.ts' import { hasCredentials, registerCredentials, validateCredentials, signSession, verifySession, hardenCredentialFilePermissions, changePassword, changeUsername, getUsername, getRequireLoopbackLogin, setRequireLoopbackLogin, getSlideVerification, setSlideVerification, getSessionMaxAgeDays, setSessionMaxAgeDays, normalizeUsername, MIN_PASSWORD_LENGTH, } from './credential-store.ts' declare module '@deepseek-ai/cordis' { interface Context { webAuth?: WebAuthService } interface Events { /** * Admit or wrap an authenticated shared API request (dsh-client-connection's * `/api` bridge). Same shape as the upstream declaration in * `packages/client/connection/src/index.ts`; declared locally because this * plugin does not depend on that package. Dispatched as a waterfall AFTER * upstream admission (trust fence + native-cookie check); a listener that * does not call `next()` vetoes the remaining chain, including the bridge. */ 'connection/request'(request: IncomingMessage, response: ServerResponse, next: () => Promise): Promise } } /** Stable Cordis plugin name. */ export const name = 'web-auth' /** Services required before the auth policy can be installed. */ export const inject = ['webServer', 'webStartup'] /** Auth plugin configuration (no static config needed; credentials are stored on disk). */ export interface Config {} export const Config: z = z.object({}) /** The auth service provided to transport/tool layers. */ export interface WebAuthService { /** * True when the request carries a valid session cookie, or when it is a * genuine loopback request (loopback peer address *and* loopback `Host`), * which is implicitly trusted and needs no session. */ authenticate(request: IncomingMessage): boolean } /** Session cookie name. */ const SESSION_COOKIE = 'dsh_sid' /** Seconds per day (session lifetimes are configured in whole days). */ const SECS_PER_DAY = 24 * 60 * 60 /** Session lifetime in seconds, as configured in the settings tab (default 14 days). */ function getSessionMaxAgeSec(): number { return getSessionMaxAgeDays() * SECS_PER_DAY } /** Maximum accepted request body, guarding the auth endpoints against memory exhaustion. */ const MAX_BODY_BYTES = 1024 * 1024 /** Login attempts allowed before a client is temporarily locked out. */ const MAX_LOGIN_FAILURES = 5 /** How long a client stays locked out after exhausting the attempts. */ const LOCKOUT_MS = 30_000 /** Rolling window in which failures count towards a lockout. */ const FAILURE_TRACKING_WINDOW_MS = 10 * 60_000 /** * Failures **across all clients** tolerated before any global penalty applies. * * The per-client limit above is the wrong shape for a distributed attack: a * botnet with a thousand addresses never trips it, because each address only * ever tries a handful of times. This counter is what makes the aggregate * volume cost something. * * The free allowance exists because a single administrator fat-fingering a * password, or a handful of users behind one NAT, must never meet a penalty. */ const GLOBAL_FREE_FAILURES = 20 /** Additional failures that buy each further backoff step. */ const GLOBAL_FAILURES_PER_STEP = 10 /** The first global penalty (the step before it is zero). */ const GLOBAL_BACKOFF_BASE_MS = 5_000 /** * Ceiling on the global penalty. * * This is also the worst case an attacker can inflict on the administrator by * flooding the login endpoint: a deliberate availability attack is possible * with any global limiter, so the penalty is bounded rather than unbounded, * and a genuine loopback caller is exempt (see {@link isGlobalLockoutExempt}). */ const GLOBAL_BACKOFF_MAX_MS = 5 * 60_000 /** Window over which global failures accumulate before they decay. */ const GLOBAL_FAILURE_WINDOW_MS = 60 * 60_000 /** * One message for every slider rejection. * * Deliberately does not distinguish "misaligned" from "expired": the * difference is an oracle for someone probing the challenge lifecycle, while a * solver only needs to know they must fetch a new puzzle. The reason is * logged instead. */ const CHALLENGE_REJECTED = '拼图没有对上,请再试一次' /** Per-client login failure tracking (memory only; keyed by socket address). */ interface LoginFailure { count: number firstAt: number lockedUntil?: number } const loginFailures = new Map() /** Aggregate failure pressure across every client (memory only). */ let globalFailures: { count: number; firstAt: number } | undefined /** When the current global penalty lapses. */ let globalLockedUntil = 0 /** * @internal Test-only: forget every failure the limiter has recorded. * * The limiters are module-global (that is the point — a per-process view is * what makes the aggregate counter work), so a test that exercises them would * otherwise leak its failures into every later test in the same file. Tests * call this in `beforeEach` instead of relying on picking unused addresses. */ export const internals = { /** Clear both the per-client map and the aggregate counter. */ resetLoginFailures(): void { loginFailures.clear() globalFailures = undefined globalLockedUntil = 0 }, /** The aggregate penalty for a given failure count (pure, for exact checks). */ globalBackoffMs, } /** * Client socket address for rate limiting and audit logs. * Deliberately NOT the `X-Forwarded-For` header, which clients can forge. */ function clientIp(req: IncomingMessage): string | undefined { return req.socket?.remoteAddress } /** * A query parameter from the request URL. * * Read off `req.url` rather than a parsed URL object: the webserver hands the * handler the raw request target, and the only caller here wants a single * presentation hint. * @param req - the incoming request. * @param name - the parameter to read. * @returns the first value, or `null` when absent. */ function queryParam(req: IncomingMessage, name: string): string | null { const url = req.url if (url === undefined) return null const start = url.indexOf('?') if (start === -1) return null return new URLSearchParams(url.slice(start + 1)).get(name) } /** Whether this client is currently locked out of the login endpoint. */ function isLockedOut(req: IncomingMessage): boolean { const entry = loginFailures.get(clientIp(req) ?? '') return entry?.lockedUntil !== undefined && entry.lockedUntil > Date.now() } /** * The global penalty for a given aggregate failure count: zero up to the free * allowance, then doubling per step, capped. * @param failures - failures recorded in the current window. * @returns the penalty in milliseconds. */ function globalBackoffMs(failures: number): number { if (failures < GLOBAL_FREE_FAILURES) return 0 const step = Math.floor((failures - GLOBAL_FREE_FAILURES) / GLOBAL_FAILURES_PER_STEP) return Math.min(GLOBAL_BACKOFF_MAX_MS, GLOBAL_BACKOFF_BASE_MS * 2 ** step) } /** * Whether the caller is exempt from the **global** penalty. * * A genuine loopback caller — peer address *and* `Host` both loopback, with the * loopback-login switch off — is already authorized without logging in, so * penalizing it protects nothing and would hand an attacker a way to lock the * administrator out of their own machine. With the switch on, loopback is * treated like any other address and the penalty applies. * @param req - the incoming request. * @returns `true` when the global penalty must not apply. */ function isGlobalLockoutExempt(req: IncomingMessage): boolean { return isTrustedOrigin(req) } /** * Whether the aggregate failure pressure currently blocks this caller. * @param req - the incoming request. * @returns `true` when the caller must wait. */ function isGloballyLockedOut(req: IncomingMessage): boolean { if (globalLockedUntil <= Date.now()) return false return !isGlobalLockoutExempt(req) } /** * Milliseconds until this caller may retry, for the `Retry-After` header. * @param req - the incoming request. * @returns whole seconds, or `undefined` when nothing is blocking. */ function retryAfterSeconds(req: IncomingMessage): number | undefined { const now = Date.now() const local = loginFailures.get(clientIp(req) ?? '')?.lockedUntil ?? 0 const until = Math.max(local, isGlobalLockoutExempt(req) ? 0 : globalLockedUntil) if (until <= now) return undefined return Math.max(1, Math.ceil((until - now) / 1000)) } /** Record a failed login; locks the client out after repeated failures. */ function recordLoginFailure(req: IncomingMessage): void { const now = Date.now() // Aggregate pressure first: it applies even when the peer address is // unreadable, which is exactly the case a per-client map cannot cover. if (globalFailures === undefined || now - globalFailures.firstAt > GLOBAL_FAILURE_WINDOW_MS) { globalFailures = { count: 1, firstAt: now } } else { globalFailures.count += 1 } const penalty = globalBackoffMs(globalFailures.count) if (penalty > 0) globalLockedUntil = now + penalty const ip = clientIp(req) if (ip === undefined) return const entry = loginFailures.get(ip) if (entry === undefined || now - entry.firstAt > FAILURE_TRACKING_WINDOW_MS) { loginFailures.set(ip, { count: 1, firstAt: now }) return } entry.count += 1 if (entry.count >= MAX_LOGIN_FAILURES) { entry.lockedUntil = now + LOCKOUT_MS } } /** Clear the failure state after a successful login. */ function recordLoginSuccess(req: IncomingMessage): void { const ip = clientIp(req) if (ip !== undefined) loginFailures.delete(ip) // Deliberately does NOT clear `globalFailures`: one administrator getting in // does not mean the aggregate pressure ended, and a successful login is // something only a holder of the password can produce. The counter decays by // window instead, and the penalty is capped, so this cannot strand anyone. } /** * Drop stale failure entries so the tracking map cannot grow without bound * when attackers spoof socket addresses from many sources. */ function pruneLoginFailures(now = Date.now()): void { if (globalFailures !== undefined && now - globalFailures.firstAt > GLOBAL_FAILURE_WINDOW_MS) { globalFailures = undefined globalLockedUntil = 0 } if (loginFailures.size < 1024) return for (const [ip, entry] of loginFailures) { if (now - entry.firstAt > FAILURE_TRACKING_WINDOW_MS) { loginFailures.delete(ip) } else if (entry.lockedUntil !== undefined && entry.lockedUntil < now) { loginFailures.delete(ip) } } } /** Cookie header string for a session cookie with the configured expiry. */ function sessionCookieSet(value: string, secure: boolean): string { const attributes = `${SESSION_COOKIE}=${value}; HttpOnly; Path=/; SameSite=Lax; Max-Age=${getSessionMaxAgeSec()}` return secure ? `${attributes}; Secure` : attributes } /** Clear the session cookie (carrying `Secure` on a TLS listener, like the set). */ function sessionCookieClear(secure: boolean): string { const attributes = `${SESSION_COOKIE}=; HttpOnly; Path=/; SameSite=Lax; Max-Age=0` return secure ? `${attributes}; Secure` : attributes } /** Parse the session cookie from a request. */ function parseSessionCookie(req: IncomingMessage): string | undefined { const cookie = req.headers.cookie if (!cookie) return undefined // Simple cookie parser (no full RFC compliance needed for a single cookie) const start = cookie.indexOf(SESSION_COOKIE + '=') if (start === -1) return undefined const valueStart = start + SESSION_COOKIE.length + 1 const end = cookie.indexOf(';', valueStart) return end === -1 ? cookie.slice(valueStart) : cookie.slice(valueStart, end) } /** Build a session payload (username + expiry) and sign it. */ function buildSessionCookie(username: string): string | undefined { const exp = Math.floor(Date.now() / 1000) + getSessionMaxAgeSec() const payload = JSON.stringify({ u: username, e: exp }) const sig = signSession(payload) if (sig === undefined) return undefined return `${Buffer.from(payload, 'utf8').toString('base64url')}.${sig}` } /** Validate a session cookie and return the username if valid. */ function validateSessionCookie(req: IncomingMessage): string | undefined { const raw = parseSessionCookie(req) if (!raw) return undefined const dot = raw.indexOf('.') if (dot === -1) return undefined const payloadBase64 = raw.slice(0, dot) const sig = raw.slice(dot + 1) let payload: string try { payload = Buffer.from(payloadBase64, 'base64url').toString('utf8') } catch { return undefined } if (!verifySession(payload, sig)) return undefined let parsed: { u?: string; e?: number } try { parsed = JSON.parse(payload) as { u?: string; e?: number } } catch { return undefined } if (typeof parsed.u !== 'string' || typeof parsed.e !== 'number') return undefined // Check expiry if (parsed.e < Math.floor(Date.now() / 1000)) return undefined return parsed.u } /** Parse a JSON body from an incoming request, capped at MAX_BODY_BYTES. */ function parseBody(req: IncomingMessage): Promise> { return new Promise((resolve, reject) => { const chunks: Buffer[] = [] let total = 0 req.on('data', (chunk: Buffer) => { total += chunk.length if (total > MAX_BODY_BYTES) { reject(new Error('request body too large')) req.destroy() return } chunks.push(chunk) }) req.on('end', () => { try { resolve(JSON.parse(Buffer.concat(chunks).toString('utf8'))) } catch (error) { reject(error) } }) req.on('error', reject) }) } /** True when the parse body rejection was the size cap. */ function isBodyTooLarge(error: unknown): boolean { return error instanceof Error && error.message === 'request body too large' } /** True when registration raced another concurrent registration. */ function isAlreadyRegistered(error: unknown): boolean { return error instanceof Error && error.message.includes('already registered') } /** Send a JSON response. */ /** * Send a JSON answer. * @param res - the response to write to. * @param status - the HTTP status. * @param data - the JSON body. * @param headers - extra headers (e.g. `retry-after`). */ function jsonResponse( res: ServerResponse, status: number, data: Record, headers: Record = {}, ): void { res.writeHead(status, { 'content-type': 'application/json', ...headers }) res.end(JSON.stringify(data)) } /** * Answer a rate-limited caller, telling them how long to wait. * * The `Retry-After` header is the standard signal and the only one a scripted * client will notice; the JSON body keeps the message the login page shows. * @param req - the incoming request. * @param res - the response to write to. */ function rateLimitedResponse(req: IncomingMessage, res: ServerResponse): void { const retryAfter = retryAfterSeconds(req) jsonResponse( res, 429, { error: '尝试次数过多,请稍后再试' }, retryAfter === undefined ? {} : { 'retry-after': String(retryAfter) }, ) } /** * Check if the request is authorized (a genuine loopback request or a valid * session cookie). * @param req - the incoming HTTP request. * @returns `true` if the request is allowed. */ function isAuthorized(req: IncomingMessage): boolean { if (isTrustedOrigin(req)) return true return validateSessionCookie(req) !== undefined } /** Loopback hostnames (same classification as dsh's own browser-trust fence). */ const LOOPBACK_HOSTNAMES = ['localhost', '[::1]'] /** * Whether a `Host` header authority is a loopback authority. * @param host - the raw `Host` header value. * @returns `true` for localhost, IPv6 loopback, or 127/8 IPv4. */ function isLoopbackAuthority(host: string | undefined): boolean { if (host === undefined) return false let hostname: string try { hostname = new URL(`http://${host}`).hostname } catch { return false } if (LOOPBACK_HOSTNAMES.includes(hostname)) return true const parts = hostname.split('.') return parts.length === 4 && parts[0] === '127' && parts.every((part) => /^\d{1,3}$/.test(part) && Number(part) <= 255) } /** * Whether a TCP peer address is a loopback address. * * Only the socket's own peer address counts. `X-Forwarded-For` and friends are * client-supplied headers and are never consulted: a reverse proxy that wants * its clients treated as remote has to forward the real `Host`, which is the * signal the loopback check below reads. * @param address - `req.socket.remoteAddress`, if any. * @returns `true` for 127/8 IPv4 (including IPv4-mapped IPv6) and IPv6 loopback. */ function isLoopbackRemoteAddress(address: string | undefined): boolean { if (address === undefined) return false // Node reports IPv4 peers on a dual-stack socket as `::ffff:127.0.0.1`. const normalized = address.startsWith('::ffff:') ? address.slice(7) : address if (normalized === '::1') return true const parts = normalized.split('.') return parts.length === 4 && parts[0] === '127' && parts.every((part) => /^\d{1,3}$/.test(part) && Number(part) <= 255) } /** * Whether the request itself is a loopback request, and therefore implicitly * trusted without a session. * * Both halves are required, because each one alone is forgeable or * insufficient: * - The `Host` header alone is forgeable: an attacker reaching the server over * the LAN can send `Host: 127.0.0.1`. The socket's peer address cannot be * forged by anyone who is not already on the loopback interface. * - The peer address alone misses reverse proxies: a proxy on the same host * connects from 127.0.0.1 while its client is remote, so the forwarded * `Host` (the external domain) is what distinguishes that case from a * genuine local browser. * * A host-local caller that reaches the server over loopback *and* claims a * loopback authority is already a local user, so implicit trust is safe. * @param req - the incoming HTTP request. * @returns `true` when the request needs no session cookie. */ function isTrustedOrigin(req: IncomingMessage): boolean { // An administrator may require every address — loopback included — to present // a session. When the persisted flag is on, loopback is no longer implicitly // trusted (the default, flag-off behavior keeps loopback trusted). if (getRequireLoopbackLogin()) return false return isLoopbackRemoteAddress(req.socket?.remoteAddress) && isLoopbackAuthority(req.headers.host) } // ── native browser-auth bridge (dsh 0.1.2) ────────────────────────────────── // // dsh 0.1.2's `browser-auth.ts` signs its own `dsh-auth-` // cookie with a 32-byte secret persisted in the credentials service under // `credentialKey('client-connection', 'browser-session')`. Every `/api` // request and the SPA index must carry that cookie (no loopback exemption), // so a caller our session layer already trusts would bounce off the upstream // fence without help. The bridge mints the exact same cookie format for such // callers. This is a deliberate coupling to the upstream cookie format; // `docs/upgrade-dsh-0.1.2-playbook.md` says to re-diff `browser-auth.ts` // after every dsh upgrade. The 0.2.1 line made the audience protocol-scoped // (HTTPS → origin, not host) and the cookie `Secure`-flagged on TLS // listeners; on HTTP both come out byte-identical to the historical form. // // The secret is read lazily (the connection plugin creates it during its own // apply, which may race ours) and cached after the first successful read. // We never create it ourselves: the key belongs to upstream. /** Credentials service shape this plugin reads (structural, no type merge). */ interface BrowserSessionCredentials { readRecord(key: unknown): Promise } const BROWSER_COOKIE_PREFIX = 'dsh-auth-' const BROWSER_COOKIE_VERSION = 1 const BROWSER_SECRET_BYTES = 32 /** Aligns with upstream `cookieMaxAgeDays` default (30 days). */ const BROWSER_COOKIE_MAX_AGE_SEC = 30 * 24 * 60 * 60 const BROWSER_AUTH_RECORD_KEY = credentialKey('client-connection', 'browser-session') /** Credential provider lookup, installed by `apply`; absent in unit tests. */ let lookupCredentials: (() => BrowserSessionCredentials | undefined) | undefined /** * Cached native signing secrets, keyed by the credentials service instance: * a fresh provider (including every test double) re-reads its own record, * so rotating or replacing the service never serves a stale key. */ const browserSecretCache = new WeakMap() /** * Protocol-scoped cookie audience, exactly as upstream computes it * (`browser-auth.ts` `requestAudience`): the `URL`-normalized host on HTTP * (lowercased, default port stripped), the full origin on HTTPS — where the * scheme makes an authority-only spelling ambiguous about the default port. * The cookie name is derived from this value, so any mismatch would produce * a cookie upstream never looks for. */ function requestAudience(headers: IncomingMessage['headers'], secure: boolean): string | undefined { const host = headers.host if (host === undefined) return undefined try { const url = new URL(`${secure ? 'https:' : 'http:'}//${host}`) return secure ? url.origin : url.host } catch { return undefined } } /** Native cookie name for an audience (`dsh-auth-` + base64url(sha256)). */ function browserCookieName(audience: string): string { const digest = createHash('sha256').update(audience).digest() return BROWSER_COOKIE_PREFIX + digest.toString('base64url') } /** Read the exact generated native cookie without general Cookie decoding. */ function readBrowserCookie(headers: IncomingMessage['headers'], audience: string): string | undefined { const raw = headers.cookie if (raw === undefined) return undefined const name = browserCookieName(audience) for (const segment of raw.split(';')) { const at = segment.indexOf('=') if (at === -1 || segment.slice(0, at).trim() !== name) continue return segment.slice(at + 1).trim() } return undefined } /** * Load (and cache) the native signing secret from the credentials service. * Returns undefined while the record does not exist yet — the caller skips * minting this request and retries on the next one. The record is never * created here: the key belongs to the connection plugin. */ async function browserAuthSecret(): Promise { const credentials = lookupCredentials?.() if (credentials === undefined) return undefined const cached = browserSecretCache.get(credentials) if (cached !== undefined) return cached try { const record = await credentials.readRecord(BROWSER_AUTH_RECORD_KEY) as | { kind?: unknown; payload?: unknown } | undefined if (record === undefined || record === null) return undefined if (record.kind !== 'grant' || record.payload === null || typeof record.payload !== 'object') { return undefined } const payload = record.payload as { version?: unknown; secret?: unknown } if (payload.version !== BROWSER_COOKIE_VERSION || typeof payload.secret !== 'string') { return undefined } const secret = Buffer.from(payload.secret, 'base64url') if (secret.length !== BROWSER_SECRET_BYTES) return undefined browserSecretCache.set(credentials, secret) return secret } catch { return undefined } } /** * Serialize the native cookie value: `v1..` * where the HMAC covers the base64url payload string itself — byte-for-byte * the format upstream `decodeCookie` expects. */ function encodeBrowserCookie( payload: { version: number; authority: string; issuedAt: number; expiresAt: number }, secret: Buffer, ): string { const body = Buffer.from(JSON.stringify(payload), 'utf8').toString('base64url') const signature = createHmac('sha256', secret).update(body).digest().toString('base64url') return `v1.${body}.${signature}` } /** Cookie attributes copied from upstream `sessionCookie`, `; Secure` appended on TLS. */ function browserCookieAttributes(expiresAt: number, secure: boolean): string { const attributes = `; Max-Age=${String(BROWSER_COOKIE_MAX_AGE_SEC)}; Path=/; Expires=${new Date(expiresAt).toUTCString()}; HttpOnly; SameSite=Strict` return secure ? `${attributes}; Secure` : attributes } /** * Mint a `Set-Cookie` value for the native browser-auth cookie, bound to the * request's own audience. Returns undefined when the audience is missing * or the signing secret is not available yet (retry on the next request). * @param req - the request whose Host (audience) and TLS listener scope the cookie. * @param secure - whether the receiving listener serves TLS. */ async function mintBrowserCookie(req: IncomingMessage, secure: boolean): Promise { const secret = await browserAuthSecret() if (secret === undefined) return undefined const audience = requestAudience(req.headers, secure) if (audience === undefined) return undefined const issuedAt = Date.now() const expiresAt = issuedAt + BROWSER_COOKIE_MAX_AGE_SEC * 1000 const value = encodeBrowserCookie({ version: BROWSER_COOKIE_VERSION, authority: audience, issuedAt, expiresAt }, secret) return `${browserCookieName(audience)}=${value}${browserCookieAttributes(expiresAt, secure)}` } /** * Clear the native cookie for the request's audience. The name is derivable * without the secret, so logout can always emit this. `Secure` mirrors the * set on a TLS listener, which is the canonical deletion of a Secure cookie. */ function clearBrowserCookie(req: IncomingMessage, secure: boolean): string | undefined { const audience = requestAudience(req.headers, secure) if (audience === undefined) return undefined const attributes = '; Max-Age=0; Path=/; HttpOnly; SameSite=Strict' return `${browserCookieName(audience)}=${secure ? `${attributes}; Secure` : attributes}` } /** * Minimal bounce document for the native-cookie mint on page navigations. * * Setting the cookie on a 200 and letting the document navigate itself is * deliberate. Browsers do not attach a cookie set by a redirect response to * that redirect's target request (WebKit #219650, Firefox #1465402) and a * `SameSite=Strict` cookie is withheld on a cross-site-initiated navigation, * so a 3xx mint is re-issued on every hop of the chain and the browser ends * up at `ERR_TOO_MANY_REDIRECTS`. A 200 stores the cookie, and the * meta-refresh navigation that follows is issued by this document, so the * cookie is sent on the very next request even when it is `Strict`. */ function mintBounceDocument(url: string): string { const escaped = url .replace(/&/g, '&') .replace(//g, '>') .replace(/"/g, '"') // `location.replace` (not `assign`) so the bounce leaves no history entry; // the meta refresh below is the no-JS fallback. JSON.stringify covers // quotes/backslashes/control chars and `<` is escaped so the URL can never // close the script element. const jsSafe = JSON.stringify(url).replace(/正在跳转…` } /** * True when the request looks like a page navigation (vs an XHR/fetch). * * `nested-navigate` (iframe/frame documents) counts as well: it is a real * navigation that hits the same redirect-replay trap as a top-level one — * a 303 inside a frame loops to ERR_TOO_MANY_REDIRECTS just the same — * and a bounce document works inside a frame exactly as it does top-level. * Clients that omit `Sec-Fetch-Mode` entirely fall back to `Accept`. */ function isPageNavigation(req: IncomingMessage): boolean { const mode = req.headers['sec-fetch-mode'] if (typeof mode === 'string' && mode !== 'navigate' && mode !== 'nested-navigate') return false if (mode === undefined) { const accept = req.headers.accept return typeof accept === 'string' && accept.includes('text/html') } return true } /** * Install the auth policy after the web server has bound. * @param ctx - plugin context with `webServer` and `webStartup`. * @param config - resolved plugin config. */ export function apply(ctx: Context, _config: Config): void { const webServer: WebServer = ctx.webServer const bindHost = webServer.host // Whether the listener terminates TLS — the sole source for the cookie // audience spelling and the `Secure` attribute, mirroring upstream // (`ctx.get('webServer')?.protocol === 'https:'` in rpc-host). Read // structurally: the 0.2.0-line WebServer type has no `protocol`, where // this yields false and every cookie stays byte-identical to its HTTP form. const secure = (webServer as { protocol?: unknown }).protocol === 'https:' // The credentials service is owned by the credentials plugin; look it up // lazily (it may activate after web-auth) instead of declaring an inject, // so a missing service degrades to "no native cookie minting" rather than // taking the auth layer down. lookupCredentials = () => (ctx as unknown as { get(key: string): unknown }).get('credentials') as | BrowserSessionCredentials | undefined // Restrict an existing credential file (created by an earlier version that // followed the umask) to owner-only access before serving any traffic. hardenCredentialFilePermissions() // ── 1. Register the login page route ────────────────────────────────────── ctx.effect(() => webServer.register({ kind: 'exact', path: '/login', handler: (req, res) => { res.writeHead(200, { 'content-type': 'text/html; charset=utf-8' }) res.end(LOGIN_PAGE_HTML) }, }), 'web-auth: /login route') // ── 2. Register auth API endpoints ──────────────────────────────────────── const authEndpoints: WebRoute[] = [ { kind: 'exact', path: '/api/auth/status', handler: async (req, res) => { const registered = hasCredentials() // Two independent facts, because `authenticated` alone cannot express // them: does this caller *hold* a session, and is it merely waved // through by loopback trust? A local browser on a default deployment // is trusted without any cookie, so it is authorized but not signed // in — "退出登录" has nothing to revoke there, and the tab has to say // so instead of showing a signed-in identity. const session = validateSessionCookie(req) const trusted = isTrustedOrigin(req) const authenticated = session !== undefined || trusted // A session names its own user. A trusted caller holding none gets the // stored admin name — that is the account that exists, not an identity // this caller proved. const username = session ?? (trusted ? getUsername() : undefined) jsonResponse(res, 200, { registered, authenticated, session: session !== undefined, trusted, username, }) }, }, { kind: 'exact', path: '/api/auth/register', handler: async (req, res) => { if (req.method !== 'POST') { res.writeHead(405) res.end() return } try { const body = await parseBody(req) const username = typeof body.username === 'string' ? normalizeUsername(body.username) : '' const password = typeof body.password === 'string' ? body.password : '' if (!username || !password) { jsonResponse(res, 400, { error: '请输入用户名和密码' }) return } if (password.length < MIN_PASSWORD_LENGTH) { jsonResponse(res, 400, { error: `密码至少 ${MIN_PASSWORD_LENGTH} 个字符` }) return } if (hasCredentials()) { jsonResponse(res, 400, { error: '管理员账号已设置,不能重复注册' }) return } registerCredentials(username, password) ctx.logger.info('web-auth: administrator registered (%s)', username) // Create a session cookie for the newly registered user const cookie = buildSessionCookie(username) if (cookie === undefined) { jsonResponse(res, 500, { error: '服务器内部错误' }) return } const cookies = [sessionCookieSet(cookie, secure)] const native = await mintBrowserCookie(req, secure) if (native !== undefined) cookies.push(native) res.writeHead(200, { 'content-type': 'application/json', 'set-cookie': cookies }) res.end(JSON.stringify({ ok: true })) } catch (error) { if (isBodyTooLarge(error)) { jsonResponse(res, 413, { error: '请求体过大' }) return } if (isAlreadyRegistered(error)) { // Raced another concurrent registration that won jsonResponse(res, 409, { error: '管理员账号已设置,不能重复注册' }) return } ctx.logger.warn('web-auth: register failed: %s', error instanceof Error ? error.message : String(error)) jsonResponse(res, 500, { error: '服务器内部错误' }) } }, }, { kind: 'exact', path: '/api/auth/login', handler: async (req, res) => { if (req.method !== 'POST') { res.writeHead(405) res.end() return } try { pruneLoginFailures() const globalBackoff = isGloballyLockedOut(req) if (isLockedOut(req) || globalBackoff) { ctx.logger.warn( 'web-auth: login rate-limited (%s, from %s)', globalBackoff ? 'global backoff' : 'client lockout', clientIp(req) ?? 'unknown', ) rateLimitedResponse(req, res) return } const body = await parseBody(req) const username = typeof body.username === 'string' ? normalizeUsername(body.username) : '' const password = typeof body.password === 'string' ? body.password : '' if (!username || !password) { jsonResponse(res, 400, { error: '请输入用户名和密码' }) return } // The puzzle sits in front of the credential check, and a rejection // is counted as a login failure: that is what ties solving it to the // limiters above (a wrong drop costs a fresh puzzle *and* one of the // five attempts). if (getSlideVerification()) { const verdict = verifySlider( clientIp(req), typeof body.challengeId === 'string' ? body.challengeId : '', typeof body.challengeAnswer === 'string' ? body.challengeAnswer : '', ) if (!verdict.ok) { recordLoginFailure(req) ctx.logger.warn( 'web-auth: slider rejected (%s, from %s)', verdict.reason, clientIp(req) ?? 'unknown', ) // `challengeExpired` is the page's cue to fetch a new puzzle: the // challenge was consumed by this attempt, whatever the reason. jsonResponse(res, 400, { error: CHALLENGE_REJECTED, challengeExpired: true }) return } } if (!validateCredentials(username, password)) { recordLoginFailure(req) ctx.logger.warn('web-auth: login failed (from %s)', clientIp(req) ?? 'unknown') jsonResponse(res, 401, { error: '用户名或密码错误' }) return } recordLoginSuccess(req) ctx.logger.info('web-auth: login ok (%s, from %s)', username, clientIp(req) ?? 'unknown') const cookie = buildSessionCookie(username) if (cookie === undefined) { jsonResponse(res, 500, { error: '服务器内部错误' }) return } const cookies = [sessionCookieSet(cookie, secure)] const native = await mintBrowserCookie(req, secure) if (native !== undefined) cookies.push(native) res.writeHead(200, { 'content-type': 'application/json', 'set-cookie': cookies }) res.end(JSON.stringify({ ok: true })) } catch (error) { if (isBodyTooLarge(error)) { jsonResponse(res, 413, { error: '请求体过大' }) return } ctx.logger.warn('web-auth: login failed: %s', error instanceof Error ? error.message : String(error)) jsonResponse(res, 500, { error: '服务器内部错误' }) } }, }, { kind: 'exact', path: '/api/auth/logout', handler: async (req, res) => { // Clear our session cookie, and the native browser-auth cookie for // this authority (its name is derivable without the secret). The // native cookie alone cannot restore access — our wrapper rejects // any request without a valid `dsh_sid` — but clearing it keeps the // browser consistent with the signed-out state. const cookies = [sessionCookieClear(secure)] const nativeClear = clearBrowserCookie(req, secure) if (nativeClear !== undefined) cookies.push(nativeClear) res.writeHead(200, { 'content-type': 'application/json', 'set-cookie': cookies }) res.end(JSON.stringify({ ok: true })) }, }, { kind: 'exact', path: '/api/auth/change-password', handler: async (req, res) => { if (req.method !== 'POST') { res.writeHead(405) res.end() return } // Change-password requires an authenticated caller: a session cookie // for a remote caller, or the implicit trust granted to a genuine // loopback request. Rate limiting mirrors the login endpoint. try { pruneLoginFailures() if (!isAuthorized(req)) { jsonResponse(res, 401, { error: '未登录或会话已过期' }) return } if (isLockedOut(req)) { rateLimitedResponse(req, res) return } const body = await parseBody(req) const oldPassword = typeof body.oldPassword === 'string' ? body.oldPassword : '' const newPassword = typeof body.newPassword === 'string' ? body.newPassword : '' if (!oldPassword || !newPassword) { jsonResponse(res, 400, { error: '请输入旧密码和新密码' }) return } if (newPassword.length < MIN_PASSWORD_LENGTH) { jsonResponse(res, 400, { error: `密码至少 ${MIN_PASSWORD_LENGTH} 个字符` }) return } // Capture the identity BEFORE changePassword: it rotates the signing // secret, after which the old session cookie no longer verifies. const username = isTrustedOrigin(req) ? getUsername() : validateSessionCookie(req) if (username === undefined) { jsonResponse(res, 401, { error: '未登录或会话已过期' }) return } if (!changePassword(oldPassword, newPassword)) { recordLoginFailure(req) ctx.logger.warn('web-auth: change-password failed (from %s)', clientIp(req) ?? 'unknown') jsonResponse(res, 401, { error: '旧密码错误' }) return } recordLoginSuccess(req) ctx.logger.info('web-auth: password changed (from %s)', clientIp(req) ?? 'unknown') // changePassword rotates the signing secret, invalidating every // previously issued session cookie — re-issue one for this caller. const cookie = buildSessionCookie(username) if (cookie === undefined) { jsonResponse(res, 500, { error: '服务器内部错误' }) return } const cookies = [sessionCookieSet(cookie, secure)] const native = await mintBrowserCookie(req, secure) if (native !== undefined) cookies.push(native) res.writeHead(200, { 'content-type': 'application/json', 'set-cookie': cookies }) res.end(JSON.stringify({ ok: true })) } catch (error) { if (isBodyTooLarge(error)) { jsonResponse(res, 413, { error: '请求体过大' }) return } ctx.logger.warn('web-auth: change-password failed: %s', error instanceof Error ? error.message : String(error)) jsonResponse(res, 500, { error: '服务器内部错误' }) } }, }, { kind: 'exact', path: '/api/auth/change-username', handler: async (req, res) => { if (req.method !== 'POST') { res.writeHead(405) res.end() return } // Same contract as change-password: an authenticated caller (session // cookie for a remote caller, or genuine loopback trust) plus the // current password. Rate limiting mirrors the login endpoint. try { pruneLoginFailures() if (!isAuthorized(req)) { jsonResponse(res, 401, { error: '未登录或会话已过期' }) return } if (isLockedOut(req)) { rateLimitedResponse(req, res) return } const body = await parseBody(req) const newUsername = typeof body.newUsername === 'string' ? normalizeUsername(body.newUsername) : '' const currentPassword = typeof body.currentPassword === 'string' ? body.currentPassword : '' if (!newUsername || !currentPassword) { jsonResponse(res, 400, { error: '请输入新用户名和当前密码' }) return } // Capture the identity BEFORE changeUsername: it rotates the signing // secret, after which the old session cookie no longer verifies. const username = isTrustedOrigin(req) ? getUsername() : validateSessionCookie(req) if (username === undefined) { jsonResponse(res, 401, { error: '未登录或会话已过期' }) return } if (newUsername === username) { // No-op: nothing to rotate, so leave every session (including // this caller's) untouched. jsonResponse(res, 200, { ok: true, username }) return } if (!changeUsername(newUsername, currentPassword)) { recordLoginFailure(req) ctx.logger.warn('web-auth: change-username failed (from %s)', clientIp(req) ?? 'unknown') jsonResponse(res, 401, { error: '当前密码错误' }) return } recordLoginSuccess(req) ctx.logger.info('web-auth: username changed %s -> %s (from %s)', username, newUsername, clientIp(req) ?? 'unknown') // changeUsername rotates the signing secret, invalidating every // previously issued session cookie — re-issue one for this caller. const cookie = buildSessionCookie(newUsername) if (cookie === undefined) { jsonResponse(res, 500, { error: '服务器内部错误' }) return } const cookies = [sessionCookieSet(cookie, secure)] const native = await mintBrowserCookie(req, secure) if (native !== undefined) cookies.push(native) res.writeHead(200, { 'content-type': 'application/json', 'set-cookie': cookies }) res.end(JSON.stringify({ ok: true, username: newUsername })) } catch (error) { if (isBodyTooLarge(error)) { jsonResponse(res, 413, { error: '请求体过大' }) return } ctx.logger.warn('web-auth: change-username failed: %s', error instanceof Error ? error.message : String(error)) jsonResponse(res, 500, { error: '服务器内部错误' }) } }, }, { kind: 'exact', path: '/api/auth/policy', handler: async (req, res) => { // Reading and flipping the switch requires an authenticated caller, // mirroring change-password: a session cookie for a remote caller, // or the implicit trust of a genuine loopback request while the // switch itself is still off. try { if (!isAuthorized(req)) { jsonResponse(res, 401, { error: '未登录或会话已过期' }) return } if (req.method === 'GET') { jsonResponse(res, 200, { requireLoopbackLogin: getRequireLoopbackLogin() }) return } if (req.method !== 'POST') { res.writeHead(405) res.end() return } const body = await parseBody(req) const requireLoopbackLogin = body.requireLoopbackLogin if (typeof requireLoopbackLogin !== 'boolean') { jsonResponse(res, 400, { error: 'requireLoopbackLogin 必须为布尔值' }) return } try { setRequireLoopbackLogin(requireLoopbackLogin) } catch (error) { // Enabling before any admin exists would lock out every caller // (loopback included): there would be no account to log into. ctx.logger.warn('web-auth: policy update failed: %s', error instanceof Error ? error.message : String(error)) jsonResponse(res, 400, { error: '请先注册管理员账号,再开启强制登录' }) return } ctx.logger.info('web-auth: requireLoopbackLogin set to %s (from %s)', requireLoopbackLogin, clientIp(req) ?? 'unknown') jsonResponse(res, 200, { ok: true, requireLoopbackLogin }) } catch (error) { if (isBodyTooLarge(error)) { jsonResponse(res, 413, { error: '请求体过大' }) return } ctx.logger.warn('web-auth: policy endpoint failed: %s', error instanceof Error ? error.message : String(error)) jsonResponse(res, 500, { error: '服务器内部错误' }) } }, }, { kind: 'exact', path: '/api/auth/session-max-age', handler: async (req, res) => { // Reading and changing the session lifetime requires an authenticated // caller, mirroring the policy endpoint: a session cookie for a // remote caller, or the implicit trust of a genuine loopback request. // Changing the value only affects freshly issued cookies — existing // sessions keep the lifetime baked into their payload at sign time. try { if (!isAuthorized(req)) { jsonResponse(res, 401, { error: '未登录或会话已过期' }) return } if (req.method === 'GET') { jsonResponse(res, 200, { days: getSessionMaxAgeDays() }) return } if (req.method !== 'POST') { res.writeHead(405) res.end() return } const body = await parseBody(req) const days = body.days if (!isValidSessionMaxAgeDays(days)) { jsonResponse(res, 400, { error: `days 必须是 ${SESSION_MAX_AGE_CHOICES.join('/')} 之一` }) return } try { setSessionMaxAgeDays(days) } catch (error) { // Thrown before any admin exists: there would be no session to // apply a lifetime to, and no authenticated caller either. ctx.logger.warn('web-auth: session lifetime update failed: %s', error instanceof Error ? error.message : String(error)) jsonResponse(res, 400, { error: '请先注册管理员账号,再调整会话有效期' }) return } ctx.logger.info('web-auth: session lifetime set to %s days (from %s)', days, clientIp(req) ?? 'unknown') jsonResponse(res, 200, { ok: true, days }) } catch (error) { if (isBodyTooLarge(error)) { jsonResponse(res, 413, { error: '请求体过大' }) return } ctx.logger.warn('web-auth: session-max-age endpoint failed: %s', error instanceof Error ? error.message : String(error)) jsonResponse(res, 500, { error: '服务器内部错误' }) } }, }, { kind: 'exact', path: '/api/auth/challenge', handler: (req, res) => { // Anonymous on purpose: the login page calls this before it holds any // session, so requiring one would make the puzzle unusable. It answers // `{ enabled: false }` while the switch is off, and otherwise hands out // nothing but a fresh puzzle — no credential, no state the caller did // not just create. // // Not rate-limited either: the store is bounded (`MAX_CHALLENGES`), // and folding this into the login limiter would hand an attacker a way // to lock the administrator out by spamming an endpoint that needs no // credentials at all. if (req.method !== 'GET') { res.writeHead(405) res.end() return } if (!getSlideVerification()) { jsonResponse(res, 200, { enabled: false }) return } const issued = issueSlider(clientIp(req), parseSliderTheme(queryParam(req, 'theme'))) jsonResponse(res, 200, { enabled: true, ...issued }) }, }, { kind: 'exact', path: '/api/auth/challenge-policy', handler: async (req, res) => { // Reading and flipping the switch requires an authenticated caller, // mirroring the loopback policy endpoint: a session cookie for a // remote caller, or the implicit trust of a genuine loopback request // while the loopback switch itself is still off. try { if (!isAuthorized(req)) { jsonResponse(res, 401, { error: '未登录或会话已过期' }) return } if (req.method === 'GET') { jsonResponse(res, 200, { slideVerification: getSlideVerification() }) return } if (req.method !== 'POST') { res.writeHead(405) res.end() return } const body = await parseBody(req) const slideVerification = body.slideVerification if (typeof slideVerification !== 'boolean') { jsonResponse(res, 400, { error: 'slideVerification 必须为布尔值' }) return } try { setSlideVerification(slideVerification) } catch (error) { // Enabling before any admin exists would write the credential file // to hold a switch, and that file's existence is what marks the // administrator as registered — the registration form would then // refuse to create one. ctx.logger.warn('web-auth: challenge policy update failed: %s', error instanceof Error ? error.message : String(error)) jsonResponse(res, 400, { error: '请先注册管理员账号,再开启拼图验证' }) return } ctx.logger.info('web-auth: slideVerification set to %s (from %s)', slideVerification, clientIp(req) ?? 'unknown') jsonResponse(res, 200, { ok: true, slideVerification: getSlideVerification() }) } catch (error) { if (isBodyTooLarge(error)) { jsonResponse(res, 413, { error: '请求体过大' }) return } ctx.logger.warn('web-auth: challenge-policy endpoint failed: %s', error instanceof Error ? error.message : String(error)) jsonResponse(res, 500, { error: '服务器内部错误' }) } }, }, ] for (const route of authEndpoints) { ctx.effect(() => webServer.register(route), `web-auth: ${route.path} route`) } // ── 3. Inject a redirect check into the SPA index ───────────────────────── // When the SPA boots without a valid session, send it to the login page. // Static assets still load without auth; the SPA shell redirects early. webServer.tapIndex((html) => { const script = `` return html.replace('', `${script}`) }) // ── 4. Wrap webServer.register / registerUpgrade to protect every route ── // dsh 0.1.2 gates `/api` behind `requestRejection = trust fence (403) + // native-cookie check (401)` and `index.html` behind `authorizeIndex`, with // NO loopback exemption. This wrapper is the deny-by-default session layer: // every request must carry a valid `dsh_sid` (or be a genuine loopback // request). For shared API requests the same boundary is re-enforced at the // official `connection/request` waterfall (section 4b — the two layers are // mutual insurance against either seam rotting silently). // A valid native cookie alone is NOT accepted here — that cookie is // stateless, lives 30 days, and cannot be revoked, so logout / password // change / auth-reset only revoke `dsh_sid`; the wrapper is what keeps // those operations meaningful. // // Callers that pass this fence but lack the native cookie get it minted: // page navigations receive a 200 bounce document carrying the Set-Cookie // that navigates itself back to the same URL (see `mintBounceDocument` — // a 3xx mint is replayed on every hop by Safari/Firefox and ends in // ERR_TOO_MANY_REDIRECTS), so the very next request clears the native // fence. Non-navigation GET/HEAD callers keep the 3xx hop, which // fetch-style clients follow transparently. Non-navigations (RPC) are // forwarded untouched: the browser already holds the cookie from the page // hop, and a 303 would turn an RPC POST into a GET. While the upstream // signing secret has not appeared yet (the connection plugin creates it in // its own apply), minting is skipped and the next request retries. // // The wrapper must cover routes registered BEFORE this plugin activated: // cordis activation order is not the bundle/tree order (dynamic imports // finish out of order), so third-party plugins can register their routes // before web-auth runs. Their route objects live in the webserver's route // tables, so wrap them retroactively here. const originalRegister = webServer.register.bind(webServer) const originalRegisterUpgrade = webServer.registerUpgrade.bind(webServer) const originalRegisterFallback = webServer.registerFallback.bind(webServer) const wrappedHandlers = new WeakSet() const wrappedUpgrades = new WeakSet() const wrappedFallbacks = new WeakSet() /** * Routes that must stay anonymous: the login page, our own auth API, and * upstream's DeepSeek-account OAuth callback. * * The callback is registered by `@deepseek-ai/dsh-deepseek-account-platform` * (base bundle) for the duration of one sign-in attempt, at * `${origin}/oauth/callback`. It arrives as a cross-site top-level * navigation from the provider: our `dsh_sid` is `SameSite=Lax` so it * survives that hop, but a browser that never held the session (link opened * elsewhere, cookies cleared, a different container) would be redirected to * `/login` and the authorization code lost with it. The route is bound to a * single-use `state` + PKCE verifier held in memory and exists only while an * attempt is in flight, so leaving it anonymous adds no reachable surface. */ const isPublicRoute = (path: string): boolean => path === '/login' || path === '/oauth/callback' || path.startsWith('/api/auth/') /** Wrap a protected request handler with the session check + minting hop. */ const protect = (handler: (req: IncomingMessage, res: ServerResponse) => void | Promise) => async (req: IncomingMessage, res: ServerResponse): Promise => { if (!isAuthorized(req)) { // Send page navigations to the login page; upstream's own // unauthenticated index answer is a bare-text 401. if ((req.method === 'GET' || req.method === 'HEAD') && isPageNavigation(req)) { res.writeHead(302, { location: '/login', 'cache-control': 'no-store' }) res.end() return } jsonResponse(res, 401, { error: 'unauthorized' }) return } const audience = requestAudience(req.headers, secure) if (audience !== undefined && readBrowserCookie(req.headers, audience) === undefined && (req.method === 'GET' || req.method === 'HEAD')) { const minted = await mintBrowserCookie(req, secure) if (minted !== undefined) { // Only ever bounce to a path on this origin. An absolute-form // request target (`GET http://host/...`, `GET //host/...`) must // not turn the mint into an open redirect — the 303 era carried // that hole in its Location header, so guard both branches. const target = req.url ?? '/' const url = target.startsWith('/') && !target.startsWith('//') ? target : '/' if (isPageNavigation(req)) { // 200 bounce, never a 3xx: see `mintBounceDocument`. res.writeHead(200, { 'content-type': 'text/html; charset=utf-8', 'cache-control': 'no-store', 'set-cookie': minted, }) res.end(req.method === 'HEAD' ? undefined : mintBounceDocument(url)) return } res.writeHead(303, { location: url, 'cache-control': 'no-store', 'set-cookie': minted, }) res.end() return } } await handler(req, res) } /** * Wrap the fallback seat (frontend-static): it serves the whole dist — * the SPA index AND the static assets next to it. Only the index paths * stay guarded; every other fallback path is a public build artifact * (favicon.svg, bundled JS/CSS/...), and the login page itself references * `/favicon.svg`, which would render as a broken image behind a 401. * Unparseable request targets keep the full guard. */ const wrapFallback = (handler: WebRoute['handler']): WebRoute['handler'] => { if (wrappedFallbacks.has(handler)) return handler wrappedFallbacks.add(handler) const guarded = protect(handler) return async (req, res) => { let pathname: string try { pathname = new URL(req.url ?? '/', 'http://x').pathname } catch { await guarded(req, res) return } if ((req.method === 'GET' || req.method === 'HEAD') && pathname !== '/' && pathname !== '/index.html') { await handler(req, res) return } await guarded(req, res) } } const wrapHandler = (route: WebRoute): void => { if (wrappedHandlers.has(route) || isPublicRoute(route.path)) return wrappedHandlers.add(route) route.handler = protect(route.handler) } const wrapUpgradeHandler = (route: WebUpgradeRoute): void => { if (wrappedUpgrades.has(route) || isPublicRoute(route.path)) return wrappedUpgrades.add(route) const originalHandler = route.handler route.handler = (req, socket, head) => { if (!isAuthorized(req)) { socket.end('HTTP/1.1 401 Unauthorized\r\n\r\n') return } // Upgrade responses cannot carry a Set-Cookie mid-handshake; the // browser issues the WS request after the page (and its minting hop) // completed, so the native cookie is already in place. return originalHandler(req, socket, head) } } // Retroactively wrap routes that were already registered before this // plugin activated (third-party plugins may have won the activation race). // The index fallback seat is wrapped too: in 0.1.2 the SPA index is served // through `webServer.registerFallback` (frontend-static), which sits // OUTSIDE the exact/prefix route tables and would otherwise answer every // unauthenticated index request with upstream's bare-text 401. type RouteLike = WebRoute | WebResourceRoute type FallbackLike = WebRoute['handler'] | Pick const tables = webServer as unknown as { exact?: Map prefixes?: Map upgrades?: Map fallback?: FallbackLike serveResource?: ( req: IncomingMessage, res: ServerResponse, target: URL, resource: WebResourceRoute['resource'], ) => Promise } /** * dsh 0.2.2 serves a route or the fallback as a resource: a Fetch `Request` * maps to a `Response`. The Request carries no socket, so `protect`'s * loopback trust cannot run at that layer; the http dispatch point * (`serveResource`) still holds the node request and is where the session * boundary moves (see below). `WebRoute` keeps the handler shape. */ const isResourceRoute = (route: RouteLike): route is WebResourceRoute => typeof (route as { resource?: unknown }).resource === 'function' const isResourceFallback = (fallback: FallbackLike): fallback is Pick => typeof fallback !== 'function' && typeof (fallback as { resource?: unknown }).resource === 'function' /** * Whether a pathname is claimed by an exact/prefix route. Only fallback * dispatches ask: a named match means the responder is not the fallback, * which is all the guard needs (upstream's longest-prefix choice does not * change existence). */ const matchesNamedRoute = (pathname: string): boolean => { if (tables.exact?.has(pathname) === true) return true for (const prefix of tables.prefixes?.keys() ?? []) { if (pathname === prefix || pathname.startsWith(`${prefix}/`)) return true } return false } /** * A resource responder bypasses the registration wrappers unless the * dispatcher is interceptable. Refuse to activate rather than serve it * unprotected — this is the one failure mode that would be silent. */ const assertResourceDispatch = (): void => { if (typeof tables.serveResource !== 'function') { throw new Error( 'web-auth: this dsh version registers Web resource routes but webServer.serveResource is not interceptable; refusing to run without route protection', ) } } // ── 4a. Resource-form http dispatch (dsh 0.2.2+) ───────────────────────── // In 0.2.2 the SPA fallback (frontend-static) and the client-bundle route // (modules' `/plugins`) are resources. Guard before the dispatcher builds // its Request, so the node request (and its socket) is still available: // named resource routes get the same session boundary as handler routes; // the fallback keeps dist assets public and guards only the index paths, // exactly like `wrapFallback` above. In-process reads (`readResource`, used // by liveshare) never pass here: their caller already admitted the Peer. if (typeof tables.serveResource === 'function') { const originalServeResource = tables.serveResource.bind(webServer) tables.serveResource = async (req, res, target, resource) => { const pathname = target.pathname const anonymous = matchesNamedRoute(pathname) ? isPublicRoute(pathname) : (req.method === 'GET' || req.method === 'HEAD') && pathname !== '/' && pathname !== '/index.html' if (anonymous) { await originalServeResource(req, res, target, resource) return } await protect(() => originalServeResource(req, res, target, resource))(req, res) } } for (const route of tables.exact?.values() ?? []) if (!isResourceRoute(route)) wrapHandler(route) for (const route of tables.prefixes?.values() ?? []) if (!isResourceRoute(route)) wrapHandler(route) for (const route of tables.upgrades?.values() ?? []) wrapUpgradeHandler(route) if (tables.fallback !== undefined) { if (isResourceFallback(tables.fallback)) assertResourceDispatch() else tables.fallback = wrapFallback(tables.fallback) } const hasRetroResource = [...(tables.exact?.values() ?? []), ...(tables.prefixes?.values() ?? [])] .some(isResourceRoute) if (hasRetroResource) assertResourceDispatch() // Wrap routes registered from now on. webServer.register = (route: RouteLike) => { if (isResourceRoute(route)) assertResourceDispatch() else wrapHandler(route) return originalRegister(route) } webServer.registerUpgrade = (route: WebUpgradeRoute) => { wrapUpgradeHandler(route) return originalRegisterUpgrade(route) } webServer.registerFallback = (fallback: FallbackLike) => { if (isResourceFallback(fallback)) { assertResourceDispatch() return originalRegisterFallback(fallback) } return originalRegisterFallback(wrapFallback(fallback)) } // ── 4b. Shared-API session boundary at the official extension point ────── // `connection/request` (upstream since 0.1.6-alpha.2; available on every dsh // line this plugin tracks) is a waterfall dispatched by the connection // plugin's `/api` route AFTER upstream admission (trust fence + // native-cookie check) and before the shared API bridge. It is the one seam // upstream explicitly documents for wrapping shared API requests, so the // session boundary for `/api` is enforced HERE as well as at the // registration wrapper above — deliberately twice: // // - The wrapper is the deny-by-default + mint layer: it answers first // (302 for page navigations, JSON 401 otherwise) and mints the native // cookie BEFORE the request would reach upstream's admission. Minting // cannot move here: by the time a waterfall listener runs, admission has // already demanded the native cookie this listener would be minting. // - This listener is the authoritative revocability boundary for shared API // requests: a valid native cookie alone (30 days, stateless, unrevocable) // must never reach the bridge without a live `dsh_sid` (or genuine // loopback). If upstream ever reshapes route registration so the wrapper // silently stops wrapping, shared API requests still die here instead of // inheriting a native-cookie-only gate — and vice versa: if the waterfall // event is renamed away, the wrapper still guards every route. // // The mutual insurance covers the SHARED API only: the surfaces this // waterfall cannot see (index fallback, upgrades, third-party channels) are // wrapper-only, so a silent wrapper failure there falls back to upstream's // native-cookie gate — revocability lost, which is exactly why the native // cookie is never an API credential on its own. Keeping both seams healthy // is the upgrade sentinels' job: diff this event's declaration and dispatch // site on every dsh bump (docs/upgrade-dsh-0.2.0-playbook.md). // // Both layers share one predicate (`isAuthorized`), so there is a single // source of truth for what "a session" means. ctx.on('connection/request', async (request, response, next) => { if (!isAuthorized(request)) { jsonResponse(response, 401, { error: 'unauthorized' }) return } await next() }) // ── 5. Provide the auth service ─────────────────────────────────────────── const service: WebAuthService = { authenticate(request) { return isAuthorized(request) }, } ctx.provide('webAuth', service) ctx.logger.info('web-auth: active (bind host %s, tls %s, credentials: %s)', bindHost, secure ? 'on' : 'off', hasCredentials() ? 'set' : 'not set') void ctx.get(WEB_STARTUP_SERVICE) // ensure injection is satisfied }