Merge #854: feat(auth): sign in through a trusted reverse proxy in multi-user mode (experimental)

This commit is contained in:
Codeman maintainer committed 2026-12-03 10:15:13 +01:00
commit 01380d8b26
20 files changed
+2374 -22

No files matched your search

+280
View File
@@ -0,0 +1,280 @@
/**
* @fileoverview Trusted reverse-proxy identity (multi-user mode, opt-in, off by default).
*
* Lets an authenticating reverse proxy on the same host (oauth2-proxy behind Caddy or
* nginx, Apache mod_auth_openidc, Authelia, ...) sign users in through an identity
* provider such as Entra ID, Google or Keycloak, instead of the Basic-auth password
* prompt. The proxy authenticates the person and forwards two headers:
*
* X-Codeman-Proxy-Secret: <the shared secret>
* X-Codeman-User: <codeman username>
*
* Codeman accepts the identity only when ALL of these hold:
* - multi-user mode is on (the username must name an existing, enabled account; there
* is no auto-provisioning, so an admin still decides who has an account);
* - a secret is configured: at least 32 printable ASCII characters, from
* `CODEMAN_TRUSTED_PROXY_SECRET_FILE` (preferred) or `CODEMAN_TRUSTED_PROXY_SECRET`;
* - the request arrives over a loopback socket (`req.ip`, which ignores
* X-Forwarded-For because Fastify runs with `trustProxy: false`);
* - the presented secret matches (timing-safe).
*
* What the secret does and does not separate: every process on the host reaches the
* loopback port, so loopback alone proves nothing, and the secret is what a local process
* lacks. It is not a boundary against code that can read the secret file or Codeman's
* memory, i.e. anything running as Codeman's OS account (see the multi-user threat
* model: sessions share that account). To keep it out of the obvious places, the value
* is read ONCE and both `CODEMAN_TRUSTED_PROXY_SECRET` and
* `CODEMAN_TRUSTED_PROXY_SECRET_FILE` are then deleted from `process.env`, because every
* session Codeman spawns inherits that environment. The file's resolved path stays in
* this module (`trustedProxySecretFilePath`, `trustedProxySecretFileRealPath`) for the
* sensitive-path blocklist.
*
* A configured setup that can't be used stops the server from starting
* (`trustedProxyConfigError`, thrown from `WebServer.start()`), so a typo never falls
* back silently to password sign-in.
*
* The two headers are taken off every request before anything else sees them
* (`takeTrustedProxyHeaders`, called from the first auth hook), so nothing downstream,
* e.g. the web-tab relay, can forward or log them.
*/
import { readFileSync, realpathSync, statSync } from 'node:fs';
import type { IncomingHttpHeaders } from 'node:http';
import { resolve } from 'node:path';
/** Header carrying the shared secret that proves the request came through the proxy. */
export const TRUSTED_PROXY_SECRET_HEADER = 'x-codeman-proxy-secret';
/** Default header carrying the authenticated Codeman username. */
export const DEFAULT_TRUSTED_PROXY_USER_HEADER = 'x-codeman-user';
/** Minimum secret length; a shorter secret stops the server from starting. */
export const TRUSTED_PROXY_SECRET_MIN_LENGTH = 32;
/**
* The username header is deleted from EVERY request (see takeTrustedProxyHeaders), so it
* must never be a header anything else needs. Allowed by shape, not by a deny list of
* standard headers: an `X-...` extension header (minus the reserved ones below) or the
* conventional `Remote-User`.
*/
const USER_HEADER_RE = /^x-[a-z0-9][a-z0-9-]*$/;
/** Identity headers authenticating proxies commonly send; allowed despite the reserved prefix. */
const ALLOWED_FORWARDED_IDENTITY_HEADERS = new Set([
'x-forwarded-user',
'x-forwarded-email',
'x-forwarded-preferred-username',
]);
const RESERVED_USER_HEADER_PREFIXES = ['x-forwarded-', 'x-codeman-'];
const RESERVED_USER_HEADERS = new Set([
'x-real-ip',
'x-requested-with',
'x-http-method-override',
'x-csrf-token',
'x-xsrf-token',
]);
/** Resolved trusted-proxy configuration, or null when the feature is off. */
export interface TrustedProxyConfig {
secret: string;
/** Lower-cased header name the username is read from. */
userHeader: string;
}
interface LoadedSecret {
secret?: string;
/** Why a configured secret can't be used (never contains the secret). */
problem?: string;
/** Absolute path of `CODEMAN_TRUSTED_PROXY_SECRET_FILE`, when it was set. */
filePath?: string;
/** That path with symlinks resolved, when it could be resolved. */
fileRealPath?: string;
}
let loaded: LoadedSecret | null = null;
/**
* Read the secret once, then delete `CODEMAN_TRUSTED_PROXY_SECRET` and
* `CODEMAN_TRUSTED_PROXY_SECRET_FILE` from `process.env` so sessions spawned later don't
* inherit either. Cached for the process lifetime.
*/
function loadSecret(): LoadedSecret {
if (loaded) return loaded;
const inline = process.env.CODEMAN_TRUSTED_PROXY_SECRET?.trim();
const file = process.env.CODEMAN_TRUSTED_PROXY_SECRET_FILE?.trim();
delete process.env.CODEMAN_TRUSTED_PROXY_SECRET;
delete process.env.CODEMAN_TRUSTED_PROXY_SECRET_FILE;
const filePath = file ? resolve(file) : undefined;
const fileRealPath = filePath ? realPathOrUndefined(filePath) : undefined;
let secret: string | undefined;
let problem: string | undefined;
if (inline && file) {
problem = 'both CODEMAN_TRUSTED_PROXY_SECRET and CODEMAN_TRUSTED_PROXY_SECRET_FILE are set; set only one';
} else if (file) {
try {
secret = readFileSync(file, 'utf-8').trim() || undefined;
if (!secret) problem = `CODEMAN_TRUSTED_PROXY_SECRET_FILE (${file}) is empty`;
// POSIX modes only; Windows reports synthetic ones.
else if (process.platform !== 'win32' && (statSync(file).mode & 0o077) !== 0) {
problem = `CODEMAN_TRUSTED_PROXY_SECRET_FILE (${file}) is readable by other users; chmod 600 it`;
}
} catch (err) {
problem = `cannot read CODEMAN_TRUSTED_PROXY_SECRET_FILE (${file}): ${(err as NodeJS.ErrnoException).code ?? 'error'}`;
}
} else if (inline) {
secret = inline;
}
if (secret && !problem) {
if (secret.length < TRUSTED_PROXY_SECRET_MIN_LENGTH) {
problem = `the trusted-proxy secret is shorter than ${TRUSTED_PROXY_SECRET_MIN_LENGTH} characters (generate one with: openssl rand -hex 32)`;
} else if (!/^[\x21-\x7e]+$/.test(secret)) {
// Header bytes arrive as latin1 and the env/file value as UTF-8, so anything outside
// printable ASCII could never match.
problem =
'the trusted-proxy secret must be printable ASCII without spaces (generate one with: openssl rand -hex 32)';
}
}
loaded = { secret, problem, filePath, fileRealPath };
return loaded;
}
function realPathOrUndefined(path: string): string | undefined {
try {
return realpathSync(path);
} catch {
return undefined;
}
}
/**
* Read the secret now and remove both variables from `process.env`. Called first in
* `WebServer.start()` and again (a no-op then) at auth setup, before any session is
* spawned or restored, in every mode.
*/
export function initTrustedProxySecret(): void {
loadSecret();
}
/**
* Absolute path of the configured secret file, or null. After the secret was read the
* variable is gone from `process.env`, so this answers from the cached value; before
* that, from the environment. Never reads the file.
*/
export function trustedProxySecretFilePath(): string | null {
if (loaded) return loaded.filePath ?? null;
const file = process.env.CODEMAN_TRUSTED_PROXY_SECRET_FILE?.trim();
return file ? resolve(file) : null;
}
/**
* The secret file's path with symlinks resolved, or null (not configured, or it can't be
* resolved). Resolved once when the secret is read; before that, from the environment.
*/
export function trustedProxySecretFileRealPath(): string | null {
if (loaded) return loaded.fileRealPath ?? null;
const file = trustedProxySecretFilePath();
return (file && realPathOrUndefined(file)) ?? null;
}
/** Test-only: forget the cached secret so the next call re-reads the environment. */
export function resetTrustedProxySecretForTests(): void {
loaded = null;
}
/** The configured username header (lower-cased), or the default. Not validated. */
function rawUserHeader(): string {
return process.env.CODEMAN_TRUSTED_PROXY_USER_HEADER?.trim().toLowerCase() || DEFAULT_TRUSTED_PROXY_USER_HEADER;
}
/** Why the configured username header can't be used, or null when it is fine. */
function userHeaderProblem(name: string): string | null {
if (name === DEFAULT_TRUSTED_PROXY_USER_HEADER || name === 'remote-user') return null;
if (ALLOWED_FORWARDED_IDENTITY_HEADERS.has(name)) return null;
if (!USER_HEADER_RE.test(name)) {
return `CODEMAN_TRUSTED_PROXY_USER_HEADER (${name}) must be an X-... header or Remote-User`;
}
if (RESERVED_USER_HEADERS.has(name) || RESERVED_USER_HEADER_PREFIXES.some((p) => name.startsWith(p))) {
return `CODEMAN_TRUSTED_PROXY_USER_HEADER may not be ${name} (reserved)`;
}
return null;
}
/**
* The username header to strip and read: the configured one when it is usable, the default
* otherwise. Resolve it once (at auth setup) and pass it to `takeTrustedProxyHeaders`. A
* rejected name is never used, so a careless setting can't strip a header others need.
*/
export function resolveTrustedProxyUserHeader(): string {
const name = rawUserHeader();
return userHeaderProblem(name) ? DEFAULT_TRUSTED_PROXY_USER_HEADER : name;
}
/**
* The active configuration, or null when the feature is off: no usable secret, an
* unusable username header, or single-user mode (no named accounts to map onto). The
* unusable cases also stop the start (`trustedProxyConfigError`); this is the second layer.
*/
export function getTrustedProxyConfig(multiUser: boolean): TrustedProxyConfig | null {
const { secret, problem } = loadSecret();
if (!multiUser || !secret || problem) return null;
const userHeader = rawUserHeader();
if (userHeaderProblem(userHeader)) return null;
return { secret, userHeader };
}
/**
* Why a configured trusted-proxy setup can't be used, as the message for the start-up
* refusal, or null when it is fine (not configured, or valid). Never includes the secret.
* Refused: both secret variables set; a secret file that can't be read, is empty or is
* readable by group or others (not checked on Windows); a secret shorter than 32
* characters or not printable ASCII; a secret with multi-user mode off; and a
* `CODEMAN_TRUSTED_PROXY_USER_HEADER` the validation rejects (set at all, secret or not).
*/
export function trustedProxyConfigError(multiUser: boolean): string | null {
const { secret, problem } = loadSecret();
let reason: string | null = null;
if (problem) reason = problem;
else if (secret && !multiUser) reason = 'a trusted-proxy secret is set but multi-user mode is off';
else if (process.env.CODEMAN_TRUSTED_PROXY_USER_HEADER?.trim()) reason = userHeaderProblem(rawUserHeader());
return reason
? `Trusted-proxy sign-in is misconfigured: ${reason}. Fix or remove the setting and start again.`
: null;
}
/** What a request presented, after `takeTrustedProxyHeaders` removed the headers. */
export interface PresentedProxyHeaders {
/** True when the secret header was present at all, even empty. */
secretPresent: boolean;
/** The presented secret (duplicates joined with ", ", so they never match). */
secret: string;
/**
* The presented username exactly as sent ('' when absent). The auth hook normalizes and
* validates it with the user store's own rule. A duplicated header arrives joined
* ("alice, bob"), which that rule rejects, so it is refused with 403.
*/
user: string;
}
/**
* Read the trusted-proxy headers and DELETE them from `headers`, so nothing that later
* copies request headers (the web-tab relay, logging) ever sees the secret. Removes the
* secret header, the default username header and `userHeader` (from
* `resolveTrustedProxyUserHeader`, so always a usable name), whether or not the feature is
* on: a proxy may send them to an instance that has it off.
*/
export function takeTrustedProxyHeaders(
headers: IncomingHttpHeaders,
userHeader: string = DEFAULT_TRUSTED_PROXY_USER_HEADER
): PresentedProxyHeaders {
const rawSecret = headers[TRUSTED_PROXY_SECRET_HEADER];
const rawUser = headers[userHeader];
delete headers[TRUSTED_PROXY_SECRET_HEADER];
delete headers[DEFAULT_TRUSTED_PROXY_USER_HEADER];
delete headers[userHeader];
return {
secretPresent: rawSecret !== undefined,
secret: Array.isArray(rawSecret) ? rawSecret.join(', ') : (rawSecret ?? ''),
user: Array.isArray(rawUser) ? rawUser.join(', ') : (rawUser ?? ''),
};
}
+6
View File
@@ -50,6 +50,12 @@ export interface UsersFile {
export interface AuthUser {
username: string;
role: UserRole;
/**
* True when a trusted reverse proxy vouched for this request (see
* src/config/trusted-proxy.ts), so no Codeman password was involved. Absent for
* cookie, Basic and QR sign-ins.
*/
viaTrustedProxy?: boolean;
}
/** Admin-facing projection of a user: never carries the password hash. */
+245 -7
View File
@@ -10,6 +10,7 @@
import type { FastifyInstance, FastifyReply, FastifyRequest } from 'fastify';
import { createHash, randomBytes, timingSafeEqual } from 'node:crypto';
import { posix } from 'node:path';
import { StaleExpirationMap } from '../../utils/index.js';
import type { AuthSessionRecord } from '../ports/auth-port.js';
import { isAllowedRequestHost, isAllowedRequestOrigin, type HostPolicy } from '../network-auth-policy.js';
@@ -22,9 +23,25 @@ import {
} from '../../config/auth-config.js';
import { getHookSecret, HOOK_SECRET_HEADER } from '../../config/hook-secret.js';
import { isMultiUserMode } from '../../config/multiuser.js';
import { findUser, setPassword, touchLastLogin, verifyPassword } from '../../user-store.js';
import {
getTrustedProxyConfig,
initTrustedProxySecret,
resolveTrustedProxyUserHeader,
takeTrustedProxyHeaders,
type PresentedProxyHeaders,
type TrustedProxyConfig,
} from '../../config/trusted-proxy.js';
import {
findUser,
isValidUsername,
normalizeUsername,
setPassword,
touchLastLogin,
verifyPassword,
} from '../../user-store.js';
import { webviewCapabilities } from '../../webview-capabilities.js';
import { capabilityFromHtmlViewPath, htmlViewCapabilities } from '../../html-view-capabilities.js';
import { capabilityFromHtmlViewPath, HTML_VIEW_PREFIX, htmlViewCapabilities } from '../../html-view-capabilities.js';
import { WEBVIEW_PROXY_PREFIX } from '../../config/webview-limits.js';
import {
capabilityFromProxyPath,
capabilityFromReferer,
@@ -56,6 +73,8 @@ interface AuthState {
userFailures: StaleExpirationMap<string, number> | null;
/** Per-(username, client IP) Basic-auth failure bucket (multi-user only). */
userIpFailures: StaleExpirationMap<string, number> | null;
/** Wrong trusted-proxy secret presentations, per client IP (multi-user + proxy secret only). */
proxySecretFailures: StaleExpirationMap<string, number> | null;
}
/** Rate-limit response for a client that exceeded the failure cap. */
@@ -118,9 +137,7 @@ function checkHookSecretBypass(
hookSecretFailures: StaleExpirationMap<string, number>
): 'bypass' | 'rejected' | 'continue' {
if ((req.url === '/api/hook-event' || req.url === '/api/status-telemetry') && req.method === 'POST') {
const ip = req.ip;
const isLoopback = ip === '127.0.0.1' || ip === '::1' || ip === '::ffff:127.0.0.1';
if (isLoopback) {
if (isLoopbackIp(req.ip)) {
const presented = Buffer.from(req.headers[HOOK_SECRET_HEADER.toLowerCase()]?.toString() ?? '');
const expected = Buffer.from(getHookSecret());
if (presented.length === expected.length && timingSafeEqual(presented, expected)) {
@@ -141,6 +158,111 @@ function checkHookSecretBypass(
return 'continue';
}
/** Whether a socket address is loopback. The one test both secret-gated paths (hook, proxy) use. */
function isLoopbackIp(ip: string): boolean {
return ip === '127.0.0.1' || ip === '::1' || ip === '::ffff:127.0.0.1';
}
/**
* The trusted-proxy headers each request presented, keyed by request. Filled by the first
* auth hook (`registerTrustedProxyHeaderStrip`), which also deletes the headers from the
* request; read by `checkTrustedProxyIdentity`. A WeakMap, so nothing outlives the request.
*/
const presentedProxyHeaders = new WeakMap<FastifyRequest, PresentedProxyHeaders>();
/** Minimum interval between `touchLastLogin` writes for proxy sign-ins, per user. */
const PROXY_LAST_LOGIN_INTERVAL_MS = 15 * 60 * 1000;
/**
* Take the trusted-proxy headers off EVERY request before any other auth logic, route or
* exemption (web-tab relay, HTML view, QR) can see them, in every auth mode. Registered
* first in `registerAuthMiddleware`, i.e. right after the Host guard.
*/
function registerTrustedProxyHeaderStrip(app: FastifyInstance): void {
const userHeader = resolveTrustedProxyUserHeader();
app.addHook('onRequest', (req, _reply, done) => {
presentedProxyHeaders.set(req, takeTrustedProxyHeaders(req.headers, userHeader));
done();
});
}
/**
* Trusted reverse-proxy identity (see src/config/trusted-proxy.ts). Returns:
* - 'continue' : no proxy secret header; fall through to cookie / Basic auth
* - 'authenticated' : req.authUser is set from the proxy's username header
* - 'rejected' : a reply was already sent
*
* Fails CLOSED once the secret header is present at all, even empty: a wrong secret or a
* non-loopback source (401), or a missing username, one the user store's rule rejects,
* or one with no enabled account (403, no challenge) is refused outright and never falls
* through to the cookie or Basic paths, so a misconfigured proxy cannot silently degrade
* into some other identity. A username header WITHOUT the secret header is ignored
* (normal auth applies).
*
* The username is matched exactly, by the store's own rule (`normalizeUsername`, then
* `isValidUsername`): no cutting at `@`, no character replacement. A duplicated header
* arrives joined ("alice, bob") and fails that rule.
*
* The secret is compared BEFORE the failure bucket is consulted, like the hook secret:
* a correct secret always passes, so local junk requests (which share 127.0.0.1 with
* the proxy) cannot lock sign-in out. Only failures are counted and throttled, in their
* own per-IP bucket, so a broken proxy cannot lock out the Basic or hook paths either.
*/
async function checkTrustedProxyIdentity(
req: FastifyRequest,
reply: FastifyReply,
config: TrustedProxyConfig,
proxySecretFailures: StaleExpirationMap<string, number>,
lastLoginTouched: Map<string, number>
): Promise<'continue' | 'authenticated' | 'rejected'> {
const presented = presentedProxyHeaders.get(req);
if (!presented?.secretPresent) return 'continue';
const clientIp = req.ip;
const given = Buffer.from(presented.secret);
const expected = Buffer.from(config.secret);
const secretOk = isLoopbackIp(clientIp) && given.length === expected.length && timingSafeEqual(given, expected);
if (!secretOk) {
const failures = proxySecretFailures.get(clientIp) ?? 0;
if (failures >= AUTH_FAILURE_MAX) {
sendAuthRateLimit(reply, proxySecretFailures, clientIp);
return 'rejected';
}
proxySecretFailures.set(clientIp, failures + 1);
reply.code(401).send('Unauthorized: trusted proxy secret rejected');
return 'rejected';
}
// The proxy vouched for the request, so none of the refusals below is a failed guess:
// 403, no challenge, no bucket.
const username = normalizeUsername(presented.user);
if (!username) {
reply.code(403).send('Forbidden: trusted proxy sent no username');
return 'rejected';
}
let user: Awaited<ReturnType<typeof findUser>>;
try {
user = isValidUsername(username) ? await findUser(username) : undefined;
} catch {
reply.code(503).send('Service Unavailable: user store unreadable');
return 'rejected';
}
if (!user || user.disabled) {
reply.code(403).send('Forbidden: no enabled Codeman account for this user');
return 'rejected';
}
// No mustChangePassword lockbox: the person did not sign in with a Codeman password,
// so a pending one-time password has nothing to do with this request.
req.authUser = { username: user.username, role: user.role, viaTrustedProxy: true };
// Keep "last login" meaningful for proxy sign-ins, without a store write per request.
const now = Date.now();
if (now - (lastLoginTouched.get(user.username) ?? 0) >= PROXY_LAST_LOGIN_INTERVAL_MS) {
lastLoginTouched.set(user.username, now);
void touchLastLogin(user.username).catch(() => {});
}
return 'authenticated';
}
/**
* Requests that a `mustChangePassword` user may still reach: the identity probe,
* the password-change endpoint, and any non-API path (static assets / index.html,
@@ -275,6 +397,80 @@ export function isLostWebviewRootFrame(req: FastifyRequest): boolean {
return !carriesAuthCredentials(req.headers, AUTH_COOKIE_NAME);
}
/**
* Which capability prefix a request falls under, judged the way a reverse proxy's path
* matcher does: query dropped, percent-decoded once, dot segments and doubled slashes
* resolved, case-insensitive. A proxy forwards everything it matches this way WITHOUT its
* sign-in, so the refusal below must recognise every such spelling, not only the literal
* one Codeman's own routes use. Any token shape counts: a malformed token is still a
* request the proxy let through.
*
* `rawUrl` has been through `stripBasePath()`, which removes the mount prefix only in its
* literal spelling, so under `basePath` a re-spelled prefix (`/CODEMAN/webview/x`,
* `/%63odeman/...`, `//codeman/...`, `/x/../codeman/...`) is still in front. So the
* normalised path is judged as it is first, and only when that is no capability path and
* it starts with the lower-cased base path, once more with the base path removed once.
* Either match counts. As it is comes first because the literal prefix may already be
* gone: under a mount named `/webview`, `/webview/webview/x` arrives as `/webview/x`, and
* removing the base again would lose the capability prefix itself.
*/
export function capabilityPrefixOf(rawUrl: string, basePath = ''): 'webview' | 'html-view' | null {
let path = rawUrl.split('?')[0];
try {
path = decodeURIComponent(path);
} catch {
// Malformed escape: judge the raw path.
}
// Fold U+0130 (capital I with dot above) to a plain "i" first: Go's lowercasing, which
// Caddy's matcher uses, does that, while toLowerCase() yields "i" + U+0307 and would miss
// the prefix. Written as an escape so Unicode normalisation can't split it.
path = posix
.normalize(path)
.replace(/\u0130/g, 'i')
.toLowerCase();
const asIs = capabilityPrefixOfNormalised(path);
if (asIs) return asIs;
const base = basePath.toLowerCase();
return base && path.startsWith(`${base}/`) ? capabilityPrefixOfNormalised(path.slice(base.length)) : null;
}
function capabilityPrefixOfNormalised(path: string): 'webview' | 'html-view' | null {
if (path.startsWith(`${WEBVIEW_PROXY_PREFIX}/`)) return 'webview';
if (path.startsWith(`${HTML_VIEW_PREFIX}/`)) return 'html-view';
return null;
}
/**
* A request under a capability prefix (`/webview/...`, `/html-view/...`, judged by
* `capabilityPrefixOf`) that the capability exemptions above did NOT let through: no live
* capability, whatever the token looks like (or a method the exemption never covers).
* Refused here with what the route answers an authenticated caller for an unknown
* capability (403 for a web tab, 404 for an HTML view), WITHOUT a Basic challenge and
* WITHOUT counting a failure.
*
* Only used when trusted-proxy sign-in is configured. There, these paths reach Codeman
* WITHOUT the proxy's own sign-in (their sandboxed frames carry no credentials, so the
* proxy has to let them through; see the trusted-proxy docs). Falling through to the
* credential checks would expose the password check and a `WWW-Authenticate` prompt to
* anyone who can reach the proxy, and let anonymous requests fill the per-IP failure
* bucket, which behind the proxy is always 127.0.0.1, locking out Basic sign-in from
* loopback. Without a proxy, these paths keep the normal 401 challenge.
*
* @returns true when the reply was sent.
*/
function serveRefusedCapabilityPath(req: FastifyRequest, reply: FastifyReply, basePath = ''): boolean {
const kind = capabilityPrefixOf(req.url ?? '', basePath);
if (kind === 'webview') {
reply.code(403).type('text/plain').send('Forbidden: unknown or expired webview capability');
return true;
}
if (kind === 'html-view') {
reply.code(404).header('Content-Type', 'text/plain; charset=utf-8').send('Not found');
return true;
}
return false;
}
/** Send the static recovery page (lostWebviewFramePage) with its own CSP, uncached. */
export function sendLostWebviewFramePage(reply: FastifyReply): FastifyReply {
reply.header('content-security-policy', LOST_FRAME_PAGE_CSP);
@@ -329,12 +525,18 @@ export function registerAuthMiddleware(app: FastifyInstance, https: boolean, bas
hookSecretFailures: null,
userFailures: null,
userIpFailures: null,
proxySecretFailures: null,
};
// Always declare req.authUser so downstream reads are safe (single-user leaves it
// undefined; the ownership helpers then default to a synthetic admin).
if (!app.hasRequestDecorator('authUser')) app.decorateRequest('authUser', undefined);
// First, in every auth mode: take the trusted-proxy headers off the request, so no
// later hook, exemption or route (e.g. the web-tab relay) can forward the secret.
registerTrustedProxyHeaderStrip(app);
initTrustedProxySecret();
const multiUser = isMultiUserMode();
const authPassword = process.env.CODEMAN_PASSWORD;
@@ -395,6 +597,15 @@ export function registerAuthMiddleware(app: FastifyInstance, https: boolean, bas
ttlMs: AUTH_FAILURE_WINDOW_MS,
refreshOnGet: false,
});
// Trusted reverse-proxy identity (opt-in). Its own failure bucket, like the hook
// secret's, so wrong proxy secrets never count against the Basic login path.
const trustedProxy = getTrustedProxyConfig(true);
if (trustedProxy) {
state.proxySecretFailures = new StaleExpirationMap<string, number>({
ttlMs: AUTH_FAILURE_WINDOW_MS,
refreshOnGet: false,
});
}
registerMultiUserAuthHook(
app,
https,
@@ -403,7 +614,10 @@ export function registerAuthMiddleware(app: FastifyInstance, https: boolean, bas
hookSecretFailures,
state.userFailures,
state.userIpFailures,
basePath
basePath,
trustedProxy && state.proxySecretFailures
? { config: trustedProxy, failures: state.proxySecretFailures, lastLoginTouched: new Map<string, number>() }
: null
);
return state;
}
@@ -534,7 +748,12 @@ function registerMultiUserAuthHook(
hookSecretFailures: StaleExpirationMap<string, number>,
userFailures: StaleExpirationMap<string, number>,
userIpFailures: StaleExpirationMap<string, number>,
basePath = ''
basePath = '',
trustedProxy: {
config: TrustedProxyConfig;
failures: StaleExpirationMap<string, number>;
lastLoginTouched: Map<string, number>;
} | null = null
): void {
const setSessionCookie = (reply: FastifyReply, token: string) =>
reply.setCookie(AUTH_COOKIE_NAME, token, {
@@ -658,6 +877,25 @@ function registerMultiUserAuthHook(
if (hasValidHtmlViewCapability(req)) return;
// A web-tab frame that lost its prefix: hand it back to its tab, no credentials involved.
if (serveLostWebviewFrame(req, reply)) return;
// Behind an authenticating proxy, capability paths reach Codeman without the proxy's
// sign-in: refuse a non-exempt one with the route's own answer, no challenge, no count.
if (trustedProxy && serveRefusedCapabilityPath(req, reply, basePath)) return;
// 0. Trusted reverse-proxy identity, checked BEFORE the cookie: when the proxy
// vouches for a person on this request, that is authoritative, and a stale cookie
// from an earlier Basic login in the same browser must not override it. No cookie
// is minted: the proxy presents the identity on every new request and WebSocket
// upgrade. A stream that is already open is not re-checked.
if (trustedProxy) {
const proxied = await checkTrustedProxyIdentity(
req,
reply,
trustedProxy.config,
trustedProxy.failures,
trustedProxy.lastLoginTouched
);
if (proxied !== 'continue') return;
}
const clientIp = req.ip;
+6 -2
View File
@@ -1,7 +1,7 @@
/**
* @fileoverview Self-service identity routes (multi-user + single-user).
*
* - GET /api/me : who am I ({ username, role, mustChangePassword }).
* - GET /api/me : who am I ({ username, role, mustChangePassword, viaTrustedProxy }).
* Works in single-user mode too, returning the synthetic
* admin so the frontend has one "am I admin" code path.
* - POST /api/me/password : change my own password (verifies the current one,
@@ -35,13 +35,17 @@ export function registerMeRoutes(app: FastifyInstance, ctx: AuthPort): void {
}
const user = getAuthUser(req);
const record = await findUser(user.username);
// A trusted-proxy sign-in never used the Codeman password, so a pending one-time
// password must not open the forced change-password modal (admin-ui.js).
const viaTrustedProxy = !!user.viaTrustedProxy;
return {
success: true,
data: {
username: user.username,
role: user.role,
mustChangePassword: !!record?.mustChangePassword,
mustChangePassword: viaTrustedProxy ? false : !!record?.mustChangePassword,
multiUser: true,
viaTrustedProxy,
},
};
});
+17
View File
@@ -34,6 +34,7 @@
import { homedir } from 'node:os';
import { join } from 'node:path';
import { trustedProxySecretFilePath, trustedProxySecretFileRealPath } from '../config/trusted-proxy.js';
const SENSITIVE_PATTERNS: RegExp[] = [
// System account databases.
@@ -81,6 +82,9 @@ const SENSITIVE_PATTERNS: RegExp[] = [
// Named individually so the surrounding trees stay attachable (see above).
/\/\.claude\/\.credentials\.json$/,
/\/\.codeman[^/]*\/hook-secret$/,
// Trusted reverse-proxy secret under its documented name (the configured path, whatever
// its name, is checked separately in isSensitivePath).
/\/\.codeman[^/]*\/proxy-secret$/,
/\/\.codeman[^/]*\/users\.json$/,
// The data dir's `.env` is the CODEMAN_USERNAME/PASSWORD fallback `codeman attach`
// reads. Named here as well as in DOTENV_PATTERNS so `allowDotenv` (the File
@@ -153,6 +157,18 @@ const DOTENV_PATTERNS: RegExp[] = [/\/\.env$/, /\/\.env\./];
*/
const HOME_SENSITIVE_MEMBERS = ['.claude.json', '.claude/settings.json', '.claude/settings.local.json'];
/**
* Whether `absPath` is the configured trusted-proxy secret file
* (`CODEMAN_TRUSTED_PROXY_SECRET_FILE`, any name and location). The variable is removed
* from `process.env` once the secret is read, so the path comes from the trusted-proxy
* module, which keeps it, as configured and with symlinks resolved (resolved once).
*/
function isTrustedProxySecretFile(absPath: string): boolean {
const file = trustedProxySecretFilePath();
if (!file) return false;
return absPath === file || absPath === trustedProxySecretFileRealPath();
}
/**
* Returns true if the given ABSOLUTE, symlink-resolved path matches the
* sensitive-file blocklist and must not be served to the browser.
@@ -162,6 +178,7 @@ const HOME_SENSITIVE_MEMBERS = ['.claude.json', '.claude/settings.json', '.claud
export function isSensitivePath(absPath: string, opts: { allowDotenv?: boolean } = {}): boolean {
if (!opts.allowDotenv && DOTENV_PATTERNS.some((pattern) => pattern.test(absPath))) return true;
if (SENSITIVE_PATTERNS.some((pattern) => pattern.test(absPath))) return true;
if (isTrustedProxySecretFile(absPath)) return true;
const home = homedir();
return HOME_SENSITIVE_MEMBERS.some((member) => absPath === join(home, member));
}
+26
View File
@@ -216,6 +216,7 @@ import {
sendLostWebviewFramePage,
} from './middleware/auth.js';
import { isMultiUserMode } from '../config/multiuser.js';
import { getTrustedProxyConfig, initTrustedProxySecret, trustedProxyConfigError } from '../config/trusted-proxy.js';
import { bootstrapInitialAdmin, findUser, hasUsers, resolveClaudeModeForUsername } from '../user-store.js';
import { installRouteErrorHandler } from './route-error-handler.js';
import { installEmptyApiPostParser } from './request-body-parser.js';
@@ -586,6 +587,7 @@ export class WebServer extends EventEmitter {
private hookSecretFailures: StaleExpirationMap<string, number> | null = null;
private userFailures: StaleExpirationMap<string, number> | null = null;
private userIpFailures: StaleExpirationMap<string, number> | null = null;
private proxySecretFailures: StaleExpirationMap<string, number> | null = null;
private pushStore: PushSubscriptionStore = new PushSubscriptionStore();
/** ntfy / Slack / Discord / generic webhook for the push events; config in webhook.json (0600). */
private webhookNotifier = new WebhookNotifier(() => readWebhookConfig(getDataDir()), webviewFetch);
@@ -1119,6 +1121,7 @@ export class WebServer extends EventEmitter {
this.hookSecretFailures = authState.hookSecretFailures;
this.userFailures = authState.userFailures;
this.userIpFailures = authState.userIpFailures;
this.proxySecretFailures = authState.proxySecretFailures;
}
// Bodyless API POSTs may arrive as empty chunked streams through a proxy.
@@ -3470,6 +3473,14 @@ export class WebServer extends EventEmitter {
}
async start(): Promise<void> {
// Trusted reverse-proxy sign-in (opt-in): read the secret now, which also removes it
// and the file path from process.env, and refuse to start on a configured setup that
// can't be used, so a typo never falls back silently to password sign-in. Not skipped
// in test mode: the refusal itself is under test.
initTrustedProxySecret();
const proxyConfigError = trustedProxyConfigError(isMultiUserMode());
if (proxyConfigError) throw new Error(proxyConfigError);
// Multi-user first boot: create the initial admin from CODEMAN_USERNAME/PASSWORD
// if there are no users yet, else refuse to start (there would be no way in).
if (isMultiUserMode() && !this.testMode) {
@@ -3661,6 +3672,17 @@ export class WebServer extends EventEmitter {
}
}
// Trusted reverse-proxy sign-in (opt-in): say when it is on. An unusable setup never
// gets here (refused at the top of start()).
const proxyConfig = getTrustedProxyConfig(isMultiUserMode());
if (proxyConfig) {
console.log(
palette.muted(
`Trusted-proxy sign-in enabled (experimental): loopback requests with the proxy secret sign in as the account named in ${proxyConfig.userHeader}.`
)
);
}
// Set API URL for child processes (MCP server, spawned sessions)
const apiHost =
this.host === '0.0.0.0' || this.host === 'localhost' || this.host === '::1' ? '127.0.0.1' : this.host;
@@ -4886,6 +4908,10 @@ export class WebServer extends EventEmitter {
this.userIpFailures.dispose();
this.userIpFailures = null;
}
if (this.proxySecretFailures) {
this.proxySecretFailures.dispose();
this.proxySecretFailures = null;
}
this.activePlanOrchestrators.clear();
this.cleaningUp.clear();
this.killingSessions.clear();
+11 -1
View File
@@ -45,6 +45,7 @@
import { createHash } from 'node:crypto';
import { WEBVIEW_PROXY_PREFIX } from '../config/webview-limits.js';
import { stripBasePath } from '../config/base-path.js';
import { resolveTrustedProxyUserHeader } from '../config/trusted-proxy.js';
/** Headers that are per-connection and must never be relayed in either direction. */
const HOP_BY_HOP = new Set([
@@ -76,6 +77,12 @@ const DROP_REQUEST_HEADERS = new Set([
'origin',
'referer',
'x-codeman-hook-secret',
// Trusted reverse-proxy sign-in headers. The auth middleware already deletes them from
// every request (takeTrustedProxyHeaders); listed here too so the relay never forwards
// them even if that ever changes. A custom username header name
// (CODEMAN_TRUSTED_PROXY_USER_HEADER) is added per request in buildUpstreamRequestHeaders.
'x-codeman-proxy-secret',
'x-codeman-user',
]);
/** Response headers dropped on the way back to the browser. */
@@ -409,10 +416,13 @@ export function buildUpstreamRequestHeaders(
}
): Record<string, string> {
const headers: Record<string, string> = {};
// The configured trusted-proxy username header (the default name is already in
// DROP_REQUEST_HEADERS). Only ever a name that passed validation.
const proxyUserHeader = resolveTrustedProxyUserHeader();
for (const [key, value] of Object.entries(incoming)) {
const lower = key.toLowerCase();
if (DROP_REQUEST_HEADERS.has(lower)) continue;
if (DROP_REQUEST_HEADERS.has(lower) || lower === proxyUserHeader) continue;
if (value === undefined) continue;
headers[lower] = Array.isArray(value) ? value.join(', ') : value;
}