Multiplayer agent harness for work.
Add password sign-in to the built-in auth broker (#1549)
Joshua France3459f8012c8b
diff --git a/cli/README.md b/cli/README.mdindex eb47506bc..785bdf36f 100644--- a/cli/README.md+++ b/cli/README.md@@ -199,7 +199,11 @@ environment. The CLI prints only the URL, which is a temporary login credential;do not publish it or put it in shared logs.`qm setup` offers email setup separately. Skip it to use administrator login-without Resend or SMTP. To enable ordinary email login later, rerun `qm setup`+without Resend or SMTP. For ordinary users before email is ready, the broker can+accept passwords: hash one with `node plugins/auth/src/hash-password.ts[email protected]` and store the output with `qm secrets set AUTH_PASSWORD_USERS`.+This is meant for onboarding; switch to email links or an identity provider+afterwards. To enable ordinary email login later, rerun `qm setup`and configure the selected transport's complete credential set and sender,then push secrets and redeploy. Missing email credentials disable email sign-in;QM and `qm admin-login` remain available, even if a sender is still configured.diff --git a/cli/src/commands/setup.ts b/cli/src/commands/setup.tsindex 28edec049..666214dd1 100644--- a/cli/src/commands/setup.ts+++ b/cli/src/commands/setup.ts@@ -71,6 +71,12 @@ const PLAYBOOKS: Readonly<Record<string, readonly string[]>> = {"refused, both when a link is requested and again when one is opened.","Set env.auth.AUTH_ALLOWED_EMAIL_DOMAIN in the config instead to admit a whole domain.",],+ AUTH_PASSWORD_USERS: [+ "Optional. Comma-separated <email>:<hash> entries for password sign-in during onboarding.",+ "Make a hash with: node plugins/auth/src/hash-password.ts [email protected]",+ "Each address must also be on AUTH_ALLOWED_EMAILS or under AUTH_ALLOWED_EMAIL_DOMAIN.",+ "Move to email links or an identity provider once the deployment is running.",+ ],AUTH_EMAIL_FROM: ["The verified sender sign-in links come from, for example","Acme <[email protected]>. It must be a domain your email provider has verified.",diff --git a/cli/src/secrets.ts b/cli/src/secrets.tsindex adc939977..77fe6ca6c 100644--- a/cli/src/secrets.ts+++ b/cli/src/secrets.ts@@ -468,6 +468,13 @@ export const FIRST_PARTY_SECRET_SPECS: readonly SecretSpec[] = [},description: "Email addresses allowed to sign in; the portal enforces the same list the broker does.",},+ {+ name: "AUTH_PASSWORD_USERS",+ service: "auth",+ required: false,+ description:+ "Optional <email>:<scrypt-hash> entries that may sign in with a password while email or an identity provider is still being set up; each address must also be allowed to sign in.",+ },{name: "AUTH_EMAIL_FROM",service: "auth",diff --git a/cli/templates/deployment/references/email.md b/cli/templates/deployment/references/email.mdindex 7a8a5c6c1..1ce272727 100644--- a/cli/templates/deployment/references/email.md+++ b/cli/templates/deployment/references/email.md@@ -6,6 +6,12 @@ credentials unset, then run `qm admin-login` after deployment. It prints a privasingle-use login link valid for five minutes. The selected account must alreadyhave `org_admin` access. Other users need email or an external identity provider.+A deployment can also start with password sign-in: hash a password with+`node plugins/auth/src/hash-password.ts [email protected]` and store the result+with `qm secrets set AUTH_PASSWORD_USERS ...`. The address must also be allowed+to sign in. Treat this as an onboarding aid and move to email links or an+identity provider once the deployment is running (see `plugins/auth/README.md`).+Email sign-in needs one transport. SMTP is the default recommendation: any existing mail account orrelay works and there is no DNS wait. Pick Resend only when the operatorprefers it and has DNS control over a domain they are happy to send from.diff --git a/plugins/auth/README.md b/plugins/auth/README.mdindex fbf5c1dba..cd2cb6353 100644--- a/plugins/auth/README.md+++ b/plugins/auth/README.md@@ -46,6 +46,8 @@ Fully supplied email configuration is validated at boot.| `AUTH_ISSUER`, `AUTH_CLIENT_ID`, `AUTH_REDIRECT_URI` | derived from `publicUrl` || `AUTH_CLIENT_SECRET`, `AUTH_TOKEN_SECRET`, `AUTH_SIGNING_JWK` | generated by `qm setup` || `AUTH_ALLOWED_EMAILS`, `AUTH_ALLOWED_EMAIL_DOMAIN` | the operator's admin address or domain |+| `AUTH_PASSWORD_USERS` | optional `<email>:<hash>` entries for password sign-in (below) |+| `AUTH_PASSWORD_LIMIT_PER_EMAIL`, `AUTH_PASSWORD_LIMIT_PER_IP` | optional, attempts per `AUTH_SEND_WINDOW_S` (defaults 10 and 30) || `AUTH_EMAIL_FROM` | the operator's verified sender || `AUTH_BRAND_NAME` | `botName` in the deployment config; the Admin page's live branding, when set, takes precedence on rendered pages and emails || `AUTH_EMAIL_TRANSPORT` and the chosen transport's variables (below) | the operator's email provider |@@ -56,6 +58,37 @@ Fully supplied email configuration is validated at boot.The signing key is single, not a set: rotating it means redeploying, and linksminted by the previous key stop verifying at that moment.+## Password sign-in for getting started++A fresh deployment can reach its first sign-in without Resend, SMTP, or an+identity provider. Set `AUTH_PASSWORD_USERS` to comma-separated `<email>:<hash>`+entries and the sign-in page offers an email-and-password form beside (or+instead of) the email-link form. A successful password sign-in creates the same+remembered browser session and the same authorization code as an email link, so+admin bootstrap, allowlists, and everything downstream behave identically. Each+address must still be permitted by `AUTH_ALLOWED_EMAILS`,+`AUTH_ALLOWED_EMAIL_DOMAIN`, or an invitation.++Generate a hash from a checkout (the password is read from a hidden prompt, or+from stdin when piped, and must be at least 12 characters):++```sh+node plugins/auth/src/hash-password.ts [email protected]+```++Then, from the deployment directory:++```sh+qm secrets set AUTH_PASSWORD_USERS '[email protected]:scrypt$15$8$1$...'+```++Only scrypt hashes are stored; a plaintext password in the list refuses boot.+Passwords are compared in constant time, and attempts are rate limited per+account and per client address through the same durable claims as link sends,+so a core outage fails closed. Password sign-in is meant for onboarding. Once+the deployment is running, configure an email transport or an external identity+provider and unset `AUTH_PASSWORD_USERS`; the page says as much.+## Invited external usersAn address an org admin has invited as an external user (Admin → Users, or bydiff --git a/plugins/auth/package.json b/plugins/auth/package.jsonindex 4093889f0..281803258 100644--- a/plugins/auth/package.json+++ b/plugins/auth/package.json@@ -10,7 +10,8 @@"scripts": {"start": "node src/index.ts","typecheck": "tsc --noEmit",- "test": "node --test"+ "test": "node --test",+ "hash-password": "node src/hash-password.ts"},"devDependencies": {"@types/node": "^24.0.0",diff --git a/plugins/auth/src/config.ts b/plugins/auth/src/config.tsindex c16837716..73c5197b6 100644--- a/plugins/auth/src/config.ts+++ b/plugins/auth/src/config.ts@@ -1,4 +1,5 @@import type { SmtpTlsMode } from "./smtp.ts";+import { parsePasswordHash } from "./password.ts";type EmailTransportKind = "resend" | "smtp";@@ -20,6 +21,10 @@ export interface AuthConfig {tokenSecret: string;allowedEmails: readonly string[];allowedEmailDomain: string | undefined;+ passwordUsers: ReadonlyMap<string, string>;+ passwordUserProblems: readonly string[];+ passwordLimitPerEmail: number;+ passwordLimitPerIp: number;emailFrom: string;brandName: string;faviconSvg: string | undefined;@@ -87,6 +92,7 @@ export function readConfig(env: NodeJS.ProcessEnv): AuthConfig {const issuer = (env.AUTH_ISSUER ?? `http://localhost:${env.PORT ?? 8099}`).replace(/\/$/, "");const publicPath = issuerPath(issuer);const transport: EmailTransportKind = env.AUTH_EMAIL_TRANSPORT?.trim() === "smtp" ? "smtp" : "resend";+ const passwordUsers = parsePasswordUsers(env.AUTH_PASSWORD_USERS);return {issuer,publicPath,@@ -97,6 +103,10 @@ export function readConfig(env: NodeJS.ProcessEnv): AuthConfig {tokenSecret: env.AUTH_TOKEN_SECRET ?? "",allowedEmails: listFrom(env.AUTH_ALLOWED_EMAILS),allowedEmailDomain: env.AUTH_ALLOWED_EMAIL_DOMAIN?.trim().toLowerCase() || undefined,+ passwordUsers: passwordUsers.users,+ passwordUserProblems: passwordUsers.problems,+ passwordLimitPerEmail: numberFrom(env.AUTH_PASSWORD_LIMIT_PER_EMAIL, 10),+ passwordLimitPerIp: numberFrom(env.AUTH_PASSWORD_LIMIT_PER_IP, 30),emailFrom: env.AUTH_EMAIL_FROM?.trim() ?? "",brandName: env.AUTH_BRAND_NAME?.trim() || "qm",faviconSvg: env.AUTH_FAVICON_SVG?.trim() || undefined,@@ -136,6 +146,31 @@ export function validEmail(value: string): boolean {return value.length <= 254 && /^[^@\s,;<>"]+@[^@\s,;<>"]+\.[^@\s,;<>"]+$/.test(value);}+export function parsePasswordUsers(raw: string | undefined): { users: Map<string, string>; problems: string[] } {+ const users = new Map<string, string>();+ const problems: string[] = [];+ for (const entry of (raw ?? "").split(/[,\s]+/).filter(Boolean)) {+ const separator = entry.indexOf(":");+ const email = separator > 0 ? entry.slice(0, separator).trim().toLowerCase() : "";+ const hash = separator > 0 ? entry.slice(separator + 1).trim() : "";+ if (!email || !validEmail(email)) {+ problems.push("AUTH_PASSWORD_USERS entries must be <email>:<hash>");+ continue;+ }+ if (!parsePasswordHash(hash)) {+ problems.push(`AUTH_PASSWORD_USERS: the hash for ${email} was not produced by the password helper`);+ continue;+ }+ if (users.has(email)) problems.push(`AUTH_PASSWORD_USERS lists ${email} more than once`);+ users.set(email, hash);+ }+ return { users, problems };+}++export function passwordConfigured(cfg: AuthConfig): boolean {+ return cfg.passwordUsers.size > 0;+}+export function emailConfigured(cfg: AuthConfig): boolean {const credentials =cfg.transport === "resend" ? [cfg.resendApiKey] : [cfg.smtp.host, cfg.smtp.username, cfg.smtp.password];@@ -219,6 +254,18 @@ export function bootProblems(cfg: AuthConfig, isProd: boolean): string[] {}}+ problems.push(...cfg.passwordUserProblems);+ for (const [name, limit] of [+ ["AUTH_PASSWORD_LIMIT_PER_EMAIL", cfg.passwordLimitPerEmail],+ ["AUTH_PASSWORD_LIMIT_PER_IP", cfg.passwordLimitPerIp],+ ] as const) {+ if (!Number.isInteger(limit) || limit < 1 || limit > MAX_RATE_LIMIT_SLOTS) {+ problems.push(+ `${name} must be a whole number between 1 and ${MAX_RATE_LIMIT_SLOTS}; each unit is one durable claim slot`,+ );+ }+ }+if (isProd && isMissingOrPlaceholder(cfg.coreSigningSecret)) {problems.push("CORE_SIGNING_SECRET is required; single-use enforcement for links and codes is durable state held by core",diff --git a/plugins/auth/src/hash-password.ts b/plugins/auth/src/hash-password.tsnew file mode 100644index 000000000..77652064f--- /dev/null+++ b/plugins/auth/src/hash-password.ts@@ -0,0 +1,66 @@+import { pathToFileURL } from "node:url";+import { hashPassword, passwordProblem } from "./password.ts";++async function readStdin(): Promise<string> {+ const chunks: Buffer[] = [];+ for await (const chunk of process.stdin) chunks.push(chunk as Buffer);+ return Buffer.concat(chunks).toString("utf8");+}++function promptHidden(label: string): Promise<string> {+ return new Promise((resolve) => {+ process.stderr.write(label);+ const stdin = process.stdin;+ stdin.setRawMode(true);+ stdin.resume();+ stdin.setEncoding("utf8");+ let value = "";+ const onData = (chunk: string): void => {+ for (const ch of chunk) {+ if (ch === "\r" || ch === "\n") {+ stdin.setRawMode(false);+ stdin.pause();+ stdin.off("data", onData);+ process.stderr.write("\n");+ resolve(value);+ return;+ }+ if (ch === "\u0003") process.exit(130);+ if (ch === "\u007f" || ch === "\b") value = value.slice(0, -1);+ else value += ch;+ }+ };+ stdin.on("data", onData);+ });+}++export async function main(argv: string[]): Promise<string> {+ const email = argv+ .find((arg) => !arg.startsWith("-"))+ ?.trim()+ .toLowerCase();+ let password: string;+ if (process.stdin.isTTY) {+ password = await promptHidden("Password: ");+ const again = await promptHidden("Again: ");+ if (password !== again) throw new Error("passwords did not match");+ } else {+ password = (await readStdin()).replace(/\r?\n$/, "");+ }+ const problem = passwordProblem(password);+ if (problem) throw new Error(problem);+ const hash = await hashPassword(password);+ return email ? `${email}:${hash}` : hash;+}++if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) {+ main(process.argv.slice(2)).then(+ (line) => {+ process.stdout.write(`${line}\n`);+ },+ (err: unknown) => {+ process.stderr.write(`hash-password: ${err instanceof Error ? err.message : String(err)}\n`);+ process.exit(1);+ },+ );+}diff --git a/plugins/auth/src/pages.ts b/plugins/auth/src/pages.tsindex 2d45a772a..f7eadea49 100644--- a/plugins/auth/src/pages.ts+++ b/plugins/auth/src/pages.ts@@ -60,9 +60,9 @@ const STYLE = `<style>.reason strong{ display:block; color:var(--warn); font-size:11px; margin-bottom:3px; }form{ display:grid; gap:10px; text-align:left; }label{ font-size:12.5px; font-weight:600; color:var(--muted); }- input[type=email]{ width:100%; min-height:44px; padding:0 14px; font:inherit; color:var(--text);+ input[type=email],input[type=password]{ width:100%; min-height:44px; padding:0 14px; font:inherit; color:var(--text);background:var(--bg); border:1px solid var(--border); border-radius:var(--radius-md); }- input[type=email]:focus-visible{ outline:2px solid color-mix(in srgb, var(--text) 35%, transparent); outline-offset:1px; }+ input[type=email]:focus-visible,input[type=password]:focus-visible{ outline:2px solid color-mix(in srgb, var(--text) 35%, transparent); outline-offset:1px; }.btn{ display:flex; align-items:center; justify-content:center; min-height:44px; padding:0 18px; width:100%;text-decoration:none; font:inherit; font-weight:600; border-radius:var(--radius-md); cursor:pointer;background:var(--text); color:var(--bg); border:1px solid var(--text); }@@ -71,6 +71,7 @@ const STYLE = `<style>.divider{ display:flex; align-items:center; gap:16px; margin:24px 0; color:var(--muted); font-size:11px; font-weight:600; letter-spacing:.08em; }.divider::before,.divider::after{ content:""; flex:1; height:1px; background:var(--border); }.help{ color:var(--muted); font-size:12.5px; margin:20px 0 0; }+ .note{ color:var(--muted); font-size:12px; margin:8px 0 0; text-align:left; }.who{ display:block; margin:0 auto 22px; font-size:13px; color:var(--text); background:var(--secondary);border:1px solid var(--border); border-radius:var(--radius-md); padding:11px 14px; word-break:break-word; }</style>`;@@ -115,30 +116,59 @@ ${STYLE}</html>`;}-export function emailFormPage(o: {+export function signInPage(o: {brandName: string;trustedSignInLabel?: string;action: string;requestToken: string;+ emailLink: boolean;+ password: boolean;email?: string;problem?: string;+ passwordProblem?: string;}): string {+ const hidden = `<input type="hidden" name="request" value="${escapeHtml(o.requestToken)}">`;+ const trusted = o.trustedSignInLabel+ ? `<a class="btn" href="/auth/trusted/login">Sign in with ${escapeHtml(o.trustedSignInLabel)}</a><div class="divider">OR</div>`+ : "";+ const secondary = Boolean(o.trustedSignInLabel) || (o.emailLink && o.password);+ const emailForm = o.emailLink+ ? `${o.problem ? `<p class="reason"><strong>Try again</strong>${escapeHtml(o.problem)}</p>` : ""}<form method="post" action="${escapeHtml(o.action)}">+ ${hidden}+ <input type="hidden" name="method" value="email">+ <label for="email">Email address</label>+ <input id="email" name="email" type="email" autocomplete="email" inputmode="email" required${secondary ? "" : " autofocus"}+ spellcheck="false" maxlength="254" placeholder="[email protected]" value="${escapeHtml(o.email ?? "")}">+ <button class="btn${secondary ? " alternative" : ""}" type="submit">Email me a sign-in link</button>+ </form>`+ : "";+ const passwordForm = o.password+ ? `${o.passwordProblem ? `<p class="reason"><strong>Try again</strong>${escapeHtml(o.passwordProblem)}</p>` : ""}<form method="post" action="${escapeHtml(o.action)}">+ ${hidden}+ <input type="hidden" name="method" value="password">+ <label for="password-email">Email address</label>+ <input id="password-email" name="email" type="email" autocomplete="username" inputmode="email" required${o.trustedSignInLabel ? "" : " autofocus"}+ spellcheck="false" maxlength="254" placeholder="[email protected]" value="${escapeHtml(o.email ?? "")}">+ <label for="password">Password</label>+ <input id="password" name="password" type="password" autocomplete="current-password" required maxlength="1024">+ <button class="btn${o.trustedSignInLabel ? " alternative" : ""}" type="submit">Sign in with password</button>+ <p class="note">Password sign-in is meant for getting started. Once ${escapeHtml(o.brandName)} is set up, your administrator should switch to email links or an identity provider.</p>+ </form>`+ : "";+ let msg = "Enter your work email and we'll send you a one-time sign-in link.";+ if (o.trustedSignInLabel) msg = `Use your ${o.trustedSignInLabel} account to continue.`;+ else if (o.password && o.emailLink) msg = "Sign in with your password, or have a one-time link emailed to you.";+ else if (o.password) msg = "Enter the email address and password your administrator gave you.";return page({title: "Sign in",brandName: o.brandName,- icon: o.trustedSignInLabel ? LOCK_ICON : MAIL_ICON,+ icon: o.trustedSignInLabel || o.password ? LOCK_ICON : MAIL_ICON,heading: `Sign in to ${o.brandName}`,- msg: o.trustedSignInLabel- ? `Use your ${o.trustedSignInLabel} account to continue.`- : "Enter your work email and we'll send you a one-time sign-in link.",- body: `${o.trustedSignInLabel ? `<a class="btn" href="/auth/trusted/login">Sign in with ${escapeHtml(o.trustedSignInLabel)}</a><div class="divider">OR</div>` : ""}${o.problem ? `<p class="reason"><strong>Try again</strong>${escapeHtml(o.problem)}</p>` : ""}<form method="post" action="${escapeHtml(o.action)}">- <input type="hidden" name="request" value="${escapeHtml(o.requestToken)}">- <label for="email">Email address</label>- <input id="email" name="email" type="email" autocomplete="email" inputmode="email" required${o.trustedSignInLabel ? "" : " autofocus"}- spellcheck="false" maxlength="254" placeholder="[email protected]" value="${escapeHtml(o.email ?? "")}">- <button class="btn${o.trustedSignInLabel ? " alternative" : ""}" type="submit">Email me a sign-in link</button>- </form>`,- help: "For email sign-in, use an address your administrator has allowed.",+ msg,+ body: `${trusted}${passwordForm}${o.password && o.emailLink ? `<div class="divider">OR</div>` : ""}${emailForm}`,+ help: o.emailLink+ ? "For email sign-in, use an address your administrator has allowed."+ : "Use the account your administrator has allowed.",});}diff --git a/plugins/auth/src/password.ts b/plugins/auth/src/password.tsnew file mode 100644index 000000000..fbfcdc8c9--- /dev/null+++ b/plugins/auth/src/password.ts@@ -0,0 +1,75 @@+import { randomBytes, scrypt, timingSafeEqual } from "node:crypto";++const SCHEME = "scrypt";+const DEFAULT_LOG2_N = 15;+const DEFAULT_R = 8;+const DEFAULT_P = 1;+const SALT_BYTES = 16;+const KEY_BYTES = 32;+const MAX_LOG2_N = 20;+const MAX_PASSWORD_BYTES = 1024;+const MIN_PASSWORD_LENGTH = 12;++interface ParsedHash {+ log2N: number;+ r: number;+ p: number;+ salt: Buffer;+ key: Buffer;+}++function derive(password: string, salt: Buffer, params: { log2N: number; r: number; p: number }): Promise<Buffer> {+ return new Promise((resolve, reject) => {+ scrypt(+ password,+ salt,+ KEY_BYTES,+ { N: 2 ** params.log2N, r: params.r, p: params.p, maxmem: 256 * 1024 * 1024 },+ (err, key) => (err ? reject(err) : resolve(key)),+ );+ });+}++export function passwordProblem(password: string): string | null {+ if (password.length < MIN_PASSWORD_LENGTH) return `passwords must be at least ${MIN_PASSWORD_LENGTH} characters`;+ if (Buffer.byteLength(password, "utf8") > MAX_PASSWORD_BYTES) return "password is too long";+ return null;+}++export async function hashPassword(password: string): Promise<string> {+ const problem = passwordProblem(password);+ if (problem) throw new Error(problem);+ const salt = randomBytes(SALT_BYTES);+ const key = await derive(password, salt, { log2N: DEFAULT_LOG2_N, r: DEFAULT_R, p: DEFAULT_P });+ return [SCHEME, DEFAULT_LOG2_N, DEFAULT_R, DEFAULT_P, salt.toString("base64url"), key.toString("base64url")].join(+ "$",+ );+}++export function parsePasswordHash(stored: string): ParsedHash | null {+ const parts = stored.split("$");+ if (parts.length !== 6 || parts[0] !== SCHEME) return null;+ const [, rawLog2N, rawR, rawP, rawSalt, rawKey] = parts as [string, string, string, string, string, string];+ if (![rawLog2N, rawR, rawP].every((value) => /^\d{1,2}$/.test(value))) return null;+ const log2N = Number(rawLog2N);+ const r = Number(rawR);+ const p = Number(rawP);+ if (log2N < 10 || log2N > MAX_LOG2_N || r < 1 || r > 32 || p < 1 || p > 16) return null;+ if (!/^[A-Za-z0-9_-]{16,}$/.test(rawSalt) || !/^[A-Za-z0-9_-]{43}$/.test(rawKey)) return null;+ const salt = Buffer.from(rawSalt, "base64url");+ const key = Buffer.from(rawKey, "base64url");+ if (salt.length < 8 || key.length !== KEY_BYTES) return null;+ return { log2N, r, p, salt, key };+}++const DECOY = parsePasswordHash(+ `${SCHEME}$${DEFAULT_LOG2_N}$${DEFAULT_R}$${DEFAULT_P}$${Buffer.alloc(SALT_BYTES).toString("base64url")}$${Buffer.alloc(KEY_BYTES).toString("base64url")}`,+)!;++export async function verifyPassword(password: string, stored: string | undefined): Promise<boolean> {+ const parsed = stored ? parsePasswordHash(stored) : null;+ const target = parsed ?? DECOY;+ if (Buffer.byteLength(password, "utf8") > MAX_PASSWORD_BYTES) return false;+ const key = await derive(password, target.salt, target);+ return timingSafeEqual(key, target.key) && parsed !== null;+}diff --git a/plugins/auth/src/server.ts b/plugins/auth/src/server.tsindex 9e574f3fa..68c2124e2 100644--- a/plugins/auth/src/server.ts+++ b/plugins/auth/src/server.ts@@ -5,13 +5,14 @@ import type { IncomingMessage, ServerResponse } from "node:http";import { readBody, PayloadTooLargeError, sendBuffered, serveFavicon } from "../../chassis/src/http.ts";import { errMessage } from "../../chassis/src/errors.ts";import type { AuthConfig } from "./config.ts";-import { validEmail } from "./config.ts";+import { passwordConfigured, validEmail } from "./config.ts";+import { verifyPassword } from "./password.ts";import { claimOnce, withinRateLimit, ClaimStoreUnavailableError, type ClaimStore } from "../../chassis/src/claims.ts";import { coreEmailAllowed } from "../../chassis/src/external-members.ts";import { mintIdToken, pkceMatches, safeEqual, subjectFor, TokenSigner, type AuthRequest } from "./tokens.ts";import { ID_TOKEN_ALG, type SigningKey } from "./keys.ts";import { renderSignInEmail, type Mailer } from "./email.ts";-import { confirmSignInPage, emailFormPage, linkSentPage, problemPage, CONFIRM_PAGE_CSP, PAGE_CSP } from "./pages.ts";+import { confirmSignInPage, signInPage, linkSentPage, problemPage, CONFIRM_PAGE_CSP, PAGE_CSP } from "./pages.ts";const MAX_FORM_BYTES = 8 * 1024;const ID_TOKEN_TTL_S = 300;@@ -124,6 +125,20 @@ export function createAuthHandler(deps: AuthDeps): (req: IncomingMessage, res: Sconst now = deps.now ?? Date.now;const notify = deps.onBackgroundTask ?? ((task: Promise<void>) => void task.catch(() => undefined));const formAction = `${cfg.publicPath}/authorize`;+ const passwords = passwordConfigured(cfg);+ const signInForm = (+ requestToken: string,+ extra: { email?: string; problem?: string; passwordProblem?: string } = {},+ ): string =>+ signInPage({+ brandName: brandName(),+ trustedSignInLabel: deps.trustedSignInLabel,+ action: formAction,+ requestToken,+ emailLink: mailer !== null,+ password: passwords,+ ...extra,+ });const linkTtlMinutes = Math.max(1, Math.round(cfg.linkTtlS / 60));let inFlightSends = 0;const background = (task: () => Promise<void>): void => {@@ -160,6 +175,14 @@ export function createAuthHandler(deps: AuthDeps): (req: IncomingMessage, res: S"Your administrator needs to configure email delivery before you can request a sign-in link.",);+ const passwordUnavailable = (res: ServerResponse): void =>+ problem(+ res,+ 503,+ "Password sign-in isn't configured",+ "Your administrator has not set up any password accounts on this deployment.",+ );+const signInUrl = ((): string | undefined => {try {return new URL("/auth/login", cfg.redirectUri).toString();@@ -267,18 +290,66 @@ export function createAuthHandler(deps: AuthDeps): (req: IncomingMessage, res: Sres.writeHead(302, noStore({ location: destination.toString() }));return void res.end();}- if (!mailer) return emailUnavailable(res);+ if (!mailer && !passwords) return emailUnavailable(res);const sealed = await signer.sealRequest(parsed.request, cfg.requestTtlS, now());- return sendHtml(- res,- 200,- emailFormPage({- brandName: brandName(),- trustedSignInLabel: deps.trustedSignInLabel,- action: formAction,- requestToken: sealed.token,- }),- );+ return sendHtml(res, 200, signInForm(sealed.token));+ }++ async function passwordSubmit(+ req: IncomingMessage,+ res: ServerResponse,+ request: AuthRequest,+ form: URLSearchParams,+ ): Promise<void> {+ if (!passwords) return passwordUnavailable(res);+ const email = normalizeEmail(form.get("email") ?? "");+ const password = form.get("password") ?? "";+ const reject = async (status: number, passwordProblem: string): Promise<void> => {+ const sealed = await signer.sealRequest(request, cfg.requestTtlS, now());+ sendHtml(res, status, signInForm(sealed.token, { email, passwordProblem }));+ };+ if (!validEmail(email) || !password) return reject(400, "Enter your email address and password.");+ const nowMs = now();+ const ip = clientIpOf(req);+ try {+ const within = async (kind: string, value: string, limit: number): Promise<boolean> =>+ withinRateLimit(claims, { secret: cfg.tokenSecret, kind, value, limit, windowS: cfg.sendWindowS, nowMs });+ if (!(await within("password-ip", ip, cfg.passwordLimitPerIp))) {+ console.warn("[auth] password sign-in refused: per-address attempt limit reached for the requesting client");+ return reject(429, "Too many sign-in attempts. Wait a while, then try again.");+ }+ if (!(await within("password-account", email, cfg.passwordLimitPerEmail))) {+ console.warn("[auth] password sign-in refused: per-account attempt limit reached");+ return reject(429, "Too many sign-in attempts. Wait a while, then try again.");+ }+ } catch (e) {+ if (!(e instanceof ClaimStoreUnavailableError)) throw e;+ reportBackendError(e);+ return problem(+ res,+ 503,+ "Sign-in is temporarily unavailable",+ "The sign-in service cannot reach its backend. Try again in a minute.",+ );+ }+ const matched = await verifyPassword(password, cfg.passwordUsers.get(email));+ if (!matched || !(await emailAllowed(email))) {+ console.warn(`[auth] password sign-in refused for ${email}`);+ return reject(401, "That email address or password is incorrect.");+ }+ let session: RememberedSession & { token: string };+ try {+ session = await sessions.create(email, cfg.sessionIdleS, cfg.sessionAbsoluteS);+ } catch {+ return problem(+ res,+ 503,+ "Sign-in is temporarily unavailable",+ "The sign-in service cannot remember this browser. Try again in a minute.",+ );+ }+ console.log(`[auth] password sign-in for ${email}`);+ return issueCode(res, request, email, session.authTime, sessionCookie(session.token, session));}async function sendLink(request: AuthRequest, email: string, ip: string, sender: Mailer): Promise<void> {@@ -320,7 +391,7 @@ export function createAuthHandler(deps: AuthDeps): (req: IncomingMessage, res: S}async function authorizeSubmit(req: IncomingMessage, res: ServerResponse): Promise<void> {- if (!mailer) return emailUnavailable(res);+ if (!mailer && !passwords) return emailUnavailable(res);let raw: string;try {raw = await readBody(req, MAX_FORM_BYTES);@@ -339,20 +410,12 @@ export function createAuthHandler(deps: AuthDeps): (req: IncomingMessage, res: S"Sign-in pages are only valid for a short while. Start again from the page you were trying to reach.",);}+ if (form.get("method") === "password" || form.has("password")) return passwordSubmit(req, res, request, form);+ if (!mailer) return emailUnavailable(res);const email = normalizeEmail(form.get("email") ?? "");if (!validEmail(email)) {const sealed = await signer.sealRequest(request, cfg.requestTtlS, now());- return sendHtml(- res,- 400,- emailFormPage({- brandName: brandName(),- trustedSignInLabel: deps.trustedSignInLabel,- action: formAction,- requestToken: sealed.token,- problem: "That doesn't look like an email address.",- }),- );+ return sendHtml(res, 400, signInForm(sealed.token, { problem: "That doesn't look like an email address." }));}const ip = clientIpOf(req);sendHtml(diff --git a/plugins/auth/test/password-flow.test.ts b/plugins/auth/test/password-flow.test.tsnew file mode 100644index 000000000..1f6f4d720--- /dev/null+++ b/plugins/auth/test/password-flow.test.ts@@ -0,0 +1,226 @@+import test from "node:test";+import assert from "node:assert/strict";+import { createLocalJWKSet, jwtVerify, type JWK } from "jose";+import { hashPassword } from "../src/password.ts";+import {+ authorizeQuery,+ basicAuth,+ CLIENT_ID,+ CLIENT_SECRET,+ hiddenRequestToken,+ ISSUER,+ pkcePair,+ REDIRECT_URI,+ refusingClaimStore,+ startHarness,+ type Harness,+} from "./helpers.ts";++const PASSWORD = "correct horse battery staple";+const HASH = await hashPassword(PASSWORD);+const USERS = `[email protected]:${HASH}`;++const form = (entries: Record<string, string>, headers: Record<string, string> = {}): RequestInit => ({+ method: "POST",+ headers: { "content-type": "application/x-www-form-urlencoded", ...headers },+ body: new URLSearchParams(entries).toString(),+ redirect: "manual",+});++async function signInPage(h: Harness, challenge: string): Promise<{ html: string; request: string; state: string }> {+ const query = authorizeQuery({ code_challenge: challenge });+ const page = await fetch(`${h.base}/authorize?${query}`);+ assert.equal(page.status, 200);+ const html = await page.text();+ return { html, request: hiddenRequestToken(html), state: query.get("state")! };+}++async function submitPassword(+ h: Harness,+ fields: { email: string; password: string; ip?: string },+): Promise<{ response: Response; verifier: string; state: string }> {+ const { verifier, challenge } = pkcePair();+ const { request, state } = await signInPage(h, challenge);+ const response = await fetch(+ `${h.base}/authorize`,+ form(+ { request, method: "password", email: fields.email, password: fields.password },+ fields.ip ? { "x-qm-client-ip": fields.ip } : {},+ ),+ );+ return { response, verifier, state };+}++async function exchange(h: Harness, code: string, verifier: string): Promise<Response> {+ return fetch(`${h.base}/token`, {+ ...form({ grant_type: "authorization_code", code, redirect_uri: REDIRECT_URI, code_verifier: verifier }),+ headers: {+ "content-type": "application/x-www-form-urlencoded",+ authorization: basicAuth(CLIENT_ID, CLIENT_SECRET),+ },+ });+}++test("password sign-in completes the same authorization-code flow and mints the same tokens", async (t) => {+ const h = await startHarness({ env: { AUTH_PASSWORD_USERS: USERS, RESEND_API_KEY: undefined } });+ t.after(() => h.close());++ const { response, verifier, state } = await submitPassword(h, { email: "[email protected]", password: PASSWORD });+ assert.equal(response.status, 302, await response.text());+ const location = new URL(response.headers.get("location")!);+ assert.equal(`${location.origin}${location.pathname}`, REDIRECT_URI);+ assert.equal(location.searchParams.get("state"), state);+ assert.match(+ response.headers.get("set-cookie") ?? "",+ /^qm_idp_session=.*HttpOnly; Secure; SameSite=Lax; Path=\/idp/,+ );+ assert.equal(h.remembered.size, 1);++ const tokens = await exchange(h, location.searchParams.get("code")!, verifier);+ assert.equal(tokens.status, 200);+ const body = (await tokens.json()) as { id_token: string; access_token: string };+ const jwks = (await (await fetch(`${h.base}/.well-known/jwks.json`)).json()) as { keys: JWK[] };+ const { payload } = await jwtVerify(body.id_token, createLocalJWKSet(jwks), { issuer: ISSUER, audience: CLIENT_ID });+ assert.equal(payload.email, "[email protected]");+ assert.equal(payload.email_verified, true);+ assert.equal(payload.auth_time, Math.floor(h.now.ms / 1000));+ const info = await fetch(`${h.base}/userinfo`, { headers: { authorization: `Bearer ${body.access_token}` } });+ assert.equal(((await info.json()) as { email: string }).email, "[email protected]");+ assert.deepEqual(h.mailer.sent, []);+});++test("the sign-in page offers only the configured methods", async (t) => {+ const both = await startHarness({ env: { AUTH_PASSWORD_USERS: USERS } });+ t.after(() => both.close());+ const bothHtml = (await signInPage(both, pkcePair().challenge)).html;+ assert.match(bothHtml, /type="password"/);+ assert.match(bothHtml, /Email me a sign-in link/);+ assert.match(bothHtml, /meant for getting started/);+ assert.doesNotMatch(bothHtml, /scrypt\$/);++ const passwordOnly = await startHarness({ env: { AUTH_PASSWORD_USERS: USERS, RESEND_API_KEY: undefined } });+ t.after(() => passwordOnly.close());+ const passwordHtml = (await signInPage(passwordOnly, pkcePair().challenge)).html;+ assert.match(passwordHtml, /type="password"/);+ assert.doesNotMatch(passwordHtml, /Email me a sign-in link/);++ const emailOnly = await startHarness();+ t.after(() => emailOnly.close());+ const emailHtml = (await signInPage(emailOnly, pkcePair().challenge)).html;+ assert.doesNotMatch(emailHtml, /type="password"/);+ assert.match(emailHtml, /Email me a sign-in link/);+ const { request } = await signInPage(emailOnly, pkcePair().challenge);+ const refused = await fetch(+ `${emailOnly.base}/authorize`,+ form({ request, method: "password", email: "[email protected]", password: PASSWORD }),+ );+ assert.equal(refused.status, 503);+ assert.match(await refused.text(), /Password sign-in isn't configured/);+ assert.equal(emailOnly.remembered.size, 0);+});++test("a wrong password, an unknown account, and an unlisted email all fail the same way", async (t) => {+ const h = await startHarness({+ env: { AUTH_PASSWORD_USERS: `${USERS},[email protected]:${HASH}`, RESEND_API_KEY: undefined },+ });+ t.after(() => h.close());+ const attempts = [+ { email: "[email protected]", password: `${PASSWORD}!` },+ { email: "[email protected]", password: PASSWORD },+ { email: "[email protected]", password: PASSWORD },+ ];+ const bodies: string[] = [];+ for (const attempt of attempts) {+ const { response } = await submitPassword(h, attempt);+ assert.equal(response.status, 401);+ const html = await response.text();+ assert.match(html, /email address or password is incorrect/);+ assert.match(html, /name="request" value="/);+ bodies.push(html.replace(/name="request" value="[^"]+"/g, "").replace(/value="[^"]*@[^"]*"/g, ""));+ }+ assert.equal(new Set(bodies).size, 1, "responses must not reveal which accounts exist");+ assert.equal(h.remembered.size, 0);+ assert.deepEqual(h.claims.calls.length, 6, "every attempt consumes an ip slot and an account slot");+});++test("password attempts are rate limited per account and per client address", async (t) => {+ const h = await startHarness({+ env: {+ AUTH_PASSWORD_USERS: USERS,+ RESEND_API_KEY: undefined,+ AUTH_PASSWORD_LIMIT_PER_EMAIL: "2",+ AUTH_PASSWORD_LIMIT_PER_IP: "3",+ },+ });+ t.after(() => h.close());+ const wrong = { email: "[email protected]", password: "not the password" };+ assert.equal((await submitPassword(h, { ...wrong, ip: "10.0.0.1" })).response.status, 401);+ assert.equal((await submitPassword(h, { ...wrong, ip: "10.0.0.2" })).response.status, 401);+ const locked = await submitPassword(h, { email: "[email protected]", password: PASSWORD, ip: "10.0.0.3" });+ assert.equal(locked.response.status, 429, "the right password no longer helps once the account budget is spent");+ assert.match(await locked.response.text(), /Too many sign-in attempts/);+ assert.equal(h.remembered.size, 0);++ for (let i = 0; i < 3; i++) {+ await submitPassword(h, { email: `user${i}@example.com`, password: "whatever it is", ip: "10.0.0.9" });+ }+ const perIp = await submitPassword(h, { email: "[email protected]", password: "whatever it is", ip: "10.0.0.9" });+ assert.equal(perIp.response.status, 429);++ h.now.ms += h.cfg.sendWindowS * 1000 + 1;+ const fresh = await submitPassword(h, { email: "[email protected]", password: PASSWORD, ip: "10.0.0.3" });+ assert.equal(fresh.response.status, 302);+});++test("password sign-in fails closed when core cannot record attempt claims", async (t) => {+ const h = await startHarness({+ env: { AUTH_PASSWORD_USERS: USERS, RESEND_API_KEY: undefined },+ claims: Object.assign(refusingClaimStore(), {+ calls: [] as string[][],+ async claimFirst(): Promise<string | null> {+ throw new (await import("../../chassis/src/claims.ts")).ClaimStoreUnavailableError("down");+ },+ }),+ });+ t.after(() => h.close());+ const { response } = await submitPassword(h, { email: "[email protected]", password: PASSWORD });+ assert.equal(response.status, 503);+ assert.equal(h.remembered.size, 0);+});++test("missing fields and a stale form are refused without touching the rate limits", async (t) => {+ const h = await startHarness({ env: { AUTH_PASSWORD_USERS: USERS, RESEND_API_KEY: undefined } });+ t.after(() => h.close());+ const { request } = await signInPage(h, pkcePair().challenge);+ const blank = await fetch(+ `${h.base}/authorize`,+ form({ request, method: "password", email: "[email protected]", password: "" }),+ );+ assert.equal(blank.status, 400);+ const badEmail = await fetch(+ `${h.base}/authorize`,+ form({ request, method: "password", email: "admin", password: PASSWORD }),+ );+ assert.equal(badEmail.status, 400);+ assert.deepEqual(h.claims.calls, []);+ const stale = await fetch(+ `${h.base}/authorize`,+ form({ request: "nope", method: "password", email: "[email protected]", password: PASSWORD }),+ );+ assert.equal(stale.status, 400);+ assert.match(await stale.text(), /sign-in page expired/);+});++test("a remembered browser from a password sign-in silently reauthorizes like an email one", async (t) => {+ const h = await startHarness({ env: { AUTH_PASSWORD_USERS: USERS, RESEND_API_KEY: undefined } });+ t.after(() => h.close());+ const { response } = await submitPassword(h, { email: "[email protected]", password: PASSWORD });+ const cookie = response.headers.get("set-cookie")!.split(";")[0]!;+ h.now.ms += 60000;+ const again = await fetch(`${h.base}/authorize?${authorizeQuery({ state: "again" })}`, {+ headers: { cookie },+ redirect: "manual",+ });+ assert.equal(again.status, 302);+ assert.equal(new URL(again.headers.get("location")!).searchParams.get("state"), "again");+});diff --git a/plugins/auth/test/password.test.ts b/plugins/auth/test/password.test.tsnew file mode 100644index 000000000..9db1d43d0--- /dev/null+++ b/plugins/auth/test/password.test.ts@@ -0,0 +1,91 @@+import test from "node:test";+import assert from "node:assert/strict";+import { hashPassword, parsePasswordHash, passwordProblem, verifyPassword } from "../src/password.ts";+import { bootProblems, parsePasswordUsers, passwordConfigured, readConfig } from "../src/config.ts";+import { testEnv } from "./helpers.ts";++const PASSWORD = "correct horse battery staple";++test("hashPassword produces a self-describing scrypt hash with a fresh salt every time", async () => {+ const a = await hashPassword(PASSWORD);+ const b = await hashPassword(PASSWORD);+ assert.notEqual(a, b);+ assert.match(a, /^scrypt\$15\$8\$1\$[A-Za-z0-9_-]{22}\$[A-Za-z0-9_-]{43}$/);+ assert.ok(parsePasswordHash(a));+ assert.ok(!a.includes(PASSWORD));+});++test("verifyPassword accepts the right password and refuses the wrong one", async () => {+ const stored = await hashPassword(PASSWORD);+ assert.equal(await verifyPassword(PASSWORD, stored), true);+ assert.equal(await verifyPassword(`${PASSWORD} `, stored), false);+ assert.equal(await verifyPassword("", stored), false);+});++test("verifyPassword refuses when no hash or a malformed hash is stored, taking the same code path", async () => {+ assert.equal(await verifyPassword(PASSWORD, undefined), false);+ assert.equal(await verifyPassword(PASSWORD, "plaintext-password"), false);+ assert.equal(await verifyPassword(PASSWORD, "scrypt$15$8$1$short$short"), false);+ assert.equal(await verifyPassword("x".repeat(2000), await hashPassword(PASSWORD)), false);+});++test("parsePasswordHash rejects unsafe or foreign parameters", () => {+ const good = "scrypt$15$8$1$IkNbPCoGdHpvuEgON4o1vA$EHD6YCiYNlcxXuuQxmnMkjkdFvBH1Jd1WlP1Lnl-a5w";+ assert.ok(parsePasswordHash(good));+ assert.equal(parsePasswordHash(good.replace("scrypt", "bcrypt")), null);+ assert.equal(parsePasswordHash(good.replace("$15$", "$4$")), null);+ assert.equal(parsePasswordHash(good.replace("$15$", "$40$")), null);+ assert.equal(parsePasswordHash(good.slice(0, -1)), null);+ assert.equal(parsePasswordHash(`${good}$extra`), null);+});++test("passwordProblem enforces a minimum length", () => {+ assert.equal(passwordProblem("short"), "passwords must be at least 12 characters");+ assert.equal(passwordProblem(PASSWORD), null);+});++test("parsePasswordUsers reads comma or whitespace separated email:hash entries", async () => {+ const hash = await hashPassword(PASSWORD);+ const { users, problems } = parsePasswordUsers(`[email protected]:${hash}, [email protected]:${hash}\n`);+ assert.deepEqual(problems, []);+ assert.deepEqual([...users.keys()], ["[email protected]", "[email protected]"]);+ assert.equal(users.get("[email protected]"), hash);+});++test("parsePasswordUsers reports malformed entries, plaintext passwords, and duplicates", async () => {+ const hash = await hashPassword(PASSWORD);+ const { users, problems } = parsePasswordUsers(+ `[email protected]:${hash},not-an-email:${hash},[email protected]:hunter2hunter2,[email protected]:${hash}`,+ );+ assert.equal(users.size, 1);+ assert.equal(problems.length, 3);+ assert.ok(problems.some((p) => p.includes("<email>:<hash>")));+ assert.ok(problems.some((p) => p.includes("[email protected]")));+ assert.ok(problems.some((p) => p.includes("more than once")));+});++test("password sign-in is off unless AUTH_PASSWORD_USERS is set, and bad entries refuse boot", async () => {+ const off = readConfig(testEnv());+ assert.equal(passwordConfigured(off), false);+ assert.deepEqual(+ bootProblems(off, true).filter((p) => p.includes("PASSWORD")),+ [],+ );++ const hash = await hashPassword(PASSWORD);+ const on = readConfig(testEnv({ AUTH_PASSWORD_USERS: `[email protected]:${hash}` }));+ assert.equal(passwordConfigured(on), true);+ assert.deepEqual(+ bootProblems(on, true).filter((p) => p.includes("PASSWORD")),+ [],+ );++ const bad = readConfig(testEnv({ AUTH_PASSWORD_USERS: "[email protected]:hunter2hunter2" }));+ assert.equal(passwordConfigured(bad), false);+ assert.ok(bootProblems(bad, true).some((p) => p.includes("AUTH_PASSWORD_USERS")));++ const limits = readConfig(+ testEnv({ AUTH_PASSWORD_USERS: `[email protected]:${hash}`, AUTH_PASSWORD_LIMIT_PER_IP: "999" }),+ );+ assert.ok(bootProblems(limits, true).some((p) => p.includes("AUTH_PASSWORD_LIMIT_PER_IP")));+});