Multiplayer agent harness for work.
feat(auth): allow operator admin login without email
Vishnu95b5a6a9941c
diff --git a/.codex/skills/deploy-qm/SKILL.md b/.codex/skills/deploy-qm/SKILL.mdindex d985222f0..99069b4e7 100644--- a/.codex/skills/deploy-qm/SKILL.md+++ b/.codex/skills/deploy-qm/SKILL.md@@ -7,16 +7,16 @@ description: Deploy the QM package from an organization-owned repository into FlRead [`../../../deployment.md`](../../../deployment.md) completely and follow itas the authoritative workflow. Read only the selected provider reference. Read-`references/email.md` before collecting secrets, because sign-in needs an email-transport and one of its steps needs the operator's DNS. Read+`references/email.md` before collecting email secrets. Administrators can defer+email setup and use `qm admin-login`; ordinary email sign-in needs a transport. Read`references/slack.md` only when Slack is requested.A deployment needs a base model key and a way for people to sign in. Collectboth in the same pass. The base model provider is a deployment choice recordedas `modelProvider`, not a setting to leave for the Admin page. Sign-in is either-the built-in `auth` broker, which needs an email transport, or an external OIDC-provider such as Slack, which needs no email at all — read `references/email.md`-only once the operator has chosen the broker.+the built-in `auth` broker, with optional email setup for an initial admin-only+deployment, or an external OIDC provider such as Slack. Read `references/email.md`+once the operator has chosen the broker.Use the installed `@yc-software/qm` dependency through `npm exec qm -- <command>`. Donot require or clone the QM source repository. Complete every acceptance checkdiff --git a/README.md b/README.mdindex d18b2b7eb..87caf521e 100644--- a/README.md+++ b/README.md@@ -8,6 +8,11 @@ A multiplayer agent harness for work. In Slack and on the web.Tell your coding agent of choice `Let's deploy https://github.com/yc-software/qm`. From here, it should follow the deployment guide in this repo.+Administrators can try a deployment before configuring email: run `qm admin-login`+with its configuration and secrets, then open the five-minute, single-use link.+Configure email delivery later for ordinary email sign-in and invitation emails.+See the [CLI instructions](cli/README.md#administrator-login-without-email).+## What is QM?Most agents are designed like personal assistants. You can make one work for a wholediff --git a/cli/README.md b/cli/README.mdindex b95eb5648..34594669f 100644--- a/cli/README.md+++ b/cli/README.md@@ -102,6 +102,7 @@ planup [--yes] [--build-from[=repo]] [--image-label label]slack renderoutputs [--json]+admin-login [--email [email protected]]proof scope-key <scope-id>secrets push [--from file]status@@ -112,7 +113,29 @@ sandbox build [--from image] [--tag tag] [--dry-run]sandbox publish [--from image] [--app registry/repo] [--tag tag] [--dry-run]```-All deploy commands accept `--config`, `--env-file`, and `--sandbox-dir`. `dev` remains+## Administrator login without email++After deployment, run `qm admin-login` to print a single-use login URL valid for+five minutes. Open it and confirm the displayed administrator email. The command+uses the deployment's existing `PORTAL_SESSION_SECRET` and the email in+`ADMIN_GRANTS`; if several admins are configured, select one with `--email`.+QM checks that the selected account still has `org_admin` access when the link+is redeemed. The command creates no account or role grant.++Run it from the deployment directory with its `.env`, or use `--config` and+`--env-file`. Inside a running deployment without a config file, supply+`PORTAL_PUBLIC_URL`, `PORTAL_SESSION_SECRET`, and `ADMIN_GRANTS` through its+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`+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.++Deployment commands accept `--config`, `--env-file`, and `--sandbox-dir`;+`admin-login` uses only `--config` and `--env-file`. `dev` remainsthe contributor worktree loop and is separate from the portable deployment contract.## Package contractdiff --git a/cli/src/backends/doctor.ts b/cli/src/backends/doctor.tsindex 77916c14b..aa2c20b4b 100644--- a/cli/src/backends/doctor.ts+++ b/cli/src/backends/doctor.ts@@ -10,7 +10,8 @@ import {} from "../config.ts";import { CliError, errMessage, step, warn } from "../log.ts";import { capture, deploymentSecretValue, flyBin, isInvalidSecret, readEnvFile, which } from "../util.ts";-import { computedSecrets } from "../secrets.ts";+import { computedSecrets, serviceSecretValue } from "../secrets.ts";+import { emailTransportConfigured } from "../preflight.ts";export function slackManifestBotScopes(manifest: string): string[] {try {@@ -283,8 +284,13 @@ async function smtpReachable(host: string, port: number): Promise<string> {}async function authBrokerCheck(config: QmConfig, secrets: Map<string, string>, haveValues: boolean): Promise<void> {+ if (haveValues && !emailTransportConfigured(config, secrets)) {+ step("sign-in email: disabled; use qm admin-login for administrator access");+ return;+ }const transport = config.env.auth?.AUTH_EMAIL_TRANSPORT?.trim() === "smtp" ? "smtp" : "resend";- const sender = deploymentSecretValue("AUTH_EMAIL_FROM", secrets.get("AUTH_EMAIL_FROM"));+ const value = (name: string): string | undefined => serviceSecretValue(config, "auth", name, secrets);+ const sender = value("AUTH_EMAIL_FROM");if (haveValues) {const address = (/<([^>]+)>\s*$/.exec((sender ?? "").trim())?.[1] ?? sender ?? "").trim();if (!/^[^@\s]+@[^@\s]+\.[^@\s]+$/.test(address)) {@@ -295,7 +301,7 @@ async function authBrokerCheck(config: QmConfig, secrets: Map<string, string>, hstep(`sign-in links send from ${address}`);}if (transport === "resend") {- const key = deploymentSecretValue("RESEND_API_KEY", secrets.get("RESEND_API_KEY"));+ const key = value("RESEND_API_KEY");if (!key) {warn("RESEND_API_KEY is not available locally — skipping the live Resend check");return;@@ -304,7 +310,7 @@ async function authBrokerCheck(config: QmConfig, secrets: Map<string, string>, hstep("Resend API key: ok (verify the sending domain under https://resend.com/domains)");return;}- const host = deploymentSecretValue("SMTP_HOST", secrets.get("SMTP_HOST"));+ const host = value("SMTP_HOST");if (!host) {warn("SMTP_HOST is not available locally — skipping the live SMTP reachability check");return;diff --git a/cli/src/cli.ts b/cli/src/cli.tsindex 272e081f2..b7dfb5590 100644--- a/cli/src/cli.ts+++ b/cli/src/cli.ts@@ -28,6 +28,7 @@ import { renderSlackFiles, runOutputs } from "./commands/outputs.ts";import { cliVersion } from "./manifest.ts";import { gitTopLevel, promptHidden, writeEnvValue } from "./util.ts";import { scopeStorageKey } from "./scope-storage-key.ts";+import { runAdminLogin } from "./commands/admin-login.ts";interface Parsed {positionals: string[];@@ -131,6 +132,7 @@ ${bold("DEPLOY (operator)")} ${dim("— runs in the deployment directory")}config get <dot.path> print one config value (raw scalar, JSON otherwise)slack render render the bot manifest (+ SSO manifest for Slack OIDC)outputs [--json] print the Web UI, health, and Slack app creation links+ admin-login [--email <admin-email>] print a single-use admin login link, valid for five minutesproof scope-key <scope-id> derive the provider snapshot key for an exact scopeinfra render re-derive infra/terraform.tfvars from configinfra build-image build the AWS deploy MicroVM image and record its pin@@ -425,6 +427,17 @@ async function dispatch(argv: string[]): Promise<void> {return;}+ case "admin-login": {+ rejectUnknownFlags(flags, ["config", "env-file", "email"]);+ rejectExtraPositionals(positionals, 0);+ runAdminLogin({+ configPath: strFlag(flags, "config"),+ envFile: strFlag(flags, "env-file"),+ email: strFlag(flags, "email"),+ });+ return;+ }+case "conformance": {rejectUnknownFlags(flags, ["static", "config", "env-file", "sandbox-dir", "target"]);rejectExtraPositionals(positionals, 1);diff --git a/cli/src/commands/admin-login.ts b/cli/src/commands/admin-login.tsnew file mode 100644index 000000000..883e8d5bb--- /dev/null+++ b/cli/src/commands/admin-login.ts@@ -0,0 +1,86 @@+import { createHmac, randomBytes } from "node:crypto";+import { dirname, join } from "node:path";+import { configPathInDir, loadConfigAt } from "../config.ts";+import { CliError, note } from "../log.ts";+import { deploymentSecretValue, isMissingOrPlaceholder, readEnvFile } from "../util.ts";++export function adminLoginUrl(options: {+ publicUrl: string;+ secret: string;+ adminGrants: string;+ email?: string;+}): string {+ let origin: string;+ try {+ const url = new URL(options.publicUrl);+ if (+ (url.protocol !== "https:" &&+ !(url.protocol === "http:" && ["localhost", "127.0.0.1", "[::1]"].includes(url.hostname))) ||+ url.pathname !== "/" ||+ url.search ||+ url.hash ||+ url.username ||+ url.password ||+ url.hostname.endsWith(".")+ )+ throw new Error("origin");+ origin = url.origin;+ } catch {+ throw new CliError("admin-login requires an HTTPS public URL (HTTP is allowed only on localhost)");+ }+ if (isMissingOrPlaceholder(options.secret) || options.secret.trim().length < 32) {+ throw new CliError("admin-login requires the deployment's PORTAL_SESSION_SECRET (at least 32 characters)");+ }+ const admins = [+ ...new Set(+ options.adminGrants.split(",").flatMap((entry) => {+ const separator = entry.lastIndexOf(":");+ const email = entry.slice(0, separator).trim().toLowerCase();+ return entry.slice(separator + 1).trim() === "org_admin" &&+ email.length <= 254 &&+ /^[^@\s,;<>"]+@[^@\s,;<>"]+\.[^@\s,;<>"]+$/.test(email)+ ? [email]+ : [];+ }),+ ),+ ];+ const email = options.email?.trim().toLowerCase() ?? (admins.length === 1 ? admins[0] : undefined);+ if (!email || !admins.includes(email)) {+ throw new CliError(+ "admin-login requires one email with :org_admin in ADMIN_GRANTS; use --email to choose among configured admins",+ );+ }+ const now = Math.floor(Date.now() / 1000);+ const payload = {+ k: "admin-login",+ sub: email,+ aud: origin,+ iat: now,+ exp: now + 300,+ jti: randomBytes(18).toString("base64url"),+ };+ const body = Buffer.from(JSON.stringify(payload)).toString("base64url");+ const key = createHmac("sha256", options.secret).update("portal.admin-login.v1").digest();+ const signature = createHmac("sha256", key).update(body).digest("base64url");+ return `${origin}/auth/admin-login#token=${body}.${signature}`;+}++export function runAdminLogin(options: { configPath?: string; envFile?: string; email?: string }): void {+ const configPath = options.configPath ?? configPathInDir(process.cwd());+ const loaded = configPath ? loadConfigAt(configPath) : undefined;+ if (loaded && (!loaded.config.services.includes("portal") || !loaded.config.services.includes("admin"))) {+ throw new CliError("admin-login requires the portal and admin services");+ }+ const env = readEnvFile(options.envFile ?? join(loaded ? dirname(loaded.path) : process.cwd(), ".env"));+ const secretValue = (name: string): string | undefined => deploymentSecretValue(name, env.get(name));+ const config = loaded?.config;+ note(+ adminLoginUrl({+ publicUrl: config?.publicUrl ?? secretValue("PORTAL_PUBLIC_URL") ?? "",+ secret: secretValue(config?.secretEnv?.portal?.PORTAL_SESSION_SECRET ?? "PORTAL_SESSION_SECRET") ?? "",+ adminGrants:+ config?.env.core?.ADMIN_GRANTS ?? secretValue(config?.secretEnv?.core?.ADMIN_GRANTS ?? "ADMIN_GRANTS") ?? "",+ email: options.email,+ }),+ );+}diff --git a/cli/src/commands/setup.ts b/cli/src/commands/setup.tsindex c475f3a26..89d402eb3 100644--- a/cli/src/commands/setup.ts+++ b/cli/src/commands/setup.ts@@ -6,8 +6,15 @@ import { Writable } from "node:stream";import { CONFIG_FILENAME, configPathInDir, loadConfigAt, validOrgId, type Target, type QmConfig } from "../config.ts";import { bold, die, dim, header, note, ok, warn } from "../log.ts";import { HOSTING_PROVIDER_IDS, isTarget } from "../providers.ts";-import { computedSecrets, MINT_JWK, MINT_LOCALLY, type ComputedSecret } from "../secrets.ts";-import { isInvalidSecret, readEnvFile } from "../util.ts";+import {+ computedSecrets,+ emailSecretNames,+ MINT_JWK,+ MINT_LOCALLY,+ serviceSecretValue,+ type ComputedSecret,+} from "../secrets.ts";+import { isInvalidSecret, isMissingOrPlaceholder, readEnvFile } from "../util.ts";import { runInit } from "./init.ts";export function adminGrantEmails(adminGrants: string | undefined): string {@@ -138,8 +145,16 @@ export function playbookFor(name: string, config: QmConfig): string[] {export function pendingSecrets(config: QmConfig,env: Map<string, string>,+ includeEmail = false,): { todo: ComputedSecret[]; done: ComputedSecret[] } {- const operator = computedSecrets(config).filter((secret) => secret.managedBy === "operator" && secret.required);+ const emailNames = includeEmail+ ? emailSecretNames(config)+ .filter((name) => isMissingOrPlaceholder(config.env.auth?.[name]))+ .map((name) => config.secretEnv?.auth?.[name] ?? name)+ : [];+ const operator = computedSecrets(config).filter(+ (secret) => secret.managedBy === "operator" && (secret.required || emailNames.includes(secret.name)),+ );const todo = operator.filter((secret) => isInvalidSecret(secret.name, env.get(secret.name)));const done = operator.filter((secret) => !isInvalidSecret(secret.name, env.get(secret.name)));todo.sort((a, b) => Number(b.required) - Number(a.required) || a.name.localeCompare(b.name));@@ -224,7 +239,12 @@ export async function runSetup(opts: { dir: string }): Promise<void> {const config = loadConfigAt(configPath).config;const envPath = join(dir, ".env");const env = readEnvFile(envPath);- const { todo, done } = pendingSecrets(config, env);+ const emailNames = emailSecretNames(config);+ const includeEmail =+ emailNames.length > 0 &&+ (emailNames.some((name) => serviceSecretValue(config, "auth", name, env)?.trim()) ||+ /^y/i.test(await ask("Set up sign-in email now? Admins can use qm admin-login without email. [y/N]: ")));+ const { todo, done } = pendingSecrets(config, env, includeEmail);header(`Secrets for org ${config.orgId} (target ${config.target})`);if (done.length > 0) ok(`${done.length} already set in .env — skipping: ${done.map((s) => s.name).join(", ")}`);@@ -292,7 +312,7 @@ export async function runSetup(opts: { dir: string }): Promise<void> {}header("Next");- const remainingRequired = todo.filter((s) => s.required && !collected.has(s.name)).map((s) => s.name);+ const remainingRequired = todo.filter((s) => !collected.has(s.name)).map((s) => s.name);const stepLine = (n: number, cmd: string, why: string): void =>note(` ${n}. ${cmd.padEnd(24)} ${dim(`# ${why}`)}`);let n = 1;diff --git a/cli/src/preflight.ts b/cli/src/preflight.tsindex 7550fe2b3..6f6892b5c 100644--- a/cli/src/preflight.ts+++ b/cli/src/preflight.ts@@ -6,6 +6,7 @@ import { fileURLToPath } from "node:url";import type { QmConfig } from "./config.ts";import { CliError, errMessage, step, warn } from "./log.ts";import { deploymentSecretValue } from "./util.ts";+import { emailSecretNames, serviceSecretValue } from "./secrets.ts";const PROBE_TIMEOUT_MS = 10_000;@@ -263,10 +264,18 @@ export async function smtpVerify(options: SmtpVerifyOptions): Promise<void> {}}+export function emailTransportConfigured(config: QmConfig, secrets: ReadonlyMap<string, string>): boolean {+ const names = emailSecretNames(config);+ return names.length > 0 && names.every((name) => Boolean(serviceSecretValue(config, "auth", name, secrets)?.trim()));+}+export async function emailTransportPreflight(config: QmConfig, secrets: ReadonlyMap<string, string>): Promise<void> {if (!config.services.includes("auth")) return;+ const configured = emailTransportConfigured(config, secrets);+ if (!configured) step("sign-in email: disabled; use qm admin-login for administrator access");const transport = config.env.auth?.AUTH_EMAIL_TRANSPORT?.trim() === "smtp" ? "smtp" : "resend";- const value = (name: string): string | undefined => deploymentSecretValue(name, secrets.get(name))?.trim();+ const value = (name: string): string | undefined =>+ (serviceSecretValue(config, "auth", name, secrets) ?? deploymentSecretValue(name, secrets.get(name)))?.trim();if (transport === "resend") {const stray = ["SMTP_HOST", "SMTP_USERNAME", "SMTP_PASSWORD"].filter((name) => value(name));if (stray.length) {@@ -283,6 +292,7 @@ export async function emailTransportPreflight(config: QmConfig, secrets: Readonl"core still uses it to email external-user invitations",);}+ if (!configured) return;const host = value("SMTP_HOST");const username = value("SMTP_USERNAME");const password = value("SMTP_PASSWORD");diff --git a/cli/src/secrets.ts b/cli/src/secrets.tsindex 11ce00b56..fb95689a7 100644--- a/cli/src/secrets.ts+++ b/cli/src/secrets.ts@@ -1,6 +1,7 @@import { isVirtualService, type DeclaredServiceName } from "./services.ts";import type { ModelProvider, QmConfig } from "./config.ts";import { TARGET_ENV_DEFAULTS } from "./target-env-defaults.ts";+import { deploymentSecretValue } from "./util.ts";type SecretCondition =| { kind: "env-equals"; service: DeclaredServiceName; name: string; value: string }@@ -19,7 +20,7 @@ export interface SecretSpec {name: string;service: DeclaredServiceName;envName?: string;- required: boolean | { when: SecretCondition; optionalOtherwise?: true };+ required: boolean | { when: SecretCondition; optional?: true; optionalOtherwise?: true };description: string;generate?: string;managedBy?: "operator" | "terraform";@@ -406,7 +407,7 @@ export const FIRST_PARTY_SECRET_SPECS: readonly SecretSpec[] = [{name: "AUTH_EMAIL_FROM",service: "auth",- required: true,+ required: false,description: 'Verified sender for sign-in links and external-user invitations, e.g. "Acme <[email protected]>".',},{@@ -419,7 +420,10 @@ export const FIRST_PARTY_SECRET_SPECS: readonly SecretSpec[] = [{name: "RESEND_API_KEY",service: "auth",- required: { when: { kind: "env-equals", service: "auth", name: "AUTH_EMAIL_TRANSPORT", value: "resend" } },+ required: {+ when: { kind: "env-equals", service: "auth", name: "AUTH_EMAIL_TRANSPORT", value: "resend" },+ optional: true,+ },description: "Resend API key used to deliver sign-in links and external-user invitations.",},{@@ -432,19 +436,28 @@ export const FIRST_PARTY_SECRET_SPECS: readonly SecretSpec[] = [{name: "SMTP_HOST",service: "auth",- required: { when: { kind: "env-equals", service: "auth", name: "AUTH_EMAIL_TRANSPORT", value: "smtp" } },+ required: {+ when: { kind: "env-equals", service: "auth", name: "AUTH_EMAIL_TRANSPORT", value: "smtp" },+ optional: true,+ },description: "SMTP relay hostname used to deliver sign-in links.",},{name: "SMTP_USERNAME",service: "auth",- required: { when: { kind: "env-equals", service: "auth", name: "AUTH_EMAIL_TRANSPORT", value: "smtp" } },+ required: {+ when: { kind: "env-equals", service: "auth", name: "AUTH_EMAIL_TRANSPORT", value: "smtp" },+ optional: true,+ },description: "SMTP username for the sign-in-link relay.",},{name: "SMTP_PASSWORD",service: "auth",- required: { when: { kind: "env-equals", service: "auth", name: "AUTH_EMAIL_TRANSPORT", value: "smtp" } },+ required: {+ when: { kind: "env-equals", service: "auth", name: "AUTH_EMAIL_TRANSPORT", value: "smtp" },+ optional: true,+ },description: "SMTP password for the sign-in-link relay.",},];@@ -478,10 +491,20 @@ function targetEnvDefault(config: QmConfig, service: string, name: string): strifunction requirementFor(config: QmConfig, spec: SecretSpec): boolean | null {if (typeof spec.required === "boolean") return spec.required;- if (conditionMatches(config, spec.required.when)) return true;+ if (conditionMatches(config, spec.required.when)) return !spec.required.optional;return spec.required.optionalOtherwise ? false : null;}+export function emailSecretNames(config: QmConfig): string[] {+ if (!config.services.includes("auth")) return [];+ return [+ "AUTH_EMAIL_FROM",+ ...(config.env.auth?.AUTH_EMAIL_TRANSPORT?.trim() === "smtp"+ ? ["SMTP_HOST", "SMTP_USERNAME", "SMTP_PASSWORD"]+ : ["RESEND_API_KEY"]),+ ];+}+export function computedSecrets(config: QmConfig): ComputedSecret[] {const byName = new Map<string, ComputedSecret>();for (const spec of FIRST_PARTY_SECRET_SPECS) {@@ -618,6 +641,21 @@ export function secretsForService(return computedSecrets(config).filter((secret) => secretDestinations(secret, pluginNames).has(service));}+export function serviceSecretValue(+ config: QmConfig,+ service: DeclaredServiceName,+ name: string,+ values: ReadonlyMap<string, string>,+): string | undefined {+ let value = config.env[service]?.[name];+ for (const secret of secretsForService(config, service)) {+ if (!runtimeSecretNames(service, secret).includes(name)) continue;+ const supplied = deploymentSecretValue(secret.name, values.get(secret.name));+ if (supplied !== undefined) value = supplied;+ }+ return value;+}+function requiresOtherEmailTransport(config: QmConfig, condition: SecretCondition): boolean {if (condition.kind === "all")return condition.conditions.some((nested) => requiresOtherEmailTransport(config, nested));diff --git a/cli/templates/deployment/SKILL.md b/cli/templates/deployment/SKILL.mdindex 7c54ca764..ca0e210c9 100644--- a/cli/templates/deployment/SKILL.md+++ b/cli/templates/deployment/SKILL.md@@ -7,16 +7,16 @@ description: Deploy the QM package from an organization-owned deployment repositRead `../../../deployment.md` completely and follow it as the authoritativeworkflow. Read only the selected provider reference. Read `references/email.md`-before collecting secrets, because sign-in needs an email transport and one of-its steps needs the operator's DNS. Read `references/slack.md` only when Slack-is requested.+before collecting email secrets. Administrators can defer email setup and use+`qm admin-login`; ordinary email sign-in needs a transport. Read+`references/slack.md` only when Slack is requested.A deployment needs a base model key and a way for people to sign in. Collectboth in the same pass. The base model provider is a deployment choice recordedas `modelProvider`, not a setting to leave for the Admin page. Sign-in is either-the built-in `auth` broker, which needs an email transport, or an external OIDC-provider such as Slack, which needs no email at all — read `references/email.md`-only once the operator has chosen the broker.+the built-in `auth` broker, with optional email setup for an initial admin-only+deployment, or an external OIDC provider such as Slack. Read `references/email.md`+once the operator has chosen the broker.Use the repository's installed `@yc-software/qm` dependency through`npm exec qm -- <command>`. Do not require or clone the QM source repository.diff --git a/cli/templates/deployment/deployment.md b/cli/templates/deployment/deployment.mdindex 7b8cbacb3..c19ee999a 100644--- a/cli/templates/deployment/deployment.md+++ b/cli/templates/deployment/deployment.md@@ -111,7 +111,13 @@ register: the CLI generates the broker's signing key and the portal's clientcredentials and derives every `OIDC_*` value from `publicUrl`. Setting any ofthem by hand is refused.-What the operator supplies is a way to send those emails. Do not ask them to+Email setup can be deferred: after deployment, `qm admin-login` prints a+single-use link for the configured administrator, valid for five minutes.+It needs the deployment's local signing secret and creates no account or role+grant. Keep the link private. `qm setup` asks whether to configure email now;+skip that step for an initial administrator-only deployment.++For ordinary user sign-in, the operator supplies a way to send emails. Do not ask them topick a transport by name; ask what they already use for email. An existingmail account or relay (Google Workspace, Postmark, SES, Fastmail) means SMTP —recommend it, since it needs no DNS work — and only an operator who prefersdiff --git a/cli/templates/deployment/references/email.md b/cli/templates/deployment/references/email.mdindex 2288f4e5d..7a8a5c6c1 100644--- a/cli/templates/deployment/references/email.md+++ b/cli/templates/deployment/references/email.md@@ -1,13 +1,21 @@# Email transport for sign-in links-Sign-in uses the built-in `auth` broker, which emails a one-time link. It needs-one transport. SMTP is the default recommendation: any existing mail account or+Ordinary sign-in uses the built-in `auth` broker, which emails a one-time link.+Administrators can start without email: leave the sender and selected transport's+credentials unset, then run `qm admin-login` after deployment. It prints a private,+single-use login link valid for five minutes. The selected account must already+have `org_admin` access. Other users need email or an external identity provider.++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.Set `env.auth.AUTH_EMAIL_TRANSPORT` to `resend` or `smtp` before collecting-secrets, then run `npm exec qm -- setup`, which prompts for exactly the-credentials that choice needs and generates every key itself.+secrets, then run `npm exec qm -- setup` and choose to configure email. It prompts+for exactly the credentials that choice needs and generates every signing key+itself. Email sign-in activates when the sender and every selected credential+are present. Missing credentials disable email sign-in without stopping QM or+`qm admin-login`, even if a sender is still configured.## What you can do, and what only the operator candiff --git a/cli/test/admin-login.test.ts b/cli/test/admin-login.test.tsnew file mode 100644index 000000000..3e1311e69--- /dev/null+++ b/cli/test/admin-login.test.ts@@ -0,0 +1,118 @@+import assert from "node:assert/strict";+import { spawnSync } from "node:child_process";+import { mkdtempSync, rmSync, writeFileSync } from "node:fs";+import { tmpdir } from "node:os";+import { dirname, join } from "node:path";+import { test } from "node:test";+import { fileURLToPath } from "node:url";+import { adminLoginUrl } from "../src/commands/admin-login.ts";+import { openAdminLogin } from "../../plugins/portal/src/admin-login.ts";++const cli = join(dirname(fileURLToPath(import.meta.url)), "../bin/qm.ts");+const settings = {+ publicUrl: "https://qm.example.com",+ secret: "deployment-secret-".repeat(3),+ adminGrants: "[email protected]:org_admin",+};+const tokenFrom = (url: string): string => new URLSearchParams(new URL(url).hash.slice(1)).get("token")!;++test("CLI-issued links satisfy the portal contract and expire after five minutes", () => {+ const url = adminLoginUrl(settings);+ const token = tokenFrom(url);+ const verified = openAdminLogin(token, settings.secret, settings.publicUrl);+ assert.equal(verified?.email, "[email protected]");+ assert.ok(verified);+ assert.equal(new URL(url).pathname, "/auth/admin-login");+ assert.equal(new URL(url).search, "");+ assert.equal(openAdminLogin(token, settings.secret, settings.publicUrl, verified.expiresAtMs), null);+ assert.equal(openAdminLogin(token, "different-secret-".repeat(3), settings.publicUrl), null);+ assert.equal(openAdminLogin(token, settings.secret, "https://other.example.com"), null);+ const other = openAdminLogin(tokenFrom(adminLoginUrl(settings)), settings.secret, settings.publicUrl);+ assert.notEqual(verified.jti, other?.jti);+});++test("CLI only selects configured administrator emails and requires a choice when ambiguous", () => {+ assert.throws(() => adminLoginUrl({ ...settings, email: "[email protected]" }), /configured admins/);+ assert.throws(() => adminLoginUrl({ ...settings, adminGrants: "[email protected]:member" }), /ADMIN_GRANTS/);+ const adminGrants = "[email protected]:org_admin,[email protected]:org_admin";+ assert.throws(() => adminLoginUrl({ ...settings, adminGrants }), /--email/);+ const url = adminLoginUrl({ ...settings, adminGrants, email: " [email protected] " });+ assert.equal(openAdminLogin(tokenFrom(url), settings.secret, settings.publicUrl)?.email, "[email protected]");+});++test("CLI refuses invalid signing keys and unsafe public URLs", () => {+ for (const secret of ["", "replace-me", "short", " ".repeat(40)]) {+ assert.throws(() => adminLoginUrl({ ...settings, secret }), /PORTAL_SESSION_SECRET/);+ }+ for (const publicUrl of [+ "http://public.example.com",+ "https://user:[email protected]",+ "https://qm.example.com/x",+ "https://qm.example.com?x=y",+ ]) {+ assert.throws(() => adminLoginUrl({ ...settings, publicUrl }), /HTTPS public URL/);+ }+ assert.match(+ adminLoginUrl({ ...settings, publicUrl: "http://127.0.0.1:8080" }),+ /^http:\/\/127\.0\.0\.1:8080\/auth\/admin-login#/,+ );+});++test("the command uses deployment config and local secrets without contacting a provider", () => {+ const dir = mkdtempSync(join(tmpdir(), "qm-admin-login-"));+ try {+ writeFileSync(+ join(dir, "qm.config.jsonc"),+ JSON.stringify({+ contract: 1,+ orgId: "acme",+ publicUrl: settings.publicUrl,+ target: "docker",+ services: ["core", "web-ui", "admin", "portal", "auth"],+ env: { auth: { AUTH_EMAIL_TRANSPORT: "resend", AUTH_ALLOWED_EMAIL_DOMAIN: "example.com" } },+ secretEnv: { core: { ADMIN_GRANTS: "OPERATOR_ADMINS" }, portal: { PORTAL_SESSION_SECRET: "SESSION_KEY" } },+ }),+ );+ writeFileSync(join(dir, ".env"), `OPERATOR_ADMINS=${settings.adminGrants}\nSESSION_KEY=${settings.secret}\n`);+ const result = spawnSync(process.execPath, [cli, "admin-login"], { cwd: dir, encoding: "utf8" });+ assert.equal(result.status, 0, result.stderr);+ assert.equal(+ openAdminLogin(tokenFrom(result.stdout.trim()), settings.secret, settings.publicUrl)?.email,+ "[email protected]",+ );+ assert.doesNotMatch(result.stdout, new RegExp(settings.secret));+ const invalid = spawnSync(process.execPath, [cli, "admin-login", "--email", "[email protected]"], {+ cwd: dir,+ encoding: "utf8",+ });+ assert.notEqual(invalid.status, 0);+ assert.equal(invalid.stdout, "");+ } finally {+ rmSync(dir, { recursive: true, force: true });+ }+});++test("the command runs inside a deployment using environment variables alone", () => {+ const dir = mkdtempSync(join(tmpdir(), "qm-admin-login-env-"));+ try {+ const env = {+ ...process.env,+ PORTAL_PUBLIC_URL: settings.publicUrl,+ PORTAL_SESSION_SECRET: settings.secret,+ ADMIN_GRANTS: settings.adminGrants,+ };+ const result = spawnSync(process.execPath, [cli, "admin-login"], { cwd: dir, encoding: "utf8", env });+ assert.equal(result.status, 0, result.stderr);+ assert.equal(+ openAdminLogin(tokenFrom(result.stdout.trim()), settings.secret, settings.publicUrl)?.email,+ "[email protected]",+ );+ for (const args of [["--ttl", "999"], ["--secret", "unsafe"], ["unexpected"]]) {+ const invalid = spawnSync(process.execPath, [cli, "admin-login", ...args], { cwd: dir, encoding: "utf8", env });+ assert.notEqual(invalid.status, 0);+ assert.equal(invalid.stdout, "");+ }+ } finally {+ rmSync(dir, { recursive: true, force: true });+ }+});diff --git a/cli/test/auth-broker.test.ts b/cli/test/auth-broker.test.tsindex c14ead7ac..a7f312ef7 100644--- a/cli/test/auth-broker.test.ts+++ b/cli/test/auth-broker.test.ts@@ -172,7 +172,7 @@ test("the broker's generated secrets reach both sides under the right names", ()assert.ok(!names.has("SMTP_HOST"), "only the configured transport's credentials are collected");for (const name of ["RESEND_API_KEY", "AUTH_EMAIL_FROM"]) {const shared = secrets.find((secret) => secret.name === name)!;- assert.ok(shared.required);+ assert.equal(shared.required, false, "email delivery can be deferred while admins use the operator CLI");assert.deepEqual(runtimeSecretNames("auth", shared), [name]);assert.deepEqual(runtimeSecretNames("core", shared), [name], `core emails external-user invitations with ${name}`);}diff --git a/cli/test/cli-dispatch.test.ts b/cli/test/cli-dispatch.test.tsindex d5b2bf131..2c7b23dff 100644--- a/cli/test/cli-dispatch.test.ts+++ b/cli/test/cli-dispatch.test.ts@@ -50,6 +50,7 @@ test("help lists every deploy + develop command and the deploy-wide options", as"plan","check","config get",+ "admin-login","status","logs","down",diff --git a/cli/test/doctor.test.ts b/cli/test/doctor.test.tsindex b94130b0d..e124af642 100644--- a/cli/test/doctor.test.ts+++ b/cli/test/doctor.test.ts@@ -113,6 +113,41 @@ test("doctor rejects missing and placeholder portal OIDC client ids and tenant g);});+test("remote doctor keeps missing local email values distinct from disabled email", async () => {+ const brokerConfig: QmConfig = {+ ...config,+ sandbox: undefined,+ services: ["core", "portal", "auth"],+ env: {+ core: { HARNESS: "mock" },+ auth: { AUTH_EMAIL_TRANSPORT: "resend", AUTH_ALLOWED_EMAIL_DOMAIN: "example.com" },+ },+ };+ const priorKey = process.env.RESEND_API_KEY;+ const priorSender = process.env.AUTH_EMAIL_FROM;+ const log = console.log;+ const warn = console.warn;+ process.env.RESEND_API_KEY = "";+ process.env.AUTH_EMAIL_FROM = "";+ try {+ for (const secrets of [new Map<string, string>(), new Map([["AUTH_EMAIL_FROM", "[email protected]"]])]) {+ const output: string[] = [];+ console.log = (...values: unknown[]): void => void output.push(values.join(" "));+ console.warn = (...values: unknown[]): void => void output.push(values.join(" "));+ await assert.doesNotReject(doctorCommon(brokerConfig, secrets));+ assert.match(output.join("\n"), /RESEND_API_KEY is not available locally/);+ assert.doesNotMatch(output.join("\n"), /sign-in email: disabled/);+ }+ } finally {+ console.log = log;+ console.warn = warn;+ if (priorKey === undefined) delete process.env.RESEND_API_KEY;+ else process.env.RESEND_API_KEY = priorKey;+ if (priorSender === undefined) delete process.env.AUTH_EMAIL_FROM;+ else process.env.AUTH_EMAIL_FROM = priorSender;+ }+});+test("Fly doctor requires the signing secret for source plugins absent from config", async () => {const dir = mkdtempSync(join(tmpdir(), "qm-fly-doctor-"));const bin = join(dir, "fake-fly.cjs");diff --git a/cli/test/init.test.ts b/cli/test/init.test.tsindex 3ba0f6004..4cdbc246a 100644--- a/cli/test/init.test.ts+++ b/cli/test/init.test.ts@@ -157,20 +157,15 @@ test("init --target fly scaffolds the full hosted topology and both Slack apps",assert.equal(config.env.auth?.AUTH_EMAIL_TRANSPORT, "resend");assert.equal(config.env.portal?.OIDC_PRINCIPAL_CLAIM, undefined, "the broker derives every OIDC_* value");const env = readFileSync(join(dir, ".env.example"), "utf8");- for (const line of [- "ADMIN_GRANTS=",- "AUTH_ALLOWED_EMAILS=",- "AUTH_EMAIL_FROM=",- "RESEND_API_KEY=",- "PORTAL_SESSION_SECRET=",- "ANTHROPIC_API_KEY=",- ]) {+ for (const line of ["ADMIN_GRANTS=", "AUTH_ALLOWED_EMAILS=", "PORTAL_SESSION_SECRET=", "ANTHROPIC_API_KEY="]) {assert.ok(env.split("\n").includes(line), `.env.example should require ${line} for the fly scaffold`);}for (const line of ["# OPENROUTER_API_KEY= # optional","# SLACK_APP_TOKEN= # optional","# SLACK_BOT_TOKEN= # optional",+ "# AUTH_EMAIL_FROM= # optional",+ "# RESEND_API_KEY= # optional",]) {assert.ok(env.split("\n").includes(line), `.env.example should offer ${line}`);}@@ -194,8 +189,8 @@ test("init --email-transport smtp scaffolds smtp keys only and a matching configassert.equal(config.env.auth?.AUTH_EMAIL_TRANSPORT, "smtp");const env = readFileSync(join(dir, ".env.example"), "utf8");assert.equal(env, renderEnvExample(config));- for (const line of ["SMTP_HOST=", "SMTP_USERNAME=", "SMTP_PASSWORD="]) {- assert.ok(env.split("\n").includes(line), `.env.example should require ${line}`);+ for (const line of ["# SMTP_HOST= # optional", "# SMTP_USERNAME= # optional", "# SMTP_PASSWORD= # optional"]) {+ assert.ok(env.split("\n").includes(line), `.env.example should offer ${line}`);}assert.ok(env.split("\n").includes("# RESEND_API_KEY= # optional"),@@ -265,20 +260,15 @@ test("init --target aws scaffolds the full hosted topology, Terraform, and the oassert.match(tfvars, /certificate_arn\s*= ""/);assert.match(readFileSync(join(dir, "infra", "main.tf"), "utf8"), /desired_count\s*= 0/);const env = readFileSync(join(dir, ".env.example"), "utf8").split("\n");- for (const name of [- "ADMIN_GRANTS=",- "PUBLIC_API_URL=",- "AUTH_ALLOWED_EMAILS=",- "AUTH_EMAIL_FROM=",- "RESEND_API_KEY=",- "ANTHROPIC_API_KEY=",- ]) {+ for (const name of ["ADMIN_GRANTS=", "PUBLIC_API_URL=", "AUTH_ALLOWED_EMAILS=", "ANTHROPIC_API_KEY="]) {assert.ok(env.includes(name), `hosted AWS scaffold requires ${name}`);}for (const name of ["# OPENROUTER_API_KEY= # optional","# SLACK_BOT_TOKEN= # optional","# SLACK_APP_TOKEN= # optional",+ "# AUTH_EMAIL_FROM= # optional",+ "# RESEND_API_KEY= # optional",]) {assert.ok(env.includes(name), `hosted AWS scaffold offers deferred ${name}`);}diff --git a/cli/test/preflight.test.ts b/cli/test/preflight.test.tsindex 79c4746e7..1a967384d 100644--- a/cli/test/preflight.test.ts+++ b/cli/test/preflight.test.ts@@ -4,6 +4,7 @@ import { createServer, type Server, type Socket } from "node:net";import type { QmConfig } from "../src/config.ts";import { CliError } from "../src/log.ts";import {+ emailTransportConfigured,emailTransportPreflight,flySandboxTokenPreflight,nodeEngineProblem,@@ -149,6 +150,7 @@ test("email preflight fails check on rejected SMTP credentials and warns on straemailTransportPreflight(config,new Map([+ ["AUTH_EMAIL_FROM", "QM <[email protected]>"],["SMTP_HOST", "127.0.0.1"],["SMTP_USERNAME", "user"],["SMTP_PASSWORD", "right"],@@ -166,6 +168,7 @@ test("email preflight fails check on rejected SMTP credentials and warns on straemailTransportPreflight(config,new Map([+ ["AUTH_EMAIL_FROM", "QM <[email protected]>"],["SMTP_HOST", "127.0.0.1"],["SMTP_USERNAME", "user"],["SMTP_PASSWORD", "wrong"],@@ -202,3 +205,40 @@ test("email preflight does nothing without the auth service", async () => {);assert.deepEqual(lines, []);});++test("missing email credentials disable email without failing deployment checks", async () => {+ for (const transport of ["resend", "smtp"]) {+ const config = { ...CONFIG, env: { auth: { AUTH_EMAIL_TRANSPORT: transport } } };+ assert.equal(emailTransportConfigured(config, new Map()), false);+ await assert.doesNotReject(emailTransportPreflight(config, new Map()));+ for (const values of [+ new Map([["AUTH_EMAIL_FROM", "[email protected]"]]),+ new Map([[transport === "resend" ? "RESEND_API_KEY" : "SMTP_HOST", "configured"]]),+ ]) {+ assert.equal(emailTransportConfigured(config, values), false);+ const output = await quietAsync(() => emailTransportPreflight(config, values));+ assert.ok(output.some((line) => line.includes("sign-in email: disabled")));+ }+ }+});++test("email preflight resolves delivered secret aliases and settings supplied directly in config", async () => {+ const aliased = {+ ...CONFIG,+ env: { auth: { AUTH_EMAIL_TRANSPORT: "resend" } },+ secretEnv: { auth: { AUTH_EMAIL_FROM: "AUTH_SENDER", RESEND_API_KEY: "MAIL_KEY" } },+ };+ const secrets = new Map([+ ["AUTH_SENDER", "[email protected]"],+ ["MAIL_KEY", "re_configured"],+ ]);+ assert.equal(emailTransportConfigured(aliased, secrets), true);+ await assert.doesNotReject(emailTransportPreflight(aliased, secrets));+ assert.equal(emailTransportConfigured(aliased, new Map([["MAIL_KEY", "re_configured"]])), false);+ const direct = {+ ...CONFIG,+ env: { auth: { AUTH_EMAIL_TRANSPORT: "resend", AUTH_EMAIL_FROM: "[email protected]" } },+ };+ assert.equal(emailTransportConfigured(direct, new Map([["RESEND_API_KEY", "re_configured"]])), true);+ await assert.doesNotReject(emailTransportPreflight(direct, new Map([["RESEND_API_KEY", "re_configured"]])));+});diff --git a/cli/test/secrets.test.ts b/cli/test/secrets.test.tsindex 44a1c373a..32398d796 100644--- a/cli/test/secrets.test.ts+++ b/cli/test/secrets.test.ts@@ -358,7 +358,7 @@ test("the invitation-email pair reaches core as optional secrets on every topoloenv: { auth: { AUTH_EMAIL_TRANSPORT: "resend" } },});const shared = secretByName(broker, name);- assert.equal(shared.required, true);+ assert.equal(shared.required, false);assert.deepEqual([...secretDestinations(shared).keys()].sort(), ["auth", "core"]);}});diff --git a/cli/test/setup.test.ts b/cli/test/setup.test.tsindex 32d2c19db..084e54b7a 100644--- a/cli/test/setup.test.ts+++ b/cli/test/setup.test.ts@@ -154,15 +154,13 @@ test("the broker's operator secrets replace the external-IdP ones", () => {assert.ok(!brokerNames.includes("OIDC_CLIENT_SECRET"), "the broker mints the portal's client secret");assert.ok(!brokerNames.includes("OIDC_CLIENT_ID"));assert.ok(!brokerNames.includes("PORTAL_EXPECTED_TEAM_ID"));- for (const name of [- "AUTH_ALLOWED_EMAILS",- "AUTH_EMAIL_FROM",- "AUTH_SIGNING_JWK",- "AUTH_TOKEN_SECRET",- "AUTH_CLIENT_SECRET",- ]) {+ for (const name of ["AUTH_ALLOWED_EMAILS", "AUTH_SIGNING_JWK", "AUTH_TOKEN_SECRET", "AUTH_CLIENT_SECRET"]) {assert.ok(brokerNames.includes(name), `broker mode should collect ${name}`);}+ for (const name of ["AUTH_EMAIL_FROM", "RESEND_API_KEY"]) {+ assert.ok(!brokerNames.includes(name), "email setup can be deferred");+ assert.ok(pendingSecrets(broker, new Map(), true).todo.some((secret) => secret.name === name));+ }assert.match(playbookFor("AUTH_EMAIL_FROM", broker).join("\n"), /verified sender/);assert.match(playbookFor("OIDC_CLIENT_ID", broker).join("\n"), /external identity provider/);});@@ -177,3 +175,32 @@ test("runSetup refuses to run without a TTY", async () => {},);});++test("email setup uses declared secret names and does not reprompt for direct config values", () => {+ const aliased = configFor(+ ["core", "web-ui", "admin", "portal", "auth"],+ `, "secretEnv": { "auth": { "AUTH_EMAIL_FROM": "AUTH_SENDER", "RESEND_API_KEY": "MAIL_KEY" } }`,+ `{ "auth": { "AUTH_EMAIL_TRANSPORT": "resend" } }`,+ );+ const waiting = pendingSecrets(aliased, new Map(), true).todo.map((secret) => secret.name);+ assert.ok(waiting.includes("AUTH_SENDER"));+ assert.ok(waiting.includes("MAIL_KEY"));+ assert.ok(!waiting.includes("AUTH_EMAIL_FROM"));+ assert.ok(!waiting.includes("RESEND_API_KEY"));+ const supplied = pendingSecrets(+ aliased,+ new Map([+ ["AUTH_SENDER", "[email protected]"],+ ["MAIL_KEY", "re_configured"],+ ]),+ true,+ );+ assert.ok(supplied.done.some((secret) => secret.name === "AUTH_SENDER"));+ assert.ok(supplied.done.some((secret) => secret.name === "MAIL_KEY"));+ const direct = {+ ...aliased,+ secretEnv: undefined,+ env: { auth: { AUTH_EMAIL_TRANSPORT: "resend", AUTH_EMAIL_FROM: "[email protected]" } },+ };+ assert.ok(!pendingSecrets(direct, new Map(), true).todo.some((secret) => secret.name === "AUTH_EMAIL_FROM"));+});diff --git a/docs/screenshots/admin-login-confirm.png b/docs/screenshots/admin-login-confirm.pngnew file mode 100644index 000000000..791d5dd91Binary files /dev/null and b/docs/screenshots/admin-login-confirm.png differdiff --git a/docs/screenshots/admin-login-mobile.png b/docs/screenshots/admin-login-mobile.pngnew file mode 100644index 000000000..bfbb3c23eBinary files /dev/null and b/docs/screenshots/admin-login-mobile.png differdiff --git a/docs/screenshots/admin-users-without-email.png b/docs/screenshots/admin-users-without-email.pngnew file mode 100644index 000000000..40ad064ccBinary files /dev/null and b/docs/screenshots/admin-users-without-email.png differdiff --git a/docs/screenshots/email-not-configured.png b/docs/screenshots/email-not-configured.pngnew file mode 100644index 000000000..afcff6c2eBinary files /dev/null and b/docs/screenshots/email-not-configured.png differdiff --git a/plugins/admin/public/index.html b/plugins/admin/public/index.htmlindex fc63aa97e..939812874 100644--- a/plugins/admin/public/index.html+++ b/plugins/admin/public/index.html@@ -11234,7 +11234,7 @@const inviteBtn = document.createElement("button");inviteBtn.className = "primary";inviteBtn.type = "button";- inviteBtn.textContent = "Send invite";+ inviteBtn.textContent = inviteEmail.configured === false ? "Add user" : "Send invite";inviteBtn.onclick = async () => {const email = emailInput.value.trim();if (!email) return setStatus("st-external", "Email required.", "err");@@ -11265,7 +11265,7 @@", but no invitation email was sent: " +r.data.emailProblem +"." +- (r.data.signInUrl ? " Share " + r.data.signInUrl + " with them." : "")+ (r.data.signInUrl ? " Portal: " + r.data.signInUrl + ". A working sign-in method is required." : ""): "Updated " + member.email + " — " + labelRole(member.role) + expires,r.data.emailSent || !r.data.emailProblem ? "ok" : "dirty",true,@@ -11285,9 +11285,9 @@inviteNote.textContent =inviteEmail.configured === false? (inviteEmail.problem || "Invitation emails are not configured") +- ". The user is still added; share the sign-in link yourself." ++ ". Users can still be added, but need a configured sign-in method before they can log in." +signInHint- : "Invitation emails go out through Resend — core needs RESEND_API_KEY and AUTH_EMAIL_FROM. Without them the user is still added and you share the sign-in link yourself.";+ : "Invitation emails go out through Resend — core needs RESEND_API_KEY and AUTH_EMAIL_FROM. Without them users can still be added, but need a configured sign-in method before they can log in.";const invite = document.createElement("div");invite.className = "hidden";invite.style.margin = "0 0 14px";diff --git a/plugins/auth/README.md b/plugins/auth/README.mdindex f3373a201..39960227a 100644--- a/plugins/auth/README.md+++ b/plugins/auth/README.md@@ -1,23 +1,22 @@# auth — the built-in sign-in brokerAn OIDC authorization server that speaks exactly the subset-[`plugins/portal`](../portal/src/oidc.ts) consumes, so the portal keeps talking-standard OIDC and never grows a second authentication path. Instead of an+[`plugins/portal`](../portal/src/oidc.ts) consumes. Instead of anexternal identity provider, people prove who they are by opening a one-time linkemailed to an allowed address.## Endpoints-| Route | Reached by | Notes |-| --------------------------------------- | ------------------------------------------- | ------------------------------------------------------------------------------ |-| `GET /authorize` | browser, via the portal at `/idp/authorize` | validates the request and renders the email form |-| `POST /authorize` | browser, via the portal | always answers with the same confirmation page, then emails a link out of band |-| `GET /verify` | browser, via the portal at `/idp/verify` | consumes the link and redirects to the portal's `/auth/callback` with a code |-| `POST /token` | portal, over the private network | HTTP Basic client auth, authorization-code grant, PKCE S256 |-| `GET /userinfo` | portal, over the private network | Bearer access token, verified statelessly |-| `GET /.well-known/jwks.json` | portal, over the private network | the ES256 public key |-| `GET /.well-known/openid-configuration` | operators | discovery, for debugging |-| `GET /healthz` | the platform | liveness |+| Route | Reached by | Notes |+| --------------------------------------- | ------------------------------------------- | ---------------------------------------------------------------------------------------------- |+| `GET /authorize` | browser, via the portal at `/idp/authorize` | validates the request and renders the email form |+| `POST /authorize` | browser, via the portal | with email configured, answers with the same confirmation page, then emails a link out of band |+| `GET /verify` | browser, via the portal at `/idp/verify` | consumes the link and redirects to the portal's `/auth/callback` with a code |+| `POST /token` | portal, over the private network | HTTP Basic client auth, authorization-code grant, PKCE S256 |+| `GET /userinfo` | portal, over the private network | Bearer access token, verified statelessly |+| `GET /.well-known/jwks.json` | portal, over the private network | the ES256 public key |+| `GET /.well-known/openid-configuration` | operators | discovery, for debugging |+| `GET /healthz` | the platform | liveness |The broker is never published directly. The portal republishes only the threebrowser-facing routes under `AUTH_BROKER_PREFIX` (`/idp` by default), which is@@ -37,8 +36,10 @@ a claim the broker fails closed and refuses the sign-in.## Configuration-Every value below is set by `qm` from the deployment config and the secret-store; the broker refuses to start if any of it is missing or a placeholder.+Values below are set by `qm` from the deployment config and the secret store.+Authentication keys and an email allowlist or domain remain required. Email+delivery is optional; missing or incomplete email configuration disables delivery.+Fully supplied email configuration is validated at boot.| Variable | Source || ------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------- |@@ -69,9 +70,17 @@ allowed. One of the two env variables is still required at boot.## Email transport-`AUTH_EMAIL_TRANSPORT` selects one of two, and the broker refuses to start-without that transport's credentials. `AUTH_EMAIL_FROM` is the verified sender-either way, optionally as `Name <[email protected]>`.+`AUTH_EMAIL_TRANSPORT` selects Resend (the default) or SMTP. When+`AUTH_EMAIL_FROM` or any of the selected transport's credentials are absent, the+broker starts without email delivery. The sign-in page and submissions return+503 with “Email delivery isn't configured”; no form is offered and no email is+claimed to have been sent. Previously issued links and codes keep their normal+expiration and single-use checks.++To enable email sign-in, configure the selected transport's credentials and+`AUTH_EMAIL_FROM`, then restart. The sender must be verified and may be written+as `Name <[email protected]>`. Supplying only part of the configuration leaves+email delivery disabled. Fully supplied but invalid configuration is refused at boot.| Transport | Variables | Notes || --------- | ------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |diff --git a/plugins/auth/src/config.ts b/plugins/auth/src/config.tsindex 12e6ad3d4..f744b8e44 100644--- a/plugins/auth/src/config.ts+++ b/plugins/auth/src/config.ts@@ -130,6 +130,12 @@ export function validEmail(value: string): boolean {return value.length <= 254 && /^[^@\s,;<>"]+@[^@\s,;<>"]+\.[^@\s,;<>"]+$/.test(value);}+export function emailConfigured(cfg: AuthConfig): boolean {+ const credentials =+ cfg.transport === "resend" ? [cfg.resendApiKey] : [cfg.smtp.host, cfg.smtp.username, cfg.smtp.password];+ return [cfg.emailFrom, ...credentials].every((value) => Boolean(value.trim()));+}+function httpsUrlProblem(label: string, value: string, requireHttps: boolean): string | null {if (isMissingOrPlaceholder(value)) return `${label} is required and may not be a placeholder`;let url: URL;@@ -184,24 +190,27 @@ export function bootProblems(cfg: AuthConfig, isProd: boolean): string[] {problems.push("AUTH_ALLOWED_EMAIL_DOMAIN must be a valid, non-placeholder email domain when set");}- if (isMissingOrPlaceholder(cfg.emailFrom) || !validEmail(senderAddress(cfg.emailFrom))) {- problems.push('AUTH_EMAIL_FROM must be a verified sender address, optionally as "Name <[email protected]>"');- }- if (cfg.transport === "resend") {- if (isMissingOrPlaceholder(cfg.resendApiKey))- problems.push("RESEND_API_KEY is required when AUTH_EMAIL_TRANSPORT is resend");- } else {- if (isMissingOrPlaceholder(cfg.smtp.host)) problems.push("SMTP_HOST is required when AUTH_EMAIL_TRANSPORT is smtp");- if (isMissingOrPlaceholder(cfg.smtp.username))- problems.push("SMTP_USERNAME is required when AUTH_EMAIL_TRANSPORT is smtp");- if (isMissingOrPlaceholder(cfg.smtp.password))- problems.push("SMTP_PASSWORD is required when AUTH_EMAIL_TRANSPORT is smtp");- if (!Number.isInteger(cfg.smtp.port) || cfg.smtp.port < 1 || cfg.smtp.port > 65535)- problems.push("SMTP_PORT must be a TCP port number");- if (isProd && cfg.smtp.tls === "none")- problems.push(- "SMTP_TLS=none may not be used in production — SMTP credentials would cross the network in cleartext",- );+ if (emailConfigured(cfg)) {+ if (isMissingOrPlaceholder(cfg.emailFrom) || !validEmail(senderAddress(cfg.emailFrom))) {+ problems.push('AUTH_EMAIL_FROM must be a verified sender address, optionally as "Name <[email protected]>"');+ }+ if (cfg.transport === "resend") {+ if (isMissingOrPlaceholder(cfg.resendApiKey))+ problems.push("RESEND_API_KEY is required when AUTH_EMAIL_TRANSPORT is resend");+ } else {+ if (isMissingOrPlaceholder(cfg.smtp.host))+ problems.push("SMTP_HOST is required when AUTH_EMAIL_TRANSPORT is smtp");+ if (isMissingOrPlaceholder(cfg.smtp.username))+ problems.push("SMTP_USERNAME is required when AUTH_EMAIL_TRANSPORT is smtp");+ if (isMissingOrPlaceholder(cfg.smtp.password))+ problems.push("SMTP_PASSWORD is required when AUTH_EMAIL_TRANSPORT is smtp");+ if (!Number.isInteger(cfg.smtp.port) || cfg.smtp.port < 1 || cfg.smtp.port > 65535)+ problems.push("SMTP_PORT must be a TCP port number");+ if (isProd && cfg.smtp.tls === "none")+ problems.push(+ "SMTP_TLS=none may not be used in production — SMTP credentials would cross the network in cleartext",+ );+ }}if (isProd && isMissingOrPlaceholder(cfg.coreSigningSecret)) {diff --git a/plugins/auth/src/email.ts b/plugins/auth/src/email.tsindex eacfc6f23..3b5468186 100644--- a/plugins/auth/src/email.ts+++ b/plugins/auth/src/email.ts@@ -1,6 +1,6 @@import { randomBytes } from "node:crypto";import { escapeHtml } from "../../chassis/src/http.ts";-import { senderAddress, type AuthConfig } from "./config.ts";+import { emailConfigured, senderAddress, type AuthConfig } from "./config.ts";import { smtpDeliver } from "./smtp.ts";export interface OutgoingEmail {@@ -65,7 +65,8 @@ function smtpMailer(cfg: AuthConfig): Mailer {};}-export function mailerFor(cfg: AuthConfig): Mailer {+export function mailerFor(cfg: AuthConfig): Mailer | null {+ if (!emailConfigured(cfg)) return null;return cfg.transport === "smtp" ? smtpMailer(cfg) : resendMailer(cfg);}diff --git a/plugins/auth/src/index.ts b/plugins/auth/src/index.tsindex 8648b3f4e..c223358c6 100644--- a/plugins/auth/src/index.ts+++ b/plugins/auth/src/index.ts@@ -25,6 +25,7 @@ export function bootChecks(): void {export async function startServer(): Promise<void> {bootChecks();const signingKey = await loadSigningKey(CFG.signingJwk!);+ const mailer = mailerFor(CFG);const branding = createBrandingCache(async () => {const path = withSourceAuthNonce("/v1/surface-config", CFG.coreSigningSecret);const r = await fetch(`${CFG.coreApiUrl}${path}`, {@@ -40,7 +41,7 @@ export async function startServer(): Promise<void> {signingKey,signer: new TokenSigner(CFG.tokenSecret, CFG.issuer),claims: coreClaimStore(CFG.coreApiUrl, CFG.coreSigningSecret, "auth"),- mailer: mailerFor(CFG),+ mailer,brandName: () => {void branding.forRender();return branding.current().selfLabel || CFG.brandName;@@ -55,7 +56,7 @@ export async function startServer(): Promise<void> {});server.listen(PORT, () => {console.log(- `[auth] sign-in broker on http://localhost:${PORT} (issuer ${CFG.issuer}, key ${signingKey.kid}, ${CFG.transport} email)`,+ `[auth] sign-in broker on http://localhost:${PORT} (issuer ${CFG.issuer}, key ${signingKey.kid}, ${mailer ? `${CFG.transport} email` : "email not configured"})`,);if (!CFG.coreSigningSecret)console.warn(diff --git a/plugins/auth/src/server.ts b/plugins/auth/src/server.tsindex cbc04284e..1225e0a0f 100644--- a/plugins/auth/src/server.ts+++ b/plugins/auth/src/server.ts@@ -19,7 +19,7 @@ export interface AuthDeps {signingKey: SigningKey;signer: TokenSigner;claims: ClaimStore;- mailer: Mailer;+ mailer: Mailer | null;brandName?: () => string;emailAllowed?: (email: string) => Promise<boolean>;now?: () => number;@@ -129,6 +129,14 @@ export function createAuthHandler(deps: AuthDeps): (req: IncomingMessage, res: Sconst problem = (res: ServerResponse, status: number, heading: string, msg: string, detail?: string): void =>sendHtml(res, status, problemPage({ brandName: brandName(), heading, msg, ...(detail ? { detail } : {}) }));+ const emailUnavailable = (res: ServerResponse): void =>+ problem(+ res,+ 503,+ "Email delivery isn't configured",+ "Your administrator needs to configure email delivery before you can request a sign-in link.",+ );+const signInUrl = ((): string | undefined => {try {return new URL("/auth/login", cfg.redirectUri).toString();@@ -159,6 +167,7 @@ export function createAuthHandler(deps: AuthDeps): (req: IncomingMessage, res: S"Start again from the page you were trying to reach.",parsed.problem,);+ if (!mailer) return emailUnavailable(res);const sealed = await signer.sealRequest(parsed.request, cfg.requestTtlS, now());return sendHtml(res,@@ -167,7 +176,7 @@ export function createAuthHandler(deps: AuthDeps): (req: IncomingMessage, res: S);}- async function sendLink(request: AuthRequest, email: string, ip: string): Promise<void> {+ async function sendLink(request: AuthRequest, email: string, ip: string, sender: Mailer): Promise<void> {const nowMs = now();const within = async (kind: string, value: string, limit: number): Promise<boolean> =>withinRateLimit(claims, { secret: cfg.tokenSecret, kind, value, limit, windowS: cfg.sendWindowS, nowMs });@@ -194,7 +203,7 @@ export function createAuthHandler(deps: AuthDeps): (req: IncomingMessage, res: Sconst sealed = await signer.sealLink({ ...request, email }, cfg.linkTtlS, nowMs);const link = `${cfg.issuer}/verify#token=${encodeURIComponent(sealed.token)}`;try {- const receipt = await mailer.send(+ const receipt = await sender.send(renderSignInEmail({ to: email, brandName: brandName(), link, ttlMinutes: linkTtlMinutes }),);console.log(`[auth] sign-in link sent to ${email} (${receipt})`);@@ -204,6 +213,7 @@ export function createAuthHandler(deps: AuthDeps): (req: IncomingMessage, res: S}async function authorizeSubmit(req: IncomingMessage, res: ServerResponse): Promise<void> {+ if (!mailer) return emailUnavailable(res);let raw: string;try {raw = await readBody(req, MAX_FORM_BYTES);@@ -238,7 +248,7 @@ export function createAuthHandler(deps: AuthDeps): (req: IncomingMessage, res: S}const ip = clientIpOf(req);sendHtml(res, 200, linkSentPage({ brandName: brandName(), email, ttlMinutes: linkTtlMinutes }));- background(() => sendLink(request, email, ip));+ background(() => sendLink(request, email, ip, mailer));}function confirmVerify(res: ServerResponse): void {diff --git a/plugins/auth/test/config.test.ts b/plugins/auth/test/config.test.tsindex 36d6bd319..3c3e91670 100644--- a/plugins/auth/test/config.test.ts+++ b/plugins/auth/test/config.test.ts@@ -19,6 +19,26 @@ test("a complete broker configuration boots", () => {);});+test("the broker boots without email delivery while keeping its authentication requirements", () => {+ for (const transport of ["resend", "smtp"]) {+ const withoutEmail = {+ AUTH_EMAIL_TRANSPORT: transport,+ AUTH_EMAIL_FROM: undefined,+ RESEND_API_KEY: undefined,+ SMTP_HOST: undefined,+ SMTP_USERNAME: undefined,+ SMTP_PASSWORD: undefined,+ CORE_SIGNING_SECRET: "a".repeat(48),+ };+ assert.equal(problemsFor(withoutEmail), "");+ assert.match(+ problemsFor({ ...withoutEmail, AUTH_ALLOWED_EMAILS: undefined }),+ /AUTH_ALLOWED_EMAILS or AUTH_ALLOWED_EMAIL_DOMAIN is required/,+ );+ assert.match(problemsFor({ ...withoutEmail, AUTH_TOKEN_SECRET: undefined }), /AUTH_TOKEN_SECRET is required/);+ }+});+test("production refuses to start without a trust boundary", () => {const problems = problemsFor({ AUTH_ALLOWED_EMAILS: undefined, AUTH_ALLOWED_EMAIL_DOMAIN: undefined });assert.match(problems, /AUTH_ALLOWED_EMAILS or AUTH_ALLOWED_EMAIL_DOMAIN is required/);@@ -30,8 +50,6 @@ test("production refuses missing or placeholder credentials and keys", () => {["AUTH_CLIENT_SECRET", /AUTH_CLIENT_SECRET is required/],["AUTH_TOKEN_SECRET", /AUTH_TOKEN_SECRET is required/],["AUTH_SIGNING_JWK", /AUTH_SIGNING_JWK is required/],- ["AUTH_EMAIL_FROM", /AUTH_EMAIL_FROM must be a verified sender/],- ["RESEND_API_KEY", /RESEND_API_KEY is required/],] as const) {for (const value of [undefined, "", " ", "replace-me", "TODO"]) {assert.match(problemsFor({ [name]: value }), pattern, `${name}=${JSON.stringify(value)}`);@@ -73,19 +91,23 @@ test("a weak or reused token secret is refused", () => {);});-test("the smtp transport demands its own credentials", () => {- const smtp = { AUTH_EMAIL_TRANSPORT: "smtp", RESEND_API_KEY: undefined };- assert.match(problemsFor(smtp), /SMTP_HOST is required/);- assert.equal(- problemsFor({- ...smtp,- SMTP_HOST: "smtp.example.com",- SMTP_USERNAME: "u",- SMTP_PASSWORD: "p",- CORE_SIGNING_SECRET: "a".repeat(48),- }),- "",- );+test("missing any email credential disables delivery without preventing startup", () => {+ const settings = {+ SMTP_HOST: "smtp.example.com",+ SMTP_USERNAME: "u",+ SMTP_PASSWORD: "p",+ CORE_SIGNING_SECRET: "a".repeat(48),+ };+ for (const transport of ["resend", "smtp"]) {+ const complete = { ...settings, AUTH_EMAIL_TRANSPORT: transport };+ assert.equal(problemsFor(complete), "");+ const credentials = transport === "resend" ? ["RESEND_API_KEY"] : ["SMTP_HOST", "SMTP_USERNAME", "SMTP_PASSWORD"];+ for (const name of ["AUTH_EMAIL_FROM", ...credentials]) {+ for (const value of [undefined, "", " "]) {+ assert.equal(problemsFor({ ...complete, [name]: value }), "", `${transport}: ${name}=${JSON.stringify(value)}`);+ }+ }+ }});test("malformed allowlists and senders are refused", () => {@@ -95,6 +117,8 @@ test("malformed allowlists and senders are refused", () => {/valid, non-placeholder email domain/,);assert.match(problemsFor({ AUTH_EMAIL_FROM: "qm <not-an-address>" }), /verified sender address/);+ assert.match(problemsFor({ AUTH_EMAIL_FROM: "replace-me" }), /verified sender address/);+ assert.match(problemsFor({ RESEND_API_KEY: "replace-me" }), /RESEND_API_KEY is required/);});test("oversized token lifetimes are refused", () => {@@ -146,16 +170,19 @@ test("`node src/index.ts` refuses to boot on a placeholder configuration and serassert.match(refuses.stderr, /AUTH_CLIENT_SECRET is required/);const PORT = "18299";- const child = spawnSync(- process.execPath,- [- "--input-type=module",- "-e",- `import('./src/index.ts').then(async (m) => { await m.startServer(); const r = await fetch('http://127.0.0.1:${PORT}/healthz'); console.log(r.status); process.exit(0); })`,- ],- { cwd: process.cwd(), env: { ...base, PORT }, encoding: "utf8" },- );- assert.equal(child.status, 0, child.stderr);- assert.match(child.stdout, /200/);- assert.match(child.stdout, /sign-in broker on/);+ for (const email of [{}, { AUTH_EMAIL_FROM: undefined, RESEND_API_KEY: undefined }, { RESEND_API_KEY: undefined }]) {+ const child = spawnSync(+ process.execPath,+ [+ "--input-type=module",+ "-e",+ `import('./src/index.ts').then(async (m) => { await m.startServer(); const r = await fetch('http://127.0.0.1:${PORT}/healthz'); console.log(r.status); process.exit(0); })`,+ ],+ { cwd: process.cwd(), env: { ...base, ...email, PORT }, encoding: "utf8" },+ );+ assert.equal(child.status, 0, child.stderr);+ assert.match(child.stdout, /200/);+ assert.match(child.stdout, /sign-in broker on/);+ if ("RESEND_API_KEY" in email) assert.match(child.stdout, /email not configured/);+ }});diff --git a/plugins/auth/test/email.test.ts b/plugins/auth/test/email.test.tsindex 03e990597..86bcb8261 100644--- a/plugins/auth/test/email.test.ts+++ b/plugins/auth/test/email.test.ts@@ -1,11 +1,32 @@import test from "node:test";import assert from "node:assert/strict";import { readConfig } from "../src/config.ts";-import { renderMessage, renderSignInEmail, resendMailer } from "../src/email.ts";+import { mailerFor, renderMessage, renderSignInEmail, resendMailer } from "../src/email.ts";import { testEnv } from "./helpers.ts";const cfg = readConfig(testEnv());+test("no mailer is created with missing or incomplete email configuration", () => {+ for (const transport of ["resend", "smtp"]) {+ assert.equal(+ mailerFor(+ readConfig(testEnv({ AUTH_EMAIL_TRANSPORT: transport, AUTH_EMAIL_FROM: undefined, RESEND_API_KEY: undefined })),+ ),+ null,+ );+ const complete = {+ AUTH_EMAIL_TRANSPORT: transport,+ SMTP_HOST: "smtp.example.com",+ SMTP_USERNAME: "u",+ SMTP_PASSWORD: "p",+ };+ const credentials = transport === "resend" ? ["RESEND_API_KEY"] : ["SMTP_HOST", "SMTP_USERNAME", "SMTP_PASSWORD"];+ for (const name of ["AUTH_EMAIL_FROM", ...credentials]) {+ assert.equal(mailerFor(readConfig(testEnv({ ...complete, [name]: undefined }))), null, `${transport}: ${name}`);+ }+ }+});+test("the sign-in email carries the link once in both alternatives and never a bare secret", () => {const message = renderSignInEmail({to: "[email protected]",diff --git a/plugins/auth/test/flow.test.ts b/plugins/auth/test/flow.test.tsindex 7679dc798..3c73354d2 100644--- a/plugins/auth/test/flow.test.ts+++ b/plugins/auth/test/flow.test.ts@@ -134,6 +134,49 @@ test("the whole authorization-code flow the portal drives succeeds", async (t) =assert.equal(userinfo.email_verified, true);});+test("without email delivery, sign-in pages explain the configuration instead of claiming to send a link", async (t) => {+ const h = await startHarness({ env: { RESEND_API_KEY: undefined } });+ t.after(() => h.close());++ const page = await fetch(`${h.base}/authorize?${authorizeQuery()}`);+ const submitted = await fetch(`${h.base}/authorize`, form({ email: "[email protected]" }));+ for (const response of [page, submitted]) {+ assert.equal(response.status, 503);+ assert.equal(response.headers.get("cache-control"), "no-store");+ const html = await response.text();+ assert.match(html, /Email delivery isn't configured/);+ assert.doesNotMatch(html, /<form|Check your email|link is on its way/);+ }+ await h.settle();+ assert.deepEqual(h.mailer.sent, []);+ assert.deepEqual(h.claims.calls, []);+ assert.equal((await fetch(`${h.base}/healthz`)).status, 200);+});++test("removing email delivery does not invalidate already issued sign-in links", async (t) => {+ const configured = await startHarness();+ t.after(() => configured.close());+ const { verifier } = await requestLink(configured);+ const link = linkFrom(configured.mailer);+ const h = await startHarness({+ env: { AUTH_EMAIL_FROM: undefined, RESEND_API_KEY: undefined },+ claims: configured.claims,+ });+ t.after(() => h.close());++ const verified = await openLink(h, link);+ assert.equal(verified.status, 302);+ const code = new URL(verified.headers.get("location")!).searchParams.get("code")!;+ const exchanged = await exchange(h, code, verifier);+ assert.equal(exchanged.status, 200);+ const tokens = (await exchanged.json()) as { id_token: string; access_token: string };+ const claims = await verifyIdTokenLikePortal(h, tokens.id_token, "nonce-value");+ assert.equal(claims.email, "[email protected]");+ const info = await fetch(`${h.base}/userinfo`, { headers: { authorization: `Bearer ${tokens.access_token}` } });+ assert.equal(info.status, 200);+ assert.equal((await openLink(h, link)).status, 400);+});+test("a replayed magic link is refused", async (t) => {const h = await startHarness();t.after(() => h.close());diff --git a/plugins/auth/test/helpers.ts b/plugins/auth/test/helpers.tsindex 5b36d639f..2e68f8ba1 100644--- a/plugins/auth/test/helpers.ts+++ b/plugins/auth/test/helpers.ts@@ -1,6 +1,6 @@import { createServer, type Server } from "node:http";import { createHash, generateKeyPairSync, randomBytes } from "node:crypto";-import { readConfig, type AuthConfig } from "../src/config.ts";+import { emailConfigured, readConfig, type AuthConfig } from "../src/config.ts";import type { ClaimStore } from "../../chassis/src/claims.ts";import type { Mailer, OutgoingEmail } from "../src/email.ts";import { loadSigningKey } from "../src/keys.ts";@@ -108,7 +108,7 @@ export async function startHarness(signingKey: await loadSigningKey(cfg.signingJwk!),signer: new TokenSigner(cfg.tokenSecret, cfg.issuer),claims,- mailer,+ mailer: emailConfigured(cfg) ? mailer : null,...(options.brandName ? { brandName: options.brandName } : {}),emailAllowed: options.emailAllowed ?? (async () => false),now: () => now.ms,diff --git a/plugins/portal/README.md b/plugins/portal/README.mdindex d5fe009d0..96dc114ad 100644--- a/plugins/portal/README.md+++ b/plugins/portal/README.md@@ -32,9 +32,38 @@ surfaces, and it does **not** import the core.synthesizing the surface cookie for compatibility and attaching a short-lived signed portalidentity. Surfaces pass that identity to core, which verifies it before any user-scoped action.+## Operator admin login without email++Run `qm admin-login` with the deployment's configuration and secrets to generate+a private admin login URL. Open it and confirm the displayed email. The URL+expires after five minutes and works once. With multiple email-based+`ADMIN_GRANTS` administrators, use `qm admin-login --email [email protected]`.+The command can also run with `PORTAL_PUBLIC_URL`, `PORTAL_SESSION_SECRET`, and+`ADMIN_GRANTS` in its environment, without a deployment config file.++`GET /auth/admin-login` only renders the confirmation page. Its script moves the+token out of the URL fragment into the form and clears the fragment. Nothing+signs in until the user submits that same-origin form. `POST /auth/admin-login`+verifies the token's purpose, portal origin, signature and lifetime, checks the+account's current admin status, and consumes its unique ID through core's+durable Postgres replay store. It then issues the ordinary portal session and+clears any old impersonation cookie. No account or role is created.++This is an operator capability: keep deployment secrets and generated URLs+private. It does not prove an email inbox, replace another user's login, or+depend on a hosting provider. Leave the built-in broker's sender and selected+email credentials unset to run without email; configure them later and restart+to enable ordinary email sign-in. Existing external OIDC login is unchanged.++Live integration checks require a running core, Postgres, admin, portal and+built-in auth broker with email unset. Set `QM_ADMIN_LOGIN_ENV_FILE` to a private+JSON file containing that deployment's environment and run+`node --test test/integration/admin-login.test.ts` from the repository root. Use a+disposable test deployment: the test redeems real links for its configured admin.+## Security model (the parts that must be right)-- **Identity comes only from the verified OIDC subject.** The browser never asserts it. The+- **Identity comes from verified OIDC or an operator-issued admin link.** The browser cannot assert an unsigned identity. Theupstream request is built **from scratch** — an _allowlist_ of safe headers(`content-type`/`accept`/`user-agent`/…) plus the one synthesized cookie. The client'sheaders and cookies are **never** forwarded, so a browser can't smuggle a forgeddiff --git a/plugins/portal/src/admin-login.ts b/plugins/portal/src/admin-login.tsnew file mode 100644index 000000000..e71901663--- /dev/null+++ b/plugins/portal/src/admin-login.ts@@ -0,0 +1,48 @@+import { createHash } from "node:crypto";+import { deriveKey, open } from "./session.ts";++export function openAdminLogin(token: string, secret: string, publicUrl: string, nowMs = Date.now()) {+ if (secret.trim().length < 32 || token.length > 4096) return null;+ const claims = open(token, deriveKey(secret, "portal.admin-login.v1"));+ if (!claims) return null;+ const { k, sub, aud, iat, exp, jti } = claims;+ const now = Math.floor(nowMs / 1000);+ if (+ k !== "admin-login" ||+ aud !== publicUrl ||+ typeof sub !== "string" ||+ sub.length > 254 ||+ !/^[^@\s,;<>"]+@[^@\s,;<>"]+\.[^@\s,;<>"]+$/.test(sub) ||+ sub !== sub.trim().toLowerCase() ||+ typeof iat !== "number" ||+ !Number.isSafeInteger(iat) ||+ typeof exp !== "number" ||+ !Number.isSafeInteger(exp) ||+ iat > now + 5 ||+ exp <= now ||+ exp <= iat ||+ exp - iat > 300 ||+ typeof jti !== "string" ||+ !/^[A-Za-z0-9_-]{24}$/.test(jti)+ )+ return null;+ return { email: sub, jti, expiresAtMs: exp * 1000 };+}++export const ADMIN_LOGIN_SCRIPT = `(function () {+ var token = new URLSearchParams(location.hash.slice(1)).get("token");+ history.replaceState(null, "", location.pathname);+ try {+ if (!token || token.length > 4096) throw new Error();+ var body = token.split(".")[0].replace(/-/g, "+").replace(/_/g, "/");+ var claims = JSON.parse(new TextDecoder().decode(Uint8Array.from(atob(body), function (c) { return c.charCodeAt(0); })));+ if (typeof claims.sub !== "string") throw new Error();+ document.getElementById("admin-email").textContent = claims.sub;+ document.getElementById("admin-token").value = token;+ document.getElementById("admin-confirm").disabled = false;+ } catch (e) {+ document.getElementById("admin-email").textContent = "This link is missing or invalid. Generate a new link with qm admin-login.";+ }+})();`;++export const ADMIN_LOGIN_SCRIPT_HASH = `sha256-${createHash("sha256").update(ADMIN_LOGIN_SCRIPT).digest("base64")}`;diff --git a/plugins/portal/src/index.ts b/plugins/portal/src/index.tsindex 444545cf2..506269ade 100644--- a/plugins/portal/src/index.ts+++ b/plugins/portal/src/index.ts@@ -1,5 +1,6 @@import { createServer, type IncomingMessage, type ServerResponse } from "node:http";import { pathToFileURL } from "node:url";+import { ADMIN_LOGIN_SCRIPT, ADMIN_LOGIN_SCRIPT_HASH, openAdminLogin } from "./admin-login.ts";import { LRUCache } from "lru-cache";import {deriveKey,@@ -38,11 +39,11 @@ import {FORWARD_WEBHOOK_HEADERS,} from "./proxy.ts";import { signedHeaders, withSourceAuthNonce } from "../../chassis/src/core-client.ts";-import { coreClaimStore, withinRateLimit, ClaimStoreUnavailableError } from "../../chassis/src/claims.ts";+import { coreClaimStore, claimOnce, withinRateLimit, ClaimStoreUnavailableError } from "../../chassis/src/claims.ts";import { coreEmailAllowed } from "../../chassis/src/external-members.ts";import { mintPortalIdentity, PORTAL_IDENTITY_HEADER } from "../../chassis/src/portal-identity.ts";import { errMessage } from "../../chassis/src/errors.ts";-import { json, escapeHtml, serveEmojiFavicon } from "../../chassis/src/http.ts";+import { json, escapeHtml, serveEmojiFavicon, readBody, PayloadTooLargeError } from "../../chassis/src/http.ts";import {CORE_API_URL as CORE,CORE_ORG_ID as ORG,@@ -265,10 +266,10 @@ async function isAdmin(sub: string): Promise<boolean> {const PAGE_CSP ="default-src 'none'; style-src 'unsafe-inline'; form-action 'self'; base-uri 'none'; frame-ancestors 'none'";-function sendHtml(res: ServerResponse, status: number, html: string): void {+function sendHtml(res: ServerResponse, status: number, html: string, csp = PAGE_CSP): void {res.writeHead(status, {"content-type": "text/html; charset=utf-8",- "content-security-policy": PAGE_CSP,+ "content-security-policy": csp,"x-content-type-options": "nosniff","cache-control": "no-store",});@@ -884,6 +885,7 @@ async function handle(req: IncomingMessage, res: ServerResponse): Promise<void>if (pathname === "/auth/login" && method === "GET") return authLogin(req, res, url);if (pathname === "/auth/callback" && method === "GET") return authCallback(req, res, url);+ if (pathname === "/auth/admin-login") return adminLogin(req, res);if (pathname === "/auth/logout" && method === "POST") {if (!sameOriginRequest(req)) return json(res, 403, { error: "forbidden" });setSession(res, [@@ -1136,6 +1138,79 @@ async function handle(req: IncomingMessage, res: ServerResponse): Promise<void>});}+async function adminLogin(req: IncomingMessage, res: ServerResponse): Promise<void> {+ if (!SESSION_SECRET || SESSION_SECRET.trim().length < 32 || !CORE_SIGNING_SECRET) {+ return json(res, 503, { error: "not_configured" });+ }+ if (req.method === "GET") {+ return sendHtml(+ res,+ 200,+ cardPage({+ title: "Admin sign-in",+ heading: "Sign in as an administrator",+ msg: "Only continue if you generated this link for your own admin account.",+ icon: LOCK_ICON,+ extra: '<p id="admin-email"></p><noscript>JavaScript is required to open this login link.</noscript>',+ actions: `<form method="post" action="/auth/admin-login"><input id="admin-token" name="token" type="hidden"><button id="admin-confirm" class="btn primary" style="width:100%" type="submit" disabled>Sign in</button></form><script>${ADMIN_LOGIN_SCRIPT}</script>`,+ help: "This link expires after five minutes and can be used once. Generate another with qm admin-login.",+ }),+ `${PAGE_CSP}; script-src '${ADMIN_LOGIN_SCRIPT_HASH}'`,+ );+ }+ if (req.method !== "POST") return json(res, 405, { error: "method_not_allowed" });+ if (!sameOriginRequest(req)) return json(res, 403, { error: "forbidden" });+ let token: string;+ try {+ token = new URLSearchParams(await readBody(req, 8192)).get("token") ?? "";+ } catch (error) {+ if (error instanceof PayloadTooLargeError) return json(res, 413, { error: "payload_too_large" });+ throw error;+ }+ const claims = openAdminLogin(token, SESSION_SECRET, ORIGIN);+ const fail = () =>+ sendHtml(+ res,+ 400,+ signInErrorHtml("This admin link is invalid, expired, or already used. Generate a new link with qm admin-login."),+ );+ if (!claims) return fail();+ const allowed = await adminProbeAttempt(claims.email);+ if (allowed === null)+ return sendHtml(res, 503, signInErrorHtml("Admin access could not be checked. Please try again."));+ if (!allowed) return sendHtml(res, 403, signInErrorHtml("This account does not have admin access."));+ try {+ const claimsStore = coreClaimStore(CORE, CORE_SIGNING_SECRET, "portal");+ if (!(await claimOnce(claimsStore, `admin-login:${claims.jti}`, claims.expiresAtMs))) return fail();+ } catch (error) {+ if (error instanceof ClaimStoreUnavailableError) {+ return sendHtml(res, 503, signInErrorHtml("Sign-in is temporarily unavailable. Please try again."));+ }+ throw error;+ }+ setAuthenticatedSession(res, claims.email);+ res.writeHead(303, { location: "/admin/", "cache-control": "no-store" });+ res.end();+}++function setAuthenticatedSession(res: ServerResponse, sub: string, name = ""): void {+ const now = Math.floor(Date.now() / 1000);+ const session: SessionClaims = {+ k: "session",+ sub,+ org: ORG,+ auth: now,+ iat: now,+ exp: now + SESSION_TTL_S,+ ...(name ? { name } : {}),+ };+ setSession(res, [+ ...sessionCookieSet(seal(session, sessionKey)),+ clearCookie("portal_oidc_tmp", "/auth", SECURE_COOKIES),+ clearCookie("portal_impersonate", "/", SECURE_COOKIES),+ ]);+}+function authLogin(req: IncomingMessage, res: ServerResponse, url: URL): void {const returnTo = sanitizeReturnTo(url.searchParams.get("returnTo"), PUBLIC_URL, APPS_DOMAIN);const localSession = localDevSession(req, Date.now(), true);@@ -1197,20 +1272,7 @@ async function authCallback(req: IncomingMessage, res: ServerResponse, url: URL)return fail(errMessage(e, "sign-in failed"));}- const now = Math.floor(Date.now() / 1000);- const session: SessionClaims = {- k: "session",- sub,- org: ORG,- auth: now,- iat: now,- exp: now + SESSION_TTL_S,- ...(name ? { name } : {}),- };- setSession(res, [- ...sessionCookieSet(seal(session, sessionKey)),- clearCookie("portal_oidc_tmp", "/auth", SECURE_COOKIES),- ]);+ setAuthenticatedSession(res, sub, name);res.writeHead(302, {location: sanitizeReturnTo(tmp.returnTo, PUBLIC_URL, APPS_DOMAIN),"cache-control": "no-store",diff --git a/test/admin-login-token.test.ts b/test/admin-login-token.test.tsnew file mode 100644index 000000000..73c3a478f--- /dev/null+++ b/test/admin-login-token.test.ts@@ -0,0 +1,62 @@+import assert from "node:assert/strict";+import test from "node:test";+import { adminLoginUrl } from "../cli/src/commands/admin-login.ts";+import { openAdminLogin } from "../plugins/portal/src/admin-login.ts";+import { deriveKey, seal } from "../plugins/portal/src/session.ts";++const secret = "admin-login-contract-test-secret-32-characters";+const publicUrl = "https://qm.example.com";++function cliToken() {+ const url = new URL(adminLoginUrl({ publicUrl, secret, adminGrants: "[email protected]:org_admin" }));+ return new URLSearchParams(url.hash.slice(1)).get("token")!;+}++test("the published CLI token format is accepted by the portal", () => {+ const token = cliToken();+ const claims = openAdminLogin(token, secret, publicUrl);+ assert.ok(claims);+ assert.equal(claims.email, "[email protected]");+ assert.ok(claims.expiresAtMs > Date.now());+ assert.ok(claims.expiresAtMs <= Date.now() + 300_000);+ assert.equal(openAdminLogin(token, `${secret}-other`, publicUrl), null);+ assert.equal(openAdminLogin(token, secret, "https://another.example.com"), null);+ assert.equal(openAdminLogin(token, secret, publicUrl, claims.expiresAtMs), null);+ assert.equal(openAdminLogin(token, secret, publicUrl, Date.now() - 60_000), null);+});++test("admin link validation enforces purpose, lifetime, and principal boundaries", () => {+ const original = JSON.parse(Buffer.from(cliToken().split(".")[0]!, "base64url").toString()) as Record<+ string,+ unknown+ >;+ const key = deriveKey(secret, "portal.admin-login.v1");+ const invalid = [+ { k: "session" },+ { k: "impersonate" },+ { aud: "https://attacker.example.com" },+ { sub: "" },+ { sub: "admin" },+ { sub: "[email protected]" },+ { sub: "[email protected]\n" },+ { jti: "" },+ { jti: "../admin" },+ { iat: "1" },+ { exp: null },+ { exp: Number(original.iat) },+ { exp: Number(original.iat) + 301 },+ { iat: Number(original.iat) + 0.5 },+ { exp: Number(original.exp) + 0.5 },+ ];+ for (const changes of invalid) {+ assert.equal(+ openAdminLogin(seal({ ...original, ...changes }, key), secret, publicUrl),+ null,+ JSON.stringify(changes),+ );+ }+ assert.equal(openAdminLogin(seal(original, deriveKey(secret, "portal.session.v1")), secret, publicUrl), null);+ for (const invalidToken of ["", "garbage", `${cliToken()}extra`, "a".repeat(4097)]) {+ assert.equal(openAdminLogin(invalidToken, secret, publicUrl), null);+ }+});diff --git a/test/integration/admin-login.test.ts b/test/integration/admin-login.test.tsnew file mode 100644index 000000000..b640014af--- /dev/null+++ b/test/integration/admin-login.test.ts@@ -0,0 +1,132 @@+import assert from "node:assert/strict";+import { spawnSync } from "node:child_process";+import { readFileSync } from "node:fs";+import { fileURLToPath } from "node:url";+import test from "node:test";+import { adminLoginUrl } from "../../cli/src/commands/admin-login.ts";+import { deriveKey, openSession, seal } from "../../plugins/portal/src/session.ts";++const envPath = process.env.QM_ADMIN_LOGIN_ENV_FILE;+const env = envPath ? (JSON.parse(readFileSync(envPath, "utf8")) as Record<string, string>) : null;+const root = fileURLToPath(new URL("../../", import.meta.url));++test(+ "operator login against real QM core, Postgres, admin, portal, and email broker",+ {+ skip: !env && "Set QM_ADMIN_LOGIN_ENV_FILE to the isolated live deployment environment JSON",+ },+ async (t) => {+ assert.ok(env);+ const publicUrl = env.PORTAL_PUBLIC_URL!;+ const secret = env.PORTAL_SESSION_SECRET!;+ const configuredAdmin = env.ADMIN_GRANTS!.split(":")[0]!.toLowerCase();+ const cli = () => {+ const command = spawnSync(process.execPath, ["cli/bin/qm.ts", "admin-login"], {+ cwd: root,+ env: { PATH: process.env.PATH, ...env },+ encoding: "utf8",+ });+ assert.equal(command.status, 0, command.stderr);+ return new URL(command.stdout.trim());+ };+ const tokenOf = (url: URL) => new URLSearchParams(url.hash.slice(1)).get("token")!;+ const post = (token: string, extraHeaders: Record<string, string> = {}) =>+ fetch(`${publicUrl}/auth/admin-login`, {+ method: "POST",+ redirect: "manual",+ headers: { origin: publicUrl, "content-type": "application/x-www-form-urlencoded", ...extraHeaders },+ body: new URLSearchParams({ token }),+ });+ const cookieOf = (res: Response) => {+ const cookie = res.headers+ .getSetCookie()+ .find((value) => value.startsWith("portal_session=") && !value.startsWith("portal_session=;"));+ assert.ok(cookie);+ assert.match(cookie, /HttpOnly/);+ assert.match(cookie, /SameSite=Lax/);+ if (publicUrl.startsWith("https:")) assert.match(cookie, /Secure/);+ return cookie.split(";")[0]!;+ };++ await t.test("all services start without email, and email sign-in reports its unavailable state", async () => {+ assert.equal(env.RESEND_API_KEY ?? "", "");+ assert.equal(env.AUTH_EMAIL_FROM ?? "", "");+ for (const base of [env.CORE_API_URL!, env.ADMIN_UPSTREAM!, env.AUTH_BROKER_UPSTREAM!, publicUrl]) {+ assert.equal((await fetch(`${base}/healthz`)).status, 200, base);+ }+ const redirect = await fetch(`${publicUrl}/auth/login`, { redirect: "manual" });+ assert.equal(redirect.status, 302);+ const emailPage = await fetch(redirect.headers.get("location")!);+ assert.equal(emailPage.status, 503);+ assert.match(await emailPage.text(), /Email delivery (?:isn.t|isn't) configured/);+ });++ await t.test("CLI link requires confirmation and establishes the existing QM admin session once", async () => {+ const url = cli();+ const confirmation = await fetch(url);+ assert.equal(confirmation.status, 200);+ assert.equal(confirmation.headers.get("cache-control"), "no-store");+ assert.equal(confirmation.headers.get("referrer-policy"), "no-referrer");+ assert.equal(confirmation.headers.getSetCookie().length, 0);+ assert.match(await confirmation.text(), /Only continue if you generated this link/);+ const res = await post(tokenOf(url));+ assert.equal(res.status, 303);+ assert.equal(res.headers.get("location"), "/admin/");+ const cookie = cookieOf(res);+ const claims = openSession(+ decodeURIComponent(cookie.slice("portal_session=".length)),+ deriveKey(secret, "portal.session.v1"),+ Date.now(),+ env.CORE_ORG_ID,+ );+ assert.equal(claims?.sub, configuredAdmin);+ assert.ok(res.headers.getSetCookie().some((value) => value.startsWith("portal_impersonate=;")));+ const whoami = await fetch(`${publicUrl}/admin/api/whoami`, { headers: { cookie } });+ assert.equal(whoami.status, 200);+ assert.equal(((await whoami.json()) as { isAdmin: boolean }).isAdmin, true);+ assert.equal((await post(tokenOf(url))).status, 400);+ });++ await t.test("concurrent redemption grants exactly one session", async () => {+ const token = tokenOf(cli());+ const results = await Promise.all([post(token), post(token)]);+ assert.deepEqual(results.map((res) => res.status).sort(), [303, 400]);+ });++ await t.test(+ "bad signatures, stale tokens, other portals and non-admin identities cannot obtain a session",+ async () => {+ const original = JSON.parse(Buffer.from(tokenOf(cli()).split(".")[0]!, "base64url").toString()) as Record<+ string,+ unknown+ >;+ const key = deriveKey(secret, "portal.admin-login.v1");+ const invalid = [+ { aud: "https://other.example.com" },+ { iat: Number(original.iat) - 600, exp: Number(original.exp) - 600 },+ { k: "session" },+ ];+ for (const changes of invalid) {+ const res = await post(seal({ ...original, ...changes }, key));+ assert.equal(res.status, 400);+ assert.equal(res.headers.getSetCookie().length, 0);+ }+ assert.equal((await post(`${tokenOf(cli())}broken`)).status, 400);+ const unauthorized = new URL(+ adminLoginUrl({ publicUrl, secret, adminGrants: "[email protected]:org_admin" }),+ );+ const denied = await post(tokenOf(unauthorized));+ assert.equal(denied.status, 403);+ assert.equal(denied.headers.getSetCookie().length, 0);+ },+ );++ await t.test("cross-origin requests cannot redeem an otherwise valid link", async () => {+ const token = tokenOf(cli());+ assert.equal((await post(token, { origin: "https://attacker.example.com" })).status, 403);+ assert.equal((await post(token, { origin: "null" })).status, 403);+ assert.equal((await post(token, { "sec-fetch-site": "cross-site" })).status, 403);+ assert.equal((await post(token)).status, 303);+ });+ },+);