home-hosted 0.12.0 → 0.13.1
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 +95 -49
- package/dist/chunks/{archive-DpCwA8Nf.js → archive-DP-XQR8X.js} +15 -2
- package/dist/chunks/archive-DP-XQR8X.js.map +1 -0
- package/dist/chunks/{atomic-CEfCUfkQ.js → atomic-C1PfJpE7.js} +3 -2
- package/dist/chunks/atomic-C1PfJpE7.js.map +1 -0
- package/dist/chunks/{backup-CPrJVPJI.js → backup-DeAJ3pbO.js} +101 -76
- package/dist/chunks/backup-DeAJ3pbO.js.map +1 -0
- package/dist/chunks/{backups-Bd2SF2qd.js → backups-twva7x2n.js} +882 -537
- package/dist/chunks/backups-twva7x2n.js.map +1 -0
- package/dist/chunks/{contracts-ku5ypHXJ.js → contracts-CMBD1TF9.js} +381 -407
- package/dist/chunks/contracts-CMBD1TF9.js.map +1 -0
- package/dist/chunks/{daemon-TwXk5vb8.js → daemon-CofN9k6Q.js} +54 -22
- package/dist/chunks/daemon-CofN9k6Q.js.map +1 -0
- package/dist/chunks/{docker-CGv4Uv7w.js → docker-Cy9Lyvda.js} +4 -3
- package/dist/chunks/docker-Cy9Lyvda.js.map +1 -0
- package/dist/chunks/{down-BlX5X3bm.js → down-C59ne5aM.js} +22 -17
- package/dist/chunks/down-C59ne5aM.js.map +1 -0
- package/dist/chunks/{init-DdmqHVra.js → init-BZ7hK9Vf.js} +19 -6
- package/dist/chunks/init-BZ7hK9Vf.js.map +1 -0
- package/dist/chunks/{last-stop-BZ08Z89-.js → last-stop-C-BXz_XI.js} +6 -5
- package/dist/chunks/last-stop-C-BXz_XI.js.map +1 -0
- package/dist/chunks/{layout-D74TGUnr.js → layout-DwTtmund.js} +2 -2
- package/dist/chunks/{layout-D74TGUnr.js.map → layout-DwTtmund.js.map} +1 -1
- package/dist/chunks/lazy-Ce5zEAq1.js +66 -0
- package/dist/chunks/lazy-Ce5zEAq1.js.map +1 -0
- package/dist/chunks/{log-buffer-HnP0jKhZ.js → log-buffer-Dy9HHDMD.js} +114 -50
- package/dist/chunks/log-buffer-Dy9HHDMD.js.map +1 -0
- package/dist/chunks/{logs-gI_69Q1P.js → logs---TI_bxM.js} +23 -21
- package/dist/chunks/logs---TI_bxM.js.map +1 -0
- package/dist/chunks/{migrate-BTlsibvF.js → migrate-Cfoq-Vgh.js} +5 -5
- package/dist/chunks/{migrate-BTlsibvF.js.map → migrate-Cfoq-Vgh.js.map} +1 -1
- package/dist/chunks/{nanny-20aBXL1o.js → nanny-COyCJXj9.js} +130 -27
- package/dist/chunks/nanny-COyCJXj9.js.map +1 -0
- package/dist/chunks/{nanny-DUaAfCV-.js → nanny-Dnun3hVB.js} +3 -3
- package/dist/chunks/{nanny-DUaAfCV-.js.map → nanny-Dnun3hVB.js.map} +1 -1
- package/dist/chunks/{nanny-CjnnrIpm.js → nanny-rewguyXg.js} +3 -3
- package/dist/chunks/{nanny-CjnnrIpm.js.map → nanny-rewguyXg.js.map} +1 -1
- package/dist/chunks/{nanny-sweep-Ca9kPAVi.js → nanny-sweep-ClVuNJRo.js} +6 -5
- package/dist/chunks/nanny-sweep-ClVuNJRo.js.map +1 -0
- package/dist/chunks/{parse-B9owE47G.js → parse-DhmG26fI.js} +4 -4
- package/dist/chunks/{parse-B9owE47G.js.map → parse-DhmG26fI.js.map} +1 -1
- package/dist/chunks/{paths-BT94q6-w.js → paths-CGlGDrOU.js} +36 -2
- package/dist/chunks/paths-CGlGDrOU.js.map +1 -0
- package/dist/chunks/{port-B8WBTRMk.js → port-k5VBw8t9.js} +5 -2
- package/dist/chunks/{port-B8WBTRMk.js.map → port-k5VBw8t9.js.map} +1 -1
- package/dist/chunks/{restart-UZgeDukG.js → restart-BYu_E7x5.js} +25 -59
- package/dist/chunks/restart-BYu_E7x5.js.map +1 -0
- package/dist/chunks/{schema-o7Lgk0V1.js → schema-B240VXcV.js} +11 -10
- package/dist/chunks/schema-B240VXcV.js.map +1 -0
- package/dist/chunks/{secrets-D7PdYh71.js → secrets-BieELnZh.js} +22 -4
- package/dist/chunks/secrets-BieELnZh.js.map +1 -0
- package/dist/chunks/{server-BuIeSsRu.js → server-By-zktjx.js} +3 -3
- package/dist/chunks/{server-BuIeSsRu.js.map → server-By-zktjx.js.map} +1 -1
- package/dist/chunks/{set-password-DegMumPh.js → set-password-D5vZqqSX.js} +7 -7
- package/dist/chunks/set-password-D5vZqqSX.js.map +1 -0
- package/dist/chunks/{set-token-21d1FTDC.js → set-token-xJkA1IZp.js} +7 -7
- package/dist/chunks/set-token-xJkA1IZp.js.map +1 -0
- package/dist/chunks/{settings-BVSBnIwJ.js → settings-xu-XTfWg.js} +126 -35
- package/dist/chunks/settings-xu-XTfWg.js.map +1 -0
- package/dist/chunks/{setup-temp-XiuAtiW2.js → setup-temp-CAN4_bA-.js} +6 -6
- package/dist/chunks/setup-temp-CAN4_bA-.js.map +1 -0
- package/dist/chunks/{src-BL97vLVb.js → src-BOBh9MBf.js} +2251 -1063
- package/dist/chunks/src-BOBh9MBf.js.map +1 -0
- package/dist/chunks/{status-EuWdRq8Q.js → status-B6f2-qhs.js} +12 -8
- package/dist/chunks/status-B6f2-qhs.js.map +1 -0
- package/dist/chunks/{ui-DbPuwddJ.js → ui-D562aqw5.js} +9 -7
- package/dist/chunks/ui-D562aqw5.js.map +1 -0
- package/dist/chunks/{ui-revert-BhqOAhmM.js → ui-revert-EkBBwRTt.js} +3 -3
- package/dist/chunks/{ui-revert-BhqOAhmM.js.map → ui-revert-EkBBwRTt.js.map} +1 -1
- package/dist/chunks/{ui-switch-CMoslPO2.js → ui-switch-BnZTdMDd.js} +3 -3
- package/dist/chunks/{ui-switch-CMoslPO2.js.map → ui-switch-BnZTdMDd.js.map} +1 -1
- package/dist/chunks/{ui-update-TTBBoDik.js → ui-update-_xryLYxw.js} +5 -5
- package/dist/chunks/{ui-update-TTBBoDik.js.map → ui-update-_xryLYxw.js.map} +1 -1
- package/dist/chunks/{up-C4H13hBw.js → up-DNZuTi2q.js} +25 -11
- package/dist/chunks/up-DNZuTi2q.js.map +1 -0
- package/dist/chunks/{usage-CSBgLRN5.js → usage-BrnDARNM.js} +29 -3
- package/dist/chunks/usage-BrnDARNM.js.map +1 -0
- package/dist/chunks/{workspaces-CAln2sQ7.js → workspaces-DYcfvKV_.js} +16 -8
- package/dist/chunks/workspaces-DYcfvKV_.js.map +1 -0
- package/dist/chunks/wsl-temperature-BiCI4iK6.js.map +1 -1
- package/dist/cli.js +80 -70
- package/dist/cli.js.map +1 -1
- package/dist/client.js +25 -1
- package/dist/client.js.map +1 -1
- package/dist/types/api/backups.d.ts +8 -3
- package/dist/types/api/control.d.ts +4 -3
- package/dist/types/api/events.d.ts +2 -1
- package/dist/types/api/health.d.ts +1 -0
- package/dist/types/api/metrics.d.ts +3 -1
- package/dist/types/api/settings.d.ts +2 -2
- package/dist/types/api/state.d.ts +8 -2
- package/dist/types/app.d.ts +26 -11
- package/dist/types/cli/backup.d.ts +7 -0
- package/dist/types/cli/down.d.ts +5 -0
- package/dist/types/cli/logs.d.ts +14 -2
- package/dist/types/cli/restart.d.ts +0 -1
- package/dist/types/cli/set-password.d.ts +2 -2
- package/dist/types/cli/up.d.ts +8 -2
- package/dist/types/client.d.ts +5618 -11
- package/dist/types/config/secrets.d.ts +2 -0
- package/dist/types/config/settings.d.ts +54 -8
- package/dist/types/config/store.d.ts +16 -3
- package/dist/types/config/workspaces.d.ts +4 -1
- package/dist/types/helpers/copy-tree.d.ts +5 -0
- package/dist/types/helpers/daemon.d.ts +20 -7
- package/dist/types/helpers/error.d.ts +8 -0
- package/dist/types/helpers/event-stream.d.ts +21 -0
- package/dist/types/helpers/openapi.d.ts +12 -24
- package/dist/types/helpers/paths.d.ts +18 -0
- package/dist/types/helpers/utf8-chunks.d.ts +15 -0
- package/dist/types/middleware/auth.d.ts +19 -3
- package/dist/types/providers/host.d.ts +1 -1
- package/dist/types/providers/log-tail.d.ts +27 -0
- package/dist/types/providers/nanny-sweep.d.ts +3 -0
- package/dist/types/providers/nanny.d.ts +10 -0
- package/dist/types/providers/proc.d.ts +9 -0
- package/dist/types/providers/process.d.ts +17 -0
- package/dist/types/providers/telegram.d.ts +45 -3
- package/dist/types/providers/wsl-temperature.d.ts +0 -4
- package/dist/types/services/auth.d.ts +36 -4
- package/dist/types/services/backups.d.ts +125 -1
- package/dist/types/services/ddns.d.ts +5 -0
- package/dist/types/services/exposure.d.ts +54 -1
- package/dist/types/services/history.d.ts +1 -0
- package/dist/types/services/host-monitor.d.ts +1 -0
- package/dist/types/services/log-buffer.d.ts +11 -0
- package/dist/types/services/log-files.d.ts +1 -11
- package/dist/types/services/log-relay.d.ts +0 -1
- package/dist/types/services/panel.d.ts +19 -0
- package/dist/types/services/proxy-certificates/certificates.d.ts +116 -0
- package/dist/types/services/proxy.d.ts +46 -69
- package/dist/types/services/state.d.ts +0 -3
- package/dist/types/services/supervisor/entry.d.ts +10 -0
- package/dist/types/services/supervisor/health.d.ts +3 -2
- package/dist/types/services/supervisor/output.d.ts +126 -0
- package/dist/types/services/supervisor/persistent.d.ts +4 -1
- package/dist/types/services/supervisor/records.d.ts +81 -1
- package/dist/types/services/supervisor.d.ts +32 -0
- package/dist/types/shared/action-outcome.d.ts +25 -0
- package/dist/types/shared/api-client.d.ts +218 -4
- package/dist/types/shared/backup-scope.d.ts +58 -0
- package/dist/types/shared/contracts.d.ts +142 -200
- package/dist/types/shared/ddns-form.d.ts +13 -0
- package/dist/types/shared/form-repair.d.ts +6 -0
- package/dist/types/shared/lazy.d.ts +4 -0
- package/dist/types/shared/live-frames.d.ts +22 -0
- package/dist/types/shared/live-series.d.ts +21 -0
- package/dist/types/shared/live-store.d.ts +72 -0
- package/dist/types/shared/patch-diff.d.ts +13 -2
- package/dist/types/shared/proxy-form.d.ts +2 -0
- package/dist/types/shared/server-form.d.ts +121 -0
- package/dist/types/shared/stream-access.d.ts +20 -0
- package/docs/API.md +45 -16
- package/docs/BACKUPS.md +31 -11
- package/docs/CLI.md +34 -61
- package/docs/DDNS.md +3 -1
- package/docs/NOTIFICATIONS.md +7 -1
- package/docs/REVERSE_PROXY.md +7 -1
- package/docs/SECURITY.md +21 -10
- package/docs/SERVERS.md +102 -23
- package/docs/UI_CREATION.md +10 -1
- package/docs/demo/blank-host-restore.sh +4 -3
- package/package.json +5 -7
- package/uis/stock/dist/assets/CopyButton-BUBKRJyY.js +1 -0
- package/uis/stock/dist/assets/GlobalSettingsView-yYMcRWvt.js +1 -0
- package/uis/stock/dist/assets/LogViewer-DIliXy62.js +1 -0
- package/uis/stock/dist/assets/LogsView-B7Z-7RNg.js +1 -0
- package/uis/stock/dist/assets/Modal-DmKa5Qpp.js +39 -0
- package/uis/stock/dist/assets/ProxyView-DvZiNkwb.js +1 -0
- package/uis/stock/dist/assets/ServerDetailView-6idGT_EX.js +2 -0
- package/uis/stock/dist/assets/SettingsShell-CeGtleYI.js +1 -0
- package/uis/stock/dist/assets/SettingsView-BrhJIrmk.js +2 -0
- package/uis/stock/dist/assets/de-BRITeb0H.js +1 -0
- package/uis/stock/dist/assets/es-B2zIEssV.js +1 -0
- package/uis/stock/dist/assets/fr-s0ZOBEqh.js +1 -0
- package/uis/stock/dist/assets/index-C1MehbKy.css +2 -0
- package/uis/stock/dist/assets/index-CnBN54wF.js +15 -0
- package/uis/stock/dist/assets/ja-CU7MR85V.js +1 -0
- package/uis/stock/dist/assets/ko-tL5Me6d-.js +1 -0
- package/uis/stock/dist/assets/ru-92yrvkNJ.js +1 -0
- package/uis/stock/dist/assets/vi-CzvY16k2.js +1 -0
- package/uis/stock/dist/assets/zh-CN-DDwFW_uW.js +1 -0
- package/uis/stock/dist/index.html +3 -2
- package/uis/stock/dist/ui.json +3 -3
- package/dist/chunks/archive-DpCwA8Nf.js.map +0 -1
- package/dist/chunks/atomic-CEfCUfkQ.js.map +0 -1
- package/dist/chunks/backup-CPrJVPJI.js.map +0 -1
- package/dist/chunks/backups-Bd2SF2qd.js.map +0 -1
- package/dist/chunks/contracts-ku5ypHXJ.js.map +0 -1
- package/dist/chunks/daemon-TwXk5vb8.js.map +0 -1
- package/dist/chunks/docker-CGv4Uv7w.js.map +0 -1
- package/dist/chunks/down-BlX5X3bm.js.map +0 -1
- package/dist/chunks/init-DdmqHVra.js.map +0 -1
- package/dist/chunks/last-stop-BZ08Z89-.js.map +0 -1
- package/dist/chunks/log-buffer-HnP0jKhZ.js.map +0 -1
- package/dist/chunks/logs-gI_69Q1P.js.map +0 -1
- package/dist/chunks/nanny-20aBXL1o.js.map +0 -1
- package/dist/chunks/nanny-sweep-Ca9kPAVi.js.map +0 -1
- package/dist/chunks/paths-BT94q6-w.js.map +0 -1
- package/dist/chunks/restart-UZgeDukG.js.map +0 -1
- package/dist/chunks/schema-o7Lgk0V1.js.map +0 -1
- package/dist/chunks/secrets-D7PdYh71.js.map +0 -1
- package/dist/chunks/set-password-DegMumPh.js.map +0 -1
- package/dist/chunks/set-token-21d1FTDC.js.map +0 -1
- package/dist/chunks/settings-BVSBnIwJ.js.map +0 -1
- package/dist/chunks/setup-temp-XiuAtiW2.js.map +0 -1
- package/dist/chunks/src-BL97vLVb.js.map +0 -1
- package/dist/chunks/status-EuWdRq8Q.js.map +0 -1
- package/dist/chunks/ui-DbPuwddJ.js.map +0 -1
- package/dist/chunks/up-C4H13hBw.js.map +0 -1
- package/dist/chunks/usage-CSBgLRN5.js.map +0 -1
- package/dist/chunks/workspaces-CAln2sQ7.js.map +0 -1
- package/docs/RESTORE_DEMO.md +0 -306
- package/uis/stock/dist/assets/de-DyGrM1KK.js +0 -1
- package/uis/stock/dist/assets/es-BebHdc0E.js +0 -1
- package/uis/stock/dist/assets/fr-DsDTrxhI.js +0 -1
- package/uis/stock/dist/assets/index-6LANO2Ua.css +0 -2
- package/uis/stock/dist/assets/index-D06cUZbM.js +0 -56
- package/uis/stock/dist/assets/ja-D3RARJjW.js +0 -1
- package/uis/stock/dist/assets/ko-CKI3dFoD.js +0 -1
- package/uis/stock/dist/assets/ru-DEU5ujXt.js +0 -1
- package/uis/stock/dist/assets/vi-ULKPnasj.js +0 -1
- package/uis/stock/dist/assets/zh-CN-tCvnOxWy.js +0 -1
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"last-stop-BZ08Z89-.js","names":[],"sources":["../../src/helpers/last-stop.ts"],"sourcesContent":["import path from 'node:path'\nimport { type } from 'arktype'\nimport { writeFileAtomic } from '#src/helpers/atomic'\nimport { readStateFile } from '#src/helpers/config-text'\nimport { hhDir } from '#src/helpers/paths'\n\n/**\n * How the panel last stopped — the fact `status` could not report.\n *\n * A clean `down` deletes `run.json`, and so does `up` when it finds a record with nothing behind the\n * pid. So \"no record\" covered both \"you stopped it\" and \"it died and the next start tidied up\", and a\n * script could only tell them apart by inferring from which *keys* were absent. This records the\n * answer instead of leaving it to be guessed.\n *\n * Only a deliberate stop writes it. A panel that was killed has nobody to write anything, which is\n * why a *stale record* stays the signal for that one — see `status`.\n */\nexport const lastStopSchema = type({\n /** Milliseconds since the epoch, from the process that stopped it. */\n at: 'number',\n /** How it stopped. `down` is the only writer today; the field exists so a future cause is named. */\n reason: '\"down\"',\n})\n\nexport type LastStop = typeof lastStopSchema.infer\n\nconst lastStopPath = path.join(hhDir, '.last-stop.json')\n\n/** Records a deliberate stop. Best-effort: a panel that stopped is stopped, whatever this file does. */\nexport function recordCleanStop(at = Date.now()): void {\n try {\n writeFileAtomic(lastStopPath, `${JSON.stringify({ at, reason: 'down' }, null, 2)}\\n`, { mode: 0o600 })\n }\n catch {\n // The stop itself succeeded; a missing marker only costs `status` one detail.\n }\n}\n\n/** The last deliberate stop, or null when there is none (or it cannot be read). */\nexport function readLastStop(): LastStop | null {\n try {\n const parsed = lastStopSchema(JSON.parse(readStateFile(lastStopPath)) as unknown)\n return parsed instanceof type.errors ? null : parsed\n }\n catch {\n return null\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;AAiBA,IAAa,iBAAiB,KAAK;;CAEjC,IAAI;;CAEJ,QAAQ;AACV,CAAC;AAID,IAAM,eAAe,KAAK,KAAK,OAAO,iBAAiB;;AAGvD,SAAgB,gBAAgB,KAAK,KAAK,IAAI,GAAS;CACrD,IAAI;EACF,gBAAgB,cAAc,GAAG,KAAK,UAAU;GAAE;GAAI,QAAQ;EAAO,GAAG,MAAM,CAAC,EAAE,KAAK,EAAE,MAAM,IAAM,CAAC;CACvG,QACM,CAEN;AACF;;AAGA,SAAgB,eAAgC;CAC9C,IAAI;EACF,MAAM,SAAS,eAAe,KAAK,MAAM,cAAc,YAAY,CAAC,CAAY;EAChF,OAAO,kBAAkB,KAAK,SAAS,OAAO;CAChD,QACM;EACJ,OAAO;CACT;AACF"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"log-buffer-HnP0jKhZ.js","names":[],"sources":["../../src/services/log-files.ts","../../src/services/log-buffer.ts"],"sourcesContent":["import type { LogLine, LogsConfig } from '#src/shared/contracts'\nimport { Buffer } from 'node:buffer'\nimport fs from 'node:fs'\nimport path from 'node:path'\n\n/**\n * Append-only JSONL per server, one line per log entry, rotated by size.\n *\n * JSONL keeps the tail readable without parsing a stream, and appending needs no\n * rewrite of the existing file. Writes are batched on a short timer so a chatty\n * child cannot turn into a syscall per line.\n */\nconst FLUSH_INTERVAL_MS = 250\nconst MAX_PENDING_LINES = 500\nconst READ_CHUNK_BYTES = 256 * 1024\n\nexport interface LogFileInfo {\n name: string\n sizeBytes: number\n}\n\nexport class LogFiles {\n private readonly pending = new Map<string, LogLine[]>()\n private timer: NodeJS.Timeout | null = null\n private closed = false\n\n constructor(\n private readonly dir: string,\n private readonly getConfig: () => LogsConfig,\n ) {}\n\n get directory(): string {\n return this.dir\n }\n\n /** The retention a nanny has to apply itself, on the same files. */\n get config(): LogsConfig {\n return this.getConfig()\n }\n\n append(serverId: string, line: LogLine): void {\n if (this.closed || !this.getConfig().persist)\n return\n\n const bucket = this.pending.get(serverId) ?? []\n bucket.push(line)\n this.pending.set(serverId, bucket)\n\n if (bucket.length >= MAX_PENDING_LINES) {\n this.flush()\n return\n }\n this.timer ??= setTimeout(() => {\n this.timer = null\n this.flush()\n }, FLUSH_INTERVAL_MS)\n this.timer.unref()\n }\n\n flush(): void {\n if (this.pending.size === 0)\n return\n\n const batches = [...this.pending.entries()]\n this.pending.clear()\n\n for (const [serverId, lines] of batches) {\n try {\n this.write(serverId, lines)\n }\n catch {\n // Logging must never take the control plane down.\n }\n }\n }\n\n info(serverId: string): { enabled: boolean, sizeBytes: number, files: LogFileInfo[] } {\n const config = this.getConfig()\n const files: LogFileInfo[] = []\n let sizeBytes = 0\n\n if (!config.persist)\n return { enabled: false, sizeBytes, files }\n\n for (const file of this.retained(serverId)) {\n try {\n const stats = fs.statSync(file)\n files.push({ name: path.basename(file), sizeBytes: stats.size })\n // The whole retained set, not just the newest file: this is summed into the page's\n // \"on disk\" total, and a server whose current file had just rotated read as nearly\n // empty while its rotations sat beside it.\n sizeBytes += stats.size\n }\n catch {\n // Not there yet.\n }\n }\n\n return { enabled: config.persist, sizeBytes, files }\n }\n\n /**\n * Reads the last `tail` lines, newest file first, padding from the rotations behind it.\n *\n * With `persist` off there is nothing this panel is willing to serve, even though a\n * persistent entry's nanny still writes its file: that file is the log's transport —\n * there is no pipe to carry it — and `persist` decides what counts as history.\n *\n * Every *retained* file is a source, not just `.1`: `keep` is the number of rotations the\n * person asked to keep, so a 5000-line window over a 10 MB rotation could not be filled by\n * the current file and `.1` alone. It read two of eleven files and returned \"no matches\" for\n * a line that was on disk — a search that answers \"nothing found\" while the log holds the\n * match is worse than a shorter window.\n */\n readTail(serverId: string, tail: number): LogLine[] {\n if (!this.getConfig().persist)\n return []\n\n // Oldest first, so `unshift` walks it backwards into reading order.\n const sources = this.retained(serverId)\n const lines: LogLine[] = []\n\n for (const file of sources) {\n if (lines.length >= tail)\n break\n const chunk = this.readTailChunk(file, tail - lines.length)\n lines.unshift(...chunk)\n }\n\n return lines.slice(-tail)\n }\n\n clear(serverId: string): void {\n // The batch that has not been flushed yet is still this server's, and `flush()` would write it\n // straight back — so the lines a delete was meant to remove reappeared a moment later.\n this.pending.delete(serverId)\n // Every file this id has, not the ones `keep` would name: lowering `keep` leaves rotations\n // numbered above it, and those are still this server's bytes. Deleting \"all the logs\" and\n // leaving five files behind is the worst version of this bug, because nothing lists them.\n for (const file of this.ownedFiles(serverId)) {\n try {\n fs.rmSync(file, { force: true })\n }\n catch {\n // Nothing to remove.\n }\n }\n }\n\n /**\n * Drops rotations above the current `keep`, for every server, now.\n *\n * `rotate` prunes too, but it only runs when a file fills — which on a quiet entry can be days\n * after the person lowered the ceiling. A retention setting that takes effect \"eventually, once\n * the server is chatty enough\" is not the promise the page makes, so the settings save calls\n * this directly.\n */\n prune(): void {\n let names: string[]\n try {\n names = fs.readdirSync(this.dir)\n }\n catch {\n return\n }\n\n const ids = new Set<string>()\n for (const name of names) {\n // `<id>.log` or `<id>.log.<n>`; the id charset has no dot, so the first dot ends it.\n const dot = name.indexOf('.log')\n if (dot > 0 && (name.length === dot + 4 || name.startsWith('.log.', dot)))\n ids.add(name.slice(0, dot))\n }\n for (const id of ids) this.pruneServer(id)\n }\n\n dispose(): void {\n this.closed = true\n if (this.timer !== null)\n clearTimeout(this.timer)\n this.timer = null\n this.flush()\n }\n\n private write(serverId: string, lines: LogLine[]): void {\n const { maxBytes } = this.getConfig()\n const file = this.currentPath(serverId)\n fs.mkdirSync(this.dir, { recursive: true })\n\n // A batch is split at the size limit: writing it whole would sail past\n // maxBytes long before the next rotation check runs.\n let encoded: string[] = []\n let bytes = 0\n\n const commit = (): void => {\n if (encoded.length === 0)\n return\n const payload = `${encoded.join('\\n')}\\n`\n const currentSize = fs.existsSync(file) ? fs.statSync(file).size : 0\n if (currentSize + Buffer.byteLength(payload) > maxBytes)\n this.rotate(serverId)\n fs.appendFileSync(this.currentPath(serverId), payload)\n encoded = []\n bytes = 0\n }\n\n for (const line of lines) {\n const json = JSON.stringify(line)\n const size = Buffer.byteLength(json) + 1\n if (bytes > 0 && bytes + size > maxBytes)\n commit()\n encoded.push(json)\n bytes += size\n }\n\n commit()\n }\n\n /**\n * Drops this id's rotations numbered above `keep`.\n *\n * They are left over from a higher ceiling (or an older release). Renaming up only ever shifts\n * them further out of reach, so they have to be removed outright: a retention setting is a\n * promise about the directory, not about a rename loop.\n */\n private pruneServer(serverId: string): void {\n const { keep } = this.getConfig()\n const current = this.currentPath(serverId)\n for (const file of this.ownedFiles(serverId)) {\n if (file === current)\n continue\n const index = Number(file.slice(current.length + 1))\n if (!Number.isInteger(index) || index <= keep)\n continue\n try {\n fs.rmSync(file, { force: true })\n }\n catch {\n // Already gone.\n }\n }\n }\n\n private rotate(serverId: string): void {\n const { keep } = this.getConfig()\n this.pruneServer(serverId)\n for (let index = keep - 1; index >= 1; index--) {\n const from = this.rotatedPath(serverId, index)\n if (!fs.existsSync(from))\n continue\n fs.renameSync(from, this.rotatedPath(serverId, index + 1))\n }\n if (fs.existsSync(this.currentPath(serverId))) {\n fs.renameSync(this.currentPath(serverId), this.rotatedPath(serverId, 1))\n }\n }\n\n /**\n * The last `tail` parseable lines of one file.\n *\n * Reads backwards, growing the window until it has enough lines. It used to read exactly one\n * fixed chunk, which silently truncated: a JSONL line here is a couple of hundred bytes, so\n * one 256 KB chunk holds roughly 1500 of them, while the route accepts `tail=5000`. Asking\n * for 5000 returned 1464 and dropped 3536 lines with no error — the oldest line handed back\n * was not the oldest asked for.\n */\n private readTailChunk(file: string, tail: number): LogLine[] {\n let handle: number\n try {\n handle = fs.openSync(file, 'r')\n }\n catch {\n return []\n }\n\n try {\n const size = fs.fstatSync(handle).size\n if (size === 0)\n return []\n\n let start = Math.max(0, size - READ_CHUNK_BYTES)\n let parsed: LogLine[] = []\n\n // One extra loop's worth of margin, because a partial line at the window's start is\n // dropped and a line can be long: growing beats guessing the exact byte count.\n while (true) {\n const length = size - start\n const buffer = Buffer.alloc(length)\n fs.readSync(handle, buffer, 0, length, start)\n\n // A mid-file cut leaves a partial first line. A JSONL log is one object per line, so a\n // fragment cannot parse and the loop below skips it — but the whole-file case has no\n // fragment, which is what `start > 0` distinguishes.\n const raw = buffer.toString('utf8').split('\\n')\n parsed = []\n for (const entry of start > 0 ? raw.slice(1) : raw) {\n if (entry.trim().length === 0)\n continue\n try {\n parsed.push(JSON.parse(entry) as LogLine)\n }\n catch {\n // A partial line, or a torn write at the file's end.\n }\n }\n\n if (parsed.length >= tail || start === 0)\n return parsed.slice(-tail)\n\n start = Math.max(0, start - READ_CHUNK_BYTES)\n }\n }\n finally {\n fs.closeSync(handle)\n }\n }\n\n private currentPath(serverId: string): string {\n return path.join(this.dir, `${serverId}.log`)\n }\n\n private rotatedPath(serverId: string, index: number): string {\n return path.join(this.dir, `${serverId}.log.${index}`)\n }\n\n /**\n * Every file this id owns on disk, newest first, found by reading the directory.\n *\n * The count comes from the directory rather than from `keep` because the two disagree the\n * moment a person lowers it: `rotate` only renames *up* to the new ceiling, so it never removes\n * the rotations numbered above it. Those files stayed, were invisible to `info()`, were served\n * by no reader, and survived a `clear` — growth the retention setting promised to bound, in\n * files nothing would ever show. Reading the directory is also what makes them prunable.\n */\n private ownedFiles(serverId: string): string[] {\n const current = this.currentPath(serverId)\n const prefix = `${serverId}.log.`\n let names: string[]\n try {\n names = fs.readdirSync(this.dir)\n }\n catch {\n return fs.existsSync(current) ? [current] : []\n }\n\n // `.log.1`, `.log.2`, … in numeric order — a plain string sort puts `.10` before `.2`.\n const rotated = names\n .filter(name => name.startsWith(prefix))\n .map(name => ({ name, index: Number(name.slice(prefix.length)) }))\n .filter(entry => Number.isInteger(entry.index) && entry.index >= 1)\n .sort((a, b) => a.index - b.index)\n .map(entry => path.join(this.dir, entry.name))\n\n // Newest first, which is the order `info()` lists and the order a tail walks.\n return fs.existsSync(current) ? [current, ...rotated] : rotated\n }\n\n /**\n * The files `keep` still covers, newest first — what `info` lists and what a tail may read.\n *\n * The current file is always first and never counted against `keep`, which is what the UI\n * promises (\"before rolling to .1, .2, …\").\n */\n private retained(serverId: string): string[] {\n const { keep } = this.getConfig()\n const owned = this.ownedFiles(serverId)\n if (owned.length === 0)\n return []\n const [current, ...rotated] = owned\n // `rotated` is ascending from `.1`, so the first `keep` of it are the newest rotations.\n const covered = rotated.slice(0, keep)\n return current === undefined ? covered : [current, ...covered]\n }\n}\n","import type { Buffer } from 'node:buffer'\nimport type { LogLine, LogStream } from '#src/shared/contracts'\n\n/** A partial line past this size is emitted rather than buffered further. */\nconst MAX_PENDING_CHARS = 64 * 1024\n\n/**\n * How many *characters* the ring may hold, on top of its line count.\n *\n * `logBufferLines` bounds lines, and a line is capped at 64 KiB by the splitter — so 500 lines\n * of a chatty 2 MB/s writer is ~32 MB per server, times every server, in the panel's heap. The\n * count is the user's setting; this is the ceiling that keeps that setting from being a memory\n * bomb. Generous enough that ordinary logs never reach it (500 lines is well under 1 MB).\n */\nconst MAX_TOTAL_CHARS = 4 * 1024 * 1024\n\n/** Fixed-capacity line buffer; oldest lines are dropped first. */\nexport class LogBuffer {\n private lines: LogLine[] = []\n /** Characters held, so the byte ceiling never needs a rescan. */\n private chars = 0\n\n constructor(private capacity: number) {}\n\n push(line: LogLine): void {\n this.lines.push(line)\n this.chars += line.text.length\n if (this.lines.length > this.capacity)\n this.dropOldest(this.lines.length - this.capacity)\n // Drop past the ceiling too, keeping at least one line so a single oversized line is still\n // shown rather than leaving the buffer empty.\n while (this.chars > MAX_TOTAL_CHARS && this.lines.length > 1)\n this.dropOldest(1)\n }\n\n /** Removes the oldest `count` lines and keeps `chars` in step with them. */\n private dropOldest(count: number): void {\n const dropped = this.lines.splice(0, count)\n for (const line of dropped) this.chars -= line.text.length\n }\n\n extend(lines: LogLine[]): void {\n for (const line of lines) this.push(line)\n }\n\n list(limit?: number): LogLine[] {\n if (limit === undefined || limit >= this.lines.length)\n return [...this.lines]\n return this.lines.slice(-limit)\n }\n\n clear(): void {\n this.lines = []\n this.chars = 0\n }\n\n get size(): number {\n return this.lines.length\n }\n}\n\n/**\n * Splits a chunk into complete lines, keeping a trailing partial line buffered:\n * a child writing \"hel\" then \"lo\\n\" must surface one line, not two.\n */\nexport class LineSplitter {\n private pending = ''\n\n constructor(private readonly emit: (stream: LogStream, text: string) => void) {}\n\n push(stream: LogStream, chunk: string | Buffer): void {\n this.pending += chunk.toString()\n const parts = this.pending.split('\\n')\n this.pending = parts.pop() ?? ''\n for (const part of parts) this.emit(stream, part.replace(/\\r$/, ''))\n // A child that never sends a newline (a progress bar, one minified JSON blob)\n // must not grow this string without bound: past the cap it is emitted in pieces.\n while (this.pending.length > MAX_PENDING_CHARS) {\n this.emit(stream, this.pending.slice(0, MAX_PENDING_CHARS))\n this.pending = this.pending.slice(MAX_PENDING_CHARS)\n }\n }\n\n flush(stream: LogStream): void {\n if (this.pending.length === 0)\n return\n this.emit(stream, this.pending.replace(/\\r$/, ''))\n this.pending = ''\n }\n}\n"],"mappings":";;;;;;;;;;;AAYA,IAAM,oBAAoB;AAC1B,IAAM,oBAAoB;AAC1B,IAAM,mBAAmB;AAOzB,IAAa,WAAb,MAAsB;CAMD;CACA;CANnB,0BAA2B,IAAI,IAAuB;CACtD,QAAuC;CACvC,SAAiB;CAEjB,YACE,KACA,WACA;EAFiB,KAAA,MAAA;EACA,KAAA,YAAA;CAChB;CAEH,IAAI,YAAoB;EACtB,OAAO,KAAK;CACd;;CAGA,IAAI,SAAqB;EACvB,OAAO,KAAK,UAAU;CACxB;CAEA,OAAO,UAAkB,MAAqB;EAC5C,IAAI,KAAK,UAAU,CAAC,KAAK,UAAU,CAAC,CAAC,SACnC;EAEF,MAAM,SAAS,KAAK,QAAQ,IAAI,QAAQ,KAAK,CAAC;EAC9C,OAAO,KAAK,IAAI;EAChB,KAAK,QAAQ,IAAI,UAAU,MAAM;EAEjC,IAAI,OAAO,UAAU,mBAAmB;GACtC,KAAK,MAAM;GACX;EACF;EACA,KAAK,UAAU,iBAAiB;GAC9B,KAAK,QAAQ;GACb,KAAK,MAAM;EACb,GAAG,iBAAiB;EACpB,KAAK,MAAM,MAAM;C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;;AAMA,IAAa,eAAb,MAA0B;CAGK;CAF7B,UAAkB;CAElB,YAAY,MAAkE;EAAjD,KAAA,OAAA;CAAkD;CAE/E,KAAK,QAAmB,OAA8B;EACpD,KAAK,WAAW,MAAM,SAAS;EAC/B,MAAM,QAAQ,KAAK,QAAQ,MAAM,IAAI;EACrC,KAAK,UAAU,MAAM,IAAI,KAAK;EAC9B,KAAK,MAAM,QAAQ,OAAO,KAAK,KAAK,QAAQ,KAAK,QAAQ,OAAO,EAAE,CAAC;EAGnE,OAAO,KAAK,QAAQ,SAAS,mBAAmB;GAC9C,KAAK,KAAK,QAAQ,KAAK,QAAQ,MAAM,GAAG,iBAAiB,CAAC;GAC1D,KAAK,UAAU,KAAK,QAAQ,MAAM,iBAAiB;EACrD;CACF;CAEA,MAAM,QAAyB;EAC7B,IAAI,KAAK,QAAQ,WAAW,GAC1B;EACF,KAAK,KAAK,QAAQ,KAAK,QAAQ,QAAQ,OAAO,EAAE,CAAC;EACjD,KAAK,UAAU;CACjB;AACF"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"logs-gI_69Q1P.js","names":[],"sources":["../../src/cli/logs.ts"],"sourcesContent":["import fs from 'node:fs'\nimport path from 'node:path'\nimport process from 'node:process'\nimport { defineCommand } from 'citty'\nimport { bold, dim, fail, refusal } from '#src/cli/io'\nimport { errorMessage } from '#src/shared/error-message'\n\n/** `logs` answers \"what has the panel been saying\" — the file `up` redirects it into. */\n\nexport const logsArgs = {\n id: { type: 'positional', required: false, description: 'show one server\\'s own log instead of the panel console' },\n lines: { type: 'string', description: 'how many lines to show (default 50, `all` for everything)' },\n follow: { type: 'boolean', description: 'keep printing as the panel writes (like tail -f)' },\n json: { type: 'boolean', description: 'print machine-readable JSON' },\n workspace: { type: 'string', alias: 'w', description: 'the workspace the server is in (default: the panel\\'s default workspace)' },\n} as const\n\nconst DEFAULT_LINES = 50\n\n/**\n * Whether a path exists but cannot be read — the case `readLog` cannot distinguish from absence,\n * because it folds every failure into \"nothing there\".\n *\n * A *missing* log is normal (a panel that has not started), so only a real permission or IO\n * refusal is reported. `R_OK` is the question being asked; existence alone would call an\n * unreadable file readable.\n */\nfunction isUnreadable(file: string): boolean {\n try {\n fs.accessSync(file, fs.constants.R_OK)\n return false\n }\n catch (error) {\n // Missing is not unreadable: that is the ordinary empty case.\n return (error as NodeJS.ErrnoException).code !== 'ENOENT'\n }\n}\n\n/**\n * `all` or a negative count means the whole log; an unreadable count is a typo, not a reason to\n * fail, so it falls back to the default.\n *\n * What it does **not** do is accept a *partly* numeric argument, which is how\n * `Number.parseInt` behaves and why this is not just a `parseInt`. `--lines 1e3` meant 1 line\n * (not 1000), and `--lines 0x10` parsed as 0 — which is the \"whole log\" sentinel, so a bounded\n * request silently became an unbounded one. Neither is a typo falling back to a default; both are\n * a wrong answer the caller cannot see. The whole trimmed argument has to be a decimal integer.\n */\nfunction parseLines(raw: string | undefined): number {\n if (raw === undefined)\n return DEFAULT_LINES\n const trimmed = raw.trim()\n if (trimmed.toLowerCase() === 'all')\n return 0\n if (!/^[+-]?\\d+$/.test(trimmed))\n return DEFAULT_LINES\n const parsed = Number.parseInt(trimmed, 10)\n if (!Number.isSafeInteger(parsed))\n return DEFAULT_LINES\n return parsed < 0 ? 0 : parsed\n}\n\nexport interface LogTarget {\n /** The file the lines come from, for the header and for `--json`'s `path`. */\n file: string\n /** The workspace the file is in, when the target is one server's log. */\n workspaceId?: string\n /** The id asked for, when the target is one server's log. */\n serverId?: string\n}\n\n/**\n * Resolves which log a `logs` call is about: the panel's own console, or one server's.\n *\n * A server's log is JSONL on disk (`<id>.log`, plus `.log.N` rotations) and is readable with no\n * session, no token and no answering panel — the same property that makes `panel.console` a\n * first-class diagnostic. The workspace is explicit because a server id is only unique inside one.\n *\n * An omitted `--workspace` resolves through `defaultWorkspaceId` — the same rule the panel uses for\n * an omitted `?workspace` — because reading `DEFAULT_WORKSPACE_ID` literally here made `logs`\n * disagree with `start`/`stop` on a host that does not declare a `default` workspace.\n */\nasync function resolveTarget(input: { id?: string, workspace?: string }): Promise<LogTarget> {\n const { daemonLogPath, workspaceLogsDir, workspacesPath } = await import('#src/helpers/paths')\n if (input.id === undefined || input.id.length === 0)\n return { file: daemonLogPath }\n\n const id = input.id.trim()\n const explicit = input.workspace !== undefined && input.workspace.length > 0\n // `readDefaultWorkspaceId`, not `DEFAULT_WORKSPACE_ID`: \"which one is the default\" is the panel's\n // own rule (`default` if declared, else the first listed), and reading the literal id here made\n // `logs` name a workspace that `start`/`stop` would not act in. Read only when it is needed.\n if (!explicit) {\n const workspaceId = await defaultWorkspace(workspacesPath)\n return { file: path.join(workspaceLogsDir(workspaceId), `${id}.log`), workspaceId, serverId: id }\n }\n // Refused rather than guessed: an id is only unique inside a workspace, and reading the default\n // one for a server that lives elsewhere would print another server's output under this name.\n const workspaceId = input.workspace!.trim()\n return { file: path.join(workspaceLogsDir(workspaceId), `${id}.log`), workspaceId, serverId: id }\n}\n\n/** The workspace this host treats as the default — the panel's own rule, read from the registry. */\nasync function defaultWorkspace(registryFile: string): Promise<string> {\n const { readDefaultWorkspaceId } = await import('#src/config/workspaces')\n return readDefaultWorkspaceId(registryFile)\n}\n\n/**\n * Refuses an id this workspace's `servers.config.json` does not declare, **unless a log for it is\n * on disk** — returns whether it refused, so the caller stops before printing an answer.\n *\n * `logs webx` printed `no output yet — …/webx.log` and exited 0, so a diagnostic session's first\n * command agreed with a typo, and `logs webx | grep -q error` was a silently empty pipeline that\n * reads as \"no errors\". `start webx`/`stop webx` refuse the same id over the same config, so the\n * two commands now agree.\n *\n * The log's own existence is the exception, on purpose: a file outlives the entry that wrote it,\n * so refusing on the config alone would make the log of a **removed** server unreadable — the one\n * log a person is most likely to want. It is read as before, and a note says the entry is gone.\n *\n * \"I cannot tell\" (no config, an unparseable one) is not \"there is no such entry\", so it answers as\n * it did before. So does the panel console, which is not a server at all.\n *\n * `refusal()` plus an exit code rather than `fail()`, the same shape as the unreadable-file branch\n * in `runLogs`: `fail()` ends the process, and a command module that can be called in-process\n * should leave that decision where the answer is decided. One refusal is still one message on one\n * stream.\n */\nasync function refuseUnknownServer(target: LogTarget, json: boolean): Promise<boolean> {\n const { serverId, workspaceId } = target\n if (serverId === undefined || workspaceId === undefined)\n return false\n\n const { workspaceServersPath, workspacesPath } = await import('#src/helpers/paths')\n const { readDeclaredServerIds } = await import('#src/config/server-ids')\n const { logExists } = await import('#src/helpers/daemon-log')\n const { nearestWord } = await import('#src/cli/nearest')\n\n /**\n * The workspace itself first: an id that names no workspace makes every answer below meaningless,\n * and the old code joined it into a path and read a file that could not exist. `logs web -w typo`\n * printed `no output yet — …/.hh/typo/.logs/web.log` and exited 0, so `logs web -w typo | grep -q\n * error` was an empty pipeline that reads as \"no errors\" — while `start web -w typo` refused the\n * same id. A log on disk still wins, for the same reason it does for a removed server.\n */\n if (!logExists(target.file)) {\n const { readWorkspaceIds } = await import('#src/config/workspaces')\n const known = readWorkspaceIds(workspacesPath)\n if (known !== null && !known.includes(workspaceId)) {\n const suggestion = nearestWord(workspaceId, known)\n refusal(`unknown workspace \"${workspaceId}\"${suggestion === null ? '' : ` — did you mean \\`${suggestion}\\`?`} (${workspacesPath})`)\n process.exitCode = 1\n return true\n }\n }\n\n const declared = readDeclaredServerIds(workspaceServersPath(workspaceId))\n if (declared === null || declared.includes(serverId))\n return false\n\n // The log is the reason this command exists, so a file on disk is always read. Saying the entry\n // is gone is the part that stops \"this server has written nothing\" from being the conclusion.\n if (logExists(target.file)) {\n if (!json)\n process.stderr.write(`${dim(`${workspaceId}/${serverId} is not in servers.config.json any more — reading the log it left behind`)}\\n`)\n return false\n }\n\n const suggestion = nearestWord(serverId, declared)\n // The hint names the config file, not `usage`: that command needs an answering panel, and the\n // person reading this is most often holding a panel that is why they are here. The file is\n // readable either way, and it is the same source this refusal just read.\n const hint = suggestion === null\n ? `it is not in ${workspaceServersPath(workspaceId)}`\n : `did you mean \\`${suggestion}\\`? (${workspaceServersPath(workspaceId)})`\n // One refusal, one message, one stream: stdout carries only an answer, and there is none to give.\n // The `--json` form answers nothing either, because `{ lines: [] }` is the empty success this\n // refusal exists to stop.\n refusal(`unknown server \"${serverId}\" in workspace \"${workspaceId}\" — ${hint}`)\n process.exitCode = 1\n return true\n}\n\nexport async function runLogs(input: { id?: string, lines?: string, follow?: boolean, json?: boolean, workspace?: string }): Promise<void> {\n const { readLog } = await import('#src/helpers/daemon-log')\n const lines = parseLines(input.lines)\n const target = await resolveTarget({ id: input.id, workspace: input.workspace })\n const logPath = target.file\n // A server's log is JSONL, the panel console is text. `--json` must still hand back the **stored**\n // record, so only the human form is rendered.\n const isServerLog = target.serverId !== undefined\n\n // A typo agrees with an empty log unless the entry's own config is consulted — see\n // `refuseUnknownServer` for why this is a refusal and not a silence.\n if (await refuseUnknownServer(target, input.json === true))\n return\n\n if (input.follow === true) {\n const { followLog } = await import('#src/helpers/daemon-log')\n // `lines` goes through unchanged: `readLog` already reads `0` as \"the whole log\", which is what\n // `--lines all` (and a negative, the same sentinel) parsed to. This used to rewrite 0 to\n // `DEFAULT_LINES`, so `logs --lines all --follow` printed 50 lines of a 200-line log while the\n // help and synopsis advertise `[--lines <n>] [--follow]` as composable — the worst failure\n // for a diagnostic command, since the answer looked complete. Same class as `--follow --json`\n // ignoring `--json`, which the branch below already fixed.\n if (input.json !== true) {\n // A server's log is JSONL, so the human form renders each line; a chunk can end mid-line, so\n // only complete lines are rendered and the tail is carried to the next chunk.\n if (!isServerLog) {\n await followLog(logPath, lines, chunk => process.stdout.write(chunk))\n return\n }\n let partial = ''\n const emitLine = (raw: string): void => {\n process.stdout.write(`${renderLine(raw, true)}\\n`)\n }\n await followLog(logPath, lines, (chunk) => {\n partial += chunk\n const parts = partial.split('\\n')\n partial = parts.pop() ?? ''\n for (const part of parts) {\n if (part.length > 0)\n emitLine(part)\n }\n })\n if (partial.length > 0)\n emitLine(partial)\n return\n }\n // `--follow --json` used to ignore `--json` and print raw text, which the synopsis\n // (`logs [--lines <n>] [--follow] [--json]`) advertised as composable. A stream has no\n // single document, so the machine-readable form of it is one JSON object per line — each\n // carrying the same `path` the one-shot form reports, so a consumer needs no out-of-band\n // knowledge of which file it is reading.\n const emit = (line: string): void => {\n process.stdout.write(`${JSON.stringify({ path: logPath, line })}\\n`)\n }\n // A chunk can end mid-line, so lines are only emitted once their newline has arrived.\n let pending = ''\n await followLog(logPath, lines, (chunk) => {\n pending += chunk\n const parts = pending.split('\\n')\n pending = parts.pop() ?? ''\n for (const part of parts) emit(part)\n })\n if (pending.length > 0)\n emit(pending)\n return\n }\n\n const output = readLog(logPath, lines)\n\n // Checked once, before either output form. `readLog` treats every read failure as \"not there\",\n // so an unreadable log and a missing one look identical to it — and both surfaces would then\n // claim the panel has written nothing when it may have written plenty. A panel run as another\n // user (systemd, root) is the realistic case. Doing this above the `--json` branch is what keeps\n // the two forms from disagreeing: `--json` used to answer `{ lines: [] }` while the text form\n // reported the permission problem, because the check sat below it.\n if (output.length === 0 && isUnreadable(logPath)) {\n if (input.json === true) {\n process.stdout.write(`${JSON.stringify({ path: logPath, error: 'unreadable' }, null, 2)}\\n`)\n }\n else {\n // The refusal goes to **stderr**: stdout is the answer, and a script reading a diagnostic\n // command's output must not have to tell a permission problem from a line of the log. The\n // `--json` branch above keeps its document on stdout because that *is* the answer — `error`\n // is the key a JSON consumer reads there.\n refusal(`cannot read ${logPath} — check its permissions`)\n }\n process.exitCode = 1\n return\n }\n\n if (input.json === true) {\n process.stdout.write(`${JSON.stringify({ path: logPath, lines: output }, null, 2)}\\n`)\n return\n }\n\n if (output.length === 0) {\n // Not an error: a panel that has just started, or never started, has nothing to say.\n process.stdout.write(`${dim(`no output yet — ${logPath}`)}\\n`)\n return\n }\n\n process.stdout.write(`${bold(logPath)}\\n`)\n for (const line of output)\n process.stdout.write(`${renderLine(line, isServerLog)}\\n`)\n}\n\n/**\n * One stored server line as text.\n *\n * A server's log is JSONL (`{ ts, stream, text }`), so the raw bytes would show a person a JSON\n * object per line where the panel shows them a log. A line that does not parse is not dropped: a\n * truncated write still says something, and hiding it is worse than showing it raw.\n */\nfunction renderLine(raw: string, server: boolean): string {\n if (!server)\n return raw\n try {\n const parsed: unknown = JSON.parse(raw)\n if (typeof parsed === 'object' && parsed !== null && typeof (parsed as { text?: unknown }).text === 'string')\n return (parsed as { text: string }).text\n }\n catch {\n // Fall through: an unparseable line is shown as it was written.\n }\n return raw\n}\n\nexport const logsCommand = defineCommand({\n // No `description`: the one copy is `SUMMARIES` in `cli.ts`. See `server.ts` for why a module copy\n // here is unreachable.\n meta: { name: 'logs' },\n args: logsArgs,\n async run({ args }) {\n try {\n await runLogs({ id: args.id, lines: args.lines, follow: args.follow, json: args.json, workspace: args.workspace })\n }\n catch (error) {\n fail(errorMessage(error))\n }\n },\n})\n"],"mappings":";;;;;;;AASA,IAAa,WAAW;CACtB,IAAI;EAAE,MAAM;EAAc,UAAU;EAAO,aAAa;CAA0D;CAClH,OAAO;EAAE,MAAM;EAAU,aAAa;CAA4D;CAClG,QAAQ;EAAE,MAAM;EAAW,aAAa;CAAmD;CAC3F,MAAM;EAAE,MAAM;EAAW,aAAa;CAA8B;CACpE,WAAW;EAAE,MAAM;EAAU,OAAO;EAAK,aAAa;CAA2E;AACnI;AAEA,IAAM,gBAAgB;;;;;;;;;AAUtB,SAAS,aAAa,MAAuB;CAC3C,IAAI;EACF,GAAG,WAAW,MAAM,GAAG,UAAU,IAAI;EACrC,OAAO;CACT,SACO,OAAO;EAEZ,OAAQ,MAAgC,SAAS;CACnD;AACF;;;;;;;;;;;AAYA,SAAS,WAAW,KAAiC;CACnD,IAAI,QAAQ,KAAA,GACV,OAAO;CACT,MAAM,UAAU,IAAI,KAAK;CACzB,IAAI,QAAQ,YAAY,MAAM,OAC5B,OAAO;CACT,IAAI,CAAC,aAAa,KAAK,OAAO,GAC5B,OAAO;CACT,MAAM,SAAS,OAAO,SAAS,SAAS,EAAE;CAC1C,IAAI,CAAC,OAAO,cAAc,MAAM,GAC9B,OAAO;CACT,OAAO,SAAS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,KAAK,UAAU;GAAE,MAAM;GAAS,OAAO;EAAO,GAAG,MAAM,CAAC,EAAE,GAAG;EACrF;CACF;CAEA,IAAI,OAAO,WAAW,GAAG;EAEvB,QAAQ,OAAO,MAAM,GAAG,IAAI,mBAAmB,SAAS,EAAE,GAAG;EAC7D;CACF;CAEA,QAAQ,OAAO,MAAM,GAAG,KAAK,OAAO,EAAE,GAAG;CACzC,KAAK,MAAM,QAAQ,QACjB,QAAQ,OAAO,MAAM,GAAG,WAAW,MAAM,WAAW,EAAE,GAAG;AAC7D;;;;;;;;AASA,SAAS,WAAW,KAAa,QAAyB;CACxD,IAAI,CAAC,QACH,OAAO;CACT,IAAI;EACF,MAAM,SAAkB,KAAK,MAAM,GAAG;EACtC,IAAI,OAAO,WAAW,YAAY,WAAW,QAAQ,OAAQ,OAA8B,SAAS,UAClG,OAAQ,OAA4B;CACxC,QACM,CAEN;CACA,OAAO;AACT;AAEA,IAAa,cAAc,cAAc;CAGvC,MAAM,EAAE,MAAM,OAAO;CACrB,MAAM;CACN,MAAM,IAAI,EAAE,QAAQ;EAClB,IAAI;GACF,MAAM,QAAQ;IAAE,IAAI,KAAK;IAAI,OAAO,KAAK;IAAO,QAAQ,KAAK;IAAQ,MAAM,KAAK;IAAM,WAAW,KAAK;GAAU,CAAC;EACnH,SACO,OAAO;GACZ,KAAK,aAAa,KAAK,CAAC;EAC1B;CACF;AACF,CAAC"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"nanny-20aBXL1o.js","names":["execFileAsync","execFileAsync"],"sources":["../../src/providers/proc.ts","../../src/providers/identity.ts","../../src/providers/process.ts","../../src/providers/nanny.ts"],"sourcesContent":["import type { ProcessResources } from '#src/shared/contracts'\nimport { execFile } from 'node:child_process'\nimport fs from 'node:fs'\nimport process from 'node:process'\nimport { promisify } from 'node:util'\n\nconst execFileAsync = promisify(execFile)\n\ninterface ProcRow {\n pid: number\n ppid: number\n rssKb: number\n /** Cumulative CPU seconds, when the platform reports it (Linux, Windows). */\n cpuSeconds?: number\n /** Instantaneous/decaying CPU percent, when the platform reports it (macOS). */\n cpuPercent?: number\n}\n\nexport function parsePsOutput(text: string): ProcRow[] {\n const rows: ProcRow[] = []\n for (const line of text.split('\\n')) {\n const parts = line.trim().split(/\\s+/)\n if (parts.length < 4)\n continue\n const [pid, ppid, rss, cpu] = parts.map(entry => Number.parseFloat(entry))\n if (pid === undefined || ppid === undefined || rss === undefined || !Number.isFinite(pid))\n continue\n rows.push({ pid, ppid, rssKb: rss, cpuPercent: Number.isFinite(cpu) ? cpu : undefined })\n }\n return rows\n}\n\n/** CSV from `Get-CimInstance ... | ConvertTo-Csv`, or wmic's `/format:csv`. */\nexport function parseWindowsCsv(text: string): ProcRow[] {\n const rows: ProcRow[] = []\n const lines = text.split(/\\r?\\n/).filter(line => line.trim().length > 0)\n const header = lines.shift()\n if (header === undefined)\n return rows\n\n const columns = header.split(',').map(entry => entry.replace(/\"/g, '').trim().toLowerCase())\n const index = (name: string): number => columns.indexOf(name.toLowerCase())\n const pidAt = index('ProcessId')\n const ppidAt = index('ParentProcessId')\n const rssAt = index('WorkingSetSize')\n const kernelAt = index('KernelModeTime')\n const userAt = index('UserModeTime')\n\n for (const line of lines) {\n const cells = line.split(',').map(entry => entry.replace(/\"/g, '').trim())\n const pid = Number.parseInt(cells[pidAt] ?? '', 10)\n if (!Number.isFinite(pid))\n continue\n\n // A missing time column must read as \"unknown\", never as zero CPU.\n const kernel = kernelAt >= 0 ? Number.parseInt(cells[kernelAt] ?? '', 10) : Number.NaN\n const user = userAt >= 0 ? Number.parseInt(cells[userAt] ?? '', 10) : Number.NaN\n const hasTimes = Number.isFinite(kernel) && Number.isFinite(user)\n\n rows.push({\n pid,\n ppid: Number.parseInt(cells[ppidAt] ?? '', 10) || 0,\n // WorkingSetSize is bytes on Windows; the sampler sums kilobytes.\n rssKb: (Number.parseInt(cells[rssAt] ?? '', 10) || 0) / 1024,\n cpuSeconds: hasTimes ? (kernel + user) / 1e7 /* 100ns units */ : undefined,\n })\n }\n\n return rows\n}\n\nlet clockTicks: number | null = null\n\n/** Linux jiffies per second; `getconf` is POSIX, with the usual default behind it. */\nasync function getClockTicks(): Promise<number> {\n if (clockTicks !== null)\n return clockTicks\n try {\n const { stdout } = await execFileAsync('getconf', ['CLK_TCK'], { timeout: 2000 })\n const parsed = Number.parseInt(stdout.trim(), 10)\n clockTicks = Number.isFinite(parsed) && parsed > 0 ? parsed : 100\n }\n catch {\n clockTicks = 100\n }\n return clockTicks\n}\n\n/**\n * `/proc/<pid>/stat` needs care: the comm field is parenthesised and may itself\n * contain spaces or parentheses, so parsing starts after the last `)`.\n */\nfunction parseStat(pid: number, content: string): ProcRow | null {\n const close = content.lastIndexOf(')')\n if (close < 0)\n return null\n const fields = content.slice(close + 2).split(' ')\n const ppid = Number.parseInt(fields[1] ?? '', 10)\n const utime = Number.parseInt(fields[11] ?? '', 10)\n const stime = Number.parseInt(fields[12] ?? '', 10)\n const rssPages = Number.parseInt(fields[21] ?? '', 10)\n\n if (!Number.isFinite(ppid) || !Number.isFinite(utime) || !Number.isFinite(stime))\n return null\n return { pid, ppid, rssKb: Number.isFinite(rssPages) ? rssPages * 4 : 0, cpuSeconds: utime + stime }\n}\n\nasync function readLinux(): Promise<ProcRow[]> {\n const rows: ProcRow[] = []\n let names: string[] = []\n try {\n names = fs.readdirSync('/proc')\n }\n catch {\n return rows\n }\n\n for (const name of names) {\n if (!/^\\d+$/.test(name))\n continue\n const pid = Number.parseInt(name, 10)\n try {\n const row = parseStat(pid, fs.readFileSync(`/proc/${pid}/stat`, 'utf8'))\n if (row === null)\n continue\n // VmRSS is exact; the stat page count assumes a 4K page.\n try {\n const vmRss = /^VmRSS:\\s+(\\d+)\\s+kB/m.exec(fs.readFileSync(`/proc/${pid}/status`, 'utf8'))?.[1]\n if (vmRss !== undefined)\n row.rssKb = Number.parseInt(vmRss, 10)\n }\n catch {\n // Fall back to the page count.\n }\n rows.push(row)\n }\n catch {\n // Exited between listing and reading.\n }\n }\n\n return rows\n}\n\nasync function readPosix(): Promise<ProcRow[]> {\n const { stdout } = await execFileAsync('ps', ['-Ao', 'pid=,ppid=,rss=,%cpu='], { timeout: 5000, maxBuffer: 16 * 1024 * 1024 })\n return parsePsOutput(stdout)\n}\n\nasync function readWindows(): Promise<ProcRow[]> {\n const script = 'Get-CimInstance Win32_Process | Select-Object ProcessId,ParentProcessId,WorkingSetSize,KernelModeTime,UserModeTime | ConvertTo-Csv -NoTypeInformation'\n try {\n const { stdout } = await execFileAsync('powershell.exe', ['-NoProfile', '-NonInteractive', '-Command', script], {\n timeout: 8000,\n maxBuffer: 16 * 1024 * 1024,\n })\n return parseWindowsCsv(stdout)\n }\n catch {\n try {\n const { stdout } = await execFileAsync('wmic', [\n 'process',\n 'get',\n 'ProcessId,ParentProcessId,WorkingSetSize,KernelModeTime,UserModeTime',\n '/format:csv',\n ], { timeout: 8000, maxBuffer: 16 * 1024 * 1024 })\n return parseWindowsCsv(stdout)\n }\n catch {\n // Neither tool is available; resource sampling degrades to \"unknown\".\n return []\n }\n }\n}\n\nasync function readProcesses(): Promise<ProcRow[]> {\n if (process.platform === 'linux')\n return readLinux()\n if (process.platform === 'win32')\n return readWindows()\n return readPosix()\n}\n\nfunction collectTree(rootPid: number, children: Map<number, number[]>): number[] {\n const pids: number[] = []\n const stack = [rootPid]\n const seen = new Set<number>()\n\n while (stack.length > 0) {\n const pid = stack.pop()!\n if (seen.has(pid))\n continue\n seen.add(pid)\n pids.push(pid)\n for (const child of children.get(pid) ?? []) stack.push(child)\n }\n\n return pids\n}\n\n/**\n * CPU time a tree used over one interval, from per-pid cumulative counters.\n *\n * Pure, and separated from the scan because this is where both CPU bugs lived — and a scan of the\n * live process table cannot pin arithmetic that depends on a child appearing or vanishing between\n * two reads.\n *\n * `previous` is the **whole process table** of the prior scan, not just this tree: that is what\n * lets a process which joins the tree later be charged only its interval, and what the caller\n * guarantees.\n *\n * Three rules make the answer a real interval:\n *\n * - A pid in both maps contributes the difference. `next >= previous` is required: a recycled pid\n * reports less than the process that used to hold it, and that is not a delta.\n * - A pid only in `next` was **born inside the window**, so its whole counter accrued in it.\n * - A pid only in `previous` **exited inside the window**; its time is already accounted for by the\n * samples where it was alive, and it contributes nothing. The old code summed the tree on both\n * sides, so an exit made the total *drop*, the delta went negative and the reading was discarded\n * — the gap. Summing only pids present in `next` is what removes it.\n *\n * `null` when the map has nothing usable, so a caller reports \"unknown\" instead of `0`.\n */\nexport function treeCpuUsedSeconds(\n previous: Map<number, number>,\n next: Map<number, number>,\n treePids: number[],\n): number | null {\n let used = 0\n let sawAny = false\n for (const pid of treePids) {\n const current = next.get(pid)\n if (current === undefined)\n continue\n const before = previous.get(pid)\n if (before === undefined) {\n used += current\n sawAny = true\n continue\n }\n if (current >= before) {\n used += current - before\n sawAny = true\n }\n }\n return sawAny ? used : null\n}\n\n/**\n * The same walk, keeping *which root* each pid belongs to.\n *\n * A refusal has to name the server to go and stop, and a pid on its own is not that: the panel\n * supervised 14 entries and told the operator \"held by pid 135113, which this panel supervises —\n * stop that server instead\", with no way to tell which of the 14 it meant. The tree loses that\n * fact, so the attribution is collected here, where the walk already happens, rather than by a\n * second scan.\n *\n * Ownership has to mean the *tree*: a persistent entry runs under a nanny, and a wrapper entry\n * spawns the real server one generation down. Both keep the pid the panel recorded, but the process\n * holding the port is a descendant of it — and a descendant classified as a stranger is one\n * `kill`/`free-port` away from stopping a server this panel is responsible for.\n *\n * A backend that cannot run answers with the roots alone, which is the old, narrower behaviour\n * rather than a wrong one.\n *\n * When two roots are nested, the ancestor keeps the pid: it is the older claim and still true.\n */\nexport async function processTreeOwners(roots: number[]): Promise<Map<number, number>> {\n const owners = new Map<number, number>()\n for (const root of roots) {\n if (!owners.has(root))\n owners.set(root, root)\n }\n if (roots.length === 0)\n return owners\n\n try {\n const rows = await readProcesses()\n const children = new Map<number, number[]>()\n for (const row of rows) {\n const siblings = children.get(row.ppid) ?? []\n siblings.push(row.pid)\n children.set(row.ppid, siblings)\n }\n for (const root of roots) {\n for (const pid of collectTree(root, children)) {\n if (!owners.has(pid))\n owners.set(pid, root)\n }\n }\n }\n catch {\n // Sampling already treats an unreadable table as \"nothing to say\".\n }\n\n return owners\n}\n\n/**\n * Samples CPU and RSS for a process *and its descendants*.\n *\n * Descendants matter: a wrapper that spawns the real server detached owns the\n * tree, and only the tree's RSS means anything.\n *\n * Backends: `/proc` on Linux, `ps` on macOS/other POSIX, and Win32_Process via\n * PowerShell (wmic as a fallback) on Windows. When a backend cannot run, samples\n * are null rather than wrong.\n */\nexport class ProcessSampler {\n /**\n * Cumulative CPU seconds per pid, from the **whole process table** of the last scan.\n *\n * A tree is not a fixed set of processes: a wrapper spawns and reaps children continuously, so\n * \"the sum over whatever is in the tree now\" is not comparable with the previous sum. Measuring\n * that rule against a wrapper respawning a 1.5 s worker, **two samples in every three were\n * discarded**: the child's exit made the sum drop, the delta went negative, and the reading was\n * thrown away — the gaps a person sees on a live server.\n *\n * Baselining every pid the scan saw, rather than only the tree's, is what makes each delta a\n * real interval. A process that was already running has a previous counter even if it only\n * joined this tree afterwards, so it cannot be charged its whole lifetime; and a pid absent from\n * the previous scan was born inside the window, so its counter really did accrue in it.\n */\n private previousTable: { at: number, cpuSeconds: Map<number, number> } | null = null\n\n /**\n * Roots whose next sample must not be differenced, stamped with when they were forgotten.\n *\n * `forget` is called when an entry stops, exits or is restarted: the pid is gone, so the reading\n * after it must be `null` rather than a delta against a previous life. The baseline is one table\n * for the whole scan, so this is the per-root suppression. Pruned at each scan, which bounds it\n * to the restarts that happened since the last one.\n */\n private readonly forgotten = new Map<number, number>()\n\n async sample(rootPid: number, now = Date.now()): Promise<ProcessResources | null> {\n const samples = await this.sampleMany([rootPid], now)\n return samples.get(rootPid) ?? null\n }\n\n async sampleMany(rootPids: number[], now = Date.now()): Promise<Map<number, ProcessResources | null>> {\n const results = new Map<number, ProcessResources | null>()\n if (rootPids.length === 0)\n return results\n\n let rows: ProcRow[] = []\n try {\n rows = await readProcesses()\n }\n catch {\n rows = []\n }\n\n const byPid = new Map(rows.map(row => [row.pid, row]))\n const children = new Map<number, number[]>()\n for (const row of rows) {\n const siblings = children.get(row.ppid) ?? []\n siblings.push(row.pid)\n children.set(row.ppid, siblings)\n }\n\n // One baseline for the scan, shared by every root: they were all read at the same instant.\n const before = this.previousTable\n const elapsedSeconds = before === null ? 0 : (now - before.at) / 1000\n const ticks = process.platform === 'linux' ? await getClockTicks() : 1\n // Stored in *seconds*, the unit the comparison uses. Keeping raw jiffies here made every\n // Linux delta compare `seconds` against `jiffies`, so each one looked negative and was skipped.\n const tableCpuSeconds = new Map<number, number>()\n for (const row of rows) {\n if (row.cpuSeconds !== undefined)\n tableCpuSeconds.set(row.pid, row.cpuSeconds / ticks)\n }\n\n for (const rootPid of rootPids) {\n if (!byPid.has(rootPid)) {\n results.set(rootPid, null)\n continue\n }\n\n // A root forgotten since the last scan has no baseline to be measured against: its next\n // reading is the first of a new life, so it reports \"no window yet\" and re-baselines.\n const wasForgotten = this.forgotten.delete(rootPid)\n const pids = collectTree(rootPid, children)\n let rssKb = 0\n let percentAverage: number | null = null\n // Per-pid cumulative seconds for this tree, in the unit the comparison uses. Linux reports\n // jiffies; every other backend reports seconds already.\n const treeSeconds = new Map<number, number>()\n\n for (const pid of pids) {\n const row = byPid.get(pid)\n if (!row)\n continue\n rssKb += row.rssKb\n if (row.cpuPercent !== undefined)\n percentAverage = (percentAverage ?? 0) + row.cpuPercent\n if (row.cpuSeconds !== undefined)\n treeSeconds.set(pid, row.cpuSeconds / ticks)\n }\n\n const usedSeconds = before === null\n ? null\n : treeCpuUsedSeconds(before.cpuSeconds, treeSeconds, pids)\n let cpuPercent: number | null = percentAverage\n if (cpuPercent === null && !wasForgotten && usedSeconds !== null && elapsedSeconds > 0)\n cpuPercent = (usedSeconds / elapsedSeconds) * 100\n\n results.set(rootPid, {\n cpuPercent: cpuPercent === null ? null : Math.round(cpuPercent * 10) / 10,\n rssBytes: Math.round(rssKb * 1024),\n processes: pids.length,\n sampledAt: now,\n })\n }\n\n this.previousTable = { at: now, cpuSeconds: tableCpuSeconds }\n return results\n }\n\n /**\n * Marks a root's next reading as the first of a new life.\n *\n * Called when an entry stops, exits or is restarted. Without it a recycled pid — or the very\n * next sample of the same root — would be differenced against a counter from the previous run,\n * which is not an interval. The scan-wide table cannot be cleared per root, so the suppression\n * is remembered here and consumed by that root's next sample.\n */\n forget(rootPid: number): void {\n this.forgotten.set(rootPid, Date.now())\n }\n}\n\n/**\n * Does this process carry the environment the supervisor gave the entry?\n *\n * A program that restarts itself — especially a plugin doing it — leaves behind a\n * detached process that still inherits `HHOSTED_SERVER_ID`, and that marker is what\n * tells a legitimate successor apart from a stranger squatting on the port.\n *\n * Linux reads `/proc`; macOS asks `ps -E`; Windows has no per-process environment,\n * so the answer is always \"no\" there and ownership falls back to the port policy.\n */\nexport async function processCarriesServerId(pid: number, serverId: string): Promise<boolean> {\n if (serverId.length === 0)\n return false\n const needle = `HHOSTED_SERVER_ID=${serverId}`\n\n if (process.platform === 'linux') {\n try {\n const raw = await fs.promises.readFile(`/proc/${pid}/environ`, 'utf8')\n return raw.split('\\0').includes(needle)\n }\n catch {\n return false\n }\n }\n\n if (process.platform === 'darwin') {\n try {\n const { stdout } = await execFileAsync('ps', ['-p', String(pid), '-E', '-ww', '-o', 'command='], { timeout: 3000 })\n // Values with spaces are unquoted in this output, so the marker is matched as a word.\n return new RegExp(`(?:^|\\\\s)${needle}(?:\\\\s|$)`).test(stdout)\n }\n catch {\n return false\n }\n }\n\n return false\n}\n","import { execFile } from 'node:child_process'\nimport fs from 'node:fs'\nimport path from 'node:path'\nimport process from 'node:process'\nimport { promisify } from 'node:util'\nimport { processCarriesServerId } from '#src/providers/proc'\n\nconst execFileAsync = promisify(execFile)\n\n/** What the panel actually spawned for an entry: the argv it has to recognize again. */\nexport interface SpawnInfo {\n command: string\n args: string[]\n cwd: string\n}\n\n/**\n * Splits a command line into words, undoing the quoting Windows put there. `CommandLine`\n * is the raw string from the spawn call, so `\"C:\\a b\\x.cmd\" /c` is one argv entry plus\n * two words, and a quoted argument that contains spaces has to come back as one word.\n *\n * Windows also *escapes* a quote inside an argument as `\\\"` (Node does this for any argv\n * containing a quote), so the escape is undone here — otherwise every argument with a\n * quote in it survives as a stray backslash and never matches what the panel spawned.\n */\nexport function splitCommandLine(line: string): string[] {\n const words: string[] = []\n let current = ''\n let quoted = false\n let started = false\n\n const chars = [...line.trim()]\n for (let index = 0; index < chars.length; index += 1) {\n const char = chars[index]!\n\n // A backslash run escapes only the quote that follows it; any other backslash is a\n // literal path separator. Node emits `\\\"` for an argument's own quote, and treating\n // that quote as a delimiter closed the argument early — so the rest of the line\n // (including the *next* argument) was swallowed into the same word, and an entry\n // whose argv contains a quote was not recognized as its own successor.\n if (char === '\\\\') {\n let run = 0\n while (chars[index + run] === '\\\\') run += 1\n const next = chars[index + run]\n if (next !== '\"') {\n current += '\\\\'.repeat(run)\n started = true\n index += run - 1\n continue\n }\n // 2n backslashes then a quote: n literal backslashes, and the quote is a real\n // delimiter. 2n+1: n literal backslashes and a literal quote.\n current += '\\\\'.repeat(Math.floor(run / 2))\n started = true\n if (run % 2 === 1) {\n current += '\"'\n index += run\n continue\n }\n quoted = !quoted\n index += run\n continue\n }\n\n if (char === '\"') {\n quoted = !quoted\n // A quote is both a delimiter and proof that a (possibly empty) word exists.\n started = true\n continue\n }\n if (!quoted && /\\s/.test(char)) {\n if (started)\n words.push(current)\n current = ''\n started = false\n continue\n }\n current += char\n started = true\n }\n\n if (started)\n words.push(current)\n return words\n}\n\nfunction comparable(target: string): string {\n // Quotes around a whole word are stripped; whitespace never is. `SpawnInfo.args` is the\n // argv `spawn` was handed, where a whitespace argument is still an argument, so trimming\n // here would make it compare equal to a missing one. A `\\\"` is Windows' escape for a\n // quote inside an argument, and the word it sits in is compared against the raw argv.\n const value = target.replace(/^\"(.*)\"$/, '$1').replace(/\\\\(?=\")/g, '')\n return process.platform === 'win32' ? value.toLowerCase() : value\n}\n\n/**\n * Literal comparison for an argument: the same text, modulo the case folding Windows needs\n * and the quoting a command line shuffles around.\n *\n * Deliberately *not* `sameWord`: folding an argument to its basename would let this\n * entry's `/srv/web/build/server.js` equal a stranger's `/tmp/evil/build/server.js`, and a\n * match here is what `reclaim` kills. Nor is it a plain string equality: reading an argv\n * back out of a Windows `CommandLine` cannot preserve quotes exactly — the OS escapes an\n * argument's own quote as `\\\"` and strips the structural ones — so quotes and backslashes\n * are dropped from both sides. That leaves the arguments' actual text, which is what the\n * match is about.\n */\nfunction sameArg(a: string, b: string): boolean {\n const normalize = (value: string): string => comparable(value).replace(/[\"\\\\]/g, '')\n return normalize(a) === normalize(b)\n}\n\n/** Whether a value names a file with no directory part, under either platform's separator. */\nfunction isBare(value: string): boolean {\n return !value.includes('/') && !value.includes('\\\\')\n}\n\n/**\n * The same file spelled differently compares equal — but only while one of the two spellings is a\n * bare name, which is the case the fallback exists for: the config says `node` and the process table\n * reports `/usr/bin/node`, or the reverse on Windows.\n *\n * When **both** spellings name a directory, they are two different files. Comparing basenames\n * unconditionally made `/tmp/evil/server.js` match `/srv/web/server.js`, and a false match here is\n * not cosmetic: the panel would treat a process it never spawned as its own entry, so `follow` adopts\n * a stranger and `reclaim`/`kill` may remove one.\n */\nfunction sameWord(a: string, b: string): boolean {\n const left = comparable(a)\n const right = comparable(b)\n if (left === right)\n return true\n if (!isBare(left) && !isBare(right))\n return false\n return path.basename(left) === path.basename(right)\n || (path.extname(b) === '' && path.basename(left, path.extname(left)) === right)\n || (path.extname(a) === '' && path.basename(right, path.extname(right)) === left)\n}\n\n/**\n * True when the argv a process is running is the entry's own: the image must match where\n * `spawn` would have looked it up — the image Path, or the first word of the command line\n * — and the words after it must open with the entry's args, compared literally. So\n * `spawn --port 4000` also covers `spawn -p 4000 --extra`, which is what a self-restarting\n * wrapper does, while `/tmp/evil/server.js` never covers `/srv/web/server.js` — two paths that name\n * a directory are different files, and the basename fallback applies only while one spelling is bare\n * (see `sameWord`).\n *\n * `words` must already be the process's own argv. A command-line *string* is only correct\n * on Windows, where the OS hands one out; `/proc/<pid>/cmdline` quotes are literal bytes\n * of an argument, so re-joining that argv into one string corrupts it.\n */\nexport function matchesSpawn(info: { words: string[], imagePath?: string | null }, spawn: SpawnInfo): boolean {\n const { words } = info\n const first = words[0] ?? ''\n\n // The image may be the first word, or absent from the command line entirely — a shim or\n // an interpreter reports its own image while the argv still carries what we passed.\n const imageMatches = sameWord(first, spawn.command)\n || (info.imagePath != null && info.imagePath !== '' && sameWord(info.imagePath, spawn.command))\n if (!imageMatches)\n return false\n\n // `>` rather than `>=`: a process has to have *more* words than we have args, so an\n // argument can never be satisfied by a word that is not there.\n const offset = sameWord(first, spawn.command) ? 1 : 0\n if (words.length < spawn.args.length + offset)\n return false\n\n return spawn.args.every((arg, index) => sameArg(words[index + offset]!, arg))\n}\n\n/** The argv of a pid on the platforms whose process table can answer it; null otherwise. */\nexport async function processArgv(pid: number): Promise<string[] | null> {\n if (process.platform === 'win32')\n return null\n\n if (process.platform === 'linux') {\n try {\n const raw = await fs.promises.readFile(`/proc/${pid}/cmdline`)\n // Every word is NUL-terminated, so the file ends with an empty element to drop — and only\n // that one. An argument may itself be empty, which is two NULs, and filtering every empty\n // string pulled the words after it into its place: the entry's own successor stopped\n // matching its argv, and a stranger's did.\n const words = raw.toString('utf8').split('\\0')\n if (words.at(-1) === '')\n words.pop()\n return words.length > 0 ? words : null\n }\n catch {\n return null\n }\n }\n\n try {\n const { stdout } = await execFileAsync('ps', ['-p', String(pid), '-ww', '-o', 'command='], { timeout: 3000 })\n // macOS receives one line and has to split it back into words here. `ps` joins argv\n // with spaces and quotes none of them, so an argument that itself contains a space\n // cannot be told from two arguments — that entry then fails to match and blocks,\n // which is the safe direction to be wrong in.\n const words = splitCommandLine(stdout.trim())\n return words.length > 0 ? words : null\n }\n catch {\n return null\n }\n}\n\nconst windowsFilter = /^\\d+$/\n\n/**\n * The first two rows of `ConvertTo-Csv` output: the header and the first record. PowerShell\n * quotes and doubles its way around CSV, so `a,\"b\"\"c\"` is three fields with the second\n * reading `b\"c`.\n */\nfunction parseCsvRows(output: string): [string[] | null, string[] | null] {\n const rows: string[][] = []\n let row: string[] = []\n let field = ''\n let quoted = false\n\n for (let index = 0; index < output.length; index++) {\n const char = output[index]!\n if (quoted) {\n if (char !== '\"') {\n field += char\n continue\n }\n if (output[index + 1] === '\"') {\n field += '\"'\n index++\n continue\n }\n quoted = false\n continue\n }\n\n if (char === '\"') {\n quoted = true\n continue\n }\n if (char === ',') {\n row.push(field)\n field = ''\n continue\n }\n if (char === '\\n') {\n row.push(field.replace(/\\r$/, ''))\n rows.push(row)\n row = []\n field = ''\n continue\n }\n field += char\n }\n\n if (field.length > 0 || row.length > 0)\n rows.push([...row, field.replace(/\\r$/, '')])\n\n return [rows[0] ?? null, rows[1] ?? null]\n}\n\n/**\n * `Win32_Process` for one pid, or null when it cannot be read.\n *\n * The whole round trip — launching PowerShell, loading the CIM provider, serializing —\n * costs seconds on a cold runner, so the timeout is generous and the result is converted\n * to CSV rather than JSON: CSV survives a value that contains a quote or a newline, which\n * an argv legitimately can.\n */\nexport async function windowsProcessInfo(pid: number): Promise<{ commandLine: string, imagePath: string | null } | null> {\n if (!windowsFilter.test(String(pid)))\n return null\n\n try {\n const script = `Get-CimInstance Win32_Process -Filter \"ProcessId=${pid}\" | Select-Object CommandLine,ExecutablePath | ConvertTo-Csv -NoTypeInformation`\n const { stdout } = await execFileAsync('powershell', ['-NoProfile', '-NonInteractive', '-Command', script], { timeout: 20000, windowsHide: true })\n const [headers, values] = parseCsvRows(stdout)\n if (!headers || !values)\n return null\n\n const commandLineIndex = headers.indexOf('CommandLine')\n const imageIndex = headers.indexOf('ExecutablePath')\n const commandLine = commandLineIndex >= 0 ? values[commandLineIndex] : undefined\n if (commandLine === undefined || commandLine.length === 0)\n return null\n\n const imagePath = imageIndex >= 0 ? values[imageIndex] : undefined\n return { commandLine, imagePath: imagePath && imagePath.length > 0 ? imagePath : null }\n }\n catch {\n return null\n }\n}\n\n/**\n * Which of these pids look like this entry's own detached successor. The environment\n * marker is authoritative where the platform can read it; otherwise the answer rests on\n * the entry's own argv, which is the only signal a detached successor is obliged to keep\n * — and the only one Windows exposes at all.\n */\nexport async function identifyHolders(serverId: string, spawn: SpawnInfo, pids: number[]): Promise<number[]> {\n const found: number[] = []\n\n for (const pid of pids) {\n if (await processCarriesServerId(pid, serverId)) {\n found.push(pid)\n continue\n }\n\n // An empty argv proves nothing, so a marker is the only way in without it.\n if (spawn.args.length === 0)\n continue\n\n if (process.platform === 'win32') {\n const info = await windowsProcessInfo(pid)\n if (info && matchesSpawn({ words: splitCommandLine(info.commandLine), imagePath: info.imagePath }, spawn))\n found.push(pid)\n continue\n }\n\n const argv = await processArgv(pid)\n if (argv !== null && matchesSpawn({ words: argv }, spawn))\n found.push(pid)\n }\n\n return found\n}\n","import type { ChildProcess } from 'node:child_process'\nimport { execFile, spawn } from 'node:child_process'\nimport fs from 'node:fs'\nimport path from 'node:path'\nimport process from 'node:process'\nimport { promisify } from 'node:util'\nimport { projectDir } from '#src/helpers/paths'\nimport { isProcessAlive } from '#src/providers/port'\n\nconst execFileAsync = promisify(execFile)\n\nexport interface SpawnSpec {\n command: string\n args: string[]\n cwd: string\n env: Record<string, string>\n}\n\n/**\n * The files `npm`/`pnpm` write into `node_modules/.bin` on Windows, in the order Node can\n * actually start them.\n *\n * All of `foo`, `foo.cmd` and `foo.ps1` exist there — the extension-less one is a `#!/bin/sh`\n * script, which is the POSIX shim, not a program Windows can spawn. Preferring it (the order\n * `[command, ...shims]` gave) resolved to a file whose first line is `#!/bin/sh`: Node has no\n * shell to hand it to, so the entry started nothing. `spawn` reports that as `ENOENT` and the\n * panel used to blame the missing program.\n *\n * `.exe` leads because it needs no shell; `.cmd`/`.bat` follow and go through `needsShell()`.\n * `.ps1` is last: it is a PowerShell script, which `cmd.exe` does not run on its own.\n */\nconst WINDOWS_SHIM_EXTENSIONS = ['.exe', '.cmd', '.bat', '.ps1']\n\n/**\n * Resolves a bare command through the entry's own directory and the project's\n * `node_modules/.bin` first, so a server installed as a project dependency is\n * found even when the launcher's PATH has no pnpm-injected bin dir.\n */\nexport function resolveCommand(command: string, ...searchDirs: string[]): string {\n if (command.includes('/') || command.includes('\\\\'))\n return command\n\n const candidates = process.platform === 'win32' && path.extname(command) === ''\n ? WINDOWS_SHIM_EXTENSIONS.map(extension => `${command}${extension}`)\n : [command]\n\n for (const dir of searchDirs) {\n for (const candidate of candidates) {\n const local = path.join(dir, 'node_modules', '.bin', candidate)\n if (fs.existsSync(local))\n return local\n }\n }\n\n return command\n}\n\n/**\n * Does this program exist where `spawn` would look it up, and where?\n *\n * Used only to tell a **pasted command line** apart from a missing program: `spawn` answers both\n * with the same `ENOENT`, and the two have opposite fixes. `null` means it was not found anywhere\n * this process would search.\n *\n * A bare name is searched on `PATH` (plus `.exe`/`.cmd`/`.bat` on Windows, because that is what\n * the OS appends); anything with a separator is a path and is stat'd as written.\n */\nexport function findProgram(command: string, cwd: string = projectDir): string | null {\n const isPath = command.includes('/') || command.includes('\\\\')\n if (isPath) {\n const resolved = path.resolve(cwd, command)\n return isExecutable(resolved) ? resolved : null\n }\n\n const extensions = process.platform === 'win32' ? ['', ...WINDOWS_SHIM_EXTENSIONS] : ['']\n const dirs = (process.env.PATH ?? '').split(path.delimiter).filter(dir => dir.length > 0)\n for (const dir of dirs) {\n for (const extension of extensions) {\n const candidate = path.join(dir, `${command}${extension}`)\n if (isExecutable(candidate))\n return candidate\n }\n }\n return null\n}\n\n/** A file this user may run. A directory named like a program is not one. */\nfunction isExecutable(file: string): boolean {\n try {\n if (!fs.statSync(file).isFile())\n return false\n if (process.platform === 'win32')\n return true\n fs.accessSync(file, fs.constants.X_OK)\n return true\n }\n catch {\n return false\n }\n}\n\n/** Relative entry paths belong to the project that launched the panel. */\nexport function resolveCwd(cwd: string, base: string = projectDir): string {\n return path.resolve(base, cwd)\n}\n\n/** Node cannot spawn a Windows `.cmd`/`.bat` shim without a shell (EINVAL). */\nexport function needsShell(command: string): boolean {\n return process.platform === 'win32' && /\\.(?:cmd|bat)$/i.test(command)\n}\n\nexport interface SpawnOptions {\n /**\n * A supervised child gets its own process group, so one `kill(-pid)` stops the tree.\n * A child spawned by a nanny does not: it shares the nanny's group, which is the\n * group the panel signals — so the same one-signal semantics still reach both.\n */\n detached?: boolean\n}\n\nexport function spawnManaged(spec: SpawnSpec, options: SpawnOptions = {}): ChildProcess {\n return spawn(spec.command, spec.args, {\n cwd: spec.cwd,\n env: { ...process.env, ...spec.env },\n // Own process group: a stop can signal the whole tree with one kill(-pid).\n detached: options.detached ?? true,\n stdio: ['ignore', 'pipe', 'pipe'],\n shell: needsShell(spec.command),\n windowsHide: true,\n })\n}\n\nexport interface TerminateOptions {\n signal: NodeJS.Signals\n killGroup: boolean\n graceMs: number\n /** The SIGKILL escalation reaches the group even when the graceful signal went to the pid alone. */\n escalateGroup?: boolean\n}\n\n/** SIGTERM (default) to the child, escalating to SIGKILL after the grace period. */\nexport async function terminate(child: ChildProcess, options: TerminateOptions): Promise<'exited' | 'force-killed'> {\n if (child.exitCode !== null || child.signalCode !== null)\n return 'exited'\n\n const exited = waitForExit(child, options.graceMs)\n signalChild(child, options.signal, options.killGroup)\n\n if (await exited)\n return 'exited'\n\n signalChild(child, 'SIGKILL', options.escalateGroup ?? options.killGroup)\n await waitForExit(child, 2000)\n return 'force-killed'\n}\n\n/**\n * Windows has no process groups and no SIGTERM: `taskkill /T` walks the tree and\n * `/F` is the only reliable way to stop a console process.\n */\nexport async function killTreeWindows(pid: number): Promise<void> {\n try {\n await execFileAsync('taskkill', ['/pid', String(pid), '/T', '/F'], { timeout: 5000 })\n }\n catch {\n // Already gone, or taskkill is unavailable.\n }\n}\n\nfunction signalChild(child: ChildProcess, signal: NodeJS.Signals, killGroup: boolean): void {\n const pid = child.pid\n if (pid === undefined)\n return\n signalPid(pid, signal, killGroup)\n}\n\nfunction signalPid(pid: number, signal: NodeJS.Signals, killGroup: boolean): void {\n if (process.platform === 'win32') {\n if (killGroup) {\n void killTreeWindows(pid)\n }\n else {\n try {\n process.kill(pid, signal)\n }\n catch {\n // already exited\n }\n }\n return\n }\n\n if (killGroup) {\n try {\n process.kill(-pid, signal)\n return\n }\n catch {\n // group already gone, fall through to the single pid\n }\n }\n\n try {\n process.kill(pid, signal)\n }\n catch {\n // already exited\n }\n}\n\n/**\n * The same shutdown a supervised child gets, for a process we adopted instead of\n * spawned: a detached successor is not our child, so it is signalled by pid (and\n * by process group when asked) and its exit is polled rather than awaited.\n *\n * Liveness comes from `isProcessAlive`, never a local signal-0 copy: a second definition returned\n * `false` for `EPERM`, so a process that was there but not ours to signal read as \"exited\" and\n * `'force-killed'` was returned for one still running. One predicate, one answer.\n */\nexport async function terminatePid(pid: number, options: TerminateOptions): Promise<'exited' | 'force-killed'> {\n if (!isProcessAlive(pid))\n return 'exited'\n\n signalPid(pid, options.signal, options.killGroup)\n\n const deadline = Date.now() + Math.max(0, options.graceMs)\n while (Date.now() < deadline && isProcessAlive(pid))\n await delay(50)\n if (!isProcessAlive(pid))\n return 'exited'\n\n signalPid(pid, 'SIGKILL', options.escalateGroup ?? options.killGroup)\n const hardDeadline = Date.now() + 2000\n while (Date.now() < hardDeadline && isProcessAlive(pid))\n await delay(50)\n return 'force-killed'\n}\n\nfunction delay(ms: number): Promise<void> {\n return new Promise(resolve => setTimeout(resolve, ms))\n}\n\nfunction waitForExit(child: ChildProcess, timeoutMs: number): Promise<boolean> {\n if (child.exitCode !== null || child.signalCode !== null)\n return Promise.resolve(true)\n if (timeoutMs <= 0)\n return Promise.resolve(false)\n\n return new Promise((resolve) => {\n const timer = setTimeout(() => {\n child.removeListener('exit', onExit)\n resolve(false)\n }, timeoutMs)\n\n function onExit(): void {\n clearTimeout(timer)\n resolve(true)\n }\n\n child.once('exit', onExit)\n })\n}\n","import type { ProcessBirth } from '#src/providers/port'\nimport type { TerminateOptions } from '#src/providers/process'\nimport type { NannyExit, NannySpec, NannyState, StopConfig } from '#src/shared/contracts'\nimport fs from 'node:fs'\nimport os from 'node:os'\nimport path from 'node:path'\nimport process from 'node:process'\nimport { type } from 'arktype'\nimport { writeFileAtomic } from '#src/helpers/atomic'\nimport { NANNY_COMMAND } from '#src/helpers/runtime'\nimport { processArgv } from '#src/providers/identity'\nimport { processLiveness } from '#src/providers/port'\nimport { processCarriesServerId } from '#src/providers/proc'\nimport { findProgram } from '#src/providers/process'\nimport { nannySpecSchema, nannyStateSchema } from '#src/shared/contracts'\n\n/**\n * A persistent entry is not run by the panel: the panel spawns a *nanny* that owns\n * the child's pipes, writes its output to the entry's JSONL log and keeps a small\n * state file. That is what lets the entry survive a panel stop, restart or kill\n * without losing its log or its identity — the pipes belong to a process that stays.\n *\n * These are the files and the liveness rules behind that arrangement; the nanny\n * itself is `src/services/nanny.ts`.\n */\n\n/** The spec carries expanded `env`, so it lives only from spawn to read. */\nconst SPEC_MODE = 0o600\n\n/** Suffix of a spawn spec, so a sweep and the state reader can tell them apart. */\nexport const SPEC_SUFFIX = '.spec.json'\n\n/**\n * The signals a nanny traps and forwards to its child. Any other signal ends the nanny outright,\n * so nothing was forwarded — see `stopPersistentEntries`, which then signals the child directly.\n */\nexport const NANNY_TRAPPED_SIGNALS: ReadonlySet<NodeJS.Signals> = new Set(['SIGTERM', 'SIGINT'])\n\n/**\n * How a nanny is stopped. A trapped signal goes to the nanny's pid alone and the nanny signals its\n * own group once (`killGroup` is honoured there): signalling the group from here as well delivered\n * the stop to the child twice. The SIGKILL escalation still covers the whole group. Windows has no\n * signal a nanny can trap, so its stop is unchanged.\n */\nexport function nannyStopOptions(stop: StopConfig, platform: NodeJS.Platform = process.platform): TerminateOptions {\n if (platform === 'win32' || !stop.killGroup || !NANNY_TRAPPED_SIGNALS.has(stop.signal))\n return stop\n return { ...stop, killGroup: false, escalateGroup: true }\n}\n\n/** How often a nanny rewrites its state file. */\nexport const NANNY_HEARTBEAT_MS = 5000\n\n/** A heartbeat older than this is not evidence of anything. */\nexport const HEARTBEAT_STALE_MS = 30_000\n\n/**\n * The state directory is passed in rather than read from a global: the panel injects\n * `$HHOSTED_HOME/.state`, and a test injects its own temp directory.\n */\nexport function nannySpecPath(dir: string, id: string): string {\n return path.join(dir, `${id}${SPEC_SUFFIX}`)\n}\n\nexport function nannyStatePath(dir: string, id: string): string {\n return path.join(dir, `${id}.json`)\n}\n\n/** The file a nanny writes and the panel tails; one derivation, so they cannot drift. */\nexport function nannyLogFile(logDir: string, id: string): string {\n return path.join(logDir, `${id}.log`)\n}\n\n/**\n * How to run this CLI again as a nanny. The panel was itself launched through this\n * entry point (`up` re-spawns itself with it), so `process.argv[1]` is the one path\n * that works under tsx, from `dist/cli.js` and through the published bin alike.\n */\nexport function nannyEntryPoint(): string {\n return process.argv[1] ?? ''\n}\n\n/** Written before the spawn, consumed by the nanny, never left behind. */\nexport function writeNannySpec(file: string, spec: NannySpec): void {\n writeFileAtomic(file, JSON.stringify(spec), { mode: SPEC_MODE })\n}\n\nexport function clearNannySpec(file: string): void {\n fs.rmSync(file, { force: true })\n}\n\n/**\n * Reads and unlinks in one step: the spec holds expanded secrets, and a spec left\n * behind — a nanny that died before reading it, a panel killed mid-spawn — is a\n * secret file with no owner. It is consumed even when it cannot be parsed.\n */\nexport function takeNannySpec(file: string): NannySpec {\n const raw = fs.readFileSync(file, 'utf8')\n fs.rmSync(file, { force: true })\n\n const parsed = nannySpecSchema(JSON.parse(raw))\n if (parsed instanceof type.errors)\n throw new Error(`invalid nanny spec: ${parsed.summary}`)\n return parsed\n}\n\n/**\n * Nothing can be waiting on a spec before this panel has spawned a nanny, so every\n * one still on disk at boot belongs to a nanny that never read it.\n */\nexport function sweepNannySpecs(dir: string): number {\n let swept = 0\n for (const name of readSpecNames(dir)) {\n fs.rmSync(path.join(dir, name), { force: true })\n swept += 1\n }\n return swept\n}\n\nfunction readSpecNames(dir: string): string[] {\n try {\n return fs.readdirSync(dir).filter(name => name.endsWith(SPEC_SUFFIX))\n }\n catch {\n return []\n }\n}\n\n/** A stale or foreign file reads as \"no state\", never as a throw. */\nexport function readNannyState(file: string): NannyState | null {\n try {\n const parsed = nannyStateSchema(JSON.parse(fs.readFileSync(file, 'utf8')))\n return parsed instanceof type.errors ? null : parsed\n }\n catch {\n return null\n }\n}\n\nexport function writeNannyState(file: string, state: NannyState): void {\n writeFileAtomic(file, JSON.stringify(state))\n}\n\nexport function clearNannyState(file: string): void {\n fs.rmSync(file, { force: true })\n}\n\n/**\n * The same wording the supervisor uses for a child's exit, so history reads alike — plus a hint\n * when the code has a conventional meaning, because `code 137` alone tells an operator nothing and\n * that is the one they most want explained (a container limit or the kernel OOM killer).\n *\n * The hint is worded as a possibility, never a claim: 128+N is a shell convention, and a program\n * is free to exit 137 for its own reasons — a JVM reports OOM that way itself. 126 and 127 are\n * firmer, since the shell sets those when it cannot run the command at all.\n */\nexport function describeNannyExit(exit: NannyExit): string {\n if (exit.signal !== null)\n return `signal ${exit.signal}`\n const hint = exitCodeHint(exit.code)\n return hint === null ? `code ${exit.code}` : `code ${exit.code} (${hint})`\n}\n\n/** What a conventional exit code usually means, or null when there is nothing to add. */\nfunction exitCodeHint(code: number | null): string | null {\n if (code === null || code === 0)\n return null\n if (code === 126)\n return 'the command is not executable'\n if (code === 127)\n return 'the command was not found'\n if (code <= 128 || code > 128 + 64)\n return null\n const signal = signalName(code - 128)\n if (signal === null)\n return null\n return code === 137\n ? `${signal} — which the kernel sends when memory runs out`\n : `${signal}, if the shell reported the kill`\n}\n\n/**\n * A spawn failure in words a person can act on.\n *\n * Node reports a missing program as `spawn <cmd> ENOENT` — the same errno as a missing *file*, and\n * the same wording whichever of the two it is. A user who pasted `java -jar server.jar` into\n * `command` saw exactly that and had nothing to go on: the message names the whole line, so it\n * reads as \"the program is missing\" even when the program is fine and only the argument is wrong.\n *\n * `command` is the configured program, so the two cases can be told apart: if a bare name has no\n * path separator, the shell would have searched `PATH` and this one did not.\n *\n * A **missing working directory** is the third cause of the same errno, and it is the one a\n * deployment hits: `spawn` resolves `cwd` before it looks for the program, so an entry whose `cwd`\n * does not exist *under this launch directory* fails exactly like an uninstalled program. That read\n * sent a person to `which node` while `node` was fine and only the relative path was wrong (a unit\n * file with no `WorkingDirectory=`, a container started from `/`). `cwd` is therefore checked first:\n * if it is not an existing directory, nothing else about the spawn could have worked.\n */\nexport function describeSpawnError(error: NodeJS.ErrnoException, command: string, cwd?: string): string {\n const missingDir = cwd === undefined ? null : describeMissingDir(cwd)\n if (missingDir !== null && (error.code === 'ENOENT' || error.code === 'ENOTDIR'))\n return missingDir\n\n if (error.code === 'ENOENT') {\n const pasted = describePastedCommandLine(command, cwd)\n if (pasted !== null)\n return pasted\n return command.includes('/') || command.includes('\\\\')\n // A path was given, so the path is what is missing — the file, or a directory on the way.\n ? `\\`${command}\\` does not exist — check the path, and any directory on the way to it`\n // A bare name: spawn does not search a shell's PATH aliases, and the program may simply\n // not be installed. Naming the program is the whole value here.\n : `\\`${command}\\` was not found — is it installed, and is it on PATH for the user running the panel?`\n }\n if (error.code === 'EACCES')\n return `\\`${command}\\` exists but is not executable — ${notExecutableHint()}`\n return `${error.message} (while running \\`${command}\\`)`\n}\n\n/**\n * What to do about `EACCES`, in the shell of the platform the panel is running on.\n *\n * `chmod +x` is not a Windows program: `cmd.exe` answers `'chmod' is not recognized…`, so the one\n * line that exists to offer a way out sent the reader to a second dead end. The platform is the\n * only signal available, exactly as it is for `shellQuote` (`helpers/shell.ts`); one function so a\n * second `EACCES` message cannot be written with the POSIX half alone.\n */\nfunction notExecutableHint(): string {\n return process.platform === 'win32'\n // Windows has no executable bit: `EACCES` there means an ACL or a blocked file, not a mode.\n ? 'check its permissions (Windows has no executable bit — look at the file\\'s Security tab for a denied account)'\n : 'check its permissions (chmod +x)'\n}\n\n/**\n * The first mistake the Add-server form invites: a whole command line typed into `Command`.\n *\n * `Command` is spawned **without a shell** and `Arguments` is a separate field, so `node server.js`\n * names a program called `node server.js`. The fix is to split it — and the sentence has to say so,\n * because the alternative reading (\"node is not installed\") is what sends someone to `which node`\n * while `node` is right there.\n *\n * Only claimed when the evidence is unambiguous: the field has whitespace, and the program it opens\n * with **does** resolve. So a genuinely missing program keeps the message about PATH, and a path with\n * a space in it is never split (it has no bare first word that resolves). See `findProgram`.\n */\nfunction describePastedCommandLine(command: string, cwd?: string): string | null {\n const words = command.trim().split(/\\s+/)\n if (words.length < 2)\n return null\n const program = words[0]!\n if (findProgram(program, cwd) === null)\n return null\n return `\\`${command}\\` is a whole command line, but \\`Command\\` is spawned without a shell — this release looks for a program named \\`${command}\\`. Put \\`${program}\\` in \\`Command\\` and the rest in \\`Arguments\\`, one argument per line`\n}\n\n/** Why a working directory cannot be used, in one sentence, or null when it can. */\nfunction describeMissingDir(cwd: string): string | null {\n try {\n if (fs.statSync(cwd).isDirectory())\n return null\n return `the working directory \\`${cwd}\\` is not a directory — a relative \\`cwd\\` resolves against the directory the panel was started from`\n }\n catch (error) {\n if ((error as NodeJS.ErrnoException).code === 'ENOENT') {\n return `the working directory \\`${cwd}\\` does not exist — a relative \\`cwd\\` resolves against the directory the panel was started from, so a service started from elsewhere (systemd, docker, a login shell) looks in a different place`\n }\n return `the working directory \\`${cwd}\\` cannot be read — check its permissions`\n }\n}\n\n/** `SIGKILL` for 9, or null when the number names nothing. */\nfunction signalName(number: number): string | null {\n for (const [name, value] of Object.entries(os.constants.signals)) {\n if (value === number)\n return name\n }\n return null\n}\n\n/**\n * Is the nanny this state describes still ours? A live pid proves nothing on its\n * own — pids are reused, and the heartbeat is written *into the file*, not by the\n * process the file names, so a recycled pid with a recent write reads as running.\n * `startedAt` settles that first (`processLiveness`), exactly as `run.json` uses it:\n * the nanny stamps its record during its own boot, so its process is always born\n * before the stamp. The environment marker (Linux, macOS) or the argv we spawned it\n * with answers the rest, Windows included.\n */\nexport async function nannyIsAlive(state: NannyState, id: string, options: { readBirth?: (pid: number) => Promise<ProcessBirth | null> } = {}): Promise<boolean> {\n if (state.nannyPid <= 0)\n return false\n // `'recycled'` is decisive and needs no threshold: a pid born after the record cannot be the\n // nanny that wrote it. `'gone'` is the plain dead pid. `'live'` and `'unknown'` both carry on —\n // a platform that cannot report a birth time must not have its running nanny dismissed.\n const liveness = await processLiveness(state.nannyPid, state.startedAt, options)\n if (liveness === 'gone' || liveness === 'recycled')\n return false\n if (Date.now() - state.heartbeatAt <= HEARTBEAT_STALE_MS)\n return true\n if (await processCarriesServerId(state.nannyPid, id))\n return true\n\n const words = await processArgv(state.nannyPid)\n return words !== null\n && words.includes(NANNY_COMMAND)\n && words.some(word => word.endsWith(`${id}.spec.json`))\n}\n"],"mappings":";;;;;;;;;;;;;;AAMA,IAAMA,kBAAgB,UAAU,QAAQ;AAYxC,SAAgB,cAAc,MAAyB;CACrD,MAAM,OAAkB,CAAC;CACzB,KAAK,MAAM,QAAQ,KAAK,MAAM,IAAI,GAAG;EACnC,MAAM,QAAQ,KAAK,KAAK,CAAC,CAAC,MAAM,KAAK;EACrC,IAAI,MAAM,SAAS,GACjB;EACF,MAAM,CAAC,KAAK,MAAM,KAAK,OAAO,MAAM,KAAI,UAAS,OAAO,WAAW,KAAK,CAAC;EACzE,IAAI,QAAQ,KAAA,KAAa,SAAS,KAAA,KAAa,QAAQ,KAAA,KAAa,CAAC,OAAO,SAAS,GAAG,GACtF;EACF,KAAK,KAAK;GAAE;GAAK;GAAM,OAAO;GAAK,YAAY,OAAO,SAAS,GAAG,IAAI,MAAM,KAAA;EAAU,CAAC;CACzF;CACA,OAAO;AACT;;AAGA,SAAgB,gBAAgB,MAAyB;CACvD,MAAM,OAAkB,CAAC;CACzB,MAAM,QAAQ,KAAK,MAAM,OAAO,CAAC,CAAC,QAAO,SAAQ,KAAK,KAAK,CAAC,CAAC,SAAS,CAAC;CACvE,MAAM,SAAS,MAAM,MAAM;CAC3B,IAAI,WAAW,KAAA,GACb,OAAO;CAET,MAAM,UAAU,OAAO,MAAM,GAAG,CAAC,CAAC,KAAI,UAAS,MAAM,QAAQ,MAAM,EAAE,CAAC,CAAC,KAAK,CAA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
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"nanny-sweep-Ca9kPAVi.js","names":[],"sources":["../../src/providers/nanny-sweep.ts"],"sourcesContent":["import type { NannyState, StopConfig } from '#src/shared/contracts'\nimport fs from 'node:fs'\nimport path from 'node:path'\nimport { NANNY_TRAPPED_SIGNALS, nannyIsAlive, nannySpecPath, nannyStatePath, nannyStopOptions, readNannyState, SPEC_SUFFIX } from '#src/providers/nanny'\nimport { isProcessAlive } from '#src/providers/port'\nimport { terminatePid } from '#src/providers/process'\nimport { stopSchema } from '#src/shared/contracts'\n\n/**\n * Finds and ends the persistent entries a host is running, with no panel in the loop.\n *\n * `down` leaves these alone on purpose, so `--with-persistent` is the one caller that has to\n * act on them — often after the panel is already gone. The nanny state files are the only\n * record that survives that, and they are per workspace, so every workspace is read.\n *\n * The **nanny** is what gets signalled: it traps the signal and forwards the entry's own\n * `stop` policy to the child it owns, which is what the panel's stop does. That is also why\n * this cannot go through `/_hh` — after a crash there is nothing left to ask.\n */\n\n/** One live persistent entry, as its state file describes it. */\nexport interface PersistentHandle {\n workspaceId: string\n serverId: string\n state: NannyState\n /** The workspace's `.state` directory, which owns the state file. */\n dir: string\n}\n\n/**\n * Every workspace's state directory.\n *\n * Read here rather than through `workspaceStateDir()`, which resolves from *this* process's\n * `HHOSTED_HOME`: a caller passing `--home` elsewhere would otherwise sweep another host's\n * state — the mistake `backup-offline` already paid for.\n */\nfunction stateDirs(hhDir: string): Array<{ workspaceId: string, dir: string }> {\n try {\n return fs.readdirSync(hhDir, { withFileTypes: true })\n .filter(entry => entry.isDirectory() && !entry.name.startsWith('.'))\n .map(entry => entry.name)\n .filter(id => /^[a-z0-9][a-z0-9_-]*$/.test(id))\n .map(workspaceId => ({ workspaceId, dir: path.join(hhDir, workspaceId, '.state') }))\n }\n catch {\n return []\n }\n}\n\n/**\n * The persistent entries whose nanny is running right now.\n *\n * A `<id>.run.json` file is a *non-persistent* child's own record and carries no nanny, so it\n * is skipped by suffix — the same distinction `backup-offline` relies on. `nannyIsAlive` is\n * the identity check: a live pid alone proves nothing, since pids are reused.\n */\nexport async function livePersistentEntries(hhDir: string): Promise<PersistentHandle[]> {\n const found: PersistentHandle[] = []\n\n for (const { workspaceId, dir } of stateDirs(hhDir)) {\n let names: string[]\n try {\n names = fs.readdirSync(dir)\n }\n catch {\n // No persistent entry was ever started in this workspace.\n continue\n }\n\n for (const name of names) {\n if (!name.endsWith('.json') || name.endsWith(SPEC_SUFFIX))\n continue\n // One file per entry, named for it: a file that disagrees with its own name is not\n // something to act on.\n const serverId = name.slice(0, -'.json'.length)\n const state = readNannyState(path.join(dir, name))\n if (state === null || state.serverId !== serverId)\n continue\n if (await nannyIsAlive(state, serverId))\n found.push({ workspaceId, serverId, state, dir })\n }\n }\n return found\n}\n\n/** What one stop did, so a survivor is reported rather than dressed up as success. */\nexport interface PersistentStop {\n handle: PersistentHandle\n stopped: boolean\n error: string | null\n}\n\n/**\n * Stops these entries and consumes the record of each one that ended.\n *\n * `stopFor` is the entry's own `stop` config, read by the caller from the workspace that\n * declares it: the grace period here has to be the one the entry asked for, or a stop that\n * was still finishing its shutdown reads as a failure and escalates to `SIGKILL`.\n */\nexport async function stopPersistentEntries(\n handles: PersistentHandle[],\n options: {\n stopFor?: (handle: PersistentHandle) => StopConfig\n /**\n * The one thing a test cannot supply: `SIGKILL` is not survivable, and a pid this process\n * may not signal (the real survivor) is a second user this host has no way to create. The\n * seam is the terminator, not the decision — everything below still runs.\n */\n terminate?: typeof terminatePid\n } = {},\n): Promise<PersistentStop[]> {\n const results: PersistentStop[] = []\n const terminate = options.terminate ?? terminatePid\n // `.assert` returns the parsed value with the schema's defaults filled in; the plain call\n // type is `Value | errors`, which would make every field a type error to read.\n const defaultStop = stopSchema.assert({})\n\n for (const handle of handles) {\n const stop = options.stopFor?.(handle) ?? defaultStop\n const { state, dir, serverId } = handle\n const nanny = await terminate(state.nannyPid, nannyStopOptions(stop))\n\n // A nanny this process could not signal, or one that outlived `SIGKILL`, keeps its\n // record: it is the only way a later boot can find that process again.\n if (isProcessAlive(state.nannyPid)) {\n results.push({ handle, stopped: false, error: `pid ${state.nannyPid} survived the stop — its record is kept, so the next \\`up\\` can still find it` })\n continue\n }\n\n // A nanny stops its child on the graceful path. A signal it does not trap — `SIGKILL` above\n // all — ends it outright, so nothing was forwarded; and with `killGroup: false` the group\n // signal never reached the child either. The pid in the state file is then the only handle on\n // a server that would otherwise keep serving. The configured signal decides this, never the\n // terminator's own label: `SIGKILL` always reports `force-killed`, which says nothing about\n // whether the nanny had a chance to pass the stop on.\n const orphaned = state.childPid !== null && state.childPid > 0\n && !stop.killGroup\n && (!NANNY_TRAPPED_SIGNALS.has(stop.signal) || nanny === 'force-killed')\n if (orphaned)\n await terminate(state.childPid!, { signal: 'SIGKILL', killGroup: false, graceMs: 0 })\n\n consumeRecord(dir, serverId)\n results.push({ handle, stopped: true, error: null })\n }\n return results\n}\n\n/**\n * The record goes only once the process it names is gone: a state file kept past its process\n * is a false reattach waiting, which is what `resumePersistent` exists to prevent.\n */\nfunction consumeRecord(dir: string, serverId: string): void {\n for (const file of [nannyStatePath(dir, serverId), nannySpecPath(dir, serverId)]) {\n try {\n fs.rmSync(file, { force: true })\n }\n catch {\n // A file this process may not remove is the next boot's business, not a stop failure.\n }\n }\n}\n"],"mappings":";;;;;;;;;;;;;AAoCA,SAAS,UAAU,OAA4D;CAC7E,IAAI;EACF,OAAO,GAAG,YAAY,OAAO,EAAE,eAAe,KAAK,CAAC,CAAC,CAClD,QAAO,UAAS,MAAM,YAAY,KAAK,CAAC,MAAM,KAAK,WAAW,GAAG,CAAC,CAAC,CACnE,KAAI,UAAS,MAAM,IAAI,CAAC,CACxB,QAAO,OAAM,wBAAwB,KAAK,EAAE,CAAC,CAAC,CAC9C,KAAI,iBAAgB;GAAE;GAAa,KAAK,KAAK,KAAK,OAAO,aAAa,QAAQ;EAAE,EAAE;CACvF,QACM;EACJ,OAAO,CAAC;CACV;AACF;;;;;;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3B,QAAQ,KAAK;GAAE;GAAQ,SAAS;GAAM,OAAO;EAAK,CAAC;CACrD;CACA,OAAO;AACT;;;;;AAMA,SAAS,cAAc,KAAa,UAAwB;CAC1D,KAAK,MAAM,QAAQ,CAAC,eAAe,KAAK,QAAQ,GAAG,cAAc,KAAK,QAAQ,CAAC,GAC7E,IAAI;EACF,GAAG,OAAO,MAAM,EAAE,OAAO,KAAK,CAAC;CACjC,QACM,CAEN;AAEJ"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"paths-BT94q6-w.js","names":[],"sources":["../../src/helpers/paths.ts"],"sourcesContent":["import fs from 'node:fs'\nimport os from 'node:os'\nimport path from 'node:path'\nimport process from 'node:process'\n\n/**\n * Where home-hosted keeps everything it owns. `HHOSTED_HOME` overrides it —\n * which is how a project repo keeps its own state directory while the package\n * itself ships no configuration at all.\n *\n * Everything below `dataRoot/.hh`: the global panel state at its top level, and\n * one directory per workspace. A workspace owns its settings, servers, secrets,\n * logs and nanny state; only what is genuinely panel-wide (listener, auth,\n * host vitals, backups, TLS, UI, run.json) stays global.\n */\nexport function resolveDataRoot(): string {\n const override = process.env.HHOSTED_HOME\n if (override !== undefined && override.length > 0)\n return path.resolve(override)\n return path.join(os.homedir(), '.home-hosted')\n}\n\nexport const dataRoot = resolveDataRoot()\n\n/**\n * The directory home-hosted was started from. Relative entry paths (`cwd`,\n * declared data directories) resolve against it, so the project's own launcher\n * decides the base instead of wherever the package happens to be installed.\n * `HHOSTED_PROJECT` pins it explicitly.\n */\nexport function resolveProjectDir(): string {\n const override = process.env.HHOSTED_PROJECT\n if (override !== undefined && override.length > 0)\n return path.resolve(override)\n return process.cwd()\n}\n\nexport const projectDir = resolveProjectDir()\n\n/** The internal state root: global files here, one directory per workspace. */\nexport const hhDir = path.join(dataRoot, '.hh')\n\nexport const DEFAULT_WORKSPACE_ID = 'default'\n\n// ---------------------------------------------------------------- global state\n\n/** Panel-wide settings: listener, auth, TLS policy, host vitals, backups. */\nexport const globalSettingsPath = path.join(hhDir, 'settings.json')\n/** Password hash + API token hash; written with mode 0600. */\nexport const globalSecretsPath = path.join(hhDir, '.control-secrets.json')\n/** The workspace registry: ids and labels. */\nexport const workspacesPath = path.join(hhDir, 'workspaces.json')\n/** Uploaded TLS PEM pair (the key is written 0600). */\nexport const tlsDir = path.join(hhDir, '.tls')\n/** The panel's own console log. */\nexport const daemonLogPath = path.join(hhDir, '.logs', 'home-hosted.log')\n/** `run.json` records the live control plane. */\nexport const runtimePath = path.join(hhDir, 'run.json')\n/** The installed UI; `UiService` owns everything under it. */\nexport const uiDir = path.join(hhDir, '.ui')\n\n// ----------------------------------------------------------------- reverse proxy\n\n/** Everything the reverse proxy owns: engine binary, its data, its state and logs. */\nexport const proxyDir = path.join(hhDir, '.proxy')\n/** The engine binary the panel installed, plus the record of what it installed. */\nexport const proxyBinDir = path.join(proxyDir, 'bin')\n/** The engine's own data and configuration directories, pinned away from `$HOME`. */\nexport const proxyEngineDir = path.join(proxyDir, 'engine')\n/** The generated engine configuration, rewritten on every change. */\nexport const proxyConfigPath = path.join(proxyEngineDir, 'current.json')\n/** The last configuration that applied, kept so a rejected change can be reverted. */\nexport const proxyPreviousConfigPath = path.join(proxyEngineDir, 'previous.json')\n/** The nanny's spec and state for the engine process, so it outlives the panel. */\nexport const proxyStateDir = path.join(proxyDir, 'state')\n/** How the panel reaches a running engine's admin endpoint. */\nexport const proxyAdminPath = path.join(proxyStateDir, 'admin.json')\n/** The PEM pair a route with `tls: \"manual\"` serves. */\nexport const proxyTlsDir = path.join(proxyDir, 'tls')\n/** The credentials the engine presents to the panel's DNS-01 endpoint, 0600. */\nexport const proxyChallengeAuthPath = path.join(proxyStateDir, 'challenge.json')\n\n// ------------------------------------------------------------- workspace state\n\nexport function workspaceDir(id: string): string {\n return path.join(hhDir, id)\n}\n\n/** Workspace-scoped settings: server defaults, logs, notifications, DDNS. */\nexport function workspaceSettingsPath(id: string): string {\n return path.join(workspaceDir(id), 'settings.json')\n}\n\n/** The servers a workspace supervises. */\nexport function workspaceServersPath(id: string): string {\n return path.join(workspaceDir(id), 'servers.config.json')\n}\n\n/** Workspace secrets: Telegram bot token and DDNS credentials. Mode 0600. */\nexport function workspaceSecretsPath(id: string): string {\n return path.join(workspaceDir(id), '.secrets.json')\n}\n\n/** Rotated per-server JSONL logs. */\nexport function workspaceLogsDir(id: string): string {\n return path.join(workspaceDir(id), '.logs')\n}\n\n/** Persisted restart/crash history for one workspace. */\nexport function workspaceHistoryPath(id: string): string {\n return path.join(workspaceLogsDir(id), 'history.json')\n}\n\n/** Per-entry nanny state and spawn specs — how a persistent server survives a restart. */\nexport function workspaceStateDir(id: string): string {\n return path.join(workspaceDir(id), '.state')\n}\n\n/**\n * The last public address each DDNS target was confirmed to serve.\n *\n * A name no server id can produce (ids carry no `.`): `ddns.json` is also the nanny state of a\n * persistent entry with the id `ddns`, and each overwrote the other.\n */\nexport function workspaceDdnsStatePath(id: string): string {\n return path.join(workspaceStateDir(id), 'ddns.cache.json')\n}\n\n/** Where releases before `ddns.cache.json` kept that cache, read once and then removed. */\nexport function workspaceLegacyDdnsStatePath(id: string): string {\n return path.join(workspaceStateDir(id), 'ddns.json')\n}\n\n// -------------------------------------------------------------------- legacy\n\n/**\n * Where a pre-workspace `$HHOSTED_HOME` kept its config and secrets: directly\n * under `dataRoot`. Nothing reads these; they only identify an instance this\n * release refuses to start against.\n */\nexport const legacy = {\n configPath: path.join(dataRoot, 'servers.config.json'),\n secretsPath: path.join(dataRoot, '.control-secrets.json'),\n} as const\n\n/**\n * True when a pre-workspace instance left state at the old paths **and** never\n * crossed into `.hh`: `workspaces.json` means the layout is current, so a stray\n * root-level copy beside it is not an old instance.\n */\nexport function hasLegacyLayout(): boolean {\n if (fs.existsSync(workspacesPath))\n return false\n return fs.existsSync(legacy.configPath) || fs.existsSync(legacy.secretsPath)\n}\n\n/** Expands `~` and resolves relative paths against `base`, for config-declared paths. */\nexport function resolveUserPath(target: string, base = projectDir): string {\n let value = target\n if (value === '~')\n value = os.homedir()\n else if (value.startsWith('~/') || value.startsWith('~\\\\'))\n value = path.join(os.homedir(), value.slice(2))\n return path.isAbsolute(value) ? value : path.resolve(base, value)\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAeA,SAAgB,kBAA0B;CACxC,MAAM,WAAW,QAAQ,IAAI;CAC7B,IAAI,aAAa,KAAA,KAAa,SAAS,SAAS,GAC9C,OAAO,KAAK,QAAQ,QAAQ;CAC9B,OAAO,KAAK,KAAK,GAAG,QAAQ,GAAG,cAAc;AAC/C;AAEA,IAAa,WAAW,gBAAgB;;;;;;;AAQxC,SAAgB,oBAA4B;CAC1C,MAAM,WAAW,QAAQ,IAAI;CAC7B,IAAI,aAAa,KAAA,KAAa,SAAS,SAAS,GAC9C,OAAO,KAAK,QAAQ,QAAQ;CAC9B,OAAO,QAAQ,IAAI;AACrB;AAEA,IAAa,aAAa,kBAAkB;;AAG5C,IAAa,QAAQ,KAAK,KAAK,UAAU,KAAK;AAE9C,IAAa,uBAAuB;;AAKpC,IAAa,qBAAqB,KAAK,KAAK,OAAO,eAAe;;AAElE,IAAa,oBAAoB,KAAK,KAAK,OAAO,uBAAuB;;AAEzE,IAAa,iBAAiB,KAAK,KAAK,OAAO,iBAAiB;;AAEhE,IAAa,SAAS,KAAK,KAAK,OAAO,MAAM;;AAE7C,IAAa,gBAAgB,KAAK,KAAK,OAAO,SAAS,iBAAiB;;AAExE,IAAa,cAAc,KAAK,KAAK,OAAO,UAAU;AAEjC,KAAK,KAAK,OAAO,KAAK;;AAK3C,IAAa,WAAW,KAAK,KAAK,OAAO,QAAQ;;AAEjD,IAAa,cAAc,KAAK,KAAK,UAAU,KAAK;;AAEpD,IAAa,iBAAiB,KAAK,KAAK,UAAU,QAAQ;;AAE1D,IAAa,kBAAkB,KAAK,KAAK,gBAAgB,cAAc;;AAEvE,IAAa,0BAA0B,KAAK,KAAK,gBAAgB,eAA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,QAAgB,OAAO,YAAoB;CACzE,IAAI,QAAQ;CACZ,IAAI,UAAU,KACZ,QAAQ,GAAG,QAAQ;MAChB,IAAI,MAAM,WAAW,IAAI,KAAK,MAAM,WAAW,KAAK,GACvD,QAAQ,KAAK,KAAK,GAAG,QAAQ,GAAG,MAAM,MAAM,CAAC,CAAC;CAChD,OAAO,KAAK,WAAW,KAAK,IAAI,QAAQ,KAAK,QAAQ,MAAM,KAAK;AAClE"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"restart-UZgeDukG.js","names":[],"sources":["../../src/cli/restart.ts"],"sourcesContent":["import process from 'node:process'\nimport { defineCommand } from 'citty'\nimport { runDown } from '#src/cli/down'\nimport { fail, paint } from '#src/cli/io'\nimport { runServerAction } from '#src/cli/server'\nimport { runUp, toUpFlags, upArgs } from '#src/cli/up'\n\n/**\n * `restart` restarts the panel (`down`, then `up`) — or, given a server id, just that entry.\n *\n * The id is optional on purpose. `restart` already meant the panel, and it still does when\n * called the way it always was; adding a positional would have been a hard error before this\n * (\"Unexpected argument 'web'\"), so nothing existing changes meaning. The per-server case is\n * what the UI's Restart button has always done and the shell could not.\n */\n\n/**\n * The `up` flags that mean nothing to `restart <id>`, with every spelling citty accepts for each.\n *\n * The bare form forwards all of them — `restart --print-config` is a real, tested use, and it is how\n * the panel path is observable without detaching a daemon. The id form is a different command: it\n * asks the panel to restart one entry over `/_hh` and never runs `down` or `up`, so a panel-level\n * flag has nothing to act on.\n *\n * `--with-persistent` already had this guard. These six did not, so they were parsed and dropped in\n * the same handler: `restart web --port 5000` reported \"restarted web\" having changed no port, and\n * `restart web --print-config` restarted a live server while reading as \"show me the config\".\n */\nconst PANEL_ONLY_FLAGS: ReadonlyArray<{ name: string, spellings: readonly string[] }> = [\n { name: '--port', spellings: ['--port', '-p'] },\n { name: '--host', spellings: ['--host'] },\n { name: '--no-autostart', spellings: ['--no-autostart', '--autostart'] },\n { name: '--open', spellings: ['--open'] },\n { name: '--foreground', spellings: ['--foreground'] },\n { name: '--print-config', spellings: ['--print-config'] },\n]\n\n/**\n * Whether argv names one of these flags, in either the `--flag value` or `--flag=value` form.\n *\n * Read from `rawArgs` rather than the parsed args: citty fills a default in for the boolean flags\n * (`autostart` defaults to true), so the parsed object cannot tell \"the caller said `--no-autostart`\"\n * from \"the caller said nothing\".\n */\nfunction mentions(rawArgs: string[], spellings: readonly string[]): boolean {\n return rawArgs.some((token) => {\n if (!token.startsWith('-'))\n return false\n const name = token.includes('=') ? token.slice(0, token.indexOf('=')) : token\n return spellings.includes(name)\n })\n}\nexport function restartCommand(entry: string) {\n return defineCommand({\n meta: { name: 'restart' },\n args: {\n ...upArgs,\n // `down`'s own flag, so the two commands cannot drift about what it means. Declared\n // here as well because citty reads one command's definitions, not two.\n withPersistent: { type: 'boolean', description: 'stop the persistent entries too, instead of leaving them running' },\n // Declared here rather than in `server.ts` because only `restart` takes it bare: for\n // `start`/`stop` the id is required, and citty's refusal is replaced by our own message.\n id: { type: 'positional', required: false, description: 'restart just this server instead of the panel' },\n workspace: { type: 'string', alias: 'w', description: 'the workspace to act in (default: the panel\\'s default workspace)' },\n },\n run: async ({ args, rawArgs }) => {\n const id = typeof args.id === 'string' ? args.id.trim() : ''\n\n if (id.length > 0) {\n // One entry, so the panel stays up. A bare `restart` would have taken the whole\n // panel — and every other server — down with it.\n if (args.withPersistent === true)\n fail('restart <id> restarts one server — drop --with-persistent, or use it on a bare `restart`')\n // `restart <id>` asks the panel to restart one entry through `/_hh`; it never runs `down`\n // or `up`, so none of `up`'s flags can be honoured here. They used to be parsed and\n // dropped: `restart web --print-config` restarted a live server while reading as \"show me\n // the config\", and `restart web --port 5000` reported success having changed no port.\n // Refused by name, the way `--with-persistent` above already was.\n const panelFlag = PANEL_ONLY_FLAGS.find(flag => mentions(rawArgs, flag.spellings))\n if (panelFlag !== undefined)\n fail(`restart <id> restarts one server and takes no panel option — drop ${panelFlag.name}, or use it on a bare \\`restart\\``)\n const workspace = typeof args.workspace === 'string' ? args.workspace.trim() : undefined\n await runServerAction('restart', id, workspace)\n return\n }\n\n // The panel's own restart takes no `--workspace`: it is not a per-server idea.\n if (args.workspace !== undefined)\n fail('restart --workspace needs a server id — `home-hosted restart <id> --workspace <id>`')\n\n // `--with-persistent` restarts them, it does not merely stop them. `up` would *reattach*\n // to a nanny left alive, so stopping them first is what makes this a restart at all —\n // and a stopped entry is only started back by `up`'s autostart pass, which an entry with\n // `autostart: false` is not in. Those are therefore started back explicitly.\n const stopped = (await runDown({ withPersistent: args.withPersistent === true })).stoppedPersistent\n await runUp(toUpFlags(args), entry)\n if (stopped.length > 0)\n await startPersistentBack(stopped)\n },\n })\n}\n\n/**\n * Starts the entries this restart stopped, through the panel that just came back.\n *\n * Only the ones `up` did not already start: its autostart pass runs asynchronously and a second\n * start of a running entry is a plain `{ ok: true }`, so re-asking is harmless — but the\n * entries with `autostart: false`, the reason this exists, would never come back otherwise.\n */\nasync function startPersistentBack(stopped: Array<{ workspaceId: string, serverId: string }>): Promise<void> {\n const { readRuntime, requestControl } = await import('#src/helpers/daemon')\n const runtime = readRuntime()\n if (runtime === null)\n return\n\n for (const { workspaceId, serverId } of stopped) {\n const workspace = `?workspace=${encodeURIComponent(workspaceId)}`\n const answer = await requestControl(runtime, `/_hh/servers/${encodeURIComponent(serverId)}/start${workspace}`)\n const body = (answer?.body ?? {}) as { ok?: boolean, error?: string }\n if (body.ok !== true)\n process.stderr.write(`${paint('31', 'error')} ${workspaceId}/${serverId} did not come back: ${body.error ?? `the panel answered ${answer?.status}`}\\n`)\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;AA4BA,IAAM,mBAAkF;CACtF;EAAE,MAAM;EAAU,WAAW,CAAC,UAAU,IAAI;CAAE;CAC9C;EAAE,MAAM;EAAU,WAAW,CAAC,QAAQ;CAAE;CACxC;EAAE,MAAM;EAAkB,WAAW,CAAC,kBAAkB,aAAa;CAAE;CACvE;EAAE,MAAM;EAAU,WAAW,CAAC,Q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MAAM,UAAU,IAAI,GAAG,KAAK;GAClC,IAAI,QAAQ,SAAS,GACnB,MAAM,oBAAoB,OAAO;EACrC;CACF,CAAC;AACH;;;;;;;;AASA,eAAe,oBAAoB,SAA0E;CAC3G,MAAM,EAAE,aAAa,mBAAmB,MAAM,OAAO;CACrD,MAAM,UAAU,YAAY;CAC5B,IAAI,YAAY,MACd;CAEF,KAAK,MAAM,EAAE,aAAa,cAAc,SAAS;EAC/C,MAAM,YAAY,cAAc,mBAAmB,WAAW;EAC9D,MAAM,SAAS,MAAM,eAAe,SAAS,gBAAgB,mBAAmB,QAAQ,EAAE,QAAQ,WAAW;EAC7G,MAAM,OAAQ,QAAQ,QAAQ,CAAC;EAC/B,IAAI,KAAK,OAAO,MACd,QAAQ,OAAO,MAAM,GAAG,MAAM,MAAM,OAAO,EAAE,GAAG,YAAY,GAAG,SAAS,sBAAsB,KAAK,SAAS,sBAAsB,QAAQ,SAAS,GAAG;CAC1J;AACF"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"schema-o7Lgk0V1.js","names":[],"sources":["../../src/config/schema.ts"],"sourcesContent":["import type { ServerConfig } from '#src/shared/contracts'\nimport { type } from 'arktype'\nimport {\n backupsSchema,\n controlSchema,\n ddnsConfigSchema,\n defaultsSchema,\n hostSchema,\n logsSchema,\n notificationsSchema,\n proxyConfigSchema,\n serverSchema,\n} from '#src/shared/contracts'\nimport { isRecord } from '#src/shared/shape'\n\nexport { backupsSchema, controlSchema, ddnsConfigSchema, defaultsSchema, hostSchema, logsSchema, notificationsSchema, proxyConfigSchema, serverSchema }\n\n/**\n * Which release wrote the file, and the config shape it wrote. Optional so a\n * config from before the stamp still reads, and so an archive made by an older\n * release still restores.\n */\nexport const metaSchema = type({\n writtenBy: 'string = \"\"',\n schema: 'number.integer >= 1 = 1',\n}).onUndeclaredKey('reject')\n\n/**\n * `$HHOSTED_HOME/.hh/settings.json`: the settings that belong to the panel\n * itself — its listener, authentication, TLS policy, host vitals, backups and\n * the reverse proxy. Nothing here is per workspace.\n */\nexport const globalSettingsSchema = type({\n $schema: 'string?',\n meta: metaSchema.optional(),\n control: controlSchema.default(() => ({})),\n host: hostSchema.default(() => ({})),\n backups: backupsSchema.default(() => ({})),\n proxy: proxyConfigSchema.default(() => ({})),\n}).onUndeclaredKey('reject')\n\n/** `$HHOSTED_HOME/.hh/<id>/settings.json`: what one workspace owns on its own. */\nexport const workspaceSettingsSchema = type({\n $schema: 'string?',\n meta: metaSchema.optional(),\n defaults: defaultsSchema.default(() => ({})),\n logs: logsSchema.default(() => ({})),\n notifications: notificationsSchema.default(() => ({})),\n ddns: ddnsConfigSchema.default(() => ({})),\n}).onUndeclaredKey('reject')\n\n/** `$HHOSTED_HOME/.hh/<id>/servers.config.json`: the entries this workspace supervises. */\nexport const serversFileSchema = type({\n $schema: 'string?',\n meta: metaSchema.optional(),\n servers: serverSchema.array().default(() => []),\n}).onUndeclaredKey('reject')\n\nexport type ResolvedGlobalConfig = typeof globalSettingsSchema.infer\nexport type ResolvedWorkspaceSettings = typeof workspaceSettingsSchema.infer\nexport type ResolvedServersFile = typeof serversFileSchema.infer\n\n/** Same shape as the settings output, with each server `port` normalized to `null` when unset. */\nexport type ResolvedWorkspaceConfig = ResolvedWorkspaceSettings & { servers: ServerConfig[] }\n\n/** Every key `globalSettingsSchema` knows, for reporting blocks a newer release added. */\nexport const GLOBAL_SETTINGS_KEYS = ['$schema', 'meta', 'control', 'host', 'backups', 'proxy'] as const\nexport const WORKSPACE_SETTINGS_KEYS = ['$schema', 'meta', 'defaults', 'logs', 'notifications', 'ddns'] as const\nexport const SERVERS_FILE_KEYS = ['$schema', 'meta', 'servers'] as const\n\n/**\n * Resolves one entry against the workspace's server defaults. A group (`restart`,\n * `health`, `health.http`, `stop`) merges key by key, so an entry that decides one\n * member does not silently fall back to the *schema* default for the others — which\n * is the whole point of the workspace having defaults at all.\n */\nexport function mergeDefaults(\n defaults: Record<string, unknown>,\n entry: Record<string, unknown>,\n): Record<string, unknown> {\n const merged: Record<string, unknown> = { ...entry }\n for (const [key, value] of Object.entries(defaults)) {\n const current = merged[key]\n if (current === undefined)\n merged[key] = value\n else if (isRecord(value) && isRecord(current))\n merged[key] = mergeDefaults(value, current)\n }\n return merged\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAsBA,IAAa,aAAa,KAAK;CAC7B,WAAW;CACX,QAAQ;AACV,CAAC,CAAC,CAAC,gBAAgB,QAAQ;;;;;;AAO3B,IAAa,uBAAuB,KAAK;CACvC,SAAS;CACT,MAAM,WAAW,SAAS;CAC1B,SAAS,cAAc,eAAe,CAAC,EAAE;CACzC,MAAM,WAAW,eAAe,CAAC,EAAE;CACnC,SAAS,cAAc,eAAe,CAAC,EAAE;CACzC,OAAO,kBAAkB,eAAe,CAAC,EAAE;AAC7C,CAAC,CAAC,CAAC,gBAAgB,QAAQ;;AAG3B,IAAa,0BAA0B,KAAK;CAC1C,SAAS;CACT,MAAM,WAAW,SAAS;CAC1B,UAAU,eAAe,eAAe,CAAC,EAAE;CAC3C,MAAM,WAAW,eAAe,CAAC,EAAE;CACnC,eAAe,oBAAoB,eAAe,CAAC,EAAE;CACrD,MAAM,iBAAiB,eAAe,CAAC,EAAE;AAC3C,CAAC,CAAC,CAAC,gBAAgB,QAAQ;;AAG3B,IAAa,oBAAoB,KAAK;CACpC,SAAS;CACT,MAAM,WAAW,SAAS;CAC1B,SAAS,aAAa,MAAM,CAAC,CAAC,cAAc,CAAC,CAAC;AAChD,CAAC,CAAC,CAAC,gBAAgB,QAAQ;;AAU3B,IAAa,uBAAuB;CAAC;CAAW;CAAQ;CAAW;CAAQ;CAAW;AAAO;AAC7F,IAAa,0BAA0B;CAAC;CAAW;CAAQ;CAAY;CAAQ;CAAiB;AAAM;AACtG,IAAa,oBAAoB;CAAC;CAAW;CAAQ;AAAS;;;;;;;AAQ9D,SAAgB,cACd,UACA,OACyB;CACzB,MAAM,SAAkC,EAAE,GAAG,MAAM;CACnD,KAAK,MAAM,CAAC,KAAK,UAAU,OAAO,QAAQ,QAAQ,GAAG;EACnD,MAAM,UAAU,OAAO;EACvB,IAAI,YAAY,KAAA,GACd,OAAO,OAAO;OACX,IAAI,SAAS,KAAK,KAAK,SAAS,OAAO,GAC1C,OAAO,OAAO,cAAc,OAAO,OAAO;CAC9C;CACA,OAAO;AACT"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"secrets-D7PdYh71.js","names":[],"sources":["../../src/config/secrets.ts"],"sourcesContent":["import { Buffer } from 'node:buffer'\nimport crypto from 'node:crypto'\nimport fs from 'node:fs'\nimport process from 'node:process'\nimport { writeFileAtomic } from '#src/helpers/atomic'\nimport { readStateFile } from '#src/helpers/config-text'\nimport { logger } from '#src/helpers/logger'\nimport { errorMessage } from '#src/shared/error-message'\nimport { isRecord } from '#src/shared/shape'\n\n/** Node's scrypt defaults, pinned so a hash stays verifiable across versions. */\nconst COST = { N: 16384, r: 8, p: 1 } as const\nconst KEYLEN = 64\nconst SALT_BYTES = 16\n\nexport interface PasswordRecord {\n algo: 'scrypt'\n salt: string\n hash: string\n keylen: number\n cost: { N: number, r: number, p: number }\n updatedAt: number\n /** Set for the boot-time default, so the UI can say so and exposure stays blocked. */\n isDefault?: boolean\n /**\n * The generated first-run password, kept in this 0600 file only while it is still in use so\n * `up`/`status` can show it on the machine. Never sent over the API; gone with the first change.\n */\n initial?: string\n}\n\n/**\n * An API token for scripts and agents. Tokens are high-entropy randoms, so a\n * plain SHA-256 is the right hash — scrypt would only make every request pay\n * for a slow KDF it does not need. `hint` is the readable head, kept so a human\n * can tell two tokens apart without the file ever holding the whole secret.\n */\nexport interface ApiTokenRecord {\n algo: 'sha256'\n hash: string\n hint: string\n updatedAt: number\n}\n\n/** One account's provider credentials, with the provider they were entered for. */\nexport interface DdnsCredentialRecord {\n provider: string\n values: Record<string, string>\n}\n\n/** An account's credentials as they sit on disk: sealed, never plaintext. */\ninterface SealedDdnsRecord {\n algo: 'aes-256-gcm'\n iv: string\n tag: string\n data: string\n}\n\n/** Read from a file written before sealing; re-sealed by the next write. */\ninterface PlainDdnsRecord {\n plain: true\n provider: string\n values: Record<string, string>\n}\n\ntype StoredDdnsRecord = SealedDdnsRecord | PlainDdnsRecord\n\n/** One derivation per process: the secret is combined with this per-file salt. */\ninterface DdnsKdfMeta {\n algo: 'scrypt'\n cost: ScryptCost\n salt: string\n}\n\n/**\n * Which halves of the file a store owns. Global secrets (the password hash and\n * the API token) live above the workspaces, in `.hh/.control-secrets.json`;\n * workspace secrets (the Telegram bot token and DDNS credentials) live in that\n * workspace's own `.secrets.json`. `all` is the shape the pre-workspace file had\n * and is still what a backup archive may carry.\n */\nexport type SecretsScope = 'all' | 'global' | 'workspace'\n\ninterface SecretsFile {\n password: PasswordRecord | null\n apiToken: ApiTokenRecord | null\n /**\n * Bot tokens by destination id. A map, not a singleton: a workspace may point at more than one\n * Telegram chat, and each destination carries its own bot.\n */\n telegram: Record<string, string>\n /** Per-DDNS-account credentials, keyed by the account id in the config. */\n ddns: Record<string, StoredDdnsRecord>\n /** How the DDNS key is derived; absent until the first sealed write. */\n ddnsKdf: DdnsKdfMeta | null\n}\n\n/**\n * The id the config migration gives a pre-list Telegram destination, so its stored `{ botToken }`\n * still finds an owner after the upgrade.\n */\nexport const LEGACY_TELEGRAM_ID = 'telegram'\n\n/** So a first run is sealed rather than plaintext; set `HHOSTED_DDNS_SECRET` for real protection. */\nexport const DEFAULT_DDNS_SECRET = 'hh'\nconst DDNS_KEYLEN = 32\nconst DDNS_IV_BYTES = 12\nconst DDNS_AAD_PREFIX = 'hh-ddns-v1:'\nconst DDNS_SEALED_ALGO = 'aes-256-gcm'\n\nexport interface ScryptCost { N: number, r: number, p: number }\n\nexport function deriveKey(password: string, salt: Buffer, cost: ScryptCost, keylen: number): Buffer {\n return crypto.scryptSync(password.normalize('NFKC'), salt, keylen, { ...cost })\n}\n\nexport function hashPassword(password: string, options: { now?: number, isDefault?: boolean, initial?: boolean } = {}): PasswordRecord {\n const salt = crypto.randomBytes(SALT_BYTES)\n return {\n algo: 'scrypt',\n salt: salt.toString('base64'),\n hash: deriveKey(password, salt, COST, KEYLEN).toString('base64'),\n keylen: KEYLEN,\n cost: { ...COST },\n updatedAt: options.now ?? Date.now(),\n ...(options.isDefault === true ? { isDefault: true } : {}),\n ...(options.isDefault === true && options.initial === true ? { initial: password } : {}),\n }\n}\n\n/** The pre-0.12 boot password every install shared. Still recognised, never created. */\nexport const LEGACY_DEFAULT_PASSWORD = 'hh'\n\n/** A random first-run password: 12 characters from an unambiguous alphabet, ~60 bits. */\nexport function generateInitialPassword(): string {\n const alphabet = 'abcdefghjkmnpqrstuvwxyz23456789'\n const bytes = crypto.randomBytes(12)\n const chars = [...bytes].map(byte => alphabet[byte % alphabet.length])\n return [chars.slice(0, 4), chars.slice(4, 8), chars.slice(8)].map(group => group.join('')).join('-')\n}\n\nexport function verifyPassword(password: string, record: PasswordRecord): boolean {\n const expected = Buffer.from(record.hash, 'base64')\n let actual: Buffer\n try {\n actual = deriveKey(password, Buffer.from(record.salt, 'base64'), record.cost, record.keylen)\n }\n catch {\n return false\n }\n if (actual.length !== expected.length)\n return false\n return crypto.timingSafeEqual(actual, expected)\n}\n\n/** Visible head of a generated token, so a token is recognisable on sight. */\nexport const API_TOKEN_PREFIX = 'hh_'\nconst API_TOKEN_BYTES = 32\nconst API_TOKEN_HINT_CHARS = 8\n\nexport function generateApiToken(): string {\n return `${API_TOKEN_PREFIX}${crypto.randomBytes(API_TOKEN_BYTES).toString('base64url')}`\n}\n\nexport function hashApiToken(token: string): string {\n return crypto.createHash('sha256').update(token, 'utf8').digest('base64')\n}\n\nexport function verifyApiToken(token: string, record: ApiTokenRecord): boolean {\n if (token.length === 0)\n return false\n const expected = Buffer.from(record.hash, 'base64')\n const actual = Buffer.from(hashApiToken(token), 'base64')\n // A hand-edited or truncated secrets file must not make every request throw.\n if (actual.length !== expected.length)\n return false\n return crypto.timingSafeEqual(actual, expected)\n}\n\nexport function apiTokenRecord(token: string, now = Date.now()): ApiTokenRecord {\n return {\n algo: 'sha256',\n hash: hashApiToken(token),\n hint: token.slice(0, API_TOKEN_HINT_CHARS),\n updatedAt: now,\n }\n}\n\n/** A field map: strings only, empty values dropped; anything else reads as absent. */\nfunction readDdnsValues(value: unknown): Record<string, string> {\n if (!isRecord(value))\n return {}\n const out: Record<string, string> = {}\n for (const [key, field] of Object.entries(value)) {\n if (typeof field === 'string' && field.length > 0)\n out[key] = field\n }\n return out\n}\n\nfunction isSealedDdns(value: unknown): value is SealedDdnsRecord {\n return isRecord(value)\n && value.algo === DDNS_SEALED_ALGO\n && typeof value.iv === 'string'\n && typeof value.tag === 'string'\n && typeof value.data === 'string'\n}\n\nfunction isPlainDdns(value: StoredDdnsRecord): value is PlainDdnsRecord {\n return 'plain' in value\n}\n\n/**\n * The bot tokens by destination id.\n *\n * Two shapes read: the map this release writes, and the single `{ botToken }` written before a\n * workspace could have more than one Telegram destination. The old one arrives under the id the\n * config migration gave the destination it came from, so an upgrade keeps a working Telegram.\n */\nfunction readTelegramTokens(value: unknown): Record<string, string> {\n if (!isRecord(value))\n return {}\n // The legacy singleton.\n if (typeof value.botToken === 'string')\n return value.botToken.trim().length > 0 ? { [LEGACY_TELEGRAM_ID]: value.botToken.trim() } : {}\n const tokens: Record<string, string> = {}\n for (const [id, token] of Object.entries(value)) {\n if (typeof token === 'string' && token.trim().length > 0)\n tokens[id] = token.trim()\n }\n return tokens\n}\n\n/**\n * Sealed on disk, or `{ provider, values }` waiting for the sealing write. A bare\n * field map — written before the provider was recorded — no longer reads, because\n * there is nothing to say which provider those fields belong to.\n */\nfunction readStoredDdns(value: unknown): Record<string, StoredDdnsRecord> {\n if (!isRecord(value))\n return {}\n const out: Record<string, StoredDdnsRecord> = {}\n for (const [accountId, entry] of Object.entries(value)) {\n if (isSealedDdns(entry)) {\n out[accountId] = entry\n continue\n }\n if (!isRecord(entry) || typeof entry.provider !== 'string' || entry.provider.length === 0)\n continue\n const values = readDdnsValues(entry.values)\n if (Object.keys(values).length === 0)\n continue\n out[accountId] = { plain: true, provider: entry.provider, values }\n }\n return out\n}\n\nfunction readDdnsKdf(value: unknown): DdnsKdfMeta | null {\n if (!isRecord(value) || value.algo !== 'scrypt' || typeof value.salt !== 'string')\n return null\n const cost = isRecord(value.cost) ? value.cost : {}\n const N = Number(cost.N)\n const r = Number(cost.r)\n const p = Number(cost.p)\n if (!Number.isInteger(N) || !Number.isInteger(r) || !Number.isInteger(p) || N < 2 || r < 1 || p < 1)\n return null\n return { algo: 'scrypt', cost: { N, r, p }, salt: value.salt }\n}\n\nfunction newDdnsKdf(): DdnsKdfMeta {\n return { algo: 'scrypt', cost: { ...COST }, salt: crypto.randomBytes(SALT_BYTES).toString('base64') }\n}\n\n/** The account id is the AAD, so a sealed entry cannot be moved to another account. */\nfunction ddnsAad(accountId: string): Buffer {\n return Buffer.from(`${DDNS_AAD_PREFIX}${accountId}`, 'utf8')\n}\n\nfunction sealDdns(accountId: string, record: DdnsCredentialRecord, key: Buffer): SealedDdnsRecord {\n const iv = crypto.randomBytes(DDNS_IV_BYTES)\n const cipher = crypto.createCipheriv(DDNS_SEALED_ALGO, key, iv)\n cipher.setAAD(ddnsAad(accountId))\n const data = Buffer.concat([cipher.update(JSON.stringify(record), 'utf8'), cipher.final()])\n return {\n algo: DDNS_SEALED_ALGO,\n iv: iv.toString('base64'),\n tag: cipher.getAuthTag().toString('base64'),\n data: data.toString('base64'),\n }\n}\n\n/** Null when the tag does not verify: a different secret, or a file somebody edited. */\nfunction openDdns(accountId: string, sealed: SealedDdnsRecord, key: Buffer): DdnsCredentialRecord | null {\n try {\n const decipher = crypto.createDecipheriv(DDNS_SEALED_ALGO, key, Buffer.from(sealed.iv, 'base64'))\n decipher.setAAD(ddnsAad(accountId))\n decipher.setAuthTag(Buffer.from(sealed.tag, 'base64'))\n const plain = Buffer.concat([decipher.update(Buffer.from(sealed.data, 'base64')), decipher.final()]).toString('utf8')\n const parsed = JSON.parse(plain) as Partial<DdnsCredentialRecord>\n if (typeof parsed?.provider !== 'string')\n return null\n const values = readDdnsValues(parsed.values)\n return Object.keys(values).length === 0 ? null : { provider: parsed.provider, values }\n }\n catch {\n return null\n }\n}\n\n/**\n * The password hash and the API token are secrets, so they live outside\n * `servers.config.json` (which is tracked) in a 0600 file that is git-ignored.\n *\n * DDNS provider credentials are the one thing here the panel has to replay to a\n * third party, so they are sealed with AES-256-GCM under `HHOSTED_DDNS_SECRET`.\n * Everything else is a one-way hash and needs no key.\n */\nexport class SecretsStore {\n private cache: SecretsFile | null = null\n private cacheKey = ''\n private error: string | null = null\n private ddnsKeyCache: { salt: string, key: Buffer } | null = null\n private readonly warnedAccounts = new Set<string>()\n private warnedDefaultSecret = false\n private readonly ddnsSecret: string\n\n constructor(private readonly file: string, ddnsSecret?: string, private readonly scope: SecretsScope = 'all') {\n const candidate = (ddnsSecret ?? process.env.HHOSTED_DDNS_SECRET ?? '').trim()\n this.ddnsSecret = candidate.length > 0 ? candidate : DEFAULT_DDNS_SECRET\n }\n\n /**\n * Whether the DDNS credentials are sealed under the built-in key.\n *\n * Sealing is what stops a leaked *file* — a backup, a committed state directory — from handing over\n * the DNS credentials. Under the default the key is the literal `hh`, so anyone holding the file can\n * open it. The docs say so; this is the same fact for code that wants to say so at runtime.\n */\n get usingDefaultDdnsSecret(): boolean {\n return this.ddnsSecret === DEFAULT_DDNS_SECRET\n }\n\n get path(): string {\n return this.file\n }\n\n /**\n * Re-reads whenever the file changes on disk, so a password set by\n * `home-hosted set-password` (or another process) takes effect without\n * restarting `up`.\n */\n load(): SecretsFile {\n const key = this.statKey()\n if (this.cache !== null && key === this.cacheKey)\n return this.cache\n this.cache = this.read()\n this.cacheKey = key\n return this.cache\n }\n\n private statKey(): string {\n try {\n const stats = fs.statSync(this.file)\n return `${stats.mtimeMs}:${stats.size}`\n }\n catch {\n return 'missing'\n }\n }\n\n get password(): PasswordRecord | null {\n return this.load().password\n }\n\n get passwordUpdatedAt(): number | null {\n return this.password?.updatedAt ?? null\n }\n\n get passwordSet(): boolean {\n return this.password !== null\n }\n\n get usingDefaultPassword(): boolean {\n return this.password?.isDefault === true\n }\n\n get apiToken(): ApiTokenRecord | null {\n return this.load().apiToken\n }\n\n get apiTokenSet(): boolean {\n return this.apiToken !== null\n }\n\n /** The readable head of the stored token, or null when none is set. */\n get apiTokenHint(): string | null {\n return this.apiToken?.hint ?? null\n }\n\n /** The bot token for one destination, or null when it has none. */\n telegramToken(id: string): string | null {\n const token = this.load().telegram[id] ?? ''\n return token.length > 0 ? token : null\n }\n\n telegramTokenSet(id: string): boolean {\n return this.telegramToken(id) !== null\n }\n\n /** Every destination id a token is stored for — including one the config no longer declares. */\n get telegramTokenIds(): string[] {\n return Object.keys(this.load().telegram).sort()\n }\n\n /**\n * The first-run password while it is still the one in use, for a person on this machine.\n * A home from before 0.12 still on the shared default reports that one.\n */\n get initialPassword(): string | null {\n const record = this.password\n if (record?.isDefault !== true)\n return null\n if (typeof record.initial === 'string' && record.initial.length > 0)\n return record.initial\n return verifyPassword(LEGACY_DEFAULT_PASSWORD, record) ? LEGACY_DEFAULT_PASSWORD : null\n }\n\n setPassword(password: string, options: { isDefault?: boolean, initial?: boolean } = {}): PasswordRecord {\n const record = hashPassword(password, options)\n this.save({ ...this.load(), password: record })\n return record\n }\n\n /** Creates the first-run password only when none exists yet. */\n ensureDefaultPassword(password: string): PasswordRecord | null {\n if (this.passwordSet)\n return null\n return this.setPassword(password, { isDefault: true, initial: true })\n }\n\n clearPassword(): void {\n this.save({ ...this.load(), password: null })\n }\n\n setApiToken(token: string): ApiTokenRecord {\n const record = apiTokenRecord(token)\n this.save({ ...this.load(), apiToken: record })\n return record\n }\n\n clearApiToken(): void {\n this.save({ ...this.load(), apiToken: null })\n }\n\n setTelegramToken(id: string, token: string | null): void {\n const trimmed = token?.trim() ?? ''\n const current = { ...this.load().telegram }\n if (trimmed.length > 0)\n current[id] = trimmed\n else\n delete current[id]\n this.save({ ...this.load(), telegram: current })\n }\n\n /** Drops every token whose destination is gone, so a deleted target leaves nothing behind. */\n forgetTelegramTokens(keep: readonly string[]): void {\n const allowed = new Set(keep)\n const current = this.load().telegram\n const next = Object.fromEntries(Object.entries(current).filter(([id]) => allowed.has(id)))\n if (Object.keys(next).length !== Object.keys(current).length)\n this.save({ ...this.load(), telegram: next })\n }\n\n /** Ids that have something stored, whether or not a config still declares them. */\n get ddnsAccountIds(): string[] {\n return Object.keys(this.load().ddns)\n }\n\n /**\n * Null when nothing is stored, when the entry belongs to a different provider,\n * or when the secret cannot open it.\n */\n getDdnsCredentials(accountId: string, provider: string): DdnsCredentialRecord | null {\n const stored = this.load().ddns[accountId]\n if (stored === undefined)\n return null\n const record = this.openStored(accountId, stored)\n if (record === null)\n return null\n return record.provider === provider ? record : null\n }\n\n /** An empty field is dropped, so clearing every field forgets the account. */\n setDdnsCredentials(accountId: string, provider: string, credentials: Record<string, string>): void {\n const current = this.load()\n const values = readDdnsValues(credentials)\n const ddns = { ...current.ddns }\n if (Object.keys(values).length === 0)\n delete ddns[accountId]\n else\n ddns[accountId] = { plain: true, provider, values }\n this.save({ ...current, ddns })\n }\n\n clearDdnsCredentials(accountId: string): void {\n const current = this.load()\n if (current.ddns[accountId] === undefined)\n return\n const ddns = { ...current.ddns }\n delete ddns[accountId]\n this.save({ ...current, ddns })\n }\n\n /** Keeps only the accounts a config still declares; returns how many were dropped. */\n pruneDdnsCredentials(keep: Iterable<string>): number {\n const wanted = new Set(keep)\n const current = this.load()\n const removed = Object.keys(current.ddns).filter(id => !wanted.has(id))\n if (removed.length === 0)\n return 0\n const ddns = { ...current.ddns }\n for (const id of removed) delete ddns[id]\n this.save({ ...current, ddns })\n return removed.length\n }\n\n private openStored(accountId: string, stored: StoredDdnsRecord): DdnsCredentialRecord | null {\n if (isPlainDdns(stored))\n return { provider: stored.provider, values: stored.values }\n\n const kdf = this.load().ddnsKdf\n if (kdf === null) {\n this.warnOnce(accountId, 'the file carries no key parameters')\n return null\n }\n const record = openDdns(accountId, stored, this.ddnsKey(kdf))\n if (record === null)\n this.warnOnce(accountId, `the entry could not be opened — is HHOSTED_DDNS_SECRET still the one it was sealed with?`)\n return record\n }\n\n /** One derivation per file salt, cached for the life of the process. */\n private ddnsKey(kdf: DdnsKdfMeta): Buffer {\n if (this.ddnsKeyCache?.salt === kdf.salt)\n return this.ddnsKeyCache.key\n const key = deriveKey(this.ddnsSecret, Buffer.from(kdf.salt, 'base64'), kdf.cost, DDNS_KEYLEN)\n this.ddnsKeyCache = { salt: kdf.salt, key }\n return key\n }\n\n private warnOnce(accountId: string, reason: string): void {\n if (this.warnedAccounts.has(accountId))\n return\n this.warnedAccounts.add(accountId)\n logger.warn(`ddns: cannot read the credentials for \"${accountId}\" — ${reason}`)\n }\n\n /**\n * A secrets file that exists but cannot be parsed, or null when it is fine (or absent).\n *\n * `read()` still returns the empty shape — a corrupt file must not authenticate anyone — but\n * \"unreadable\" and \"absent\" have to stay distinguishable: treated as absent, a truncated\n * `.control-secrets.json` reads as a fresh install, and `runControlPlane` then writes a\n * **default-password** file over it, destroying the password hash, the API token and every\n * Telegram and DDNS credential. Only the caller can refuse the boot, so this is its surface.\n */\n get configError(): string | null {\n this.load()\n return this.error\n }\n\n private read(): SecretsFile {\n this.error = null\n const empty: SecretsFile = { password: null, apiToken: null, telegram: {}, ddns: {}, ddnsKdf: null }\n if (!fs.existsSync(this.file))\n return this.inScope(empty)\n let text: string\n try {\n text = readStateFile(this.file)\n }\n catch (error) {\n // Present but unreadable is not absent: permissions or a directory, say.\n this.error = `cannot read ${this.file}: ${errorMessage(error)}`\n return this.inScope(empty)\n }\n try {\n const parsed = JSON.parse(text) as Partial<SecretsFile>\n return this.inScope({\n password: parsed?.password ?? null,\n apiToken: parsed?.apiToken?.hash ? parsed.apiToken : null,\n telegram: readTelegramTokens(parsed?.telegram),\n ddns: readStoredDdns(parsed?.ddns),\n ddnsKdf: readDdnsKdf((parsed as { ddnsKdf?: unknown })?.ddnsKdf),\n })\n }\n catch (error) {\n this.error = `${this.file} is not readable JSON (${errorMessage(error)}) — it was left untouched`\n return this.inScope(empty)\n }\n }\n\n /** Everything a store does not own is neither read from nor written to its file. */\n private inScope(contents: SecretsFile): SecretsFile {\n if (this.scope === 'global')\n return { ...contents, telegram: {}, ddns: {}, ddnsKdf: null }\n if (this.scope === 'workspace')\n return { ...contents, password: null, apiToken: null }\n return contents\n }\n\n private save(contents: SecretsFile): void {\n // Refuse to write over a file this store could not parse. Every writer reaches here\n // through `load()`, so without this the first `set-password`/`set-token` after a bad\n // edit replaces the user's password hash, API token and credentials with the one field\n // being set. `runControlPlane` refuses at boot; this is the same rule for every command\n // that does not boot one.\n if (this.configError !== null)\n throw new Error(`refusing to write ${this.file}: ${this.error}`)\n\n const sealed = this.sealStored(this.inScope(contents))\n writeFileAtomic(this.file, `${JSON.stringify(sealed, null, 2)}\\n`, { mode: 0o600 })\n this.cache = sealed\n }\n\n /** Any write seals the entries still sitting in the clear, so the file never keeps both. */\n private sealStored(contents: SecretsFile): SecretsFile {\n const plain = Object.entries(contents.ddns)\n .filter((entry): entry is [string, PlainDdnsRecord] => isPlainDdns(entry[1]))\n if (plain.length === 0)\n return contents\n\n // Warned here rather than at startup: this is the moment credentials exist to protect, so a panel\n // with no DDNS accounts stays quiet. The condition and the message are asserted in the test.\n if (this.usingDefaultDdnsSecret && !this.warnedDefaultSecret) {\n this.warnedDefaultSecret = true\n logger.warn(`ddns: credentials are sealed under the built-in key — set HHOSTED_DDNS_SECRET to protect them if this state directory is ever copied or committed (docs/DDNS.md)`)\n }\n\n const kdf = contents.ddnsKdf ?? newDdnsKdf()\n const key = this.ddnsKey(kdf)\n const ddns = { ...contents.ddns }\n for (const [accountId, record] of plain)\n ddns[accountId] = sealDdns(accountId, { provider: record.provider, values: record.values }, key)\n return { ...contents, ddns, ddnsKdf: kdf }\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;AAWA,IAAM,OAAO;CAAE,GAAG;CAA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MAAM,IAAI,MAAM,qBAAqB,KAAK,KAAK,IAAI,KAAK,OAAO;EAEjE,MAAM,SAAS,KAAK,WAAW,KAAK,QAAQ,QAAQ,CAAC;EACrD,gBAAgB,KAAK,MAAM,GAAG,KAAK,UAAU,QAAQ,MAAM,CAAC,EAAE,KAAK,EAAE,MAAM,IAAM,CAAC;EAClF,KAAK,QAAQ;CACf;;CAGA,WAAmB,UAAoC;EACrD,MAAM,QAAQ,OAAO,QAAQ,SAAS,IAAI,CAAC,CACxC,QAAQ,UAA8C,YAAY,MAAM,EAAE,CAAC;EAC9E,IAAI,MAAM,WAAW,GACnB,OAAO;EAIT,IAAI,KAAK,0BAA0B,CAAC,KAAK,qBAAqB;GAC5D,KAAK,sBAAsB;GAC3B,OAAO,KAAK,kKAAkK;EAChL;EAEA,MAAM,MAAM,SAAS,WAAW,WAAW;EAC3C,MAAM,MAAM,KAAK,QAAQ,GAAG;EAC5B,MAAM,OAAO,EAAE,GAAG,SAAS,KAAK;EAChC,KAAK,MAAM,CAAC,WAAW,WAAW,OAChC,KAAK,aAAa,SAAS,WAAW;GAAE,UAAU,OAAO;GAAU,QAAQ,OAAO;EAAO,GAAG,GAAG;EACjG,OAAO;GAAE,GAAG;GAAU;GAAM,SAAS;EAAI;CAC3C;AACF"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"set-password-DegMumPh.js","names":["secretsPath"],"sources":["../../src/cli/set-password.ts"],"sourcesContent":["import process from 'node:process'\nimport { defineCommand } from 'citty'\nimport { dim, fail, green, promptHidden } from '#src/cli/io'\nimport { SecretsStore } from '#src/config/secrets'\nimport { globalSecretsPath as secretsPath } from '#src/helpers/paths'\n\n/** `set-password` sets the panel password without the API. */\n\nexport const setPasswordArgs = {\n clear: { type: 'boolean', description: 'remove the password, which disables authentication' },\n} as const\n\nexport async function runSetPassword(clear: boolean): Promise<void> {\n const store = new SecretsStore(secretsPath, undefined, 'global')\n\n if (clear) {\n store.clearPassword()\n process.stdout.write(`cleared the control panel password in ${secretsPath}\\n`)\n process.stdout.write(`${dim('authentication stays disabled until you enable it again in the settings page')}\\n`)\n return\n }\n\n const interactive = process.stdin.isTTY === true\n let password = process.env.HHOSTED_PASSWORD\n\n if (password === undefined && interactive) {\n password = await promptHidden('New control panel password: ')\n const again = await promptHidden('Repeat it: ')\n if (password !== again)\n fail('the passwords do not match')\n }\n\n if (password === undefined || password.length === 0) {\n fail('no password given: run interactively, or set HHOSTED_PASSWORD for a non-interactive run')\n }\n\n store.setPassword(password)\n process.stdout.write(`${green('password stored')} in ${secretsPath} (mode 0600)\\n`)\n if (password.length < 8)\n process.stdout.write(`${dim(`\"${password}\" is short — easy to guess if the panel is reachable beyond loopback`)}\\n`)\n process.stdout.write(`${dim('a running panel picks it up immediately, and every existing browser session is signed out')}\\n`)\n}\n\nexport const setPasswordCommand = defineCommand({\n meta: { name: 'set-password' },\n args: setPasswordArgs,\n run: async ({ args }) => {\n await runSetPassword(args.clear === true)\n },\n})\n"],"mappings":";;;;;;;AAQA,IAAa,kBAAkB,EAC7B,OAAO;CAAE,MAAM;CAAW,aAAa;AAAqD,EAC9F;AAEA,eAAsB,eAAe,OAA+B;CAClE,MAAM,QAAQ,IAAI,aAAaA,mBAAa,KAAA,GAAW,QAAQ;CAE/D,IAAI,OAAO;EACT,MAAM,cAAc;EACpB,QAAQ,OAAO,MAAM,yCAAyCA,kBAAY,GAAG;EAC7E,QAAQ,OAAO,MAAM,GAAG,IAAI,8EAA8E,EAAE,GAAG;EAC/G;CACF;CAEA,MAAM,cAAc,QAAQ,MAAM,UAAU;CAC5C,IAAI,WAAW,QAAQ,IAAI;CAE3B,IAAI,aAAa,KAAA,KAAa,aAAa;EACzC,WAAW,MAAM,aAAa,8BAA8B;EAC5D,MAAM,QAAQ,MAAM,aAAa,aAAa;EAC9C,IAAI,aAAa,OACf,KAAK,4BAA4B;CACrC;CAEA,IAAI,aAAa,KAAA,KAAa,SAAS,WAAW,GAChD,KAAK,yFAAyF;CAGhG,MAAM,YAAY,QAAQ;CAC1B,QAAQ,OAAO,MAAM,GAAG,MAAM,iBAAiB,EAAE,MAAMA,kBAAY,eAAe;CAClF,IAAI,SAAS,SAAS,GACpB,QAAQ,OAAO,MAAM,GAAG,IAAI,IAAI,SAAS,qEAAqE,EAAE,GAAG;CACrH,QAAQ,OAAO,MAAM,GAAG,IAAI,2FAA2F,EAAE,GAAG;AAC9H;AAEA,IAAa,qBAAqB,cAAc;CAC9C,MAAM,EAAE,MAAM,eAAe;CAC7B,MAAM;CACN,KAAK,OAAO,EAAE,WAAW;EACvB,MAAM,eAAe,KAAK,UAAU,IAAI;CAC1C;AACF,CAAC"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"set-token-21d1FTDC.js","names":["secretsPath"],"sources":["../../src/cli/set-token.ts"],"sourcesContent":["import process from 'node:process'\nimport { defineCommand } from 'citty'\nimport { bold, dim, fail, green, promptHidden } from '#src/cli/io'\nimport { generateApiToken, SecretsStore } from '#src/config/secrets'\nimport { globalSecretsPath as secretsPath } from '#src/helpers/paths'\n\n/** `set-token` sets the bearer credential scripts and agents use. */\n\nconst DEFAULT_PORT = 3999\n\nexport const setTokenArgs = {\n generate: { type: 'boolean', description: 'create a strong token and print it once' },\n clear: { type: 'boolean', description: 'remove the token, so it stops working' },\n} as const\n\nexport async function runSetToken(generate: boolean, clear: boolean): Promise<void> {\n if (generate && clear)\n fail('use either --generate or --clear, not both')\n\n const store = new SecretsStore(secretsPath, undefined, 'global')\n\n if (clear) {\n if (!store.apiTokenSet) {\n process.stdout.write('no API token is set — nothing to clear\\n')\n return\n }\n store.clearApiToken()\n process.stdout.write(`${green('API token cleared')} in ${secretsPath} — it stops working immediately\\n`)\n return\n }\n\n let token: string | null = process.env.HHOSTED_TOKEN ?? null\n if (generate)\n token = generateApiToken()\n else if (token === null && process.stdin.isTTY === true)\n token = await promptHidden('API token: ')\n if (token !== null)\n token = token.trim()\n if (token === null || token.length === 0) {\n fail('no token given: run `home-hosted set-token --generate`, set HHOSTED_TOKEN, or paste one interactively')\n }\n\n store.setApiToken(token)\n process.stdout.write(`${green(generate ? 'token generated' : 'token stored')} in ${secretsPath} (mode 0600)\\n`)\n if (generate) {\n process.stdout.write(` ${bold(token)}\\n`)\n process.stdout.write(`${dim(' shown once — only its SHA-256 is kept on disk, so copy it now')}\\n`)\n }\n else {\n process.stdout.write(`${dim(` stored as ${token.slice(0, 8)}… — the file keeps only its hash`)}\\n`)\n }\n\n const { readRuntime } = await import('#src/helpers/daemon')\n // Only the panel that owns *this* state directory is worth asking: guessing a\n // port would probe someone else's panel and call the mismatch a failure.\n const runtime = readRuntime()\n const base = (runtime?.url ?? `http://127.0.0.1:${DEFAULT_PORT}`).replace(/\\/+$/, '')\n\n if (runtime !== null) {\n const verified = await verifyToken(base, token)\n if (verified === true)\n process.stdout.write(`${dim(`verified: ${base}/api/auth/session accepted it`)}\\n`)\n else if (verified === false)\n process.stdout.write(`${dim(`the panel at ${base} did not accept it — is it running with this state directory?`)}\\n`)\n }\n\n process.stdout.write(`Use it from a script or an agent:\\n`)\n process.stdout.write(` ${bold(`curl -H \"Authorization: Bearer ${generate ? token : '<token>'}\" ${base}/api/state`)}\\n`)\n process.stdout.write(`${dim('It needs no restart and outlives sessions, and it holds the same access as a signed-in browser — except clearing the panel password, which a token may not do.')}\\n`)\n process.stdout.write(`${dim('Changing the password does NOT revoke it: `set-password` drops sessions and leaves the token working. Rotate with this command if it may have leaked.')}\\n`)\n process.stdout.write(`${dim('Remove it any time with: home-hosted set-token --clear')}\\n`)\n if (store.usingDefaultPassword)\n process.stdout.write(`${dim('The panel password is still the default — change it before the panel is reachable beyond loopback.')}\\n`)\n}\n\n/** Asks the live panel whether it accepts the token, without failing when it cannot. */\nasync function verifyToken(base: string, token: string): Promise<boolean | null> {\n // An https endpoint is usually TLS this project generated itself, which a plain\n // fetch refuses; the liveness probe in `helpers/daemon` is the one that knows how.\n if (!base.startsWith('http://'))\n return null\n try {\n const response = await fetch(`${base}/api/auth/session`, { headers: { authorization: `Bearer ${token}` } })\n if (!response.ok)\n return false\n const body = await response.json() as { authenticated?: boolean }\n return body.authenticated === true\n }\n catch {\n return null\n }\n}\n\nexport const setTokenCommand = defineCommand({\n meta: { name: 'set-token' },\n args: setTokenArgs,\n run: async ({ args }) => {\n await runSetToken(args.generate === true, args.clear === true)\n },\n})\n"],"mappings":";;;;;;;AAQA,IAAM,eAAe;AAErB,IAAa,eAAe;CAC1B,UAAU;EAAE,MAAM;EAAW,aAAa;CAA0C;CACpF,OAAO;EAAE,MAAM;EAAW,aAAa;CAAwC;AACjF;AAEA,eAAsB,YAAY,UAAmB,OAA+B;CAClF,IAAI,YAAY,OACd,KAAK,4CAA4C;CAEnD,MAAM,QAAQ,IAAI,aAAaA,mBAAa,KAAA,GAAW,QAAQ;CAE/D,IAAI,OAAO;EACT,IAAI,CAAC,MAAM,aAAa;GACtB,QAAQ,OAAO,MAAM,0CAA0C;GAC/D;EACF;EACA,MAAM,cAAc;EACpB,QAAQ,OAAO,MAAM,GAAG,MAAM,mBAAmB,EAAE,MAAMA,kBAAY,kCAAkC;EACvG;CACF;CAEA,IAAI,QAAuB,QAAQ,IAAI,iBAAiB;CACxD,IAAI,UACF,QAAQ,iBAAiB;MACtB,IAAI,UAAU,QAAQ,QAAQ,MAAM,UAAU,MACjD,QAAQ,MAAM,aAAa,aAAa;CAC1C,IAAI,UAAU,MACZ,QAAQ,MAAM,KAAK;CACrB,IAAI,UAAU,QAAQ,MAAM,WAAW,GACrC,KAAK,uGAAuG;CAG9G,MAAM,YAAY,KAAK;CACvB,QAAQ,OAAO,MAAM,GAAG,MAAM,WAAW,oBAAoB,cAAc,EAAE,MAAMA,kBAAY,eAAe;CAC9G,IAAI,UAAU;EACZ,QAAQ,OAAO,MAAM,KAAK,KAAK,KAAK,EAAE,GAAG;EACzC,QAAQ,OAAO,MAAM,GAAG,IAAI,iEAAiE,EAAE,GAAG;CACpG,OAEE,QAAQ,OAAO,MAAM,GA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AAK,OAAO,EAAE,WAAW;EACvB,MAAM,YAAY,KAAK,aAAa,MAAM,KAAK,UAAU,IAAI;CAC/D;AACF,CAAC"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"settings-BVSBnIwJ.js","names":[],"sources":["../../src/config/patch.ts","../../src/config/seed.ts","../../src/config/settings.ts"],"sourcesContent":["import { isRecord } from '#src/shared/shape'\n/** Nested groups a patch merges into instead of replacing. */\nexport const SERVER_MERGE_KEYS = new Set(['restart', 'health', 'stop'])\nexport const CONTROL_MERGE_KEYS = new Set(['auth', 'tls'])\n/** The general block merges key by key; `destinations` is a list a patch replaces. */\nexport const NOTIFICATION_MERGE_KEYS = new Set(['defaults'])\n/** The DDNS lists are replaced; only its two IP-family groups merge. */\nexport const DDNS_MERGE_KEYS = new Set(['ipv4', 'ipv6'])\n/** The proxy's one nested group; `routes` and `certificates` are lists a patch replaces. */\nexport const PROXY_MERGE_KEYS = new Set(['dns01'])\n/** Backups' scheduled half merges, so a patch sending only `intervalMs` keeps the retention. */\nexport const BACKUP_MERGE_KEYS = new Set(['schedule'])\nexport const EMPTY_MERGE_KEYS = new Set<string>()\n\nexport function applyPatch(target: Record<string, unknown>, patch: Record<string, unknown>, mergeKeys: Set<string>): void {\n for (const [key, value] of Object.entries(patch)) {\n if (value === undefined)\n continue\n if (mergeKeys.has(key) && isRecord(value) && isRecord(target[key])) {\n target[key] = mergeGroup(target[key], value)\n continue\n }\n // An explicit `null` **removes** the key, exactly as it does inside a group. Setting it instead made the\n // two paths disagree, and the stored `null` then failed the schema that reads the file:\n // `servers[0]: label must be a string (was null)`. This was reachable all along — `label` is not in\n // `SERVER_MERGE_KEYS`, so it took this branch.\n if (value === null) {\n delete target[key]\n continue\n }\n target[key] = value\n }\n}\n\n/**\n * Merges one nested group recursively — `health.http` is a group of its own, and\n * replacing it wholesale would silently reset the siblings a partial patch never\n * mentioned. An explicit `null` removes a key, which is how a schema-optional\n * field is cleared.\n */\nexport function mergeGroup(target: Record<string, unknown>, patch: Record<string, unknown>): Record<string, unknown> {\n const merged = { ...target }\n for (const [key, value] of Object.entries(patch)) {\n if (value === undefined)\n continue\n if (value === null) {\n delete merged[key]\n continue\n }\n if (isRecord(value) && isRecord(merged[key])) {\n merged[key] = mergeGroup(merged[key] as Record<string, unknown>, value)\n continue\n }\n merged[key] = value\n }\n return merged\n}\n","/**\n * Written when `$HHOSTED_HOME` has no state yet. Every seed stays empty of\n * servers on purpose: home-hosted ships none, so what a user supervises is\n * theirs to declare. The rest is default policy, which the settings pages can\n * change.\n */\n\n/** `$HHOSTED_HOME/.hh/settings.json`. */\nexport const SEED_GLOBAL_SETTINGS = {\n $schema: './settings.schema.json',\n control: {\n port: 3999,\n host: 'local',\n openBrowser: false,\n },\n} as const\n\n/** `$HHOSTED_HOME/.hh/<id>/settings.json`. */\nexport const SEED_WORKSPACE_SETTINGS = {\n $schema: './settings.schema.json',\n defaults: {\n enabled: true,\n autostart: false,\n bind: 'local',\n onPortConflict: 'block',\n },\n} as const\n\n/** `$HHOSTED_HOME/.hh/<id>/servers.config.json`. */\nexport const SEED_SERVERS_FILE = {\n $schema: './servers.config.schema.json',\n servers: [],\n} as const\n","import type { ResolvedGlobalConfig } from '#src/config/schema'\nimport type { BackupsConfig, ControlConfig, HostConfig, ProxyConfig, ProxyPatch, SettingsPatch } from '#src/shared/contracts'\nimport fs from 'node:fs'\nimport path from 'node:path'\nimport { type } from 'arktype'\nimport { planConfigMigrations, UNSTAMPED_SCHEMA } from '#src/config/migrations'\nimport { parseGlobalSettings, parseTolerant, stampConfig } from '#src/config/parse'\nimport { applyPatch, BACKUP_MERGE_KEYS, CONTROL_MERGE_KEYS, EMPTY_MERGE_KEYS, PROXY_MERGE_KEYS } from '#src/config/patch'\nimport { backupsSchema, controlSchema, globalSettingsSchema, hostSchema, proxyConfigSchema } from '#src/config/schema'\nimport { SEED_GLOBAL_SETTINGS } from '#src/config/seed'\nimport { writeFileAtomic } from '#src/helpers/atomic'\nimport { readStateFile } from '#src/helpers/config-text'\nimport { globalSettingsPath } from '#src/helpers/paths'\n\nexport class ConfigError extends Error {\n override name = 'ConfigError'\n /**\n * The *kind* of config problem, when a caller has to branch on it rather than just report it.\n * `UNKNOWN_SERVER` is the one case today: the servers route answers 404 for a missing id and 400\n * for an invalid patch, and it decided that by matching the message text.\n */\n readonly code: 'UNKNOWN_SERVER' | undefined\n\n constructor(message: string, code?: 'UNKNOWN_SERVER') {\n super(message)\n this.code = code\n }\n}\n\n/**\n * The panel-wide settings file (`$HHOSTED_HOME/.hh/settings.json`): the listener,\n * authentication, TLS policy, host vitals and backups. Nothing here belongs to a\n * workspace, which is why it sits above them.\n */\nexport class GlobalSettingsStore {\n private raw: Record<string, unknown> = {}\n /** The bytes behind the live settings, so a watcher can tell a real edit from our own write. */\n private lastText: string | null = null\n private resolvedConfig!: ResolvedGlobalConfig\n private error: string | null = null\n /** A JSON parse failure, kept apart from a schema problem so `apply()` cannot clear it. */\n private parseError: string | null = null\n private warnings: string[] = []\n private schemaVersion = UNSTAMPED_SCHEMA\n private readonly listeners = new Set<() => void>()\n\n constructor(private readonly file: string = globalSettingsPath, private readonly seed: Record<string, unknown> = SEED_GLOBAL_SETTINGS) {}\n\n get path(): string {\n return this.file\n }\n\n get config(): ResolvedGlobalConfig {\n return this.resolvedConfig\n }\n\n get control(): ControlConfig {\n return this.resolvedConfig.control\n }\n\n get host(): HostConfig {\n return this.resolvedConfig.host\n }\n\n get backups(): BackupsConfig {\n return this.resolvedConfig.backups\n }\n\n get proxy(): ProxyConfig {\n return this.resolvedConfig.proxy\n }\n\n get configError(): string | null {\n return this.error\n }\n\n /** Keys a newer release wrote that this one ignores; nothing to refuse over. */\n get configWarnings(): string[] {\n return [...this.warnings]\n }\n\n get configSchemaVersion(): number {\n return this.schemaVersion\n }\n\n /**\n * Steps that would have to run before this release could use the file.\n *\n * A file that cannot be **parsed** has no schema to plan from, and `migrate` refuses one it\n * cannot read rather than lifting it — so claiming a migration here sends the person to the one\n * command guaranteed not to help. Measured: a truncated `.hh/settings.json` made `up` say\n * \"needs 1 migration(s)\" and `migrate` answer \"cannot read … Unexpected end of JSON input\". The\n * workspace pair already excluded the parse failure (`WorkspaceStore.pendingMigrations`); this is\n * the same rule on the global file, which is the one the startup guard reads first.\n */\n get pendingMigrations() {\n if (this.parseError !== null)\n return []\n return planConfigMigrations(this.schemaVersion).steps\n }\n\n get rawConfig(): Record<string, unknown> {\n return structuredClone(this.raw)\n }\n\n onChange(listener: () => void): () => void {\n this.listeners.add(listener)\n return () => this.listeners.delete(listener)\n }\n\n load(): void {\n this.read()\n this.notify()\n }\n\n reloadFromDisk(): { changed: boolean, applied: boolean, error: string | null } {\n let text: string\n try {\n text = readStateFile(this.file)\n }\n catch {\n this.error = `${path.basename(this.file)} is gone`\n return { changed: false, applied: false, error: this.error }\n }\n\n if (text === this.lastText) {\n if (this.error !== null) {\n this.error = null\n this.load()\n }\n return { changed: false, applied: false, error: null }\n }\n\n const before = this.resolvedConfig\n this.load()\n return { changed: true, applied: this.resolvedConfig !== before, error: this.error }\n }\n\n private read(): void {\n // Cleared up front so both branches answer the same question: a file that reads cleanly now is\n // not still \"unparseable\" from the read before it.\n this.parseError = null\n if (!fs.existsSync(this.file)) {\n const seed = stampConfig(structuredClone(this.seed))\n const text = `${JSON.stringify(seed, null, 2)}\\n`\n writeFileAtomic(this.file, text)\n this.lastText = text\n this.raw = seed\n this.apply(seed)\n return\n }\n\n let text: string\n let parsed: unknown\n try {\n text = readStateFile(this.file)\n parsed = JSON.parse(text)\n }\n catch (error) {\n this.error = `cannot parse ${path.basename(this.file)}: ${(error as Error).message}`\n this.parseError = this.error\n if (this.resolvedConfig === undefined) {\n this.raw = {}\n this.resolvedConfig = this.resolveFallback()\n }\n return\n }\n\n this.lastText = text\n this.apply(parsed)\n }\n\n private notify(): void {\n for (const listener of this.listeners) listener()\n }\n\n updateControl(patch: NonNullable<SettingsPatch['control']>): ControlConfig {\n const draft = structuredClone(this.raw)\n draft.control = { ...(draft.control as Record<string, unknown> ?? {}) }\n applyPatch(draft.control as Record<string, unknown>, patch as Record<string, unknown>, CONTROL_MERGE_KEYS)\n\n const control = this.parseGroup<ControlConfig>(controlSchema as unknown as (input: unknown) => unknown, draft.control as Record<string, unknown>, 'control')\n\n this.commit(draft)\n return control\n }\n\n updateHost(patch: NonNullable<SettingsPatch['host']>): HostConfig {\n const draft = structuredClone(this.raw)\n draft.host = { ...(draft.host as Record<string, unknown> ?? {}) }\n applyPatch(draft.host as Record<string, unknown>, patch as Record<string, unknown>, EMPTY_MERGE_KEYS)\n\n const host = this.parseGroup<HostConfig>(hostSchema as unknown as (input: unknown) => unknown, draft.host as Record<string, unknown>, 'host')\n\n this.commit(draft)\n return host\n }\n\n updateBackups(patch: NonNullable<SettingsPatch['backups']>): BackupsConfig {\n const draft = structuredClone(this.raw)\n draft.backups = { ...(draft.backups as Record<string, unknown> ?? {}) }\n applyPatch(draft.backups as Record<string, unknown>, patch as Record<string, unknown>, BACKUP_MERGE_KEYS)\n\n const backups = this.parseGroup<BackupsConfig>(backupsSchema as unknown as (input: unknown) => unknown, draft.backups as Record<string, unknown>, 'backups')\n\n this.commit(draft)\n return backups\n }\n\n /** The reverse proxy. `routes` is a list a patch replaces; `dns01` merges key by key. */\n updateProxy(patch: ProxyPatch): ProxyConfig {\n const draft = structuredClone(this.raw)\n draft.proxy = { ...(draft.proxy as Record<string, unknown> ?? {}) }\n applyPatch(draft.proxy as Record<string, unknown>, patch as Record<string, unknown>, PROXY_MERGE_KEYS)\n\n const proxy = this.parseGroup<ProxyConfig>(proxyConfigSchema as unknown as (input: unknown) => unknown, draft.proxy as Record<string, unknown>, 'proxy')\n\n this.commit(draft)\n return proxy\n }\n\n /** Regenerates `settings.schema.json` for editor autocomplete, beside the file it describes. */\n writeJsonSchema(): void {\n const target = path.join(path.dirname(this.file), 'settings.schema.json')\n const schema = JSON.stringify(globalSettingsSchema.toJsonSchema(), null, 2)\n const current = fs.existsSync(target) ? fs.readFileSync(target, 'utf8') : null\n if (current !== schema)\n writeFileAtomic(target, schema)\n }\n\n private parseGroup<T>(schema: (input: unknown) => unknown, value: Record<string, unknown>, label: string): T {\n const parsed = parseTolerant(value, schema, label, [])\n if (parsed.error !== null)\n throw new ConfigError(`${label}: ${parsed.error}`)\n return parsed.value as T\n }\n\n private commit(draft: Record<string, unknown>): void {\n const stamped = stampConfig(draft)\n const text = `${JSON.stringify(stamped, null, 2)}\\n`\n writeFileAtomic(this.file, text)\n this.lastText = text\n this.raw = stamped\n this.apply(stamped)\n this.notify()\n }\n\n private resolveFallback(): ResolvedGlobalConfig {\n const control = controlSchema({})\n const host = hostSchema({})\n const backups = backupsSchema({})\n const proxy = proxyConfigSchema({})\n if (control instanceof type.errors || host instanceof type.errors || backups instanceof type.errors || proxy instanceof type.errors)\n throw new ConfigError('internal: default settings failed validation')\n return { control, host, backups, proxy }\n }\n\n private apply(raw: unknown): void {\n const parsed = parseGlobalSettings(raw)\n this.raw = structuredClone(raw as Record<string, unknown>)\n this.error = parsed.errors.length > 0 ? parsed.errors.join('; ') : null\n this.schemaVersion = parsed.schemaVersion\n this.warnings = [\n ...parsed.warnings,\n ...(parsed.unknownKeys.length === 0\n ? []\n : [`${path.basename(this.file)} carries ${parsed.unknownKeys.length} unrecognized key(s) this release ignores: ${parsed.unknownKeys.join(', ')}`]),\n ]\n if (parsed.config !== null)\n this.resolvedConfig = parsed.config\n else if (this.resolvedConfig === undefined)\n this.resolvedConfig = this.resolveFallback()\n }\n}\n"],"mappings":";;;;;;;;;;;;;AAEA,IAAa,oCAAoB,IAAI,IAAI;CAAC;CAAW;CAAU;AAAM,CAAC;AACtE,IAAa,qCAAqB,IAAI,IAAI,CAAC,QAAQ,KAAK,CAAC;;AAEzD,IAAa,0CAA0B,IAAI,IAAI,CAAC,UAAU,CAAC;;AAE3D,IAAa,kCAAkB,IAAI,IAAI,CAAC,QAAQ,MAAM,CAAC;;AAEvD,IAAa,mCAAmB,IAAI,IAAI,CAAC,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ChB;CAEA,OAAe,OAAsC;EACnD,MAAM,UAAU,YAAY,KAAK;EACjC,MAAM,OAAO,GAAG,KAAK,UAAU,SAAS,MAAM,CAAC,EAAE;EACjD,gBAAgB,KAAK,MAAM,IAAI;EAC/B,KAAK,WAAW;EAChB,KAAK,MAAM;EACX,KAAK,MAAM,OAAO;EAClB,KAAK,OAAO;CACd;CAEA,kBAAgD;EAC9C,MAAM,UAAU,cAAc,CAAC,CAAC;EAChC,MAAM,OAAO,WAAW,CAAC,CAAC;EAC1B,MAAM,UAAU,cAAc,CAAC,CAAC;EAChC,MAAM,QAAQ,kBAAkB,CAAC,CAAC;EAClC,IAAI,mBAAmB,KAAK,UAAU,gBAAgB,KAAK,UAAU,mBAAmB,KAAK,UAAU,iBAAiB,KAAK,QAC3H,MAAM,IAAI,YAAY,8CAA8C;EACtE,OAAO;GAAE;GAAS;GAAM;GAAS;EAAM;CACzC;CAEA,MAAc,KAAoB;EAChC,MAAM,SAAS,oBAAoB,GAAG;EACtC,KAAK,MAAM,gBAAgB,GAA8B;EACzD,KAAK,QAAQ,OAAO,OAAO,SAAS,IAAI,OAAO,OAAO,KAAK,IAAI,IAAI;EACnE,KAAK,gBAAgB,OAAO;EAC5B,KAAK,WAAW,CACd,GAAG,OAAO,UACV,GAAI,OAAO,YAAY,WAAW,IAC9B,CAAC,IACD,CAAC,GAAG,KAAK,SAAS,KAAK,IAAI,EAAE,WAAW,OAAO,YAAY,OAAO,6CAA6C,OAAO,YAAY,KAAK,IAAI,GAAG,CACpJ;EACA,IAAI,OAAO,WAAW,MACpB,KAAK,iBAAiB,OAAO;OAC1B,IAAI,KAAK,mBAAmB,KAAA,GAC/B,KAAK,iBAAiB,KAAK,gBAAgB;CAC/C;AACF"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"setup-temp-XiuAtiW2.js","names":[],"sources":["../../src/cli/setup-temp.ts"],"sourcesContent":["import fs from 'node:fs'\nimport process from 'node:process'\nimport { defineCommand } from 'citty'\nimport { bold, dim, fail, green, prompt } from '#src/cli/io'\nimport { GlobalSettingsStore } from '#src/config/settings'\nimport { globalSettingsPath } from '#src/helpers/paths'\nimport { installLibreHardwareMonitor, lhmDirectoryWindows, lhmInstalled, probeWslTemperature, removeWslTemperatureScript, tempCommandFor, windowsScriptPath, writeWslTemperatureScript, wslScriptPath } from '#src/providers/wsl-temperature'\n\n/**\n * `setup-temp` — teach the panel how to read this machine's CPU temperature.\n *\n * `--wsl` is one *source*; the next bridge is another flag beside it, not a second command.\n */\n\nexport const setupTempArgs = {\n wsl: { type: 'boolean', description: 'read the temperature through the Windows host (WSL2)', default: false },\n clear: { type: 'boolean', description: 'stop using a configured command and delete its helper', default: false },\n // No `default`: citty leaves it `undefined` when absent and `false` for `--no-download`, which is\n // what lets one flag express the three outcomes — ask, install, refuse — instead of needing a\n // second flag to say \"no\".\n download: { type: 'boolean', description: 'download LibreHardwareMonitor without asking; --no-download never does (for a script)' },\n} as const\n\n/** The temperature sources `setup-temp` can install. One today; a flag each as more appear. */\nexport type TemperatureSource = 'wsl'\n\n/** Which source a flag names, or null when the invocation asks for no change. */\nexport function sourceFromFlags(flags: { wsl?: boolean, clear?: boolean }): TemperatureSource | null {\n if (flags.clear === true)\n return null\n if (flags.wsl === true)\n return 'wsl'\n return null\n}\n\n/**\n * The refusal for a flag set that cannot mean what it says, or `null`.\n *\n * `download` is a **modifier of `--wsl`**, not a command of its own: only the WSL2 branch fetches\n * anything, and the no-flag branch ends before a source is chosen. Left unreachable it was silently\n * dropped — `setup-temp --download` exited 0 having done nothing, which a script reads as\n * \"installed\" — so the flag is refused instead, naming the one it belongs to.\n *\n * `--clear` is the opposite request, so pairing it with either is refused rather than letting one\n * quietly win.\n */\nexport function flagProblem(flags: { wsl?: boolean, clear?: boolean, download?: boolean }): string | null {\n const download = flags.download === undefined ? null : flags.download === true ? '--download' : '--no-download'\n if (flags.clear === true) {\n if (download !== null)\n return `\\`--clear\\` and \\`${download}\\` ask for opposite things — clear the source, or set one up, not both`\n if (flags.wsl === true)\n return '`--clear` and `--wsl` ask for opposite things — clear the source, or set one up, not both'\n return null\n }\n if (download !== null && flags.wsl !== true)\n return `\\`${download}\\` only means something with \\`--wsl\\` — pass \\`setup-temp --wsl ${download}\\`, or drop it to read the state`\n return null\n}\n\nexport async function runSetupTemp(flags: { wsl?: boolean, clear?: boolean, download?: boolean }): Promise<void> {\n // Before any read: a flag this command cannot honour is a mistake in the invocation, not a\n // property of the machine's config.\n const problem = flagProblem(flags)\n if (problem !== null)\n fail(problem)\n\n const store = new GlobalSettingsStore(globalSettingsPath)\n store.load()\n const host = store.host\n const configured = host.tempCommand.trim().length > 0\n\n if (flags.clear === true) {\n // `--clear` promises to delete the helper as well as the setting, and it used to clear the\n // command only: measured, the file outlived every `--clear`. A stale helper is also the one\n // thing left when the command is already empty, so it is removed on both paths.\n const helper = wslScriptPath()\n const hadHelper = helper !== null && fs.existsSync(helper)\n if (configured)\n store.updateHost({ tempCommand: '' })\n removeWslTemperatureScript(helper)\n if (!configured && !hadHelper) {\n process.stdout.write('no temperature command is set — nothing to clear\\n')\n return\n }\n if (!configured) {\n process.stdout.write(`no temperature command is set — removed the leftover helper at ${dim(helper!)}\\n`)\n return\n }\n process.stdout.write(`${green('temperature command cleared')} — the tile uses the built-in probe again\\n`)\n if (hadHelper)\n process.stdout.write(` ${dim(`helper ${helper!} deleted`)}\\n`)\n return\n }\n\n const source = sourceFromFlags(flags)\n if (source === null) {\n // No flag: say what is going on, so this is the one command a confused person types.\n if (configured) {\n process.stdout.write(`${green('a temperature command is set')}: ${bold(host.tempCommand)}\\n`)\n const probe = await probeWslTemperature(host.tempCommand, host.tempCommandTimeoutMs)\n process.stdout.write(probe.celsius === null\n ? ` ${dim(`it did not answer: ${probe.error ?? 'unknown reason'}`)}\\n`\n : ` last reading: ${green(`${probe.celsius}°C`)}\\n`)\n return\n }\n process.stdout.write('the panel reads the temperature from the kernel when the machine exposes a sensor.\\n')\n process.stdout.write(`this machine: ${host.tempCelsius > 0 ? `threshold ${host.tempCelsius}°C` : 'no temperature alert'}\\n`)\n process.stdout.write(`\\n${dim('if the Host vitals tile says n/a, set a source up:')}\\n`)\n process.stdout.write(` ${bold('setup-temp --wsl')} read it through the Windows host (WSL2)\\n`)\n return\n }\n\n if (source === 'wsl') {\n const { isWsl } = await import('#src/providers/wsl-temperature')\n if (!isWsl()) {\n fail('--wsl is for a WSL2 guest, and this is not one. Run `setup-temp` with no flag to see the options')\n }\n const scriptPath = wslScriptPath()\n if (scriptPath === null) {\n fail('the Windows drive is not mounted, so the helper cannot be written where powershell.exe can read it')\n }\n // The helper only prints a number; the sensor comes from LibreHardwareMonitor, a third-party\n // Windows binary the panel does not ship. Offer to fetch it — someone who just typed this\n // command has no way to know a library is missing, and the tile only ever says `n/a`.\n if (!lhmInstalled())\n await offerLibreHardwareMonitor(flags)\n\n writeWslTemperatureScript(scriptPath)\n const command = tempCommandFor(scriptPath)\n process.stdout.write(` helper ${dim(`${scriptPath} (${windowsScriptPath(scriptPath)} on Windows)`)}\\n`)\n\n // Probe **before** saving. A command that cannot work must not reach the config: the panel would\n // run a failing PowerShell on every sample, and the tile would stay `n/a` while the settings page\n // claimed a source was configured — the one state a person has no way to diagnose.\n const probe = await probeWslTemperature(command, 5000)\n if (probe.celsius === null) {\n // One refusal, whole, on stderr. It used to be built as `${fail('not set up')} — …`, and\n // `fail()` exits before the template is finished, so the reason the probe gave was lost.\n fail(`not set up — the helper did not answer: ${probe.error ?? 'unknown reason'}\\n the script is at ${scriptPath}; the config was left unchanged`)\n }\n\n store.updateHost({ tempCommand: command, tempCommandTimeoutMs: 5000 })\n process.stdout.write(`${green('WSL temperature bridge set up')}\\n`)\n process.stdout.write(` command ${bold(command)}\\n`)\n process.stdout.write(` reading ${green(`${probe.celsius}°C`)}\\n`)\n }\n}\n\n/**\n * Offer the ~6 MB download. A prompt, never a silent fetch: installing software nobody asked for is\n * not a setup command's job, and a non-interactive stdin answers no.\n */\nasync function offerLibreHardwareMonitor(flags: { download?: boolean }): Promise<void> {\n const where = lhmDirectoryWindows() ?? 'C:\\\\ProgramData\\\\home-hosted\\\\LibreHardwareMonitor'\n\n // `undefined` (absent): ask. `true` (`--download`): install. `false` (`--no-download`): refuse.\n if (flags.download !== true) {\n if (flags.download === false) {\n process.stdout.write(`${dim(`LibreHardwareMonitor is not installed; install it into ${where}, or pass --download`)}\\n`)\n return\n }\n const answer = await prompt(`LibreHardwareMonitor is required to read the sensor. Download it now (~6 MB)? [y/N] `)\n if (!/^y(?:es)?$/i.test(answer.trim())) {\n process.stdout.write(`${dim(`left it alone — install it into ${where} and re-run this command`)}\\n`)\n return\n }\n }\n\n const result = await installLibreHardwareMonitor({ onProgress: message => process.stdout.write(` ${dim(message)}\\n`) })\n if (result.error !== null)\n fail(`the download did not install — ${result.error}`)\n process.stdout.write(` library ${green('installed')} in ${result.dir}\\n`)\n}\n\nexport const setupTempCommand = defineCommand({\n meta: { name: 'setup-temp' },\n args: setupTempArgs,\n async run({ args }) {\n await runSetupTemp({ wsl: args.wsl === true, clear: args.clear === true, download: args.download })\n },\n})\n"],"mappings":";;;;;;;;;;;;;AAcA,IAAa,gBAAgB;CAC3B,KAAK;EAAE,MAAM;EAAW,aAAa;EAAwD,SAAS;CAAM;CAC5G,OAAO;EAAE,MAAM;EAAW,aAAa;EAAyD,SAAS;CAAM;CAI/G,UAAU;EAAE,MAAM;EAAW,aAAa;CAAwF;AACpI;;AAMA,SAAgB,gBAAgB,OAAqE;CACnG,IAAI,MAAM,UAAU,MAClB,OAAO;CACT,IAAI,MAAM,QAAQ,MAChB,OAAO;CACT,OAAO;AACT;;;;;;;;;;;;AAaA,SAAgB,YAAY,OAA8E;CACxG,MAAM,WAAW,MAAM,aAAa,KAAA,IAAY,OAAO,MAAM,aAAa,OAAO,eAAe;CAChG,IAAI,MAAM,UAAU,MAAM;EACxB,IAAI,aAAa,MACf,OAAO,qBAAqB,SAAS;EACvC,IAAI,MAAM,QAAQ,MAChB,OAAO;E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