Skip to content

A local-first multi-agent app development platform, built on PenguinHarness

feat(cli,server): terminal sign-in, signed sessions, and no auth secret on disk (#443)

Myriad-Dreamin3ba0f8392eae
diff --git a/README.md b/README.md
index 441f5bed..060cbb1b 100644
--- a/README.md
+++ b/README.md
@@ -126,7 +126,7 @@ Start with the desktop app, or install the command line on a workstation or serv
- **⌨️ CLI** — a one-line installer (or npm / offline package) puts the `penguin` command on the machine; `penguin web` then serves the full Web experience in your browser at `http://127.0.0.1:7364` (multi-session chat, agent / skill / model management, usage stats, Trace observability, evaluation center). The online installers bundle their own Node runtime — unpack and run; upgrades and reinstalls never touch your data.
> [!NOTE]
-> On a CLI install, the first Web login is `admin`, with the initial password (of the form `penguin-1234`) printed as a framed notice on every server start until it is changed — change it right after. Models are configured on the in-app **Models** page.
+> On a CLI install, the server prints a first-login link as a framed notice on every start until a password is set — open it to claim the built-in `admin` account and choose one. Models are configured on the in-app **Models** page.
### 🖥️ Desktop app
diff --git a/README.zh.md b/README.zh.md
index 3e76c03e..2284770f 100644
--- a/README.zh.md
+++ b/README.zh.md
@@ -126,7 +126,7 @@ https://github.com/user-attachments/assets/aec49ae9-b743-467b-b247-37bedfeaa36e
- **⌨️ 命令行**——一行命令(或 npm / 离线包)装出 `penguin` 命令,`penguin web` 即在浏览器打开完整 Web 体验 `http://127.0.0.1:7364`(多会话对话、Agent / 技能 / 模型管理、用量统计、轨迹观测、评估中心)。在线安装器自带 Node 运行时,解压即用;升级与重装不触碰数据。
> [!NOTE]
-> 命令行安装后,Web 首次登录用户名为 `admin`,初始密码(形如 `penguin-1234`)在改掉之前每次启动服务端都会以边框提示打印,登录后请尽快修改;模型在应用内「模型」页配置。
+> 命令行安装后,服务端会以边框提示打印一条首次登录链接(在密码被设置之前每次启动都会重新打印)——打开即可认领内置管理员 `admin` 并设置密码;模型在应用内「模型」页配置。
### 🖥️ 桌面端应用
diff --git a/changelog/unreleased/2026-08-24-penguin-auth.md b/changelog/unreleased/2026-08-24-penguin-auth.md
new file mode 100644
index 00000000..108febbf
--- /dev/null
+++ b/changelog/unreleased/2026-08-24-penguin-auth.md
@@ -0,0 +1,71 @@
+# `penguin auth` — terminal sign-in, first-login links, offline admin reset
+
+- **Date:** 2026-08-24
+- **Type:** feature
+- **Scope:** `cli`, `server`, `docs`
+- **PR:** [#443](https://github.com/Prism-Shadow/penguin-harness/pull/443)
+- **Breaking:** yes — the fixed seed password retires; claim the account through the printed first-login link
+
+[中文版](2026-08-24-penguin-auth.zh.md)
+
+Signing in to a server from a terminal is now possible, and the account bootstrap around it is
+rebuilt: a fresh server prints a first-login link instead of a fixed password, and a forgotten
+admin password is recovered offline.
+
+```bash
+penguin auth login # password, against the server on this data root
+penguin auth login --server https://penguin.example --user-id alice
+penguin auth status
+penguin auth logout
+penguin auth token # no password: writes a session row on this machine
+```
+
+## Details
+
+- `login` asks a running server for a session, defaulting to the server on this data root, read
+ from a *live* lock (PID + port). Interactively it asks for the account and names it in the
+ password prompt; `PENGUIN_PASSWORD` or `--password` supplies the password and it asks nothing.
+ Prefer the environment variable — a command line is world-readable through `ps`.
+- `token` takes no password: it opens `web.db` and inserts a session row, so it needs no running
+ server and is safe alongside one (WAL + busy timeout). Bare output for
+ `TOKEN=$(penguin auth token)`; `--mark` prefixes a marker line for a caller parsing it out of a
+ shell that may print a banner.
+- The CLI session is stored at `<root>/cli-session.json`, mode 0600 through a symlink-refusing
+ write. `logout` ends it on the server, not only locally.
+
+## First login
+
+A fresh server's seed password is 24 base64url characters (144 bits), generated, hashed and
+discarded unseen. Every start prints a sign-in link until a password is set. The link carries a
+`setup` session — it may set a password without the old one, and opens no desktop-only route —
+redeemed at `GET /api/auth/claim`, which also serves the desktop shell's one-shot token. It is
+reusable until claimed and stops working the moment a password exists; a claimed server mints no
+such session.
+
+`penguin server reset-admin-password` returns the admin to that unclaimed state offline (server
+stopped), deleting its sessions and producing no plaintext; the next start prints a fresh link.
+
+## Sessions
+
+A session is a 32-byte random token in the cookie, stored as its sha256 in `auth_sessions`.
+Logout deletes the row, an admin password reset deletes that user's rows, and a session survives
+a restart. Validity is **30 days** (previously 7) with sliding renewal topped up in place, so the
+cookie value never changes; only a session whose own span reaches the renewal window slides, so
+an hour-long `cli` token expires at its hour.
+
+## Compatibility
+
+The fixed seed password (`PENGUIN_SEED_ADMIN_PASSWORD` unset used to print `penguin-<4 digits>`)
+retires: claim the account through the first-login link the server prints instead. A data root
+carried over from an earlier build has any `initial-admin-password` plaintext deleted at the next
+start.
+
+Sessions in a v0.2.0 `web.db` are kept: `auth_sessions` gains its `via` column at the next start
+and existing rows read as ordinary password sessions, so an upgrade does not sign anyone out.
+
+Session cookies carry `Secure` only where the deployment opts in. An HTTPS deployment behind a
+reverse proxy sets `PENGUIN_TRUST_PROXY=1` and keeps forwarding `x-forwarded-proto`; left unset,
+cookies are issued without the flag.
+
+`penguin server auth-token` is now `penguin auth token`; `GET /api/auth/desktop-login` is now
+`GET /api/auth/claim`.
diff --git a/changelog/unreleased/2026-08-24-penguin-auth.zh.md b/changelog/unreleased/2026-08-24-penguin-auth.zh.md
new file mode 100644
index 00000000..88a52254
--- /dev/null
+++ b/changelog/unreleased/2026-08-24-penguin-auth.zh.md
@@ -0,0 +1,59 @@
+# `penguin auth` —— 终端登录、首次登录链接、离线管理员重置
+
+- **Date:** 2026-08-24
+- **Type:** feature
+- **Scope:** `cli`, `server`, `docs`
+- **PR:** [#443](https://github.com/Prism-Shadow/penguin-harness/pull/443)
+- **Breaking:** yes —— 固定种子密码退役,改为通过打印的首次登录链接认领账号
+
+[English](2026-08-24-penguin-auth.md)
+
+现在可以从终端登录服务器,围绕它的账号引导也重建了:新服务器打印首次登录链接而非固定密码,管理员忘记密码可离线恢复。
+
+```bash
+penguin auth login # 用密码登录本数据根上的服务器
+penguin auth login --server https://penguin.example --user-id alice
+penguin auth status
+penguin auth logout
+penguin auth token # 无需密码:在本机写入一行会话
+```
+
+## 细节
+
+- `login` 向运行中的服务器请求会话,默认指向本数据根上的服务器,目标取自**存活**的 server lock(PID +
+ 端口)。交互式时先问账号并在密码提示里点名;用 `PENGUIN_PASSWORD` 或 `--password` 提供密码则什么都不问,
+ 优先用环境变量——命令行经 `ps` 全局可读。
+- `token` 不需要密码:它打开 `web.db` 插入一行会话,因此不需要服务器在跑,服务器在跑时也安全(WAL +
+ 忙等超时)。默认裸输出以便 `TOKEN=$(penguin auth token)`;`--mark` 在前面加一行标记,供从可能打印横幅的
+ shell 里解析的调用方。
+- CLI 会话记在 `<root>/cli-session.json`,0600、防 symlink 写;`logout` 在服务端结束它,而不仅是本地。
+
+## 首次登录
+
+新服务器的种子密码是 24 位 base64url(144 比特),生成后即哈希、丢弃、无人见过。在密码被设置之前,每次启动
+打印一条登录链接。链接携带一个 `setup` 会话——可免旧密码设置密码,且不开启任何桌面专属路由——在
+`GET /api/auth/claim` 兑换(桌面客户端的一次性令牌也走这条路由)。它在认领前可重复使用,密码存在的那一刻即
+失效;已认领的服务器不再签发这样的会话。
+
+`penguin server reset-admin-password` 在离线(服务停止)时把管理员退回未认领状态,删除其会话、不产生任何
+明文;下次启动打印新链接。
+
+## 会话
+
+会话是 Cookie 里的一个 32 字节随机令牌,以其 sha256 存于 `auth_sessions`。logout 删除该行,管理员重置密码
+删除该用户的行,会话跨重启存活。有效期 **30 天**(此前 7 天),滑动续期在原地续、Cookie 值不变;只有自身
+跨度达到续期窗口的会话才滑动,因此 1 小时的 `cli` 令牌就在 1 小时到期。
+
+## 兼容性
+
+固定种子密码(未设置 `PENGUIN_SEED_ADMIN_PASSWORD` 时旧版打印 `penguin-<四位数字>`)退役:改为通过服务器
+打印的首次登录链接认领账号。从旧版沿用的数据根,其 `initial-admin-password` 明文会在下次启动时删除。
+
+v0.2.0 的 `web.db` 里的会话会保留:`auth_sessions` 表在下次启动时补上 `via` 列,已有行按普通密码会话处理,
+因此升级不会让任何人掉线。
+
+会话 Cookie 只在部署方显式开启时带 `Secure`。经反向代理提供 HTTPS 的部署需设置 `PENGUIN_TRUST_PROXY=1`
+并继续转发 `x-forwarded-proto`;不设置则签发的 Cookie 不带该标记。
+
+`penguin server auth-token` 现为 `penguin auth token`;`GET /api/auth/desktop-login` 现为
+`GET /api/auth/claim`。
diff --git a/install.ps1 b/install.ps1
index 118a7fca..cc92dd2d 100644
--- a/install.ps1
+++ b/install.ps1
@@ -725,5 +725,5 @@ if ($PathUpdateMessage) {
Write-Host ""
Write-Host "Get started:"
Write-Host " penguin --help # all commands"
-Write-Host " penguin web # start the Web UI at http://127.0.0.1:7364 (login: admin, initial password printed on first start)"
+Write-Host " penguin web # start the Web UI at http://127.0.0.1:7364 (a first-login link is printed on first start)"
Write-Host " penguin server # headless server (PORT / HOST to override)"
diff --git a/install.sh b/install.sh
index 0d6bc2b5..7c374321 100644
--- a/install.sh
+++ b/install.sh
@@ -781,5 +781,5 @@ fi
echo ""
echo "Get started:"
echo " penguin --help # all commands"
-echo " penguin web # start the Web UI at http://127.0.0.1:7364 (login: admin, initial password printed on first start)"
+echo " penguin web # start the Web UI at http://127.0.0.1:7364 (a first-login link is printed on first start)"
echo " penguin server # headless server (PORT / HOST to override)"
diff --git a/packages/cli/src/auth-session.ts b/packages/cli/src/auth-session.ts
new file mode 100644
index 00000000..cde8d4f4
--- /dev/null
+++ b/packages/cli/src/auth-session.ts
@@ -0,0 +1,214 @@
+/**
+ * Signing in to a PenguinHarness server from a terminal, and remembering it.
+ *
+ * Everything else this CLI does works on the data root directly — `config`, `run`, `chat` all
+ * open files, never a socket. This is the one place that talks to a running server as a
+ * client, so the two things that make that awkward live here rather than in the command.
+ *
+ * THE HOST HEADER. The API answers only under its canonical app host; a request as
+ * `Host: 127.0.0.1:<port>` is refused as the preview surface. So `call()` connects to the
+ * address while the header says the canonical name — which fetch cannot express, node:http can.
+ *
+ * THE SESSION FILE. `<root>/cli-session.json`, mode 0600, holding the token a login issued.
+ * It is a credential with an expiry, so it is written like one: 0600 on create AND on
+ * overwrite (the mode option only applies when the file is new), and never printed unless
+ * asked for.
+ */
+import fs from "node:fs";
+import http from "node:http";
+import https from "node:https";
+import path from "node:path";
+import { writeSecretFile } from "@prismshadow/penguin-server/secret-file";
+
+/** Where a login is remembered, beside the data root it belongs to. */
+export function sessionFile(root: string): string {
+ return path.join(root, "cli-session.json");
+}
+
+/** A remembered login. `expiresAt` is the server's, so `status` can say it has run out. */
+export interface StoredSession {
+ server: string;
+ userId: string;
+ token: string;
+ expiresAt?: string;
+}
+
+export function readSession(root: string): StoredSession | null {
+ try {
+ const parsed: unknown = JSON.parse(fs.readFileSync(sessionFile(root), "utf8"));
+ if (parsed === null || typeof parsed !== "object") return null;
+ const row = parsed as Record<string, unknown>;
+ if (typeof row.server !== "string" || typeof row.token !== "string") return null;
+ return {
+ server: row.server,
+ userId: typeof row.userId === "string" ? row.userId : "admin",
+ token: row.token,
+ ...(typeof row.expiresAt === "string" ? { expiresAt: row.expiresAt } : {}),
+ };
+ } catch {
+ return null;
+ }
+}
+
+export function writeSession(root: string, session: StoredSession): void {
+ const file = sessionFile(root);
+ fs.mkdirSync(path.dirname(file), { recursive: true });
+ // Holds a bearer token; writeSecretFile makes the write refuse a symlink parked at the path.
+ writeSecretFile(file, JSON.stringify(session, null, 2) + "\n");
+}
+
+export function clearSession(root: string): boolean {
+ try {
+ fs.unlinkSync(sessionFile(root));
+ return true;
+ } catch {
+ return false;
+ }
+}
+
+export interface HttpAnswer {
+ status: number;
+ headers: Record<string, string | string[] | undefined>;
+ text: string;
+}
+
+/**
+ * One request with the Host header set to the target's canonical app host (see module doc).
+ * Both schemes: a login target may be a TLS deployment as easily as a loopback port. Loopback
+ * connects by address (`localhost` may resolve to ::1 where the server bound 127.0.0.1 only)
+ * while the header keeps the name — the spelling the API accepts.
+ */
+export function call(
+ url: string,
+ options: { method: string; path: string; cookie?: string },
+ body?: unknown,
+): Promise<HttpAnswer> {
+ return new Promise((resolve, reject) => {
+ let target: URL;
+ try {
+ target = new URL(url);
+ } catch {
+ reject(new Error(`not a URL: ${url}`));
+ return;
+ }
+ const secure = target.protocol === "https:";
+ const payload = body === undefined ? null : Buffer.from(JSON.stringify(body));
+ const port = target.port !== "" ? Number(target.port) : secure ? 443 : 80;
+ const host = target.hostname === "localhost" ? "127.0.0.1" : target.hostname;
+ const req = (secure ? https : http).request(
+ {
+ host,
+ port,
+ path: options.path,
+ method: options.method,
+ headers: {
+ host: target.host,
+ ...(options.cookie !== undefined ? { cookie: options.cookie } : {}),
+ ...(payload === null
+ ? {}
+ : { "content-type": "application/json", "content-length": String(payload.length) }),
+ },
+ timeout: 30_000,
+ },
+ (res) => {
+ const chunks: Buffer[] = [];
+ res.on("data", (chunk: Buffer) => chunks.push(chunk));
+ res.on("end", () =>
+ resolve({
+ status: res.statusCode ?? 0,
+ headers: res.headers,
+ text: Buffer.concat(chunks).toString("utf8"),
+ }),
+ );
+ },
+ );
+ req.on("timeout", () => {
+ req.destroy();
+ reject(new Error("the server did not answer in time"));
+ });
+ req.on("error", reject);
+ if (payload === null) req.end();
+ else req.end(payload);
+ });
+}
+
+/** The session token out of a login's Set-Cookie lines. */
+export function tokenFromSetCookie(lines: string[] | undefined, name: string): string | null {
+ for (const line of lines ?? []) {
+ const pair = String(line).split(";")[0]?.trim() ?? "";
+ const at = pair.indexOf("=");
+ if (at > 0 && pair.slice(0, at) === name) return pair.slice(at + 1);
+ }
+ return null;
+}
+
+/**
+ * Reads one echoed line from the terminal, for answers that are not secret.
+ *
+ * `fallback` is what an empty answer means, so the common case is a bare Enter rather than
+ * retyping what the prompt already suggested.
+ */
+export function promptLine(prompt: string, fallback: string): Promise<string> {
+ return new Promise((resolve) => {
+ process.stderr.write(prompt);
+ const stdin = process.stdin;
+ const onData = (chunk: Buffer) => {
+ stdin.pause();
+ stdin.removeListener("data", onData);
+ const value = chunk
+ .toString("utf8")
+ .replace(/\r?\n$/, "")
+ .trim();
+ resolve(value === "" ? fallback : value);
+ };
+ stdin.resume();
+ stdin.on("data", onData);
+ });
+}
+
+/**
+ * Reads a password from the terminal without echoing it.
+ *
+ * Falls back to a plain read when stdin is not a TTY, so a password can be piped in — the
+ * echo is the only thing being suppressed, not the ability to script.
+ */
+export function promptPassword(prompt: string): Promise<string> {
+ return new Promise((resolve, reject) => {
+ process.stderr.write(prompt);
+ const stdin = process.stdin;
+ const raw = stdin.isTTY === true;
+ let value = "";
+ const done = (out: string) => {
+ if (raw) {
+ stdin.setRawMode(false);
+ process.stderr.write("\n");
+ }
+ stdin.pause();
+ stdin.removeListener("data", onData);
+ resolve(out);
+ };
+ const onData = (chunk: Buffer) => {
+ const text = chunk.toString("utf8");
+ if (!raw) {
+ done(text.replace(/\r?\n$/, ""));
+ return;
+ }
+ for (const ch of text) {
+ // Enter ends it; Ctrl-C is an abort, not an empty password.
+ if (ch === "\r" || ch === "\n") return done(value);
+ if (ch === "\u0003") {
+ stdin.setRawMode(false);
+ stdin.pause();
+ stdin.removeListener("data", onData);
+ reject(new Error("cancelled"));
+ return;
+ }
+ if (ch === "\u007f" || ch === "\b") value = value.slice(0, -1);
+ else value += ch;
+ }
+ };
+ if (raw) stdin.setRawMode(true);
+ stdin.resume();
+ stdin.on("data", onData);
+ });
+}
diff --git a/packages/cli/src/commands/auth.ts b/packages/cli/src/commands/auth.ts
new file mode 100644
index 00000000..47b33dec
--- /dev/null
+++ b/packages/cli/src/commands/auth.ts
@@ -0,0 +1,254 @@
+/**
+ * `penguin auth` — signing in to a PenguinHarness server from a terminal.
+ *
+ * penguin auth login [--server <url>] [--user-id <id>] [--password <pw>] [--print] [--root <dir>]
+ * penguin auth status [--root <dir>]
+ * penguin auth logout [--root <dir>]
+ * penguin auth token [--user-id <id>] [--ttl-seconds <n>] [--root <dir>]
+ *
+ * `login` takes a password and asks a RUNNING server, so it works against a remote URL too.
+ * `token` takes none: it mints from the data root on THIS machine, authorized by being able
+ * to read it — for a hand-set admin password, a script that must not carry one, or a
+ * controller reaching a managed machine over ssh (`--mark`).
+ *
+ * The session lands in `<root>/cli-session.json` (0600) rather than a shell's history.
+ * Docs: /docs/cli § "penguin auth".
+ */
+import { mintApiToken } from "@prismshadow/penguin-server/auth-token";
+import { liveServerLock } from "@prismshadow/penguin-server/lock";
+import type { Command } from "commander";
+import {
+ call,
+ clearSession,
+ promptLine,
+ promptPassword,
+ readSession,
+ sessionFile,
+ tokenFromSetCookie,
+ writeSession,
+} from "../auth-session.js";
+import { resolveRootOption } from "../root-option.js";
+import type { Messages } from "../i18n.js";
+
+/** Must match the server's SESSION_COOKIE — it is the name a login's Set-Cookie carries. */
+const SESSION_COOKIE = "penguin_session";
+
+/** The built-in account every server has; on a personal or desktop server it is the only one. */
+const DEFAULT_USER = "admin";
+
+/**
+ * The line `--mark` prints before the token. A caller reading the token out of a remote shell
+ * anchors on this rather than on position, so nothing the shell prints on its own can be
+ * mistaken for a credential.
+ */
+export const TOKEN_MARK = "---penguin-auth-token---";
+
+/**
+ * One line for the terminal out of text the TARGET SERVER chose: whitespace collapsed, C0
+ * controls and DEL made visible in caret form, C1 controls dropped. `--server` takes any URL,
+ * so this text is as untrusted as a web page — printed raw, an ESC would let that server run
+ * terminal escape sequences (retitle the window, write the clipboard via OSC 52) on the
+ * machine signing in.
+ */
+function neutralLine(raw: string): string {
+ return raw
+ .replace(/\s+/g, " ")
+ .trim()
+ .replace(/[\u0000-\u001f\u007f-\u009f]/g, (ch) => {
+ const code = ch.charCodeAt(0);
+ if (code <= 0x1f) return `^${String.fromCharCode(code + 64)}`;
+ return code === 0x7f ? "^?" : "";
+ });
+}
+
+/**
+ * What the server said about a refusal, as one line (neutralized — see {@link neutralLine}).
+ * The API's own error body is quoted in full; anything else (a proxy's HTML page) is bounded
+ * with the cut MARKED, so a fragment is never presented as the whole message.
+ */
+export function serverSaid(text: string): string {
+ try {
+ const body: unknown = JSON.parse(text);
+ const message = (body as { error?: { message?: unknown } })?.error?.message;
+ if (typeof message === "string") return neutralLine(message);
+ } catch {
+ // Not the API's shape; fall through to the bounded raw form.
+ }
+ const line = neutralLine(text);
+ if (line === "") return "(no message)";
+ return line.length <= 500 ? line : `${line.slice(0, 500)}… (truncated)`;
+}
+
+/** Writes an error line and marks the run failed; `return fail(msg)` ends the action. */
+function fail(message: string): void {
+ process.stderr.write(message + "\n");
+ process.exitCode = 1;
+}
+
+export function registerAuthCommand(program: Command, t: Messages): void {
+ const auth = program.command("auth").description(t.auth.desc);
+
+ auth
+ .command("login")
+ .description(t.auth.loginDesc)
+ .option("--server <url>", t.auth.server)
+ .option("--user-id <id>", t.auth.userId)
+ .option("--password <pw>", t.auth.password)
+ .option("--print", t.auth.print, false)
+ .option("--root <dir>", t.common.root)
+ .action(
+ async (opts: {
+ server?: string;
+ userId?: string;
+ password?: string;
+ print: boolean;
+ root?: string;
+ }) => {
+ const root = resolveRootOption(opts.root);
+ // A password is about to be sent here, so the default target comes from a VERIFIED
+ // live lock (PID + port): a stale one from a crashed server may name a port another
+ // process now holds. An explicit --server is the caller's own responsibility.
+ let server: string | null = opts.server ?? null;
+ if (server === null) {
+ const lock = await liveServerLock(root);
+ server = lock === null ? null : `http://localhost:${lock.port}`;
+ }
+ if (server === null) return fail(t.auth.noServer(root));
+ // A script cannot answer a prompt, so a non-interactive password suppresses both
+ // questions; the account is only asked for when the password will be too.
+ const given = opts.password ?? process.env.PENGUIN_PASSWORD;
+ const userId =
+ opts.userId ??
+ (given === undefined && process.stdin.isTTY === true
+ ? await promptLine(t.auth.accountPrompt(DEFAULT_USER), DEFAULT_USER)
+ : DEFAULT_USER);
+ // Env before prompt, but never argv by default: a command line is world-readable
+ // through ps. The prompt names the account, so one account's password is not typed
+ // at another's.
+ const password = given ?? (await promptPassword(t.auth.prompt(userId)));
+ if (password === "") return fail(t.auth.emptyPassword);
+
+ let answer;
+ try {
+ answer = await call(
+ server,
+ { method: "POST", path: "/api/auth/login" },
+ { userId, password },
+ );
+ } catch (err) {
+ return fail(t.auth.unreachable(server, err instanceof Error ? err.message : String(err)));
+ }
+ if (answer.status !== 200) {
+ return fail(t.auth.refused(answer.status, serverSaid(answer.text)));
+ }
+ const setCookie = answer.headers["set-cookie"];
+ const token = tokenFromSetCookie(
+ Array.isArray(setCookie) ? setCookie : setCookie === undefined ? [] : [setCookie],
+ SESSION_COOKIE,
+ );
+ if (token === null) return fail(t.auth.noCookie);
+ writeSession(root, { server, userId, token });
+ process.stderr.write(t.auth.loggedIn(userId, server, sessionFile(root)) + "\n");
+ // STDOUT and only on request, so it pipes cleanly and never lands in a log by accident.
+ if (opts.print) process.stdout.write(token + "\n");
+ },
+ );
+
+ auth
+ .command("status")
+ .description(t.auth.statusDesc)
+ .option("--root <dir>", t.common.root)
+ .action((opts: { root?: string }) => {
+ const root = resolveRootOption(opts.root);
+ const session = readSession(root);
+ if (session === null) {
+ process.stdout.write(t.auth.notLoggedIn(sessionFile(root)) + "\n");
+ return;
+ }
+ process.stdout.write(t.auth.statusLine(session.userId, session.server) + "\n");
+ if (session.expiresAt !== undefined) {
+ const over = Date.parse(session.expiresAt) <= Date.now();
+ process.stdout.write(
+ (over ? t.auth.expired(session.expiresAt) : t.auth.expires(session.expiresAt)) + "\n",
+ );
+ }
+ });
+
+ auth
+ .command("logout")
+ .description(t.auth.logoutDesc)
+ .option("--root <dir>", t.common.root)
+ .action(async (opts: { root?: string }) => {
+ const root = resolveRootOption(opts.root);
+ const session = readSession(root);
+ if (session === null) {
+ process.stdout.write(t.auth.notLoggedIn(sessionFile(root)) + "\n");
+ return;
+ }
+ // Server first: a token deleted only locally stays valid for whoever else holds a copy.
+ // An unreachable server does not block the local clear.
+ let revoked = false;
+ try {
+ const answer = await call(session.server, {
+ method: "POST",
+ path: "/api/auth/logout",
+ cookie: `${SESSION_COOKIE}=${session.token}`,
+ });
+ revoked = answer.status >= 200 && answer.status < 300;
+ } catch {
+ revoked = false;
+ }
+ clearSession(root);
+ process.stdout.write(
+ (revoked ? t.auth.loggedOut(session.server) : t.auth.loggedOutLocally(session.server)) +
+ "\n",
+ );
+ });
+
+ auth
+ .command("token")
+ .description(t.authToken.desc)
+ .option("--user-id <id>", t.authToken.userId, DEFAULT_USER)
+ // Number, not parseInt: parseInt("3600abc") is 3600, and a lifetime silently taken from
+ // a typo is worse than a rejected flag.
+ .option("--ttl-seconds <n>", t.authToken.ttlSeconds, (raw: string) => Number(raw))
+ .option("--mark", t.authToken.mark, false)
+ .option("--root <dir>", t.common.root)
+ .action(async (opts: { userId: string; ttlSeconds?: number; mark: boolean; root?: string }) => {
+ const ttl = opts.ttlSeconds;
+ if (ttl !== undefined && (!Number.isSafeInteger(ttl) || ttl <= 0)) {
+ return fail(t.authToken.badTtl);
+ }
+ const root = resolveRootOption(opts.root);
+ // A session row written straight into web.db (auth-token.ts); no server needed, and safe
+ // while one runs. PENGUIN_WEB_DB honored as everywhere else, or the token would be
+ // minted into a file the live server never reads.
+ const result = mintApiToken(root, {
+ userId: opts.userId,
+ ...(process.env.PENGUIN_WEB_DB ? { dbPath: process.env.PENGUIN_WEB_DB } : {}),
+ ...(ttl === undefined ? {} : { ttlMs: ttl * 1000 }),
+ });
+ if (result.outcome === "no_server") {
+ return fail(t.authToken.noServer(root));
+ }
+ if (result.outcome === "failed") {
+ return fail(t.authToken.failed(result.detail));
+ }
+ // The session file says where a later `logout` goes, so the URL comes from a live lock
+ // — a stale one would hand the token to whatever now holds that port.
+ const lock = await liveServerLock(root);
+ const server = lock === null ? null : `http://localhost:${lock.port}`;
+ if (server !== null) {
+ writeSession(root, {
+ server,
+ userId: result.userId,
+ token: result.token,
+ expiresAt: result.expiresAt,
+ });
+ }
+ // Bare so `TOKEN=$(penguin auth token)` works. `--mark` prefixes a fixed line for a
+ // caller parsing this out of a shell whose banner would otherwise be the last line.
+ if (opts.mark) process.stdout.write(TOKEN_MARK + "\n");
+ process.stdout.write(result.token + "\n");
+ });
+}
diff --git a/packages/cli/src/commands/config.ts b/packages/cli/src/commands/config.ts
index 4942651c..02618ae1 100644
--- a/packages/cli/src/commands/config.ts
+++ b/packages/cli/src/commands/config.ts
@@ -54,14 +54,10 @@ import {
setVisionModel,
} from "@prismshadow/penguin-core";
import { parseApprovalAnswer } from "../approval.js";
+import { resolveRootOption } from "../root-option.js";
import { getMessages, maskApiKey, type Messages } from "../i18n.js";
import { applyLanguageToRc, restartShell } from "../lang-config.js";
-/** Data root directory: the `--root` option takes priority (relative paths resolved against cwd), then PENGUIN_HOME / ~/.penguin/data. */
-function resolveRootOption(root: string | undefined): string {
- return root !== undefined ? path.resolve(root) : resolveRoot();
-}
-
/**
* Renders the model list as column-aligned lines (the default model is marked with `*`;
* fully empty columns are omitted automatically). `provider` and `model_id` each occupy
diff --git a/packages/cli/src/commands/reset-password.ts b/packages/cli/src/commands/reset-password.ts
index 31012feb..ae4737e0 100644
--- a/packages/cli/src/commands/reset-password.ts
+++ b/packages/cli/src/commands/reset-password.ts
@@ -13,7 +13,6 @@
*/
import path from "node:path";
import { resolveRoot } from "@prismshadow/penguin-core";
-import { renderInitialPasswordNotice } from "@prismshadow/penguin-server/initial-password";
import { resetAdminPassword } from "@prismshadow/penguin-server/reset-admin-password";
import type { Command } from "commander";
import type { Messages } from "../i18n.js";
@@ -44,7 +43,6 @@ export function registerResetPasswordCommand(server: Command, t: Messages): void
return;
case "reset":
process.stdout.write(t.resetPassword.done(root) + "\n");
- process.stdout.write(renderInitialPasswordNotice("admin", result.password) + "\n");
process.stdout.write(t.resetPassword.next() + "\n");
}
});
diff --git a/packages/cli/src/commands/serve.ts b/packages/cli/src/commands/serve.ts
index 371b5bb3..79830769 100644
--- a/packages/cli/src/commands/serve.ts
+++ b/packages/cli/src/commands/serve.ts
@@ -18,10 +18,6 @@
import { spawn } from "node:child_process";
import path from "node:path";
import { DEFAULT_SERVER_PORT, resolveRoot } from "@prismshadow/penguin-core";
-import {
- readInitialAdminPassword,
- renderInitialPasswordNotice,
-} from "@prismshadow/penguin-server/initial-password";
import { liveServerLock } from "@prismshadow/penguin-server/lock";
import type { Command } from "commander";
import type { Messages, WebProbeFailureKind } from "../i18n.js";
@@ -285,16 +281,10 @@ export function registerServeCommands(program: Command, t: Messages): void {
const existing = await existingInstanceUrl();
if (existing !== null) {
process.stdout.write(t.webAlreadyRunning(existing) + "\n");
- // The running server prints the initial-password reminder only into ITS OWN
- // console; someone attaching from a fresh terminal would never see it. The data
- // root's stored plaintext exists exactly while the admin password is still the
- // initial one (the server removes it on change), so its presence alone gates the
- // reminder here. The fresh-start path below needs nothing: the server module
- // runs in this same process and prints the notice itself.
- const initialPassword = readInitialAdminPassword(resolveRoot());
- if (initialPassword !== null) {
- process.stdout.write(renderInitialPasswordNotice("admin", initialPassword) + "\n");
- }
+ // Nothing is printed when attaching to a server that is already up: a server with
+ // no admin password yet prints a first-login LINK, and that link's token lives only
+ // in the running server's memory — this terminal cannot reproduce it, and should
+ // not. Its own console has it; restarting reissues it.
if (opts.open) openBrowser(existing);
return;
}
diff --git a/packages/cli/src/i18n.ts b/packages/cli/src/i18n.ts
index 2caaa650..b0da734d 100644
--- a/packages/cli/src/i18n.ts
+++ b/packages/cli/src/i18n.ts
@@ -287,6 +287,39 @@ export interface Messages {
noOpen: string;
};
/** `penguin server reset-admin-password`: help text and every line the command can print. */
+ auth: {
+ desc: string;
+ loginDesc: string;
+ statusDesc: string;
+ logoutDesc: string;
+ server: string;
+ userId: string;
+ password: string;
+ print: string;
+ accountPrompt(fallback: string): string;
+ prompt(userId: string): string;
+ emptyPassword: string;
+ noServer(root: string): string;
+ unreachable(server: string, detail: string): string;
+ refused(status: number, detail: string): string;
+ noCookie: string;
+ loggedIn(userId: string, server: string, file: string): string;
+ notLoggedIn(file: string): string;
+ statusLine(userId: string, server: string): string;
+ expires(when: string): string;
+ expired(when: string): string;
+ loggedOut(server: string): string;
+ loggedOutLocally(server: string): string;
+ };
+ authToken: {
+ desc: string;
+ userId: string;
+ ttlSeconds: string;
+ mark: string;
+ badTtl: string;
+ noServer(root: string): string;
+ failed(detail: string): string;
+ };
resetPassword: {
desc: string;
/** Refusal while a live server owns the data root (stop it first, then retry). */
@@ -776,6 +809,42 @@ const en: Messages = {
host: "Listen address (falls back to the HOST env var, default 127.0.0.1)",
noOpen: "Do not open a browser automatically",
},
+ auth: {
+ desc: "Sign in to a PenguinHarness server from the terminal",
+ loginDesc: "Sign in with a password and remember the session",
+ statusDesc: "Show the remembered session, if there is one",
+ logoutDesc: "Revoke the remembered session and forget it",
+ server: "Server URL (default: the server running on this data root)",
+ userId: "Account to sign in as (asked for when omitted; default admin)",
+ password: "Password (also read from PENGUIN_PASSWORD; prompted when neither is given)",
+ print: "Also print the session token to stdout",
+ accountPrompt: (fallback) => `Account [${fallback}]: `,
+ prompt: (userId) => `Password for ${userId}: `,
+ emptyPassword: "No password given.",
+ noServer: (root) =>
+ `No server is running on ${root}, so there is nothing to sign in to \u2014 pass --server <url>.`,
+ unreachable: (server, detail) => `Could not reach ${server}: ${detail}`,
+ refused: (status, detail) => `The server refused the sign-in (${status}): ${detail}`,
+ noCookie: "The server accepted the sign-in but issued no session cookie.",
+ loggedIn: (userId, server, file) => `Signed in as ${userId} on ${server}. Saved to ${file}.`,
+ notLoggedIn: (file) => `Not signed in (no ${file}).`,
+ statusLine: (userId, server) => `Signed in as ${userId} on ${server}.`,
+ expires: (when) => `Expires ${when}.`,
+ expired: (when) => `Expired ${when} \u2014 sign in again.`,
+ loggedOut: (server) => `Signed out of ${server}; the session was revoked there.`,
+ loggedOutLocally: (server) =>
+ `Forgotten locally, but ${server} could not be reached \u2014 the session may still be valid there until it expires.`,
+ },
+ authToken: {
+ desc: "Mint a short-lived API session token for this data root (for a controller reaching this machine over ssh)",
+ userId: "Account to mint for (default: admin)",
+ ttlSeconds: "Lifetime in seconds (default: 3600)",
+ mark: "Print a fixed marker line before the token, for callers parsing it out of a shell",
+ badTtl: "--ttl-seconds must be a positive integer.",
+ noServer: (root) =>
+ `${root} has no web.db — no server has ever run on this data root, so there is no account to mint for.`,
+ failed: (detail) => `Could not mint a token: ${detail}`,
+ },
resetPassword: {
desc: "Reset the Web admin password to a fresh initial password (the server must be stopped)",
serverRunning: (url) =>
@@ -788,8 +857,9 @@ const en: Messages = {
"The Web database has no admin account yet — nothing to reset. " +
"Start the service once (`penguin web`) to seed it.",
done: (root) =>
- `Admin password reset for data root ${root}. All admin sign-in sessions were cleared.`,
- next: () => "Start the service (`penguin web`) and sign in with the password above.",
+ `The admin account on data root ${root} was returned to its unclaimed state, and all of its sign-in sessions were revoked.`,
+ next: () =>
+ "Start the service (`penguin web`): it will print a sign-in link that claims the account — usable until a password is set.",
},
version: {
description: "Show which build is running",
@@ -1245,6 +1315,40 @@ const zh: Messages = {
host: "监听地址(其次取环境变量 HOST,缺省 127.0.0.1)",
noOpen: "不自动打开浏览器",
},
+ auth: {
+ desc: "在终端里登录 PenguinHarness 服务",
+ loginDesc: "用密码登录并记住会话",
+ statusDesc: "显示已记住的会话",
+ logoutDesc: "吊销并忘记已记住的会话",
+ server: "服务地址(默认:该数据根上正在运行的服务)",
+ userId: "登录的账号(不给时会询问;默认 admin)",
+ password: "密码(也可用 PENGUIN_PASSWORD;都没给时会提示输入)",
+ print: "同时把会话令牌打印到 stdout",
+ accountPrompt: (fallback) => `账号 [${fallback}]:`,
+ prompt: (userId) => `${userId} 的密码:`,
+ emptyPassword: "没有输入密码。",
+ noServer: (root) => `${root} 上没有正在运行的服务,无处登录——请用 --server <url> 指定。`,
+ unreachable: (server, detail) => `连接不上 ${server}:${detail}`,
+ refused: (status, detail) => `服务拒绝了登录(${status}):${detail}`,
+ noCookie: "服务接受了登录,但没有下发会话 Cookie。",
+ loggedIn: (userId, server, file) => `已以 ${userId} 登录 ${server},会话保存在 ${file}。`,
+ notLoggedIn: (file) => `尚未登录(没有 ${file})。`,
+ statusLine: (userId, server) => `已以 ${userId} 登录 ${server}。`,
+ expires: (when) => `有效期至 ${when}。`,
+ expired: (when) => `已于 ${when} 过期——请重新登录。`,
+ loggedOut: (server) => `已登出 ${server},该会话已在服务端吊销。`,
+ loggedOutLocally: (server) =>
+ `已在本地忘记,但连接不上 ${server}——该会话可能在过期前仍然有效。`,
+ },
+ authToken: {
+ desc: "为该数据根签发短期 API 会话令牌(供通过 ssh 连接本机的控制端使用)",
+ userId: "签发给哪个账号(默认 admin)",
+ ttlSeconds: "有效期秒数(默认 3600)",
+ mark: "在令牌前打印固定标记行,供需要从 shell 输出里解析它的调用方使用",
+ badTtl: "--ttl-seconds 必须是正整数。",
+ noServer: (root) => `${root} 上没有 web.db——该数据根上从未运行过服务,因此没有可签发的账号。`,
+ failed: (detail) => `签发失败:${detail}`,
+ },
resetPassword: {
desc: "把 Web 管理员密码重置为新的初始密码(须先停止服务)",
serverRunning: (url) =>
@@ -1254,8 +1358,9 @@ const zh: Messages = {
`${dbPath} 处没有 Web 数据库,无可重置。请先执行 \`penguin web\` 启动一次服务以创建管理员账号。`,
noAdmin: () =>
"Web 数据库中尚无管理员账号,无可重置。请先执行 `penguin web` 启动一次服务完成种子创建。",
- done: (root) => `已重置数据根目录 ${root} 的管理员密码,并清空其全部登录会话。`,
- next: () => "启动服务(`penguin web`)后用上方密码登录。",
+ done: (root) => `数据根目录 ${root} 的管理员账号已退回未认领状态,其全部登录会话已吊销。`,
+ next: () =>
+ "启动服务(`penguin web`),它会打印一条登录链接用于认领该账号——在密码被设置之前一直有效。",
},
version: {
description: "显示当前运行的是哪个构建",
diff --git a/packages/cli/src/index.ts b/packages/cli/src/index.ts
index f5749754..38b19672 100644
--- a/packages/cli/src/index.ts
+++ b/packages/cli/src/index.ts
@@ -8,6 +8,7 @@
*/
import { Command, CommanderError } from "commander";
import { buildInfo } from "@prismshadow/penguin-core";
+import { registerAuthCommand } from "./commands/auth.js";
import { registerConfigCommand } from "./commands/config.js";
import { registerRunCommand } from "./commands/run.js";
import { registerChatCommand } from "./commands/chat.js";
@@ -46,6 +47,7 @@ export async function cli(argv: string[]): Promise<number> {
// are copied down (commander's copyInheritedSettings).
.configureOutput({ outputError: () => {} });
+ registerAuthCommand(program, t);
registerConfigCommand(program, t);
registerRunCommand(program, t);
registerChatCommand(program, t);
diff --git a/packages/cli/src/root-option.ts b/packages/cli/src/root-option.ts
new file mode 100644
index 00000000..5cc515e0
--- /dev/null
+++ b/packages/cli/src/root-option.ts
@@ -0,0 +1,14 @@
+/**
+ * The `--root` option's meaning, in one place.
+ *
+ * Every command that touches the data root offers it, and the priority is a documented part
+ * of the CLI's contract (/docs/cli): the option wins, then PENGUIN_HOME, then the default
+ * root. Two copies of that rule is two chances for one of them to drift.
+ */
+import path from "node:path";
+import { resolveRoot } from "@prismshadow/penguin-core";
+
+/** Data root: `--root` first (relative paths against cwd), else PENGUIN_HOME / ~/.penguin/data. */
+export function resolveRootOption(root: string | undefined): string {
+ return root !== undefined ? path.resolve(root) : resolveRoot();
+}
diff --git a/packages/cli/test/auth-session.test.ts b/packages/cli/test/auth-session.test.ts
new file mode 100644
index 00000000..fb56e083
--- /dev/null
+++ b/packages/cli/test/auth-session.test.ts
@@ -0,0 +1,156 @@
+/**
+ * `penguin auth login`'s moving parts (src/auth-session.ts).
+ *
+ * The command itself is thin; what is easy to get wrong lives here, and each of these has a
+ * failure that only shows up on somebody's machine:
+ *
+ * - The Host header. The API refuses a request arriving as the preview host, so a login that
+ * connects to 127.0.0.1 must still SAY `localhost:<port>` — and `fetch` cannot, which is
+ * why this is hand-rolled at all.
+ * - The stored token's file mode. It is a credential; 0600 has to survive an overwrite, where
+ * the `mode` write option silently does not apply.
+ * - Picking the session cookie out of Set-Cookie, which arrives beside others.
+ * - What a refusal prints (commands/auth.ts serverSaid): the text is the target server's, so
+ * it is neutralized before it reaches this terminal.
+ */
+import fs from "node:fs";
+import http from "node:http";
+import os from "node:os";
+import path from "node:path";
+import type { AddressInfo } from "node:net";
+import { afterEach, beforeEach, describe, expect, it } from "vitest";
+import {
+ call,
+ clearSession,
+ readSession,
+ tokenFromSetCookie,
+ writeSession,
+} from "../src/auth-session.js";
+import { serverSaid } from "../src/commands/auth.js";
+
+describe("serverSaid", () => {
+ it("quotes the API's own error message", () => {
+ expect(
+ serverSaid(JSON.stringify({ error: { message: "Incorrect username or password." } })),
+ ).toBe("Incorrect username or password.");
+ });
+
+ it("neutralizes terminal control sequences a hostile server embeds", () => {
+ // ESC ] 0 ; … BEL — an OSC window-title write. `--server` accepts any URL, so this text
+ // is attacker-chosen; the ESC must not reach the terminal from either the JSON path or
+ // the raw one.
+ const osc = "\u001b]0;owned\u0007done";
+ expect(serverSaid(JSON.stringify({ error: { message: osc } }))).toBe("^[]0;owned^Gdone");
+ expect(serverSaid(`<html>${osc}</html>`)).toBe("<html>^[]0;owned^Gdone</html>");
+ // A C1 control (0x9b is a one-byte CSI) is dropped outright.
+ expect(serverSaid(JSON.stringify({ error: { message: "a\u009b31mb" } }))).toBe("a31mb");
+ });
+
+ it("collapses and bounds a non-API body, marking the cut", () => {
+ expect(serverSaid(" a \n\n b ")).toBe("a b");
+ expect(serverSaid("")).toBe("(no message)");
+ const out = serverSaid("x".repeat(600));
+ expect(out.endsWith("… (truncated)")).toBe(true);
+ expect(out.length).toBeLessThan(600);
+ });
+});
+
+describe("tokenFromSetCookie", () => {
+ it("takes the session cookie and not its neighbours", () => {
+ expect(
+ tokenFromSetCookie(
+ ["other=1; Path=/", "penguin_session=abc.def; Path=/; HttpOnly", "last=2"],
+ "penguin_session",
+ ),
+ ).toBe("abc.def");
+ expect(tokenFromSetCookie(["other=1"], "penguin_session")).toBeNull();
+ expect(tokenFromSetCookie(undefined, "penguin_session")).toBeNull();
+ });
+});
+
+describe("the session file", () => {
+ let root: string;
+ beforeEach(() => {
+ root = fs.mkdtempSync(path.join(os.tmpdir(), "penguin-cli-auth-"));
+ });
+ afterEach(() => {
+ fs.rmSync(root, { recursive: true, force: true });
+ });
+
+ it("replaces the previous session when it is written again", () => {
+ writeSession(root, { server: "http://localhost:1", userId: "admin", token: "t1" });
+ writeSession(root, { server: "http://localhost:1", userId: "admin", token: "t2" });
+ expect(readSession(root)?.token).toBe("t2");
+ });
+
+ /**
+ * Windows has no POSIX mode bits — chmod there only toggles the read-only attribute and
+ * stat reports 0o666 whatever was asked for — so the permission this guards can only be
+ * checked where it exists. The write itself is platform-neutral (the case above).
+ */
+ it.skipIf(process.platform === "win32")("stays 0600 even when it is overwritten", () => {
+ writeSession(root, { server: "http://localhost:1", userId: "admin", token: "t1" });
+ fs.chmodSync(path.join(root, "cli-session.json"), 0o644); // As a careless editor might.
+ writeSession(root, { server: "http://localhost:1", userId: "admin", token: "t2" });
+ // A create-time mode does not apply to an existing file, so without the write's own
+ // unlink-and-recreate this stays 644 — a token readable by everyone on the machine.
+ expect(fs.statSync(path.join(root, "cli-session.json")).mode & 0o777).toBe(0o600);
+ });
+
+ it("refuses to write the token through a symlink parked at its path", () => {
+ const outside = path.join(root, "attacker-readable");
+ fs.writeFileSync(outside, "");
+ fs.symlinkSync(outside, path.join(root, "cli-session.json"));
+ // A local attacker who can write the root but not read the session file could otherwise
+ // redirect the token into a file they can read. The write unlinks and creates exclusively,
+ // so the parked link is gone and the outside file never receives the token.
+ writeSession(root, { server: "http://localhost:1", userId: "admin", token: "secret-token" });
+ expect(fs.readFileSync(outside, "utf8")).toBe("");
+ expect(fs.lstatSync(path.join(root, "cli-session.json")).isSymbolicLink()).toBe(false);
+ expect(readSession(root)?.token).toBe("secret-token");
+ });
+
+ it("reads nothing from a missing, damaged or shapeless file", () => {
+ expect(readSession(root)).toBeNull();
+ fs.writeFileSync(path.join(root, "cli-session.json"), "{ not json");
+ expect(readSession(root)).toBeNull();
+ fs.writeFileSync(path.join(root, "cli-session.json"), JSON.stringify({ server: "x" }));
+ expect(readSession(root)).toBeNull();
+ writeSession(root, { server: "http://localhost:1", userId: "admin", token: "t" });
+ expect(clearSession(root)).toBe(true);
+ expect(readSession(root)).toBeNull();
+ });
+
+ it("says the canonical app host while connecting to the address", async () => {
+ // The whole reason this is node:http and not fetch. A server that only answers under its
+ // app host would 401 every request otherwise, and the message would blame the password.
+ const seen: { host?: string; body?: string } = {};
+ const server = http.createServer((req, res) => {
+ seen.host = req.headers.host;
+ const chunks: Buffer[] = [];
+ req.on("data", (c: Buffer) => chunks.push(c));
+ req.on("end", () => {
+ seen.body = Buffer.concat(chunks).toString("utf8");
+ res.setHeader("set-cookie", "penguin_session=tok; Path=/; HttpOnly");
+ res.writeHead(200, { "content-type": "application/json" });
+ res.end(JSON.stringify({ user: { userId: "admin" } }));
+ });
+ });
+ await new Promise<void>((resolve) => server.listen(0, "127.0.0.1", resolve));
+ const port = (server.address() as AddressInfo).port;
+ try {
+ const answer = await call(
+ `http://localhost:${port}`,
+ { method: "POST", path: "/api/auth/login" },
+ { userId: "admin", password: "pw" },
+ );
+ expect(answer.status).toBe(200);
+ expect(seen.host).toBe(`localhost:${port}`);
+ expect(seen.body).toBe(JSON.stringify({ userId: "admin", password: "pw" }));
+ const setCookie = answer.headers["set-cookie"];
+ expect(tokenFromSetCookie(setCookie as string[], "penguin_session")).toBe("tok");
+ } finally {
+ server.close();
+ }
+ });
+});
diff --git a/packages/core/src/environment/tools/command/session-manager.ts b/packages/core/src/environment/tools/command/session-manager.ts
index b4e0a4cd..3404cc3f 100644
--- a/packages/core/src/environment/tools/command/session-manager.ts
+++ b/packages/core/src/environment/tools/command/session-manager.ts
@@ -86,7 +86,7 @@ const STRIPPED_ENV_KEYS = new Set([
"FORCE_COLOR",
"CLICOLOR_FORCE",
// Desktop-mode process credentials and wiring: the shell's token authorizes the
- // server shutdown endpoint (and desktop-login until redeemed), and the port file is
+ // server shutdown endpoint (and the claim link until redeemed), and the port file is
// the shell's private channel — neither is a user-facing setting, and leaking them
// into Agent-run commands would let a prompt-injected command stop the server.
"PENGUIN_DESKTOP_TOKEN",
diff --git a/packages/desktop/src/main.ts b/packages/desktop/src/main.ts
index afa15196..5aadf79d 100644
--- a/packages/desktop/src/main.ts
+++ b/packages/desktop/src/main.ts
@@ -12,7 +12,7 @@
* One window over the embedded server: fork penguin-server as a utilityProcess on the
* shared data root (PENGUIN_HOME or ~/.penguin/data), learn its port (last launch's when
* still free, so origin-scoped localStorage preferences survive restarts), and load
- * `http://localhost:<port>/api/auth/desktop-login?token=…` — the one-shot token lands
+ * `http://localhost:<port>/api/auth/claim?token=…` — the one-shot token lands
* the window signed in as admin. The window is a plain browser environment (no preload,
* no node integration); every capability flows through the server's HTTP API.
*
@@ -164,7 +164,7 @@ function wireUpdaterRelay(child: EmbeddedServer["child"]): void {
child.postMessage(updaterStatusMessage(getUpdaterStatus()));
}
-/** Starts (or restarts) the embedded server and points the window at desktop-login. */
+/** Starts (or restarts) the embedded server and points the window at the claim link. */
async function startServerAndWindow(dataRoot: string): Promise<void> {
const started = await startEmbeddedServer({
dataRoot,
diff --git a/packages/desktop/src/server-process.ts b/packages/desktop/src/server-process.ts
index 6504af02..425d123f 100644
--- a/packages/desktop/src/server-process.ts
+++ b/packages/desktop/src/server-process.ts
@@ -18,7 +18,7 @@ export interface EmbeddedServer {
child: UtilityProcess;
/** App origin, e.g. `http://localhost:53187` (always localhost — 127.0.0.1 is the preview host). */
origin: string;
- /** This launch's PENGUIN_DESKTOP_TOKEN: one-shot for desktop-login, reusable for the shutdown endpoint. */
+ /** This launch's PENGUIN_DESKTOP_TOKEN: one-shot for the claim link, reusable for the shutdown endpoint. */
token: string;
}
diff --git a/packages/desktop/src/util.ts b/packages/desktop/src/util.ts
index 2883c5a2..e3ed0625 100644
--- a/packages/desktop/src/util.ts
+++ b/packages/desktop/src/util.ts
@@ -21,7 +21,7 @@ export function appOriginFor(port: number): string {
/** The window's first navigation: redeems the shell's one-shot token for a cookie session. */
export function desktopLoginUrl(origin: string, token: string): string {
- return `${origin}/api/auth/desktop-login?token=${encodeURIComponent(token)}`;
+ return `${origin}/api/auth/claim?token=${encodeURIComponent(token)}`;
}
/**
diff --git a/packages/desktop/test/util.test.ts b/packages/desktop/test/util.test.ts
index bac748db..9aa85f68 100644
--- a/packages/desktop/test/util.test.ts
+++ b/packages/desktop/test/util.test.ts
@@ -26,7 +26,7 @@ describe("app origin and login URL", () => {
it("builds the localhost origin and the one-shot login URL", () => {
expect(appOriginFor(7364)).toBe("http://localhost:7364");
expect(desktopLoginUrl("http://localhost:7364", "a b/c")).toBe(
- "http://localhost:7364/api/auth/desktop-login?token=a%20b%2Fc",
+ "http://localhost:7364/api/auth/claim?token=a%20b%2Fc",
);
});
});
diff --git a/packages/docs/content/cli.en.md b/packages/docs/content/cli.en.md
index b602abf4..162f014d 100644
--- a/packages/docs/content/cli.en.md
+++ b/packages/docs/content/cli.en.md
@@ -315,7 +315,7 @@ Offline rescue when the Web admin password is forgotten. Run it with the server
penguin server reset-admin-password
```
-The built-in `admin` gets a fresh initial password of the usual `penguin-1234` form, printed in the framed notice — and re-printed on every server start until it is changed — and all of admin's sign-in sessions are cleared. Other accounts are reset by the admin on the user-management page; this command only touches `admin`. The data root is selected by `PENGUIN_HOME` as usual.
+The built-in `admin` is returned to the unclaimed state — a random password nobody ever sees, and every one of admin's sessions revoked. Start the server again and open the first-login link it prints to set a new password; nothing is written down in the meantime. Other accounts are reset by the admin on the user-management page; this command only touches `admin`. The data root is selected by `PENGUIN_HOME` as usual.
## penguin version
@@ -355,6 +355,42 @@ This is the one thing the version line cannot report. A pushed bundle lands outs
It describes the store, not the process: `penguin` runs the packaged CLI while `penguin-hmr` runs the store's, so a non-null `harness` does not by itself mean the command printing it is the pushed code. `source` is null for a version pushed by a client that recorded no provenance, including anything pushed before it was recorded at all.
An installed penguin never shells out to git: it reads constants stamped into the build. A release gets them from the release workflow; every other build gets its git position inlined by the bundler that produced it, so an artifact still identifies itself after it has left the checkout it came from — a hot-pushed bundle under `<root>/hmr/store/` reports the revision it was built at, on a machine with no checkout and no git installed. Asking git at run time is only the fallback, for an un-bundled `tsx` run; even then it asks about its own checkout, so `penguin version` inside an unrelated repository reports the harness's revision and not that repository's.
+## penguin auth
+
+Signs in to a running PenguinHarness server from the terminal. This is the only part of the CLI that talks to a server as a client — `config`, `run` and `chat` all work on the data root directly.
+
+Two ways in, and which is right depends on where you are standing.
+
+```bash
+penguin auth login # password, against the server on this data root
+penguin auth login --server https://penguin.example --user-id alice
+penguin auth status
+penguin auth logout
+penguin auth token # no password: minted from this data root
+```
+
+`login` takes a password and asks a running server for a session, exactly as the browser's login page does. The target defaults to the server running on this data root (read from its lock file), so signing in to your own needs no URL.
+
+Run interactively it asks for the account first, then the password — and the password prompt names the account, so one account's password is never typed at another's. Supply the password non-interactively (`--password` or `PENGUIN_PASSWORD`) and neither question is asked: that is a script, and a script cannot answer one.
+
+| Option | Description |
+| --- | --- |
+| `--server <url>` | Server to sign in to; default the one running on this data root |
+| `--user-id <id>` | Account; asked for when omitted, defaulting to `admin` on a bare Enter |
+| `--password <pw>` | Password; also read from `PENGUIN_PASSWORD`, otherwise prompted without echo |
+| `--print` | Also print the session token to stdout, for piping |
+
+Prefer `PENGUIN_PASSWORD` or the prompt over `--password`: a command line is world-readable through `ps`.
+
+`token` takes no password at all. It writes a session row straight into the data root's `web.db`, and what authorizes it is that you can read and write that root — which already holds every credential the token could reach. That makes it the **data root owner's** tool: on a multi-user deployment the root belongs to the OS account running the server, and everyone else signs in with `auth login` instead. Use it where there is no password to give: a machine whose admin password somebody set by hand, a script that must not hold one, or a controller reaching a managed machine over ssh.
+
+| Option | Description |
+| --- | --- |
+| `--user-id <id>` | Account, default `admin` |
+| `--ttl-seconds <n>` | Lifetime, default 3600 |
+| `--mark` | Print a fixed marker line before the token — for a caller parsing it out of a shell whose login profile may print a banner |
+
+The session is written to `<root>/cli-session.json` at mode 0600, which is what `status` reads and `logout` revokes and deletes. `logout` tells the server first, so the session dies there rather than merely being forgotten here; if the server cannot be reached it says so, and the local file goes anyway.
## penguin update
diff --git a/packages/docs/content/cli.zh.md b/packages/docs/content/cli.zh.md
index 1e998674..7e93c72d 100644
--- a/packages/docs/content/cli.zh.md
+++ b/packages/docs/content/cli.zh.md
@@ -315,7 +315,7 @@ penguin web
penguin server reset-admin-password
```
-内置 `admin` 会得到一个新的初始密码(形如 `penguin-1234`),以边框提示打印——此后每次启动服务端都会重印,直到密码被修改——并清空 admin 的全部登录会话。其他账号由管理员在用户管理页重置,本命令只作用于 `admin`。数据根目录照常由 `PENGUIN_HOME` 决定。
+内置 `admin` 会被恢复成未认领状态——密码随机生成且无人见过,admin 的全部会话一并吊销。重新启动服务,打开它打印的首次登录链接即可设置新密码;整个过程无需记下任何东西。其他账号由管理员在用户管理页重置,本命令只作用于 `admin`。数据根目录照常由 `PENGUIN_HOME` 决定。
## penguin version
@@ -355,6 +355,42 @@ JSON 与 `GET /api/version` 返回的是同一份记录,因此在 HTTP 边界
它描述的是 store 而非当前进程:`penguin` 运行的是随包发布的 CLI,`penguin-hmr` 才运行 store 里的那份,因此 `harness` 非 null 并不意味着打印它的这条命令本身就是被推送的代码。若推送方未记录来源(包括在该机制存在之前推送的版本),`source` 为 null。
已安装的 penguin 从不调用 git,只读取构建时打入的常量:发布版由发布流程打入,其余构建则由打包器把 git 位置内联进产物,因此产物离开生成它的 checkout 之后依然能说明自己的身份——位于 `<root>/hmr/store/` 下被热推送的 bundle,在既无 checkout 也未安装 git 的机器上,仍会报告它被构建时的 revision。运行时询问 git 只是兜底,用于未经打包的 `tsx` 运行;即便如此它也只问自己所在的那个 checkout,所以在无关仓库里执行 `penguin version` 报告的仍是 harness 自身的版本,而非该仓库的。
+## penguin auth
+
+在终端里登录正在运行的 PenguinHarness 服务。这是 CLI 里唯一以客户端身份与服务通信的部分——`config`、`run`、`chat` 都是直接操作数据根。
+
+有两种登录方式,取决于你站在哪里。
+
+```bash
+penguin auth login # 用密码登录该数据根上运行的服务
+penguin auth login --server https://penguin.example --user-id alice
+penguin auth status
+penguin auth logout
+penguin auth token # 不需要密码:直接从数据根签发
+```
+
+`login` 需要密码,向正在运行的服务请求会话,和浏览器登录页做的事完全一样。目标默认是该数据根上正在运行的服务(从锁文件读端口),所以登录自己的服务不必写 URL。
+
+交互运行时会先问账号,再问密码,并且密码提示里写明是哪个账号的,避免把一个账号的密码输到另一个账号上。如果用非交互方式给了密码(`--password` 或 `PENGUIN_PASSWORD`),两个问题都不会问——那是脚本,脚本没法回答。
+
+| 选项 | 说明 |
+| --- | --- |
+| `--server <url>` | 要登录的服务;默认是该数据根上运行的那个 |
+| `--user-id <id>` | 账号;不给时会询问,直接回车即用 `admin` |
+| `--password <pw>` | 密码;也可用 `PENGUIN_PASSWORD`,都没给时会无回显地提示输入 |
+| `--print` | 同时把会话令牌打印到 stdout,便于管道使用 |
+
+优先用 `PENGUIN_PASSWORD` 或交互输入,而不是 `--password`:命令行参数可以被 `ps` 看到。
+
+`token` 完全不需要密码。它把一行会话直接写进数据根的 `web.db`,其授权依据就是你能读写这个数据根——而它本来就装着这个令牌所能触及的全部凭据。因此它是**数据根属主**的工具:多用户部署时数据根属于运行服务的那个操作系统账号,其他人一律用 `auth login` 凭密码登录。适用于没有密码可给的场合:管理员密码被人改过的机器、不该持有密码的脚本,以及控制端通过 ssh 管理机器时。
+
+| 选项 | 说明 |
+| --- | --- |
+| `--user-id <id>` | 账号,默认 `admin` |
+| `--ttl-seconds <n>` | 有效期秒数,默认 3600 |
+| `--mark` | 在令牌前打印固定标记行——供需要从 shell 输出里解析它的调用方使用,因为登录 profile 可能打印横幅 |
+
+会话写入 `<root>/cli-session.json`,权限 0600;`status` 读它,`logout` 吊销并删除它。`logout` 会先告诉服务端,让会话真正失效,而不只是本地忘记;连不上服务时会明说,本地文件照样删除。
## penguin update
diff --git a/packages/docs/content/configuration.en.md b/packages/docs/content/configuration.en.md
index fe5904e1..6c3c89de 100644
--- a/packages/docs/content/configuration.en.md
+++ b/packages/docs/content/configuration.en.md
@@ -17,7 +17,8 @@ The CLI and the server automatically load a `.env` file from the working directo
| `PENGUIN_WEB_DB` | Server SQLite database path | `<root>/web.db` |
| `PENGUIN_WEB_DIST` | Front-end static assets directory | the npm server package falls back to its bundled web-dist |
| `PENGUIN_PREVIEW_ORIGIN` | Origin that serves Workspace HTML previews, e.g. `https://preview.example.com` | unset — the loopback counterpart is derived per request |
-| `PENGUIN_SEED_ADMIN_PASSWORD` | Fixed initial password for the seeded built-in admin (automated tests / e2e) | unset — a random `penguin-<4 digits>` password is generated and printed once at seed time |
+| `PENGUIN_TRUST_PROXY` | `1` trusts the `x-forwarded-proto` header — set it behind a reverse proxy that terminates TLS (and sets/strips the header itself) so session cookies are marked `Secure` and the hot-update network gate sees HTTPS | unset — the header is ignored |
+| `PENGUIN_SEED_ADMIN_PASSWORD` | Fixed initial password for the seeded built-in admin (automated tests / e2e) | unset — the seed generates a random password, hashed and discarded unseen; the account is claimed through the first-login link |
| `PENGUIN_LANG` | CLI language (`en` / `zh`), set via `penguin config lang` | `en` |
| `PENGUIN_UPDATE_CHECK` | `off` disables the web app's new-release check (the server's only outbound internet call) | enabled |
| `PENGUIN_NO_LOGIN_SHELL_ENV` | Any non-empty value stops the desktop app from importing the login shell's environment on macOS/Linux GUI launches (see [Desktop quickstart](/quickstart-desktop)) | unset — the import runs, filling only variables the launch left unset |
diff --git a/packages/docs/content/configuration.zh.md b/packages/docs/content/configuration.zh.md
index 305dac6f..4fe4200d 100644
--- a/packages/docs/content/configuration.zh.md
+++ b/packages/docs/content/configuration.zh.md
@@ -17,7 +17,8 @@ CLI 与服务端启动时会自动加载工作目录下的 `.env` 文件。
| `PENGUIN_WEB_DB` | 服务端 SQLite 数据库路径 | `<root>/web.db` |
| `PENGUIN_WEB_DIST` | 前端静态资源目录 | npm 安装的服务端包回退到内置 web-dist |
| `PENGUIN_PREVIEW_ORIGIN` | 提供 Workspace HTML 预览的独立源,如 `https://preview.example.com` | 未设置,按请求推导回环对应名 |
-| `PENGUIN_SEED_ADMIN_PASSWORD` | 固定内置管理员的种子初始密码(自动化测试 / e2e 使用) | 未设置,种子时随机生成 `penguin-<四位数字>` 并打印一次 |
+| `PENGUIN_TRUST_PROXY` | 设为 `1` 信任 `x-forwarded-proto` 请求头——在终结 TLS 的反向代理(且由代理自行设置/清除该头)之后设置,使会话 Cookie 带 `Secure` 标记、热更新网络门禁识别 HTTPS | 未设置,忽略该请求头 |
+| `PENGUIN_SEED_ADMIN_PASSWORD` | 固定内置管理员的种子初始密码(自动化测试 / e2e 使用) | 未设置,种子时随机生成一个密码,哈希后即丢弃、无人见过;账号通过首次登录链接认领 |
| `PENGUIN_LANG` | CLI 语言(`en` / `zh`),用 `penguin config lang` 设置 | `en` |
| `PENGUIN_UPDATE_CHECK` | 设为 `off` 关闭 Web 应用的新版本检查(服务端唯一的对外网络请求) | 开启 |
| `PENGUIN_NO_LOGIN_SHELL_ENV` | 任意非空值可禁止桌面版在 macOS/Linux 图形界面启动时导入登录 shell 环境变量(见[桌面版速上手](/quickstart-desktop)) | 未设置,导入开启,且只补启动环境中缺失的变量 |
diff --git a/packages/docs/content/quickstart-cli.en.md b/packages/docs/content/quickstart-cli.en.md
index eedcd5e7..76f36e48 100644
--- a/packages/docs/content/quickstart-cli.en.md
+++ b/packages/docs/content/quickstart-cli.en.md
@@ -46,7 +46,7 @@ penguin config model add --provider deepseek --model-id deepseek-v4-flash --api-
penguin web
```
-The service runs at http://127.0.0.1:7364 and opens your browser (`--no-open` to skip). First login is `admin` — the server prints the initial password (of the form `penguin-1234`) in a framed notice on every start until it is changed; change it right away. `penguin server` starts the same process headless.
+The service runs at http://127.0.0.1:7364 and opens your browser (`--no-open` to skip). The account is `admin`, and it has no password yet: the server prints a first-login link in a framed notice, which opens the browser signed in so you can set one. The link works until a password exists (30-day ceiling — a restart prints a fresh one), and you can reopen it as often as you need. `penguin server` starts the same process headless.
The [Web App Guide](/web-app) covers the interface in full.
diff --git a/packages/docs/content/quickstart-cli.zh.md b/packages/docs/content/quickstart-cli.zh.md
index 1aa6c86d..16323097 100644
--- a/packages/docs/content/quickstart-cli.zh.md
+++ b/packages/docs/content/quickstart-cli.zh.md
@@ -46,7 +46,7 @@ penguin config model add --provider deepseek --model-id deepseek-v4-flash --api-
penguin web
```
-服务运行在 http://127.0.0.1:7364 并自动打开浏览器(`--no-open` 跳过)。首次登录使用 `admin`,初始密码(形如 `penguin-1234`)在改掉之前每次启动服务端都会以边框提示打印,请立即修改密码。`penguin server` 启动同一进程的 headless 版本。
+服务运行在 http://127.0.0.1:7364 并自动打开浏览器(`--no-open` 跳过)。账号是 `admin`,此时它还没有密码:服务端会以边框提示打印一条首次登录链接,打开即以登录态进入,随后设置密码即可。在密码被设置之前该链接一直有效(上限 30 天,重启会打印新的),可以重复打开。`penguin server` 启动同一进程的 headless 版本。
界面的完整说明见 [Web App 指南](/web-app)。
diff --git a/packages/docs/content/server-api.en.md b/packages/docs/content/server-api.en.md
index f820d77b..8a68cc75 100644
--- a/packages/docs/content/server-api.en.md
+++ b/packages/docs/content/server-api.en.md
@@ -33,16 +33,16 @@ packages/server/src
## Authentication
-- Cookie session: `penguin_session` (HttpOnly, SameSite=Lax), valid for 7 days with sliding renewal;
-- Passwords are stored as scrypt hashes; the server keeps only the sha256 of the session token, never the plaintext;
-- No open registration: the built-in admin `admin` is seeded at startup with a random initial password (of the form `penguin-1234`) — kept in `<root>/initial-admin-password` and re-printed to the server console on every start until it is changed; `PENGUIN_SEED_ADMIN_PASSWORD` pins it for automation — and all other accounts are created by an admin;
+- Cookie session: `penguin_session` (HttpOnly, SameSite=Lax), valid for 30 days with sliding renewal;
+- Passwords are stored as scrypt hashes. A session is a row in `auth_sessions` keyed by the sha256 of a random cookie token (the raw token is never stored); it survives a restart, renews in place, and logout deletes the row;
+- No open registration: the built-in admin `admin` is seeded at startup with a random password that is hashed and discarded unseen. Until a password is actually set, every start prints a first-login link that claims the account (`PENGUIN_SEED_ADMIN_PASSWORD` pins a known password instead, for automation). All other accounts are created by an admin;
- Same-origin only — no CORS middleware is enabled.
```bash
-# Use the initial password printed at first start (or your changed one).
+# Use the password you set when claiming the account from the first-login link.
curl -c cookies.txt -H "Content-Type: application/json" \
- -d '{"userId":"admin","password":"penguin-1234"}' \
- http://127.0.0.1:7364/api/auth/login
+ -d '{"userId":"admin","password":"<your password>"}' \
+ http://localhost:7364/api/auth/login
```
### Local API token (Bearer)
@@ -68,9 +68,10 @@ curl -H "Authorization: Bearer $(cat ~/.penguin/data/api-token)" \
| --- | --- | --- |
| POST | /api/auth/login | Log in: `{userId, password}` → `{user}` |
| POST | /api/auth/logout | Log out, returns 204 |
+| GET | /api/auth/claim?token=… | Redeem a sign-in link (first-login, or the desktop shell's one-shot token): sets the cookie, redirects to `/` |
| GET | /api/install | Public: `{installId}` — an opaque id identifying the data root being served (`<root>/install-id`), minted the first time the root is used. The Web App compares it against the one it stored and clears the browser-side UI state that references server entities when it differs, so replacing the data root no longer leaves the old Workspace, drafts and pins in place. `null` means the server could not establish one; clients must then change nothing. |
| GET | /api/me | Current user info |
-| PUT | /api/me/password | Change password: `{oldPassword, newPassword}` |
+| PUT | /api/me/password | Change password: `{oldPassword, newPassword}`; a desktop or first-login session may omit `oldPassword` — its current password is random and was never shown |
| GET | /api/me/prefs | Read UI preferences |
| PUT | /api/me/prefs | Write UI preferences (shallow merge) |
diff --git a/packages/docs/content/server-api.zh.md b/packages/docs/content/server-api.zh.md
index 398ca192..9a9c3309 100644
--- a/packages/docs/content/server-api.zh.md
+++ b/packages/docs/content/server-api.zh.md
@@ -33,16 +33,16 @@ packages/server/src
## 认证
-- Cookie 会话:`penguin_session`(HttpOnly、SameSite=Lax),有效期 7 天,滑动续期;
-- 密码以 scrypt 哈希存储;服务端只保存会话 Token 的 sha256,不落明文;
-- 不开放注册:启动时种子化内置管理员 `admin`,初始密码随机生成(形如 `penguin-1234`),在改掉之前保存在 `<root>/initial-admin-password` 中并于每次启动时打印到服务端控制台——自动化可用 `PENGUIN_SEED_ADMIN_PASSWORD` 固定——其余账号由管理员创建;
+- Cookie 会话:`penguin_session`(HttpOnly、SameSite=Lax),有效期 30 天,滑动续期;
+- 密码以 scrypt 哈希存储;会话是 `auth_sessions` 表中的一行,以随机 Cookie 令牌的 sha256 为键(原始令牌从不落库);它跨重启存活、原地续期,logout 删除该行;
+- 不开放注册:启动时种子化内置管理员 `admin`,其初始密码随机生成、哈希后即丢弃,无人见过。在真正设置密码之前,每次启动都会打印一条首次登录链接用于认领账号(自动化场景可用 `PENGUIN_SEED_ADMIN_PASSWORD` 固定一个已知密码)。其余账号由管理员创建;
- 仅限同源访问,未启用 CORS 中间件。
```bash
-# 密码用首次启动时打印的初始密码(或改过之后的密码)。
+# 密码用认领账号(首次登录链接)时设置的那个。
curl -c cookies.txt -H "Content-Type: application/json" \
- -d '{"userId":"admin","password":"penguin-1234"}' \
- http://127.0.0.1:7364/api/auth/login
+ -d '{"userId":"admin","password":"<你的密码>"}' \
+ http://localhost:7364/api/auth/login
```
### 本机 API token(Bearer)
@@ -68,9 +68,10 @@ curl -H "Authorization: Bearer $(cat ~/.penguin/data/api-token)" \
| --- | --- | --- |
| POST | /api/auth/login | 登录:`{userId, password}` → `{user}` |
| POST | /api/auth/logout | 退出登录,返回 204 |
+| GET | /api/auth/claim?token=… | 兑换登录链接(首次登录链接,或桌面 shell 的一次性 token):种下 Cookie 并跳转到 `/` |
| GET | /api/install | 公开:`{installId}`——标识当前所服务数据根的不透明 id(`<root>/install-id`),在该根首次被使用时铸造。Web App 将其与自己存下的值比较,不一致时清除浏览器侧那些引用服务端实体的 UI 状态,因此更换数据根后不会再留下旧的 Workspace、草稿与置顶。`null` 表示服务端无法确定该 id,此时客户端不应改动任何内容。 |
| GET | /api/me | 当前用户信息 |
-| PUT | /api/me/password | 修改密码:`{oldPassword, newPassword}` |
+| PUT | /api/me/password | 修改密码:`{oldPassword, newPassword}`;桌面会话与首次登录会话可省略 `oldPassword`——其当前密码是随机生成且从未展示过的 |
| GET | /api/me/prefs | 读取 UI 偏好 |
| PUT | /api/me/prefs | 写入 UI 偏好(浅合并) |
diff --git a/packages/docs/content/web-app.en.md b/packages/docs/content/web-app.en.md
index d64bf77e..55304c21 100644
--- a/packages/docs/content/web-app.en.md
+++ b/packages/docs/content/web-app.en.md
@@ -23,9 +23,9 @@ penguin web
# open http://127.0.0.1:7364
```
-The initial account is `admin`; its initial password (of the form `penguin-1234`) is printed in the server startup output — as a framed notice on every start — until it is changed. There is no self-registration: accounts are created by an admin on the user-management page, and every new user automatically gets an independent initial Project named `<userId>-default_project`. While the initial password is still in use, a banner prompts the user to change it. A forgotten password is reset by the admin on the user-management page; a forgotten **admin** password is reset offline with `penguin server reset-admin-password` (server stopped), which issues a fresh initial password.
+The initial account is `admin`, and it starts with no password of its own: the server prints a first-login link in a framed notice on every start until one is set, and opening that link signs the browser in to set it. The link stays usable — and identical — until the password exists. There is no self-registration: accounts are created by an admin on the user-management page, and every new user automatically gets an independent initial Project named `<userId>-default_project`. While the initial password is still in use, a banner prompts the user to change it. A forgotten password is reset by the admin on the user-management page; a forgotten **admin** password is reset offline with `penguin server reset-admin-password` (server stopped), which returns the account to the unclaimed state and brings the first-login link back.
-Logins persist for 7 days with sliding renewal; an admin password reset invalidates all of that user's login sessions.
+Logins persist for 30 days with sliding renewal; an admin password reset invalidates all of that user's login sessions.
The interface language (中文 / English / system) and theme (light / dark / system) can be switched at any time.
diff --git a/packages/docs/content/web-app.zh.md b/packages/docs/content/web-app.zh.md
index a360bc7e..3151c46a 100644
--- a/packages/docs/content/web-app.zh.md
+++ b/packages/docs/content/web-app.zh.md
@@ -23,9 +23,9 @@ penguin web
# 打开 http://127.0.0.1:7364
```
-初始账号为 `admin`,初始密码(形如 `penguin-1234`)在改掉之前每次启动服务端都会以边框提示打印。系统不开放自助注册:账号由管理员在用户管理页创建;每个新用户会自动获得一个独立的初始 Project,命名为 `<userId>-default_project`。仍在使用初始密码时,页面会以横幅提示尽快修改。用户忘记密码由管理员在用户管理页重置;**管理员**自己忘记密码时,停止服务后执行 `penguin server reset-admin-password` 离线重置为新的初始密码。
+初始账号为 `admin`,它一开始并没有自己的密码:在设置密码之前,每次启动服务端都会以边框提示打印一条首次登录链接,打开该链接即以登录态进入浏览器并设置密码。该链接在密码存在之前一直有效,可以重复打开。系统不开放自助注册:账号由管理员在用户管理页创建;每个新用户会自动获得一个独立的初始 Project,命名为 `<userId>-default_project`。仍在使用初始密码时,页面会以横幅提示尽快修改。用户忘记密码由管理员在用户管理页重置;**管理员**自己忘记密码时,停止服务后执行 `penguin server reset-admin-password` 离线把账号恢复成未认领状态,首次登录链接随之回来。
-登录状态保持 7 天(滑动续期);管理员重置密码会使该用户的全部登录会话失效。
+登录状态保持 30 天(滑动续期);管理员重置密码会使该用户的全部登录会话失效。
界面语言(中文 / English / 跟随系统)与主题(浅色 / 深色 / 跟随系统)可随时切换。
diff --git a/packages/server/README.md b/packages/server/README.md
index c2e9314c..f38823c5 100644
--- a/packages/server/README.md
+++ b/packages/server/README.md
@@ -21,7 +21,7 @@ The full route tables and the SSE protocol are documented in the [Server API ref
| `PENGUIN_HOME` | Data root (shared with SDK/CLI) | `~/.penguin/data` |
| `PENGUIN_WEB_DB` | SQLite file path | `<root>/web.db` |
| `PENGUIN_WEB_DIST` | Front-end build dir (static hosting + SPA fallback when present) | `../web/dist`, or the bundled `web-dist/` in the npm package |
-| `PENGUIN_TRUST_PROXY` | Trust `x-forwarded-proto` for the hot-update network gate (`1` to enable) — only behind a reverse proxy that sets/strips the header itself | unset (untrusted) |
+| `PENGUIN_TRUST_PROXY` | Trust `x-forwarded-proto` (`1` to enable): it opens the hot-update network gate over proxied HTTPS and marks session cookies `Secure` — only behind a reverse proxy that sets/strips the header itself | unset (untrusted) |
`.env` in the process cwd is loaded automatically.
@@ -39,10 +39,10 @@ pnpm --filter @prismshadow/penguin-server start # node dist/index.js
- **CSRF**: session cookie is `SameSite=Lax` and writes accept only `Content-Type: application/json`; no CSRF token yet.
- **Login throttling**: per-username exponential backoff after 5 consecutive failures (1s doubling to a 60s cap, `429 too_many_attempts` inside the window, reset on success; in-memory, so a restart clears it). Unknown usernames are throttled identically, so it is not an account-existence oracle. A reverse proxy can still add IP-level limits for public deployments.
-- **Built-in admin `admin` starts with a random initial password** of the form `penguin-1234`, printed once to the server console at seed time (`PENGUIN_SEED_ADMIN_PASSWORD` pins it for tests/e2e): change it immediately (a banner keeps reminding until you do).
-- Passwords use `node:crypto` scrypt (`scrypt$N$r$p$salt$hash`, timingSafeEqual); login sessions renew on a 7-day sliding window; the DB stores only the token's sha256.
+- **Built-in admin `admin` is seeded with a random password that is hashed and discarded unseen** (`PENGUIN_SEED_ADMIN_PASSWORD` pins it for tests/e2e). Until a password is set, every start prints a first-login link that signs the browser in to choose one; a banner keeps reminding until the initial flag clears.
+- Passwords use `node:crypto` scrypt (`scrypt$N$r$p$salt$hash`, timingSafeEqual). A session is a row in `auth_sessions` (the cookie holds a random token, the row its sha256); it survives a restart, renews the expiry in place, and logout deletes the row. Sessions run 30 days with sliding renewal.
- Model credentials live in the Project's hidden 0600 config file; the API always masks them.
- **Terminals are a shell as the OS account running the server**, i.e. the most privileged thing the API hands out — they are not Project-scoped. A terminal is only visible to the account that created it (someone else's id answers 404, not 403), and the stream WebSocket checks `Origin` on top of the session cookie because a WebSocket handshake is not subject to CORS. Do not expose a deployment with terminals enabled to accounts you would not give SSH.
-- Behind a reverse proxy, disable response buffering for SSE paths (the server already sends `X-Accel-Buffering: no`) and forward `x-forwarded-proto` to enable Secure cookies.
+- Behind a reverse proxy, disable response buffering for SSE paths (the server already sends `X-Accel-Buffering: no`), and set `PENGUIN_TRUST_PROXY=1` with `x-forwarded-proto` forwarded so session cookies are marked `Secure` — the header alone is not trusted, so without the opt-in an HTTPS deployment issues its cookies without the flag.
Part of [PenguinHarness](https://github.com/Prism-Shadow/penguin-harness) · Apache-2.0
diff --git a/packages/server/package.json b/packages/server/package.json
index 24bea7fb..aff5a61a 100644
--- a/packages/server/package.json
+++ b/packages/server/package.json
@@ -38,6 +38,14 @@
"types": "./dist/version-report.d.ts",
"import": "./dist/version-report.js"
},
+ "./auth-token": {
+ "types": "./dist/auth-token.d.ts",
+ "import": "./dist/auth-token.js"
+ },
+ "./secret-file": {
+ "types": "./dist/secret-file.d.ts",
+ "import": "./dist/secret-file.js"
+ },
"./extension": {
"types": "./dist/extension/index.d.ts",
"import": "./dist/extension/index.js"
diff --git a/packages/server/src/api/types.ts b/packages/server/src/api/types.ts
index 2ddee8ec..ae902e0e 100644
--- a/packages/server/src/api/types.ts
+++ b/packages/server/src/api/types.ts
@@ -96,18 +96,19 @@ export interface MeResponse {
/**
* Whether this server runs in desktop mode (spawned by the desktop shell with
* PENGUIN_DESKTOP_TOKEN). The web app then hides the logout entry, the
- * initial-password banner and the self-update entry, and omits the old-password
- * field when changing the password.
+ * initial-password banner and the self-update entry.
*/
desktopMode: boolean;
/**
- * How THIS session was established. Distinct from desktopMode: a browser signed into a
- * desktop-mode server holds a "password" session and must still provide the old
- * password when changing it — only "desktop" sessions (opened by the shell's one-shot
- * token) may omit it. "token" marks a request authenticated by the local API token's
- * Bearer header (the CLI and agent-driven calls).
+ * How THIS session was established — distinct from desktopMode, which describes the
+ * server: a browser signed into a desktop-mode server holds a "password" session.
+ * "desktop" is the shell's own window (one-shot token); "setup" was claimed through the
+ * first-login link on a server whose admin password has never been set. Both may set a
+ * password without the old one (it is random and was never shown); only "desktop" opens
+ * desktop-only routes. "token" marks a request authenticated by the local API token's
+ * Bearer header (the CLI and agent-driven calls) — no stored session at all.
*/
- sessionVia: "password" | "desktop" | "token";
+ sessionVia: "password" | "desktop" | "setup" | "token";
/**
* The upload limits currently in force, so the composer can refuse an oversize pick before
* reading it and can name the real number in the message. They are admin-settable and ride
@@ -144,7 +145,7 @@ export interface UploadLimits {
}
export interface PasswordChangeRequest {
- /** Omitted only by desktop-established sessions (desktop mode); required otherwise. */
+ /** Omitted only by a "desktop" or "setup" session (see {@link MeResponse.sessionVia}); required otherwise. */
oldPassword?: string;
/** At least 8 characters. */
newPassword: string;
diff --git a/packages/server/src/app.ts b/packages/server/src/app.ts
index 2252fd63..72bea8ef 100644
--- a/packages/server/src/app.ts
+++ b/packages/server/src/app.ts
@@ -29,7 +29,7 @@ import { applyProxySettings, mergedNoProxy } from "./net/proxy.js";
import {
RUNTIME_INTERFACES,
RUNTIME_INTERFACES_RESOURCE_ID,
- RUNTIME_AUTH_RESOURCE_ID,
+ RUNTIME_AUTH_STATE_RESOURCE_ID,
RUNTIME_CHANNELS_RESOURCE_ID,
RUNTIME_CONFIG_RESOURCE_ID,
RUNTIME_DB_RESOURCE_ID,
@@ -41,7 +41,6 @@ import {
} from "./hmr/capabilities.js";
import type { ProxyControl } from "./hmr/capabilities.js";
import { openDatabase } from "./db/database.js";
-import { AuthSessionsRepo } from "./db/repos/auth-sessions.js";
import { ErrorsRepo } from "./db/repos/errors.js";
import { MessagingBindingsRepo } from "./db/repos/messaging-bindings.js";
import { GoalsRepo } from "./db/repos/goals.js";
@@ -58,8 +57,9 @@ import { terminalRoutes } from "./terminal/routes.js";
import type { TerminalManager } from "./terminal/manager.js";
import { EXTENSIONS_RESOURCE_ID, type ExtensionHost } from "./extension/host.js";
import type { AppEnv } from "./auth/middleware.js";
-import { ADMIN_USER_ID, AuthService } from "./auth/service.js";
-import { clearInitialAdminPassword } from "./initial-password.js";
+import { AuthService } from "./auth/service.js";
+import { newAuthRuntimeState } from "./auth/runtime-state.js";
+import { AuthSessionsRepo } from "./db/repos/auth-sessions.js";
import { ensureInstallId } from "./install-id.js";
import { handleError, HttpError, errorBody } from "./http/errors.js";
import { attributedProjectId } from "./http/attribution.js";
@@ -260,7 +260,6 @@ export async function bootAppDeps(
const db = openDatabase(config.dbPath);
const usersRepo = new UsersRepo(db);
- const authSessionsRepo = new AuthSessionsRepo(db);
// Hoisted above the services so its registry can be populated before anything boots
// against it.
@@ -272,41 +271,18 @@ export async function bootAppDeps(
// by each generation. Until the first App boots, nothing is active.
const channels = new ChannelHub();
- // Any password update for the built-in admin makes the persisted initial-password
- // plaintext stale (either the password is no longer initial, or a reset replaced it
- // with an admin-chosen value that is never persisted): drop the file so later startups
- // stop re-printing a credential that no longer signs in.
- const onPasswordChanged = (userId: string): void => {
- if (userId === ADMIN_USER_ID) clearInitialAdminPassword(config.root);
- };
- const authService = new AuthService({
- users: usersRepo,
- authSessions: authSessionsRepo,
- // Auth is runtime mechanism, but WHAT a fresh user is provisioned with is business
- // policy: the App installs the real provisioner via setProvisioner at every create
- // (see hmr/platform.ts). This constructor fallback only answers before the first
- // boot, which the startup order below makes unreachable in practice.
- provisionInitialProject: () => {
- throw new Error("no business platform is running to provision the initial Project");
- },
- seedAdminPassword: config.seedAdminPassword,
- onPasswordChanged,
- sessionTtlMs: config.authSessionTtlMs,
- sessionRenewMs: config.authSessionRenewMs,
- ...(overrides.passwordHashCost !== undefined
- ? { passwordHashCost: overrides.passwordHashCost }
- : {}),
- ...(overrides.now ? { now: overrides.now } : {}),
- });
+ // Authentication itself is business behaviour and is built per App (buildAppDeps), so a
+ // change to it ships by push. Only the values that must survive a push live out here.
+ const authState = newAuthRuntimeState();
- // Local API token: minted per boot, persisted at <root>/api-token (0600) and installed
- // on the runtime auth service, so authMiddleware accepts it as the admin for this
- // process's whole life — across hot swaps too (the auth service is a runtime
- // singleton). Local filesystem access to the data root is admin authority (the
- // reset-admin-password rule); see auth/api-token.ts.
+ // Local API token: minted per boot, persisted at <root>/api-token (0600) and published on
+ // the runtime auth state, so authMiddleware accepts it as the admin for this process's
+ // whole life — across hot swaps too, since the App that verifies it is rebuilt but the
+ // file on disk is not rewritten. Local filesystem access to the data root is admin
+ // authority (the reset-admin-password rule); see auth/api-token.ts.
const apiToken = mintApiToken();
storeApiToken(config.root, apiToken);
- authService.setLocalApiToken(apiToken);
+ authState.apiToken = apiToken;
// Install identity: minted here so a root gets its name the first time it is used rather
// than on the first browser request, which keeps `<root>/install-id` alongside the other
@@ -322,7 +298,7 @@ export async function bootAppDeps(
hmr.resources.register(RUNTIME_INTERFACES_RESOURCE_ID, RUNTIME_INTERFACES);
hmr.resources.register(RUNTIME_CONFIG_RESOURCE_ID, config);
hmr.resources.register(RUNTIME_DB_RESOURCE_ID, db);
- hmr.resources.register(RUNTIME_AUTH_RESOURCE_ID, authService);
+ hmr.resources.register(RUNTIME_AUTH_STATE_RESOURCE_ID, authState);
hmr.resources.register(RUNTIME_CHANNELS_RESOURCE_ID, channels);
hmr.resources.register(RUNTIME_PROXY_RESOURCE_ID, applyProxySettings);
hmr.resources.register(RUNTIME_HMR_RESOURCE_ID, hmr);
@@ -457,8 +433,8 @@ export function createRuntimeApp(deps: AppDeps): Hono<AppEnv> {
// check/install back. Cookie-authed, unlike the Bearer-token shutdown above, so it
// carries the auth middleware on its own subtree — the routes then gate on
// `sessionVia === "desktop"`, i.e. the shell's own window.
- app.use("/api/desktop/update", authMiddleware(deps.authService));
- app.use("/api/desktop/update/*", authMiddleware(deps.authService));
+ app.use("/api/desktop/update", authMiddleware(deps.authService, deps.config.trustProxy));
+ app.use("/api/desktop/update/*", authMiddleware(deps.authService, deps.config.trustProxy));
app.route("/api/desktop/update", desktopUpdateRoutes(deps));
}
// Hot platform APIs authenticate themselves (local-agent Bearer token OR
@@ -592,12 +568,30 @@ export function buildAppDeps(
caps: RuntimeCapabilities,
overrides: BuildDepsOverrides = {},
): AppDeps {
- const { config, db, authService, channels, hmr } = caps;
+ const { config, db, authState, channels, hmr } = caps;
const log = overrides.log ?? ((line: string) => console.log(line));
const usersRepo = new UsersRepo(db);
const projectsRepo = new ProjectsRepo(db);
const membersRepo = new MembersRepo(db);
+ // Auth is built HERE, with the App, so every rule it carries ships by push. The runtime
+ // publishes only `authState` — the values a push must not forget (auth/runtime-state.ts).
+ // `provisionInitialProject` closes over the projectService created below: seeding runs long
+ // after this returns, so the cycle costs a closure rather than an install-it-later hook.
+ const authService = new AuthService({
+ users: usersRepo,
+ authSessions: new AuthSessionsRepo(db),
+ state: authState,
+ provisionInitialProject: (user, isAdmin) =>
+ projectService.provisionInitialProject(user, isAdmin),
+ seedAdminPassword: config.seedAdminPassword,
+ sessionTtlMs: config.authSessionTtlMs,
+ sessionRenewMs: config.authSessionRenewMs,
+ ...(overrides.passwordHashCost !== undefined
+ ? { passwordHashCost: overrides.passwordHashCost }
+ : {}),
+ ...(overrides.now ? { now: overrides.now } : {}),
+ });
const agentsRepo = new AgentsRepo(db);
const sessionsRepo = new SessionsRepo(db);
const usageRepo = new UsageRepo(db);
@@ -749,20 +743,11 @@ export function buildAppDeps(
manager,
traceIndex,
});
- // Any password update for the built-in admin makes the persisted initial-password
- // plaintext stale (either the password is no longer initial, or a reset replaced it
- // with an admin-chosen value that is never persisted): drop the file so later startups
- // stop re-printing a credential that no longer signs in. (The runtime's AuthService
- // carries the same rule for the self-service path; this one covers admin resets.)
- const onPasswordChanged = (userId: string): void => {
- if (userId === ADMIN_USER_ID) clearInitialAdminPassword(config.root);
- };
const adminService = new AdminService({
users: usersRepo,
authSessions: new AuthSessionsRepo(db),
projects: projectsRepo,
projectService,
- onPasswordChanged,
...(overrides.passwordHashCost !== undefined
? { passwordHashCost: overrides.passwordHashCost }
: {}),
@@ -969,7 +954,7 @@ export function createApp(
app.route("/api/install", installRoutes(deps));
// Protected routes: cookie -> auth_session -> user, over the runtime's auth service.
- app.use("/api/*", authMiddleware(deps.authService));
+ app.use("/api/*", authMiddleware(deps.authService, deps.config.trustProxy));
app.route("/api/me", meRoutes(deps));
app.route("/api/version", versionRoutes(deps));
app.route("/api/admin/users", adminUsersRoutes(deps));
diff --git a/packages/server/src/auth-token.ts b/packages/server/src/auth-token.ts
new file mode 100644
index 00000000..b461fe60
--- /dev/null
+++ b/packages/server/src/auth-token.ts
@@ -0,0 +1,79 @@
+/**
+ * Mints an API session by inserting a row into the root's `web.db` — no running server needed.
+ * Authorized by being able to read and write that root, which already holds every credential
+ * the token could reach. On a multi-user box that means the OS account running the server;
+ * everyone else signs in with `penguin auth login --server <url>`.
+ */
+import path from "node:path";
+import fs from "node:fs";
+import { openExistingDatabase } from "./db/database.js";
+import { AuthSessionsRepo } from "./db/repos/auth-sessions.js";
+import { UsersRepo } from "./db/repos/users.js";
+
+/** An hour: long enough for a controller to finish, short enough to forget. */
+export const CLI_TOKEN_TTL_MS = 60 * 60_000;
+
+/**
+ * Ceiling on a caller-supplied `--ttl-seconds`, matching the default session TTL (config.ts):
+ * a token that lives in a file must not outlive an ordinary browser session.
+ */
+export const CLI_TOKEN_MAX_TTL_MS = 30 * 24 * 60 * 60_000;
+
+export type MintTokenResult =
+ | { outcome: "minted"; token: string; userId: string; expiresAt: string }
+ /** No web.db on this root — the server has never run here, so there is no account to mint for. */
+ | { outcome: "no_server" }
+ | { outcome: "failed"; detail: string };
+
+/**
+ * Turns a failure into something the person at the terminal can act on. Both cases are
+ * ordinary situations, not crashes: a database owned by another OS account, and one written
+ * by an older release (minting deliberately does not migrate — see openExistingDatabase).
+ */
+function explain(err: unknown, dbPath: string): string {
+ const message = err instanceof Error ? err.message : String(err);
+ if (message.includes("no column named via")) {
+ return `${dbPath} predates this release — start the server once (\`penguin web\`) to upgrade it`;
+ }
+ if (message.includes("unable to open database")) {
+ return (
+ `cannot open ${dbPath} — minting needs the data root's own OS account; ` +
+ "otherwise sign in with `penguin auth login --server <url>`"
+ );
+ }
+ return message;
+}
+
+/** Issues an API session token for the data root at `root`. */
+export function mintApiToken(
+ root: string,
+ opts: { userId?: string; ttlMs?: number; dbPath?: string; now?: Date } = {},
+): MintTokenResult {
+ const userId = opts.userId ?? "admin";
+ const dbPath = opts.dbPath ?? path.join(root, "web.db");
+ // Existence check first: openExistingDatabase would otherwise create an empty file, and a
+ // root with no web.db has no account to mint for.
+ if (!fs.existsSync(dbPath)) return { outcome: "no_server" };
+
+ let db: ReturnType<typeof openExistingDatabase> | null = null;
+ try {
+ db = openExistingDatabase(dbPath);
+ if (new UsersRepo(db).findById(userId) === null) {
+ return { outcome: "failed", detail: `no such account: ${userId}` };
+ }
+ // The repo is the single minting point (token shape, hash, TTL ceiling), so a CLI-minted
+ // row cannot drift from one the server issues itself.
+ const { token, expiresAt } = new AuthSessionsRepo(db).issue({
+ userId,
+ via: "cli",
+ now: opts.now ?? new Date(),
+ ttlMs: opts.ttlMs ?? CLI_TOKEN_TTL_MS,
+ maxTtlMs: CLI_TOKEN_MAX_TTL_MS,
+ });
+ return { outcome: "minted", token, userId, expiresAt };
+ } catch (err) {
+ return { outcome: "failed", detail: explain(err, dbPath) };
+ } finally {
+ db?.close();
+ }
+}
diff --git a/packages/server/src/auth/middleware.ts b/packages/server/src/auth/middleware.ts
index af6f4463..2e5c9759 100644
--- a/packages/server/src/auth/middleware.ts
+++ b/packages/server/src/auth/middleware.ts
@@ -1,6 +1,6 @@
/**
* Auth middleware: `Authorization: Bearer <local API token>` -> the built-in admin, or
- * cookie -> auth_session -> user; either way the user is injected into c.var.
+ * session cookie -> auth_sessions row -> user; either way the user is injected into c.var.
*
* The Bearer path authenticates the boot's local API token (`<root>/api-token`, see
* auth/api-token.ts) as the admin — the CLI's and agents' machine-local credential; it
@@ -10,13 +10,11 @@
* credential would mask misconfiguration.
*
* Accessing a protected API while logged out -> 401 `{error:{code:"unauthorized"}}`.
- * CSRF (MVP): SameSite=Lax cookie + write requests only accept
- * `Content-Type: application/json` (an HTML form can't forge that Content-Type),
- * see the README security notes. The Content-Type guard stays for Bearer requests too —
- * the CLI always sends application/json.
+ * CSRF: SameSite=Lax plus a Content-Type an HTML form cannot forge (see jsonOnlyWrites).
+ * That guard stays for Bearer requests too — the CLI always sends application/json.
*/
import type { MiddlewareHandler } from "hono";
-import { getCookie } from "hono/cookie";
+import { getCookie, setCookie } from "hono/cookie";
import { HttpError } from "../http/errors.js";
import type { UserRow } from "../db/repos/users.js";
import type { AuthService, SessionVia } from "./service.js";
@@ -24,11 +22,37 @@ import type { AuthService, SessionVia } from "./service.js";
/** Session cookie name. */
export const SESSION_COOKIE = "penguin_session";
+/**
+ * Session cookie attributes, shared by every path that sets one. `maxAge` comes from the
+ * service that issues the sessions, never written here: the ROW carries the authoritative
+ * expiry, and a cookie that expired first would log someone out mid-session.
+ */
+export function cookieOptions(
+ c: { req: { url: string; header(name: string): string | undefined } },
+ ttlMs: number,
+ trustProxy: boolean,
+) {
+ // `x-forwarded-proto` is caller-supplied and untrusted unless the deployment opts in
+ // (config.trustProxy — the same gate hmr/routes.ts uses, and for the same reason). Trusting
+ // it on a plain-HTTP bind would let anyone reaching the port get a Secure cookie back, which
+ // the browser then refuses to send over that connection: a sign-in that never takes.
+ const proto = trustProxy
+ ? (c.req.header("x-forwarded-proto") ?? new URL(c.req.url).protocol.replace(":", ""))
+ : new URL(c.req.url).protocol.replace(":", "");
+ return {
+ httpOnly: true,
+ sameSite: "Lax" as const,
+ path: "/",
+ maxAge: Math.floor(ttlMs / 1000),
+ ...(proto === "https" ? { secure: true } : {}),
+ };
+}
+
/** Hono env: variables injected by the auth middleware. */
export type AppEnv = {
Variables: {
user: UserRow;
- /** How the current session was established ("password" | "desktop"); legacy rows read as "password". */
+ /** How the current session was established — see {@link SessionVia}. */
sessionVia: SessionVia;
};
};
@@ -38,7 +62,7 @@ export function currentUser(c: { var: { user: UserRow } }): UserRow {
return c.var.user;
}
-export function authMiddleware(auth: AuthService): MiddlewareHandler<AppEnv> {
+export function authMiddleware(auth: AuthService, trustProxy: boolean): MiddlewareHandler<AppEnv> {
return async (c, next) => {
// Bearer first: an explicit credential on the request outranks ambient cookies, and
// a wrong one is an error, never a silent fallback (see the module doc).
@@ -58,6 +82,11 @@ export function authMiddleware(auth: AuthService): MiddlewareHandler<AppEnv> {
if (!authed) {
throw new HttpError(401, "unauthorized", "Not signed in or the sign-in has expired.");
}
+ // Sliding renewal: the session's expiry was topped up in place, so refresh the cookie's
+ // own max-age to match. The token value is unchanged — same session, longer life.
+ if (authed.renewed && token) {
+ setCookie(c, SESSION_COOKIE, token, cookieOptions(c, auth.sessionTtlMs, trustProxy));
+ }
c.set("user", authed.user);
c.set("sessionVia", authed.via);
await next();
@@ -74,12 +103,11 @@ export function bearerToken(header: string | undefined): string | null {
const WRITE_METHODS = new Set(["POST", "PUT", "PATCH", "DELETE"]);
/**
- * Content-Types write requests may carry. application/json is the default
- * for the whole API; application/gzip and application/octet-stream are the
- * hot-update web push's binary artifact transport (packages/server/src/hmr) —
- * like application/json, neither is one of the three Content-Types an HTML
- * form can forge (application/x-www-form-urlencoded, multipart/form-data,
- * text/plain), so allowing them here does not reopen the CSRF gap below.
+ * CSRF defense: a write must carry one of these Content-Types, none of which an HTML form can
+ * forge (a form is limited to x-www-form-urlencoded, multipart/form-data, text/plain). json is
+ * the API default; gzip and octet-stream are the hot-update web push's artifact transport
+ * (src/hmr). A write with NO Content-Type and an empty body is let through — a form always
+ * sends a form-type one.
*/
const ALLOWED_WRITE_CONTENT_TYPES = [
"application/json",
@@ -87,12 +115,6 @@ const ALLOWED_WRITE_CONTENT_TYPES = [
"application/octet-stream",
];
-/**
- * Content-Type defense for write requests: a write request with a Content-Type
- * other than one of ALLOWED_WRITE_CONTENT_TYPES is rejected (a request with no
- * Content-Type and an empty body is let through — an HTML form always carries
- * a form-type Content-Type).
- */
export const jsonOnlyWrites: MiddlewareHandler = async (c, next) => {
if (WRITE_METHODS.has(c.req.method)) {
const contentType = c.req.header("content-type")?.toLowerCase();
diff --git a/packages/server/src/auth/runtime-state.ts b/packages/server/src/auth/runtime-state.ts
new file mode 100644
index 00000000..fc375346
--- /dev/null
+++ b/packages/server/src/auth/runtime-state.ts
@@ -0,0 +1,30 @@
+/**
+ * The auth values that belong to the PROCESS, not to the App built on top of it.
+ *
+ * Auth policy — who may set a password, how long a session lasts, how logins are throttled —
+ * is business behaviour and lives in the platform, so it ships by push. But a couple of values
+ * must outlive a push while still dying at a restart: the first-login link a boot printed is
+ * compared verbatim at redemption, so a swap that forgot it would strand whoever is holding
+ * the link the console shows, and the local API token was written to `<root>/api-token` at
+ * boot — a swap that forgot it would 401 every CLI and every command subprocess still
+ * holding the file's value.
+ *
+ * That is the state layer of the four-layer model (hmr/README.md): a runtime resource the
+ * platform claims, riding across swaps and never across restarts. The holder is deliberately
+ * a plain mutable bag rather than a service — it carries no behaviour to go stale, so a
+ * platform newer than its runtime can still use one an older runtime published.
+ */
+export interface AuthRuntimeState {
+ /** The first-login link this boot printed, or null before one was minted. */
+ firstLoginToken: string | null;
+ /**
+ * This boot's local API token (auth/api-token.ts), installed by the startup assembly.
+ * Null in constructions that never minted one — they simply never authenticate a Bearer
+ * header.
+ */
+ apiToken: string | null;
+}
+
+export function newAuthRuntimeState(): AuthRuntimeState {
+ return { firstLoginToken: null, apiToken: null };
+}
diff --git a/packages/server/src/auth/service.ts b/packages/server/src/auth/service.ts
index 9096af9e..967520df 100644
--- a/packages/server/src/auth/service.ts
+++ b/packages/server/src/auth/service.ts
@@ -1,23 +1,20 @@
/**
- * Auth service: built-in admin seeding /
- * login / logout / password change / session validation.
+ * Auth service: admin seeding / login / logout / password change / session validation.
*
- * - No open registration: on startup, if there are no users at all, the built-in
- * admin `admin` is seeded with a random `penguin-<4 digits>` initial password
- * (printed once by the startup entrypoint; PENGUIN_SEED_ADMIN_PASSWORD injects
- * a fixed one for tests/e2e), and it adopts `default_project`; all other users
- * are created by an admin via the user backend (admin-service).
- * - An initial password (whether seeded or set by an admin) is flagged with
- * password_is_initial, which the frontend uses to prompt for a password change soon.
- * - Sessions: a 32-byte random token, with only its sha256 hash stored in the DB;
- * valid for 7 days, with sliding renewal once less than 6 days remain.
+ * No open registration: an empty users table seeds `admin` with a random password hashed and
+ * discarded unseen, claimed through the first-login link; every other user is created by an
+ * admin. Sessions are rows in auth_sessions (cookie holds the token, the row its sha256), so
+ * they outlive a restart and renew in place.
*/
-import { createHash, randomBytes, randomInt } from "node:crypto";
+import { randomBytes } from "node:crypto";
import { tokensEqual } from "./api-token.js";
import type { UserInfo } from "../api/types.js";
import { HttpError } from "../http/errors.js";
-import type { AuthSessionsRepo } from "../db/repos/auth-sessions.js";
import type { UserRow, UsersRepo } from "../db/repos/users.js";
+import { sessionTokenHash } from "../db/repos/auth-sessions.js";
+import type { SessionViaValue } from "../db/repos/auth-sessions.js";
+import type { AuthRuntimeState } from "./runtime-state.js";
+import type { AuthSessionsRepo } from "../db/repos/auth-sessions.js";
import { SCRYPT_COST, hashPassword, verifyPassword } from "./password.js";
export const MIN_PASSWORD_LENGTH = 8;
@@ -26,18 +23,11 @@ export const MIN_PASSWORD_LENGTH = 8;
export const ADMIN_USER_ID = "admin";
/**
- * Login throttling (per userId): the seeded initial password is `penguin-<4 digits>` —
- * 10,000 combinations — so unthrottled guessing would enumerate it in minutes. After
- * LOGIN_FREE_ATTEMPTS consecutive failures, the next attempt is admitted only after an
- * exponentially growing delay from the last failure (1s, 2s, … capped at 60s; attempts
- * inside the window are 429 `too_many_attempts` and do not extend it). Beyond ~40
- * failures that is one guess per minute, so the 10k space stops being enumerable, while
- * a legitimate user who mistyped a few times never waits more than the cap. A successful
- * login clears the counter. Counters are process memory (a restart clears them —
- * restarting is slower than waiting out the cap) and are kept for nonexistent userIds
- * too, so throttling is not an account-existence oracle. Known limit: a concurrent burst
- * can slip in before its first failure is recorded; the steady-state backoff still
- * dominates the search space.
+ * Login throttling, per userId. After LOGIN_FREE_ATTEMPTS failures each attempt waits an
+ * exponentially growing delay (1s doubling to a 60s cap), settling at a guess per minute.
+ * Kept for nonexistent userIds too, so it is not an account-existence oracle. Deliberately NOT
+ * covered: a concurrent burst before the first failure lands, and guesses spread across many
+ * accounts.
*/
const LOGIN_FREE_ATTEMPTS = 5;
const LOGIN_BACKOFF_START_MS = 1000;
@@ -45,27 +35,23 @@ const LOGIN_BACKOFF_CAP_MS = 60_000;
/** Failure entries idle longer than this are swept (bounds the map; far above the cap). */
const LOGIN_FAILURE_IDLE_MS = 15 * 60_000;
+/** Characters of base64url in a seeded password — 18 random bytes, 144 bits. */
+const SEED_PASSWORD_CHARS = 24;
+
/**
- * Random initial password for the seeded admin: `penguin-<4 digits>` — brand-related and
- * easy to type, shown once in the server startup output (the README, docs and login-page
- * hint all describe this form).
+ * Never read or typed — hashed at once and discarded — which is what lets it be long enough
+ * that the login endpoint, reachable the moment the account exists, has no search space.
*/
export function generateInitialAdminPassword(): string {
- return "penguin-" + String(randomInt(0, 10000)).padStart(4, "0");
-}
-
-function sha256Hex(value: string): string {
- return createHash("sha256").update(value).digest("hex");
+ return randomBytes(SEED_PASSWORD_CHARS).toString("base64url").slice(0, SEED_PASSWORD_CHARS);
}
/**
- * How a session was established: "password" via the login form, "desktop" via the
- * desktop shell's one-shot token, "token" via the local API token's Bearer header (no
- * stored session — the value is per request). Persisted per session (Bearer excepted) so
- * desktop-specific allowances (password change without the old password) apply only to
- * sessions the shell itself opened. Legacy rows (NULL) read as "password".
+ * "desktop" and "setup" may set a password without the old one (theirs is random and was never
+ * shown); desktop-only routes open to "desktop" alone. "token" is the local API token's Bearer
+ * header — per request, never a stored row. Anything else reads as "password".
*/
-export type SessionVia = "password" | "desktop" | "token";
+export type SessionVia = "password" | "desktop" | "setup" | "token";
export function toUserInfo(row: UserRow): UserInfo {
return {
@@ -79,60 +65,73 @@ export function toUserInfo(row: UserRow): UserInfo {
export interface AuthServiceDeps {
users: UsersRepo;
authSessions: AuthSessionsRepo;
+ /**
+ * Process-scoped auth values (runtime-state.ts). Held by the RUNTIME so the link a boot
+ * printed survives a platform push; everything else about auth is rebuilt with the App.
+ */
+ state: AuthRuntimeState;
/** Provisions the initial Project at signup (injected by project-service, to avoid a circular dependency). */
provisionInitialProject: (user: UserRow, isAdmin: boolean) => Promise<void>;
/** Fixed initial password for the seeded admin (config.seedAdminPassword); null generates a random one at seed time. */
seedAdminPassword: string | null;
- /**
- * Fired after any successful password update (self change / desktop set). The server
- * wires it to drop the stored initial-password plaintext once it goes stale (see
- * initial-password.ts); standalone/test constructions may omit it.
- */
- onPasswordChanged?: (userId: string) => void;
sessionTtlMs: number;
sessionRenewMs: number;
- /**
- * Test double: scrypt work factor for hashes this service writes. Omitted in
- * production, where {@link SCRYPT_COST} applies.
- */
+ /** Test double: scrypt work factor for hashes this service writes (SCRYPT_COST in production). */
passwordHashCost?: number;
now?: () => Date;
}
export class AuthService {
- /**
- * What a fresh user is provisioned with is business policy, answered by the CURRENT
- * App: the platform installs its answer at create over the claimed auth capability
- * (ordinary capability use, not a registry entry), and each swap's successor overwrites
- * it. Starts as the constructor-supplied fallback so standalone/test constructions
- * keep working unchanged.
- */
- private provisioner: (user: UserRow, isAdmin: boolean) => Promise<void>;
-
private readonly now: () => Date;
private readonly hashCost: number;
+ /** Session lifetime, for the cookie that must expire WITH the session, not before it. */
+ get sessionTtlMs(): number {
+ return this.deps.sessionTtlMs;
+ }
constructor(private readonly deps: AuthServiceDeps) {
- this.provisioner = deps.provisionInitialProject;
this.now = deps.now ?? (() => new Date());
this.hashCost = deps.passwordHashCost ?? SCRYPT_COST;
+ this.deps.authSessions.deleteExpired(this.now().toISOString());
+ }
+
+ /**
+ * Null once the server is claimed, so the only setup session that exists is a printed one.
+ * On demand rather than in the constructor: seedAdmin() runs after it, so "claimed?" has no
+ * answer there. A cached link whose row is gone is re-minted, not handed out dead.
+ */
+ mintFirstLogin(): string | null {
+ if (!this.adminPasswordIsInitial()) return null;
+ if (
+ this.deps.state.firstLoginToken !== null &&
+ this.authenticateWithMeta(this.deps.state.firstLoginToken) === null
+ ) {
+ this.deps.state.firstLoginToken = null;
+ }
+ this.deps.state.firstLoginToken ??= this.issueSession(ADMIN_USER_ID, "setup");
+ return this.deps.state.firstLoginToken;
}
/**
- * Startup seeding (idempotent): creates the built-in admin and adopts
- * default_project when the users table is empty; if the initial Project fails,
- * the user row is rolled back and the server retries on next startup.
- * Returns the initial password when it actually seeded — the caller prints it,
- * the only place a generated password is ever shown — and null when users
- * already exist.
+ * For the startup notice's pinned-seed gate (index.ts): a pin usually means the operator
+ * knows the password, but an offline reset makes it stale, and the gate must see through
+ * that or the rescue link stays suppressed.
*/
- async seedAdmin(): Promise<string | null> {
- if (this.deps.users.count() > 0) return null;
+ async adminPasswordIs(password: string): Promise<boolean> {
+ const row = this.deps.users.findById(ADMIN_USER_ID);
+ return row !== null && (await verifyPassword(password, row.passwordHash));
+ }
+
+ /**
+ * Startup seeding (idempotent): creates the built-in admin and adopts default_project when
+ * the users table is empty; if the initial Project fails, the user row is rolled back and
+ * the server retries on next startup.
+ */
+ async seedAdmin(): Promise<void> {
+ if (this.deps.users.count() > 0) return;
const password = this.deps.seedAdminPassword ?? generateInitialAdminPassword();
- // The override (PENGUIN_SEED_ADMIN_PASSWORD) must meet the same policy as every
- // other initial/reset password; rejecting it here, before any insert, keeps a
- // configuration typo from creating a trivially weak privileged account. Generated
- // passwords are always 12 characters and never trip this.
+ // A pinned override must meet the same policy as every other password — rejected before
+ // any insert, so a configuration typo cannot create a trivially weak privileged account.
if (password.length < MIN_PASSWORD_LENGTH) {
throw new Error(
`PENGUIN_SEED_ADMIN_PASSWORD must be at least ${MIN_PASSWORD_LENGTH} characters.`,
@@ -147,20 +146,25 @@ export class AuthService {
};
this.deps.users.insert(user);
try {
- await this.provisioner(user, true);
+ await this.deps.provisionInitialProject(user, true);
} catch (err) {
this.deps.users.delete(user.userId);
throw err;
}
- return password;
}
- /** Installs the current App's provisioning policy (see the `provisioner` field). */
- setProvisioner(provision: (user: UserRow, isAdmin: boolean) => Promise<void>): void {
- this.provisioner = provision;
+ /**
+ * Compared against the printed value, not merely verified: a cookie made out of ANY valid
+ * token would let one person hand another a link into the sender's account. Not single-use,
+ * because a prefetching browser would burn it before its reader clicked.
+ */
+ redeemFirstLogin(given: string): string | null {
+ const expected = this.deps.state.firstLoginToken;
+ if (expected === null || given === "" || !tokensEqual(given, expected)) return null;
+ return this.authenticateWithMeta(expected) === null ? null : expected;
}
- /** Whether the built-in admin still runs on its initial password (drives the startup reminder notice). */
+ /** Whether the built-in admin still runs on its initial password (gates the first-login link). */
adminPasswordIsInitial(): boolean {
return this.deps.users.findById(ADMIN_USER_ID)?.passwordIsInitial === true;
}
@@ -206,114 +210,124 @@ export class AuthService {
}
/**
- * Desktop-mode sign-in: issues an admin session WITHOUT a password check — the caller
- * (the desktop-login route) has already redeemed the shell's one-shot token, which is
- * the credential here. Throws if the admin has not been seeded yet (desktop-login runs
- * after startup seeding, so this only trips on a broken deployment).
+ * Desktop-mode sign-in: an admin session with no password check — the claim route already
+ * redeemed the shell's one-shot token, which is the credential here. Throws only on a
+ * broken deployment (seeding runs before the route exists).
*/
loginDesktop(): { user: UserInfo; token: string } {
const row = this.deps.users.findById(ADMIN_USER_ID);
if (!row) {
throw new HttpError(500, "internal", "Built-in admin has not been seeded.");
}
- this.deps.authSessions.deleteExpired(this.now().toISOString());
return { user: toUserInfo(row), token: this.issueSession(row.userId, "desktop") };
}
- /** Self password change (user settings): validates the old password, and on success clears the initial-password flag; the current session remains valid. */
+ /** Self password change (user settings): validates the old password first; the current session stays valid. */
async changePassword(userId: string, oldPassword: string, newPassword: string): Promise<void> {
const row = this.deps.users.findById(userId);
if (!row || !(await verifyPassword(oldPassword, row.passwordHash))) {
throw new HttpError(400, "password_mismatch", "Current password is incorrect.");
}
- if (newPassword.length < MIN_PASSWORD_LENGTH) {
- throw new HttpError(400, "invalid_password", "Password must be at least 8 characters.");
- }
- this.deps.users.updatePassword(userId, await hashPassword(newPassword, this.hashCost), false);
- this.deps.onPasswordChanged?.(userId);
+ await this.setPassword(userId, newPassword);
+ }
+
+ /** No old-password check; the me route gates which sessions may call this. */
+ async setInitialPassword(userId: string, newPassword: string): Promise<void> {
+ await this.setPassword(userId, newPassword);
}
/**
- * Desktop-session password set: no old-password check. Only reachable for sessions
- * established via desktop-login (the me route gates on sessionVia) — the seed password
- * of a desktop-created root is random and never shown, so its holder has nothing to
- * type into an old-password field; the shell's token already proved machine ownership.
+ * Validation comes FIRST, so a rejected password leaves the first-login link alive: burning
+ * it on a typo would strand the claimer until a restart.
*/
- async setPasswordDesktop(userId: string, newPassword: string): Promise<void> {
+ private async setPassword(userId: string, newPassword: string): Promise<void> {
if (newPassword.length < MIN_PASSWORD_LENGTH) {
throw new HttpError(400, "invalid_password", "Password must be at least 8 characters.");
}
this.deps.users.updatePassword(userId, await hashPassword(newPassword, this.hashCost), false);
- this.deps.onPasswordChanged?.(userId);
+ // A successful set proves at least what the successful login that resets the counter
+ // proves (the old password, or a desktop/setup session), so it resets it too. Without
+ // this, anyone spamming the login endpoint holds the backoff window open, and the sign-in
+ // that follows a first-login claim (routes/me.ts) would 429 AFTER the password committed —
+ // reporting failure for a change that took, with the claimer's setup session already gone.
+ this.loginFailures.delete(userId);
+ // EVERY first-login session for this account, not just the link this process printed: an
+ // earlier boot's link can still be live in a terminal scrollback, and a `setup` session is
+ // allowed to change the password without knowing the old one — so one left behind is an
+ // account takeover waiting to happen.
+ if (userId === ADMIN_USER_ID) {
+ this.deps.authSessions.deleteByUserAndVia(userId, "setup");
+ this.deps.state.firstLoginToken = null;
+ }
}
+ /** Ends a session: the row is the session, so logout deletes it. Unknown token is a no-op. */
logout(token: string): void {
- this.deps.authSessions.delete(sha256Hex(token));
+ this.deps.authSessions.delete(sessionTokenHash(token));
}
/**
- * The boot-scoped local API token (`<root>/api-token`, see auth/api-token.ts): held in
- * memory by the process that minted it. Null until the startup assembly installs it
- * (standalone/test constructions without one simply never authenticate a Bearer
- * header).
+ * The current boot's local API token (what control-env injection hands to tool
+ * subprocesses); null when none was minted. It lives on the runtime state, not on this
+ * service: the token was written to `<root>/api-token` by the process, so it must
+ * outlive the App a push replaces (auth/runtime-state.ts).
*/
- private apiToken: string | null = null;
-
- /** Installs the boot's local API token (called once by the startup assembly). */
- setLocalApiToken(token: string): void {
- this.apiToken = token;
- }
-
- /** The current boot's local API token (what control-env injection hands to tool subprocesses); null when none was installed. */
localApiToken(): string | null {
- return this.apiToken;
+ return this.deps.state.apiToken;
}
/**
* Validates a Bearer token against the boot's local API token (constant-time compare):
* a match authenticates as the built-in admin — holding the token proves filesystem
* access to the data root, which is admin authority (see auth/api-token.ts). Returns
- * null on mismatch, when no token is installed, or when the admin row is missing.
+ * null on mismatch, when no token was minted, or when the admin row is missing.
*/
authenticateApiToken(token: string): { user: UserRow; via: SessionVia } | null {
- if (this.apiToken === null || token.length === 0) return null;
- if (!tokensEqual(token, this.apiToken)) return null;
+ const apiToken = this.deps.state.apiToken;
+ if (apiToken === null || token.length === 0) return null;
+ if (!tokensEqual(token, apiToken)) return null;
const user = this.deps.users.findById(ADMIN_USER_ID);
return user === null ? null : { user, via: "token" };
}
- /** Validates the cookie token: returns null if expired/unknown; sliding renewal once less than 6 days remain. */
- authenticateWithMeta(token: string): { user: UserRow; via: SessionVia } | null {
- const tokenHash = sha256Hex(token);
+ /**
+ * Validates the cookie token. Sliding renewal tops the expiry up IN PLACE, so the cookie
+ * value never changes and there is no second identity to revoke. Only a session whose own
+ * span reaches the renewal window slides — a one-hour minted token must expire at its hour,
+ * not stretch by being used.
+ */
+ authenticateWithMeta(token: string): { user: UserRow; via: SessionVia; renewed: boolean } | null {
+ const tokenHash = sessionTokenHash(token);
const session = this.deps.authSessions.findByTokenHash(tokenHash);
if (!session) return null;
const now = this.now();
const expiresAt = Date.parse(session.expiresAt);
- if (!(expiresAt > now.getTime())) {
+ if (expiresAt <= now.getTime()) {
this.deps.authSessions.delete(tokenHash);
return null;
}
- if (expiresAt - now.getTime() < this.deps.sessionRenewMs) {
+ const user = this.deps.users.findById(session.userId);
+ if (!user) return null;
+ const renewable = expiresAt - Date.parse(session.createdAt) >= this.deps.sessionRenewMs;
+ let renewed = false;
+ if (renewable && expiresAt - now.getTime() < this.deps.sessionRenewMs) {
this.deps.authSessions.touch(
tokenHash,
new Date(now.getTime() + this.deps.sessionTtlMs).toISOString(),
);
+ renewed = true;
}
- const user = this.deps.users.findById(session.userId);
- if (!user) return null;
- return { user, via: session.via === "desktop" ? "desktop" : "password" };
+ const via: SessionVia =
+ session.via === "desktop" ? "desktop" : session.via === "setup" ? "setup" : "password";
+ return { user, via, renewed };
}
- private issueSession(userId: string, via: SessionVia): string {
- const token = randomBytes(32).toString("base64url");
- const now = this.now();
- this.deps.authSessions.insert({
- tokenHash: sha256Hex(token),
+ private issueSession(userId: string, via: SessionViaValue): string {
+ return this.deps.authSessions.issue({
userId,
- createdAt: now.toISOString(),
- expiresAt: new Date(now.getTime() + this.deps.sessionTtlMs).toISOString(),
via,
- });
- return token;
+ now: this.now(),
+ ttlMs: this.deps.sessionTtlMs,
+ }).token;
}
}
diff --git a/packages/server/src/config.ts b/packages/server/src/config.ts
index 1e1c29bc..36864edd 100644
--- a/packages/server/src/config.ts
+++ b/packages/server/src/config.ts
@@ -9,7 +9,6 @@
* detected to exist.
* Docs: /docs/configuration § "Environment variables".
*/
-import { randomBytes } from "node:crypto";
import fs from "node:fs";
import path from "node:path";
import { fileURLToPath } from "node:url";
@@ -41,20 +40,23 @@ export interface ServerConfig {
previewOrigin: string | null;
/**
* Fixed initial password for the seeded built-in admin (PENGUIN_SEED_ADMIN_PASSWORD),
- * used by automated tests and e2e; null (the norm) makes the seed generate a random
- * `penguin-<4 digits>` password, printed once to the server console. In desktop mode
- * an unpinned value resolves to a FULLY random password instead (never printed):
- * sign-in there goes through the shell's one-shot token, so nobody needs to read the
- * seed.
+ * used by automated tests and e2e. Null is the norm: the seed then generates a random
+ * password that is hashed and discarded unseen, and the account is claimed through the
+ * first-login link instead.
*/
seedAdminPassword: string | null;
- /** Login session validity period (7 days). */
+ /** Login session validity period (30 days). */
authSessionTtlMs: number;
- /** Sliding renewal threshold: if the remaining validity is below this value when validation succeeds, it's renewed to the full TTL (renews under 6 days). */
+ /**
+ * Sliding renewal threshold: a session validated with less than this much left is renewed to
+ * the full TTL. Set one day below the TTL, so any session used at least a day after it was
+ * issued renews — in practice a session in regular use never expires, and the TTL is the
+ * idle timeout.
+ */
authSessionRenewMs: number;
/**
* Desktop mode (PENGUIN_DESKTOP_TOKEN): the per-launch token minted by the desktop
- * shell. Non-null enables the one-shot desktop-login and Bearer-token shutdown
+ * shell. Non-null enables the one-shot claim link and the Bearer-token shutdown
* endpoints and requires a loopback HOST — desktop mode passes the token through a
* URL, which must never leave the machine.
*/
@@ -69,8 +71,11 @@ export interface ServerConfig {
* Trust `x-forwarded-proto` from the request (PENGUIN_TRUST_PROXY=1). Off by default:
* the header is caller-supplied, so on a non-loopback bind an untrusted caller could
* set it to `https` to walk through the hot-update network gate (hmr/routes.ts) while
- * actually speaking plaintext. Enable this only behind a reverse proxy that terminates
- * TLS and either sets or strips the header itself before it reaches this process.
+ * actually speaking plaintext — or get session cookies stamped `Secure` over plain HTTP,
+ * which the browser then never sends back (a sign-in that never takes). Enable this only
+ * behind a reverse proxy that terminates TLS and either sets or strips the header itself
+ * before it reaches this process; an HTTPS deployment that leaves it off issues session
+ * cookies WITHOUT the `Secure` flag (auth/middleware.ts cookieOptions).
*/
trustProxy: boolean;
}
@@ -133,15 +138,10 @@ export function resolveServerConfig(env: NodeJS.ProcessEnv = process.env): Serve
dbPath: env.PENGUIN_WEB_DB ?? path.join(root, "web.db"),
webDist: env.PENGUIN_WEB_DIST ?? defaultWebDist(),
previewOrigin: normalizePreviewOrigin(env.PENGUIN_PREVIEW_ORIGIN),
- // An empty/whitespace value is treated as unset (→ random seed password). Desktop
- // mode without a pinned value seeds a FULLY random password rather than the
- // printable penguin-<4 digits>: desktop sign-in goes through the shell's token, so
- // the seed never needs to be read — and index.ts deliberately does not print it.
- seedAdminPassword:
- env.PENGUIN_SEED_ADMIN_PASSWORD?.trim() ||
- (desktopToken !== null ? randomBytes(24).toString("base64url") : null),
- authSessionTtlMs: 7 * DAY_MS,
- authSessionRenewMs: 6 * DAY_MS,
+ // An empty/whitespace value is treated as unset, which leaves the seed to generate one.
+ seedAdminPassword: env.PENGUIN_SEED_ADMIN_PASSWORD?.trim() || null,
+ authSessionTtlMs: 30 * DAY_MS,
+ authSessionRenewMs: 29 * DAY_MS,
desktopToken,
portFile: env.PENGUIN_PORT_FILE?.trim() || null,
trustProxy: env.PENGUIN_TRUST_PROXY === "1",
diff --git a/packages/server/src/db/database.ts b/packages/server/src/db/database.ts
index 9842e714..a29f56df 100644
--- a/packages/server/src/db/database.ts
+++ b/packages/server/src/db/database.ts
@@ -15,6 +15,23 @@ import { SCHEMA_SQL } from "./schema.js";
// recognize this experimental module).
const sqlite = process.getBuiltinModule("node:sqlite");
+/**
+ * Opens an EXISTING database for a narrow write, without running any schema work.
+ *
+ * `openDatabase` migrates — CREATE TABLE, six ensureColumn calls, a DROP INDEX and a backfill.
+ * That is right for the process that owns the database and wrong for a short-lived CLI writing
+ * one row (`penguin auth token`): after `penguin update` the CLI on disk can be NEWER than the
+ * running server, and migrating under a live server's prepared statements is not something a
+ * token mint should do. The caller has already established that the file exists.
+ */
+export function openExistingDatabase(dbPath: string): DatabaseSync {
+ const db = new sqlite.DatabaseSync(dbPath);
+ db.exec("PRAGMA foreign_keys = ON;");
+ // Wait for the live server's write lock instead of failing SQLITE_BUSY at once.
+ db.exec("PRAGMA busy_timeout = 5000;");
+ return db;
+}
+
/** Open (creating if necessary) the database: ensure the parent directory exists, set PRAGMAs, run table creation. */
export function openDatabase(dbPath: string): DatabaseSync {
if (dbPath !== ":memory:") {
@@ -22,6 +39,9 @@ export function openDatabase(dbPath: string): DatabaseSync {
}
const db = new sqlite.DatabaseSync(dbPath);
db.exec("PRAGMA journal_mode = WAL;");
+ // A second connection (the CLI minting a token while the server runs) waits for the write
+ // lock rather than failing SQLITE_BUSY at once.
+ db.exec("PRAGMA busy_timeout = 5000;");
db.exec("PRAGMA foreign_keys = ON;");
db.exec(SCHEMA_SQL);
// Columns added to the schema after a web.db was formed: CREATE TABLE IF NOT EXISTS never
@@ -31,6 +51,8 @@ export function openDatabase(dbPath: string): DatabaseSync {
ensureColumn(db, "sessions", "has_trace", "INTEGER NOT NULL DEFAULT 0");
ensureColumn(db, "sessions", "fork_count", "INTEGER NOT NULL DEFAULT 0");
ensureColumn(db, "sessions", "thinking_level", "TEXT");
+ // A v0.2.0 web.db has auth_sessions without `via`; CREATE TABLE IF NOT EXISTS never adds a
+ // column, so every INSERT would fail "no column named via" until this runs.
ensureColumn(db, "auth_sessions", "via", "TEXT");
ensureColumn(db, "trace_files", "page_stats", "TEXT");
ensureColumn(db, "messaging_bindings", "line_per_message", "INTEGER NOT NULL DEFAULT 0");
diff --git a/packages/server/src/db/repos/auth-sessions.ts b/packages/server/src/db/repos/auth-sessions.ts
index 94d34829..743e5f38 100644
--- a/packages/server/src/db/repos/auth-sessions.ts
+++ b/packages/server/src/db/repos/auth-sessions.ts
@@ -1,22 +1,58 @@
/**
- * auth_sessions table repo (server-side sessions backing the HttpOnly cookie).
- *
- * Stores only the sha256(token) hex hash; the raw token appears only in the cookie.
+ * auth_sessions table repo (server-side sessions backing the HttpOnly cookie). Stores only
+ * sha256(token); the raw token appears only in the cookie. `issue()` is the ONE minting point,
+ * so a CLI-minted row cannot drift from one the server issues itself.
*/
+import { createHash, randomBytes } from "node:crypto";
import type { DatabaseSync } from "node:sqlite";
+/** How a session was established, as stored. NULL on rows formed before the column existed. */
+export type SessionViaValue = "password" | "desktop" | "setup" | "cli";
+
export interface AuthSessionRow {
tokenHash: string;
userId: string;
createdAt: string;
expiresAt: string;
- /** How the session was established ("password" | "desktop"); null on rows formed before the column existed (treated as "password"). */
- via: string | null;
+ via: SessionViaValue | null;
+}
+
+/** sha256 hex of a raw session token — the only form the database ever holds. */
+export function sessionTokenHash(token: string): string {
+ return createHash("sha256").update(token).digest("hex");
}
export class AuthSessionsRepo {
constructor(private readonly db: DatabaseSync) {}
+ /**
+ * Mints a session and returns the raw token for a cookie or the terminal. `maxTtlMs` caps a
+ * caller-supplied lifetime (`--ttl-seconds`): one longer than an ordinary session would make
+ * a leaked token file outlive every other credential, sliding forever. Expired rows are
+ * swept here too, so a cron that only mints does not accumulate them.
+ */
+ issue(opts: {
+ userId: string;
+ via: SessionViaValue;
+ now: Date;
+ ttlMs: number;
+ maxTtlMs?: number;
+ }): { token: string; expiresAt: string } {
+ const ttlMs = Math.max(1_000, Math.min(opts.ttlMs, opts.maxTtlMs ?? opts.ttlMs));
+ const token = randomBytes(32).toString("base64url");
+ const createdAt = opts.now.toISOString();
+ const expiresAt = new Date(opts.now.getTime() + ttlMs).toISOString();
+ this.deleteExpired(createdAt);
+ this.insert({
+ tokenHash: sessionTokenHash(token),
+ userId: opts.userId,
+ createdAt,
+ expiresAt,
+ via: opts.via,
+ });
+ return { token, expiresAt };
+ }
+
insert(row: AuthSessionRow): void {
this.db
.prepare(
@@ -33,7 +69,7 @@ export class AuthSessionsRepo {
userId: r.user_id as string,
createdAt: r.created_at as string,
expiresAt: r.expires_at as string,
- via: (r.via as string | null) ?? null,
+ via: (r.via as SessionViaValue | null) ?? null,
};
}
@@ -57,4 +93,13 @@ export class AuthSessionsRepo {
deleteByUser(userId: string): void {
this.db.prepare("DELETE FROM auth_sessions WHERE user_id = ?").run(userId);
}
+
+ /**
+ * Clear a user's sessions of one kind. Used to end EVERY first-login session when a password
+ * is set: an earlier boot's link may still be live in someone's scrollback, and a `setup`
+ * session may change the password without knowing the old one.
+ */
+ deleteByUserAndVia(userId: string, via: SessionViaValue): void {
+ this.db.prepare("DELETE FROM auth_sessions WHERE user_id = ? AND via = ?").run(userId, via);
+ }
}
diff --git a/packages/server/src/db/schema.ts b/packages/server/src/db/schema.ts
index 58f700ec..b3161dff 100644
--- a/packages/server/src/db/schema.ts
+++ b/packages/server/src/db/schema.ts
@@ -20,13 +20,21 @@ CREATE TABLE IF NOT EXISTS users (
password_is_initial INTEGER NOT NULL DEFAULT 0, -- 1=initial password (seeded/admin-set); cleared once the user changes it
created_at TEXT NOT NULL
);
+-- Server-side sessions backing the HttpOnly cookie: the cookie carries a 32-byte random
+-- token, the row stores only its sha256. A session outlives a restart (it is on disk), which
+-- is why the model is a row and not a signed statement.
CREATE TABLE IF NOT EXISTS auth_sessions (
token_hash TEXT PRIMARY KEY, -- sha256(token) hex; the cookie stores only the raw token
user_id TEXT NOT NULL REFERENCES users(user_id) ON DELETE CASCADE,
created_at TEXT NOT NULL,
- expires_at TEXT NOT NULL, -- 7-day sliding renewal (topped up when <6 days remain)
- via TEXT -- 'password' | 'desktop'; NULL = legacy row (password)
+ expires_at TEXT NOT NULL, -- 30-day sliding renewal, topped up in place when <29 days remain
+ via TEXT -- 'password'|'desktop'|'setup'|'cli'; NULL = legacy (password)
);
+-- deleteExpired runs on every login and mint, deleteByUser on every admin reset; without
+-- these both scan the whole table.
+CREATE INDEX IF NOT EXISTS idx_auth_sessions_expires ON auth_sessions(expires_at);
+CREATE INDEX IF NOT EXISTS idx_auth_sessions_user ON auth_sessions(user_id);
+
CREATE TABLE IF NOT EXISTS projects (
project_id TEXT PRIMARY KEY, -- directory name doubles as id; display name lives in project_config.toml
owner_user_id TEXT NOT NULL REFERENCES users(user_id),
diff --git a/packages/server/src/hmr/README.md b/packages/server/src/hmr/README.md
index c2d55aa8..a431a5ae 100644
--- a/packages/server/src/hmr/README.md
+++ b/packages/server/src/hmr/README.md
@@ -1,7 +1,7 @@
# The runtime layer — mechanism only
-This directory is the heart of the **runtime**: the layer that boots, transports, authenticates
-and hot-swaps everything else. Read this before changing anything here (or in
+This directory is the heart of the **runtime**: the layer that boots, transports and hot-swaps
+everything else. Read this before changing anything here (or in
`packages/desktop/`, or in core's environment tooling — the other runtime homes).
## The four layers
@@ -18,8 +18,15 @@ and hot-swaps everything else. Read this before changing anything here (or in
**The runtime carries mechanism. It must not carry policy.**
Mechanism is the machinery that is the same no matter what the product does: HTTP transport,
-SSE channels, authentication and the network gate, the kernel's park → migrate → boot swap,
-the resource registry, artifact storage and the atomic `harness.json` commit.
+SSE channels, the network gate, the kernel's park → migrate → boot swap, the resource registry,
+artifact storage and the atomic `harness.json` commit.
+
+Authentication is NOT on that list, and used to be. Who may set a password, how long a session
+lasts, how logins are throttled — that is policy, and a runtime that owned it made every auth
+fix wait for a full reinstall: a platform naming a member an older runtime's AuthService lacked
+was refused at the handshake. The App builds its own AuthService now (app.ts's buildAppDeps).
+What the runtime still publishes is `runtime:auth-state`, the process-scoped values a push must
+not forget — the state layer, not a capability.
Policy is everything a deployment might reasonably want to change: business APIs, what an agent
sees, what a command does, how a capability behaves. Policy belongs in the **platform**, which is
diff --git a/packages/server/src/hmr/capabilities.ts b/packages/server/src/hmr/capabilities.ts
index b60b7e87..b83c1318 100644
--- a/packages/server/src/hmr/capabilities.ts
+++ b/packages/server/src/hmr/capabilities.ts
@@ -23,7 +23,8 @@
import type { DatabaseSync } from "node:sqlite";
import type { Resources } from "@prismshadow/penguin-core/kernel";
import type { ServerConfig } from "../config.js";
-import type { AuthService } from "../auth/service.js";
+import type { AuthRuntimeState } from "../auth/runtime-state.js";
+import { newAuthRuntimeState } from "../auth/runtime-state.js";
import type { ChannelHub } from "../runtime/channel.js";
import type { ProxySettings } from "../net/proxy.js";
import type { BuildDepsOverrides } from "../app.js";
@@ -85,7 +86,6 @@ interface RuntimeInterfaces extends Interfaces {
family: string;
config: MembersOf<ServerConfig>;
db: MembersOf<DatabaseSync>;
- auth: MembersOf<AuthService>;
channels: MembersOf<ChannelHub>;
proxy: MembersOf<ProxyControl>;
hmr: MembersOf<HmrHost>;
@@ -109,17 +109,6 @@ export const RUNTIME_INTERFACES: RuntimeInterfaces = {
"trustProxy",
],
db: ["prepare", "exec", "close"],
- auth: [
- "authenticateWithMeta",
- "seedAdmin",
- "adminPasswordIsInitial",
- "login",
- "logout",
- "changePassword",
- "loginDesktop",
- "setPasswordDesktop",
- "setProvisioner",
- ],
channels: ["get", "peek", "broadcast", "dispose", "setActivityProbe"],
proxy: [],
hmr: ["resources", "ensure", "resolveWebSource", "assetsDir", "dispose"],
@@ -177,7 +166,14 @@ export function lacksMembers(value: unknown, need: readonly string[]): string[]
export const RUNTIME_CONFIG_RESOURCE_ID = "runtime:config";
export const RUNTIME_DB_RESOURCE_ID = "runtime:db";
-export const RUNTIME_AUTH_RESOURCE_ID = "runtime:auth-service";
+/**
+ * Process-scoped auth STATE (auth/runtime-state.ts), not an auth service: authentication is
+ * business behaviour the platform builds for itself, so it ships by push. Only the values that
+ * must ride across a swap and die at a restart live here. Claimed optionally — a runtime older
+ * than this resource simply gives the platform a fresh holder, which costs one reprint of the
+ * first-login link and nothing else.
+ */
+export const RUNTIME_AUTH_STATE_RESOURCE_ID = "runtime:auth-state";
export const RUNTIME_CHANNELS_RESOURCE_ID = "runtime:channels";
export const RUNTIME_PROXY_RESOURCE_ID = "runtime:proxy-control";
export const RUNTIME_HMR_RESOURCE_ID = "runtime:hmr-host";
@@ -210,7 +206,7 @@ export const RESOURCE_IFACES_RESOURCE_ID = "resource-interfaces";
* the current App — it is `hmr.ensure()`'s instance — and everything it needs from the
* business side is an in-process member on that instance's api (`business()`,
* `shutdown()`, `drained()`) or a hook the App installs over a claimed capability
- * (ChannelHub.setActivityProbe, AuthService.setProvisioner). A "current App" pointer in
+ * (ChannelHub.setActivityProbe). A "current App" pointer in
* the registry was a duplicate of the host's own instance field, and the registry should
* carry only what has no other channel: resources, capabilities, and the contract
* declarations about them.
@@ -223,7 +219,8 @@ export type ProxyControl = (settings: ProxySettings) => void;
export interface RuntimeCapabilities {
config: ServerConfig;
db: DatabaseSync;
- authService: AuthService;
+ /** Process-scoped auth values; the AuthService itself is built per App (see buildAppDeps). */
+ authState: AuthRuntimeState;
channels: ChannelHub;
proxyControl: ProxyControl;
hmr: HmrHost;
@@ -274,23 +271,30 @@ export function claimRuntimeCapabilities(resources: Resources): RuntimeClaim {
if (mismatch !== null) return { kind: "refused", reason: mismatch };
const config = resources.claim<ServerConfig>(RUNTIME_CONFIG_RESOURCE_ID);
const db = resources.claim<DatabaseSync>(RUNTIME_DB_RESOURCE_ID);
- const authService = resources.claim<AuthService>(RUNTIME_AUTH_RESOURCE_ID);
const channels = resources.claim<ChannelHub>(RUNTIME_CHANNELS_RESOURCE_ID);
const proxyControl = resources.claim<ProxyControl>(RUNTIME_PROXY_RESOURCE_ID);
const hmr = resources.claim<HmrHost>(RUNTIME_HMR_RESOURCE_ID);
- if (!config || !db || !authService || !channels || !proxyControl || !hmr) {
+ if (!config || !db || !channels || !proxyControl || !hmr) {
return { kind: "refused", reason: "a declared capability was not actually published" };
}
// Desktop is nullable by meaning, so it sits outside the all-present check.
const desktop = resources.claim<DesktopService | null>(RUNTIME_DESKTOP_RESOURCE_ID) ?? null;
const overrides = resources.claim<BuildDepsOverrides>(RUNTIME_OVERRIDES_RESOURCE_ID) ?? {};
+ // Optional by design (see the resource's own note): an older runtime published no such
+ // holder, and a fresh one is a correct, slightly forgetful substitute. A runtime older
+ // than this platform may also publish a holder missing the fields added since; they are
+ // filled IN PLACE, never by copying — the bag is shared with the runtime by identity, and
+ // a copy would strand every write the App makes to it.
+ const authState =
+ resources.claim<AuthRuntimeState>(RUNTIME_AUTH_STATE_RESOURCE_ID) ?? newAuthRuntimeState();
+ authState.firstLoginToken ??= null;
+ authState.apiToken ??= null;
// …then the objects themselves. A descriptor is a claim about what is there; this is
// the part that checks it, so an honest-but-wrong runtime is caught here rather than at
// the first call site. `desktop` is exempt when null — that is a value, not a shortfall.
const live: Array<[string, unknown]> = [
["config", config],
["db", db],
- ["auth", authService],
["channels", channels],
["proxy", proxyControl],
["hmr", hmr],
@@ -306,6 +310,6 @@ export function claimRuntimeCapabilities(resources: Resources): RuntimeClaim {
}
return {
kind: "claimed",
- caps: { config, db, authService, channels, proxyControl, hmr, desktop, overrides },
+ caps: { config, db, authState, channels, proxyControl, hmr, desktop, overrides },
};
}
diff --git a/packages/server/src/hmr/platform.ts b/packages/server/src/hmr/platform.ts
index 56c2c951..d5dda402 100644
--- a/packages/server/src/hmr/platform.ts
+++ b/packages/server/src/hmr/platform.ts
@@ -188,10 +188,6 @@ export const platformImpl: Impl<PlatformApi, PlatformCtx> = {
// and must not adopt them. It does not dispose them either: that happens at the
// commit below, so a failed boot leaves them for the recovered predecessor.
terminals.adopt(doomedGroups.includes("terminal") ? [] : (context.terminals ?? []));
- // Ordinary code over the claimed capability (see terminal/identity.ts): the resolver
- // wraps caps.authService, the same object the business routes authenticate with. A
- // bare kernel has no auth — terminals stay fail-closed there.
- const identity = identityFrom(caps?.authService ?? null);
// The extension seam (see ../extension/index.ts): the definition view first, then the
// instance context, with the workflows built in between — so an extension that registers
// one always sees it instantiated in the App it registered into. The host is CLAIMED
@@ -238,21 +234,20 @@ export const platformImpl: Impl<PlatformApi, PlatformCtx> = {
});
}
+ // Ordinary code over this App's own auth (terminal/identity.ts): the same object the
+ // business routes authenticate with. A bare kernel has none — terminals stay fail-closed.
+ const identity = identityFrom(deps?.authService ?? null);
+
// ONE app, ONE pointer: every route this App serves — terminal group and business
// groups — registers into a single Hono table, and the swap publishes deps + table +
// wrap-up as a single registry write, so no reader can observe a half-swapped pair.
const app = createApp(deps, terminals, identity);
const business = deps;
- // The runtime's two mid-request needs of the CURRENT App are hooks installed over the
- // claimed capabilities — ordinary capability use, overwrite-only across swaps (a dead
- // generation's hook is replaced, never removed, so nothing ever un-installs a
- // successor's): "is this session busy" for channel sweep, and "what does a fresh user
- // get" for login provisioning.
+ // The runtime's one mid-request need of the CURRENT App is a hook installed over a
+ // claimed capability — overwrite-only across swaps, so a dead generation's hook is
+ // replaced and never removed: "is this session busy" for the channel sweep.
if (caps !== null && business !== null) {
caps.channels.setActivityProbe((key) => business.manager.statusOf(key) !== "idle");
- caps.authService.setProvisioner((user, isAdmin) =>
- business.projectService.provisionInitialProject(user, isAdmin),
- );
}
// PARK — the App's complete resource inventory, split by fate. Everything stateful
// this App creates is on one of these three lists; a new resource must pick its list
diff --git a/packages/server/src/hmr/routes.ts b/packages/server/src/hmr/routes.ts
index 677b1be1..37c5042a 100644
--- a/packages/server/src/hmr/routes.ts
+++ b/packages/server/src/hmr/routes.ts
@@ -34,7 +34,7 @@ export function hmrRoutes(deps: AppDeps): Hono<AppEnv> {
// does its own auth (admin cookie only — see the network gate above for the
// other half) rather than relying on the generic middleware being mounted
// later.
- const cookieAuth = authMiddleware(deps.authService);
+ const cookieAuth = authMiddleware(deps.authService, deps.config.trustProxy);
routes.use("*", async (c, next) => {
// Dangerous-network off: hot APIs load and run code, so on a non-loopback
diff --git a/packages/server/src/http/routes/auth.ts b/packages/server/src/http/routes/auth.ts
index 9047d4db..289dd834 100644
--- a/packages/server/src/http/routes/auth.ts
+++ b/packages/server/src/http/routes/auth.ts
@@ -1,29 +1,20 @@
/**
- * Auth routes: POST /api/auth/login | logout, GET /api/auth/desktop-login (desktop mode).
+ * Auth routes: POST /api/auth/login | logout, GET /api/auth/claim.
* No self-registration: users are created by an admin in the user backend (/api/admin/users).
- * Login issues a cookie session; logout deletes the server-side session and clears the cookie.
+ * Login issues a cookie session; logout deletes its row and clears the cookie.
+ *
+ * `claim` is the one password-free entry, and answers a browser with no session yet: only the
+ * server can set an HttpOnly cookie, hence a GET that redirects rather than a call.
*/
import { Hono } from "hono";
import { deleteCookie, getCookie, setCookie } from "hono/cookie";
import type { AuthResponse } from "../../api/types.js";
import { HttpError } from "../errors.js";
-import { SESSION_COOKIE } from "../../auth/middleware.js";
+import { SESSION_COOKIE, cookieOptions } from "../../auth/middleware.js";
import type { AppEnv } from "../../auth/middleware.js";
import { readJson, requireString } from "../validate.js";
import type { AppDeps } from "../../app.js";
-/** Session cookie attributes: HttpOnly, SameSite=Lax, 7 days. */
-function cookieOptions(c: { req: { header(name: string): string | undefined } }) {
- return {
- httpOnly: true,
- sameSite: "Lax" as const,
- path: "/",
- maxAge: 7 * 24 * 60 * 60,
- // Add Secure when the reverse proxy declares https.
- ...(c.req.header("x-forwarded-proto") === "https" ? { secure: true } : {}),
- };
-}
-
export function authRoutes(deps: AppDeps): Hono<AppEnv> {
const app = new Hono<AppEnv>();
@@ -32,7 +23,12 @@ export function authRoutes(deps: AppDeps): Hono<AppEnv> {
const userId = requireString(body, "userId", { label: "userId" });
const password = requireString(body, "password", { label: "password" });
const { user, token } = await deps.authService.login(userId, password);
- setCookie(c, SESSION_COOKIE, token, cookieOptions(c));
+ setCookie(
+ c,
+ SESSION_COOKIE,
+ token,
+ cookieOptions(c, deps.authService.sessionTtlMs, deps.config.trustProxy),
+ );
return c.json({ user } satisfies AuthResponse);
});
@@ -43,20 +39,29 @@ export function authRoutes(deps: AppDeps): Hono<AppEnv> {
return c.body(null, 204);
});
- // Desktop-mode sign-in: the window's FIRST navigation redeems the shell's one-shot
- // token for a standard admin cookie session and lands on the app — the desktop user
- // never sees the login page. 404 outside desktop mode (the route "doesn't exist");
- // a wrong or already-used token is a plain 401 with no distinction, so a leaked URL
- // reveals nothing and cannot be replayed.
- app.get("/desktop-login", (c) => {
- const desktop = deps.desktop;
- if (!desktop) throw new HttpError(404, "not_found", "Desktop mode is not enabled.");
+ /**
+ * Two proofs, expiring differently: the desktop shell's token is spent on first use, while
+ * the first-login link keeps working until a password exists — a link a mail client may
+ * prefetch cannot afford to be one-shot, and until then the account protects nothing.
+ * Both fail with the same 401, so a caller learns nothing about which it got wrong.
+ */
+ app.get("/claim", (c) => {
const token = c.req.query("token") ?? "";
- if (token === "" || !desktop.redeemLoginToken(token)) {
- throw new HttpError(401, "unauthorized", "Invalid or already-used desktop token.");
+ // Desktop first, and only it consumes on success: a first-login value handed to the
+ // shell's redeemer is simply not its token, so nothing is spent looking.
+ const session =
+ token !== "" && deps.desktop?.redeemLoginToken(token) === true
+ ? deps.authService.loginDesktop().token
+ : deps.authService.redeemFirstLogin(token);
+ if (session === null) {
+ throw new HttpError(401, "unauthorized", "Invalid or already-used sign-in link.");
}
- const { token: session } = deps.authService.loginDesktop();
- setCookie(c, SESSION_COOKIE, session, cookieOptions(c));
+ setCookie(
+ c,
+ SESSION_COOKIE,
+ session,
+ cookieOptions(c, deps.authService.sessionTtlMs, deps.config.trustProxy),
+ );
return c.redirect("/", 302);
});
diff --git a/packages/server/src/http/routes/me.ts b/packages/server/src/http/routes/me.ts
index f0ddc570..68245e61 100644
--- a/packages/server/src/http/routes/me.ts
+++ b/packages/server/src/http/routes/me.ts
@@ -6,8 +6,10 @@
* carrying user-authored text is validated and capped on the way in (draftShortcuts).
*/
import { Hono } from "hono";
+import { setCookie } from "hono/cookie";
import type { MeResponse, PrefsResponse, UiPrefs } from "../../api/types.js";
import { toUserInfo } from "../../auth/service.js";
+import { SESSION_COOKIE, cookieOptions } from "../../auth/middleware.js";
import type { AppEnv } from "../../auth/middleware.js";
import { readJson, requireString } from "../validate.js";
import type { AppDeps } from "../../app.js";
@@ -53,15 +55,28 @@ export function meRoutes(deps: AppDeps): Hono<AppEnv> {
});
// Self-service password change (user settings): validates the old password; on success, the initial-password prompt disappears from GET /api/me.
- // Desktop sessions may omit oldPassword: the seed password of a desktop-created root is
- // random and never shown, so its holder has nothing to type — the shell's redeemed
- // token already proved machine ownership.
+ // Two kinds of session may omit oldPassword, because for them there is no old password to
+ // know — the account's current one is random and was never shown: the desktop shell's own
+ // window, and a session claimed through this boot's first-login link.
app.put("/password", async (c) => {
const body = await readJson(c);
const newPassword = requireString(body, "newPassword", { label: "newPassword" });
const desktopSession = deps.desktop !== null && c.var.sessionVia === "desktop";
- if (desktopSession && body.oldPassword === undefined) {
- await deps.authService.setPasswordDesktop(c.var.user.userId, newPassword);
+ const setupSession = c.var.sessionVia === "setup";
+ if ((desktopSession || setupSession) && body.oldPassword === undefined) {
+ await deps.authService.setInitialPassword(c.var.user.userId, newPassword);
+ // Claiming deletes every first-login session, this request's included, so without a
+ // replacement the next call 401s and a brand-new user lands back on the login page.
+ // Signed in with the password just set: an ordinary login, not a session given on trust.
+ if (setupSession) {
+ const { token } = await deps.authService.login(c.var.user.userId, newPassword);
+ setCookie(
+ c,
+ SESSION_COOKIE,
+ token,
+ cookieOptions(c, deps.authService.sessionTtlMs, deps.config.trustProxy),
+ );
+ }
} else {
const oldPassword = requireString(body, "oldPassword", { label: "oldPassword" });
await deps.authService.changePassword(c.var.user.userId, oldPassword, newPassword);
diff --git a/packages/server/src/index.ts b/packages/server/src/index.ts
index 4da4f108..db8fd349 100644
--- a/packages/server/src/index.ts
+++ b/packages/server/src/index.ts
@@ -22,12 +22,7 @@ import { serve } from "@hono/node-server";
import { bootAppDeps, createRuntimeApp, type AppDeps } from "./app.js";
import { ADMIN_USER_ID } from "./auth/service.js";
import { resolveServerConfig, type ServerConfig } from "./config.js";
-import {
- clearInitialAdminPassword,
- readInitialAdminPassword,
- renderInitialPasswordNotice,
- storeInitialAdminPassword,
-} from "./initial-password.js";
+import { clearInitialAdminPassword, renderFirstLoginNotice } from "./initial-password.js";
import { applyProxySettings, installGlobalProxyDispatcher } from "./net/proxy.js";
import { ExtensionHost } from "./extension/host.js";
import { loadExtensions } from "./extension/loader.js";
@@ -65,6 +60,9 @@ async function main(): Promise<void> {
* read without a null check from the step after the one that assigns them.
*/
class PenguinServer {
+ /** Set at seed when this server still has no admin password; printed once the port is known. */
+ private pendingFirstLoginNotice = false;
+
/** Assigned by readConfig(); every later step reads it. */
private config!: ServerConfig;
/** Assigned by loadExtensions(); published to the platform tree by buildDeps(). */
@@ -179,32 +177,29 @@ class PenguinServer {
/**
* Built-in admin seed (idempotent): creates admin and adopts default_project when the
- * users table is empty. The returned initial password (random unless pinned via
- * PENGUIN_SEED_ADMIN_PASSWORD) is persisted in the data root while it remains the
- * initial one, and EVERY startup re-prints the framed reminder until the password is
- * changed (any password update for admin removes the file — see initial-password.ts).
- * Never printed (or persisted) in desktop mode: the seed there is fully random by design
- * (config.ts) and sign-in goes through the shell's one-shot token, so showing it would
- * only leak a credential into a log nobody needs.
+ * users table is empty. The seed password is random, hashed, and discarded — nobody ever
+ * sees it — so a server that still has no admin password of its own prints a one-time
+ * sign-in LINK instead, carrying this boot's first-login token. The notice re-prints on
+ * every start until a password is set, because the link is regenerated every start.
+ *
+ * Nothing is printed in desktop mode: the shell's own window signs in through its one-shot
+ * token, so a link in a log would be a credential nobody needs. Nothing is printed either
+ * when the pinned PENGUIN_SEED_ADMIN_PASSWORD is still the admin's actual password — the
+ * operator knows it. The pin alone is not enough: an offline reset-admin-password replaces
+ * the password with an unknowable one while the pin stays configured, and the rescue flow
+ * IS this link, so the gate verifies the pin against the hash rather than trusting it.
+ *
+ * The sweep runs unconditionally: a root carried over from a build that stored the
+ * plaintext must not keep holding it (see initial-password.ts).
*/
async seedAdmin(): Promise<void> {
- const seededPassword = await this.deps.authService.seedAdmin();
+ await this.deps.authService.seedAdmin();
+ clearInitialAdminPassword(this.config.root);
if (this.config.desktopToken !== null) return;
- if (seededPassword !== null) {
- storeInitialAdminPassword(this.config.root, seededPassword);
- }
- if (this.deps.authService.adminPasswordIsInitial()) {
- const initialPassword = seededPassword ?? readInitialAdminPassword(this.config.root);
- // Roots seeded before the password was persisted have no file: stay silent — the
- // plaintext is unrecoverable, and a reminder with nothing to type is pure nagging.
- if (initialPassword !== null) {
- console.log(renderInitialPasswordNotice(ADMIN_USER_ID, initialPassword));
- }
- } else {
- // Heal: the flag was cleared while the file survived (e.g. the password was changed
- // under a build that predates the file) — a stale plaintext must not outlive it.
- clearInitialAdminPassword(this.config.root);
- }
+ if (!this.deps.authService.adminPasswordIsInitial()) return;
+ const pinned = this.config.seedAdminPassword;
+ if (pinned !== null && (await this.deps.authService.adminPasswordIs(pinned))) return;
+ this.pendingFirstLoginNotice = true;
}
/**
@@ -290,6 +285,20 @@ class PenguinServer {
if (this.config.host === "127.0.0.1" || this.config.host === "localhost") {
this.openIpv6Loopback(port);
}
+ // Last, so the link is what a console is left showing rather than something scrolled
+ // past — and here rather than in seedAdmin() because the URL needs the port the OS
+ // actually handed out, which PORT=0 only settles at this point.
+ if (this.pendingFirstLoginNotice) {
+ // Minting here rather than at seed time is what keeps "exists" and "was printed" the
+ // same thing for a setup session: the modes that decline to print never ask for one.
+ const link = this.deps.authService.mintFirstLogin();
+ if (link !== null) {
+ const token = encodeURIComponent(link);
+ console.log(
+ renderFirstLoginNotice(`http://${this.appHost()}:${port}/api/auth/claim?token=${token}`),
+ );
+ }
+ }
}
/**
@@ -298,6 +307,10 @@ class PenguinServer {
* only 302s back here for App routes (see the canonical-host guard in app.ts).
*/
private appHost(): string {
+ // A wildcard bind is not an address anyone can open — `http://0.0.0.0:<port>` fails in a
+ // browser. Whoever reads this console is on the machine, where `localhost` reaches it;
+ // someone connecting from elsewhere substitutes the host they use to reach this box.
+ if (this.config.host === "0.0.0.0" || this.config.host === "::") return "localhost";
return loopbackHostRoles(this.config.host)?.app ?? this.config.host;
}
diff --git a/packages/server/src/initial-password.ts b/packages/server/src/initial-password.ts
index b05554f7..02e5e062 100644
--- a/packages/server/src/initial-password.ts
+++ b/packages/server/src/initial-password.ts
@@ -1,24 +1,4 @@
-/**
- * Initial-admin-password persistence (`<root>/initial-admin-password`) and the startup
- * reminder notice.
- *
- * The seeded admin password used to be printed exactly once, at first seed; if that line
- * scrolled away unread, the credential was unrecoverable. The plaintext is now kept in
- * the data root FOR AS LONG AS the admin password remains the initial one, so every
- * server start — and `penguin web` attaching to an already-running instance — can
- * re-print it inside a hard-to-miss ASCII frame together with the change-it reminder.
- *
- * The file is removed the moment the admin's password is updated by any path (self
- * change, desktop set, or an admin reset picking a new value — the reset re-arms the
- * initial FLAG, but the file's content would be stale, and an admin-chosen password is
- * never persisted). Only the auto-generated / PENGUIN_SEED_ADMIN_PASSWORD seed value is
- * ever stored, with owner-only permissions; the SQLite db next to it already holds
- * strictly more sensitive data. Legacy roots seeded before this file existed simply have
- * no file: the reminder then stays silent (the plaintext is genuinely unrecoverable).
- *
- * Published as `@prismshadow/penguin-server/initial-password` (side-effect-free, like
- * ./lock) so the CLI can print the same notice when it attaches to a live instance.
- */
+/** The framed first-run notice carrying the first-login link (minted in auth/service.ts). */
import fs from "node:fs";
import path from "node:path";
@@ -26,26 +6,11 @@ export function initialAdminPasswordPath(root: string): string {
return path.join(root, "initial-admin-password");
}
-/** Persists the seeded plaintext (owner-only file). Best-effort: the seed itself must not fail on an exotic filesystem — the reminder just degrades to first-start-only. */
-export function storeInitialAdminPassword(root: string, password: string): void {
- try {
- fs.writeFileSync(initialAdminPasswordPath(root), `${password}\n`, { mode: 0o600 });
- } catch {
- // e.g. a read-only root: the password was still printed once by the seed path.
- }
-}
-
-/** The stored plaintext, or null when absent/unreadable/empty. */
-export function readInitialAdminPassword(root: string): string | null {
- try {
- const value = fs.readFileSync(initialAdminPasswordPath(root), "utf8").trim();
- return value === "" ? null : value;
- } catch {
- return null;
- }
-}
-
-/** Removes the stored plaintext (idempotent, best-effort). */
+/**
+ * Removes the plaintext an older build stored here; nothing writes it any more.
+ *
+ * TODO(compat): goes once no supported upgrade path can carry an `initial-admin-password`.
+ */
export function clearInitialAdminPassword(root: string): void {
try {
fs.rmSync(initialAdminPasswordPath(root), { force: true });
@@ -54,22 +19,19 @@ export function clearInitialAdminPassword(root: string): void {
}
}
-/** Interior padding (spaces) between the frame bars and the text on each side. */
const NOTICE_PADDING = 3;
/**
- * The framed reminder block, ready for console.log. Plain ASCII (`+`/`-`/`|`) rather
- * than box-drawing characters: the server may run under terminals and log collectors
- * with non-UTF-8 code pages (legacy Windows consoles above all), and a misrendered frame
- * would bury exactly the line it exists to highlight. Width follows the longest line, so
- * a long pinned password widens the frame instead of breaking it.
+ * Plain ASCII rather than box-drawing characters: a non-UTF-8 console (legacy Windows above
+ * all) would mangle the frame around exactly the line it exists to highlight.
*/
-export function renderInitialPasswordNotice(userId: string, password: string): string {
+export function renderFirstLoginNotice(url: string): string {
const lines = [
- `Web sign-in: ${userId} / ${password}`,
+ "This server has no admin password yet. Open this link to claim it:",
+ "",
+ ` ${url}`,
"",
- "This is the initial password and it has not been changed yet.",
- "Please sign in and change it soon (user menu -> Change password).",
+ "The link lasts 30 days or until a password is set; restarting prints a fresh one.",
];
const width = Math.max(...lines.map((line) => line.length));
const bar = `+${"-".repeat(width + NOTICE_PADDING * 2)}+`;
diff --git a/packages/server/src/reset-admin-password.ts b/packages/server/src/reset-admin-password.ts
index b23271a2..f5245647 100644
--- a/packages/server/src/reset-admin-password.ts
+++ b/packages/server/src/reset-admin-password.ts
@@ -1,33 +1,19 @@
/**
- * Offline admin-password reset — the rescue path when the Web admin password is
- * forgotten (`penguin server reset-admin-password`).
- *
- * The admin can reset every OTHER user from the user-management page, but nobody can
- * reset the admin itself once its password is lost: the plaintext file in the data root
- * only survives while the password is still the initial one. This module closes that
- * gap from the machine that owns the data root: it re-arms the whole initial-password
- * machinery — a fresh `penguin-<4 digits>` password flagged password_is_initial, the
- * plaintext stored via initial-password.ts so every server start re-prints the framed
- * reminder until the password is changed, and all of the admin's login sessions
- * cleared (matching an admin-initiated reset).
- *
- * web.db is single-process / single-writer (see db/database.ts and lock.ts), so the
- * reset refuses while a live server owns the root: the caller tells the user to stop it
- * first. Requiring local filesystem access is the authorization model — whoever can run
- * this already owns the SQLite database sitting next to the file it writes.
- *
- * Published as `@prismshadow/penguin-server/reset-admin-password` (side-effect-free,
- * like ./lock) so the CLI can run the reset without importing the package entry, which
- * starts listening.
+ * Offline rescue for a forgotten admin password — nobody can reset the admin from the web UI,
+ * so this does it from the machine that owns the data root (local filesystem access IS the
+ * authorization). The account goes back to unclaimed and the next start prints a first-login
+ * link, so no plaintext is produced for anyone to write down. Refuses while a server is live,
+ * web.db being single-writer. Exported as `@prismshadow/penguin-server/reset-admin-password`
+ * so the CLI need not import the package entry, which starts listening.
*/
import fs from "node:fs";
import path from "node:path";
import { hashPassword } from "./auth/password.js";
import { ADMIN_USER_ID, generateInitialAdminPassword } from "./auth/service.js";
import { openDatabase } from "./db/database.js";
-import { AuthSessionsRepo } from "./db/repos/auth-sessions.js";
import { UsersRepo } from "./db/repos/users.js";
-import { storeInitialAdminPassword } from "./initial-password.js";
+import { AuthSessionsRepo } from "./db/repos/auth-sessions.js";
+import { clearInitialAdminPassword } from "./initial-password.js";
import { liveServerLock } from "./lock.js";
import type { ServerLock } from "./lock.js";
@@ -38,13 +24,10 @@ export type ResetAdminPasswordResult =
| { outcome: "no_database"; dbPath: string }
/** Nothing to reset: the database exists but the admin was never seeded. */
| { outcome: "no_admin" }
- | { outcome: "reset"; password: string };
+ /** Returned to the unclaimed state: start the server and open the first-login link it prints. */
+ | { outcome: "reset" };
-/**
- * Resets the built-in admin to a fresh initial password. `dbPath` defaults to the
- * root's `web.db`; callers honoring PENGUIN_WEB_DB pass the resolved path (the
- * plaintext reminder file always lives in `root`, matching the server's own layout).
- */
+/** `dbPath` may be elsewhere (PENGUIN_WEB_DB); `root` stays the root, which the sweep needs. */
export async function resetAdminPassword(
root: string,
dbPath: string = path.join(root, "web.db"),
@@ -58,11 +41,12 @@ export async function resetAdminPassword(
try {
const users = new UsersRepo(db);
if (users.findById(ADMIN_USER_ID) === null) return { outcome: "no_admin" };
+ // Discarded unread: a value nobody holds cannot be typed, phished, or left in a buffer.
const password = generateInitialAdminPassword();
users.updatePassword(ADMIN_USER_ID, await hashPassword(password), true);
new AuthSessionsRepo(db).deleteByUser(ADMIN_USER_ID);
- storeInitialAdminPassword(root, password);
- return { outcome: "reset", password };
+ clearInitialAdminPassword(root);
+ return { outcome: "reset" };
} finally {
db.close();
}
diff --git a/packages/server/src/secret-file.ts b/packages/server/src/secret-file.ts
new file mode 100644
index 00000000..a22e14cc
--- /dev/null
+++ b/packages/server/src/secret-file.ts
@@ -0,0 +1,23 @@
+/**
+ * Writes a bearer secret to a 0600 file, refusing to follow a symlink parked at the path:
+ * someone who can write the directory but not read the file could otherwise redirect the write
+ * into a file they CAN read. Hence unlink + exclusive create, and chmod on the fd rather than
+ * the path. Exported as `@prismshadow/penguin-server/secret-file` so the CLI shares it.
+ */
+import fs from "node:fs";
+
+export function writeSecretFile(filePath: string, contents: string): void {
+ fs.rmSync(filePath, { force: true });
+ const flags =
+ fs.constants.O_WRONLY |
+ fs.constants.O_CREAT |
+ fs.constants.O_EXCL |
+ (fs.constants.O_NOFOLLOW ?? 0);
+ const fd = fs.openSync(filePath, flags, 0o600);
+ try {
+ fs.fchmodSync(fd, 0o600);
+ fs.writeSync(fd, contents);
+ } finally {
+ fs.closeSync(fd);
+ }
+}
diff --git a/packages/server/src/services/admin-service.ts b/packages/server/src/services/admin-service.ts
index 81221b11..66e2416b 100644
--- a/packages/server/src/services/admin-service.ts
+++ b/packages/server/src/services/admin-service.ts
@@ -12,10 +12,10 @@
*/
import type { UserInfo } from "../api/types.js";
import { HttpError } from "../http/errors.js";
-import { MIN_PASSWORD_LENGTH, toUserInfo } from "../auth/service.js";
+import { ADMIN_USER_ID, MIN_PASSWORD_LENGTH, toUserInfo } from "../auth/service.js";
import { SCRYPT_COST, hashPassword } from "../auth/password.js";
-import type { AuthSessionsRepo } from "../db/repos/auth-sessions.js";
import type { ProjectsRepo } from "../db/repos/projects.js";
+import type { AuthSessionsRepo } from "../db/repos/auth-sessions.js";
import type { UserRow, UsersRepo } from "../db/repos/users.js";
import { SEMANTIC_ID_RULE, USERNAME_PATTERN } from "./ids.js";
import type { ProjectService } from "./project-service.js";
@@ -25,13 +25,6 @@ export interface AdminServiceDeps {
authSessions: AuthSessionsRepo;
projects: ProjectsRepo;
projectService: ProjectService;
- /**
- * Fired after a password reset. The server wires it to drop the stored
- * initial-password plaintext once it goes stale (a reset re-arms the initial FLAG,
- * but with an admin-chosen value the stored seed no longer matches — see
- * initial-password.ts); test constructions may omit it.
- */
- onPasswordChanged?: (userId: string) => void;
/**
* Test double: scrypt work factor for hashes this service writes. Omitted in
* production, where {@link SCRYPT_COST} applies.
@@ -85,7 +78,13 @@ export class AdminService {
return toUserInfo(user);
}
- /** Reset another user's password: flags it as initial and clears all their sessions (prompts a password change on next login). */
+ /**
+ * Reset a user's password and clear all their sessions (prompts a password change on next
+ * login). Only an admin reaches this route, so `userId === admin` is the admin resetting
+ * ITSELF: it chose a KNOWN password, which is a claimed state — not the unclaimed one the
+ * first-login link exists for — so the initial flag stays off and no link is re-opened.
+ * Every other user gets the flag, to be prompted to change the password their admin picked.
+ */
async resetPassword(userId: string, password: string): Promise<void> {
if (!this.deps.users.findById(userId)) {
throw new HttpError(404, "user_not_found", `User does not exist: ${userId}.`);
@@ -93,9 +92,14 @@ export class AdminService {
if (password.length < MIN_PASSWORD_LENGTH) {
throw new HttpError(400, "invalid_password", "Password must be at least 8 characters.");
}
- this.deps.users.updatePassword(userId, await hashPassword(password, this.hashCost), true);
+ const isSelfAdminReset = userId === ADMIN_USER_ID;
+ this.deps.users.updatePassword(
+ userId,
+ await hashPassword(password, this.hashCost),
+ !isSelfAdminReset,
+ );
+ // Force re-login: delete every session row for this user.
this.deps.authSessions.deleteByUser(userId);
- this.deps.onPasswordChanged?.(userId);
}
/** Delete user: the built-in admin cannot be deleted; owned Projects (including data directories) are deleted along with it. */
@@ -110,6 +114,6 @@ export class AdminService {
for (const project of this.deps.projects.listByOwner(userId)) {
await this.deps.projectService.destroyProject(project.projectId);
}
- this.deps.users.delete(userId); // auth_sessions / project_members / ui_prefs cascade-deleted
+ this.deps.users.delete(userId); // project_members / ui_prefs cascade-deleted
}
}
diff --git a/packages/server/src/services/desktop-service.ts b/packages/server/src/services/desktop-service.ts
index c00a5359..f85b1762 100644
--- a/packages/server/src/services/desktop-service.ts
+++ b/packages/server/src/services/desktop-service.ts
@@ -3,7 +3,7 @@
* with a per-launch random token, which backs two endpoints with different consumption
* rules:
*
- * - `GET /api/auth/desktop-login?token=…` — ONE-SHOT: the window's first navigation
+ * - `GET /api/auth/claim?token=…` — ONE-SHOT: the window's first navigation
* redeems the token for a standard admin cookie session; every later attempt fails,
* so a leaked URL cannot be replayed.
* - `POST /api/desktop/shutdown` (Authorization: Bearer <token>) — REUSABLE for the
diff --git a/packages/server/test/admin-users.test.ts b/packages/server/test/admin-users.test.ts
index 192858e4..e9d145b9 100644
--- a/packages/server/test/admin-users.test.ts
+++ b/packages/server/test/admin-users.test.ts
@@ -99,6 +99,20 @@ describe("admin users backend", () => {
expect(again.user.passwordIsInitial).toBe(true);
});
+ it("the admin resetting ITSELF chooses a known password: claimed, no first-login link", async () => {
+ // Only an admin reaches this route, so resetting `admin` is a self-reset with a KNOWN
+ // password — a claimed state, not the unclaimed one the setup link exists for. Leaving
+ // the initial flag on would re-open the link on the next restart (reviewer's repro).
+ expect(
+ (await admin.post("/api/admin/users/admin/password", { password: "chosen-admin-1" })).status,
+ ).toBe(204);
+ expect(t.deps.authService.adminPasswordIsInitial()).toBe(false);
+ // mintFirstLogin gates on the initial flag, so no link is offered.
+ expect(t.deps.authService.mintFirstLogin()).toBeNull();
+ const back = await loginUser(t.app, "admin", "chosen-admin-1");
+ expect(back.user.passwordIsInitial).toBe(false);
+ });
+
it("user deletion: owned Projects (with directories) and memberships removed", async () => {
const gone = await provisionUser(t.app, "gone");
const goneApi = apiClient(t.app, gone.cookie);
diff --git a/packages/server/test/auth-sessions.test.ts b/packages/server/test/auth-sessions.test.ts
new file mode 100644
index 00000000..27a75c8c
--- /dev/null
+++ b/packages/server/test/auth-sessions.test.ts
@@ -0,0 +1,182 @@
+/**
+ * Sessions as rows in auth_sessions (auth/service.ts): the cookie carries a random token, the
+ * row stores its sha256. Every property the row model is chosen FOR is pinned here — a session
+ * survives a restart (it is on disk), logout deletes the row, an admin reset deletes the
+ * user's rows, and sliding renewal tops the expiry up IN PLACE so the cookie value never
+ * changes and a short minted token never stretches into a long one.
+ */
+import path from "node:path";
+import { describe, expect, it } from "vitest";
+import { SESSION_COOKIE } from "../src/auth/middleware.js";
+import { apiClient, cookieFrom, createTestApp, loginAdmin, makeTempRoot } from "./helpers.js";
+
+const DAY_MS = 24 * 60 * 60 * 1000;
+/** The session TTL test apps are built with (helpers.ts) — fixtures derive from it, not from literals. */
+const TEST_SESSION_TTL_MS = 30 * DAY_MS;
+
+describe("auth sessions", () => {
+ /**
+ * A v0.2.0 web.db has auth_sessions WITHOUT the `via` column, and CREATE TABLE IF NOT EXISTS
+ * never adds one — so without the ensureColumn migration every login, first-login mint and
+ * `penguin auth token` on an upgraded database fails "no column named via".
+ */
+ it("upgrades a v0.2.0 database that has auth_sessions without `via`", async () => {
+ const root = await makeTempRoot();
+ const p = path.join(root, "web.db");
+ const sqlite = process.getBuiltinModule("node:sqlite");
+ const legacy = new sqlite.DatabaseSync(p);
+ legacy.exec(
+ "CREATE TABLE auth_sessions (token_hash TEXT PRIMARY KEY, user_id TEXT, created_at TEXT, expires_at TEXT)",
+ );
+ legacy.close();
+
+ const t = await createTestApp({ config: { root, dbPath: p } });
+ try {
+ const cols = (
+ t.deps.db.prepare("PRAGMA table_info(auth_sessions)").all() as { name: string }[]
+ ).map((c) => c.name);
+ expect(cols).toContain("via");
+ // And the whole login path works on it.
+ const { cookie } = await loginAdmin(t.app);
+ expect((await apiClient(t.app, cookie).get("/api/me")).status).toBe(200);
+ } finally {
+ await t.cleanup();
+ }
+ });
+
+ it("survives a restart, because the session is a row on disk", async () => {
+ const root = await makeTempRoot();
+ const config = { root, dbPath: `${root}/web.db` };
+ const t = await createTestApp({ config });
+ let cookie: string;
+ try {
+ cookie = (await loginAdmin(t.app)).cookie;
+ expect((await apiClient(t.app, cookie).get("/api/me")).status).toBe(200);
+ } finally {
+ await t.cleanup();
+ }
+ // A new process on the same database: the row is still there, so the cookie still works —
+ // a restart does not sign everyone out.
+ const reborn = await createTestApp({ config });
+ try {
+ expect((await apiClient(reborn.app, cookie).get("/api/me")).status).toBe(200);
+ } finally {
+ await reborn.cleanup();
+ }
+ });
+
+ it("logout deletes the row, and it stays deleted across a restart", async () => {
+ const root = await makeTempRoot();
+ const config = { root, dbPath: `${root}/web.db` };
+ const t = await createTestApp({ config });
+ let cookie: string;
+ try {
+ cookie = (await loginAdmin(t.app)).cookie;
+ await apiClient(t.app, cookie).post("/api/auth/logout");
+ expect((await apiClient(t.app, cookie).get("/api/me")).status).toBe(401);
+ } finally {
+ await t.cleanup();
+ }
+ const reborn = await createTestApp({ config });
+ try {
+ expect((await apiClient(reborn.app, cookie).get("/api/me")).status).toBe(401);
+ } finally {
+ await reborn.cleanup();
+ }
+ });
+
+ it("expired rows are swept on login", async () => {
+ let nowMs = Date.now();
+ const t = await createTestApp({ now: () => new Date(nowMs) });
+ try {
+ await loginAdmin(t.app);
+ const rows = () =>
+ Number(
+ (t.deps.db.prepare("SELECT COUNT(*) AS n FROM auth_sessions").get() as { n: unknown }).n,
+ );
+ expect(rows()).toBe(1);
+ // Past the TTL, the row is dead weight; the next login sweeps it (and adds its own).
+ nowMs += TEST_SESSION_TTL_MS + DAY_MS;
+ await loginAdmin(t.app);
+ expect(rows()).toBe(1);
+ } finally {
+ await t.cleanup();
+ }
+ });
+
+ it("an admin password reset deletes the user's sessions", async () => {
+ const t = await createTestApp();
+ try {
+ const admin = apiClient(t.app, (await loginAdmin(t.app)).cookie);
+ await admin.post("/api/admin/users", { userId: "alice", password: "alice-pass-1" });
+ const login = await t.app.request("/api/auth/login", {
+ method: "POST",
+ headers: { "content-type": "application/json" },
+ body: JSON.stringify({ userId: "alice", password: "alice-pass-1" }),
+ });
+ const aliceCookie = cookieFrom(login);
+ expect((await apiClient(t.app, aliceCookie).get("/api/me")).status).toBe(200);
+
+ await t.deps.adminService.resetPassword("alice", "fresh-pass-1");
+ expect((await apiClient(t.app, aliceCookie).get("/api/me")).status).toBe(401);
+ } finally {
+ await t.cleanup();
+ }
+ });
+
+ it("slides a long session in place, so the cookie value never changes", async () => {
+ let nowMs = Date.now();
+ const t = await createTestApp({ now: () => new Date(nowMs) });
+ try {
+ const cookie = (await loginAdmin(t.app)).cookie;
+ const token = cookie.split("=").slice(1).join("=");
+ // Two days in, past the renewal threshold (29 days): the request tops up the expiry and
+ // refreshes the cookie, but the token VALUE is unchanged — same session, longer life.
+ nowMs += 2 * DAY_MS;
+ const res = await apiClient(t.app, cookie).get("/api/me");
+ expect(res.status).toBe(200);
+ const refreshed = cookieFrom(res);
+ expect(refreshed).toBe(`${SESSION_COOKIE}=${token}`);
+ // The DB expiry moved forward to now+TTL.
+ const row = t.deps.db.prepare("SELECT expires_at FROM auth_sessions LIMIT 1").get() as {
+ expires_at: string;
+ };
+ expect(Date.parse(row.expires_at)).toBeGreaterThan(nowMs + TEST_SESSION_TTL_MS - DAY_MS);
+ } finally {
+ await t.cleanup();
+ }
+ });
+
+ it("a short cli token expires at its hour rather than renewing", async () => {
+ // A cli token spans an hour, well under the renewal window, so being used must not top it
+ // up to the full term. Insert one directly (as `penguin auth token` does) and use it.
+ let nowMs = Date.now();
+ const t = await createTestApp({ now: () => new Date(nowMs) });
+ try {
+ const { createHash, randomBytes } = await import("node:crypto");
+ const token = randomBytes(32).toString("base64url");
+ const hash = createHash("sha256").update(token).digest("hex");
+ t.deps.db
+ .prepare(
+ "INSERT INTO auth_sessions (token_hash, user_id, created_at, expires_at, via) VALUES (?,?,?,?,?)",
+ )
+ .run(
+ hash,
+ "admin",
+ new Date(nowMs).toISOString(),
+ new Date(nowMs + 60 * 60_000).toISOString(),
+ "cli",
+ );
+ const res = await apiClient(t.app, `${SESSION_COOKIE}=${token}`).get("/api/me");
+ expect(res.status).toBe(200);
+ // No renewal cookie, and the expiry did not move to the full term.
+ expect(res.headers.get("set-cookie")).toBeNull();
+ const row = t.deps.db
+ .prepare("SELECT expires_at FROM auth_sessions WHERE token_hash = ?")
+ .get(hash) as { expires_at: string };
+ expect(Date.parse(row.expires_at)).toBe(nowMs + 60 * 60_000);
+ } finally {
+ await t.cleanup();
+ }
+ });
+});
diff --git a/packages/server/test/auth-token.test.ts b/packages/server/test/auth-token.test.ts
new file mode 100644
index 00000000..a24b3ac8
--- /dev/null
+++ b/packages/server/test/auth-token.test.ts
@@ -0,0 +1,100 @@
+/**
+ * Minting an API session from the data root (auth-token.ts).
+ *
+ * A session is a row in web.db, so minting opens the database and inserts one — no running
+ * server, no owner token, no loopback. Reading the root already reaches every credential the
+ * token could, so the write adds no authority; the row is a `cli` session the server honors
+ * on its next request.
+ */
+import path from "node:path";
+import { describe, expect, it } from "vitest";
+import { CLI_TOKEN_MAX_TTL_MS, mintApiToken } from "../src/auth-token.js";
+import { SESSION_COOKIE } from "../src/auth/middleware.js";
+import { apiClient, createTestApp, makeTempRoot } from "./helpers.js";
+
+describe("minting an API session", () => {
+ it("reports no_server when the root has no web.db", async () => {
+ const root = await makeTempRoot();
+ expect(mintApiToken(root, { dbPath: path.join(root, "web.db") })).toEqual({
+ outcome: "no_server",
+ });
+ });
+
+ it("inserts a session row the server then authenticates", async () => {
+ const root = await makeTempRoot();
+ const dbPath = path.join(root, "web.db");
+ // Seed the account by booting an app on this file, then mint against the same file as the
+ // CLI would — the app and the mint share one on-disk database, no cross-process hop.
+ const t = await createTestApp({ config: { root, dbPath } });
+ try {
+ const minted = mintApiToken(root, { dbPath, ttlMs: 60_000 });
+ expect(minted.outcome).toBe("minted");
+ if (minted.outcome !== "minted") return;
+ expect(minted.userId).toBe("admin");
+ expect(
+ (await apiClient(t.app, `${SESSION_COOKIE}=${minted.token}`).get("/api/me")).status,
+ ).toBe(200);
+ } finally {
+ await t.cleanup();
+ }
+ });
+
+ /**
+ * The multi-user case: web.db exists but belongs to another OS account (the one running the
+ * server), and this caller cannot open it. That must come back as a failed outcome pointing
+ * at `auth login` — not an unhandled throw. chmod-based, so meaningless as root or on
+ * Windows.
+ */
+ it.skipIf(process.platform === "win32" || process.getuid?.() === 0)(
+ "fails cleanly on a database this OS account cannot open",
+ async () => {
+ const root = await makeTempRoot();
+ const dbPath = path.join(root, "web.db");
+ const t = await createTestApp({ config: { root, dbPath } });
+ await t.cleanup();
+ const fs = await import("node:fs");
+ fs.chmodSync(dbPath, 0o000);
+ try {
+ const r = mintApiToken(root, { dbPath });
+ expect(r.outcome).toBe("failed");
+ if (r.outcome !== "failed") return;
+ expect(r.detail).toContain("penguin auth login");
+ } finally {
+ fs.chmodSync(dbPath, 0o600);
+ }
+ },
+ );
+
+ /**
+ * A caller-supplied lifetime must not exceed an ordinary session's. `--ttl-seconds` only
+ * rejects values <= 0, so without the clamp `penguin auth token --ttl-seconds 315360000`
+ * writes a ten-year row — and because its span passes the renewal window it would slide
+ * forever, turning a leaked cli-session.json into a permanent credential.
+ */
+ it("clamps a caller's TTL to the session ceiling", async () => {
+ const root = await makeTempRoot();
+ const dbPath = path.join(root, "web.db");
+ const t = await createTestApp({ config: { root, dbPath } });
+ try {
+ const now = new Date();
+ const r = mintApiToken(root, { dbPath, ttlMs: 10 * 365 * 24 * 60 * 60_000, now });
+ expect(r.outcome).toBe("minted");
+ if (r.outcome !== "minted") return;
+ expect(Date.parse(r.expiresAt)).toBe(now.getTime() + CLI_TOKEN_MAX_TTL_MS);
+ } finally {
+ await t.cleanup();
+ }
+ });
+
+ it("refuses an account that does not exist", async () => {
+ const root = await makeTempRoot();
+ const dbPath = path.join(root, "web.db");
+ const t = await createTestApp({ config: { root, dbPath } });
+ try {
+ const r = mintApiToken(root, { dbPath, userId: "ghost" });
+ expect(r.outcome).toBe("failed");
+ } finally {
+ await t.cleanup();
+ }
+ });
+});
diff --git a/packages/server/test/auth.test.ts b/packages/server/test/auth.test.ts
index 8501ee2f..b33555e5 100644
--- a/packages/server/test/auth.test.ts
+++ b/packages/server/test/auth.test.ts
@@ -67,9 +67,11 @@ describe("auth", () => {
await expect(
fs.access(path.join(t.root, "default_project", "agents", "default_agent", "agent_state")),
).resolves.toBeUndefined();
- // Seeding is idempotent: re-seeding returns null and does not create a duplicate account.
- expect(await t.deps.authService.seedAdmin()).toBeNull();
+ // Seeding is idempotent: re-seeding neither duplicates the account nor rerolls its
+ // password — the original still signs in.
+ await t.deps.authService.seedAdmin();
expect(t.deps.db.prepare("SELECT COUNT(*) AS n FROM users").get()?.n).toBe(1);
+ await loginAdmin(t.app);
});
it("admin-created: default Project is <userId>-default_project, name defaults", async () => {
@@ -150,6 +152,33 @@ describe("auth", () => {
await loginUser(t.app, "dave", "new-password-1");
});
+ it("ignores x-forwarded-proto for the Secure flag unless the proxy is trusted", async () => {
+ // Caller-supplied, and untrusted by default (the stance hmr/routes.ts states). Trusting
+ // it would let anyone who can reach a plain-HTTP port make the server hand out a Secure
+ // cookie the browser then refuses to send back over that same connection.
+ const login = await t.app.request("/api/auth/login", {
+ method: "POST",
+ headers: { "content-type": "application/json", "x-forwarded-proto": "https" },
+ body: JSON.stringify({ userId: "admin", password: TEST_ADMIN_PASSWORD }),
+ });
+ expect(login.status).toBe(200);
+ expect(login.headers.get("set-cookie")).not.toContain("Secure");
+
+ // With the deployment opting in, the same header is honored.
+ const trusting = await createTestApp({ config: { trustProxy: true } });
+ try {
+ const res = await trusting.app.request("/api/auth/login", {
+ method: "POST",
+ headers: { "content-type": "application/json", "x-forwarded-proto": "https" },
+ body: JSON.stringify({ userId: "admin", password: TEST_ADMIN_PASSWORD }),
+ });
+ expect(res.status).toBe(200);
+ expect(res.headers.get("set-cookie")).toContain("Secure");
+ } finally {
+ await trusting.cleanup();
+ }
+ });
+
it("write requests reject non-JSON Content-Type (CSRF defense)", async () => {
const res = await t.app.request("/api/auth/login", {
method: "POST",
@@ -171,30 +200,6 @@ describe("auth", () => {
expect(got.prefs.theme).toBe("dark");
});
- it("seedAdmin without an injected password generates penguin-<4 digits> and returns it", async () => {
- // Bypass the fixed test password: null matches the production default (random generation).
- const fresh = await createTestApp({ config: { seedAdminPassword: null } });
- try {
- expect(fresh.adminPassword).toMatch(/^penguin-\d{4}$/);
- // The returned password is the one that actually logs in.
- await loginUser(fresh.app, "admin", fresh.adminPassword);
- // Users exist now: re-seeding reports that nothing was seeded.
- expect(await fresh.deps.authService.seedAdmin()).toBeNull();
- } finally {
- await fresh.cleanup();
- }
- });
-
- it("seedAdmin honors the injected seedAdminPassword", async () => {
- const fresh = await createTestApp({ config: { seedAdminPassword: "penguin-7777" } });
- try {
- expect(fresh.adminPassword).toBe("penguin-7777");
- await loginUser(fresh.app, "admin", "penguin-7777");
- } finally {
- await fresh.cleanup();
- }
- });
-
it("seedAdmin rejects an override below the password policy before creating the account", async () => {
const root = await makeTempRoot();
const deps = await bootAppDeps(
@@ -260,10 +265,23 @@ describe("auth", () => {
}
});
- it("generateInitialAdminPassword matches penguin-<4 digits>", () => {
- for (let i = 0; i < 32; i++) {
- expect(generateInitialAdminPassword()).toMatch(/^penguin-\d{4}$/);
+ it("adminPasswordIs verifies the pin against the hash, not the config", async () => {
+ // Sole consumer is the startup notice gate: a pinned seed normally silences the
+ // first-login link, but an offline reset makes the pin stale — the gate must notice.
+ expect(await t.deps.authService.adminPasswordIs(TEST_ADMIN_PASSWORD)).toBe(true);
+ expect(await t.deps.authService.adminPasswordIs("not-the-password")).toBe(false);
+ });
+
+ it("generateInitialAdminPassword is 24 base64url characters, and never repeats", () => {
+ const seen = new Set<string>();
+ for (let i = 0; i < 64; i++) {
+ const password = generateInitialAdminPassword();
+ expect(password).toMatch(/^[A-Za-z0-9_-]{24}$/);
+ seen.add(password);
}
+ // Drawn from randomBytes, not from a small printable space that a login endpoint could
+ // be walked through.
+ expect(seen.size).toBe(64);
});
it("PUT prefs shallow-merges without clobbering other writers' fields", async () => {
diff --git a/packages/server/test/config.test.ts b/packages/server/test/config.test.ts
index 254d439a..eeb9fffe 100644
--- a/packages/server/test/config.test.ts
+++ b/packages/server/test/config.test.ts
@@ -32,14 +32,12 @@ describe("resolveServerConfig: PORT parsing", () => {
});
describe("resolveServerConfig: desktop-mode seed password", () => {
- it("desktop mode without a pinned value generates a fully random seed password", () => {
- const a = resolveServerConfig({ ...base, PENGUIN_DESKTOP_TOKEN: "tok" }).seedAdminPassword;
- const b = resolveServerConfig({ ...base, PENGUIN_DESKTOP_TOKEN: "tok" }).seedAdminPassword;
- expect(a).not.toBeNull();
- // base64url of 24 random bytes: far beyond the printable penguin-<4 digits> space.
- expect(a!.length).toBeGreaterThanOrEqual(24);
- expect(a).not.toMatch(/^penguin-\d{4}$/);
- expect(a).not.toBe(b);
+ it("desktop mode leaves the seed unpinned, exactly like every other mode", () => {
+ // Nothing pins it: the password the seed generates on its own is already unguessable, so
+ // supplying one here would just be a second way to say the same thing.
+ expect(
+ resolveServerConfig({ ...base, PENGUIN_DESKTOP_TOKEN: "tok" }).seedAdminPassword,
+ ).toBeNull();
});
it("an explicit PENGUIN_SEED_ADMIN_PASSWORD still wins in desktop mode", () => {
@@ -52,7 +50,7 @@ describe("resolveServerConfig: desktop-mode seed password", () => {
).toBe("penguin-2026");
});
- it("outside desktop mode the unpinned value stays null (random penguin-<4 digits> at seed time)", () => {
+ it("outside desktop mode the unpinned value stays null (the seed generates one)", () => {
expect(resolveServerConfig({ ...base }).seedAdminPassword).toBeNull();
});
});
diff --git a/packages/server/test/desktop.test.ts b/packages/server/test/desktop.test.ts
index a583f430..a3281e03 100644
--- a/packages/server/test/desktop.test.ts
+++ b/packages/server/test/desktop.test.ts
@@ -1,5 +1,5 @@
/**
- * Desktop mode: one-shot desktop-login, Bearer-token shutdown, desktopMode in /api/me,
+ * Desktop mode: the one-shot desktop claim, Bearer-token shutdown, desktopMode in /api/me,
* the desktop-session password change without oldPassword, and the single-user guard
* closing the user-management and Project-member surfaces.
*/
@@ -14,11 +14,11 @@ import {
} from "./helpers.js";
import type { ErrorBody, MeResponse } from "../src/api/types.js";
-describe("desktop-login", () => {
+describe("desktop claim", () => {
it("redeems the token once: cookie session, redirect to /, second attempt 401", async () => {
const t = await createDesktopApp();
try {
- const res = await t.app.request(`/api/auth/desktop-login?token=${TEST_DESKTOP_TOKEN}`);
+ const res = await t.app.request(`/api/auth/claim?token=${TEST_DESKTOP_TOKEN}`);
expect(res.status).toBe(302);
expect(res.headers.get("location")).toBe("/");
const cookie = res.headers.get("set-cookie");
@@ -32,7 +32,7 @@ describe("desktop-login", () => {
expect(body.user.userId).toBe("admin");
expect(body.desktopMode).toBe(true);
- const replay = await t.app.request(`/api/auth/desktop-login?token=${TEST_DESKTOP_TOKEN}`);
+ const replay = await t.app.request(`/api/auth/claim?token=${TEST_DESKTOP_TOKEN}`);
expect(replay.status).toBe(401);
} finally {
await t.cleanup();
@@ -42,21 +42,22 @@ describe("desktop-login", () => {
it("rejects a wrong or missing token without consuming the real one", async () => {
const t = await createDesktopApp();
try {
- expect((await t.app.request("/api/auth/desktop-login?token=wrong")).status).toBe(401);
- expect((await t.app.request("/api/auth/desktop-login")).status).toBe(401);
+ expect((await t.app.request("/api/auth/claim?token=wrong")).status).toBe(401);
+ expect((await t.app.request("/api/auth/claim")).status).toBe(401);
// The real token still works after failed attempts.
- expect(
- (await t.app.request(`/api/auth/desktop-login?token=${TEST_DESKTOP_TOKEN}`)).status,
- ).toBe(302);
+ expect((await t.app.request(`/api/auth/claim?token=${TEST_DESKTOP_TOKEN}`)).status).toBe(302);
} finally {
await t.cleanup();
}
});
- it("is 404 outside desktop mode, and /api/me reports desktopMode false", async () => {
+ it("refuses a desktop token outside desktop mode, and /api/me reports desktopMode false", async () => {
const t = await createTestApp();
try {
- expect((await t.app.request("/api/auth/desktop-login?token=x")).status).toBe(404);
+ // The claim route serves the first-login link too, so it exists in every mode. A
+ // server with no shell has no shell token to honour, and says so as 401 — the same
+ // answer any wrong value gets, so the reply does not report which modes are enabled.
+ expect((await t.app.request("/api/auth/claim?token=x")).status).toBe(401);
const admin = await loginAdmin(t.app);
const me = await apiClient(t.app, admin.cookie).get("/api/me");
expect(((await me.json()) as MeResponse).desktopMode).toBe(false);
diff --git a/packages/server/test/first-login.test.ts b/packages/server/test/first-login.test.ts
new file mode 100644
index 00000000..23cb021d
--- /dev/null
+++ b/packages/server/test/first-login.test.ts
@@ -0,0 +1,300 @@
+/**
+ * The first-login proof of the claim route (auth/service.ts, routes/auth.ts) — the other one,
+ * the desktop shell's token, is covered in desktop.test.ts.
+ *
+ * What is peculiar to this proof is that the link CARRIES a session rather than a secret
+ * redeemed for one. That buys simplicity and costs a hazard the desktop token does not have:
+ * an endpoint that made a cookie out of any valid token would let one person sign another
+ * into their own account. So the printed value is compared, not merely verified — and it stops
+ * working the moment a password exists, since a console scrollback must not stay a way in.
+ */
+import fs from "node:fs";
+import path from "node:path";
+import { afterEach, beforeEach, describe, expect, it } from "vitest";
+import { SESSION_COOKIE } from "../src/auth/middleware.js";
+import { apiClient, cookieFrom, createTestApp, loginAdmin, makeTempRoot } from "./helpers.js";
+import type { TestApp } from "./helpers.js";
+
+describe("the first-login link", () => {
+ let t: TestApp;
+ /** The session the server would print — read from it, not injected, as a browser would get it. */
+ let link: string;
+
+ beforeEach(async () => {
+ t = await createTestApp();
+ link = t.deps.authService.mintFirstLogin()!;
+ });
+ afterEach(async () => {
+ await t.cleanup();
+ });
+
+ const redeem = (token: string) =>
+ t.app.request(`/api/auth/claim?token=${encodeURIComponent(token)}`, {
+ redirect: "manual",
+ });
+
+ it("claims an unclaimed server, with a session that may set a password but is not desktop", async () => {
+ const res = await redeem(link);
+ expect(res.status).toBe(302);
+ expect(res.headers.get("location")).toBe("/");
+ const cookie = cookieFrom(res);
+
+ const me = (await (await apiClient(t.app, cookie).get("/api/me")).json()) as {
+ user: { userId: string };
+ sessionVia: string;
+ };
+ expect(me.user.userId).toBe("admin");
+ // "setup", never "desktop": reading a link proves someone read a link, not that they own
+ // the machine the shell runs on.
+ expect(me.sessionVia).toBe("setup");
+
+ // The one allowance it carries — and the account's password is a random value nobody has
+ // seen, so there is nothing to put in an old-password field.
+ const set = await apiClient(t.app, cookie).put("/api/me/password", {
+ newPassword: "claimed-password-1",
+ });
+ expect(set.status).toBe(204);
+ expect(t.deps.authService.adminPasswordIsInitial()).toBe(false);
+
+ // Claimed: a console scrollback is not a way in.
+ expect((await redeem(link)).status).toBe(401);
+ });
+
+ it("refuses any token but the printed one, and says nothing about which it got", async () => {
+ // Otherwise this endpoint would make a cookie out of ANY valid token, and a link could
+ // sign its recipient into the SENDER's account. The two refusals are byte-identical, so
+ // a caller cannot tell "wrong token" from "already claimed".
+ const someoneElse = (await loginAdmin(t.app)).cookie.split("=").slice(1).join("=");
+ const other = await redeem(someoneElse);
+ const wrong = await redeem("not-the-token");
+ expect([other.status, wrong.status]).toEqual([401, 401]);
+ expect(await other.text()).toBe(await wrong.text());
+ });
+
+ /**
+ * Not single-use, deliberately: a mail client or a browser that prefetches the link would
+ * spend a one-shot token before its reader ever clicked, and the window it stays open is
+ * exactly the window in which the account protects nothing yet. Opening it twice yields the
+ * same session rather than two, since the link IS the session.
+ */
+ it("can be opened more than once, and both pages land in one session", async () => {
+ const a = await redeem(link);
+ const b = await redeem(link);
+ expect([a.status, b.status]).toEqual([302, 302]);
+ const cookieOf = (r: Response) => cookieFrom(r);
+ expect(cookieOf(a)).toBe(cookieOf(b));
+ expect(cookieOf(a)).not.toBe("");
+ // Still the same link afterwards: redemption spends nothing.
+ expect(t.deps.authService.mintFirstLogin()).toBe(link);
+ });
+
+ /**
+ * The one reachable way to set a password WITHOUT going through setInitialPassword's
+ * revocation: a pinned seed (PENGUIN_SEED_ADMIN_PASSWORD) makes the current password
+ * knowable, so the ordinary change-password door opens. The link must die there too —
+ * the invariant is "any password set on the admin ends the link", not "the door we
+ * expected ends it".
+ */
+ it("dies when the admin sets a password through the ordinary door (pinned seed)", async () => {
+ const pinned = await createTestApp();
+ try {
+ const pinnedLink = pinned.deps.authService.mintFirstLogin()!;
+ const { cookie } = await loginAdmin(pinned.app);
+ await apiClient(pinned.app, cookie).put("/api/me/password", {
+ oldPassword: pinned.adminPassword,
+ newPassword: "chosen-password-1",
+ });
+ expect(pinned.deps.authService.redeemFirstLogin(pinnedLink)).toBeNull();
+ } finally {
+ await pinned.cleanup();
+ }
+ });
+
+ /**
+ * Claiming deletes the very session making the request, so the response has to carry a
+ * replacement or the browser's next call 401s and a brand-new user lands back on a login
+ * screen seconds after choosing their password. The replacement is an ordinary login with
+ * the password just set — the old cookie is still dead.
+ */
+ it("hands the claimer a working session back, while the link's own cookie dies", async () => {
+ const res = await redeem(link);
+ const claimCookie = cookieFrom(res);
+ const set = await apiClient(t.app, claimCookie).put("/api/me/password", {
+ newPassword: "claimed-password-1",
+ });
+ expect(set.status).toBe(204);
+ const replacement = cookieFrom(set);
+ expect(replacement).toMatch(new RegExp(`^${SESSION_COOKIE}=.+`));
+ expect(replacement).not.toBe(claimCookie);
+ // The replacement works…
+ const me = await apiClient(t.app, replacement).get("/api/me");
+ expect(me.status).toBe(200);
+ // …as an ordinary password session, not a setup one that could re-set the password.
+ expect(((await me.json()) as { sessionVia: string }).sessionVia).toBe("password");
+ // …and the claimed link is dead.
+ expect((await apiClient(t.app, claimCookie).get("/api/me")).status).toBe(401);
+ });
+
+ /**
+ * Setting a password must end EVERY first-login session for the account, not just the link
+ * the current process printed. An earlier boot's link stays live in a terminal scrollback,
+ * and a `setup` session may change the password without knowing the old one — so one left
+ * behind is an account takeover, not merely an extra session.
+ */
+ it("kills a setup session left over from an earlier boot", async () => {
+ const root = await makeTempRoot();
+ const config = { root, dbPath: path.join(root, "web.db"), seedAdminPassword: null };
+ const boot1 = await createTestApp({ config });
+ const linkA = boot1.deps.authService.mintFirstLogin()!;
+ await boot1.cleanup();
+
+ // Still unclaimed, so this boot prints its OWN link; both rows are live setup sessions.
+ const boot2 = await createTestApp({ config });
+ try {
+ const linkB = boot2.deps.authService.mintFirstLogin()!;
+ expect(linkB).not.toBe(linkA);
+ const set = await apiClient(boot2.app, `${SESSION_COOKIE}=${linkB}`).put("/api/me/password", {
+ newPassword: "claimed-password-1",
+ });
+ expect(set.status).toBe(204);
+ // The older link is dead too — not merely unable to set a password, but unauthenticated.
+ expect((await apiClient(boot2.app, `${SESSION_COOKIE}=${linkA}`).get("/api/me")).status).toBe(
+ 401,
+ );
+ } finally {
+ await boot2.cleanup();
+ }
+ });
+
+ /**
+ * The setup session renews in place (the row's expiry is topped up, the cookie value is
+ * unchanged), so it survives well past the printed link's original 30-day mark. Setting a
+ * password deletes that row, and the link goes dead — no surviving setup session, whether
+ * or not it was renewed first.
+ */
+ /**
+ * The revocation fires only after the password actually updates: a rejected attempt must
+ * leave the link alive, or a typo (or anyone poking the endpoint with a bad value) burns
+ * the only way in until a restart.
+ */
+ it("keeps the link alive when the chosen password is rejected", async () => {
+ const res = await redeem(link);
+ const cookie = cookieFrom(res);
+ const short = await apiClient(t.app, cookie).put("/api/me/password", {
+ newPassword: "short",
+ });
+ expect(short.status).toBe(400);
+ // The same printed link still redeems — nothing was spent on the failure.
+ expect((await redeem(link)).status).toBe(302);
+ expect(t.deps.authService.mintFirstLogin()).toBe(link);
+ });
+
+ /**
+ * The claim ends with its own sign-in (routes/me.ts hands the claimer a replacement
+ * session), and that sign-in must not be blockable from outside: anyone who can reach the
+ * port can spam POST /api/auth/login with wrong guesses and hold the per-user backoff
+ * window open. A successful password set resets the counter — it proves at least what the
+ * successful login that already resets it proves — so the claimer lands signed in instead
+ * of 429ing AFTER the password committed, with the setup session already deleted.
+ */
+ it("signs the claimer in even while a guessing spree has the login throttled", async () => {
+ const nowMs = Date.now();
+ const clocked = await createTestApp({ now: () => new Date(nowMs) });
+ try {
+ const clockedLink = clocked.deps.authService.mintFirstLogin()!;
+ const guess = () =>
+ clocked.app.request("/api/auth/login", {
+ method: "POST",
+ headers: { "content-type": "application/json" },
+ body: JSON.stringify({ userId: "admin", password: "not-the-password" }),
+ });
+ // Six wrong guesses arm the backoff; the frozen clock keeps its window open.
+ for (let i = 0; i < 6; i++) expect((await guess()).status).toBe(401);
+ expect((await guess()).status).toBe(429);
+
+ const res = await clocked.app.request(
+ `/api/auth/claim?token=${encodeURIComponent(clockedLink)}`,
+ { redirect: "manual" },
+ );
+ const set = await apiClient(clocked.app, cookieFrom(res)).put("/api/me/password", {
+ newPassword: "claimed-password-1",
+ });
+ expect(set.status).toBe(204);
+ // The replacement session works: the claim was not spent on somebody else's 429.
+ expect((await apiClient(clocked.app, cookieFrom(set)).get("/api/me")).status).toBe(200);
+ } finally {
+ await clocked.cleanup();
+ }
+ });
+
+ /**
+ * An unclaimed server outliving the session TTL (30 days without anyone setting a
+ * password) must not keep handing out the same dead link: the cached token no longer
+ * authenticates, so minting re-rolls it.
+ */
+ it("re-mints the link once the cached one has aged out", async () => {
+ let nowMs = Date.now();
+ const clocked = await createTestApp({
+ config: { seedAdminPassword: null },
+ now: () => new Date(nowMs),
+ });
+ try {
+ const first = clocked.deps.authService.mintFirstLogin()!;
+ nowMs += 31 * 24 * 60 * 60 * 1000;
+ const second = clocked.deps.authService.mintFirstLogin();
+ expect(second).not.toBeNull();
+ expect(second).not.toBe(first);
+ expect(clocked.deps.authService.redeemFirstLogin(second!)).toBe(second);
+ } finally {
+ await clocked.cleanup();
+ }
+ });
+
+ /**
+ * A claimed server that restarts must not end up holding a usable setup session. Revocation
+ * cannot be what prevents that — a restart's token is new, and nothing revoked a token that
+ * did not exist yet — so the server declines to mint one at all.
+ */
+ it("mints nothing once the server has been claimed, so a restart has no link", async () => {
+ const root = await makeTempRoot();
+ const dbPath = path.join(root, "web.db");
+
+ const first = await createTestApp({ config: { dbPath, seedAdminPassword: null } });
+ const claim = await first.app.request(
+ `/api/auth/claim?token=${encodeURIComponent(first.deps.authService.mintFirstLogin()!)}`,
+ { redirect: "manual" },
+ );
+ const cookie = cookieFrom(claim);
+ await apiClient(first.app, cookie).put("/api/me/password", {
+ newPassword: "claimed-password-1",
+ });
+ await first.cleanup();
+
+ // Same database, new process: a new signing key, and a new setup session with it.
+ const second = await createTestApp({ config: { dbPath, seedAdminPassword: null } });
+ try {
+ expect(second.deps.authService.adminPasswordIsInitial()).toBe(false);
+ expect(second.deps.authService.mintFirstLogin()).toBeNull();
+ // Nothing to match, so the endpoint refuses whatever is presented.
+ const res = await second.app.request("/api/auth/claim?token=anything", {
+ redirect: "manual",
+ });
+ expect(res.status).toBe(401);
+ } finally {
+ await second.cleanup();
+ }
+ });
+
+ /**
+ * A minted token that is never delivered is a feature nobody can reach, and every test
+ * above mints its own — so none of them would notice. The entrypoint runs main() on import
+ * and exports nothing, which leaves reading it the way to check that what it mints actually
+ * reaches a console.
+ */
+ it("is printed by the entrypoint, not merely minted", () => {
+ const entrypoint = fs.readFileSync(new URL("../src/index.ts", import.meta.url), "utf8");
+ expect(entrypoint).toMatch(/renderFirstLoginNotice\(/);
+ expect(entrypoint).toMatch(/mintFirstLogin\(/);
+ expect(entrypoint).toMatch(/\/api\/auth\/claim\?token=/);
+ });
+});
diff --git a/packages/server/test/helpers.ts b/packages/server/test/helpers.ts
index 1b3f40b5..51116a4c 100644
--- a/packages/server/test/helpers.ts
+++ b/packages/server/test/helpers.ts
@@ -52,8 +52,8 @@ export function testConfig(root: string): ServerConfig {
webDist: path.join(root, "__no_web_dist__"),
// Fixed seed password so loginAdmin needs no seed-time capture.
seedAdminPassword: TEST_ADMIN_PASSWORD,
- authSessionTtlMs: 7 * DAY_MS,
- authSessionRenewMs: 6 * DAY_MS,
+ authSessionTtlMs: 30 * DAY_MS,
+ authSessionRenewMs: 29 * DAY_MS,
desktopToken: null,
portFile: null,
trustProxy: false,
@@ -80,20 +80,20 @@ export async function createTestApp(options: TestAppOptions = {}): Promise<TestA
const { beforeSeed, config, ...overrides } = options;
const root = await makeTempRoot();
if (beforeSeed) await beforeSeed(root);
- const deps = await bootAppDeps(
- { ...testConfig(root), ...config },
- {
- log: () => {},
- passwordHashCost: TEST_PASSWORD_HASH_COST,
- // The bridge's per-line pace is a real wait in production; every test but the one
- // about the pacing itself collapses it to nothing.
- messagingLineDelayMs: 0,
- ...overrides,
- },
- );
- // Consistent with the startup entrypoint: seed the built-in admin (owning default_project),
- // keeping the password it returns (only null if a beforeSeed hook ever pre-created users).
- const adminPassword = (await deps.authService.seedAdmin()) ?? TEST_ADMIN_PASSWORD;
+ const finalConfig = { ...testConfig(root), ...config };
+ const deps = await bootAppDeps(finalConfig, {
+ log: () => {},
+ passwordHashCost: TEST_PASSWORD_HASH_COST,
+ // The bridge's per-line pace is a real wait in production; every test but the one
+ // about the pacing itself collapses it to nothing.
+ messagingLineDelayMs: 0,
+ ...overrides,
+ });
+ // Consistent with the startup entrypoint: seed the built-in admin (owning default_project).
+ await deps.authService.seedAdmin();
+ // The seed hashes and discards; tests know the password only because the config injects it.
+ // With a null override there is nothing to know, and such tests never password-login.
+ const adminPassword = finalConfig.seedAdminPassword ?? TEST_ADMIN_PASSWORD;
const app = createRuntimeApp(deps);
return {
app,
@@ -123,9 +123,9 @@ export function createDesktopApp(): Promise<TestApp> {
return createTestApp({ config: { desktopToken: TEST_DESKTOP_TOKEN } });
}
-/** Redeems the one-shot desktop-login for a `sessionVia: "desktop"` cookie. */
+/** Redeems the shell's one-shot token for a `sessionVia: "desktop"` cookie. */
export async function desktopLoginCookie(app: Hono<AppEnv>): Promise<string> {
- const res = await app.request(`/api/auth/desktop-login?token=${TEST_DESKTOP_TOKEN}`);
+ const res = await app.request(`/api/auth/claim?token=${TEST_DESKTOP_TOKEN}`);
if (res.status !== 302) {
throw new Error(`Desktop login failed: ${res.status} ${await res.text()}`);
}
@@ -159,6 +159,11 @@ export function loginAdmin(app: Hono<AppEnv>): Promise<{ cookie: string; user: U
return loginUser(app, ADMIN_USER_ID, TEST_ADMIN_PASSWORD);
}
+/** The `name=value` cookie pair from a response's Set-Cookie (the shape apiClient wants). */
+export function cookieFrom(res: Response): string {
+ return (res.headers.get("set-cookie") ?? "").split(";")[0]!;
+}
+
/** Admin creates the account and logs in as that user (the only way to create test users while registration is closed). */
export async function provisionUser(
app: Hono<AppEnv>,
diff --git a/packages/server/test/hmr-resources.test.ts b/packages/server/test/hmr-resources.test.ts
index fb05638a..cf94cd7a 100644
--- a/packages/server/test/hmr-resources.test.ts
+++ b/packages/server/test/hmr-resources.test.ts
@@ -21,7 +21,6 @@ import type { TerminalSession } from "../src/terminal/session.js";
import { DECLARED_RESOURCES as PARKED, packagedPlatform } from "../src/hmr/platform.js";
import {
RESOURCE_IFACES_RESOURCE_ID,
- RUNTIME_AUTH_RESOURCE_ID,
PENGUIN_FAMILY,
RUNTIME_INTERFACES,
RUNTIME_INTERFACES_RESOURCE_ID,
@@ -30,6 +29,7 @@ import {
RUNTIME_DB_RESOURCE_ID,
RUNTIME_HMR_RESOURCE_ID,
RUNTIME_PROXY_RESOURCE_ID,
+ RUNTIME_AUTH_STATE_RESOURCE_ID,
claimRuntimeCapabilities,
} from "../src/hmr/capabilities.js";
@@ -316,7 +316,6 @@ describe("runtime capability handshake", () => {
};
r.register(RUNTIME_CONFIG_RESOURCE_ID, carrying("config"));
r.register(RUNTIME_DB_RESOURCE_ID, carrying("db"));
- r.register(RUNTIME_AUTH_RESOURCE_ID, carrying("auth"));
r.register(RUNTIME_CHANNELS_RESOURCE_ID, carrying("channels"));
r.register(RUNTIME_PROXY_RESOURCE_ID, () => {});
r.register(RUNTIME_HMR_RESOURCE_ID, carrying("hmr"));
@@ -342,7 +341,7 @@ describe("runtime capability handshake", () => {
it("refuses when one interface is missing a member the claimer names", () => {
const r = new HotResources();
stubCaps(r);
- r.register(RUNTIME_INTERFACES_RESOURCE_ID, { ...RUNTIME_INTERFACES, auth: ["login"] });
+ r.register(RUNTIME_INTERFACES_RESOURCE_ID, { ...RUNTIME_INTERFACES, channels: ["nope"] });
expect(claimRuntimeCapabilities(r)).toMatchObject({ kind: "refused" });
});
@@ -357,11 +356,43 @@ describe("runtime capability handshake", () => {
// What a member set buys over a number: the declaration is verified, not trusted.
const r = new HotResources();
stubCaps(r);
- r.register(RUNTIME_AUTH_RESOURCE_ID, { login: () => undefined }); // missing the rest
+ r.register(RUNTIME_CHANNELS_RESOURCE_ID, { get: () => undefined }); // missing the rest
r.register(RUNTIME_INTERFACES_RESOURCE_ID, RUNTIME_INTERFACES);
expect(claimRuntimeCapabilities(r)).toMatchObject({
kind: "refused",
- reason: expect.stringContaining("auth lacks") as unknown,
+ reason: expect.stringContaining("channels lacks") as unknown,
+ });
+ });
+
+ it("claims a runtime that predates the auth-state resource, on a fresh holder", () => {
+ // The point of the whole change: authentication is business behaviour built per App, so
+ // a platform newer than its runtime must still boot on it. Only the process-scoped
+ // values are claimed, and optionally.
+ const r = new HotResources();
+ stubCaps(r);
+ r.register(RUNTIME_INTERFACES_RESOURCE_ID, RUNTIME_INTERFACES);
+ const claim = claimRuntimeCapabilities(r);
+ expect(claim).toMatchObject({ kind: "claimed" });
+ if (claim.kind !== "claimed") return;
+ expect(claim.caps.authState).toEqual({ firstLoginToken: null, apiToken: null });
+ });
+
+ it("fills the fields an older runtime's auth state lacks, in place", () => {
+ // A runtime one build behind published a holder without `apiToken`. The platform fills
+ // it rather than substituting a fresh bag: the runtime keeps a reference to THIS object,
+ // so a copy would strand the first-login link the App writes into it.
+ const r = new HotResources();
+ stubCaps(r);
+ r.register(RUNTIME_INTERFACES_RESOURCE_ID, RUNTIME_INTERFACES);
+ const published = { firstLoginToken: "printed-by-the-old-runtime" };
+ r.register(RUNTIME_AUTH_STATE_RESOURCE_ID, published);
+ const claim = claimRuntimeCapabilities(r);
+ expect(claim).toMatchObject({ kind: "claimed" });
+ if (claim.kind !== "claimed") return;
+ expect(claim.caps.authState).toBe(published);
+ expect(claim.caps.authState).toEqual({
+ firstLoginToken: "printed-by-the-old-runtime",
+ apiToken: null,
});
});
diff --git a/packages/server/test/initial-password.test.ts b/packages/server/test/initial-password.test.ts
deleted file mode 100644
index df86fe68..00000000
--- a/packages/server/test/initial-password.test.ts
+++ /dev/null
@@ -1,109 +0,0 @@
-/**
- * Initial-admin-password persistence and reminder notice: file roundtrip, notice shape,
- * and the app wiring that drops the stored plaintext the moment it goes stale (self
- * change / admin reset of the admin), while other users' password events leave it alone.
- */
-import fs from "node:fs";
-import path from "node:path";
-import { afterEach, beforeEach, describe, expect, it } from "vitest";
-import {
- initialAdminPasswordPath,
- readInitialAdminPassword,
- renderInitialPasswordNotice,
- storeInitialAdminPassword,
- clearInitialAdminPassword,
-} from "../src/initial-password.js";
-import {
- apiClient,
- createTestApp,
- loginAdmin,
- provisionUser,
- TEST_ADMIN_PASSWORD,
-} from "./helpers.js";
-import type { TestApp } from "./helpers.js";
-
-describe("initial password file", () => {
- let t: TestApp;
-
- beforeEach(async () => {
- t = await createTestApp();
- });
- afterEach(async () => {
- await t.cleanup();
- });
-
- it("stores, reads back and clears the plaintext in the data root", () => {
- expect(readInitialAdminPassword(t.root)).toBeNull();
- storeInitialAdminPassword(t.root, "penguin-1234");
- expect(fs.existsSync(path.join(t.root, "initial-admin-password"))).toBe(true);
- expect(readInitialAdminPassword(t.root)).toBe("penguin-1234");
- clearInitialAdminPassword(t.root);
- expect(readInitialAdminPassword(t.root)).toBeNull();
- // Idempotent on an already-missing file.
- clearInitialAdminPassword(t.root);
- expect(readInitialAdminPassword(t.root)).toBeNull();
- });
-
- it("treats an empty or whitespace-only file as absent", () => {
- fs.writeFileSync(initialAdminPasswordPath(t.root), " \n");
- expect(readInitialAdminPassword(t.root)).toBeNull();
- });
-
- it("self password change drops the stored plaintext for admin", async () => {
- storeInitialAdminPassword(t.root, t.adminPassword);
- const admin = await loginAdmin(t.app);
- const res = await apiClient(t.app, admin.cookie).put("/api/me/password", {
- oldPassword: TEST_ADMIN_PASSWORD,
- newPassword: "changed-password-1",
- });
- expect(res.status).toBe(204);
- expect(readInitialAdminPassword(t.root)).toBeNull();
- expect(t.deps.authService.adminPasswordIsInitial()).toBe(false);
- });
-
- it("admin password reset of the admin drops the stored plaintext; resets of other users keep it", async () => {
- storeInitialAdminPassword(t.root, t.adminPassword);
- const admin = await loginAdmin(t.app);
- await provisionUser(t.app, "alice", "password-123");
- // Resetting ANOTHER user leaves the admin's stored seed in place.
- const other = await apiClient(t.app, admin.cookie).post("/api/admin/users/alice/password", {
- password: "password-456",
- });
- expect(other.status).toBe(204);
- expect(readInitialAdminPassword(t.root)).toBe(t.adminPassword);
- // Resetting the ADMIN itself replaces the password with an admin-chosen value the
- // file no longer matches: the stale plaintext must go, even though the initial FLAG
- // is re-armed by the reset.
- const self = await apiClient(t.app, admin.cookie).post(
- `/api/admin/users/${admin.user.userId}/password`,
- { password: "password-789" },
- );
- expect(self.status).toBe(204);
- expect(readInitialAdminPassword(t.root)).toBeNull();
- expect(t.deps.authService.adminPasswordIsInitial()).toBe(true);
- });
-});
-
-describe("renderInitialPasswordNotice", () => {
- it("frames the credentials and the reminder in an aligned ASCII box", () => {
- const notice = renderInitialPasswordNotice("admin", "penguin-1234");
- const lines = notice.split("\n");
- expect(lines.length).toBeGreaterThanOrEqual(5);
- expect(lines[0]).toMatch(/^\+-+\+$/);
- expect(lines.at(-1)).toBe(lines[0]);
- // Every row is exactly as wide as the frame, so the right edge lines up.
- for (const line of lines) expect(line.length).toBe(lines[0]!.length);
- for (const line of lines.slice(1, -1)) expect(line).toMatch(/^\|.*\|$/);
- expect(notice).toContain("admin / penguin-1234");
- expect(notice).toContain("change it soon");
- // Plain ASCII only: box-drawing characters misrender on legacy code pages.
- expect([...notice].every((ch) => ch.codePointAt(0)! < 128)).toBe(true);
- });
-
- it("widens with a long pinned password instead of breaking the frame", () => {
- const long = "a-very-long-pinned-password-for-automation-use-only";
- const lines = renderInitialPasswordNotice("admin", long).split("\n");
- for (const line of lines) expect(line.length).toBe(lines[0]!.length);
- expect(lines.some((line) => line.includes(long))).toBe(true);
- });
-});
diff --git a/packages/server/test/reset-admin-password.test.ts b/packages/server/test/reset-admin-password.test.ts
index c4f2e38a..832b52bd 100644
--- a/packages/server/test/reset-admin-password.test.ts
+++ b/packages/server/test/reset-admin-password.test.ts
@@ -11,9 +11,9 @@ import { afterEach, describe, expect, it } from "vitest";
import { hashPassword, verifyPassword } from "../src/auth/password.js";
import { ADMIN_USER_ID } from "../src/auth/service.js";
import { openDatabase } from "../src/db/database.js";
-import { AuthSessionsRepo } from "../src/db/repos/auth-sessions.js";
import { UsersRepo } from "../src/db/repos/users.js";
-import { readInitialAdminPassword } from "../src/initial-password.js";
+import { AuthSessionsRepo } from "../src/db/repos/auth-sessions.js";
+import { initialAdminPasswordPath } from "../src/initial-password.js";
import { acquireServerLock } from "../src/lock.js";
import { resetAdminPassword } from "../src/reset-admin-password.js";
import { makeTempRoot } from "./helpers.js";
@@ -37,9 +37,7 @@ describe("resetAdminPassword", () => {
const dbPath = path.join(root, "web.db");
const db = openDatabase(dbPath);
const users = new UsersRepo(db);
- const sessions = new AuthSessionsRepo(db);
const createdAt = "2026-01-01T00:00:00.000Z";
- const expiresAt = "2100-01-01T00:00:00.000Z";
users.insert({
userId: ADMIN_USER_ID,
passwordHash: await hashPassword("old-password-1"),
@@ -54,45 +52,48 @@ describe("resetAdminPassword", () => {
passwordIsInitial: false,
createdAt,
});
+ const sessions = new AuthSessionsRepo(db);
+ const later = "2027-01-01T00:00:00.000Z";
sessions.insert({
- tokenHash: "admin-token",
+ tokenHash: "admin-session",
userId: ADMIN_USER_ID,
createdAt,
- expiresAt,
+ expiresAt: later,
via: "password",
});
sessions.insert({
- tokenHash: "alice-token",
+ tokenHash: "alice-session",
userId: "alice",
createdAt,
- expiresAt,
+ expiresAt: later,
via: "password",
});
db.close();
return dbPath;
}
- it("re-arms the initial-password machinery: fresh password, flag, cleared sessions, stored plaintext", async () => {
+ it("returns the admin to the unclaimed state, producing no plaintext at all", async () => {
const root = await tempRoot();
const dbPath = await seedDatabase(root);
+ // A plaintext an older build left behind must not survive the rescue.
+ fs.writeFileSync(initialAdminPasswordPath(root), "penguin-0000\n");
const result = await resetAdminPassword(root);
- expect(result.outcome).toBe("reset");
- const password = (result as { outcome: "reset"; password: string }).password;
- expect(password).toMatch(/^penguin-\d{4}$/);
- // The plaintext lands in the data root, so every server start re-prints the notice.
- expect(readInitialAdminPassword(root)).toBe(password);
+ expect(result).toEqual({ outcome: "reset" });
+ // Nothing to write down and nothing left on disk: the next server start prints a
+ // first-login link, and claiming it is what sets a real password.
+ expect(fs.existsSync(initialAdminPasswordPath(root))).toBe(false);
const db = openDatabase(dbPath);
try {
const admin = new UsersRepo(db).findById(ADMIN_USER_ID);
expect(admin?.passwordIsInitial).toBe(true);
- expect(await verifyPassword(password, admin!.passwordHash)).toBe(true);
+ // The old password no longer works, and the new one is a value nobody holds.
expect(await verifyPassword("old-password-1", admin!.passwordHash)).toBe(false);
- // Admin sessions cleared (as an admin-initiated reset would); bystanders keep theirs.
+ // The admin's session rows are deleted; a bystander's are untouched.
const sessions = new AuthSessionsRepo(db);
- expect(sessions.findByTokenHash("admin-token")).toBeNull();
- expect(sessions.findByTokenHash("alice-token")).not.toBeNull();
+ expect(sessions.findByTokenHash("admin-session")).toBeNull();
+ expect(sessions.findByTokenHash("alice-session")).not.toBeNull();
const alice = new UsersRepo(db).findById("alice");
expect(await verifyPassword("alice-password-1", alice!.passwordHash)).toBe(true);
} finally {
@@ -118,7 +119,7 @@ describe("resetAdminPassword", () => {
} finally {
db.close();
}
- expect(readInitialAdminPassword(root)).toBeNull();
+ expect(fs.existsSync(initialAdminPasswordPath(root))).toBe(false);
} finally {
await new Promise<void>((resolve) => srv.close(() => resolve()));
}
diff --git a/packages/server/tsup.config.ts b/packages/server/tsup.config.ts
index dab1ff05..0ab13224 100644
--- a/packages/server/tsup.config.ts
+++ b/packages/server/tsup.config.ts
@@ -4,10 +4,11 @@ export default defineConfig({
// Explicitly name entries to preserve subpath exports: "./api", "./lock",
// "./initial-password" and "./reset-admin-password" (lock, initial-password and
// reset-admin-password are side-effect-free for CLI pre-checks and the offline
- // admin-password rescue); "./hmr/manifest" is the host-less harness.json reader the
- // CLI's thin loader resolves the current cli bundle through, and "./version-report" is
- // the shared assembler `penguin version` and GET /api/version both render (core plus
- // that same reader — no server). There is deliberately no
+ // admin-password rescue); "./secret-file" is the shared symlink-safe writer;
+ // "./hmr/manifest" is the host-less harness.json reader the CLI's thin loader
+ // resolves the current cli bundle through, and "./version-report" is the shared
+ // assembler `penguin version` and GET /api/version both render (core plus that
+ // same reader — no server). There is deliberately no
// "./platform" subpath: src/hmr/entry.ts (this package's platform artifact
// compile target — see its own module doc) is compiled straight from source by
// esbuild in scripts/deploy.mjs, never through this package's published dist,
@@ -18,6 +19,8 @@ export default defineConfig({
lock: "src/lock.ts",
"initial-password": "src/initial-password.ts",
"reset-admin-password": "src/reset-admin-password.ts",
+ "auth-token": "src/auth-token.ts",
+ "secret-file": "src/secret-file.ts",
"hmr/manifest": "src/hmr/manifest.ts",
"version-report": "src/version-report.ts",
// "./extension": the surface extension PACKAGES compile against. Extensions live outside
diff --git a/packages/web/src/components/account/change-password-dialog.tsx b/packages/web/src/components/account/change-password-dialog.tsx
index f384b1db..69edefd9 100644
--- a/packages/web/src/components/account/change-password-dialog.tsx
+++ b/packages/web/src/components/account/change-password-dialog.tsx
@@ -9,17 +9,18 @@ import { ApiError } from "../../api/client";
import { S } from "../../lib/strings";
import { apiErrorText } from "../../lib/api-error";
import { useAuth } from "../../state/auth";
+import { omitsOldPassword } from "../../lib/account-menu";
import { Button } from "../ui/button";
import { PasswordInput } from "../ui/password-input";
import { Modal } from "../ui/modal";
export function ChangePasswordDialog({ open, onClose }: { open: boolean; onClose: () => void }) {
const { refresh, sessionVia } = useAuth();
- // Desktop-established sessions set the password without the old one: the desktop seed
- // password is random and never shown, so there is nothing to type. Keyed on the
- // session's origin, not desktopMode — a browser signed into the same server holds a
- // password session and must still prove the current password.
- const desktopSession = sessionVia === "desktop";
+ // Desktop and first-login sessions set the password without the old one — for them the
+ // current password is random and was never shown (see omitsOldPassword). Keyed on the
+ // session's origin, not desktopMode: a browser signed into the same server with a password
+ // must still prove it.
+ const noOldPassword = omitsOldPassword(sessionVia);
const [oldPassword, setOldPassword] = useState("");
const [newPassword, setNewPassword] = useState("");
const [confirmPassword, setConfirmPassword] = useState("");
@@ -37,7 +38,7 @@ export function ChangePasswordDialog({ open, onClose }: { open: boolean; onClose
const submit = async () => {
const next: { old?: string; new?: string; confirm?: string } = {};
- if (!desktopSession && !oldPassword) next.old = S.common.requiredField;
+ if (!noOldPassword && !oldPassword) next.old = S.common.requiredField;
if (!newPassword) next.new = S.common.requiredField;
if (!confirmPassword) next.confirm = S.common.requiredField;
if (!next.confirm && newPassword !== confirmPassword) next.confirm = S.account.passwordMismatch;
@@ -48,7 +49,7 @@ export function ChangePasswordDialog({ open, onClose }: { open: boolean; onClose
setBusy(true);
setErrors({});
try {
- await api.changePassword(desktopSession ? { newPassword } : { oldPassword, newPassword });
+ await api.changePassword(noOldPassword ? { newPassword } : { oldPassword, newPassword });
await refresh();
onClose();
} catch (e) {
@@ -81,7 +82,7 @@ export function ChangePasswordDialog({ open, onClose }: { open: boolean; onClose
}
>
<div className="space-y-3">
- {!desktopSession && (
+ {!noOldPassword && (
<PasswordInput
label={S.account.oldPassword}
required
@@ -110,7 +111,7 @@ export function ChangePasswordDialog({ open, onClose }: { open: boolean; onClose
error={errors.new}
autoComplete="new-password"
hint={S.auth.passwordHint}
- autoFocus={desktopSession}
+ autoFocus={noOldPassword}
/>
<PasswordInput
label={S.account.confirmPassword}
diff --git a/packages/web/src/lib/account-menu.ts b/packages/web/src/lib/account-menu.ts
index 4e4cad17..452f77c8 100644
--- a/packages/web/src/lib/account-menu.ts
+++ b/packages/web/src/lib/account-menu.ts
@@ -37,3 +37,15 @@ export interface AccountMenuSession {
export function offersChangePassword(session: AccountMenuSession): boolean {
return !(session.desktopMode && session.sessionVia === "desktop");
}
+
+/**
+ * Whether the change-password form omits the current-password field.
+ *
+ * Two kinds of session set a password without the old one, mirroring the server's gate in
+ * `routes/me.ts`: the desktop shell's own window, and a session claimed through a first-login
+ * link. In both, the account's current password is a random value that was hashed and
+ * discarded unseen — demanding it would dead-end the one flow the session exists for.
+ */
+export function omitsOldPassword(sessionVia: MeResponse["sessionVia"]): boolean {
+ return sessionVia === "desktop" || sessionVia === "setup";
+}
diff --git a/packages/web/src/lib/strings-en.ts b/packages/web/src/lib/strings-en.ts
index 78f0780c..8ac34777 100644
--- a/packages/web/src/lib/strings-en.ts
+++ b/packages/web/src/lib/strings-en.ts
@@ -274,7 +274,7 @@ export const en: Strings = {
logout: "Sign out",
admin: "Admin",
defaultAdminNote:
- "First run: sign in as the built-in admin “admin” with the initial password printed in the server startup output (looks like penguin-1234), then change it soon",
+ "First run: the server prints a first-login link in its startup output — open it to claim the built-in admin “admin” and set a password. No initial password exists to type here",
/** Login footer line 2: the offline rescue for a forgotten admin password (other users ask the admin instead). */
forgotAdminNote:
"Forgot the admin password? Stop the server and run penguin server reset-admin-password to issue a fresh initial one",
@@ -284,7 +284,7 @@ export const en: Strings = {
changePassword: "Change password",
oldPassword: "Current password",
oldPasswordHint:
- "The built-in admin's initial password is printed in the server startup output (looks like penguin-1234)",
+ "The password this account currently signs in with — checked before the new one takes effect",
newPassword: "New password",
confirmPassword: "Confirm new password",
passwordMismatch: "New passwords do not match",
diff --git a/packages/web/src/lib/strings.ts b/packages/web/src/lib/strings.ts
index 68831d63..fd3aea0b 100644
--- a/packages/web/src/lib/strings.ts
+++ b/packages/web/src/lib/strings.ts
@@ -276,7 +276,7 @@ export const zh = {
logout: "登出",
admin: "管理员",
defaultAdminNote:
- "首次使用请以内置管理员 admin 登录,初始密码在服务端首次启动时打印(形如 penguin-1234),登录后请尽快修改密码",
+ "首次使用请打开服务端启动输出中的首次登录链接,认领内置管理员 admin 并设置密码。这里没有可输入的初始密码",
/** Login footer line 2: the offline rescue for a forgotten admin password (other users ask the admin instead). */
forgotAdminNote:
"忘记管理员密码时,停止服务后执行 penguin server reset-admin-password 重置为新的初始密码",
@@ -285,7 +285,7 @@ export const zh = {
account: {
changePassword: "修改密码",
oldPassword: "当前密码",
- oldPasswordHint: "内置管理员的初始密码在服务端首次启动时打印(形如 penguin-1234)",
+ oldPasswordHint: "当前账号登录所用的密码——先校验它,新密码才会生效",
newPassword: "新密码",
confirmPassword: "确认新密码",
passwordMismatch: "两次输入的新密码不一致",
diff --git a/packages/web/src/state/auth.tsx b/packages/web/src/state/auth.tsx
index 40523238..9809a6b1 100644
--- a/packages/web/src/state/auth.tsx
+++ b/packages/web/src/state/auth.tsx
@@ -6,7 +6,7 @@
*/
import { createContext, useCallback, useContext, useEffect, useState } from "react";
import type { ReactNode } from "react";
-import type { UploadLimits, UserInfo } from "@prismshadow/penguin-server/api";
+import type { MeResponse, UploadLimits, UserInfo } from "@prismshadow/penguin-server/api";
import * as api from "../api/endpoints";
import { ApiError, setUnauthorizedHandler } from "../api/client";
@@ -42,12 +42,13 @@ interface AuthContextValue {
*/
desktopMode: boolean;
/**
- * How THIS session was established. A browser signed into a desktop-mode server holds
- * a "password" session; only "desktop" sessions (the shell's window) may change the
- * password without the old one. ("token" marks Bearer-authenticated API callers and
- * never occurs in a browser session; it is carried for type parity with the server.)
+ * How THIS session was established — a browser signed into a desktop-mode server holds a
+ * "password" session. "desktop" and "setup" may change the password without the old one
+ * (see omitsOldPassword in lib/account-menu). ("token" marks Bearer-authenticated API
+ * callers and never occurs in a browser session; it is carried for type parity with the
+ * server.)
*/
- sessionVia: "password" | "desktop" | "token";
+ sessionVia: MeResponse["sessionVia"];
/**
* Upload limits in force on this server (admin-settable). The composer reads them to refuse an
* oversize pick before reading it and to name the real number in the message, so the client
@@ -68,7 +69,7 @@ export function AuthProvider({ children }: { children: ReactNode }) {
// flashing it during initialization would be noise.
const [previewIsolated, setPreviewIsolated] = useState(true);
const [desktopMode, setDesktopMode] = useState(false);
- const [sessionVia, setSessionVia] = useState<"password" | "desktop" | "token">("password");
+ const [sessionVia, setSessionVia] = useState<MeResponse["sessionVia"]>("password");
const [uploadLimits, setUploadLimits] = useState<UploadLimits>(DEFAULT_UPLOAD_LIMITS);
// Any API returning 401 (session expired / database rebuilt) clears the current user, and
diff --git a/packages/web/test/account-menu.test.ts b/packages/web/test/account-menu.test.ts
index 13bd81c9..5bf20685 100644
--- a/packages/web/test/account-menu.test.ts
+++ b/packages/web/test/account-menu.test.ts
@@ -16,7 +16,7 @@ import { readFileSync } from "node:fs";
import { dirname, resolve } from "node:path";
import { fileURLToPath } from "node:url";
import { describe, expect, it } from "vitest";
-import { offersChangePassword } from "../src/lib/account-menu";
+import { offersChangePassword, omitsOldPassword } from "../src/lib/account-menu";
describe("offersChangePassword", () => {
it("hides it in the desktop shell's own window — no login form, seed password never shown", () => {
@@ -38,6 +38,18 @@ describe("offersChangePassword", () => {
// password like any other session — so the control is live and must stay visible.
expect(offersChangePassword({ desktopMode: false, sessionVia: "desktop" })).toBe(true);
});
+});
+
+describe("omitsOldPassword", () => {
+ it("omits the current-password field for desktop and first-login sessions only", () => {
+ // For both, the account's current password was hashed and discarded unseen — demanding
+ // it would dead-end the flow: a first-login claimer would face a field nobody on earth
+ // can fill. A password session must still prove the current password, mirroring
+ // routes/me.ts.
+ expect(omitsOldPassword("desktop")).toBe(true);
+ expect(omitsOldPassword("setup")).toBe(true);
+ expect(omitsOldPassword("password")).toBe(false);
+ });
it("is hidden in exactly one of the four states", () => {
const states = [true, false].flatMap((desktopMode) =>