home-hosted 0.12.0 → 0.13.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (221) hide show
  1. package/README.md +95 -49
  2. package/dist/chunks/{archive-DpCwA8Nf.js → archive-DP-XQR8X.js} +15 -2
  3. package/dist/chunks/archive-DP-XQR8X.js.map +1 -0
  4. package/dist/chunks/{atomic-CEfCUfkQ.js → atomic-C1PfJpE7.js} +3 -2
  5. package/dist/chunks/atomic-C1PfJpE7.js.map +1 -0
  6. package/dist/chunks/{backup-CPrJVPJI.js → backup-CZcVca2a.js} +101 -76
  7. package/dist/chunks/backup-CZcVca2a.js.map +1 -0
  8. package/dist/chunks/{backups-Bd2SF2qd.js → backups-CFRaWe_m.js} +881 -536
  9. package/dist/chunks/backups-CFRaWe_m.js.map +1 -0
  10. package/dist/chunks/{contracts-ku5ypHXJ.js → contracts-CMBD1TF9.js} +381 -407
  11. package/dist/chunks/contracts-CMBD1TF9.js.map +1 -0
  12. package/dist/chunks/{daemon-TwXk5vb8.js → daemon-qKVECISl.js} +52 -20
  13. package/dist/chunks/daemon-qKVECISl.js.map +1 -0
  14. package/dist/chunks/{docker-CGv4Uv7w.js → docker-Cy9Lyvda.js} +4 -3
  15. package/dist/chunks/docker-Cy9Lyvda.js.map +1 -0
  16. package/dist/chunks/{down-BlX5X3bm.js → down-pKbGCW9d.js} +22 -17
  17. package/dist/chunks/down-pKbGCW9d.js.map +1 -0
  18. package/dist/chunks/{init-DdmqHVra.js → init-BZ7hK9Vf.js} +19 -6
  19. package/dist/chunks/init-BZ7hK9Vf.js.map +1 -0
  20. package/dist/chunks/{last-stop-BZ08Z89-.js → last-stop-C-BXz_XI.js} +6 -5
  21. package/dist/chunks/last-stop-C-BXz_XI.js.map +1 -0
  22. package/dist/chunks/{layout-D74TGUnr.js → layout-DwTtmund.js} +2 -2
  23. package/dist/chunks/{layout-D74TGUnr.js.map → layout-DwTtmund.js.map} +1 -1
  24. package/dist/chunks/lazy-Ce5zEAq1.js +66 -0
  25. package/dist/chunks/lazy-Ce5zEAq1.js.map +1 -0
  26. package/dist/chunks/{log-buffer-HnP0jKhZ.js → log-buffer-Dy9HHDMD.js} +114 -50
  27. package/dist/chunks/log-buffer-Dy9HHDMD.js.map +1 -0
  28. package/dist/chunks/{logs-gI_69Q1P.js → logs---TI_bxM.js} +23 -21
  29. package/dist/chunks/logs---TI_bxM.js.map +1 -0
  30. package/dist/chunks/{migrate-BTlsibvF.js → migrate-Cfoq-Vgh.js} +5 -5
  31. package/dist/chunks/{migrate-BTlsibvF.js.map → migrate-Cfoq-Vgh.js.map} +1 -1
  32. package/dist/chunks/{nanny-CjnnrIpm.js → nanny-B-Eu0sFW.js} +3 -3
  33. package/dist/chunks/{nanny-CjnnrIpm.js.map → nanny-B-Eu0sFW.js.map} +1 -1
  34. package/dist/chunks/{nanny-20aBXL1o.js → nanny-BtWfy0QH.js} +121 -23
  35. package/dist/chunks/nanny-BtWfy0QH.js.map +1 -0
  36. package/dist/chunks/{nanny-DUaAfCV-.js → nanny-ChMtq1Zl.js} +3 -3
  37. package/dist/chunks/{nanny-DUaAfCV-.js.map → nanny-ChMtq1Zl.js.map} +1 -1
  38. package/dist/chunks/{nanny-sweep-Ca9kPAVi.js → nanny-sweep-DErnlPY1.js} +5 -4
  39. package/dist/chunks/nanny-sweep-DErnlPY1.js.map +1 -0
  40. package/dist/chunks/{parse-B9owE47G.js → parse-DhmG26fI.js} +4 -4
  41. package/dist/chunks/{parse-B9owE47G.js.map → parse-DhmG26fI.js.map} +1 -1
  42. package/dist/chunks/{paths-BT94q6-w.js → paths-CGlGDrOU.js} +36 -2
  43. package/dist/chunks/paths-CGlGDrOU.js.map +1 -0
  44. package/dist/chunks/{restart-UZgeDukG.js → restart-Des4DrAN.js} +25 -59
  45. package/dist/chunks/restart-Des4DrAN.js.map +1 -0
  46. package/dist/chunks/{schema-o7Lgk0V1.js → schema-B240VXcV.js} +11 -10
  47. package/dist/chunks/schema-B240VXcV.js.map +1 -0
  48. package/dist/chunks/{secrets-D7PdYh71.js → secrets-BieELnZh.js} +22 -4
  49. package/dist/chunks/secrets-BieELnZh.js.map +1 -0
  50. package/dist/chunks/{server-BuIeSsRu.js → server-Bge2r2qQ.js} +3 -3
  51. package/dist/chunks/{server-BuIeSsRu.js.map → server-Bge2r2qQ.js.map} +1 -1
  52. package/dist/chunks/{set-password-DegMumPh.js → set-password-D5vZqqSX.js} +7 -7
  53. package/dist/chunks/set-password-D5vZqqSX.js.map +1 -0
  54. package/dist/chunks/{set-token-21d1FTDC.js → set-token-obPiEJYk.js} +7 -7
  55. package/dist/chunks/set-token-obPiEJYk.js.map +1 -0
  56. package/dist/chunks/{settings-BVSBnIwJ.js → settings-xu-XTfWg.js} +126 -35
  57. package/dist/chunks/settings-xu-XTfWg.js.map +1 -0
  58. package/dist/chunks/{setup-temp-XiuAtiW2.js → setup-temp-CAN4_bA-.js} +6 -6
  59. package/dist/chunks/setup-temp-CAN4_bA-.js.map +1 -0
  60. package/dist/chunks/{src-BL97vLVb.js → src-BtWMFmzZ.js} +2246 -1061
  61. package/dist/chunks/src-BtWMFmzZ.js.map +1 -0
  62. package/dist/chunks/{status-EuWdRq8Q.js → status-DT1EsA-B.js} +12 -8
  63. package/dist/chunks/status-DT1EsA-B.js.map +1 -0
  64. package/dist/chunks/{ui-DbPuwddJ.js → ui-D562aqw5.js} +9 -7
  65. package/dist/chunks/ui-D562aqw5.js.map +1 -0
  66. package/dist/chunks/{ui-revert-BhqOAhmM.js → ui-revert-EkBBwRTt.js} +3 -3
  67. package/dist/chunks/{ui-revert-BhqOAhmM.js.map → ui-revert-EkBBwRTt.js.map} +1 -1
  68. package/dist/chunks/{ui-switch-CMoslPO2.js → ui-switch-BnZTdMDd.js} +3 -3
  69. package/dist/chunks/{ui-switch-CMoslPO2.js.map → ui-switch-BnZTdMDd.js.map} +1 -1
  70. package/dist/chunks/{ui-update-TTBBoDik.js → ui-update-_xryLYxw.js} +5 -5
  71. package/dist/chunks/{ui-update-TTBBoDik.js.map → ui-update-_xryLYxw.js.map} +1 -1
  72. package/dist/chunks/{up-C4H13hBw.js → up-Pdz-l6IH.js} +25 -11
  73. package/dist/chunks/up-Pdz-l6IH.js.map +1 -0
  74. package/dist/chunks/{usage-CSBgLRN5.js → usage-DFrCVXpT.js} +29 -3
  75. package/dist/chunks/usage-DFrCVXpT.js.map +1 -0
  76. package/dist/chunks/{workspaces-CAln2sQ7.js → workspaces-DYcfvKV_.js} +16 -8
  77. package/dist/chunks/workspaces-DYcfvKV_.js.map +1 -0
  78. package/dist/chunks/wsl-temperature-BiCI4iK6.js.map +1 -1
  79. package/dist/cli.js +80 -70
  80. package/dist/cli.js.map +1 -1
  81. package/dist/client.js +25 -1
  82. package/dist/client.js.map +1 -1
  83. package/dist/types/api/backups.d.ts +8 -3
  84. package/dist/types/api/control.d.ts +4 -3
  85. package/dist/types/api/events.d.ts +2 -1
  86. package/dist/types/api/health.d.ts +1 -0
  87. package/dist/types/api/metrics.d.ts +3 -1
  88. package/dist/types/api/settings.d.ts +2 -2
  89. package/dist/types/api/state.d.ts +8 -2
  90. package/dist/types/app.d.ts +26 -11
  91. package/dist/types/cli/backup.d.ts +7 -0
  92. package/dist/types/cli/down.d.ts +5 -0
  93. package/dist/types/cli/logs.d.ts +14 -2
  94. package/dist/types/cli/restart.d.ts +0 -1
  95. package/dist/types/cli/set-password.d.ts +2 -2
  96. package/dist/types/cli/up.d.ts +8 -2
  97. package/dist/types/client.d.ts +5618 -11
  98. package/dist/types/config/secrets.d.ts +2 -0
  99. package/dist/types/config/settings.d.ts +54 -8
  100. package/dist/types/config/store.d.ts +16 -3
  101. package/dist/types/config/workspaces.d.ts +4 -1
  102. package/dist/types/helpers/copy-tree.d.ts +5 -0
  103. package/dist/types/helpers/daemon.d.ts +20 -7
  104. package/dist/types/helpers/error.d.ts +8 -0
  105. package/dist/types/helpers/event-stream.d.ts +21 -0
  106. package/dist/types/helpers/openapi.d.ts +12 -24
  107. package/dist/types/helpers/paths.d.ts +18 -0
  108. package/dist/types/helpers/utf8-chunks.d.ts +15 -0
  109. package/dist/types/middleware/auth.d.ts +19 -3
  110. package/dist/types/providers/host.d.ts +1 -1
  111. package/dist/types/providers/log-tail.d.ts +27 -0
  112. package/dist/types/providers/nanny-sweep.d.ts +3 -0
  113. package/dist/types/providers/nanny.d.ts +10 -0
  114. package/dist/types/providers/proc.d.ts +9 -0
  115. package/dist/types/providers/process.d.ts +17 -0
  116. package/dist/types/providers/telegram.d.ts +45 -3
  117. package/dist/types/providers/wsl-temperature.d.ts +0 -4
  118. package/dist/types/services/auth.d.ts +36 -4
  119. package/dist/types/services/backups.d.ts +125 -1
  120. package/dist/types/services/ddns.d.ts +5 -0
  121. package/dist/types/services/exposure.d.ts +54 -1
  122. package/dist/types/services/history.d.ts +1 -0
  123. package/dist/types/services/host-monitor.d.ts +1 -0
  124. package/dist/types/services/log-buffer.d.ts +11 -0
  125. package/dist/types/services/log-files.d.ts +1 -11
  126. package/dist/types/services/log-relay.d.ts +0 -1
  127. package/dist/types/services/panel.d.ts +19 -0
  128. package/dist/types/services/proxy-certificates/certificates.d.ts +116 -0
  129. package/dist/types/services/proxy.d.ts +46 -69
  130. package/dist/types/services/state.d.ts +0 -3
  131. package/dist/types/services/supervisor/entry.d.ts +10 -0
  132. package/dist/types/services/supervisor/health.d.ts +3 -2
  133. package/dist/types/services/supervisor/output.d.ts +126 -0
  134. package/dist/types/services/supervisor/persistent.d.ts +4 -1
  135. package/dist/types/services/supervisor/records.d.ts +81 -1
  136. package/dist/types/services/supervisor.d.ts +32 -0
  137. package/dist/types/shared/action-outcome.d.ts +25 -0
  138. package/dist/types/shared/api-client.d.ts +218 -4
  139. package/dist/types/shared/backup-scope.d.ts +58 -0
  140. package/dist/types/shared/contracts.d.ts +142 -200
  141. package/dist/types/shared/ddns-form.d.ts +13 -0
  142. package/dist/types/shared/form-repair.d.ts +6 -0
  143. package/dist/types/shared/lazy.d.ts +4 -0
  144. package/dist/types/shared/live-frames.d.ts +22 -0
  145. package/dist/types/shared/live-series.d.ts +21 -0
  146. package/dist/types/shared/live-store.d.ts +72 -0
  147. package/dist/types/shared/patch-diff.d.ts +13 -2
  148. package/dist/types/shared/proxy-form.d.ts +2 -0
  149. package/dist/types/shared/server-form.d.ts +121 -0
  150. package/dist/types/shared/stream-access.d.ts +20 -0
  151. package/docs/API.md +45 -16
  152. package/docs/BACKUPS.md +31 -11
  153. package/docs/CLI.md +34 -61
  154. package/docs/DDNS.md +3 -1
  155. package/docs/NOTIFICATIONS.md +7 -1
  156. package/docs/REVERSE_PROXY.md +7 -1
  157. package/docs/SECURITY.md +21 -10
  158. package/docs/SERVERS.md +102 -23
  159. package/docs/UI_CREATION.md +10 -1
  160. package/docs/demo/blank-host-restore.sh +4 -3
  161. package/package.json +5 -7
  162. package/uis/stock/dist/assets/CopyButton-BUBKRJyY.js +1 -0
  163. package/uis/stock/dist/assets/GlobalSettingsView-yYMcRWvt.js +1 -0
  164. package/uis/stock/dist/assets/LogViewer-DIliXy62.js +1 -0
  165. package/uis/stock/dist/assets/LogsView-B7Z-7RNg.js +1 -0
  166. package/uis/stock/dist/assets/Modal-DmKa5Qpp.js +39 -0
  167. package/uis/stock/dist/assets/ProxyView-DvZiNkwb.js +1 -0
  168. package/uis/stock/dist/assets/ServerDetailView-6idGT_EX.js +2 -0
  169. package/uis/stock/dist/assets/SettingsShell-CeGtleYI.js +1 -0
  170. package/uis/stock/dist/assets/SettingsView-BrhJIrmk.js +2 -0
  171. package/uis/stock/dist/assets/de-BRITeb0H.js +1 -0
  172. package/uis/stock/dist/assets/es-B2zIEssV.js +1 -0
  173. package/uis/stock/dist/assets/fr-s0ZOBEqh.js +1 -0
  174. package/uis/stock/dist/assets/index-C1MehbKy.css +2 -0
  175. package/uis/stock/dist/assets/index-CnBN54wF.js +15 -0
  176. package/uis/stock/dist/assets/ja-CU7MR85V.js +1 -0
  177. package/uis/stock/dist/assets/ko-tL5Me6d-.js +1 -0
  178. package/uis/stock/dist/assets/ru-92yrvkNJ.js +1 -0
  179. package/uis/stock/dist/assets/vi-CzvY16k2.js +1 -0
  180. package/uis/stock/dist/assets/zh-CN-DDwFW_uW.js +1 -0
  181. package/uis/stock/dist/index.html +3 -2
  182. package/uis/stock/dist/ui.json +3 -3
  183. package/dist/chunks/archive-DpCwA8Nf.js.map +0 -1
  184. package/dist/chunks/atomic-CEfCUfkQ.js.map +0 -1
  185. package/dist/chunks/backup-CPrJVPJI.js.map +0 -1
  186. package/dist/chunks/backups-Bd2SF2qd.js.map +0 -1
  187. package/dist/chunks/contracts-ku5ypHXJ.js.map +0 -1
  188. package/dist/chunks/daemon-TwXk5vb8.js.map +0 -1
  189. package/dist/chunks/docker-CGv4Uv7w.js.map +0 -1
  190. package/dist/chunks/down-BlX5X3bm.js.map +0 -1
  191. package/dist/chunks/init-DdmqHVra.js.map +0 -1
  192. package/dist/chunks/last-stop-BZ08Z89-.js.map +0 -1
  193. package/dist/chunks/log-buffer-HnP0jKhZ.js.map +0 -1
  194. package/dist/chunks/logs-gI_69Q1P.js.map +0 -1
  195. package/dist/chunks/nanny-20aBXL1o.js.map +0 -1
  196. package/dist/chunks/nanny-sweep-Ca9kPAVi.js.map +0 -1
  197. package/dist/chunks/paths-BT94q6-w.js.map +0 -1
  198. package/dist/chunks/restart-UZgeDukG.js.map +0 -1
  199. package/dist/chunks/schema-o7Lgk0V1.js.map +0 -1
  200. package/dist/chunks/secrets-D7PdYh71.js.map +0 -1
  201. package/dist/chunks/set-password-DegMumPh.js.map +0 -1
  202. package/dist/chunks/set-token-21d1FTDC.js.map +0 -1
  203. package/dist/chunks/settings-BVSBnIwJ.js.map +0 -1
  204. package/dist/chunks/setup-temp-XiuAtiW2.js.map +0 -1
  205. package/dist/chunks/src-BL97vLVb.js.map +0 -1
  206. package/dist/chunks/status-EuWdRq8Q.js.map +0 -1
  207. package/dist/chunks/ui-DbPuwddJ.js.map +0 -1
  208. package/dist/chunks/up-C4H13hBw.js.map +0 -1
  209. package/dist/chunks/usage-CSBgLRN5.js.map +0 -1
  210. package/dist/chunks/workspaces-CAln2sQ7.js.map +0 -1
  211. package/docs/RESTORE_DEMO.md +0 -306
  212. package/uis/stock/dist/assets/de-DyGrM1KK.js +0 -1
  213. package/uis/stock/dist/assets/es-BebHdc0E.js +0 -1
  214. package/uis/stock/dist/assets/fr-DsDTrxhI.js +0 -1
  215. package/uis/stock/dist/assets/index-6LANO2Ua.css +0 -2
  216. package/uis/stock/dist/assets/index-D06cUZbM.js +0 -56
  217. package/uis/stock/dist/assets/ja-D3RARJjW.js +0 -1
  218. package/uis/stock/dist/assets/ko-CKI3dFoD.js +0 -1
  219. package/uis/stock/dist/assets/ru-DEU5ujXt.js +0 -1
  220. package/uis/stock/dist/assets/vi-ULKPnasj.js +0 -1
  221. package/uis/stock/dist/assets/zh-CN-tCvnOxWy.js +0 -1
@@ -1 +0,0 @@
1
- {"version":3,"file":"src-BL97vLVb.js","names":["standardValidator","idParam","GrammyBot","escapeHtml","idParam"],"sources":["../../src/helpers/factory.ts","../../src/middleware/loopback.ts","../../src/api/acme.ts","../../src/helpers/cookies.ts","../../src/helpers/openapi.ts","../../src/helpers/validator.ts","../../src/services/auth.ts","../../src/middleware/auth.ts","../../src/services/exposure.ts","../../src/api/auth/$.routes.ts","../../src/helpers/validate.ts","../../src/api/backups.ts","../../src/helpers/action-result.ts","../../src/helpers/deferred.ts","../../src/helpers/secret-compare.ts","../../src/helpers/workspace.ts","../../src/api/control.ts","../../src/api/ddns.ts","../../src/helpers/sse.ts","../../src/shared/server-key.ts","../../src/services/events.ts","../../src/api/events.ts","../../src/shared/server-attention.ts","../../src/api/health.ts","../../src/api/logs.ts","../../src/api/metrics.ts","../../src/providers/telegram.ts","../../src/api/notifications.ts","../../src/providers/proxy/caddy.ts","../../src/providers/proxy/index.ts","../../src/shared/proxy-form.ts","../../src/services/proxy-config.ts","../../src/services/tls.ts","../../src/services/proxy.ts","../../src/api/proxy.ts","../../src/api/servers/$.routes.ts","../../src/services/state.ts","../../src/api/settings.ts","../../src/api/state.ts","../../src/api/static.ts","../../src/api/tls.ts","../../src/api/workspaces/$.routes.ts","../../src/api/wsl-temperature.ts","../../src/helpers/error.ts","../../src/middleware/host.ts","../../src/openapi-reference.ts","../../src/openapi.ts","../../src/app.ts","../../src/helpers/open.ts","../../src/services/acme-challenge.ts","../../src/services/config-watch.ts","../../src/services/control-server.ts","../../src/providers/host.ts","../../src/services/host-monitor.ts","../../src/providers/ddns/ip.ts","../../src/services/ddns.ts","../../src/services/history.ts","../../src/services/notifications.ts","../../src/helpers/backoff.ts","../../src/services/dependencies.ts","../../src/services/supervisor/spawn.ts","../../src/services/supervisor/compose.ts","../../src/services/supervisor/entry.ts","../../src/providers/health-check.ts","../../src/services/supervisor/port-preflight.ts","../../src/services/supervisor/health.ts","../../src/services/supervisor/pending-load.ts","../../src/providers/log-tail.ts","../../src/services/log-relay.ts","../../src/services/supervisor/persistent.ts","../../src/services/supervisor/records.ts","../../src/services/supervisor/view.ts","../../src/services/supervisor.ts","../../src/services/panel.ts","../../src/services/ui-update.ts","../../src/index.ts"],"sourcesContent":["import { createFactory } from 'hono/factory'\n\n/**\n * Every route is built from this factory and chained (`app.get(...).post(...)`)\n * so Hono keeps the full route map in its type — which is what `AppType` exports\n * for `hc<AppType>` clients and for the generated OpenAPI document.\n */\nexport const appFactory = createFactory()\n","/** Client address helpers shared by the auth guard and the setup routes. */\n\nexport function requestIp(c: { req: { raw: unknown } }): string | null {\n // srvx resolves this hop-aware from `trustProxy` + x-forwarded-for.\n const raw = c.req.raw as { ip?: string } | undefined\n return raw?.ip ?? null\n}\n\nexport function isLoopback(address: string | null): boolean {\n if (!address)\n return false\n return address === '127.0.0.1' || address === '::1' || address === '::ffff:127.0.0.1'\n}\n\n/** Headers a proxy adds; their presence means the TCP peer is a relay, not the person. */\nconst FORWARDING_HEADERS = ['forwarded', 'x-forwarded-for', 'x-real-ip']\n\n/**\n * Whether the request was made on this machine, by something that did not relay it.\n *\n * The panel's own reverse proxy connects from 127.0.0.1, so a loopback peer alone would hand every\n * internet client this machine's trust (the \"no password set yet\" pass, first-setup, `/_hh`).\n */\nexport function isLoopbackRequest(c: { req: { raw: unknown } }): boolean {\n const headers = (c.req.raw as { headers?: Headers } | undefined)?.headers\n if (headers !== undefined && FORWARDING_HEADERS.some(name => headers.has(name)))\n return false\n return isLoopback(requestIp(c))\n}\n","import type { AppDeps } from '#src/app'\nimport { describeRoute } from 'hono-openapi'\nimport { appFactory } from '#src/helpers/factory'\nimport { logger } from '#src/helpers/logger'\nimport { isLoopbackRequest } from '#src/middleware/loopback'\n\n/**\n * The ACMEProxy endpoint the reverse-proxy engine calls for a DNS-01 challenge.\n *\n * Deliberately outside `/api` — the engine is not a session — and outside `/_hh`,\n * which carries the panel's own local token. Two things guard it: only a loopback\n * peer is answered, and the engine must present the Basic credentials the panel\n * generated for it. The engine never holds DNS credentials; this endpoint writes\n * the record through the workspace account a route names.\n */\nexport function createAcmeChallengeRoute(deps: AppDeps) {\n return appFactory.createApp()\n .post(\n '/:action',\n describeRoute({\n tags: ['proxy'],\n summary: 'Answer one ACME DNS-01 challenge (local engine only)',\n responses: { 200: { description: 'Written or removed' }, 401: { description: 'Bad credentials' }, 403: { description: 'Not a local caller' } },\n }),\n async (c) => {\n if (!isLoopbackRequest(c)) {\n logger.warn('proxy: refused a DNS-01 challenge from a non-loopback caller')\n return c.json({ error: 'only this machine may answer a challenge' }, 403)\n }\n return await deps.challenge.handle(c.req.raw, c.req.param('action') ?? '')\n },\n )\n}\n","/** Minimal cookie helpers, enough for one httpOnly session cookie. */\nexport interface CookieOptions {\n maxAgeMs?: number\n httpOnly?: boolean\n sameSite?: 'Strict' | 'Lax' | 'None'\n secure?: boolean\n path?: string\n}\n\nexport function parseCookies(header: string | null | undefined): Record<string, string> {\n const cookies: Record<string, string> = {}\n if (!header)\n return cookies\n for (const part of header.split(';')) {\n const separator = part.indexOf('=')\n if (separator < 0)\n continue\n const name = part.slice(0, separator).trim()\n if (name.length === 0)\n continue\n const value = part.slice(separator + 1).trim()\n try {\n cookies[name] = decodeURIComponent(value)\n }\n catch {\n cookies[name] = value\n }\n }\n return cookies\n}\n\nexport function serializeCookie(name: string, value: string, options: CookieOptions = {}): string {\n const parts = [`${name}=${encodeURIComponent(value)}`]\n parts.push(`Path=${options.path ?? '/'}`)\n if (options.maxAgeMs !== undefined)\n parts.push(`Max-Age=${Math.max(0, Math.floor(options.maxAgeMs / 1000))}`)\n if (options.httpOnly !== false)\n parts.push('HttpOnly')\n parts.push(`SameSite=${options.sameSite ?? 'Strict'}`)\n if (options.secure)\n parts.push('Secure')\n return parts.join('; ')\n}\n\n/**\n * Whether this response's cookie may carry `Secure`, from the configured policy and the protocol the\n * request actually arrived on.\n *\n * One home, because two responses now set the session cookie — the login route and the guard that\n * slides an active session forward. `auto` is the proxy case: behind TLS the panel sees `https:` only\n * because srvx rewrote it from `x-forwarded-proto` (see `.agentDocs/GOTCHAS.md`).\n */\nexport function secureCookieFor(mode: 'auto' | 'always' | 'never', protocol: string): boolean {\n if (mode === 'always')\n return true\n if (mode === 'never')\n return false\n return protocol === 'https:'\n}\n","import type { StandardSchemaV1 } from '@standard-schema/spec'\nimport type { ResolverReturnType } from 'hono-openapi'\nimport { resolver } from 'hono-openapi'\nimport { apiErrorSchema } from '#src/shared/contracts'\n\n/**\n * A JSON response body for `describeRoute`. The resolver needs a real Standard\n * Schema, so only ArkType schemas go in here — never a hand-written JSON schema.\n */\nexport function jsonBody(schema: StandardSchemaV1): { 'application/json': { schema: ResolverReturnType } } {\n return { 'application/json': { schema: resolver(schema as never) } }\n}\n\n/** The envelope every failing request gets (see `src/helpers/error.ts`). */\nexport const ERROR_RESPONSES = {\n 400: { description: 'The request was rejected', content: jsonBody(apiErrorSchema) },\n 401: { description: 'No valid session', content: jsonBody(apiErrorSchema) },\n 404: { description: 'Unknown id', content: jsonBody(apiErrorSchema) },\n 413: { description: 'The body is larger than this route accepts', content: jsonBody(apiErrorSchema) },\n} as const\n","import type { StandardSchemaV1 } from '@standard-schema/spec'\nimport type { ValidationTargets } from 'hono'\nimport { DetailedError } from '@namesmt/utils'\nimport { validator as standardValidator } from 'hono-openapi'\n\n/**\n * ArkType-backed request validation. On success Hono stores the *parsed* value,\n * so `c.req.valid('json')` is fully typed and already normalized; on failure it\n * becomes a `DetailedError`, which the global error handler turns into the one\n * error envelope this API speaks.\n */\nexport function validate<Target extends keyof ValidationTargets, Schema extends StandardSchemaV1>(target: Target, schema: Schema) {\n return standardValidator(target, schema, (result) => {\n if (result.success === false)\n // The same `code` and `detail` shape `parseOrThrow` uses: both mean \"the input was invalid\", and\n // a client that wants to act on that should not have to tell a generic `DETAILED_ERROR` from a\n // real one. `detail[]` is the field list either way.\n throw new DetailedError('validation failed', { statusCode: 400, code: 'INVALID_INPUT', detail: normalizeIssues(result.error) })\n })\n}\n\n/** ArkType issues serialize poorly, so only the fields a client can act on survive. */\nfunction normalizeIssues(error: StandardSchemaV1.FailureResult['issues']): Array<{ path: string, message: string }> {\n return error.map((issue) => {\n const path = (issue.path ?? [])\n .map(segment => (typeof segment === 'object' && segment !== null && 'key' in segment ? String(segment.key) : String(segment)))\n .join('.')\n return { path, message: issue.message }\n })\n}\n","import type { SecretsStore } from '#src/config/secrets'\nimport type { AuthConfig, SessionView } from '#src/shared/contracts'\nimport crypto from 'node:crypto'\nimport { verifyApiToken, verifyPassword } from '#src/config/secrets'\nimport { parseCookies } from '#src/helpers/cookies'\n\nexport const SESSION_COOKIE = 'hh_session'\n\nconst MAX_SESSIONS = 100\nconst MAX_LOCKOUT_MS = 15 * 60_000\n/** Bounds on the per-IP bookkeeping, which an attacker can otherwise grow. */\nconst MAX_ATTEMPT_RECORDS = 10_000\nconst ATTEMPT_RECORD_TTL_MS = 60 * 60_000\n\nexport interface SessionRecord {\n token: string\n /**\n * The `updatedAt` of the password this session was issued under.\n *\n * Sessions live in this process's memory, so a password written by *another* process — the\n * `set-password` CLI, which writes the secrets file directly — was invisible here: it rotated\n * the hash the panel honoured while every existing cookie stayed valid for up to `sessionTtlMs`.\n * Stamping the revision on the session makes any rotation invalidate it, whoever wrote it.\n */\n passwordRevision: number | null\n /**\n * Slid forward on every validated request, so this is an **idle** timeout — `sessionTtlMs` after the\n * last visit, not after login. There is deliberately no absolute cap; the login page says so.\n */\n expiresAt: number\n /**\n * The deadline the browser's cookie was last told about.\n *\n * `expiresAt` slides on every request, but a cookie is only re-sent when something sets it — so\n * without this the browser deleted the cookie `sessionTtlMs` after *login* while the server kept\n * a perfectly good session, and a panel in constant use still signed its owner out.\n */\n cookieExpiresAt: number\n lastSeenAt: number\n ip: string | null\n}\n\ninterface AttemptRecord {\n failures: number\n blockedUntil: number\n blocks: number\n /** For expiring idle records: with `trustProxy` the key is client-chosen. */\n lastAttemptAt: number\n}\n\nexport type LoginOutcome\n = | { ok: true, status: 200, token: string, maxAgeMs: number }\n | { ok: false, status: 401 | 409 | 429, error: string, retryAfterMs?: number }\n\n/** Which credential a request presented. */\nexport type AuthMethod = 'cookie' | 'token'\n\nexport interface AuthIdentity {\n authenticated: boolean\n method: AuthMethod | null\n /** The session record, when the cookie resolved to one. */\n session: SessionRecord | null\n}\n\nexport const ANONYMOUS: AuthIdentity = { authenticated: false, method: null, session: null }\n\n/**\n * `Authorization: Bearer <token>`; the scheme is case-insensitive per RFC 7235,\n * and the credential is taken whole so a stray space cannot silently shorten it.\n */\nexport function bearerToken(header: string | null | undefined): string | null {\n if (!header)\n return null\n const [scheme, ...rest] = header.trim().split(/\\s+/)\n if (scheme?.toLowerCase() !== 'bearer')\n return null\n const token = rest.join('')\n return token.length > 0 ? token : null\n}\n\n/**\n * Authentication for the control panel.\n *\n * Two credentials are accepted: the browser's session cookie, and a long-lived\n * API token for scripts and agents. They carry the same authority on purpose —\n * a token that could do less than a signed-in browser would only be surprising.\n *\n * The password hash lives in the git-ignored secrets file; sessions live only in\n * memory, so restarting `up` invalidates every session, while a token outlives\n * the process until it is cleared.\n */\nexport class AuthService {\n private readonly sessions = new Map<string, SessionRecord>()\n private readonly attempts = new Map<string, AttemptRecord>()\n private readonly timer: NodeJS.Timeout\n\n constructor(\n private readonly secrets: SecretsStore,\n private readonly getConfig: () => AuthConfig,\n ) {\n this.timer = setInterval(() => this.cleanup(), 60_000)\n this.timer.unref()\n }\n\n get passwordSet(): boolean {\n return this.secrets.passwordSet\n }\n\n get passwordUpdatedAt(): number | null {\n return this.secrets.passwordUpdatedAt\n }\n\n /** Still the boot-time default: the login page says so, exposure stays blocked. */\n get usingDefaultPassword(): boolean {\n return this.secrets.usingDefaultPassword\n }\n\n /** The feature is on. */\n isEnabled(): boolean {\n return this.getConfig().enabled\n }\n\n /** A password is set, so a browser has something to sign in with. */\n isArmed(): boolean {\n return this.getConfig().enabled && this.secrets.passwordSet\n }\n\n /** Kept as the \"should the guard demand a session\" predicate. */\n isRequired(): boolean {\n return this.isArmed()\n }\n\n get apiTokenSet(): boolean {\n return this.secrets.apiTokenSet\n }\n\n /** The readable head of the stored token, never the token itself. */\n get apiTokenHint(): string | null {\n return this.secrets.apiTokenHint\n }\n\n /** Compared against the stored SHA-256, in constant time. */\n validateApiToken(token: string | null): boolean {\n if (token === null)\n return false\n const record = this.secrets.apiToken\n if (record === null)\n return false\n return verifyApiToken(token, record)\n }\n\n /**\n * Resolves whichever credential the request carried. The token is only\n * consulted when no session matched, so a stale cookie cannot mask it.\n */\n authenticate(credentials: { cookieToken: string | null, bearerToken: string | null }): AuthIdentity {\n const session = this.validate(credentials.cookieToken)\n if (session !== null)\n return { authenticated: true, method: 'cookie', session }\n if (this.validateApiToken(credentials.bearerToken))\n return { authenticated: true, method: 'token', session: null }\n return ANONYMOUS\n }\n\n sessionView(authenticated: boolean): SessionView {\n return {\n authenticated,\n authRequired: this.isRequired(),\n passwordSet: this.secrets.passwordSet,\n apiTokenSet: this.secrets.apiTokenSet,\n usingDefaultPassword: this.secrets.usingDefaultPassword,\n // Kept for older UIs; the first-run password is shown on the machine, never over the API.\n defaultPassword: null,\n sessionTtlMs: this.getConfig().sessionTtlMs,\n }\n }\n\n tokenFromCookie(cookieHeader: string | null | undefined): string | null {\n return parseCookies(cookieHeader)[SESSION_COOKIE] ?? null\n }\n\n /** Sliding expiry: an active panel stays logged in, an idle one does not. */\n validate(token: string | null): SessionRecord | null {\n if (!token)\n return null\n const session = this.sessions.get(token)\n if (!session)\n return null\n // The password changed since this session was issued — by the API, or by `set-password` in\n // another process writing the same file. Either way the credential it represents is gone.\n\n // The password changed since this session was issued — by the API, or by `set-password` in\n // another process writing the same file. Either way the credential it represents is gone.\n if (session.passwordRevision !== this.secrets.passwordUpdatedAt) {\n this.sessions.delete(token)\n return null\n }\n\n const now = Date.now()\n if (session.expiresAt <= now) {\n this.sessions.delete(token)\n return null\n }\n\n session.lastSeenAt = now\n session.expiresAt = now + this.getConfig().sessionTtlMs\n return session\n }\n\n /**\n * How far the session deadline may slide past the deadline the browser was last told about before\n * the cookie is re-sent.\n *\n * The cookie is only re-issued when it has fallen this far behind, so a panel in constant use keeps\n * a live cookie without a `Set-Cookie` on every request — an SSE stream opens one connection and\n * holds it. Quarter of the idle window, floored at 30 s so a short TTL still refreshes usefully and\n * capped at an hour so a week-long one costs at most one header an hour.\n */\n private cookieRefreshThresholdMs(): number {\n const ttl = this.getConfig().sessionTtlMs\n return Math.max(30_000, Math.min(ttl / 4, 3_600_000))\n }\n\n /**\n * The `Max-Age` to send, when this request should slide the *cookie* forward too; otherwise null.\n *\n * `validate()` slides `expiresAt` on every request, which makes the lifetime an idle timeout — but\n * a browser drops a cookie at the `Max-Age` it was issued with, and nothing was re-issuing it. So\n * the server kept a session a week after login while the browser had thrown its half away: a panel\n * used every ten seconds was still signed out at the configured lifetime, which is the opposite of\n * what the login page promises. Marking the deadline actually sent makes the two agree, and only\n * when it has moved enough to matter.\n */\n refreshCookie(session: SessionRecord): number | null {\n const now = Date.now()\n if (session.expiresAt - session.cookieExpiresAt < this.cookieRefreshThresholdMs())\n return null\n session.cookieExpiresAt = session.expiresAt\n return Math.max(0, session.expiresAt - now)\n }\n\n /** The cookie policy the guard and the login route must agree on. */\n get cookieSecureMode(): AuthConfig['cookieSecure'] {\n return this.getConfig().cookieSecure\n }\n\n verifyCurrentPassword(password: string): boolean {\n const record = this.secrets.password\n if (record === null)\n return false\n return verifyPassword(password, record)\n }\n\n login(password: string, ip: string | null): LoginOutcome {\n const config = this.getConfig()\n const key = ip ?? 'unknown'\n const now = Date.now()\n const attempt = this.attempts.get(key)\n\n if (attempt && attempt.blockedUntil > now) {\n const retryAfterMs = attempt.blockedUntil - now\n return {\n ok: false,\n status: 429,\n error: `too many failed attempts, retry in ${Math.ceil(retryAfterMs / 1000)}s`,\n retryAfterMs,\n }\n }\n\n const record = this.secrets.password\n if (record === null) {\n return { ok: false, status: 409, error: 'no password is set yet' }\n }\n\n if (!verifyPassword(password, record)) {\n const failures = (attempt?.failures ?? 0) + 1\n if (failures >= config.maxLoginAttempts) {\n const blocks = (attempt?.blocks ?? 0) + 1\n const blockedUntil = Date.now() + Math.min(config.lockoutMs * 2 ** (blocks - 1), MAX_LOCKOUT_MS)\n this.attempts.set(key, { failures: 0, blockedUntil, blocks, lastAttemptAt: Date.now() })\n }\n else {\n this.attempts.set(key, { failures, blockedUntil: 0, blocks: attempt?.blocks ?? 0, lastAttemptAt: Date.now() })\n }\n return { ok: false, status: 401, error: 'invalid password' }\n }\n\n this.attempts.delete(key)\n if (this.sessions.size >= MAX_SESSIONS) {\n const oldest = [...this.sessions.values()].sort((a, b) => a.lastSeenAt - b.lastSeenAt)[0]\n if (oldest)\n this.sessions.delete(oldest.token)\n }\n\n const token = crypto.randomBytes(32).toString('base64url')\n const expiresAt = now + config.sessionTtlMs\n this.sessions.set(token, {\n token,\n passwordRevision: this.secrets.passwordUpdatedAt,\n expiresAt,\n // The login response sets this same deadline, so the browser is already in step.\n cookieExpiresAt: expiresAt,\n lastSeenAt: now,\n ip,\n })\n\n return { ok: true, status: 200, token, maxAgeMs: config.sessionTtlMs }\n }\n\n logout(token: string | null): void {\n if (token)\n this.sessions.delete(token)\n }\n\n logoutAll(): void {\n this.sessions.clear()\n }\n\n /**\n * Changing the password must not leave old sessions valid. The session that\n * made the change is kept — being signed out of the page you just used is not\n * a security requirement, and it makes a successful change look like a failure.\n */\n setPassword(password: string, options: { isDefault?: boolean, keepToken?: string | null } = {}): void {\n this.secrets.setPassword(password, options)\n const keep = options.keepToken ?? null\n this.logoutOthers(keep)\n // The kept session is re-stamped with the new revision, or the freshness check below would\n // sign the very browser that made the change out of the page it just used.\n const session = keep === null ? undefined : this.sessions.get(keep)\n if (session !== undefined)\n session.passwordRevision = this.secrets.passwordUpdatedAt\n }\n\n /** Drops every session except one, which is how a password change stays signed in. */\n private logoutOthers(keep: string | null): void {\n if (keep === null) {\n this.sessions.clear()\n return\n }\n for (const token of [...this.sessions.keys()]) {\n if (token !== keep)\n this.sessions.delete(token)\n }\n }\n\n /** Creates the boot-time default only when nothing is set yet. */\n ensureDefaultPassword(password: string): boolean {\n const created = this.secrets.ensureDefaultPassword(password) !== null\n if (created)\n this.logoutAll()\n return created\n }\n\n clearPassword(): void {\n this.secrets.clearPassword()\n this.logoutAll()\n }\n\n activeSessions(): number {\n return this.sessions.size\n }\n\n dispose(): void {\n clearInterval(this.timer)\n this.sessions.clear()\n }\n\n private cleanup(): void {\n const now = Date.now()\n for (const [token, session] of this.sessions) {\n if (session.expiresAt <= now)\n this.sessions.delete(token)\n }\n for (const [key, attempt] of this.attempts) {\n // Idle records go, whether or not they were ever blocked — a failed login\n // from an address that never comes back must not be remembered forever.\n if (now - attempt.lastAttemptAt >= ATTEMPT_RECORD_TTL_MS)\n this.attempts.delete(key)\n }\n\n if (this.attempts.size > MAX_ATTEMPT_RECORDS) {\n const oldest = [...this.attempts.entries()]\n .sort((a, b) => a[1].lastAttemptAt - b[1].lastAttemptAt)\n .slice(0, this.attempts.size - MAX_ATTEMPT_RECORDS)\n for (const [key] of oldest) this.attempts.delete(key)\n }\n }\n}\n","import type { Context, MiddlewareHandler } from 'hono'\nimport type { AuthIdentity, AuthService } from '#src/services/auth'\nimport type { HistoryActor } from '#src/shared/contracts'\nimport { DetailedError } from '@namesmt/utils'\nimport { secureCookieFor, serializeCookie } from '#src/helpers/cookies'\nimport { isLoopbackRequest } from '#src/middleware/loopback'\nimport { bearerToken, SESSION_COOKIE } from '#src/services/auth'\n\n/** Endpoints the SPA needs before it can show a login form. */\nconst PUBLIC_PATHS = new Set(['/api/auth/login', '/api/auth/session'])\n\n/** 401s from the guard carry this code so the SPA can route to the login view. */\nexport const AUTH_REQUIRED_CODE = 'AUTH_REQUIRED'\n\n/**\n * The one place that reads a request's credentials, so the guard, the session\n * route and `/healthz` can never disagree about who is calling.\n */\nexport function requestIdentity(c: Context, auth: AuthService): AuthIdentity {\n return auth.authenticate({\n cookieToken: auth.tokenFromCookie(c.req.header('cookie')),\n bearerToken: bearerToken(c.req.header('authorization')),\n })\n}\n\nexport interface AuthGuardDeps {\n auth: AuthService\n /** Test hook: bind the guard to an explicit cookie header / ip. */\n now?: () => number\n}\n\n/**\n * Guards every `/api/*` route. The SPA shell stays public (it holds no data),\n * so the browser can load the app and show the login screen.\n *\n * A request may prove itself with the session cookie or with an API token\n * (`Authorization: Bearer …`), which is what lets a script or an agent drive the\n * panel without a browser. The token also works while auth is enabled but no\n * password is set — that state otherwise only trusts this machine.\n *\n * State-changing requests that carry an `Origin` must come from this same host:\n * with `SameSite=Strict` cookies that closes the cross-site CSRF path.\n */\nexport function createAuthGuard(deps: AuthGuardDeps): MiddlewareHandler {\n return async (c, next) => {\n const path = c.req.path\n\n if (path.startsWith('/api')) {\n const method = c.req.method\n // A browser never attaches a bearer token by itself, so a request carrying one cannot be a\n // cross-site forgery — which is what lets a desktop app or another origin use the API.\n const viaToken = bearerToken(c.req.header('authorization')) !== null && requestIdentity(c, deps.auth).method === 'token'\n if (method !== 'GET' && method !== 'HEAD' && !viaToken) {\n const origin = c.req.header('origin')\n if (origin !== undefined) {\n // `Host` is required by HTTP/1.1 but not guaranteed to be set by every\n // client, so fall back to the authority the server itself resolved.\n const requestHost = c.req.header('host') ?? new URL(c.req.url).host\n let originHost: string | null = null\n try {\n originHost = new URL(origin).host\n }\n catch {\n originHost = null\n }\n if (originHost === null || originHost !== requestHost)\n throw new DetailedError('cross-origin request rejected', { statusCode: 403, code: 'CROSS_ORIGIN' })\n }\n }\n\n if (!PUBLIC_PATHS.has(path)) {\n const identity = requestIdentity(c, deps.auth)\n\n if (deps.auth.isArmed()) {\n if (!identity.authenticated) {\n if (deps.auth.apiTokenSet)\n c.header('WWW-Authenticate', 'Bearer realm=\"home-hosted\"')\n throw new DetailedError('authentication required', { statusCode: 401, code: AUTH_REQUIRED_CODE })\n }\n /**\n * An active session slides forward, so the browser's copy of the deadline has to slide with\n * it — otherwise it is dropped at the lifetime measured from *login*, whatever the person\n * did in between, and the panel signs its owner out mid-use.\n */\n if (identity.method === 'cookie' && identity.session !== null) {\n const maxAgeMs = deps.auth.refreshCookie(identity.session)\n if (maxAgeMs !== null) {\n c.header('Set-Cookie', serializeCookie(SESSION_COOKIE, identity.session.token, {\n maxAgeMs,\n secure: secureCookieFor(deps.auth.cookieSecureMode, new URL(c.req.url).protocol),\n sameSite: 'Strict',\n httpOnly: true,\n }))\n }\n }\n }\n else if (deps.auth.isEnabled()) {\n // Enabled but not armed: only an API token or this machine may look. A\n // proxied request must set `trustProxy` to be seen as remote, otherwise\n // it is indistinguishable from a local one.\n if (!identity.authenticated && !isLoopbackRequest(c)) {\n throw new DetailedError('authentication is enabled but no password is set — set one from the machine running the panel', {\n statusCode: 401,\n code: 'AUTH_UNARMED',\n })\n }\n }\n }\n }\n\n await next()\n }\n}\n\nexport { SESSION_COOKIE }\n\n/**\n * Who is behind a request, as a history event names them: a cookie is a person at\n * the panel, a bearer token is a script or an agent. Anonymous callers can only be\n * loopback requests while auth is unarmed, which is the browser's own origin.\n */\nexport function requestActor(c: Context, auth: AuthService): HistoryActor {\n return requestIdentity(c, auth).method === 'token' ? 'agent' : 'user'\n}\n\nexport { isLoopbackRequest, requestIp } from '#src/middleware/loopback'\n","import type { ControlConfig, ProxyConfig } from '#src/shared/contracts'\nimport { isExposed } from '#src/helpers/bind'\n\nexport interface ExposureState {\n /** The control panel listens beyond loopback. */\n exposed: boolean\n /** Non-null when that exposure is not backed by a password. */\n blockedReason: string | null\n}\n\n/**\n * Exposing the panel beyond loopback is only allowed with authentication fully\n * configured — this is checked at startup, on every settings write, and shown in\n * the UI, so the three can never disagree.\n */\nexport function checkExposure(control: ControlConfig, passwordSet: boolean, usingDefaultPassword = false): ExposureState {\n const exposed = isExposed(control.host)\n if (!exposed)\n return { exposed, blockedReason: null }\n\n if (!control.auth.enabled && !passwordSet) {\n return {\n exposed,\n blockedReason: `the control panel is bound to ${control.host} but authentication is disabled and no password is set`,\n }\n }\n if (!control.auth.enabled) {\n return { exposed, blockedReason: `the control panel is bound to ${control.host} but authentication is disabled` }\n }\n if (!passwordSet) {\n return {\n exposed,\n blockedReason: `the control panel is bound to ${control.host} but no password is set (run \\`home-hosted set-password\\`)`,\n }\n }\n if (usingDefaultPassword) {\n return {\n exposed,\n blockedReason: `the control panel is bound to ${control.host} but still uses the default password — change it first`,\n }\n }\n return { exposed, blockedReason: null }\n}\n\n/**\n * A route pointing at the panel puts it on the internet, which is the same\n * exposure the listener rule guards — so it answers to the same bar. Said here\n * rather than in the proxy service because that rule must not have two homes.\n */\nexport function checkProxyExposure(\n proxy: ProxyConfig,\n authEnabled: boolean,\n passwordSet: boolean,\n usingDefaultPassword = false,\n): string | null {\n if (!proxy.enabled)\n return null\n // Every enabled route to the panel, whatever its `tls` says. `tls: \"off\"` was excluded here, and\n // that was backwards: the engine dials the panel on `127.0.0.1`, the `/api` guard reads a\n // loopback request as local while auth is enabled but unarmed, and so a plain-HTTP panel route\n // with no password set served the whole panel to anyone reaching that hostname — the same\n // exposure as a `tls: \"auto\"` one, but in the clear. A route pointing at the panel is exposure\n // and obeys this bar, which is what the rule already said in prose.\n const panelRoutes = proxy.routes.filter(route => route.enabled && route.target === 'panel')\n if (panelRoutes.length === 0)\n return null\n\n const hosts = panelRoutes.map(route => route.host).join(', ')\n if (!authEnabled && !passwordSet)\n return `the reverse proxy would serve the control panel at ${hosts} but authentication is disabled and no password is set`\n if (!authEnabled)\n return `the reverse proxy would serve the control panel at ${hosts} but authentication is disabled`\n if (!passwordSet)\n return `the reverse proxy would serve the control panel at ${hosts} but no password is set (run \\`home-hosted set-password\\`)`\n if (usingDefaultPassword)\n return `the reverse proxy would serve the control panel at ${hosts} but it still uses the default password — change it first`\n return null\n}\n\n/**\n * A warning for the combination that makes the login lockout advisory.\n *\n * `trustProxy: true` tells srvx to trust `x-forwarded-*` from **any** peer, and it resolves the client\n * address from the leftmost entry of `x-forwarded-for` — a value the caller controls. Login failures are\n * keyed on that address, so a client that rotates the header never accumulates them: measured, 30 wrong\n * passwords from 30 forged addresses produced **zero** 429s, against 27 from a fixed address.\n *\n * This is a warning rather than a refusal because `true` has legitimate uses — a proxy on another host —\n * and, once the header is trusted, the real peer is not reachable through srvx (`#remoteAddress` is\n * private), so the panel cannot re-key the lockout on it. Prefer `host: local` with the proxy on this\n * machine, or leave `trustProxy` off and reach the panel directly.\n */\nexport function proxyTrustWarning(control: ControlConfig): string | null {\n // `'loopback'` is not the dangerous case: it trusts `x-forwarded-*` only when the peer *is* loopback,\n // so a forged header from anywhere else is ignored and the lockout keeps counting per real address.\n // Only the blanket `true` believes whoever asks.\n if (control.auth.trustProxy !== true || !isExposed(control.host))\n return null\n return `auth.trustProxy is on while the panel is bound to ${control.host}: the client address comes from `\n + `the caller's own x-forwarded-for header, so the login lockout (maxLoginAttempts/lockoutMs) counts `\n + `per forged address and can be bypassed. Keep the bind on local with the proxy on this machine, or `\n + `put an authenticating gateway in front`\n}\n","import type { Context } from 'hono'\nimport type { AppDeps } from '#src/app'\nimport type { LoginRequest, PasswordRequest } from '#src/shared/contracts'\nimport { DetailedError } from '@namesmt/utils'\nimport { describeRoute } from 'hono-openapi'\nimport { bodyLimit } from 'hono/body-limit'\nimport { generateApiToken } from '#src/config/secrets'\nimport { secureCookieFor, serializeCookie } from '#src/helpers/cookies'\nimport { appFactory } from '#src/helpers/factory'\nimport { ERROR_RESPONSES, jsonBody } from '#src/helpers/openapi'\nimport { validate } from '#src/helpers/validator'\nimport { AUTH_REQUIRED_CODE, requestIdentity, SESSION_COOKIE } from '#src/middleware/auth'\nimport { isLoopbackRequest, requestIp } from '#src/middleware/loopback'\nimport { checkExposure, checkProxyExposure } from '#src/services/exposure'\nimport { apiTokenCreatedSchema, loginSchema, okResponseSchema, passwordSchema, passwordSetResponseSchema, sessionViewSchema } from '#src/shared/contracts'\n\n/** `Secure` only helps over TLS, and would break plain http on a LAN. */\nfunction secureCookie(c: Context, deps: AppDeps): boolean {\n return secureCookieFor(deps.auth.cookieSecureMode, new URL(c.req.url).protocol)\n}\n\nexport function createAuthRoute(deps: AppDeps) {\n return appFactory.createApp()\n .get(\n '/auth/session',\n describeRoute({\n tags: ['auth'],\n summary: 'Who this request is, and how the panel is protected',\n responses: { 200: { description: 'Session', content: jsonBody(sessionViewSchema) } },\n }),\n c => c.json(deps.auth.sessionView(requestIdentity(c, deps.auth).authenticated)),\n )\n\n .post(\n '/auth/login',\n describeRoute({\n tags: ['auth'],\n summary: 'Exchange the panel password for a session cookie',\n responses: {\n 200: { description: 'Signed in', content: jsonBody(sessionViewSchema) },\n 400: ERROR_RESPONSES[400],\n 401: { description: 'Wrong password, or locked out (see `Retry-After`)' },\n },\n }),\n // Unauthenticated by nature, so the body is bounded before it is parsed.\n bodyLimit({\n maxSize: 4096,\n onError: () => {\n throw new DetailedError('the login request is too large', { statusCode: 413, code: 'PAYLOAD_TOO_LARGE' })\n },\n }),\n validate('json', loginSchema),\n (c) => {\n const body: LoginRequest = c.req.valid('json')\n const outcome = deps.auth.login(body.password, requestIp(c))\n\n if (!outcome.ok) {\n if (outcome.retryAfterMs !== undefined)\n c.header('Retry-After', String(Math.ceil(outcome.retryAfterMs / 1000)))\n throw new DetailedError(outcome.error, { statusCode: outcome.status, code: 'LOGIN_FAILED' })\n }\n\n c.header('Set-Cookie', serializeCookie(SESSION_COOKIE, outcome.token, {\n maxAgeMs: outcome.maxAgeMs,\n secure: secureCookie(c, deps),\n sameSite: 'Strict',\n httpOnly: true,\n }))\n\n return c.json(deps.auth.sessionView(true))\n },\n )\n\n .post(\n '/auth/logout',\n describeRoute({\n tags: ['auth'],\n summary: 'Drop the session cookie',\n responses: { 200: { description: 'Signed out', content: jsonBody(okResponseSchema) } },\n }),\n (c) => {\n deps.auth.logout(deps.auth.tokenFromCookie(c.req.header('cookie')))\n c.header('Set-Cookie', serializeCookie(SESSION_COOKIE, '', {\n maxAgeMs: 0,\n secure: secureCookie(c, deps),\n sameSite: 'Strict',\n httpOnly: true,\n }))\n return c.json({ ok: true })\n },\n )\n\n /**\n * First-time setup is allowed from loopback without a session (there is\n * nothing to authenticate against yet); every later change needs the session\n * and* the current password.\n */\n .post(\n '/auth/password',\n describeRoute({\n tags: ['auth'],\n summary: 'Set, change or enable the panel password',\n responses: { 200: { description: 'Updated', content: jsonBody(passwordSetResponseSchema) }, 400: ERROR_RESPONSES[400], 401: ERROR_RESPONSES[401] },\n }),\n validate('json', passwordSchema),\n (c) => {\n const body: PasswordRequest = c.req.valid('json')\n const identity = requestIdentity(c, deps.auth)\n const hadPassword = deps.auth.passwordSet\n const firstSetup = !hadPassword && isLoopbackRequest(c)\n\n if (!identity.authenticated && !firstSetup)\n throw new DetailedError('authentication required', { statusCode: 401, code: AUTH_REQUIRED_CODE })\n\n // The current password is demanded of every credential, so a stolen API\n // token cannot rewrite the password it would then need to be recovered from.\n if (identity.authenticated && hadPassword) {\n if (body.currentPassword === undefined)\n throw new DetailedError('currentPassword is required to change an existing password', { statusCode: 400, code: 'CURRENT_PASSWORD_REQUIRED' })\n if (!deps.auth.verifyCurrentPassword(body.currentPassword))\n throw new DetailedError('current password is incorrect', { statusCode: 401, code: 'CURRENT_PASSWORD_WRONG' })\n }\n\n // Keep the caller signed in: every *other* session is dropped. A token\n // caller holds no session, so this signs every browser out instead.\n deps.auth.setPassword(body.newPassword, { keepToken: identity.session?.token ?? null })\n\n // A password that is not enforced protects nothing, so the first setup enables it.\n let enabled = deps.panel.settings.control.auth.enabled\n if (!enabled) {\n deps.panel.settings.updateControl({ auth: { enabled: true } })\n enabled = true\n }\n\n return c.json({ ok: true, enabled, sessionsInvalidated: true })\n },\n )\n\n /**\n * Mint (or rotate) the API token from a signed-in browser, so a remote person can hand a script,\n * TUI or desktop app a credential without a shell on the machine. Session only: a token minting\n * its own successor would make a leaked one impossible to revoke from the panel.\n */\n .post(\n '/auth/token',\n describeRoute({\n tags: ['auth'],\n summary: 'Generate a new API token, replacing any existing one (signed-in session required)',\n responses: { 200: { description: 'The token, shown once', content: jsonBody(apiTokenCreatedSchema) }, 401: ERROR_RESPONSES[401], 403: { description: 'An API token may not mint a token' } },\n }),\n (c) => {\n requireSession(c, deps, 'generating an API token')\n const token = generateApiToken()\n deps.secrets.setApiToken(token)\n return c.json({ token, hint: deps.secrets.apiTokenHint ?? token.slice(0, 8) })\n },\n )\n\n /**\n * Revoke the API token. Session only, for the same reason minting is: a token that could revoke\n * its own successor — or itself — would let a leaked credential destroy the operator's access,\n * and with auth switched off it was reachable with no credential at all.\n */\n .delete(\n '/auth/token',\n describeRoute({\n tags: ['auth'],\n summary: 'Revoke the API token (signed-in session required)',\n responses: { 200: { description: 'Revoked', content: jsonBody(okResponseSchema) }, 401: ERROR_RESPONSES[401], 403: { description: 'An API token may not revoke a token' } },\n }),\n (c) => {\n requireSession(c, deps, 'revoking an API token')\n deps.secrets.clearApiToken()\n return c.json({ ok: true })\n },\n )\n\n .delete(\n '/auth/password',\n describeRoute({\n tags: ['auth'],\n summary: 'Clear the password and turn authentication off (signed-in session required)',\n responses: { 200: { description: 'Cleared', content: jsonBody(okResponseSchema) }, 400: ERROR_RESPONSES[400], 401: ERROR_RESPONSES[401], 403: { description: 'An API token may not clear the password' } },\n }),\n (c) => {\n const identity = requestIdentity(c, deps.auth)\n if (!identity.authenticated)\n throw new DetailedError('authentication required', { statusCode: 401, code: AUTH_REQUIRED_CODE })\n\n /**\n * A **session**, not merely an identity, because clearing the password is the other way\n * authentication goes away. A bearer token must not be able to do it: `POST` refuses to\n * rewrite a password it already has without `currentPassword` (so a stolen token cannot\n * arm the panel), and a token that could `DELETE` instead would reach the same end —\n * `DELETE`, then `POST` a new password with none set, needing no current one. The refusal\n * names the two real paths, both of which the person can follow.\n */\n if (identity.method !== 'cookie') {\n throw new DetailedError('clearing the panel password needs a signed-in session, not an API token — sign in at the panel, or run `home-hosted set-password --clear` on the machine', {\n statusCode: 403,\n code: 'SESSION_REQUIRED',\n })\n }\n\n const exposure = checkExposure(deps.panel.settings.control, false)\n if (exposure.exposed) {\n throw new DetailedError('refusing to clear the password while the control panel is bound beyond loopback — set the bind back to local first', {\n statusCode: 400,\n code: 'EXPOSED_WITHOUT_PASSWORD',\n })\n }\n\n // Clearing the password is the other way authentication goes away, so the\n // proxy's own exposure rule has to hold here too: a route with `target: \"panel\"`\n // serves this control panel on a public hostname, and that guard only runs when a\n // route is written.\n const proxyExposure = checkProxyExposure(deps.proxy.config, false, false, false)\n if (proxyExposure !== null)\n throw new DetailedError(proxyExposure, { statusCode: 400, code: 'PROXY_EXPOSURE_BLOCKED' })\n\n deps.auth.clearPassword()\n deps.panel.settings.updateControl({ auth: { enabled: false } })\n return c.json({ ok: true })\n },\n )\n}\n\n/** Refuses anything but a signed-in browser session, naming what needed one. */\nfunction requireSession(c: Context, deps: AppDeps, what: string): void {\n const identity = requestIdentity(c, deps.auth)\n if (!identity.authenticated)\n throw new DetailedError('authentication required', { statusCode: 401, code: AUTH_REQUIRED_CODE })\n if (identity.method !== 'cookie')\n throw new DetailedError(`${what} needs a signed-in session, not an API token — sign in at the panel, or run \\`home-hosted set-token --generate\\` on the machine`, { statusCode: 403, code: 'SESSION_REQUIRED' })\n}\n","import { DetailedError } from '@namesmt/utils'\nimport { type } from 'arktype'\n\n/**\n * Validates a value that is not a request target (a query string, a URL\n * parameter, a payload read by hand) and fails with the standard error envelope.\n * Request bodies and queries that a route reads once go through the `validate()`\n * middleware instead, which also carries the type into the handler.\n */\nexport function parseOrThrow<T>(schema: (input: unknown) => unknown, input: unknown, label: string): T {\n const result = schema(input)\n if (result instanceof type.errors) {\n throw new DetailedError(`${label}: ${result.summary}`, {\n statusCode: 400,\n code: 'INVALID_INPUT',\n detail: result.issues.map(issue => ({ path: issue.path.join('.'), message: issue.message })),\n })\n }\n return result as T\n}\n","import type { AppDeps } from '#src/app'\nimport type { BackupCreate, RestoreRequest } from '#src/shared/contracts'\nimport { Buffer } from 'node:buffer'\nimport crypto from 'node:crypto'\nimport fs, { createReadStream } from 'node:fs'\nimport path from 'node:path'\nimport { Readable } from 'node:stream'\nimport { DetailedError } from '@namesmt/utils'\nimport { type } from 'arktype'\nimport { describeRoute, resolver } from 'hono-openapi'\nimport { bodyLimit } from 'hono/body-limit'\nimport { appFactory } from '#src/helpers/factory'\nimport { logger } from '#src/helpers/logger'\nimport { ERROR_RESPONSES, jsonBody } from '#src/helpers/openapi'\nimport { parseOrThrow } from '#src/helpers/validate'\nimport { validate } from '#src/helpers/validator'\nimport { requestIdentity } from '#src/middleware/auth'\nimport { selectionWritesCredentials } from '#src/shared/backup-scope'\nimport { backupCreatedResponseSchema, backupCreateSchema, backupFilesResponseSchema, backupSelectionSchema, restorePlanSchema, restoreRequestSchema } from '#src/shared/contracts'\n\n/** Uploads are buffered in memory by `parseBody`, so they get a hard ceiling. */\nconst MAX_UPLOAD_BYTES = 256 * 1024 * 1024\n\nconst nameParam = type({ name: 'string >= 1' })\n\n/** A backup that failed to be created is a bad request, not a server fault. */\nfunction backupFailed(error: string | undefined): DetailedError {\n return new DetailedError(error ?? 'the backup failed', { statusCode: 400, code: 'BACKUP_FAILED' })\n}\n\nexport function createBackupsRoute(deps: AppDeps) {\n return appFactory.createApp()\n .get(\n '/backups',\n describeRoute({\n tags: ['backups'],\n summary: 'Archives on disk, and the paths a backup would capture',\n responses: { 200: { description: 'Backups', content: jsonBody(backupSelectionSchema) } },\n }),\n c => c.json(deps.backups.selection()),\n )\n\n .post(\n '/backups',\n describeRoute({\n tags: ['backups'],\n summary: 'Create a backup (optionally password-protected)',\n responses: { 200: { description: 'Created', content: jsonBody(backupCreatedResponseSchema) }, 400: ERROR_RESPONSES[400] },\n }),\n validate('json', backupCreateSchema),\n async (c) => {\n const body: BackupCreate = c.req.valid('json')\n // `include` and `exclude` together are allowed, and mean what the CLI means by them: the\n // exclusion applies after the selection. The pair stays coherent because `create` reads\n // both through one `selectionOf`, and a scope that leaves nothing refuses there rather\n // than writing an empty archive.\n const result = await deps.backups.create({ password: body.password, include: body.include, exclude: body.exclude })\n if (!result.ok)\n throw backupFailed(result.error)\n return c.json({ file: result.file, files: deps.backups.list() })\n },\n )\n\n .get(\n '/backups/:name/download',\n describeRoute({\n tags: ['backups'],\n summary: 'Download one archive',\n responses: { 200: { description: 'the archive (application/zip)' }, 404: ERROR_RESPONSES[404] },\n }),\n validate('param', nameParam),\n async (c) => {\n const file = deps.backups.resolve(c.req.valid('param').name)\n if (file === null)\n throw new DetailedError('unknown backup', { statusCode: 404, code: 'UNKNOWN_BACKUP' })\n\n // Streamed, not read into memory. An archive has **no size ceiling** — it carries whatever the\n // declared data paths hold — so `readFileSync` blocked the event loop for the whole read and\n // held it: measured at 82 ms for 100 MB, 841 ms for 500 MB and 1.3 s for 1 GB, with every\n // state frame and health probe waiting.\n //\n // `createReadStream`, not `FileHandle.readableWebStream`: consuming the latter to the end\n // leaves the handle **open** (measured — a `stat()` on it still succeeds), so every download\n // would leak a descriptor. `createReadStream` destroys itself on end *and* on a client that\n // disconnects (measured `destroyed: true`).\n const stats = await fs.promises.stat(file)\n return c.body(Readable.toWeb(createReadStream(file)) as ReadableStream, 200, {\n 'Content-Type': 'application/zip',\n 'Content-Length': String(stats.size),\n 'Content-Disposition': `attachment; filename=\"${path.basename(file)}\"`,\n })\n },\n )\n\n .delete(\n '/backups/:name',\n describeRoute({\n tags: ['backups'],\n summary: 'Delete one archive',\n responses: { 200: { description: 'Removed', content: jsonBody(backupFilesResponseSchema) }, 404: ERROR_RESPONSES[404] },\n }),\n validate('param', nameParam),\n (c) => {\n if (!deps.backups.remove(c.req.valid('param').name))\n throw new DetailedError('unknown backup', { statusCode: 404, code: 'UNKNOWN_BACKUP' })\n return c.json({ ok: true, files: deps.backups.list() })\n },\n )\n\n /**\n * Restore from a stored backup (`{ \"name\": \"...\" }`) or an uploaded one.\n * Without `confirm` it answers with the plan and changes nothing; `password`\n * unlocks a protected archive, and `include`/`exclude` select the items to apply.\n *\n * The body is declared so a generated client can send one: this is the only `/api` write route\n * that reads a JSON body, and it was the only one the document gave no `requestBody` — so\n * `openapi-typescript` and Scalar's \"try it\" produced a restore call with nowhere to put\n * `name`, while the README tells an agent this document *is* the API it may call. An upload is\n * `multipart/form-data` with the same fields as JSON strings, which is why the schema is named\n * but not required.\n */\n .post('/backups/restore', describeRoute({\n tags: ['backups'],\n summary: 'Plan or apply a restore from a stored or uploaded archive',\n requestBody: { required: false, content: { 'application/json': { schema: resolver(restoreRequestSchema) } } },\n responses: { 200: { description: 'The plan', content: jsonBody(restorePlanSchema) }, 400: ERROR_RESPONSES[400], 404: ERROR_RESPONSES[404], 413: ERROR_RESPONSES[413] },\n }),\n /**\n * Bound the body **while it arrives**, not after.\n *\n * The handler's own checks read `Content-Length` first — a header a chunked request simply does\n * not send — and then compare `file.size` after `parseBody()` has already buffered the whole\n * body into memory. So an upload with no length is buffered in full and *then* refused: the\n * ceiling was a memory limit rather than a guard. This middleware counts chunks and aborts at the\n * cap, which is the half the header check cannot do.\n */\n bodyLimit({\n maxSize: MAX_UPLOAD_BYTES,\n onError: () => {\n throw new DetailedError(`the upload is larger than ${Math.round(MAX_UPLOAD_BYTES / 1024 / 1024)}MB`, { statusCode: 413, code: 'UPLOAD_TOO_LARGE' })\n },\n }), async (c) => {\n const confirm = c.req.query('confirm') === 'true'\n const contentType = c.req.header('content-type') ?? ''\n\n let archive: string | null = null\n let uploadedTo: string | null = null\n let request: RestoreRequest\n\n try {\n if (contentType.includes('multipart/form-data')) {\n // `parseInt` is deliberate here and is not the prefix bug it resembles elsewhere: this\n // value is a header Node has already validated. A non-decimal `Content-Length` gets a\n // 400 from the HTTP parser before any handler runs (verified by sending a raw\n // `Content-Length: 1e12`), so the only shapes that arrive are decimal — and a partial\n // parse cannot make an oversized upload pass. This is a pre-flight check anyway; the\n // body is parsed and counted below.\n const declared = Number.parseInt(c.req.header('content-length') ?? '0', 10)\n if (Number.isFinite(declared) && declared > MAX_UPLOAD_BYTES)\n throw new DetailedError(`the upload is larger than ${Math.round(MAX_UPLOAD_BYTES / 1024 / 1024)}MB`, { statusCode: 413, code: 'UPLOAD_TOO_LARGE' })\n\n const body = await c.req.parseBody()\n const file = body.file\n if (!(file instanceof File))\n throw new DetailedError('expected a `file` field with the archive', { statusCode: 400, code: 'MISSING_FILE' })\n if (file.size > MAX_UPLOAD_BYTES)\n throw new DetailedError(`the upload is larger than ${Math.round(MAX_UPLOAD_BYTES / 1024 / 1024)}MB`, { statusCode: 413, code: 'UPLOAD_TOO_LARGE' })\n\n const uploads = path.join(deps.backups.directory, 'uploads')\n fs.mkdirSync(uploads, { recursive: true })\n uploadedTo = path.join(uploads, `upload-${crypto.randomUUID()}.zip`)\n // 0600: the archive holds whatever the config declares as data, possibly in\n // the clear, and sits here until the request finishes.\n fs.writeFileSync(uploadedTo, Buffer.from(await file.arrayBuffer()), { mode: 0o600 })\n archive = uploadedTo\n // A multipart body can only carry strings, so each selection is JSON. Both directions are\n // read the same way: `include` and `exclude` are one idea (`selectionOf`) and a body that\n // could carry only one of them made \"everything except these\" inexpressible on an upload.\n const jsonField = (key: 'include' | 'exclude'): unknown => {\n const raw = typeof body[key] === 'string' && body[key].length > 0 ? body[key] : null\n if (raw === null)\n return undefined\n try {\n return JSON.parse(raw)\n }\n catch {\n throw new DetailedError(`\\`${key}\\` must be a JSON array of item ids`, { statusCode: 400, code: key === 'include' ? 'INVALID_INCLUDE' : 'INVALID_EXCLUDE' })\n }\n }\n const include = jsonField('include')\n const exclude = jsonField('exclude')\n request = parseOrThrow<RestoreRequest>(restoreRequestSchema, {\n ...(typeof body.password === 'string' ? { password: body.password } : {}),\n ...(include === undefined ? {} : { include }),\n ...(exclude === undefined ? {} : { exclude }),\n }, 'body')\n }\n else {\n request = parseOrThrow<RestoreRequest>(restoreRequestSchema, await c.req.json().catch(() => ({})), 'body')\n if (request.name === undefined)\n throw new DetailedError('expected a backup name or a file upload', { statusCode: 400, code: 'MISSING_ARCHIVE' })\n archive = deps.backups.resolve(request.name)\n if (archive === null)\n throw new DetailedError('unknown backup', { statusCode: 404, code: 'UNKNOWN_BACKUP' })\n }\n\n // A restore that writes `global:secrets` replaces the password and token hashes of *this*\n // panel, so it needs the same bar as clearing the password: a session, not a token. Measured\n // before this guard, a token-only upload restore left the owner locked out with the\n // attacker's hash in the file.\n if (confirm && selectionWritesCredentials({ include: request.include, exclude: request.exclude })) {\n if (requestIdentity(c, deps.auth).method !== 'cookie') {\n throw new DetailedError('restoring the panel\\'s own credentials needs a signed-in session, not an API token — sign in, or run this from the machine with `home-hosted backup restore`', {\n statusCode: 403,\n code: 'SESSION_REQUIRED',\n })\n }\n }\n\n const plan = await deps.backups.restore(archive, {\n confirm,\n password: request.password,\n include: request.include,\n // The exclusion is what makes \"everything but the credentials\" expressible over HTTP, the\n // same pair the CLI and the docs recommend: leave the password and token hashes behind.\n exclude: request.exclude,\n })\n // A wrong or missing password is a prompt, not a failure.\n if (plan.needsPassword)\n return c.json(plan)\n if (plan.error !== undefined)\n throw new DetailedError(plan.error, { statusCode: 400, code: 'RESTORE_FAILED', detail: { items: plan.items, applied: plan.applied, skipped: plan.skipped } })\n if (confirm)\n logger.info(`restored from ${path.basename(archive)}: ${plan.applied.join(', ')}`)\n\n return c.json(plan)\n }\n finally {\n // An uploaded archive is only needed for this request.\n if (uploadedTo !== null)\n fs.rmSync(uploadedTo, { force: true })\n }\n })\n}\n","import { DetailedError } from '@namesmt/utils'\n\n/** The internal marker. A symbol so it never survives `JSON.stringify`. */\nexport const UNKNOWN_SERVER: unique symbol = Symbol('hh.unknownServer')\n\n/** What a per-server action (`start`/`stop`/`restart`/`free-port`) answers with. */\nexport interface ActionResult {\n ok: boolean\n error?: string\n /**\n * Set when the failure was \"no such entry\" rather than \"this entry cannot act\".\n *\n * The status rule needs the *kind* of failure, and a message is not a kind: any text beginning\n * `unknown server` — a future \"unknown serverless runtime\" — was read as a missing id, telling the\n * client to fix an id that was fine.\n *\n * A **symbol**, so it is internal: it carries the meaning to `statusForAction` without joining the\n * JSON a client receives, which would be an unintended wire change. `missingServer()` is the only\n * writer.\n */\n [UNKNOWN_SERVER]?: true\n}\n\n/** The one shape a missing entry takes, so the marker and the message cannot drift apart. */\nexport function missingServer(id: string): ActionResult {\n return { ok: false, error: `unknown server \"${id}\"`, [UNKNOWN_SERVER]: true }\n}\n\n/**\n * The same failure where the caller throws instead of answering — the route side of `missingServer()`.\n *\n * `api/logs.ts` and `api/servers/$.routes.ts` each carried a byte-identical private copy of this, with\n * six call sites between them. Two copies of a wire contract (the message, the 404, the `UNKNOWN_SERVER`\n * code) is the drift that already happened once for `request`: a change landing in one UI and not the\n * other. Defining it beside the message keeps one owner for the wording.\n */\nexport function unknownServerError(id: string): DetailedError {\n return new DetailedError(`unknown server \"${id}\"`, { statusCode: 404, code: 'UNKNOWN_SERVER' })\n}\n\n/**\n * The stable code for a failed action, so a script branches on it rather than on English.\n *\n * Two values, not one per message: a missing id is what the caller must fix, and everything else\n * (\"disabled\", \"stopping\", \"port in use\") is the entry refusing right now. `code` is added beside\n * `ok`/`error` rather than replacing them, because an older UI reads those.\n */\nexport function actionCode(result: ActionResult): string {\n return result[UNKNOWN_SERVER] === true ? 'UNKNOWN_SERVER' : 'ACTION_FAILED'\n}\n\n/** What a lifecycle route puts on the wire. A success carries no code — a code names a failure. */\nexport function actionAnswer(result: ActionResult): ActionResult & { code?: string, message?: string } {\n // A refusal carries the same `message`/`code` as every other failure; `ok`/`error` stay for older clients.\n return result.ok ? { ...result } : { ...result, message: result.error ?? 'the action failed', code: actionCode(result) }\n}\n\n/** Unknown ids are 404; a server that exists but cannot act is a 409. */\nexport function statusForAction(result: ActionResult): 200 | 404 | 409 {\n if (result.ok)\n return 200\n return result[UNKNOWN_SERVER] === true ? 404 : 409\n}\n","/**\n * Runs a task after the current response has been written.\n *\n * Moving the control listener closes the connection serving the request that\n * asked for the move, so those steps must happen once the response is out.\n */\nexport function afterResponse(task: () => Promise<void>, onError?: (error: unknown) => void): void {\n setImmediate(() => {\n void task().catch((error: unknown) => {\n onError?.(error)\n })\n })\n}\n","import { Buffer } from 'node:buffer'\nimport crypto from 'node:crypto'\n\n/**\n * Compares two secrets without leaking their contents through timing.\n *\n * `a !== b` short-circuits at the first differing byte, so an attacker who can measure response time\n * recovers a secret one byte at a time. That matters wherever the secret is the *only* thing standing\n * between a caller and a privileged action — the `/_hh` control channel, which is deliberately outside\n * `/api` and guarded by nothing else.\n *\n * Length is compared first because `timingSafeEqual` **throws** on differing lengths. That leaks only\n * the length, which is not secret here (the token has a fixed shape and a `hh_` prefix); rejecting it\n * is what keeps a truncated header from becoming a 500.\n */\nexport function secretEqual(actual: string, expected: string): boolean {\n const left = Buffer.from(actual, 'utf8')\n const right = Buffer.from(expected, 'utf8')\n if (left.length !== right.length || left.length === 0)\n return false\n return crypto.timingSafeEqual(left, right)\n}\n","import type { WorkspaceRuntime } from '#src/services/panel'\nimport { DetailedError } from '@namesmt/utils'\nimport { type } from 'arktype'\nimport { WorkspaceError } from '#src/config/workspaces'\n\n/**\n * Every workspace-scoped route reads its target from this one query key.\n *\n * **Strict, like every other request schema.** ArkType is permissive by default, so a key this\n * schema did not name was silently dropped and the request ran against the **default** workspace:\n * measured on the built panel, `POST /api/servers/<id>/stop?worspace=staging` answered\n * `200 {\"ok\":true}` having stopped that entry in `default` — a destructive action applied to the\n * wrong workspace because of one transposed letter, with nothing naming the typo. A misspelt\n * workspace must be a refused key, never a different workspace.\n *\n * A route that reads a second query key merges its own schema with this one **as the argument**\n * (`extra.merge(workspaceQuerySchema)`): `merge` keeps the argument's `onUndeclaredKey`, so that\n * spelling inherits the rejection while the reverse would lose it.\n */\nexport const workspaceQuerySchema = type({ 'workspace?': 'string' }).onUndeclaredKey('reject')\n\n/**\n * Resolves the workspace a request is about. Omitting it means the panel's\n * default workspace, which keeps `curl /api/servers` working the way it always\n * did on a single-workspace instance; naming one that does not exist is a 404,\n * never a silent fallback to another workspace's servers.\n */\nexport function requireWorkspace(select: (id?: string) => WorkspaceRuntime, id?: string): WorkspaceRuntime {\n try {\n return select(id)\n }\n catch (error) {\n if (error instanceof WorkspaceError)\n throw new DetailedError(error.message, { statusCode: 404, code: 'UNKNOWN_WORKSPACE' })\n throw error\n }\n}\n","import type { Context } from 'hono'\nimport type { AppDeps } from '#src/app'\nimport path from 'node:path'\nimport { DetailedError } from '@namesmt/utils'\nimport { type } from 'arktype'\nimport { describeRoute } from 'hono-openapi'\nimport { actionAnswer, statusForAction } from '#src/helpers/action-result'\nimport { afterResponse } from '#src/helpers/deferred'\nimport { appFactory } from '#src/helpers/factory'\nimport { logger } from '#src/helpers/logger'\nimport { ERROR_RESPONSES, jsonBody } from '#src/helpers/openapi'\nimport { secretEqual } from '#src/helpers/secret-compare'\nimport { validate } from '#src/helpers/validator'\nimport { requireWorkspace, workspaceQuerySchema } from '#src/helpers/workspace'\n\nimport { isLoopbackRequest } from '#src/middleware/loopback'\nimport { selectionOf } from '#src/shared/backup-scope'\nimport { actionResultSchema, backupCreatedResponseSchema, backupSelectionSchema, freePortResultSchema, okResponseSchema, restorePlanSchema, serverViewSchema, usageViewSchema } from '#src/shared/contracts'\n\n/**\n * The local control channel used by `home-hosted down` and `home-hosted start|stop`.\n *\n * It is deliberately outside `/api` (so no session is needed) and guarded by a\n * token that only the owner of `run.json` can read, plus a loopback check: a\n * different local user, or anyone on the network, gets nothing.\n */\n/** The local channel's query keys, declared so a typo is refused and the spec names them. */\nconst shutdownQuery = type({ 'withPersistent?': 'string' }).onUndeclaredKey('reject')\nconst backupQuery = type({ 'password?': 'string', 'include?': 'string', 'exclude?': 'string', 'confirm?': 'string' }).onUndeclaredKey('reject')\nconst restoreQuery = type({ 'password?': 'string', 'include?': 'string', 'exclude?': 'string', 'confirm?': 'string', 'name?': 'string', 'from?': 'string' }).onUndeclaredKey('reject')\n\nexport function createControlRoute(deps: AppDeps) {\n /** The one place the local channel's credentials are read. */\n function assertLocalCall(c: Context, action: string): void {\n const token = c.req.header('x-home-hosted-token')\n // Constant-time: this channel is outside `/api`, so the token is the only thing guarding it, and a\n // byte-by-byte timing recovery by another local user is exactly what it exists to stop.\n if (token === undefined || !secretEqual(token, deps.runtimeToken))\n throw new DetailedError('invalid token', { statusCode: 403, code: 'INVALID_TOKEN' })\n if (!isLoopbackRequest(c))\n throw new DetailedError(`only this machine may ${action}`, { statusCode: 403, code: 'NOT_LOOPBACK' })\n }\n\n return appFactory.createApp()\n .post(\n '/shutdown',\n describeRoute({\n tags: ['panel'],\n summary: 'Stop the panel and everything it supervises (local token required)',\n responses: { 200: { description: 'Stopping', content: jsonBody(okResponseSchema) }, 403: { description: 'Bad token, or not a local caller' } },\n }),\n validate('query', shutdownQuery),\n (c) => {\n assertLocalCall(c, 'stop the control panel')\n\n // `?withPersistent=true` is `down --with-persistent`: a persistent entry survives this\n // shutdown by design, so only an explicit ask ends it — and doing it here, while the\n // panel is still alive, is what records the stop.\n const withPersistent = c.req.query('withPersistent') === 'true'\n // Deferred: the answer has to reach `down` before the process goes away.\n afterResponse(() => deps.onShutdown({ withPersistent }), error => logger.error('shutdown failed', error))\n\n return c.json({ ok: true })\n },\n )\n\n .post(\n '/servers/:id/start',\n describeRoute({\n tags: ['panel'],\n summary: 'Start one server, without a session (local token required)',\n responses: { 200: { description: 'Started', content: jsonBody(actionResultSchema) }, 403: { description: 'Bad token, or not a local caller' }, 404: { description: 'No such server' }, 409: { description: 'The entry cannot act right now: disabled, stopping, or port in use (`ACTION_FAILED`)' } },\n }),\n validate('query', workspaceQuerySchema),\n async (c) => {\n assertLocalCall(c, 'start or stop a server')\n const runtime = requireWorkspace(deps.panel.requireWorkspace.bind(deps.panel), c.req.valid('query').workspace)\n const result = await runtime.supervisor.start(c.req.param('id'), { actor: 'user' })\n return c.json(actionAnswer(result), statusForAction(result))\n },\n )\n\n /**\n * One server's live view, over the local channel.\n *\n * A read, like `GET /_hh/usage`: `start` returns the moment the process is spawned, which is\n * right for the panel but wrong for a script — `start x && curl x` raced every boot, and an\n * entry whose command exits immediately still reported \"started\". The CLI asks this a moment\n * later and tells the truth, rather than re-deriving the state from a second source.\n */\n .get(\n '/servers/:id',\n describeRoute({\n tags: ['panel'],\n summary: 'One server\\'s live state, without a session (local token required)',\n responses: { 200: { description: 'The view', content: jsonBody(serverViewSchema) }, 403: { description: 'Bad token, or not a local caller' }, 404: { description: 'No such server' } },\n }),\n validate('query', workspaceQuerySchema),\n (c) => {\n assertLocalCall(c, 'read one server')\n const runtime = requireWorkspace(deps.panel.requireWorkspace.bind(deps.panel), c.req.valid('query').workspace)\n const id = c.req.param('id')\n const view = runtime.supervisor.views().find(entry => entry.id === id)\n if (view === undefined)\n throw new DetailedError(`unknown server \"${id}\"`, { statusCode: 404, code: 'UNKNOWN_SERVER' })\n return c.json(view)\n },\n )\n\n .post(\n '/servers/:id/stop',\n describeRoute({\n tags: ['panel'],\n summary: 'Stop one server, without a session (local token required)',\n responses: { 200: { description: 'Stopped', content: jsonBody(actionResultSchema) }, 403: { description: 'Bad token, or not a local caller' }, 404: { description: 'No such server' }, 409: { description: 'The entry cannot act right now: disabled, stopping, or port in use (`ACTION_FAILED`)' } },\n }),\n validate('query', workspaceQuerySchema),\n async (c) => {\n assertLocalCall(c, 'start or stop a server')\n const runtime = requireWorkspace(deps.panel.requireWorkspace.bind(deps.panel), c.req.valid('query').workspace)\n const result = await runtime.supervisor.stop(c.req.param('id'))\n return c.json(actionAnswer(result), statusForAction(result))\n },\n )\n\n // The panel's own `restart` is the daemon; this is one entry. The UI has had a Restart\n // button on every server card, and the supervisor has always had `restart()`, so the\n // shell was the only client that could not do it.\n .post(\n '/servers/:id/restart',\n describeRoute({\n tags: ['panel'],\n summary: 'Restart one server, without a session (local token required)',\n responses: { 200: { description: 'Restarted', content: jsonBody(actionResultSchema) }, 403: { description: 'Bad token, or not a local caller' }, 404: { description: 'No such server' }, 409: { description: 'The entry cannot act right now: disabled, stopping, or port in use (`ACTION_FAILED`)' } },\n }),\n validate('query', workspaceQuerySchema),\n async (c) => {\n assertLocalCall(c, 'restart a server')\n const runtime = requireWorkspace(deps.panel.requireWorkspace.bind(deps.panel), c.req.valid('query').workspace)\n const result = await runtime.supervisor.restart(c.req.param('id'), { actor: 'user' })\n return c.json(actionAnswer(result), statusForAction(result))\n },\n )\n\n // The UI has had a **Free port** button; the shell could not reach it. It is a destructive\n // action (it signals processes the panel does not own), so it is a command of its own with the\n // same refusals rather than a flag on `start` — `start --free-port` is the convenient spelling\n // and adds nothing to the rules.\n .post(\n '/servers/:id/free-port',\n describeRoute({\n tags: ['panel'],\n summary: 'Free one server\\'s port, without a session (local token required)',\n responses: {\n 200: { description: 'What was signalled', content: jsonBody(freePortResultSchema) },\n 403: { description: 'Bad token, or not a local caller' },\n 404: { description: 'No such server' },\n 409: { description: 'Nothing to free, or the holder is supervised by this panel' },\n },\n }),\n validate('query', workspaceQuerySchema),\n async (c) => {\n assertLocalCall(c, 'free a server\\'s port')\n const runtime = requireWorkspace(deps.panel.requireWorkspace.bind(deps.panel), c.req.valid('query').workspace)\n const result = await runtime.supervisor.freePort(c.req.param('id'))\n // `ok: false` carries the sentence a person acts on, and the status says which kind of\n // failure it was — the same pair the `/api` route answers, so the two cannot disagree.\n return c.json(actionAnswer(result), statusForAction(result))\n },\n )\n\n /**\n * Backups over the local channel, so an operator (or a cron job) can take and restore one\n * without a browser session. The panel stays the only writer: these call the same service the\n * `/api/backups` routes do, so the archive shape and the allowlist cannot drift.\n */\n .get(\n '/backups',\n describeRoute({\n tags: ['panel'],\n summary: 'List the stored backup archives (local token required)',\n responses: { 200: { description: 'The archives', content: jsonBody(backupSelectionSchema) }, 403: { description: 'Bad token, or not a local caller' } },\n }),\n (c) => {\n assertLocalCall(c, 'list backups')\n return c.json(deps.backups.selection())\n },\n )\n\n /**\n * Every server's live resource reading, over the local channel.\n *\n * A read, like `GET /_hh/backups`: `home-hosted usage` is the operator's \"which of my twelve\n * services is eating memory\" question, and the answer already exists on every view. Putting it\n * on `/_hh` keeps the CLI on its own token-plus-loopback channel instead of opening an `/api`\n * route or inventing a browser session.\n *\n * Absent readings stay absent — a stopped entry sends no `cpuPercent`/`rssBytes` rather than a\n * zero, which is the same rule the metrics scrape follows.\n */\n .get(\n '/usage',\n describeRoute({\n tags: ['panel'],\n summary: 'Every server\\'s live CPU and memory (local token required)',\n responses: { 200: { description: 'The readings', content: jsonBody(usageViewSchema) }, 403: { description: 'Bad token, or not a local caller' } },\n }),\n (c) => {\n assertLocalCall(c, 'read resource usage')\n return c.json(buildUsage(deps))\n },\n )\n\n .post(\n '/backups',\n describeRoute({\n tags: ['panel'],\n summary: 'Create a backup archive (local token required)',\n responses: { 200: { description: 'Created', content: jsonBody(backupCreatedResponseSchema) }, 400: ERROR_RESPONSES[400], 403: { description: 'Bad token, or not a local caller' } },\n }),\n validate('query', backupQuery),\n async (c) => {\n assertLocalCall(c, 'create a backup')\n // Query, not body: the local channel's request helper sends no payload, and `workspace`\n // already travels this way. The password is in the URL on loopback only, which is the same\n // trust boundary as the token in the header.\n const password = c.req.query('password')\n const include = c.req.query('include')?.split(',').filter(part => part.length > 0)\n const exclude = c.req.query('exclude')?.split(',').filter(part => part.length > 0)\n // Without `confirm` this answers the plan and writes nothing, so a script can read what a\n // backup would capture before taking one.\n if (c.req.query('confirm') !== 'true') {\n // `selection()` for the entries, `view()` for `includePaths`: the model is off the state\n // frame now, and a plan still needs both halves.\n const view = deps.backups.selection()\n const includePaths = deps.backups.view().includePaths\n // The service's own selection rule, so the plan cannot disagree with what an apply writes —\n // that divergence is exactly how `--exclude` would work on backup and do nothing in a plan.\n const selects = selectionOf({ include, exclude })\n // Leaves are filtered as well as entries: a plan naming a leaf the apply will leave out is\n // a plan for a different backup.\n // A leaf selection keeps its parent entry in the plan: `--include workspace:default:servers`\n // captures that one file, and a plan showing nothing for it describes no backup at all.\n const namesLeafOf = (id: string): boolean =>\n include !== undefined && include.some(entry => entry.startsWith(`${id}:`))\n const entries = view.entries\n .filter(entry => selects(entry.id) || namesLeafOf(entry.id))\n .map(entry => ({ ...entry, items: entry.items.filter(item => selects(item.id)) }))\n return c.json({ apply: false, entries, includePaths })\n }\n const result = await deps.backups.create({ password, include, exclude })\n if (!result.ok)\n throw new DetailedError(result.error ?? 'the backup failed', { statusCode: 400, code: 'BACKUP_FAILED' })\n return c.json({ file: result.file, files: deps.backups.list() })\n },\n )\n\n .post(\n '/backups/restore',\n describeRoute({\n tags: ['panel'],\n summary: 'Plan or apply a restore from a stored archive or a file on this machine (local token required)',\n responses: { 200: { description: 'The plan', content: jsonBody(restorePlanSchema) }, 400: ERROR_RESPONSES[400], 403: { description: 'Bad token, or not a local caller' }, 404: ERROR_RESPONSES[404] },\n }),\n validate('query', restoreQuery),\n async (c) => {\n assertLocalCall(c, 'restore a backup')\n const confirm = c.req.query('confirm') === 'true'\n const name = c.req.query('name')\n const from = c.req.query('from')\n // `name` (an allowlist entry in the backups directory) or `from` (a file anywhere) — exactly\n // one. Both name the same thing, so taking one silently would be a guess on the destructive\n // path, and `--from` is additive: a caller still passing `name` keeps the behaviour it had.\n //\n // `from` is a new input class, so the question \"can it escape the restore allowlist\" is\n // answered here: it changes only where the bytes are *read* from. A restore writes to a\n // staging directory it creates, then only to the paths the live config declares, and every\n // entry is checked by `admitArchive` — so an arbitrary path cannot reach a write target that\n // a name-in-the-directory could not. Nor does it widen who may call: the local channel needs\n // run.json's token and a loopback peer, which is the same user who could read that file\n // without the panel at all.\n if (from !== undefined && from.length > 0 && name !== undefined && name.length > 0)\n throw new DetailedError('pass name or from, not both', { statusCode: 400, code: 'NAME_AND_FROM' })\n if (from === undefined || from.length === 0) {\n if (name === undefined || name.length === 0)\n throw new DetailedError('name is required', { statusCode: 400, code: 'MISSING_NAME' })\n // `resolve` is the allowlist: it refuses anything that is not a plain archive name.\n const archive = deps.backups.resolve(name)\n if (archive === null)\n throw new DetailedError(`no backup named \"${name}\"`, { statusCode: 404, code: 'BACKUP_NOT_FOUND' })\n const include = c.req.query('include')?.split(',').filter(part => part.length > 0)\n const exclude = c.req.query('exclude')?.split(',').filter(part => part.length > 0)\n return c.json(await deps.backups.restore(archive, { confirm, password: c.req.query('password'), include, exclude }))\n }\n\n // Absolute only: this process's working directory is not the caller's, so a relative path\n // would silently read a different file than the one the person typed.\n if (!path.isAbsolute(from))\n throw new DetailedError('from must be an absolute path — the panel would resolve a relative one against its own directory', { statusCode: 400, code: 'FROM_NOT_ABSOLUTE' })\n const include = c.req.query('include')?.split(',').filter(part => part.length > 0)\n const exclude = c.req.query('exclude')?.split(',').filter(part => part.length > 0)\n return c.json(await deps.backups.restore(from, { confirm, password: c.req.query('password'), include, exclude }))\n },\n )\n}\n\n/**\n * Every server's live reading, flattened across workspaces.\n *\n * Built from the same views the state frame publishes, so the CLI and the page cannot disagree\n * about what a server is using. A reading is copied as a **value**: an entry with no sample omits\n * the key rather than sending `0`, because a `0` on a CPU gauge reads as \"idle\" and hides a server\n * the sampler is not measuring at all.\n */\nfunction buildUsage(deps: AppDeps): { servers: Array<Record<string, unknown>>, sampledAt?: number } {\n const state = deps.panel.getState()\n const servers = state.workspaces.flatMap(workspace => workspace.servers.map((server) => {\n const resources = server.resources\n // The window's behaviour, from the same `ServerView.history` the page reads — a live snapshot\n // cannot say \"this has restarted nine times in the last hour\", which is what a flapping entry\n // looks like from a terminal.\n const history = server.history\n return {\n id: server.id,\n workspaceId: server.workspaceId ?? workspace.id,\n label: server.config.label ?? server.id,\n status: server.status,\n ...(resources?.cpuPercent == null ? {} : { cpuPercent: resources.cpuPercent }),\n ...(resources?.rssBytes == null ? {} : { rssBytes: resources.rssBytes }),\n ...(resources == null ? {} : { processes: resources.processes, sampledAt: resources.sampledAt }),\n ...(history == null\n ? {}\n : {\n restarts: history.restarts,\n crashes: history.crashes,\n ...(history.uptimeRatio == null ? {} : { uptimeRatio: history.uptimeRatio }),\n ...(history.lastExitAt == null ? {} : { lastExitAt: history.lastExitAt }),\n }),\n }\n }))\n return {\n servers,\n ...(state.host.sampledAt == null ? {} : { sampledAt: state.host.sampledAt }),\n }\n}\n","import type { AppDeps } from '#src/app'\nimport type { WorkspaceRuntime } from '#src/services/panel'\nimport type { DdnsConfig } from '#src/shared/contracts'\nimport { DetailedError } from '@namesmt/utils'\nimport { type } from 'arktype'\nimport { describeRoute } from 'hono-openapi'\nimport { ConfigError } from '#src/config/store'\nimport { appFactory } from '#src/helpers/factory'\nimport { logger } from '#src/helpers/logger'\nimport { ERROR_RESPONSES, jsonBody } from '#src/helpers/openapi'\nimport { validate } from '#src/helpers/validator'\nimport { requireWorkspace, workspaceQuerySchema } from '#src/helpers/workspace'\nimport { ddnsProvider, ddnsProviderInfos, validateDdnsConfig } from '#src/providers/ddns'\nimport { ddnsConfigSchema, ddnsCredentialsSchema, ddnsViewSchema } from '#src/shared/contracts'\n\nconst accountParam = type({ id: '/^[a-z0-9][a-z0-9_-]*$/' })\n\n/**\n * Dynamic DNS is configured as one whole block, not as settings patches: its\n * accounts and hostnames are lists, and a key-by-key merge would leave a removed\n * account or hostname behind. Provider credentials never come back over the API —\n * the view only says which accounts have them.\n *\n * It is workspace-scoped: each workspace keeps its own hostnames, credentials and\n * DDNS state under its directory.\n */\nexport function createDdnsRoute(deps: AppDeps) {\n const view = (runtime: WorkspaceRuntime) => {\n const config = runtime.store.ddns\n return {\n config,\n status: runtime.ddns.view,\n providers: ddnsProviderInfos(),\n // An id with a stored secret counts as saved even before the account itself is\n // — that is the draft flow. Once the config declares it, the provider has to\n // match the entry, or the badge would claim credentials that cannot be used.\n credentials: runtime.secrets.ddnsAccountIds.filter((id) => {\n const account = config.accounts.find(entry => entry.id === id)\n return account === undefined || runtime.secrets.getDdnsCredentials(id, account.provider) !== null\n }),\n }\n }\n\n return appFactory.createApp()\n .get(\n '/ddns',\n describeRoute({\n tags: ['ddns'],\n summary: 'Dynamic DNS policy, live state and the providers this build knows',\n responses: { 200: { description: 'The DDNS view', content: jsonBody(ddnsViewSchema) } },\n }),\n validate('query', workspaceQuerySchema),\n (c) => {\n const runtime = requireWorkspace(deps.panel.requireWorkspace.bind(deps.panel), c.req.valid('query').workspace)\n return c.json(view(runtime))\n },\n )\n\n .put(\n '/ddns',\n describeRoute({\n tags: ['ddns'],\n summary: 'Replace the dynamic DNS block',\n responses: { 200: { description: 'Saved', content: jsonBody(ddnsViewSchema) }, 400: ERROR_RESPONSES[400] },\n }),\n validate('query', workspaceQuerySchema),\n validate('json', ddnsConfigSchema),\n (c) => {\n const runtime = requireWorkspace(deps.panel.requireWorkspace.bind(deps.panel), c.req.valid('query').workspace)\n const config: DdnsConfig = c.req.valid('json')\n const problems = validateDdnsConfig(config)\n if (problems.length > 0)\n throw new DetailedError(`invalid DDNS configuration: ${problems.join('; ')}`, { statusCode: 400, code: 'INVALID_DDNS', detail: problems })\n\n try {\n runtime.store.updateDdns(config)\n }\n catch (error) {\n if (error instanceof ConfigError)\n throw new DetailedError(error.message, { statusCode: 400, code: 'INVALID_DDNS' })\n throw error\n }\n\n // A removed account takes its stored secret with it; without this, a token\n // typed for a draft that was never saved would sit in the file forever.\n const pruned = runtime.secrets.pruneDdnsCredentials(config.accounts.map(account => account.id))\n if (pruned > 0)\n logger.info(`ddns: dropped stored credentials for ${pruned} account(s) the config no longer declares`)\n\n // A config edit is a reason to look again now, not on the next interval.\n runtime.ddns.refresh()\n return c.json(view(runtime))\n },\n )\n\n .put(\n '/ddns/credentials/:id',\n describeRoute({\n tags: ['ddns'],\n summary: 'Store the credentials of one DDNS account',\n responses: { 200: { description: 'Stored', content: jsonBody(ddnsViewSchema) }, 400: ERROR_RESPONSES[400] },\n }),\n validate('query', workspaceQuerySchema),\n validate('param', accountParam),\n validate('json', ddnsCredentialsSchema),\n (c) => {\n const runtime = requireWorkspace(deps.panel.requireWorkspace.bind(deps.panel), c.req.valid('query').workspace)\n const { id } = c.req.valid('param')\n const { provider: providerId, credentials } = c.req.valid('json')\n\n // The account itself may still be an unsaved draft; only its provider is needed.\n const provider = ddnsProvider(providerId)\n if (provider === null)\n throw new DetailedError(`unknown DDNS provider \"${providerId}\"`, { statusCode: 400, code: 'UNKNOWN_DDNS_PROVIDER' })\n\n const problem = provider.validate(credentials)\n if (problem !== null)\n throw new DetailedError(`${provider.label}: ${problem}`, { statusCode: 400, code: 'INVALID_DDNS_CREDENTIALS' })\n\n runtime.secrets.setDdnsCredentials(id, providerId, credentials)\n runtime.ddns.refresh({ account: id })\n return c.json(view(runtime))\n },\n )\n\n .delete(\n '/ddns/credentials/:id',\n describeRoute({\n tags: ['ddns'],\n summary: 'Forget the credentials of one DDNS account',\n responses: { 200: { description: 'Removed', content: jsonBody(ddnsViewSchema) } },\n }),\n validate('query', workspaceQuerySchema),\n validate('param', accountParam),\n (c) => {\n const runtime = requireWorkspace(deps.panel.requireWorkspace.bind(deps.panel), c.req.valid('query').workspace)\n const { id } = c.req.valid('param')\n runtime.secrets.clearDdnsCredentials(id)\n runtime.ddns.refresh({ account: id })\n return c.json(view(runtime))\n },\n )\n\n .post(\n '/ddns/check',\n describeRoute({\n tags: ['ddns'],\n summary: 'Run a dynamic DNS pass now',\n responses: { 200: { description: 'The pass, with its result', content: jsonBody(ddnsViewSchema) } },\n }),\n validate('query', workspaceQuerySchema),\n async (c) => {\n const runtime = requireWorkspace(deps.panel.requireWorkspace.bind(deps.panel), c.req.valid('query').workspace)\n await runtime.ddns.run({ force: true })\n return c.json(view(runtime))\n },\n )\n}\n","import type { SSEStreamingApi } from 'hono/streaming'\n\n/** Log frames queued past this are dropped; a client that falls behind loses output, not state. */\nconst MAX_QUEUED_LOGS = 200\n\ninterface Frame {\n event: string\n data: string\n /** Frames sharing a key supersede each other; `null` is a frame that never coalesces. */\n key: string | null\n}\n\n/**\n * One subscriber's outbound queue, bounded whatever the client does.\n *\n * A client that stops reading without disconnecting must not grow the panel's memory: a queued\n * `state` or `server` frame is replaced by the newer one (only the latest snapshot matters), and log\n * frames are dropped once too many are waiting.\n */\nexport function sseChannel(stream: SSEStreamingApi) {\n const queue: Frame[] = []\n const state = { closed: false }\n let writing = false\n\n const pump = async (): Promise<void> => {\n if (writing)\n return\n writing = true\n try {\n while (!state.closed && queue.length > 0) {\n const frame = queue.shift()!\n await stream.writeSSE({ event: frame.event, data: frame.data })\n }\n }\n catch {\n state.closed = true\n queue.length = 0\n }\n finally {\n writing = false\n }\n }\n\n return {\n get closed(): boolean {\n return state.closed\n },\n close(): void {\n state.closed = true\n queue.length = 0\n },\n /** Queue a frame: `key` makes it supersede a queued frame with the same key; `droppable` caps it. */\n send(event: string, data: string, options: { key?: string, droppable?: boolean } = {}): void {\n if (state.closed)\n return\n const key = options.key ?? null\n if (key !== null) {\n const index = queue.findIndex(frame => frame.key === key)\n if (index !== -1) {\n queue[index] = { event, data, key }\n return\n }\n }\n else if (options.droppable === true && queue.filter(frame => frame.event === event).length >= MAX_QUEUED_LOGS) {\n return\n }\n queue.push({ event, data, key })\n void pump()\n },\n }\n}\n\n/** The coalescing key for a hub message: snapshots supersede, logs and one-offs do not. */\nexport function frameKey(message: { type: string, workspaceId?: string, serverId?: string }): string | undefined {\n if (message.type === 'state')\n return 'state'\n if (message.type === 'server')\n return `server:${message.workspaceId ?? ''}/${message.serverId ?? ''}`\n return undefined\n}\n","/**\n * The SSE bucket key: one server inside one workspace.\n *\n * A server id is only unique within its workspace, so anything keyed by id alone mixes frames between\n * same-named servers — and this key was **three separate definitions**: `services/events.ts` (which\n * dispatches) and both UIs' composables (which subscribe). Byte-identical today, but a change to the\n * format on either side would route messages to the wrong bucket or to none, silently — the panel\n * would simply stop updating, with nothing to error on.\n *\n * It lives in `src/shared` rather than a UI because this module imports no Vue and is reachable from\n * the server and both UIs alike.\n */\nexport function serverKey(workspaceId: string, serverId: string): string {\n return `${workspaceId}/${serverId}`\n}\n","import type { SseMessage } from '#src/shared/contracts'\nimport { serverKey } from '#src/shared/server-key'\n\nexport type EventListener = (message: SseMessage) => void\n\nconst ALL = '*'\n\n/**\n * Fan-out for SSE subscribers, optionally scoped to one server.\n *\n * The scope is `workspaceId/serverId`, never the bare id: server ids are only\n * unique *within* a workspace, so keying on the id alone would deliver one\n * workspace's log lines to a subscriber watching another workspace's server of\n * the same name.\n */\n// One definition, in `src/shared`: the UIs subscribe with the same key, and a divergence here would\n// route frames to the wrong bucket with nothing to error on. Re-exported so callers are unchanged.\nexport { serverKey } from '#src/shared/server-key'\n\nexport class EventHub {\n private readonly listeners = new Map<string, Set<EventListener>>()\n\n subscribe(key: string | null, listener: EventListener): () => void {\n const bucketKey = key ?? ALL\n const bucket = this.listeners.get(bucketKey) ?? new Set<EventListener>()\n bucket.add(listener)\n this.listeners.set(bucketKey, bucket)\n\n return () => {\n bucket.delete(listener)\n if (bucket.size === 0)\n this.listeners.delete(bucketKey)\n }\n }\n\n publish(message: SseMessage): void {\n this.dispatch(ALL, message)\n if ((message.type === 'server' || message.type === 'log') && message.workspaceId)\n this.dispatch(serverKey(message.workspaceId, message.serverId), message)\n }\n\n private dispatch(key: string, message: SseMessage): void {\n const bucket = this.listeners.get(key)\n if (!bucket)\n return\n for (const listener of [...bucket]) {\n try {\n listener(message)\n }\n catch {\n bucket.delete(listener)\n }\n }\n }\n}\n","import type { AppDeps } from '#src/app'\nimport type { SseMessage } from '#src/shared/contracts'\nimport { type } from 'arktype'\nimport { describeRoute } from 'hono-openapi'\nimport { streamSSE } from 'hono/streaming'\nimport { appFactory } from '#src/helpers/factory'\nimport { frameKey, sseChannel } from '#src/helpers/sse'\nimport { validate } from '#src/helpers/validator'\nimport { serverKey } from '#src/services/events'\n\nconst PING_INTERVAL_MS = 15000\n\nconst eventsQuery = type({\n /** Only this server's frames. */\n 'serverId?': 'string',\n /** Only this workspace's server and log frames. */\n 'workspace?': 'string',\n /** `logs=0` drops log frames; the first frame is always the full state. */\n 'logs?': 'string',\n}).onUndeclaredKey('reject')\n\n/**\n * One SSE stream per subscriber. `?workspace=<id>` narrows server and log frames to one workspace,\n * `&serverId=<id>` to one server; the first frame always carries the full state snapshot.\n */\nexport function createEventsRoute(deps: AppDeps) {\n return appFactory.createApp()\n .get(\n '/events',\n describeRoute({\n tags: ['panel'],\n summary: 'Panel state and log frames as server-sent events',\n responses: { 200: { description: 'text/event-stream' } },\n }),\n validate('query', eventsQuery),\n (c) => {\n const query = c.req.valid('query')\n const serverId = query.serverId ?? null\n const workspaceId = query.workspace ?? null\n const includeLogs = query.logs !== '0'\n\n return streamSSE(c, async (stream) => {\n const channel = sseChannel(stream)\n const send = (message: SseMessage): void => {\n channel.send(message.type, JSON.stringify(message), { key: frameKey(message), droppable: message.type === 'log' })\n }\n\n // A named workspace scopes the subscription to one `workspaceId/serverId`;\n // a bare id keeps working but can only be filtered, because the same id may\n // exist in several workspaces.\n const subscription = workspaceId !== null && serverId !== null\n ? serverKey(workspaceId, serverId)\n : null\n const unsubscribe = deps.hub.subscribe(subscription, (message) => {\n if (!includeLogs && message.type === 'log')\n return\n // A state frame carries no server, so a single-server subscription skips it too.\n if (subscription === null && serverId !== null && (!('serverId' in message) || message.serverId !== serverId))\n return\n // `?workspace=` alone narrows server and log frames; state frames are panel-wide.\n if (subscription === null && workspaceId !== null && 'workspaceId' in message && message.workspaceId !== workspaceId)\n return\n send(message)\n })\n\n stream.onAbort(() => {\n channel.close()\n unsubscribe()\n })\n\n send({ type: 'hello', ts: Date.now(), state: deps.panel.getState() })\n\n while (!channel.closed) {\n await stream.sleep(PING_INTERVAL_MS)\n channel.send('ping', String(Date.now()), { key: 'ping' })\n }\n })\n },\n )\n}\n","import type { HealthState, ServerStatus } from './contracts'\n\n/**\n * Whether one entry is a problem someone has to look at.\n *\n * Every surface that answers \"is anything wrong\" asks this question — the panel's own `/healthz`,\n * which an external monitor polls, and the three \"needs attention\" counts and filters the UIs draw\n * — and it was written out at **seven** call sites as a hand-picked disjunction. They had already\n * disagreed, in both directions, and each disagreement was invisible from the surface that got it\n * right:\n *\n * - **`/healthz` said `ok` with a `conflict` entry.** Its filter named `crashed`, `stoppedByPanel`\n * and a running-unhealthy entry, but not `conflict` — the status that means \"this entry cannot\n * start because its port is held\". Measured on a panel whose only entry was blocked:\n * `GET /healthz` → `200 {\"status\":\"ok\"}` while `GET /_hh/usage` and the card both read\n * `web conflict`. A monitor watching that endpoint reported a healthy home with a server down.\n *\n * - **The UIs said nothing about an entry the panel itself gave up on.** They read `health` and\n * `status` but never `stoppedByPanel`, so an entry stopped after its health budget was spent\n * counted as \"stopped\", which is the status the same predicate deliberately treats as fine. The\n * card kept its reason on `lastError` and `/healthz` answered 503, so the one page a person opens\n * to find out what broke was the one place it was not counted.\n *\n * Both are the same defect: a question with several right answers, decided once per call site. The\n * list is read from the **status enum**, not from whichever statuses a given surface happened to\n * think of, and `stoppedByPanel` is part of it because `stopped` cannot say which stop it was.\n *\n * A deliberate stop is not here, and that is the distinction the statuses exist to make: stopping\n * sets `stopped`, never `crashed` or `conflict`. `stoppedByPanel` is the exception, because the\n * panel stopping an entry that cannot serve is a broken service, not an operator's decision.\n */\nexport interface AttentionSource {\n status: ServerStatus\n health?: HealthState\n /** Optional so a newer UI reading an older panel's frame still parses it. */\n stoppedByPanel?: boolean\n}\n\nexport function needsAttention(server: AttentionSource): boolean {\n // `crashed`: it died and stayed dead. `conflict`: it cannot start — its port is held, or a stop\n // could not end it. Both are the entry being down for a reason nobody chose.\n if (server.status === 'crashed' || server.status === 'conflict')\n return true\n // The panel gave up on it: `stopped`, but not because someone asked.\n if (server.stoppedByPanel === true)\n return true\n // Up and failing its own check. `status === 'running'` is load-bearing: `health` keeps its last\n // value through a stop, so a stopped entry would otherwise hold the panel degraded for ever.\n return server.status === 'running' && server.health === 'unhealthy'\n}\n","import type { Context } from 'hono'\nimport type { AppDeps } from '#src/app'\nimport process from 'node:process'\nimport { describeRoute } from 'hono-openapi'\nimport { appFactory } from '#src/helpers/factory'\nimport { jsonBody } from '#src/helpers/openapi'\nimport { secretEqual } from '#src/helpers/secret-compare'\nimport { requestIdentity } from '#src/middleware/auth'\nimport { healthResponseSchema } from '#src/shared/contracts'\nimport { needsAttention } from '#src/shared/server-attention'\n\n/**\n * Liveness for external monitors. Mounted outside `/api`, so it answers without a\n * session: it reports whether the panel itself is serving, and 503 while any entry\n * `needsAttention` — crashed, blocked on its port, given up on by the panel, or running and\n * failing its own health check. Server details are only included for an authenticated caller.\n */\nexport function createHealthRoute(deps: AppDeps) {\n return appFactory.createApp()\n .get(\n '/healthz',\n describeRoute({\n tags: ['panel'],\n summary: 'Liveness for monitors — no session required',\n responses: {\n 200: {\n description: 'Serving',\n content: jsonBody(healthResponseSchema),\n },\n 503: {\n description: 'An entry needs attention: crashed, blocked on its port, stopped by the panel, or running and unhealthy',\n /**\n * The same schema as the 200, because a degraded panel answers the same document with\n * `status: \"degraded\"`. Leaving `content` off made `finishSpec` stamp the error envelope\n * onto it — every declared status ≥ 400 gets one — so the published spec told a generated\n * monitor client to expect `{ message, code }` from the one endpoint whose whole job is\n * machine consumption, and a degraded-but-working panel read as unparseable.\n */\n content: jsonBody(healthResponseSchema),\n },\n },\n }),\n (c) => {\n const state = deps.panel.getState()\n // Every workspace's servers, so a crash anywhere degrades the panel.\n const servers = state.workspaces.flatMap(workspace => workspace.servers)\n // One predicate, shared with the UIs, so this endpoint and the pages cannot disagree about\n // what \"broken\" means — they had, in both directions. See `#src/shared/server-attention`.\n const broken = servers.filter(needsAttention)\n // Detail is for a signed-in browser, an API token, or the local channel's token. The status\n // line stays public, which is the whole point of a monitor endpoint.\n //\n // The local token is a **different secret** from the API bearer token, and it is the one\n // `run.json` hands the CLI. Without it here `status` could see \"degraded\" but not the count,\n // while `usage` read the same numbers over `/_hh` — the gap was `status` using a channel that\n // refused it, not the data being unavailable.\n const authenticated = requestIdentity(c, deps.auth).authenticated || localTokenValid(c, deps)\n\n return c.json({\n status: broken.length > 0 ? 'degraded' : 'ok',\n uptimeMs: Math.round(process.uptime() * 1000),\n ...(authenticated\n ? {\n servers: {\n total: servers.length,\n running: servers.filter(server => server.status === 'running').length,\n crashed: servers.filter(server => server.status === 'crashed').length,\n unhealthy: servers.filter(server => server.health === 'unhealthy').length,\n },\n hostAlerts: state.host.alerts,\n }\n : {}),\n }, broken.length > 0 ? 503 : 200)\n },\n )\n}\n\n/**\n * Whether the caller proved itself with the local channel's token.\n *\n * The same secret `assertLocalCall` reads, checked the same constant-time way — it means \"a process\n * that can read this home's `run.json`\", which is exactly the trust the CLI already has. Loopback\n * alone is deliberately not enough: any local user could reach the port.\n */\nfunction localTokenValid(c: Context, deps: AppDeps): boolean {\n const token = c.req.header('x-home-hosted-token')\n return token !== undefined && secretEqual(token, deps.runtimeToken)\n}\n","import type { AppDeps } from '#src/app'\nimport fs, { createReadStream } from 'node:fs'\nimport path from 'node:path'\nimport { Readable } from 'node:stream'\nimport { DetailedError } from '@namesmt/utils'\nimport { type } from 'arktype'\nimport { describeRoute } from 'hono-openapi'\nimport { unknownServerError } from '#src/helpers/action-result'\nimport { appFactory } from '#src/helpers/factory'\nimport { ERROR_RESPONSES, jsonBody } from '#src/helpers/openapi'\nimport { validate } from '#src/helpers/validator'\nimport { requireWorkspace, workspaceQuerySchema } from '#src/helpers/workspace'\nimport { logHistoryQuerySchema, logLinesResponseSchema, logServersViewSchema, okResponseSchema } from '#src/shared/contracts'\n\n/** Bounds for the tail query, so a bad client cannot ask for the whole file. */\nconst MIN_TAIL = 50\nconst MAX_TAIL = 5000\nconst DEFAULT_TAIL = 500\n\nconst idParam = type({ id: 'string >= 1' })\n// The workspace schema is the **argument** in both, and that is what keeps these strict: `merge`\n// takes the argument's `onUndeclaredKey`, so `extra.merge(workspaceQuerySchema)` refuses a\n// misspelt key while `workspaceQuerySchema.merge(extra)` would have lost the rejection and run the\n// request against the default workspace.\nconst downloadQuery = type({ 'file?': 'string' }).merge(workspaceQuerySchema)\nconst historyQuery = logHistoryQuerySchema.merge(workspaceQuerySchema)\n\nexport function createLogsRoute(deps: AppDeps) {\n return appFactory.createApp()\n .get(\n '/logs',\n describeRoute({\n tags: ['logs'],\n summary: 'Every server in one workspace with its on-disk log files',\n responses: { 200: { description: 'Log sources', content: jsonBody(logServersViewSchema) } },\n }),\n validate('query', workspaceQuerySchema),\n (c) => {\n const runtime = requireWorkspace(deps.panel.requireWorkspace.bind(deps.panel), c.req.valid('query').workspace)\n return c.json({\n servers: runtime.supervisor.views().map(server => ({\n serverId: server.id,\n label: server.config.label ?? server.id,\n status: server.status,\n ...runtime.logFiles.info(server.id),\n })),\n })\n },\n )\n\n .get(\n '/logs/:id',\n describeRoute({\n tags: ['logs'],\n summary: 'Persisted log lines, with search and a stream filter',\n responses: { 200: { description: 'Lines', content: jsonBody(logLinesResponseSchema) }, 404: ERROR_RESPONSES[404] },\n }),\n validate('query', historyQuery),\n validate('param', idParam),\n (c) => {\n const runtime = requireWorkspace(deps.panel.requireWorkspace.bind(deps.panel), c.req.valid('query').workspace)\n const { id } = c.req.valid('param')\n if (!runtime.store.getServer(id))\n throw unknownServerError(id)\n\n const query = c.req.valid('query')\n const requested = query.tail === undefined ? DEFAULT_TAIL : Number.parseInt(query.tail, 10)\n const tail = Number.isNaN(requested) ? DEFAULT_TAIL : Math.min(Math.max(requested, MIN_TAIL), MAX_TAIL)\n\n const info = runtime.logFiles.info(id)\n const search = query.search?.trim() ?? ''\n const stream = query.stream ?? ''\n\n /**\n * A filter that keeps only *some* of the lines has to read a wider window than the\n * display tail, or \"the last 500 stderr lines\" silently means \"the stderr lines among\n * the last 500 overall\" — 50 of them, in a log where every tenth line is stderr, and\n * 500 exist. `search` already widened for exactly this reason; `stream` is the same\n * shape of filter and did not, so it was short whenever the two streams interleave.\n */\n const window = search.length > 0 || stream.length > 0 ? Math.max(tail, MAX_TAIL) : tail\n\n let lines = runtime.logFiles.readTail(id, window)\n if (stream.length > 0)\n lines = lines.filter(line => line.stream === stream)\n\n // What the search actually looked at, which is not always what it asked for: a log\n // shorter than the window yields fewer lines, and the UI prints this number verbatim\n // (\"searched 5000 lines\"). Reporting the *requested* window told a person reading a\n // 100-line log that 5000 lines had been searched.\n const windowLines = lines.length\n\n if (search.length > 0) {\n const needle = search.toLowerCase()\n lines = lines.filter(line => line.text.toLowerCase().includes(needle))\n }\n\n return c.json({\n serverId: id,\n enabled: info.enabled,\n sizeBytes: info.sizeBytes,\n files: info.files.map(file => file.name),\n searched: search.length > 0 ? windowLines : null,\n lines: lines.slice(-tail),\n })\n },\n )\n\n /** Raw file download; the name is checked against the rotation allowlist. */\n .get(\n '/logs/:id/download',\n describeRoute({\n tags: ['logs'],\n summary: 'Download one rotated log file',\n responses: { 200: { description: 'application/x-ndjson' }, 404: ERROR_RESPONSES[404] },\n }),\n validate('query', downloadQuery),\n validate('param', idParam),\n async (c) => {\n const runtime = requireWorkspace(deps.panel.requireWorkspace.bind(deps.panel), c.req.valid('query').workspace)\n const { id } = c.req.valid('param')\n if (!runtime.store.getServer(id))\n throw unknownServerError(id)\n\n const requested = c.req.valid('query').file ?? `${id}.log`\n const known = runtime.logFiles.info(id).files.map(file => file.name)\n if (!known.includes(requested))\n throw new DetailedError('unknown log file', { statusCode: 404, code: 'UNKNOWN_LOG_FILE' })\n\n const file = path.join(runtime.logFiles.directory, requested)\n /**\n * Streamed, not read into memory. This is the same class the archive download answers, and the\n * logs are the *bigger* case in practice: `logs.maxBytes` bounds one rotation at up to 100 MB and\n * `keep` keeps 10 of them, and a person downloads exactly when a log is large.\n *\n * Measured on the built panel with a real 100 MB rotation: `readFileSync` cost **+199 MB RSS**\n * for one download and **+402 MB** for four arriving together, `/healthz` went from 4 ms to\n * p95 859 ms / max 898 ms, and the headers only arrived after the whole read (TTFB 272 ms). The\n * archive route with the same four downloads grew **+2 MB** and answered `/healthz` in p50 17 ms.\n * `stat` gives the same `Content-Length` a client needs for a progress bar without the buffer.\n */\n const stats = await fs.promises.stat(file)\n return c.body(Readable.toWeb(createReadStream(file)) as ReadableStream, 200, {\n 'Content-Type': 'application/x-ndjson; charset=utf-8',\n 'Content-Length': String(stats.size),\n 'Content-Disposition': `attachment; filename=\"${requested}\"`,\n })\n },\n )\n\n .delete(\n '/logs/:id',\n describeRoute({\n tags: ['logs'],\n summary: 'Delete the persisted logs of one server',\n responses: { 200: { description: 'Cleared', content: jsonBody(okResponseSchema) }, 404: ERROR_RESPONSES[404] },\n }),\n validate('query', workspaceQuerySchema),\n validate('param', idParam),\n (c) => {\n const runtime = requireWorkspace(deps.panel.requireWorkspace.bind(deps.panel), c.req.valid('query').workspace)\n const { id } = c.req.valid('param')\n if (!runtime.store.getServer(id))\n throw unknownServerError(id)\n runtime.logFiles.clear(id)\n return c.json({ ok: true })\n },\n )\n}\n","import type { AppDeps } from '#src/app'\nimport type { ServerView } from '#src/shared/contracts'\nimport { describeRoute } from 'hono-openapi'\nimport { appFactory } from '#src/helpers/factory'\nimport { hostReadings } from '#src/shared/host-readings'\n\n/**\n * Escapes a value for the quoted form of a Prometheus label, per the exposition\n * format: only `\\\\`, `\"` and a newline are special, and each needs a backslash.\n *\n * A raw Windows path is the reachable case — `diskPaths` is user config and\n * `C:\\Users\\me` emits `\\U`, which is not a valid escape, so the scraper rejects the\n * whole sample. The ids are charset-constrained by their schemas, but the paths are not.\n */\nfunction labelValue(value: string): string {\n return value.replace(/\\\\/g, '\\\\\\\\').replace(/\"/g, '\\\\\"').replace(/\\n/g, '\\\\n')\n}\n\n/** A server id repeats across workspaces, so every sample names both. */\nfunction labels(server: ServerView): string {\n return `server=\"${labelValue(server.id)}\",workspace=\"${labelValue(server.workspaceId ?? '')}\"`\n}\n\n/**\n * Prometheus text for whatever wants to scrape the panel (Beszel, Grafana,\n * `curl`). Lives under `/api`, so it needs a session like every other route.\n *\n * It aggregates every workspace: each per-server sample carries its\n * `workspace` label so a same-named server in another unit is still distinct.\n */\nexport function createMetricsRoute(deps: AppDeps) {\n return appFactory.createApp()\n .get('/metrics', describeRoute({\n tags: ['panel'],\n summary: 'Prometheus text for whatever scrapes the panel',\n responses: { 200: { description: 'text/plain; version=0.0.4' } },\n }), (c) => {\n const servers = deps.panel.serverViews()\n const host = hostReadings(deps.panel.getState().host)\n const lines: string[] = []\n\n /*\n * Nothing here is a counter: every value is a snapshot a stop, a delete or a manual start\n * can lower. A name must therefore never end in `_total`, which is Prometheus' word for\n * \"monotonically increasing since the process started\" — the scrape test fails on one.\n */\n const metric = (name: string, help: string, samples: string[]): void => {\n if (samples.length === 0)\n return\n lines.push(`# HELP ${name} ${help}`, `# TYPE ${name} gauge`, ...samples)\n }\n\n metric('hh_control_up', 'Control plane is serving', ['hh_control_up 1'])\n // Adding or removing an entry moves this either way, so it is a count of what is configured\n // now — not a running total.\n metric('hh_servers', 'Configured servers', [`hh_servers ${servers.length}`])\n\n const up = servers.map(server => `hh_server_up{${labels(server)}} ${server.status === 'running' ? 1 : 0}`)\n metric('hh_server_up', 'Server process is running', up)\n\n /*\n * `restarts` is the retry budget spent on the **current** crash sequence, which a start\n * someone asked for resets to zero (`Supervisor.start()`). It was published as\n * `hh_server_restarts_total`; the `_total` suffix promises Prometheus' counter contract, and a\n * value an operator can reset makes `rate()` see a phantom reset (measured `2` → `0`). The\n * name carries no suffix now, and the HELP says the reset out loud so a dashboard author\n * reading only the scrape knows why `rate()` is the wrong query. `hh_server_crashes_24h` is\n * the series that only grows inside its window.\n */\n const restarts = servers.map(server => `hh_server_restarts{${labels(server)}} ${server.restarts}`)\n metric('hh_server_restarts', 'Restart attempts spent on the current crash sequence; a start someone asked for resets it to 0', restarts)\n\n const crashes = servers.map(server => `hh_server_crashes_24h{${labels(server)}} ${server.history.crashes}`)\n metric('hh_server_crashes_24h', 'Crashes in the last 24 hours', crashes)\n\n const uptime = servers\n .filter(server => server.history.uptimeRatio !== null)\n .map(server => `hh_server_uptime_ratio_24h{${labels(server)}} ${server.history.uptimeRatio!.toFixed(4)}`)\n /*\n * The denominator is the time this server was **observed**, not the whole window. A server added\n * ten minutes ago and up the whole time reads `1`, which is what a person means by \"up\"; dividing\n * by a fixed 24h made it read `0.0069`, indistinguishable from a dead one, and every new entry\n * tripped a \"< 99% up\" alert for its first day. The HELP states the denominator because a scrape\n * has no page to explain itself, and an alert written against the old sentence now needs to know.\n */\n metric('hh_server_uptime_ratio_24h', 'Share of the last 24h the server was up, measured over the time it was observed (a server seen for ten minutes and up throughout reads 1)', uptime)\n\n const response = servers\n .filter(server => server.responseMs !== null)\n .map(server => `hh_server_response_ms{${labels(server)}} ${server.responseMs}`)\n metric('hh_server_response_ms', 'Last health probe latency in milliseconds', response)\n\n const rss = servers\n .filter(server => server.resources?.rssBytes != null)\n .map(server => `hh_server_rss_bytes{${labels(server)}} ${server.resources!.rssBytes}`)\n metric('hh_server_rss_bytes', 'RSS of the server process tree, or the summed containers of a compose entry', rss)\n\n const cpu = servers\n .filter(server => server.resources?.cpuPercent != null)\n .map(server => `hh_server_cpu_percent{${labels(server)}} ${server.resources!.cpuPercent}`)\n metric('hh_server_cpu_percent', 'CPU percent of the server process tree, or the summed containers of a compose entry', cpu)\n\n /*\n * Every host gauge exists only once the host has actually been sampled.\n *\n * `emptyHostView()` is what `HostMonitor` starts from, and it answers `sampledAt: null` with\n * every value at zero. Emitting those published `hh_host_memory_used_percent 0` on a fresh\n * panel — or on one whose sampling is switched off — which is the one reading a homelab\n * dashboard must not invent: a memory or disk alert rule (`> 90`) stays quiet while the\n * series looks healthy and present, and `hh_host_load1_per_cpu 0.000` says \"idle\". The\n * rule is `hostReadings` (`src/shared/host-readings.ts`), which the panel's own pages read\n * too — one home, so the scrape and the page cannot disagree about whether anything was\n * measured. `enabled: false` is not enough on its own: a panel switched off *after*\n * sampling keeps its last view, which is stale, not empty.\n */\n const disks = host.disks.map(disk => `hh_host_disk_used_percent{mount=\"${labelValue(disk.path)}\"} ${disk.usedPercent.toFixed(2)}`)\n metric('hh_host_disk_used_percent', 'Disk usage percent per configured path', disks)\n\n /*\n * `cpuUsedPercent` is `null` on the first sample, which has no window to measure.\n * `loadAvg` is a **count of runnable tasks**, not a share, so it is a different unit from\n * this one and neither substitutes for the other — a dashboard that wants host CPU was\n * reaching for `hh_host_load1_per_cpu` and reading it as a percentage.\n */\n metric('hh_host_cpu_used_percent', 'Share of this machine\\'s CPU capacity in use, 0-100', host.cpuUsedPercent === null\n ? []\n : [`hh_host_cpu_used_percent ${host.cpuUsedPercent.toFixed(2)}`])\n metric('hh_host_memory_used_percent', 'Memory usage percent', host.memoryUsedPercent === null\n ? []\n : [`hh_host_memory_used_percent ${host.memoryUsedPercent.toFixed(2)}`])\n metric('hh_host_swap_used_percent', 'Swap usage percent', host.swapUsedPercent === null\n ? []\n : [`hh_host_swap_used_percent ${host.swapUsedPercent.toFixed(2)}`])\n metric('hh_host_load1_per_cpu', '1 minute load average per cpu', host.loadPerCpu === null\n ? []\n : [`hh_host_load1_per_cpu ${host.loadPerCpu.toFixed(3)}`])\n\n return c.text(`${lines.join('\\n')}\\n`, 200, { 'Content-Type': 'text/plain; version=0.0.4; charset=utf-8' })\n })\n}\n","import type { Bot } from 'grammy'\nimport { autoRetry } from '@grammyjs/auto-retry'\nimport { Bot as GrammyBot } from 'grammy'\nimport { errorMessage } from '#src/shared/error-message'\n\n/**\n * Telegram Bot API access, built on grammY.\n *\n * grammY is used for what it is good at — a typed, retrying, extensible Bot API\n * client — while the bot itself stays outbound-only for now. If inbound commands\n * or a webhook are ever wanted, the same instance can host handlers without\n * touching the notification code.\n *\n * `autoRetry` handles Telegram's 429 `retry_after` (and other transient failures)\n * so callers get either a result or a real error.\n */\n\nconst bots = new Map<string, Bot>()\n\nexport function getBot(token: string): Bot {\n const cached = bots.get(token)\n if (cached)\n return cached\n\n const bot = new GrammyBot(token, { client: { timeoutSeconds: 10 } })\n bot.api.config.use(autoRetry({ maxRetryAttempts: 3, maxDelaySeconds: 20 }))\n bots.set(token, bot)\n return bot\n}\n\n/** Drops cached clients; used when the token changes or the service shuts down. */\nexport function forgetBots(): void {\n bots.clear()\n}\n\nexport function escapeHtml(value: string): string {\n return value.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;')\n}\n\nexport function formatTelegramMessage(title: string, lines: string[]): string {\n const body = lines.filter(line => line.length > 0).map(line => `• ${escapeHtml(line)}`).join('\\n')\n return `<b>${escapeHtml(title)}</b>${body.length > 0 ? `\\n${body}` : ''}`\n}\n\nexport interface TelegramOutcome {\n ok: boolean\n error?: string\n}\n\n/** Turns a grammY error into something worth showing in the settings page. */\nexport function describeTelegramError(error: unknown): string {\n if (typeof error === 'object' && error !== null) {\n const candidate = error as { error_code?: number, description?: string, message?: string, parameters?: { retry_after?: number } }\n const description = candidate.description ?? candidate.message\n if (description) {\n const code = candidate.error_code === undefined ? '' : ` (${candidate.error_code})`\n const retry = candidate.parameters?.retry_after === undefined ? '' : `, retry in ${candidate.parameters.retry_after}s`\n return `${description}${code}${retry}`\n }\n }\n return errorMessage(error)\n}\n\nexport async function sendTelegramMessage(token: string, chatId: string, html: string): Promise<TelegramOutcome> {\n try {\n await getBot(token).api.sendMessage(chatId, html, {\n parse_mode: 'HTML',\n link_preview_options: { is_disabled: true },\n })\n return { ok: true }\n }\n catch (error) {\n return { ok: false, error: describeTelegramError(error) }\n }\n}\n\nexport async function verifyTelegramToken(token: string): Promise<{ ok: boolean, username?: string, error?: string }> {\n try {\n const me = await getBot(token).api.getMe()\n return { ok: true, username: me.username }\n }\n catch (error) {\n return { ok: false, error: describeTelegramError(error) }\n }\n}\n\nexport interface TelegramChat {\n id: number | string\n title: string\n}\n\n/**\n * Recent chats that talked to the bot, so a chat id can be picked instead of\n * hunted down by hand. Telegram only reports chats with pending updates, so the\n * caller is told to message the bot first.\n */\nexport async function listTelegramChats(token: string): Promise<{ ok: boolean, chats: TelegramChat[], error?: string }> {\n try {\n const updates = await getBot(token).api.getUpdates({\n limit: 100,\n allowed_updates: ['message', 'channel_post', 'edited_message'],\n })\n\n const chats = new Map<string, TelegramChat>()\n for (const update of updates) {\n const chat = update.message?.chat ?? update.channel_post?.chat ?? update.edited_message?.chat\n if (!chat)\n continue\n const title = 'title' in chat && chat.title\n ? chat.title\n : 'username' in chat && chat.username\n ? `@${chat.username}`\n : 'first_name' in chat && chat.first_name\n ? chat.first_name\n : 'private chat'\n chats.set(String(chat.id), { id: chat.id, title })\n }\n\n return { ok: true, chats: [...chats.values()] }\n }\n catch (error) {\n return { ok: false, chats: [], error: describeTelegramError(error) }\n }\n}\n","import type { AppDeps } from '#src/app'\nimport { DetailedError } from '@namesmt/utils'\nimport { describeRoute } from 'hono-openapi'\nimport { appFactory } from '#src/helpers/factory'\nimport { ERROR_RESPONSES, jsonBody } from '#src/helpers/openapi'\nimport { validate } from '#src/helpers/validator'\nimport { requireWorkspace, workspaceQuerySchema } from '#src/helpers/workspace'\nimport { forgetBots } from '#src/providers/telegram'\nimport { deliveryResultSchema, destinationIdParamSchema, destinationTestSchema, notificationActionSchema, okResponseSchema, telegramChatsSchema, telegramTokenSchema } from '#src/shared/contracts'\n\n/**\n * A destination's credential is written straight to a workspace's secrets file and never into a\n * servers config, so notification *policy* and the *credential* stay separate.\n *\n * Notifications belong to a workspace, and every route is scoped to one. The token is keyed by the\n * **destination id**, which is what lets a workspace point at more than one Telegram chat.\n */\nexport function createNotificationsRoute(deps: AppDeps) {\n const runtimeFor = (workspace: string | undefined) =>\n requireWorkspace(deps.panel.requireWorkspace.bind(deps.panel), workspace)\n\n return appFactory.createApp()\n .put(\n '/notifications/destinations/:id/token',\n describeRoute({\n tags: ['notifications'],\n summary: 'Store a Telegram destination\\'s bot token (verified first)',\n responses: { 200: { description: 'Stored', content: jsonBody(okResponseSchema) }, 400: ERROR_RESPONSES[400] },\n }),\n validate('query', workspaceQuerySchema),\n validate('param', destinationIdParamSchema),\n validate('json', telegramTokenSchema),\n async (c) => {\n const runtime = runtimeFor(c.req.valid('query').workspace)\n const id = c.req.valid('param').id\n const { botToken } = c.req.valid('json')\n const verified = await runtime.notifications.verifyToken(botToken)\n if (!verified.ok)\n throw new DetailedError(`telegram rejected the token: ${verified.error ?? 'unknown error'}`, { statusCode: 400, code: 'TELEGRAM_TOKEN_REJECTED' })\n\n runtime.secrets.setTelegramToken(id, botToken)\n forgetBots()\n return c.json({ ok: true, username: verified.username ?? null })\n },\n )\n\n .delete(\n '/notifications/destinations/:id/token',\n describeRoute({\n tags: ['notifications'],\n summary: 'Forget a Telegram destination\\'s bot token',\n responses: { 200: { description: 'Removed', content: jsonBody(okResponseSchema) } },\n }),\n validate('query', workspaceQuerySchema),\n validate('param', destinationIdParamSchema),\n (c) => {\n const runtime = runtimeFor(c.req.valid('query').workspace)\n runtime.secrets.setTelegramToken(c.req.valid('param').id, null)\n forgetBots()\n return c.json({ ok: true })\n },\n )\n\n .post(\n '/notifications/destinations/:id/test',\n describeRoute({\n tags: ['notifications'],\n summary: 'Send a test message to one destination',\n responses: { 200: { description: 'Sent or refused', content: jsonBody(deliveryResultSchema) }, 400: ERROR_RESPONSES[400] },\n }),\n validate('query', workspaceQuerySchema),\n validate('param', destinationIdParamSchema),\n validate('json', notificationActionSchema),\n async (c) => {\n const runtime = runtimeFor(c.req.valid('query').workspace)\n const id = c.req.valid('param').id\n /*\n * The code names the *transport*, because one route serves both kinds and a client\n * branching on it was told `TELEGRAM_SEND_FAILED` for a webhook. Measured on a webhook\n * destination whose receiver was down: `{\"message\":\"fetch failed\",\"code\":\"TELEGRAM_SEND_FAILED\"}`.\n * `test-webhook` (the draft route) already answers `WEBHOOK_SEND_FAILED`, so the same\n * failure had two names depending on which one the page called. An id that does not exist\n * keeps the Telegram wording, which is what `sendTest` itself answers (\"no such\n * destination\") — there is no kind to read.\n */\n const kind = runtime.notifications.destinations().find(destination => destination.id === id)?.kind\n const result = await runtime.notifications.sendTest(id, c.req.valid('json'))\n if (!result.ok) {\n throw new DetailedError(result.error ?? 'the test message failed', {\n statusCode: 400,\n code: kind === 'webhook' ? 'WEBHOOK_SEND_FAILED' : 'TELEGRAM_SEND_FAILED',\n })\n }\n return c.json(result)\n },\n )\n\n /**\n * Tests a webhook the page has **not saved yet**.\n *\n * The target travels whole, so a URL and its headers can be tried before they are stored — and\n * so a destination's own button tests that destination rather than the first in the list.\n */\n .post(\n '/notifications/test-webhook',\n describeRoute({\n tags: ['notifications'],\n summary: 'Send a test to one webhook destination',\n responses: { 200: { description: 'Sent or refused', content: jsonBody(deliveryResultSchema) }, 400: ERROR_RESPONSES[400] },\n }),\n validate('query', workspaceQuerySchema),\n validate('json', destinationTestSchema),\n async (c) => {\n const runtime = runtimeFor(c.req.valid('query').workspace)\n const { target, id } = c.req.valid('json')\n const result = await runtime.notifications.testWebhook(target, id)\n if (!result.ok)\n throw new DetailedError(result.error ?? 'the test message failed', { statusCode: 400, code: 'WEBHOOK_SEND_FAILED' })\n return c.json(result)\n },\n )\n\n .post(\n '/notifications/destinations/:id/detect-chats',\n describeRoute({\n tags: ['notifications'],\n summary: 'List the chats a Telegram destination\\'s bot can see',\n responses: {\n 200: { description: 'Chats', content: jsonBody(telegramChatsSchema) },\n 400: ERROR_RESPONSES[400],\n },\n }),\n validate('query', workspaceQuerySchema),\n validate('param', destinationIdParamSchema),\n validate('json', notificationActionSchema),\n async (c) => {\n const runtime = runtimeFor(c.req.valid('query').workspace)\n const result = await runtime.notifications.detectChats(c.req.valid('param').id, c.req.valid('json'))\n if (!result.ok)\n throw new DetailedError(result.error ?? 'could not list chats', { statusCode: 400, code: 'TELEGRAM_LIST_FAILED' })\n return c.json({ chats: result.chats })\n },\n )\n}\n","import type { ProxyEngine, ProxyEngineDownload, ProxyEngineRun, ProxyEngineTarget } from '#src/providers/proxy/types'\n\n/**\n * Caddy, driven through its admin API.\n *\n * The panel generates the whole JSON configuration and applies it with\n * `POST /load`, which is atomic: a configuration that does not load leaves the\n * running one in place. Plugins are compiled into the binary by Caddy's own build\n * service, so the download is a single URL that names them.\n *\n * The release is **not** pinned: an install takes whatever the build service\n * currently serves, so a security fix reaches the user by pressing Update. What the\n * panel is known to work against is written down in `docs/REVERSE_PROXY.md`; the\n * version that actually arrived is read from the binary and recorded.\n */\n\n/** The Next.js-style build service that returns a ready binary, plugins included. */\nconst BUILD_URL = 'https://caddyserver.com/api/download'\n\n/**\n * The one module this build carries: the ACMEProxy DNS provider, which lets the\n * engine ask the panel to write a DNS-01 challenge record instead of holding DNS\n * credentials itself. It is compiled in for every install, not only when DNS-01 is\n * switched on, so the binary does not depend on a setting that can change later.\n */\nconst PLUGINS = ['github.com/caddy-dns/acmeproxy']\n\n/** `process.platform` matches Caddy's own GOOS names; only the arch needs mapping. */\nfunction goArch(arch: string): string | null {\n switch (arch) {\n case 'x64': return 'amd64'\n case 'arm64': return 'arm64'\n case 'arm': return 'armv7'\n case 'ia32': return '386'\n default: return null\n }\n}\n\nexport const caddyEngine: ProxyEngine = {\n info: {\n id: 'caddy',\n label: 'Caddy',\n docsUrl: 'https://caddyserver.com/docs/',\n releaseUrl: 'https://github.com/caddyserver/caddy/releases',\n acme: true,\n internalCa: true,\n // Compiled in (see PLUGINS): the panel answers the challenge, the engine asks it.\n dns01: true,\n tcp: false,\n },\n\n binaryName(platform: NodeJS.Platform): string {\n return platform === 'win32' ? 'hh-caddy.exe' : 'hh-caddy'\n },\n\n download(target: ProxyEngineTarget): ProxyEngineDownload | null {\n const arch = goArch(target.arch)\n if (arch === null)\n return null\n if (target.platform !== 'linux' && target.platform !== 'darwin' && target.platform !== 'win32')\n return null\n\n // No `version` unless one was asked for, which is how \"the current release\" is\n // spelled. A named release is only a request: the build service answers a URL\n // that names plugins with its own current release either way.\n const wanted = target.version.length > 0 ? `&version=${encodeURIComponent(target.version)}` : ''\n const plugins = PLUGINS.map(plugin => `&p=${encodeURIComponent(plugin)}`).join('')\n const url = `${BUILD_URL}?os=${target.platform}&arch=${arch}${wanted}${plugins}`\n return { url, version: target.version }\n },\n\n runArgs(run: ProxyEngineRun): string[] {\n // No `--adapter`: the `.json` extension already selects the native adapter,\n // and Caddy has no adapter it calls \"json\".\n return ['run', '--config', run.configPath]\n },\n\n /**\n * Only a belt beside the generated config's own `storage.root`: the engine must\n * never scatter certificates under a home directory the panel does not own.\n * `APPDATA` is what Caddy calls the data directory on Windows.\n */\n env(run: ProxyEngineRun): Record<string, string> {\n return {\n XDG_DATA_HOME: `${run.engineDir}/data`,\n XDG_CONFIG_HOME: `${run.engineDir}/config`,\n APPDATA: `${run.engineDir}/appdata`,\n LOCALAPPDATA: `${run.engineDir}/localappdata`,\n }\n },\n\n /** `caddy version` prints `v2.11.4 h1:...`; the first token is the release. */\n parseVersion(output: string): string | null {\n const match = output.trim().match(/^v?(\\d+\\.\\d+\\.\\d[\\w.+-]*)/)\n return match?.[1] ?? null\n },\n}\n","import type { ProxyEngine } from '#src/providers/proxy/types'\nimport type { ProxyEngineInfo } from '#src/shared/contracts'\nimport { caddyEngine } from '#src/providers/proxy/caddy'\n\n/** Registry order is what the page offers; one engine ships today. */\nexport const PROXY_ENGINES: readonly ProxyEngine[] = [caddyEngine]\n\nconst BY_ID = new Map(PROXY_ENGINES.map(engine => [engine.info.id, engine]))\n\nexport function proxyEngine(id: string): ProxyEngine | null {\n return BY_ID.get(id as ProxyEngineInfo['id']) ?? null\n}\n\nexport function proxyEngineInfos(): ProxyEngineInfo[] {\n return PROXY_ENGINES.map(engine => engine.info)\n}\n\nexport type { ProxyAdminTransport, ProxyEngine, ProxyEngineDownload, ProxyEngineRun, ProxyEngineTarget } from '#src/providers/proxy/types'\n","import type { ProxyCertificateView, ProxyConfig, ProxyPatch, ProxyRoute, ProxyRoutePatch } from './contracts'\nimport { type } from 'arktype'\nimport { clonePlain } from './clone'\nimport { proxyRouteSchema } from './contracts'\nimport { mergeReplacedList, replacedListConflicts } from './patch-diff'\n\n/**\n * The reverse-proxy form, shared by both UIs: the route draft the table edits, the patch a save\n * sends, and the checks the panel would otherwise answer with a 400.\n *\n * These declarations were identical copies in `uis/stock` and `uis/noc-console`\n * (`parseUpstream` differs only in a doc comment, so it takes the fuller one). Eight commits had\n * touched both files, one literally \"carry the fix into the other UI\" — a measured cost.\n *\n * Nothing here may import Vue: the UIs bundle it as a devDependency while the published package\n * does not ship it, so a Vue import would break the server if it ever read this file. That is also\n * why the detach is `clonePlain` (`./clone.ts`), never `structuredClone(toRaw(...))`.\n */\n\nexport interface CertificateErrors {\n label?: string\n id?: string\n certificate?: string\n privateKey?: string\n}\n\nexport const HOST_PATTERN = /^[a-z0-9](?:[a-z0-9-]*[a-z0-9])?(?:\\.[a-z0-9](?:[a-z0-9-]*[a-z0-9])?)*$/i\n\nexport const LOCAL_LISTENER = /^(?:[a-z][a-z0-9+.-]*:\\/\\/)?(?<authority>[^/?#]+)/i\n\nexport /** The reserved and homelab TLDs a public CA cannot serve (`isPublicHost` in the panel). */\nconst LOCAL_TLDS = ['.localhost', '.local', '.internal', '.home.arpa', '.lan', '.home', '.test', '.invalid', '.example']\n\n/** The panel-wide block a save writes besides the route table. */\nexport interface ListenerDraft {\n enabled: boolean\n httpPort: number\n httpsPort: number\n email: string\n staging: boolean\n /** DNS-01: the panel answers the challenge instead of the engine using ports. */\n dns01: boolean\n /** Nameservers the engine checks the record against, as typed: one per line or comma. */\n resolvers: string\n}\n\nexport interface ProxyWorkspace {\n id: string\n label: string\n servers: Array<{ id: string }>\n}\n\nexport const ROUTE_ID_PATTERN = /^[a-z0-9][a-z0-9_-]*$/\n\n/** The route as the page edits it: the config plus a stable key for `v-for`. */\nexport interface RouteDraft extends ProxyRoute { key: string }\n\nexport interface RouteErrors {\n host?: string\n id?: string\n workspace?: string\n server?: string\n url?: string\n path?: string\n form?: string\n}\n\n/**\n * The sentences `validateRouteDraft` puts in {@link RouteErrors}, as a seam for translation.\n *\n * The rules belong here — both UIs must refuse the same input for the same reason — but the\n * wording does not: a UI shipping more than one language has to render these in the reader's\n * language, and `src/shared/` may not import Vue or the UI's i18n. So the caller passes messages\n * and the defaults keep every existing caller's output byte-identical.\n */\nexport interface RouteErrorMessages {\n hostRequired: () => string\n hostInvalid: () => string\n hostDuplicate: (host: string) => string\n pathNeedsSlash: () => string\n pathHasSpace: () => string\n idInvalid: () => string\n idDuplicate: (id: string) => string\n workspaceRequired: () => string\n serverRequired: () => string\n urlInvalid: () => string\n}\n\n/** The default wording, unchanged from when it was inlined in `validateRouteDraft`. */\nconst ENGLISH_ROUTE_ERROR_MESSAGES: RouteErrorMessages = {\n hostRequired: () => 'a hostname is required',\n hostInvalid: () => 'a hostname of letters, digits, dots and dashes, e.g. home.example.com',\n hostDuplicate: host => `\"${host}\" is already routed for this path`,\n pathNeedsSlash: () => 'a path prefix starts with /',\n pathHasSpace: () => 'a path prefix cannot contain a space',\n idInvalid: () => 'the id must start with a letter or digit, then letters, digits, dash or underscore',\n idDuplicate: id => `route id \"${id}\" is used twice`,\n workspaceRequired: () => 'pick the workspace that owns the server',\n serverRequired: () => 'pick a server in that workspace',\n urlInvalid: () => 'an upstream like http://10.0.0.5:8080',\n}\n\n/** The words the route list shows for a target or a retry delay, as a translation seam. */\nexport interface RouteSummaryLabels {\n controlPanel: () => string\n noUpstream: () => string\n noServerPicked: () => string\n fallbackRetry: () => string\n retryOne: (count: number, unit: 'minute' | 'hour') => string\n retryMany: (count: number, unit: 'minute' | 'hour') => string\n}\n\nconst ENGLISH_ROUTE_SUMMARY_LABELS: RouteSummaryLabels = {\n controlPanel: () => 'control panel',\n noUpstream: () => 'no upstream',\n noServerPicked: () => 'no server picked',\n fallbackRetry: () => '~8 hours',\n // `minute`/`hour` carry their own plural: English needs `s`, Russian needs three forms.\n retryOne: (count, unit) => `~${count} ${unit}`,\n retryMany: (count, unit) => `~${count} ${unit}s`,\n}\n\nexport const UNPRIVILEGED_HTTPS_PORT = 4443\n\nexport const UNPRIVILEGED_HTTP_PORT = 4480\n\n/** One uploaded pair, as the list shows it; the files themselves are on disk. */\nexport function certificateTitle(certificate: Pick<ProxyCertificateView, 'label' | 'id'>): string {\n return certificate.label.trim().length > 0 ? certificate.label : certificate.id\n}\n\nlet counter = 0\n\n/** The first public name that would need the e-mail, for the hint to name it. */\nexport function firstPublicHost(routes: readonly RouteDraft[]): string | null {\n return routes.find(route => route.tls !== 'off' && isPublicHost(route.host))?.host ?? null\n}\n\nexport function formatBytes(bytes: number | null): string {\n // Only `null` (and a nonsensical negative) is unknown. **0 is an answer** — an empty log, an empty\n // backup, a just-started engine — and rendering it as the em-dash claimed the size could not be\n // measured when it had been measured as nothing.\n if (bytes === null || bytes < 0)\n return '—'\n const units = ['B', 'KiB', 'MiB', 'GiB']\n let value = bytes\n let unit = 0\n while (value >= 1024 && unit < units.length - 1) {\n value /= 1024\n unit += 1\n }\n return `${value.toFixed(unit === 0 ? 0 : 1)} ${units[unit]}`\n}\n\nexport function isPrivilegedPort(port: number): boolean {\n return port > 0 && port < 1024\n}\n\n/** A name an ACME CA could issue for; anything else gets the engine's own CA. */\nexport function isPublicHost(host: string): boolean {\n const name = host.trim().toLowerCase()\n if (name.length === 0 || name === 'localhost' || !name.includes('.'))\n return false\n if (LOCAL_TLDS.some(tld => name.endsWith(tld)))\n return false\n // Four octets is an IPv4 literal, and more still reads as dotted digits rather\n // than a registrable name — a CA could never issue for `1.2.3.4.5`.\n return !/^\\d{1,3}(?:\\.\\d{1,3}){3,}$/.test(name)\n}\n\nexport function listenerPatch(current: ProxyConfig, draft: ListenerDraft): Partial<ProxyPatch> {\n const patch: Partial<ProxyPatch> = {}\n if (current.enabled !== draft.enabled)\n patch.enabled = draft.enabled\n if (current.httpPort !== draft.httpPort)\n patch.httpPort = draft.httpPort\n if (current.httpsPort !== draft.httpsPort)\n patch.httpsPort = draft.httpsPort\n if (current.email !== draft.email)\n patch.email = draft.email\n if (current.staging !== draft.staging)\n patch.staging = draft.staging\n // Sent only when it changed, so a save never rewrites a group it did not touch.\n const resolvers = parseResolvers(draft.resolvers)\n if (current.dns01.enabled !== draft.dns01 || current.dns01.resolvers.join(',') !== resolvers.join(','))\n patch.dns01 = { enabled: draft.dns01, resolvers }\n return patch\n}\n\nexport function newRouteDraft(): RouteDraft {\n return {\n key: newRouteKey(),\n id: 'route',\n host: '',\n enabled: true,\n target: 'server',\n workspace: '',\n server: '',\n url: '',\n path: '',\n tls: 'auto',\n dnsAccount: '',\n }\n}\n\nexport function newRouteKey(): string {\n counter += 1\n return `proxy-route-${counter}`\n}\n\n/**\n * A detached, plain copy of the route list, so an edit cannot reach live state.\n *\n * `clonePlain`, not `structuredClone(toRaw(...))`: a list the page rebuilt holds Vue proxies\n * inside the raw array, and the clone then throws `DataCloneError`.\n */\nexport function cloneRoutes(routes: readonly ProxyRoute[]): RouteDraft[] {\n return clonePlain(routes).map(route => ({ ...route, key: newRouteKey() }))\n}\n\n/**\n * Applies a dialog result to the draft list.\n *\n * `edited` is matched by route **id**, never by the row's `key`: a state frame arriving while the\n * dialog is open re-clones the list and mints a fresh key per row, so the row the dialog was opened\n * from no longer matches by key — and the edit was then dropped with the dialog closing as if it\n * had saved. An id survives the re-clone. `null` means the dialog is adding, which is why the add\n * case is not \"no match found\".\n */\nexport function applyRouteDraft(routes: readonly RouteDraft[], edited: RouteDraft | null, next: RouteDraft): RouteDraft[] {\n if (edited === null)\n return [...routes, next]\n return routes.map(route => (route.id === edited.id ? next : route))\n}\n\n/** Nameservers as typed: split on commas or newlines, trimmed, empties dropped. */\nexport function parseResolvers(value: string): string[] {\n return value.split(/[\\s,]+/).map(entry => entry.trim()).filter(entry => entry.length > 0)\n}\n\n/** The whole patch a save sends, or `null` when nothing changed. */\nexport function proxyPatch(\n current: ProxyConfig,\n listener: ListenerDraft,\n drafts: readonly RouteDraft[],\n filledRoutes?: readonly ProxyRoute[],\n): ProxyPatch | null {\n const patch: ProxyPatch = listenerPatch(current, listener)\n const routes = routesPatch(current.routes, drafts, filledRoutes)\n if (routes !== null)\n patch.routes = routes\n return Object.keys(patch).length === 0 ? null : patch\n}\n\n/**\n * The e-mail rule the panel enforces: a public name served over TLS needs an\n * ACME account address. A local-only name gets the engine's own CA, so a\n * LAN-only setup never needs one.\n */\nexport function requiresEmail(listener: Pick<ListenerDraft, 'email' | 'staging'>, routes: readonly RouteDraft[]): boolean {\n if (listener.staging || listener.email.trim().length > 0)\n return false\n return routes.some(route => route.tls !== 'off' && isPublicHost(route.host))\n}\n\nexport function retryInLabel(minutes: number | null, labels: RouteSummaryLabels = ENGLISH_ROUTE_SUMMARY_LABELS): string {\n // An older panel sends no interval; the engine's own CA issues 12 hours by default,\n // which certmagic's one-third renewal window turns into eight.\n if (minutes === null)\n return labels.fallbackRetry()\n if (minutes < 60)\n return minutes === 1 ? labels.retryOne(minutes, 'minute') : labels.retryMany(minutes, 'minute')\n const hours = Math.max(1, Math.round(minutes / 60))\n return hours === 1 ? labels.retryOne(hours, 'hour') : labels.retryMany(hours, 'hour')\n}\n\n/**\n * Where a route answers, for the list's link. A route with TLS off is served on the\n * plain port, and a standard port stays out of the URL.\n */\nexport function routeUrl(route: Pick<ProxyRoute, 'host' | 'path' | 'tls'>, httpPort: number, httpsPort: number): string | null {\n const host = route.host.trim()\n if (host.length === 0)\n return null\n const plain = route.tls === 'off'\n const port = plain ? httpPort : httpsPort\n const standard = plain ? 80 : 443\n const path = route.path.length === 0 || route.path.startsWith('/') ? route.path : `/${route.path}`\n return `${plain ? 'http' : 'https'}://${host}${port === standard ? '' : `:${port}`}${path}`\n}\n\nexport function routesEqual(current: readonly ProxyRoute[], drafts: readonly RouteDraft[]): boolean {\n if (current.length !== drafts.length)\n return false\n return current.every((route, index) => sameWire(route, drafts[index]!))\n}\n\n/**\n * The route table to send, or `null` when unchanged.\n *\n * `filled` is the table this form was filled with. With it the patch is a three-way merge, so a\n * route another client added while the page was open survives a save from this one; without it the\n * draft's whole view is sent, which is only safe when the caller knows it holds the current table.\n */\nexport function routesPatch(\n current: readonly ProxyRoute[],\n drafts: readonly RouteDraft[],\n filled?: readonly ProxyRoute[],\n): ProxyRoutePatch[] | null {\n if (filled === undefined)\n return routesEqual(current, drafts) ? null : toProxyRoutes(drafts)\n const merged = mergeReplacedList({\n filled: filled.map(toRouteWire),\n draft: toProxyRoutes(drafts),\n live: current.map(toRouteWire),\n key: route => route.id,\n })\n return merged\n}\n\n/**\n * The routes both this form and another client changed, so the save can refuse instead of choosing.\n *\n * Same rule as `destinationConflicts`: a three-way merge keeps a concurrent addition but cannot keep\n * a concurrent edit to one route, because both sides moved it off the same baseline.\n */\nexport function routeConflicts(\n current: readonly ProxyRoute[],\n drafts: readonly RouteDraft[],\n filled?: readonly ProxyRoute[],\n): string[] {\n if (filled === undefined)\n return []\n return replacedListConflicts({\n filled: filled.map(toRouteWire),\n draft: toProxyRoutes(drafts),\n live: current.map(toRouteWire),\n key: route => route.id,\n })\n}\n\nexport function sameWire(a: ProxyRoute, b: ProxyRoute): boolean {\n return JSON.stringify(toRouteWire(a)) === JSON.stringify(toRouteWire(b))\n}\n\n/** A certificate is named by its label; the id names the files on disk. */\nexport function slugifyCertificateId(label: string): string {\n return slugifyId(label, 'certificate')\n}\n\nexport function slugifyId(value: string, fallback: string): string {\n const slug = value.trim().toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-+|-+$/g, '').slice(0, 40).replace(/-+$/, '')\n if (slug.length === 0)\n return fallback\n return /^[a-z0-9]/.test(slug) ? slug : `r-${slug}`\n}\n\nexport function slugifyRouteId(host: string): string {\n return slugifyId(host, 'route')\n}\n\n/** What the target column reads: who a route forwards to. */\nexport function targetSummary(route: ProxyRoute, workspaces: readonly ProxyWorkspace[], labels: RouteSummaryLabels = ENGLISH_ROUTE_SUMMARY_LABELS): string {\n if (route.target === 'panel')\n return labels.controlPanel()\n if (route.target === 'external')\n return route.url.trim().length > 0 ? route.url.trim() : labels.noUpstream()\n if (route.workspace.length === 0 || route.server.length === 0)\n return labels.noServerPicked()\n const workspace = workspaces.find(entry => entry.id === route.workspace)\n return `${workspace?.label ?? route.workspace} / ${route.server}`\n}\n\nexport function toProxyRoutes(drafts: readonly RouteDraft[]): ProxyRoutePatch[] {\n return drafts.map(toRouteWire)\n}\n\n/**\n * The wire shape of a route: a row key is a UI detail, and the schema rejects\n * undeclared keys.\n */\nexport function toRouteWire(route: ProxyRoute): ProxyRoutePatch {\n return {\n id: route.id,\n host: route.host,\n enabled: route.enabled,\n target: route.target,\n workspace: route.workspace,\n server: route.server,\n url: route.url,\n path: route.path,\n tls: route.tls,\n dnsAccount: route.dnsAccount,\n }\n}\n\nexport function uniqueCertificateId(base: string, taken: readonly string[]): string {\n return uniqueId(base, taken)\n}\n\nexport /** An id no other entry uses: the panel refuses duplicates outright. */\nfunction uniqueId(base: string, taken: readonly string[]): string {\n const used = new Set(taken)\n if (!used.has(base))\n return base\n let index = 2\n while (used.has(`${base}-${index}`))\n index += 1\n return `${base}-${index}`\n}\n\nexport function uniqueRouteId(base: string, taken: readonly string[]): string {\n return uniqueId(base, taken)\n}\n\n/** True while the ports are the unprivileged pair this page offers as a switch. */\nexport function usesFallbackPorts(config: Pick<ProxyConfig, 'httpPort' | 'httpsPort'>): boolean {\n return config.httpPort === UNPRIVILEGED_HTTP_PORT && config.httpsPort === UNPRIVILEGED_HTTPS_PORT\n}\n\nexport function validateRouteDraft(draft: RouteDraft, options: { others: readonly RouteDraft[], workspaces: readonly ProxyWorkspace[], messages?: Partial<RouteErrorMessages> }): RouteErrors {\n const messages = { ...ENGLISH_ROUTE_ERROR_MESSAGES, ...options.messages }\n const errors: RouteErrors = {}\n const host = draft.host.trim()\n\n if (host.length === 0)\n errors.host = messages.hostRequired()\n else if (!HOST_PATTERN.test(host))\n errors.host = messages.hostInvalid()\n // `/app` and `/app/` render overlapping matchers, so one would shadow the other.\n else if (options.others.some(other => other.host.trim().toLowerCase() === host.toLowerCase() && other.path.replace(/\\/+$/, '') === draft.path.replace(/\\/+$/, '')))\n errors.host = messages.hostDuplicate(host)\n\n if (draft.path.length > 0 && !draft.path.startsWith('/'))\n errors.path = messages.pathNeedsSlash()\n else if (/\\s/.test(draft.path))\n errors.path = messages.pathHasSpace()\n\n if (!ROUTE_ID_PATTERN.test(draft.id))\n errors.id = messages.idInvalid()\n else if (options.others.some(other => other.id === draft.id))\n errors.id = messages.idDuplicate(draft.id)\n\n if (draft.target === 'server') {\n const workspace = options.workspaces.find(entry => entry.id === draft.workspace)\n if (draft.workspace.length === 0 || workspace === undefined)\n errors.workspace = messages.workspaceRequired()\n else if (draft.server.length === 0 || !workspace.servers.some(entry => entry.id === draft.server))\n errors.server = messages.serverRequired()\n }\n\n if (draft.target === 'external' && parseUpstream(draft.url) === null)\n errors.url = messages.urlInvalid()\n\n // The schema is the last word on anything the field checks cannot see.\n const parsed = proxyRouteSchema({ ...toRouteWire(draft), host })\n if (parsed instanceof type.errors && Object.keys(errors).length === 0)\n errors.form = parsed.summary\n\n return errors\n}\n\n/**\n * The panel accepts an upstream with or without a scheme, and a port is optional\n * because every scheme has a default one — the panel fills in :80 or :443.\n *\n * A typed default port is dropped on the way to the panel: `new URL` normalizes\n * `:80` on `http:` away, so `http://10.0.0.5:80` and `http://10.0.0.5` are one\n * upstream, and a route table that keeps both forms would read as unchanged after\n * a save that the panel had actually rewritten.\n */\nexport function parseUpstream(value: string): { host: string, port: string } | null {\n const trimmed = value.trim()\n if (trimmed.length === 0)\n return null\n const match = LOCAL_LISTENER.exec(trimmed)\n const authority = match?.groups?.authority\n if (authority === undefined || authority.length === 0)\n return null\n // An empty port (`host:`) is not one the panel could use, and `lastIndexOf` reads\n // the colons of an IPv6 literal as a port unless they are told apart first.\n if (authority.endsWith(':') || /\\s/.test(authority))\n return null\n const scheme = trimmed.slice(0, trimmed.indexOf(':')).toLowerCase()\n const separator = authority.lastIndexOf(':')\n if (separator <= 0)\n return { host: authority, port: scheme === 'https' ? '443' : '80' }\n const port = authority.slice(separator + 1)\n if (!/^\\d{1,5}$/.test(port))\n return null\n return { host: authority.slice(0, separator), port }\n}\n","import type { ProxyAdminTransport } from '#src/providers/proxy'\nimport type { ProxyConfig, ProxyTlsMode } from '#src/shared/contracts'\nimport { isPublicHost } from '#src/shared/proxy-form'\n\n/** One route, resolved to something the engine can actually dial. */\nexport interface ProxyUpstreamRoute {\n host: string\n path: string\n /** `host:port` the engine forwards to. */\n dial: string\n /** The upstream speaks TLS (the panel itself may), so verification is skipped. */\n upstreamTls: boolean\n tls: ProxyTlsMode\n /** The handshake for this name can complete: a certificate is there or will be. */\n certificateReady: boolean\n}\n\nexport interface ProxyConfigInput {\n config: ProxyConfig\n admin: ProxyAdminTransport\n /** Where certificates and other engine state live; never a home directory. */\n engineDir: string\n routes: ProxyUpstreamRoute[]\n /** The PEM pairs `tls: \"manual\"` may serve, as paths on disk; the engine picks by SNI. */\n manual: Array<{ certificate: string, key: string }>\n /**\n * The ACME account, and the names it may issue for. Without this the engine still\n * gets certificates, but registers an account with no contact address and has no\n * way to be pointed at the staging endpoint.\n */\n acme: { email: string, staging: boolean, subjects: string[] }\n /**\n * How the panel answers a DNS-01 challenge. Absent means the engine keeps using\n * HTTP-01/TLS-ALPN-01 for every name.\n *\n * One entry per DNS account, because an engine policy carries one challenge\n * provider: a name whose zone lives at Cloudflare and one at deSEC need one policy\n * each. The caller groups them, so the renderer never guesses which account owns a\n * hostname.\n */\n dns01?: {\n /** The panel's ACMEProxy endpoint, e.g. `http://127.0.0.1:3999/_acme`. */\n endpoint: string\n username: string\n password: string\n /** Nameservers the engine checks the record against; empty leaves it to Caddy. */\n resolvers: string[]\n policies: Array<{\n /** `<workspace>/<account>`, for the panel's own record of who answers. */\n account: string\n /** The DNS provider, for the engine log when a challenge fails. */\n provider: string\n subjects: string[]\n }>\n }\n}\n\n/** The ACME staging directory: untrusted certificates, and no rate limit burnt. */\nconst ACME_STAGING = 'https://acme-staging-v02.api.letsencrypt.org/directory'\n\n/**\n * The name the engine answers with when a visitor reaches the port without an SNI\n * (a bare IP) — or with one it has no certificate for. Caddy issues it from its own\n * CA, which is why nothing here has to generate a certificate.\n */\nexport const FALLBACK_NAME = 'hh-fallback.invalid'\n\n/**\n * The DNS-01 challenge block, which names the panel as the one that answers it. The\n * engine holds no DNS credentials: it asks the panel over the ACMEProxy protocol, and\n * the panel writes the record through the workspace account the route names.\n */\nfunction challengeBlock(dns01: NonNullable<ProxyConfigInput['dns01']>): Record<string, unknown> {\n return {\n challenges: {\n dns: {\n provider: {\n name: 'acmeproxy',\n endpoint: dns01.endpoint,\n username: dns01.username,\n password: dns01.password,\n },\n // Only when asked for: an empty list would otherwise mean \"no resolver\".\n ...(dns01.resolvers.length > 0 ? { resolvers: dns01.resolvers } : {}),\n },\n },\n }\n}\n\n/**\n * The issuers for the public names: ACME with the account address, then the engine's\n * own CA as a last resort.\n *\n * The fallback is what keeps a missing certificate from being a dead connection: the\n * handshake completes with an untrusted certificate (the browser offers to continue),\n * instead of failing with a protocol error the visitor cannot read past. The engine\n * keeps trying ACME, and the panel reports which of the two is being served.\n *\n * ZeroSSL is deliberately absent: it needs an EAB key the panel does not collect, so\n * listing it only added a failing issuer and a second retry on every name.\n */\nfunction acmeIssuers(acme: ProxyConfigInput['acme'], challenge: Record<string, unknown> = {}): Array<Record<string, unknown>> {\n return [\n {\n module: 'acme',\n ...(acme.email.length > 0 ? { email: acme.email } : {}),\n ...(acme.staging ? { ca: ACME_STAGING } : {}),\n ...challenge,\n },\n { module: 'internal' },\n ]\n}\n\n/**\n * HTML-escape a value interpolated into a page.\n *\n * The notice page interpolates a routed hostname — configuration, but a config file may be\n * hand-edited, so it is not trusted markup. Escaped here rather than left to the engine's\n * authority parser, so correct encoding does not depend on what sits in front of it.\n */\nfunction escapeHtml(value: string): string {\n return value\n .replace(/&/g, '&amp;')\n .replace(/</g, '&lt;')\n .replace(/>/g, '&gt;')\n .replace(/\"/g, '&quot;')\n .replace(/'/g, '&#39;')\n}\n\n/**\n * The one page shell both visitor-facing pages use. They are the same document with\n * different words, and the stylesheet has to stay identical — a page the engine serves\n * on a port a person reaches by hand is a page that has to look like this panel.\n */\nfunction htmlPage(title: string, heading: string, body: string): string {\n return `<!doctype html>\n<html lang=\"en\">\n<head><meta charset=\"utf-8\"><meta name=\"viewport\" content=\"width=device-width,initial-scale=1\">\n<title>${title}</title>\n<style>\n :root { color-scheme: light dark }\n body { margin: 0; min-height: 100dvh; display: grid; place-items: center; font: 15px/1.6 system-ui, sans-serif }\n main { max-width: 34rem; padding: 2rem }\n h1 { font-size: 1.15rem; margin: 0 0 .75rem }\n p { margin: 0 0 .75rem }\n code { font-family: ui-monospace, monospace; font-size: .9em }\n footer { color: #888; font-size: .85em }\n</style></head>\n<body><main>\n <h1>${heading}</h1>\n${body}\n</main></body></html>`\n}\n\n/**\n * The page a visitor gets when the hostname they reached is not routed at all. It is\n * the answer on both ports, so a request never lands on a redirect into a handshake\n * that cannot finish.\n */\nfunction notConfiguredPage(): string {\n return htmlPage(\n 'No route for this hostname',\n 'This route is not configured for any target yet',\n ` <p>No route in <strong>home-hosted</strong>'s reverse proxy claims the hostname you\n reached, so there is nothing here to serve.</p>\n <p>Add a route for it under <strong>Others → Reverse Proxy</strong>, or check that you\n reached the hostname you meant to.</p>\n <footer>home-hosted reverse proxy</footer>`,\n )\n}\n\n/** The catch-all: it answers last, so every configured route wins over it. */\nfunction notConfiguredRoute(): Record<string, unknown> {\n return {\n handle: [{\n handler: 'static_response',\n status_code: 404,\n headers: {\n 'content-type': ['text/html; charset=utf-8'],\n 'cache-control': ['no-store'],\n 'vary': ['Host'],\n },\n body: notConfiguredPage(),\n }],\n }\n}\n\n/** The page a visitor gets when a name has no certificate yet and HTTPS cannot work. */\nfunction noticePage(host: string, httpPort: number, httpsPort: number): string {\n const safeHost = escapeHtml(host)\n return htmlPage(\n escapeHtml(`Certificate not ready — ${host}`),\n escapeHtml(`No certificate yet for ${host}`),\n ` <p>This hostname is routed, but the certificate authority has not issued a certificate\n for it yet, so HTTPS cannot complete a handshake. The engine keeps trying in the\n background and will serve the name as soon as it succeeds.</p>\n <p>The usual cause is that the CA cannot reach this machine: with the proxy on\n <code>${httpPort}</code>/<code>${httpsPort}</code>, forward <code>80 → ${httpPort}</code>\n and <code>443 → ${httpsPort}</code> on your router. Otherwise <code>http://${safeHost}</code>\n will keep landing here.</p>\n <footer>Details, and the engine's own reason, are in the panel: Others → Reverse Proxy.</footer>`,\n )\n}\n\n/**\n * The same match, minus the ACME challenge path: the CA has to be able to read it on\n * the cleartext port, so nothing this panel generates may answer for it. HTTP-01 is\n * always asked at the root of the host (RFC 8555 §8.3), which is why one pattern is\n * enough.\n */\nfunction matchForWithoutChallenge(route: ProxyUpstreamRoute): Record<string, unknown> {\n return { ...matchFor(route), not: [{ path: ['/.well-known/acme-challenge/*'] }] }\n}\n\n/**\n * The whole host, for a name whose certificate is not there yet. The prefix is dropped\n * on purpose: readiness is a property of the hostname, so a visitor who lands outside\n * the route's prefix must get the page too, not a redirect into a handshake that\n * cannot finish.\n */\nfunction noticeMatcher(route: ProxyUpstreamRoute): Record<string, unknown> {\n return { host: [route.host], not: [{ path: ['/.well-known/acme-challenge/*'] }] }\n}\n\nfunction matchFor(route: ProxyUpstreamRoute): Record<string, unknown> {\n const match: Record<string, unknown> = { host: [route.host] }\n const prefix = route.path.trim()\n if (prefix.length > 0) {\n const leading = prefix.startsWith('/') ? prefix : `/${prefix}`\n // Trailing slashes are stripped *before* the matchers are built, because\n // `ProxyService.pathKey` already treats `/app` and `/app/` as the same route and refuses two of\n // them as a clash. Emitting them differently made the pair clash-free and yet behave differently:\n // Caddy matches `path` exactly, so `/app/` produced `[\"/app/\", \"/app/*\"]` and never matched the\n // bare `/app` the panel reported as covered.\n const base = leading.replace(/\\/+$/, '')\n match.path = base.length === 0 ? ['/*'] : [base, `${base}/*`]\n }\n return match\n}\n\nfunction proxyHandler(route: ProxyUpstreamRoute): Record<string, unknown> {\n return {\n handler: 'reverse_proxy',\n upstreams: [{ dial: route.dial }],\n // Caddy decides https from the port alone; a local upstream is plain HTTP\n // unless we say otherwise, and the panel's own TLS is self-signed.\n ...(route.upstreamTls\n ? { transport: { protocol: 'http', tls: { insecure_skip_verify: true } } }\n : {}),\n }\n}\n\n/**\n * The ports a rendered configuration listens on.\n *\n * The one derivation: `httpPort`/`httpsPort` are what was *asked for*, not what is bound — a\n * `tls: 'off'`-only table binds no HTTPS listener, and a table with no servable route binds nothing.\n * Both the applied record and the port preflight read this, so they cannot disagree.\n */\nexport function boundPorts(rendered: Record<string, unknown>): number[] {\n const servers = (rendered.apps as { http?: { servers?: Record<string, { listen?: string[] }> } } | undefined)?.http?.servers\n if (servers === undefined)\n return []\n return Object.values(servers)\n .flatMap(server => server.listen ?? [])\n .map(listen => Number.parseInt(listen.replace(/^.*:/, ''), 10))\n .filter(port => Number.isInteger(port))\n}\n\n/**\n * The whole engine configuration, generated from the panel's route table.\n *\n * Two servers on purpose: one terminates TLS for the names that ask for it, the\n * other keeps the cleartext port for ACME HTTP-01 challenges, plaintext routes and\n * an explicit redirect. Caddy's own redirect insertion is off so the redirect\n * carries our `httpsPort`, which is not necessarily 443.\n */\nexport function renderCaddyConfig(input: ProxyConfigInput): Record<string, unknown> {\n const { config, admin, engineDir, routes } = input\n const managed = routes.filter(route => route.tls !== 'off')\n const plain = routes.filter(route => route.tls === 'off')\n const suffix = config.httpsPort === 443 ? '' : `:${config.httpsPort}`\n\n const servers: Record<string, unknown> = {}\n if (managed.length > 0) {\n servers.https = {\n listen: [`:${config.httpsPort}`],\n // A visitor with no SNI (a bare IP) or an unrouted name still gets a handshake,\n // served by Caddy's own CA, and then the catch-all page below.\n tls_connection_policies: [{ default_sni: FALLBACK_NAME }],\n routes: [\n ...managed.map(route => ({ match: [matchFor(route)], handle: [proxyHandler(route)], terminal: true })),\n // Named so Caddy manages it, which is what makes it issue the certificate the\n // policy above falls back to. Nothing is served from it but the same page.\n { match: [{ host: [FALLBACK_NAME] }], ...notConfiguredRoute(), terminal: true },\n notConfiguredRoute(),\n ],\n }\n }\n if (routes.length > 0) {\n servers.http = {\n listen: [`:${config.httpPort}`],\n // Caddy would redirect every host it manages; we do it, with the real port.\n automatic_https: { disable_redirects: true, skip: plain.map(route => route.host) },\n routes: [\n ...plain.map(route => ({ match: [matchFor(route)], handle: [proxyHandler(route)], terminal: true })),\n // A name whose certificate is not there yet gets the reason as a page rather\n // than a redirect into a handshake that cannot finish — once per host, since\n // that is what the certificate belongs to.\n ...managed.filter(route => route.certificateReady).map(route => ({\n match: [matchForWithoutChallenge(route)],\n handle: [{\n handler: 'static_response',\n status_code: 308,\n headers: { Location: [`https://{http.request.host}${suffix}{http.request.uri}`] },\n }],\n })),\n ...[...new Set(managed.filter(route => !route.certificateReady).map(route => route.host))].map(host => ({\n match: [noticeMatcher({ host } as ProxyUpstreamRoute)],\n handle: [{\n handler: 'static_response',\n status_code: 503,\n headers: {\n 'content-type': ['text/html; charset=utf-8'],\n 'cache-control': ['no-store'],\n 'vary': ['Host'],\n },\n body: noticePage(host, config.httpPort, config.httpsPort),\n }],\n })),\n notConfiguredRoute(),\n ],\n }\n }\n\n const adminBlock: Record<string, unknown> = { config: { persist: false } }\n if (admin.kind === 'unix') {\n adminBlock.listen = `unix/${admin.path}`\n }\n else {\n adminBlock.listen = `${admin.host}:${admin.port}`\n // No auth on the admin API, so a loopback listener still refuses a browser\n // from another origin. Our own client sends the matching `Origin`.\n adminBlock.enforce_origin = true\n adminBlock.origins = [admin.origin]\n }\n\n const tlsApp: Record<string, unknown> = {}\n if (input.manual.length > 0)\n tlsApp.certificates = { load_files: input.manual }\n // Subjects are the public names only: a local-only name must keep falling to the\n // engine's own CA, which a catch-all policy would take away from it.\n const policies: Array<Record<string, unknown>> = []\n if (input.acme.subjects.length > 0) {\n const challenge = input.dns01 === undefined ? {} : challengeBlock(input.dns01)\n const dnsSubjects = new Set(input.dns01?.policies.flatMap(policy => policy.subjects) ?? [])\n // One policy per DNS account, plus one for every public name that is not answered\n // by DNS-01 — that last one keeps HTTP-01/TLS-ALPN-01 for the names it still can.\n for (const policy of input.dns01?.policies ?? [])\n policies.push({ subjects: policy.subjects, issuers: acmeIssuers(input.acme, challenge) })\n const rest = input.acme.subjects.filter(subject => !dnsSubjects.has(subject))\n if (rest.length > 0)\n policies.push({ subjects: rest, issuers: acmeIssuers(input.acme) })\n }\n // Everything the engine's own CA signs: every local-only name, plus the one a bare-IP\n // visitor falls back to. They get a policy of their own because the ACME one must never\n // see them — and because **a name no policy names falls to Caddy's default automation,\n // which is the public CA**. That is what a `.lan` route used to get: Let's Encrypt\n // answered `rejectedIdentifier` (a `.lan` name has no public suffix), nothing was issued,\n // and the HTTPS handshake failed with `tlsv1 alert internal error` while the page said\n // \"signed by the engine's own CA\" and the cleartext port redirected into it.\n const localNames = [...new Set(\n managed.filter(route => route.tls === 'auto' && !isPublicHost(route.host)).map(route => route.host),\n )]\n if (managed.length > 0)\n policies.push({ subjects: [FALLBACK_NAME, ...localNames], issuers: [{ module: 'internal' }] })\n if (policies.length > 0)\n tlsApp.automation = { policies }\n\n return {\n admin: adminBlock,\n storage: { module: 'file_system', root: `${engineDir}/data` },\n logging: { logs: { default: { level: 'INFO' } } },\n apps: {\n ...(Object.keys(tlsApp).length === 0 ? {} : { tls: tlsApp }),\n http: {\n http_port: config.httpPort,\n https_port: config.httpsPort,\n servers,\n },\n },\n }\n}\n","import type { TlsStatus } from '#src/shared/contracts'\nimport { Buffer } from 'node:buffer'\nimport { createPrivateKey, createPublicKey, X509Certificate } from 'node:crypto'\nimport fs from 'node:fs'\nimport path from 'node:path'\nimport { writeFileAtomic } from '#src/helpers/atomic'\nimport { logger } from '#src/helpers/logger'\nimport { errorMessage } from '#src/shared/error-message'\n\n/**\n * Stores an uploaded PEM pair and reports what it contains.\n *\n * The key is written 0600 and both files stay out of git. Nothing here binds a\n * socket — the control server reads the pair and hands it to srvx. The reverse\n * proxy keeps its own pair in its own directory through the same class.\n */\nexport class TlsStore {\n private cached: { cert: string, key: string } | null = null\n private cachedMtime = ''\n\n constructor(private readonly dir: string, private readonly name = 'control') {}\n\n get directory(): string {\n return this.dir\n }\n\n get certPath(): string {\n return path.join(this.dir, `${this.name}.crt.pem`)\n }\n\n get keyPath(): string {\n return path.join(this.dir, `${this.name}.key.pem`)\n }\n\n get present(): boolean {\n return fs.existsSync(this.certPath) && fs.existsSync(this.keyPath)\n }\n\n /** Returns the PEM pair, re-read when the files change on disk. */\n load(): { cert: string, key: string } | null {\n if (!this.present) {\n this.cached = null\n return null\n }\n\n const key = [this.certPath, this.keyPath].map((file) => {\n try {\n return `${fs.statSync(file).mtimeMs}`\n }\n catch {\n return 'x'\n }\n }).join(':')\n\n if (this.cached !== null && key === this.cachedMtime)\n return this.cached\n\n try {\n this.cached = {\n cert: fs.readFileSync(this.certPath, 'utf8'),\n key: fs.readFileSync(this.keyPath, 'utf8'),\n }\n this.cachedMtime = key\n return this.cached\n }\n catch {\n this.cached = null\n return null\n }\n }\n\n save(certificate: string, privateKey: string): { ok: boolean, error?: string } {\n const validation = validatePair(certificate, privateKey)\n if (!validation.ok)\n return { ok: false, error: validation.error }\n\n fs.mkdirSync(this.dir, { recursive: true })\n writeFileAtomic(this.certPath, `${certificate.trimEnd()}\\n`)\n writeFileAtomic(this.keyPath, `${privateKey.trimEnd()}\\n`, { mode: 0o600 })\n this.cached = null\n this.cachedMtime = ''\n return { ok: true }\n }\n\n /**\n * The pair to serve, or `null` when there is nothing servable.\n *\n * `load()` returns whatever is on disk, and `serve({ tls })` **throws synchronously** on a pair that\n * does not match (`ERR_OSSL_X509_KEY_VALUES_MISMATCH`) — before `listen()`'s `ready()`/`error` race\n * can catch it. A mismatched pair therefore fails the reboot: hand-copied files, a restore, or a\n * crash between `save()`'s two writes all reach it, and the panel reports an OpenSSL code instead of\n * booting on http or naming the problem. Validated here, where the answer is still recoverable.\n */\n servable(): { cert: string, key: string } | null {\n const pair = this.load()\n if (pair === null)\n return null\n const validation = validatePair(pair.cert, pair.key)\n if (!validation.ok) {\n logger.warn(`the stored TLS pair will not be served: ${validation.error ?? 'it is not usable'}`)\n return null\n }\n return pair\n }\n\n clear(): void {\n for (const file of [this.certPath, this.keyPath]) {\n try {\n fs.rmSync(file, { force: true })\n }\n catch {\n // Nothing to remove.\n }\n }\n this.cached = null\n }\n\n status(enabled: boolean): TlsStatus {\n const base: TlsStatus = {\n enabled,\n certPresent: this.present,\n subject: null,\n issuer: null,\n validFrom: null,\n validTo: null,\n daysRemaining: null,\n fingerprint: null,\n keyMatches: null,\n error: null,\n }\n\n if (!this.present) {\n return enabled ? { ...base, error: 'TLS is enabled but no certificate has been uploaded' } : base\n }\n\n const pair = this.load()\n if (pair === null)\n return { ...base, error: 'the stored certificate could not be read' }\n\n try {\n const x509 = new X509Certificate(pair.cert)\n const validTo = new Date(x509.validTo)\n const daysRemaining = Math.floor((validTo.getTime() - Date.now()) / 86_400_000)\n // The key verdict is computed once, and never by `validatePair`: that also fails a certificate\n // outside its validity window, so a window problem would read as \"the key does not match\" and\n // send the reader to the wrong file.\n const keyMatches = publicKeysMatch(pair.cert, pair.key)\n return {\n ...base,\n subject: x509.subject.replace(/\\n/g, ', '),\n issuer: x509.issuer.replace(/\\n/g, ', '),\n validFrom: new Date(x509.validFrom).toISOString(),\n validTo: validTo.toISOString(),\n daysRemaining,\n fingerprint: x509.fingerprint256,\n keyMatches,\n // The same guards the upload path and `servable()` use, so the page names the real reason — and\n // a pair the server refuses is never shown as healthy while the panel quietly serves http. A\n // `keyMatches: false` with a null `error` read as \"enabled and fine\".\n error: validityError(x509) ?? (keyMatches ? null : 'the private key does not match the certificate'),\n }\n }\n catch (error) {\n return { ...base, error: `invalid certificate: ${errorMessage(error)}` }\n }\n }\n}\n\n/** Whether the certificate's validity window covers now. Both ends, from one place. */\nfunction validityError(x509: X509Certificate, now = Date.now()): string | null {\n if (new Date(x509.validFrom).getTime() > now)\n return `the certificate is not valid until ${x509.validFrom}`\n if (new Date(x509.validTo).getTime() < now)\n return `the certificate expired on ${x509.validTo}`\n return null\n}\n\n/** Whether the private key is the one that certificate was issued for. */\nfunction publicKeysMatch(certificate: string, privateKey: string): boolean {\n const fromKey = createPublicKey(createPrivateKey(privateKey)).export({ type: 'spki', format: 'der' })\n const fromCert = new X509Certificate(certificate).publicKey.export({ type: 'spki', format: 'der' })\n return Buffer.from(fromKey).equals(Buffer.from(fromCert))\n}\n\n/** Checks the certificate parses, is time-valid, and matches the private key. */\nexport function validatePair(certificate: string, privateKey: string): { ok: boolean, error?: string } {\n let x509: X509Certificate\n try {\n x509 = new X509Certificate(certificate)\n }\n catch (error) {\n return { ok: false, error: `certificate is not a valid PEM: ${errorMessage(error)}` }\n }\n\n try {\n if (!publicKeysMatch(certificate, privateKey))\n return { ok: false, error: 'the private key does not match the certificate' }\n }\n catch (error) {\n return { ok: false, error: `private key is not a valid PEM: ${errorMessage(error)}` }\n }\n\n // Both ends of the window. Checking only `validTo` accepted a certificate whose `notBefore` is in\n // the future — browsers refuse one, so `POST /settings/tls` saved it and moved the panel to HTTPS\n // answering with an untrusted certificate.\n const invalid = validityError(x509)\n if (invalid !== null)\n return { ok: false, error: invalid }\n\n return { ok: true }\n}\n","import type { ChildProcess } from 'node:child_process'\nimport type { GlobalSettingsStore } from '#src/config/settings'\nimport type { ProxyAdminTransport, ProxyEngine } from '#src/providers/proxy'\nimport type { ChallengeAccount } from '#src/services/acme-challenge'\nimport type { ControlEndpoint } from '#src/services/control-server'\nimport type { ProxyConfigInput, ProxyUpstreamRoute } from '#src/services/proxy-config'\nimport type {\n ProxyCertificateState,\n ProxyCertificateView,\n ProxyConfig,\n ProxyDnsAccountView,\n ProxyEngineStatus,\n ProxyPatch,\n ProxyRoute,\n ProxyRouteStatus,\n ProxyRouteView,\n ProxyRunState,\n ProxyStatus,\n ProxyView,\n} from '#src/shared/contracts'\nimport { Buffer } from 'node:buffer'\nimport { spawn } from 'node:child_process'\nimport { randomBytes, X509Certificate } from 'node:crypto'\nimport fs from 'node:fs'\nimport http from 'node:http'\nimport path from 'node:path'\nimport process from 'node:process'\nimport { DetailedError } from '@namesmt/utils'\nimport { type } from 'arktype'\nimport { writeFileAtomic } from '#src/helpers/atomic'\nimport { logger } from '#src/helpers/logger'\nimport { dataRoot, projectDir, proxyChallengeAuthPath } from '#src/helpers/paths'\nimport { nannyArgv } from '#src/helpers/runtime'\nimport { ddnsProvider } from '#src/providers/ddns'\nimport { normalizeHost } from '#src/providers/ddns/types'\nimport {\n HEARTBEAT_STALE_MS,\n nannyEntryPoint,\n nannyIsAlive,\n nannySpecPath,\n nannyStatePath,\n readNannyState,\n sweepNannySpecs,\n writeNannySpec,\n} from '#src/providers/nanny'\nimport { isPortFree, isProcessAlive, listPortHolders } from '#src/providers/port'\nimport { processCarriesServerId } from '#src/providers/proc'\nimport { proxyEngine, proxyEngineInfos } from '#src/providers/proxy'\nimport { boundPorts, FALLBACK_NAME, renderCaddyConfig } from '#src/services/proxy-config'\nimport { TlsStore } from '#src/services/tls'\nimport { errorMessage } from '#src/shared/error-message'\nimport { isPublicHost } from '#src/shared/proxy-form'\n\n/** The engine is not a server entry, but it borrows the nanny's shape. */\nconst PROXY_ID = 'proxy'\n/** A failing `sync()` re-apply backs off from this, doubling to the cap, then stops retrying. */\nconst SYNC_RETRY_BASE_MS = 2_000\nconst SYNC_RETRY_MAX_MS = 5 * 60_000\nconst SYNC_MAX_FAILURES = 8\n\nconst ADMIN_TIMEOUT_MS = 5000\nconst READY_TIMEOUT_MS = 20_000\nconst READY_POLL_MS = 250\nconst DOWNLOAD_TIMEOUT_MS = 15 * 60 * 1000\n\n/** How long the binary gets to answer `version` or `list-modules` before it is killed. */\nconst ENGINE_COMMAND_TIMEOUT_MS = 10_000\n\n/** The module the panel's DNS-01 configuration names; the engine must carry it. */\nconst DNS01_MODULE = 'dns.providers.acmeproxy'\n\n/**\n * What the panel recorded when it installed the engine. Nothing here is verified\n * against the binary: replacing it by hand is a supported way to run a custom build,\n * so no digest is recorded. A file from an older release, which did record one,\n * carries an undeclared key and is rejected wholesale — it reads as \"not installed\".\n */\nexport const engineRecordSchema = type({\n engine: 'string',\n version: 'string',\n source: '\"downloaded\" | \"custom\"',\n url: 'string',\n bytes: 'number',\n installedAt: 'number',\n}).onUndeclaredKey('reject')\nexport type EngineRecord = typeof engineRecordSchema.infer\n\n/**\n * The Basic credentials the engine uses to reach the panel's DNS-01 endpoint.\n * Generated once and kept beside the engine's other state, 0600 — the endpoint is\n * loopback-only, and this is the second lock on a door that writes into DNS.\n */\nexport const challengeAuthSchema = type({\n username: 'string >= 1',\n password: 'string >= 1',\n}).onUndeclaredKey('reject')\nexport type ChallengeAuth = typeof challengeAuthSchema.infer\n\n/** The DNS names a certificate covers, from its SANs (and its subject as a fallback). */\nfunction namesOf(x509: X509Certificate): string[] {\n const names = new Set<string>()\n for (const part of (x509.subjectAltName ?? '').split(',')) {\n const trimmed = part.trim()\n if (!trimmed.toUpperCase().startsWith('DNS:'))\n continue\n const value = trimmed.slice(4).trim().toLowerCase()\n if (value.length > 0)\n names.add(value)\n }\n if (names.size === 0) {\n const cn = /CN=([^,\\n]+)/.exec(x509.subject)?.[1]?.trim()\n if (cn !== undefined && cn.length > 0)\n names.add(cn.toLowerCase())\n }\n return [...names]\n}\n\n/** True when a pair covers this hostname, wildcards included. */\nexport function coversHost(hosts: readonly string[], host: string): boolean {\n const name = host.toLowerCase()\n return hosts.some((entry) => {\n if (entry === name)\n return true\n if (!entry.startsWith('*.'))\n return false\n const suffix = entry.slice(1)\n return name.endsWith(suffix) && !name.slice(0, -suffix.length).includes('.')\n })\n}\n\n/** One route resolved far enough for the engine (and the UI) to use it. */\ninterface ResolvedRoute {\n route: ProxyRoute\n status: ProxyRouteStatus\n upstream: string | null\n /** The upstream speaks TLS, so the engine must not dial it in cleartext. */\n upstreamTls: boolean\n message: string | null\n}\n\n/**\n * The ports the engine actually bound, so a rejected reload cannot make the panel lie.\n *\n * `null` means the document did not listen there — a `tls: 'off'`-only route table binds no HTTPS\n * listener, and a route whose upstream is down binds nothing at all. Configured-but-unbound is not\n * the same as bound, and treating it as bound admits a stranger standing on that port.\n */\nconst appliedRecordSchema = type({\n httpPort: '1 <= number.integer <= 65535 | null',\n httpsPort: '1 <= number.integer <= 65535 | null',\n at: 'number',\n}).onUndeclaredKey('reject')\n\n/** How the panel reaches a running engine; kept beside the nanny's state so a new panel finds it. */\nconst adminRecordSchema = type({\n kind: '\"unix\" | \"tcp\"',\n path: 'string = \"\"',\n host: 'string = \"\"',\n port: 'number = 0',\n origin: 'string = \"\"',\n}).onUndeclaredKey('reject')\n\nexport interface ProxyServiceOptions {\n settings: GlobalSettingsStore\n /** The engine binary and its record. */\n binDir: string\n /** Where the engine may write; also holds the generated configuration. */\n engineDir: string\n /** Paths of the generated configuration and its previous revision. */\n configPath: string\n previousConfigPath: string\n /** The nanny's spec and state for the engine process. */\n stateDir: string\n /** Path of the admin record, so a panel that restarts can reach a running engine. */\n adminPath: string\n /** How long `version`/`list-modules` may take; overridden in tests. */\n engineCommandTimeoutMs?: number\n /** Where the engine's DNS-01 credentials live, 0600. */\n challengeAuthPath?: string\n /** JSONL directory the nanny writes into; the panel's own `.hh/.logs`. */\n logDir: string\n /** Where the uploaded PEM pairs live, one `<id>.crt.pem`/`<id>.key.pem` per entry. */\n tlsDir: string\n /** The live control listener, read lazily — it is created after this service. */\n control: () => ControlEndpoint\n /**\n * Resolves a supervised entry to the address the proxy should forward to.\n * `null` means the pair is unknown; a null `url` means it exists but is not up.\n */\n resolveServer: (workspaceId: string, serverId: string) => { url: string | null, message: string | null } | null\n /** Test seams: the lifecycle steps that wait on a real engine. */\n waitReady?: () => Promise<boolean>\n chooseAdmin?: () => Promise<ProxyAdminTransport>\n /** How long a stop waits for SIGTERM before escalating; shortened in tests. */\n stopGraceMs?: number\n /**\n * The DNS account a hostname's DNS-01 challenge is written through, by\n * `<workspace>/<account>`. `null` means no account claims the name, so the\n * challenge is refused rather than guessed at.\n */\n resolveDnsAccount?: (workspaceId: string, accountId: string) => { provider: string, credentials: Record<string, string> | null } | null\n /**\n * Every account a route may name, for the page's picker. Flattened here so the\n * page reads one list instead of walking every workspace itself.\n */\n listDnsAccounts?: () => ProxyDnsAccountView[]\n /** The workspace a route belongs to, when it does not name one itself. */\n defaultWorkspaceId?: () => string\n /**\n * The exposure rule for a route that points at the panel. Injected because the\n * rule lives in `exposure.ts` and must not have a second home here.\n */\n exposureBlocked: () => string | null\n /** Called when the panel-wide state would have changed. */\n onStateChange: () => void\n}\n\n/**\n * The reverse proxy as one panel-wide service: install the engine, keep its\n * generated configuration in step with the route table, and run it under a nanny\n * so a panel restart never drops the socket that faces the internet.\n *\n * The engine's admin API is applied to, never edited by hand: `POST /load` is\n * atomic, so a configuration that does not load leaves the running one in place.\n */\nexport class ProxyService {\n private nanny: ChildProcess | null = null\n private admin: ProxyAdminTransport | null = null\n private lastError: string | null = null\n\n /** The parsed failure map, keyed on the log's identity — see `obtainFailures`. */\n private failureCache: { stamp: string, failures: Map<string, string> } | null = null\n /** The installed binary's modules, read once per process; an install clears it. */\n private moduleCache: Set<string> | null = null\n /** Why the engine's nanny could not be spawned, cleared on the next start. */\n private nannyError: string | null = null\n private certCache: { at: number, key: string, days: number | null, issued: Map<string, { notAfter: number, issuer: string }>, local: Map<string, { notAfter: number, lifetimeMs: number }>, views: ProxyCertificateView[] } | null = null\n /** What the last apply was built from — certificates and upstreams — so a change re-applies once. */\n private certificateSignature: string | null = null\n\n constructor(private readonly options: ProxyServiceOptions) {}\n\n get config(): ProxyConfig {\n return this.options.settings.proxy\n }\n\n get engine(): ProxyEngine {\n const engine = proxyEngine(this.config.engine)\n if (engine === null)\n throw new DetailedError(`unknown proxy engine \"${this.config.engine}\"`, { statusCode: 500, code: 'UNKNOWN_ENGINE' })\n return engine\n }\n\n get enginePath(): string {\n return path.join(this.options.binDir, this.engine.binaryName(process.platform))\n }\n\n /** The hostnames an enabled route serves the panel itself on. */\n panelHosts(): string[] {\n return this.config.routes.filter(route => route.enabled && route.target === 'panel').map(route => route.host)\n }\n\n /**\n * The Basic credentials the engine uses to reach the panel's DNS-01 endpoint.\n * Generated on first use and kept 0600: the endpoint is loopback-only, and this\n * is the second lock on a door that writes into somebody's DNS.\n */\n challengeAuth(): ChallengeAuth {\n const file = this.options.challengeAuthPath ?? proxyChallengeAuthPath\n try {\n const parsed = challengeAuthSchema(JSON.parse(fs.readFileSync(file, 'utf8')))\n if (!(parsed instanceof type.errors))\n return parsed\n }\n catch {\n // Absent or unreadable: a fresh pair below is the answer either way.\n }\n const auth: ChallengeAuth = {\n username: 'hh',\n password: randomBytes(24).toString('base64url'),\n }\n fs.mkdirSync(path.dirname(file), { recursive: true, mode: 0o700 })\n writeFileAtomic(file, `${JSON.stringify(auth, null, 2)}\\n`, { mode: 0o600 })\n return auth\n }\n\n /**\n * The DNS-01 half of the renderer's input, or undefined when it is switched off.\n *\n * One entry per account, because an engine policy carries one challenge provider:\n * a name whose zone is at Cloudflare and one at deSEC need a policy each.\n */\n private dns01Input(routes: readonly ProxyUpstreamRoute[]): ProxyConfigInput['dns01'] {\n if (!this.config.dns01.enabled)\n return undefined\n const endpoint = this.options.control()\n const auth = this.challengeAuth()\n\n // The hostnames the engine would ask a challenge for, grouped by the account\n // that answers each one.\n const policies = groupDns01Policies(routes, host => this.resolveAccount(host))\n\n return {\n resolvers: this.config.dns01.resolvers,\n // The engine dials the panel on loopback, whatever the panel binds for people.\n endpoint: `${endpoint.protocol}://127.0.0.1:${endpoint.port}/_acme`,\n username: auth.username,\n password: auth.password,\n policies,\n }\n }\n\n /** The workspace a route's DNS account is looked up in. */\n private workspaceOf(route: ProxyRoute): string {\n if (route.workspace.length > 0)\n return route.workspace\n return this.options.defaultWorkspaceId?.() ?? ''\n }\n\n /**\n * The account a route names, or null when it names none.\n *\n * A bare id belongs to the route's own workspace; `<workspace>/<id>` crosses into\n * another one, which is what lets one route table cover zones owned by different\n * workspaces.\n */\n private dnsAccountRef(route: ProxyRoute | undefined): { owner: string, accountId: string, provider: string } | null {\n if (route === undefined)\n return null\n const named = route.dnsAccount.trim()\n if (named.length === 0)\n return null\n const workspaceId = this.workspaceOf(route)\n if (workspaceId.length === 0)\n return null\n const [owner, accountId] = named.includes('/') ? named.split('/', 2) : [workspaceId, named]\n const resolved = this.options.resolveDnsAccount?.(owner ?? '', accountId ?? '')\n if (resolved === undefined || resolved === null)\n return null\n return { owner: owner ?? '', accountId: accountId ?? '', provider: resolved.provider }\n }\n\n /** The route that answers for a hostname, challenge prefix or not. */\n private routeForHost(host: string): ProxyRoute | undefined {\n return this.config.routes.find(route => route.enabled && route.host.toLowerCase() === host)\n }\n\n /**\n * The account that answers a DNS-01 challenge for one hostname.\n *\n * The route is the authority. An explicit `dnsAccount` wins; an empty one falls back\n * to the only account any route names, so a single-account setup needs no per-route\n * choice — and never to a guess among several, because writing the wrong zone fails\n * silently.\n */\n challengeAccount(fqdn: string): ChallengeAccount | null {\n const host = fqdn.startsWith('_acme-challenge.')\n ? fqdn.slice('_acme-challenge.'.length)\n : fqdn\n // Normalized here too: `handle` already normalizes, but a caller that does not\n // must not silently get \"no account answers\" for an upper-case or dotted name.\n return this.resolveAccount(normalizeHost(host))\n }\n\n private resolveAccount(host: string): ChallengeAccount | null {\n // Nothing answers a challenge while the feature is off, whatever a route names:\n // the account lookup is the last gate before a record is written.\n if (!this.config.dns01.enabled)\n return null\n // A local-only name is signed by the engine's own CA and never challenged; a\n // request for one must not reach a provider.\n if (!isPublicHost(host))\n return null\n if (this.options.resolveDnsAccount === undefined)\n return null\n const route = this.routeForHost(host)\n if (route === undefined)\n return null\n\n const named = this.dnsAccountRef(route)\n if (named !== null)\n return this.accountOf(named.owner, named.accountId)\n\n // Nothing named on this route. One account named anywhere answers for every name;\n // more than one is ambiguous rather than a reason to guess.\n const declared = new Map<string, { owner: string, accountId: string }>()\n for (const entry of this.config.routes) {\n if (!entry.enabled)\n continue\n const ref = this.dnsAccountRef(entry)\n if (ref !== null)\n declared.set(`${ref.owner}/${ref.accountId}`, { owner: ref.owner, accountId: ref.accountId })\n }\n if (declared.size === 1) {\n const only = [...declared.values()][0]!\n return this.accountOf(only.owner, only.accountId)\n }\n if (declared.size > 1)\n return null\n\n // No route names one at all — the usual single-account setup. The only account in\n // the panel that can answer is the obvious reading of \"Automatic\"; without this\n // the challenge block was never generated and the certificate stayed pending.\n const usable = (this.options.listDnsAccounts?.() ?? []).filter(entry => entry.writesTxt && entry.hasCredentials)\n if (usable.length !== 1)\n return null\n const only = usable[0]!\n return this.accountOf(only.workspace, only.account)\n }\n\n private accountOf(workspaceId: string, accountId: string): ChallengeAccount | null {\n const found = this.options.resolveDnsAccount?.(workspaceId, accountId)\n if (found === undefined || found === null || found.credentials === null)\n return null\n return { workspaceId, accountId, provider: found.provider, credentials: found.credentials }\n }\n\n /**\n * What a route's `dnsAccount` refers to, for the save-time check.\n *\n * A bare id belongs to the default workspace, which is what a person typing one\n * account means; `<workspace>/<id>` crosses into another.\n */\n checkDnsAccount(reference: string, workspaceId = ''): DnsAccountCheck | null {\n const named = reference.trim()\n if (named.length === 0)\n return null\n // A bare id belongs to the route's own workspace, exactly as the challenge path\n // reads it — otherwise the same string could be checked in one workspace and\n // used from another.\n const owner = named.includes('/') ? named.split('/', 2)[0] ?? '' : workspaceId.length > 0 ? workspaceId : this.options.defaultWorkspaceId?.() ?? ''\n const accountId = named.includes('/') ? named.split('/', 2)[1] ?? '' : named\n const found = this.options.resolveDnsAccount?.(owner, accountId)\n if (found === undefined || found === null)\n return null\n return {\n provider: found.provider,\n writesTxt: ddnsProvider(found.provider)?.challenge !== undefined,\n hasCredentials: found.credentials !== null,\n }\n }\n\n /** One uploaded pair, by the id that names it in the config. */\n private pairStore(id: string): TlsStore {\n return new TlsStore(this.options.tlsDir, id)\n }\n\n /**\n * Stores a pair under `id` and records it in the config, so a route can be\n * checked against what it actually covers.\n */\n saveCertificate(id: string, label: string, certificate: string, privateKey: string): { ok: boolean, error?: string } {\n const saved = this.pairStore(id).save(certificate, privateKey)\n if (!saved.ok)\n return saved\n\n const certificates = this.config.certificates.some(entry => entry.id === id)\n ? this.config.certificates.map(entry => (entry.id === id ? { ...entry, label } : entry))\n : [...this.config.certificates, { id, label }]\n this.options.settings.updateProxy({ certificates })\n this.certCache = null\n this.certificateSignature = null\n this.options.onStateChange()\n return { ok: true }\n }\n\n /**\n * Removes a pair — refused while a route still serves it, because deleting the\n * files first would leave the engine on a certificate the panel has dropped.\n */\n clearCertificate(id: string): void {\n const pair = this.certificateViews().find(entry => entry.id === id)\n const holders = this.config.routes.filter(route => route.tls === 'manual' && pair !== undefined && coversHost(pair.hosts, route.host))\n if (holders.length > 0) {\n throw new DetailedError(\n `that certificate is still served by ${holders.map(route => `\"${route.id}\"`).join(', ')} — set those routes to another TLS mode first`,\n { statusCode: 400, code: 'PROXY_TLS_IN_USE', detail: { routes: holders.map(route => route.id) } },\n )\n }\n this.pairStore(id).clear()\n this.options.settings.updateProxy({ certificates: this.config.certificates.filter(entry => entry.id !== id) })\n this.certCache = null\n this.certificateSignature = null\n this.options.onStateChange()\n }\n\n /** Every uploaded pair, described: what it is for, and what it covers. */\n certificateViews(): ProxyCertificateView[] {\n return this.certSnapshot().views\n }\n\n /**\n * What the certificate snapshot depends on: the config it resolves against, and the\n * uploaded pair files themselves. Keying on both means a route edit, an upload, or a\n * pair that expired (or was replaced) on disk is reflected on the next read, while a\n * steady state still costs one read per 15 seconds.\n */\n private certKey(): string {\n const config = [\n ...this.config.certificates.map(entry => `${entry.id}:${entry.label}`),\n ...this.config.routes.map(route => `${route.id}:${route.host}:${route.tls}:${route.enabled}`),\n ].join('|')\n const files = this.config.certificates.map((entry) => {\n const store = this.pairStore(entry.id)\n const stamp = (file: string): string => {\n try {\n const stats = fs.statSync(file)\n return `${stats.mtimeMs}:${stats.size}`\n }\n catch {\n return 'x'\n }\n }\n return `${entry.id}:${stamp(store.certPath)}:${stamp(store.keyPath)}`\n }).join('|')\n return `${config}#${files}`\n }\n\n /** The certificate store read once, so a per-second tick costs nothing. */\n private certSnapshot(): { at: number, key: string, days: number | null, issued: Map<string, { notAfter: number, issuer: string }>, local: Map<string, { notAfter: number, lifetimeMs: number }>, views: ProxyCertificateView[] } {\n const key = this.certKey()\n if (this.certCache !== null && this.certCache.key === key && Date.now() - this.certCache.at < 15_000)\n return this.certCache\n const views = this.readCertificateViews()\n const issued = this.readIssuedCertificates()\n const local = this.readLocalCertificates()\n const values = [...issued.values()]\n const soonest = values.length === 0 ? null : Math.min(...values.map(entry => entry.notAfter))\n this.certCache = {\n at: Date.now(),\n key,\n days: soonest === null ? null : Math.floor((soonest - Date.now()) / 86_400_000),\n issued,\n local,\n views,\n }\n return this.certCache\n }\n\n /**\n * The pair that would actually serve this hostname: an exact SAN beats a wildcard,\n * and an expired or unreadable pair is not a candidate at all.\n */\n private bestCover(host: string): ProxyCertificateView | null {\n const usable = this.certificateViews().filter(entry => entry.present && entry.error === null)\n const name = host.toLowerCase()\n return usable.find(entry => entry.hosts.includes(name))\n ?? usable.find(entry => coversHost(entry.hosts, name))\n ?? null\n }\n\n private readCertificateViews(): ProxyCertificateView[] {\n const views = this.config.certificates.map((entry) => {\n const store = this.pairStore(entry.id)\n const base: ProxyCertificateView = {\n id: entry.id,\n label: entry.label,\n present: store.present,\n used: false,\n subject: null,\n issuer: null,\n validTo: null,\n daysRemaining: null,\n hosts: [],\n error: store.present ? null : 'the pair is not on disk',\n }\n const pair = store.load()\n if (pair === null)\n return base\n try {\n const x509 = new X509Certificate(pair.cert)\n const validTo = new Date(x509.validTo)\n return {\n ...base,\n subject: x509.subject.replace(/\\n/g, ', '),\n issuer: x509.issuer.replace(/\\n/g, ', '),\n validTo: validTo.toISOString(),\n daysRemaining: Math.floor((validTo.getTime() - Date.now()) / 86_400_000),\n hosts: namesOf(x509),\n error: store.status(true).error,\n }\n }\n catch (error) {\n return { ...base, error: `unreadable certificate: ${errorMessage(error)}` }\n }\n })\n\n // Two pairs can cover one name (a wildcard and an exact one, or two copies of the\n // same thing); the engine serves one, so say which. A pair no route would get is\n // reported as unused rather than healthy.\n const wanted = new Set<string>()\n for (const route of this.config.routes.filter(entry => entry.tls === 'manual')) {\n const name = route.host.toLowerCase()\n const usable = views.filter(entry => entry.present && entry.error === null)\n const best = usable.find(entry => entry.hosts.includes(name)) ?? usable.find(entry => coversHost(entry.hosts, name))\n if (best !== undefined)\n wanted.add(best.id)\n }\n return views.map(entry => ({ ...entry, used: wanted.has(entry.id) }))\n }\n\n /**\n * What a route's certificate situation is: read from the engine's own store for a\n * managed name, and from the last thing the engine said about it in its log.\n */\n private certificateFor(route: ProxyRoute): { state: ProxyCertificateState, message: string | null, retryInMinutes?: number } {\n if (route.tls === 'off')\n return { state: 'off', message: null }\n\n if (route.tls === 'manual') {\n const best = this.bestCover(route.host)\n if (best !== null)\n return { state: 'uploaded', message: best.label.length > 0 ? best.label : best.id }\n\n // A pair that covers the name but cannot be used says why — an expired one is the\n // case that would otherwise be served happily.\n const covering = this.certificateViews().find(entry => entry.present && coversHost(entry.hosts, route.host))\n return {\n state: 'failed',\n message: covering === undefined\n ? `no uploaded certificate covers ${route.host}`\n : `${covering.error ?? 'the uploaded certificate cannot be used'} — upload a valid pair for ${route.host}`,\n }\n }\n\n if (!isPublicHost(route.host)) {\n // A local-only name is signed by the engine's own CA — but only once that CA has\n // actually issued it. Saying \"signed\" from the hostname alone meant the page read\n // `local` while the handshake failed (`tlsv1 alert internal error`) and the cleartext\n // port redirected into it, because readiness is what decides between the redirect and\n // the notice page. Until the leaf is there it is pending, and a refusal the engine\n // logged is `failed` with the engine's own reason.\n if (this.localCertificates().has(route.host.toLowerCase()))\n return { state: 'local', message: 'signed by the engine\\'s own CA' }\n const refusal = this.obtainFailures().get(route.host.toLowerCase())\n return refusal === undefined\n ? { state: 'pending', message: 'the engine is issuing its own certificate' }\n : { state: 'failed', message: refusal }\n }\n\n const issued = this.issuedCertificates().get(route.host.toLowerCase())\n if (issued !== undefined)\n return { state: 'issued', message: `expires in ${Math.floor((issued.notAfter - Date.now()) / 86_400_000)} days` }\n\n const failure = this.obtainFailures().get(route.host.toLowerCase())\n\n // The engine fell back to its own CA: the name is served, but not by a trusted\n // issuer. It is not `pending` — nothing is still coming unless the engine tries\n // again — and not `failed`, because the name answers.\n const local = this.localCertificates().get(route.host.toLowerCase())\n if (local !== undefined) {\n return {\n state: 'fallback',\n message: failure ?? 'the CA has not issued for this name',\n retryInMinutes: retryWindowMinutes(local.lifetimeMs),\n }\n }\n\n return failure === undefined\n ? { state: 'pending', message: 'the engine is waiting for a certificate' }\n : { state: 'failed', message: failure }\n }\n\n /** Managed certificates the engine holds, by hostname. */\n private issuedCertificates(): Map<string, { notAfter: number, issuer: string }> {\n return this.certSnapshot().issued\n }\n\n /** Certificates the engine's own CA issued, by hostname. */\n private localCertificates(): Map<string, { notAfter: number, lifetimeMs: number }> {\n return this.certSnapshot().local\n }\n\n /**\n * The engine's own certificates, which `readIssuedCertificates` skips on purpose.\n *\n * A public name in here means the CA would not issue and the engine fell back to\n * its own CA — a state worth its own name, because the name is served but not by a\n * trusted issuer, and it clears itself when the engine next tries the CA.\n */\n private readLocalCertificates(): Map<string, { notAfter: number, lifetimeMs: number }> {\n const found = new Map<string, { notAfter: number, lifetimeMs: number }>()\n const root = path.join(this.options.engineDir, 'data', 'certificates', 'local')\n let entries: fs.Dirent[]\n try {\n entries = fs.readdirSync(root, { withFileTypes: true })\n }\n catch {\n return found\n }\n for (const entry of entries) {\n if (!entry.isDirectory())\n continue\n try {\n const x509 = new X509Certificate(fs.readFileSync(path.join(root, entry.name, `${entry.name}.crt`)))\n const notAfter = new Date(x509.validTo).getTime()\n const notBefore = new Date(x509.validFrom).getTime()\n for (const host of namesOf(x509))\n found.set(host, { notAfter, lifetimeMs: Math.max(0, notAfter - notBefore) })\n }\n catch {\n // Not a PEM we can read; it is not evidence about any certificate.\n }\n }\n return found\n }\n\n private readIssuedCertificates(): Map<string, { notAfter: number, issuer: string }> {\n const found = new Map<string, { notAfter: number, issuer: string }>()\n const root = path.join(this.options.engineDir, 'data', 'certificates')\n const walk = (dir: string, inside: boolean): void => {\n let entries: fs.Dirent[]\n try {\n entries = fs.readdirSync(dir, { withFileTypes: true })\n }\n catch {\n return\n }\n for (const entry of entries) {\n const full = path.join(dir, entry.name)\n if (entry.isDirectory()) {\n // The engine's own CA renews constantly; only public issuance is reported.\n if (!inside && entry.name === 'local')\n continue\n walk(full, true)\n continue\n }\n if (!entry.name.endsWith('.crt'))\n continue\n try {\n const x509 = new X509Certificate(fs.readFileSync(full))\n const info = { notAfter: new Date(x509.validTo).getTime(), issuer: x509.issuer.replace(/\\n/g, ', ') }\n for (const host of namesOf(x509)) {\n const known = found.get(host)\n if (known === undefined || info.notAfter < known.notAfter)\n found.set(host, info)\n }\n }\n catch {\n // Not a PEM we can read; it is not evidence about any certificate.\n }\n }\n }\n walk(root, false)\n return found\n }\n\n /**\n * The last thing the engine said about obtaining a certificate, per name. Caddy\n * has no admin endpoint that lists failures, so its own log is the source.\n *\n * Memoised on the file's identity and mtime, because this is called **per route** from\n * `routeViews()` — which `view()` runs for every state frame and `sync()` runs every tick.\n * Each call read the whole log (bounded at 2 MB by rotation), split every line and kept the\n * last 400: ~1.3 ms each, so ~13 ms of blocking synchronous I/O per second at ten routes,\n * for a file that only changes when the engine tries to obtain a certificate.\n *\n * The key is `ino` + `mtimeMs` + size, not mtime alone: rotation replaces the file, and a\n * replacement can land in the same millisecond as the previous read.\n */\n private obtainFailures(): Map<string, string> {\n const file = path.join(this.options.logDir, `${PROXY_ID}.log`)\n\n let stamp: string\n try {\n const stats = fs.statSync(file)\n stamp = `${stats.ino}:${stats.mtimeMs}:${stats.size}`\n }\n catch {\n // No log is a real answer, and it must not be cached as one: the engine may write it a\n // moment from now.\n this.failureCache = null\n return new Map()\n }\n\n if (this.failureCache !== null && this.failureCache.stamp === stamp)\n return this.failureCache.failures\n\n let text: string\n try {\n text = fs.readFileSync(file, 'utf8')\n }\n catch {\n return new Map()\n }\n\n const failures = this.parseFailures(text, new Map())\n this.failureCache = { stamp, failures }\n return failures\n }\n\n private parseFailures(text: string, failures: Map<string, string>): Map<string, string> {\n for (const line of text.trimEnd().split('\\n').slice(-400)) {\n let inner: Record<string, unknown>\n try {\n const outer = JSON.parse(line) as { text?: string }\n inner = JSON.parse(outer.text ?? '') as Record<string, unknown>\n }\n catch {\n continue\n }\n const identifier = typeof inner.identifier === 'string' ? inner.identifier.toLowerCase() : null\n if (identifier === null)\n continue\n if (inner.logger === 'tls.obtain' && typeof inner.error === 'string')\n failures.set(identifier, inner.error)\n // A later success clears it, so a name that recovered is not reported failed —\n // but only a CA issuance counts. The engine's own CA answering is the fallback\n // itself, and letting that clear the reason would hide why the CA refused.\n if (inner.msg === 'certificate obtained successfully' && inner.issuer !== 'local')\n failures.delete(identifier)\n }\n return failures\n }\n\n // ------------------------------------------------------------------ lifecycle\n\n /**\n * Called once at boot. A running engine is reattached, not restarted: unlike a\n * server entry it was never the panel's child, so it is still serving.\n */\n async initialize(): Promise<void> {\n fs.mkdirSync(this.options.stateDir, { recursive: true, mode: 0o700 })\n // A spec on disk belongs to a nanny that never read it.\n const swept = sweepNannySpecs(this.options.stateDir)\n if (swept > 0)\n logger.warn(`proxy: removed ${swept} unread nanny spec file(s)`)\n this.admin = this.readAdmin()\n\n if (!this.config.enabled)\n return\n const blocked = this.options.exposureBlocked()\n if (blocked !== null) {\n // A hand-edited config can ask for something the settings write would have\n // refused; the engine simply does not start, and the panel says why.\n this.lastError = blocked\n logger.error(`proxy: not starting — ${blocked}`)\n return\n }\n if (!this.installed()) {\n this.lastError = 'the proxy engine is not installed'\n return\n }\n\n if (this.live()) {\n logger.info(`proxy: reattached to the running ${this.config.engine} engine`)\n // A reattached engine still holds the configuration from before this panel\n // started — after an upgrade that is the old shape. Applying is a no-op when\n // nothing changed.\n await this.apply().catch((error: unknown) => {\n logger.warn(`proxy: could not apply the current configuration to the reattached engine: ${errorMessage(error)}`)\n })\n return\n }\n try {\n await this.start()\n }\n catch (error) {\n this.lastError = errorMessage(error)\n logger.error(`proxy: could not start: ${this.lastError}`)\n }\n }\n\n /**\n * True while a process from the installed binary is alive, however the panel's view\n * reads. `live()` additionally requires a fresh heartbeat, so a nanny that died and\n * left its child behind would look gone while the binary is still in use.\n */\n private engineRunning(): boolean {\n const state = readNannyState(nannyStatePath(this.options.stateDir, PROXY_ID))\n if (state === null || state.serverId !== PROXY_ID)\n return false\n return [state.nannyPid, state.childPid].some(pid => pid !== null && pid > 0 && isProcessAlive(pid))\n }\n\n private live(): boolean {\n const state = readNannyState(nannyStatePath(this.options.stateDir, PROXY_ID))\n if (state === null || state.serverId !== PROXY_ID)\n return false\n return state.nannyPid > 0\n && isProcessAlive(state.nannyPid)\n && Date.now() - state.heartbeatAt <= HEARTBEAT_STALE_MS\n }\n\n status(): ProxyStatus {\n const config = this.config\n const base: ProxyStatus = {\n state: 'off',\n pid: null,\n urls: [],\n certExpiryDays: null,\n since: null,\n lastError: null,\n }\n if (!config.enabled)\n return base\n\n // The ports the engine bound, not the ones the settings now ask for: a reload the engine\n // rejected leaves it serving on what it already had.\n //\n // Three states, and `??` conflated two of them: no record at all (fall back to what is\n // configured, the engine has not said), and a record whose port is `null` — \"the document did\n // not bind it\", which must advertise **no** URL rather than the configured one. The page links\n // these, so a substituted port is a link that refuses.\n const applied = this.readApplied()\n const boundPortsNow = (port: number | null | undefined, configured: number): number | null =>\n port === undefined ? configured : port\n // 127.0.0.1 rather than `localhost`: the engine listens on IPv4, and a resolver that answers\n // ::1 first makes a working engine look dead.\n const urls: string[] = []\n const httpPort = boundPortsNow(applied === null ? undefined : applied.httpPort, config.httpPort)\n if (httpPort !== null)\n urls.push(`http://127.0.0.1:${httpPort}`)\n const httpsPort = boundPortsNow(applied === null ? undefined : applied.httpsPort, config.httpsPort)\n if (httpsPort !== null)\n urls.push(`https://127.0.0.1:${httpsPort}`)\n const certExpiryDays = this.certificateExpiryDays()\n if (!this.installed())\n return { ...base, state: 'stopped', urls, certExpiryDays, lastError: 'the proxy engine is not installed' }\n\n const state = readNannyState(nannyStatePath(this.options.stateDir, PROXY_ID))\n if (state === null || state.serverId !== PROXY_ID || state.nannyPid <= 0 || !isProcessAlive(state.nannyPid)) {\n const lastExit = state?.lastExit\n const detail = lastExit === undefined\n ? null\n : `the engine exited with ${lastExit.signal === null ? `code ${lastExit.code}` : `signal ${lastExit.signal}`}`\n const lastError = this.lastError ?? detail\n return { ...base, state: lastError === null ? 'stopped' : 'error', urls, certExpiryDays, lastError }\n }\n if (Date.now() - state.heartbeatAt > HEARTBEAT_STALE_MS)\n return { ...base, state: 'error', urls, certExpiryDays, pid: state.childPid, since: state.startedAt, lastError: 'the engine stopped answering (its nanny is gone)' }\n\n const identity = { pid: state.childPid ?? state.nannyPid, since: state.startedAt, certExpiryDays }\n if (this.admin === null)\n return { ...base, state: 'starting', urls, ...identity, lastError: this.lastError }\n // A nanny that outlived its child leaves a state file behind for a moment; the\n // admin endpoint is the thing we would actually talk to.\n if (this.admin.kind === 'unix' && !fs.existsSync(this.admin.path))\n return { ...base, state: 'error', urls, ...identity, lastError: this.lastError ?? 'the engine is not answering on its admin endpoint' }\n\n return { ...base, state: 'running' as ProxyRunState, urls, ...identity, lastError: this.lastError }\n }\n\n // --------------------------------------------------------------------- config\n\n /** Backoff for a failing `sync()` re-apply; see the retry notes there. */\n private nextSyncAttemptAt = 0\n private syncFailures = 0\n private lastSyncError: string | null = null\n\n /** Records why the last start or apply failed, for the frame the page reads. */\n recordError(message: string | null): void {\n this.lastError = message\n this.options.onStateChange()\n }\n\n update(patch: ProxyPatch): ProxyConfig {\n const config = this.options.settings.updateProxy(patch)\n this.options.onStateChange()\n return config\n }\n\n /**\n * Makes the engine ask the CA again for one name, without restarting it.\n *\n * Caddy keeps the certificate it holds — in memory and on disk — until the name\n * leaves its configuration, and the engine's own CA is the last issuer in the\n * policy, so a name the CA refused is served that untrusted pair and never asks\n * again until renewal. Reloading the configuration without the route is what makes\n * the engine let go; the stored pair is dropped while it is out, so putting the\n * route back leaves nothing to reuse and the engine asks the CA.\n *\n * Only this name is out of the configuration, and only for the two reloads: every\n * other route keeps serving.\n */\n async retryCertificate(routeId: string): Promise<void> {\n const route = this.config.routes.find(entry => entry.id === routeId)\n if (route === undefined)\n throw new DetailedError(`unknown route \"${routeId}\"`, { statusCode: 404, code: 'PROXY_ROUTE_UNKNOWN' })\n if (route.tls !== 'auto' || !isPublicHost(route.host)) {\n throw new DetailedError(`\"${route.host}\" is not a name a CA issues for, so there is nothing to retry`, { statusCode: 400, code: 'PROXY_CERT_NOT_MANAGED' })\n }\n if (!this.installed())\n throw new DetailedError('the proxy engine is not installed yet', { statusCode: 400, code: 'ENGINE_MISSING' })\n if (this.status().state !== 'running') {\n // Nothing is serving the certificate, so there is nothing to make it let go of.\n this.forgetCertificates(route.host)\n await this.apply({ force: true })\n return\n }\n\n // Loading a configuration with this route removed is what makes the engine let go of its\n // certificate. With a single route that configuration has **no listeners at all** — the render\n // drops every server when no route is left — and a `load` it accepts takes the site dark, so\n // refuse before posting anything rather than rely on the apply behind it to put it back.\n // Count what the staged config actually *serves*, not routes: a second route that is disabled\n // or whose target is down renders no listener either, and a `load` the engine accepts would\n // take the site dark.\n const staged = this.render(new Set([route.id]))\n if (boundPorts(staged).length === 0) {\n throw new DetailedError(\n `making the engine forget its certificate for \"${route.host}\" would leave nothing served — add another working route first`,\n { statusCode: 409, code: 'PROXY_CERT_RETRY_LAST_ROUTE' },\n )\n }\n const servedText = fs.existsSync(this.options.configPath) ? fs.readFileSync(this.options.configPath, 'utf8') : null\n await this.loadIntoEngine(staged)\n this.forgetCertificates(route.host)\n try {\n await this.apply({ force: true })\n }\n catch (error) {\n // The engine is still on the staged config, which leaves this name dark: put back what it\n // served before. Its stored pair is already gone, so the engine still asks the CA again.\n if (servedText !== null) {\n await this.loadIntoEngine(JSON.parse(servedText) as Record<string, unknown>).catch((restoreError: unknown) => {\n logger.error(`proxy: could not restore the configuration after a failed certificate retry: ${errorMessage(restoreError)}`)\n })\n }\n throw error\n }\n }\n\n /** Removes the engine's stored certificates for one name, and nothing else. */\n private forgetCertificates(host: string): void {\n const root = path.join(this.options.engineDir, 'data', 'certificates')\n let issuers: string[]\n try {\n issuers = fs.readdirSync(root)\n }\n catch {\n // Nothing stored yet: the next attempt is already a fresh one.\n return\n }\n for (const issuer of issuers) {\n const dir = path.join(root, issuer, host)\n // The host comes from the route table and not from a request, so this is a\n // second belt rather than the only one.\n if (!dir.startsWith(`${root}${path.sep}`))\n continue\n fs.rmSync(dir, { recursive: true, force: true })\n }\n }\n\n /** Renders the current route table and applies it; the engine keeps serving on failure. */\n async apply(options: { force?: boolean } = {}): Promise<void> {\n if (!this.config.enabled || !this.installed())\n return\n // The same preflight `start()` makes: turning DNS-01 on against a running engine\n // from an older release lands here, and the user deserves the reason rather than\n // whatever Caddy says about an unknown module.\n await this.assertDns01Module()\n if (this.admin === null) {\n const stillThere = this.readAdmin()\n if (stillThere === null)\n return\n this.admin = stillThere\n }\n\n const signature = this.syncSignature()\n const rendered = this.render()\n const text = `${JSON.stringify(rendered, null, 2)}\\n`\n if (options.force !== true && fs.existsSync(this.options.configPath) && fs.readFileSync(this.options.configPath, 'utf8') === text) {\n this.certificateSignature = signature\n this.lastError = null\n return\n }\n\n // The engine cannot bind a port a stranger holds, and the raw error it answers\n // with names no process. Ask first, so the answer names the pid to stop.\n await this.assertPortsFree(this.config.httpPort, this.config.httpsPort)\n\n await this.postConfiguration(rendered)\n\n // Only now is this the configuration: the file the engine boots from must never\n // hold a revision it refused.\n this.rememberConfig(text)\n this.recordApplied(rendered)\n this.certificateSignature = signature\n // The reload is also what makes the engine forget a name it no longer serves, so\n // this is the moment its stored certificate for that name is safe to drop.\n const swept = this.sweepUnroutedCertificates()\n if (swept > 0)\n logger.info(`proxy: dropped ${swept} certificate(s) for names no longer routed`)\n this.lastError = null\n this.options.onStateChange()\n }\n\n /**\n * Certificates the engine holds for names it no longer serves.\n *\n * Caddy keeps a certificate until the name leaves its configuration, so a removed\n * route would leave its pair behind and re-adding the route would serve that stale\n * certificate instead of asking the CA. A *disabled* route keeps its pair: it is\n * still configured, and a temporary switch-off should not cost a new issuance.\n */\n private sweepUnroutedCertificates(): number {\n const managed = new Set(this.config.routes.filter(route => route.tls !== 'off').map(route => route.host.toLowerCase()))\n // The name the engine answers a bare-IP visitor with is not a route, but its\n // certificate is one the engine manages.\n managed.add(FALLBACK_NAME.toLowerCase())\n\n const root = path.join(this.options.engineDir, 'data', 'certificates')\n let issuers: string[]\n try {\n issuers = fs.readdirSync(root)\n }\n catch {\n return 0\n }\n\n let removed = 0\n for (const issuer of issuers) {\n const dir = path.join(root, issuer)\n let hosts: fs.Dirent[]\n try {\n hosts = fs.readdirSync(dir, { withFileTypes: true })\n }\n catch {\n continue\n }\n for (const host of hosts) {\n if (!host.isDirectory() || managed.has(host.name.toLowerCase()))\n continue\n fs.rmSync(path.join(dir, host.name), { recursive: true, force: true })\n removed += 1\n }\n }\n return removed\n }\n\n /**\n * Posts one rendered configuration to the engine's admin endpoint and reports a refusal.\n *\n * The three call sites used to spell this out themselves, and one of them forgot to record\n * `lastError` — which is what `status()` shows as the proxy's state, so a configuration the\n * engine refused could leave the panel reporting the proxy as healthy. Keeping both the\n * message and the state in one place is the point.\n */\n private async postConfiguration(rendered: unknown): Promise<void> {\n const result = await this.request('POST', '/load', rendered).catch((error: unknown) => {\n this.lastError = `the engine did not accept the configuration: ${errorMessage(error)}`\n throw new DetailedError(this.lastError, { statusCode: 502, code: 'ENGINE_UNREACHABLE' })\n })\n if (result.status >= 400) {\n this.lastError = engineMessage(result.body) ?? `the engine rejected the configuration (HTTP ${result.status})`\n throw new DetailedError(this.lastError, { statusCode: 400, code: 'PROXY_CONFIG_REJECTED' })\n }\n }\n\n /** Hands a configuration to the running engine without touching the file on disk. */\n private async loadIntoEngine(rendered: Record<string, unknown>): Promise<void> {\n await this.postConfiguration(rendered)\n }\n\n /** Advances `previous.json` only for a configuration the engine accepted. */\n private rememberConfig(text: string): void {\n // 0600: the generated configuration carries the DNS-01 challenge password in\n // cleartext, because the engine has to read it. The engine runs as this user.\n if (fs.existsSync(this.options.configPath))\n writeFileAtomic(this.options.previousConfigPath, fs.readFileSync(this.options.configPath, 'utf8'), { mode: 0o600 })\n writeFileAtomic(this.options.configPath, text, { mode: 0o600 })\n }\n\n /** The ports the engine last bound — `null` for a configured port the document did not bind. */\n private readApplied(): { httpPort: number | null, httpsPort: number | null } | null {\n try {\n const parsed = appliedRecordSchema(JSON.parse(fs.readFileSync(path.join(this.options.stateDir, 'applied.json'), 'utf8')))\n return parsed instanceof type.errors ? null : { httpPort: parsed.httpPort ?? null, httpsPort: parsed.httpsPort ?? null }\n }\n catch {\n return null\n }\n }\n\n /**\n * Records what the engine is now bound to, derived from the document it was given.\n *\n * One implementation for both write sites (`apply()` and `start()`): a `tls: 'off'`-only table\n * binds no HTTPS listener, and a table with nothing servable binds neither, so a configured port\n * the document did not bind is recorded as `null` rather than claimed. The preflight reads this\n * record as its witness, so a wrong number here admits a stranger standing on that port.\n */\n private recordApplied(rendered: Record<string, unknown>): void {\n const bound = boundPorts(rendered)\n const config = this.config\n this.rememberApplied(\n bound.includes(config.httpPort) ? config.httpPort : null,\n bound.includes(config.httpsPort) ? config.httpsPort : null,\n )\n }\n\n private rememberApplied(httpPort: number | null, httpsPort: number | null): void {\n writeFileAtomic(path.join(this.options.stateDir, 'applied.json'), `${JSON.stringify({ httpPort, httpsPort, at: Date.now() })}\\n`, { mode: 0o600 })\n }\n\n /**\n * Days until the soonest publicly-issued certificate expires. The engine's own CA\n * is left out on purpose: it re-issues constantly, so its leaves are always hours\n * from expiry and would read as a problem.\n */\n private certificateExpiryDays(): number | null {\n return this.certSnapshot().days\n }\n\n /** True when an uploaded pair covers this hostname. */\n private manualCovers(host: string): boolean {\n return this.bestCover(host) !== null\n }\n\n /** Everything `render()` reads that moves without a config save: certificate state and live upstreams. */\n private syncSignature(): string {\n return this.resolveRoutes()\n .map(({ route, status, upstream, upstreamTls }) => `${route.id}:${this.certificateFor(route).state}:${status}:${upstream ?? ''}:${upstreamTls}`)\n .join('|')\n }\n\n /**\n * Re-applies the configuration when what it was built from moved — a name that just\n * obtained its certificate, or a `server` route whose entry came up or went down (the\n * boot apply runs before any entry has started). Cheap enough for the panel's tick:\n * the store read is cached.\n */\n async sync(): Promise<void> {\n if (!this.config.enabled || !this.installed())\n return\n if (this.status().state !== 'running')\n return\n const signature = this.syncSignature()\n if (signature === this.certificateSignature)\n return\n const first = this.certificateSignature === null\n if (first) {\n this.certificateSignature = signature\n return\n }\n // A failure must be retried — that is the difference between \"transient\" and \"permanently\n // stuck\" — but the tick is one second, so retrying every tick posts to the engine 86k times a\n // day and logs every one. Back off, and give up on a failure that has repeated.\n if (Date.now() < this.nextSyncAttemptAt)\n return\n try {\n await this.apply()\n this.certificateSignature = signature\n this.syncFailures = 0\n this.nextSyncAttemptAt = 0\n }\n catch (error) {\n const message = errorMessage(error)\n this.syncFailures += 1\n this.nextSyncAttemptAt = Date.now() + Math.min(SYNC_RETRY_MAX_MS, SYNC_RETRY_BASE_MS * 2 ** (this.syncFailures - 1))\n // Logged on the first failure and then only when it changes, so a stuck route neither\n // floods the log nor goes quiet.\n if (message !== this.lastSyncError) {\n this.lastSyncError = message\n logger.warn(`proxy: could not re-apply after a certificate or upstream change: ${message}`)\n }\n if (this.lastError !== message)\n this.recordError(message)\n // After the cap, stop retrying this signature until it changes again: a re-apply that has\n // failed this many times will not start working on its own.\n if (this.syncFailures >= SYNC_MAX_FAILURES)\n this.certificateSignature = signature\n }\n }\n\n /**\n * Puts the last configuration that applied back, and keeps the rejected one as\n * the new \"previous\" — so a revert is itself revertible.\n */\n async revert(): Promise<void> {\n if (!fs.existsSync(this.options.previousConfigPath)) {\n throw new DetailedError('there is no earlier engine configuration to go back to', { statusCode: 400, code: 'PROXY_NO_PREVIOUS' })\n }\n const current = fs.existsSync(this.options.configPath) ? fs.readFileSync(this.options.configPath, 'utf8') : null\n const previous = fs.readFileSync(this.options.previousConfigPath, 'utf8')\n\n // Routed through the same helper as every other load: this path used to let a bare\n // request failure escape without recording `lastError`, and without the one error shape\n // the rest of the panel speaks.\n const restored = JSON.parse(previous) as Record<string, unknown>\n await this.postConfiguration(restored)\n\n // 0600 here too: reverting must not hand back a world-readable configuration\n // that carries the DNS-01 challenge password.\n writeFileAtomic(this.options.configPath, previous, { mode: 0o600 })\n // The record follows the engine, not the file: a revert moves it to another revision, so\n // leaving the old ports recorded makes `assertPortsFree` refuse this panel's own engine and\n // admit a stranger standing on a port the reverted document no longer binds.\n this.recordApplied(restored)\n if (current === null)\n fs.rmSync(this.options.previousConfigPath, { force: true })\n else writeFileAtomic(this.options.previousConfigPath, current, { mode: 0o600 })\n this.lastError = null\n this.options.onStateChange()\n }\n\n /**\n * The engine configuration for the current route table. Throws when a route cannot\n * be built, because a half-built configuration is worse than a refused one.\n */\n private render(exclude?: ReadonlySet<string>): Record<string, unknown> {\n const blocked = this.resolveRoutes(exclude).find(view => view.status === 'error')\n if (blocked !== undefined)\n throw new DetailedError(blocked.message ?? `${blocked.route.host} cannot be routed`, { statusCode: 400, code: 'PROXY_ROUTE_INVALID' })\n\n const routes = this.engineRoutes(exclude)\n return renderCaddyConfig({\n config: this.config,\n admin: this.admin ?? this.unixAdmin(),\n engineDir: this.options.engineDir,\n manual: this.manualPairs(),\n acme: this.acmeAccount(routes),\n dns01: this.dns01Input(routes),\n routes,\n })\n }\n\n /** The uploaded pairs, when any route actually asks for one. */\n private manualPairs(): Array<{ certificate: string, key: string }> {\n if (!this.config.routes.some(route => route.tls === 'manual'))\n return []\n return this.certificateViews()\n .filter(entry => entry.present && entry.error === null)\n .map(entry => this.pairStore(entry.id))\n .map(store => ({ certificate: store.certPath, key: store.keyPath }))\n }\n\n /** The ACME account, and the names it may issue for: only the public ones. */\n private acmeAccount(routes: readonly ProxyUpstreamRoute[]): { email: string, staging: boolean, subjects: string[] } {\n return {\n email: this.config.email.trim(),\n staging: this.config.staging,\n subjects: routes.filter(route => route.tls === 'auto' && isPublicHost(route.host)).map(route => route.host),\n }\n }\n\n /** The route's path as an engine prefix: trailing slashes are not a different route. */\n private static pathKey(path: string): string {\n const trimmed = path.trim()\n return trimmed.replace(/\\/+$/, '')\n }\n\n /** Every route, resolved far enough to render. */\n private resolveRoutes(exclude?: ReadonlySet<string>): ResolvedRoute[] {\n const seen = new Map<string, string>()\n return this.config.routes.filter(route => exclude?.has(route.id) !== true).map((route): ResolvedRoute => {\n // `/app` and `/app/` render overlapping matchers, so one would silently shadow\n // the other; they are the same route for this check.\n const key = `${route.host.toLowerCase()}${ProxyService.pathKey(route.path)}`\n const clash = seen.get(key)\n if (clash !== undefined)\n return { route, status: 'error', upstream: null, upstreamTls: false, message: `\"${route.host}\" is routed twice (${clash} and ${route.id})` }\n seen.set(key, route.id)\n\n if (!route.enabled)\n return { route, status: 'disabled', upstream: null, upstreamTls: false, message: null }\n\n // `manual` means the uploaded pair and nothing else: without one the engine\n // would quietly obtain its own certificate for a name the user marked manual.\n if (route.tls === 'manual' && !this.manualCovers(route.host)) {\n const reason = this.certificateFor(route).message ?? `no uploaded certificate covers ${route.host}`\n return { route, status: 'error', upstream: null, upstreamTls: false, message: `\"${route.id}\" ${reason}` }\n }\n\n if (route.target === 'external') {\n const parsed = parseUpstream(route.url)\n if (parsed === null)\n return { route, status: 'error', upstream: null, upstreamTls: false, message: `\"${route.id}\" needs an upstream like http://10.0.0.5:8080` }\n return { route, status: 'ok', upstream: parsed.dial, upstreamTls: parsed.tls, message: null }\n }\n\n if (route.target === 'panel') {\n const endpoint = this.options.control()\n if (!endpoint.port)\n return { route, status: 'no-upstream', upstream: null, upstreamTls: false, message: 'the control panel is not listening' }\n return { route, status: 'ok', upstream: `127.0.0.1:${endpoint.port}`, upstreamTls: endpoint.protocol === 'https', message: null }\n }\n\n if (route.workspace.length === 0 || route.server.length === 0)\n return { route, status: 'error', upstream: null, upstreamTls: false, message: `\"${route.id}\" needs a workspace and a server` }\n\n const resolved = this.options.resolveServer(route.workspace, route.server)\n if (resolved === null)\n return { route, status: 'error', upstream: null, upstreamTls: false, message: `\"${route.id}\" points at ${route.workspace}/${route.server}, which does not exist` }\n if (resolved.url === null)\n return { route, status: 'no-upstream', upstream: null, upstreamTls: false, message: resolved.message ?? `${route.workspace}/${route.server} is not running` }\n return { route, status: 'ok', upstream: resolved.url.replace(/^https?:\\/\\//, ''), upstreamTls: resolved.url.startsWith('https://'), message: null }\n })\n }\n\n /** Only the routes the engine can serve, in the shape the renderer wants. */\n private engineRoutes(exclude?: ReadonlySet<string>): ProxyUpstreamRoute[] {\n return this.resolveRoutes(exclude)\n .filter(resolved => resolved.status === 'ok' && resolved.upstream !== null)\n .map((resolved) => {\n const certificate = this.certificateFor(resolved.route)\n return {\n host: resolved.route.host,\n path: resolved.route.path,\n dial: resolved.upstream!,\n upstreamTls: resolved.upstreamTls,\n tls: resolved.route.tls,\n // A name whose certificate is not there yet gets a rendered page on the\n // cleartext side instead of a redirect into a handshake that cannot finish.\n certificateReady: certificate.state === 'issued' || certificate.state === 'local' || certificate.state === 'uploaded',\n }\n })\n }\n\n /**\n * Every route, with the upstream resolved live. A route whose entry is stopped\n * is reported, not silently dropped: the panel says why the hostname is dark.\n */\n routeViews(): ProxyRouteView[] {\n return this.resolveRoutes().map(({ route, status, upstream, message }) => ({\n route,\n status,\n upstream,\n message,\n certificate: this.certificateFor(route),\n }))\n }\n\n view(): ProxyView {\n return {\n config: this.config,\n engine: this.engineStatus(),\n engines: proxyEngineInfos(),\n status: this.status(),\n routes: this.routeViews(),\n certificates: this.certificateViews(),\n dnsAccounts: this.options.listDnsAccounts?.() ?? [],\n }\n }\n\n // ---------------------------------------------------------------------- engine\n\n installed(): boolean {\n try {\n return fs.statSync(this.enginePath).isFile()\n }\n catch {\n return false\n }\n }\n\n private readEngineRecord(): EngineRecord | null {\n try {\n const parsed: unknown = JSON.parse(fs.readFileSync(path.join(this.options.binDir, 'engine.json'), 'utf8'))\n if (typeof parsed !== 'object' || parsed === null || Array.isArray(parsed))\n return null\n const parsedRecord = engineRecordSchema(parsed)\n return parsedRecord instanceof type.errors ? null : parsedRecord\n }\n catch {\n return null\n }\n }\n\n engineStatus(): ProxyEngineStatus {\n const path_ = this.enginePath\n const base: ProxyEngineStatus = {\n id: this.config.engine,\n installed: false,\n version: null,\n source: null,\n path: null,\n bytes: null,\n error: null,\n }\n let stats: fs.Stats\n try {\n stats = fs.statSync(path_)\n }\n catch {\n return base\n }\n const record = this.readEngineRecord()\n return {\n ...base,\n installed: stats.isFile(),\n version: record?.version ?? null,\n source: record?.source ?? (stats.isFile() ? 'custom' : null),\n path: path_,\n bytes: record?.bytes ?? stats.size,\n }\n }\n\n /**\n * Downloads a release from the engine's own build service. Plugins are compiled\n * in server-side, so no toolchain is involved. An empty `version` asks for the\n * current release, which is how a security fix reaches the user by pressing Update.\n *\n * Refused while the engine is up: the binary is replaced on disk, and Windows\n * will not replace a running executable at all. Stopping first is the caller's\n * move, so the panel never drops a socket that faces the internet on its own.\n */\n async install(version = ''): Promise<ProxyEngineStatus> {\n const engine = this.engine\n if (version.length > 0 && !/^v?\\d+\\.\\d+\\.\\d[\\w.+-]*$/.test(version)) {\n throw new DetailedError(`\"${version}\" is not a ${engine.info.label} version`, { statusCode: 400, code: 'INVALID_ENGINE_VERSION' })\n }\n if (this.engineRunning()) {\n throw new DetailedError(`the ${engine.info.label} engine is still running — stop it before installing another build`, { statusCode: 409, code: 'ENGINE_BUSY' })\n }\n const download = engine.download({ platform: process.platform, arch: process.arch, version })\n if (download === null) {\n throw new DetailedError(`${engine.info.label} has no build for ${process.platform}/${process.arch}`, { statusCode: 400, code: 'UNSUPPORTED_PLATFORM' })\n }\n\n fs.mkdirSync(this.options.binDir, { recursive: true, mode: 0o700 })\n // Keeps the binary's own extension, because it is run before the swap and Windows starts a `.exe`.\n const target = path.join(path.dirname(this.enginePath), `download-${path.basename(this.enginePath)}`)\n fs.rmSync(target, { force: true })\n\n const response = await fetch(download.url, { redirect: 'follow', signal: AbortSignal.timeout(DOWNLOAD_TIMEOUT_MS) })\n if (!response.ok || response.body === null) {\n throw new DetailedError(`the ${engine.info.label} build service answered ${response.status}`, { statusCode: 502, code: 'ENGINE_DOWNLOAD_FAILED' })\n }\n\n const handle = fs.openSync(target, 'w', 0o755)\n let bytes = 0\n try {\n for await (const chunk of response.body as unknown as AsyncIterable<Uint8Array>) {\n const buffer = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk)\n bytes += buffer.length\n fs.writeSync(handle, buffer)\n }\n }\n finally {\n fs.closeSync(handle)\n }\n if (bytes === 0) {\n fs.rmSync(target, { force: true })\n throw new DetailedError(`the ${engine.info.label} build service returned an empty binary`, { statusCode: 502, code: 'ENGINE_DOWNLOAD_FAILED' })\n }\n\n if (process.platform !== 'win32')\n fs.chmodSync(target, 0o755)\n\n // Probed before the swap: a build that cannot run must not replace one that can. And what\n // the binary says it is, not what was asked for — the build service answers a request for\n // a version (or plugins) it does not have with its current release.\n const probed = await this.probeEngineVersion(target)\n if (probed === null) {\n fs.rmSync(target, { force: true })\n throw new DetailedError(`the downloaded ${engine.info.label} build did not report a version, so the installed engine was kept`, { statusCode: 502, code: 'ENGINE_DOWNLOAD_FAILED' })\n }\n fs.renameSync(target, this.enginePath)\n\n const record: EngineRecord = {\n engine: engine.info.id,\n version: probed,\n source: 'downloaded',\n url: download.url,\n bytes,\n installedAt: Date.now(),\n }\n writeFileAtomic(path.join(this.options.binDir, 'engine.json'), `${JSON.stringify(record, null, 2)}\\n`, { mode: 0o600 })\n // The binary changed, so what it carries has to be read again.\n this.moduleCache = null\n logger.info(`proxy: installed ${engine.info.label} ${record.version} (${Math.round(bytes / 1024 / 1024)} MB)`)\n this.options.onStateChange()\n return this.engineStatus()\n }\n\n /**\n * Runs the binary for its stdout, with a deadline. The engine is operator-supplied\n * — a replaced or wrapped binary that never exits must not hang `start()` or the\n * request that triggered it, so a timeout kills it and reads as \"no answer\".\n */\n private runEngine(args: string[], timeoutMs: number, binary = this.enginePath): Promise<string | null> {\n if (binary === this.enginePath && !this.installed())\n return Promise.resolve(null)\n return new Promise<string | null>((resolve) => {\n const child = spawn(binary, args, { stdio: ['ignore', 'pipe', 'ignore'], windowsHide: true })\n let output = ''\n let settled = false\n let timer: NodeJS.Timeout | undefined\n let killTimer: NodeJS.Timeout | undefined\n /** The escalation is cancelled by a real exit, never by `finish`. */\n const stopEscalation = (): void => {\n if (killTimer === undefined)\n return\n clearTimeout(killTimer)\n killTimer = undefined\n }\n const finish = (value: string | null): void => {\n if (settled)\n return\n settled = true\n if (timer !== undefined)\n clearTimeout(timer)\n resolve(value)\n }\n timer = setTimeout(() => {\n // Polite first, then certain: a binary that ignores SIGTERM would otherwise\n // stay alive after we have already given up on it. The escalation outlives\n // this call on purpose — clearing it here cancelled the SIGKILL in the same\n // tick and left the pathological engine running.\n child.kill()\n killTimer = setTimeout(() => child.kill('SIGKILL'), 500)\n killTimer.unref()\n finish(null)\n }, timeoutMs)\n child.stdout?.on('data', (chunk: Buffer) => {\n output += chunk.toString('utf8')\n })\n child.on('error', () => {\n stopEscalation()\n finish(null)\n })\n child.on('exit', () => {\n // It really is gone, so there is nothing left to escalate against.\n stopEscalation()\n finish(output)\n })\n })\n }\n\n /** Runs `version` once and reports what the binary — the installed one unless named — actually is. */\n async probeEngineVersion(binary = this.enginePath): Promise<string | null> {\n const output = await this.runEngine(['version'], this.options.engineCommandTimeoutMs ?? ENGINE_COMMAND_TIMEOUT_MS, binary)\n return output === null ? null : this.engine.parseVersion(output)\n }\n\n /**\n * The modules the installed binary carries, by module name.\n *\n * A build from an earlier release has no ACMEProxy module, and a configuration\n * that names it fails inside the engine with something a person cannot act on.\n * `list-modules` answers in a few milliseconds, so asking is cheaper than the\n * support question it prevents.\n */\n async installedModules(): Promise<Set<string> | null> {\n if (!this.installed())\n return null\n if (this.moduleCache !== null)\n return this.moduleCache\n const output = await this.runEngine(['list-modules'], this.options.engineCommandTimeoutMs ?? ENGINE_COMMAND_TIMEOUT_MS)\n // No answer is not an empty answer: nothing is cached, so a later call retries.\n if (output === null)\n return null\n const modules = new Set(output.split('\\n').map(line => line.trim()).filter(line => line.length > 0))\n this.moduleCache = modules\n return modules\n }\n\n /** The module the panel's DNS-01 configuration needs the engine to carry. */\n private async assertDns01Module(): Promise<void> {\n if (!this.config.dns01.enabled)\n return\n const modules = await this.installedModules()\n // An unreadable module list is not evidence of a missing module: the engine\n // still gets its chance, and its own log carries the reason if it refuses.\n if (modules === null || modules.has(DNS01_MODULE))\n return\n throw new DetailedError(\n `the installed ${this.engine.info.label} build has no ${DNS01_MODULE} module — update the engine to enable DNS-01`,\n { statusCode: 400, code: 'ENGINE_MODULE_NOT_INSTALLED' },\n )\n }\n\n // -------------------------------------------------------------------- start/stop\n\n async start(): Promise<void> {\n const config = this.config\n if (!config.enabled)\n throw new DetailedError('the reverse proxy is switched off', { statusCode: 400, code: 'PROXY_DISABLED' })\n const blocked = this.options.exposureBlocked()\n if (blocked !== null)\n throw new DetailedError(blocked, { statusCode: 400, code: 'PROXY_EXPOSURE_BLOCKED' })\n if (!this.installed()) {\n throw new DetailedError('the proxy engine is not installed yet', { statusCode: 400, code: 'ENGINE_MISSING' })\n }\n await this.assertDns01Module()\n if (this.live()) {\n const admin = this.readAdmin()\n if (admin === null) {\n throw new DetailedError('the engine is already running but its admin endpoint is unknown — stop it first', { statusCode: 409, code: 'ENGINE_ALREADY_RUNNING' })\n }\n this.admin = admin\n await this.apply()\n return\n }\n\n await this.assertPortsFree(config.httpPort, config.httpsPort)\n\n const admin = await (this.options.chooseAdmin ?? this.chooseAdmin.bind(this))()\n this.admin = admin\n const invalid = this.resolveRoutes().find(view => view.status === 'error')\n if (invalid !== undefined)\n throw new DetailedError(invalid.message ?? 'a route cannot be built', { statusCode: 400, code: 'PROXY_ROUTE_INVALID' })\n\n const signature = this.syncSignature()\n const routes = this.engineRoutes()\n const rendered = renderCaddyConfig({\n config,\n admin,\n engineDir: this.options.engineDir,\n manual: this.manualPairs(),\n acme: this.acmeAccount(routes),\n dns01: this.dns01Input(routes),\n routes,\n })\n fs.mkdirSync(this.options.engineDir, { recursive: true, mode: 0o700 })\n this.rememberConfig(`${JSON.stringify(rendered, null, 2)}\\n`)\n writeFileAtomic(this.options.adminPath, `${JSON.stringify(admin)}\\n`, { mode: 0o600 })\n\n const specPath = nannySpecPath(this.options.stateDir, PROXY_ID)\n const statePath = nannyStatePath(this.options.stateDir, PROXY_ID)\n const env = {\n ...this.engine.env({ configPath: this.options.configPath, engineDir: this.options.engineDir, admin }),\n HHOSTED_SERVER_ID: PROXY_ID,\n }\n writeNannySpec(specPath, {\n serverId: PROXY_ID,\n command: this.enginePath,\n args: this.engine.runArgs({ configPath: this.options.configPath, engineDir: this.options.engineDir, admin }),\n cwd: this.options.engineDir,\n env,\n logDir: this.options.logDir,\n logs: { persist: true, maxBytes: 2_000_000, keep: 3 },\n // Caddy shuts down gracefully on SIGTERM; the group is not ours to signal.\n stop: { signal: 'SIGTERM', killGroup: false, graceMs: 10_000, killPortHolders: false },\n })\n\n const nanny = spawn(process.execPath, nannyArgv(nannyEntryPoint(), PROXY_ID, specPath, statePath), {\n cwd: this.options.engineDir,\n env: { ...process.env, ...env, HHOSTED_HOME: dataRoot, HHOSTED_PROJECT: projectDir },\n stdio: ['ignore', 'ignore', 'ignore'],\n detached: true,\n windowsHide: true,\n })\n // A failure from an earlier attempt must not be read as this one's cause.\n this.nannyError = null\n this.nanny = nanny\n // A spawn that never happens — EMFILE/ENFILE, EACCES, or an execPath that moved —\n // emits 'error' and no 'exit' at all, and an unhandled 'error' event ends the whole\n // panel. A failure and a short life clean up identically, once.\n const nannyGone = (): void => {\n if (this.nanny !== nanny)\n return\n this.nanny = null\n // The handle is gone, so nothing it owned is ours to talk to any more — a\n // stale admin.json would have the next apply() reach for a dead socket.\n this.admin = null\n fs.rmSync(this.options.adminPath, { force: true })\n this.options.onStateChange()\n }\n nanny.on('error', (error: Error) => {\n this.nannyError = `the proxy engine's nanny could not be started: ${error.message}`\n logger.error(`proxy: ${this.nannyError}`)\n nannyGone()\n })\n nanny.on('exit', nannyGone)\n\n const ready = await this.waitReady()\n if (!ready) {\n // The specific cause wins: a nanny that never spawned already recorded why.\n const failure = this.nannyError ?? `the engine did not answer on its admin endpoint within ${Math.round(READY_TIMEOUT_MS / 1000)}s: ${this.logTail()}`\n await this.stop().catch(() => undefined)\n this.lastError = failure\n throw new DetailedError(failure, { statusCode: 502, code: 'ENGINE_NOT_READY' })\n }\n this.recordApplied(rendered)\n this.certificateSignature = signature\n this.lastError = null\n logger.info(`proxy: ${this.engine.info.label} serving on :${this.config.httpPort} and :${this.config.httpsPort}`)\n this.options.onStateChange()\n }\n\n /**\n * Stops the engine for real. The nanny holds its pipes, so the child is\n * signalled by pid first — the arrangement a persistent entry uses, and the\n * reason a stop cannot be a bare SIGKILL.\n */\n async stop(): Promise<void> {\n const statePath = nannyStatePath(this.options.stateDir, PROXY_ID)\n const state = readNannyState(statePath)\n\n if (state !== null && state.serverId === PROXY_ID) {\n // A state file is not proof the engine is running. Pids are recycled, and `PROXY_ID` is a\n // constant, so an old record can name a stranger that this panel has no handle on —\n // signalling it would kill an unrelated process. Ask the same identity question the\n // supervisor, `down` and the install guard ask, and only then treat the pids as ours.\n //\n // The nanny's own liveness proves the whole record is live (so its `childPid` is trusted\n // too, exactly as `resumePersistent` does after adoption); a child that outlived its nanny\n // is still ours when it carries the marker the nanny gave it.\n const nanny = await nannyIsAlive(state, PROXY_ID)\n const child = state.childPid !== null && state.childPid > 0\n && await processCarriesServerId(state.childPid, PROXY_ID)\n const pids = [\n ...(nanny ? [state.nannyPid] : []),\n ...(nanny || child ? [state.childPid] : []),\n ].filter((pid): pid is number => pid !== null && pid > 0)\n\n for (const pid of pids) {\n if (!isProcessAlive(pid))\n continue\n try {\n process.kill(pid, 'SIGTERM')\n }\n catch (error) {\n logger.warn(`proxy: could not signal pid ${pid}`, error)\n }\n }\n const deadline = Date.now() + (this.options.stopGraceMs ?? 10_000)\n while (Date.now() < deadline && pids.some(pid => isProcessAlive(pid)))\n await new Promise(resolve => setTimeout(resolve, 100))\n // Every survivor, not just the first: a nanny and a child that both ignore\n // SIGTERM left the second one holding :80/:443 while the state file, admin.json\n // and applied.json were removed right after — a later boot had no record to\n // stop it by, and the port preflight kept refusing on a pid the panel would\n // not touch.\n const survivors = pids.filter(isProcessAlive)\n for (const pid of survivors) {\n try {\n process.kill(pid, 'SIGKILL')\n }\n catch {\n // Already gone between the check and the signal.\n }\n }\n // The state file is the only record that can find a process which outlived SIGKILL, so it\n // is kept for one — the same exception `stopEntry` makes — rather than orphaning it.\n if (survivors.some(isProcessAlive))\n logger.warn(`proxy: pid ${survivors.join(', ')} ignored SIGKILL — keeping ${path.basename(statePath)} so a later boot can still stop it`)\n else\n fs.rmSync(statePath, { force: true })\n }\n\n this.nanny = null\n this.admin = null\n this.certCache = null\n this.certificateSignature = null\n // The failure described the run that just ended; keeping it pinned the badge to\n // \"Error\" with nothing left to stop, and blocked installing another build.\n this.lastError = null\n fs.rmSync(nannySpecPath(this.options.stateDir, PROXY_ID), { force: true })\n fs.rmSync(this.options.adminPath, { force: true })\n fs.rmSync(path.join(this.options.stateDir, 'applied.json'), { force: true })\n this.options.onStateChange()\n }\n\n /** The panel never owns the engine's lifetime, so a shutdown leaves it serving. */\n dispose(): void {\n if (this.nanny !== null)\n this.nanny.unref()\n this.nanny = null\n }\n\n /**\n * \"May we bind these ports\" — a **start** question, asked before handing the engine a\n * configuration it would fail to serve.\n *\n * A busy port is not automatically a problem: on a re-apply the engine is already bound to it,\n * which is the normal case. Pid attribution cannot tell the difference — the engine carries\n * `cap_net_bind_service`, which makes it non-dumpable, so `listPortHolders` returns an empty list\n * for the very port it serves on, and the old code read that as \"nothing there\" and then threw.\n *\n * What makes a port ours is the engine being live *and this configuration binding it*, both\n * answerable without inspecting anything: the nanny state's heartbeat, and the rendered config.\n * Note the two are not `httpPort`/`httpsPort` — a `tls: 'off'`-only config binds no HTTPS\n * listener, so claiming that port would admit a stranger standing on it.\n *\n * An attributable pid that is neither the nanny nor the engine is always foreign, whatever the\n * records say.\n */\n private async assertPortsFree(httpPort: number, httpsPort: number): Promise<void> {\n const state = readNannyState(nannyStatePath(this.options.stateDir, PROXY_ID))\n const live = state !== null && await nannyIsAlive(state, PROXY_ID)\n // What the engine is actually listening on, per the record written when it last applied. NOT\n // `engineRoutes()`: that drops every route whose upstream is down, so a stopped supervised\n // server would empty the set and freeze the config — the original bug in a narrower case.\n const applied = this.readApplied()\n const binds = new Set([applied?.httpPort ?? null, applied?.httpsPort ?? null].filter((port): port is number => port !== null))\n const enginePids = state === null ? [] : [state.nannyPid, state.childPid].filter((pid): pid is number => pid !== null)\n\n for (const port of [httpPort, httpsPort]) {\n if (await isPortFree(port))\n continue\n const holders = await listPortHolders(port)\n if (holders.some(pid => enginePids.includes(pid)))\n continue\n // A pid we can attribute is decisive: the engine is the only listener that may be ours.\n if (holders.length > 0) {\n throw new DetailedError(\n `port ${port} is already in use${this.describeHolders(port, holders)} — stop what holds it, or set another port in the reverse proxy settings`,\n { statusCode: 409, code: 'PROXY_PORT_IN_USE', detail: { port, holders } },\n )\n }\n // Unattributable: ours only if the engine is live *and* this configuration binds the port.\n if (live && binds.has(port))\n continue\n throw new DetailedError(\n `port ${port} is already in use${this.describeHolders(port, holders)} — stop what holds it, or set another port in the reverse proxy settings`,\n { statusCode: 409, code: 'PROXY_PORT_IN_USE', detail: { port, holders } },\n )\n }\n }\n\n /**\n * Who holds a busy port, in the most specific terms available.\n *\n * An empty holder list is not \"nothing is listening\": for a capped engine it is the normal\n * reading, and for a docker-published port it is a root-owned proxy this user may not inspect.\n * Say which engine it is when it is our own, and say plainly that the socket is uninspectable\n * rather than implying the port is idle.\n */\n private describeHolders(port: number, holders: number[]): string {\n if (holders.length > 0)\n return ` (pid ${holders.join(', ')})`\n const state = readNannyState(nannyStatePath(this.options.stateDir, PROXY_ID))\n // The engine's own ports are accepted before this is reached, so a port landing here is *not*\n // the engine — say only what is known: the socket cannot be inspected.\n if (state !== null) {\n const applied = this.readApplied()\n const bound = [applied?.httpPort ?? null, applied?.httpsPort ?? null].filter((port): port is number => port !== null)\n return bound.length === 0\n ? ' — the listener cannot be identified by this user (a process carrying cap_net_bind_service is non-dumpable), and the engine has no applied ports to match it against'\n : ` — the listener cannot be identified by this user (a process carrying cap_net_bind_service is non-dumpable), and the panel's engine binds :${bound.join('/')}, not this port`\n }\n return ' — the socket cannot be inspected by this user, so the holder cannot be named'\n }\n\n // ----------------------------------------------------------------------- admin\n\n private unixAdmin(): Extract<ProxyAdminTransport, { kind: 'unix' }> {\n return { kind: 'unix', path: path.join(this.options.stateDir, 'admin.sock') }\n }\n\n private async chooseAdmin(): Promise<ProxyAdminTransport> {\n const unix = this.unixAdmin()\n // A unix socket path has a platform limit (about 104 bytes on macOS), and a long\n // `$HHOSTED_HOME` can cross it.\n if (process.platform !== 'win32' && Buffer.byteLength(unix.path) <= 100) {\n // A socket file left by a killed engine would stop it binding a new one.\n fs.rmSync(unix.path, { force: true })\n return unix\n }\n // No unix sockets here, so loopback TCP plus the engine's own origin check.\n for (let attempt = 0; attempt < 20; attempt++) {\n const port = 45_000 + Math.floor(Math.random() * 10_000)\n if (await isPortFree(port))\n return { kind: 'tcp', host: '127.0.0.1', port, origin: `http://127.0.0.1:${port}` }\n }\n throw new DetailedError('could not find a free loopback port for the engine admin endpoint', { statusCode: 500, code: 'PROXY_NO_ADMIN_PORT' })\n }\n\n private readAdmin(): ProxyAdminTransport | null {\n try {\n const parsed = adminRecordSchema(JSON.parse(fs.readFileSync(this.options.adminPath, 'utf8')))\n if (parsed instanceof type.errors)\n return null\n if (parsed.kind === 'unix')\n return parsed.path.length > 0 ? { kind: 'unix', path: parsed.path } : null\n return parsed.port > 0 ? { kind: 'tcp', host: parsed.host, port: parsed.port, origin: parsed.origin } : null\n }\n catch {\n return null\n }\n }\n\n private request(method: string, urlPath: string, body?: unknown): Promise<{ status: number, body: string }> {\n const admin = this.admin\n if (admin === null)\n return Promise.reject(new DetailedError('the proxy engine is not running', { statusCode: 400, code: 'ENGINE_NOT_RUNNING' }))\n\n const payload = body === undefined ? null : Buffer.from(JSON.stringify(body))\n const headers: Record<string, string | number> = {}\n if (payload !== null) {\n headers['content-type'] = 'application/json'\n headers['content-length'] = payload.length\n }\n if (admin.kind === 'tcp')\n headers.origin = admin.origin\n\n return new Promise((resolve, reject) => {\n // The engine can answer with headers and half a body and then destroy the\n // socket. Only the first outcome wins, so a late 'error' after 'end' is noise.\n let settled = false\n const succeed = (value: { status: number, body: string }): void => {\n if (settled)\n return\n settled = true\n resolve(value)\n }\n const fail = (error: unknown): void => {\n if (settled)\n return\n settled = true\n reject(error instanceof Error ? error : new Error(String(error)))\n }\n\n const request = http.request({\n ...(admin.kind === 'unix' ? { socketPath: admin.path } : { host: admin.host, port: admin.port }),\n method,\n path: urlPath,\n headers,\n timeout: ADMIN_TIMEOUT_MS,\n }, (response) => {\n const chunks: Buffer[] = []\n response.on('data', (chunk: Buffer) => chunks.push(chunk))\n response.on('end', () => succeed({ status: response.statusCode ?? 0, body: Buffer.concat(chunks).toString('utf8') }))\n // A truncated response is not an answer: without these the promise never\n // settles, and everything awaiting it — apply(), start()'s waitReady() and\n // the panel tick's sync() — waits for good.\n response.on('error', fail)\n response.on('aborted', () => fail(new Error('the engine closed the connection before it answered')))\n })\n request.on('timeout', () => request.destroy(new Error('the engine did not answer in time')))\n request.on('error', fail)\n if (payload !== null)\n request.write(payload)\n request.end()\n })\n }\n\n private async waitReady(): Promise<boolean> {\n if (this.options.waitReady !== undefined)\n return this.options.waitReady()\n const deadline = Date.now() + READY_TIMEOUT_MS\n while (Date.now() < deadline) {\n // The nanny that was going to bring the engine up is gone — a spawn that\n // failed, or one that died with its child. Nothing answers after that, so the\n // rest of the deadline would only delay the failure that is already recorded.\n if (this.nanny === null)\n return false\n try {\n const result = await this.request('GET', '/config/')\n if (result.status < 400)\n return true\n }\n catch {\n // Not up yet, or not there at all.\n }\n await new Promise(resolve => setTimeout(resolve, READY_POLL_MS))\n }\n return false\n }\n\n /** The last few engine lines, for a start that failed. */\n private logTail(): string {\n try {\n const file = path.join(this.options.logDir, `${PROXY_ID}.log`)\n const text = fs.readFileSync(file, 'utf8')\n const lines = text.trimEnd().split('\\n').slice(-3)\n return lines.map((line) => {\n try {\n const parsed = JSON.parse(line) as { text?: string }\n return parsed.text ?? line\n }\n catch {\n return line\n }\n }).join(' | ')\n }\n catch {\n return 'no engine output yet'\n }\n }\n}\n\n/**\n * When the engine tries the CA again, in minutes.\n *\n * certmagic renews once a third of a certificate's lifetime is left, so two thirds\n * of it is the wait; the engine's own CA issues 12 hours by default, which is where\n * the \"about 8 hours\" comes from. Read from the certificate, so shortening that\n * lifetime shortens the wait too.\n */\nfunction retryWindowMinutes(lifetimeMs: number): number {\n return Math.max(1, Math.round((lifetimeMs / 60_000) * (2 / 3)))\n}\n\n/** `host:port`, `http://host:port` or `https://host:port`; `null` when unusable. */\nexport function parseUpstream(value: string): { dial: string, tls: boolean } | null {\n const trimmed = value.trim()\n if (trimmed.length === 0)\n return null\n // An explicit scheme that is neither http nor https is a mistake, not a hostname: `ftp://x.com` used\n // to fall through to the prefixing branch, become `http://ftp://x.com`, parse with hostname `ftp`,\n // and report `status: 'ok'` with a dial target of `ftp:80`.\n const explicit = /^([a-z][a-z0-9+.-]*):\\/\\//i.exec(trimmed)\n if (explicit !== null && !/^https?$/i.test(explicit[1]!))\n return null\n\n const withScheme = explicit === null ? `http://${trimmed}` : trimmed\n try {\n const url = new URL(withScheme)\n // `new URL` normalizes a default port away, and the scheme's own default is a\n // port all the same: without this, `http://10.0.0.5:80` was refused, and a route\n // in that state made the whole table read as invalid.\n const port = url.port.length > 0 ? url.port : url.protocol === 'https:' ? '443' : '80'\n return { dial: `${url.hostname}:${port}`, tls: url.protocol === 'https:' }\n }\n catch {\n return null\n }\n}\n\n/** What a route's `dnsAccount` resolves to, for the save-time check. */\nexport interface DnsAccountCheck {\n provider: string\n /** The provider can write a TXT record, which is the only thing a challenge needs. */\n writesTxt: boolean\n /** Credentials are stored for the account. */\n hasCredentials: boolean\n}\n\n/**\n * The engine policies DNS-01 needs: one per account, because a policy carries one\n * challenge provider. Names that no account answers are left out, and the caller\n * renders them on the port challenges as before.\n *\n * Pure so the grouping can be checked without an engine: getting it wrong means a\n * hostname is asked for through the wrong zone, which fails with nothing to read.\n */\nexport function groupDns01Policies(\n routes: readonly ProxyUpstreamRoute[],\n accountFor: (host: string) => { workspaceId: string, accountId: string, provider: string } | null,\n): Array<{ account: string, provider: string, subjects: string[] }> {\n const byAccount = new Map<string, { provider: string, subjects: string[] }>()\n for (const route of routes) {\n // Only names a CA could issue for: a loopback address or a `.lan` name belongs to\n // the engine's own CA, and listing it here made Caddy try ACME for an IP.\n if (route.tls !== 'auto' || !isPublicHost(route.host))\n continue\n const account = accountFor(route.host)\n if (account === null)\n continue\n const key = `${account.workspaceId}/${account.accountId}`\n const existing = byAccount.get(key)\n if (existing === undefined)\n byAccount.set(key, { provider: account.provider, subjects: [route.host] })\n else if (!existing.subjects.includes(route.host))\n existing.subjects.push(route.host)\n }\n return [...byAccount.entries()].map(([account, group]) => ({ account, provider: group.provider, subjects: group.subjects }))\n}\n\n/** Cross-field problems ArkType cannot see, reported by the API before a save. */\nexport function validateProxyConfig(config: ProxyConfig, dnsAccount?: (ref: string, workspaceId: string) => DnsAccountCheck | null): string[] {\n const errors: string[] = []\n if (config.httpPort === config.httpsPort)\n errors.push('the http and https ports must differ')\n\n const advertised = new Set(config.routes.filter(route => route.tls !== 'off').map(route => route.host.toLowerCase()))\n const publicNames = [...advertised].filter(host => isPublicHost(host))\n if (publicNames.length > 0 && config.email.trim().length === 0 && !config.staging)\n errors.push(`automatic HTTPS needs an ACME account e-mail for ${publicNames.join(', ')}`)\n\n const seen = new Set<string>()\n const ids = new Set<string>()\n for (const route of config.routes) {\n if (ids.has(route.id))\n errors.push(`route id \"${route.id}\" is used twice`)\n ids.add(route.id)\n\n const key = `${route.host.toLowerCase()}${route.path.trim().replace(/\\/+$/, '')}`\n if (seen.has(key))\n errors.push(`\"${route.host}\" is routed twice`)\n seen.add(key)\n\n if (route.target === 'server' && (route.workspace.length === 0 || route.server.length === 0))\n errors.push(`route \"${route.id}\" needs a workspace and a server`)\n if (route.target === 'external' && parseUpstream(route.url) === null)\n errors.push(`route \"${route.id}\" needs an upstream like http://10.0.0.5:8080`)\n\n // A named account has to be able to do the one thing it is named for. Catching it\n // here beats a challenge that fails weeks later with nothing to read.\n const named = route.dnsAccount.trim()\n if (named.length === 0 || dnsAccount === undefined)\n continue\n if (!config.dns01.enabled)\n errors.push(`route \"${route.id}\" names DNS account \"${named}\", but DNS-01 is switched off`)\n // The route's own workspace, which is where the challenge path looks it up too.\n const found = dnsAccount(named, route.workspace)\n if (found === null)\n errors.push(`route \"${route.id}\" names unknown DNS account \"${named}\"`)\n else if (!found.writesTxt)\n errors.push(`route \"${route.id}\": the \"${found.provider}\" account cannot write TXT records, so it cannot answer a DNS-01 challenge`)\n else if (!found.hasCredentials)\n errors.push(`route \"${route.id}\": the \"${found.provider}\" account has no credentials stored yet`)\n }\n return errors\n}\n\n/** Caddy answers with `{\"error\": \"...\"}`; that sentence is the useful part. */\nfunction engineMessage(body: string): string | null {\n try {\n const parsed = JSON.parse(body) as { error?: unknown }\n return typeof parsed.error === 'string' && parsed.error.length > 0 ? parsed.error : null\n }\n catch {\n return body.trim().length > 0 ? body.trim().slice(0, 400) : null\n }\n}\n","import type { AppDeps } from '#src/app'\nimport type { ProxyConfig } from '#src/shared/contracts'\nimport { DetailedError } from '@namesmt/utils'\nimport { type } from 'arktype'\nimport { describeRoute } from 'hono-openapi'\nimport { applyPatch, PROXY_MERGE_KEYS } from '#src/config/patch'\nimport { ConfigError } from '#src/config/settings'\nimport { appFactory } from '#src/helpers/factory'\nimport { ERROR_RESPONSES, jsonBody } from '#src/helpers/openapi'\nimport { validate } from '#src/helpers/validator'\nimport { checkProxyExposure } from '#src/services/exposure'\nimport { validateProxyConfig } from '#src/services/proxy'\nimport {\n proxyCertificateUploadSchema,\n proxyConfigSchema,\n proxyEngineInstallSchema,\n proxyPatchSchema,\n proxyViewSchema,\n} from '#src/shared/contracts'\nimport { errorMessage } from '#src/shared/error-message'\n\nconst certificateParam = type({ id: '/^[a-z0-9][a-z0-9_-]*$/' })\n\n/** The patch, applied to the live config the way the store would apply it. */\nfunction candidateConfig(current: ProxyConfig, patch: Record<string, unknown>): ProxyConfig {\n const merged: Record<string, unknown> = { ...current }\n // The same merge the store will apply, so what is validated is what is committed:\n // a spread here would replace `dns01` where `updateProxy` merges it.\n applyPatch(merged, patch, PROXY_MERGE_KEYS)\n const parsed = proxyConfigSchema(merged)\n if (parsed instanceof type.errors)\n throw new DetailedError(parsed.summary, { statusCode: 400, code: 'INVALID_PROXY' })\n return parsed\n}\n\n/**\n * The reverse proxy is panel-wide: one engine, one route table, one set of ports.\n * Routes name a workspace for the entries they point at, because an id is only\n * unique inside one.\n */\nexport function createProxyRoute(deps: AppDeps) {\n const proxy = () => deps.proxy\n const view = () => proxy().view()\n\n /** Everything that has to hold before a change is written to disk. */\n const guard = (candidate: ProxyConfig): void => {\n const problems = validateProxyConfig(candidate, (ref, workspaceId) => proxy().checkDnsAccount(ref, workspaceId))\n if (problems.length > 0)\n throw new DetailedError(`invalid reverse proxy configuration: ${problems.join('; ')}`, { statusCode: 400, code: 'INVALID_PROXY', detail: problems })\n\n const exposure = checkProxyExposure(candidate, deps.panel.settings.control.auth.enabled, deps.auth.passwordSet, deps.auth.usingDefaultPassword)\n if (exposure !== null)\n throw new DetailedError(exposure, { statusCode: 400, code: 'PROXY_EXPOSURE_BLOCKED' })\n }\n\n /** A settings edit takes effect at once: apply to a running engine, start or stop otherwise. */\n const reconcile = async (): Promise<void> => {\n const config = proxy().config\n try {\n if (!config.enabled) {\n // Switching it off has to end the engine: `status()` calls a disabled proxy\n // \"off\" by definition, so it can never be the thing that decides this.\n await proxy().stop()\n return\n }\n if (proxy().status().state === 'running')\n await proxy().apply()\n else\n await proxy().start()\n }\n catch (error) {\n // The client gets the failure; the page gets it too, on the next frame.\n proxy().recordError(errorMessage(error))\n throw error\n }\n }\n\n return appFactory.createApp()\n .get(\n '/proxy',\n describeRoute({\n tags: ['proxy'],\n summary: 'Reverse proxy policy, engine and resolved routes',\n responses: { 200: { description: 'The proxy view', content: jsonBody(proxyViewSchema) } },\n }),\n c => c.json(view()),\n )\n\n .patch(\n '/proxy',\n describeRoute({\n tags: ['proxy'],\n summary: 'Change the reverse proxy settings or its route table',\n responses: { 200: { description: 'Saved and applied', content: jsonBody(proxyViewSchema) }, 400: ERROR_RESPONSES[400] },\n }),\n validate('json', proxyPatchSchema),\n async (c) => {\n const patch = c.req.valid('json')\n const candidate = candidateConfig(proxy().config, patch)\n guard(candidate)\n\n try {\n proxy().update(patch)\n }\n catch (error) {\n if (error instanceof ConfigError)\n throw new DetailedError(error.message, { statusCode: 400, code: 'INVALID_PROXY' })\n throw error\n }\n\n await reconcile()\n return c.json(view())\n },\n )\n\n .post(\n '/proxy/engine',\n describeRoute({\n tags: ['proxy'],\n summary: 'Install or update the proxy engine',\n responses: { 200: { description: 'Installed', content: jsonBody(proxyViewSchema) }, 400: ERROR_RESPONSES[400] },\n }),\n validate('json', proxyEngineInstallSchema),\n async (c) => {\n await proxy().install(c.req.valid('json').version)\n await reconcile()\n return c.json(view())\n },\n )\n\n .post(\n '/proxy/start',\n describeRoute({\n tags: ['proxy'],\n summary: 'Start the proxy engine',\n responses: { 200: { description: 'Started', content: jsonBody(proxyViewSchema) }, 400: ERROR_RESPONSES[400] },\n }),\n async (c) => {\n await proxy().start()\n return c.json(view())\n },\n )\n\n .post(\n '/proxy/stop',\n describeRoute({\n tags: ['proxy'],\n summary: 'Stop the proxy engine',\n responses: { 200: { description: 'Stopped', content: jsonBody(proxyViewSchema) } },\n }),\n async (c) => {\n await proxy().stop()\n return c.json(view())\n },\n )\n\n .post(\n '/proxy/routes/:id/retry-certificate',\n describeRoute({\n tags: ['proxy'],\n summary: 'Make the engine ask the CA again for one route',\n responses: {\n 200: { description: 'Retried', content: jsonBody(proxyViewSchema) },\n 400: ERROR_RESPONSES[400],\n 404: ERROR_RESPONSES[404],\n },\n }),\n async (c) => {\n await proxy().retryCertificate(c.req.param('id'))\n return c.json(view())\n },\n )\n\n .post(\n '/proxy/apply',\n describeRoute({\n tags: ['proxy'],\n summary: 'Regenerate and reload the engine configuration',\n responses: { 200: { description: 'Applied', content: jsonBody(proxyViewSchema) }, 400: ERROR_RESPONSES[400] },\n }),\n async (c) => {\n await proxy().apply()\n return c.json(view())\n },\n )\n\n .post(\n '/proxy/revert',\n describeRoute({\n tags: ['proxy'],\n summary: 'Go back to the engine configuration that applied before the last one',\n responses: { 200: { description: 'Reverted', content: jsonBody(proxyViewSchema) }, 400: ERROR_RESPONSES[400] },\n }),\n async (c) => {\n await proxy().revert()\n return c.json(view())\n },\n )\n\n .put(\n '/proxy/certificates/:id',\n describeRoute({\n tags: ['proxy'],\n summary: 'Store a certificate pair that routes with `tls: \"manual\"` serve',\n responses: { 200: { description: 'Stored', content: jsonBody(proxyViewSchema) }, 400: ERROR_RESPONSES[400] },\n }),\n validate('param', certificateParam),\n validate('json', proxyCertificateUploadSchema),\n async (c) => {\n const { id } = c.req.valid('param')\n const body = c.req.valid('json')\n const saved = proxy().saveCertificate(id, body.label, body.certificate, body.privateKey)\n if (!saved.ok)\n throw new DetailedError(saved.error ?? 'the certificate pair was rejected', { statusCode: 400, code: 'INVALID_CERTIFICATE' })\n\n if (proxy().status().state === 'running')\n await proxy().apply()\n return c.json(view())\n },\n )\n\n .delete(\n '/proxy/certificates/:id',\n describeRoute({\n tags: ['proxy'],\n summary: 'Remove an uploaded certificate pair',\n responses: { 200: { description: 'Removed', content: jsonBody(proxyViewSchema) }, 400: ERROR_RESPONSES[400] },\n }),\n validate('param', certificateParam),\n async (c) => {\n proxy().clearCertificate(c.req.valid('param').id)\n if (proxy().status().state === 'running')\n await proxy().apply()\n return c.json(view())\n },\n )\n}\n","import type { AppDeps } from '#src/app'\nimport { DetailedError } from '@namesmt/utils'\nimport { type } from 'arktype'\nimport { describeRoute } from 'hono-openapi'\nimport { streamSSE } from 'hono/streaming'\nimport { ConfigError } from '#src/config/store'\nimport { actionAnswer, actionCode, statusForAction, unknownServerError } from '#src/helpers/action-result'\nimport { appFactory } from '#src/helpers/factory'\nimport { ERROR_RESPONSES, jsonBody } from '#src/helpers/openapi'\nimport { frameKey, sseChannel } from '#src/helpers/sse'\nimport { validate } from '#src/helpers/validator'\nimport { requireWorkspace, workspaceQuerySchema } from '#src/helpers/workspace'\nimport { requestActor } from '#src/middleware/auth'\nimport { serverKey } from '#src/services/events'\nimport { actionResultSchema, bufferedLogsResponseSchema, freePortResultSchema, logQuerySchema, okResponseSchema, serverCreateSchema, serverPatchSchema, serverSchema, serverViewSchema } from '#src/shared/contracts'\n\nconst idParam = type({ id: 'string >= 1' })\nconst serverResponse = type({ server: serverViewSchema })\nconst serversResponse = type({ servers: serverViewSchema.array() })\n/**\n * A write answers the *stored* entry, not a view: `addServer`/`updateServer` return the\n * `ServerConfig` they committed, which is flat and carries no live status. Declaring the\n * view here was wrong and quietly misled clients — a consumer reading `server.config`\n * off a create got `undefined` with no error anywhere.\n */\nconst storedServerResponse = type({ server: serverSchema })\nconst bufferedLogsQuery = logQuerySchema.merge(workspaceQuerySchema)\n/**\n * `stop-all`'s own query: the workspace, plus `withPersistent`.\n *\n * Declared rather than read with `c.req.query('withPersistent')`, because `workspaceQuerySchema`\n * refuses a key it does not name — so the raw read would have been a `400` for the flag the route\n * exists to accept. The workspace schema is the **argument** of the merge, which is the side whose\n * `onUndeclaredKey` the result carries: `workspaceQuerySchema.merge(extra)` would have lost the\n * rejection and this route's typo rule with it.\n */\nconst stopAllQuery = type({ 'withPersistent?': 'string' }).merge(workspaceQuerySchema)\n\nexport function createServersRoute(deps: AppDeps) {\n return appFactory.createApp()\n .get(\n '/',\n describeRoute({\n tags: ['servers'],\n summary: 'Every supervised server in one workspace, with its live state',\n responses: { 200: { description: 'The servers', content: jsonBody(serversResponse) } },\n }),\n validate('query', workspaceQuerySchema),\n (c) => {\n const runtime = requireWorkspace(deps.panel.requireWorkspace.bind(deps.panel), c.req.valid('query').workspace)\n return c.json({ servers: runtime.supervisor.views() })\n },\n )\n\n .post(\n '/',\n describeRoute({\n tags: ['servers'],\n summary: 'Add a server to a workspace',\n responses: {\n 201: { description: 'Created', content: jsonBody(storedServerResponse) },\n 400: ERROR_RESPONSES[400],\n },\n }),\n validate('query', workspaceQuerySchema),\n validate('json', serverCreateSchema),\n (c) => {\n const runtime = requireWorkspace(deps.panel.requireWorkspace.bind(deps.panel), c.req.valid('query').workspace)\n try {\n return c.json({ server: runtime.store.addServer(c.req.valid('json')) }, 201)\n }\n catch (error) {\n if (error instanceof ConfigError)\n throw new DetailedError(error.message, { statusCode: 400, code: 'INVALID_SERVER' })\n throw error\n }\n },\n )\n\n /**\n * Declare an entry whether or not it exists — \"make it so\", for config management.\n *\n * `POST` refuses a duplicate and `PATCH` only merges, so a deploy script had to GET, diff and\n * then pick one; a re-run of an unchanged declaration answered `400 INVALID_SERVER` for its\n * trouble. The body is the whole entry (the create schema), never a patch, so a re-run\n * converges: 201 when it created, 200 when it replaced.\n */\n .put(\n '/:id',\n describeRoute({\n tags: ['servers'],\n summary: 'Create or replace one entry (idempotent)',\n responses: {\n 200: { description: 'Replaced', content: jsonBody(storedServerResponse) },\n 201: { description: 'Created', content: jsonBody(storedServerResponse) },\n 400: ERROR_RESPONSES[400],\n },\n }),\n validate('query', workspaceQuerySchema),\n validate('param', idParam),\n validate('json', serverCreateSchema),\n (c) => {\n const runtime = requireWorkspace(deps.panel.requireWorkspace.bind(deps.panel), c.req.valid('query').workspace)\n const { id } = c.req.valid('param')\n const body = c.req.valid('json')\n // The path names the entry; a body naming a different one is a mistake, not a rename.\n if (body.id !== id)\n throw new DetailedError(`the body's id \"${body.id}\" does not match the path id \"${id}\"`, { statusCode: 400, code: 'ID_MISMATCH' })\n\n try {\n const result = runtime.store.putServer(body)\n return c.json({ server: result.server }, result.created ? 201 : 200)\n }\n catch (error) {\n if (error instanceof ConfigError)\n throw new DetailedError(error.message, { statusCode: 400, code: 'INVALID_SERVER' })\n throw error\n }\n },\n )\n\n /**\n * Stop a process the panel started that no entry claims any more.\n *\n * The orphan list is on the workspace view; this is the action that makes it recoverable from\n * the panel instead of from `ps` and `kill` in a shell.\n */\n .post(\n '/orphans/:id/stop',\n describeRoute({\n tags: ['servers'],\n summary: 'Stop an orphaned process this panel started',\n responses: { 200: { description: 'Stopped', content: jsonBody(okResponseSchema) }, 404: ERROR_RESPONSES[404], 409: { description: 'The process survived the stop' } },\n }),\n validate('query', workspaceQuerySchema),\n validate('param', idParam),\n async (c) => {\n const runtime = requireWorkspace(deps.panel.requireWorkspace.bind(deps.panel), c.req.valid('query').workspace)\n const id = c.req.valid('param').id\n const result = await runtime.supervisor.stopOrphan(id)\n if (!result.ok) {\n // 404 when nothing is running under that id; 409 when a process is there and refused to\n // die — two different fixes, and the declared 409 had no path to it.\n const survived = result.error?.includes('survived the stop') === true\n throw new DetailedError(result.error ?? `could not stop the orphaned process \"${id}\"`, {\n statusCode: survived ? 409 : 404,\n code: survived ? 'ORPHAN_SURVIVED' : 'UNKNOWN_ORPHAN',\n })\n }\n return c.json({ ok: true })\n },\n )\n\n // Registered before `/:id` so the literal segments always win.\n .post(\n '/start-all',\n describeRoute({ tags: ['servers'], summary: 'Start every enabled server in a workspace', responses: { 200: { description: 'The servers', content: jsonBody(serversResponse) } } }),\n validate('query', workspaceQuerySchema),\n async (c) => {\n const runtime = requireWorkspace(deps.panel.requireWorkspace.bind(deps.panel), c.req.valid('query').workspace)\n await runtime.supervisor.startAll()\n return c.json({ servers: runtime.supervisor.views() })\n },\n )\n\n .post(\n '/stop-all',\n describeRoute({\n tags: ['servers'],\n summary: 'Stop every server in a workspace, persistent entries included if asked',\n responses: { 200: { description: 'The servers', content: jsonBody(serversResponse) } },\n }),\n validate('query', stopAllQuery),\n async (c) => {\n const runtime = requireWorkspace(deps.panel.requireWorkspace.bind(deps.panel), c.req.valid('query').workspace)\n // A client that omits `withPersistent` keeps the behaviour it has always had: the flag is\n // optional, and `=== 'true'` is the only spelling that asks for it.\n await runtime.supervisor.stopAll({ withPersistent: c.req.valid('query').withPersistent === 'true' })\n return c.json({ servers: runtime.supervisor.views() })\n },\n )\n\n .get(\n '/:id',\n describeRoute({ tags: ['servers'], summary: 'One server', responses: { 200: { description: 'The server', content: jsonBody(serverResponse) }, 404: ERROR_RESPONSES[404] } }),\n validate('query', workspaceQuerySchema),\n validate('param', idParam),\n (c) => {\n const runtime = requireWorkspace(deps.panel.requireWorkspace.bind(deps.panel), c.req.valid('query').workspace)\n const { id } = c.req.valid('param')\n const server = runtime.supervisor.views().find(entry => entry.id === id)\n if (!server)\n throw unknownServerError(id)\n return c.json({ server })\n },\n )\n\n .get(\n '/:id/logs',\n describeRoute({ tags: ['servers'], summary: 'Buffered log lines from memory', responses: { 200: { description: 'Lines', content: jsonBody(bufferedLogsResponseSchema) }, 404: ERROR_RESPONSES[404] } }),\n validate('query', bufferedLogsQuery),\n validate('param', idParam),\n (c) => {\n const runtime = requireWorkspace(deps.panel.requireWorkspace.bind(deps.panel), c.req.valid('query').workspace)\n const { id } = c.req.valid('param')\n if (!runtime.store.getServer(id))\n throw unknownServerError(id)\n\n const { limit } = c.req.valid('query')\n const parsed = limit === undefined ? Number.NaN : Number.parseInt(limit, 10)\n // Clamped: a negative or huge value must not slice from the wrong end.\n const bounded = Number.isNaN(parsed) ? undefined : Math.min(Math.max(parsed, 1), 100_000)\n return c.json({ lines: runtime.supervisor.logLines(id, bounded) })\n },\n )\n\n .get(\n '/:id/stream',\n describeRoute({ tags: ['servers'], summary: 'Server state and logs as server-sent events', responses: { 200: { description: 'text/event-stream' }, 404: ERROR_RESPONSES[404] } }),\n validate('query', workspaceQuerySchema),\n validate('param', idParam),\n (c) => {\n const runtime = requireWorkspace(deps.panel.requireWorkspace.bind(deps.panel), c.req.valid('query').workspace)\n const { id } = c.req.valid('param')\n if (!runtime.store.getServer(id))\n throw unknownServerError(id)\n\n return streamSSE(c, async (stream) => {\n const channel = sseChannel(stream)\n const send = (message: { type: string, workspaceId?: string, serverId?: string }): void => {\n channel.send(message.type, JSON.stringify(message), { key: frameKey(message), droppable: message.type === 'log' })\n }\n\n const unsubscribe = deps.hub.subscribe(serverKey(runtime.id, id), send)\n stream.onAbort(() => {\n channel.close()\n unsubscribe()\n })\n\n const server = runtime.supervisor.views().find(entry => entry.id === id)\n send({ type: 'server', ts: Date.now(), workspaceId: runtime.id, serverId: id, server } as never)\n send({ type: 'log', ts: Date.now(), workspaceId: runtime.id, serverId: id, lines: runtime.supervisor.logLines(id, 200) } as never)\n\n while (!channel.closed) {\n await stream.sleep(15000)\n channel.send('ping', String(Date.now()), { key: 'ping' })\n }\n })\n },\n )\n\n .post(\n '/:id/start',\n describeRoute({ tags: ['servers'], summary: 'Start a server', responses: { 200: { description: 'Result', content: jsonBody(actionResultSchema) }, 404: ERROR_RESPONSES[404], 409: { description: 'The entry cannot act right now' } } }),\n validate('query', workspaceQuerySchema),\n validate('param', idParam),\n async (c) => {\n const runtime = requireWorkspace(deps.panel.requireWorkspace.bind(deps.panel), c.req.valid('query').workspace)\n const result = await runtime.supervisor.start(c.req.valid('param').id, { actor: requestActor(c, deps.auth) })\n return c.json(actionAnswer(result), statusForAction(result))\n },\n )\n\n .post(\n '/:id/stop',\n describeRoute({ tags: ['servers'], summary: 'Stop a server', responses: { 200: { description: 'Result', content: jsonBody(actionResultSchema) }, 404: ERROR_RESPONSES[404], 409: { description: 'The entry cannot act right now' } } }),\n validate('query', workspaceQuerySchema),\n validate('param', idParam),\n async (c) => {\n const runtime = requireWorkspace(deps.panel.requireWorkspace.bind(deps.panel), c.req.valid('query').workspace)\n const result = await runtime.supervisor.stop(c.req.valid('param').id)\n return c.json(actionAnswer(result), statusForAction(result))\n },\n )\n\n .post(\n '/:id/restart',\n describeRoute({ tags: ['servers'], summary: 'Restart a server', responses: { 200: { description: 'Result', content: jsonBody(actionResultSchema) }, 404: ERROR_RESPONSES[404], 409: { description: 'The entry cannot act right now' } } }),\n validate('query', workspaceQuerySchema),\n validate('param', idParam),\n async (c) => {\n const runtime = requireWorkspace(deps.panel.requireWorkspace.bind(deps.panel), c.req.valid('query').workspace)\n const result = await runtime.supervisor.restart(c.req.valid('param').id, { actor: requestActor(c, deps.auth) })\n return c.json(actionAnswer(result), statusForAction(result))\n },\n )\n\n .post(\n '/:id/clear-logs',\n describeRoute({ tags: ['servers'], summary: 'Forget the buffered log lines', responses: { 200: { description: 'Cleared', content: jsonBody(okResponseSchema) } } }),\n validate('query', workspaceQuerySchema),\n validate('param', idParam),\n (c) => {\n const runtime = requireWorkspace(deps.panel.requireWorkspace.bind(deps.panel), c.req.valid('query').workspace)\n const { id } = c.req.valid('param')\n // `200 {\"ok\":true}` for an id that never existed is a lie a script believes: it cannot\n // tell \"cleared\" from \"I typo'd the id\".\n if (!runtime.store.getServer(id))\n throw unknownServerError(id)\n runtime.supervisor.clearLogs(id)\n return c.json({ ok: true })\n },\n )\n\n /**\n * The escape hatch for `port x is already in use (pid x)`: it re-lists the\n * listeners itself, so what is killed is the process holding the port now —\n * never a pid quoted in an old message, and never one this panel supervises.\n */\n .post(\n '/:id/free-port',\n describeRoute({\n tags: ['servers'],\n summary: 'Ask whatever holds this server\\'s port to stop',\n responses: {\n 200: { description: 'What was signalled', content: jsonBody(freePortResultSchema) },\n 404: ERROR_RESPONSES[404],\n 409: { description: 'Nothing to free, or the holder is supervised by this panel' },\n },\n }),\n validate('query', workspaceQuerySchema),\n validate('param', idParam),\n async (c) => {\n const runtime = requireWorkspace(deps.panel.requireWorkspace.bind(deps.panel), c.req.valid('query').workspace)\n const { id } = c.req.valid('param')\n const result = await runtime.supervisor.freePort(id)\n if (!result.ok) {\n // `UNKNOWN_SERVER` for a missing id, because that is the fix the caller needs; every\n // other refusal here is genuinely about the port.\n throw new DetailedError(result.error ?? `could not free the port for \"${id}\"`, {\n statusCode: statusForAction(result),\n code: actionCode(result) === 'UNKNOWN_SERVER' ? 'UNKNOWN_SERVER' : 'FREE_PORT_FAILED',\n })\n }\n return c.json(result)\n },\n )\n\n .patch(\n '/:id',\n describeRoute({ tags: ['servers'], summary: 'Edit a server', responses: { 200: { description: 'The server', content: jsonBody(storedServerResponse) }, 400: ERROR_RESPONSES[400], 404: ERROR_RESPONSES[404] } }),\n validate('query', workspaceQuerySchema),\n validate('param', idParam),\n validate('json', serverPatchSchema),\n (c) => {\n const runtime = requireWorkspace(deps.panel.requireWorkspace.bind(deps.panel), c.req.valid('query').workspace)\n try {\n return c.json({ server: runtime.store.updateServer(c.req.valid('param').id, c.req.valid('json')) })\n }\n catch (error) {\n if (error instanceof ConfigError) {\n // Branch on the exception's *code*, not its message: `startsWith('unknown server')` read\n // any future message with that prefix — \"unknown serverless runtime\" — as a missing id.\n const status = error.code === 'UNKNOWN_SERVER' ? 404 : 400\n throw new DetailedError(error.message, { statusCode: status, code: status === 404 ? 'UNKNOWN_SERVER' : 'INVALID_SERVER' })\n }\n throw error\n }\n },\n )\n\n .delete(\n '/:id',\n describeRoute({ tags: ['servers'], summary: 'Stop and remove a server', responses: { 200: { description: 'Removed', content: jsonBody(okResponseSchema) }, 404: ERROR_RESPONSES[404] } }),\n validate('query', workspaceQuerySchema),\n validate('param', idParam),\n async (c) => {\n const runtime = requireWorkspace(deps.panel.requireWorkspace.bind(deps.panel), c.req.valid('query').workspace)\n const { id } = c.req.valid('param')\n try {\n await runtime.supervisor.stop(id)\n runtime.store.removeServer(id)\n return c.json({ ok: true })\n }\n catch (error) {\n if (error instanceof ConfigError)\n throw unknownServerError(id)\n throw error\n }\n },\n )\n}\n","import type { GlobalSettingsStore } from '#src/config/settings'\nimport type { AuthService } from '#src/services/auth'\nimport type { ControlEndpoint } from '#src/services/control-server'\nimport type { TlsStore } from '#src/services/tls'\nimport type { ControlConfig, ControlView, DdnsStatus, DestinationStatusView, LogsConfig, NotificationDefaults, ServerDefaults, ServerOrphan, ServerView, WorkspaceView } from '#src/shared/contracts'\nimport { dataRoot, projectDir } from '#src/helpers/paths'\nimport { appVersion } from '#src/helpers/version'\nimport { checkExposure } from '#src/services/exposure'\n\nexport interface WorkspaceViewSource {\n id: string\n label: string\n store: {\n path: string\n settingsPath: string\n configError: string | null\n configWarnings: string[]\n defaults: ServerDefaults\n logs: LogsConfig\n }\n logsDir: string\n notifications: { defaults: () => NotificationDefaults, destinations: () => DestinationStatusView[] }\n ddns: { view: DdnsStatus }\n supervisor: { views: () => ServerView[], orphans?: () => ServerOrphan[] }\n}\n\n/**\n * The panel's own settings are derived here — configured values from the store,\n * live values from the listener, security state from the auth service and the\n * certificate pair from disk — so the UI never has to reason about the\n * differences.\n */\nexport function buildControlView(\n settings: GlobalSettingsStore,\n auth: AuthService,\n control: ControlEndpoint,\n tls: TlsStore,\n): ControlView {\n const config: ControlConfig = settings.control\n const exposure = checkExposure(config, auth.passwordSet, auth.usingDefaultPassword)\n\n return {\n label: config.label,\n port: config.port,\n host: config.host,\n bindHost: control.bindHost,\n url: control.url,\n protocol: control.protocol,\n openBrowser: config.openBrowser,\n allowedHosts: config.allowedHosts,\n restartRequired: control.port !== config.port || control.host !== config.host,\n auth: {\n enabled: config.auth.enabled,\n passwordSet: auth.passwordSet,\n passwordUpdatedAt: auth.passwordUpdatedAt,\n apiTokenSet: auth.apiTokenSet,\n usingDefaultPassword: auth.usingDefaultPassword,\n exposed: exposure.exposed,\n blockedReason: exposure.blockedReason,\n sessionTtlMs: config.auth.sessionTtlMs,\n cookieSecure: config.auth.cookieSecure,\n trustProxy: config.auth.trustProxy,\n maxLoginAttempts: config.auth.maxLoginAttempts,\n lockoutMs: config.auth.lockoutMs,\n },\n tls: tls.status(config.tls.enabled),\n }\n}\n\n/** One workspace's subtree of the state frame. */\nexport function buildWorkspaceView(source: WorkspaceViewSource): WorkspaceView {\n const servers = source.supervisor.views()\n return {\n id: source.id,\n label: source.label,\n configPath: source.store.path,\n settingsPath: source.store.settingsPath,\n configError: source.store.configError,\n configWarnings: source.store.configWarnings,\n logsDir: source.logsDir,\n defaults: source.store.defaults,\n logs: source.store.logs,\n notifications: {\n defaults: source.notifications.defaults(),\n destinations: source.notifications.destinations(),\n },\n ddns: source.ddns.view,\n serverCount: servers.length,\n runningCount: servers.filter(server => server.status === 'running').length,\n crashedCount: servers.filter(server => server.status === 'crashed').length,\n // Optional on the source so a fixture need not implement it; the real supervisor always\n // answers, and an empty array is the honest answer for \"nothing is running stray\".\n orphans: source.supervisor.orphans?.() ?? [],\n servers,\n }\n}\n\nexport { appVersion, dataRoot, projectDir }\n","import type { AppDeps } from '#src/app'\nimport type { WorkspaceRuntime } from '#src/services/panel'\nimport type { SettingsPatch } from '#src/shared/contracts'\nimport { Buffer } from 'node:buffer'\nimport fs from 'node:fs'\nimport path from 'node:path'\nimport { DetailedError } from '@namesmt/utils'\nimport { describeRoute } from 'hono-openapi'\nimport { bodyLimit } from 'hono/body-limit'\nimport { ConfigError } from '#src/config/store'\nimport { displayHost } from '#src/helpers/bind'\nimport { afterResponse } from '#src/helpers/deferred'\nimport { appFactory } from '#src/helpers/factory'\nimport { logger } from '#src/helpers/logger'\nimport { ERROR_RESPONSES, jsonBody } from '#src/helpers/openapi'\nimport { validate } from '#src/helpers/validator'\nimport { requireWorkspace, workspaceQuerySchema } from '#src/helpers/workspace'\nimport { requestIdentity } from '#src/middleware/auth'\nimport { checkExposure, checkProxyExposure } from '#src/services/exposure'\nimport { buildControlView } from '#src/services/state'\nimport { unknownBackupIds } from '#src/shared/backup-scope'\nimport {\n settingsPatchSchema,\n settingsSavedSchema,\n settingsViewSchema,\n uiInstallResponseSchema,\n workspaceSettingsPatchSchema,\n workspaceSettingsSavedSchema,\n workspaceSettingsViewSchema,\n} from '#src/shared/contracts'\n\n/** Uploads are buffered in memory by `parseBody`, so they get a hard ceiling. */\nconst MAX_UI_UPLOAD_BYTES = 128 * 1024 * 1024\n\n/** The archive's name is only a label, so it never reaches the filesystem. */\nfunction sanitizeName(name: string): string {\n const cleaned = name.replace(/\\.zip$/i, '').replace(/[^\\w.-]+/g, '-').replace(/^-+|-+$/g, '')\n return cleaned.length > 0 ? cleaned.slice(0, 60) : 'custom-ui'\n}\n\n/** What a workspace owns and can change on its own — never the panel-wide settings. */\nfunction buildWorkspaceSettings(runtime: WorkspaceRuntime) {\n return {\n id: runtime.id,\n label: runtime.label,\n settingsPath: runtime.store.settingsPath,\n configPath: runtime.store.path,\n configError: runtime.store.configError,\n defaults: runtime.store.defaults,\n logs: runtime.store.logs,\n notifications: {\n defaults: runtime.notifications.defaults(),\n destinations: runtime.notifications.destinations(),\n },\n }\n}\n\nexport function createSettingsRoute(deps: AppDeps) {\n const settings = deps.panel.settings\n\n return appFactory.createApp()\n .get(\n '/settings',\n describeRoute({\n tags: ['panel'],\n summary: 'The panel-wide settings: listener, host vitals, backups and UI',\n responses: { 200: { description: 'The settings', content: jsonBody(settingsViewSchema) } },\n }),\n c => c.json({\n control: buildControlView(settings, deps.auth, deps.controlServer.endpoint, deps.tls),\n host: settings.host,\n backups: deps.backups.view(),\n ui: deps.ui.status(),\n }),\n )\n\n .patch('/settings', describeRoute({\n tags: ['panel'],\n summary: 'Edit the panel-wide settings: listener, host vitals and backups',\n responses: { 200: { description: 'Saved; the listener may be moving', content: jsonBody(settingsSavedSchema) }, 400: ERROR_RESPONSES[400] },\n }), validate('json', settingsPatchSchema), async (c) => {\n const patch: SettingsPatch = c.req.valid('json')\n const current = settings.control\n\n // Refuse an exposure that is not backed by a password before writing anything.\n const exposure = checkExposure(\n {\n ...current,\n host: patch.control?.host ?? current.host,\n auth: { ...current.auth, enabled: patch.control?.auth?.enabled ?? current.auth.enabled },\n },\n deps.auth.passwordSet,\n deps.auth.usingDefaultPassword,\n )\n if (exposure.blockedReason !== null)\n throw new DetailedError(exposure.blockedReason, { statusCode: 400, code: 'EXPOSURE_BLOCKED' })\n\n // Turning authentication off is also an exposure *through the proxy*: a route with\n // `target: \"panel\"` serves this control panel on a public hostname, and the proxy's\n // own guard cannot see a later settings write. Without this, a panel route written\n // while auth was on stays served after auth is switched off.\n const proxyExposure = checkProxyExposure(\n deps.proxy.config,\n patch.control?.auth?.enabled ?? current.auth.enabled,\n deps.auth.passwordSet,\n deps.auth.usingDefaultPassword,\n )\n if (proxyExposure !== null)\n throw new DetailedError(proxyExposure, { statusCode: 400, code: 'PROXY_EXPOSURE_BLOCKED' })\n\n /*\n * Switching authentication off is the third way a token could end up holding the panel, after\n * clearing the password and restoring `global:secrets` — and it is the cheapest. Measured with\n * nothing but a bearer token: `PATCH {\"control\":{\"auth\":{\"enabled\":false}}}` answered 200, and\n * `/api/state` then answered with no credential at all. So it takes the same bar as those two,\n * which is what makes \"rotate the password to re-secure the panel\" true.\n *\n * Turning it *on* stays open to a token: that only adds protection.\n */\n if (patch.control?.auth?.enabled === false && requestIdentity(c, deps.auth).method !== 'cookie') {\n throw new DetailedError('switching authentication off needs a signed-in session, not an API token — sign in, or run `home-hosted set-password --clear` on the machine', {\n statusCode: 403,\n code: 'SESSION_REQUIRED',\n })\n }\n\n // A schedule scope may only name something this panel can capture.\n //\n // Checked here, where a person is present to be told, rather than at pass time: a scope id\n // outlives the thing it names (a workspace can be deleted), and that must not make the panel\n // refuse a config it wrote itself. What it *must* not do is accept a typo on the way in — an\n // unknown `only` id narrows the archive and an unknown `except` id widens it back over what\n // was meant to be left out, and nobody is watching the pass that does it.\n const scope = patch.backups?.schedule?.scope\n if (scope !== undefined && scope !== null) {\n const unknown = unknownBackupIds(scope.ids, deps.backups.selection().entries)\n if (unknown.length > 0) {\n throw new DetailedError(\n `the automatic backup scope names ${unknown.map(id => `\"${id}\"`).join(', ')}, which this panel cannot capture`,\n { statusCode: 400, code: 'INVALID_SETTINGS' },\n )\n }\n }\n\n const previous = { trustProxy: current.auth.trustProxy, tlsEnabled: current.tls.enabled }\n try {\n if (patch.host !== undefined)\n settings.updateHost(patch.host)\n if (patch.backups !== undefined)\n settings.updateBackups(patch.backups)\n if (patch.control !== undefined)\n settings.updateControl(patch.control)\n }\n catch (error) {\n if (error instanceof ConfigError)\n throw new DetailedError(error.message, { statusCode: 400, code: 'INVALID_SETTINGS' })\n throw error\n }\n\n const next = settings.control\n const endpointChanged = next.host !== deps.controlServer.endpoint.host || next.port !== deps.controlServer.endpoint.port\n const proxyChanged = next.auth.trustProxy !== previous.trustProxy\n const tlsChanged = next.tls.enabled !== previous.tlsEnabled\n let targetUrl: string | null = null\n\n if (endpointChanged || proxyChanged || tlsChanged) {\n // Moving the listener kills the connection serving this very response, so\n // it happens after the response is written. A failure reverts the config\n // and shows up as `restartRequired` in the next state frame.\n const nextProtocol = tlsChanged ? (next.tls.enabled ? 'https' : 'http') : deps.controlServer.endpoint.protocol\n targetUrl = `${nextProtocol}://${displayHost(next.host)}:${next.port}`\n\n afterResponse(async () => {\n const result = endpointChanged\n ? await deps.controlServer.rebind({ host: next.host, port: next.port })\n : await deps.controlServer.restart()\n\n if (result.ok) {\n logger.info(`control panel listening on ${deps.controlServer.endpoint.url}`)\n return\n }\n\n logger.error(`could not move the control panel: ${result.error ?? 'unknown error'}`)\n settings.updateControl({\n host: deps.controlServer.endpoint.host,\n port: deps.controlServer.endpoint.port,\n ...(proxyChanged ? { auth: { trustProxy: previous.trustProxy } } : {}),\n ...(tlsChanged ? { tls: { enabled: previous.tlsEnabled } } : {}),\n })\n }, error => logger.error('control panel move failed', error))\n }\n\n return c.json({\n // `control` describes the listener that is live *right now*; `targetUrl`\n // is where it is about to be, which is what the client should open.\n control: buildControlView(settings, deps.auth, deps.controlServer.endpoint, deps.tls),\n host: settings.host,\n backups: deps.backups.view(),\n ui: deps.ui.status(),\n rebinding: endpointChanged || proxyChanged || tlsChanged,\n targetUrl,\n })\n })\n\n /**\n * Replace the panel's UI with an uploaded static build. The archive is validated\n * and staged before it is swapped in, so a bad upload changes nothing.\n */\n .post('/settings/ui', describeRoute({\n tags: ['panel'],\n summary: 'Replace the panel UI with an uploaded static build',\n responses: { 200: { description: 'Installed', content: jsonBody(uiInstallResponseSchema) }, 400: ERROR_RESPONSES[400], 413: ERROR_RESPONSES[413] },\n }),\n /**\n * Bound the body **while it arrives**, not after. The checks below read `Content-Length`, which a\n * chunked request does not send, and compare `file.size` only after `parseBody()` has buffered\n * everything — so an upload with no declared length was read into memory in full and then refused.\n * See the same reasoning in `api/backups.ts`.\n */\n bodyLimit({\n maxSize: MAX_UI_UPLOAD_BYTES,\n onError: () => {\n throw new DetailedError(`the upload is larger than ${Math.round(MAX_UI_UPLOAD_BYTES / 1024 / 1024)}MB`, { statusCode: 413, code: 'UPLOAD_TOO_LARGE' })\n },\n }), async (c) => {\n // Pre-flight only; `file.size` below is the authoritative check for a *declared* length.\n // `parseInt` is safe because Node's HTTP parser rejects a non-decimal `Content-Length` with a\n // 400 before any handler runs — see the same note in `api/backups.ts`.\n const declared = Number.parseInt(c.req.header('content-length') ?? '0', 10)\n if (Number.isFinite(declared) && declared > MAX_UI_UPLOAD_BYTES)\n throw new DetailedError(`the upload is larger than ${Math.round(MAX_UI_UPLOAD_BYTES / 1024 / 1024)}MB`, { statusCode: 413, code: 'UPLOAD_TOO_LARGE' })\n\n const body = await c.req.parseBody()\n const file = body.file\n if (!(file instanceof File))\n throw new DetailedError('expected a `file` field with the UI archive', { statusCode: 400, code: 'MISSING_FILE' })\n if (file.size > MAX_UI_UPLOAD_BYTES)\n throw new DetailedError(`the upload is larger than ${Math.round(MAX_UI_UPLOAD_BYTES / 1024 / 1024)}MB`, { statusCode: 413, code: 'UPLOAD_TOO_LARGE' })\n\n const staging = path.join(path.dirname(deps.ui.directory), `.ui-upload-${Date.now()}.zip`)\n try {\n await fs.promises.writeFile(staging, Buffer.from(await file.arrayBuffer()))\n const result = await deps.ui.install(staging, sanitizeName(file.name))\n if (!result.ok)\n throw new DetailedError(result.error, { statusCode: 400, code: 'INVALID_UI' })\n\n logger.info(`UI replaced with ${result.meta.name} (${result.meta.files} files)`)\n return c.json({ ok: true, meta: result.meta, ui: deps.ui.status() })\n }\n finally {\n fs.rmSync(staging, { force: true })\n }\n })\n\n /** Back to the stock UI. */\n .delete('/settings/ui', describeRoute({\n tags: ['panel'],\n summary: 'Go back to the stock UI',\n responses: { 200: { description: 'Reverted', content: jsonBody(uiInstallResponseSchema) } },\n }), (c) => {\n const removed = deps.ui.revert()\n logger.info(removed ? 'custom UI removed — the stock panel is back' : 'no custom UI was installed')\n return c.json({ ok: true, removed, ui: deps.ui.status() })\n })\n\n .get(\n '/settings/workspace',\n describeRoute({\n tags: ['panel'],\n summary: 'One workspace\\'s own settings: server defaults, logs and notifications',\n responses: { 200: { description: 'The workspace settings', content: jsonBody(workspaceSettingsViewSchema) } },\n }),\n validate('query', workspaceQuerySchema),\n (c) => {\n const runtime = requireWorkspace(deps.panel.requireWorkspace.bind(deps.panel), c.req.valid('query').workspace)\n return c.json(buildWorkspaceSettings(runtime))\n },\n )\n\n .patch(\n '/settings/workspace',\n describeRoute({\n tags: ['panel'],\n summary: 'Edit one workspace\\'s server defaults, logs and notifications',\n responses: { 200: { description: 'Saved', content: jsonBody(workspaceSettingsSavedSchema) }, 400: ERROR_RESPONSES[400] },\n }),\n validate('query', workspaceQuerySchema),\n validate('json', workspaceSettingsPatchSchema),\n (c) => {\n const runtime = requireWorkspace(deps.panel.requireWorkspace.bind(deps.panel), c.req.valid('query').workspace)\n const patch = c.req.valid('json')\n try {\n if (patch.defaults !== undefined)\n runtime.store.updateDefaults(patch.defaults)\n if (patch.logs !== undefined) {\n runtime.store.updateLogs(patch.logs)\n // `keep` bounds the directory, not the next rotation: a quiet entry can go days\n // without filling a file, and \"I lowered it\" must not mean \"eventually\".\n runtime.logFiles.prune()\n }\n if (patch.notifications !== undefined) {\n const saved = runtime.store.updateNotifications(patch.notifications)\n // A removed destination must not leave its bot token behind: the id keys the secret, so\n // a later destination reusing that id would silently inherit another bot's token.\n runtime.secrets.forgetTelegramTokens(saved.destinations.map(destination => destination.id))\n }\n }\n catch (error) {\n if (error instanceof ConfigError)\n throw new DetailedError(error.message, { statusCode: 400, code: 'INVALID_SETTINGS' })\n throw error\n }\n\n return c.json(buildWorkspaceSettings(runtime))\n },\n )\n}\n","import type { AppDeps } from '#src/app'\nimport { describeRoute } from 'hono-openapi'\nimport { appFactory } from '#src/helpers/factory'\nimport { jsonBody } from '#src/helpers/openapi'\nimport { appStateSchema } from '#src/shared/contracts'\n\n/** The whole panel in one payload: config, live server state and host vitals. */\nexport function createStateRoute(deps: AppDeps) {\n return appFactory.createApp()\n .get(\n '/state',\n describeRoute({\n tags: ['panel'],\n summary: 'Full snapshot of the panel',\n responses: { 200: { description: 'The snapshot', content: jsonBody(appStateSchema) } },\n }),\n c => c.json(deps.panel.getState()),\n )\n}\n","import type { Context } from 'hono'\nimport fs from 'node:fs'\nimport path from 'node:path'\nimport { Hono } from 'hono'\n\nconst CONTENT_TYPES: Record<string, string> = {\n '.html': 'text/html; charset=utf-8',\n '.js': 'text/javascript; charset=utf-8',\n '.mjs': 'text/javascript; charset=utf-8',\n '.css': 'text/css; charset=utf-8',\n '.json': 'application/json; charset=utf-8',\n '.map': 'application/json; charset=utf-8',\n '.svg': 'image/svg+xml',\n '.png': 'image/png',\n '.jpg': 'image/jpeg',\n '.jpeg': 'image/jpeg',\n '.gif': 'image/gif',\n '.webp': 'image/webp',\n '.ico': 'image/x-icon',\n '.woff': 'font/woff',\n '.woff2': 'font/woff2',\n '.ttf': 'font/ttf',\n '.txt': 'text/plain; charset=utf-8',\n}\n\nexport interface StaticRouteOptions {\n /** Resolved per request, so a UI installed at runtime takes effect on refresh. */\n dir: string | (() => string)\n entry?: string\n}\n\n/**\n * Serves the built control UI and falls back to `index.html` for client routes,\n * so a deep URL like `/servers/static` works after a refresh.\n */\nexport function createStaticRoute(options: StaticRouteOptions): Hono {\n const route = new Hono()\n const entry = options.entry ?? 'index.html'\n const currentRoot = (): string => path.resolve(typeof options.dir === 'function' ? options.dir() : options.dir)\n\n route.get('*', async (c) => {\n const root = currentRoot()\n const pathname = safeDecode(new URL(c.req.url).pathname)\n if (pathname === null)\n return c.text('bad path', 400)\n\n // A path under `/api` that reached this catch-all matched no route, so it is a client\n // mistake — never a UI route. Falling through to `index.html` answered a typo'd API call\n // with `200 text/html`, which `curl --fail` and a `.json()` parse both treat as success.\n if (isApiPath(pathname))\n return c.json({ message: `no route for ${c.req.method} ${pathname}`, code: 'NOT_FOUND' }, 404)\n\n const file = resolveWithin(root, pathname)\n if (file !== null) {\n const response = await serveFile(c, file, pathname)\n if (response !== null)\n return response\n }\n\n const indexFile = path.join(root, entry)\n if (fs.existsSync(indexFile)) {\n const response = await serveFile(c, indexFile, '/')\n if (response !== null)\n return response\n }\n\n return c.text('no UI is installed — build one and upload it under Settings → Interface', 503)\n })\n\n return route\n}\n\n/** `/api` itself and everything under it is the JSON surface, never a UI route. */\nfunction isApiPath(pathname: string): boolean {\n return pathname === '/api' || pathname.startsWith('/api/')\n}\n\nfunction safeDecode(value: string): string | null {\n try {\n return decodeURIComponent(value)\n }\n catch {\n return null\n }\n}\n\nfunction resolveWithin(root: string, pathname: string): string | null {\n const resolved = path.resolve(root, `.${pathname}`)\n if (resolved !== root && !resolved.startsWith(`${root}${path.sep}`))\n return null\n return resolved\n}\n\nasync function serveFile(c: Context, file: string, pathname: string): Promise<Response | null> {\n let stats: fs.Stats\n try {\n stats = await fs.promises.stat(file)\n }\n catch {\n return null\n }\n if (!stats.isFile())\n return null\n\n const body = await fs.promises.readFile(file)\n const ext = path.extname(file).toLowerCase()\n const immutable = pathname.startsWith('/assets/')\n const payload = body.buffer.slice(body.byteOffset, body.byteOffset + body.byteLength) as ArrayBuffer\n\n return c.body(payload, 200, {\n 'Content-Type': CONTENT_TYPES[ext] ?? 'application/octet-stream',\n 'Content-Length': String(stats.size),\n 'Cache-Control': immutable ? 'public, max-age=31536000, immutable' : 'no-cache',\n })\n}\n","import type { AppDeps } from '#src/app'\nimport { DetailedError } from '@namesmt/utils'\nimport { describeRoute } from 'hono-openapi'\nimport { afterResponse } from '#src/helpers/deferred'\nimport { appFactory } from '#src/helpers/factory'\nimport { logger } from '#src/helpers/logger'\nimport { ERROR_RESPONSES, jsonBody } from '#src/helpers/openapi'\nimport { validate } from '#src/helpers/validator'\nimport { buildControlView } from '#src/services/state'\nimport { tlsReviewResponseSchema, tlsUploadSchema } from '#src/shared/contracts'\n\n/**\n * Uploads the PEM pair used for https on the control panel.\n *\n * When TLS is already enabled the listener has to be rebuilt with the new pair,\n * which kills the connection serving this request — so the swap is deferred, and\n * the response tells the client where the panel will be.\n */\nexport function createTlsRoute(deps: AppDeps) {\n const review = () => ({\n control: buildControlView(deps.panel.settings, deps.auth, deps.controlServer.endpoint, deps.tls),\n rebinding: deps.panel.settings.control.tls.enabled,\n targetUrl: deps.controlServer.endpoint.url,\n })\n\n return appFactory.createApp()\n .post(\n '/settings/tls',\n describeRoute({\n tags: ['tls'],\n summary: 'Upload the certificate and key the panel should serve',\n responses: { 200: { description: 'Stored; the panel may be moving to https', content: jsonBody(tlsReviewResponseSchema) }, 400: ERROR_RESPONSES[400] },\n }),\n validate('json', tlsUploadSchema),\n (c) => {\n const body = c.req.valid('json')\n const saved = deps.tls.save(body.certificate, body.privateKey)\n if (!saved.ok)\n throw new DetailedError(saved.error ?? 'the certificate pair was rejected', { statusCode: 400, code: 'INVALID_CERTIFICATE' })\n\n if (deps.panel.settings.control.tls.enabled) {\n afterResponse(async () => {\n const result = await deps.controlServer.restart()\n if (!result.ok)\n logger.error(`could not reload TLS: ${result.error ?? 'unknown error'}`)\n else logger.info(`control panel listening on ${deps.controlServer.endpoint.url} (https)`)\n }, error => logger.error('tls reload failed', error))\n }\n\n return c.json(review())\n },\n )\n\n .delete(\n '/settings/tls',\n describeRoute({\n tags: ['tls'],\n summary: 'Remove the certificate pair',\n responses: { 200: { description: 'Removed', content: jsonBody(tlsReviewResponseSchema) } },\n }),\n (c) => {\n deps.tls.clear()\n if (deps.panel.settings.control.tls.enabled) {\n afterResponse(async () => {\n // The result is checked, as on the POST above: `restart()` closes the listener first, so a\n // failed bind leaves the panel listening **nowhere** — and discarding this made that\n // completely silent, with the panel still reporting a certificate that is no longer on disk.\n const result = await deps.controlServer.restart()\n if (!result.ok)\n logger.error(`could not reload TLS after removing the pair: ${result.error ?? 'unknown error'}`)\n // Not `endpoint.url`: it is computed once in the constructor, so it still says whatever the\n // protocol was at boot. What the listener actually serves is `tls.enabled && servable()`.\n else logger.info(`control panel reloaded — ${deps.panel.settings.control.tls.enabled && deps.tls.servable() !== null ? 'https' : 'http'}`)\n }, error => logger.error('tls reload failed', error))\n }\n return c.json(review())\n },\n )\n}\n","import type { AppDeps } from '#src/app'\nimport { DetailedError } from '@namesmt/utils'\nimport { type } from 'arktype'\nimport { describeRoute } from 'hono-openapi'\nimport { WorkspaceError } from '#src/config/workspaces'\nimport { appFactory } from '#src/helpers/factory'\nimport { ERROR_RESPONSES, jsonBody } from '#src/helpers/openapi'\nimport { validate } from '#src/helpers/validator'\nimport { workspaceCreateSchema, workspaceRenameSchema, workspaceViewSchema } from '#src/shared/contracts'\n\nconst idParam = type({ id: 'string >= 1' })\nconst workspacesResponse = type({ workspaces: workspaceViewSchema.array() })\nconst workspaceResponse = type({ workspace: workspaceViewSchema })\nconst removedResponse = type({ ok: 'boolean', removed: type({ id: 'string', label: 'string' }) })\n\n/** A registry failure is an API failure: unknown ids are 404, conflicts 409, the rest 400. */\nfunction workspaceFailure(error: unknown): never {\n if (error instanceof WorkspaceError) {\n // The exception carries the kind. Matching the message would misroute a *validation* failure\n // whose summary happened to begin `unknown workspace` or end `already exists`.\n const unknown = error.code === 'UNKNOWN_WORKSPACE'\n const conflict = error.code === 'WORKSPACE_EXISTS'\n throw new DetailedError(error.message, {\n statusCode: unknown ? 404 : conflict ? 409 : 400,\n code: unknown ? 'UNKNOWN_WORKSPACE' : conflict ? 'WORKSPACE_EXISTS' : 'INVALID_WORKSPACE',\n })\n }\n throw error\n}\n\n/** A workspace selector needs the list, and the CRUD behind it. */\nexport function createWorkspacesRoute(deps: AppDeps) {\n return appFactory.createApp()\n .get(\n '/',\n describeRoute({\n tags: ['workspaces'],\n summary: 'Every workspace, with its live state',\n responses: { 200: { description: 'The workspaces', content: jsonBody(workspacesResponse) } },\n }),\n c => c.json({ workspaces: deps.panel.workspaces().map(workspace => workspace.view()) }),\n )\n\n .post(\n '/',\n describeRoute({\n tags: ['workspaces'],\n summary: 'Create a workspace',\n responses: {\n 201: { description: 'Created', content: jsonBody(workspaceResponse) },\n 400: ERROR_RESPONSES[400],\n },\n }),\n validate('json', workspaceCreateSchema),\n (c) => {\n try {\n return c.json({ workspace: deps.panel.create(c.req.valid('json')) }, 201)\n }\n catch (error) {\n workspaceFailure(error)\n }\n },\n )\n\n .patch(\n '/:id',\n describeRoute({\n tags: ['workspaces'],\n summary: 'Rename a workspace',\n responses: {\n 200: { description: 'Renamed', content: jsonBody(workspaceResponse) },\n 400: ERROR_RESPONSES[400],\n 404: ERROR_RESPONSES[404],\n },\n }),\n validate('param', idParam),\n validate('json', workspaceRenameSchema),\n (c) => {\n try {\n return c.json({ workspace: deps.panel.rename(c.req.valid('param').id, c.req.valid('json').label) })\n }\n catch (error) {\n workspaceFailure(error)\n }\n },\n )\n\n .delete(\n '/:id',\n describeRoute({\n tags: ['workspaces'],\n summary: 'Stop and remove a workspace',\n responses: {\n 200: { description: 'Removed', content: jsonBody(removedResponse) },\n 400: ERROR_RESPONSES[400],\n 404: ERROR_RESPONSES[404],\n },\n }),\n validate('param', idParam),\n async (c) => {\n try {\n const removed = await deps.panel.remove(c.req.valid('param').id)\n return c.json({ ok: true, removed: { id: removed.id, label: removed.label } })\n }\n catch (error) {\n workspaceFailure(error)\n }\n },\n )\n}\n","import type { AppDeps } from '#src/app'\nimport type { WslTemperatureStatus } from '#src/shared/contracts'\nimport { DetailedError } from '@namesmt/utils'\nimport { type } from 'arktype'\nimport { describeRoute } from 'hono-openapi'\nimport { appFactory } from '#src/helpers/factory'\nimport { ERROR_RESPONSES, jsonBody } from '#src/helpers/openapi'\nimport { validate } from '#src/helpers/validator'\nimport { installLibreHardwareMonitor, lhmInstalled, probeWslTemperature, removeWslTemperatureScript, tempCommandFor, writeWslTemperatureScript, wslScriptPath, wslTemperatureStatus } from '#src/providers/wsl-temperature'\nimport { wslTemperatureSchema } from '#src/shared/contracts'\n\n/**\n * The helper's location, or null when the Windows drive is not mounted.\n *\n * It lives on the *Windows* side: `powershell.exe` cannot read the guest's Linux home, so a script\n * written there is invisible to it.\n */\nfunction scriptPath(): string | null {\n return wslScriptPath()\n}\n\nfunction status(deps: AppDeps): WslTemperatureStatus {\n return wslTemperatureStatus(scriptPath(), deps.panel.settings.host.tempCommand)\n}\n\n/**\n * The WSL2 temperature bridge, over the panel's own settings.\n *\n * Panel-wide (a temperature is the machine's, not a workspace's), and deliberately three small\n * routes rather than one: read the state, install it, test it. Installing writes a file and changes\n * a setting, so it is the one that can fail and has to say why.\n */\nexport function createWslTemperatureRoute(deps: AppDeps) {\n return appFactory.createApp()\n .get(\n '/host/temperature',\n describeRoute({\n tags: ['panel'],\n summary: 'Whether the WSL temperature bridge is set up, and what it last read',\n responses: { 200: { description: 'The bridge state', content: jsonBody(wslTemperatureSchema) } },\n }),\n async (c) => {\n const current = status(deps)\n // Probe only when the command is configured, so the page can show a live reading — a setup\n // that was never saved must not spawn a PowerShell on every page load.\n if (!current.configured)\n return c.json(current)\n const probe = await probeWslTemperature(deps.panel.settings.host.tempCommand, deps.panel.settings.host.tempCommandTimeoutMs)\n return c.json({ ...current, lastReadingCelsius: probe.celsius, lastError: probe.error })\n },\n )\n\n .post(\n '/host/temperature',\n describeRoute({\n tags: ['panel'],\n summary: 'Write the WSL helper script and point the temperature command at it',\n responses: { 200: { description: 'Set up', content: jsonBody(wslTemperatureSchema) }, 400: ERROR_RESPONSES[400] },\n }),\n validate('query', type({ 'download?': '\"true\" | \"false\"' }).onUndeclaredKey('reject')),\n async (c) => {\n const current = status(deps)\n if (!current.supported) {\n throw new DetailedError('this is not a WSL2 guest, so there is no host sensor to bridge to', {\n statusCode: 400,\n code: 'NOT_WSL',\n })\n }\n const target = scriptPath()\n if (target === null)\n throw new DetailedError('the Windows drive is not mounted at /mnt/c, so the helper cannot be written where powershell.exe can read it', { statusCode: 400, code: 'WINDOWS_DRIVE_MISSING' })\n try {\n writeWslTemperatureScript(target)\n }\n catch (error) {\n throw new DetailedError(`the helper could not be written to ${target}: ${error instanceof Error ? error.message : String(error)}`, {\n statusCode: 400,\n code: 'SCRIPT_WRITE_FAILED',\n })\n }\n\n // The helper only prints a number; the sensor comes from a third-party Windows binary the\n // panel does not ship. The first press says so and asks; a second press carries\n // `?download=true` and installs it. Never on the same click that did not mention a download.\n if (!lhmInstalled()) {\n if (c.req.valid('query').download !== 'true')\n return c.json({ ...status(deps), needsDownload: true })\n const install = await installLibreHardwareMonitor()\n if (install.error !== null)\n throw new DetailedError(`LibreHardwareMonitor could not be installed: ${install.error}`, { statusCode: 400, code: 'LIBRARY_INSTALL_FAILED' })\n }\n // The command is what the panel will run; saving it here is the whole point, so the person\n // does not have to copy a path out of a log.\n const command = tempCommandFor(target)\n // Probe **before** saving: a command that cannot work must not reach the config, or the panel\n // runs a failing PowerShell every sample while the page says a source is configured. The\n // helper file stays on disk — it is what the person re-runs after installing the library.\n const probe = await probeWslTemperature(command, 5000)\n if (probe.celsius === null) {\n return c.json({\n ...status(deps),\n lastReadingCelsius: null,\n lastError: probe.error ?? 'the helper did not answer',\n })\n }\n deps.panel.settings.updateHost({ tempCommand: command, tempCommandTimeoutMs: 5000 })\n return c.json({ ...status(deps), lastReadingCelsius: probe.celsius, lastError: null })\n },\n )\n\n .delete(\n '/host/temperature',\n describeRoute({\n tags: ['panel'],\n summary: 'Stop using the helper and delete it',\n responses: { 200: { description: 'Cleared', content: jsonBody(wslTemperatureSchema) }, 400: ERROR_RESPONSES[400] },\n }),\n async (c) => {\n deps.panel.settings.updateHost({ tempCommand: '' })\n removeWslTemperatureScript(scriptPath())\n return c.json(status(deps))\n },\n )\n}\n","import type { DetailedError } from '@namesmt/utils'\nimport type { ErrorHandler as HonoErrorHandler } from 'hono'\nimport type { ContentfulStatusCode } from 'hono/utils/http-status'\nimport { HTTPException } from 'hono/http-exception'\nimport { logger } from '#src/helpers/logger'\n\n/**\n * The one error envelope this API speaks:\n *\n * ```json\n * { \"message\": \"human readable\", \"code\": \"MACHINE_READABLE\", \"detail\": … }\n * ```\n *\n * `@namesmt/utils`' `DetailedError` is the preferred way to fail — it carries the\n * status, a stable code and structured detail — so a client (and the OpenAPI\n * schema) can rely on the shape.\n */\nexport interface ApiErrorBody {\n message: string\n code: string\n detail?: unknown\n}\n\nexport const errorHandler: HonoErrorHandler = (error, c) => {\n const body = toErrorBody(error)\n const status = statusOf(error)\n\n if (status >= 500)\n logger.error(`${c.req.method} ${new URL(c.req.url).pathname} failed:`, error)\n else\n logger.debug(`${c.req.method} ${new URL(c.req.url).pathname} → ${status} ${body.message}`)\n\n return c.json(body, status)\n}\n\nfunction toErrorBody(error: unknown): ApiErrorBody {\n if (error instanceof HTTPException)\n return { message: error.message, code: 'HTTP_EXCEPTION' }\n\n // `DetailedError` can come from this code or from Hono's own parsing helpers,\n // so a name check is safer than `instanceof` across module instances.\n if (isDetailedError(error)) {\n return {\n message: error.message,\n code: error.code ?? 'DETAILED_ERROR',\n ...(error.detail === undefined ? {} : { detail: error.detail }),\n }\n }\n\n if (error instanceof Error)\n return { message: error.message, code: error.name === 'Error' ? 'INTERNAL_ERROR' : error.name.toUpperCase() }\n\n return { message: String(error), code: 'INTERNAL_ERROR' }\n}\n\nfunction isDetailedError(error: unknown): error is DetailedError {\n return error instanceof Error && error.name === 'DetailedError' && 'statusCode' in error\n}\n\nfunction statusOf(error: unknown): ContentfulStatusCode {\n const candidate = (error as { statusCode?: unknown, status?: unknown })?.statusCode ?? (error as { status?: unknown })?.status\n const status = typeof candidate === 'number' ? candidate : 500\n return status >= 400 && status <= 599 ? (status as ContentfulStatusCode) : 500\n}\n","import type { Context, MiddlewareHandler } from 'hono'\nimport { isIP } from 'node:net'\nimport { DetailedError } from '@namesmt/utils'\nimport { isPublicHost } from '#src/shared/proxy-form'\n\n/**\n * The authority a request named, from either protocol.\n *\n * HTTP/2 carries no `Host` header — the name arrives as the `:authority` pseudo-header, which srvx\n * keeps on the underlying node request and filters out of the header bag. Reading only `host` left\n * the guard blind on every TLS listener, so a rebound name reached the app unchecked.\n *\n * Deliberately **not** `new URL(c.req.url).host`: with `trustProxy: 'loopback'` srvx builds that\n * from `X-Forwarded-Host`, which a rebound page sets freely (it is same-origin with the panel, so no\n * preflight stops it) — using it would hand the attacker back the field being checked.\n */\nexport function requestAuthority(c: Context): string | undefined {\n const host = c.req.header('host')\n if (host !== undefined)\n return host\n const node = (c.req.raw as { runtime?: { node?: { req?: { headers?: Record<string, unknown> } } } }).runtime?.node?.req\n const authority = node?.headers?.[':authority']\n if (typeof authority === 'string')\n return authority\n /**\n * No header and no pseudo-header: take the authority the request was *addressed* with.\n *\n * Only reachable off a real listener in tests (`app.request('/path')` sets neither), because\n * HTTP/1.1 requires `Host` and HTTP/2 requires `:authority`. `c.req.url` is used rather than\n * `requestAuthority`'s caller because srvx derives it from `X-Forwarded-Host` when it trusts the\n * peer — so it is consulted only after both real fields are known to be absent, and a request that\n * spoofs that header still cannot use it to *pass* (the value it names is judged like any other).\n */\n try {\n return new URL(c.req.url).host\n }\n catch {\n return undefined\n }\n}\n\n/** The hostname part of a `Host` header: port and IPv6 brackets dropped, lowercased. */\nexport function hostnameOf(header: string): string {\n let value = header.trim().toLowerCase()\n if (value.startsWith('[')) {\n const end = value.indexOf(']')\n return value.slice(1, end === -1 ? undefined : end)\n }\n const colon = value.lastIndexOf(':')\n // A bare IPv6 literal has several colons and no port.\n if (colon !== -1 && value.indexOf(':') === colon)\n value = value.slice(0, colon)\n return value.replace(/\\.$/, '')\n}\n\nfunction matches(hostname: string, pattern: string): boolean {\n const rule = pattern.trim().toLowerCase().replace(/\\.$/, '')\n if (rule.startsWith('*.'))\n return hostname.endsWith(rule.slice(1)) && hostname.length > rule.length - 1\n return hostname === rule\n}\n\n/**\n * Whether a request's `Host` names this panel rather than an attacker's domain.\n *\n * DNS rebinding points a public name at 127.0.0.1, which makes the attacker's page same-origin with\n * the panel — the `Origin` check cannot see it. An IP literal or a name no public DNS can answer\n * (`localhost`, a single label, `.local`, `.lan`, …) cannot be rebound by a remote site, so those are\n * always allowed; a public name must be one the person declared or a proxy route serving the panel.\n *\n * A request that names no host at all is **refused**: HTTP/1.1 requires `Host`, so its absence means\n * the caller reached us through a channel this guard cannot inspect — and answering `true` there is\n * what turned \"no `Host` over HTTP/2\" into an open door rather than a closed one.\n */\nexport function isAllowedHost(header: string | undefined, allowed: Iterable<string>): boolean {\n if (header === undefined || header.trim() === '')\n return false\n const hostname = hostnameOf(header)\n if (isIP(hostname) !== 0 || !isPublicHost(hostname))\n return true\n for (const pattern of allowed) {\n if (matches(hostname, pattern))\n return true\n }\n return false\n}\n\nexport function createHostGuard(allowed: () => Iterable<string>): MiddlewareHandler {\n return async (c, next) => {\n const authority = requestAuthority(c)\n if (!isAllowedHost(authority, allowed())) {\n const named = authority === undefined || authority.trim() === '' ? 'no host' : `host \"${hostnameOf(authority)}\"`\n throw new DetailedError(`${named} is not allowed — add it to control.allowedHosts in the panel's settings.json (or reach the panel by IP and add it under Global settings → Listener)`, {\n statusCode: 421,\n code: 'HOST_NOT_ALLOWED',\n })\n }\n await next()\n }\n}\n","/**\n * The browsable API reference at `/openapi/ui`.\n *\n * It used to be `Scalar()`, whose HTML is a `<script type=\"module\">` importing the reference from\n * `cdn.jsdelivr.net` and nothing else — so with no route to the internet `#app` held 0 children and 0\n * characters. Measured in Chromium with every non-panel request aborted; the same page made 30 off-origin\n * requests and pulled a 754 KB bundle when it could reach them.\n *\n * Scalar itself is not the limitation: its standalone bundle renders fine offline when it is served\n * alongside the panel. It weighs 4.9 MB, and `docs/UI_CREATION.md` point 5 says an offline home server\n * should not need a CDN, so shipping that to every install is a worse trade than rendering the route\n * index from `/openapi/spec.json` — grouped by tag, every operation with its method, path and summary —\n * and offering the interactive browser to whoever can reach it. The index is what renders first and\n * stays if the import fails, so the page is never blank.\n *\n * The spec stays the single source of truth; this file only formats what the routes already declare.\n */\n\n/**\n * The Scalar release the optional enhancement loads, pinned so an upstream release cannot change this\n * page without a commit here. Bump it deliberately and re-check `/openapi/ui` with the network on.\n */\nconst SCALAR_VERSION = '1.76.0'\n\n/**\n * Deliberately a string, not a `.vue` or a template dependency: this route is outside `/api` and outside\n * both UIs, and `src/**` may not know a UI's files.\n */\nexport function openApiReferencePage(specUrl: string): string {\n return `<!doctype html>\n<html lang=\"en\">\n <head>\n <meta charset=\"utf-8\" />\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\" />\n <title>home-hosted — API reference</title>\n <style>\n :root { color-scheme: light dark; --line: #d8dee9; --ink: #14202e; --muted: #5b6b80; --page: #fbfcfe; --code: #eef2f8; }\n @media (prefers-color-scheme: dark) { :root { --line: #263243; --ink: #e6edf7; --muted: #9fb0c6; --page: #0d131c; --code: #16202c; } }\n * { box-sizing: border-box; }\n body { margin: 0; padding: 2rem 1.25rem 4rem; background: var(--page); color: var(--ink);\n font: 15px/1.55 ui-sans-serif, system-ui, -apple-system, \"Segoe UI\", Roboto, sans-serif; }\n main { max-width: 60rem; margin: 0 auto; }\n h1 { font-size: 1.35rem; margin: 0 0 .35rem; letter-spacing: -.01em; }\n p.lede { margin: 0 0 1.75rem; color: var(--muted); }\n a { color: inherit; }\n h2 { font-size: .8rem; text-transform: uppercase; letter-spacing: .07em; color: var(--muted);\n margin: 2rem 0 .6rem; }\n ul { list-style: none; margin: 0; padding: 0; }\n li { display: grid; grid-template-columns: 4.6rem 1fr; gap: .75rem; align-items: baseline;\n padding: .55rem .7rem; border: 1px solid var(--line); border-radius: .5rem; margin-bottom: .4rem; }\n .m { font: 600 .72rem/1 ui-monospace, SFMono-Regular, Menlo, monospace; letter-spacing: .04em;\n padding: .3rem .4rem; border-radius: .3rem; text-align: center; background: var(--code); }\n .m[data-m=\"GET\"] { color: #0a7d52; } .m[data-m=\"POST\"] { color: #1f5fd0; }\n .m[data-m=\"PUT\"], .m[data-m=\"PATCH\"] { color: #8a5b00; } .m[data-m=\"DELETE\"] { color: #b32020; }\n code { font-family: ui-monospace, SFMono-Regular, Menlo, monospace; font-size: .86rem; }\n .summary { color: var(--muted); font-size: .87rem; }\n .error { padding: 1rem; border: 1px solid var(--line); border-radius: .5rem; color: var(--muted); }\n footer { margin-top: 2.5rem; padding-top: 1rem; border-top: 1px solid var(--line);\n color: var(--muted); font-size: .85rem; }\n @media (max-width: 30rem) { li { grid-template-columns: 4rem 1fr; } body { padding: 1.25rem 1rem 3rem; } }\n </style>\n </head>\n <body>\n <main>\n <h1>home-hosted API</h1>\n <p class=\"lede\">Every route the panel serves, generated from the same schemas the routes validate\n with. Send <code>Authorization: Bearer hh_…</code> with any call; a cookie session works too.</p>\n <div id=\"app\" data-fallback=\"index\"><p class=\"error\">Loading the route index…</p></div>\n <footer>\n <a href=\"${specUrl}\">${specUrl}</a> — the OpenAPI document, for\n <code>openapi-typescript</code>, <code>openapi-generator</code> or any other client.\n </footer>\n </main>\n <script type=\"module\">\n const specUrl = ${JSON.stringify(specUrl)}\n const app = document.getElementById('app')\n\n /**\n * The index, from the spec, with nothing but \\`fetch\\`. This is the page's real content: it is what a\n * person on an air-gapped box sees, and what the browser below replaces only if the CDN answers.\n */\n async function renderIndex() {\n let spec\n try {\n const response = await fetch(specUrl, { headers: { accept: 'application/json' } })\n if (!response.ok) throw new Error(String(response.status))\n spec = await response.json()\n } catch (error) {\n app.dataset.fallback = 'error'\n app.innerHTML = '<p class=\"error\">The OpenAPI document could not be read (' +\n String(error && error.message ? error.message : error) + ').</p>'\n return\n }\n\n const tags = (spec.tags || []).map(tag => tag.name)\n const groups = new Map(tags.map(name => [name, []]))\n for (const [path, operations] of Object.entries(spec.paths || {})) {\n for (const [method, operation] of Object.entries(operations || {})) {\n const name = (operation.tags && operation.tags[0]) || 'other'\n if (!groups.has(name)) groups.set(name, [])\n groups.get(name).push({ path, method: method.toUpperCase(), summary: operation.summary || '' })\n }\n }\n\n let html = ''\n for (const [tag, rows] of groups) {\n if (rows.length === 0) continue\n html += '<h2>' + escapeHtml(tag) + '</h2><ul>'\n for (const row of rows.sort((a, b) => a.path.localeCompare(b.path) || a.method.localeCompare(b.method)))\n html += '<li><span class=\"m\" data-m=\"' + row.method + '\">' + row.method + '</span><span><code>' +\n escapeHtml(row.path) + '</code><br><span class=\"summary\">' + escapeHtml(row.summary) + '</span></span></li>'\n html += '</ul>'\n }\n app.dataset.fallback = 'rendered'\n app.innerHTML = html || '<p class=\"error\">The OpenAPI document lists no operations.</p>'\n }\n\n function escapeHtml(value) {\n return String(value).replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;')\n .replace(/\"/g, '&quot;')\n }\n\n await renderIndex()\n\n /**\n * Optional enhancement: the interactive reference, which lives on a CDN. It is allowed to fail —\n * that is the whole point of rendering the index first — so a LAN box with no internet keeps a\n * usable page instead of a blank one.\n *\n * The version is pinned: this is an enhancement fetched from a third party at page load, and a\n * floating major would let an upstream release break or restyle the panel's page with no change\n * here. The index above is unaffected either way.\n */\n try {\n const { createApiReference } = await import('https://cdn.jsdelivr.net/npm/@scalar/api-reference@${SCALAR_VERSION}/esm.js')\n app.innerHTML = ''\n app.dataset.fallback = 'enhanced'\n createApiReference('#app', { _integration: 'hono', url: specUrl, theme: 'deepSpace' })\n } catch {\n // No CDN: the index above stays, and that is a supported outcome.\n }\n </script>\n </body>\n</html>`\n}\n","import { generateSpecs } from 'hono-openapi'\nimport { appFactory } from '#src/helpers/factory'\nimport { ERROR_RESPONSES } from '#src/helpers/openapi'\nimport { appVersion } from '#src/helpers/version'\nimport { openApiReferencePage } from '#src/openapi-reference'\n\nconst PREFIX = '/openapi'\n\n/**\n * The machine-readable contract, generated from the same ArkType schemas the\n * routes validate with — one source of truth, no second set of DTOs to drift.\n * `/openapi/ui` is the browsable reference and needs no session, since a UI\n * author has to be able to read it before they can log in.\n */\n/** The version the package was built with, so the spec never drifts from it. */\nexport function setupOpenAPI(app: Parameters<typeof generateSpecs>[0]) {\n let spec: Record<string, unknown> | undefined\n return appFactory.createApp()\n .get(\n `${PREFIX}/spec.json`,\n async (c) => {\n spec ??= finishSpec(await generateSpecs(app, {\n /**\n * The `400` every validated route gets, written as this server's own envelope.\n *\n * hono-openapi injects its own default on any operation that has a validator and does not\n * name a `400`: `{ success: false, error: [], data }`. This API has never sent that shape —\n * `src/helpers/error.ts` maps every failure through one `DetailedError` envelope,\n * `{ message, code, detail }`, which is what AGENTS.md promises and what a client parses.\n * Measured on 29 operations: `GET /api/servers`, `POST /api/servers/{id}/start`, every\n * `/_hh` lifecycle route, `GET /api/logs/{id}`. The document described a body no successful\n * client would ever see, and every generated client was typed against it.\n *\n * Spelled as a resolved JSON schema rather than `ERROR_RESPONSES[400]`: this option takes\n * an OpenAPI response object, not a Standard Schema, and `apiErrorSchema` is what that\n * envelope is defined by (`test/api/panel.test.ts` pins the two together).\n */\n defaultValidationErrorResponse: {\n description: ERROR_RESPONSES[400].description,\n content: {\n 'application/json': {\n schema: {\n type: 'object',\n properties: {\n message: { type: 'string' },\n code: { type: 'string' },\n detail: {},\n },\n required: ['message', 'code'],\n },\n },\n },\n },\n documentation: {\n info: {\n title: 'home-hosted',\n version: appVersion(),\n description: 'Control plane for the processes you host at home: servers, logs, vitals, backups and settings.',\n },\n tags: [\n { name: 'panel', description: 'Snapshot, health and the local shutdown channel' },\n { name: 'servers', description: 'The processes being supervised' },\n { name: 'logs', description: 'Live and persisted logs' },\n { name: 'workspaces', description: 'The ownership boundary: one scope per setup' },\n { name: 'backups', description: 'Archives of config, secrets, TLS and data paths' },\n { name: 'auth', description: 'Sessions and the panel password' },\n { name: 'notifications', description: 'Telegram delivery and webhook destinations' },\n { name: 'ddns', description: 'Dynamic DNS accounts and hostnames' },\n { name: 'proxy', description: 'The reverse proxy: engine, routes and certificates' },\n { name: 'tls', description: 'The panel certificate' },\n ],\n /**\n * The auth scheme, so a generated client can be told how to send a credential.\n *\n * Every `/api` route takes `Authorization: Bearer hh_…`, and the spec said nothing\n * about it: openapi-typescript, openapi-generator and Scalar's \"try it\" all produced\n * clients with no auth hook, and the README tells an agent this document *is* the API\n * it may call. Two lines here are the difference between generating a client and\n * hand-writing one.\n */\n\n components: {\n securitySchemes: {\n bearerAuth: {\n type: 'http',\n scheme: 'bearer',\n description: 'An API token from `home-hosted set-token --generate`. A cookie session works too, but is not part of this scheme.',\n },\n localToken: {\n type: 'apiKey',\n in: 'header',\n name: 'x-home-hosted-token',\n description: 'The local control channel: the token in `run.json`, from a loopback caller only.',\n },\n },\n },\n security: [{ bearerAuth: [] }],\n servers: [{ url: '/', description: 'This panel' }],\n },\n }, c) as unknown as Record<string, unknown>)\n return c.json(spec)\n },\n )\n .get(\n `${PREFIX}/ui`,\n // A page that works with no internet, with the CDN browser as optional enhancement — see\n // `src/openapi-reference.ts` for why `Scalar()` alone was blank on the box this ships to.\n c => c.html(openApiReferencePage(`${PREFIX}/spec.json`)),\n )\n}\n\n/** Routes answered without any credential. */\nconst PUBLIC_OPERATIONS = new Set(['/healthz', '/api/auth/login', '/api/auth/session'])\n\nconst ERROR_BODY = {\n 'application/json': {\n schema: {\n type: 'object',\n properties: { message: { type: 'string' }, code: { type: 'string' }, detail: {} },\n required: ['message', 'code'],\n },\n },\n}\n\n/**\n * What the route table cannot say for itself: which credential each group takes, the failures the\n * guards answer before any handler runs, and a body on every documented error.\n */\nexport function finishSpec(spec: Record<string, unknown>): Record<string, unknown> {\n const paths = (spec.paths ?? {}) as Record<string, Record<string, Record<string, unknown>>>\n for (const route of Object.keys(paths)) {\n // The engine's DNS-01 channel is internal plumbing, not part of the API.\n if (route.startsWith('/_acme')) {\n delete paths[route]\n continue\n }\n for (const operation of Object.values(paths[route]!)) {\n const responses = (operation.responses ??= {}) as Record<string, Record<string, unknown>>\n if (PUBLIC_OPERATIONS.has(route))\n operation.security = []\n else if (route.startsWith('/_hh'))\n operation.security = [{ localToken: [] }]\n if (route.startsWith('/api') && !PUBLIC_OPERATIONS.has(route)) {\n responses['401'] ??= { description: 'No valid session or token (`AUTH_REQUIRED`)' }\n responses['403'] ??= { description: 'A cross-origin write, or an operation this credential may not perform' }\n }\n responses['421'] ??= { description: 'The `Host` header names a host this panel does not answer to (`HOST_NOT_ALLOWED`)' }\n for (const [status, response] of Object.entries(responses)) {\n if (Number(status) >= 400 && response.content === undefined)\n response.content = ERROR_BODY\n }\n }\n }\n return spec\n}\n","import type { SecretsStore } from '#src/config/secrets'\nimport type { AcmeChallengeService } from '#src/services/acme-challenge'\nimport type { AuthService } from '#src/services/auth'\nimport type { BackupService } from '#src/services/backups'\nimport type { ControlServer } from '#src/services/control-server'\nimport type { EventHub } from '#src/services/events'\nimport type { PanelService } from '#src/services/panel'\nimport type { ProxyService } from '#src/services/proxy'\nimport type { TlsStore } from '#src/services/tls'\nimport type { UiService } from '#src/services/ui'\nimport { createAcmeChallengeRoute } from '#src/api/acme'\nimport { createAuthRoute } from '#src/api/auth/$.routes'\nimport { createBackupsRoute } from '#src/api/backups'\nimport { createControlRoute } from '#src/api/control'\nimport { createDdnsRoute } from '#src/api/ddns'\nimport { createEventsRoute } from '#src/api/events'\nimport { createHealthRoute } from '#src/api/health'\nimport { createLogsRoute } from '#src/api/logs'\nimport { createMetricsRoute } from '#src/api/metrics'\nimport { createNotificationsRoute } from '#src/api/notifications'\nimport { createProxyRoute } from '#src/api/proxy'\nimport { createServersRoute } from '#src/api/servers/$.routes'\nimport { createSettingsRoute } from '#src/api/settings'\nimport { createStateRoute } from '#src/api/state'\nimport { createStaticRoute } from '#src/api/static'\nimport { createTlsRoute } from '#src/api/tls'\nimport { createWorkspacesRoute } from '#src/api/workspaces/$.routes'\nimport { createWslTemperatureRoute } from '#src/api/wsl-temperature'\nimport { errorHandler } from '#src/helpers/error'\nimport { appFactory } from '#src/helpers/factory'\nimport { logger } from '#src/helpers/logger'\nimport { createAuthGuard } from '#src/middleware/auth'\nimport { createHostGuard } from '#src/middleware/host'\nimport { setupOpenAPI } from '#src/openapi'\n\n/**\n * What the routes are handed. Only the panel-wide services live here; anything a\n * workspace owns (its store, secrets, logs, notifications, DDNS, supervisor) is\n * resolved per request from `panel.requireWorkspace(...)`.\n */\nexport interface AppDeps {\n panel: PanelService\n hub: EventHub\n auth: AuthService\n secrets: SecretsStore\n controlServer: ControlServer\n tls: TlsStore\n backups: BackupService\n ui: UiService\n /** The panel-wide reverse proxy: engine, routes and its own TLS pair. */\n proxy: ProxyService\n /** Answers the engine's DNS-01 challenges through a route's DNS account. */\n challenge: AcmeChallengeService\n /** Token for the local `down` command, and the graceful stop it asks for. */\n runtimeToken: string\n /** `withPersistent` is `down --with-persistent`: end the persistent entries too. */\n onShutdown: (options?: { withPersistent?: boolean }) => Promise<void>\n}\n\n/**\n * The root app: middleware and sub-routes only, never a handler of its own.\n *\n * The whole thing is one chained expression on purpose — that is what keeps the\n * route map in the type, which `AppType` hands to `hc<AppType>` clients and to\n * `setupOpenAPI`.\n */\nexport function createRootApp(deps: AppDeps) {\n const app = appFactory.createApp()\n .use('*', async (c, next) => {\n const started = Date.now()\n await next()\n logger.debug(`${c.req.method} ${new URL(c.req.url).pathname} ${c.res.status} ${Date.now() - started}ms`)\n })\n\n .onError(errorHandler)\n\n // Before anything else: a rebound public name must not reach a single route.\n .use('*', createHostGuard(() => [...deps.panel.settings.control.allowedHosts, ...deps.proxy.panelHosts()]))\n\n // Outside `/api`, so a local `down` needs no session — but it needs the token\n // from `run.json` and a loopback peer. Behind the host guard like every route; a local\n // caller reaches it by IP, which the guard always allows.\n .route('/_hh', createControlRoute(deps))\n\n // The engine's DNS-01 channel: outside `/api` too, loopback-only, and behind\n // credentials the panel generates. The engine calls it on `127.0.0.1`, which the guard allows.\n .route('/_acme', createAcmeChallengeRoute(deps))\n\n .use('/api/*', createAuthGuard({ auth: deps.auth }))\n\n .route('/api', createAuthRoute(deps))\n .route('/api', createStateRoute(deps))\n .route('/api', createEventsRoute(deps))\n .route('/api', createSettingsRoute(deps))\n .route('/api', createTlsRoute(deps))\n .route('/api', createWslTemperatureRoute(deps))\n .route('/api', createLogsRoute(deps))\n .route('/api', createNotificationsRoute(deps))\n .route('/api', createDdnsRoute(deps))\n .route('/api', createProxyRoute(deps))\n .route('/api', createMetricsRoute(deps))\n .route('/api', createBackupsRoute(deps))\n .route('/api/workspaces', createWorkspacesRoute(deps))\n .route('/api/servers', createServersRoute(deps))\n\n .route('/', createHealthRoute(deps))\n\n // The spec is generated from the finished route table (and must be routed\n // *before* the static catch-all, which would otherwise swallow it).\n const documented = app.route('/', setupOpenAPI(app))\n return documented.route('/', createStaticRoute({ dir: () => deps.ui.resolveDir() }))\n}\n\n/** What a typed client (`hc<AppType>`) and the OpenAPI document are built from. */\nexport type AppType = ReturnType<typeof createRootApp>\n","import { exec } from 'node:child_process'\nimport process from 'node:process'\n\n/** Best-effort browser launch; a headless host simply logs instead. */\nexport function openBrowser(url: string): void {\n const command = process.platform === 'darwin'\n ? `open \"${url}\"`\n : process.platform === 'win32'\n ? `start \"\" \"${url}\"`\n : `xdg-open \"${url}\"`\n\n exec(command, { windowsHide: true }, () => {\n // No display / no handler: the URL is already printed, so this is not an error.\n })\n}\n","import type { DdnsChallengeRecord, DdnsFetch } from '#src/providers/ddns/types'\nimport { Buffer } from 'node:buffer'\nimport { type } from 'arktype'\nimport { secretEqual } from '#src/helpers/secret-compare'\nimport { ddnsProvider } from '#src/providers/ddns'\nimport { normalizeHost } from '#src/providers/ddns/types'\n\n/**\n * The ACMEProxy protocol, which is what Caddy's `dns.providers.acmeproxy` module\n * speaks: it POSTs a name and a value to `present` and again to `cleanup`, and\n * checks that the reply echoes both. The DNS write itself is the panel's, through\n * a workspace account's stored credentials — so the engine never holds them.\n *\n * `libdns/acmeproxy` only ever handles TXT records, and sends the absolute name\n * (`_acme-challenge.git.example.com.`).\n */\n\n/** The request and the reply are the same two fields. */\nconst proxyMessageSchema = type({\n fqdn: 'string >= 1',\n value: 'string >= 1',\n}).onUndeclaredKey('reject')\n\nexport interface ChallengeAccount {\n /** The workspace that owns the account, so a write is attributable. */\n workspaceId: string\n /** The account id inside that workspace. */\n accountId: string\n /** The provider that knows how to write the record. */\n provider: string\n credentials: Record<string, string>\n}\n\nexport interface AcmeChallengeOptions {\n /**\n * The Basic credentials the engine is configured with, read per request so a panel\n * that has DNS-01 switched off writes no credentials file at all. `null` means the\n * feature is off, and every request is refused.\n */\n auth: () => { username: string, password: string } | null\n /** Which account answers for a name, or null when no route claims it. */\n accountFor: (fqdn: string) => ChallengeAccount | null\n fetchImpl?: DdnsFetch\n /** Called after every attempt, so a failure is reportable outside the engine's log. */\n onResult?: (result: { fqdn: string, action: string, ok: boolean, message: string, account: ChallengeAccount | null }) => void\n}\n\nfunction reply(message: { fqdn: string, value: string }, status = 200): Response {\n return new Response(JSON.stringify(message), { status, headers: { 'content-type': 'application/json' } })\n}\n\nfunction failure(status: number, message: string): Response {\n return new Response(JSON.stringify({ error: message }), { status, headers: { 'content-type': 'application/json' } })\n}\n\n/**\n * Serves `POST /present` and `POST /cleanup` for the engine. The caller mounts it\n * on a loopback-only path: a route pointing at a name is what decides the account,\n * so an unreachable endpoint is the only thing standing between a stranger and\n * somebody's DNS.\n */\nexport class AcmeChallengeService {\n constructor(private readonly options: AcmeChallengeOptions) {}\n\n async handle(request: Request, action: string): Promise<Response> {\n if (action !== 'present' && action !== 'cleanup')\n return failure(404, `unknown action \"${action}\"`)\n\n // No credentials means DNS-01 is not switched on. Refusing is the whole point:\n // an absent lock must never read as \"no lock\", because this endpoint writes\n // records into somebody's zone.\n const auth = this.options.auth()\n if (auth === null)\n return failure(403, 'DNS-01 is not switched on for this panel')\n if (!this.authorized(request, auth))\n return failure(401, 'authentication required')\n\n let parsed: unknown\n try {\n parsed = await request.json()\n }\n catch {\n return failure(400, 'the body must be JSON')\n }\n const message = proxyMessageSchema(parsed)\n if (message instanceof type.errors)\n return failure(400, 'the body must carry fqdn and value')\n\n // The engine sends the absolute name; every provider speaks the relative one.\n const fqdn = normalizeHost(message.fqdn)\n const account = this.options.accountFor(fqdn)\n if (account === null)\n return failure(404, `no DNS account answers for ${fqdn}`)\n\n const provider = ddnsProvider(account.provider)\n if (provider?.challenge === undefined)\n return failure(400, `the \"${account.provider}\" account cannot write TXT records`)\n\n const record: DdnsChallengeRecord = { fqdn, value: message.value, action }\n const result = await provider.challenge(record, {\n credentials: account.credentials,\n fetch: this.options.fetchImpl ?? fetch,\n })\n this.options.onResult?.({ fqdn, action, ok: result.ok, message: result.message, account })\n\n // A failed cleanup must not fail the issuance: the certificate is already in\n // hand, and a leftover TXT record is harmless until it is swept.\n if (!result.ok && action === 'cleanup')\n return reply({ fqdn: message.fqdn, value: message.value })\n\n if (!result.ok)\n return failure(502, result.message)\n\n return reply({ fqdn: message.fqdn, value: message.value })\n }\n\n private authorized(request: Request, auth: { username: string, password: string }): boolean {\n const header = request.headers.get('authorization') ?? ''\n if (!header.toLowerCase().startsWith('basic '))\n return false\n try {\n const decoded = Buffer.from(header.slice(6).trim(), 'base64').toString('utf8')\n const separator = decoded.indexOf(':')\n if (separator < 0)\n return false\n const user = decoded.slice(0, separator)\n const password = decoded.slice(separator + 1)\n // Both compared, without short-circuiting: `&&` skips the password check when the username is\n // wrong, so the two halves cost different work — the opposite of what this comment used to say.\n // The difference is ~90 ns, below loopback jitter, and this endpoint is loopback-only with a\n // generated credential, so it is not a demonstrated leak; computing both costs nothing.\n const userOk = secretEqual(user, auth.username)\n const passwordOk = secretEqual(password, auth.password)\n return userOk && passwordOk\n }\n catch {\n return false\n }\n }\n}\n","import type { FSWatcher } from 'node:fs'\nimport fs from 'node:fs'\nimport path from 'node:path'\n\n/**\n * Tells the caller when the config file *may* have changed. Whether it really did\n * is the store's decision: it remembers the bytes it last read and the bytes it\n * wrote, so a save from the panel's own UI never reloads anything.\n *\n * The watch is on the file's directory, because that is what catches the common\n * edit — an editor writes a temporary file and renames it over the target, which\n * replaces the inode and would slip past a watch on the file itself. `fs.watch` is\n * not dependable on network mounts, so a slow poll backs it up: one small read\n * every couple of seconds costs nothing next to a state frame.\n */\n\nexport interface ConfigWatchOptions {\n /** The config file; its directory is what is actually watched. */\n file: string\n /** Called after a burst of changes settles. */\n onChange: () => void\n /** How long to wait for an editor to finish writing. */\n debounceMs?: number\n /** Backup poll interval in ms; 0 turns the poll off. */\n pollMs?: number\n /** A watch that cannot be established is reported; the poll still covers the file. */\n onError?: (error: unknown) => void\n}\n\nconst DEFAULT_DEBOUNCE_MS = 150\nconst DEFAULT_POLL_MS = 2000\n\nexport class ConfigWatch {\n private readonly debounceMs: number\n private readonly pollMs: number\n private watcher: FSWatcher | null = null\n private debounceTimer: NodeJS.Timeout | null = null\n private pollTimer: NodeJS.Timeout | null = null\n private disposed = false\n\n constructor(private readonly options: ConfigWatchOptions) {\n this.debounceMs = options.debounceMs ?? DEFAULT_DEBOUNCE_MS\n this.pollMs = options.pollMs ?? DEFAULT_POLL_MS\n }\n\n start(): void {\n if (this.disposed || this.watcher !== null)\n return\n\n try {\n this.watcher = fs.watch(path.dirname(this.options.file), (_event, filename) => {\n // Only our file: the directory is shared with the logs, the secrets file and\n // whatever else home-hosted keeps beside its config. The name is compared by\n // basename because a platform may hand back a path, not the bare name — macOS\n // has been seen to — and an exact compare then drops the edit it was told about.\n if (filename !== null && path.basename(filename) !== path.basename(this.options.file))\n return\n this.schedule()\n })\n this.watcher.on('error', (error) => {\n // A watch can die with the mount it was opened on. Stop pretending it works\n // and let the poll carry the file.\n this.options.onError?.(error)\n this.closeWatcher()\n })\n this.watcher.unref()\n }\n catch (error) {\n this.options.onError?.(error)\n }\n\n if (this.pollMs > 0) {\n this.pollTimer = setInterval(() => this.check(), this.pollMs)\n this.pollTimer.unref()\n }\n }\n\n /** One check, exactly what the poll does — tests drive this instead of waiting. */\n check(): void {\n this.schedule()\n }\n\n dispose(): void {\n this.disposed = true\n if (this.debounceTimer !== null) {\n clearTimeout(this.debounceTimer)\n this.debounceTimer = null\n }\n if (this.pollTimer !== null) {\n clearInterval(this.pollTimer)\n this.pollTimer = null\n }\n this.closeWatcher()\n }\n\n /** One reload per burst: an editor writing in pieces is still one edit. */\n private schedule(): void {\n if (this.disposed || this.debounceTimer !== null)\n return\n this.debounceTimer = setTimeout(() => {\n this.debounceTimer = null\n if (!this.disposed)\n this.options.onChange()\n }, this.debounceMs)\n this.debounceTimer.unref()\n }\n\n private closeWatcher(): void {\n this.watcher?.close()\n this.watcher = null\n }\n}\n","import type { Server } from 'srvx'\nimport type { Bind } from '#src/shared/contracts'\nimport { serve } from 'srvx'\nimport { bindHost, displayHost } from '#src/helpers/bind'\nimport { isPortFree } from '#src/providers/port'\nimport { errorMessage } from '#src/shared/error-message'\n\nexport interface ControlEndpoint {\n /** Configured bind value: `local` | `lan` | ipv4. */\n host: Bind\n port: number\n /** Address actually bound. */\n bindHost: string\n url: string\n protocol: 'http' | 'https'\n}\n\nexport interface ControlServerOptions {\n /** A thunk, so the app can be built after this server exists. */\n fetch: (request: Request) => Response | Promise<Response>\n /** Read per (re)bind, so a settings change applies without a restart. */\n /** `boolean | 'loopback'`, passed through to srvx, which understands both. */\n trustProxy: () => boolean | 'loopback'\n /** The uploaded PEM pair, or null for plain http. Read per (re)bind. */\n tls: () => { cert: string, key: string } | null\n}\n\nexport interface RebindResult {\n ok: boolean\n error?: string\n}\n\n/**\n * Owns the control panel's own listener, so the settings page can move it to a\n * new host/port without stopping the supervised servers.\n */\nexport class ControlServer {\n readonly endpoint: ControlEndpoint\n private server: Server | null = null\n\n constructor(\n private readonly options: ControlServerOptions,\n initial: { host: Bind, port: number, tls?: boolean },\n ) {\n this.endpoint = {\n host: initial.host,\n port: initial.port,\n bindHost: bindHost(initial.host),\n url: `${initial.tls ? 'https' : 'http'}://${displayHost(initial.host)}:${initial.port}`,\n protocol: initial.tls ? 'https' : 'http',\n }\n }\n\n get liveHost(): string {\n return this.endpoint.host\n }\n\n get livePort(): number {\n return this.endpoint.port\n }\n\n async start(): Promise<void> {\n await this.listenWithRetry(this.endpoint.host, this.endpoint.port)\n }\n\n /** Re-listens on the same endpoint, e.g. after `trustProxy` changed. */\n async restart(): Promise<RebindResult> {\n const { host, port } = this.endpoint\n await this.close()\n try {\n await this.listenWithRetry(host, port)\n return { ok: true }\n }\n catch (error) {\n return { ok: false, error: `restart failed: ${errorMessage(error)}` }\n }\n }\n\n /**\n * Moves the listener. Preflights the new port, and restores the previous\n * endpoint if the new one refuses to bind — otherwise the panel would become\n * unreachable and need a manual restart.\n */\n async rebind(next: { host: Bind, port: number }): Promise<RebindResult> {\n if (next.host === this.endpoint.host && next.port === this.endpoint.port)\n return { ok: true }\n\n const previous = { host: this.endpoint.host, port: this.endpoint.port }\n if (next.port !== previous.port && !(await isPortFree(next.port))) {\n return { ok: false, error: `port ${next.port} is already in use` }\n }\n\n await this.close()\n try {\n await this.listenWithRetry(next.host, next.port)\n return { ok: true }\n }\n catch (error) {\n const message = errorMessage(error)\n try {\n await this.listenWithRetry(previous.host, previous.port)\n }\n catch {\n // Nothing left to fall back to; the caller surfaces the original error.\n }\n return { ok: false, error: `rebind failed: ${message}` }\n }\n }\n\n async close(force = true): Promise<void> {\n const server = this.server\n this.server = null\n if (!server)\n return\n try {\n await server.close(force)\n }\n catch {\n // Already gone.\n }\n }\n\n /** A just-closed listener can refuse a rebind for a moment, so retry briefly. */\n private async listenWithRetry(host: Bind, port: number, attempts = 3): Promise<void> {\n let lastError: unknown\n for (let attempt = 1; attempt <= attempts; attempt++) {\n try {\n await this.listen(host, port)\n return\n }\n catch (error) {\n lastError = error\n if (attempt < attempts)\n await new Promise(resolve => setTimeout(resolve, 200))\n }\n }\n throw lastError\n }\n\n private async listen(host: Bind, port: number): Promise<void> {\n const tls = this.options.tls()\n const server = serve({\n fetch: this.options.fetch,\n port,\n hostname: bindHost(host),\n trustProxy: this.options.trustProxy(),\n ...(tls === null ? {} : { tls: { cert: tls.cert, key: tls.key } }),\n })\n\n // Without a listener, a failed bind would surface as an unhandled 'error' event.\n const nodeServer = server.node?.server\n const failure = new Promise<Error>((resolve) => {\n nodeServer?.once('error', error => resolve(error as Error))\n })\n\n const outcome = await Promise.race([\n server.ready().then(() => null).catch((error: unknown) => error as Error),\n failure,\n ])\n if (outcome !== null)\n throw outcome\n\n this.server = server\n this.endpoint.host = host\n this.endpoint.port = port\n this.endpoint.bindHost = bindHost(host)\n this.endpoint.protocol = tls === null ? 'http' : 'https'\n this.endpoint.url = `${this.endpoint.protocol}://${displayHost(host)}:${port}`\n }\n}\n","import type { HostConfig, HostView } from '#src/shared/contracts'\nimport { execFile, execFileSync } from 'node:child_process'\nimport fs from 'node:fs'\nimport os from 'node:os'\nimport path from 'node:path'\nimport process from 'node:process'\nimport { promisify } from 'node:util'\n\nconst execFileAsync = promisify(execFile)\n\n/**\n * How long a swap reading is reused.\n *\n * Reading swap off Linux costs a *process spawn*: `sysctl` on macOS, and a full PowerShell\n * start on Windows, where `wmic` no longer exists. The host is sampled every 15 s by default,\n * so that was 5,760 spawns a day — minutes of process churn for one number that moves slowly\n * and only feeds an alert threshold and a Prometheus gauge.\n *\n * A stale-by-a-minute reading is not a lie anyone acts on, and the alternative is worse: the\n * spawn happens inside the sample, so it also delays the whole state frame.\n */\nconst SWAP_CACHE_MS = 60_000\n\nlet swapCache: { at: number, percent: number } | null = null\n\n/**\n * Whether a cached reading may be reused.\n *\n * Separate from the reading itself so the rule can be tested anywhere — the read is\n * `sysctl`/PowerShell, which no CI runner but macOS and Windows can perform, and a bug here\n * would be one that only shows up as either a stale alert or a spawn storm.\n *\n * A stamp in the future (a backwards wall-clock step) counts as stale: with a plain\n * `now - at < ttl` it computes a negative age, which is \"fresh\", and the reading would stick\n * until wall time caught back up — potentially hours after an NTP correction.\n */\nexport function isSwapCacheFresh(cache: { at: number } | null, now: number, ttlMs = SWAP_CACHE_MS): boolean {\n if (cache === null)\n return false\n const age = now - cache.at\n return age >= 0 && age < ttlMs\n}\n\n/** Swap usage per platform: /proc on Linux, sysctl on macOS, CIM on Windows. */\nasync function swapUsedPercent(now = Date.now()): Promise<number> {\n if (process.platform === 'linux')\n return 0 // filled by memoryInfo below\n\n if (isSwapCacheFresh(swapCache, now))\n return swapCache!.percent\n\n const percent = await readSwapUsedPercent()\n swapCache = { at: now, percent }\n return percent\n}\n\n/**\n * `sysctl -n vm.swapusage` as a percentage. Pure, so the arithmetic is testable with the readings\n * the platform can actually produce rather than only the ones a runner happens to have.\n */\nexport function swapPercentFromSysctl(stdout: string): number {\n const total = /total\\s*=\\s*([\\d.]+)M/.exec(stdout)?.[1]\n const used = /used\\s*=\\s*([\\d.]+)M/.exec(stdout)?.[1]\n const totalMb = Number.parseFloat(total ?? '0')\n const usedMb = Number.parseFloat(used ?? '0')\n // `usedPercent` takes what is *free*, so pass the remainder. macOS counts compressed swap, where\n // `used` can exceed `total` — and the swap alert is `used >= threshold`, so a negative silently\n // suppresses it.\n return usedPercent(Math.max(0, totalMb - usedMb), totalMb)\n}\n\n/** One `Win32_PageFileUsage` CSV row as a percentage; see `swapPercentFromSysctl` for the clamp. */\nexport function swapPercentFromPageFile(stdout: string): number {\n const line = stdout.split(/\\r?\\n/).slice(1).find(entry => entry.trim().length > 0)\n const cells = (line ?? '').split(',').map(entry => entry.replace(/\"/g, '').trim())\n const totalMb = Number.parseFloat(cells[0] ?? '0')\n const usedMb = Number.parseFloat(cells[1] ?? '0')\n // `CurrentUsage` can exceed `AllocatedBaseSize` when the pagefile has grown since the snapshot.\n return usedPercent(Math.max(0, totalMb - usedMb), totalMb)\n}\n\nexport async function readSwapUsedPercent(): Promise<number> {\n if (process.platform === 'darwin') {\n try {\n const { stdout } = await execFileAsync('sysctl', ['-n', 'vm.swapusage'], { timeout: 3000 })\n return swapPercentFromSysctl(stdout)\n }\n catch {\n return 0\n }\n }\n\n if (process.platform === 'win32') {\n try {\n const script = 'Get-CimInstance Win32_PageFileUsage | Select-Object AllocatedBaseSize,CurrentUsage | ConvertTo-Csv -NoTypeInformation'\n const { stdout } = await execFileAsync('powershell.exe', ['-NoProfile', '-NonInteractive', '-Command', script], { timeout: 5000 })\n return swapPercentFromPageFile(stdout)\n }\n catch {\n return 0\n }\n }\n\n return 0\n}\n\n/**\n * Cumulative CPU time across every core, split into the two halves a utilisation reading needs.\n *\n * `os.cpus()` is the only CPU source common to Linux, macOS and Windows, and each entry is a\n * cumulative* counter since boot — so a percentage is the delta between two snapshots, never a\n * single read. One core busy for the whole window is 100%; all 8 cores busy is 800%, which is why\n * the per-core figure and the machine-wide figure are not interchangeable.\n */\nexport interface CpuTimes {\n /** Milliseconds of CPU time spent doing anything but idling, every core summed. */\n busyMs: number\n /** Milliseconds of CPU time across every core, idle included. */\n totalMs: number\n}\n\nexport function cpuTimesSnapshot(cpus = os.cpus()): CpuTimes {\n let busyMs = 0\n let totalMs = 0\n for (const cpu of cpus) {\n const times = cpu.times\n const idle = times.idle\n // `irq`/`nice` are absent on some platforms' `os.cpus()`; an absent field is zero.\n const busy = times.user + (times.nice ?? 0) + times.sys + (times.irq ?? 0)\n busyMs += busy\n totalMs += busy + idle\n }\n return { busyMs, totalMs }\n}\n\n/**\n * Share of the machine's CPU capacity in use between two snapshots, 0–100.\n *\n * `null` when the window is empty or the counters went backwards (a suspended host, a clock\n * resync), because \"no reading\" is honest while a fabricated 0 reads as \"idle\". Pure, so the\n * arithmetic is testable against snapshots a runner can construct rather than only the one its\n * own scheduler happens to produce.\n */\nexport function cpuUsedPercent(previous: CpuTimes, next: CpuTimes): number | null {\n const totalDelta = next.totalMs - previous.totalMs\n const busyDelta = next.busyMs - previous.busyMs\n if (!(totalDelta > 0) || busyDelta < 0)\n return null\n return Math.max(0, Math.min(100, (busyDelta / totalDelta) * 100))\n}\n\n/**\n * The last snapshot, kept only long enough to difference against the next.\n *\n * Module state, like `swapCache`, because `sampleHost` is the one host sampler and the *interval*\n * between two calls is what makes the reading mean anything. The first call has no baseline and\n * answers `null` rather than inventing a number.\n */\nlet previousCpuTimes: CpuTimes | null = null\n\n/**\n * Memory used, as a percentage of what the machine actually has.\n *\n * The definition matters more than the arithmetic, and it differs per platform:\n *\n * - Linux: `/proc/meminfo`'s `MemAvailable` already excludes cache, because Linux counts\n * page cache as reclaimable. `os.freemem()` happens to read the same value here.\n * - macOS: **`os.freemem()` is wrong for this.** libuv reports `host_statistics64`'s\n * `free_count` alone, while macOS keeps as much RAM as it can in *inactive* and\n * speculative* pages — file cache it drops on demand. A perfectly healthy Mac therefore\n * reads as 90%+ used, which is the report a user brought back from a 0.7.3 panel. Read\n * `vm_stat` and count what macOS itself counts as available.\n * - Windows: `os.freemem()` is the free physical page count, which is the ordinary reading.\n */\n\n/**\n * How much of `total` is not `free`, as a percentage clamped into `[0, 100]`; 0 when `total` is\n * meaningless.\n *\n * `MemAvailable` is a kernel *estimate* and can exceed `MemTotal`, and `SwapFree` can exceed\n * `SwapTotal` — both make the raw ratio negative. That matters more than a strange display: the\n * alert is `used >= threshold`, so a negative reading silently **suppresses** the memory alert\n * entirely. The fallback branch already clamped for exactly this reason; the `/proc` branch did not,\n * so the two disagreed on the same quantity.\n */\nexport function usedPercent(free: number, total: number): number {\n if (!(total > 0))\n return 0\n return Math.max(0, Math.min(100, ((total - free) / total) * 100))\n}\n\nexport function memoryInfo(): { memoryUsedPercent: number, swapUsedPercent: number } {\n try {\n const info = fs.readFileSync('/proc/meminfo', 'utf8')\n const read = (key: string): number => Number.parseInt(new RegExp(`^${key}:\\\\s+(\\\\d+)`, 'm').exec(info)?.[1] ?? '0', 10)\n\n return {\n memoryUsedPercent: usedPercent(read('MemAvailable'), read('MemTotal')),\n swapUsedPercent: usedPercent(read('SwapFree'), read('SwapTotal')),\n }\n }\n catch {\n const total = os.totalmem()\n const available = availableMemoryBytes(process.platform, os.freemem())\n return {\n memoryUsedPercent: available === null ? 0 : usedPercent(available, total),\n swapUsedPercent: 0,\n }\n }\n}\n\n/**\n * Which \"available memory\" reading a platform's fallback should use.\n *\n * Split out from `memoryInfo` because the branch it decides is otherwise unreachable off\n * macOS: Linux answers from `/proc/meminfo` first, so the fallback never runs there and no\n * Linux test can prove which reader was chosen. Taking the platform and the OS reading as\n * arguments makes the decision testable on any runner, which matters — using the wrong\n * reader here is the whole macOS bug.\n */\nexport function availableMemoryBytes(platform: NodeJS.Platform, osFree: number, vmStat?: string): number | null {\n if (platform !== 'darwin')\n return osFree\n return macAvailableBytes(vmStat)\n}\n\n/**\n * What macOS counts as available: free + inactive + speculative pages.\n *\n * `vm_stat` reports pages, so the page size is needed — and it is not always 4096 (Apple\n * silicon uses 16384 for the physical page size, and `vm_stat` has printed a `page size of`\n * header since macOS 11). Both are handled: the header when it is there, `getpagesize` when\n * it is not.\n *\n * Returns `null` when the reading cannot be taken, so the caller reports \"unknown\" rather\n * than inventing a percentage.\n */\nexport function macAvailableBytes(vmStat?: string): number | null {\n try {\n const text = vmStat ?? execFileSync('vm_stat', { timeout: 3000, encoding: 'utf8' })\n const pageSize = Number.parseInt(/page size of (\\d+) bytes/.exec(text)?.[1] ?? '', 10)\n\n const pages = (label: string): number => {\n // \"Pages free: 12345.\"\n const found = new RegExp(`^${label}:\\\\s+(\\\\d+)`, 'm').exec(text)?.[1]\n return Number.parseInt(found ?? '', 10)\n }\n\n // Without the header, ask the OS: `sysconf(_SC_PAGESIZE)` through node's own binding.\n const size = Number.isFinite(pageSize) && pageSize > 0 ? pageSize : getPageSize()\n if (!Number.isFinite(size) || size <= 0)\n return null\n\n let totalPages = 0\n let sawAny = false\n // Free plus everything the OS will hand back without swapping. `purgeable` is counted\n // by macOS as reclaimable, and omitting it under-reports available memory on a Mac\n // running an app that marks memory purgeable.\n for (const label of ['Pages free', 'Pages inactive', 'Pages speculative', 'Pages purgeable']) {\n const value = pages(label)\n if (Number.isFinite(value)) {\n totalPages += value\n sawAny = true\n }\n }\n\n return sawAny ? totalPages * size : null\n }\n catch {\n return null\n }\n}\n\n/** The OS page size, without adding a dependency for one sysconf. */\nfunction getPageSize(): number {\n try {\n // `getconf` is POSIX and present on every macOS; it prints the same value vm_stat uses.\n return Number.parseInt(execFileSync('getconf', ['PAGESIZE'], { timeout: 3000, encoding: 'utf8' }).trim(), 10)\n }\n catch {\n return Number.NaN\n }\n}\n\n/**\n * Sensor names that report the **CPU** package/die temperature, best first.\n *\n * `hwmon` exposes one directory per chip and each has a `name`; `thermal_zone` exposes a `type`.\n * A machine has several: `nvme` and `drivemet` are disks, `amdgpu` is a GPU, `acpitz` is the ACPI\n * thermal zone. Taking the maximum over *all* of them and calling it \"CPU temp\" reported the NVMe's\n * 89 °C as the CPU on any box with one — and fired the temperature alert on a disk.\n */\nconst CPU_SENSOR = /coretemp|k10temp|zenpower|cpu_thermal|cpu-thermal|x86_pkg_temp|soc_thermal|package/i\n\n/** A fallback that is the machine's own thermal zone rather than a peripheral's. */\nconst ACPI_SENSOR = /acpitz|acpi/i\n\nexport interface TemperatureSensor {\n /** The chip or zone name, e.g. `coretemp`, `nvme`, `x86_pkg_temp`. */\n name: string\n celsius: number\n}\n\n/**\n * The CPU temperature, or null when this machine names no CPU sensor.\n *\n * One tier is chosen and the maximum is taken only *within* it — a CPU package reports several\n * dies, so the hottest die is the reading, but a disk's temperature is not a second opinion.\n */\nexport function pickCpuTemperature(sensors: TemperatureSensor[]): number | null {\n for (const pattern of [CPU_SENSOR, ACPI_SENSOR]) {\n const tier = sensors.filter(sensor => pattern.test(sensor.name)).map(sensor => sensor.celsius)\n if (tier.length > 0)\n return Math.max(...tier)\n }\n return null\n}\n\n/**\n * Best-effort CPU temperature from Linux thermal zones / hwmon. macOS and Windows expose no\n * unprivileged sensor, so those platforms report null and both UIs read \"n/a\" — a WSL2 guest has\n * none either, and the Windows host's `MSAcpi_ThermalZoneTemperature` answers a constant 20 °C\n * regardless of load, so reaching across for it would be a fabricated number rather than a reading.\n */\nexport function cpuTemperature(): number | null {\n const sensors: TemperatureSensor[] = []\n\n /** `name` is the sensor's own label; absent means the file could not be read, so skip it. */\n const inspect = (file: string, name: string): void => {\n try {\n const raw = Number.parseInt(fs.readFileSync(file, 'utf8').trim(), 10)\n if (!Number.isFinite(raw))\n return\n const celsius = raw / 1000 // both interfaces report millidegrees\n if (celsius > 0 && celsius < 150)\n sensors.push({ name, celsius })\n }\n catch {\n // Absent on this machine.\n }\n }\n\n try {\n for (const zone of fs.readdirSync('/sys/class/thermal')) {\n if (!zone.startsWith('thermal_zone'))\n continue\n const dir = path.join('/sys/class/thermal', zone)\n let type = ''\n try {\n type = fs.readFileSync(path.join(dir, 'type'), 'utf8').trim()\n }\n catch {\n // A zone with no `type` is unnamed, and an unnamed sensor cannot be claimed as the CPU.\n }\n inspect(path.join(dir, 'temp'), type)\n }\n }\n catch {\n // No thermal class.\n }\n\n try {\n for (const hwmon of fs.readdirSync('/sys/class/hwmon')) {\n const dir = path.join('/sys/class/hwmon', hwmon)\n let chip = ''\n try {\n chip = fs.readFileSync(path.join(dir, 'name'), 'utf8').trim()\n }\n catch {\n // Unnamed chip: keep reading its files, they are just not attributable to the CPU.\n }\n for (const entry of fs.readdirSync(dir)) {\n if (/^temp\\d+_input$/.test(entry))\n inspect(path.join(dir, entry), chip)\n }\n }\n }\n catch {\n // No hwmon.\n }\n\n return pickCpuTemperature(sensors)\n}\n\nasync function diskUsage(target: string): Promise<HostView['disks'][number] | null> {\n try {\n const stats = await fs.promises.statfs(target)\n const totalBytes = stats.blocks * stats.bsize\n const freeBytes = stats.bavail * stats.bsize\n return {\n path: target,\n totalBytes,\n freeBytes,\n usedPercent: usedPercent(freeBytes, totalBytes),\n }\n }\n catch {\n return null\n }\n}\n\n/**\n * Run the configured temperature command and parse one number out of its stdout.\n *\n * This is the escape hatch for a machine whose kernel exposes no sensor — a WSL2 guest above all,\n * where `/sys/class/hwmon` is empty and the Windows ACPI zone answers a constant 20 °C. The user\n * supplies the command, so it is spawned without a shell and given a timeout: a hung helper must\n * not stall a sample that the whole panel's tick waits on.\n *\n * Only a whole-number or decimal reading in a plausible range is accepted. Anything else answers\n * null, which the UI reads as `n/a` — never a guess, for the same reason a missing sensor is not\n * published as 0.\n */\nexport async function temperatureFromCommand(command: string, timeoutMs: number): Promise<number | null> {\n const trimmed = command.trim()\n if (trimmed.length === 0)\n return null\n try {\n // Run through a shell: the value is a command *line* the person wrote in their own config, like a\n // server entry's `command`+`args` they could have written instead, and a pipeline\n // (`… | awk '{print $1}'`) cannot be expressed without one. `execFile` picks cmd.exe on Windows\n // and /bin/sh elsewhere; `windowsHide` keeps a console from flashing on a desktop.\n const { stdout } = await execFileAsync(trimmed, { timeout: timeoutMs, windowsHide: true, maxBuffer: 64 * 1024, shell: true })\n return parseTemperature(stdout)\n }\n catch {\n return null\n }\n}\n\n/** The first plausible °C reading in a command's output, or null. Exported for its own tests. */\nexport function parseTemperature(output: string): number | null {\n // A helper may print a label before the number (`Tctl: 63.9`), so take the first match anywhere.\n const match = /-?\\d+(?:\\.\\d+)?/.exec(output)\n if (match === null)\n return null\n const celsius = Number.parseFloat(match[0])\n if (!Number.isFinite(celsius) || celsius <= 0 || celsius >= 150)\n return null\n return celsius\n}\n\n/**\n * The temperature to report: the configured command when there is one, else the built-in probe.\n *\n * The command wins even on a platform whose probe works, because a person who set it did so to\n * override what the panel found.\n */\nexport async function readTemperature(config: HostConfig): Promise<number | null> {\n if (config.tempCommand.trim().length > 0)\n return temperatureFromCommand(config.tempCommand, config.tempCommandTimeoutMs)\n return cpuTemperature()\n}\n\n/**\n * Samples the machine itself: the failures a home server actually dies from are\n * a full disk, exhausted memory or a runaway load — none of which a port probe\n * can see.\n */\nexport async function sampleHost(config: HostConfig, resolvePath: (target: string) => string): Promise<HostView> {\n const cpus = os.cpus().length || 1\n const loadAvg = os.loadavg()\n const memory = memoryInfo()\n // The deltas are taken at the *start*, so the window covers the whole sample rather than\n // whichever part of it the disk stats and swap spawn happened to leave over.\n const cpuTimes = cpuTimesSnapshot()\n const cpuUsedPercentNow = previousCpuTimes === null ? null : cpuUsedPercent(previousCpuTimes, cpuTimes)\n previousCpuTimes = cpuTimes\n // `os.loadavg()` is always zero on Windows, so per-cpu load would alert forever.\n if (process.platform === 'win32')\n loadAvg.fill(0)\n if (memory.swapUsedPercent === 0 && process.platform !== 'linux') {\n memory.swapUsedPercent = await swapUsedPercent()\n }\n const tempCelsius = await readTemperature(config)\n\n const disks = (await Promise.all(config.diskPaths.map(entry => diskUsage(resolvePath(entry))))).filter(\n (disk): disk is HostView['disks'][number] => disk !== null,\n )\n\n const alerts: string[] = []\n for (const disk of disks) {\n if (config.diskUsedPercent > 0 && disk.usedPercent >= config.diskUsedPercent) {\n alerts.push(`disk ${disk.path} is ${disk.usedPercent.toFixed(1)}% full`)\n }\n }\n if (config.memoryUsedPercent > 0 && memory.memoryUsedPercent >= config.memoryUsedPercent) {\n alerts.push(`memory is ${memory.memoryUsedPercent.toFixed(1)}% used`)\n }\n if (config.swapUsedPercent > 0 && memory.swapUsedPercent >= config.swapUsedPercent) {\n alerts.push(`swap is ${memory.swapUsedPercent.toFixed(1)}% used`)\n }\n const loadPerCpu = Number(loadAvg[0] ?? 0) / cpus\n if (config.loadPerCpu > 0 && loadPerCpu >= config.loadPerCpu) {\n alerts.push(`load ${loadPerCpu.toFixed(2)}/cpu exceeds ${config.loadPerCpu}`)\n }\n if (tempCelsius !== null && config.tempCelsius > 0 && tempCelsius >= config.tempCelsius) {\n alerts.push(`cpu temperature is ${tempCelsius.toFixed(0)}°C`)\n }\n\n return {\n enabled: config.enabled,\n cpus,\n loadAvg: [...loadAvg],\n cpuUsedPercent: cpuUsedPercentNow,\n uptimeMs: os.uptime() * 1000,\n memoryUsedPercent: memory.memoryUsedPercent,\n swapUsedPercent: memory.swapUsedPercent,\n tempCelsius,\n disks,\n alerts,\n sampledAt: Date.now(),\n // The thresholds a surface bands against, so a raised one is not painted as a breach while\n // the notification it governs stays silent.\n loadAlertPerCpu: config.loadPerCpu,\n memoryUsedPercentAlert: config.memoryUsedPercent,\n swapUsedPercentAlert: config.swapUsedPercent,\n tempCelsiusAlert: config.tempCelsius,\n diskUsedPercentAlert: config.diskUsedPercent,\n }\n}\n\nexport function emptyHostView(config: HostConfig): HostView {\n return {\n enabled: config.enabled,\n cpus: os.cpus().length || 1,\n loadAvg: [0, 0, 0],\n cpuUsedPercent: null,\n uptimeMs: os.uptime() * 1000,\n memoryUsedPercent: 0,\n swapUsedPercent: 0,\n tempCelsius: null,\n disks: [],\n alerts: [],\n sampledAt: null,\n loadAlertPerCpu: config.loadPerCpu,\n memoryUsedPercentAlert: config.memoryUsedPercent,\n swapUsedPercentAlert: config.swapUsedPercent,\n tempCelsiusAlert: config.tempCelsius,\n diskUsedPercentAlert: config.diskUsedPercent,\n }\n}\n","import type { NotificationEvent } from '#src/services/notifications'\nimport type { HostConfig, HostView } from '#src/shared/contracts'\nimport { emptyHostView, sampleHost } from '#src/providers/host'\n\n/** Anything that can receive a host-vitals notification; `NotificationService` qualifies. */\nexport interface HostNotifier {\n notify: (event: NotificationEvent) => void\n}\n\n/**\n * Samples host vitals on their own (slower) interval and turns threshold\n * breaches into one notification per transition, not one per sample.\n */\nexport class HostMonitor {\n private current: HostView\n private lastSampleAt = 0\n private alerting = false\n\n constructor(\n private readonly getConfig: () => HostConfig,\n private readonly resolvePath: (target: string) => string,\n /**\n * Every workspace's notification service: host vitals are panel-wide, so a\n * breach reaches each workspace that asked for host alerts.\n */\n private readonly notifications: HostNotifier | HostNotifier[],\n ) {\n this.current = emptyHostView(getConfig())\n }\n\n get view(): HostView {\n return this.current\n }\n\n private notify(event: NotificationEvent): void {\n const targets = Array.isArray(this.notifications) ? this.notifications : [this.notifications]\n for (const service of targets) service.notify(event)\n }\n\n /** Cheap when the interval has not elapsed; safe to call every tick. */\n async tick(now = Date.now()): Promise<void> {\n const config = this.getConfig()\n if (!config.enabled) {\n if (this.current.enabled)\n this.current = { ...this.current, enabled: false }\n return\n }\n if (now - this.lastSampleAt < config.intervalMs)\n return\n\n this.lastSampleAt = now\n this.current = await sampleHost(config, this.resolvePath)\n\n if (this.current.alerts.length > 0) {\n if (!this.alerting) {\n this.alerting = true\n this.notify({\n serverId: 'host',\n label: 'Host',\n reason: 'host',\n detail: this.current.alerts.join('; '),\n })\n }\n return\n }\n\n if (this.alerting) {\n this.alerting = false\n this.notify({\n serverId: 'host',\n label: 'Host',\n reason: 'host-recovered',\n detail: 'every host threshold is back to normal',\n })\n }\n }\n}\n","import type { DdnsFetch } from '#src/providers/ddns/types'\nimport { isIP } from 'node:net'\nimport { errorMessage } from '#src/shared/error-message'\n\n/**\n * Keyless public-address services. The family-specific hostnames are the point:\n * a bare `ipify.org` answers over whichever family the connection happened to\n * take, which is exactly what an AAAA update must not get.\n */\nexport const DEFAULT_IPV4_ENDPOINTS = [\n 'https://api4.ipify.org',\n 'https://ipv4.icanhazip.com',\n 'https://checkip.amazonaws.com',\n 'https://4.ident.me',\n 'https://cloudflare.com/cdn-cgi/trace',\n]\n\nexport const DEFAULT_IPV6_ENDPOINTS = [\n 'https://api6.ipify.org',\n 'https://ipv6.icanhazip.com',\n 'https://6.ident.me',\n 'https://cloudflare.com/cdn-cgi/trace',\n]\n\n/** RFC1918, loopback, link-local, CGNAT, documentation, benchmarking and multicast/reserved are never a public DNS target. */\nexport function isPublicAddress(ip: string, family: 'A' | 'AAAA'): boolean {\n if (family === 'A') {\n const parts = ip.split('.').map(part => Number.parseInt(part, 10))\n if (parts.length !== 4 || parts.some(part => !Number.isInteger(part) || part < 0 || part > 255))\n return false\n const [a, b, c] = parts as [number, number, number, number]\n const documentation = (a === 192 && b === 0 && c === 2) || (a === 198 && b === 51 && c === 100) || (a === 203 && b === 0 && c === 113)\n const benchmarking = a === 198 && (b === 18 || b === 19)\n // `224.0.0.0/3`: multicast, then the reserved block up to broadcast.\n return !(a === 0 || a === 10 || a === 127 || (a === 169 && b === 254) || (a === 172 && b >= 16 && b <= 31) || (a === 192 && b === 168) || (a === 100 && b >= 64 && b <= 127) || documentation || benchmarking || a >= 224)\n }\n\n const words = ipv6Words(ip)\n if (words === null)\n return false\n const [w0, w1] = words as [number, number, number, number, number, number, number, number]\n\n // `::` and `::1`.\n if (words.every(word => word === 0) || (w0 === 0 && w1 === 0 && words.slice(2, 7).every(word => word === 0) && words[7] === 1))\n return false\n // `::ffff:0:0/96` (IPv4-mapped) and `::/96` (IPv4-compatible): an IPv4 address in an AAAA slot.\n // The mapped block is where the earlier prefix checks failed — `::ffff:192.168.1.5` passed as\n // \"public\", so a private address could be published as a AAAA record.\n if (w0 === 0 && w1 === 0 && words[2] === 0 && words[3] === 0 && (words[4] === 0xFFFF || words[4] === 0))\n return false\n // Multicast `ff00::/8`.\n if ((w0 & 0xFF00) === 0xFF00)\n return false\n // Unique local `fc00::/7`, link-local `fe80::/10`.\n if ((w0 & 0xFE00) === 0xFC00 || (w0 & 0xFFC0) === 0xFE80)\n return false\n // Documentation: `2001:db8::/32`, `3fff::/20`.\n if (w0 === 0x2001 && w1 === 0x0DB8)\n return false\n if (w0 === 0x3FFF && (w1 & 0xF000) === 0)\n return false\n // 6to4 `2002::/16`, and the IETF protocol-assignment block `2001::/23` (Teredo, benchmarking,\n // ORCHID) — none of which is an address a host is reached at.\n if (w0 === 0x2002 || (w0 === 0x2001 && w1 <= 0x01FF))\n return false\n // IPv4/IPv6 translation `64:ff9b::/96`.\n if (w0 === 0x0064 && w1 === 0xFF9B)\n return false\n return true\n}\n\n/**\n * An IPv6 address as eight 16-bit words, or null when it cannot be parsed.\n *\n * The prefix checks above compare bits, and the same address has many spellings (`::ffff:c000:201`\n * and `::ffff:192.168.1.5` are one address), so a textual `startsWith` is not enough — that is how\n * the mapped block slipped through.\n */\nfunction ipv6Words(ip: string): number[] | null {\n let text = ip.toLowerCase()\n // A trailing dotted quad is the IPv4 form of the last two words.\n const dotted = /(\\d{1,3}(?:\\.\\d{1,3}){3})$/.exec(text)\n if (dotted !== null) {\n const parts = dotted[1]!.split('.').map(part => Number.parseInt(part, 10))\n if (parts.some(part => !Number.isInteger(part) || part < 0 || part > 255))\n return null\n const hi = (((parts[0]! << 8) | parts[1]!) >>> 0).toString(16)\n const lo = (((parts[2]! << 8) | parts[3]!) >>> 0).toString(16)\n text = `${text.slice(0, dotted.index)}${hi}:${lo}`\n }\n\n const halves = text.split('::')\n if (halves.length > 2)\n return null\n const head = halves[0] === '' ? [] : halves[0]!.split(':')\n const tail = halves.length === 1 || halves[1] === '' ? [] : halves[1]!.split(':')\n // The elided words are zeroes. Built with a push loop rather than `Array.from`/`new Array`: the\n // two lint-preferred spellings disagree with each other and both widen the element type.\n const zeros: string[] = []\n if (halves.length > 1) {\n for (let index = 0; index < 8 - head.length - tail.length; index += 1)\n zeros.push('0')\n }\n const words = halves.length === 1 ? head : [...head, ...zeros, ...tail]\n if (words.length !== 8)\n return null\n\n const numbers = words.map(word => (/^[0-9a-f]{1,4}$/.test(word) ? Number.parseInt(word, 16) : Number.NaN))\n return numbers.some(number => Number.isNaN(number)) ? null : numbers\n}\n\n/**\n * Reads the address out of whatever the endpoint answered: a bare address, a\n * Cloudflare `cdn-cgi/trace` body (`ip=…`), or a small JSON object.\n */\nexport function parseAddressResponse(text: string, family: 'A' | 'AAAA'): string | null {\n const trimmed = text.trim()\n if (trimmed.length === 0)\n return null\n\n const candidates: string[] = []\n const trace = /^ip=(.+)$/m.exec(trimmed)?.[1]\n if (trace !== undefined)\n candidates.push(trace.trim())\n if (trimmed.startsWith('{')) {\n try {\n const parsed = JSON.parse(trimmed) as Record<string, unknown>\n for (const key of ['ip', 'address', 'ip_addr', 'query']) {\n const value = parsed[key]\n if (typeof value === 'string')\n candidates.push(value.trim())\n }\n }\n catch {\n // Not JSON after all; the raw text below is the last chance.\n }\n }\n candidates.push(trimmed)\n\n const wanted = family === 'A' ? 4 : 6\n for (const candidate of candidates) {\n const value = candidate.split(/[\\s,]/)[0] ?? ''\n if (isIP(value) === wanted && isPublicAddress(value, family))\n return value\n }\n return null\n}\n\n/** One address lookup; the pass's own deadline still bounds the whole list. */\nexport const DETECT_TIMEOUT_MS = 10_000\n\nexport interface DetectResult {\n ip: string | null\n error: string | null\n}\n\n/**\n * Tries the configured endpoint, or the built-in list in order, and returns the\n * first address that is really public. A transient failure never deletes a\n * record; it just leaves the previous one in place.\n */\nexport async function detectPublicAddress(\n family: 'A' | 'AAAA',\n overrideUrl: string,\n fetchImpl: DdnsFetch,\n signal?: AbortSignal,\n timeoutMs = DETECT_TIMEOUT_MS,\n): Promise<DetectResult> {\n const configured = overrideUrl.trim()\n const endpoints = configured.length > 0\n ? [configured]\n : (family === 'A' ? DEFAULT_IPV4_ENDPOINTS : DEFAULT_IPV6_ENDPOINTS)\n\n let lastError: string | null = null\n for (const endpoint of endpoints) {\n if (signal?.aborted === true)\n break\n // Per endpoint, so one that never answers costs its own budget and not the whole pass's.\n const deadline = AbortSignal.timeout(timeoutMs)\n try {\n const response = await fetchImpl(endpoint, { signal: signal === undefined ? deadline : AbortSignal.any([signal, deadline]), headers: { Accept: 'text/plain, application/json' } })\n if (!response.ok) {\n lastError = `${endpoint} answered ${response.status}`\n continue\n }\n const parsed = parseAddressResponse(await response.text(), family)\n if (parsed !== null)\n return { ip: parsed, error: null }\n lastError = `${endpoint} did not answer with a public ${family === 'A' ? 'IPv4' : 'IPv6'} address`\n }\n catch (error) {\n lastError = `${endpoint}: ${errorMessage(error)}`\n }\n }\n\n return { ip: null, error: lastError ?? `no endpoint for ${family}` }\n}\n","import type { DdnsFetch, DdnsRecord } from '#src/providers/ddns/types'\nimport type { NotificationService } from '#src/services/notifications'\nimport type { DdnsConfig, DdnsRecordState, DdnsRecordView, DdnsStatus } from '#src/shared/contracts'\nimport { createHash } from 'node:crypto'\nimport fs from 'node:fs'\nimport { writeFileAtomic } from '#src/helpers/atomic'\nimport { logger } from '#src/helpers/logger'\nimport { ddnsProvider } from '#src/providers/ddns'\nimport { detectPublicAddress } from '#src/providers/ddns/ip'\nimport { normalizeHost } from '#src/providers/ddns/types'\nimport { errorMessage } from '#src/shared/error-message'\nimport { isRecord } from '#src/shared/shape'\n\n/** One network pass, however many hosts it covers. */\nconst RUN_TIMEOUT_MS = 60_000\n\ninterface CacheEntry {\n ip: string\n updatedAt: number\n zoneId?: string\n recordId?: string\n}\n\ninterface DdnsStateFile {\n version: 1\n updatedAt: number\n /** Last address each `host|type|account|provider` was confirmed to serve, so an unchanged IP costs no call. */\n records: Record<string, CacheEntry>\n}\n\ninterface ResultEntry {\n state: DdnsRecordState\n ip: string | null\n message: string | null\n updatedAt: number | null\n stopped?: boolean\n}\n\n/** A permanent refusal, and what it was given: the same inputs would get the same answer. */\ninterface StoppedEntry {\n fingerprint: string\n message: string\n}\n\nexport interface DdnsDeps {\n getConfig: () => DdnsConfig\n /** Provider credentials for one account, or null when none are stored for that provider. */\n getCredentials: (accountId: string, provider: string) => Record<string, string> | null\n notifications: NotificationService\n statePath: string\n /** The pre-rename cache, adopted when `statePath` does not exist yet. */\n legacyStatePath?: string\n fetchImpl?: DdnsFetch\n now?: () => number\n}\n\nfunction emptyState(): DdnsStateFile {\n return { version: 1, updatedAt: 0, records: {} }\n}\n\n/**\n * The cache an older release left at the legacy path, moved to the new one. Only a file shaped like\n * that cache is taken: the same name is a persistent `ddns` entry's nanny state, which stays put.\n */\nfunction adoptLegacyState(file: string, legacy: string): void {\n if (fs.existsSync(file))\n return\n try {\n const text = fs.readFileSync(legacy, 'utf8')\n const parsed = JSON.parse(text) as unknown\n if (!isRecord(parsed) || !isRecord(parsed.records))\n return\n writeFileAtomic(file, text)\n fs.rmSync(legacy, { force: true })\n }\n catch {\n // Nothing there, or nothing readable: the cache only saves provider calls.\n }\n}\n\nfunction readState(file: string): DdnsStateFile {\n try {\n const parsed = JSON.parse(fs.readFileSync(file, 'utf8')) as Partial<DdnsStateFile>\n const records: Record<string, CacheEntry> = {}\n for (const [key, value] of Object.entries(parsed?.records ?? {})) {\n // A key from before the account and provider were part of it is a miss, not a match.\n if (typeof value?.ip === 'string' && key.split('|').length === 4)\n records[key] = value\n }\n return { version: 1, updatedAt: typeof parsed?.updatedAt === 'number' ? parsed.updatedAt : 0, records }\n }\n catch {\n // A missing or unreadable cache only costs one extra provider call.\n return emptyState()\n }\n}\n\nfunction cacheKey(host: string, type: string, account: string, provider: string): string {\n return `${normalizeHost(host)}|${type}|${account}|${provider}`\n}\n\nfunction fingerprint(input: unknown): string {\n return createHash('sha256').update(JSON.stringify(input)).digest('hex')\n}\n\n/**\n * Keeps a list of hostnames pointed at this machine's public address.\n *\n * Detection is cheap and runs on the interval; a provider is only called when\n * the address differs from the one it last confirmed, which is what keeps the\n * simple token endpoints (FreeDNS, No-IP) inside their rate limits.\n */\nexport class DdnsService {\n private readonly results = new Map<string, ResultEntry>()\n private readonly stopped = new Map<string, StoppedEntry>()\n private persisted: DdnsStateFile\n private running = false\n private disposed = false\n /** Null until the first pass, so a fresh panel looks immediately. */\n private lastStartedAt: number | null = null\n private lastRunAt: number | null = null\n private lastResult: string | null = null\n private ipv4: string | null = null\n private ipv6: string | null = null\n\n constructor(private readonly deps: DdnsDeps) {\n if (deps.legacyStatePath !== undefined)\n adoptLegacyState(deps.statePath, deps.legacyStatePath)\n this.persisted = readState(deps.statePath)\n }\n\n private now(): number {\n return this.deps.now?.() ?? Date.now()\n }\n\n /** What the state frame and the settings page read. */\n get view(): DdnsStatus {\n return {\n enabled: this.deps.getConfig().enabled,\n running: this.running,\n lastRunAt: this.lastRunAt,\n lastResult: this.lastResult,\n ipv4: this.ipv4,\n ipv6: this.ipv6,\n records: this.records(),\n }\n }\n\n /** One entry per configured target, with whatever the last pass learned. */\n private records(): DdnsRecordView[] {\n const config = this.deps.getConfig()\n const views: DdnsRecordView[] = []\n for (const domain of config.domains) {\n const account = config.accounts.find(entry => entry.id === domain.account)\n const provider = account === undefined ? null : ddnsProvider(account.provider)\n for (const type of domain.types) {\n const key = cacheKey(domain.host, type, domain.account, account?.provider ?? '')\n const found = this.results.get(key)\n views.push({\n host: domain.host,\n account: domain.account,\n provider: account?.provider ?? '',\n type,\n ip: found?.ip ?? this.persisted.records[key]?.ip ?? null,\n state: found?.state ?? (provider === null ? 'skipped' : 'pending'),\n message: found?.message ?? (account === undefined ? `unknown account \"${domain.account}\"` : provider === null ? `unknown provider \"${account.provider}\"` : null),\n updatedAt: found?.updatedAt ?? null,\n ...(found?.stopped === true ? { stopped: true } : {}),\n })\n }\n }\n return views\n }\n\n /**\n * Makes the next tick run immediately, after a config or credential save, and lifts every\n * permanent stop. Naming an account forgets what its records were confirmed to serve, because\n * new credentials may reach another provider account.\n */\n refresh(options: { account?: string } = {}): void {\n this.lastStartedAt = null\n this.stopped.clear()\n if (options.account !== undefined) {\n for (const key of Object.keys(this.persisted.records)) {\n if (key.split('|')[2] === options.account)\n delete this.persisted.records[key]\n }\n }\n }\n\n /**\n * Cheap enough to call every supervisor tick, and deliberately non-blocking:\n * a slow provider must never hold up health probes.\n */\n tick(now = this.now()): void {\n if (this.disposed || this.running)\n return\n const config = this.deps.getConfig()\n if (!config.enabled)\n return\n if (this.lastStartedAt !== null && now - this.lastStartedAt < config.intervalMs)\n return\n this.lastStartedAt = now\n void this.run().catch((error: unknown) => {\n logger.error('ddns pass failed', error)\n })\n }\n\n /** Runs one pass now; `force` re-sends addresses the cache already knows. */\n async run(options: { force?: boolean } = {}): Promise<DdnsStatus> {\n if (this.running || this.disposed)\n return this.view\n this.running = true\n\n const config = this.deps.getConfig()\n const signal = AbortSignal.timeout(RUN_TIMEOUT_MS)\n const fetchImpl = this.deps.fetchImpl ?? ((input, init) => fetch(input, init))\n let changed = 0\n let unchanged = 0\n let failed = 0\n let skipped = 0\n let stopped = 0\n\n try {\n const wanted = this.wantedFamilies(config)\n const detected = {\n ipv4: wanted.ipv4 ? await detectPublicAddress('A', config.ipv4.url, fetchImpl, signal) : { ip: null, error: null },\n ipv6: wanted.ipv6 ? await detectPublicAddress('AAAA', config.ipv6.url, fetchImpl, signal) : { ip: null, error: null },\n }\n if (detected.ipv4.ip !== null)\n this.ipv4 = detected.ipv4.ip\n if (detected.ipv6.ip !== null)\n this.ipv6 = detected.ipv6.ip\n if (detected.ipv4.error !== null)\n logger.warn(`ddns: could not detect the public IPv4 address (${detected.ipv4.error})`)\n if (detected.ipv6.error !== null)\n logger.warn(`ddns: could not detect the public IPv6 address (${detected.ipv6.error})`)\n\n for (const domain of config.domains) {\n if (!domain.enabled)\n continue\n const account = config.accounts.find(entry => entry.id === domain.account)\n const provider = account === undefined ? null : ddnsProvider(account.provider)\n const credentials = account === undefined ? null : this.deps.getCredentials(account.id, account.provider)\n\n for (const type of domain.types) {\n const key = cacheKey(domain.host, type, domain.account, account?.provider ?? '')\n const family = type === 'A' ? 'ipv4' : 'ipv6'\n const familyConfig = type === 'A' ? config.ipv4 : config.ipv6\n const address = type === 'A' ? detected.ipv4.ip : detected.ipv6.ip\n\n if (provider === null || account === undefined) {\n this.remember(key, 'skipped', address, `unknown account or provider for \"${domain.account}\"`)\n skipped += 1\n continue\n }\n if (!familyConfig.enabled) {\n this.remember(key, 'skipped', address, `${type} records need ${family} detection, which is off`)\n skipped += 1\n continue\n }\n if (address === null) {\n this.remember(key, 'skipped', null, detected[family].error ?? `no public ${family} address was found`)\n skipped += 1\n continue\n }\n if (!provider.families.includes(type)) {\n this.remember(key, 'skipped', address, `${provider.label} cannot manage ${type} records`)\n skipped += 1\n continue\n }\n if (!options.force && this.persisted.records[key]?.ip === address) {\n this.remember(key, 'unchanged', address, null)\n unchanged += 1\n continue\n }\n\n const cache = this.persisted.records[key]\n const record: DdnsRecord = {\n host: domain.host,\n type,\n ip: address,\n ttl: domain.ttl ?? config.ttl,\n proxied: domain.proxied,\n ...(domain.zone === undefined ? {} : { zone: domain.zone }),\n ...(cache === undefined ? {} : { cache: { ...(cache.zoneId === undefined ? {} : { zoneId: cache.zoneId }), ...(cache.recordId === undefined ? {} : { recordId: cache.recordId }) } }),\n }\n\n const update = provider.update\n if (update === undefined) {\n this.remember(key, 'skipped', address, `the \"${account.provider}\" provider does not update addresses`)\n continue\n }\n const inputs = fingerprint({ domain, account, credentials })\n const stop = this.stopped.get(key)\n if (!options.force && stop !== undefined && stop.fingerprint === inputs) {\n this.remember(key, 'error', address, `stopped: ${stop.message} — fix the hostname, account or credentials, or run a check`, true)\n stopped += 1\n continue\n }\n this.stopped.delete(key)\n\n const result = await update(record, { credentials: credentials ?? {}, fetch: fetchImpl, signal })\n if (result.ok) {\n this.persisted.records[key] = {\n ip: address,\n updatedAt: this.now(),\n ...(result.cache?.zoneId === undefined ? {} : { zoneId: result.cache.zoneId }),\n ...(result.cache?.recordId === undefined ? {} : { recordId: result.cache.recordId }),\n }\n this.remember(key, result.changed ? 'ok' : 'unchanged', address, result.message)\n if (result.changed)\n changed += 1\n else\n unchanged += 1\n }\n else {\n if (result.permanent === true)\n this.stopped.set(key, { fingerprint: inputs, message: result.error ?? result.message })\n this.remember(key, 'error', address, result.error ?? result.message, result.permanent === true)\n failed += 1\n logger.warn(`ddns: ${domain.host} ${type}: ${result.error ?? result.message}`)\n }\n }\n }\n }\n finally {\n this.running = false\n this.lastRunAt = this.now()\n this.persisted.updatedAt = this.lastRunAt\n this.writeState()\n this.lastResult = this.describe(changed, unchanged, failed, skipped, stopped)\n this.announce({ changed, failed })\n }\n\n return this.view\n }\n\n /** Only the families a configured target actually asks for. */\n private wantedFamilies(config: DdnsConfig): { ipv4: boolean, ipv6: boolean } {\n return {\n ipv4: config.ipv4.enabled && config.domains.some(domain => domain.enabled && domain.types.includes('A')),\n ipv6: config.ipv6.enabled && config.domains.some(domain => domain.enabled && domain.types.includes('AAAA')),\n }\n }\n\n private remember(key: string, state: DdnsRecordState, ip: string | null, message: string | null, stopped = false): void {\n this.results.set(key, { state, ip, message, updatedAt: this.now(), ...(stopped ? { stopped: true } : {}) })\n }\n\n /** Counts only: the detected addresses are shown beside it, and are the status's own. */\n private describe(changed: number, unchanged: number, failed: number, skipped: number, stopped: number): string {\n const parts = [\n changed > 0 ? `${changed} updated` : null,\n unchanged > 0 ? `${unchanged} already current` : null,\n failed > 0 ? `${failed} failed` : null,\n stopped > 0 ? `${stopped} stopped` : null,\n skipped > 0 ? `${skipped} skipped` : null,\n ].filter((part): part is string => part !== null)\n return parts.length === 0 ? 'nothing to update' : parts.join(', ')\n }\n\n /** One message per pass, so a flapping provider cannot flood the chat. */\n private announce(counts: { changed: number, failed: number }): void {\n if (counts.changed === 0 && counts.failed === 0)\n return\n if (counts.failed > 0) {\n this.deps.notifications.notify({\n serverId: 'ddns',\n label: 'DDNS',\n reason: 'ddns-error',\n detail: this.lastResult ?? 'a dynamic DNS update failed',\n })\n return\n }\n this.deps.notifications.notify({\n serverId: 'ddns',\n label: 'DDNS',\n reason: 'ddns',\n detail: this.lastResult ?? 'a dynamic DNS record changed',\n })\n }\n\n private writeState(): void {\n try {\n writeFileAtomic(this.deps.statePath, `${JSON.stringify(this.persisted, null, 2)}\\n`)\n }\n catch (error) {\n logger.warn(`ddns: could not save its state (${errorMessage(error)})`)\n }\n }\n\n dispose(): void {\n this.disposed = true\n }\n}\n","import type { HistoryEvent, ServerHistory } from '#src/shared/contracts'\nimport fs from 'node:fs'\nimport { writeFileAtomic } from '#src/helpers/atomic'\n\nconst MAX_EVENTS = 5000\nconst SAVE_DEBOUNCE_MS = 2000\nconst EVENTS_IN_VIEW = 8\n\n/**\n * Bounded event log per server, persisted as JSON so uptime and crash counts\n * survive a restart of the control plane.\n *\n * Uptime is derived from recorded runtimes (each exit stores how long the process\n * was up) rather than from sampling, so it stays accurate without a background\n * poller.\n */\nexport class HistoryStore {\n private events: HistoryEvent[] = []\n private saveTimer: NodeJS.Timeout | null = null\n private loaded = false\n /** Bumped on every record, so readers can cache their summaries. */\n private version = 0\n\n constructor(private readonly file: string) {}\n\n get revision(): number {\n return this.version\n }\n\n load(): void {\n if (this.loaded)\n return\n this.loaded = true\n try {\n const parsed = JSON.parse(fs.readFileSync(this.file, 'utf8')) as { events?: HistoryEvent[] }\n this.events = Array.isArray(parsed.events) ? parsed.events.slice(-MAX_EVENTS) : []\n }\n catch {\n this.events = []\n }\n }\n\n record(serverId: string, event: Omit<HistoryEvent, 'serverId' | 'ts'>, ts = Date.now()): void {\n this.load()\n this.events.push({ serverId, ts, ...event })\n this.version += 1\n if (this.events.length > MAX_EVENTS)\n this.events.splice(0, this.events.length - MAX_EVENTS)\n this.scheduleSave()\n }\n\n all(): HistoryEvent[] {\n this.load()\n return [...this.events]\n }\n\n /**\n * Drops every event for a server that no longer exists.\n *\n * An id is only unique *while* it exists. Nothing pruned on removal, so re-adding an id — a\n * rename-back, a restore, a config edit — inherited the old entry's crash time and event list, and\n * the card showed \"Last crash\" for a server that had never been started. Bounded (5000 events) so it\n * was never a leak, but wrong in the same way the log files were.\n */\n forget(serverId: string): void {\n this.load()\n const kept = this.events.filter(event => event.serverId !== serverId)\n if (kept.length === this.events.length)\n return\n this.events = kept\n this.version += 1\n this.scheduleSave()\n }\n\n /** `runningSince` adds the in-flight up-interval so a long-running server shows its real ratio. */\n summarize(serverId: string, windowMs: number, now = Date.now(), runningSince: number | null = null): ServerHistory {\n this.load()\n const since = now - windowMs\n const mine = this.events.filter(event => event.serverId === serverId)\n const recent = mine.filter(event => event.ts >= since)\n\n // Each recorded runtime ends at its own event, so only the part that falls inside the window\n // counts. `Math.min(runtimeMs, windowMs)` alone kept the *whole* run: a 24h run that ended 12h\n // before `now` sits half outside a 24h window, and was reported as 100% up. Clipping the start\n // against `since` is what makes the number mean \"up during this window\".\n let upMs = 0\n for (const event of recent) {\n if (event.runtimeMs === undefined)\n continue\n const startedAt = event.ts - event.runtimeMs\n upMs += event.ts - Math.max(startedAt, since)\n }\n if (runningSince !== null)\n upMs += Math.max(0, now - Math.max(runningSince, since))\n\n // The ratio is over the part of the window this server existed for: a server first seen ten\n // minutes ago and up the whole time is 100% up, not 0.7% of a day.\n const firstSeen = Math.min(...mine.map(event => event.ts - (event.runtimeMs ?? 0)), runningSince ?? now)\n const observedMs = Math.max(1, now - Math.max(since, firstSeen))\n\n const lastCrash = [...mine].reverse().find(event => event.type === 'crash')\n const lastExit = [...mine].reverse().find(event => event.type === 'exit' || event.type === 'crash')\n\n return {\n windowMs,\n uptimeRatio: mine.length === 0 ? null : Math.max(0, Math.min(1, upMs / observedMs)),\n restarts: recent.filter(event => event.type === 'start').length,\n crashes: recent.filter(event => event.type === 'crash').length,\n forcedRestarts: recent.filter(event => event.type === 'forced-restart').length,\n lastCrashAt: lastCrash?.ts ?? null,\n lastExitAt: lastExit?.ts ?? null,\n lastRuntimeMs: lastExit?.runtimeMs ?? null,\n events: recent.slice(-EVENTS_IN_VIEW),\n }\n }\n\n dispose(): void {\n if (this.saveTimer !== null)\n clearTimeout(this.saveTimer)\n this.saveTimer = null\n this.save()\n }\n\n private scheduleSave(): void {\n if (this.saveTimer !== null)\n return\n this.saveTimer = setTimeout(() => {\n this.saveTimer = null\n this.save()\n }, SAVE_DEBOUNCE_MS)\n this.saveTimer.unref()\n }\n\n private save(): void {\n try {\n writeFileAtomic(this.file, `${JSON.stringify({ version: 1, events: this.events })}\\n`)\n }\n catch {\n // History is best-effort; never let it break supervision.\n }\n }\n}\n","import type { SecretsStore } from '#src/config/secrets'\nimport type { DestinationStatusView, NotificationDefaults, NotificationsConfig, NotificationTarget, WebhookTarget } from '#src/shared/contracts'\nimport { logger } from '#src/helpers/logger'\nimport { formatTelegramMessage, listTelegramChats, sendTelegramMessage, verifyTelegramToken } from '#src/providers/telegram'\nimport { sendWebhook, targetProblem } from '#src/providers/webhook'\nimport { errorMessage } from '#src/shared/error-message'\n\nexport type NotificationReason = 'crash' | 'unhealthy' | 'forced-restart' | 'recovered' | 'restart-ok' | 'rss' | 'host' | 'host-recovered' | 'ddns' | 'ddns-error'\n\nexport interface NotificationEvent {\n serverId: string\n label: string\n reason: NotificationReason\n detail: string\n}\n\nconst REASON_LABEL: Record<NotificationReason, string> = {\n 'crash': 'gave up restarting',\n 'unhealthy': 'health check failing',\n 'forced-restart': 'force restarted',\n /**\n * The other half of `forced-restart`: the entry came back and is serving.\n *\n * Without it a force restart was announced and then never closed, so a reader could not\n * tell \"it restarted and is fine now\" from \"it restarted and is still broken\" — the two\n * cases looked identical until the next crash.\n */\n 'restart-ok': 'restarted and healthy again',\n 'recovered': 'recovered',\n 'rss': 'exceeded its memory limit',\n 'host': 'host thresholds breached',\n 'host-recovered': 'host thresholds recovered',\n 'ddns': 'updated a dynamic DNS record',\n 'ddns-error': 'hit a dynamic DNS error',\n}\n\nconst TITLE: Record<NotificationReason, string> = {\n 'crash': '🔴 server down',\n 'unhealthy': '🟠 server unhealthy',\n 'forced-restart': '🔁 server force restarted',\n 'restart-ok': '🟢 server back up',\n 'recovered': '🟢 server recovered',\n 'rss': '🔴 server over its memory limit',\n 'host': '🟠 host warning',\n 'host-recovered': '🟢 host recovered',\n 'ddns': '🌐 DNS updated',\n 'ddns-error': '🌐 DNS update failed',\n}\n\n/** The event toggles and the throttle: what a destination may inherit, and what it may override. */\ntype NotificationPolicy = NotificationDefaults\n\n/** Which toggles apply to a reason. `rss` rides the crash toggle: an out-of-memory restart is the same event to a reader. */\nconst COVERS: Record<NotificationReason, (policy: NotificationPolicy) => boolean> = {\n 'crash': policy => policy.onCrash,\n 'rss': policy => policy.onCrash,\n 'unhealthy': policy => policy.onUnhealthy,\n 'forced-restart': policy => policy.onForcedRestart,\n // The closure of a force restart, so it rides the same toggle: someone who asked to be\n // told about restarts asked to hear how each one ended, not only that it began.\n 'restart-ok': policy => policy.onForcedRestart,\n 'recovered': policy => policy.onRecovered,\n 'host': policy => policy.onHost,\n 'host-recovered': policy => policy.onHost,\n 'ddns': policy => policy.onDdns,\n 'ddns-error': policy => policy.onDdns,\n}\n\ninterface DeliveryResult {\n lastResult: string | null\n lastResultAt: number | null\n}\n\n/**\n * Fans supervision events out to the configured destinations.\n *\n * **One list, two kinds.** A destination is a Telegram chat or a webhook; both carry an `enabled`\n * switch, an optional policy of their own, and one row on the page. A workspace may point at\n * several Telegram chats, which is why the bot token is a per-destination secret rather than the\n * singleton it used to be.\n *\n * **Inheritance is the default.** A destination with `useOwnSettings: false` follows\n * `notifications.defaults`, so the common case is configured once instead of per destination. A\n * destination that sets its own opts out entirely — no field is merged, because a half-inherited\n * policy is one nobody can reason about.\n *\n * The throttle is per destination *and* server *and* reason: a flapping server must not flood one\n * destination, and one destination going quiet must not silence another.\n */\nexport class NotificationService {\n private readonly cooldowns = new Map<string, number>()\n private readonly results = new Map<string, DeliveryResult>()\n\n constructor(\n private readonly secrets: SecretsStore,\n private readonly getConfig: () => NotificationsConfig,\n ) {}\n\n /** The general block, as the page edits it. */\n defaults(): NotificationDefaults {\n return { ...this.getConfig().defaults }\n }\n\n /**\n * Every destination as a row: its own fields, the policy it will actually use, and its last result.\n *\n * The page shows this rather than the raw config, so an inheriting destination displays the\n * inherited toggles — the values a send will use, not the stale ones on disk.\n */\n destinations(): DestinationStatusView[] {\n return this.getConfig().destinations.map((target) => {\n const result = this.results.get(target.id) ?? { lastResult: null, lastResultAt: null }\n const common = {\n id: target.id,\n kind: target.kind,\n enabled: target.enabled,\n useOwnSettings: target.useOwnSettings,\n ...this.effectivePolicy(target),\n lastResult: result.lastResult,\n lastResultAt: result.lastResultAt,\n }\n if (target.kind === 'telegram') {\n return {\n ...common,\n chatId: target.chatId,\n tokenSet: this.secrets.telegramTokenSet(target.id),\n url: null,\n method: null,\n format: null,\n headers: null,\n }\n }\n return {\n ...common,\n chatId: null,\n tokenSet: false,\n url: target.url,\n method: target.method,\n format: target.format,\n headers: target.headers,\n }\n })\n }\n\n /** The policy a destination actually uses: its own, or the general block's. */\n effectivePolicy(target: NotificationTarget): NotificationPolicy {\n if (target.useOwnSettings) {\n return {\n onCrash: target.onCrash,\n onUnhealthy: target.onUnhealthy,\n onForcedRestart: target.onForcedRestart,\n onRecovered: target.onRecovered,\n onHost: target.onHost,\n onDdns: target.onDdns,\n cooldownMs: target.cooldownMs,\n }\n }\n // No field merges: a half-inherited policy is one nobody can reason about.\n return { ...this.getConfig().defaults }\n }\n\n /**\n * The destinations that would deliver this event right now.\n *\n * Per destination rather than one boolean for the service: a single answer would either send a\n * host warning somewhere switched off for it, or silence a crash because another destination's\n * cooldown was still running.\n */\n targetsFor(event: NotificationEvent, now = Date.now()): NotificationTarget[] {\n return this.getConfig().destinations.filter((target) => {\n if (!target.enabled)\n return false\n const policy = this.effectivePolicy(target)\n if (!COVERS[event.reason](policy))\n return false\n const until = this.cooldowns.get(this.cooldownKey(target, event)) ?? 0\n return !(policy.cooldownMs > 0 && until > now)\n })\n }\n\n /** Whether *any* destination would deliver this event. */\n shouldNotify(event: NotificationEvent, now = Date.now()): boolean {\n return this.targetsFor(event, now).length > 0\n }\n\n /** Starts the cooldown window for every destination about to be asked to send. */\n markSent(event: NotificationEvent, now = Date.now()): void {\n for (const target of this.targetsFor(event, now))\n this.armCooldown(target, event, now)\n }\n\n /** One destination's window, returning the deadline it set so a failed send can undo it. */\n private armCooldown(target: NotificationTarget, event: NotificationEvent, now = Date.now()): number {\n const until = now + this.effectivePolicy(target).cooldownMs\n this.cooldowns.set(this.cooldownKey(target, event), until)\n return until\n }\n\n /**\n * Gives back the window a **failed** send took.\n *\n * The window exists to collapse a flapping server into one message, so it is armed before the\n * send rather than after: two events already in flight must not both go out. But a send that\n * never arrived has told nobody anything — measured on the built panel, a crash alert sent while\n * the receiver was down recorded `fetch failed`, and the next two crashes inside the 5-minute\n * window were silenced by it, so the one alert that would have reached a working receiver was\n * the one the outage took. Undo only the deadline this send set: a concurrent dispatch may have\n * armed a later one, and clearing that would reopen the flood the window is for.\n */\n private releaseCooldown(target: NotificationTarget, event: NotificationEvent, armed: number): void {\n const key = this.cooldownKey(target, event)\n if (this.cooldowns.get(key) === armed)\n this.cooldowns.delete(key)\n }\n\n /** Fire-and-forget by design: supervision must never wait on a chat or webhook API. */\n notify(event: NotificationEvent): void {\n void this.dispatch(event).catch((error: unknown) => {\n logger.warn(`notification failed: ${errorMessage(error)}`)\n })\n }\n\n async dispatch(event: NotificationEvent): Promise<boolean> {\n // `targetsFor` owns the toggles and the cooldown, so the policy lives once.\n const targets = this.targetsFor(event)\n if (targets.length === 0)\n return false\n // Armed per destination so a failure can hand its own window back (see `releaseCooldown`).\n const armed = new Map(targets.map(target => [target.id, this.armCooldown(target, event)]))\n\n const title = TITLE[event.reason]\n const message = `${event.label} (${event.serverId}) ${REASON_LABEL[event.reason]}\\n${event.detail}`\n // One destination failing must not stop the others, so each is settled on its own.\n const results = await Promise.all(targets.map(target => this.deliver(target, title, message, event, armed.get(target.id) ?? 0)))\n return results.includes(true)\n }\n\n /** One destination, one event. A throw is recorded against it and nothing else. */\n private async deliver(target: NotificationTarget, title: string, message: string, event: NotificationEvent, armed: number): Promise<boolean> {\n try {\n const result = target.kind === 'telegram'\n ? await this.sendTelegram(target, title, message)\n : await sendWebhook(target, { title, message, reason: event.reason, serverId: event.serverId, label: event.label })\n this.remember(target.id, result.ok ? 'sent' : result.error ?? 'send failed')\n if (!result.ok)\n this.releaseCooldown(target, event, armed)\n return result.ok\n }\n catch (error) {\n this.remember(target.id, errorMessage(error))\n this.releaseCooldown(target, event, armed)\n return false\n }\n }\n\n /** A probe for one destination. */\n async sendTest(id: string, overrides: { chatId?: string, botToken?: string } = {}): Promise<{ ok: boolean, error?: string }> {\n const target = this.getConfig().destinations.find(entry => entry.id === id)\n if (target === undefined)\n return { ok: false, error: 'no such destination' }\n\n const result = target.kind === 'telegram'\n ? await this.testTelegram(id, target.chatId, overrides.chatId, overrides.botToken)\n : await this.testWebhook(target, id)\n this.remember(id, result.ok ? 'test message sent' : result.error ?? 'test failed')\n return result\n }\n\n /**\n * A Telegram destination's own token, with the chat id and the token both overridable.\n *\n * The override is what lets a token be tried before it is saved — the route advertises it and\n * `detect-chats` honours it, so ignoring it here made \"send a test\" fail on a token the page was\n * still holding.\n */\n private async testTelegram(id: string, chatId: string, overrideChatId?: string, overrideToken?: string): Promise<{ ok: boolean, error?: string }> {\n const chat = (overrideChatId ?? chatId).trim()\n if (chat.length === 0)\n return { ok: false, error: 'no chat id configured' }\n const token = overrideToken !== undefined && overrideToken.length > 0 ? overrideToken : this.secrets.telegramToken(id)\n if (token === null)\n return { ok: false, error: 'no bot token configured for this destination' }\n\n return sendTelegramMessage(token, chat, formatTelegramMessage('✅ home-hosted test', ['notifications are wired up correctly']))\n }\n\n /**\n * A webhook probe, for a saved destination or for a draft the page has not saved.\n *\n * A draft is passed whole, so a URL and its headers can be tried before they are stored — and so\n * a destination's own \"test\" tests *that* destination, not whichever one comes first.\n */\n async testWebhook(target: Pick<WebhookTarget, 'url' | 'method' | 'format' | 'headers'>, id?: string): Promise<{ ok: boolean, error?: string }> {\n const problem = targetProblem(target, { requireUrl: true })\n if (problem !== null)\n return { ok: false, error: problem }\n\n const result = await sendWebhook(target, {\n title: 'home-hosted test',\n message: 'notifications are wired up correctly',\n reason: 'test',\n serverId: '',\n label: '',\n })\n if (id !== undefined)\n this.remember(id, result.ok ? 'test message sent' : result.error ?? 'test failed')\n return result\n }\n\n /** Lists the chats a destination's bot can see, so its chat id can be picked. */\n async detectChats(id: string, overrides: { botToken?: string } = {}): Promise<{ ok: boolean, chats: Array<{ id: number | string, title: string }>, error?: string }> {\n const token = (overrides.botToken ?? this.secrets.telegramToken(id) ?? '').trim()\n if (token.length === 0)\n return { ok: false, chats: [], error: 'no bot token configured for this destination' }\n\n const result = await listTelegramChats(token)\n this.remember(id, result.ok ? `${result.chats.length} chat(s) found` : result.error ?? 'detect failed')\n return result\n }\n\n /** Verifies a token without storing or sending anything. */\n async verifyToken(token: string): Promise<{ ok: boolean, username?: string, error?: string }> {\n return verifyTelegramToken(token)\n }\n\n private cooldownKey(target: NotificationTarget, event: NotificationEvent): string {\n return `${target.id}:${event.serverId}:${event.reason}`\n }\n\n private async sendTelegram(target: Extract<NotificationTarget, { kind: 'telegram' }>, title: string, message: string): Promise<{ ok: boolean, error?: string }> {\n if (target.chatId.length === 0)\n return { ok: false, error: 'no chat id configured' }\n\n const token = this.secrets.telegramToken(target.id)\n if (token === null)\n return { ok: false, error: 'no bot token configured for this destination' }\n\n // The title is the first line of the message; Telegram gets it bold, the rest as bullets.\n const body = message.split('\\n').filter(line => line.length > 0)\n return sendTelegramMessage(token, target.chatId, formatTelegramMessage(title, body))\n }\n\n /** Records one destination's outcome, keyed by its id. */\n private remember(id: string, message: string): void {\n this.results.set(id, { lastResult: message, lastResultAt: Date.now() })\n }\n}\n","export interface BackoffOptions {\n baseDelayMs: number\n factor: number\n maxDelayMs: number\n}\n\n/** Exponential backoff: base * factor^(attempt - 1), capped at maxDelayMs. */\nexport function computeBackoff(attempt: number, options: BackoffOptions): number {\n const normalized = Math.max(1, Math.floor(attempt))\n const raw = options.baseDelayMs * options.factor ** (normalized - 1)\n if (!Number.isFinite(raw))\n return options.maxDelayMs\n return Math.min(Math.max(0, raw), options.maxDelayMs)\n}\n","import type { ServerConfig } from '#src/shared/contracts'\n\n/**\n * Orders servers so every dependency comes before its dependents.\n *\n * Cycles and unknown ids are ignored here — the config store reports them as\n * config errors — so this can never throw and stall supervision.\n */\nexport function orderByDependencies(servers: ServerConfig[]): ServerConfig[] {\n const byId = new Map(servers.map(server => [server.id, server]))\n const ordered: ServerConfig[] = []\n const visited = new Set<string>()\n\n const visit = (server: ServerConfig): void => {\n if (visited.has(server.id))\n return\n visited.add(server.id)\n for (const dependency of server.dependsOn) {\n const target = byId.get(dependency)\n if (target && target.id !== server.id)\n visit(target)\n }\n ordered.push(server)\n }\n\n for (const server of servers) visit(server)\n return ordered\n}\n\n/**\n * The transitive dependencies of a server, **deepest first** — the order they have to be started in, so\n * every dependency is up before something that depends on it.\n *\n * A dependency is pushed *after* its own dependencies are walked, which is what makes that hold. Pushing\n * it before (the shape this used to have) yielded a list that was not topological: for\n * `a -> [b, c], b -> [x], c -> [b]` it returned `[b, x, c]`, where `b` precedes `x` even though `b`\n * depends on `x` — so `startDependencies` started `b` without `x` running and awaited a readiness that\n * could not arrive.\n */\nexport function dependenciesOf(server: ServerConfig, servers: ServerConfig[]): ServerConfig[] {\n const byId = new Map(servers.map(entry => [entry.id, entry]))\n const found: ServerConfig[] = []\n const seen = new Set<string>()\n\n const walk = (current: ServerConfig): void => {\n for (const dependency of current.dependsOn) {\n if (seen.has(dependency))\n continue\n seen.add(dependency)\n const target = byId.get(dependency)\n // The walk starts at `server`, so a cycle leads back to it — and a config may name it\n // directly (`a -> a`). Either way it is not its own dependency: `startDependencies` would\n // find `this.entries.get(that.id)` to be the entry it is starting, log\n // `starting dependency \"a\" first`, and then wait the full `health.startTimeoutMs`\n // (20 s by default) for the entry that is itself still starting. A cycle is a warning,\n // not a refusal (`validateCrossField`), so it does reach here.\n if (!target || target.id === server.id)\n continue\n walk(target)\n found.push(target)\n }\n }\n\n walk(server)\n return found\n}\n\n/** Dependents that must stop before this server does. */\nexport function dependentsOf(server: ServerConfig, servers: ServerConfig[]): ServerConfig[] {\n return servers.filter(entry => entry.id !== server.id && dependenciesOf(entry, servers).some(d => d.id === server.id))\n}\n","import type { ChildProcess } from 'node:child_process'\nimport type { Entry, ResolvedSpawn, SupervisorContext } from '#src/services/supervisor/entry'\nimport { spawn } from 'node:child_process'\nimport path from 'node:path'\nimport process from 'node:process'\nimport { expandEnvList, expandEnvRecord, loadEnvFile, resolveEnvFilePath } from '#src/helpers/env-file'\nimport { projectDir } from '#src/helpers/paths'\nimport { resolveRecord, resolveTemplates } from '#src/helpers/template'\nimport { composeTarget } from '#src/providers/docker'\nimport { resolveCommand, resolveCwd } from '#src/providers/process'\nimport { serverTemplateVars } from '#src/providers/server-vars'\nimport { LineSplitter } from '#src/services/log-buffer'\n\n/**\n * Everything `spawn` needs for an entry. The preflight recognizes the entry's own detached successor\n * by this argv too, so spawn and identification must never resolve it with two different rules.\n */\nexport function resolveSpawn(ctx: SupervisorContext, entry: Entry): ResolvedSpawn {\n const vars = serverTemplateVars(entry.config)\n const cwd = resolveCwd(entry.config.cwd)\n const command = resolveCommand(entry.config.command, cwd, projectDir)\n\n // A machine-local env file layers over the tracked config and feeds `${VAR}`, so secrets stay out of it.\n let fileEnv: Record<string, string> = {}\n if (entry.config.envFile.length > 0) {\n const file = resolveEnvFilePath(entry.config.envFile, cwd)\n const loaded = loadEnvFile(file)\n if (loaded.error !== null)\n ctx.log(entry, 'system', `env file ${file} could not be read: ${loaded.error}`)\n else if (Object.keys(loaded.env).length > 0)\n ctx.log(entry, 'system', `env file ${file} (${Object.keys(loaded.env).length} vars)`)\n fileEnv = loaded.env\n }\n\n const expansionVars: Record<string, string | undefined> = { ...process.env, ...fileEnv }\n const dataEnvs = resolveRecord(entry.config.dataEnvs, vars)\n const env: Record<string, string> = {\n // `envFile` is the machine-local layer, so it overrides the tracked `env`.\n ...expandEnvRecord(resolveRecord(entry.config.env, vars), expansionVars),\n ...fileEnv,\n // Data envs win: their value is the directory that gets backed up.\n ...expandEnvRecord(dataEnvs, expansionVars),\n HHOSTED_SERVER_ID: entry.config.id,\n HHOSTED_CONTROL_PORT: String(ctx.options.control.port),\n }\n // One absolute native path, so Windows never hands the process a mixed `D:\\…\\app/data`.\n for (const key of Object.keys(dataEnvs))\n env[key] = path.resolve(cwd, env[key]!)\n\n // `spawn` throws on an env key containing a NUL (from an envFile line or a JSON `\\u0000`); drop the key.\n for (const key of Object.keys(env)) {\n if (!key.includes('\\0'))\n continue\n delete env[key]\n ctx.log(entry, 'system', 'ignored an environment key containing a null byte')\n }\n\n const args = expandEnvList(resolveTemplates(entry.config.args, vars), expansionVars)\n\n return {\n command,\n args,\n env,\n cwd,\n // Logged *before* `${VAR}` expansion, so a secret argument never reaches logs, SSE or chat.\n loggedArgs: resolveTemplates(entry.config.args, vars),\n }\n}\n\n/**\n * Whether this entry runs a compose stack, read from what it would actually spawn. `null` is the\n * common case; a shell that happens to run docker is not detectable, and guessing would attribute a\n * stranger's containers (limits in `src/providers/docker.ts`).\n */\nexport function detectCompose(entry: Entry, resolved: ResolvedSpawn): void {\n entry.compose = composeTarget({ command: resolved.command, args: resolved.args, cwd: resolved.cwd, env: resolved.env })\n}\n\nexport function killBootstrap(entry: Entry): void {\n try {\n entry.bootstrapChild?.kill('SIGKILL')\n }\n catch {\n // already gone\n }\n}\n\n/** Runs the entry's bootstrap, best-effort: a failure is logged and the start carries on. */\nexport async function runBootstrap(ctx: SupervisorContext, entry: Entry, current: () => boolean): Promise<void> {\n const spec = entry.config.bootstrap\n if (!spec || (spec.runOnce && entry.bootstrapDone))\n return\n\n const vars = serverTemplateVars(entry.config)\n const cwd = resolveCwd(entry.config.cwd)\n const args = resolveTemplates(spec.args, vars)\n ctx.log(entry, 'system', `bootstrap: ${spec.command} ${args.join(' ')}`)\n\n const splitter = new LineSplitter((_stream, text) => {\n if (text.trim().length > 0)\n ctx.log(entry, 'system', `[bootstrap] ${text}`)\n })\n\n // `spawn` throws synchronously for an unusable command (empty, a NUL, a cwd through a file); escaping\n // would leave the entry wedged in `starting`.\n let child: ChildProcess\n try {\n child = spawn(resolveCommand(spec.command, cwd, projectDir), args, {\n cwd,\n env: { ...process.env, ...resolveRecord(spec.env, vars) },\n stdio: ['ignore', 'pipe', 'pipe'],\n windowsHide: true,\n })\n }\n catch (error) {\n ctx.log(entry, 'system', `bootstrap could not start: ${(error as Error).message} — continuing anyway`)\n entry.bootstrapDone = true\n ctx.persist(entry)\n return\n }\n child.stdout?.on('data', chunk => splitter.push('stdout', chunk))\n child.stderr?.on('data', chunk => splitter.push('stderr', chunk))\n entry.bootstrapChild = child\n\n const code = await new Promise<number | null>((resolve) => {\n const timer = setTimeout(() => {\n ctx.log(entry, 'system', `bootstrap timed out after ${spec.timeoutMs}ms`)\n try {\n child.kill('SIGKILL')\n }\n catch {\n // already gone\n }\n }, spec.timeoutMs)\n child.once('exit', (exitCode) => {\n clearTimeout(timer)\n resolve(exitCode)\n })\n child.once('error', (error) => {\n clearTimeout(timer)\n ctx.log(entry, 'system', `bootstrap failed: ${(error as Error).message}`)\n resolve(null)\n })\n })\n entry.bootstrapChild = null\n\n // Cut short by a stop: it did not finish, so a `runOnce` bootstrap is still owed.\n if (!current()) {\n ctx.log(entry, 'system', 'bootstrap stopped')\n return\n }\n entry.bootstrapDone = true\n ctx.persist(entry)\n if (code === 0)\n ctx.log(entry, 'system', 'bootstrap finished')\n else if (code !== null)\n ctx.log(entry, 'system', `bootstrap exited with code ${code} — continuing anyway`)\n}\n","import type { Entry, SupervisorContext } from '#src/services/supervisor/entry'\nimport { isComposeCommand, stopComposeContainers } from '#src/providers/docker'\nimport { detectCompose, resolveSpawn } from '#src/services/supervisor/spawn'\n\n/**\n * Stops the running containers of a compose entry. Its server is the containers, which are not the\n * wrapper's descendants: a reboot, a `compose up -d` from a shell or a panel crash leaves them up with\n * no child to signal, and \"stopped\" would be a lie.\n *\n * `null` means \"no compose stack, or docker could not be asked\" — the caller then reports only what\n * it can see, never a stack it did not confirm is gone.\n */\nexport async function stopComposeStack(ctx: SupervisorContext, entry: Entry): Promise<{ stopped: string[], survivors: string[] } | null> {\n // An entry this panel never started has no detected target yet; resolve it rather than skip the stack.\n if (entry.compose === null && !isComposeCommand(entry.config.command, entry.config.args))\n return null\n if (entry.compose === null)\n detectCompose(entry, resolveSpawn(ctx, entry))\n if (entry.compose === null)\n return null\n const outcome = await stopComposeContainers(entry.compose)\n if (outcome === null) {\n ctx.log(entry, 'system', 'docker could not be asked to stop this stack — its containers were not confirmed stopped')\n return null\n }\n if (outcome.stopped.length > 0)\n ctx.log(entry, 'system', `stopped the container${outcome.stopped.length === 1 ? '' : 's'} ${outcome.stopped.join(', ')}`)\n return outcome\n}\n\n/** Marks a stop that did not take because a container outlived it, and reports whether it happened. */\nexport function refuseLingeringStack(ctx: SupervisorContext, entry: Entry, stack: { survivors: string[] } | null): boolean {\n const survivors = stack?.survivors ?? []\n if (survivors.length === 0)\n return false\n entry.status = 'conflict'\n entry.lastError = `the stack \"${entry.config.id}\" is still running: container${survivors.length === 1 ? '' : 's'} ${survivors.join(', ')} — docker was asked to stop them and they stayed up`\n // Logged too: a pid that also survived replaces `lastError`, and the stack must stay on record.\n ctx.log(entry, 'system', entry.lastError)\n return true\n}\n","import type { ChildProcess } from 'node:child_process'\nimport type { ComposeTarget } from '#src/providers/docker'\nimport type { SpawnInfo } from '#src/providers/identity'\nimport type { ControlEndpoint } from '#src/services/control-server'\nimport type { HistoryStore } from '#src/services/history'\nimport type { LogFiles } from '#src/services/log-files'\nimport type { NotificationReason, NotificationService } from '#src/services/notifications'\nimport type { HealthState, HistoryActor, LogStream, NannyExit, PortState, ProcessResources, ServerConfig, ServerStatus, ServerView } from '#src/shared/contracts'\nimport { entryStatePath, readEntryState } from '#src/providers/entry-state'\nimport { LogBuffer } from '#src/services/log-buffer'\n\nexport interface SupervisorOptions {\n /** The workspace this supervisor supervises; every view is tagged with it. */\n workspaceId: string\n configPath: string\n /** Live listener info, mutated by the control server when it rebinds. */\n control: ControlEndpoint\n history: HistoryStore\n logFiles: LogFiles\n notifications: NotificationService\n /** Signals a state change; the panel owns and publishes the aggregate frame. */\n onStateChange: () => void\n /** Where a persistent entry's nanny keeps its state. */\n nannyDir: string\n /**\n * The *other* workspaces' running servers, so a port they hold is recognized as the panel's own.\n * The pair travels with the pid because a refusal has to say **where** the holder lives. A lone\n * supervisor (a unit harness) has no siblings.\n */\n siblingServers?: () => Promise<SiblingServer[]>\n}\n\nexport interface StartResult {\n ok: boolean\n error?: string\n}\n\n/** One running server in another workspace: the identity a cross-workspace refusal has to name. */\nexport interface SiblingServer {\n pid: number\n workspaceId: string\n serverId: string\n}\n\n/**\n * Everything a start needs, resolved once. `loggedArgs` is the argv *before* `${VAR}` expansion, so\n * a secret in an argument never reaches the log; `args` is what is spawned.\n */\nexport interface ResolvedSpawn extends SpawnInfo {\n env: Record<string, string>\n loggedArgs: string[]\n}\n\nexport interface Entry {\n config: ServerConfig\n status: ServerStatus\n health: HealthState\n portState: PortState\n child: ChildProcess | null\n pid: number | null\n startedAt: number | null\n /**\n * The last non-persistent child this panel spawned — the only trace of a detached child that\n * outlived a panel killed hard. Always null for a persistent entry: its nanny's state file is the record.\n */\n lastChild: { pid: number, startedAt: number } | null\n exitCode: number | null\n exitSignal: string | null\n restarts: number\n /** Force restarts spent on the current unhealthy sequence, bounded by `restart.maxRetries`. */\n healthRestarts: number\n lastError: string | null\n nextRetryAt: number | null\n retryTimer: NodeJS.Timeout | null\n healthFailures: number\n unhealthySince: number | null\n /**\n * A force restart whose outcome is still owed, with its cause. Remembered rather than inferred from\n * `health`, because the restart resets health and the `unhealthy -> healthy` transition never happens.\n */\n pendingRestart: { cause: string } | null\n lastProbeAt: number\n lastOccupancyProbeAt: number\n probing: boolean\n /** The running process is a detached successor we adopted, not a child we spawned. */\n adopted: boolean\n /** The panel stopped this entry because it could not serve — not the operator. */\n stoppedByPanel: boolean\n /** How a persistent entry's child ended, read from its nanny's state file. */\n nannyExit: NannyExit | null\n /** A start is in flight (set synchronously, unlike `status`). */\n starting: boolean\n stopping: boolean\n /**\n * Bumped by every stop and by the end of every run, so a start or a probe that awaited across one\n * can tell its work no longer belongs to the entry.\n */\n runToken: number\n /** The start in flight, which a stop waits out once it has cancelled it. */\n startTask: Promise<StartResult> | null\n /**\n * The stop in flight. Two stops on one entry join this instead of each running a tail — a second\n * tail would clear `stopping` mid-teardown and publish `stopped` over a start it never saw.\n */\n stopTask: Promise<StartResult> | null\n bootstrapChild: ChildProcess | null\n /** Who asked for the start in flight, recorded on its history event. */\n actor: HistoryActor\n /** The config dropped this entry: the stop that follows must not recreate its reclaimed logs or history. */\n removed: boolean\n bootstrapDone: boolean\n /** A staged dump this entry still has to load, run once its process is answering. */\n pendingLoad: string | null\n /** A load is running right now, so a second `start` must not run it again. */\n loadingPending: boolean\n logs: LogBuffer\n /** Lines this panel wrote into a persistent entry's log file, so the relay does not push them twice. */\n echoed: Set<string>\n responseMs: number | null\n resources: ProcessResources | null\n resourcesSampledAt: number\n /** The compose project this entry runs, detected once at start; `null` means \"sample the process tree\". */\n compose: ComposeTarget | null\n historyCache: { revision: number, at: number, summary: ServerView['history'] } | null\n}\n\n/** What the extracted modules need from the supervisor that owns an entry. */\nexport interface SupervisorContext {\n readonly options: SupervisorOptions\n log: (entry: Entry, stream: LogStream, text: string) => void\n publishServer: (entry: Entry) => void\n persist: (entry: Entry) => void\n notify: (entry: Entry, reason: NotificationReason, detail: string) => void\n}\n\nexport function delay(ms: number): Promise<void> {\n return new Promise(resolve => setTimeout(resolve, ms))\n}\n\nexport function createEntry(config: ServerConfig, nannyDir: string): Entry {\n // The retry budget, the bootstrap flag and the last child must outlive the panel: in memory alone a\n // crash loop got a fresh budget on every boot, and a detached child that survived became a twin.\n const persisted = readEntryState(entryStatePath(nannyDir, config.id))\n const lastPid = persisted?.lastPid ?? null\n return {\n config,\n status: 'stopped',\n health: config.health.enabled ? 'unknown' : 'disabled',\n portState: 'unknown',\n child: null,\n pid: null,\n startedAt: null,\n lastChild: !config.persistent && lastPid !== null ? { pid: lastPid, startedAt: persisted?.lastStartedAt ?? 0 } : null,\n exitCode: null,\n exitSignal: null,\n restarts: persisted?.restarts ?? 0,\n healthRestarts: persisted?.healthRestarts ?? 0,\n lastError: null,\n nextRetryAt: null,\n retryTimer: null,\n healthFailures: 0,\n unhealthySince: null,\n pendingRestart: null,\n lastProbeAt: 0,\n lastOccupancyProbeAt: 0,\n probing: false,\n adopted: false,\n stoppedByPanel: false,\n nannyExit: null,\n starting: false,\n stopping: false,\n runToken: 0,\n startTask: null,\n stopTask: null,\n bootstrapChild: null,\n actor: 'policy',\n removed: false,\n bootstrapDone: persisted?.bootstrapDone ?? !config.bootstrap,\n pendingLoad: persisted?.pendingLoad ?? null,\n loadingPending: false,\n logs: new LogBuffer(config.logBufferLines),\n echoed: new Set(),\n responseMs: null,\n resources: null,\n resourcesSampledAt: 0,\n compose: null,\n historyCache: null,\n }\n}\n\nexport function isActive(entry: Entry): boolean {\n // An adopted successor has no child of ours but is running; disabling it must still stop it.\n return entry.child !== null || entry.pid !== null || entry.adopted || entry.status === 'backoff'\n}\n","import type { HttpCheckConfig } from '#src/shared/contracts'\nimport { Buffer } from 'node:buffer'\nimport http from 'node:http'\nimport https from 'node:https'\nimport { probePort } from '#src/providers/port'\nimport { errorMessage } from '#src/shared/error-message'\n\nexport interface HealthProbeResult {\n healthy: boolean\n ms: number\n detail: string\n}\n\n/** TCP connect timing, used for the default `port` mode and readiness. */\nexport async function probeTcp(host: string, port: number, timeoutMs: number): Promise<HealthProbeResult> {\n const started = Date.now()\n const accepting = await probePort(host, port, timeoutMs)\n const ms = Date.now() - started\n return { healthy: accepting, ms, detail: accepting ? 'port accepted a connection' : 'port did not accept a connection' }\n}\n\nexport interface HttpProbeOptions extends Pick<HttpCheckConfig, 'scheme' | 'allowInvalidCert' | 'path' | 'method' | 'expectBody' | 'expectStatusBelow'> {\n /** `null` counts as \"not set\", so a value saved by the UI can be cleared again. */\n expectStatus?: number | null\n timeoutMs: number\n}\n\n/**\n * How much of a response body a probe will read.\n *\n * A probe asserts `expectStatus` and a substring; neither needs the whole document. The cap is\n * also a safety property, not just an allocation one: `http.request`'s `timeout` is an **idle**\n * timeout, so an endpoint that keeps streaming never trips it, and an unbounded `+=` on the\n * chunks grew until V8 threw `RangeError: Invalid string length` **inside the data handler** —\n * which kills the panel rather than failing one probe. Measured against a stream that writes\n * 64 KB every millisecond.\n */\nconst MAX_BODY_BYTES = 1_000_000\n\n/**\n * One request/response, capped at `timeoutMs` and `MAX_BODY_BYTES`.\n *\n * Node's `fetch` cannot be told to accept a certificate it does not trust, which is the normal\n * case for a backend on a home network: its own self-signed pair, or one from the engine's local\n * CA. So this speaks http/https directly, the same way `helpers/daemon.ts` reaches a panel with an\n * uploaded pair. A `HEAD` gets no body, which the caller already accounts for.\n */\nfunction request(\n url: URL,\n method: 'GET' | 'HEAD',\n allowInvalidCert: boolean,\n timeoutMs: number,\n): Promise<{ status: number, body: string, truncated: boolean }> {\n return new Promise((resolve, reject) => {\n const secure = url.protocol === 'https:'\n // `req` is assigned below; the deadline and the settle wrappers close over it, which is why\n // the request is created before any of them can run.\n let req: http.ClientRequest\n // Every path settles through these, so the deadline is always cleared and a second\n // settlement — a `timeout` after the deadline fired, a `destroy()` error after the cap —\n // is dropped instead of escaping as an unhandled rejection.\n let settled = false\n let deadline: NodeJS.Timeout\n const finish = (value: { status: number, body: string, truncated: boolean }): void => {\n if (settled)\n return\n settled = true\n clearTimeout(deadline)\n resolve(value)\n }\n const fail = (error: unknown): void => {\n if (settled)\n return\n settled = true\n clearTimeout(deadline)\n reject(error instanceof Error ? error : new Error(String(error)))\n }\n\n /**\n * The whole exchange, not just the socket.\n *\n * `timeout` on the request is an **idle** timeout, so a server dripping one byte every half\n * second keeps resetting it and the probe never returns — which hangs the supervisor's tick,\n * since the probe is awaited. The old `fetch` path had `AbortSignal.timeout`, an absolute\n * cap; this restores that guarantee.\n */\n deadline = setTimeout(() => {\n fail(new Error(`no complete response within ${timeoutMs}ms`))\n req.destroy()\n }, timeoutMs)\n deadline.unref()\n\n req = (secure ? https : http).request({\n hostname: url.hostname,\n port: url.port,\n path: `${url.pathname}${url.search}`,\n method,\n // Local and explicit: the operator asked the panel to trust this backend.\n ...(secure && allowInvalidCert ? { rejectUnauthorized: false } : {}),\n timeout: timeoutMs,\n }, (response) => {\n let body = ''\n let bytes = 0\n let truncated = false\n response.setEncoding('utf8')\n response.on('data', (chunk: string) => {\n if (truncated)\n return\n bytes += Buffer.byteLength(chunk)\n if (bytes > MAX_BODY_BYTES) {\n // Stop reading rather than accumulate: the assertion runs against this prefix, and\n // the detail says so instead of reporting a silent pass.\n truncated = true\n body += chunk.slice(0, Math.max(0, MAX_BODY_BYTES - (bytes - Buffer.byteLength(chunk))))\n response.destroy()\n finish({ status: response.statusCode ?? 0, body, truncated })\n return\n }\n body += chunk\n })\n response.once('end', () => {\n if (!truncated)\n finish({ status: response.statusCode ?? 0, body, truncated })\n })\n response.once('error', (error) => {\n // A `destroy()` after the cap surfaces here; the resolution above already happened.\n if (!truncated)\n fail(error)\n })\n })\n\n // The deadline above outlives these handlers, so a late error after it fired is ignored by\n // the already-settled promise rather than escaping as an unhandled rejection.\n req.once('error', error => fail(error))\n // Catches a socket that goes idle before the headers arrive, sooner than the deadline.\n req.once('timeout', () => {\n fail(new Error(`no response within ${timeoutMs}ms`))\n req.destroy()\n })\n req.end()\n })\n}\n\n/**\n * Fetches the configured path and asserts the response, so \"listening\" is not\n * mistaken for \"working\".\n */\nexport async function probeHttp(host: string, port: number, options: HttpProbeOptions): Promise<HealthProbeResult> {\n const started = Date.now()\n\n try {\n // Inside the `try`: a host the URL parser refuses must be a failed probe, not a throw out\n // of the probe and into the supervisor's tick.\n const url = new URL(`${options.scheme}://${host}:${port}${options.path.startsWith('/') ? options.path : `/${options.path}`}`)\n const response = await request(url, options.method, options.allowInvalidCert, options.timeoutMs)\n const ms = Date.now() - started\n\n const expected = options.expectStatus ?? null\n if (expected !== null && response.status !== expected) {\n return { healthy: false, ms, detail: `expected status ${expected}, got ${response.status}` }\n }\n if (expected === null && response.status >= options.expectStatusBelow) {\n return { healthy: false, ms, detail: `status ${response.status} is >= ${options.expectStatusBelow}` }\n }\n\n // A `HEAD` cannot carry a body, so a configured body requirement is skipped — said in the detail\n // rather than passed over in silence. The card and the log read this line, and `HTTP 200` looked\n // identical whether or not the assertion ran; the config parser also warns at load.\n const bodySkipped = options.expectBody.length > 0 && options.method === 'HEAD'\n if (options.expectBody.length > 0 && !bodySkipped) {\n if (!response.body.includes(options.expectBody)) {\n const scope = response.truncated ? ` (only the first ${MAX_BODY_BYTES} bytes were read)` : ''\n return { healthy: false, ms, detail: `body does not contain ${JSON.stringify(options.expectBody)}${scope}` }\n }\n }\n\n if (bodySkipped)\n return { healthy: true, ms, detail: `HTTP ${response.status} (a HEAD carries no body, so the body check was skipped)` }\n\n return { healthy: true, ms, detail: `HTTP ${response.status}` }\n }\n catch (error) {\n const ms = Date.now() - started\n const reason = errorMessage(error)\n return { healthy: false, ms, detail: `request failed: ${reason}` }\n }\n}\n\nexport async function probeHealth(options: {\n mode: 'port' | 'http'\n hosts: string[]\n port: number\n timeoutMs: number\n http: Pick<HttpCheckConfig, 'scheme' | 'allowInvalidCert' | 'path' | 'method' | 'expectBody' | 'expectStatusBelow'> & { expectStatus?: number | null }\n}): Promise<HealthProbeResult> {\n let last: HealthProbeResult = { healthy: false, ms: 0, detail: 'not probed' }\n\n // Try each candidate host in order (loopback first), so a server bound to one\n // specific address is still probed somewhere it actually listens.\n for (const host of options.hosts) {\n const result = options.mode === 'http'\n ? await probeHttp(host, options.port, { ...options.http, timeoutMs: options.timeoutMs })\n : await probeTcp(host, options.port, options.timeoutMs)\n if (result.healthy)\n return result\n last = result\n }\n\n return last\n}\n","import type { Entry, ResolvedSpawn, SiblingServer, SupervisorContext } from '#src/services/supervisor/entry'\nimport type { FreePortResult } from '#src/shared/contracts'\nimport process from 'node:process'\nimport { bindHost, lanAddress } from '#src/helpers/bind'\nimport { isOwnStack } from '#src/providers/docker'\nimport { identifyHolders } from '#src/providers/identity'\nimport { findDockerPortHolder, isPortFree, listPortHolders, probePort, releaseDockerPort, terminatePids } from '#src/providers/port'\nimport { processTreeOwners } from '#src/providers/proc'\nimport { delay } from '#src/services/supervisor/entry'\n\nconst PORT_RELEASE_RECHECK_MS = 300\n\n/** What the port preflight found: nothing in the way, our own successor, or a blocker. */\nexport type PreflightConflict\n = | { kind: 'free' }\n | { kind: 'adopt', pid: number }\n | { kind: 'blocked', error: string }\n\n/** Pids this panel owns, and the `workspace/id` behind each, which a refusal names. */\nexport interface SupervisedPids {\n pids: Set<number>\n owners: Map<number, string>\n}\n\nexport interface PortContext extends SupervisorContext {\n supervisedPids: () => Promise<SupervisedPids>\n resolveSpawn: (entry: Entry) => ResolvedSpawn\n}\n\n/**\n * The whole process *tree* of every entry, plus the panel itself. A persistent entry's server is a\n * nanny's child and a wrapper's is one generation down, so a descendant mistaken for a stranger is\n * one `free-port` away from being killed. Sibling workspaces' roots join before the walk so their\n * descendants are covered by the same rule. The panel's own tree is *not* walked: \"ours\" must mean a\n * process a server owns.\n */\nexport async function supervisedPids(\n workspaceId: string,\n entries: Iterable<Entry>,\n siblingServers: (() => Promise<SiblingServer[]>) | undefined,\n): Promise<SupervisedPids> {\n const roots: number[] = []\n const labels = new Map<number, string>()\n const own = (pid: number, label: string): void => {\n roots.push(pid)\n if (!labels.has(pid))\n labels.set(pid, label)\n }\n for (const entry of entries) {\n if (entry.pid !== null)\n own(entry.pid, `${workspaceId}/${entry.config.id}`)\n else if (entry.child?.pid !== undefined)\n own(entry.child.pid, `${workspaceId}/${entry.config.id}`)\n }\n\n const siblings = [...await siblingServers?.() ?? []]\n for (const sibling of siblings)\n own(sibling.pid, `${sibling.workspaceId}/${sibling.serverId}`)\n\n const tree = await processTreeOwners(roots)\n const owners = new Map<number, string>()\n for (const [pid, root] of tree) {\n const label = labels.get(root)\n if (label !== undefined)\n owners.set(pid, label)\n }\n tree.set(process.pid, process.pid)\n return { pids: new Set(tree.keys()), owners }\n}\n\n/**\n * Where a port can be observed for this entry: a specific bind is not reachable on loopback, and a\n * `lan` bind is reachable on loopback *and* the LAN address.\n */\nexport function occupancyHosts(entry: Entry): string[] {\n const configured = bindHost(entry.config.bind)\n const candidates = configured === '0.0.0.0'\n ? ['127.0.0.1', lanAddress() ?? '127.0.0.1']\n : [configured, '127.0.0.1']\n return [...new Set(candidates)]\n}\n\n/** True when the port accepts a connection on any of the entry's addresses. */\nexport async function portAccepts(entry: Entry, port: number, timeoutMs: number): Promise<boolean> {\n const results = await Promise.all(occupancyHosts(entry).map(host => probePort(host, port, timeoutMs)))\n return results.some(Boolean)\n}\n\n/** Whether the port is free on all of the entry's addresses. */\nfunction portFreeOnAll(entry: Entry, port: number): () => Promise<boolean> {\n const hosts = occupancyHosts(entry)\n return async () => {\n const results = await Promise.all(hosts.map(host => isPortFree(port, host)))\n return results.every(Boolean)\n }\n}\n\n/** The port's own answer, with one short recheck: a just-closed listener can still complete a handshake. */\nasync function waitForPortRelease(entry: Entry, port: number): Promise<boolean> {\n if (await portFreeOnAll(entry, port)())\n return true\n await delay(PORT_RELEASE_RECHECK_MS)\n return portFreeOnAll(entry, port)()\n}\n\n/** Splits the port's listeners into ours and everyone else; only the foreign half may be signalled. */\nasync function portHolders(ctx: PortContext, port: number): Promise<{ ours: number[], foreign: number[], owners: Map<number, string> }> {\n const { pids: supervised, owners } = await ctx.supervisedPids()\n const holders = await listPortHolders(port)\n return {\n ours: holders.filter(pid => supervised.has(pid)),\n foreign: holders.filter(pid => !supervised.has(pid)),\n owners,\n }\n}\n\n/** A refused port names the holder **and the server that owns it**, or \"stop that server\" is not actionable. */\nfunction heldByOurs(port: number, ours: number[], owners: Map<number, string>): string {\n const named = [...new Set(ours.map(pid => owners.get(pid)).filter((owner): owner is string => owner !== undefined))]\n const place = named.length === 0 ? '' : ` on ${named.join(', ')}`\n return `port ${port} is held by pid ${ours.join(', ')}, which this panel supervises${place} — stop that server instead`\n}\n\n/**\n * The holder that is this entry's own detached successor. The env marker decides where the platform\n * can read it; otherwise the entry's argv. Two candidates means we do not know which is ours, so neither.\n */\nasync function ownPortHolder(ctx: PortContext, entry: Entry, holders: number[]): Promise<number | null> {\n const candidates = await identifyHolders(entry.config.id, ctx.resolveSpawn(entry), holders)\n if (candidates.length > 1) {\n ctx.log(entry, 'system', `pid ${candidates.join(', ')} all look like this entry: refusing to guess which is ours, set onPortConflict to \"kill\" to clear the port anyway`)\n return null\n }\n return candidates[0] ?? null\n}\n\n/** The port is free again: a `conflict` it caused clears with it. */\nfunction markPortFreed(ctx: PortContext, entry: Entry, message: string): void {\n if (entry.status === 'conflict') {\n entry.status = 'stopped'\n entry.lastError = null\n }\n entry.portState = 'free'\n ctx.log(entry, 'system', message)\n ctx.publishServer(entry)\n}\n\n/**\n * Frees the port this entry wants. Holders are listed fresh here, never taken from a message, and a\n * listener this panel supervises is refused rather than killed.\n */\nexport async function freePort(ctx: PortContext, entry: Entry): Promise<FreePortResult & { error?: string }> {\n const id = entry.config.id\n const empty: FreePortResult & { error?: string } = { ok: false, port: null, terminated: [], forced: [], skipped: [], free: false }\n const port = entry.config.port\n if (port === null)\n return { ...empty, error: `server \"${id}\" has no port configured` }\n if (entry.starting || entry.stopping)\n return { ...empty, port, error: `server \"${id}\" is busy — try again in a moment` }\n\n const { ours, foreign, owners } = await portHolders(ctx, port)\n const holders = [...ours, ...foreign]\n\n if (holders.length === 0) {\n // An empty pid list is not a free port: docker publishes through a root-owned proxy this user\n // cannot list, but the container can still be stopped through docker.\n const docker = await findDockerPortHolder(port)\n if (docker !== null) {\n ctx.log(entry, 'system', `freeing port ${port}: stopping the docker container \"${docker.container}\"`)\n const released = await releaseDockerPort(docker)\n const free = released && await waitForPortRelease(entry, port)\n if (free) {\n markPortFreed(ctx, entry, `port ${port} is free (stopped the docker container \"${docker.container}\")`)\n return { ...empty, ok: true, port, terminated: [], forced: [], skipped: [], free: true }\n }\n return {\n ...empty,\n port,\n error: `docker could not stop the container \"${docker.container}\" publishing port ${port} — check \\`docker logs ${docker.container}\\``,\n }\n }\n // A listener this user cannot inspect looks exactly like no listener, so probe before calling it idle.\n if (!(await waitForPortRelease(entry, port))) {\n return {\n ...empty,\n port,\n error: `port ${port} is still in use, but no listener could be attributed to it — this user cannot inspect that socket, so it cannot be freed from here`,\n }\n }\n return { ...empty, port, error: `nothing is listening on port ${port} any more` }\n }\n if (foreign.length === 0) {\n return { ...empty, port, error: heldByOurs(port, ours, owners), skipped: ours }\n }\n\n ctx.log(entry, 'system', `freeing port ${port}: asking pid ${foreign.join(', ')} to stop`)\n const { stopped, forced } = await terminatePids(foreign, { graceMs: entry.config.stop.graceMs })\n if (forced.length > 0)\n ctx.log(entry, 'system', `pid ${forced.join(', ')} ignored SIGTERM and was killed`)\n\n // A held socket can take a moment to go away, so the port decides the outcome.\n const free = await waitForPortRelease(entry, port)\n if (free) {\n markPortFreed(ctx, entry, `port ${port} is free${ours.length > 0 ? ` (pid ${ours.join(', ')} left untouched)` : ''}`)\n }\n else {\n entry.lastError = `port ${port} is still in use after killing pid ${foreign.join(', ')}`\n ctx.log(entry, 'system', entry.lastError)\n ctx.publishServer(entry)\n }\n\n return { ok: true, port, terminated: stopped, forced, skipped: ours, free }\n}\n\nfunction blocked(ctx: PortContext, entry: Entry, error: string, logLine?: string): PreflightConflict {\n entry.status = 'conflict'\n entry.lastError = error\n if (logLine !== undefined)\n ctx.log(entry, 'system', logLine)\n ctx.publishServer(entry)\n return { kind: 'blocked', error }\n}\n\n/** Decides what the entry's port allows before a spawn, applying `onPortConflict`. */\nexport async function preflight(ctx: PortContext, entry: Entry): Promise<PreflightConflict> {\n const port = entry.config.port\n if (port === null)\n return { kind: 'free' }\n\n // A busy-looking port gets a second look: a just-closed listener is the window a fast restart lands in.\n const freeOnAll = portFreeOnAll(entry, port)\n let free = await freeOnAll()\n if (!free) {\n await delay(PORT_RELEASE_RECHECK_MS)\n free = await freeOnAll()\n }\n\n entry.portState = free ? 'free' : 'in-use'\n if (free)\n return { kind: 'free' }\n\n // The supervised half is never a target; the foreign half is where our own detached successor hides.\n const { ours, foreign, owners } = await portHolders(ctx, port)\n const holders = [...ours, ...foreign]\n const own = await ownPortHolder(ctx, entry, foreign)\n // No listed pid may still be a docker-published port; name the container instead.\n const docker = holders.length === 0 ? await findDockerPortHolder(port) : null\n const suffix = holders.length > 0\n ? ` (pid ${holders.join(', ')})`\n : docker === null ? '' : ` (published by the docker container \"${docker.container}\")`\n\n // `kill` takes the port from anyone — our own successor included — but never from our own tree.\n if (entry.config.onPortConflict === 'kill') {\n if (ours.length > 0) {\n const error = heldByOurs(port, ours, owners)\n return blocked(ctx, entry, error, `${error} — not starting (onPortConflict: kill)`)\n }\n\n if (foreign.length === 0) {\n if (docker !== null) {\n ctx.log(entry, 'system', `port ${port} is published by the docker container \"${docker.container}\" — onPortConflict: kill, stopping it`)\n if (await releaseDockerPort(docker) && await waitForPortRelease(entry, port))\n return { kind: 'free' }\n return blocked(ctx, entry, `docker could not stop the container \"${docker.container}\" publishing port ${port}`)\n }\n ctx.log(entry, 'system', `port ${port} looks busy but no listener could be found — starting anyway`)\n return { kind: 'free' }\n }\n\n ctx.log(entry, 'system', `port ${port} is held by pid ${foreign.join(', ')} — onPortConflict: kill, stopping the holder`)\n return await stopPortHolders(ctx, entry, foreign, port, 'killing', freeOnAll)\n }\n\n // `follow` keeps a detached restart of this server; `reclaim` replaces it with a supervised one.\n if (own !== null && entry.config.onPortConflict === 'follow')\n return { kind: 'adopt', pid: own }\n\n if (own !== null && entry.config.onPortConflict === 'reclaim') {\n ctx.log(entry, 'system', `port ${port} is held by pid ${own}, a detached restart of this entry — replacing it with a supervised process`)\n return await stopPortHolders(ctx, entry, [own], port, 'replacing', freeOnAll)\n }\n\n // This entry's own compose stack already serving is not a stranger: offer `warn` to attach to it.\n const ownStack = isOwnStack(docker ?? { project: null, composeDir: null }, entry.compose)\n const hint = ownStack\n ? ` — this is this entry's own stack, already up: set onPortConflict to \"warn\" to attach to it`\n : own !== null\n ? ` — pid ${own} is a detached restart of this entry: set onPortConflict to \"follow\" to adopt it, \"reclaim\" to replace it with a supervised process, or \"kill\" to stop whatever holds the port`\n : docker === null\n ? ''\n : ` — it is published by a docker container, which \\`kill\\` stops through docker; \\`block\\` and \\`warn\\` leave it alone`\n // A holder another of our servers owns gets its own sentence, naming where it lives.\n const blockedError = ours.length > 0\n ? heldByOurs(port, ours, owners)\n : `port ${port} is already in use${suffix}${hint}`\n\n // `follow` and `reclaim` refine `block`: never a stranger's port.\n if (entry.config.onPortConflict !== 'warn')\n return blocked(ctx, entry, blockedError, `${blockedError} — not starting (onPortConflict: ${entry.config.onPortConflict})`)\n\n ctx.log(entry, 'system', `warning: ${blockedError} — starting anyway`)\n return { kind: 'free' }\n}\n\n/**\n * Stops the listed holders and reports whether the port came free. `kill` and `reclaim` share it so\n * neither can spawn onto a listener that is still there.\n */\nasync function stopPortHolders(ctx: PortContext, entry: Entry, pids: number[], port: number, word: string, freeOnAll: () => Promise<boolean>): Promise<PreflightConflict> {\n const { forced } = await terminatePids(pids, { graceMs: entry.config.stop.graceMs })\n if (forced.length > 0)\n ctx.log(entry, 'system', `pid ${forced.join(', ')} ignored SIGTERM and was killed`)\n\n await delay(PORT_RELEASE_RECHECK_MS)\n if (await freeOnAll()) {\n entry.portState = 'free'\n return { kind: 'free' }\n }\n const error = `port ${port} is still in use after ${word} pid ${pids.join(', ')}`\n return blocked(ctx, entry, error, error)\n}\n","import type { ChildProcess } from 'node:child_process'\nimport type { DockerMetrics } from '#src/providers/docker'\nimport type { ProcessSampler } from '#src/providers/proc'\nimport type { Entry, StartResult, SupervisorContext } from '#src/services/supervisor/entry'\nimport type { HealthState } from '#src/shared/contracts'\nimport { displayHost } from '#src/helpers/bind'\nimport { probeHealth } from '#src/providers/health-check'\nimport { delay } from '#src/services/supervisor/entry'\nimport { portAccepts } from '#src/services/supervisor/port-preflight'\n\nconst PORT_STATE_INTERVAL_MS = 10000\nconst RESOURCE_SAMPLE_INTERVAL_MS = 5000\n\nexport interface HealthContext extends SupervisorContext {\n isDisposed: () => boolean\n restart: (id: string) => Promise<StartResult>\n stopEntry: (entry: Entry) => Promise<StartResult>\n}\n\n/**\n * The health state, together with the streak that produced it. `healthFailures` and `unhealthySince`\n * describe one process's run, so anything other than `unhealthy` ends the streak — a caller that set\n * one and forgot the other left a duration counting while nothing was measured.\n */\nexport function setHealth(entry: Entry, health: HealthState): void {\n entry.health = health\n if (health !== 'unhealthy')\n endHealthStreak(entry)\n}\n\n/** Forgets the streak without deciding the verdict: a refused stop keeps its `conflict` outcome. */\nexport function endHealthStreak(entry: Entry): void {\n entry.healthFailures = 0\n entry.unhealthySince = null\n}\n\n/** The health of an entry nothing is probing: `disabled` with the probe off, else `unknown`. */\nexport function resetHealth(entry: Entry): void {\n setHealth(entry, entry.config.health.enabled ? 'unknown' : 'disabled')\n}\n\n/**\n * The measurements one process produced, dropped when that process is gone. Every path that ends a\n * run calls this — an adopted entry has no exit event, so a path that forgot left a stopped server\n * publishing live CPU, RSS and probe numbers. `adopted` goes too: there is no pid left to say it of.\n */\nexport function endProcessReadings(entry: Entry): void {\n entry.runToken += 1\n entry.pid = null\n entry.adopted = false\n entry.responseMs = null\n entry.resources = null\n}\n\n/** Loopback first, then the configured address, so a custom bind is still probed. */\nfunction probeHosts(entry: Entry): string[] {\n const primary = '127.0.0.1'\n const configured = displayHost(entry.config.bind)\n return configured === primary ? [primary] : [primary, configured]\n}\n\n/** One probe using the configured mode (TCP or HTTP), with timing. */\nasync function probeEntryHealth(entry: Entry): Promise<{ healthy: boolean, ms: number, detail: string }> {\n const { port, health } = entry.config\n if (port === null)\n return { healthy: true, ms: 0, detail: 'no port configured' }\n\n return probeHealth({\n mode: health.mode,\n hosts: probeHosts(entry),\n port,\n timeoutMs: health.timeoutMs,\n http: health.http,\n })\n}\n\n/**\n * Announces a force restart's outcome once, the first moment the entry is serving. Every \"it is up\n * again\" path calls this; the pending flag makes it idempotent.\n */\nexport function settleRestart(ctx: SupervisorContext, entry: Entry, detail: string): void {\n const pending = entry.pendingRestart\n if (pending === null)\n return\n entry.pendingRestart = null\n // The cause is repeated: chat messages arrive out of order, and \"back up\" alone says not from what.\n const message = `after ${pending.cause}: ${detail}`\n ctx.log(entry, 'system', `restarted, and it is serving again — ${message}`)\n ctx.notify(entry, 'restart-ok', message)\n}\n\n/** Moves a freshly spawned child from `starting` to `running` once its port answers (or times out). */\nexport async function awaitReadiness(ctx: HealthContext, entry: Entry, child: ChildProcess): Promise<void> {\n const { port, health } = entry.config\n\n if (port === null) {\n if (entry.child !== child || entry.status !== 'starting')\n return\n entry.status = 'running'\n setHealth(entry, health.enabled ? 'unknown' : 'disabled')\n ctx.log(entry, 'system', 'running (no port configured; readiness assumed on spawn)')\n settleRestart(ctx, entry, 'it spawned and is running')\n ctx.publishServer(entry)\n return\n }\n\n const deadline = Date.now() + health.startTimeoutMs\n while (Date.now() < deadline) {\n if (entry.child !== child || entry.status !== 'starting' || ctx.isDisposed())\n return\n if (await portAccepts(entry, port, Math.min(health.timeoutMs, 1000))) {\n entry.portState = 'in-use'\n // In `http` mode an accept is only half a probe (the server may answer 500), so health stays\n // `unknown` and the restart outcome waits for the first real probe.\n setHealth(entry, !health.enabled ? 'disabled' : health.mode === 'http' ? 'unknown' : 'healthy')\n entry.status = 'running'\n entry.lastProbeAt = 0\n ctx.log(entry, 'system', `accepting connections on port ${port}`)\n if (health.mode !== 'http')\n settleRestart(ctx, entry, `accepting connections on port ${port}`)\n ctx.publishServer(entry)\n return\n }\n await delay(300)\n }\n\n if (entry.child === child && entry.status === 'starting') {\n entry.status = 'running'\n setHealth(entry, 'unhealthy')\n entry.unhealthySince = Date.now()\n ctx.log(entry, 'system', `no connection on port ${port} after ${health.startTimeoutMs}ms — supervising anyway`)\n ctx.publishServer(entry)\n }\n}\n\n/** Port occupancy on its own slow cadence, then one health probe when it is due. */\nexport async function probeEntry(ctx: SupervisorContext, entry: Entry, now: number): Promise<void> {\n const { port, health } = entry.config\n if (port === null || entry.probing)\n return\n\n entry.probing = true\n try {\n // Occupancy is shown even while stopped, so it is not gated on the health probe's timer.\n if (now - entry.lastOccupancyProbeAt >= PORT_STATE_INTERVAL_MS) {\n const occupancyToken = entry.runToken\n entry.lastOccupancyProbeAt = now\n const accepting = await portAccepts(entry, port, health.timeoutMs)\n // The same rule the health half follows: a probe answers for the run it started in. Without\n // this, a probe launched before a stop resolved afterwards and wrote its verdict onto the\n // *next* run's port state — the card then showed \"free\" for a port the new run was serving.\n if (entry.runToken === occupancyToken && entry.config.port === port)\n entry.portState = accepting ? 'in-use' : 'free'\n }\n\n if (entry.status !== 'running' || !health.enabled)\n return\n if (now - entry.lastProbeAt < health.intervalMs)\n return\n\n const token = entry.runToken\n const probe = await probeEntryHealth(entry)\n // The run it measured ended while it was out (a stop, a restart, an exit): not this run's verdict.\n if (entry.runToken !== token || entry.status !== 'running')\n return\n entry.lastProbeAt = now\n entry.responseMs = probe.ms\n entry.portState = probe.healthy ? 'in-use' : entry.portState\n\n if (probe.healthy) {\n if (entry.health === 'unhealthy') {\n ctx.log(entry, 'system', `${probe.detail} — healthy again (${probe.ms}ms)`)\n ctx.options.history.record(entry.config.id, { type: 'recovered', detail: probe.detail })\n ctx.notify(entry, 'recovered', probe.detail)\n }\n settleRestart(ctx, entry, `${probe.detail} (${probe.ms}ms)`)\n setHealth(entry, 'healthy')\n // The budget refills after `restart.resetAfterMs` of *uptime*, not on one healthy probe — that\n // made it a per-life cap of one and the force-restart loop endless.\n const servedForMs = entry.startedAt === null ? 0 : Date.now() - entry.startedAt\n if (entry.healthRestarts > 0 && servedForMs >= entry.config.restart.resetAfterMs) {\n entry.healthRestarts = 0\n ctx.persist(entry)\n }\n return\n }\n\n entry.healthFailures += 1\n if (entry.healthFailures >= health.unhealthyThreshold) {\n if (entry.unhealthySince === null) {\n entry.unhealthySince = now\n ctx.log(entry, 'system', `unhealthy: ${probe.detail} (${entry.healthFailures} failed probes) — warning only`)\n ctx.options.history.record(entry.config.id, { type: 'unhealthy', detail: probe.detail })\n ctx.notify(entry, 'unhealthy', probe.detail)\n }\n setHealth(entry, 'unhealthy')\n }\n }\n finally {\n entry.probing = false\n }\n}\n\n/**\n * One scan of /proc covers every live server. A docker-backed entry is measured through docker\n * instead (its containers are not the wrapper's descendants), falling back to the tree sample when\n * docker has no reading.\n */\nexport async function sampleResources(entries: Iterable<Entry>, sampler: ProcessSampler, docker: DockerMetrics, now: number): Promise<void> {\n const due = [...entries].filter(entry =>\n entry.pid !== null\n && (entry.child !== null || entry.adopted)\n && now - entry.resourcesSampledAt >= RESOURCE_SAMPLE_INTERVAL_MS)\n if (due.length === 0)\n return\n\n for (const entry of due) entry.resourcesSampledAt = now\n\n const composeTargets = due.flatMap(entry => entry.compose === null ? [] : [entry.compose])\n // Once per sample: the class batches every container into one `docker stats` call.\n const containerReadings = docker.readings(composeTargets, now)\n\n try {\n const samples = await sampler.sampleMany(due.map(entry => entry.pid!))\n for (const entry of due) {\n const summed = entry.compose === null ? undefined : containerReadings.get(entry.compose.key)\n entry.resources = summed === undefined\n ? samples.get(entry.pid!) ?? null\n : { cpuPercent: summed.cpuPercent, rssBytes: summed.rssBytes, processes: summed.processes, sampledAt: now }\n }\n }\n catch {\n // Sampling is best effort; a missing /proc must not break supervision.\n }\n}\n\n/**\n * The memory ceiling, on whatever the sample carries (summed container RSS for a docker entry). It\n * asks \"is there a live process?\", not \"did we spawn it\", so an adopted successor is held to it too.\n */\nexport async function enforceMemoryLimit(ctx: HealthContext, entry: Entry): Promise<boolean> {\n const limit = entry.config.resources.maxRssBytes\n const rss = entry.resources?.rssBytes ?? null\n const live = entry.child !== null || (entry.adopted && entry.pid !== null)\n if (limit <= 0 || rss === null || !live || entry.status !== 'running' || rss <= limit)\n return false\n\n const measured = entry.compose === null ? 'process tree' : 'containers'\n const detail = `${measured} use ${Math.round(rss / 1024 / 1024)}MB, over the ${Math.round(limit / 1024 / 1024)}MB limit`\n ctx.log(entry, 'system', `${detail} — restarting`)\n ctx.options.history.record(entry.config.id, { type: 'forced-restart', detail })\n ctx.notify(entry, 'rss', detail)\n entry.pendingRestart = { cause: 'exceeding its memory limit' }\n await ctx.restart(entry.config.id)\n return true\n}\n\n/** Unhealthy for longer than `forceRestartAfterMs`; spends one unit of the health budget when it says yes. */\nexport function shouldForceRestart(ctx: SupervisorContext, entry: Entry, now: number): boolean {\n const { port, health, restart } = entry.config\n if (port === null || entry.status !== 'running' || entry.health !== 'unhealthy')\n return false\n if (entry.unhealthySince === null || health.forceRestartAfterMs <= 0)\n return false\n if (now - entry.unhealthySince < health.forceRestartAfterMs)\n return false\n\n // Same budget as crashes, separate counter. A spent budget is the tick's `healthBudgetSpent` stop.\n if (!restart.enabled || entry.healthRestarts >= restart.maxRetries)\n return false\n\n entry.healthRestarts += 1\n ctx.persist(entry)\n ctx.log(entry, 'system', `unhealthy for ${health.forceRestartAfterMs}ms — forcing a restart (${entry.healthRestarts}/${restart.maxRetries})`)\n ctx.options.history.record(entry.config.id, { type: 'forced-restart', detail: `health check stayed unhealthy` })\n ctx.notify(entry, 'forced-restart', `unhealthy for ${Math.round(health.forceRestartAfterMs / 1000)}s`)\n // The restart resets health, so this is the only place that remembers an outcome is owed.\n entry.pendingRestart = { cause: 'staying unhealthy through its health check' }\n return true\n}\n\n/** Whether this entry's health budget is spent, so the tick should stop it. */\nexport function healthBudgetSpent(entry: Entry): boolean {\n const { port, health, restart } = entry.config\n if (port === null || entry.status !== 'running' || entry.health !== 'unhealthy')\n return false\n if (entry.unhealthySince === null || health.forceRestartAfterMs <= 0)\n return false\n return !restart.enabled || entry.healthRestarts >= restart.maxRetries\n}\n\n/**\n * Stops an entry that cannot pass its own health check once the budget is spent. `stopped`, because\n * the process really is; the reason stays on `lastError`.\n */\nexport async function giveUpOnHealth(ctx: HealthContext, entry: Entry): Promise<void> {\n const budgetEnabled = entry.config.restart.enabled\n const detail = budgetEnabled\n ? `stopped after ${entry.config.restart.maxRetries} health restarts (the health check kept failing)`\n : 'stopped because health restarts are disabled and the health check is failing'\n\n entry.pendingRestart = null\n entry.healthRestarts = 0\n entry.stoppedByPanel = true\n ctx.log(entry, 'system', detail)\n ctx.options.history.record(entry.config.id, { type: 'crash', detail })\n ctx.notify(entry, 'crash', detail)\n await ctx.stopEntry(entry)\n // After the stop, which clears `lastError` on the stopped path.\n if (!entry.removed) {\n entry.lastError = detail\n ctx.publishServer(entry)\n }\n}\n","import type { Entry, SupervisorContext } from '#src/services/supervisor/entry'\nimport { hookFailure, runBackupHook } from '#src/providers/backup-hook'\nimport { probePort } from '#src/providers/port'\n\n/**\n * Runs the load hook a restore left behind, once the entry is answering: `mongorestore` and\n * `pg_restore` connect, so running them the instant the process spawns fails with \"connection refused\".\n */\nexport async function runPendingLoad(ctx: SupervisorContext, entry: Entry): Promise<void> {\n const dumpDir = entry.pendingLoad\n const hook = entry.config.load\n // `loadingPending` stops two overlapping starts from loading the dump twice.\n if (entry.loadingPending || dumpDir === null || hook === undefined || hook === null) {\n // No hook in the live config: drop the staged dump rather than keep a path nothing will read.\n if (hook === undefined || hook === null) {\n entry.pendingLoad = null\n ctx.persist(entry)\n }\n return\n }\n entry.loadingPending = true\n\n if (entry.config.port !== null) {\n const deadline = Date.now() + hook.timeoutMs\n while (Date.now() < deadline && entry.status !== 'stopped') {\n if (await probePort('127.0.0.1', entry.config.port))\n break\n await new Promise(resolve => setTimeout(resolve, 500))\n }\n }\n else if (hook.waitMs > 0) {\n // No port to probe: wait a bounded moment rather than load into something not yet bound.\n await new Promise(resolve => setTimeout(resolve, hook.waitMs))\n }\n\n // Cleared before the run: a failing load must not retry on every restart; the dump stays on disk.\n entry.pendingLoad = null\n ctx.persist(entry)\n\n const result = await runBackupHook(hook, entry.config, dumpDir)\n entry.loadingPending = false\n ctx.log(entry, 'system', result.ok\n ? 'load: the restored dump was applied'\n : `load: ${hookFailure('load', entry.config, result)}`)\n}\n","import type { LogLine } from '#src/shared/contracts'\nimport { Buffer } from 'node:buffer'\nimport fs from 'node:fs'\n\n/**\n * Reads the JSONL a nanny writes for a persistent entry, from where it last stopped.\n *\n * The panel is not the writer here, so the reader has to survive the two things a\n * writer does on its own: rotation (a renamed file next to a fresh one) and\n * truncation. Both are detected by comparing the file's identity and size against\n * the position last read, and every poll reads to EOF so a rotation never strands\n * bytes in the file it left behind.\n */\n\n/** One poll reads at most this much, so a burst cannot stall the tick. */\nconst MAX_BYTES_PER_READ = 256 * 1024\n\n/**\n * The window a backfill starts with, and the ceiling it may grow to.\n *\n * It has to grow because the request is in *lines* and the window is in *bytes*: a\n * persistent entry's JSONL carries whatever its server printed, so one line can be a stack\n * trace. A fixed 256 KB window returned 178 of the 200 lines asked for at ~1500-byte lines,\n * and the oldest line handed back was not the oldest asked for. The ceiling keeps a bounded\n * request bounded — a log of nothing but megabyte lines stops growing rather than being read\n * whole.\n */\nconst BACKFILL_INITIAL_BYTES = 256 * 1024\nconst BACKFILL_MAX_BYTES = 8 * 1024 * 1024\n\n/** A partial line longer than this is dropped rather than buffered without bound. */\nconst MAX_CARRY_CHARS = 1024 * 1024\n\nconst LOG_STREAMS = new Set(['stdout', 'stderr', 'system'])\n\nexport class LogTailer {\n private offset = 0\n private identity: number | null = null\n private carry = ''\n\n constructor(private readonly file: string) {}\n\n /** Bytes consumed so far; equal to the file size once it has been drained. */\n get position(): number {\n return this.offset\n }\n\n /** Start from the beginning again — used when a fresh process takes the entry over. */\n reset(): void {\n this.offset = 0\n this.identity = null\n this.carry = ''\n }\n\n /**\n * The last `count` lines, with the read position moved to the end of the file in the\n * same operation.\n *\n * A panel attaching to a running entry wants both a backfill and a live stream, and\n * only one thing may own the offset. Reading the tail through the same tailer is what\n * keeps a line from being replayed as news or skipped as history — and it is why this\n * does not delegate to `LogFiles.readTail()`, which knows nothing of this position.\n */\n readTailLines(count: number): LogLine[] {\n let stats: fs.Stats\n try {\n stats = fs.statSync(this.file)\n }\n catch {\n return []\n }\n\n const size = stats.size\n this.carry = ''\n this.offset = size\n this.identity = stats.ino === 0 ? stats.birthtimeMs : stats.ino\n if (size === 0 || count <= 0)\n return []\n\n let handle: number\n try {\n handle = fs.openSync(this.file, 'r')\n }\n catch {\n return []\n }\n\n try {\n let window = Math.min(size, BACKFILL_INITIAL_BYTES)\n for (;;) {\n const start = size - window\n const buffer = Buffer.alloc(window)\n const bytes = fs.readSync(handle, buffer, 0, buffer.length, start)\n const raw = buffer.subarray(0, bytes).toString('utf8').split('\\n')\n // A read that starts mid-file begins on a partial line — but only when the byte\n // before `start` is not the newline that ended the previous one. Dropping the\n // first element unconditionally lost one complete line per attach once the log\n // passed the tail window, and filtering *before* the drop made a blank leading\n // fragment drop a real line as well.\n let partialStart = false\n if (start > 0) {\n const previous = Buffer.alloc(1)\n const readBack = fs.readSync(handle, previous, 0, 1, start - 1)\n partialStart = readBack === 1 && previous[0] !== 0x0A\n }\n const lines = (partialStart ? raw.slice(1) : raw).filter(line => line.trim().length > 0)\n\n // Enough for the request, the whole file, or the ceiling: stop. Otherwise the window\n // was too small for lines this long, so read more rather than returning short.\n const grew = window < size && window < BACKFILL_MAX_BYTES\n if (lines.length >= count || !grew) {\n return lines.slice(-count)\n .map(parseLogLine)\n .filter((line): line is LogLine => line !== null)\n }\n\n window = Math.min(size, window * 4)\n }\n }\n catch {\n return []\n }\n finally {\n fs.closeSync(handle)\n }\n }\n\n /**\n * Ignore what is already in the file and follow it from here.\n */\n skipToEnd(): void {\n this.carry = ''\n try {\n const stats = fs.statSync(this.file)\n this.offset = stats.size\n this.identity = stats.ino === 0 ? stats.birthtimeMs : stats.ino\n }\n catch {\n this.offset = 0\n this.identity = null\n }\n }\n\n /** Every complete line written since the previous call. */\n read(): LogLine[] {\n let stats: fs.Stats\n try {\n stats = fs.statSync(this.file)\n }\n catch {\n // Not created yet, or rotated away between the two syscalls.\n return []\n }\n\n // `ino` is 0 on some Windows filesystems; the birth time identifies the file there.\n const identity = stats.ino === 0 ? stats.birthtimeMs : stats.ino\n if (this.identity !== null && (identity !== this.identity || stats.size < this.offset)) {\n this.carry = ''\n this.offset = 0\n }\n this.identity = identity\n\n if (stats.size <= this.offset)\n return []\n\n const lines: LogLine[] = []\n let handle: number\n try {\n handle = fs.openSync(this.file, 'r')\n }\n catch {\n return []\n }\n\n try {\n // A poll consumes at most `MAX_BYTES_PER_READ`, which is what the constant promises. Sizing the\n // buffer is not enough: refilling it in a loop until EOF drained a whole backlog in one\n // synchronous call, and `LogRelay` calls this every 250 ms — so a server flooding its log while\n // the panel was busy stalled the event loop for the entire catch-up. The remainder waits for the\n // next poll, which is 250 ms away.\n const budget = Math.min(MAX_BYTES_PER_READ, stats.size - this.offset)\n const buffer = Buffer.alloc(budget)\n let consumed = 0\n while (consumed < budget && this.offset < stats.size) {\n const length = Math.min(buffer.length, budget - consumed, stats.size - this.offset)\n const bytes = fs.readSync(handle, buffer, 0, length, this.offset)\n if (bytes <= 0)\n break\n this.offset += bytes\n consumed += bytes\n this.consume(buffer.subarray(0, bytes).toString('utf8'), lines)\n if (bytes < length)\n break\n }\n }\n catch {\n // A file replaced mid-read is picked up by the next poll.\n }\n finally {\n fs.closeSync(handle)\n }\n\n return lines\n }\n\n private consume(text: string, lines: LogLine[]): void {\n if (this.carry.length === 0) {\n this.carry = text\n }\n else {\n this.carry += text\n }\n\n const parts = this.carry.split('\\n')\n // The last part has no newline yet: it is a write we have half seen.\n this.carry = parts.pop() ?? ''\n\n for (const part of parts) {\n if (part.trim().length === 0)\n continue\n const line = parseLogLine(part)\n if (line !== null)\n lines.push(line)\n }\n\n if (this.carry.length > MAX_CARRY_CHARS)\n this.carry = ''\n }\n}\n\n/**\n * Cheap structural guard rather than a full schema pass: this runs per line on a hot\n * path, and the writer is our own nanny (which serializes `LogLine` unchanged).\n */\nfunction parseLogLine(raw: string): LogLine | null {\n try {\n const value = JSON.parse(raw) as Partial<LogLine>\n if (typeof value.ts !== 'number' || typeof value.text !== 'string' || typeof value.stream !== 'string')\n return null\n if (!LOG_STREAMS.has(value.stream))\n return null\n return { ts: value.ts, stream: value.stream as LogLine['stream'], text: value.text }\n }\n catch {\n // A partial line from a rotation boundary.\n return null\n }\n}\n","import type { LogLine } from '#src/shared/contracts'\nimport { logger } from '#src/helpers/logger'\nimport { LogTailer } from '#src/providers/log-tail'\nimport { errorMessage } from '#src/shared/error-message'\n\n/**\n * Live logs for persistent entries.\n *\n * A normal entry's output reaches the panel through the pipe the panel owns, so it is\n * pushed the moment the child writes. A persistent entry's output is written by its\n * nanny, so the panel has to *read* it back: this service watches the entries it was\n * asked to follow and hands new lines to the supervisor, which treats them exactly\n * like lines that came down a pipe.\n *\n * Polling rather than `fs.watch`: the file is rotated (renamed) under us, and a\n * watcher would have to be re-established on a path that briefly does not exist —\n * for a handful of stat+read calls four times a second, the simple thing wins.\n */\n\n/** Fast enough that a live log reads as live; cheap enough to ignore. */\nconst TAIL_INTERVAL_MS = 250\n\nexport interface LogRelayOptions {\n onLines: (serverId: string, lines: LogLine[]) => void\n intervalMs?: number\n}\n\nexport class LogRelay {\n private readonly followed = new Map<string, { file: string, tailer: LogTailer }>()\n private timer: NodeJS.Timeout | null = null\n private closed = false\n\n constructor(private readonly options: LogRelayOptions) {}\n\n /**\n * Idempotent: following the same file again keeps the position already read.\n *\n * With `backfill`, the last lines already on disk are returned *and* the live position\n * is set past them by the same tailer, so the caller can fill a buffer without a line\n * being both history and news. Without it, the live stream simply starts at the end.\n */\n follow(serverId: string, file: string, options: { backfill?: number } = {}): LogLine[] {\n if (this.closed)\n return []\n\n const current = this.followed.get(serverId)\n if (current !== undefined && current.file === file)\n return []\n\n const tailer = new LogTailer(file)\n const backfill = options.backfill ?? 0\n const history = backfill > 0 ? tailer.readTailLines(backfill) : []\n if (backfill <= 0)\n tailer.skipToEnd()\n\n this.followed.set(serverId, { file, tailer })\n this.start()\n return history\n }\n\n /**\n * Stops following and hands back whatever the file still held unread.\n *\n * A nanny writes its last lines and exits in the same breath, so the tailer can be\n * dropped between two polls with its final lines — the child's crash output — still\n * on disk. Losing them here is what made a persistent entry's crash silent in the\n * panel, so the caller gets them to ingest rather than an empty hand.\n */\n unfollow(serverId: string): LogLine[] {\n const current = this.followed.get(serverId)\n const rest = current === undefined ? [] : current.tailer.read()\n this.followed.delete(serverId)\n if (this.followed.size === 0)\n this.stopTimer()\n return rest\n }\n\n followedIds(): string[] {\n return [...this.followed.keys()]\n }\n\n dispose(): void {\n this.closed = true\n this.followed.clear()\n this.stopTimer()\n }\n\n private start(): void {\n if (this.timer !== null)\n return\n this.timer = setInterval(() => {\n // A throw here must not become an unhandled rejection: on Node 24 that ends the\n // panel, and this timer is what keeps every persistent entry's log flowing.\n try {\n this.poll()\n }\n catch (error) {\n logger.warn(`tail failed: ${errorMessage(error)}`)\n }\n }, this.options.intervalMs ?? TAIL_INTERVAL_MS)\n this.timer.unref()\n }\n\n private stopTimer(): void {\n if (this.timer !== null)\n clearInterval(this.timer)\n this.timer = null\n }\n\n private poll(): void {\n for (const [serverId, { tailer }] of this.followed) {\n const lines = tailer.read()\n if (lines.length > 0)\n this.options.onLines(serverId, lines)\n }\n }\n}\n","import type { ChildProcess } from 'node:child_process'\nimport type { EventHub } from '#src/services/events'\nimport type { Entry, ResolvedSpawn, SupervisorContext } from '#src/services/supervisor/entry'\nimport type { LogLine, NannySpec, NannyState } from '#src/shared/contracts'\nimport { spawn } from 'node:child_process'\nimport process from 'node:process'\nimport { dataRoot, projectDir } from '#src/helpers/paths'\nimport { nannyArgv } from '#src/helpers/runtime'\nimport {\n clearNannySpec,\n clearNannyState,\n describeNannyExit,\n nannyEntryPoint,\n nannyIsAlive,\n nannyLogFile,\n nannySpecPath,\n nannyStatePath,\n readNannyState,\n writeNannySpec,\n} from '#src/providers/nanny'\nimport { LogRelay } from '#src/services/log-relay'\nimport { resetHealth } from '#src/services/supervisor/health'\n\n/** History a panel attaches with, so a persistent entry's live view is not blank. */\nconst PERSISTENT_BACKFILL_LINES = 200\n\n/** Echoes are read within a poll or two of being written; a bounded set is plenty. */\nconst ECHOED_LINE_LIMIT = 100\n\n/** One line's exact identity: a timestamp this panel minted, its stream and its text. */\nfunction echoedKey(line: LogLine): string {\n return `${line.ts}\\u0000${line.stream}\\u0000${line.text}`\n}\n\nexport function rememberEchoedLine(set: Set<string>, line: LogLine): void {\n set.add(echoedKey(line))\n while (set.size > ECHOED_LINE_LIMIT)\n set.delete(set.values().next().value as string)\n}\n\n/** True when this line is this panel's own echo, so it is only ever reported once. */\nfunction forgetEchoedLine(set: Set<string>, line: LogLine): boolean {\n return set.delete(echoedKey(line))\n}\n\nexport interface PersistentContext extends SupervisorContext {\n hub: EventHub\n entry: (id: string) => Entry | undefined\n}\n\n/**\n * The persistent-entry half of supervision: a nanny owns the child's pipes so it outlives the panel,\n * and the panel reads its output back from the log file and its exit from the nanny's state file.\n */\nexport class PersistentEntries {\n private readonly relay: LogRelay\n\n constructor(private readonly ctx: PersistentContext) {\n this.relay = new LogRelay({ onLines: (serverId, lines) => this.ingest(serverId, lines) })\n }\n\n /**\n * Spawns the nanny that runs this entry. The spec carries the already-expanded argv and env, so\n * `resolveSpawn()` stays the only resolver; it is 0600 and unlinked by the nanny as it reads it.\n */\n launch(entry: Entry, resolved: ResolvedSpawn): { child: ChildProcess, detail: string } | { error: string } {\n const { command, args, env, cwd, loggedArgs } = resolved\n const { options } = this.ctx\n\n this.ctx.log(entry, 'system', `start (persistent): ${command} ${loggedArgs.join(' ')}`)\n\n // The CLI this panel was launched through, under tsx, dist/cli.js and the published bin alike.\n const entryPoint = nannyEntryPoint()\n if (entryPoint.length === 0)\n return { error: 'cannot locate this CLI to start a persistent entry' }\n\n const id = entry.config.id\n const specPath = nannySpecPath(options.nannyDir, id)\n const statePath = nannyStatePath(options.nannyDir, id)\n const spec: NannySpec = {\n serverId: id,\n command,\n args,\n cwd,\n env,\n logDir: options.logFiles.directory,\n logs: options.logFiles.config,\n stop: entry.config.stop,\n }\n\n let child: ChildProcess\n try {\n writeNannySpec(specPath, spec)\n child = spawn(process.execPath, nannyArgv(entryPoint, id, specPath, statePath), {\n cwd,\n env: { ...process.env, ...env, HHOSTED_HOME: dataRoot, HHOSTED_PROJECT: projectDir },\n // The nanny reports through the entry's log file and holds no pipe of ours.\n stdio: ['ignore', 'ignore', 'ignore'],\n detached: true,\n windowsHide: true,\n })\n }\n catch (error) {\n clearNannySpec(specPath)\n return { error: (error as Error).message }\n }\n\n // Outliving this panel is the point, so the loop must not be held open by it.\n child.unref()\n return { child, detail: `nanny → ${command} ${args.join(' ')}`.trim() }\n }\n\n /**\n * Follows the entry's log file. The backfill is read *through* the tailer, the only owner of the\n * offset. `attach` means \"already running, and its history is new to this panel\" — the buffer cannot\n * tell, because spawn, adopt and reattach all log a line first — and an empty buffer is still\n * required so a second attach cannot replay older lines.\n */\n follow(entry: Entry, attach = false): void {\n const id = entry.config.id\n const { logFiles } = this.ctx.options\n // `logs.persist: false` means that history is not served, and the backfill follows suit.\n const backfill = attach && entry.logs.size === 0 && logFiles.config.persist\n ? PERSISTENT_BACKFILL_LINES\n : 0\n\n const history = this.relay.follow(id, nannyLogFile(logFiles.directory, id), { backfill })\n if (history.length > 0)\n entry.logs.extend(history)\n }\n\n /** Whatever the relay had not read yet, ingested before its tailer goes. */\n drain(entry: Entry): void {\n const rest = this.relay.unfollow(entry.config.id)\n if (rest.length > 0)\n this.ingest(entry.config.id, rest)\n }\n\n /** Stops tailing a removed entry, discarding what was unread: nothing will serve it. */\n forget(id: string): void {\n this.relay.unfollow(id)\n }\n\n dispose(): void {\n this.relay.dispose()\n }\n\n readState(id: string): NannyState | null {\n return readNannyState(nannyStatePath(this.ctx.options.nannyDir, id))\n }\n\n /**\n * An explicit stop ends the entry for real: its records go, so nothing reattaches. A pid that\n * outlived the stop keeps them — they are the only way a later boot can find it.\n */\n finishStop(entry: Entry, survivor: number | null): void {\n const { nannyDir } = this.ctx.options\n if (survivor === null) {\n clearNannyState(nannyStatePath(nannyDir, entry.config.id))\n clearNannySpec(nannySpecPath(nannyDir, entry.config.id))\n }\n else {\n this.ctx.log(entry, 'system', `pid ${survivor} is still alive after the stop — its state file is kept`)\n }\n // The last chance to read what the nanny wrote on its way out.\n this.drain(entry)\n }\n\n /**\n * Reattaches to a nanny that is still running, or reports how it ended while nobody was watching.\n * Never starts anything — that is `start()`'s job.\n */\n async resume(entry: Entry, current: () => boolean = () => true): Promise<boolean> {\n const id = entry.config.id\n const { history } = this.ctx.options\n const state = this.readState(id)\n\n const alive = state !== null && state.serverId === id && await nannyIsAlive(state, id)\n // A start cancelled meanwhile: the stop that cancelled it does its own reattach.\n if (!current())\n return false\n if (alive) {\n entry.adopted = true\n entry.child = null\n entry.pid = state.nannyPid\n entry.startedAt = state.startedAt\n entry.status = 'running'\n resetHealth(entry)\n entry.portState = entry.config.port === null ? 'unknown' : 'in-use'\n entry.lastError = null\n entry.nannyExit = null\n const child = state.childPid === null ? '' : `, server pid ${state.childPid}`\n this.follow(entry, true)\n this.ctx.log(entry, 'system', `persistent: still running (nanny pid ${state.nannyPid}${child}) — reattached`)\n this.ctx.publishServer(entry)\n return true\n }\n\n if (state === null)\n return false\n\n // The nanny is gone; its state file is the only witness, read and consumed exactly once.\n this.consumeExit(entry)\n const exit = entry.nannyExit\n entry.nannyExit = null\n if (exit === null)\n return false\n\n const detail = exit.code === null && exit.signal === null ? 'it could not start' : describeNannyExit(exit)\n const ranFor = `${Math.max(1, Math.round(exit.runtimeMs / 1000))}s`\n history.record(id, { type: 'exit', detail: `while the panel was away: ${detail}`, runtimeMs: exit.runtimeMs })\n this.ctx.log(entry, 'system', `persistent: exited while the panel was away with ${detail} after ${ranFor}`)\n\n if (exit.code !== 0 || exit.signal !== null) {\n entry.status = 'crashed'\n entry.lastError = `exited while the panel was away with ${detail}`\n history.record(id, { type: 'crash', detail: entry.lastError, runtimeMs: exit.runtimeMs })\n this.ctx.notify(entry, 'crash', entry.lastError)\n }\n this.ctx.publishServer(entry)\n return false\n }\n\n /** The nanny's last word onto `entry.nannyExit`, then its state file goes so it is reported once. */\n consumeExit(entry: Entry): void {\n const statePath = nannyStatePath(this.ctx.options.nannyDir, entry.config.id)\n const state = readNannyState(statePath)\n if (state?.lastExit !== undefined)\n entry.nannyExit = state.lastExit\n clearNannyState(statePath)\n // A nanny writes its last lines and exits in one breath; a crash on start fits between two polls.\n this.drain(entry)\n }\n\n /** Lines read back from the log file, into the same buffer and SSE frame a piped entry uses. */\n private ingest(serverId: string, lines: LogLine[]): void {\n const entry = this.ctx.entry(serverId)\n if (entry === undefined || !entry.config.persistent || lines.length === 0)\n return\n\n // This panel's own lines live in that file too: an echo is not news.\n const kept = lines.filter(line => !forgetEchoedLine(entry.echoed, line))\n if (kept.length === 0)\n return\n\n for (const line of kept) entry.logs.push(line)\n // One frame per batch, so a burst of lines is not a burst of frames.\n this.ctx.hub.publish({ type: 'log', ts: kept[kept.length - 1]!.ts, workspaceId: this.ctx.options.workspaceId, serverId, lines: kept })\n }\n}\n","import type { Entry, SupervisorContext } from '#src/services/supervisor/entry'\nimport type { ServerOrphan } from '#src/shared/contracts'\nimport fs from 'node:fs'\nimport path from 'node:path'\nimport process from 'node:process'\nimport { clearEntryState, entryStatePath, readEntryState, writeEntryState } from '#src/providers/entry-state'\nimport { isProcessAlive, processLiveness, terminatePids } from '#src/providers/port'\nimport { processCarriesServerId } from '#src/providers/proc'\n\n/** What this entry's own state file says about the child the last panel spawned. */\nexport type RecordedChild\n = | { kind: 'none' }\n | { kind: 'adopt', pid: number }\n | { kind: 'blocked', error: string }\n\n/** The decisions that have to survive this panel, and nothing else. */\nexport function persistEntryState(nannyDir: string, entry: Entry): void {\n // A removed entry's file was reclaimed; the async stop that follows must not recreate it.\n if (entry.removed)\n return\n writeEntryState(entryStatePath(nannyDir, entry.config.id), {\n restarts: entry.restarts,\n healthRestarts: entry.healthRestarts,\n bootstrapDone: entry.bootstrapDone,\n // Carried, not recomputed: a rewrite without it silently drops a restore's staged load.\n pendingLoad: entry.pendingLoad,\n // A persistent entry's nanny state is already its record; a second one could only disagree.\n lastPid: entry.config.persistent ? null : entry.lastChild?.pid ?? null,\n lastStartedAt: entry.config.persistent ? null : entry.lastChild?.startedAt ?? null,\n })\n}\n\n/**\n * The child this entry's state file recorded, when it is still that same process.\n *\n * A non-persistent child is detached and survives a panel killed hard; `preflight` cannot find a\n * portless one. Birth time and the marker decide, never liveness alone, and a pid this platform\n * cannot place is never adopted on a guess. The record is cleared only once its process is known gone\n * or to be somebody else.\n */\nexport async function resolveRecordedChild(ctx: SupervisorContext, entry: Entry): Promise<RecordedChild> {\n const recorded = entry.lastChild\n if (recorded === null)\n return { kind: 'none' }\n\n // Never adopt the panel itself.\n if (recorded.pid === process.pid) {\n entry.lastChild = null\n ctx.persist(entry)\n return { kind: 'none' }\n }\n\n // An older file has no birth stamp, and 0 would read as recycled, so liveness is all it can be judged by.\n const liveness = recorded.startedAt > 0\n ? await processLiveness(recorded.pid, recorded.startedAt)\n : (isProcessAlive(recorded.pid) ? 'unknown' : 'gone')\n if (liveness === 'gone' || liveness === 'recycled') {\n entry.lastChild = null\n ctx.persist(entry)\n return { kind: 'none' }\n }\n\n if (await processCarriesServerId(recorded.pid, entry.config.id))\n return { kind: 'adopt', pid: recorded.pid }\n\n // Alive and unattributable (Windows has no per-process env). With a port the preflight still has\n // witnesses; without one, refusing beats a duplicate portless worker.\n if (entry.config.port !== null)\n return { kind: 'none' }\n\n const error = `pid ${recorded.pid} may be a child this panel started for \"${entry.config.id}\" before it died, and this platform cannot confirm whose it is — not starting a second copy, stop pid ${recorded.pid} to clear it`\n entry.status = 'conflict'\n entry.lastError = error\n ctx.log(entry, 'system', error)\n ctx.publishServer(entry)\n return { kind: 'blocked', error }\n}\n\n/** Clears the durable record of the last child, once that pid is known to be gone. */\nexport function forgetRecordedChild(ctx: SupervisorContext, entry: Entry, pid: number | null): void {\n if (pid === null || entry.lastChild === null || entry.lastChild.pid !== pid)\n return\n entry.lastChild = null\n ctx.persist(entry)\n}\n\n/**\n * Processes this panel started that no configured entry claims any more (renamed or removed while the\n * panel was down), read from the state directory so an earlier panel's files count too.\n */\nexport async function scanOrphans(nannyDir: string, owned: (id: string) => boolean): Promise<ServerOrphan[]> {\n let names: string[]\n try {\n names = fs.readdirSync(nannyDir)\n }\n catch {\n return []\n }\n\n const found: ServerOrphan[] = []\n for (const name of names) {\n if (!name.endsWith('.run.json'))\n continue\n const id = name.slice(0, -'.run.json'.length)\n if (owned(id))\n continue\n const state = readEntryState(path.join(nannyDir, name))\n const pid = state?.lastPid ?? null\n if (pid === null || pid === process.pid)\n continue\n const startedAt = state?.lastStartedAt ?? 0\n // A pid born after the record is a stranger, and reporting it would offer a one-click SIGTERM of\n // it. No stamp can only be judged by liveness, and `unknown` counts as alive.\n const liveness = startedAt > 0\n ? await processLiveness(pid, startedAt)\n : (isProcessAlive(pid) ? 'unknown' : 'gone')\n if (liveness === 'gone' || liveness === 'recycled')\n continue\n found.push({ serverId: id, pid, startedAt: startedAt > 0 ? startedAt : null })\n }\n return found\n}\n\n/** Stops one orphan; its record is cleared only once the pid is gone, so a survivor stays findable. */\nexport async function stopOrphanProcess(nannyDir: string, orphan: ServerOrphan): Promise<{ ok: true, forced: number[] } | { ok: false, error: string }> {\n const { forced } = await terminatePids([orphan.pid], { graceMs: 5000 })\n if (isProcessAlive(orphan.pid))\n return { ok: false, error: `pid ${orphan.pid} survived the stop — kill it from a shell, its record is kept` }\n clearEntryState(entryStatePath(nannyDir, orphan.serverId))\n return { ok: true, forced }\n}\n","import type { HistoryStore } from '#src/services/history'\nimport type { Entry } from '#src/services/supervisor/entry'\nimport type { ServerView } from '#src/shared/contracts'\nimport { bindHost, displayHost } from '#src/helpers/bind'\n\n/** Uptime/crash counters are reported over this window. */\nconst HISTORY_WINDOW_MS = 24 * 60 * 60 * 1000\nconst HISTORY_CACHE_MS = 5000\n\n/** Rebuilt when history changes or every few seconds: the view runs per frame and the window math is O(events). */\nfunction summarizeHistory(entry: Entry, history: HistoryStore): ServerView['history'] {\n const now = Date.now()\n const revision = history.revision\n const cached = entry.historyCache\n if (cached !== null && cached.revision === revision && now - cached.at < HISTORY_CACHE_MS)\n return cached.summary\n\n const runningSince = entry.child !== null && entry.startedAt !== null ? entry.startedAt : null\n const summary = history.summarize(entry.config.id, HISTORY_WINDOW_MS, now, runningSince)\n entry.historyCache = { revision, at: now, summary }\n return summary\n}\n\nexport function buildView(entry: Entry, workspaceId: string, history: HistoryStore): ServerView {\n const config = entry.config\n const host = displayHost(config.bind)\n return {\n id: config.id,\n workspaceId,\n config,\n bindHost: bindHost(config.bind),\n url: config.port === undefined || config.port === null ? null : `http://${host}:${config.port}`,\n status: entry.status,\n health: entry.health,\n portState: entry.portState,\n pid: entry.pid,\n // Omitted when false: an optional ArkType property rejects an explicit undefined.\n ...(entry.adopted ? { adopted: true } : {}),\n ...(entry.stoppedByPanel ? { stoppedByPanel: true } : {}),\n startedAt: entry.startedAt,\n exitCode: entry.exitCode,\n exitSignal: entry.exitSignal,\n restarts: entry.restarts,\n maxRetries: config.restart.maxRetries,\n lastError: entry.lastError,\n nextRetryAt: entry.nextRetryAt,\n unhealthySince: entry.unhealthySince,\n bufferedLines: entry.logs.size,\n history: summarizeHistory(entry, history),\n responseMs: entry.responseMs,\n resources: entry.resources,\n }\n}\n","import type { ChildProcess } from 'node:child_process'\nimport type { WorkspaceStore } from '#src/config/store'\nimport type { EventHub } from '#src/services/events'\nimport type { NotificationReason } from '#src/services/notifications'\nimport type { Entry, ResolvedSpawn, StartResult, SupervisorOptions } from '#src/services/supervisor/entry'\nimport type { HealthContext } from '#src/services/supervisor/health'\nimport type { PersistentContext } from '#src/services/supervisor/persistent'\nimport type { PortContext, SupervisedPids } from '#src/services/supervisor/port-preflight'\nimport type { FreePortResult, HistoryActor, LogLine, LogStream, NannyExit, ServerOrphan, ServerStatus, ServerView } from '#src/shared/contracts'\nimport { missingServer } from '#src/helpers/action-result'\nimport { computeBackoff } from '#src/helpers/backoff'\nimport { logger } from '#src/helpers/logger'\nimport { DockerMetrics } from '#src/providers/docker'\nimport { clearEntryState, entryStatePath } from '#src/providers/entry-state'\nimport { describeNannyExit, describeSpawnError, nannyStopOptions, sweepNannySpecs } from '#src/providers/nanny'\nimport { isProcessAlive, killPortHolders } from '#src/providers/port'\nimport { ProcessSampler } from '#src/providers/proc'\nimport { spawnManaged, terminate, terminatePid } from '#src/providers/process'\nimport { dependenciesOf, dependentsOf, orderByDependencies } from '#src/services/dependencies'\nimport { LineSplitter, LogBuffer } from '#src/services/log-buffer'\nimport { refuseLingeringStack, stopComposeStack } from '#src/services/supervisor/compose'\nimport { createEntry, delay, isActive } from '#src/services/supervisor/entry'\nimport {\n awaitReadiness,\n endHealthStreak,\n endProcessReadings,\n enforceMemoryLimit,\n giveUpOnHealth,\n healthBudgetSpent,\n probeEntry,\n resetHealth,\n sampleResources,\n shouldForceRestart,\n} from '#src/services/supervisor/health'\nimport { runPendingLoad } from '#src/services/supervisor/pending-load'\nimport { PersistentEntries, rememberEchoedLine } from '#src/services/supervisor/persistent'\nimport { freePort, preflight, supervisedPids } from '#src/services/supervisor/port-preflight'\nimport { forgetRecordedChild, persistEntryState, resolveRecordedChild, scanOrphans, stopOrphanProcess } from '#src/services/supervisor/records'\nimport { detectCompose, killBootstrap, resolveSpawn, runBootstrap } from '#src/services/supervisor/spawn'\nimport { buildView } from '#src/services/supervisor/view'\n\nexport { serverTemplateVars } from '#src/providers/server-vars'\nexport type { SiblingServer, StartResult, SupervisorOptions } from '#src/services/supervisor/entry'\n\n/*\n * The lifecycle state machine for one workspace's entries: start, stop, restart, exit, retry, and the\n * tick that drives probes and sampling. Each concern it delegates lives in `./supervisor/`:\n * `port-preflight` (conflicts, free-port, what the panel owns), `persistent` (nannies and their logs),\n * `health` (the health trio, readiness, probes, budgets, memory ceiling, sampling), `records`\n * (entry-state file, recorded child, orphans), `spawn` (resolution, bootstrap), `compose`, `view`.\n */\n\nconst TICK_INTERVAL_MS = 1000\n\ntype Context = PortContext & HealthContext & PersistentContext\n\nexport class Supervisor {\n private readonly sampler = new ProcessSampler()\n /** Container readings for docker-backed entries, batched across the workspace. */\n private readonly docker = new DockerMetrics()\n private readonly entries = new Map<string, Entry>()\n private readonly ctx: Context\n private readonly persistent: PersistentEntries\n /** Processes no entry owns, refreshed by the tick; read synchronously by the state frame. */\n private orphanCache: ServerOrphan[] = []\n private readonly tickTimer: NodeJS.Timeout\n /** Detaches this supervisor from the store's listener set in `dispose()`. */\n private readonly storeUnsubscribe: () => void\n private disposed = false\n\n constructor(\n private readonly store: WorkspaceStore,\n private readonly hub: EventHub,\n private readonly options: SupervisorOptions,\n ) {\n const ctx: Context = {\n options,\n hub,\n log: (entry, stream, text) => this.log(entry, stream, text),\n publishServer: entry => this.publishServer(entry),\n persist: entry => persistEntryState(options.nannyDir, entry),\n notify: (entry, reason, detail) => this.notify(entry, reason, detail),\n entry: id => this.entries.get(id),\n supervisedPids: () => this.supervisedPids(),\n resolveSpawn: entry => resolveSpawn(ctx, entry),\n isDisposed: () => this.disposed,\n restart: id => this.restart(id),\n stopEntry: entry => this.stopEntry(entry),\n }\n this.ctx = ctx\n this.persistent = new PersistentEntries(ctx)\n\n // A spec on disk belongs to a nanny that never read it (nothing of ours can be waiting yet), and it\n // holds expanded env.\n const swept = sweepNannySpecs(this.options.nannyDir)\n if (swept > 0)\n logger.warn(`removed ${swept} unread nanny spec file(s) from ${this.options.nannyDir}`)\n\n this.sync()\n // Kept so `dispose()` can let go: the store outlives the supervisor.\n this.storeUnsubscribe = this.store.onChange(() => this.sync())\n // A throw inside the tick must not become an unhandled rejection: on Node 24 that ends the process.\n this.tickTimer = setInterval(() => {\n void this.tick().catch((error: unknown) => logger.error('the supervisor tick failed', error))\n }, TICK_INTERVAL_MS)\n this.tickTimer.unref()\n }\n\n views(): ServerView[] {\n return [...this.entries.values()].map(entry => this.view(entry))\n }\n\n /**\n * Processes this panel started that no configured entry claims any more. Reported, never touched:\n * the platform may not be able to confirm a pid's identity, and a stray duplicate (two consumers of\n * one queue) is the most damaging kind. `stopOrphan` is the explicit action.\n */\n orphans(): ServerOrphan[] {\n return [...this.orphanCache]\n }\n\n /** Async (a birth time per pid), so it runs on the tick, never in the per-frame view. */\n private async refreshOrphans(): Promise<void> {\n this.orphanCache = await scanOrphans(this.options.nannyDir, id => this.entries.has(id))\n }\n\n /** Stops one reported orphan and reclaims its record once the pid is gone. */\n async stopOrphan(serverId: string): Promise<{ ok: boolean, error?: string }> {\n await this.refreshOrphans()\n const orphan = this.orphans().find(entry => entry.serverId === serverId)\n if (orphan === undefined)\n return { ok: false, error: `no orphaned process is running as \"${serverId}\"` }\n\n const stopped = await stopOrphanProcess(this.options.nannyDir, orphan)\n if (!stopped.ok)\n return stopped\n // The record is gone, so the cached list is already wrong; refresh before publishing.\n await this.refreshOrphans()\n logger.info(`stopped the orphaned process ${orphan.pid} (was \"${serverId}\")${stopped.forced.length > 0 ? ', force-killed' : ''}`)\n this.publishState()\n return { ok: true }\n }\n\n logLines(id: string, limit?: number): LogLine[] {\n return this.entries.get(id)?.logs.list(limit) ?? []\n }\n\n async startAll(options: { autostartOnly?: boolean } = {}): Promise<void> {\n // Reattaching ignores `autostartOnly`: adopting what already runs is not starting it, and an\n // unmanaged persistent entry would look like a stranger holding its port.\n for (const entry of [...this.entries.values()]) {\n if (!entry.config.persistent || isActive(entry))\n continue\n if (entry.config.enabled) {\n await this.persistent.resume(entry).catch((error: unknown) => {\n logger.error(`could not reattach the persistent server ${entry.config.id}`, error)\n })\n continue\n }\n // Disabled while the panel was down: adopt the leftover nanny only to stop it.\n try {\n if (await this.persistent.resume(entry))\n await this.stop(entry.config.id)\n }\n catch (error) {\n logger.error(`could not stop the disabled persistent server ${entry.config.id}`, error)\n }\n }\n\n const targets = [...this.entries.values()]\n .filter(entry => !options.autostartOnly || entry.config.autostart)\n .map(entry => entry.config)\n // Dependencies first; levels are still started concurrently.\n for (const config of orderByDependencies(targets)) {\n await this.start(config.id, { actor: 'boot' })\n }\n }\n\n /**\n * Stops every entry this command owns. A persistent entry is skipped unless asked, and said so, so\n * \"stopped everything\" is never claimed about a running server.\n */\n async stopAll(options: { withPersistent?: boolean } = {}): Promise<void> {\n const targets = orderByDependencies([...this.entries.values()].map(entry => entry.config)).reverse()\n for (const config of targets) {\n const entry = this.entries.get(config.id)\n if (entry !== undefined && entry.config.persistent && options.withPersistent !== true) {\n if (isActive(entry))\n this.log(entry, 'system', 'persistent: left running (stop it explicitly to end it)')\n continue\n }\n await this.stop(config.id)\n }\n }\n\n async start(id: string, options: { retry?: boolean, actor?: HistoryActor } = {}): Promise<StartResult> {\n const entry = this.entries.get(id)\n if (!entry)\n return missingServer(id)\n if (!entry.config.enabled)\n return { ok: false, error: `server \"${id}\" is disabled` }\n if (entry.status === 'running' || entry.status === 'starting' || entry.starting) {\n // A staged load still has to run when the entry is already up, or the dump sits there forever.\n if (entry.pendingLoad !== null)\n this.runPendingLoadInBackground(entry)\n return { ok: true }\n }\n if (entry.stopping)\n return { ok: false, error: `server \"${id}\" is stopping` }\n\n // Set before the first await, so two overlapping starts cannot both spawn.\n entry.starting = true\n // A retry is always the panel's own doing, whatever asked for the start.\n entry.actor = options.retry ? 'policy' : (options.actor ?? 'policy')\n entry.stoppedByPanel = false\n this.clearRetry(entry)\n if (!options.retry) {\n entry.restarts = 0\n // Only a start *someone asked for* ends the health sequence and its owed outcome: the force\n // restart also comes through here as `policy`, and resetting then refilled the budget forever.\n if (entry.actor !== 'policy')\n entry.healthRestarts = 0\n if (entry.actor !== 'policy')\n entry.pendingRestart = null\n resetHealth(entry)\n // The reset has to reach disk too, or the next boot resurrects the old budget.\n this.ctx.persist(entry)\n }\n\n // Every await below can be overtaken by a stop, a disable, a removal or a dispose; each bumps\n // `runToken`, and the start abandons its work rather than spawn behind them.\n const token = entry.runToken\n const current = (): boolean => entry.runToken === token && !this.disposed\n const task = this.runStart(entry, current)\n entry.startTask = task\n try {\n return await task\n }\n finally {\n entry.starting = false\n if (entry.startTask === task)\n entry.startTask = null\n }\n }\n\n private async runStart(entry: Entry, current: () => boolean): Promise<StartResult> {\n const id = entry.config.id\n const cancelled = (): StartResult => this.disposed\n ? { ok: false, error: 'supervisor is shutting down' }\n : { ok: false, error: `server \"${id}\" was stopped before it started` }\n\n await this.startDependencies(entry, current)\n if (!current())\n return cancelled()\n\n // Resolved once, before every branch that can leave the entry running (it reads the env file and\n // can log), so an adopted compose stack is measured as its containers too.\n const resolved = resolveSpawn(this.ctx, entry)\n detectCompose(entry, resolved)\n\n entry.lastError = null\n entry.status = 'starting'\n resetHealth(entry)\n this.publishServer(entry)\n\n // A persistent entry whose nanny is alive is reattached, not restarted.\n if (entry.config.persistent && await this.persistent.resume(entry, current))\n return { ok: true }\n if (!current())\n return cancelled()\n\n // The same reattach for a non-persistent child that outlived the panel — before the bootstrap,\n // because a bootstrap is work done on the way to spawning a duplicate.\n if (!entry.config.persistent) {\n const recorded = await resolveRecordedChild(this.ctx, entry)\n if (!current())\n return cancelled()\n if (recorded.kind === 'blocked')\n return { ok: false, error: recorded.error }\n if (recorded.kind === 'adopt')\n return this.adoptEntry(entry, recorded.pid, 'the child this panel started before it died is still running')\n }\n\n await runBootstrap(this.ctx, entry, current)\n if (!current())\n return cancelled()\n\n const conflict = await preflight(this.ctx, entry)\n if (!current())\n return cancelled()\n if (conflict.kind === 'blocked')\n return { ok: false, error: conflict.error }\n if (conflict.kind === 'adopt')\n return this.adoptEntry(entry, conflict.pid, `a detached restart of this entry is already serving port ${entry.config.port}`)\n\n const started = this.spawnEntry(entry, resolved)\n // In the background: `start` returns on spawn, and a slow restore would make it feel hung.\n if (entry.pendingLoad !== null)\n this.runPendingLoadInBackground(entry)\n return started\n }\n\n /** A throw from a background task is an unhandled rejection, which ends the process on Node 24. */\n private runPendingLoadInBackground(entry: Entry): void {\n void runPendingLoad(this.ctx, entry).catch((error: unknown) => {\n entry.loadingPending = false\n logger.error(`the staged load for ${entry.config.id} failed`, error)\n })\n }\n\n /** Marks a restored dump as waiting to load, on the entry and on disk (a panel restart must not lose it). */\n stagePendingLoad(id: string, dumpDir: string): void {\n const entry = this.entries.get(id)\n if (entry === undefined)\n return\n entry.pendingLoad = dumpDir\n this.ctx.persist(entry)\n this.log(entry, 'system', `load: a restored dump is waiting, it runs on the next start`)\n // Already up: no later `start` is coming, so kick the load now.\n if (entry.status === 'running' && !entry.starting)\n this.runPendingLoadInBackground(entry)\n }\n\n async stop(id: string): Promise<StartResult> {\n const entry = this.entries.get(id)\n if (!entry)\n return missingServer(id)\n return this.stopEntry(entry)\n }\n\n async restart(id: string, options: { actor?: HistoryActor } = {}): Promise<StartResult> {\n // A force restart's outcome is owed, so the internal stop must not discard it; `start()` clears it\n // for a user's restart.\n const owed = this.entries.get(id)?.pendingRestart ?? null\n await this.stop(id)\n const entry = this.entries.get(id)\n if (entry !== undefined && owed !== null && entry.pendingRestart === null)\n entry.pendingRestart = owed\n return this.start(id, options)\n }\n\n async freePort(id: string): Promise<FreePortResult & { error?: string }> {\n const entry = this.entries.get(id)\n if (!entry) {\n const empty: FreePortResult = { ok: false, port: null, terminated: [], forced: [], skipped: [], free: false }\n return { ...empty, ...missingServer(id) }\n }\n return freePort(this.ctx, entry)\n }\n\n private supervisedPids(): Promise<SupervisedPids> {\n return supervisedPids(this.options.workspaceId, this.entries.values(), this.options.siblingServers)\n }\n\n clearLogs(id: string): void {\n const entry = this.entries.get(id)\n if (!entry)\n return\n entry.logs.clear()\n this.publishServer(entry)\n }\n\n /**\n * Ends this supervisor's work. Persistent entries are left running unless `withPersistent` asks —\n * `down --with-persistent` needs the stop recorded while the panel is still alive.\n */\n async dispose(options: { withPersistent?: boolean } = {}): Promise<void> {\n this.disposed = true\n clearInterval(this.tickTimer)\n this.storeUnsubscribe()\n for (const entry of this.entries.values()) this.clearRetry(entry)\n await Promise.all(\n [...this.entries.values()]\n .filter(entry => options.withPersistent === true || !entry.config.persistent)\n .map(entry => this.stopEntry(entry)),\n )\n this.persistent.dispose()\n }\n\n /**\n * Starts whatever this server depends on and waits until it is ready. A dependency that refuses to\n * come up is logged and skipped rather than blocking the dependent forever.\n */\n private async startDependencies(entry: Entry, current: () => boolean): Promise<void> {\n if (entry.config.dependsOn.length === 0)\n return\n\n for (const dependency of dependenciesOf(entry.config, this.store.servers)) {\n if (!current())\n return\n const target = this.entries.get(dependency.id)\n if (!target || !dependency.enabled)\n continue\n\n // Start it only when it is not already on its way up — but *always* wait for it to be ready;\n // skipping the wait let a dependent serve before its dependency had bound its port.\n if (target.status !== 'running' && target.child === null) {\n this.log(entry, 'system', `starting dependency \"${dependency.id}\" first`)\n // Not awaited outright: a stop of this entry must not wait out the dependency's own bootstrap.\n const started = { settled: false }\n void this.start(dependency.id)\n .catch((error: unknown) => logger.error(`could not start the dependency ${dependency.id}`, error))\n .finally(() => {\n started.settled = true\n })\n while (!started.settled && current()) await delay(100)\n if (!current())\n return\n }\n\n const deadline = Date.now() + dependency.health.startTimeoutMs\n const isReady = (): boolean => {\n const status = this.statusOf(target)\n if (status !== 'running')\n return false\n // \"Healthy\" specifically: in http mode `unknown` means nobody has checked it yet. `disabled`\n // means no health check, so `running` is all there is.\n return target.health === 'healthy' || target.health === 'disabled'\n }\n\n while (!isReady() && Date.now() < deadline && current()) await delay(250)\n if (!current())\n return\n\n if (!isReady()) {\n const status = this.statusOf(target)\n this.log(entry, 'system', `dependency \"${dependency.id}\" is ${status}/${target.health} — starting anyway`)\n }\n }\n }\n\n /** Read through a method so TypeScript does not carry a stale narrowing across awaits. */\n private statusOf(entry: Entry): ServerStatus {\n return entry.status\n }\n\n private notify(entry: Entry, reason: NotificationReason, detail: string): void {\n this.options.notifications.notify({\n serverId: entry.config.id,\n label: entry.config.label ?? entry.config.id,\n reason,\n detail,\n })\n }\n\n private async stopEntry(entry: Entry): Promise<StartResult> {\n /**\n * Two stops on one entry are **one** stop, not two racing tails.\n *\n * `stopping` is a bare boolean with no owner, so it cannot express \"a teardown is still running\n * even though some stop has finished\". Two overlapping calls each cleared it at their own tail:\n * the first finisher dropped the flag while the second was still parked in `stopComposeStack`,\n * `start()` saw a stopped-looking entry and spawned for real, and the second tail then cleared\n * the readings, dropped that pid and published `stopped` over a live child. Joining the in-flight\n * stop removes the second tail entirely.\n *\n * Reached by a double-click on Stop, `stop-all` racing a per-entry stop, and `sync()` stopping a\n * disabled entry while a stop is already running.\n */\n if (entry.stopTask !== null)\n return entry.stopTask\n const task = this.runStop(entry)\n // Assigned after `runStop` has run synchronously up to its first await (it sets `stopping`\n // before then), so no second caller can slip in between.\n entry.stopTask = task\n try {\n return await task\n }\n finally {\n if (entry.stopTask === task)\n entry.stopTask = null\n }\n }\n\n private async runStop(entry: Entry): Promise<StartResult> {\n this.clearRetry(entry)\n entry.nextRetryAt = null\n\n // Set first: it refuses a new start while this one runs.\n entry.stopping = true\n // A start in flight is cancelled and waited out, so nothing it was about to do lands after this.\n entry.runToken += 1\n killBootstrap(entry)\n await entry.startTask?.catch(() => undefined)\n\n // A persistent entry this panel never attached to (`--no-autostart`, a hand edit) has no handle;\n // adopt it first, or \"stopped\" would be answered while the nanny kept running.\n if (entry.config.persistent && entry.child === null && entry.pid === null) {\n await this.persistent.resume(entry).catch((error: unknown) => {\n logger.error(`could not reattach the persistent server ${entry.config.id} to stop it`, error)\n })\n }\n\n if (entry.child === null && entry.pid === null) {\n // Nothing of ours runs, but a compose entry's server is its containers, which may still be up.\n const stack = await stopComposeStack(this.ctx, entry)\n // Cleared after the await, for the same reason as the tail below: a start accepted during the\n // teardown must be refused by `start()`, not overwritten by this branch's verdict.\n entry.stopping = false\n if (refuseLingeringStack(this.ctx, entry, stack))\n return { ok: false, error: entry.lastError! }\n entry.status = 'stopped'\n this.publishServer(entry)\n return { ok: true }\n }\n\n // A single stop does not cascade, but it must say who is now running without its dependency.\n const orphaned = dependentsOf(entry.config, this.store.servers)\n .filter((dependent) => {\n const state = this.entries.get(dependent.id)\n return state !== undefined && isActive(state)\n })\n if (orphaned.length > 0)\n this.log(entry, 'system', `still running and depending on this: ${orphaned.map(dependent => dependent.id).join(', ')}`)\n\n entry.status = 'stopping'\n this.publishServer(entry)\n\n // A persistent entry's server is the nanny's child; a stop the nanny cannot forward (`SIGKILL`,\n // `killGroup: false`) would leave it running, so its pid is read from the state file.\n const nannyState = entry.config.persistent ? this.persistent.readState(entry.config.id) : null\n\n // An adopted successor is not our child: same shutdown, signalled by pid.\n const stopOptions = entry.config.persistent ? nannyStopOptions(entry.config.stop) : entry.config.stop\n const outcome = entry.child === null && entry.pid !== null\n ? await terminatePid(entry.pid, stopOptions)\n : await terminate(entry.child!, stopOptions)\n if (outcome === 'force-killed')\n this.log(entry, 'system', 'force-killed after grace period')\n\n if (nannyState?.childPid != null && !entry.config.stop.killGroup)\n await terminatePid(nannyState.childPid, { ...entry.config.stop, killGroup: false })\n\n const { port, stop } = entry.config\n if (stop.killPortHolders && port !== null) {\n // Only a stranger: a port held by a server this panel supervises is never killed from here.\n const leftover = await killPortHolders(port, (await this.supervisedPids()).pids)\n if (leftover.length > 0)\n this.log(entry, 'system', `port ${port} was still held by pid ${leftover.join(', ')} — killed`)\n }\n\n // A pid that outlived SIGKILL keeps its records and the outcome is not dressed up as \"stopped\".\n const survivor = entry.config.persistent && entry.pid !== null && isProcessAlive(entry.pid)\n ? entry.pid\n : null\n if (entry.config.persistent)\n this.persistent.finishStop(entry, survivor)\n\n entry.child = null\n // A SIGKILL, an adopted wrapper or a `compose up -d` from elsewhere leaves the containers up, so\n // the stack is ended too and confirmed by a fresh listing.\n const stack = await stopComposeStack(this.ctx, entry)\n // Cleared **after** the last await, never before it. Clearing both this and `child` first left a\n // window where the entry looked stopped while the teardown was still running: a `start()` accepted\n // there spawned for real, and this tail then cleared the readings — bumping the *new* run's\n // `runToken`, dropping its pid and publishing `stopped` over a live child nothing was watching,\n // so no exit event ever came. Keeping `stopping` set lets `start()`'s existing refusal cover the\n // whole window, and there is no await between this line and the writes below.\n entry.stopping = false\n endProcessReadings(entry)\n entry.nannyExit = null\n // The streak goes with the run; the verdict too, unless a survivor keeps its `conflict` outcome.\n endHealthStreak(entry)\n if (survivor === null || !entry.config.health.enabled)\n resetHealth(entry)\n // A recorded child that is gone must not be chased by a later boot; a survivor's record is kept.\n if (entry.lastChild !== null && !isProcessAlive(entry.lastChild.pid)) {\n entry.lastChild = null\n this.ctx.persist(entry)\n }\n // A container that stayed up is a refusal for the same reason a pid is.\n const lingering = refuseLingeringStack(this.ctx, entry, stack)\n if (survivor !== null)\n entry.lastError = `pid ${survivor} survived the stop`\n entry.status = survivor === null && !lingering ? 'stopped' : 'conflict'\n this.log(entry, 'system', entry.status === 'stopped' ? 'stopped' : entry.lastError!)\n this.publishServer(entry)\n return entry.status === 'stopped'\n ? { ok: true }\n : { ok: false, error: entry.lastError! }\n }\n\n private sync(): void {\n const wanted = new Map(this.store.servers.map(server => [server.id, server]))\n\n for (const [id, entry] of [...this.entries]) {\n const config = wanted.get(id)\n if (!config) {\n this.entries.delete(id)\n this.persistent.forget(id)\n // Reclaim everything keyed by the id, so a re-added id does not inherit the old server's log\n // lines, crash history or spent retry budget. Safe: a config that fails to parse keeps the\n // last trusted server list, so a bad edit does not read as \"every server was removed\".\n this.options.logFiles.clear(id)\n this.options.history.forget(id)\n clearEntryState(entryStatePath(this.options.nannyDir, id))\n // Flagged so the stop below cannot write them back; clearing *after* it would race a re-add.\n entry.removed = true\n void this.stopEntry(entry).catch((error: unknown) => {\n logger.error(`could not stop the removed server ${id}`, error)\n })\n continue\n }\n const bufferChanged = entry.config.logBufferLines !== config.logBufferLines\n // `persistent` takes effect on the next start; what must not linger is the tailer, and what it\n // had not read yet still belongs to this entry.\n if (entry.config.persistent && !config.persistent)\n this.persistent.drain(entry)\n entry.config = config\n if (bufferChanged) {\n const kept = entry.logs.list(config.logBufferLines)\n entry.logs = new LogBuffer(config.logBufferLines)\n entry.logs.extend(kept)\n }\n if (!config.enabled && (isActive(entry) || entry.starting)) {\n void this.stopEntry(entry).catch((error: unknown) => {\n logger.error(`could not stop the disabled server ${id}`, error)\n })\n }\n }\n\n for (const [id, config] of wanted) {\n if (!this.entries.has(id))\n this.entries.set(id, createEntry(config, this.options.nannyDir))\n }\n\n this.publishState()\n }\n\n /**\n * Takes over a detached successor: no spawn, no duplicate. Its output stays wherever it went, except\n * a persistent entry's, which its nanny still writes to the log file the relay follows. `reason` is\n * the only place a person sees *why* this pid is ours.\n */\n private adoptEntry(entry: Entry, pid: number, reason: string): StartResult {\n entry.adopted = true\n entry.pid = pid\n entry.child = null\n entry.status = 'running'\n resetHealth(entry)\n entry.startedAt = Date.now()\n entry.lastError = null\n // History first, then this line, so the buffer stays in order.\n if (entry.config.persistent)\n this.persistent.follow(entry, true)\n this.log(entry, 'system', `adopted pid ${pid}: ${reason}`)\n this.publishServer(entry)\n return { ok: true }\n }\n\n /** An adopted successor disappeared: fall back to the normal lifecycle. */\n private handleAdoptedExit(entry: Entry): void {\n const adoptedPid = entry.pid\n if (entry.pid !== null)\n this.sampler.forget(entry.pid)\n // A nanny that vanished while we watched still leaves the real exit behind.\n if (entry.config.persistent)\n this.persistent.consumeExit(entry)\n const ranForMs = entry.nannyExit?.runtimeMs ?? (entry.startedAt === null ? 0 : Date.now() - entry.startedAt)\n const detail = entry.nannyExit === null ? 'adopted process exited' : describeNannyExit(entry.nannyExit)\n entry.nannyExit = null\n // Known gone: a pid record kept past its process is a later boot adopting a stranger.\n forgetRecordedChild(this.ctx, entry, adoptedPid)\n endProcessReadings(entry)\n resetHealth(entry)\n entry.exitCode = null\n entry.exitSignal = null\n if (!entry.removed) {\n this.options.history.record(entry.config.id, {\n type: 'exit',\n detail,\n runtimeMs: ranForMs,\n })\n }\n this.log(entry, 'system', `the adopted process is gone after ${Math.max(1, Math.round(ranForMs / 1000))}s`)\n this.afterExit(entry, detail, ranForMs, false)\n }\n\n private spawnEntry(entry: Entry, resolved: ResolvedSpawn): StartResult {\n // A persistent entry gets a nanny, which keeps the pipes alive when the panel is gone.\n return entry.config.persistent ? this.spawnNanny(entry, resolved) : this.spawnDirect(entry, resolved)\n }\n\n private spawnDirect(entry: Entry, resolved: ResolvedSpawn): StartResult {\n const { command, args, env, cwd, loggedArgs } = resolved\n\n this.log(entry, 'system', `start: ${command} ${loggedArgs.join(' ')}`)\n\n let child: ChildProcess\n try {\n child = spawnManaged({ command, args, cwd, env })\n }\n catch (error) {\n return this.failSpawn(entry, (error as Error).message)\n }\n\n const stdout = new LineSplitter((stream, text) => this.log(entry, stream, text))\n const stderr = new LineSplitter((stream, text) => this.log(entry, stream, text))\n child.stdout?.on('data', chunk => stdout.push('stdout', chunk))\n child.stderr?.on('data', chunk => stderr.push('stderr', chunk))\n\n this.attachChild(entry, child, `${command} ${args.join(' ')}`.trim(), cwd, () => {\n stdout.flush('stdout')\n stderr.flush('stderr')\n })\n return { ok: true }\n }\n\n /** The nanny is the child this supervisor tracks; the real exit cause is read from its state file. */\n private spawnNanny(entry: Entry, resolved: ResolvedSpawn): StartResult {\n const launched = this.persistent.launch(entry, resolved)\n if ('error' in launched)\n return this.failSpawn(entry, launched.error)\n this.attachChild(entry, launched.child, launched.detail, resolved.cwd)\n this.persistent.follow(entry)\n return { ok: true }\n }\n\n private failSpawn(entry: Entry, message: string): StartResult {\n entry.status = 'crashed'\n entry.lastError = message\n this.log(entry, 'system', `spawn failed: ${message}`)\n this.publishServer(entry)\n return { ok: false, error: message }\n }\n\n /**\n * The bookkeeping every spawn shares, plus the exit events that end it. `cwd` lets\n * `describeSpawnError` tell a missing working directory from a missing program (both `ENOENT`).\n */\n private attachChild(entry: Entry, child: ChildProcess, detail: string, cwd: string, flush?: () => void): void {\n entry.child = child\n // A new run: whatever an earlier step said no longer describes it, and readiness only acts on `starting`.\n entry.status = 'starting'\n entry.lastError = null\n entry.pid = child.pid ?? null\n entry.startedAt = Date.now()\n // The durable record of a detached child. Not for a persistent entry: its nanny's state file is that record.\n if (!entry.config.persistent && child.pid !== undefined) {\n entry.lastChild = { pid: child.pid, startedAt: entry.startedAt }\n this.ctx.persist(entry)\n }\n this.options.history.record(entry.config.id, { type: 'start', detail, actor: entry.actor })\n entry.exitCode = null\n entry.exitSignal = null\n entry.nannyExit = null\n entry.lastProbeAt = 0\n resetHealth(entry)\n this.publishServer(entry)\n\n child.once('error', (error) => {\n // Name the program and what to check, not raw errno text.\n entry.lastError = describeSpawnError(error as NodeJS.ErrnoException, entry.config.command, cwd)\n this.log(entry, 'system', `process error: ${entry.lastError}`)\n flush?.()\n this.handleExit(entry, child, null, null)\n })\n\n child.once('exit', (code, signal) => {\n flush?.()\n this.handleExit(entry, child, code, signal)\n })\n\n void awaitReadiness(this.ctx, entry, child).catch((error: unknown) => {\n logger.error(`the readiness wait for ${entry.config.id} failed`, error)\n })\n }\n\n private handleExit(entry: Entry, child: ChildProcess, code: number | null, signal: NodeJS.Signals | null): void {\n if (entry.child !== child)\n return\n if (entry.pid !== null)\n this.sampler.forget(entry.pid)\n // A nanny's own exit code is only a mirror: the state file decides the reason.\n if (entry.config.persistent)\n this.persistent.consumeExit(entry)\n const nannyExit = entry.nannyExit\n entry.nannyExit = null\n\n entry.child = null\n endProcessReadings(entry)\n // Health describes a process; kept, a crashed server whose port a stranger holds read as green.\n resetHealth(entry)\n entry.exitCode = code\n entry.exitSignal = signal\n\n // Known exited: pids are recycled, and a record kept past its process is a false adoption waiting.\n forgetRecordedChild(this.ctx, entry, child.pid ?? null)\n\n // Both null means the process never got off the ground, so its error says more than \"code null\".\n const neverStarted = nannyExit !== null\n ? nannyExit.code === null && nannyExit.signal === null\n : code === null && signal === null && entry.lastError !== null\n const detail = neverStarted\n ? (entry.lastError ?? 'the entry could not start')\n // One formatter for both kinds of exit, so the same event reads the same however it was run.\n : nannyExit !== null\n ? describeNannyExit(nannyExit)\n : describeNannyExit({ code, signal, runtimeMs: 0, at: Date.now() } as NannyExit)\n const ranForMs = nannyExit?.runtimeMs ?? (entry.startedAt === null ? 0 : Date.now() - entry.startedAt)\n\n // Every exit feeds the rolling window, except a removed entry's: its history was reclaimed.\n if (!entry.removed) {\n this.options.history.record(entry.config.id, {\n type: 'exit',\n detail,\n runtimeMs: ranForMs,\n })\n }\n\n this.afterExit(entry, detail, ranForMs, neverStarted)\n }\n\n /** Once a process is gone, spawned or adopted: back off and retry, or record the crash. */\n private afterExit(entry: Entry, detail: string, ranForMs: number, neverStarted: boolean): void {\n const ranFor = `${Math.max(1, Math.round(ranForMs / 1000))}s`\n\n if (entry.stopping) {\n entry.status = 'stopped'\n this.publishServer(entry)\n return\n }\n\n const restart = entry.config.restart\n if (ranForMs >= restart.resetAfterMs)\n entry.restarts = 0\n // On disk before the retry decision, in case the panel dies again.\n this.ctx.persist(entry)\n\n this.log(entry, 'system', neverStarted ? `did not start: ${detail}` : `exited with ${detail} after ${ranFor}`)\n entry.lastError = neverStarted ? detail : `exited with ${detail}`\n\n if (restart.enabled && entry.restarts < restart.maxRetries) {\n entry.restarts += 1\n this.ctx.persist(entry)\n const backoffMs = computeBackoff(entry.restarts, restart)\n entry.status = 'backoff'\n entry.nextRetryAt = Date.now() + backoffMs\n this.log(entry, 'system', `restart ${entry.restarts}/${restart.maxRetries} in ${backoffMs}ms`)\n entry.retryTimer = setTimeout(() => {\n entry.retryTimer = null\n void this.start(entry.config.id, { retry: true }).catch((error: unknown) => {\n logger.error(`could not restart ${entry.config.id}`, error)\n })\n }, backoffMs)\n entry.retryTimer.unref()\n }\n else {\n entry.status = 'crashed'\n entry.nextRetryAt = null\n // The crash is the answer now; a flag left standing would announce a recovery that never came.\n entry.pendingRestart = null\n entry.lastError = restart.enabled\n ? `gave up after ${restart.maxRetries} retries (${detail})`\n : `${detail} (automatic restart disabled)`\n this.log(entry, 'system', entry.lastError)\n this.options.history.record(entry.config.id, {\n type: 'crash',\n detail: entry.lastError,\n runtimeMs: ranForMs,\n })\n this.notify(entry, 'crash', entry.lastError)\n }\n\n this.publishServer(entry)\n }\n\n private async tick(): Promise<void> {\n if (this.disposed)\n return\n const now = Date.now()\n\n await sampleResources(this.entries.values(), this.sampler, this.docker, now)\n // Cheap when nothing changed (a readdir); birth checks run only for files no entry owns.\n await this.refreshOrphans().catch((error: unknown) => {\n logger.warn('could not refresh the orphaned-process list', error)\n })\n\n // Probes run concurrently: one slow server must not delay the others' health.\n await Promise.allSettled([...this.entries.values()].map(entry => probeEntry(this.ctx, entry, now)))\n\n for (const entry of this.entries.values()) {\n // An adopted process is not our child, so nothing tells us it died.\n if (entry.adopted && entry.pid !== null && !isProcessAlive(entry.pid)) {\n this.handleAdoptedExit(entry)\n continue\n }\n if (await enforceMemoryLimit(this.ctx, entry))\n continue\n if (healthBudgetSpent(entry)) {\n await giveUpOnHealth(this.ctx, entry)\n continue\n }\n if (shouldForceRestart(this.ctx, entry, now)) {\n await this.restart(entry.config.id)\n continue\n }\n if (entry.status === 'backoff' && entry.nextRetryAt !== null && now >= entry.nextRetryAt && entry.retryTimer === null) {\n void this.start(entry.config.id, { retry: true }).catch((error: unknown) => {\n logger.error(`could not restart ${entry.config.id}`, error)\n })\n }\n }\n\n this.publishState()\n }\n\n private clearRetry(entry: Entry): void {\n if (entry.retryTimer !== null) {\n clearTimeout(entry.retryTimer)\n entry.retryTimer = null\n }\n }\n\n private view(entry: Entry): ServerView {\n return buildView(entry, this.options.workspaceId, this.options.history)\n }\n\n private log(entry: Entry, stream: LogStream, text: string): void {\n // A removed entry's artifacts were reclaimed; the stop that follows logs to the console only.\n if (entry.removed) {\n logger.debug(`[${entry.config.id}] ${text}`)\n return\n }\n const line: LogLine = { ts: Date.now(), stream, text }\n entry.logs.push(line)\n this.options.logFiles.append(entry.config.id, line)\n // The relay reads a persistent entry's file back, so this line must be recognizable as ours.\n if (entry.config.persistent && this.options.logFiles.config.persist)\n rememberEchoedLine(entry.echoed, line)\n this.hub.publish({ type: 'log', ts: line.ts, workspaceId: this.options.workspaceId, serverId: entry.config.id, lines: [line] })\n if (stream === 'system')\n logger.debug(`[${entry.config.id}] ${text}`)\n }\n\n private publishServer(entry: Entry): void {\n if (!this.entries.has(entry.config.id))\n return\n this.hub.publish({\n type: 'server',\n ts: Date.now(),\n workspaceId: this.options.workspaceId,\n serverId: entry.config.id,\n server: this.view(entry),\n })\n }\n\n /** Signals the panel, which diffs the aggregate state and publishes at most one frame. */\n private publishState(): void {\n this.options.onStateChange()\n }\n}\n","import type { GlobalSettingsStore } from '#src/config/settings'\nimport type { WorkspaceRegistry } from '#src/config/workspaces'\nimport type { AuthService } from '#src/services/auth'\nimport type { BackupService, BackupSources } from '#src/services/backups'\nimport type { ControlEndpoint } from '#src/services/control-server'\nimport type { EventHub } from '#src/services/events'\nimport type { HostMonitor } from '#src/services/host-monitor'\nimport type { ProxyService } from '#src/services/proxy'\nimport type { TlsStore } from '#src/services/tls'\nimport type { UiService } from '#src/services/ui'\nimport type { AppState, DdnsAccount, ProxyDnsAccountView, ServerConfig, ServerView, Workspace, WorkspaceView } from '#src/shared/contracts'\nimport fs from 'node:fs'\nimport path from 'node:path'\nimport { SecretsStore } from '#src/config/secrets'\nimport { WorkspaceStore } from '#src/config/store'\nimport { WorkspaceError } from '#src/config/workspaces'\nimport { logger } from '#src/helpers/logger'\nimport {\n dataRoot,\n projectDir,\n workspaceDdnsStatePath,\n workspaceDir,\n workspaceHistoryPath,\n workspaceLegacyDdnsStatePath,\n workspaceLogsDir,\n workspaceSecretsPath,\n workspaceServersPath,\n workspaceSettingsPath,\n workspaceStateDir,\n} from '#src/helpers/paths'\nimport { appVersion } from '#src/helpers/version'\nimport { ddnsProvider } from '#src/providers/ddns'\nimport { entryStatePath, readEntryState, writeEntryState } from '#src/providers/entry-state'\nimport { buildBackupSources } from '#src/services/backups'\nimport { ConfigWatch } from '#src/services/config-watch'\nimport { DdnsService } from '#src/services/ddns'\nimport { HistoryStore } from '#src/services/history'\nimport { LogFiles } from '#src/services/log-files'\nimport { NotificationService } from '#src/services/notifications'\nimport { buildControlView, buildWorkspaceView } from '#src/services/state'\nimport { Supervisor } from '#src/services/supervisor'\nimport { errorMessage } from '#src/shared/error-message'\n\n/** Everything one workspace owns at runtime, plus the objects that watch it. */\nexport interface WorkspaceRuntime {\n id: string\n label: string\n store: WorkspaceStore\n secrets: SecretsStore\n logFiles: LogFiles\n history: HistoryStore\n notifications: NotificationService\n ddns: DdnsService\n supervisor: Supervisor\n watches: ConfigWatch[]\n logsDir: string\n /** The config error last written to the log, so a standing typo is reported once. */\n reportedConfigError: string | null\n /** The state frame's view of this runtime, rebuilt on every read. */\n view: () => WorkspaceView\n}\n\nexport interface PanelServiceOptions {\n registry: WorkspaceRegistry\n /** The panel-wide settings: listener, auth, TLS policy, host vitals, backups. */\n settings: GlobalSettingsStore\n /** The panel-wide secrets: password hash and API token. */\n secrets: SecretsStore\n auth: AuthService\n tls: TlsStore\n backups: BackupService\n ui: UiService\n hostMonitor: HostMonitor\n hub: EventHub\n /** The live listener; read lazily because it is created after this service. */\n control: () => ControlEndpoint\n /** The panel-wide reverse proxy; read lazily for the same reason. */\n proxy: () => ProxyService | null\n /** `--no-autostart` still means \"start nothing on your own\", reloads included. */\n autostart: boolean\n}\n\nconst TICK_MS = 1000\n\n/**\n * The panel process at the workspace level: one runtime per workspace, one\n * aggregate state frame, and the CRUD a workspace selector needs.\n *\n * Every workspace gets its own store, secrets, log files, history, DDNS service\n * and supervisor, so nothing an entry does can leak across the unit a person\n * chose to separate it into. Only what is genuinely panel-wide — the listener,\n * auth, TLS, host vitals, backups, UI — stays here.\n */\nexport class PanelService {\n private readonly runtimes = new Map<string, WorkspaceRuntime>()\n private readonly timer: NodeJS.Timeout\n private disposed = false\n private lastStateSignature = ''\n private stateScheduled = false\n\n constructor(private readonly options: PanelServiceOptions) {\n for (const workspace of this.options.registry.all())\n this.runtimes.set(workspace.id, this.createRuntime(workspace))\n\n // Config errors and warnings are reported by the caller that owns the startup\n // decision (`runControlPlane` refuses on them); repeating them here would print\n // the same line twice before the refusal.\n\n this.timer = setInterval(() => {\n void this.tick().catch((error: unknown) => logger.error('the panel tick failed', error))\n }, TICK_MS)\n this.timer.unref()\n }\n\n get settings(): GlobalSettingsStore {\n return this.options.settings\n }\n\n get registry(): WorkspaceRegistry {\n return this.options.registry\n }\n\n get hub(): EventHub {\n return this.options.hub\n }\n\n workspaces(): WorkspaceRuntime[] {\n return [...this.runtimes.values()]\n }\n\n workspace(id: string): WorkspaceRuntime | undefined {\n return this.runtimes.get(id)\n }\n\n /** The id a workspace-scoped request without one resolves to. */\n defaultId(): string {\n const preferred = this.options.registry.defaultId\n return this.runtimes.has(preferred) ? preferred : this.runtimes.values().next().value?.id ?? ''\n }\n\n requireWorkspace(id?: string): WorkspaceRuntime {\n const resolved = id === undefined || id.length === 0 ? this.defaultId() : id\n const runtime = this.runtimes.get(resolved)\n if (runtime === undefined)\n throw new WorkspaceError(`unknown workspace \"${id ?? resolved}\"`)\n return runtime\n }\n\n /** Resolves a `(workspace, server)` pair, the only unique key now that ids repeat. */\n findServer(workspaceId: string, serverId: string): { workspace: WorkspaceRuntime, config: ServerConfig } | null {\n const workspace = this.runtimes.get(workspaceId)\n if (workspace === undefined)\n return null\n const config = workspace.store.getServer(serverId)\n return config === undefined ? null : { workspace, config }\n }\n\n /**\n * One workspace's DDNS account, credentials included, for the panel-wide proxy.\n *\n * The account stays where it lives — a workspace owns its secrets and its\n * notification routing — so the proxy references it instead of holding a copy.\n */\n findDnsAccount(workspaceId: string, accountId: string): { workspace: WorkspaceRuntime, account: DdnsAccount, credentials: Record<string, string> | null } | null {\n const workspace = this.runtimes.get(workspaceId)\n if (workspace === undefined)\n return null\n const account = workspace.store.ddns.accounts.find(entry => entry.id === accountId)\n if (account === undefined)\n return null\n return {\n workspace,\n account,\n credentials: workspace.secrets.getDdnsCredentials(accountId, account.provider)?.values ?? null,\n }\n }\n\n /**\n * Every DNS account a proxy route may name, across every workspace.\n *\n * A route references `<workspace>/<account>`, so the picker needs all of them; the\n * account itself never leaves the workspace that owns it.\n */\n listDnsAccounts(): ProxyDnsAccountView[] {\n const accounts: ProxyDnsAccountView[] = []\n for (const workspace of this.runtimes.values()) {\n for (const account of workspace.store.ddns.accounts) {\n const provider = ddnsProvider(account.provider)\n accounts.push({\n workspace: workspace.id,\n account: account.id,\n provider: account.provider,\n label: account.label,\n writesTxt: provider?.challenge !== undefined,\n hasCredentials: workspace.secrets.getDdnsCredentials(account.id, account.provider) !== null,\n })\n }\n }\n return accounts\n }\n\n serverViews(workspaceId?: string): ServerView[] {\n if (workspaceId !== undefined)\n return this.runtimes.get(workspaceId)?.supervisor.views() ?? []\n return this.workspaces().flatMap(runtime => runtime.supervisor.views())\n }\n\n /**\n * The running servers of every workspace *except* `except`, so one supervisor can recognize a\n * sibling workspace's process as one the panel owns rather than a stranger to signal — and can\n * name it when it refuses.\n *\n * Read from the live views rather than from nanny state: an adopted entry has no child record,\n * and a persistent one's pid is the nanny's, whose tree the supervisor walks itself.\n */\n siblingServers(except: string): Array<{ pid: number, workspaceId: string, serverId: string }> {\n return this.workspaces()\n .filter(runtime => runtime.id !== except)\n .flatMap(runtime => runtime.supervisor.views()\n .filter(view => view.pid !== null)\n .map(view => ({ pid: view.pid!, workspaceId: runtime.id, serverId: view.id })))\n }\n\n getState(): AppState {\n const proxy = this.options.proxy()\n return {\n control: buildControlView(this.options.settings, this.options.auth, this.options.control(), this.options.tls),\n host: this.options.hostMonitor.view,\n backups: this.options.backups.view(),\n ui: this.options.ui.status(),\n workspaces: this.workspaces().map(runtime => runtime.view()),\n ...(proxy === null ? {} : { proxy: proxy.view() }),\n projectDir,\n dataRoot,\n version: appVersion(),\n }\n }\n\n /** The sources a backup archive is built from and restored into. */\n backupSources(): BackupSources {\n return buildBackupSources({\n globalSettingsPath: this.options.settings.path,\n globalSecretsPath: this.options.secrets.path,\n tlsDir: this.options.tls.directory,\n registryPath: this.options.registry.path,\n includePaths: this.options.settings.backups.includePaths,\n // Live state, so a restore can say whose data it replaced under a running process.\n runningServers: () => this.workspaces().flatMap(runtime =>\n runtime.supervisor.views()\n .filter(view => view.status === 'running')\n .map(view => ({ workspaceId: runtime.id, serverId: view.id })),\n ),\n workspaces: this.workspaces().map(runtime => ({\n id: runtime.id,\n label: runtime.label,\n // The runtime's own paths, never ones re-derived from the module constants.\n settingsPath: runtime.store.settingsPath,\n serversPath: runtime.store.path,\n secretsPath: runtime.secrets.path,\n servers: runtime.store.servers,\n })),\n })\n }\n\n create(input: { id?: string, label?: string }): WorkspaceView {\n const workspace = this.options.registry.create(input)\n const runtime = this.createRuntime(workspace)\n this.runtimes.set(workspace.id, runtime)\n logger.info(`workspace \"${workspace.id}\" created at ${workspaceDir(workspace.id)}`)\n this.scheduleState()\n return runtime.view()\n }\n\n /**\n * Registers a workspace an archive brought but this host did not have, then builds\n * its runtime so the files a restore is about to write have an owner.\n *\n * Idempotent, and it never touches an existing workspace: a restore must fill one\n * that is already here, not replace its label or its runtime.\n */\n ensureWorkspace(input: { id: string, label: string }): void {\n if (this.options.registry.has(input.id))\n return\n const workspace = this.options.registry.create(input)\n const runtime = this.createRuntime(workspace)\n this.runtimes.set(workspace.id, runtime)\n logger.info(`workspace \"${workspace.id}\" restored from an archive`)\n // Its leaves were written before this ran, so `createRuntime` already loaded them —\n // which means the `reloadAll()` that follows sees no *new* ids here. Start them now,\n // for the same reason that method starts the ones it reveals.\n this.startRestored(runtime, new Set())\n this.scheduleState()\n }\n\n rename(id: string, label: string): WorkspaceView {\n const workspace = this.options.registry.rename(id, label)\n const runtime = this.runtimes.get(id)\n if (runtime === undefined)\n throw new WorkspaceError(`unknown workspace \"${id}\"`)\n runtime.label = workspace.label\n this.scheduleState()\n return runtime.view()\n }\n\n /**\n * Stops every entry the workspace supervises — persistent ones included, because\n * deleting a workspace removes the state file its nanny would be found through —\n * and then removes its directory.\n */\n async remove(id: string): Promise<Workspace> {\n const runtime = this.runtimes.get(id)\n if (runtime === undefined)\n throw new WorkspaceError(`unknown workspace \"${id}\"`)\n if (this.runtimes.size <= 1)\n throw new WorkspaceError('cannot remove the only workspace')\n\n for (const server of runtime.store.servers) {\n const stopped = await runtime.supervisor.stop(server.id).catch((error: unknown) => {\n logger.warn(`could not stop ${server.id} while removing workspace \"${id}\"`, error)\n return { ok: true, error: undefined } as Awaited<ReturnType<typeof runtime.supervisor.stop>>\n })\n // A pid that outlived SIGKILL is deliberately kept findable: `stopEntry` keeps its nanny state\n // file because \"its pid is in the state file\" is how a later boot reaches the child the stop\n // could not forward. That file lives under `workspaceDir(id)`, which the `rmSync` below deletes\n // recursively — so removing anyway would leave the process running with nothing that knows its\n // name. Refused; the person can stop it and remove the workspace afterwards.\n if (!stopped.ok && stopped.error?.includes('survived the stop'))\n throw new WorkspaceError(`cannot remove \"${id}\": ${stopped.error} — stop it first, or the workspace would be deleted while that process is still running and unreachable from here`)\n }\n await runtime.supervisor.dispose()\n this.disposeRuntime(runtime)\n this.runtimes.delete(id)\n\n const entry = this.options.registry.remove(id)\n fs.rmSync(workspaceDir(id), { recursive: true, force: true })\n logger.info(`workspace \"${id}\" removed`)\n this.scheduleState()\n return entry\n }\n\n /**\n * Re-reads every workspace and the global settings, e.g. after a restore.\n *\n * `store.load()` resets the byte baseline the config watcher compares against, so the\n * poll that follows sees \"no change\" and never reaches its autostart pass. The entries\n * an archive brought therefore waited for a panel restart — which is why the start of\n * newly appeared autostart entries belongs here, the one place that knows what was new.\n */\n /**\n * Record a dump a restore staged, so this entry's next start loads it.\n *\n * Written to the entry's own state file rather than memory: the restore usually happens before the\n * entry has ever started, and a panel restart between the two must not lose the load.\n */\n stagePendingLoad(workspaceId: string, serverId: string, dumpDir: string): void {\n // The supervisor owns both the entry and its state file, so it does the writing when there is\n // one. On a blank host there is not: the restore creates the workspace, and its runtime appears\n // only when `reloadAll` runs — so the state file is written here and the supervisor picks it up\n // on the start that follows. An optional chain would silently drop the load instead.\n // Whether the supervisor can record it is not the same as whether it has an entry: a workspace\n // whose config the restore is about to write has a runtime but no entry yet, and the supervisor\n // returns silently. So the state file is the authority, written here in every case.\n const stateDir = workspaceStateDir(workspaceId)\n // The directory is created here: `writeEntryState` is best-effort and swallows a failure, so on a\n // blank host — where the workspace's `.state/` does not exist yet — the staged load vanished\n // without a word.\n fs.mkdirSync(stateDir, { recursive: true })\n const statePath = entryStatePath(stateDir, serverId)\n writeEntryState(statePath, {\n ...(readEntryState(statePath) ?? { restarts: 0, bootstrapDone: false }),\n pendingLoad: dumpDir,\n })\n // And tell the supervisor, which kicks the load if the entry is already up.\n this.runtimes.get(workspaceId)?.supervisor.stagePendingLoad(serverId, dumpDir)\n }\n\n reloadAll(): void {\n this.options.settings.load()\n for (const runtime of this.workspaces()) {\n const before = new Set(runtime.store.servers.map(server => server.id))\n runtime.store.load()\n runtime.history.load()\n this.pruneLogs(runtime)\n this.reportWorkspaceErrors(runtime.id)\n this.startRestored(runtime, before)\n }\n this.scheduleState()\n }\n\n /**\n * Applies a lowered `logs.keep` to the files already on disk, after any reload.\n *\n * `keep` bounds the directory, not the next rotation — and a quiet entry may not fill a file for\n * days, so \"I lowered it\" must not mean \"eventually\". The HTTP settings route always did this;\n * the hand-edit paths (`handleConfigChange`, `reloadAll`) reloaded the store and stopped there, so\n * a `settings.json` edit left `.3`…`.5` sitting under a `keep: 2` that the same docs invite a\n * person to write. One derivation, called from every path that can lower it, because pruning is\n * idempotent and cheap: it is one `readdir` per workspace.\n */\n private pruneLogs(runtime: WorkspaceRuntime): void {\n try {\n runtime.logFiles.prune()\n }\n catch (error) {\n // A directory that cannot be listed is reported by the Logs page, not by a reload.\n logger.warn(`workspace \"${runtime.id}\": could not prune the log rotations: ${errorMessage(error)}`)\n }\n }\n\n /** Starts the autostart entries a reload just revealed, exactly as a hand edit would. */\n private startRestored(runtime: WorkspaceRuntime, before: Set<string>): void {\n if (!this.options.autostart)\n return\n for (const server of runtime.store.servers) {\n if (before.has(server.id) || !server.enabled || !server.autostart)\n continue\n void runtime.supervisor.start(server.id, { actor: 'boot' }).catch((error: unknown) => {\n logger.error(`could not start the restored server ${server.id}`, error)\n })\n }\n }\n\n /** Starts whatever the config marks autostart, across every workspace. */\n async startAll(workspaces: string[] = this.workspaces().map(runtime => runtime.id)): Promise<void> {\n for (const id of workspaces) {\n const runtime = this.runtimes.get(id)\n if (runtime === undefined)\n continue\n try {\n await runtime.supervisor.startAll({ autostartOnly: true })\n }\n catch (error) {\n logger.error(`autostart failed for workspace \"${id}\"`, error)\n }\n }\n }\n\n /** `withPersistent` reaches every workspace's supervisor: a `down` is host-wide. */\n async dispose(options: { withPersistent?: boolean } = {}): Promise<void> {\n this.disposed = true\n clearInterval(this.timer)\n this.options.backups.dispose()\n await Promise.all(this.workspaces().map(runtime => runtime.supervisor.dispose(options)))\n for (const runtime of this.workspaces()) this.disposeRuntime(runtime)\n }\n\n // ------------------------------------------------------------------ internals\n\n private createRuntime(workspace: Workspace): WorkspaceRuntime {\n const id = workspace.id\n fs.mkdirSync(workspaceDir(id), { recursive: true })\n\n const store = new WorkspaceStore(id, workspaceSettingsPath(id), workspaceServersPath(id))\n store.load()\n store.writeJsonSchema()\n\n const secrets = new SecretsStore(workspaceSecretsPath(id), undefined, 'workspace')\n const logFiles = new LogFiles(workspaceLogsDir(id), () => store.logs)\n const history = new HistoryStore(workspaceHistoryPath(id))\n const notifications = new NotificationService(secrets, () => store.notifications)\n const ddns = new DdnsService({\n getConfig: () => store.ddns,\n getCredentials: (accountId, provider) => secrets.getDdnsCredentials(accountId, provider)?.values ?? null,\n notifications,\n statePath: workspaceDdnsStatePath(id),\n legacyStatePath: workspaceLegacyDdnsStatePath(id),\n })\n\n const supervisor = new Supervisor(store, this.options.hub, {\n workspaceId: id,\n configPath: store.path,\n control: this.options.control(),\n history,\n logFiles,\n notifications,\n onStateChange: () => this.scheduleState(),\n nannyDir: workspaceStateDir(id),\n // Lazily, so a workspace created later is still part of the answer: the runtimes map is read\n // at call time, never captured when this supervisor was built.\n siblingServers: async () => this.siblingServers(id),\n })\n\n const runtime: WorkspaceRuntime = {\n id,\n label: workspace.label,\n store,\n secrets,\n logFiles,\n history,\n notifications,\n ddns,\n supervisor,\n watches: [],\n logsDir: logFiles.directory,\n reportedConfigError: store.configError,\n view: () => buildWorkspaceView({\n id,\n label: runtime.label,\n store,\n logsDir: logFiles.directory,\n notifications,\n ddns,\n supervisor,\n }),\n }\n\n runtime.watches = [\n new ConfigWatch({ file: store.path, onChange: () => this.handleConfigChange(id), onError: error => logger.warn(`cannot watch ${path.basename(store.path)}: ${errorMessage(error)}`) }),\n new ConfigWatch({ file: store.settingsPath, onChange: () => this.handleConfigChange(id), onError: error => logger.warn(`cannot watch ${path.basename(store.settingsPath)}: ${errorMessage(error)}`) }),\n ]\n for (const watch of runtime.watches) watch.start()\n\n return runtime\n }\n\n private disposeRuntime(runtime: WorkspaceRuntime): void {\n for (const watch of runtime.watches) watch.dispose()\n runtime.logFiles.dispose()\n runtime.history.dispose()\n runtime.ddns.dispose()\n }\n\n private reportWorkspaceErrors(id: string): void {\n const runtime = this.runtimes.get(id)\n if (runtime === undefined)\n return\n if (runtime.store.configError !== null)\n logger.error(`workspace \"${id}\": ${runtime.store.configError} — keeping the config already running`)\n for (const warning of runtime.store.configWarnings) logger.warn(`workspace \"${id}\": ${warning}`)\n }\n\n /**\n * A workspace file edited by hand is picked up without a restart. A revision\n * this release cannot read is reported in the state frame, and the workspace\n * keeps running what it had — a typo never stops a server.\n */\n private handleConfigChange(id: string): void {\n const runtime = this.runtimes.get(id)\n if (runtime === undefined)\n return\n\n const before = new Set(runtime.store.servers.map(server => server.id))\n const result = runtime.store.reloadFromDisk()\n\n // One line per change of state, not one per poll: a typo stays a typo until\n // somebody fixes it, and the watcher checks every two seconds.\n const currentError = runtime.store.configError\n if (currentError !== runtime.reportedConfigError) {\n runtime.reportedConfigError = currentError\n if (currentError === null)\n logger.info(`workspace \"${id}\": the config is readable again`)\n else\n logger.error(`workspace \"${id}\": ${currentError} — keeping the config already running`)\n }\n\n if (!result.applied) {\n if (result.changed && currentError === null)\n logger.info(`workspace \"${id}\": the config changed, but not in a way that changes it`)\n this.scheduleState()\n return\n }\n\n // A hand edit can lower `logs.keep`; the settings route prunes at save, and this is the same\n // intent arriving through the file instead.\n this.pruneLogs(runtime)\n\n const added = runtime.store.servers.filter(server => !before.has(server.id))\n const removed = [...before].filter(serverId => !runtime.store.getServer(serverId))\n logger.info(`workspace \"${id}\" config reloaded — ${runtime.store.servers.length} server(s)${added.length === 0 ? '' : `, ${added.length} added`}${removed.length === 0 ? '' : `, ${removed.length} removed`}`)\n\n this.scheduleState()\n if (!this.options.autostart)\n return\n for (const server of added) {\n if (!server.enabled || !server.autostart)\n continue\n void runtime.supervisor.start(server.id).catch((error: unknown) => {\n logger.error(`could not start the added server ${server.id}`, error)\n })\n }\n }\n\n private async tick(): Promise<void> {\n if (this.disposed)\n return\n const now = Date.now()\n await this.options.hostMonitor.tick(now)\n // Deliberately not awaited, like DDNS below: archiving a large data path must not hold up\n // health probes or the state frame.\n this.options.backups.tick(now)\n for (const runtime of this.workspaces()) {\n // Deliberately not awaited: a provider that is slow to answer must not hold\n // up anything else.\n runtime.ddns.tick(now)\n }\n // A certificate that arrives (or expires) changes what the proxy serves on the\n // cleartext port, so the engine is re-applied when that state moves. Cheap: the\n // certificate store is read once and cached.\n const proxy = this.options.proxy()\n if (proxy !== null) {\n await proxy.sync().catch((error: unknown) => {\n logger.warn('the proxy certificate check failed', error)\n })\n }\n this.scheduleState()\n }\n\n /** A panel-wide service changed something the state frame carries. */\n notifyStateChange(): void {\n this.scheduleState()\n }\n\n /** Coalesces every signal in a turn into at most one frame. */\n private scheduleState(): void {\n if (this.stateScheduled || this.disposed)\n return\n this.stateScheduled = true\n setImmediate(() => {\n this.stateScheduled = false\n if (!this.disposed)\n this.publishState()\n })\n }\n\n private publishState(): void {\n const state = this.getState()\n const signature = stateSignature(state)\n if (signature === this.lastStateSignature)\n return\n this.lastStateSignature = signature\n this.options.hub.publish({ type: 'state', ts: Date.now(), state })\n }\n}\n\n/** A cheap change key: everything the UI redraws from, nothing it does not. */\nfunction stateSignature(state: AppState): string {\n return [\n // Whole, like the host view below: a hand-picked list missed `apiTokenSet`, `passwordSet` and\n // `allowedHosts`, so another tab never saw a token minted or a password set.\n JSON.stringify(state.control),\n /*\n * The whole host view, not a list of its fields. Signing only `sampledAt` and `alerts` published\n * nothing when sampling was switched off — that branch of `HostMonitor.tick` changes `enabled`\n * alone — so every other tab kept drawing dials. A field this list omits is a change no client\n * sees; the measurement is in `.agentDocs/GOTCHAS.md`.\n */\n JSON.stringify(state.host),\n // The archive list and the capture entries are no longer in the frame — they are `GET\n // /api/backups`, fetched when the settings page mounts — so a new archive does not change this\n // signature. `lastAutomaticAt` and `scheduleError` are the policy facts a page still redraws from.\n state.backups.lastAutomaticAt,\n state.backups.scheduleError?.at ?? 0,\n // Which UI the panel serves. `ui.status()` reads the installed `ui.json`, so an upload\n // or a revert is news the moment it happens — and without this it was only picked up when\n // something else moved, which the host sample eventually does (up to one interval later).\n `${state.ui.custom}:${state.ui.meta?.name ?? ''}:${state.ui.meta?.version ?? ''}`,\n // The proxy is the one panel-wide service whose live state changes on its own\n // (a start, a stop, a rejected route), so it has to be part of the signature.\n state.proxy === undefined\n ? ''\n : [\n state.proxy.config.enabled,\n state.proxy.status.state,\n state.proxy.status.pid,\n state.proxy.status.lastError ?? '',\n state.proxy.engine.installed,\n state.proxy.engine.version ?? '',\n ...state.proxy.routes.map(route => `${route.route.id}:${route.status}:${route.upstream ?? ''}`),\n ].join(':'),\n /*\n * The whole workspace view, for the reason the host view above is signed whole: a hand-picked\n * list left out `orphans`, so a stray process appearing or going published nothing.\n */\n ...state.workspaces.map(workspace => JSON.stringify(workspace)),\n ].join('|')\n}\n","import type { UiSourceContext } from '#src/providers/ui-release'\nimport type { UiService } from '#src/services/ui'\nimport process from 'node:process'\nimport { logger } from '#src/helpers/logger'\nimport { appVersion } from '#src/helpers/version'\nimport {\n assetDownloadUrl,\n DEFAULT_REPO,\n downloadToTemp,\n fetchRelease,\n isOwnRepo,\n isUiAsset,\n matchAsset,\n parseRepoSlug,\n} from '#src/providers/ui-release'\nimport { errorMessage } from '#src/shared/error-message'\n\n/**\n * Keeping an *official* UI paired with the panel that serves it, without a person\n * having to notice. A UI from `NamesMT/home-hosted` is built for a release, and this\n * panel knows its own release, so \"the wrong tag\" is a fact rather than a preference —\n * unlike someone else's UI, where only the person can say what they want.\n *\n * Only ever installed by tag, never by guess, and every failure is a log line: this runs\n * at startup, and a UI problem must never stop a panel from serving.\n */\n\nexport type UiSyncResult = { kind: 'not-custom' }\n | { kind: 'foreign' }\n | { kind: 'no-identity' }\n | { kind: 'current', tag: string }\n | { kind: 'updated', tag: string }\n | { kind: 'failed', error: string }\n\n/**\n * `ui.json` says which release this build came from. Anything else — an unofficial UI,\n * or one that never declared itself — is left for `home-hosted ui-update`.\n */\nexport function officialTagFor(\n meta: { repo?: string, tag?: string } | null,\n runningVersion: string,\n): { tag: string, repo: string } | null {\n if (meta === null || typeof meta.repo !== 'string')\n return null\n const repo = parseRepoSlug(meta.repo)\n if (repo === null || !isOwnRepo(repo))\n return null\n return { tag: `v${runningVersion}`, repo: `${repo.owner}/${repo.name}` }\n}\n\nexport async function syncOfficialUi(ui: UiService, runningVersion = appVersion()): Promise<UiSyncResult> {\n if (!ui.custom)\n return { kind: 'not-custom' }\n\n const meta = ui.readMeta()\n if (meta === null)\n return { kind: 'no-identity' }\n\n const repo = meta.repo === undefined ? null : parseRepoSlug(meta.repo)\n if (repo === null)\n return { kind: 'no-identity' }\n if (!isOwnRepo(repo))\n return { kind: 'foreign' }\n\n const target = `v${runningVersion}`\n if (meta.tag === target)\n return { kind: 'current', tag: target }\n\n const context: UiSourceContext = {\n io: { write: () => {}, style: { bold: (t: string) => t, dim: (t: string) => t, green: (t: string) => t } },\n version: runningVersion,\n // The one unattended call may use a token like the interactive commands do; without\n // one, a shared or CI address hits GitHub's 60/hour unauthenticated limit.\n token: process.env.GITHUB_TOKEN ?? process.env.GH_TOKEN ?? null,\n quiet: true,\n }\n\n try {\n const release = await fetchRelease(repo, target, context)\n const names = release.assets.map(asset => asset.name ?? '').filter(isUiAsset)\n if (names.length === 0)\n throw new Error(`no UI asset in ${DEFAULT_REPO}@${release.tag}`)\n\n // The asset this UI came from, or the only one on offer when it never said.\n const wanted = meta.asset ?? ''\n const matched = wanted.length > 0 ? matchAsset(names, wanted) : { ok: true as const, name: names[0]! }\n if (!matched.ok)\n throw new Error(matched.error)\n\n const asset = release.assets.find(entry => entry.name === matched.name)\n if (asset === undefined)\n throw new Error(`no asset named ${matched.name} in ${release.tag}`)\n\n const download = await downloadToTemp(assetDownloadUrl(asset), {\n 'accept': 'application/octet-stream',\n 'user-agent': `home-hosted/${runningVersion}`,\n }, context)\n\n try {\n // The tag is the release we just fetched, never what the archive claims.\n const result = await ui.install(download.file, matched.name.replace(/\\.zip$/i, ''), release.tag)\n if (!result.ok)\n throw new Error(result.error)\n }\n finally {\n const fs = await import('node:fs')\n fs.rmSync(download.dir, { recursive: true, force: true })\n }\n\n return { kind: 'updated', tag: release.tag }\n }\n catch (error) {\n return { kind: 'failed', error: errorMessage(error) }\n }\n}\n\n/**\n * The startup hook. Never awaited by the caller and never allowed to throw: the panel\n * serves the UI it already has while this runs, and the next request picks up the new\n * one, because `UiService.resolveDir()` is read per request.\n */\nexport function autoUpdateOfficialUi(ui: UiService, runningVersion = appVersion()): void {\n if (!ui.custom)\n return\n\n const meta = ui.readMeta()\n const plan = officialTagFor(meta, runningVersion)\n if (plan === null || meta?.tag === plan.tag)\n return\n\n logger.info(`ui: ${meta?.name ?? 'custom UI'} ${meta?.version ?? ''} came from ${meta?.tag ?? 'an unknown release'}; this panel is ${plan.tag} — updating`)\n\n void syncOfficialUi(ui, runningVersion).then((result) => {\n if (result.kind === 'updated')\n logger.info(`ui: updated to ${result.tag} — refresh the browser`)\n else if (result.kind === 'failed')\n logger.warn(`ui: could not update to ${plan.tag}: ${result.error}`)\n }).catch((error: unknown) => {\n logger.warn(`ui: could not update: ${errorMessage(error)}`)\n })\n}\n","import type { AppType } from '#src/app'\nimport type { Runtime } from '#src/helpers/daemon'\nimport type { NotificationEvent } from '#src/services/notifications'\nimport fs from 'node:fs'\nimport os from 'node:os'\nimport path from 'node:path'\nimport process from 'node:process'\nimport { createRootApp } from '#src/app'\nimport { ensureLayout } from '#src/config/layout'\nimport { generateInitialPassword, SecretsStore } from '#src/config/secrets'\nimport { GlobalSettingsStore } from '#src/config/settings'\nimport { WorkspaceRegistry } from '#src/config/workspaces'\nimport { readStateFile } from '#src/helpers/config-text'\nimport { clearRuntime, newToken, readRuntime, runtimeIsAlive, runtimeIsGone, writeRuntime } from '#src/helpers/daemon'\nimport { logger } from '#src/helpers/logger'\nimport { openBrowser } from '#src/helpers/open'\nimport {\n daemonLogPath,\n dataRoot,\n globalSecretsPath,\n hhDir,\n projectDir,\n proxyAdminPath,\n proxyBinDir,\n proxyConfigPath,\n proxyEngineDir,\n proxyPreviousConfigPath,\n proxyStateDir,\n proxyTlsDir,\n resolveUserPath,\n tlsDir,\n} from '#src/helpers/paths'\nimport { resolveTemplate } from '#src/helpers/template'\nimport { appVersion, packageRoot } from '#src/helpers/version'\nimport { isPortFree, listPortHolders } from '#src/providers/port'\nimport { AcmeChallengeService } from '#src/services/acme-challenge'\nimport { AuthService } from '#src/services/auth'\nimport { BackupService } from '#src/services/backups'\nimport { ConfigWatch } from '#src/services/config-watch'\nimport { ControlServer } from '#src/services/control-server'\nimport { EventHub } from '#src/services/events'\nimport { checkExposure, checkProxyExposure, proxyTrustWarning } from '#src/services/exposure'\nimport { HostMonitor } from '#src/services/host-monitor'\nimport { PanelService } from '#src/services/panel'\nimport { ProxyService } from '#src/services/proxy'\nimport { TlsStore } from '#src/services/tls'\nimport { UiService } from '#src/services/ui'\nimport { autoUpdateOfficialUi } from '#src/services/ui-update'\nimport { parseBind } from '#src/shared/contracts'\nimport { errorMessage } from '#src/shared/error-message'\n\nexport interface ControlPlaneOptions {\n /** One-off overrides, persisted only after every guard below passes. */\n port?: number\n host?: string\n autostart: boolean\n open: boolean\n /** Print the effective settings and workspaces and exit without starting anything. */\n printConfig: boolean\n}\n\n/** A probe target for a `lan` bind, which is not connectable as `0.0.0.0`. */\nfunction probeHostFor(bindHost: string): string {\n return bindHost === '0.0.0.0' || bindHost === '::' ? '127.0.0.1' : bindHost\n}\n\n/**\n * Runs the control plane in *this* process until it is stopped. `home-hosted up`\n * detaches a child that calls this; `--foreground` (systemd, docker) calls it\n * directly.\n */\nexport async function runControlPlane(options: ControlPlaneOptions): Promise<void> {\n // A state directory this release cannot use stops the daemon before anything reads\n // a path into it. Caught rather than thrown: a detached `up` runs this in a child, and\n // an unhandled rejection there is a stack trace instead of one line naming the fix.\n try {\n ensureLayout()\n }\n catch (error) {\n logger.error(errorMessage(error))\n process.exit(1)\n }\n restrictStateDir()\n\n const existing = readRuntime()\n // A live pid is not proof the panel is up: the OS recycles pids, and a stale record's own\n // `startedAt` is what tells this daemon from whatever inherited the number.\n //\n // `--print-config` starts nothing, so it is not the second panel this guard exists to stop: it\n // answers \"already running\" on the one home a person most wants to inspect — the live one — and\n // exited 1 there while `up --print-config` promises only to print and exit. Every other guard\n // below still runs, so a config this release would refuse is still reported.\n if (!options.printConfig && existing !== null && existing.pid !== process.pid && await runtimeIsAlive(existing)) {\n logger.error(`already running (pid ${existing.pid}) at ${existing.url} — run \\`home-hosted down\\` first`)\n process.exit(1)\n }\n // Deleted only when nothing is behind the pid; see `runtimeIsGone`. Otherwise the live daemon\n // overwrites the record when it writes its own below.\n if (existing !== null && await runtimeIsGone(existing))\n clearRuntime()\n\n const settings = new GlobalSettingsStore()\n settings.load()\n settings.writeJsonSchema()\n\n // A settings file this release cannot read is refused rather than run with\n // defaults: for `control` that would mean a different port, bind and auth policy\n // than the file asked for.\n //\n // A *pending migration* reaches this error too — `readStamp` refuses a file whose\n // schema still has steps to run — so the migration gets its own advice **first**.\n // Printing \"fix … or install the release that wrote it\" for a file that only needs\n // `migrate` sent the person to the wrong tool, and the branch below could never run\n // because this one had already answered (`pendingMigrations` is non-empty exactly\n // when `configError` says so). The two cases are disjoint: a file from a newer\n // release has `tooNew` and no steps, so it still gets \"install that release\".\n if (settings.pendingMigrations.length > 0) {\n logger.error(`refusing to start: ${settings.path} needs ${settings.pendingMigrations.length} migration(s) before ${appVersion()} can use it`)\n logger.info('run `home-hosted migrate` to see and apply them')\n process.exit(1)\n }\n if (settings.configError !== null) {\n logger.error(`refusing to start: ${settings.configError}`)\n logger.info(`fix ${settings.path}, or install the release that wrote it`)\n process.exit(1)\n }\n\n const registry = new WorkspaceRegistry()\n registry.load()\n if (registry.configError !== null) {\n logger.error(`refusing to start: ${registry.configError}`)\n process.exit(1)\n }\n\n const secrets = new SecretsStore(globalSecretsPath, undefined, 'global')\n // A secrets file that cannot be parsed is refused, never read as a first boot: the\n // default password written below would otherwise replace it, taking the password\n // hash, the API token and every workspace's Telegram and DDNS credentials with it.\n if (secrets.configError !== null) {\n logger.error(`refusing to start: ${secrets.configError}`)\n logger.info('fix or restore the file, or move it aside to start fresh — starting fresh discards it')\n process.exit(1)\n }\n const auth = new AuthService(secrets, () => settings.control.auth)\n const tls = new TlsStore(tlsDir)\n const hub = new EventHub()\n\n let app: AppType | undefined\n const token = newToken()\n\n const configured = settings.control\n const intendedHost = options.host === undefined ? configured.host : parseBind(options.host)\n if (intendedHost === null) {\n logger.error(`invalid control host: ${String(options.host)} (expected local, lan or an ipv4 address)`)\n process.exit(1)\n }\n\n // `--port`/`--host` move the *listener*, so the server is built from them rather\n // than from what is on disk — the persisted value only follows the port preflight.\n const intended = { host: intendedHost, port: options.port ?? configured.port }\n if (!Number.isInteger(intended.port) || intended.port <= 0 || intended.port > 65535) {\n logger.error(`invalid control port: ${String(options.port)}`)\n process.exit(1)\n }\n\n const controlServer = new ControlServer(\n {\n fetch: (request) => {\n if (!app)\n throw new Error('the control app is not ready yet')\n return app.fetch(request)\n },\n trustProxy: () => settings.control.auth.trustProxy,\n // `servable()`, not `load()`: srvx throws synchronously on a pair whose key does not match the\n // certificate, which fails the boot with a raw OpenSSL code. A rejected pair falls back to http.\n tls: () => (settings.control.tls.enabled ? tls.servable() : null),\n },\n { host: intended.host, port: intended.port, tls: settings.control.tls.enabled },\n )\n\n // `--print-config` prints what the panel would read and starts nothing. It returns *here*, before\n // the branch below arms a boot password: \"show me my config\" on a fresh home used to write\n // `.control-secrets.json` with the default `hh` in it, so a command that promises to print and\n // exit left a credential behind and made the next real `up` start on the boot password.\n // A listener this release would refuse is reported as a warning rather than a refusal, because the\n // config is exactly what the person asked to see.\n if (options.printConfig) {\n const planned = checkExposure({ ...configured, host: intended.host }, auth.passwordSet, auth.usingDefaultPassword)\n if (planned.blockedReason !== null)\n logger.warn(`this config would be refused at startup: ${planned.blockedReason}`)\n printEffectiveConfig(settings, registry)\n return\n }\n\n // Auth is on by default, so a first boot needs *a* password; the default is\n // deliberately weak and flagged, which keeps LAN/exposure binding blocked (and\n // is announced on the login page) until it is changed.\n if (!auth.passwordSet) {\n const initial = generateInitialPassword()\n auth.ensureDefaultPassword(initial)\n logger.warn(`no password was set — generated the first-run password \"${initial}\"; change it in Global settings → Authentication (\\`status\\` shows it until you do)`)\n }\n\n // Never serve the panel beyond loopback without a password behind it.\n const exposure = checkExposure({ ...configured, host: intended.host }, auth.passwordSet, auth.usingDefaultPassword)\n if (exposure.blockedReason !== null) {\n logger.error(`refusing to start: ${exposure.blockedReason}`)\n logger.info('bind the panel back to `local`, or set a password with `home-hosted set-password` and enable auth in Global Settings')\n process.exit(1)\n }\n // Not a refusal: `true` has legitimate uses, and the real peer is not reachable once the header is\n // trusted. Saying so is what stops the lockout reading as a control it is not.\n const trustWarning = proxyTrustWarning({ ...configured, host: intended.host })\n if (trustWarning !== null)\n logger.warn(trustWarning)\n\n if (!(await isPortFree(intended.port))) {\n // The question this used to ask — \"is another home-hosted running?\" — is answerable from what\n // the probe already consulted, so it is answered rather than asked. A pid is what makes the\n // next step possible: `ps -p <pid>`, or the panel's own Free-port button.\n const holders = await listPortHolders(intended.port)\n logger.error(`control port ${intended.port} is already in use${holders.length > 0 ? ` by pid ${holders.join(', ')}` : ''} — another home-hosted, or something else on this port`)\n process.exit(1)\n }\n\n if (intended.host !== configured.host || intended.port !== configured.port)\n settings.updateControl({ host: intended.host, port: intended.port })\n\n const ui = new UiService({ dataRoot: hhDir, stockDir: path.join(packageRoot(), 'uis', 'stock', 'dist') })\n // An install killed between its two renames leaves `.ui` missing and the user's copy in\n // a backup; put that back before anything reads the directory.\n const uiRecovery = ui.recover()\n if (uiRecovery.restored !== null)\n logger.warn(`ui: restored the installed UI from ${uiRecovery.restored} — an earlier update was interrupted`)\n\n // The panel owns the aggregate state; host vitals fan out to every workspace's\n // notification service, so a host alert reaches whichever chats asked for one.\n let panel: PanelService | undefined\n const hostMonitor = new HostMonitor(\n () => settings.host,\n target => resolveUserPath(resolveTemplate(target, { projectDir, dataRoot, home: os.homedir() })),\n {\n notify: (event: NotificationEvent) => {\n for (const workspace of panel?.workspaces() ?? []) workspace.notifications.notify(event)\n },\n },\n )\n\n // The reverse proxy is created before the panel so the state frame can carry it,\n // and resolves entries through the panel lazily — the same closure trick.\n const proxy = new ProxyService({\n settings,\n binDir: proxyBinDir,\n engineDir: proxyEngineDir,\n configPath: proxyConfigPath,\n previousConfigPath: proxyPreviousConfigPath,\n stateDir: proxyStateDir,\n adminPath: proxyAdminPath,\n logDir: path.join(hhDir, '.logs'),\n tlsDir: proxyTlsDir,\n control: () => controlServer.endpoint,\n resolveServer: (workspaceId, serverId) => {\n const found = panel?.findServer(workspaceId, serverId)\n if (found === undefined || found === null)\n return null\n const view = panel?.serverViews(workspaceId).find(entry => entry.id === serverId)\n const port = view?.config.port ?? null\n if (port === null)\n return { url: null, message: `\"${serverId}\" has no port to forward to` }\n if (view?.status !== 'running' && view?.status !== 'starting')\n return { url: null, message: `\"${workspaceId}/${serverId}\" is ${view?.status ?? 'not running'}` }\n return { url: `${view.bindHost === '0.0.0.0' ? '127.0.0.1' : view.bindHost}:${port}`, message: null }\n },\n // A DNS-01 challenge writes through the workspace account the route names, so\n // the credentials never leave the workspace that owns them.\n resolveDnsAccount: (workspaceId, accountId) => {\n const found = panel?.findDnsAccount(workspaceId, accountId)\n if (found === undefined || found === null)\n return null\n return { provider: found.account.provider, credentials: found.credentials }\n },\n listDnsAccounts: () => panel?.listDnsAccounts() ?? [],\n defaultWorkspaceId: () => registry.defaultId,\n exposureBlocked: () => checkProxyExposure(settings.proxy, settings.control.auth.enabled, auth.passwordSet, auth.usingDefaultPassword),\n onStateChange: () => panel?.notifyStateChange(),\n })\n\n // The backups service needs the panel's sources, and the panel needs the\n // backups service for its state frame — one closure bridges the pair.\n const backups = new BackupService({\n dataRoot: hhDir,\n getConfig: () => settings.backups,\n getSources: () => panel!.backupSources(),\n ensureWorkspace: input => panel?.ensureWorkspace(input),\n onRestored: () => panel?.reloadAll(),\n onLoadPending: (workspaceId, serverId, dumpDir) => panel?.stagePendingLoad(workspaceId, serverId, dumpDir),\n })\n\n panel = new PanelService({\n registry,\n settings,\n secrets,\n auth,\n tls,\n backups,\n ui,\n hostMonitor,\n hub,\n control: () => controlServer.endpoint,\n proxy: () => proxy,\n autostart: options.autostart,\n })\n\n // A workspace's files are configs like any other, so a bad one refuses the\n // start too — the same rule the global settings and the registry just obeyed.\n // Checked before the listener binds or `run.json` exists, so a refused start\n // leaves no trace of a panel that pretends to supervise nothing.\n for (const workspace of panel.workspaces()) {\n const store = workspace.store\n // Same ordering as the global settings above, and for the same reason: a pending\n // migration is reported through `configError`, so the generic message answered first\n // and told the person to edit or reinstall a file that only needed `migrate`.\n if (store.pendingMigrations.length > 0) {\n logger.error(`refusing to start: workspace \"${workspace.id}\" needs ${store.pendingMigrations.length} migration(s) before ${appVersion()} can use it`)\n logger.info('run `home-hosted migrate` to see and apply them')\n process.exit(1)\n }\n if (store.configError !== null) {\n logger.error(`refusing to start: workspace \"${workspace.id}\": ${store.configError}`)\n logger.info(`fix ${store.path} and ${store.settingsPath}, or install the release that wrote them`)\n process.exit(1)\n }\n // Workspace secrets are configs too: a bad one must not be replaced by a fresh\n // file, which would drop that workspace's Telegram token and DDNS credentials.\n if (workspace.secrets.configError !== null) {\n logger.error(`refusing to start: workspace \"${workspace.id}\": ${workspace.secrets.configError}`)\n logger.info('fix or restore the file, or move it aside to start fresh — starting fresh discards it')\n process.exit(1)\n }\n }\n\n let shuttingDown = false\n const shutdown = async (reason: string, options: { withPersistent?: boolean } = {}): Promise<void> => {\n if (shuttingDown)\n return\n shuttingDown = true\n logger.info(`${reason} — stopping ${panel!.serverViews().length} server(s) across ${panel!.workspaces().length} workspace(s)`)\n if (proxy.status().state === 'running')\n logger.info('reverse proxy: left running (stop it from the panel, or switch the proxy off first)')\n clearRuntime()\n auth.dispose()\n proxy.dispose()\n await panel!.dispose(options)\n await controlServer.close(true)\n process.exit(0)\n }\n\n app = createRootApp({\n panel,\n hub,\n auth,\n secrets,\n controlServer,\n tls,\n backups,\n ui,\n proxy,\n // Credentials are read per request, so a panel with DNS-01 off never writes the\n // file — and one that switches it on picks the new pair up without a restart.\n challenge: new AcmeChallengeService({\n auth: () => (proxy.config.dns01.enabled ? proxy.challengeAuth() : null),\n accountFor: fqdn => proxy.challengeAccount(fqdn),\n onResult: (result) => {\n if (!result.ok)\n logger.warn(`proxy: the DNS-01 challenge for ${result.fqdn} failed (${result.action}): ${result.message}`)\n },\n }),\n runtimeToken: token,\n onShutdown: options => shutdown('shutdown requested locally', options),\n })\n\n await controlServer.start()\n // Reads every existing archive once, so the first state frame already shows\n // which backups are password-protected.\n await backups.warm()\n // Reattach to an engine that outlived the panel, or start the one this config asks for.\n await proxy.initialize()\n\n const endpoint = controlServer.endpoint\n const runtime: Runtime = {\n version: appVersion(),\n pid: process.pid,\n url: endpoint.url,\n probeUrl: `${endpoint.protocol}://${probeHostFor(endpoint.bindHost)}:${endpoint.port}`,\n protocol: endpoint.protocol,\n port: endpoint.port,\n bindHost: endpoint.bindHost,\n startedAt: Date.now(),\n projectDir,\n dataRoot,\n configPath: hhDir,\n logFile: daemonLogPath,\n token,\n }\n writeRuntime(runtime)\n\n logger.box(`home-hosted ${runtime.version}\\n${endpoint.url}`)\n logger.info(`state: ${hhDir}`)\n logger.info(`settings: ${settings.path}${auth.passwordSet ? '' : ' (no password set)'}`)\n logger.info(`auth: ${auth.isRequired() ? 'required' : 'disabled'}${auth.usingDefaultPassword ? ' (default password)' : ''}${auth.apiTokenSet ? ' · API token set' : ''}${exposure.exposed ? ' · exposed beyond loopback' : ''}`)\n logger.info(`project: ${projectDir}`)\n for (const workspace of panel.workspaces()) {\n logger.info(`workspace ${workspace.id} \"${workspace.label}\" — ${workspace.store.servers.length} server(s) · ${workspace.logsDir}`)\n if (workspace.store.configError !== null)\n logger.error(`workspace ${workspace.id}: ${workspace.store.configError}`)\n for (const warning of workspace.store.configWarnings) logger.warn(`workspace ${workspace.id}: ${warning}`)\n }\n for (const warning of settings.configWarnings) logger.warn(warning)\n if (ui.custom) {\n const meta = ui.status().meta\n logger.warn(`custom UI in use${meta === null ? '' : ` (${meta.name}${meta.version === null ? '' : ` ${meta.version}`})`} — if it breaks, run \\`home-hosted ui-revert\\``)\n autoUpdateOfficialUi(ui, runtime.version)\n }\n for (const workspace of panel.workspaces()) {\n for (const entry of workspace.supervisor.views())\n logger.info(` ${`${workspace.id}/${entry.id}`.padEnd(24)} ${entry.config.command} ${entry.config.args.join(' ')}`.trimEnd())\n }\n\n if (configured.openBrowser || options.open)\n openBrowser(endpoint.url)\n\n if (options.autostart) {\n void panel.startAll().catch((error: unknown) => {\n logger.error('autostart failed', error)\n })\n }\n\n // A failure while tearing down must still end the process: a rejected promise\n // here would leave the panel half-stopped.\n const onSignal = (signal: string): void => {\n void shutdown(signal).catch((error: unknown) => {\n logger.error(`shutdown after ${signal} failed`, error)\n process.exit(1)\n })\n }\n process.on('SIGINT', () => onSignal('SIGINT'))\n process.on('SIGTERM', () => onSignal('SIGTERM'))\n}\n\n/** `--print-config`: the global settings and every workspace, without starting anything. */\nfunction printEffectiveConfig(settings: GlobalSettingsStore, registry: WorkspaceRegistry): void {\n const workspaces = registry.all().map((workspace) => {\n const dir = path.join(hhDir, workspace.id)\n const read = (name: string): unknown => {\n try {\n // `readStateFile`, not a `'utf8'` read: these are the two files people hand-edit, and a\n // Windows editor puts a BOM on them — which would report `null` here, so `--print-config`\n // printed a workspace with no settings rather than the config it was asked for.\n return JSON.parse(readStateFile(path.join(dir, name)))\n }\n catch {\n return null\n }\n }\n return { id: workspace.id, label: workspace.label, settings: read('settings.json'), servers: read('servers.config.json') }\n })\n\n process.stdout.write(`${JSON.stringify({ settings: settings.rawConfig, workspaces }, null, 2)}\\n`)\n}\n\nexport { ConfigWatch }\n\n/**\n * `.hh` holds server output, configs with `env` values and the reverse proxy's keys: the owner's\n * alone. Applied on every boot so a home created by an older release is tightened too.\n */\nfunction restrictStateDir(): void {\n if (process.platform === 'win32')\n return\n try {\n fs.mkdirSync(hhDir, { recursive: true, mode: 0o700 })\n fs.chmodSync(hhDir, 0o700)\n }\n catch (error) {\n logger.warn(`could not restrict ${hhDir} to its owner: ${errorMessage(error)}`)\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAOA,IAAa,aAAa,cAAc;;;;ACLxC,SAAgB,UAAU,GAA6C;CAGrE,OADY,EAAE,IAAI,KACN,MAAM;AACpB;AAEA,SAAgB,WAAW,SAAiC;CAC1D,IAAI,CAAC,SACH,OAAO;CACT,OAAO,YAAY,eAAe,YAAY,SAAS,YAAY;AACrE;;AAGA,IAAM,qBAAqB;CAAC;CAAa;CAAmB;AAAW;;;;;;;AAQvE,SAAgB,kBAAkB,GAAuC;CACvE,MAAM,UAAW,EAAE,IAAI,KAA2C;CAClE,IAAI,YAAY,KAAA,KAAa,mBAAmB,MAAK,SAAQ,QAAQ,IAAI,IAAI,CAAC,GAC5E,OAAO;CACT,OAAO,WAAW,UAAU,CAAC,CAAC;AAChC;;;;;;;;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