Skip to content

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

fix(server): a login for an unknown username costs the same scrypt check as a wrong password (#774)

Yaowei Zhengc70155db614f
diff --git a/changelog/unreleased/2026-09-17-login-unknown-user-timing.md b/changelog/unreleased/2026-09-17-login-unknown-user-timing.md
new file mode 100644
index 00000000..100ab9f8
--- /dev/null
+++ b/changelog/unreleased/2026-09-17-login-unknown-user-timing.md
@@ -0,0 +1,15 @@
+# A login for an unknown username costs the same scrypt check as a wrong password
+
+- **Date:** 2026-09-17
+- **Type:** fix
+- **Scope:** `server`
+- **PR:** [#774](https://github.com/Prism-Shadow/penguin-harness/pull/774)
+
+[中文版](2026-09-17-login-unknown-user-timing.zh.md)
+
+A sign-in with a username that has no account returned without running scrypt, while a wrong password on a real account paid for a full derivation. At production cost the first answered in well under a millisecond and the second took tens of milliseconds, so response time told which usernames exist. An unknown username is now checked against a dummy hash, and both failures return the same 401 `invalid_credentials` body after one derivation.
+
+## Details
+
+- `verifyAccountPassword` runs exactly one scrypt derivation per call. If the account is missing, its hash is empty, or its hash cannot be checked (wrong format, or parameters scrypt refuses), it checks the password against the dummy hash instead and fails the sign-in.
+- `AuthService.login` makes the dummy hash with the server's own password hasher, so the dummy carries the same cost parameters as real hashes. The hash is computed on the first sign-in that needs it and then kept.
diff --git a/changelog/unreleased/2026-09-17-login-unknown-user-timing.zh.md b/changelog/unreleased/2026-09-17-login-unknown-user-timing.zh.md
new file mode 100644
index 00000000..e0c5a3d7
--- /dev/null
+++ b/changelog/unreleased/2026-09-17-login-unknown-user-timing.zh.md
@@ -0,0 +1,15 @@
+# 不存在的用户名登录时,与密码错误付出同样的 scrypt 校验
+
+- **Date:** 2026-09-17
+- **Type:** fix
+- **Scope:** `server`
+- **PR:** [#774](https://github.com/Prism-Shadow/penguin-harness/pull/774)
+
+[English](2026-09-17-login-unknown-user-timing.md)
+
+用不存在的用户名登录时,服务端不跑 scrypt 就直接返回;真实账号输错密码,却要完整做一次派生。在生产强度下,前者远不到 1 毫秒就有回应,后者要几十毫秒,响应时间因此暴露了哪些用户名存在。现在不存在的用户名会拿一个占位 hash(dummy hash)校验,两种失败都在一次派生之后返回同样的 401 `invalid_credentials` 响应体。
+
+## 细节
+
+- `verifyAccountPassword` 每次调用恰好执行一次 scrypt 派生。账号不存在、hash 为空,或 hash 无法校验(格式错误,或参数被 scrypt 拒绝)时,它改为拿占位 hash 校验密码,并判定登录失败。
+- `AuthService.login` 用服务端自己的密码哈希器生成占位 hash,因此它与真实 hash 的代价参数相同。占位 hash 在第一次需要时计算,之后一直保留。
diff --git a/packages/server/src/auth/password.ts b/packages/server/src/auth/password.ts
index baf5bd19..2e9170fd 100644
--- a/packages/server/src/auth/password.ts
+++ b/packages/server/src/auth/password.ts
@@ -6,7 +6,9 @@ import { Component, Interface } from "@prismshadow/penguin-core/kernel";
* slow-hash requirement as bcrypt/argon2). Storage format:
* `scrypt$N$r$p$<salt b64>$<hash b64>` — parameters are stored alongside the hash,
* so old hashes remain verifiable after future parameter tuning; comparison uses
- * timingSafeEqual to guard against timing side-channels.
+ * timingSafeEqual to guard against timing side-channels, and a sign-in for an account
+ * that does not exist costs the same derivation as a wrong password
+ * (verifyAccountPassword).
*/
import { randomBytes, scrypt, timingSafeEqual } from "node:crypto";
@@ -57,30 +59,57 @@ export async function hashPassword(password: string, cost: number = SCRYPT_COST)
].join("$");
}
-/** Verifies a password; returns false if the stored string has an invalid format (never throws, so the login path can uniformly treat it as a credential error). */
-export async function verifyPassword(password: string, stored: string): Promise<boolean> {
+/**
+ * What checking a password against a stored string found. `match` and `mismatch` each cost one
+ * scrypt derivation; `unverifiable` — not the `scrypt$N$r$p$salt$hash` format, or parameters
+ * scrypt refuses — cost none.
+ */
+export type PasswordCheck = "match" | "mismatch" | "unverifiable";
+
+/** Checks a password against a stored hash. Never throws. */
+export async function checkPassword(password: string, stored: string): Promise<PasswordCheck> {
const parts = stored.split("$");
- if (parts.length !== 6 || parts[0] !== "scrypt") return false;
+ if (parts.length !== 6 || parts[0] !== "scrypt") return "unverifiable";
const n = Number(parts[1]);
const r = Number(parts[2]);
const p = Number(parts[3]);
- if (!Number.isInteger(n) || !Number.isInteger(r) || !Number.isInteger(p)) return false;
- let salt: Buffer;
- let expected: Buffer;
- try {
- salt = Buffer.from(parts[4]!, "base64");
- expected = Buffer.from(parts[5]!, "base64");
- } catch {
- return false;
- }
- if (salt.length === 0 || expected.length === 0) return false;
+ if (!Number.isInteger(n) || !Number.isInteger(r) || !Number.isInteger(p)) return "unverifiable";
+ const salt = Buffer.from(parts[4]!, "base64");
+ const expected = Buffer.from(parts[5]!, "base64");
+ if (salt.length === 0 || expected.length === 0) return "unverifiable";
let actual: Buffer;
try {
actual = await scryptAsync(password, salt, expected.length, n, r, p);
} catch {
- return false;
+ return "unverifiable";
}
- return actual.length === expected.length && timingSafeEqual(actual, expected);
+ return timingSafeEqual(actual, expected) ? "match" : "mismatch";
+}
+
+/** Verifies a password; returns false if the stored string has an invalid format (never throws, so the login path can uniformly treat it as a credential error). */
+export async function verifyPassword(password: string, stored: string): Promise<boolean> {
+ return (await checkPassword(password, stored)) === "match";
+}
+
+/**
+ * Verifies a sign-in password for an account that may not exist, at the cost a real account's
+ * check has. `stored` is the account's hash, or null when there is no such account. When there is
+ * nothing to derive against — no account, an empty hash, or one `checkPassword` finds
+ * unverifiable — the password is checked against `dummyHash` instead and the result is false, so
+ * every call runs exactly one scrypt derivation and how long a failure takes does not tell a
+ * missing username from a wrong password. `check` is a parameter so a test can count the
+ * derivations.
+ */
+export async function verifyAccountPassword(
+ password: string,
+ stored: string | null,
+ dummyHash: () => Promise<string>,
+ check: (password: string, stored: string) => Promise<PasswordCheck> = checkPassword,
+): Promise<boolean> {
+ const outcome = stored === null ? "unverifiable" : await check(password, stored);
+ if (outcome !== "unverifiable") return outcome === "match";
+ await check(password, await dummyHash());
+ return false;
}
/** Hashes the passwords this server writes; a test stands in a cheap one. */
diff --git a/packages/server/src/auth/service.ts b/packages/server/src/auth/service.ts
index fc8e64d8..3e1961cb 100644
--- a/packages/server/src/auth/service.ts
+++ b/packages/server/src/auth/service.ts
@@ -14,7 +14,7 @@ import type { UserRow } from "../db/repos/users.js";
import { sessionTokenHash } from "../db/repos/auth-sessions.js";
import type { SessionViaValue, AuthSessionsRepo } from "../db/repos/auth-sessions.js";
import type { AuthRuntimeState } from "./runtime-state.js";
-import { verifyPassword } from "./password.js";
+import { verifyAccountPassword, verifyPassword } from "./password.js";
import type { PasswordHasher } from "./password.js";
import { Component, Use, Interface } from "@prismshadow/penguin-core/kernel";
import type { AuthState, Clock, Config } from "../hmr/capabilities.js";
@@ -28,9 +28,10 @@ export const ADMIN_USER_ID = "admin";
/**
* 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.
+ * Kept for nonexistent userIds too, so it is not an account-existence oracle — and neither is
+ * the time a failure takes: a nonexistent userId is checked against a dummy hash (loginDummyHash).
+ * 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;
@@ -177,6 +178,20 @@ export class AuthService implements Auth {
/** Consecutive login failures per userId (see the throttling comment on the constants). */
private readonly loginFailures = new Map<string, { failures: number; lastFailureAt: number }>();
+ /** Cache for loginDummyHash. */
+ private dummyHash: string | null = null;
+
+ /**
+ * The hash a sign-in with no account to check is verified against (verifyAccountPassword), so
+ * it costs what a wrong password costs. Made by this server's own hasher, hence at the cost its
+ * real hashes carry, from a random password nobody holds; computed on the first such sign-in
+ * and kept.
+ */
+ private async loginDummyHash(): Promise<string> {
+ this.dummyHash ??= await this.hasher.hash(randomBytes(18).toString("base64url"));
+ return this.dummyHash;
+ }
+
/** The wait imposed after `failures` consecutive failures (0 while within the free attempts). */
private loginDelayMs(failures: number): number {
const excess = failures - LOGIN_FREE_ATTEMPTS;
@@ -201,7 +216,11 @@ export class AuthService implements Auth {
}
}
const row = this.users.findById(userId);
- const ok = row !== null && (await verifyPassword(password, row.passwordHash));
+ // A missing account, or one whose hash cannot be checked, still costs one scrypt
+ // derivation, and fails with the same 401 as a wrong password.
+ const ok = await verifyAccountPassword(password, row?.passwordHash ?? null, () =>
+ this.loginDummyHash(),
+ );
if (!row || !ok) {
this.loginFailures.set(userId, {
failures: (failed?.failures ?? 0) + 1,
diff --git a/packages/server/test/auth.test.ts b/packages/server/test/auth.test.ts
index aa0c2eeb..9c4e2698 100644
--- a/packages/server/test/auth.test.ts
+++ b/packages/server/test/auth.test.ts
@@ -7,6 +7,7 @@ import path from "node:path";
import { afterEach, beforeEach, describe, expect, it } from "vitest";
import type { MeResponse, ProjectsResponse } from "../src/api/types.js";
import { bootAppDeps } from "../src/app.js";
+import { hashPassword, ScryptHasher } from "../src/auth/password.js";
import { generateInitialAdminPassword } from "../src/auth/service.js";
import {
apiClient,
@@ -269,6 +270,73 @@ describe("auth", () => {
}
});
+ it("answers an unknown username exactly as it answers a wrong password", async () => {
+ await provisionUser(t.app, "carol");
+ // An account whose stored hash cannot be checked is no different either.
+ await provisionUser(t.app, "grace");
+ t.deps.db.prepare("UPDATE users SET password_hash = ? WHERE user_id = ?").run("", "grace");
+ const attempt = async (userId: string, password: string) => {
+ const res = await t.app.request("/api/auth/login", {
+ method: "POST",
+ headers: { "content-type": "application/json" },
+ body: JSON.stringify({ userId, password }),
+ });
+ return {
+ status: res.status,
+ headers: Object.fromEntries(res.headers),
+ body: await res.text(),
+ };
+ };
+ const wrongPassword = await attempt("carol", "wrong-password");
+ expect(wrongPassword.status).toBe(401);
+ expect(JSON.parse(wrongPassword.body)).toEqual({
+ error: { code: "invalid_credentials", message: "Incorrect username or password." },
+ });
+ expect(wrongPassword.headers["set-cookie"]).toBeUndefined();
+ expect(await attempt("nobody", "wrong-password")).toEqual(wrongPassword);
+ expect(await attempt("grace", "password-123")).toEqual(wrongPassword);
+ });
+
+ it("checks an unknown username against a dummy hash made once, by the server's own hasher", async () => {
+ const root = await makeTempRoot();
+ const hashed: string[] = [];
+ const hasher = {
+ async hash(password: string): Promise<string> {
+ const stored = await hashPassword(password, 2);
+ hashed.push(stored);
+ return stored;
+ },
+ };
+ const deps = flattenForTests(
+ await bootAppDeps(testConfig(root), [
+ ...replacementsFor({ log: () => {} }),
+ [ScryptHasher, hasher],
+ ]),
+ );
+ const invalid = { status: 401, code: "invalid_credentials" };
+ try {
+ await deps.authService.seedAdmin();
+ expect(hashed).toHaveLength(1);
+ // A wrong password on a real account is checked against that account's hash: no dummy.
+ await expect(deps.authService.login("admin", "wrong-password")).rejects.toMatchObject(
+ invalid,
+ );
+ expect(hashed).toHaveLength(1);
+ // The first unknown username makes the dummy, and every later one reuses it.
+ await expect(deps.authService.login("ghost", "whatever-123")).rejects.toMatchObject(invalid);
+ expect(hashed).toHaveLength(2);
+ await expect(deps.authService.login("phantom", "whatever-123")).rejects.toMatchObject(
+ invalid,
+ );
+ expect(hashed).toHaveLength(2);
+ } finally {
+ deps.hmr.dispose();
+ deps.channels.dispose();
+ deps.db.close();
+ await fs.rm(root, { recursive: true, force: true, maxRetries: 10, retryDelay: 100 });
+ }
+ });
+
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.
diff --git a/packages/server/test/password.test.ts b/packages/server/test/password.test.ts
index ded7ec3b..1b9618f4 100644
--- a/packages/server/test/password.test.ts
+++ b/packages/server/test/password.test.ts
@@ -1,10 +1,19 @@
/**
* Unit tests for scrypt password hashing: format, verification, salt randomness,
- * and fallback behavior for invalid stored strings. These call `hashPassword` without a
- * cost argument, so they are the one place the production work factor is exercised.
+ * and fallback behavior for invalid stored strings. The `password` cases call `hashPassword`
+ * without a cost argument, so they are the one place the production work factor is exercised.
+ * The account-check cases hash at a token cost: they count derivations through an injected
+ * check, never time them.
*/
-import { describe, expect, it } from "vitest";
-import { SCRYPT_COST, hashPassword, verifyPassword } from "../src/auth/password.js";
+import { describe, expect, it, vi } from "vitest";
+import {
+ SCRYPT_COST,
+ checkPassword,
+ hashPassword,
+ verifyAccountPassword,
+ verifyPassword,
+} from "../src/auth/password.js";
+import type { PasswordCheck } from "../src/auth/password.js";
describe("password", () => {
it("hash format is scrypt$N$r$p$salt$hash and verifies", async () => {
@@ -38,3 +47,74 @@ describe("password", () => {
await expect(verifyPassword("x", "scrypt$abc$8$1$!!$!!")).resolves.toBe(false);
});
});
+
+describe("account password check", () => {
+ /** A token work factor: nothing here depends on how long a derivation takes. */
+ const COST = 2;
+ /** Well-formed, but N = 3 is not a power of two: scrypt refuses it before deriving anything. */
+ const REFUSED_PARAMETERS = "scrypt$3$8$1$c2FsdHNhbHQ=$aGFzaGhhc2g=";
+
+ /** The real check, recording what each call checked against and what it found. */
+ function recordingCheck() {
+ const calls: Array<{ stored: string; outcome: PasswordCheck }> = [];
+ const check = async (password: string, stored: string): Promise<PasswordCheck> => {
+ const outcome = await checkPassword(password, stored);
+ calls.push({ stored, outcome });
+ return outcome;
+ };
+ /** The calls that ran a scrypt derivation. */
+ const derivations = () => calls.filter((call) => call.outcome !== "unverifiable");
+ return { calls, check, derivations };
+ }
+
+ it("checkPassword tells a mismatch from a hash it cannot check", async () => {
+ const stored = await hashPassword("right-password", COST);
+ await expect(checkPassword("right-password", stored)).resolves.toBe("match");
+ await expect(checkPassword("wrong-password", stored)).resolves.toBe("mismatch");
+ await expect(checkPassword("right-password", "")).resolves.toBe("unverifiable");
+ await expect(checkPassword("right-password", "not-a-hash")).resolves.toBe("unverifiable");
+ await expect(checkPassword("right-password", REFUSED_PARAMETERS)).resolves.toBe("unverifiable");
+ });
+
+ it("checks an unknown username against the dummy hash, once, and fails", async () => {
+ const dummy = await hashPassword("held-by-nobody", COST);
+ const dummyHash = vi.fn(async () => dummy);
+ const { calls, check } = recordingCheck();
+ await expect(verifyAccountPassword("guess-123", null, dummyHash, check)).resolves.toBe(false);
+ expect(dummyHash).toHaveBeenCalledTimes(1);
+ expect(calls).toEqual([{ stored: dummy, outcome: "mismatch" }]);
+ // The dummy never signs anyone in, even with the password it was made from.
+ await expect(verifyAccountPassword("held-by-nobody", null, dummyHash, check)).resolves.toBe(
+ false,
+ );
+ });
+
+ it("checks a real account against its own hash, once, without the dummy", async () => {
+ const stored = await hashPassword("right-password", COST);
+ const dummyHash = vi.fn(async () => hashPassword("held-by-nobody", COST));
+ const wrong = recordingCheck();
+ await expect(
+ verifyAccountPassword("wrong-password", stored, dummyHash, wrong.check),
+ ).resolves.toBe(false);
+ expect(wrong.calls).toEqual([{ stored, outcome: "mismatch" }]);
+ const right = recordingCheck();
+ await expect(
+ verifyAccountPassword("right-password", stored, dummyHash, right.check),
+ ).resolves.toBe(true);
+ expect(right.calls).toEqual([{ stored, outcome: "match" }]);
+ expect(dummyHash).not.toHaveBeenCalled();
+ });
+
+ it("spends the one derivation on the dummy when the stored hash cannot be checked", async () => {
+ const dummy = await hashPassword("held-by-nobody", COST);
+ for (const stored of ["", "not-a-hash", "bcrypt$a$b$c$d$e", REFUSED_PARAMETERS]) {
+ const { check, derivations } = recordingCheck();
+ await expect(
+ verifyAccountPassword("right-password", stored, async () => dummy, check),
+ ).resolves.toBe(false);
+ expect(derivations(), `stored ${JSON.stringify(stored)}`).toEqual([
+ { stored: dummy, outcome: "mismatch" },
+ ]);
+ }
+ });
+});