@prismshadow/penguin-server 0.2.9 → 0.2.11

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (37) hide show
  1. package/README.md +1 -0
  2. package/dist/api/types.d.ts +426 -87
  3. package/dist/auth-token.js +4 -2
  4. package/dist/auth-token.js.map +1 -1
  5. package/dist/{chunk-WL5FUO3A.js → chunk-ADZJYDNC.js} +201 -140
  6. package/dist/chunk-ADZJYDNC.js.map +1 -0
  7. package/dist/{chunk-OMBFPEGQ.js → chunk-GOO5VUAB.js} +10 -8
  8. package/dist/chunk-GOO5VUAB.js.map +1 -0
  9. package/dist/chunk-HMTT2PX4.js +93 -0
  10. package/dist/chunk-HMTT2PX4.js.map +1 -0
  11. package/dist/chunk-HOS3W3UP.js +127 -0
  12. package/dist/chunk-HOS3W3UP.js.map +1 -0
  13. package/dist/{chunk-OTYHSDV7.js → chunk-Q65VPAQS.js} +2 -2
  14. package/dist/chunk-Q65VPAQS.js.map +1 -0
  15. package/dist/index.js +5587 -2922
  16. package/dist/index.js.map +1 -1
  17. package/dist/lock.d.ts +9 -1
  18. package/dist/lock.js +3 -1
  19. package/dist/machine-status.d.ts +18 -0
  20. package/dist/machine-status.js +37 -0
  21. package/dist/machine-status.js.map +1 -0
  22. package/dist/reset-admin-password.js +6 -4
  23. package/dist/reset-admin-password.js.map +1 -1
  24. package/package.json +6 -3
  25. package/web-dist/assets/addon-clipboard-1cARCaK9.js +1 -0
  26. package/web-dist/assets/{addon-fit-BjXzaLkS.js → addon-fit-BWdzl8Er.js} +1 -1
  27. package/web-dist/assets/{addon-web-links-D4HvCIde.js → addon-web-links-DjXuvn4Z.js} +1 -1
  28. package/web-dist/assets/{highlighter-Di8euoN5.js → highlighter-Cu43iYr8.js} +1 -1
  29. package/web-dist/assets/index-Bm9n7ZV-.js +457 -0
  30. package/web-dist/assets/index-DR4PrRzS.css +1 -0
  31. package/web-dist/assets/{xterm-XhYBaOEK.js → xterm-DKcY6q-I.js} +1 -1
  32. package/web-dist/index.html +2 -2
  33. package/dist/chunk-OMBFPEGQ.js.map +0 -1
  34. package/dist/chunk-OTYHSDV7.js.map +0 -1
  35. package/dist/chunk-WL5FUO3A.js.map +0 -1
  36. package/web-dist/assets/index-C6i84Esu.js +0 -451
  37. package/web-dist/assets/index-DW00p4Ny.css +0 -1
@@ -0,0 +1,93 @@
1
+ // src/db/repos/machines.ts
2
+ import { randomBytes } from "crypto";
3
+ var MACHINE_ID_BYTES = 12;
4
+ var MachinesRepo = class {
5
+ constructor(db) {
6
+ this.db = db;
7
+ }
8
+ db;
9
+ /**
10
+ * This server's own id if one has been minted, WITHOUT minting one — `penguin server
11
+ * status` runs on a data root whose server may never have started, and must not create an
12
+ * identity as a side effect of the question.
13
+ */
14
+ peekOwnId() {
15
+ const row = this.db.prepare("SELECT machine_id FROM machine WHERE singleton = 1").get();
16
+ return row ? row.machine_id : null;
17
+ }
18
+ /** This server's own id, minted on first call and stable ever after. */
19
+ ownId() {
20
+ const existing = this.peekOwnId();
21
+ if (existing !== null) return existing;
22
+ const minted = randomBytes(MACHINE_ID_BYTES).toString("base64url");
23
+ this.db.prepare("INSERT INTO machine (singleton, machine_id) VALUES (1, ?)").run(minted);
24
+ return minted;
25
+ }
26
+ get(address) {
27
+ const row = this.db.prepare("SELECT * FROM machines WHERE address = ?").get(address);
28
+ return row === void 0 ? null : toRow(row);
29
+ }
30
+ /**
31
+ * Every row answering to a machine's own id — two aliases for one host are two rows with
32
+ * one id. Newest install first, then by address, so the order is the same every time; which
33
+ * of them to speak through is the service's to decide (it knows which has a session).
34
+ */
35
+ byMachineId(machineId) {
36
+ return this.db.prepare(
37
+ "SELECT * FROM machines WHERE machine_id = ? ORDER BY installed_at DESC, address ASC"
38
+ ).all(machineId).map(toRow);
39
+ }
40
+ all() {
41
+ return this.db.prepare("SELECT * FROM machines").all().map(toRow);
42
+ }
43
+ /** Writes the fields given, creating the row when there is none. */
44
+ patch(address, patch) {
45
+ const next = {
46
+ ...this.get(address) ?? {
47
+ address,
48
+ machineId: null,
49
+ version: null,
50
+ installedAt: null,
51
+ sessionPid: null,
52
+ remotePort: null,
53
+ platform: null
54
+ },
55
+ ...patch
56
+ };
57
+ this.db.prepare(
58
+ "INSERT OR REPLACE INTO machines (address, machine_id, version, installed_at, session_pid, remote_port, platform) VALUES (?, ?, ?, ?, ?, ?, ?)"
59
+ ).run(
60
+ address,
61
+ next.machineId,
62
+ next.version,
63
+ next.installedAt,
64
+ next.sessionPid,
65
+ next.remotePort,
66
+ next.platform
67
+ );
68
+ }
69
+ /** The addresses a Project uses, or null when it has never had a list written for it. */
70
+ members(projectId) {
71
+ const row = this.db.prepare("SELECT addresses FROM machine_project WHERE project_id = ?").get(projectId);
72
+ return row ? JSON.parse(row.addresses) : null;
73
+ }
74
+ setMembers(projectId, addresses) {
75
+ this.db.prepare("INSERT OR REPLACE INTO machine_project (project_id, addresses) VALUES (?, ?)").run(projectId, JSON.stringify(addresses));
76
+ }
77
+ };
78
+ function toRow(row) {
79
+ return {
80
+ address: row.address,
81
+ machineId: row.machine_id ?? null,
82
+ version: row.version ?? null,
83
+ installedAt: row.installed_at ?? null,
84
+ sessionPid: row.session_pid ?? null,
85
+ remotePort: row.remote_port ?? null,
86
+ platform: row.platform ?? null
87
+ };
88
+ }
89
+
90
+ export {
91
+ MachinesRepo
92
+ };
93
+ //# sourceMappingURL=chunk-HMTT2PX4.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/db/repos/machines.ts"],"sourcesContent":["/**\n * What this server remembers about machines: its own identity, one row per machine it has\n * installed on or reached (what is installed there, the session held to it), and which\n * machines each Project uses. All in web.db, so a hot swap or a restart reads back exactly\n * what the last generation wrote — the JSON file this replaces could not survive a schema\n * change, and nothing else this server remembers lives outside the database.\n */\nimport type { DatabaseSync } from \"node:sqlite\";\nimport { randomBytes } from \"node:crypto\";\n\nexport interface MachineRow {\n /** `ssh:<alias>` */\n address: string;\n /** That machine's own id, once heard. */\n machineId: string | null;\n /** What this server last installed there; null when it never has. */\n version: string | null;\n installedAt: string | null;\n /**\n * Non-null while a connection to it is HELD: the pid of the session as of the last connect.\n * A record of intent, not a handle — a restart or a hot push re-holds every machine with one,\n * and a disconnect clears it. It is never used to kill anything: a pid read back from a file\n * may by then be anyone's.\n */\n sessionPid: number | null;\n /** The port its server was bound to over there, as of the last connect. */\n remotePort: number | null;\n /** What the install found the machine to be; null until one has. The status probe speaks that dialect. */\n platform: \"linux\" | \"darwin\" | \"win32\" | null;\n}\n\n/** Everything but the address may be patched; absent fields keep their value. */\ntype MachinePatch = Partial<Omit<MachineRow, \"address\">>;\n\n/**\n * 12 random bytes as base64url: 16 characters a person can read in a tooltip, 96 bits\n * against ids minted on machines that never coordinate.\n */\nconst MACHINE_ID_BYTES = 12;\n\nexport class MachinesRepo {\n constructor(private readonly db: DatabaseSync) {}\n\n /**\n * This server's own id if one has been minted, WITHOUT minting one — `penguin server\n * status` runs on a data root whose server may never have started, and must not create an\n * identity as a side effect of the question.\n */\n peekOwnId(): string | null {\n const row = this.db.prepare(\"SELECT machine_id FROM machine WHERE singleton = 1\").get();\n return row ? (row.machine_id as string) : null;\n }\n\n /** This server's own id, minted on first call and stable ever after. */\n ownId(): string {\n const existing = this.peekOwnId();\n if (existing !== null) return existing;\n const minted = randomBytes(MACHINE_ID_BYTES).toString(\"base64url\");\n this.db.prepare(\"INSERT INTO machine (singleton, machine_id) VALUES (1, ?)\").run(minted);\n return minted;\n }\n\n get(address: string): MachineRow | null {\n const row = this.db.prepare(\"SELECT * FROM machines WHERE address = ?\").get(address);\n return row === undefined ? null : toRow(row);\n }\n\n /**\n * Every row answering to a machine's own id — two aliases for one host are two rows with\n * one id. Newest install first, then by address, so the order is the same every time; which\n * of them to speak through is the service's to decide (it knows which has a session).\n */\n byMachineId(machineId: string): MachineRow[] {\n return this.db\n .prepare(\n \"SELECT * FROM machines WHERE machine_id = ? ORDER BY installed_at DESC, address ASC\",\n )\n .all(machineId)\n .map(toRow);\n }\n\n all(): MachineRow[] {\n return this.db.prepare(\"SELECT * FROM machines\").all().map(toRow);\n }\n\n /** Writes the fields given, creating the row when there is none. */\n patch(address: string, patch: MachinePatch): void {\n const next: MachineRow = {\n ...(this.get(address) ?? {\n address,\n machineId: null,\n version: null,\n installedAt: null,\n sessionPid: null,\n remotePort: null,\n platform: null,\n }),\n ...patch,\n };\n this.db\n .prepare(\n \"INSERT OR REPLACE INTO machines (address, machine_id, version, installed_at, session_pid, remote_port, platform) VALUES (?, ?, ?, ?, ?, ?, ?)\",\n )\n .run(\n address,\n next.machineId,\n next.version,\n next.installedAt,\n next.sessionPid,\n next.remotePort,\n next.platform,\n );\n }\n\n /** The addresses a Project uses, or null when it has never had a list written for it. */\n members(projectId: string): string[] | null {\n const row = this.db\n .prepare(\"SELECT addresses FROM machine_project WHERE project_id = ?\")\n .get(projectId);\n return row ? (JSON.parse(row.addresses as string) as string[]) : null;\n }\n\n setMembers(projectId: string, addresses: string[]): void {\n this.db\n .prepare(\"INSERT OR REPLACE INTO machine_project (project_id, addresses) VALUES (?, ?)\")\n .run(projectId, JSON.stringify(addresses));\n }\n}\n\nfunction toRow(row: Record<string, unknown>): MachineRow {\n return {\n address: row.address as string,\n machineId: (row.machine_id as string | null) ?? null,\n version: (row.version as string | null) ?? null,\n installedAt: (row.installed_at as string | null) ?? null,\n sessionPid: (row.session_pid as number | null) ?? null,\n remotePort: (row.remote_port as number | null) ?? null,\n platform: (row.platform as MachineRow[\"platform\"]) ?? null,\n };\n}\n"],"mappings":";AAQA,SAAS,mBAAmB;AA8B5B,IAAM,mBAAmB;AAElB,IAAM,eAAN,MAAmB;AAAA,EACxB,YAA6B,IAAkB;AAAlB;AAAA,EAAmB;AAAA,EAAnB;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAO7B,YAA2B;AACzB,UAAM,MAAM,KAAK,GAAG,QAAQ,oDAAoD,EAAE,IAAI;AACtF,WAAO,MAAO,IAAI,aAAwB;AAAA,EA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ACvD,SAAK,GACF,QAAQ,8EAA8E,EACtF,IAAI,WAAW,KAAK,UAAU,SAAS,CAAC;AAAA,EAC7C;AACF;AAEA,SAAS,MAAM,KAA0C;AACvD,SAAO;AAAA,IACL,SAAS,IAAI;AAAA,IACb,WAAY,IAAI,cAAgC;AAAA,IAChD,SAAU,IAAI,WAA6B;AAAA,IAC3C,aAAc,IAAI,gBAAkC;AAAA,IACpD,YAAa,IAAI,eAAiC;AAAA,IAClD,YAAa,IAAI,eAAiC;AAAA,IAClD,UAAW,IAAI,YAAuC;AAAA,EACxD;AACF;","names":[]}
@@ -0,0 +1,127 @@
1
+ // src/db/repos/users.ts
2
+ function mapRow(r) {
3
+ return {
4
+ userId: r.user_id,
5
+ passwordHash: r.password_hash,
6
+ isAdmin: r.is_admin === 1,
7
+ passwordIsInitial: r.password_is_initial === 1,
8
+ createdAt: r.created_at
9
+ };
10
+ }
11
+ var UsersRepo = class {
12
+ constructor(db) {
13
+ this.db = db;
14
+ }
15
+ db;
16
+ insert(row) {
17
+ this.db.prepare(
18
+ "INSERT INTO users (user_id, password_hash, is_admin, password_is_initial, created_at) VALUES (?, ?, ?, ?, ?)"
19
+ ).run(
20
+ row.userId,
21
+ row.passwordHash,
22
+ row.isAdmin ? 1 : 0,
23
+ row.passwordIsInitial ? 1 : 0,
24
+ row.createdAt
25
+ );
26
+ }
27
+ findById(userId) {
28
+ const r = this.db.prepare("SELECT * FROM users WHERE user_id = ?").get(userId);
29
+ return r ? mapRow(r) : null;
30
+ }
31
+ /** All users (for the admin user backend), ordered by creation time ascending. */
32
+ list() {
33
+ const rows = this.db.prepare("SELECT * FROM users ORDER BY created_at ASC, user_id ASC").all();
34
+ return rows.map(mapRow);
35
+ }
36
+ count() {
37
+ const r = this.db.prepare("SELECT COUNT(*) AS n FROM users").get();
38
+ return r?.n ?? 0;
39
+ }
40
+ /** Update the password hash; isInitial marks whether the password was set by someone else (seed / admin). */
41
+ updatePassword(userId, passwordHash, isInitial) {
42
+ this.db.prepare("UPDATE users SET password_hash = ?, password_is_initial = ? WHERE user_id = ?").run(passwordHash, isInitial ? 1 : 0, userId);
43
+ }
44
+ /** Used by admin user deletion and account-creation compensation paths (owned Projects must be cleaned up first). */
45
+ delete(userId) {
46
+ this.db.prepare("DELETE FROM users WHERE user_id = ?").run(userId);
47
+ }
48
+ };
49
+
50
+ // src/db/repos/auth-sessions.ts
51
+ import { createHash, randomBytes } from "crypto";
52
+ function sessionTokenHash(token) {
53
+ return createHash("sha256").update(token).digest("hex");
54
+ }
55
+ var AuthSessionsRepo = class {
56
+ constructor(db) {
57
+ this.db = db;
58
+ }
59
+ db;
60
+ /**
61
+ * Mints a session and returns the raw token for a cookie or the terminal. `maxTtlMs` caps a
62
+ * caller-supplied lifetime (`--ttl-seconds`): one longer than an ordinary session would make
63
+ * a leaked token file outlive every other credential, sliding forever. Expired rows are
64
+ * swept here too, so a cron that only mints does not accumulate them.
65
+ */
66
+ issue(opts) {
67
+ const ttlMs = Math.max(1e3, Math.min(opts.ttlMs, opts.maxTtlMs ?? opts.ttlMs));
68
+ const token = randomBytes(32).toString("base64url");
69
+ const createdAt = opts.now.toISOString();
70
+ const expiresAt = new Date(opts.now.getTime() + ttlMs).toISOString();
71
+ this.deleteExpired(createdAt);
72
+ this.insert({
73
+ tokenHash: sessionTokenHash(token),
74
+ userId: opts.userId,
75
+ createdAt,
76
+ expiresAt,
77
+ via: opts.via
78
+ });
79
+ return { token, expiresAt };
80
+ }
81
+ insert(row) {
82
+ this.db.prepare(
83
+ "INSERT INTO auth_sessions (token_hash, user_id, created_at, expires_at, via) VALUES (?, ?, ?, ?, ?)"
84
+ ).run(row.tokenHash, row.userId, row.createdAt, row.expiresAt, row.via);
85
+ }
86
+ findByTokenHash(tokenHash) {
87
+ const r = this.db.prepare("SELECT * FROM auth_sessions WHERE token_hash = ?").get(tokenHash);
88
+ if (!r) return null;
89
+ return {
90
+ tokenHash: r.token_hash,
91
+ userId: r.user_id,
92
+ createdAt: r.created_at,
93
+ expiresAt: r.expires_at,
94
+ via: r.via ?? null
95
+ };
96
+ }
97
+ /** Sliding renewal: update the expiration time. */
98
+ touch(tokenHash, expiresAt) {
99
+ this.db.prepare("UPDATE auth_sessions SET expires_at = ? WHERE token_hash = ?").run(expiresAt, tokenHash);
100
+ }
101
+ delete(tokenHash) {
102
+ this.db.prepare("DELETE FROM auth_sessions WHERE token_hash = ?").run(tokenHash);
103
+ }
104
+ /** Opportunistically clean up expired sessions (called during login/validation). */
105
+ deleteExpired(nowIso) {
106
+ this.db.prepare("DELETE FROM auth_sessions WHERE expires_at < ?").run(nowIso);
107
+ }
108
+ /** Clear all sessions for a user (forces re-login after an admin resets the password). */
109
+ deleteByUser(userId) {
110
+ this.db.prepare("DELETE FROM auth_sessions WHERE user_id = ?").run(userId);
111
+ }
112
+ /**
113
+ * Clear a user's sessions of one kind. Used to end EVERY first-login session when a password
114
+ * is set: an earlier boot's link may still be live in someone's scrollback, and a `setup`
115
+ * session may change the password without knowing the old one.
116
+ */
117
+ deleteByUserAndVia(userId, via) {
118
+ this.db.prepare("DELETE FROM auth_sessions WHERE user_id = ? AND via = ?").run(userId, via);
119
+ }
120
+ };
121
+
122
+ export {
123
+ UsersRepo,
124
+ sessionTokenHash,
125
+ AuthSessionsRepo
126
+ };
127
+ //# sourceMappingURL=chunk-HOS3W3UP.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/db/repos/users.ts","../src/db/repos/auth-sessions.ts"],"sourcesContent":["/**\n * users table repo: pure SQL wrapper, no business rules.\n * user_id is the login name (a semantic id, specified at creation, immutable).\n */\nimport type { DatabaseSync } from \"node:sqlite\";\n\nexport interface UserRow {\n userId: string;\n passwordHash: string;\n isAdmin: boolean;\n /** Still using the initial password (seeded / set by an admin); cleared to 0 once the user changes it. */\n passwordIsInitial: boolean;\n createdAt: string;\n}\n\nfunction mapRow(r: Record<string, unknown>): UserRow {\n return {\n userId: r.user_id as string,\n passwordHash: r.password_hash as string,\n isAdmin: (r.is_admin as number) === 1,\n passwordIsInitial: (r.password_is_initial as number) === 1,\n createdAt: r.created_at as string,\n };\n}\n\nexport class UsersRepo {\n constructor(private readonly db: DatabaseSync) {}\n\n insert(row: UserRow): void {\n this.db\n .prepare(\n \"INSERT INTO users (user_id, password_hash, is_admin, password_is_initial, created_at) VALUES (?, ?, ?, ?, ?)\",\n )\n .run(\n row.userId,\n row.passwordHash,\n row.isAdmin ? 1 : 0,\n row.passwordIsInitial ? 1 : 0,\n row.createdAt,\n );\n }\n\n findById(userId: string): UserRow | null {\n const r = this.db.prepare(\"SELECT * FROM users WHERE user_id = ?\").get(userId);\n return r ? mapRow(r) : null;\n }\n\n /** All users (for the admin user backend), ordered by creation time ascending. */\n list(): UserRow[] {\n const rows = this.db.prepare(\"SELECT * FROM users ORDER BY created_at ASC, user_id ASC\").all();\n return rows.map(mapRow);\n }\n\n count(): number {\n const r = this.db.prepare(\"SELECT COUNT(*) AS n FROM users\").get();\n return (r?.n as number) ?? 0;\n }\n\n /** Update the password hash; isInitial marks whether the password was set by someone else (seed / admin). */\n updatePassword(userId: string, passwordHash: string, isInitial: boolean): void {\n this.db\n .prepare(\"UPDATE users SET password_hash = ?, password_is_initial = ? WHERE user_id = ?\")\n .run(passwordHash, isInitial ? 1 : 0, userId);\n }\n\n /** Used by admin user deletion and account-creation compensation paths (owned Projects must be cleaned up first). */\n delete(userId: string): void {\n this.db.prepare(\"DELETE FROM users WHERE user_id = ?\").run(userId);\n }\n}\n","/**\n * auth_sessions table repo (server-side sessions backing the HttpOnly cookie). Stores only\n * sha256(token); the raw token appears only in the cookie. `issue()` is the ONE minting point,\n * so a CLI-minted row cannot drift from one the server issues itself.\n */\nimport { createHash, randomBytes } from \"node:crypto\";\nimport type { DatabaseSync } from \"node:sqlite\";\n\n/** How a session was established, as stored. NULL on rows formed before the column existed. */\nexport type SessionViaValue = \"password\" | \"desktop\" | \"setup\" | \"cli\";\n\nexport interface AuthSessionRow {\n tokenHash: string;\n userId: string;\n createdAt: string;\n expiresAt: string;\n via: SessionViaValue | null;\n}\n\n/** sha256 hex of a raw session token — the only form the database ever holds. */\nexport function sessionTokenHash(token: string): string {\n return createHash(\"sha256\").update(token).digest(\"hex\");\n}\n\nexport class AuthSessionsRepo {\n constructor(private readonly db: DatabaseSync) {}\n\n /**\n * Mints a session and returns the raw token for a cookie or the terminal. `maxTtlMs` caps a\n * caller-supplied lifetime (`--ttl-seconds`): one longer than an ordinary session would make\n * a leaked token file outlive every other credential, sliding forever. Expired rows are\n * swept here too, so a cron that only mints does not accumulate them.\n */\n issue(opts: {\n userId: string;\n via: SessionViaValue;\n now: Date;\n ttlMs: number;\n maxTtlMs?: number;\n }): { token: string; expiresAt: string } {\n const ttlMs = Math.max(1_000, Math.min(opts.ttlMs, opts.maxTtlMs ?? opts.ttlMs));\n const token = randomBytes(32).toString(\"base64url\");\n const createdAt = opts.now.toISOString();\n const expiresAt = new Date(opts.now.getTime() + ttlMs).toISOString();\n this.deleteExpired(createdAt);\n this.insert({\n tokenHash: sessionTokenHash(token),\n userId: opts.userId,\n createdAt,\n expiresAt,\n via: opts.via,\n });\n return { token, expiresAt };\n }\n\n insert(row: AuthSessionRow): void {\n this.db\n .prepare(\n \"INSERT INTO auth_sessions (token_hash, user_id, created_at, expires_at, via) VALUES (?, ?, ?, ?, ?)\",\n )\n .run(row.tokenHash, row.userId, row.createdAt, row.expiresAt, row.via);\n }\n\n findByTokenHash(tokenHash: string): AuthSessionRow | null {\n const r = this.db.prepare(\"SELECT * FROM auth_sessions WHERE token_hash = ?\").get(tokenHash);\n if (!r) return null;\n return {\n tokenHash: r.token_hash as string,\n userId: r.user_id as string,\n createdAt: r.created_at as string,\n expiresAt: r.expires_at as string,\n via: (r.via as SessionViaValue | null) ?? null,\n };\n }\n\n /** Sliding renewal: update the expiration time. */\n touch(tokenHash: string, expiresAt: string): void {\n this.db\n .prepare(\"UPDATE auth_sessions SET expires_at = ? WHERE token_hash = ?\")\n .run(expiresAt, tokenHash);\n }\n\n delete(tokenHash: string): void {\n this.db.prepare(\"DELETE FROM auth_sessions WHERE token_hash = ?\").run(tokenHash);\n }\n\n /** Opportunistically clean up expired sessions (called during login/validation). */\n deleteExpired(nowIso: string): void {\n this.db.prepare(\"DELETE FROM auth_sessions WHERE expires_at < ?\").run(nowIso);\n }\n\n /** Clear all sessions for a user (forces re-login after an admin resets the password). */\n deleteByUser(userId: string): void {\n this.db.prepare(\"DELETE FROM auth_sessions WHERE user_id = ?\").run(userId);\n }\n\n /**\n * Clear a user's sessions of one kind. Used to end EVERY first-login session when a password\n * is set: an earlier boot's link may still be live in someone's scrollback, and a `setup`\n * session may change the password without knowing the old one.\n */\n deleteByUserAndVia(userId: string, via: SessionViaValue): void {\n this.db.prepare(\"DELETE FROM auth_sessions WHERE user_id = ? AND via = ?\").run(userId, via);\n }\n}\n"],"mappings":";AAeA,SAAS,OAAO,GAAqC;AACnD,SAAO;AAAA,IACL,QAAQ,EAAE;AAAA,IACV,cAAc,EAAE;AAAA,IAChB,SAAU,EAAE,aAAwB;AAAA,IACpC,mBAAoB,EAAE,wBAAmC;AAAA,IACzD,WAAW,EAAE;AAAA,EACf;AACF;AAEO,IAAM,YAAN,MAAgB;AAAA,EACrB,YAA6B,IAAkB;AAAlB;AAAA,EAAmB;AAAA,EAAnB;AAAA,EAE7B,OAAO,KAAoB;AACzB,SAAK,GACF;AAAA,MACC;AAAA,IACF,EACC;AAAA,MACC,IAAI;AAAA,MACJ,IAAI;AAAA,MACJ,IAAI,UAAU,IAAI;AAAA,MAClB,IAAI,oBAAoB,IAAI;AAAA,MAC5B,IAAI;AAAA,IACN;AAAA,EACJ;AAAA,EAEA,SAAS,QAAgC;AACvC,UAAM,IAAI,KAAK,GAAG,QAAQ,uCAAuC,EAAE,IAAI,MAAM;AAC7E,WAAO,IAAI,OAAO,CAAC,IAAI;AAAA,EACzB;AAAA;AAAA,EAGA,OAAkB;AAChB,UAAM,OAAO,KAAK,GAAG,QAAQ,0DAA0D,EAAE,IAAI;AAC7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IAAI,WAAW,IAAI,GAAG;AAAA,EACzE;AAAA,EAEA,gBAAgB,WAA0C;AACxD,UAAM,IAAI,KAAK,GAAG,QAAQ,kDAAkD,EAAE,IAAI,SAAS;AAC3F,QAAI,CAAC,EAAG,QAAO;AACf,WAAO;AAAA,MACL,WAAW,EAAE;AAAA,MACb,QAAQ,EAAE;AAAA,MACV,WAAW,EAAE;AAAA,MACb,WAAW,EAAE;AAAA,MACb,KAAM,EAAE,OAAkC;AAAA,IAC5C;AAAA,EACF;AAAA;AAAA,EAGA,MAAM,WAAmB,WAAyB;AAChD,SAAK,GACF,QAAQ,8DAA8D,EACtE,IAAI,WAAW,SAAS;AAAA,EAC7B;AAAA,EAEA,OAAO,WAAyB;AAC9B,SAAK,GAAG,QAAQ,gDAAgD,EAAE,IAAI,SAAS;AAAA,EACjF;AAAA;AAAA,EAGA,cAAc,QAAsB;AAClC,SAAK,GAAG,QAAQ,gDAAgD,EAAE,IAAI,MAAM;AAAA,EAC9E;AAAA;AAAA,EAGA,aAAa,QAAsB;AACjC,SAAK,GAAG,QAAQ,6CAA6C,EAAE,IAAI,MAAM;AAAA,EAC3E;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAOA,mBAAmB,QAAgB,KAA4B;AAC7D,SAAK,GAAG,QAAQ,yDAAyD,EAAE,IAAI,QAAQ,GAAG;AAAA,EAC5F;AACF;","names":[]}
@@ -1,6 +1,6 @@
1
1
  import {
2
2
  sessionTokenHash
3
- } from "./chunk-WL5FUO3A.js";
3
+ } from "./chunk-HOS3W3UP.js";
4
4
 
5
5
  // src/auth/password.ts
6
6
  import { randomBytes, scrypt, timingSafeEqual } from "crypto";
@@ -371,4 +371,4 @@ export {
371
371
  toUserInfo,
372
372
  AuthService
373
373
  };
374
- //# sourceMappingURL=chunk-OTYHSDV7.js.map
374
+ //# sourceMappingURL=chunk-Q65VPAQS.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/auth/password.ts","../src/auth/service.ts","../src/auth/api-token.ts","../src/http/errors.ts"],"sourcesContent":["/**\n * Password hashing (slow-hash storage).\n *\n * Uses node:crypto's scrypt (built-in, no extra dependency, meets the same\n * slow-hash requirement as bcrypt/argon2). Storage format:\n * `scrypt$N$r$p$<salt b64>$<hash b64>` — parameters are stored alongside the hash,\n * so old hashes remain verifiable after future parameter tuning; comparison uses\n * timingSafeEqual to guard against timing side-channels.\n */\nimport { randomBytes, scrypt, timingSafeEqual } from \"node:crypto\";\n\n/**\n * Work factor for new hashes. `hashPassword` takes it as a defaulted argument so the server's\n * own test suite can hash at a token cost: almost every case there seeds an admin, provisions\n * users and logs them in, and one derivation at this strength costs on the order of 100ms.\n * Nothing on the production path passes the argument, and no configuration reaches it —\n * `buildAppDeps`, which carries the test override, is not part of this package's exports.\n */\nexport const SCRYPT_COST = 16384;\nconst SCRYPT_R = 8;\nconst SCRYPT_P = 1;\nconst SALT_BYTES = 16;\nconst KEY_BYTES = 64;\n\nfunction scryptAsync(\n password: string,\n salt: Buffer,\n keyLen: number,\n n: number,\n r: number,\n p: number,\n): Promise<Buffer> {\n return new Promise((resolve, reject) => {\n scrypt(password, salt, keyLen, { N: n, r, p, maxmem: 128 * 1024 * 1024 }, (err, key) => {\n if (err) reject(err);\n else resolve(key);\n });\n });\n}\n\n/**\n * Generates a password hash in `scrypt$N$r$p$salt$hash` format. `cost` is scrypt's N and\n * is recorded in the hash, so `verifyPassword` re-derives at whatever cost produced the\n * stored string.\n */\nexport async function hashPassword(password: string, cost: number = SCRYPT_COST): Promise<string> {\n const salt = randomBytes(SALT_BYTES);\n const key = await scryptAsync(password, salt, KEY_BYTES, cost, SCRYPT_R, SCRYPT_P);\n return [\n \"scrypt\",\n String(cost),\n String(SCRYPT_R),\n String(SCRYPT_P),\n salt.toString(\"base64\"),\n key.toString(\"base64\"),\n ].join(\"$\");\n}\n\n/** 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). */\nexport async function verifyPassword(password: string, stored: string): Promise<boolean> {\n const parts = stored.split(\"$\");\n if (parts.length !== 6 || parts[0] !== \"scrypt\") return false;\n const n = Number(parts[1]);\n const r = Number(parts[2]);\n const p = Number(parts[3]);\n if (!Number.isInteger(n) || !Number.isInteger(r) || !Number.isInteger(p)) return false;\n let salt: Buffer;\n let expected: Buffer;\n try {\n salt = Buffer.from(parts[4]!, \"base64\");\n expected = Buffer.from(parts[5]!, \"base64\");\n } catch {\n return false;\n }\n if (salt.length === 0 || expected.length === 0) return false;\n let actual: Buffer;\n try {\n actual = await scryptAsync(password, salt, expected.length, n, r, p);\n } catch {\n return false;\n }\n return actual.length === expected.length && timingSafeEqual(actual, expected);\n}\n","/**\n * Auth service: admin seeding / login / logout / password change / session validation.\n *\n * No open registration: an empty users table seeds `admin` with a random password hashed and\n * discarded unseen, claimed through the first-login link; every other user is created by an\n * admin. Sessions are rows in auth_sessions (cookie holds the token, the row its sha256), so\n * they outlive a restart and renew in place.\n */\nimport { randomBytes } from \"node:crypto\";\nimport { tokensEqual } from \"./api-token.js\";\nimport type { UserInfo } from \"../api/types.js\";\nimport { HttpError } from \"../http/errors.js\";\nimport type { UserRow, UsersRepo } from \"../db/repos/users.js\";\nimport { sessionTokenHash } from \"../db/repos/auth-sessions.js\";\nimport type { SessionViaValue, AuthSessionsRepo } from \"../db/repos/auth-sessions.js\";\nimport type { AuthRuntimeState } from \"./runtime-state.js\";\nimport { SCRYPT_COST, hashPassword, verifyPassword } from \"./password.js\";\n\nexport const MIN_PASSWORD_LENGTH = 8;\n\n/** Built-in admin user_id. */\nexport const ADMIN_USER_ID = \"admin\";\n\n/**\n * Login throttling, per userId. After LOGIN_FREE_ATTEMPTS failures each attempt waits an\n * exponentially growing delay (1s doubling to a 60s cap), settling at a guess per minute.\n * Kept for nonexistent userIds too, so it is not an account-existence oracle. Deliberately NOT\n * covered: a concurrent burst before the first failure lands, and guesses spread across many\n * accounts.\n */\nconst LOGIN_FREE_ATTEMPTS = 5;\nconst LOGIN_BACKOFF_START_MS = 1000;\nconst LOGIN_BACKOFF_CAP_MS = 60_000;\n/** Failure entries idle longer than this are swept (bounds the map; far above the cap). */\nconst LOGIN_FAILURE_IDLE_MS = 15 * 60_000;\n\n/** Characters of base64url in a seeded password — 18 random bytes, 144 bits. */\nconst SEED_PASSWORD_CHARS = 24;\n\n/**\n * Never read or typed — hashed at once and discarded — which is what lets it be long enough\n * that the login endpoint, reachable the moment the account exists, has no search space.\n */\nexport function generateInitialAdminPassword(): string {\n return randomBytes(SEED_PASSWORD_CHARS).toString(\"base64url\").slice(0, SEED_PASSWORD_CHARS);\n}\n\n/**\n * \"desktop\" and \"setup\" may set a password without the old one (theirs is random and was never\n * shown); desktop-only routes open to \"desktop\" alone. \"token\" is the local API token's Bearer\n * header — per request, never a stored row. Anything else reads as \"password\".\n */\nexport type SessionVia = \"password\" | \"desktop\" | \"setup\" | \"token\";\n\nexport function toUserInfo(row: UserRow): UserInfo {\n return {\n userId: row.userId,\n isAdmin: row.isAdmin,\n passwordIsInitial: row.passwordIsInitial,\n createdAt: row.createdAt,\n };\n}\n\nexport interface AuthServiceDeps {\n users: UsersRepo;\n authSessions: AuthSessionsRepo;\n /**\n * Process-scoped auth values (runtime-state.ts). Held by the RUNTIME so the link a boot\n * printed survives a platform push; everything else about auth is rebuilt with the App.\n */\n state: AuthRuntimeState;\n /** Provisions the initial Project at signup (injected by project-service, to avoid a circular dependency). */\n provisionInitialProject: (user: UserRow, isAdmin: boolean) => Promise<void>;\n /** Fixed initial password for the seeded admin (config.seedAdminPassword); null generates a random one at seed time. */\n seedAdminPassword: string | null;\n sessionTtlMs: number;\n sessionRenewMs: number;\n /** Test double: scrypt work factor for hashes this service writes (SCRYPT_COST in production). */\n passwordHashCost?: number;\n now?: () => Date;\n}\n\nexport class AuthService {\n private readonly now: () => Date;\n private readonly hashCost: number;\n /** Session lifetime, for the cookie that must expire WITH the session, not before it. */\n get sessionTtlMs(): number {\n return this.deps.sessionTtlMs;\n }\n\n constructor(private readonly deps: AuthServiceDeps) {\n this.now = deps.now ?? (() => new Date());\n this.hashCost = deps.passwordHashCost ?? SCRYPT_COST;\n this.deps.authSessions.deleteExpired(this.now().toISOString());\n }\n\n /**\n * Null once the server is claimed, so the only setup session that exists is a printed one.\n * On demand rather than in the constructor: seedAdmin() runs after it, so \"claimed?\" has no\n * answer there. A cached link whose row is gone is re-minted, not handed out dead.\n */\n mintFirstLogin(): string | null {\n if (!this.adminPasswordIsInitial()) return null;\n if (\n this.deps.state.firstLoginToken !== null &&\n this.authenticateWithMeta(this.deps.state.firstLoginToken) === null\n ) {\n this.deps.state.firstLoginToken = null;\n }\n this.deps.state.firstLoginToken ??= this.issueSession(ADMIN_USER_ID, \"setup\");\n return this.deps.state.firstLoginToken;\n }\n\n /**\n * For the startup notice's pinned-seed gate (index.ts): a pin usually means the operator\n * knows the password, but an offline reset makes it stale, and the gate must see through\n * that or the rescue link stays suppressed.\n */\n async adminPasswordIs(password: string): Promise<boolean> {\n const row = this.deps.users.findById(ADMIN_USER_ID);\n return row !== null && (await verifyPassword(password, row.passwordHash));\n }\n\n /**\n * Startup seeding (idempotent): creates the built-in admin and adopts default_project when\n * the users table is empty; if the initial Project fails, the user row is rolled back and\n * the server retries on next startup.\n */\n async seedAdmin(): Promise<void> {\n if (this.deps.users.count() > 0) return;\n const password = this.deps.seedAdminPassword ?? generateInitialAdminPassword();\n // A pinned override must meet the same policy as every other password — rejected before\n // any insert, so a configuration typo cannot create a trivially weak privileged account.\n if (password.length < MIN_PASSWORD_LENGTH) {\n throw new Error(\n `PENGUIN_SEED_ADMIN_PASSWORD must be at least ${MIN_PASSWORD_LENGTH} characters.`,\n );\n }\n const user: UserRow = {\n userId: ADMIN_USER_ID,\n passwordHash: await hashPassword(password, this.hashCost),\n isAdmin: true,\n passwordIsInitial: true,\n createdAt: this.now().toISOString(),\n };\n this.deps.users.insert(user);\n try {\n await this.deps.provisionInitialProject(user, true);\n } catch (err) {\n this.deps.users.delete(user.userId);\n throw err;\n }\n }\n\n /**\n * Compared against the printed value, not merely verified: a cookie made out of ANY valid\n * token would let one person hand another a link into the sender's account. Not single-use,\n * because a prefetching browser would burn it before its reader clicked.\n */\n redeemFirstLogin(given: string): string | null {\n const expected = this.deps.state.firstLoginToken;\n if (expected === null || given === \"\" || !tokensEqual(given, expected)) return null;\n return this.authenticateWithMeta(expected) === null ? null : expected;\n }\n\n /** Whether the built-in admin still runs on its initial password (gates the first-login link). */\n adminPasswordIsInitial(): boolean {\n return this.deps.users.findById(ADMIN_USER_ID)?.passwordIsInitial === true;\n }\n\n /** Consecutive login failures per userId (see the throttling comment on the constants). */\n private readonly loginFailures = new Map<string, { failures: number; lastFailureAt: number }>();\n\n /** The wait imposed after `failures` consecutive failures (0 while within the free attempts). */\n private loginDelayMs(failures: number): number {\n const excess = failures - LOGIN_FREE_ATTEMPTS;\n if (excess <= 0) return 0;\n return Math.min(LOGIN_BACKOFF_START_MS * 2 ** (excess - 1), LOGIN_BACKOFF_CAP_MS);\n }\n\n async login(userId: string, password: string): Promise<{ user: UserInfo; token: string }> {\n const nowMs = this.now().getTime();\n for (const [key, entry] of this.loginFailures) {\n if (nowMs - entry.lastFailureAt > LOGIN_FAILURE_IDLE_MS) this.loginFailures.delete(key);\n }\n const failed = this.loginFailures.get(userId);\n if (failed) {\n const readyAt = failed.lastFailureAt + this.loginDelayMs(failed.failures);\n if (nowMs < readyAt) {\n throw new HttpError(\n 429,\n \"too_many_attempts\",\n `Too many failed sign-in attempts. Try again in ${Math.ceil((readyAt - nowMs) / 1000)}s.`,\n );\n }\n }\n const row = this.deps.users.findById(userId);\n const ok = row !== null && (await verifyPassword(password, row.passwordHash));\n if (!row || !ok) {\n this.loginFailures.set(userId, {\n failures: (failed?.failures ?? 0) + 1,\n lastFailureAt: this.now().getTime(),\n });\n throw new HttpError(401, \"invalid_credentials\", \"Incorrect username or password.\");\n }\n this.loginFailures.delete(userId);\n this.deps.authSessions.deleteExpired(this.now().toISOString());\n return { user: toUserInfo(row), token: this.issueSession(row.userId, \"password\") };\n }\n\n /**\n * Desktop-mode sign-in: an admin session with no password check — the claim route already\n * redeemed the shell's one-shot token, which is the credential here. Throws only on a\n * broken deployment (seeding runs before the route exists).\n */\n loginDesktop(): { user: UserInfo; token: string } {\n const row = this.deps.users.findById(ADMIN_USER_ID);\n if (!row) {\n throw new HttpError(500, \"internal\", \"Built-in admin has not been seeded.\");\n }\n return { user: toUserInfo(row), token: this.issueSession(row.userId, \"desktop\") };\n }\n\n /** Self password change (user settings): validates the old password first; the current session stays valid. */\n async changePassword(userId: string, oldPassword: string, newPassword: string): Promise<void> {\n const row = this.deps.users.findById(userId);\n if (!row || !(await verifyPassword(oldPassword, row.passwordHash))) {\n throw new HttpError(400, \"password_mismatch\", \"Current password is incorrect.\");\n }\n await this.setPassword(userId, newPassword);\n }\n\n /** No old-password check; the me route gates which sessions may call this. */\n async setInitialPassword(userId: string, newPassword: string): Promise<void> {\n await this.setPassword(userId, newPassword);\n }\n\n /**\n * Validation comes FIRST, so a rejected password leaves the first-login link alive: burning\n * it on a typo would strand the claimer until a restart.\n */\n private async setPassword(userId: string, newPassword: string): Promise<void> {\n if (newPassword.length < MIN_PASSWORD_LENGTH) {\n throw new HttpError(400, \"invalid_password\", \"Password must be at least 8 characters.\");\n }\n this.deps.users.updatePassword(userId, await hashPassword(newPassword, this.hashCost), false);\n // A successful set proves at least what the successful login that resets the counter\n // proves (the old password, or a desktop/setup session), so it resets it too. Without\n // this, anyone spamming the login endpoint holds the backoff window open, and the sign-in\n // that follows a first-login claim (routes/me.ts) would 429 AFTER the password committed —\n // reporting failure for a change that took, with the claimer's setup session already gone.\n this.loginFailures.delete(userId);\n // EVERY first-login session for this account, not just the link this process printed: an\n // earlier boot's link can still be live in a terminal scrollback, and a `setup` session is\n // allowed to change the password without knowing the old one — so one left behind is an\n // account takeover waiting to happen.\n if (userId === ADMIN_USER_ID) {\n this.deps.authSessions.deleteByUserAndVia(userId, \"setup\");\n this.deps.state.firstLoginToken = null;\n }\n }\n\n /** Ends a session: the row is the session, so logout deletes it. Unknown token is a no-op. */\n logout(token: string): void {\n this.deps.authSessions.delete(sessionTokenHash(token));\n }\n\n /**\n * The current boot's local API token (what control-env injection hands to tool\n * subprocesses); null when none was minted. It lives on the runtime state, not on this\n * service: the token was written to `<root>/api-token` by the process, so it must\n * outlive the App a push replaces (auth/runtime-state.ts).\n */\n localApiToken(): string | null {\n return this.deps.state.apiToken;\n }\n\n /**\n * Validates a Bearer token against the boot's local API token (constant-time compare):\n * a match authenticates as the built-in admin — holding the token proves filesystem\n * access to the data root, which is admin authority (see auth/api-token.ts). Returns\n * null on mismatch, when no token was minted, or when the admin row is missing.\n */\n authenticateApiToken(token: string): { user: UserRow; via: SessionVia } | null {\n const apiToken = this.deps.state.apiToken;\n if (apiToken === null || token.length === 0) return null;\n if (!tokensEqual(token, apiToken)) return null;\n const user = this.deps.users.findById(ADMIN_USER_ID);\n return user === null ? null : { user, via: \"token\" };\n }\n\n /**\n * Validates the cookie token. Sliding renewal tops the expiry up IN PLACE, so the cookie\n * value never changes and there is no second identity to revoke. Only a session whose own\n * span reaches the renewal window slides — a one-hour minted token must expire at its hour,\n * not stretch by being used.\n */\n authenticateWithMeta(token: string): { user: UserRow; via: SessionVia; renewed: boolean } | null {\n const tokenHash = sessionTokenHash(token);\n const session = this.deps.authSessions.findByTokenHash(tokenHash);\n if (!session) return null;\n const now = this.now();\n const expiresAt = Date.parse(session.expiresAt);\n if (expiresAt <= now.getTime()) {\n this.deps.authSessions.delete(tokenHash);\n return null;\n }\n const user = this.deps.users.findById(session.userId);\n if (!user) return null;\n const renewable = expiresAt - Date.parse(session.createdAt) >= this.deps.sessionRenewMs;\n let renewed = false;\n if (renewable && expiresAt - now.getTime() < this.deps.sessionRenewMs) {\n this.deps.authSessions.touch(\n tokenHash,\n new Date(now.getTime() + this.deps.sessionTtlMs).toISOString(),\n );\n renewed = true;\n }\n const via: SessionVia =\n session.via === \"desktop\" ? \"desktop\" : session.via === \"setup\" ? \"setup\" : \"password\";\n return { user, via, renewed };\n }\n\n private issueSession(userId: string, via: SessionViaValue): string {\n return this.deps.authSessions.issue({\n userId,\n via,\n now: this.now(),\n ttlMs: this.deps.sessionTtlMs,\n }).token;\n }\n}\n","/**\n * Local API token (`<root>/api-token`): the machine-local credential behind\n * `Authorization: Bearer`.\n *\n * Minted fresh at every server boot (same recipe as auth-session tokens) and written to\n * the data root with owner-only permissions, so anything that can read the file can call\n * the API as the admin. That equivalence is the authorization model, not an accident:\n * local filesystem access to the data root already IS admin authority — the same rule\n * `penguin server reset-admin-password` stands on (whoever can run it owns web.db\n * anyway) — and agents driving their own harness through the CLI is the product feature\n * this token exists for (server-driven Sessions hand it to tool subprocesses as\n * PENGUIN_API_TOKEN). Rotation per boot bounds the life of any leaked copy to the\n * process that minted it.\n */\nimport { createHash, randomBytes, timingSafeEqual } from \"node:crypto\";\nimport fs from \"node:fs\";\nimport path from \"node:path\";\n\nexport function apiTokenPath(root: string): string {\n return path.join(root, \"api-token\");\n}\n\n/** Mints a boot-scoped local API token (the auth-session token recipe). */\nexport function mintApiToken(): string {\n return randomBytes(32).toString(\"base64url\");\n}\n\n/**\n * Persists the boot token (owner-only file, tmp + rename so a concurrent reader never\n * sees a partial write). Best-effort like the initial-password file: an exotic read-only\n * root must not stop the server — local CLI callers then fall back to\n * PENGUIN_API_TOKEN.\n */\nexport function storeApiToken(root: string, token: string): void {\n try {\n fs.mkdirSync(root, { recursive: true });\n const target = apiTokenPath(root);\n const tmp = `${target}.${process.pid}.tmp`;\n fs.writeFileSync(tmp, `${token}\\n`, { mode: 0o600 });\n fs.renameSync(tmp, target);\n } catch {\n // Best-effort: Bearer auth still works for callers holding the token some other way.\n }\n}\n\n/** The stored token, or null when absent/unreadable/empty (shared with the CLI's file fallback). */\nexport function readApiToken(root: string): string | null {\n try {\n const value = fs.readFileSync(apiTokenPath(root), \"utf8\").trim();\n return value === \"\" ? null : value;\n } catch {\n return null;\n }\n}\n\n/**\n * Constant-time equality for token checks: both sides are reduced to fixed-size sha256\n * digests first, so the comparison's timing depends on neither the content nor the\n * length of an attacker-supplied value.\n */\nexport function tokensEqual(a: string, b: string): boolean {\n const digest = (v: string): Buffer => createHash(\"sha256\").update(v).digest();\n return timingSafeEqual(digest(a), digest(b));\n}\n","/**\n * Unified HTTP error: `{error: {code, message}}` response body,\n * with message in English.\n *\n * Routes and services express business errors via throw HttpError; app-level onError\n * uniformly converges these into a JSON response, with unknown errors converged to 500\n * (never leaking internal details to the client).\n */\nimport type { Context } from \"hono\";\nimport type { ErrorBody } from \"../api/types.js\";\n\nexport class HttpError extends Error {\n constructor(\n readonly status: number,\n readonly code: string,\n message: string,\n ) {\n super(message);\n this.name = \"HttpError\";\n }\n}\n\nexport function errorBody(code: string, message: string): ErrorBody {\n return { error: { code, message } };\n}\n\n/**\n * Model missing a credential: the provider SDK throws this at **client-construction\n * time** (hit by both creating a Session and resuming a Session); the original message\n * is full of environment variable names, meaningless to a user — uniformly replaced\n * with a single actionable sentence. The frontend produces localized text by code\n * (message is only a fallback); see web's lib/api-error.ts.\n */\nexport function isMissingCredential(err: unknown): boolean {\n const message = err instanceof Error ? err.message : String(err);\n return /missing credentials|api[_ ]?key/i.test(message);\n}\n\nexport function modelCredentialMissing(modelId: string): HttpError {\n return new HttpError(\n 400,\n \"model_credential_missing\",\n `Model ${modelId} has no API key yet. Configure it on the Models page first.`,\n );\n}\n\n/** app.onError handler: maps HttpError through as-is; everything else is logged and converged to 500. */\nexport function handleError(err: Error, c: Context): Response {\n if (err instanceof HttpError) {\n return c.json(errorBody(err.code, err.message), err.status as 400);\n }\n // Unknown error: print the stack for diagnosis, but never expose details externally.\n console.error(`[server] Unhandled exception: ${err.stack ?? err.message}`);\n return c.json(errorBody(\"internal\", \"Internal server error.\"), 500);\n}\n"],"mappings":";;;;;AASA,SAAS,aAAa,QAAQ,uBAAuB;AAS9C,IAAM,cAAc;AAC3B,IAAM,WAAW;AACjB,IAAM,WAAW;AACjB,IAAM,aAAa;AACnB,IAAM,Y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