@prismshadow/penguin-server 0.2.3 → 0.2.5

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.
@@ -0,0 +1,50 @@
1
+ // src/hmr/manifest.ts
2
+ import fs from "fs";
3
+ import fsp from "fs/promises";
4
+ import path from "path";
5
+ function str(value) {
6
+ return typeof value === "string" && value.length > 0 ? value : null;
7
+ }
8
+ async function readHarnessInfo(root) {
9
+ const manifest = await readManifest(root);
10
+ if (manifest === null) return null;
11
+ const bundles = {
12
+ platform: str(manifest.platform?.bundle),
13
+ cli: str(manifest.cli?.bundle),
14
+ web: str(manifest.web?.manifest)
15
+ };
16
+ if (bundles.platform === null && bundles.cli === null && bundles.web === null) return null;
17
+ const repo = str(manifest.source?.repo);
18
+ const revision = str(manifest.source?.revision);
19
+ return {
20
+ // Both halves or neither: half a provenance names nothing.
21
+ source: repo !== null && revision !== null ? { repo, revision } : null,
22
+ pushedAt: str(manifest.pushedAt),
23
+ bundles
24
+ };
25
+ }
26
+ async function readManifest(root) {
27
+ try {
28
+ const raw = await fsp.readFile(path.join(root, "hmr", "harness.json"), "utf8");
29
+ return JSON.parse(raw);
30
+ } catch {
31
+ return null;
32
+ }
33
+ }
34
+ async function resolveCliBundlePath(root) {
35
+ const manifest = await readManifest(root);
36
+ const bundle = manifest?.cli?.bundle;
37
+ if (typeof bundle !== "string" || bundle.length === 0) return null;
38
+ const hmrDir = path.join(root, "hmr");
39
+ const abs = path.resolve(hmrDir, bundle);
40
+ const withinHmrDir = abs === hmrDir || abs.startsWith(hmrDir + path.sep);
41
+ if (!withinHmrDir) return null;
42
+ return fs.existsSync(abs) ? abs : null;
43
+ }
44
+
45
+ export {
46
+ readHarnessInfo,
47
+ readManifest,
48
+ resolveCliBundlePath
49
+ };
50
+ //# sourceMappingURL=chunk-4SXGU7RO.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/hmr/manifest.ts"],"sourcesContent":["/**\n * The harness.json shape (`<root>/hmr/harness.json`) and pure readers over it.\n *\n * Split out of host.ts so a reader never needs a running HmrHost: `penguin` is a\n * separate, short-lived process per invocation (see packages/cli/src/index.ts) — it\n * has no host instance to ask, only the data root's own harness.json on disk.\n * `resolveCliBundlePath` is that reader: a plain disk read, no HTTP, no boot, no\n * in-memory state.\n *\n * ONE atomic version, THREE independent artifacts: `platform`, `cli`, and `web` are\n * always written together by HmrHost's single merged upgrade path (see host.ts's\n * persistVersion), but each is content-addressed and stored on its own — a push to\n * POST /api/hmr/upgrade carries `platform` and `cli` as two separate single-file ESM\n * sources, so `cli.bundle` points at its OWN file, a different sha from\n * `platform.bundle`. They are read back together too (see host.ts's restore): a\n * partial record (e.g. `platform` present but `web` or `cli` missing) is never\n * trusted — the whole version is treated as absent instead of partially applied.\n */\nimport fs from \"node:fs\";\nimport fsp from \"node:fs/promises\";\nimport path from \"node:path\";\nimport type { HarnessInfo } from \"@prismshadow/penguin-core\";\n\n/**\n * The committed on-disk record: a runtime restart resumes exactly this CODE (platform,\n * cli, web). It carries no STATE — a restart always boots the resumed platform bundle\n * against its own fresh initial context (bundle.context, see host.ts's PlatformBundle),\n * never a document parked from a previous run (see host.ts's module doc for why: a\n * parked doc's live-resource handles die with the process anyway, so resuming one could\n * only ever produce handles that fail to reclaim). Paths are relative to hmrDir\n * (`<root>/hmr`).\n */\nexport interface Manifest {\n platform?: { bundle: string };\n /**\n * The CLI's own bundle pointer — its own independent file (a different sha from\n * `platform.bundle`; the two are separately compiled artifacts), kept as its own\n * field so a reader that only wants \"which bundle does the CLI load right now\"\n * never has to reach into `platform` at all.\n */\n cli?: { bundle: string };\n /** One gzip(JSON.stringify({ files })) artifact, restored straight into memory. */\n web?: { manifest: string };\n /**\n * Files the pushed platform needs as REAL files on disk, unpacked under this directory\n * (relative to hmrDir). The web artifact stays in memory because it is only ever served\n * as bytes; an asset is something the platform hands to the OS — a native `.node` the\n * loader must resolve by path, a helper binary it execs — so it has to exist on the\n * filesystem, with its exec bit intact.\n */\n assets?: { dir: string };\n /**\n * Provenance of the push that produced this version, exactly as the pushing client sent\n * it (scripts/deploy.mjs fills it from its own checkout). Recorded, never executed or\n * resolved. Absent for a version pushed without it, and for every version committed\n * before the field existed — which is why every reader treats it as optional.\n */\n source?: { repo: string; revision: string };\n /** When this version was committed to the store (ISO 8601). Absent on older records. */\n pushedAt?: string;\n}\n\n/** A string field of an untrusted manifest, or null unless it is a non-empty string. */\nfunction str(value: unknown): string | null {\n return typeof value === \"string\" && value.length > 0 ? value : null;\n}\n\n/**\n * What the store has committed, for version reporting: provenance, commit time, and the\n * three artifact pointers. Null when nothing has ever been pushed to this root.\n *\n * Read defensively rather than cast: harness.json is written only by persistVersion, but a\n * truncated or hand-edited file must degrade a `penguin version` to missing fields, never\n * crash it. A record missing every artifact pointer counts as nothing pushed.\n */\nexport async function readHarnessInfo(root: string): Promise<HarnessInfo | null> {\n const manifest = await readManifest(root);\n if (manifest === null) return null;\n\n const bundles = {\n platform: str(manifest.platform?.bundle),\n cli: str(manifest.cli?.bundle),\n web: str(manifest.web?.manifest),\n };\n if (bundles.platform === null && bundles.cli === null && bundles.web === null) return null;\n\n const repo = str(manifest.source?.repo);\n const revision = str(manifest.source?.revision);\n return {\n // Both halves or neither: half a provenance names nothing.\n source: repo !== null && revision !== null ? { repo, revision } : null,\n pushedAt: str(manifest.pushedAt),\n bundles,\n };\n}\n\n/** Reads and parses `<root>/hmr/harness.json`; null when missing or corrupt (nothing committed yet). */\nexport async function readManifest(root: string): Promise<Manifest | null> {\n try {\n const raw = await fsp.readFile(path.join(root, \"hmr\", \"harness.json\"), \"utf8\");\n return JSON.parse(raw) as Manifest;\n } catch {\n return null;\n }\n}\n\n/**\n * Resolves the current CLI bundle's absolute path from a data root, or null when\n * nothing has been pushed yet: a fresh root, a missing/corrupt manifest, no `cli`\n * entry, a `cli.bundle` that isn't a non-empty string (e.g. `{\"cli\":{}}` — a\n * hand-edited or truncated harness.json), a path that resolves outside `<root>/hmr/`\n * (defense in depth: `manifest.cli.bundle` is trusted content today, written only by\n * this same process's persistVersion, but a reader must never let a malformed or\n * malicious manifest value walk it out of the store directory via `..` segments), or\n * a referenced file that no longer exists (e.g. pruned from the store — see host.ts's\n * pruneStore). A null return means \"use the packaged default\" to every caller;\n * nothing here ever throws for an ordinary unconfigured or malformed root.\n */\nexport async function resolveCliBundlePath(root: string): Promise<string | null> {\n const manifest = await readManifest(root);\n const bundle = manifest?.cli?.bundle;\n if (typeof bundle !== \"string\" || bundle.length === 0) return null;\n const hmrDir = path.join(root, \"hmr\");\n const abs = path.resolve(hmrDir, bundle);\n const withinHmrDir = abs === hmrDir || abs.startsWith(hmrDir + path.sep);\n if (!withinHmrDir) return null;\n return fs.existsSync(abs) ? abs : null;\n}\n"],"mappings":";AAkBA,OAAO,QAAQ;AACf,OAAO,SAAS;AAChB,OAAO,UAAU;AA2CjB,SAAS,IAAI,OAA+B;AAC1C,SAAO,OAAO,UAAU,YAAY,MAAM,SAAS,IAAI,QAAQ;AACjE;AAUA,eAAsB,gBAAgB,MAA2C;AAC/E,QAAM,WAAW,MAAM,aAAa,IAAI;AACxC,MAAI,aAAa,KAAM,QAAO;AAE9B,QAAM,UAAU;AAAA,IACd,UAAU,IAAI,SAAS,UAAU,MAAM;AAAA,IACvC,KAAK,IAAI,SAAS,KAAK,MAAM;AAAA,IAC7B,KAAK,IAAI,SAAS,KAAK,QAAQ;AAAA,EACjC;AACA,MAAI,QAAQ,aAAa,QAAQ,QAAQ,QAAQ,QAAQ,QAAQ,QAAQ,KAAM,QAAO;AAEtF,QAAM,OAAO,IAAI,SAAS,QAAQ,IAAI;AACtC,QAAM,WAAW,IAAI,SAAS,QAAQ,QAAQ;AAC9C,SAAO;AAAA;AAAA,IAEL,QAAQ,SAAS,QAAQ,aAAa,OAAO,EAAE,MAAM,SAAS,IAAI;AAAA,IAClE,UAAU,IAAI,SAAS,QAAQ;AAAA,IAC/B;AAAA,EACF;AACF;AAGA,eAAsB,aAAa,MAAwC;AACzE,MAAI;AACF,UAAM,MAAM,MAAM,IAAI,SAAS,KAAK,KAAK,MAAM,OAAO,cAAc,GAAG,MAAM;AAC7E,WAAO,KAAK,MAAM,GAAG;AAAA,EACvB,QAAQ;AACN,WAAO;AAAA,EACT;AACF;AAcA,eAAsB,qBAAqB,MAAsC;AAC/E,QAAM,WAAW,MAAM,aAAa,IAAI;AACxC,QAAM,SAAS,UAAU,KAAK;AAC9B,MAAI,OAAO,WAAW,YAAY,OAAO,WAAW,EAAG,QAAO;AAC9D,QAAM,SAAS,KAAK,KAAK,MAAM,KAAK;AACpC,QAAM,MAAM,KAAK,QAAQ,QAAQ,MAAM;AACvC,QAAM,eAAe,QAAQ,UAAU,IAAI,WAAW,SAAS,KAAK,GAAG;AACvE,MAAI,CAAC,aAAc,QAAO;AAC1B,SAAO,GAAG,WAAW,GAAG,IAAI,MAAM;AACpC;","names":[]}
@@ -0,0 +1,14 @@
1
+ import {
2
+ readHarnessInfo
3
+ } from "./chunk-4SXGU7RO.js";
4
+
5
+ // src/version-report.ts
6
+ import { buildInfo } from "@prismshadow/penguin-core";
7
+ async function versionReport(root) {
8
+ return { ...buildInfo(), harness: await readHarnessInfo(root) };
9
+ }
10
+
11
+ export {
12
+ versionReport
13
+ };
14
+ //# sourceMappingURL=chunk-TTGGJDNA.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/version-report.ts"],"sourcesContent":["/**\n * The one assembler behind `penguin version --json` and GET /api/version.\n *\n * The report has two halves that no single layer can produce. Core knows the artifact this\n * process is executing and nothing about data roots; the HMR store knows what harness was\n * pushed to a root and nothing about the process reading it. Joining them here — rather\n * than in each caller — is what makes \"the CLI and the API report the same thing\" a\n * structural fact instead of two spreads that have to be kept in step.\n *\n * It lives in the server package because that is where the harness.json format is owned\n * (see ./hmr/manifest.ts), and is exported as its own entry point so the CLI can reach it\n * without pulling in a server: the module graph here is core plus a `node:fs` read.\n */\nimport { buildInfo } from \"@prismshadow/penguin-core\";\nimport type { VersionReport } from \"@prismshadow/penguin-core\";\nimport { readHarnessInfo } from \"./hmr/manifest.js\";\n\n/**\n * The running build's identity plus the harness committed to `root`'s HMR store.\n *\n * Never throws: an unreadable or malformed store reports `harness: null`, which is also\n * what a root with nothing ever pushed to it reports. Version reporting degrades to fewer\n * facts, never to a failure.\n */\nexport async function versionReport(root: string): Promise<VersionReport> {\n return { ...buildInfo(), harness: await readHarnessInfo(root) };\n}\n"],"mappings":";;;;;AAaA,SAAS,iBAAiB;AAW1B,eAAsB,cAAc,MAAsC;AACxE,SAAO,EAAE,GAAG,UAAU,GAAG,SAAS,MAAM,gBAAgB,IAAI,EAAE;AAChE;","names":[]}
@@ -78,7 +78,7 @@ CREATE TABLE IF NOT EXISTS error_records ( -- server-side error capture (the
78
78
  project_id TEXT, -- nullable: sign-in/registration and process-level errors have no Project context
79
79
  agent_id TEXT,
80
80
  session_id TEXT,
81
- source TEXT NOT NULL, -- http | session | usage | title | subagent | process | llm | environment | compaction | schedule
81
+ source TEXT NOT NULL, -- http | session | usage | title | subagent | process | llm | environment | compaction | schedule | messaging
82
82
  kind TEXT NOT NULL, -- expected (HttpError, business 4xx) | unexpected (500/runtime)
83
83
  code TEXT NOT NULL, -- HttpError.code / internal / session_run_failed / ...
84
84
  status INTEGER, -- HTTP status code; NULL for non-HTTP sources
@@ -113,6 +113,19 @@ CREATE TABLE IF NOT EXISTS goal_state ( -- goal-mode runtime state (GOAL.
113
113
  updated_at TEXT NOT NULL
114
114
  );
115
115
  CREATE INDEX IF NOT EXISTS idx_goal_session ON goal_state(session_id);
116
+ CREATE TABLE IF NOT EXISTS messaging_bindings ( -- Session \u2194 messaging-channel bot bindings (runtime/messaging/ holds the long connections)
117
+ session_id TEXT NOT NULL, -- a Session keeps at most one saved config PER channel (composite PK below); at most ONE of them is enabled at a time (route-enforced, 409 another_channel_enabled)
118
+ channel TEXT NOT NULL, -- messaging channel discriminator ('feishu' | 'telegram')
119
+ account_id TEXT NOT NULL, -- channel-scoped bot/app identity (feishu: app_id; telegram: the bot token's numeric id); one binding per account per channel (idx_messaging_account: one account has one event stream, two Sessions would race it)
120
+ config_json TEXT NOT NULL, -- channel-specific credentials/config JSON (feishu: appId/appSecret/baseDomain; telegram: botToken); secrets plaintext at rest (same trade-off as the proxy address in server_settings), masked at every API surface; a cleared secret is stored as "" (the row and its account identity stay)
121
+ enabled INTEGER NOT NULL DEFAULT 0, -- INTENT state (the connection's runtime status stays in memory): new bindings start disabled \u2014 saving credentials never opens a connection, the explicit state toggle does
122
+ last_chat_id TEXT, -- most recent inbound chat (NULL until the bot is messaged once; replies and test messages target it)
123
+ last_chat_is_direct INTEGER NOT NULL DEFAULT 1, -- 1 = direct chat (reply by chat id), 0 = group chat (prefer reply-to-message)
124
+ created_at TEXT NOT NULL,
125
+ updated_at TEXT NOT NULL,
126
+ PRIMARY KEY (session_id, channel)
127
+ );
128
+ CREATE UNIQUE INDEX IF NOT EXISTS idx_messaging_account ON messaging_bindings(channel, account_id);
116
129
  CREATE TABLE IF NOT EXISTS ui_prefs (
117
130
  user_id TEXT PRIMARY KEY REFERENCES users(user_id) ON DELETE CASCADE,
118
131
  prefs_json TEXT NOT NULL -- {theme?, lastProjectId?, ...} free-form JSON
@@ -282,7 +295,7 @@ var UsersRepo = class {
282
295
 
283
296
  // src/auth/password.ts
284
297
  import { randomBytes, scrypt, timingSafeEqual } from "crypto";
285
- var SCRYPT_N = 16384;
298
+ var SCRYPT_COST = 16384;
286
299
  var SCRYPT_R = 8;
287
300
  var SCRYPT_P = 1;
288
301
  var SALT_BYTES = 16;
@@ -295,12 +308,12 @@ function scryptAsync(password, salt, keyLen, n, r, p) {
295
308
  });
296
309
  });
297
310
  }
298
- async function hashPassword(password) {
311
+ async function hashPassword(password, cost = SCRYPT_COST) {
299
312
  const salt = randomBytes(SALT_BYTES);
300
- const key = await scryptAsync(password, salt, KEY_BYTES, SCRYPT_N, SCRYPT_R, SCRYPT_P);
313
+ const key = await scryptAsync(password, salt, KEY_BYTES, cost, SCRYPT_R, SCRYPT_P);
301
314
  return [
302
315
  "scrypt",
303
- String(SCRYPT_N),
316
+ String(cost),
304
317
  String(SCRYPT_R),
305
318
  String(SCRYPT_P),
306
319
  salt.toString("base64"),
@@ -333,7 +346,33 @@ async function verifyPassword(password, stored) {
333
346
  }
334
347
 
335
348
  // src/auth/service.ts
336
- import { createHash, randomBytes as randomBytes2, randomInt } from "crypto";
349
+ import { createHash as createHash2, randomBytes as randomBytes3, randomInt } from "crypto";
350
+
351
+ // src/auth/api-token.ts
352
+ import { createHash, randomBytes as randomBytes2, timingSafeEqual as timingSafeEqual2 } from "crypto";
353
+ import fs from "fs";
354
+ import path2 from "path";
355
+ function apiTokenPath(root) {
356
+ return path2.join(root, "api-token");
357
+ }
358
+ function mintApiToken() {
359
+ return randomBytes2(32).toString("base64url");
360
+ }
361
+ function storeApiToken(root, token) {
362
+ try {
363
+ fs.mkdirSync(root, { recursive: true });
364
+ const target = apiTokenPath(root);
365
+ const tmp = `${target}.${process.pid}.tmp`;
366
+ fs.writeFileSync(tmp, `${token}
367
+ `, { mode: 384 });
368
+ fs.renameSync(tmp, target);
369
+ } catch {
370
+ }
371
+ }
372
+ function tokensEqual(a, b) {
373
+ const digest = (v) => createHash("sha256").update(v).digest();
374
+ return timingSafeEqual2(digest(a), digest(b));
375
+ }
337
376
 
338
377
  // src/http/errors.ts
339
378
  var HttpError = class extends Error {
@@ -379,7 +418,7 @@ function generateInitialAdminPassword() {
379
418
  return "penguin-" + String(randomInt(0, 1e4)).padStart(4, "0");
380
419
  }
381
420
  function sha256Hex(value) {
382
- return createHash("sha256").update(value).digest("hex");
421
+ return createHash2("sha256").update(value).digest("hex");
383
422
  }
384
423
  function toUserInfo(row) {
385
424
  return {
@@ -392,10 +431,21 @@ function toUserInfo(row) {
392
431
  var AuthService = class {
393
432
  constructor(deps) {
394
433
  this.deps = deps;
434
+ this.provisioner = deps.provisionInitialProject;
395
435
  this.now = deps.now ?? (() => /* @__PURE__ */ new Date());
436
+ this.hashCost = deps.passwordHashCost ?? SCRYPT_COST;
396
437
  }
397
438
  deps;
439
+ /**
440
+ * What a fresh user is provisioned with is business policy, answered by the CURRENT
441
+ * App: the platform installs its answer at create over the claimed auth capability
442
+ * (ordinary capability use, not a registry entry), and each swap's successor overwrites
443
+ * it. Starts as the constructor-supplied fallback so standalone/test constructions
444
+ * keep working unchanged.
445
+ */
446
+ provisioner;
398
447
  now;
448
+ hashCost;
399
449
  /**
400
450
  * Startup seeding (idempotent): creates the built-in admin and adopts
401
451
  * default_project when the users table is empty; if the initial Project fails,
@@ -414,20 +464,24 @@ var AuthService = class {
414
464
  }
415
465
  const user = {
416
466
  userId: ADMIN_USER_ID,
417
- passwordHash: await hashPassword(password),
467
+ passwordHash: await hashPassword(password, this.hashCost),
418
468
  isAdmin: true,
419
469
  passwordIsInitial: true,
420
470
  createdAt: this.now().toISOString()
421
471
  };
422
472
  this.deps.users.insert(user);
423
473
  try {
424
- await this.deps.provisionInitialProject(user, true);
474
+ await this.provisioner(user, true);
425
475
  } catch (err) {
426
476
  this.deps.users.delete(user.userId);
427
477
  throw err;
428
478
  }
429
479
  return password;
430
480
  }
481
+ /** Installs the current App's provisioning policy (see the `provisioner` field). */
482
+ setProvisioner(provision) {
483
+ this.provisioner = provision;
484
+ }
431
485
  /** Whether the built-in admin still runs on its initial password (drives the startup reminder notice). */
432
486
  adminPasswordIsInitial() {
433
487
  return this.deps.users.findById(ADMIN_USER_ID)?.passwordIsInitial === true;
@@ -492,7 +546,7 @@ var AuthService = class {
492
546
  if (newPassword.length < MIN_PASSWORD_LENGTH) {
493
547
  throw new HttpError(400, "invalid_password", "Password must be at least 8 characters.");
494
548
  }
495
- this.deps.users.updatePassword(userId, await hashPassword(newPassword), false);
549
+ this.deps.users.updatePassword(userId, await hashPassword(newPassword, this.hashCost), false);
496
550
  this.deps.onPasswordChanged?.(userId);
497
551
  }
498
552
  /**
@@ -505,12 +559,39 @@ var AuthService = class {
505
559
  if (newPassword.length < MIN_PASSWORD_LENGTH) {
506
560
  throw new HttpError(400, "invalid_password", "Password must be at least 8 characters.");
507
561
  }
508
- this.deps.users.updatePassword(userId, await hashPassword(newPassword), false);
562
+ this.deps.users.updatePassword(userId, await hashPassword(newPassword, this.hashCost), false);
509
563
  this.deps.onPasswordChanged?.(userId);
510
564
  }
511
565
  logout(token) {
512
566
  this.deps.authSessions.delete(sha256Hex(token));
513
567
  }
568
+ /**
569
+ * The boot-scoped local API token (`<root>/api-token`, see auth/api-token.ts): held in
570
+ * memory by the process that minted it. Null until the startup assembly installs it
571
+ * (standalone/test constructions without one simply never authenticate a Bearer
572
+ * header).
573
+ */
574
+ apiToken = null;
575
+ /** Installs the boot's local API token (called once by the startup assembly). */
576
+ setLocalApiToken(token) {
577
+ this.apiToken = token;
578
+ }
579
+ /** The current boot's local API token (what control-env injection hands to tool subprocesses); null when none was installed. */
580
+ localApiToken() {
581
+ return this.apiToken;
582
+ }
583
+ /**
584
+ * Validates a Bearer token against the boot's local API token (constant-time compare):
585
+ * a match authenticates as the built-in admin — holding the token proves filesystem
586
+ * access to the data root, which is admin authority (see auth/api-token.ts). Returns
587
+ * null on mismatch, when no token is installed, or when the admin row is missing.
588
+ */
589
+ authenticateApiToken(token) {
590
+ if (this.apiToken === null || token.length === 0) return null;
591
+ if (!tokensEqual(token, this.apiToken)) return null;
592
+ const user = this.deps.users.findById(ADMIN_USER_ID);
593
+ return user === null ? null : { user, via: "token" };
594
+ }
514
595
  /** Validates the cookie token: returns null if expired/unknown; sliding renewal once less than 6 days remain. */
515
596
  authenticateWithMeta(token) {
516
597
  const tokenHash = sha256Hex(token);
@@ -533,7 +614,7 @@ var AuthService = class {
533
614
  return { user, via: session.via === "desktop" ? "desktop" : "password" };
534
615
  }
535
616
  issueSession(userId, via) {
536
- const token = randomBytes2(32).toString("base64url");
617
+ const token = randomBytes3(32).toString("base64url");
537
618
  const now = this.now();
538
619
  this.deps.authSessions.insert({
539
620
  tokenHash: sha256Hex(token),
@@ -555,6 +636,9 @@ export {
555
636
  isMissingCredential,
556
637
  modelCredentialMissing,
557
638
  handleError,
639
+ mintApiToken,
640
+ storeApiToken,
641
+ SCRYPT_COST,
558
642
  hashPassword,
559
643
  MIN_PASSWORD_LENGTH,
560
644
  ADMIN_USER_ID,
@@ -562,4 +646,4 @@ export {
562
646
  toUserInfo,
563
647
  AuthService
564
648
  };
565
- //# sourceMappingURL=chunk-3QINBW3W.js.map
649
+ //# sourceMappingURL=chunk-WKJ3ANJP.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/db/database.ts","../src/db/schema.ts","../src/db/repos/auth-sessions.ts","../src/db/repos/users.ts","../src/auth/password.ts","../src/auth/service.ts","../src/auth/api-token.ts","../src/http/errors.ts"],"sourcesContent":["/**\n * SQLite connection & initialization (node:sqlite DatabaseSync).\n *\n * Single process, single writer: a synchronous API is sufficient and avoids a connection\n * pool; WAL mode and foreign key constraints are enabled. Table-creation SQL runs on open\n * (idempotent), with no migration branches (product not yet released).\n */\nimport { mkdirSync } from \"node:fs\";\nimport path from \"node:path\";\nimport type { DatabaseSync } from \"node:sqlite\";\nimport { SCHEMA_SQL } from \"./schema.js\";\n\n// Fetch the runtime module via process.getBuiltinModule (node >=22.3): avoids static\n// resolution of `node:sqlite` by bundlers/vite (some tools' builtin lists don't yet\n// recognize this experimental module).\nconst sqlite = process.getBuiltinModule(\"node:sqlite\");\n\n/** Open (creating if necessary) the database: ensure the parent directory exists, set PRAGMAs, run table creation. */\nexport function openDatabase(dbPath: string): DatabaseSync {\n if (dbPath !== \":memory:\") {\n mkdirSync(path.dirname(dbPath), { recursive: true });\n }\n const db = new sqlite.DatabaseSync(dbPath);\n db.exec(\"PRAGMA journal_mode = WAL;\");\n db.exec(\"PRAGMA foreign_keys = ON;\");\n db.exec(SCHEMA_SQL);\n // Columns added to the schema after a web.db was formed: CREATE TABLE IF NOT EXISTS never\n // touches an existing table, so they are ALTERed in here. Keep the list in sync with\n // schema.ts; drop entries only in a release allowed to break existing web.db files.\n ensureColumn(db, \"sessions\", \"client\", \"TEXT\");\n ensureColumn(db, \"sessions\", \"has_trace\", \"INTEGER NOT NULL DEFAULT 0\");\n ensureColumn(db, \"sessions\", \"fork_count\", \"INTEGER NOT NULL DEFAULT 0\");\n ensureColumn(db, \"sessions\", \"thinking_level\", \"TEXT\");\n ensureColumn(db, \"auth_sessions\", \"via\", \"TEXT\");\n ensureColumn(db, \"trace_files\", \"page_stats\", \"TEXT\");\n // Superseded by idx_usage_session_ts (session_id, ts), which SCHEMA_SQL just created on\n // this database: the old index is a strict prefix of it, so every query it served is\n // served identically. Dropping is safe — an index is derived, never data.\n db.exec(\"DROP INDEX IF EXISTS idx_usage_session\");\n upgradeLastActiveAt(db);\n return db;\n}\n\n/**\n * One-time `sessions.last_active_at` upgrade, ALTER + backfill in a single transaction.\n *\n * The backfill runs **only in the open that actually adds the column** (SQLite's ALTER\n * TABLE ADD COLUMN is transactional, so a crash mid-upgrade rolls back to \"no column\" and\n * the next open redoes both halves — never a half-migrated table, and never a full\n * `sessions` scan on the millions of opens that follow). Legacy rows take the session's\n * most recent request timestamp — usage_records, covered by idx_usage_session_ts, the\n * closest persisted proxy for \"last Trace activity\" — else their own created_at.\n */\nfunction upgradeLastActiveAt(db: DatabaseSync): void {\n db.exec(\"BEGIN\");\n try {\n if (ensureColumn(db, \"sessions\", \"last_active_at\", \"TEXT\")) {\n db.exec(\n `UPDATE sessions SET last_active_at = COALESCE(\n (SELECT MAX(ts) FROM usage_records WHERE usage_records.session_id = sessions.session_id),\n created_at\n )`,\n );\n }\n db.exec(\"COMMIT\");\n } catch (err) {\n db.exec(\"ROLLBACK\");\n throw err;\n }\n}\n\n/**\n * Idempotent per-column upgrade for databases formed before the column existed.\n * Returns whether this call actually ALTERed the table (false = the column was already\n * there), so a caller can gate one-time backfill work on it.\n */\nfunction ensureColumn(db: DatabaseSync, table: string, column: string, ddl: string): boolean {\n const cols = db.prepare(`PRAGMA table_info(${table})`).all() as { name: string }[];\n if (cols.some((c) => c.name === column)) return false;\n db.exec(`ALTER TABLE ${table} ADD COLUMN ${column} ${ddl}`);\n return true;\n}\n","/**\n * SQLite table-creation SQL.\n *\n * SQLite stores only indexes and aggregates: users / login sessions / Project authorization /\n * Agent & Session indexes / usage summaries / error records / UI preferences. Agent State,\n * Trace, and Workspace still follow the local directory-based storage rules.\n * Product not yet released: no migration branches — everything is CREATE IF NOT EXISTS, formed\n * once. The one exception: columns added to an existing table after release of a web.db are\n * ALTERed in by the idempotent per-column guard in database.ts (ensureColumn), since CREATE\n * TABLE IF NOT EXISTS never touches an existing table. A *reshaped* index follows the same\n * rule under a new name, with the superseded one dropped on open (idx_usage_session →\n * idx_usage_session_ts): CREATE INDEX IF NOT EXISTS never rebuilds an existing index either.\n */\n\nexport const SCHEMA_SQL = `\nCREATE TABLE IF NOT EXISTS users (\n user_id TEXT PRIMARY KEY, -- semantic id doubles as login name: ^[a-z][a-z0-9_-]{1,31}$\n password_hash TEXT NOT NULL, -- scrypt$N$r$p$salt$hash(base64)\n is_admin INTEGER NOT NULL DEFAULT 0, -- 1 for the built-in admin (seeded at startup)\n password_is_initial INTEGER NOT NULL DEFAULT 0, -- 1=initial password (seeded/admin-set); cleared once the user changes it\n created_at TEXT NOT NULL\n);\nCREATE TABLE IF NOT EXISTS auth_sessions (\n token_hash TEXT PRIMARY KEY, -- sha256(token) hex; the cookie stores only the raw token\n user_id TEXT NOT NULL REFERENCES users(user_id) ON DELETE CASCADE,\n created_at TEXT NOT NULL,\n expires_at TEXT NOT NULL, -- 7-day sliding renewal (topped up when <6 days remain)\n via TEXT -- 'password' | 'desktop'; NULL = legacy row (password)\n);\nCREATE TABLE IF NOT EXISTS projects (\n project_id TEXT PRIMARY KEY, -- directory name doubles as id; display name lives in project_config.toml\n owner_user_id TEXT NOT NULL REFERENCES users(user_id),\n created_at TEXT NOT NULL\n);\nCREATE TABLE IF NOT EXISTS project_members ( -- member grants only; owners are not stored here\n project_id TEXT NOT NULL REFERENCES projects(project_id) ON DELETE CASCADE,\n user_id TEXT NOT NULL REFERENCES users(user_id) ON DELETE CASCADE,\n created_at TEXT NOT NULL,\n PRIMARY KEY (project_id, user_id)\n);\nCREATE TABLE IF NOT EXISTS agents ( -- index only; name/description live in system_config.yaml\n project_id TEXT NOT NULL,\n agent_id TEXT NOT NULL,\n created_at TEXT NOT NULL,\n PRIMARY KEY (project_id, agent_id)\n);\nCREATE TABLE IF NOT EXISTS sessions (\n session_id TEXT PRIMARY KEY,\n project_id TEXT NOT NULL,\n agent_id TEXT NOT NULL,\n provider TEXT NOT NULL, -- provider group of the session model (paired with model_id as a model reference)\n model_id TEXT NOT NULL, -- upstream model id (sent to AgentHub as-is; never concatenate <provider>/<id>)\n workspace TEXT NOT NULL,\n approval_mode TEXT NOT NULL DEFAULT 'allow-all', -- allow-all|deny-all|read-only|always-ask\n thinking_level TEXT, -- level pinned for THIS session (none|low|medium|high|xhigh|max); NULL=not pinned, runs follow the Agent config\n title TEXT, -- auto-generated by the model after the first exchange; NULL=not yet (frontend shows \"New chat\")\n archived_at TEXT, -- archive time; NULL=not archived (shown by default; archived ones move under \"Archived\")\n client TEXT, -- creating client: 'web' (created via the Web App) | 'cli' (adopted from a CLI Trace); NULL = legacy row, treated as web\n has_trace INTEGER NOT NULL DEFAULT 0, -- cache: a Trace record exists (set at task start / adoption / subagent registration; lazily backfilled by list hydration)\n fork_count INTEGER NOT NULL DEFAULT 0, -- monotonically allocated child-fork number for this source Session; never decremented when a fork is deleted\n last_active_at TEXT, -- last activity this server drove for the session (ISO; stamped once when a run starts and once when it ends, initialized to created_at); monotonic, never moves backwards; NULL only before openDatabase's one-time backfill\n created_at TEXT NOT NULL\n); -- the schedule/subagent SOURCE is NOT stored: session_meta in the Trace is the single source of truth (see runtime/session-sources.ts); \"client\" is a different, DB-only axis (who created the row)\nCREATE INDEX IF NOT EXISTS idx_sessions_agent_created ON sessions(project_id, agent_id, created_at DESC);\nCREATE TABLE IF NOT EXISTS usage_records (\n id INTEGER PRIMARY KEY AUTOINCREMENT,\n ts TEXT NOT NULL,\n date TEXT NOT NULL, -- local date yyyy-mm-dd (aggregation key; same convention as Trace date directories)\n project_id TEXT NOT NULL,\n agent_id TEXT NOT NULL,\n session_id TEXT NOT NULL, -- top-level Session (child-session usage counts toward its main Session)\n origin_session_id TEXT, -- immediate source child Session (last of the origin chain); NULL=main session\n provider TEXT NOT NULL, -- provider group: paired with model_id as the attribution key; always GROUP BY provider, model_id\n model_id TEXT NOT NULL, -- upstream model id (paired with provider; same model_id across providers aggregates separately)\n cache_read INTEGER NOT NULL,\n cache_write INTEGER NOT NULL,\n output INTEGER NOT NULL,\n total INTEGER NOT NULL, -- from token_usage.request (one row per Request)\n status TEXT NOT NULL DEFAULT 'completed' -- request outcome: completed=success (with tokens); others=failure (0 tokens, for success rate)\n); -- cost is not stored: computed at query time from current pricing\nCREATE INDEX IF NOT EXISTS idx_usage_project_date ON usage_records(project_id, date);\nCREATE INDEX IF NOT EXISTS idx_usage_session_ts ON usage_records(session_id, ts); -- (session_id) alone was idx_usage_session (dropped on open): ts makes the last_active_at backfill's MAX(ts) a covering index scan instead of a random row lookup per usage record\nCREATE TABLE IF NOT EXISTS error_records ( -- server-side error capture (the Costs page's \"Errors\" tab)\n id INTEGER PRIMARY KEY AUTOINCREMENT,\n ts TEXT NOT NULL,\n date TEXT NOT NULL, -- local date yyyy-mm-dd (same convention as usage_records)\n project_id TEXT, -- nullable: sign-in/registration and process-level errors have no Project context\n agent_id TEXT,\n session_id TEXT,\n source TEXT NOT NULL, -- http | session | usage | title | subagent | process | llm | environment | compaction | schedule | messaging\n kind TEXT NOT NULL, -- expected (HttpError, business 4xx) | unexpected (500/runtime)\n code TEXT NOT NULL, -- HttpError.code / internal / session_run_failed / ...\n status INTEGER, -- HTTP status code; NULL for non-HTTP sources\n message TEXT NOT NULL -- truncated to 500 chars (no stack stored: stacks go to logs only)\n);\nCREATE INDEX IF NOT EXISTS idx_error_project_date ON error_records(project_id, date);\nCREATE TABLE IF NOT EXISTS schedule_state ( -- schedule runtime state (files are declarative intent; the system never writes back)\n project_id TEXT NOT NULL,\n agent_id TEXT NOT NULL,\n name TEXT NOT NULL, -- file name (without .toml) doubles as the identifier\n creator_user_id TEXT, -- creator (recorded on API create; hand-edited file reconciliation falls back to the Project owner)\n start_at_ms INTEGER NOT NULL, -- defines identity: a start_at change counts as a new task instance, resetting fire state\n def_hash TEXT NOT NULL, -- file content fingerprint: any change clears the invalid flag (the file takes effect again after edits)\n last_slot_ms INTEGER, -- latest due slot already consumed (advances on fire or skip; no re-fire across restarts)\n last_fired_at TEXT, -- last actual fire time (for display)\n fired_once INTEGER NOT NULL DEFAULT 0, -- one-shot task has fired\n missed INTEGER NOT NULL DEFAULT 0, -- one-shot task was missed (flagged by startup/registration reconciliation; not backfilled)\n invalid_reason TEXT, -- invalidation reason (e.g. the bound Session was deleted); NULL=healthy\n PRIMARY KEY (project_id, agent_id, name)\n);\nCREATE TABLE IF NOT EXISTS goal_state ( -- goal-mode runtime state (GOAL.yaml on disk is the model-facing protocol; this row is what the UI reads)\n id INTEGER PRIMARY KEY AUTOINCREMENT, -- one row per goal run; a Session may run goals repeatedly, latest row wins for display\n session_id TEXT NOT NULL,\n project_id TEXT NOT NULL,\n agent_id TEXT NOT NULL,\n objective TEXT NOT NULL,\n status TEXT NOT NULL, -- active | complete | blocked | budget_limited | aborted (aborted is server-side only; on-disk status stays active)\n budget INTEGER NOT NULL, -- token budget; -1 = unlimited\n used INTEGER NOT NULL DEFAULT 0, -- uncached input + output, refreshed per round (mirrors the runner's accounting)\n rounds INTEGER NOT NULL DEFAULT 0,\n created_at TEXT NOT NULL,\n updated_at TEXT NOT NULL\n);\nCREATE INDEX IF NOT EXISTS idx_goal_session ON goal_state(session_id);\nCREATE TABLE IF NOT EXISTS messaging_bindings ( -- Session ↔ messaging-channel bot bindings (runtime/messaging/ holds the long connections)\n session_id TEXT NOT NULL, -- a Session keeps at most one saved config PER channel (composite PK below); at most ONE of them is enabled at a time (route-enforced, 409 another_channel_enabled)\n channel TEXT NOT NULL, -- messaging channel discriminator ('feishu' | 'telegram')\n account_id TEXT NOT NULL, -- channel-scoped bot/app identity (feishu: app_id; telegram: the bot token's numeric id); one binding per account per channel (idx_messaging_account: one account has one event stream, two Sessions would race it)\n config_json TEXT NOT NULL, -- channel-specific credentials/config JSON (feishu: appId/appSecret/baseDomain; telegram: botToken); secrets plaintext at rest (same trade-off as the proxy address in server_settings), masked at every API surface; a cleared secret is stored as \"\" (the row and its account identity stay)\n enabled INTEGER NOT NULL DEFAULT 0, -- INTENT state (the connection's runtime status stays in memory): new bindings start disabled — saving credentials never opens a connection, the explicit state toggle does\n last_chat_id TEXT, -- most recent inbound chat (NULL until the bot is messaged once; replies and test messages target it)\n last_chat_is_direct INTEGER NOT NULL DEFAULT 1, -- 1 = direct chat (reply by chat id), 0 = group chat (prefer reply-to-message)\n created_at TEXT NOT NULL,\n updated_at TEXT NOT NULL,\n PRIMARY KEY (session_id, channel)\n);\nCREATE UNIQUE INDEX IF NOT EXISTS idx_messaging_account ON messaging_bindings(channel, account_id);\nCREATE TABLE IF NOT EXISTS ui_prefs (\n user_id TEXT PRIMARY KEY REFERENCES users(user_id) ON DELETE CASCADE,\n prefs_json TEXT NOT NULL -- {theme?, lastProjectId?, ...} free-form JSON\n);\nCREATE TABLE IF NOT EXISTS server_settings ( -- admin-level server-global settings (GET/PUT /api/admin/settings)\n key TEXT PRIMARY KEY, -- setting name, e.g. 'proxy_for_app'\n value TEXT NOT NULL -- JSON-encoded value; an absent row means the setting's built-in default\n);\nCREATE TABLE IF NOT EXISTS trace_files ( -- DERIVED CACHE of the on-disk Trace tree (services/trace-index.ts): the directories stay the single source of truth, every row is rebuildable from disk, and a row is never authority for absence — consumers reconcile + retry on a miss, so a stale index costs one extra scan, never a false 404\n project_id TEXT NOT NULL,\n agent_id TEXT NOT NULL,\n session_id TEXT NOT NULL,\n file_index INTEGER NOT NULL, -- shard index NNN of <session_id>_NNN.jsonl (name/path are reconstructed from the row, never stored: the data root may move)\n date TEXT NOT NULL, -- date directory name (local yyyy-mm-dd)\n size_bytes INTEGER NOT NULL, -- last observed size (listings stat-refresh the returned page and write back; an actively-appended shard may lag in between)\n page_stats TEXT, -- cached message-window scan state at this shard's END (services/message-window.ts ShardPrefixRecord JSON); immutable shards only, NULL = not yet computed, nulled whenever size_bytes changes\n PRIMARY KEY (project_id, agent_id, session_id, file_index)\n);\nCREATE INDEX IF NOT EXISTS idx_trace_files_agent_date ON trace_files(project_id, agent_id, date);\nCREATE INDEX IF NOT EXISTS idx_trace_files_session ON trace_files(session_id);\nCREATE TABLE IF NOT EXISTS trace_sessions ( -- per-session facts read ONCE at registration from the earliest shard's head (same derived-cache rules as trace_files; listing needs zero head-reads)\n session_id TEXT PRIMARY KEY,\n project_id TEXT NOT NULL,\n agent_id TEXT NOT NULL,\n source TEXT, -- session_meta origin: 'subagent' | 'schedule' | NULL = user-created (or head not yet readable)\n workspace TEXT NOT NULL DEFAULT '',\n title TEXT, -- first-prompt fallback title (sessions.title always wins when present)\n provider TEXT, -- model reference from session_meta (CLI adoption reads it from here; NULL = meta unreadable / legacy without provider)\n model_id TEXT,\n first_ts TEXT, -- first record's timestamp (adoption's createdAt fallback when the id embeds no time)\n meta_read INTEGER NOT NULL DEFAULT 0 -- 1 once the head parsed; 0 = facts unknown, retried by the next reconcile that touches the session\n);\nCREATE INDEX IF NOT EXISTS idx_trace_sessions_agent ON trace_sessions(project_id, agent_id);\n`;\n","/**\n * auth_sessions table repo (server-side sessions backing the HttpOnly cookie).\n *\n * Stores only the sha256(token) hex hash; the raw token appears only in the cookie.\n */\nimport type { DatabaseSync } from \"node:sqlite\";\n\nexport interface AuthSessionRow {\n tokenHash: string;\n userId: string;\n createdAt: string;\n expiresAt: string;\n /** How the session was established (\"password\" | \"desktop\"); null on rows formed before the column existed (treated as \"password\"). */\n via: string | null;\n}\n\nexport class AuthSessionsRepo {\n constructor(private readonly db: DatabaseSync) {}\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 string | 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 * 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 * 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: built-in admin seeding /\n * login / logout / password change / session validation.\n *\n * - No open registration: on startup, if there are no users at all, the built-in\n * admin `admin` is seeded with a random `penguin-<4 digits>` initial password\n * (printed once by the startup entrypoint; PENGUIN_SEED_ADMIN_PASSWORD injects\n * a fixed one for tests/e2e), and it adopts `default_project`; all other users\n * are created by an admin via the user backend (admin-service).\n * - An initial password (whether seeded or set by an admin) is flagged with\n * password_is_initial, which the frontend uses to prompt for a password change soon.\n * - Sessions: a 32-byte random token, with only its sha256 hash stored in the DB;\n * valid for 7 days, with sliding renewal once less than 6 days remain.\n */\nimport { createHash, randomBytes, randomInt } from \"node:crypto\";\nimport { tokensEqual } from \"./api-token.js\";\nimport type { UserInfo } from \"../api/types.js\";\nimport { HttpError } from \"../http/errors.js\";\nimport type { AuthSessionsRepo } from \"../db/repos/auth-sessions.js\";\nimport type { UserRow, UsersRepo } from \"../db/repos/users.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): the seeded initial password is `penguin-<4 digits>` —\n * 10,000 combinations — so unthrottled guessing would enumerate it in minutes. After\n * LOGIN_FREE_ATTEMPTS consecutive failures, the next attempt is admitted only after an\n * exponentially growing delay from the last failure (1s, 2s, … capped at 60s; attempts\n * inside the window are 429 `too_many_attempts` and do not extend it). Beyond ~40\n * failures that is one guess per minute, so the 10k space stops being enumerable, while\n * a legitimate user who mistyped a few times never waits more than the cap. A successful\n * login clears the counter. Counters are process memory (a restart clears them —\n * restarting is slower than waiting out the cap) and are kept for nonexistent userIds\n * too, so throttling is not an account-existence oracle. Known limit: a concurrent burst\n * can slip in before its first failure is recorded; the steady-state backoff still\n * dominates the search space.\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/**\n * Random initial password for the seeded admin: `penguin-<4 digits>` — brand-related and\n * easy to type, shown once in the server startup output (the README, docs and login-page\n * hint all describe this form).\n */\nexport function generateInitialAdminPassword(): string {\n return \"penguin-\" + String(randomInt(0, 10000)).padStart(4, \"0\");\n}\n\nfunction sha256Hex(value: string): string {\n return createHash(\"sha256\").update(value).digest(\"hex\");\n}\n\n/**\n * How a session was established: \"password\" via the login form, \"desktop\" via the\n * desktop shell's one-shot token, \"token\" via the local API token's Bearer header (no\n * stored session — the value is per request). Persisted per session (Bearer excepted) so\n * desktop-specific allowances (password change without the old password) apply only to\n * sessions the shell itself opened. Legacy rows (NULL) read as \"password\".\n */\nexport type SessionVia = \"password\" | \"desktop\" | \"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 /** 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 /**\n * Fired after any successful password update (self change / desktop set). The server\n * wires it to drop the stored initial-password plaintext once it goes stale (see\n * initial-password.ts); standalone/test constructions may omit it.\n */\n onPasswordChanged?: (userId: string) => void;\n sessionTtlMs: number;\n sessionRenewMs: number;\n /**\n * Test double: scrypt work factor for hashes this service writes. Omitted in\n * production, where {@link SCRYPT_COST} applies.\n */\n passwordHashCost?: number;\n now?: () => Date;\n}\n\nexport class AuthService {\n /**\n * What a fresh user is provisioned with is business policy, answered by the CURRENT\n * App: the platform installs its answer at create over the claimed auth capability\n * (ordinary capability use, not a registry entry), and each swap's successor overwrites\n * it. Starts as the constructor-supplied fallback so standalone/test constructions\n * keep working unchanged.\n */\n private provisioner: (user: UserRow, isAdmin: boolean) => Promise<void>;\n\n private readonly now: () => Date;\n private readonly hashCost: number;\n\n constructor(private readonly deps: AuthServiceDeps) {\n this.provisioner = deps.provisionInitialProject;\n this.now = deps.now ?? (() => new Date());\n this.hashCost = deps.passwordHashCost ?? SCRYPT_COST;\n }\n\n /**\n * Startup seeding (idempotent): creates the built-in admin and adopts\n * default_project when the users table is empty; if the initial Project fails,\n * the user row is rolled back and the server retries on next startup.\n * Returns the initial password when it actually seeded — the caller prints it,\n * the only place a generated password is ever shown — and null when users\n * already exist.\n */\n async seedAdmin(): Promise<string | null> {\n if (this.deps.users.count() > 0) return null;\n const password = this.deps.seedAdminPassword ?? generateInitialAdminPassword();\n // The override (PENGUIN_SEED_ADMIN_PASSWORD) must meet the same policy as every\n // other initial/reset password; rejecting it here, before any insert, keeps a\n // configuration typo from creating a trivially weak privileged account. Generated\n // passwords are always 12 characters and never trip this.\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.provisioner(user, true);\n } catch (err) {\n this.deps.users.delete(user.userId);\n throw err;\n }\n return password;\n }\n\n /** Installs the current App's provisioning policy (see the `provisioner` field). */\n setProvisioner(provision: (user: UserRow, isAdmin: boolean) => Promise<void>): void {\n this.provisioner = provision;\n }\n\n /** Whether the built-in admin still runs on its initial password (drives the startup reminder notice). */\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: issues an admin session WITHOUT a password check — the caller\n * (the desktop-login route) has already redeemed the shell's one-shot token, which is\n * the credential here. Throws if the admin has not been seeded yet (desktop-login runs\n * after startup seeding, so this only trips on a broken deployment).\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 this.deps.authSessions.deleteExpired(this.now().toISOString());\n return { user: toUserInfo(row), token: this.issueSession(row.userId, \"desktop\") };\n }\n\n /** Self password change (user settings): validates the old password, and on success clears the initial-password flag; the current session remains 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 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 this.deps.onPasswordChanged?.(userId);\n }\n\n /**\n * Desktop-session password set: no old-password check. Only reachable for sessions\n * established via desktop-login (the me route gates on sessionVia) — the seed password\n * of a desktop-created root is random and never shown, so its holder has nothing to\n * type into an old-password field; the shell's token already proved machine ownership.\n */\n async setPasswordDesktop(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 this.deps.onPasswordChanged?.(userId);\n }\n\n logout(token: string): void {\n this.deps.authSessions.delete(sha256Hex(token));\n }\n\n /**\n * The boot-scoped local API token (`<root>/api-token`, see auth/api-token.ts): held in\n * memory by the process that minted it. Null until the startup assembly installs it\n * (standalone/test constructions without one simply never authenticate a Bearer\n * header).\n */\n private apiToken: string | null = null;\n\n /** Installs the boot's local API token (called once by the startup assembly). */\n setLocalApiToken(token: string): void {\n this.apiToken = token;\n }\n\n /** The current boot's local API token (what control-env injection hands to tool subprocesses); null when none was installed. */\n localApiToken(): string | null {\n return this.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 is installed, or when the admin row is missing.\n */\n authenticateApiToken(token: string): { user: UserRow; via: SessionVia } | null {\n if (this.apiToken === null || token.length === 0) return null;\n if (!tokensEqual(token, this.apiToken)) return null;\n const user = this.deps.users.findById(ADMIN_USER_ID);\n return user === null ? null : { user, via: \"token\" };\n }\n\n /** Validates the cookie token: returns null if expired/unknown; sliding renewal once less than 6 days remain. */\n authenticateWithMeta(token: string): { user: UserRow; via: SessionVia } | null {\n const tokenHash = sha256Hex(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 if (expiresAt - now.getTime() < this.deps.sessionRenewMs) {\n this.deps.authSessions.touch(\n tokenHash,\n new Date(now.getTime() + this.deps.sessionTtlMs).toISOString(),\n );\n }\n const user = this.deps.users.findById(session.userId);\n if (!user) return null;\n return { user, via: session.via === \"desktop\" ? \"desktop\" : \"password\" };\n }\n\n private issueSession(userId: string, via: SessionVia): string {\n const token = randomBytes(32).toString(\"base64url\");\n const now = this.now();\n this.deps.authSessions.insert({\n tokenHash: sha256Hex(token),\n userId,\n createdAt: now.toISOString(),\n expiresAt: new Date(now.getTime() + this.deps.sessionTtlMs).toISOString(),\n via,\n });\n return 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":";AAOA,SAAS,iBAAiB;AAC1B,OAAO,UAAU;;;ACMV,IAAM,aAAa;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;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,YAAY,IAAI,QAAQ,IAAI,KAAK,KAAK,gBAAgB;AACxD,WAAK,KAAK,aAAa;AAAA,QACrB;AAAA,QACA,IAAI,KAAK,IAAI,QAAQ,IAAI,KAAK,KAAK,YAAY,EAAE,YAAY;AAAA,MAC/D;AAAA,IACF;AACA,UAAM,OAAO,KAAK,KAAK,MAAM,SAAS,QAAQ,MAAM;AACpD,QAAI,CAAC,KAAM,QAAO;AAClB,WAAO,EAAE,MAAM,KAAK,QAAQ,QAAQ,YAAY,YAAY,WAAW;AAAA,EACzE;AAAA,EAEQ,aAAa,QAAgB,KAAyB;AAC5D,UAAM,QAAQC,aAAY,EAAE,EAAE,SAAS,WAAW;AAClD,UAAM,MAAM,KAAK,IAAI;AACrB,SAAK,KAAK,aAAa,OAAO;AAAA,MAC5B,WAAW,UAAU,KAAK;AAAA,MAC1B;AAAA,MACA,WAAW,IAAI,YAAY;AAAA,MAC3B,WAAW,IAAI,KAAK,IAAI,QAAQ,IAAI,KAAK,KAAK,YAAY,EAAE,YAAY;AAAA,MACxE;AAAA,IACF,CAAC;AACD,WAAO;AAAA,EACT;AACF;","names":["createHash","randomBytes","randomBytes","timingSafeEqual","path","timingSafeEqual","createHash","randomBytes"]}
@@ -1,3 +1,5 @@
1
+ import { HarnessInfo } from '@prismshadow/penguin-core';
2
+
1
3
  /**
2
4
  * The committed on-disk record: a runtime restart resumes exactly this CODE (platform,
3
5
  * cli, web). It carries no STATE — a restart always boots the resumed platform bundle
@@ -24,7 +26,38 @@ interface Manifest {
24
26
  web?: {
25
27
  manifest: string;
26
28
  };
29
+ /**
30
+ * Files the pushed platform needs as REAL files on disk, unpacked under this directory
31
+ * (relative to hmrDir). The web artifact stays in memory because it is only ever served
32
+ * as bytes; an asset is something the platform hands to the OS — a native `.node` the
33
+ * loader must resolve by path, a helper binary it execs — so it has to exist on the
34
+ * filesystem, with its exec bit intact.
35
+ */
36
+ assets?: {
37
+ dir: string;
38
+ };
39
+ /**
40
+ * Provenance of the push that produced this version, exactly as the pushing client sent
41
+ * it (scripts/deploy.mjs fills it from its own checkout). Recorded, never executed or
42
+ * resolved. Absent for a version pushed without it, and for every version committed
43
+ * before the field existed — which is why every reader treats it as optional.
44
+ */
45
+ source?: {
46
+ repo: string;
47
+ revision: string;
48
+ };
49
+ /** When this version was committed to the store (ISO 8601). Absent on older records. */
50
+ pushedAt?: string;
27
51
  }
52
+ /**
53
+ * What the store has committed, for version reporting: provenance, commit time, and the
54
+ * three artifact pointers. Null when nothing has ever been pushed to this root.
55
+ *
56
+ * Read defensively rather than cast: harness.json is written only by persistVersion, but a
57
+ * truncated or hand-edited file must degrade a `penguin version` to missing fields, never
58
+ * crash it. A record missing every artifact pointer counts as nothing pushed.
59
+ */
60
+ declare function readHarnessInfo(root: string): Promise<HarnessInfo | null>;
28
61
  /** Reads and parses `<root>/hmr/harness.json`; null when missing or corrupt (nothing committed yet). */
29
62
  declare function readManifest(root: string): Promise<Manifest | null>;
30
63
  /**
@@ -41,4 +74,4 @@ declare function readManifest(root: string): Promise<Manifest | null>;
41
74
  */
42
75
  declare function resolveCliBundlePath(root: string): Promise<string | null>;
43
76
 
44
- export { type Manifest, readManifest, resolveCliBundlePath };
77
+ export { type Manifest, readHarnessInfo, readManifest, resolveCliBundlePath };
@@ -1,26 +1,10 @@
1
- // src/hmr/manifest.ts
2
- import fs from "fs";
3
- import fsp from "fs/promises";
4
- import path from "path";
5
- async function readManifest(root) {
6
- try {
7
- const raw = await fsp.readFile(path.join(root, "hmr", "harness.json"), "utf8");
8
- return JSON.parse(raw);
9
- } catch {
10
- return null;
11
- }
12
- }
13
- async function resolveCliBundlePath(root) {
14
- const manifest = await readManifest(root);
15
- const bundle = manifest?.cli?.bundle;
16
- if (typeof bundle !== "string" || bundle.length === 0) return null;
17
- const hmrDir = path.join(root, "hmr");
18
- const abs = path.resolve(hmrDir, bundle);
19
- const withinHmrDir = abs === hmrDir || abs.startsWith(hmrDir + path.sep);
20
- if (!withinHmrDir) return null;
21
- return fs.existsSync(abs) ? abs : null;
22
- }
1
+ import {
2
+ readHarnessInfo,
3
+ readManifest,
4
+ resolveCliBundlePath
5
+ } from "../chunk-4SXGU7RO.js";
23
6
  export {
7
+ readHarnessInfo,
24
8
  readManifest,
25
9
  resolveCliBundlePath
26
10
  };
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/hmr/manifest.ts"],"sourcesContent":["/**\n * The harness.json shape (`<root>/hmr/harness.json`) and pure readers over it.\n *\n * Split out of host.ts so a reader never needs a running HmrHost: `penguin` is a\n * separate, short-lived process per invocation (see packages/cli/src/index.ts) — it\n * has no host instance to ask, only the data root's own harness.json on disk.\n * `resolveCliBundlePath` is that reader: a plain disk read, no HTTP, no boot, no\n * in-memory state.\n *\n * ONE atomic version, THREE independent artifacts: `platform`, `cli`, and `web` are\n * always written together by HmrHost's single merged upgrade path (see host.ts's\n * persistVersion), but each is content-addressed and stored on its own — a push to\n * POST /api/hmr/upgrade carries `platform` and `cli` as two separate single-file ESM\n * sources, so `cli.bundle` points at its OWN file, a different sha from\n * `platform.bundle`. They are read back together too (see host.ts's restore): a\n * partial record (e.g. `platform` present but `web` or `cli` missing) is never\n * trusted — the whole version is treated as absent instead of partially applied.\n */\nimport fs from \"node:fs\";\nimport fsp from \"node:fs/promises\";\nimport path from \"node:path\";\n\n/**\n * The committed on-disk record: a runtime restart resumes exactly this CODE (platform,\n * cli, web). It carries no STATE — a restart always boots the resumed platform bundle\n * against its own fresh initial context (bundle.context, see host.ts's PlatformBundle),\n * never a document parked from a previous run (see host.ts's module doc for why: a\n * parked doc's live-resource handles die with the process anyway, so resuming one could\n * only ever produce handles that fail to reclaim). Paths are relative to hmrDir\n * (`<root>/hmr`).\n */\nexport interface Manifest {\n platform?: { bundle: string };\n /**\n * The CLI's own bundle pointer — its own independent file (a different sha from\n * `platform.bundle`; the two are separately compiled artifacts), kept as its own\n * field so a reader that only wants \"which bundle does the CLI load right now\"\n * never has to reach into `platform` at all.\n */\n cli?: { bundle: string };\n /** One gzip(JSON.stringify({ files })) artifact, restored straight into memory. */\n web?: { manifest: string };\n}\n\n/** Reads and parses `<root>/hmr/harness.json`; null when missing or corrupt (nothing committed yet). */\nexport async function readManifest(root: string): Promise<Manifest | null> {\n try {\n const raw = await fsp.readFile(path.join(root, \"hmr\", \"harness.json\"), \"utf8\");\n return JSON.parse(raw) as Manifest;\n } catch {\n return null;\n }\n}\n\n/**\n * Resolves the current CLI bundle's absolute path from a data root, or null when\n * nothing has been pushed yet: a fresh root, a missing/corrupt manifest, no `cli`\n * entry, a `cli.bundle` that isn't a non-empty string (e.g. `{\"cli\":{}}` — a\n * hand-edited or truncated harness.json), a path that resolves outside `<root>/hmr/`\n * (defense in depth: `manifest.cli.bundle` is trusted content today, written only by\n * this same process's persistVersion, but a reader must never let a malformed or\n * malicious manifest value walk it out of the store directory via `..` segments), or\n * a referenced file that no longer exists (e.g. pruned from the store — see host.ts's\n * pruneStore). A null return means \"use the packaged default\" to every caller;\n * nothing here ever throws for an ordinary unconfigured or malformed root.\n */\nexport async function resolveCliBundlePath(root: string): Promise<string | null> {\n const manifest = await readManifest(root);\n const bundle = manifest?.cli?.bundle;\n if (typeof bundle !== \"string\" || bundle.length === 0) return null;\n const hmrDir = path.join(root, \"hmr\");\n const abs = path.resolve(hmrDir, bundle);\n const withinHmrDir = abs === hmrDir || abs.startsWith(hmrDir + path.sep);\n if (!withinHmrDir) return null;\n return fs.existsSync(abs) ? abs : null;\n}\n"],"mappings":";AAkBA,OAAO,QAAQ;AACf,OAAO,SAAS;AAChB,OAAO,UAAU;AAyBjB,eAAsB,aAAa,MAAwC;AACzE,MAAI;AACF,UAAM,MAAM,MAAM,IAAI,SAAS,KAAK,KAAK,MAAM,OAAO,cAAc,GAAG,MAAM;AAC7E,WAAO,KAAK,MAAM,GAAG;AAAA,EACvB,QAAQ;AACN,WAAO;AAAA,EACT;AACF;AAcA,eAAsB,qBAAqB,MAAsC;AAC/E,QAAM,WAAW,MAAM,aAAa,IAAI;AACxC,QAAM,SAAS,UAAU,KAAK;AAC9B,MAAI,OAAO,WAAW,YAAY,OAAO,WAAW,EAAG,QAAO;AAC9D,QAAM,SAAS,KAAK,KAAK,MAAM,KAAK;AACpC,QAAM,MAAM,KAAK,QAAQ,QAAQ,MAAM;AACvC,QAAM,eAAe,QAAQ,UAAU,IAAI,WAAW,SAAS,KAAK,GAAG;AACvE,MAAI,CAAC,aAAc,QAAO;AAC1B,SAAO,GAAG,WAAW,GAAG,IAAI,MAAM;AACpC;","names":[]}
1
+ {"version":3,"sources":[],"sourcesContent":[],"mappings":"","names":[]}