@prismshadow/penguin-server 0.2.7 → 0.2.9
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.
- package/README.md +4 -4
- package/dist/api/types.d.ts +528 -39
- package/dist/auth-token.d.ts +29 -0
- package/dist/auth-token.js +51 -0
- package/dist/auth-token.js.map +1 -0
- package/dist/chunk-K4ZSUT72.js +34 -0
- package/dist/chunk-K4ZSUT72.js.map +1 -0
- package/dist/chunk-OTYHSDV7.js +374 -0
- package/dist/chunk-OTYHSDV7.js.map +1 -0
- package/dist/{chunk-WKJ3ANJP.js → chunk-WL5FUO3A.js} +92 -381
- package/dist/chunk-WL5FUO3A.js.map +1 -0
- package/dist/extension/index.d.ts +212 -0
- package/dist/extension/index.js +1 -0
- package/dist/extension/index.js.map +1 -0
- package/dist/index.js +7337 -1774
- package/dist/index.js.map +1 -1
- package/dist/initial-password.d.ts +9 -12
- package/dist/initial-password.js +3 -7
- package/dist/install.ps1 +729 -0
- package/dist/install.sh +785 -0
- package/dist/reset-admin-password.d.ts +4 -7
- package/dist/reset-admin-password.js +11 -9
- package/dist/reset-admin-password.js.map +1 -1
- package/dist/secret-file.d.ts +3 -0
- package/dist/secret-file.js +17 -0
- package/dist/secret-file.js.map +1 -0
- package/package.json +19 -3
- package/web-dist/assets/KaTeX_AMS-Regular-BQhdFMY1.woff2 +0 -0
- package/web-dist/assets/KaTeX_Caligraphic-Bold-Dq_IR9rO.woff2 +0 -0
- package/web-dist/assets/KaTeX_Caligraphic-Regular-Di6jR-x-.woff2 +0 -0
- package/web-dist/assets/KaTeX_Fraktur-Bold-CL6g_b3V.woff2 +0 -0
- package/web-dist/assets/KaTeX_Fraktur-Regular-CTYiF6lA.woff2 +0 -0
- package/web-dist/assets/KaTeX_Main-Bold-Cx986IdX.woff2 +0 -0
- package/web-dist/assets/KaTeX_Main-BoldItalic-DxDJ3AOS.woff2 +0 -0
- package/web-dist/assets/KaTeX_Main-Italic-NWA7e6Wa.woff2 +0 -0
- package/web-dist/assets/KaTeX_Main-Regular-B22Nviop.woff2 +0 -0
- package/web-dist/assets/KaTeX_Math-BoldItalic-CZnvNsCZ.woff2 +0 -0
- package/web-dist/assets/KaTeX_Math-Italic-t53AETM-.woff2 +0 -0
- package/web-dist/assets/KaTeX_SansSerif-Bold-D1sUS0GD.woff2 +0 -0
- package/web-dist/assets/KaTeX_SansSerif-Italic-C3H0VqGB.woff2 +0 -0
- package/web-dist/assets/KaTeX_SansSerif-Regular-DDBCnlJ7.woff2 +0 -0
- package/web-dist/assets/KaTeX_Script-Regular-D3wIWfF6.woff2 +0 -0
- package/web-dist/assets/KaTeX_Size1-Regular-mCD8mA8B.woff2 +0 -0
- package/web-dist/assets/KaTeX_Size2-Regular-Dy4dx90m.woff2 +0 -0
- package/web-dist/assets/KaTeX_Size4-Regular-Dl5lxZxV.woff2 +0 -0
- package/web-dist/assets/KaTeX_Typewriter-Regular-CO6r4hn1.woff2 +0 -0
- package/web-dist/assets/{addon-fit-BXTX0Xqu.js → addon-fit-BjXzaLkS.js} +1 -1
- package/web-dist/assets/{addon-web-links-KebkunbU.js → addon-web-links-D4HvCIde.js} +1 -1
- package/web-dist/assets/{highlighter-B3HctNDB.js → highlighter-Di8euoN5.js} +1 -1
- package/web-dist/assets/index-C6i84Esu.js +451 -0
- package/web-dist/assets/index-DW00p4Ny.css +1 -0
- package/web-dist/assets/{xterm-fEUfDV0F.js → xterm-XhYBaOEK.js} +1 -1
- package/web-dist/index.html +2 -2
- package/dist/chunk-UUJCF46V.js +0 -50
- package/dist/chunk-UUJCF46V.js.map +0 -1
- package/dist/chunk-WKJ3ANJP.js.map +0 -1
- package/web-dist/assets/index-BbLm3DrY.css +0 -1
- package/web-dist/assets/index-DwgTjTHO.js +0 -189
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
/** An hour: long enough for a controller to finish, short enough to forget. */
|
|
2
|
+
declare const CLI_TOKEN_TTL_MS: number;
|
|
3
|
+
/**
|
|
4
|
+
* Ceiling on a caller-supplied `--ttl-seconds`, matching the default session TTL (config.ts):
|
|
5
|
+
* a token that lives in a file must not outlive an ordinary browser session.
|
|
6
|
+
*/
|
|
7
|
+
declare const CLI_TOKEN_MAX_TTL_MS: number;
|
|
8
|
+
type MintTokenResult = {
|
|
9
|
+
outcome: "minted";
|
|
10
|
+
token: string;
|
|
11
|
+
userId: string;
|
|
12
|
+
expiresAt: string;
|
|
13
|
+
}
|
|
14
|
+
/** No web.db on this root — the server has never run here, so there is no account to mint for. */
|
|
15
|
+
| {
|
|
16
|
+
outcome: "no_server";
|
|
17
|
+
} | {
|
|
18
|
+
outcome: "failed";
|
|
19
|
+
detail: string;
|
|
20
|
+
};
|
|
21
|
+
/** Issues an API session token for the data root at `root`. */
|
|
22
|
+
declare function mintApiToken(root: string, opts?: {
|
|
23
|
+
userId?: string;
|
|
24
|
+
ttlMs?: number;
|
|
25
|
+
dbPath?: string;
|
|
26
|
+
now?: Date;
|
|
27
|
+
}): MintTokenResult;
|
|
28
|
+
|
|
29
|
+
export { CLI_TOKEN_MAX_TTL_MS, CLI_TOKEN_TTL_MS, type MintTokenResult, mintApiToken };
|
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
import {
|
|
2
|
+
AuthSessionsRepo,
|
|
3
|
+
UsersRepo,
|
|
4
|
+
openExistingDatabase
|
|
5
|
+
} from "./chunk-WL5FUO3A.js";
|
|
6
|
+
|
|
7
|
+
// src/auth-token.ts
|
|
8
|
+
import path from "path";
|
|
9
|
+
import fs from "fs";
|
|
10
|
+
var CLI_TOKEN_TTL_MS = 60 * 6e4;
|
|
11
|
+
var CLI_TOKEN_MAX_TTL_MS = 30 * 24 * 60 * 6e4;
|
|
12
|
+
function explain(err, dbPath) {
|
|
13
|
+
const message = err instanceof Error ? err.message : String(err);
|
|
14
|
+
if (message.includes("no column named via")) {
|
|
15
|
+
return `${dbPath} predates this release \u2014 start the server once (\`penguin web\`) to upgrade it`;
|
|
16
|
+
}
|
|
17
|
+
if (message.includes("unable to open database")) {
|
|
18
|
+
return `cannot open ${dbPath} \u2014 minting needs the data root's own OS account; otherwise sign in with \`penguin auth login --server <url>\``;
|
|
19
|
+
}
|
|
20
|
+
return message;
|
|
21
|
+
}
|
|
22
|
+
function mintApiToken(root, opts = {}) {
|
|
23
|
+
const userId = opts.userId ?? "admin";
|
|
24
|
+
const dbPath = opts.dbPath ?? path.join(root, "web.db");
|
|
25
|
+
if (!fs.existsSync(dbPath)) return { outcome: "no_server" };
|
|
26
|
+
let db = null;
|
|
27
|
+
try {
|
|
28
|
+
db = openExistingDatabase(dbPath);
|
|
29
|
+
if (new UsersRepo(db).findById(userId) === null) {
|
|
30
|
+
return { outcome: "failed", detail: `no such account: ${userId}` };
|
|
31
|
+
}
|
|
32
|
+
const { token, expiresAt } = new AuthSessionsRepo(db).issue({
|
|
33
|
+
userId,
|
|
34
|
+
via: "cli",
|
|
35
|
+
now: opts.now ?? /* @__PURE__ */ new Date(),
|
|
36
|
+
ttlMs: opts.ttlMs ?? CLI_TOKEN_TTL_MS,
|
|
37
|
+
maxTtlMs: CLI_TOKEN_MAX_TTL_MS
|
|
38
|
+
});
|
|
39
|
+
return { outcome: "minted", token, userId, expiresAt };
|
|
40
|
+
} catch (err) {
|
|
41
|
+
return { outcome: "failed", detail: explain(err, dbPath) };
|
|
42
|
+
} finally {
|
|
43
|
+
db?.close();
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
export {
|
|
47
|
+
CLI_TOKEN_MAX_TTL_MS,
|
|
48
|
+
CLI_TOKEN_TTL_MS,
|
|
49
|
+
mintApiToken
|
|
50
|
+
};
|
|
51
|
+
//# sourceMappingURL=auth-token.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/auth-token.ts"],"sourcesContent":["/**\n * Mints an API session by inserting a row into the root's `web.db` — no running server needed.\n * Authorized by being able to read and write that root, which already holds every credential\n * the token could reach. On a multi-user box that means the OS account running the server;\n * everyone else signs in with `penguin auth login --server <url>`.\n */\nimport path from \"node:path\";\nimport fs from \"node:fs\";\nimport { openExistingDatabase } from \"./db/database.js\";\nimport { AuthSessionsRepo } from \"./db/repos/auth-sessions.js\";\nimport { UsersRepo } from \"./db/repos/users.js\";\n\n/** An hour: long enough for a controller to finish, short enough to forget. */\nexport const CLI_TOKEN_TTL_MS = 60 * 60_000;\n\n/**\n * Ceiling on a caller-supplied `--ttl-seconds`, matching the default session TTL (config.ts):\n * a token that lives in a file must not outlive an ordinary browser session.\n */\nexport const CLI_TOKEN_MAX_TTL_MS = 30 * 24 * 60 * 60_000;\n\nexport type MintTokenResult =\n | { outcome: \"minted\"; token: string; userId: string; expiresAt: string }\n /** No web.db on this root — the server has never run here, so there is no account to mint for. */\n | { outcome: \"no_server\" }\n | { outcome: \"failed\"; detail: string };\n\n/**\n * Turns a failure into something the person at the terminal can act on. Both cases are\n * ordinary situations, not crashes: a database owned by another OS account, and one written\n * by an older release (minting deliberately does not migrate — see openExistingDatabase).\n */\nfunction explain(err: unknown, dbPath: string): string {\n const message = err instanceof Error ? err.message : String(err);\n if (message.includes(\"no column named via\")) {\n return `${dbPath} predates this release — start the server once (\\`penguin web\\`) to upgrade it`;\n }\n if (message.includes(\"unable to open database\")) {\n return (\n `cannot open ${dbPath} — minting needs the data root's own OS account; ` +\n \"otherwise sign in with `penguin auth login --server <url>`\"\n );\n }\n return message;\n}\n\n/** Issues an API session token for the data root at `root`. */\nexport function mintApiToken(\n root: string,\n opts: { userId?: string; ttlMs?: number; dbPath?: string; now?: Date } = {},\n): MintTokenResult {\n const userId = opts.userId ?? \"admin\";\n const dbPath = opts.dbPath ?? path.join(root, \"web.db\");\n // Existence check first: openExistingDatabase would otherwise create an empty file, and a\n // root with no web.db has no account to mint for.\n if (!fs.existsSync(dbPath)) return { outcome: \"no_server\" };\n\n let db: ReturnType<typeof openExistingDatabase> | null = null;\n try {\n db = openExistingDatabase(dbPath);\n if (new UsersRepo(db).findById(userId) === null) {\n return { outcome: \"failed\", detail: `no such account: ${userId}` };\n }\n // The repo is the single minting point (token shape, hash, TTL ceiling), so a CLI-minted\n // row cannot drift from one the server issues itself.\n const { token, expiresAt } = new AuthSessionsRepo(db).issue({\n userId,\n via: \"cli\",\n now: opts.now ?? new Date(),\n ttlMs: opts.ttlMs ?? CLI_TOKEN_TTL_MS,\n maxTtlMs: CLI_TOKEN_MAX_TTL_MS,\n });\n return { outcome: \"minted\", token, userId, expiresAt };\n } catch (err) {\n return { outcome: \"failed\", detail: explain(err, dbPath) };\n } finally {\n db?.close();\n }\n}\n"],"mappings":";;;;;;;AAMA,OAAO,UAAU;AACjB,OAAO,QAAQ;AAMR,IAAM,mBAAmB,KAAK;AAM9B,IAAM,uBAAuB,KAAK,KAAK,KAAK;AAanD,SAAS,QAAQ,KAAc,QAAwB;AACrD,QAAM,UAAU,eAAe,QAAQ,IAAI,UAAU,OAAO,GAAG;AAC/D,MAAI,QAAQ,SAAS,qBAAqB,GAAG;AAC3C,WAAO,GAAG,MAAM;AAAA,EAClB;AACA,MAAI,QAAQ,SAAS,yBAAyB,GAAG;AAC/C,WACE,eAAe,MAAM;AAAA,EAGzB;AACA,SAAO;AACT;AAGO,SAAS,aACd,MACA,OAAyE,CAAC,GACzD;AACjB,QAAM,SAAS,KAAK,UAAU;AAC9B,QAAM,SAAS,KAAK,UAAU,KAAK,KAAK,MAAM,QAAQ;AAGtD,MAAI,CAAC,GAAG,WAAW,MAAM,EAAG,QAAO,EAAE,SAAS,YAAY;AAE1D,MAAI,KAAqD;AACzD,MAAI;AACF,SAAK,qBAAqB,MAAM;AAChC,QAAI,IAAI,UAAU,EAAE,EAAE,SAAS,MAAM,MAAM,MAAM;AAC/C,aAAO,EAAE,SAAS,UAAU,QAAQ,oBAAoB,MAAM,GAAG;AAAA,IACnE;AAGA,UAAM,EAAE,OAAO,UAAU,IAAI,IAAI,iBAAiB,EAAE,EAAE,MAAM;AAAA,MAC1D;AAAA,MACA,KAAK;AAAA,MACL,KAAK,KAAK,OAAO,oBAAI,KAAK;AAAA,MAC1B,OAAO,KAAK,SAAS;AAAA,MACrB,UAAU;AAAA,IACZ,CAAC;AACD,WAAO,EAAE,SAAS,UAAU,OAAO,QAAQ,UAAU;AAAA,EACvD,SAAS,KAAK;AACZ,WAAO,EAAE,SAAS,UAAU,QAAQ,QAAQ,KAAK,MAAM,EAAE;AAAA,EAC3D,UAAE;AACA,QAAI,MAAM;AAAA,EACZ;AACF;","names":[]}
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
// src/initial-password.ts
|
|
2
|
+
import fs from "fs";
|
|
3
|
+
import path from "path";
|
|
4
|
+
function initialAdminPasswordPath(root) {
|
|
5
|
+
return path.join(root, "initial-admin-password");
|
|
6
|
+
}
|
|
7
|
+
function clearInitialAdminPassword(root) {
|
|
8
|
+
try {
|
|
9
|
+
fs.rmSync(initialAdminPasswordPath(root), { force: true });
|
|
10
|
+
} catch {
|
|
11
|
+
}
|
|
12
|
+
}
|
|
13
|
+
var NOTICE_PADDING = 3;
|
|
14
|
+
function renderFirstLoginNotice(url) {
|
|
15
|
+
const lines = [
|
|
16
|
+
"This server has no admin password yet. Open this link to claim it:",
|
|
17
|
+
"",
|
|
18
|
+
` ${url}`,
|
|
19
|
+
"",
|
|
20
|
+
"The link lasts 30 days or until a password is set; restarting prints a fresh one."
|
|
21
|
+
];
|
|
22
|
+
const width = Math.max(...lines.map((line) => line.length));
|
|
23
|
+
const bar = `+${"-".repeat(width + NOTICE_PADDING * 2)}+`;
|
|
24
|
+
const pad = " ".repeat(NOTICE_PADDING);
|
|
25
|
+
const body = lines.map((line) => `|${pad}${line.padEnd(width)}${pad}|`);
|
|
26
|
+
return [bar, ...body, bar].join("\n");
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
export {
|
|
30
|
+
initialAdminPasswordPath,
|
|
31
|
+
clearInitialAdminPassword,
|
|
32
|
+
renderFirstLoginNotice
|
|
33
|
+
};
|
|
34
|
+
//# sourceMappingURL=chunk-K4ZSUT72.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/initial-password.ts"],"sourcesContent":["/** The framed first-run notice carrying the first-login link (minted in auth/service.ts). */\nimport fs from \"node:fs\";\nimport path from \"node:path\";\n\nexport function initialAdminPasswordPath(root: string): string {\n return path.join(root, \"initial-admin-password\");\n}\n\n/**\n * Removes the plaintext an older build stored here; nothing writes it any more.\n *\n * TODO(compat): goes once no supported upgrade path can carry an `initial-admin-password`.\n */\nexport function clearInitialAdminPassword(root: string): void {\n try {\n fs.rmSync(initialAdminPasswordPath(root), { force: true });\n } catch {\n // Best-effort: a leftover file only re-prints a password that no longer works.\n }\n}\n\nconst NOTICE_PADDING = 3;\n\n/**\n * Plain ASCII rather than box-drawing characters: a non-UTF-8 console (legacy Windows above\n * all) would mangle the frame around exactly the line it exists to highlight.\n */\nexport function renderFirstLoginNotice(url: string): string {\n const lines = [\n \"This server has no admin password yet. Open this link to claim it:\",\n \"\",\n ` ${url}`,\n \"\",\n \"The link lasts 30 days or until a password is set; restarting prints a fresh one.\",\n ];\n const width = Math.max(...lines.map((line) => line.length));\n const bar = `+${\"-\".repeat(width + NOTICE_PADDING * 2)}+`;\n const pad = \" \".repeat(NOTICE_PADDING);\n const body = lines.map((line) => `|${pad}${line.padEnd(width)}${pad}|`);\n return [bar, ...body, bar].join(\"\\n\");\n}\n"],"mappings":";AACA,OAAO,QAAQ;AACf,OAAO,UAAU;AAEV,SAAS,yBAAyB,MAAsB;AAC7D,SAAO,KAAK,KAAK,MAAM,wBAAwB;AACjD;AAOO,SAAS,0BAA0B,MAAoB;AAC5D,MAAI;AACF,OAAG,OAAO,yBAAyB,IAAI,GAAG,EAAE,OAAO,KAAK,CAAC;AAAA,EAC3D,QAAQ;AAAA,EAER;AACF;AAEA,IAAM,iBAAiB;AAMhB,SAAS,uBAAuB,KAAqB;AAC1D,QAAM,QAAQ;AAAA,IACZ;AAAA,IACA;AAAA,IACA,KAAK,GAAG;AAAA,IACR;AAAA,IACA;AAAA,EACF;AACA,QAAM,QAAQ,KAAK,IAAI,GAAG,MAAM,IAAI,CAAC,SAAS,KAAK,MAAM,CAAC;AAC1D,QAAM,MAAM,IAAI,IAAI,OAAO,QAAQ,iBAAiB,CAAC,CAAC;AACtD,QAAM,MAAM,IAAI,OAAO,cAAc;AACrC,QAAM,OAAO,MAAM,IAAI,CAAC,SAAS,IAAI,GAAG,GAAG,KAAK,OAAO,KAAK,CAAC,GAAG,GAAG,GAAG;AACtE,SAAO,CAAC,KAAK,GAAG,MAAM,GAAG,EAAE,KAAK,IAAI;AACtC;","names":[]}
|
|
@@ -0,0 +1,374 @@
|
|
|
1
|
+
import {
|
|
2
|
+
sessionTokenHash
|
|
3
|
+
} from "./chunk-WL5FUO3A.js";
|
|
4
|
+
|
|
5
|
+
// src/auth/password.ts
|
|
6
|
+
import { randomBytes, scrypt, timingSafeEqual } from "crypto";
|
|
7
|
+
var SCRYPT_COST = 16384;
|
|
8
|
+
var SCRYPT_R = 8;
|
|
9
|
+
var SCRYPT_P = 1;
|
|
10
|
+
var SALT_BYTES = 16;
|
|
11
|
+
var KEY_BYTES = 64;
|
|
12
|
+
function scryptAsync(password, salt, keyLen, n, r, p) {
|
|
13
|
+
return new Promise((resolve, reject) => {
|
|
14
|
+
scrypt(password, salt, keyLen, { N: n, r, p, maxmem: 128 * 1024 * 1024 }, (err, key) => {
|
|
15
|
+
if (err) reject(err);
|
|
16
|
+
else resolve(key);
|
|
17
|
+
});
|
|
18
|
+
});
|
|
19
|
+
}
|
|
20
|
+
async function hashPassword(password, cost = SCRYPT_COST) {
|
|
21
|
+
const salt = randomBytes(SALT_BYTES);
|
|
22
|
+
const key = await scryptAsync(password, salt, KEY_BYTES, cost, SCRYPT_R, SCRYPT_P);
|
|
23
|
+
return [
|
|
24
|
+
"scrypt",
|
|
25
|
+
String(cost),
|
|
26
|
+
String(SCRYPT_R),
|
|
27
|
+
String(SCRYPT_P),
|
|
28
|
+
salt.toString("base64"),
|
|
29
|
+
key.toString("base64")
|
|
30
|
+
].join("$");
|
|
31
|
+
}
|
|
32
|
+
async function verifyPassword(password, stored) {
|
|
33
|
+
const parts = stored.split("$");
|
|
34
|
+
if (parts.length !== 6 || parts[0] !== "scrypt") return false;
|
|
35
|
+
const n = Number(parts[1]);
|
|
36
|
+
const r = Number(parts[2]);
|
|
37
|
+
const p = Number(parts[3]);
|
|
38
|
+
if (!Number.isInteger(n) || !Number.isInteger(r) || !Number.isInteger(p)) return false;
|
|
39
|
+
let salt;
|
|
40
|
+
let expected;
|
|
41
|
+
try {
|
|
42
|
+
salt = Buffer.from(parts[4], "base64");
|
|
43
|
+
expected = Buffer.from(parts[5], "base64");
|
|
44
|
+
} catch {
|
|
45
|
+
return false;
|
|
46
|
+
}
|
|
47
|
+
if (salt.length === 0 || expected.length === 0) return false;
|
|
48
|
+
let actual;
|
|
49
|
+
try {
|
|
50
|
+
actual = await scryptAsync(password, salt, expected.length, n, r, p);
|
|
51
|
+
} catch {
|
|
52
|
+
return false;
|
|
53
|
+
}
|
|
54
|
+
return actual.length === expected.length && timingSafeEqual(actual, expected);
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
// src/auth/service.ts
|
|
58
|
+
import { randomBytes as randomBytes3 } from "crypto";
|
|
59
|
+
|
|
60
|
+
// src/auth/api-token.ts
|
|
61
|
+
import { createHash, randomBytes as randomBytes2, timingSafeEqual as timingSafeEqual2 } from "crypto";
|
|
62
|
+
import fs from "fs";
|
|
63
|
+
import path from "path";
|
|
64
|
+
function apiTokenPath(root) {
|
|
65
|
+
return path.join(root, "api-token");
|
|
66
|
+
}
|
|
67
|
+
function mintApiToken() {
|
|
68
|
+
return randomBytes2(32).toString("base64url");
|
|
69
|
+
}
|
|
70
|
+
function storeApiToken(root, token) {
|
|
71
|
+
try {
|
|
72
|
+
fs.mkdirSync(root, { recursive: true });
|
|
73
|
+
const target = apiTokenPath(root);
|
|
74
|
+
const tmp = `${target}.${process.pid}.tmp`;
|
|
75
|
+
fs.writeFileSync(tmp, `${token}
|
|
76
|
+
`, { mode: 384 });
|
|
77
|
+
fs.renameSync(tmp, target);
|
|
78
|
+
} catch {
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
function tokensEqual(a, b) {
|
|
82
|
+
const digest = (v) => createHash("sha256").update(v).digest();
|
|
83
|
+
return timingSafeEqual2(digest(a), digest(b));
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
// src/http/errors.ts
|
|
87
|
+
var HttpError = class extends Error {
|
|
88
|
+
constructor(status, code, message) {
|
|
89
|
+
super(message);
|
|
90
|
+
this.status = status;
|
|
91
|
+
this.code = code;
|
|
92
|
+
this.name = "HttpError";
|
|
93
|
+
}
|
|
94
|
+
status;
|
|
95
|
+
code;
|
|
96
|
+
};
|
|
97
|
+
function errorBody(code, message) {
|
|
98
|
+
return { error: { code, message } };
|
|
99
|
+
}
|
|
100
|
+
function isMissingCredential(err) {
|
|
101
|
+
const message = err instanceof Error ? err.message : String(err);
|
|
102
|
+
return /missing credentials|api[_ ]?key/i.test(message);
|
|
103
|
+
}
|
|
104
|
+
function modelCredentialMissing(modelId) {
|
|
105
|
+
return new HttpError(
|
|
106
|
+
400,
|
|
107
|
+
"model_credential_missing",
|
|
108
|
+
`Model ${modelId} has no API key yet. Configure it on the Models page first.`
|
|
109
|
+
);
|
|
110
|
+
}
|
|
111
|
+
function handleError(err, c) {
|
|
112
|
+
if (err instanceof HttpError) {
|
|
113
|
+
return c.json(errorBody(err.code, err.message), err.status);
|
|
114
|
+
}
|
|
115
|
+
console.error(`[server] Unhandled exception: ${err.stack ?? err.message}`);
|
|
116
|
+
return c.json(errorBody("internal", "Internal server error."), 500);
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
// src/auth/service.ts
|
|
120
|
+
var MIN_PASSWORD_LENGTH = 8;
|
|
121
|
+
var ADMIN_USER_ID = "admin";
|
|
122
|
+
var LOGIN_FREE_ATTEMPTS = 5;
|
|
123
|
+
var LOGIN_BACKOFF_START_MS = 1e3;
|
|
124
|
+
var LOGIN_BACKOFF_CAP_MS = 6e4;
|
|
125
|
+
var LOGIN_FAILURE_IDLE_MS = 15 * 6e4;
|
|
126
|
+
var SEED_PASSWORD_CHARS = 24;
|
|
127
|
+
function generateInitialAdminPassword() {
|
|
128
|
+
return randomBytes3(SEED_PASSWORD_CHARS).toString("base64url").slice(0, SEED_PASSWORD_CHARS);
|
|
129
|
+
}
|
|
130
|
+
function toUserInfo(row) {
|
|
131
|
+
return {
|
|
132
|
+
userId: row.userId,
|
|
133
|
+
isAdmin: row.isAdmin,
|
|
134
|
+
passwordIsInitial: row.passwordIsInitial,
|
|
135
|
+
createdAt: row.createdAt
|
|
136
|
+
};
|
|
137
|
+
}
|
|
138
|
+
var AuthService = class {
|
|
139
|
+
constructor(deps) {
|
|
140
|
+
this.deps = deps;
|
|
141
|
+
this.now = deps.now ?? (() => /* @__PURE__ */ new Date());
|
|
142
|
+
this.hashCost = deps.passwordHashCost ?? SCRYPT_COST;
|
|
143
|
+
this.deps.authSessions.deleteExpired(this.now().toISOString());
|
|
144
|
+
}
|
|
145
|
+
deps;
|
|
146
|
+
now;
|
|
147
|
+
hashCost;
|
|
148
|
+
/** Session lifetime, for the cookie that must expire WITH the session, not before it. */
|
|
149
|
+
get sessionTtlMs() {
|
|
150
|
+
return this.deps.sessionTtlMs;
|
|
151
|
+
}
|
|
152
|
+
/**
|
|
153
|
+
* Null once the server is claimed, so the only setup session that exists is a printed one.
|
|
154
|
+
* On demand rather than in the constructor: seedAdmin() runs after it, so "claimed?" has no
|
|
155
|
+
* answer there. A cached link whose row is gone is re-minted, not handed out dead.
|
|
156
|
+
*/
|
|
157
|
+
mintFirstLogin() {
|
|
158
|
+
if (!this.adminPasswordIsInitial()) return null;
|
|
159
|
+
if (this.deps.state.firstLoginToken !== null && this.authenticateWithMeta(this.deps.state.firstLoginToken) === null) {
|
|
160
|
+
this.deps.state.firstLoginToken = null;
|
|
161
|
+
}
|
|
162
|
+
this.deps.state.firstLoginToken ??= this.issueSession(ADMIN_USER_ID, "setup");
|
|
163
|
+
return this.deps.state.firstLoginToken;
|
|
164
|
+
}
|
|
165
|
+
/**
|
|
166
|
+
* For the startup notice's pinned-seed gate (index.ts): a pin usually means the operator
|
|
167
|
+
* knows the password, but an offline reset makes it stale, and the gate must see through
|
|
168
|
+
* that or the rescue link stays suppressed.
|
|
169
|
+
*/
|
|
170
|
+
async adminPasswordIs(password) {
|
|
171
|
+
const row = this.deps.users.findById(ADMIN_USER_ID);
|
|
172
|
+
return row !== null && await verifyPassword(password, row.passwordHash);
|
|
173
|
+
}
|
|
174
|
+
/**
|
|
175
|
+
* Startup seeding (idempotent): creates the built-in admin and adopts default_project when
|
|
176
|
+
* the users table is empty; if the initial Project fails, the user row is rolled back and
|
|
177
|
+
* the server retries on next startup.
|
|
178
|
+
*/
|
|
179
|
+
async seedAdmin() {
|
|
180
|
+
if (this.deps.users.count() > 0) return;
|
|
181
|
+
const password = this.deps.seedAdminPassword ?? generateInitialAdminPassword();
|
|
182
|
+
if (password.length < MIN_PASSWORD_LENGTH) {
|
|
183
|
+
throw new Error(
|
|
184
|
+
`PENGUIN_SEED_ADMIN_PASSWORD must be at least ${MIN_PASSWORD_LENGTH} characters.`
|
|
185
|
+
);
|
|
186
|
+
}
|
|
187
|
+
const user = {
|
|
188
|
+
userId: ADMIN_USER_ID,
|
|
189
|
+
passwordHash: await hashPassword(password, this.hashCost),
|
|
190
|
+
isAdmin: true,
|
|
191
|
+
passwordIsInitial: true,
|
|
192
|
+
createdAt: this.now().toISOString()
|
|
193
|
+
};
|
|
194
|
+
this.deps.users.insert(user);
|
|
195
|
+
try {
|
|
196
|
+
await this.deps.provisionInitialProject(user, true);
|
|
197
|
+
} catch (err) {
|
|
198
|
+
this.deps.users.delete(user.userId);
|
|
199
|
+
throw err;
|
|
200
|
+
}
|
|
201
|
+
}
|
|
202
|
+
/**
|
|
203
|
+
* Compared against the printed value, not merely verified: a cookie made out of ANY valid
|
|
204
|
+
* token would let one person hand another a link into the sender's account. Not single-use,
|
|
205
|
+
* because a prefetching browser would burn it before its reader clicked.
|
|
206
|
+
*/
|
|
207
|
+
redeemFirstLogin(given) {
|
|
208
|
+
const expected = this.deps.state.firstLoginToken;
|
|
209
|
+
if (expected === null || given === "" || !tokensEqual(given, expected)) return null;
|
|
210
|
+
return this.authenticateWithMeta(expected) === null ? null : expected;
|
|
211
|
+
}
|
|
212
|
+
/** Whether the built-in admin still runs on its initial password (gates the first-login link). */
|
|
213
|
+
adminPasswordIsInitial() {
|
|
214
|
+
return this.deps.users.findById(ADMIN_USER_ID)?.passwordIsInitial === true;
|
|
215
|
+
}
|
|
216
|
+
/** Consecutive login failures per userId (see the throttling comment on the constants). */
|
|
217
|
+
loginFailures = /* @__PURE__ */ new Map();
|
|
218
|
+
/** The wait imposed after `failures` consecutive failures (0 while within the free attempts). */
|
|
219
|
+
loginDelayMs(failures) {
|
|
220
|
+
const excess = failures - LOGIN_FREE_ATTEMPTS;
|
|
221
|
+
if (excess <= 0) return 0;
|
|
222
|
+
return Math.min(LOGIN_BACKOFF_START_MS * 2 ** (excess - 1), LOGIN_BACKOFF_CAP_MS);
|
|
223
|
+
}
|
|
224
|
+
async login(userId, password) {
|
|
225
|
+
const nowMs = this.now().getTime();
|
|
226
|
+
for (const [key, entry] of this.loginFailures) {
|
|
227
|
+
if (nowMs - entry.lastFailureAt > LOGIN_FAILURE_IDLE_MS) this.loginFailures.delete(key);
|
|
228
|
+
}
|
|
229
|
+
const failed = this.loginFailures.get(userId);
|
|
230
|
+
if (failed) {
|
|
231
|
+
const readyAt = failed.lastFailureAt + this.loginDelayMs(failed.failures);
|
|
232
|
+
if (nowMs < readyAt) {
|
|
233
|
+
throw new HttpError(
|
|
234
|
+
429,
|
|
235
|
+
"too_many_attempts",
|
|
236
|
+
`Too many failed sign-in attempts. Try again in ${Math.ceil((readyAt - nowMs) / 1e3)}s.`
|
|
237
|
+
);
|
|
238
|
+
}
|
|
239
|
+
}
|
|
240
|
+
const row = this.deps.users.findById(userId);
|
|
241
|
+
const ok = row !== null && await verifyPassword(password, row.passwordHash);
|
|
242
|
+
if (!row || !ok) {
|
|
243
|
+
this.loginFailures.set(userId, {
|
|
244
|
+
failures: (failed?.failures ?? 0) + 1,
|
|
245
|
+
lastFailureAt: this.now().getTime()
|
|
246
|
+
});
|
|
247
|
+
throw new HttpError(401, "invalid_credentials", "Incorrect username or password.");
|
|
248
|
+
}
|
|
249
|
+
this.loginFailures.delete(userId);
|
|
250
|
+
this.deps.authSessions.deleteExpired(this.now().toISOString());
|
|
251
|
+
return { user: toUserInfo(row), token: this.issueSession(row.userId, "password") };
|
|
252
|
+
}
|
|
253
|
+
/**
|
|
254
|
+
* Desktop-mode sign-in: an admin session with no password check — the claim route already
|
|
255
|
+
* redeemed the shell's one-shot token, which is the credential here. Throws only on a
|
|
256
|
+
* broken deployment (seeding runs before the route exists).
|
|
257
|
+
*/
|
|
258
|
+
loginDesktop() {
|
|
259
|
+
const row = this.deps.users.findById(ADMIN_USER_ID);
|
|
260
|
+
if (!row) {
|
|
261
|
+
throw new HttpError(500, "internal", "Built-in admin has not been seeded.");
|
|
262
|
+
}
|
|
263
|
+
return { user: toUserInfo(row), token: this.issueSession(row.userId, "desktop") };
|
|
264
|
+
}
|
|
265
|
+
/** Self password change (user settings): validates the old password first; the current session stays valid. */
|
|
266
|
+
async changePassword(userId, oldPassword, newPassword) {
|
|
267
|
+
const row = this.deps.users.findById(userId);
|
|
268
|
+
if (!row || !await verifyPassword(oldPassword, row.passwordHash)) {
|
|
269
|
+
throw new HttpError(400, "password_mismatch", "Current password is incorrect.");
|
|
270
|
+
}
|
|
271
|
+
await this.setPassword(userId, newPassword);
|
|
272
|
+
}
|
|
273
|
+
/** No old-password check; the me route gates which sessions may call this. */
|
|
274
|
+
async setInitialPassword(userId, newPassword) {
|
|
275
|
+
await this.setPassword(userId, newPassword);
|
|
276
|
+
}
|
|
277
|
+
/**
|
|
278
|
+
* Validation comes FIRST, so a rejected password leaves the first-login link alive: burning
|
|
279
|
+
* it on a typo would strand the claimer until a restart.
|
|
280
|
+
*/
|
|
281
|
+
async setPassword(userId, newPassword) {
|
|
282
|
+
if (newPassword.length < MIN_PASSWORD_LENGTH) {
|
|
283
|
+
throw new HttpError(400, "invalid_password", "Password must be at least 8 characters.");
|
|
284
|
+
}
|
|
285
|
+
this.deps.users.updatePassword(userId, await hashPassword(newPassword, this.hashCost), false);
|
|
286
|
+
this.loginFailures.delete(userId);
|
|
287
|
+
if (userId === ADMIN_USER_ID) {
|
|
288
|
+
this.deps.authSessions.deleteByUserAndVia(userId, "setup");
|
|
289
|
+
this.deps.state.firstLoginToken = null;
|
|
290
|
+
}
|
|
291
|
+
}
|
|
292
|
+
/** Ends a session: the row is the session, so logout deletes it. Unknown token is a no-op. */
|
|
293
|
+
logout(token) {
|
|
294
|
+
this.deps.authSessions.delete(sessionTokenHash(token));
|
|
295
|
+
}
|
|
296
|
+
/**
|
|
297
|
+
* The current boot's local API token (what control-env injection hands to tool
|
|
298
|
+
* subprocesses); null when none was minted. It lives on the runtime state, not on this
|
|
299
|
+
* service: the token was written to `<root>/api-token` by the process, so it must
|
|
300
|
+
* outlive the App a push replaces (auth/runtime-state.ts).
|
|
301
|
+
*/
|
|
302
|
+
localApiToken() {
|
|
303
|
+
return this.deps.state.apiToken;
|
|
304
|
+
}
|
|
305
|
+
/**
|
|
306
|
+
* Validates a Bearer token against the boot's local API token (constant-time compare):
|
|
307
|
+
* a match authenticates as the built-in admin — holding the token proves filesystem
|
|
308
|
+
* access to the data root, which is admin authority (see auth/api-token.ts). Returns
|
|
309
|
+
* null on mismatch, when no token was minted, or when the admin row is missing.
|
|
310
|
+
*/
|
|
311
|
+
authenticateApiToken(token) {
|
|
312
|
+
const apiToken = this.deps.state.apiToken;
|
|
313
|
+
if (apiToken === null || token.length === 0) return null;
|
|
314
|
+
if (!tokensEqual(token, apiToken)) return null;
|
|
315
|
+
const user = this.deps.users.findById(ADMIN_USER_ID);
|
|
316
|
+
return user === null ? null : { user, via: "token" };
|
|
317
|
+
}
|
|
318
|
+
/**
|
|
319
|
+
* Validates the cookie token. Sliding renewal tops the expiry up IN PLACE, so the cookie
|
|
320
|
+
* value never changes and there is no second identity to revoke. Only a session whose own
|
|
321
|
+
* span reaches the renewal window slides — a one-hour minted token must expire at its hour,
|
|
322
|
+
* not stretch by being used.
|
|
323
|
+
*/
|
|
324
|
+
authenticateWithMeta(token) {
|
|
325
|
+
const tokenHash = sessionTokenHash(token);
|
|
326
|
+
const session = this.deps.authSessions.findByTokenHash(tokenHash);
|
|
327
|
+
if (!session) return null;
|
|
328
|
+
const now = this.now();
|
|
329
|
+
const expiresAt = Date.parse(session.expiresAt);
|
|
330
|
+
if (expiresAt <= now.getTime()) {
|
|
331
|
+
this.deps.authSessions.delete(tokenHash);
|
|
332
|
+
return null;
|
|
333
|
+
}
|
|
334
|
+
const user = this.deps.users.findById(session.userId);
|
|
335
|
+
if (!user) return null;
|
|
336
|
+
const renewable = expiresAt - Date.parse(session.createdAt) >= this.deps.sessionRenewMs;
|
|
337
|
+
let renewed = false;
|
|
338
|
+
if (renewable && expiresAt - now.getTime() < this.deps.sessionRenewMs) {
|
|
339
|
+
this.deps.authSessions.touch(
|
|
340
|
+
tokenHash,
|
|
341
|
+
new Date(now.getTime() + this.deps.sessionTtlMs).toISOString()
|
|
342
|
+
);
|
|
343
|
+
renewed = true;
|
|
344
|
+
}
|
|
345
|
+
const via = session.via === "desktop" ? "desktop" : session.via === "setup" ? "setup" : "password";
|
|
346
|
+
return { user, via, renewed };
|
|
347
|
+
}
|
|
348
|
+
issueSession(userId, via) {
|
|
349
|
+
return this.deps.authSessions.issue({
|
|
350
|
+
userId,
|
|
351
|
+
via,
|
|
352
|
+
now: this.now(),
|
|
353
|
+
ttlMs: this.deps.sessionTtlMs
|
|
354
|
+
}).token;
|
|
355
|
+
}
|
|
356
|
+
};
|
|
357
|
+
|
|
358
|
+
export {
|
|
359
|
+
HttpError,
|
|
360
|
+
errorBody,
|
|
361
|
+
isMissingCredential,
|
|
362
|
+
modelCredentialMissing,
|
|
363
|
+
handleError,
|
|
364
|
+
mintApiToken,
|
|
365
|
+
storeApiToken,
|
|
366
|
+
SCRYPT_COST,
|
|
367
|
+
hashPassword,
|
|
368
|
+
MIN_PASSWORD_LENGTH,
|
|
369
|
+
ADMIN_USER_ID,
|
|
370
|
+
generateInitialAdminPassword,
|
|
371
|
+
toUserInfo,
|
|
372
|
+
AuthService
|
|
373
|
+
};
|
|
374
|
+
//# sourceMappingURL=chunk-OTYHSDV7.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 } from \"../db/repos/auth-sessions.js\";\nimport type { AuthRuntimeState } from \"./runtime-state.js\";\nimport type { AuthSessionsRepo } from \"../db/repos/auth-sessions.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,YAAY;AAElB,SAAS,YACP,UACA,MACA,QACA,GACA,GACA,GACiB;AACjB,SAAO,IAAI,QAAQ,CAAC,SAAS,WAAW;AACtC,WAAO,UAAU,MAAM,QAAQ,EAAE,GAAG,GAAG,GAAG,GAAG,QAAQ,MAAM,OAAO,KAAK,GAAG,CAAC,KAAK,QAAQ;AACtF,UAAI,IAAK,QAAO,GAAG;AAAA,UACd,SAAQ,GAAG;AAAA,IAClB,CAAC;AAAA,EACH,CAAC;AACH;AAOA,eAAsB,aAAa,UAAkB,OAAe,aAA8B;AAChG,QAAM,OAAO,YAAY,UAAU;AACnC,QAAM,MAAM,MAAM,YAAY,UAAU,MAAM,WAAW,MAAM,UAAU,QAAQ;AACjF,SAAO;AAAA,IACL;AAAA,IACA,OAAO,IAAI;AAAA,IACX,OAAO,QAAQ;AAAA,IACf,OAAO,QAAQ;AAAA,IACf,KAAK,SAAS,QAAQ;AAAA,IACtB,IAAI,SAAS,QAAQ;AAAA,EACvB,EAAE,KAAK,GAAG;AACZ;AAGA,eAAsB,eAAe,UAAkB,QAAkC;AACvF,QAAM,QAAQ,OAAO,MAAM,GAAG;AAC9B,MAAI,MAAM,WAAW,KAAK,MAAM,CAAC,MAAM,SAAU,QAAO;AACx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