/** * File-based credential store for the auth plugin. * * Stores username, password hash, and session HMAC secret in * `$DSH_HOME/web-auth.json` (`~/.dsh/web-auth.json` by default). Created on * first registration; read on every authentication and session-verification. */ import { readFileSync, writeFileSync, existsSync, mkdirSync, chmodSync } from 'node:fs' import { homedir } from 'node:os' import { join } from 'node:path' import { randomBytes, scryptSync, createHmac } from 'node:crypto' import { DEFAULT_SESSION_MAX_AGE_DAYS, isValidSessionMaxAgeDays, SESSION_MAX_AGE_CHOICES } from './session-limits.ts' /** Minimum password length for registration and the CLI password reset. */ export const MIN_PASSWORD_LENGTH = 8 /** * Normalize a username: strip C0 control characters (0x00-0x1F) and DEL * (0x7F), then trim surrounding whitespace. * * `String.prototype.trim()` alone only removes whitespace — keyboards/IMEs * can emit DEL and pasted text can carry invisible control characters, which * would otherwise be stored verbatim (issue #14). * @param raw - the raw username input. * @returns the sanitized username (possibly empty). */ export function normalizeUsername(raw: string): string { // eslint-disable-next-line no-control-regex return raw.replace(/[\u0000-\u001F\u007F]/g, '').trim() } /** * dsh's data directory, mirroring the harness's own resolution * (`@deepseek-ai/dsh-home-paths`): `$DSH_HOME` when set, otherwise `~/.dsh`. * * Reading the same root the harness reads keeps a custom-`DSH_HOME` deployment * (or a second instance used for testing) from silently sharing — and * overwriting — the credentials in the real `~/.dsh`. An empty or * whitespace-only `$DSH_HOME` counts as unset, so a blank override never * resolves the file against the current working directory. * @returns the harness home directory. */ function dshHomeDir(): string { const fromEnv = process.env.DSH_HOME return fromEnv !== undefined && fromEnv.trim().length > 0 ? fromEnv : join(homedir(), '.dsh') } /** The persisted credential file (overridable via DSH_WEB_AUTH_FILE for tests). */ function credentialFile(): string { return process.env.DSH_WEB_AUTH_FILE ?? join(dshHomeDir(), 'web-auth.json') } /** In-memory snapshot of the credential file (re-read on every auth). */ interface CredentialFile { /** The configured username. */ username: string /** `salt:hash` where hash = scryptSync(password, salt, 64)` */ passwordHash: string /** Random hex used to sign session cookies. */ secret: string /** When true, loopback requests need a session like every other address. */ requireLoopbackLogin?: boolean /** Admin-selected session lifetime in days (see session-limits.ts). */ sessionMaxAgeDays?: number /** When true, the login endpoint also demands a solved slider puzzle. */ slideVerification?: boolean } /** Hash a password with a salt using scrypt. */ function hashPassword(password: string, salt: string): string { const hash = scryptSync(password, salt, 64).toString('hex') return `${salt}:${hash}` } /** Generate a random salt (16 bytes hex). */ function makeSalt(): string { return randomBytes(16).toString('hex') } /** Generate a random session secret (32 bytes hex). */ function makeSecret(): string { return randomBytes(32).toString('hex') } /** * Read the credential file if it exists. * @returns the stored credentials, or `undefined` if not registered. */ function readCredentials(): CredentialFile | undefined { if (!existsSync(credentialFile())) return undefined try { return JSON.parse(readFileSync(credentialFile(), 'utf8')) as CredentialFile } catch { return undefined } } /** Ensure the credential directory exists (owner-only access). */ function ensureDir(): void { const dir = dshHomeDir() if (!existsSync(dir)) { mkdirSync(dir, { recursive: true, mode: 0o700 }) } } /** * Write the credential file (creates the directory if needed). * * The file is written owner-only (0o600): it holds the scrypt password hash * and the session HMAC secret, so group/other readers could crack the * password offline or forge session cookies outright. * @param data - the credentials to persist. */ function writeCredentials(data: CredentialFile): void { ensureDir() writeFileSync(credentialFile(), JSON.stringify(data, null, 2), { encoding: 'utf8', mode: 0o600 }) } /** * Restrict an existing credential file to owner-only access. * * Fixes files created by earlier versions that followed the process umask * (commonly 0o644), which would let other local users read the session * signing secret and forge cookies. No-op when the file does not exist yet. */ export function hardenCredentialFilePermissions(): void { if (existsSync(credentialFile())) { chmodSync(credentialFile(), 0o600) } } /** Whether a username/password has been registered. */ export function hasCredentials(): boolean { return readCredentials() !== undefined } /** * Register a new username/password. Throws if credentials already exist. * @param username - the username. * @param password - the password. * @returns the newly created secret (for session signing). */ export function registerCredentials(username: string, password: string): string { if (hasCredentials()) { throw new Error('web-auth: credentials already registered') } const salt = makeSalt() const secret = makeSecret() const passwordHash = hashPassword(password, salt) writeCredentials({ username, passwordHash, secret }) return secret } /** * Validate a username/password against the stored credentials. * @param username - the candidate username. * @param password - the candidate password. * @returns `true` if the credentials match. */ export function validateCredentials(username: string, password: string): boolean { const creds = readCredentials() if (creds === undefined) return false if (creds.username !== username) return false const [salt, storedHash] = creds.passwordHash.split(':') const candidateHash = hashPassword(password, salt) return candidateHash === creds.passwordHash } /** * Update stored credentials in a single write. * * Always rotates the session signing secret, which invalidates every already * issued session cookie — callers must re-issue a fresh session for the * authenticated user. * @param opts - the fields to replace; omitted fields keep their values. * @throws when no credentials exist yet. */ export function updateCredentials(opts: { username?: string; password?: string }): void { const creds = readCredentials() if (creds === undefined) { throw new Error('web-auth: no credentials to update') } writeCredentials({ ...creds, username: opts.username ?? creds.username, passwordHash: opts.password !== undefined ? hashPassword(opts.password, makeSalt()) : creds.passwordHash, secret: makeSecret(), }) } /** * Whether loopback requests must also present a session. * * Defaults to `false` (the historical behavior: a genuine loopback request is * implicitly trusted). Persisted next to the credentials because both share * one write path and one threat model. * @returns the persisted flag; `false` before registration. */ export function getRequireLoopbackLogin(): boolean { return readCredentials()?.requireLoopbackLogin === true } /** * Persist the loopback-login requirement. * * Refuses to enable the switch before any admin account exists: with no * credentials to log into, requiring sessions everywhere would lock out every * caller — loopback included — with only `auth-reset` as a recovery. Disabling * is always allowed (it re-opens the server). * @param value - the new flag value. * @throws when no credentials exist yet and `value` is `true`. */ export function setRequireLoopbackLogin(value: boolean): void { const creds = readCredentials() if (creds === undefined) { if (value) throw new Error('web-auth: register an administrator before requiring loopback login') return } if ((creds.requireLoopbackLogin === true) === value) return writeCredentials({ ...creds, requireLoopbackLogin: value }) } /** * Whether the login endpoint demands a solved slider puzzle. * * Defaults to `false`. The puzzle is decorative (see `src/slider/index.ts`), * so this is off unless someone turns it on for fun — but it still costs a * real step on every login, which is why it is never on by default. * @returns the persisted flag; `false` before registration. */ export function getSlideVerification(): boolean { return readCredentials()?.slideVerification === true } /** * Persist the slider-puzzle requirement. * * Refuses to enable the switch before any admin account exists, for the same * mechanical reason as {@link setRequireLoopbackLogin}: this flag lives in the * credential file, and that file's mere existence is what `hasCredentials()` * reads as "an administrator is registered". Writing one to hold a switch * would therefore make the registration form unreachable — the first admin * could never be created. Disabling is always allowed (and is a no-op with no * file to write). * @param value - the new flag value. * @throws when no credentials exist yet and `value` is `true`. */ export function setSlideVerification(value: boolean): void { const creds = readCredentials() if (creds === undefined) { if (value) throw new Error('web-auth: register an administrator before enabling the slider puzzle') return } if ((creds.slideVerification === true) === value) return writeCredentials({ ...creds, slideVerification: value }) } /** * The configured session lifetime, in days. * * Persisted next to the credentials because both share one write path. * Changing it only affects freshly issued cookies: the expiry is baked into * each session payload at signing time, so existing sessions keep their * original lifetime (unlike password changes, this never rotates the secret). * @returns the persisted lifetime; the default before registration or when * the stored value is not one of the selectable choices. */ export function getSessionMaxAgeDays(): number { const stored = readCredentials()?.sessionMaxAgeDays return isValidSessionMaxAgeDays(stored) ? stored : DEFAULT_SESSION_MAX_AGE_DAYS } /** * Persist the session lifetime. * @param days - the new lifetime in days (must be a selectable choice). * @throws when `days` is not one of the selectable choices, or when no * credentials exist yet. */ export function setSessionMaxAgeDays(days: number): void { if (!isValidSessionMaxAgeDays(days)) { throw new Error(`web-auth: session lifetime must be one of ${SESSION_MAX_AGE_CHOICES.join('/')}`) } const creds = readCredentials() if (creds === undefined) { throw new Error('web-auth: register an administrator before changing the session lifetime') } if (getSessionMaxAgeDays() === days) return writeCredentials({ ...creds, sessionMaxAgeDays: days }) } /** * Replace the stored password (keeps the username). * * Also rotates the session signing secret, which invalidates every already * issued session cookie — resetting a forgotten password therefore signs the * previous administrator out everywhere at once. * @param newPassword - the replacement password. * @throws when no credentials exist yet. */ export function resetPassword(newPassword: string): void { updateCredentials({ password: newPassword }) } /** * Change the stored password after verifying the old one. * * Rotates the session signing secret (like {@link resetPassword}), which * invalidates every already-issued session cookie — the caller must re-issue * a fresh session for the authenticated user. * @param oldPassword - the current password (verified against the store). * @param newPassword - the replacement password. * @returns `true` when the old password matched and the change was applied. */ export function changePassword(oldPassword: string, newPassword: string): boolean { const creds = readCredentials() if (creds === undefined) return false if (!validateCredentials(creds.username, oldPassword)) return false resetPassword(newPassword) return true } /** * Change the stored username after verifying the current password. * * Mirrors {@link changePassword}: rotates the session signing secret, which * invalidates every already-issued session cookie — the caller must re-issue * a fresh session for the authenticated user. * @param newUsername - the replacement username (already normalized). * @param currentPassword - the current password (verified against the store). * @returns `true` when the password matched and the change was applied. */ export function changeUsername(newUsername: string, currentPassword: string): boolean { const creds = readCredentials() if (creds === undefined) return false if (!validateCredentials(creds.username, currentPassword)) return false updateCredentials({ username: newUsername }) return true } /** * Get the configured username, if credentials are set. * @returns the username, or `undefined` when not registered. */ export function getUsername(): string | undefined { return readCredentials()?.username } /** * Get the session HMAC secret. * @returns the secret, or `undefined` if not registered. */ export function getSessionSecret(): string | undefined { const creds = readCredentials() return creds?.secret } /** * Sign a session payload (username + exp) with the stored secret. * @param payload - serialized JSON payload to sign. * @returns the signature (hex). */ export function signSession(payload: string): string | undefined { const secret = getSessionSecret() if (secret === undefined) return undefined return createHmac('sha256', secret).update(payload).digest('hex') } /** * Verify a signed session payload. * @param payload - the payload that was signed. * @param signature - the signature to verify. * @returns `true` if the signature matches. */ export function verifySession(payload: string, signature: string): boolean { const expected = signSession(payload) if (expected === undefined) return false // Constant-time comparison if (expected.length !== signature.length) return false let diff = 0 for (let i = 0; i < expected.length; i += 1) { diff |= expected.charCodeAt(i) ^ signature.charCodeAt(i) } return diff === 0 } /** @internal export for testing. */ export const internals = { credentialFile, makeSalt, makeSecret, hashPassword, readCredentials, writeCredentials, ensureDir, }