home-hosted 0.11.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 (340) hide show
  1. package/README.md +319 -628
  2. package/dist/chunks/archive-DP-XQR8X.js +352 -0
  3. package/dist/chunks/archive-DP-XQR8X.js.map +1 -0
  4. package/dist/chunks/atomic-C1PfJpE7.js +26 -0
  5. package/dist/chunks/atomic-C1PfJpE7.js.map +1 -0
  6. package/dist/chunks/backup-CZcVca2a.js +822 -0
  7. package/dist/chunks/backup-CZcVca2a.js.map +1 -0
  8. package/dist/chunks/backups-CFRaWe_m.js +4691 -0
  9. package/dist/chunks/backups-CFRaWe_m.js.map +1 -0
  10. package/dist/chunks/config-text-DifCHhnz.js +50 -0
  11. package/dist/chunks/config-text-DifCHhnz.js.map +1 -0
  12. package/dist/chunks/contracts-CMBD1TF9.js +2230 -0
  13. package/dist/chunks/contracts-CMBD1TF9.js.map +1 -0
  14. package/dist/chunks/daemon-log-BVj8cDEo.js +241 -0
  15. package/dist/chunks/daemon-log-BVj8cDEo.js.map +1 -0
  16. package/dist/chunks/daemon-qKVECISl.js +247 -0
  17. package/dist/chunks/daemon-qKVECISl.js.map +1 -0
  18. package/dist/chunks/docker-Cy9Lyvda.js +437 -0
  19. package/dist/chunks/docker-Cy9Lyvda.js.map +1 -0
  20. package/dist/chunks/down-pKbGCW9d.js +383 -0
  21. package/dist/chunks/down-pKbGCW9d.js.map +1 -0
  22. package/dist/chunks/init-BZ7hK9Vf.js +276 -0
  23. package/dist/chunks/init-BZ7hK9Vf.js.map +1 -0
  24. package/dist/chunks/last-stop-C-BXz_XI.js +53 -0
  25. package/dist/chunks/last-stop-C-BXz_XI.js.map +1 -0
  26. package/dist/chunks/layout-DwTtmund.js +24 -0
  27. package/dist/chunks/layout-DwTtmund.js.map +1 -0
  28. package/dist/chunks/lazy-Ce5zEAq1.js +66 -0
  29. package/dist/chunks/lazy-Ce5zEAq1.js.map +1 -0
  30. package/dist/chunks/log-buffer-Dy9HHDMD.js +414 -0
  31. package/dist/chunks/log-buffer-Dy9HHDMD.js.map +1 -0
  32. package/dist/chunks/logger-B5U4GD3j.js +13 -0
  33. package/dist/chunks/logger-B5U4GD3j.js.map +1 -0
  34. package/dist/chunks/logs---TI_bxM.js +267 -0
  35. package/dist/chunks/logs---TI_bxM.js.map +1 -0
  36. package/dist/chunks/migrate-Cfoq-Vgh.js +155 -0
  37. package/dist/chunks/migrate-Cfoq-Vgh.js.map +1 -0
  38. package/dist/chunks/nanny-B-Eu0sFW.js +132 -0
  39. package/dist/chunks/nanny-B-Eu0sFW.js.map +1 -0
  40. package/dist/chunks/nanny-BtWfy0QH.js +1167 -0
  41. package/dist/chunks/nanny-BtWfy0QH.js.map +1 -0
  42. package/dist/chunks/nanny-ChMtq1Zl.js +39 -0
  43. package/dist/chunks/nanny-ChMtq1Zl.js.map +1 -0
  44. package/dist/chunks/nanny-sweep-DErnlPY1.js +105 -0
  45. package/dist/chunks/nanny-sweep-DErnlPY1.js.map +1 -0
  46. package/dist/chunks/nearest-6KgQEDUe.js +41 -0
  47. package/dist/chunks/nearest-6KgQEDUe.js.map +1 -0
  48. package/dist/chunks/parse-DhmG26fI.js +383 -0
  49. package/dist/chunks/parse-DhmG26fI.js.map +1 -0
  50. package/dist/chunks/paths-CGlGDrOU.js +206 -0
  51. package/dist/chunks/paths-CGlGDrOU.js.map +1 -0
  52. package/dist/chunks/port-B8WBTRMk.js +333 -0
  53. package/dist/chunks/port-B8WBTRMk.js.map +1 -0
  54. package/dist/chunks/restart-Des4DrAN.js +92 -0
  55. package/dist/chunks/restart-Des4DrAN.js.map +1 -0
  56. package/dist/chunks/rolldown-runtime-D7D4PA-g.js +13 -0
  57. package/dist/chunks/schema-B240VXcV.js +103 -0
  58. package/dist/chunks/schema-B240VXcV.js.map +1 -0
  59. package/dist/chunks/secrets-BieELnZh.js +562 -0
  60. package/dist/chunks/secrets-BieELnZh.js.map +1 -0
  61. package/dist/chunks/server-Bge2r2qQ.js +169 -0
  62. package/dist/chunks/server-Bge2r2qQ.js.map +1 -0
  63. package/dist/chunks/server-ids-DRuNLVCV.js +32 -0
  64. package/dist/chunks/server-ids-DRuNLVCV.js.map +1 -0
  65. package/dist/chunks/set-password-D5vZqqSX.js +43 -0
  66. package/dist/chunks/set-password-D5vZqqSX.js.map +1 -0
  67. package/dist/chunks/set-token-obPiEJYk.js +78 -0
  68. package/dist/chunks/set-token-obPiEJYk.js.map +1 -0
  69. package/dist/chunks/settings-xu-XTfWg.js +423 -0
  70. package/dist/chunks/settings-xu-XTfWg.js.map +1 -0
  71. package/dist/chunks/setup-temp-CAN4_bA-.js +150 -0
  72. package/dist/chunks/setup-temp-CAN4_bA-.js.map +1 -0
  73. package/dist/chunks/shape-DnTKzjQ2.js +24 -0
  74. package/dist/chunks/shape-DnTKzjQ2.js.map +1 -0
  75. package/dist/chunks/src-BtWMFmzZ.js +12338 -0
  76. package/dist/chunks/src-BtWMFmzZ.js.map +1 -0
  77. package/dist/chunks/status-DT1EsA-B.js +123 -0
  78. package/dist/chunks/status-DT1EsA-B.js.map +1 -0
  79. package/dist/chunks/ui-D562aqw5.js +325 -0
  80. package/dist/chunks/ui-D562aqw5.js.map +1 -0
  81. package/dist/chunks/ui-dir-CsU3uLNV.js +39 -0
  82. package/dist/chunks/ui-dir-CsU3uLNV.js.map +1 -0
  83. package/dist/chunks/ui-release-DKzVvlLd.js +312 -0
  84. package/dist/chunks/ui-release-DKzVvlLd.js.map +1 -0
  85. package/dist/chunks/ui-revert-EkBBwRTt.js +27 -0
  86. package/dist/chunks/ui-revert-EkBBwRTt.js.map +1 -0
  87. package/dist/chunks/ui-switch-BnZTdMDd.js +150 -0
  88. package/dist/chunks/ui-switch-BnZTdMDd.js.map +1 -0
  89. package/dist/chunks/ui-update-_xryLYxw.js +272 -0
  90. package/dist/chunks/ui-update-_xryLYxw.js.map +1 -0
  91. package/dist/chunks/up-Pdz-l6IH.js +210 -0
  92. package/dist/chunks/up-Pdz-l6IH.js.map +1 -0
  93. package/dist/chunks/usage-DFrCVXpT.js +111 -0
  94. package/dist/chunks/usage-DFrCVXpT.js.map +1 -0
  95. package/dist/chunks/workspaces-DYcfvKV_.js +229 -0
  96. package/dist/chunks/workspaces-DYcfvKV_.js.map +1 -0
  97. package/dist/chunks/wsl-temperature-BiCI4iK6.js +322 -0
  98. package/dist/chunks/wsl-temperature-BiCI4iK6.js.map +1 -0
  99. package/dist/cli.js +441 -25418
  100. package/dist/cli.js.map +1 -1
  101. package/dist/client.js +144 -0
  102. package/dist/client.js.map +1 -0
  103. package/dist/types/api/acme.d.ts +24 -0
  104. package/dist/types/api/auth/$.routes.d.ts +103 -0
  105. package/dist/types/api/backups.d.ts +184 -0
  106. package/dist/types/api/control.d.ts +470 -0
  107. package/dist/types/api/ddns.d.ts +432 -0
  108. package/dist/types/api/events.d.ts +22 -0
  109. package/dist/types/api/health.d.ts +28 -0
  110. package/dist/types/api/logs.d.ts +95 -0
  111. package/dist/types/api/metrics.d.ts +21 -0
  112. package/dist/types/api/notifications.d.ts +141 -0
  113. package/dist/types/api/proxy.d.ts +1128 -0
  114. package/dist/types/api/servers/$.routes.d.ts +1318 -0
  115. package/dist/types/api/settings.d.ts +642 -0
  116. package/dist/types/api/state.d.ts +498 -0
  117. package/dist/types/api/static.d.ts +11 -0
  118. package/dist/types/api/tls.d.ts +112 -0
  119. package/dist/types/api/workspaces/$.routes.d.ts +797 -0
  120. package/dist/types/api/wsl-temperature.d.ts +113 -0
  121. package/dist/types/app.d.ts +6095 -0
  122. package/dist/types/cli/args.d.ts +75 -0
  123. package/dist/types/cli/backup-offline.d.ts +23 -0
  124. package/dist/types/cli/backup.d.ts +86 -0
  125. package/dist/types/cli/down.d.ts +80 -0
  126. package/dist/types/cli/init.d.ts +60 -0
  127. package/dist/types/cli/io.d.ts +65 -0
  128. package/dist/types/cli/logs.d.ts +76 -0
  129. package/dist/types/cli/migrate.d.ts +33 -0
  130. package/dist/types/cli/nanny.d.ts +19 -0
  131. package/dist/types/cli/nearest.d.ts +10 -0
  132. package/dist/types/cli/restart.d.ts +41 -0
  133. package/dist/types/cli/server.d.ts +68 -0
  134. package/dist/types/cli/set-password.d.ts +14 -0
  135. package/dist/types/cli/set-token.d.ts +21 -0
  136. package/dist/types/cli/setup-temp.d.ts +65 -0
  137. package/dist/types/cli/status.d.ts +14 -0
  138. package/dist/types/cli/ui-revert.d.ts +3 -0
  139. package/dist/types/cli/ui-switch.d.ts +27 -0
  140. package/dist/types/cli/ui-update.d.ts +72 -0
  141. package/dist/types/cli/up.d.ts +96 -0
  142. package/dist/types/cli/usage.d.ts +23 -0
  143. package/dist/types/cli.d.ts +12 -0
  144. package/dist/types/client.d.ts +11891 -0
  145. package/dist/types/config/layout.d.ts +11 -0
  146. package/dist/types/config/migrations.d.ts +69 -0
  147. package/dist/types/config/parse.d.ts +54 -0
  148. package/dist/types/config/patch.d.ts +20 -0
  149. package/dist/types/config/schema.d.ts +318 -0
  150. package/dist/types/config/secret-parts.d.ts +48 -0
  151. package/dist/types/config/secrets.d.ts +208 -0
  152. package/dist/types/config/seed.d.ts +30 -0
  153. package/dist/types/config/server-ids.d.ts +14 -0
  154. package/dist/types/config/settings.d.ts +120 -0
  155. package/dist/types/config/store.d.ts +145 -0
  156. package/dist/types/config/workspaces.d.ts +99 -0
  157. package/dist/types/helpers/action-result.d.ts +46 -0
  158. package/dist/types/helpers/atomic.d.ts +9 -0
  159. package/dist/types/helpers/backoff.d.ts +7 -0
  160. package/dist/types/helpers/bind.d.ts +16 -0
  161. package/dist/types/helpers/config-text.d.ts +23 -0
  162. package/dist/types/helpers/cookies.d.ts +19 -0
  163. package/dist/types/helpers/copy-tree.d.ts +20 -0
  164. package/dist/types/helpers/daemon-log.d.ts +45 -0
  165. package/dist/types/helpers/daemon.d.ts +135 -0
  166. package/dist/types/helpers/deferred.d.ts +7 -0
  167. package/dist/types/helpers/env-file.d.ts +20 -0
  168. package/dist/types/helpers/error.d.ts +26 -0
  169. package/dist/types/helpers/event-stream.d.ts +21 -0
  170. package/dist/types/helpers/factory.d.ts +6 -0
  171. package/dist/types/helpers/last-stop.d.ts +20 -0
  172. package/dist/types/helpers/logger.d.ts +7 -0
  173. package/dist/types/helpers/open.d.ts +2 -0
  174. package/dist/types/helpers/openapi.d.ts +34 -0
  175. package/dist/types/helpers/paths.d.ts +112 -0
  176. package/dist/types/helpers/restore-lock.d.ts +32 -0
  177. package/dist/types/helpers/runtime.d.ts +18 -0
  178. package/dist/types/helpers/secret-compare.d.ts +13 -0
  179. package/dist/types/helpers/shell.d.ts +19 -0
  180. package/dist/types/helpers/sse.d.ts +23 -0
  181. package/dist/types/helpers/template.d.ts +8 -0
  182. package/dist/types/helpers/ui-dir.d.ts +11 -0
  183. package/dist/types/helpers/utf8-chunks.d.ts +15 -0
  184. package/dist/types/helpers/validate.d.ts +7 -0
  185. package/dist/types/helpers/validator.d.ts +12 -0
  186. package/dist/types/helpers/version.d.ts +10 -0
  187. package/dist/types/helpers/workspace.d.ts +25 -0
  188. package/dist/types/index.d.ts +17 -0
  189. package/dist/types/middleware/auth.d.ts +53 -0
  190. package/dist/types/middleware/host.d.ts +29 -0
  191. package/dist/types/middleware/loopback.d.ts +18 -0
  192. package/dist/types/openapi-reference.d.ts +22 -0
  193. package/dist/types/openapi.d.ts +34 -0
  194. package/dist/types/providers/archive.d.ts +54 -0
  195. package/dist/types/providers/backup-hook.d.ts +34 -0
  196. package/dist/types/providers/ddns/cloudflare.d.ts +2 -0
  197. package/dist/types/providers/ddns/desec.d.ts +2 -0
  198. package/dist/types/providers/ddns/digitalocean.d.ts +2 -0
  199. package/dist/types/providers/ddns/duckdns.d.ts +2 -0
  200. package/dist/types/providers/ddns/dyndns2.d.ts +15 -0
  201. package/dist/types/providers/ddns/dynu.d.ts +2 -0
  202. package/dist/types/providers/ddns/freedns.d.ts +2 -0
  203. package/dist/types/providers/ddns/gandi.d.ts +2 -0
  204. package/dist/types/providers/ddns/godaddy.d.ts +2 -0
  205. package/dist/types/providers/ddns/henet.d.ts +3 -0
  206. package/dist/types/providers/ddns/index.d.ts +12 -0
  207. package/dist/types/providers/ddns/ip.d.ts +27 -0
  208. package/dist/types/providers/ddns/namecheap-api.d.ts +13 -0
  209. package/dist/types/providers/ddns/namecheap.d.ts +6 -0
  210. package/dist/types/providers/ddns/noip.d.ts +2 -0
  211. package/dist/types/providers/ddns/porkbun.d.ts +2 -0
  212. package/dist/types/providers/ddns/spaceship.d.ts +7 -0
  213. package/dist/types/providers/ddns/types.d.ts +98 -0
  214. package/dist/types/providers/ddns/zone.d.ts +11 -0
  215. package/dist/types/providers/docker.d.ts +117 -0
  216. package/dist/types/providers/entry-state.d.ts +15 -0
  217. package/dist/types/providers/health-check.d.ts +27 -0
  218. package/dist/types/providers/host.d.ts +147 -0
  219. package/dist/types/providers/identity.d.ts +54 -0
  220. package/dist/types/providers/log-tail.d.ts +56 -0
  221. package/dist/types/providers/nanny-sweep.d.ts +54 -0
  222. package/dist/types/providers/nanny.d.ts +104 -0
  223. package/dist/types/providers/port.d.ts +142 -0
  224. package/dist/types/providers/proc.d.ts +125 -0
  225. package/dist/types/providers/process.d.ts +78 -0
  226. package/dist/types/providers/proxy/caddy.d.ts +2 -0
  227. package/dist/types/providers/proxy/index.d.ts +7 -0
  228. package/dist/types/providers/proxy/types.d.ts +54 -0
  229. package/dist/types/providers/server-vars.d.ts +4 -0
  230. package/dist/types/providers/telegram.d.ts +74 -0
  231. package/dist/types/providers/ui-release.d.ts +113 -0
  232. package/dist/types/providers/webhook.d.ts +64 -0
  233. package/dist/types/providers/wsl-temperature.d.ts +65 -0
  234. package/dist/types/services/acme-challenge.d.ts +44 -0
  235. package/dist/types/services/auth.d.ts +177 -0
  236. package/dist/types/services/backups.d.ts +476 -0
  237. package/dist/types/services/config-watch.d.ts +40 -0
  238. package/dist/types/services/control-server.d.ts +58 -0
  239. package/dist/types/services/ddns.d.ts +72 -0
  240. package/dist/types/services/dependencies.d.ts +21 -0
  241. package/dist/types/services/events.d.ts +17 -0
  242. package/dist/types/services/exposure.d.ts +86 -0
  243. package/dist/types/services/history.d.ts +37 -0
  244. package/dist/types/services/host-monitor.d.ts +33 -0
  245. package/dist/types/services/init.d.ts +71 -0
  246. package/dist/types/services/log-buffer.d.ts +39 -0
  247. package/dist/types/services/log-files.d.ts +77 -0
  248. package/dist/types/services/log-relay.d.ts +35 -0
  249. package/dist/types/services/nanny.d.ts +14 -0
  250. package/dist/types/services/notifications.d.ts +124 -0
  251. package/dist/types/services/panel.d.ts +213 -0
  252. package/dist/types/services/proxy-certificates/certificates.d.ts +116 -0
  253. package/dist/types/services/proxy-config.d.ts +83 -0
  254. package/dist/types/services/proxy.d.ts +431 -0
  255. package/dist/types/services/state.d.ts +38 -0
  256. package/dist/types/services/supervisor/compose.d.ts +17 -0
  257. package/dist/types/services/supervisor/entry.d.ts +149 -0
  258. package/dist/types/services/supervisor/health.d.ts +56 -0
  259. package/dist/types/services/supervisor/output.d.ts +126 -0
  260. package/dist/types/services/supervisor/pending-load.d.ts +6 -0
  261. package/dist/types/services/supervisor/persistent.d.ts +58 -0
  262. package/dist/types/services/supervisor/port-preflight.d.ts +45 -0
  263. package/dist/types/services/supervisor/records.d.ts +118 -0
  264. package/dist/types/services/supervisor/spawn.d.ts +15 -0
  265. package/dist/types/services/supervisor/view.d.ts +4 -0
  266. package/dist/types/services/supervisor.d.ts +145 -0
  267. package/dist/types/services/tls.d.ts +48 -0
  268. package/dist/types/services/ui-update.d.ts +44 -0
  269. package/dist/types/services/ui.d.ts +50 -0
  270. package/dist/types/shared/action-outcome.d.ts +25 -0
  271. package/dist/types/shared/api-client.d.ts +351 -0
  272. package/dist/types/shared/backup-scope.d.ts +167 -0
  273. package/dist/types/shared/clone.d.ts +14 -0
  274. package/dist/types/shared/contracts.d.ts +4175 -0
  275. package/dist/types/shared/cpu-scale.d.ts +25 -0
  276. package/dist/types/shared/ddns-form.d.ts +75 -0
  277. package/dist/types/shared/endpoint.d.ts +8 -0
  278. package/dist/types/shared/error-message.d.ts +8 -0
  279. package/dist/types/shared/fields.d.ts +21 -0
  280. package/dist/types/shared/form-repair.d.ts +6 -0
  281. package/dist/types/shared/generated.d.ts +26 -0
  282. package/dist/types/shared/host-readings.d.ts +185 -0
  283. package/dist/types/shared/lazy.d.ts +4 -0
  284. package/dist/types/shared/live-frames.d.ts +22 -0
  285. package/dist/types/shared/live-series.d.ts +21 -0
  286. package/dist/types/shared/live-store.d.ts +72 -0
  287. package/dist/types/shared/patch-diff.d.ts +105 -0
  288. package/dist/types/shared/probe-latency.d.ts +25 -0
  289. package/dist/types/shared/proxy-form.d.ts +184 -0
  290. package/dist/types/shared/server-attention.d.ts +37 -0
  291. package/dist/types/shared/server-form.d.ts +121 -0
  292. package/dist/types/shared/server-key.d.ts +13 -0
  293. package/dist/types/shared/server-readings.d.ts +55 -0
  294. package/dist/types/shared/server-url.d.ts +43 -0
  295. package/dist/types/shared/shape.d.ts +17 -0
  296. package/dist/types/shared/stream-access.d.ts +20 -0
  297. package/dist/types/shared/ui-format.d.ts +89 -0
  298. package/docs/API.md +209 -0
  299. package/docs/BACKUPS.md +117 -0
  300. package/docs/CLI.md +95 -0
  301. package/docs/DDNS.md +11 -1
  302. package/docs/NOTIFICATIONS.md +7 -1
  303. package/docs/REVERSE_PROXY.md +9 -3
  304. package/docs/SECURITY.md +93 -0
  305. package/docs/SERVERS.md +141 -34
  306. package/docs/UI_CREATION.md +91 -291
  307. package/docs/demo/blank-host-restore.sh +4 -3
  308. package/package.json +22 -14
  309. package/uis/stock/dist/assets/CopyButton-BUBKRJyY.js +1 -0
  310. package/uis/stock/dist/assets/GlobalSettingsView-yYMcRWvt.js +1 -0
  311. package/uis/stock/dist/assets/LogViewer-DIliXy62.js +1 -0
  312. package/uis/stock/dist/assets/LogsView-B7Z-7RNg.js +1 -0
  313. package/uis/stock/dist/assets/Modal-DmKa5Qpp.js +39 -0
  314. package/uis/stock/dist/assets/ProxyView-DvZiNkwb.js +1 -0
  315. package/uis/stock/dist/assets/ServerDetailView-6idGT_EX.js +2 -0
  316. package/uis/stock/dist/assets/SettingsShell-CeGtleYI.js +1 -0
  317. package/uis/stock/dist/assets/SettingsView-BrhJIrmk.js +2 -0
  318. package/uis/stock/dist/assets/de-BRITeb0H.js +1 -0
  319. package/uis/stock/dist/assets/es-B2zIEssV.js +1 -0
  320. package/uis/stock/dist/assets/fr-s0ZOBEqh.js +1 -0
  321. package/uis/stock/dist/assets/index-C1MehbKy.css +2 -0
  322. package/uis/stock/dist/assets/index-CnBN54wF.js +15 -0
  323. package/uis/stock/dist/assets/ja-CU7MR85V.js +1 -0
  324. package/uis/stock/dist/assets/ko-tL5Me6d-.js +1 -0
  325. package/uis/stock/dist/assets/ru-92yrvkNJ.js +1 -0
  326. package/uis/stock/dist/assets/vi-CzvY16k2.js +1 -0
  327. package/uis/stock/dist/assets/zh-CN-DDwFW_uW.js +1 -0
  328. package/uis/stock/dist/index.html +3 -2
  329. package/uis/stock/dist/ui.json +3 -3
  330. package/docs/RESTORE_DEMO.md +0 -306
  331. package/uis/stock/dist/assets/de-0YLueNal.js +0 -1
  332. package/uis/stock/dist/assets/es-FCHhRmn2.js +0 -1
  333. package/uis/stock/dist/assets/fr-C69Z8o0z.js +0 -1
  334. package/uis/stock/dist/assets/index-Cok5msAO.css +0 -2
  335. package/uis/stock/dist/assets/index-KdyqrVv8.js +0 -53
  336. package/uis/stock/dist/assets/ja-Chz9YOqR.js +0 -1
  337. package/uis/stock/dist/assets/ko-CtXZ2x1l.js +0 -1
  338. package/uis/stock/dist/assets/ru-D_jE64xN.js +0 -1
  339. package/uis/stock/dist/assets/vi-sxSffss7.js +0 -1
  340. package/uis/stock/dist/assets/zh-CN-ChTpf29X.js +0 -1
@@ -0,0 +1 @@
1
+ {"version":3,"file":"backups-CFRaWe_m.js","names":["API","call","ENDPOINT","API","ENDPOINT","ENDPOINT","ENDPOINT","API","API","ENDPOINT","ENDPOINT","ENDPOINT","API"],"sources":["../../src/providers/ddns/types.ts","../../src/providers/ddns/cloudflare.ts","../../src/providers/ddns/dyndns2.ts","../../src/providers/ddns/desec.ts","../../src/providers/ddns/zone.ts","../../src/providers/ddns/digitalocean.ts","../../src/providers/ddns/duckdns.ts","../../src/providers/ddns/dynu.ts","../../src/providers/ddns/freedns.ts","../../src/providers/ddns/gandi.ts","../../src/providers/ddns/godaddy.ts","../../src/providers/ddns/henet.ts","../../src/providers/ddns/namecheap.ts","../../src/providers/ddns/namecheap-api.ts","../../src/providers/ddns/noip.ts","../../src/providers/ddns/porkbun.ts","../../src/providers/ddns/spaceship.ts","../../src/providers/ddns/index.ts","../../src/helpers/env-file.ts","../../src/providers/webhook.ts","../../src/config/store.ts","../../src/providers/entry-state.ts","../../src/config/secret-parts.ts","../../src/helpers/restore-lock.ts","../../src/helpers/template.ts","../../src/helpers/bind.ts","../../src/providers/server-vars.ts","../../src/providers/backup-hook.ts","../../src/shared/backup-scope.ts","../../src/shared/generated.ts","../../src/services/backups.ts"],"sourcesContent":["import type { DdnsProviderField, DdnsRecordType } from '#src/shared/contracts'\nimport { Buffer } from 'node:buffer'\n\n/**\n * One record to keep current. Providers are stateless adapters over one HTTP\n * call each, so everything they need is resolved before they are called.\n */\n/** Provider ids the panel may have cached (a Cloudflare zone, a record), so the next pass skips lookups. */\nexport interface DdnsRecordCache {\n zoneId?: string\n recordId?: string\n}\n\nexport interface DdnsRecord {\n host: string\n type: DdnsRecordType\n ip: string\n /** The registered domain, when the config pins it; providers that need a zone fall back to a heuristic. */\n zone?: string\n /** Seconds; `1` is \"automatic\" where the provider supports it. */\n ttl: number\n proxied: boolean\n cache?: DdnsRecordCache\n}\n\nexport type DdnsFetch = (input: string, init?: RequestInit) => Promise<Response>\n\nexport interface DdnsContext {\n /** Whatever the person stored for this account; provider fields only. */\n credentials: Record<string, string>\n fetch: DdnsFetch\n signal?: AbortSignal\n}\n\nexport interface DdnsResult {\n ok: boolean\n /** False when the provider already served exactly this address. */\n changed: boolean\n message: string\n error?: string\n /** The provider refused in a way retrying cannot fix (bad credentials, unknown host, abuse block). */\n permanent?: boolean\n /** Provider ids worth remembering, so the next pass skips a lookup. */\n cache?: DdnsRecordCache\n}\n\nexport interface DdnsProvider {\n id: string\n label: string\n docsUrl: string\n /** Record families this provider can manage. */\n families: DdnsRecordType[]\n fields: DdnsProviderField[]\n /** The provider honours a per-record TTL. */\n ttl: boolean\n /** The provider has a proxy/CDN flag (Cloudflare). */\n proxied: boolean\n /**\n * Non-null when the stored credentials cannot drive this provider yet.\n */\n validate: (credentials: Record<string, string> | null) => string | null\n /**\n * Keeps one address record current. Absent for a provider that exists only to\n * answer DNS-01 challenges — an account on one of those cannot be used as a DDNS\n * hostname, and saying so beats a stub that pretends to work.\n */\n update?: (record: DdnsRecord, context: DdnsContext) => Promise<DdnsResult>\n /**\n * Present when these credentials can answer an ACME DNS-01 challenge, which\n * needs a temporary `TXT` record — a capability the update path does not imply.\n * A router-style Dynamic DNS password cannot write TXT, so it is absent there.\n */\n challenge?: (record: DdnsChallengeRecord, context: DdnsContext) => Promise<DdnsChallengeResult>\n}\n\n/** One `_acme-challenge` TXT record, as the ACME server asked for it. */\nexport interface DdnsChallengeRecord {\n /** The full name the CA reads, e.g. `_acme-challenge.git.example.com`. */\n fqdn: string\n /** The value the CA expects to find. */\n value: string\n /** `present` writes it, `cleanup` removes it again. */\n action: 'present' | 'cleanup'\n}\n\nexport interface DdnsChallengeResult {\n ok: boolean\n message: string\n}\n\nexport function succeeded(message: string, changed: boolean): DdnsResult {\n return { ok: true, changed, message }\n}\n\nexport function failed(error: string, permanent = false): DdnsResult {\n return { ok: false, changed: false, message: error, error, ...(permanent ? { permanent: true } : {}) }\n}\n\n/**\n * The result of the write six providers end their `update()` with.\n *\n * They repeated the same two lines after their own write call, and they have to agree: a\n * non-ok response is a provider error with its body attached, and an ok one is a change.\n * The message names the record, because a settings page shows it as the account's last\n * result and \"ok\" would not say what actually moved.\n */\nexport async function wrote(response: Response, record: DdnsRecord): Promise<DdnsResult> {\n if (!response.ok)\n return failed(await errorText(response))\n return succeeded(`set ${record.host} ${record.type} to ${record.ip}`, true)\n}\n\n/** Missing required credential keys, as a sentence for the settings page. */\nexport function missingFields(credentials: Record<string, string> | null, keys: string[]): string | null {\n const missing = keys.filter(key => (credentials?.[key] ?? '').trim().length === 0)\n return missing.length === 0 ? null : `set ${missing.join(', ')}`\n}\n\nexport function basicAuth(user: string, password: string): string {\n return `Basic ${Buffer.from(`${user}:${password}`, 'utf8').toString('base64')}`\n}\n\n/** A provider error body is useful, but never worth throwing over. */\nexport async function errorText(response: Response, limit = 300): Promise<string> {\n try {\n const text = (await response.text()).replace(/\\s+/g, ' ').trim()\n return text.length === 0 ? `HTTP ${response.status}` : `HTTP ${response.status}: ${text.slice(0, limit)}`\n }\n catch {\n return `HTTP ${response.status}`\n }\n}\n\nconst NORMALIZE_DOTS = /\\.$/\n\n/** `Sub.Domain.COM.` -> `sub.domain.com`; DuckDNS and friends are case-insensitive. */\nexport function normalizeHost(host: string): string {\n return host.trim().toLowerCase().replace(NORMALIZE_DOTS, '')\n}\n","import type { DdnsChallengeResult, DdnsContext, DdnsProvider, DdnsRecord, DdnsResult } from '#src/providers/ddns/types'\nimport { failed, missingFields, succeeded } from '#src/providers/ddns/types'\nimport { errorMessage } from '#src/shared/error-message'\n\nconst API = 'https://api.cloudflare.com/client/v4'\n\ninterface CloudflareZone { id: string, name: string }\ninterface CloudflareRecord { id: string, content: string, ttl: number, proxied: boolean }\ninterface CloudflareEnvelope<T> { success: boolean, result: T, result_info?: { total_pages?: number }, errors?: Array<{ code: number, message: string }> }\n\nfunction authHeaders(credentials: Record<string, string>): Record<string, string> | null {\n const token = (credentials.apiToken ?? '').trim()\n if (token.length > 0)\n return { Authorization: `Bearer ${token}` }\n const email = (credentials.email ?? '').trim()\n const key = (credentials.apiKey ?? '').trim()\n if (email.length > 0 && key.length > 0)\n return { 'X-Auth-Email': email, 'X-Auth-Key': key }\n return null\n}\n\nasync function call<T>(\n path: string,\n headers: Record<string, string>,\n context: DdnsContext,\n init: RequestInit = {},\n): Promise<{ data: CloudflareEnvelope<T> | null, status: number, error: string | null }> {\n try {\n const response = await context.fetch(`${API}${path}`, {\n ...init,\n headers: { ...headers, 'Content-Type': 'application/json', ...(init.headers ?? {}) },\n signal: context.signal,\n })\n const text = await response.text()\n let parsed: CloudflareEnvelope<T>\n try {\n parsed = JSON.parse(text) as CloudflareEnvelope<T>\n }\n catch {\n return { data: null, status: response.status, error: `cloudflare answered ${response.status}: ${text.slice(0, 200)}` }\n }\n if (!response.ok || parsed.success !== true) {\n const detail = (parsed.errors ?? []).map(entry => `${entry.code} ${entry.message}`).join('; ')\n return { data: parsed, status: response.status, error: detail.length > 0 ? detail : `HTTP ${response.status}` }\n }\n return { data: parsed, status: response.status, error: null }\n }\n catch (error) {\n return { data: null, status: 0, error: errorMessage(error) }\n }\n}\n\n/**\n * Walks the host's parents through `GET /zones?name=`, which is how the\n * reference image resolves a zone without a pasted zone id; the id is cached in\n * the panel's state file, so it usually costs nothing.\n *\n * A cached id is **confirmed before use**, the same way `findRecord` treats its own. It was returned\n * outright, so a stale id — the zone deleted, the API token swapped to another account, a restored\n * `ddns.json` — made every later call address a zone the token cannot see, and the walk that would have\n * found the right one never ran: the update failed permanently, with the provider's error for a zone\n * that is not even the host's. One extra request per run, and only when a cache exists.\n */\nasync function resolveZone(\n host: string,\n headers: Record<string, string>,\n context: DdnsContext,\n cached: string | undefined,\n): Promise<CloudflareZone | null> {\n if (cached !== undefined) {\n const confirmed = await call<CloudflareZone>(`/zones/${cached}`, headers, context)\n if (confirmed.error === null && confirmed.data !== null)\n return { id: cached, name: host }\n // A network failure is not evidence the id is wrong; anything the API answered means the walk\n // should decide instead.\n if (confirmed.status === 0)\n throw new Error(confirmed.error ?? 'could not reach Cloudflare')\n }\n\n const labels = host.split('.')\n for (let index = 0; index <= labels.length - 2; index++) {\n const candidate = labels.slice(index).join('.')\n const { data, error } = await call<CloudflareZone[]>(`/zones?name=${encodeURIComponent(candidate)}&per_page=1`, headers, context)\n if (error !== null || data === null)\n throw new Error(error ?? 'could not look up the zone')\n const zone = data.result[0]\n if (zone !== undefined)\n return zone\n }\n return null\n}\n\nasync function findRecord(\n zoneId: string,\n record: DdnsRecord,\n headers: Record<string, string>,\n context: DdnsContext,\n cached: string | undefined,\n): Promise<{ record: CloudflareRecord | null, error: string | null }> {\n if (cached !== undefined) {\n const fetched = await call<CloudflareRecord>(`/zones/${zoneId}/dns_records/${cached}`, headers, context)\n if (fetched.error === null && fetched.data !== null)\n return { record: fetched.data.result, error: null }\n // A cached id the provider no longer knows is dropped; the list is the truth.\n if (fetched.status !== 404 && fetched.status !== 400)\n return { record: null, error: fetched.error }\n }\n\n const listed = await call<CloudflareRecord[]>(\n `/zones/${zoneId}/dns_records?type=${record.type}&name=${encodeURIComponent(record.host)}&per_page=100`,\n headers,\n context,\n )\n if (listed.error !== null)\n return { record: null, error: listed.error }\n const match = (listed.data?.result ?? []).find(entry => entry.id !== undefined)\n return { record: match ?? null, error: null }\n}\n\nexport const cloudflareProvider: DdnsProvider = {\n id: 'cloudflare',\n label: 'Cloudflare',\n docsUrl: 'https://developers.cloudflare.com/api/resources/dns/subresources/records/',\n families: ['A', 'AAAA'],\n ttl: true,\n proxied: true,\n fields: [\n { key: 'apiToken', label: 'API token', hint: 'Zone → DNS → Edit (plus Zone → Zone → Read) for your zones. Preferred.', optional: true },\n { key: 'email', label: 'Account email', hint: 'Only for the legacy Global API Key.', optional: true },\n { key: 'apiKey', label: 'Global API key', hint: 'Legacy; prefer an API token.', optional: true },\n ],\n\n validate(credentials) {\n if (authHeaders(credentials ?? {}) !== null)\n return null\n return missingFields(credentials, ['apiToken'])\n },\n\n async update(record: DdnsRecord, context: DdnsContext): Promise<DdnsResult> {\n const headers = authHeaders(context.credentials)\n if (headers === null)\n return failed('cloudflare needs an API token (or the legacy email + global key)')\n\n try {\n const zone = await resolveZone(record.host, headers, context, record.cache?.zoneId)\n if (zone === null)\n return failed(`cloudflare does not have a zone for ${record.host}`)\n\n // A proxied record must be on automatic TTL; a TTL of 1 means automatic.\n const ttl = record.proxied ? 1 : record.ttl\n const found = await findRecord(zone.id, record, headers, context, record.cache?.recordId)\n if (found.error !== null)\n return failed(found.error)\n\n const existing = found.record\n if (existing !== null\n && existing.content === record.ip\n && existing.ttl === ttl\n && existing.proxied === record.proxied) {\n // The ids are still worth keeping: without them the next real change pays\n // for the zone walk and the record listing all over again.\n return { ...succeeded(`already ${record.ip}`, false), cache: { zoneId: zone.id, recordId: existing.id } }\n }\n\n const cache = { zoneId: zone.id, recordId: existing?.id }\n const body = JSON.stringify({ type: record.type, name: record.host, content: record.ip, ttl, proxied: record.proxied })\n // PATCH merges, so a comment or tag somebody set by hand survives an update.\n const written = existing === null\n ? await call<CloudflareRecord>(`/zones/${zone.id}/dns_records`, headers, context, { method: 'POST', body })\n : await call<CloudflareRecord>(`/zones/${zone.id}/dns_records/${existing.id}`, headers, context, { method: 'PATCH', body })\n if (written.error !== null)\n return failed(written.error)\n\n return { ...succeeded(`set ${record.host} ${record.type} to ${record.ip}`, true), cache: { ...cache, recordId: written.data?.result?.id ?? existing?.id } }\n }\n catch (error) {\n return failed(errorMessage(error))\n }\n },\n\n /**\n * One `_acme-challenge` TXT record, written and removed around a validation.\n * Cloudflare has real per-record endpoints, so nothing else in the zone is read\n * or rewritten — the failure mode that makes a whole-record-set API risky.\n */\n async challenge(record, context): Promise<DdnsChallengeResult> {\n const headers = authHeaders(context.credentials)\n if (headers === null)\n return { ok: false, message: 'cloudflare needs an API token (or the legacy email + global key)' }\n\n try {\n const zone = await resolveZone(record.fqdn, headers, context, undefined)\n if (zone === null)\n return { ok: false, message: `cloudflare does not have a zone for ${record.fqdn}` }\n\n // Every TXT at this name, because the CA may find several. What matters is\n // whether the one carrying *this* value is among them: a different value left\n // by an earlier attempt is not a substitute, and ACME checks the value.\n const listed = await call<CloudflareRecord[]>(\n `/zones/${zone.id}/dns_records?type=TXT&name=${encodeURIComponent(record.fqdn)}&per_page=100`,\n headers,\n context,\n )\n if (listed.error !== null)\n return { ok: false, message: listed.error }\n const matches = (listed.data?.result ?? []).filter(entry => entry.id !== undefined)\n const ours = matches.filter(entry => entry.content === record.value)\n\n if (record.action === 'present') {\n if (ours.length > 0)\n return { ok: true, message: `${record.fqdn} already carries this value` }\n // Another TXT at the same name is left alone: Cloudflare serves several, and\n // deleting somebody else's record to make room is not ours to do.\n // TTL 1 is Cloudflare's \"automatic\", which is what a record this short-lived wants.\n const written = await call<CloudflareRecord>(`/zones/${zone.id}/dns_records`, headers, context, {\n method: 'POST',\n body: JSON.stringify({ type: 'TXT', name: record.fqdn, content: record.value, ttl: 1 }),\n })\n if (written.error !== null)\n return { ok: false, message: written.error }\n return { ok: true, message: `wrote the TXT record for ${record.fqdn}` }\n }\n\n // Only the records carrying this value: a second challenge for the same name\n // must survive our cleanup, and so must an unrelated TXT record.\n for (const entry of ours) {\n const removed = await call<unknown>(`/zones/${zone.id}/dns_records/${entry.id}`, headers, context, { method: 'DELETE' })\n // Already gone is the state we wanted: a retry must not fail on it.\n if (removed.error !== null && removed.status !== 404)\n return { ok: false, message: removed.error }\n }\n if (ours.length === 0)\n return { ok: true, message: `${record.fqdn} had no challenge record to remove` }\n return { ok: true, message: `removed the TXT record for ${record.fqdn}` }\n }\n catch (error) {\n return { ok: false, message: errorMessage(error) }\n }\n },\n}\n","import type { DdnsResult } from '#src/providers/ddns/types'\nimport { failed, succeeded } from '#src/providers/ddns/types'\n\n/**\n * The dyndns2 reply vocabulary, shared by every `…/nic/update` endpoint. A\n * provider that answers something else maps its own text instead.\n */\nconst CODES: Record<string, { ok: boolean, changed: boolean, message: string, permanent: boolean }> = {\n 'good': { ok: true, changed: true, message: 'updated', permanent: false },\n 'nochg': { ok: true, changed: false, message: 'already current', permanent: false },\n 'nohost': { ok: false, changed: false, message: 'the provider does not know this hostname', permanent: true },\n 'notfqdn': { ok: false, changed: false, message: 'the provider wants a fully qualified hostname', permanent: true },\n 'numhost': { ok: false, changed: false, message: 'too many hostnames for this provider', permanent: true },\n 'badauth': { ok: false, changed: false, message: 'the provider rejected the credentials', permanent: true },\n 'badagent': { ok: false, changed: false, message: 'the provider rejected this client (User-Agent)', permanent: true },\n '!donator': { ok: false, changed: false, message: 'this feature needs a paid provider plan', permanent: true },\n 'abuse': { ok: false, changed: false, message: 'the provider blocked this account for abuse', permanent: true },\n 'dnserr': { ok: false, changed: false, message: 'the provider had a DNS error', permanent: false },\n 'servererror': { ok: false, changed: false, message: 'the provider had a server error', permanent: false },\n '911': { ok: false, changed: false, message: 'the provider is down; it asks you to wait about 30 minutes', permanent: false },\n 'unknown': { ok: false, changed: false, message: 'the provider answered with an unknown error', permanent: false },\n}\n\nexport interface DyndnsReply {\n code: string\n /** Everything after the code, typically the address the provider now serves. */\n detail: string\n}\n\n/** The first word of the body is the code; the rest is provider detail. */\nexport function parseDyndnsReply(body: string): DyndnsReply {\n const trimmed = body.trim()\n const separator = trimmed.search(/\\s/)\n if (separator < 0)\n return { code: trimmed.toLowerCase(), detail: '' }\n return { code: trimmed.slice(0, separator).toLowerCase(), detail: trimmed.slice(separator).trim() }\n}\n\n/** Maps a dyndns2 body onto the panel's result shape. */\nexport function describeDyndnsReply(body: string, provider: string): DdnsResult {\n const { code, detail } = parseDyndnsReply(body)\n const known = CODES[code]\n if (known === undefined)\n return failed(`${provider} answered \"${(body.trim() || 'an empty body').slice(0, 120)}\"`)\n if (known.ok)\n return succeeded(`${known.message}${detail.length === 0 ? '' : ` (${detail})`}`, known.changed)\n return failed(`${known.message}${detail.length === 0 ? '' : `: ${detail}`}`, known.permanent)\n}\n\n/**\n * A 401/400 with a non-dyndns2 body is still an answer worth quoting; a known\n * code wins, because several of these endpoints report errors with HTTP 200.\n */\nexport function describeDyndnsResponse(response: Response, body: string, provider: string): DdnsResult {\n const { code } = parseDyndnsReply(body)\n if (!response.ok && CODES[code] === undefined) {\n const text = body.replace(/\\s+/g, ' ').trim().slice(0, 160)\n return failed(`${provider} answered HTTP ${response.status}${text.length === 0 ? '' : `: ${text}`}`)\n }\n return describeDyndnsReply(body, provider)\n}\n","import type { DdnsContext, DdnsProvider, DdnsRecord, DdnsResult } from '#src/providers/ddns/types'\nimport { describeDyndnsResponse } from '#src/providers/ddns/dyndns2'\nimport { basicAuth, failed, missingFields } from '#src/providers/ddns/types'\nimport { errorMessage } from '#src/shared/error-message'\n\nconst ENDPOINT = 'https://update.dedyn.io/'\n\nexport const desecProvider: DdnsProvider = {\n id: 'desec',\n label: 'deSEC',\n docsUrl: 'https://desec.readthedocs.io/en/latest/dyndns/update-api.html',\n families: ['A', 'AAAA'],\n ttl: false,\n proxied: false,\n fields: [\n { key: 'token', label: 'API token', hint: 'desec.io → Token management; the token must allow the RRset update.', optional: false },\n ],\n\n validate(credentials) {\n return missingFields(credentials, ['token'])\n },\n\n async update(record: DdnsRecord, context: DdnsContext): Promise<DdnsResult> {\n const token = (context.credentials.token ?? '').trim()\n if (token.length === 0)\n return failed('desec needs an API token')\n\n // Basic auth binds the token to the hostname, so the token never rides in a URL.\n const family = record.type === 'A' ? `myipv4=${encodeURIComponent(record.ip)}` : `myipv6=${encodeURIComponent(record.ip)}`\n const url = `${ENDPOINT}?hostname=${encodeURIComponent(record.host)}&${family}`\n\n try {\n const response = await context.fetch(url, {\n headers: { Authorization: basicAuth(record.host, token) },\n signal: context.signal,\n })\n return describeDyndnsResponse(response, await response.text(), 'desec')\n }\n catch (error) {\n return failed(errorMessage(error))\n }\n },\n}\n","import { normalizeHost } from '#src/providers/ddns/types'\n\n/**\n * Public suffixes that take one extra label, so `home.example.co.uk` splits as\n * `home` in `example.co.uk` instead of `home.example` in `co.uk`. A per-domain\n * `zone` overrides this, which is the escape hatch for anything not listed.\n */\nconst MULTI_LABEL_SUFFIXES = new Set([\n 'ac.uk',\n 'co.in',\n 'co.jp',\n 'co.ke',\n 'co.kr',\n 'co.nz',\n 'co.uk',\n 'co.za',\n 'com.au',\n 'com.br',\n 'com.cn',\n 'com.hk',\n 'com.mx',\n 'com.sg',\n 'com.tr',\n 'com.tw',\n 'edu.au',\n 'gov.uk',\n 'net.au',\n 'net.uk',\n 'org.au',\n 'org.uk',\n])\n\nexport interface HostParts {\n /** The registered domain (the zone), e.g. `example.com`. */\n zone: string\n /** The record name inside that zone; `@` for the apex. */\n name: string\n}\n\n/**\n * Splits a hostname into the zone and the record name, which is what every\n * provider that has no zone lookup needs. `zone` short-circuits the heuristic.\n */\nexport function splitHost(host: string, zone?: string): HostParts {\n const normalized = normalizeHost(host)\n const override = normalizeHost(zone ?? '')\n const resolved = override.length > 0 ? override : guessZone(normalized)\n if (normalized === resolved)\n return { zone: resolved, name: '@' }\n return { zone: resolved, name: normalized.endsWith(`.${resolved}`) ? normalized.slice(0, -(resolved.length + 1)) : normalized }\n}\n\nfunction guessZone(host: string): string {\n const labels = host.split('.')\n if (labels.length <= 2)\n return host\n const lastTwo = labels.slice(-2).join('.')\n const lastThree = labels.slice(-3).join('.')\n return MULTI_LABEL_SUFFIXES.has(lastTwo) ? lastThree : lastTwo\n}\n","import type { DdnsContext, DdnsProvider, DdnsRecord, DdnsResult } from '#src/providers/ddns/types'\nimport { errorText, failed, missingFields, succeeded, wrote } from '#src/providers/ddns/types'\nimport { splitHost } from '#src/providers/ddns/zone'\nimport { errorMessage } from '#src/shared/error-message'\n\nconst API = 'https://api.digitalocean.com/v2/domains'\n\ninterface DigitalOceanRecord { id: number, type: string, name: string, data: string, ttl: number }\n\nfunction oceanTtl(ttl: number): number {\n return Math.max(30, ttl)\n}\n\nexport const digitaloceanProvider: DdnsProvider = {\n id: 'digitalocean',\n label: 'DigitalOcean',\n docsUrl: 'https://docs.digitalocean.com/reference/api/api-reference/#tag/Domain-Records',\n families: ['A', 'AAAA'],\n ttl: true,\n proxied: false,\n fields: [\n { key: 'token', label: 'API token', hint: 'A personal access token with the `domain` scope.', optional: false },\n ],\n\n validate(credentials) {\n return missingFields(credentials, ['token'])\n },\n\n async update(record: DdnsRecord, context: DdnsContext): Promise<DdnsResult> {\n const { zone, name } = splitHost(record.host, record.zone)\n const ttl = oceanTtl(record.ttl)\n const headers = { 'Authorization': `Bearer ${(context.credentials.token ?? '').trim()}`, 'Content-Type': 'application/json' }\n const collection = `${API}/${encodeURIComponent(zone)}/records`\n\n try {\n const listed = await context.fetch(`${collection}?per_page=200`, { headers, signal: context.signal })\n if (!listed.ok)\n return failed(await errorText(listed))\n const body = await listed.json() as { domain_records?: DigitalOceanRecord[] }\n const existing = (body.domain_records ?? []).find(entry => entry.name === name && entry.type === record.type)\n\n if (existing !== undefined && existing.data === record.ip)\n return succeeded(`already ${record.ip}`, false)\n\n const written = existing === undefined\n ? await context.fetch(collection, {\n method: 'POST',\n headers,\n body: JSON.stringify({ type: record.type, name, data: record.ip, ttl }),\n signal: context.signal,\n })\n : await context.fetch(`${collection}/${existing.id}`, {\n method: 'PUT',\n headers,\n body: JSON.stringify({ type: record.type, name, data: record.ip, ttl }),\n signal: context.signal,\n })\n\n return await wrote(written, record)\n }\n catch (error) {\n return failed(errorMessage(error))\n }\n },\n}\n","import type { DdnsContext, DdnsProvider, DdnsRecord, DdnsResult } from '#src/providers/ddns/types'\nimport { failed, missingFields, succeeded } from '#src/providers/ddns/types'\nimport { errorMessage } from '#src/shared/error-message'\n\nconst ENDPOINT = 'https://www.duckdns.org/update'\n\n/** DuckDNS addresses one subdomain at a time, so the label is the domain. */\nfunction subdomain(host: string): string {\n const normalized = host.trim().toLowerCase()\n return normalized.endsWith('.duckdns.org') ? normalized.slice(0, -'.duckdns.org'.length) : normalized\n}\n\nexport const duckdnsProvider: DdnsProvider = {\n id: 'duckdns',\n label: 'DuckDNS',\n docsUrl: 'https://www.duckdns.org/spec.jsp',\n families: ['A', 'AAAA'],\n ttl: false,\n proxied: false,\n fields: [\n { key: 'token', label: 'Account token', hint: 'On duckdns.org after signing in. One token covers every subdomain.', optional: false },\n ],\n\n validate(credentials) {\n return missingFields(credentials, ['token'])\n },\n\n async update(record: DdnsRecord, context: DdnsContext): Promise<DdnsResult> {\n const token = (context.credentials.token ?? '').trim()\n if (token.length === 0)\n return failed('duckdns needs the account token')\n\n const family = record.type === 'A' ? `ip=${encodeURIComponent(record.ip)}` : `ipv6=${encodeURIComponent(record.ip)}`\n const url = `${ENDPOINT}?domains=${encodeURIComponent(subdomain(record.host))}&token=${encodeURIComponent(token)}&${family}`\n\n try {\n const response = await context.fetch(url, { signal: context.signal })\n const body = (await response.text()).trim()\n if (body.toUpperCase() === 'OK')\n return succeeded(`set ${record.host} ${record.type} to ${record.ip}`, true)\n return failed(`duckdns answered \"${body.slice(0, 120) || `HTTP ${response.status}`}\"`)\n }\n catch (error) {\n return failed(errorMessage(error))\n }\n },\n}\n","import type { DdnsContext, DdnsProvider, DdnsRecord, DdnsResult } from '#src/providers/ddns/types'\nimport { describeDyndnsResponse } from '#src/providers/ddns/dyndns2'\nimport { basicAuth, failed, missingFields } from '#src/providers/ddns/types'\nimport { errorMessage } from '#src/shared/error-message'\n\nconst ENDPOINT = 'https://api.dynu.com/nic/update'\n\nexport const dynuProvider: DdnsProvider = {\n id: 'dynu',\n label: 'Dynu',\n docsUrl: 'https://www.dynu.com/DynamicDNS/IP-Update-Protocol',\n families: ['A', 'AAAA'],\n ttl: false,\n proxied: false,\n fields: [\n { key: 'username', label: 'Username', hint: 'Dynu username; used for HTTP Basic auth.', optional: false },\n { key: 'password', label: 'Password', hint: 'Account password, or its SHA-256 hash.', optional: false },\n ],\n\n validate(credentials) {\n return missingFields(credentials, ['username', 'password'])\n },\n\n async update(record: DdnsRecord, context: DdnsContext): Promise<DdnsResult> {\n const username = (context.credentials.username ?? '').trim()\n const password = (context.credentials.password ?? '').trim()\n if (username.length === 0 || password.length === 0)\n return failed('dynu needs the username and password')\n\n const address = record.type === 'A' ? `myip=${encodeURIComponent(record.ip)}` : `myipv6=${encodeURIComponent(record.ip)}`\n const url = `${ENDPOINT}?hostname=${encodeURIComponent(record.host)}&${address}`\n\n try {\n const response = await context.fetch(url, {\n headers: { Authorization: basicAuth(username, password) },\n signal: context.signal,\n })\n return describeDyndnsResponse(response, await response.text(), 'dynu')\n }\n catch (error) {\n return failed(errorMessage(error))\n }\n },\n}\n","import type { DdnsContext, DdnsProvider, DdnsRecord, DdnsResult } from '#src/providers/ddns/types'\nimport { failed, missingFields, succeeded } from '#src/providers/ddns/types'\nimport { errorMessage } from '#src/shared/error-message'\n\nconst ENDPOINT = 'https://freedns.afraid.org/dynamic/update.php'\n\n/**\n * FreeDNS credentials *are* a URL: the per-record \"Direct URL\" hash. Both the\n * bare hash and the whole URL are accepted, because that is what people copy.\n */\nfunction updateToken(credentials: Record<string, string>): string {\n const raw = (credentials.token ?? '').trim()\n if (raw.length === 0)\n return ''\n const query = raw.includes('?') ? raw.slice(raw.indexOf('?') + 1) : raw\n return query.replace(/^https?:\\/\\/[^?]*\\?/, '')\n}\n\nexport const freednsProvider: DdnsProvider = {\n id: 'freedns',\n label: 'FreeDNS (afraid.org)',\n docsUrl: 'https://freedns.afraid.org/faq/',\n families: ['A', 'AAAA'],\n ttl: false,\n proxied: false,\n fields: [\n { key: 'token', label: 'Direct URL', hint: 'FreeDNS → Dynamic DNS → the per-record \"Direct URL\". Paste the whole URL or just its hash.', optional: false },\n ],\n\n validate(credentials) {\n return missingFields(credentials, ['token'])\n },\n\n async update(record: DdnsRecord, context: DdnsContext): Promise<DdnsResult> {\n const token = updateToken(context.credentials)\n if (token.length === 0)\n return failed('freedns needs the per-record Direct URL')\n\n try {\n const response = await context.fetch(`${ENDPOINT}?${token}&address=${encodeURIComponent(record.ip)}`, { signal: context.signal })\n const body = (await response.text()).trim()\n if (!response.ok || /^ERROR/i.test(body))\n return failed(`freedns answered \"${body.slice(0, 160) || `HTTP ${response.status}`}\"`)\n return succeeded(`set ${record.host} ${record.type} to ${record.ip}`, true)\n }\n catch (error) {\n return failed(errorMessage(error))\n }\n },\n}\n","import type { DdnsContext, DdnsProvider, DdnsRecord, DdnsResult } from '#src/providers/ddns/types'\nimport { failed, missingFields, succeeded, wrote } from '#src/providers/ddns/types'\nimport { splitHost } from '#src/providers/ddns/zone'\nimport { errorMessage } from '#src/shared/error-message'\n\nconst API = 'https://api.gandi.net/v5/livedns/domains'\n\n/** Gandi's documented minimum; `1` (automatic) has no meaning here. */\nfunction gandiTtl(ttl: number): number {\n return Math.min(2_592_000, Math.max(300, ttl))\n}\n\n/** A Personal Access Token (`pat_…`) is preferred; the legacy API key is still accepted. */\nfunction authHeader(token: string): string {\n return token.startsWith('pat_') ? `Bearer ${token}` : `Apikey ${token}`\n}\n\nexport const gandiProvider: DdnsProvider = {\n id: 'gandi',\n label: 'Gandi',\n docsUrl: 'https://api.gandi.net/docs/livedns/',\n families: ['A', 'AAAA'],\n ttl: true,\n proxied: false,\n fields: [\n { key: 'token', label: 'Personal access token', hint: 'A `pat_…` token from admin.gandi.net → Organizations. A legacy API key also works.', optional: false },\n ],\n\n validate(credentials) {\n return missingFields(credentials, ['token'])\n },\n\n async update(record: DdnsRecord, context: DdnsContext): Promise<DdnsResult> {\n const token = (context.credentials.token ?? '').trim()\n if (token.length === 0)\n return failed('gandi needs an API token')\n\n const { zone, name } = splitHost(record.host, record.zone)\n const ttl = gandiTtl(record.ttl)\n const url = `${API}/${encodeURIComponent(zone)}/records/${encodeURIComponent(name)}/${record.type}`\n const headers = { 'Authorization': authHeader(token), 'Content-Type': 'application/json' }\n\n try {\n const current = await context.fetch(url, { headers, signal: context.signal })\n if (current.ok) {\n const body = await current.json() as { rrset_values?: string[], rrset_ttl?: number }\n if (body.rrset_values?.length === 1 && body.rrset_values[0] === record.ip)\n return succeeded(`already ${record.ip}`, false)\n }\n\n const written = await context.fetch(url, {\n method: 'PUT',\n headers,\n body: JSON.stringify({ rrset_values: [record.ip], rrset_ttl: ttl }),\n signal: context.signal,\n })\n return await wrote(written, record)\n }\n catch (error) {\n return failed(errorMessage(error))\n }\n },\n}\n","import type { DdnsContext, DdnsProvider, DdnsRecord, DdnsResult } from '#src/providers/ddns/types'\nimport { failed, missingFields, succeeded, wrote } from '#src/providers/ddns/types'\nimport { splitHost } from '#src/providers/ddns/zone'\nimport { errorMessage } from '#src/shared/error-message'\n\nconst API = 'https://api.godaddy.com/v1/domains'\n\n/** GoDaddy's floor; `1` (automatic) has no meaning here. */\nfunction godaddyTtl(ttl: number): number {\n return Math.min(86_400, Math.max(600, ttl))\n}\n\ninterface GoDaddyRecord { data: string, ttl: number, name: string, type: string }\n\nexport const godaddyProvider: DdnsProvider = {\n id: 'godaddy',\n label: 'GoDaddy',\n docsUrl: 'https://developer.godaddy.com/doc/endpoint/dns',\n families: ['A', 'AAAA'],\n ttl: true,\n proxied: false,\n fields: [\n { key: 'key', label: 'API key', hint: 'developer.godaddy.com/keys.', optional: false },\n { key: 'secret', label: 'API secret', hint: 'Shown once with the key.', optional: false },\n {\n key: 'baseUrl',\n label: 'API base URL',\n hint: 'Optional; use https://api.ote-godaddy.com to rehearse against the test environment.',\n optional: true,\n },\n ],\n\n validate(credentials) {\n return missingFields(credentials, ['key', 'secret'])\n },\n\n async update(record: DdnsRecord, context: DdnsContext): Promise<DdnsResult> {\n const { zone, name } = splitHost(record.host, record.zone)\n const ttl = godaddyTtl(record.ttl)\n const base = (context.credentials.baseUrl ?? '').trim() || API\n const url = `${base}/${encodeURIComponent(zone)}/records/${record.type}/${encodeURIComponent(name)}`\n const headers = {\n 'Authorization': `sso-key ${context.credentials.key ?? ''}:${context.credentials.secret ?? ''}`,\n 'Content-Type': 'application/json',\n }\n\n try {\n const current = await context.fetch(url, { headers, signal: context.signal })\n if (current.ok) {\n const body = await current.json() as GoDaddyRecord[]\n if (body.length === 1 && body[0]?.data === record.ip)\n return succeeded(`already ${record.ip}`, false)\n }\n\n const written = await context.fetch(url, {\n method: 'PUT',\n headers,\n body: JSON.stringify([{ data: record.ip, ttl }]),\n signal: context.signal,\n })\n return await wrote(written, record)\n }\n catch (error) {\n return failed(errorMessage(error))\n }\n },\n}\n","import type { DdnsContext, DdnsProvider, DdnsRecord, DdnsResult } from '#src/providers/ddns/types'\nimport { describeDyndnsResponse } from '#src/providers/ddns/dyndns2'\nimport { failed, missingFields } from '#src/providers/ddns/types'\nimport { errorMessage } from '#src/shared/error-message'\n\nconst ENDPOINT = 'https://dyn.dns.he.net/nic/update'\n\n/** Hurricane Electric keeps a per-host DDNS key, shown in its DNS panel. */\nexport const henetProvider: DdnsProvider = {\n id: 'henet',\n label: 'Hurricane Electric',\n docsUrl: 'https://dns.he.net/docs.html',\n families: ['A', 'AAAA'],\n ttl: false,\n proxied: false,\n fields: [\n { key: 'key', label: 'DDNS key', hint: 'dns.he.net → the key shown next to the host when DDNS is enabled.', optional: false },\n ],\n\n validate(credentials) {\n return missingFields(credentials, ['key'])\n },\n\n async update(record: DdnsRecord, context: DdnsContext): Promise<DdnsResult> {\n const key = (context.credentials.key ?? '').trim()\n if (key.length === 0)\n return failed('hurricane electric needs the per-host DDNS key')\n\n const url = `${ENDPOINT}?hostname=${encodeURIComponent(record.host)}&password=${encodeURIComponent(key)}&myip=${encodeURIComponent(record.ip)}`\n\n try {\n const response = await context.fetch(url, { signal: context.signal })\n return describeDyndnsResponse(response, await response.text(), 'hurricane electric')\n }\n catch (error) {\n return failed(errorMessage(error))\n }\n },\n}\n","import type { DdnsContext, DdnsProvider, DdnsRecord, DdnsResult } from '#src/providers/ddns/types'\nimport { failed, missingFields, succeeded } from '#src/providers/ddns/types'\nimport { splitHost } from '#src/providers/ddns/zone'\nimport { errorMessage } from '#src/shared/error-message'\n\nconst ENDPOINT = 'https://dynamicdns.park-your-domain.com/update'\n\nfunction tag(body: string, name: string): string | null {\n const match = new RegExp(`<${name}>([\\\\s\\\\S]*?)</${name}>`, 'i').exec(body)\n return match?.[1]?.trim() ?? null\n}\n\n/**\n * Namecheap's router-style Dynamic DNS: one GET, one A record, HTTP 200 even on\n * failure — the XML `ErrCount` is the only truth.\n */\nexport const namecheapProvider: DdnsProvider = {\n id: 'namecheap',\n label: 'Namecheap',\n docsUrl: 'https://www.namecheap.com/support/knowledgebase/article.aspx/29/11/how-to-dynamically-update-the-hosts-ip-with-an-https-request/',\n families: ['A'],\n ttl: false,\n proxied: false,\n fields: [\n {\n key: 'password',\n label: 'Dynamic DNS password',\n hint: 'Dashboard → Manage domain → Advanced DNS → Dynamic DNS. Not your account password or API key.',\n optional: false,\n },\n ],\n\n validate(credentials) {\n return missingFields(credentials, ['password'])\n },\n\n async update(record: DdnsRecord, context: DdnsContext): Promise<DdnsResult> {\n const password = (context.credentials.password ?? '').trim()\n if (password.length === 0)\n return failed('namecheap needs the Dynamic DNS password')\n\n const { zone, name } = splitHost(record.host, record.zone)\n const host = name === '@' ? '@' : name\n const url = `${ENDPOINT}?host=${encodeURIComponent(host)}&domain=${encodeURIComponent(zone)}&password=${encodeURIComponent(password)}&ip=${encodeURIComponent(record.ip)}`\n\n try {\n const response = await context.fetch(url, { signal: context.signal })\n const body = await response.text()\n const errCount = Number.parseInt(tag(body, 'ErrCount') ?? '0', 10)\n const ip = tag(body, 'IP')\n if (errCount > 0) {\n const first = tag(body, 'Err1')\n return failed(`namecheap rejected the update${first === null ? '' : `: ${first}`}`)\n }\n if (ip === null)\n return failed(`namecheap answered without an IP: ${body.replace(/\\s+/g, ' ').slice(0, 160)}`)\n return succeeded(`${host === '@' ? zone : `${host}.${zone}`} now ${ip}`, ip !== record.ip)\n }\n catch (error) {\n return failed(errorMessage(error))\n }\n },\n}\n","import type { DdnsChallengeRecord, DdnsChallengeResult, DdnsContext, DdnsProvider } from '#src/providers/ddns/types'\nimport { normalizeHost } from '#src/providers/ddns/types'\nimport { splitHost } from '#src/providers/ddns/zone'\nimport { errorMessage } from '#src/shared/error-message'\n\n/**\n * Namecheap through its XML API, which is the only way to write a `TXT` record\n * there: the router-style Dynamic DNS endpoint in `namecheap.ts` updates an\n * address and nothing else, and its password is not this one.\n *\n * The API has no \"add one record\" call. `setHosts` **replaces the whole record\n * set**, so answering a challenge means reading every record, writing them all\n * back with one added (or removed) — twice per issuance. That is why this is a\n * separate provider with its own credentials rather than a mode of the other one:\n * the failure mode is different in kind, and nobody should reach it by accident.\n */\n\nconst ENDPOINT = 'https://api.namecheap.com/xml.response'\n\n/**\n * The most host records one `setHosts` call can carry. A zone with more than this\n * cannot be rewritten through the API at all, which is why the guard refuses rather\n * than sending a call that would silently drop the records it could not express.\n */\nconst RECORD_LIMIT = 150\n\n/** TTL for the challenge record: short, because it is deleted minutes later. */\nconst CHALLENGE_TTL = 60\n\nexport interface NamecheapRecord {\n name: string\n type: string\n address: string\n mxPref: string\n ttl: string\n}\n\ninterface ApiReply {\n status: string\n errors: string[]\n body: string\n}\n\nconst XML_ENTITIES: Record<string, string> = { amp: '&', lt: '<', gt: '>', quot: '\"', apos: '\\'' }\n\n/**\n * Namecheap escapes attribute values, so a value read back has to be unescaped\n * before it is written out again: the whole-zone rewrite would otherwise turn\n * `a&b` into `a&amp;b` on every challenge, corrupting a record we did not create.\n */\nfunction decodeXml(value: string): string {\n return value.replace(/&(#X?[0-9a-f]+|[a-z]+);/gi, (whole, body: string) => {\n if (body.startsWith('#')) {\n const hex = body[1] === 'x' || body[1] === 'X'\n const code = Number.parseInt(hex ? body.slice(2) : body.slice(1), hex ? 16 : 10)\n return Number.isInteger(code) && code >= 0 && code <= 0x10_FF_FF ? String.fromCodePoint(code) : whole\n }\n return XML_ENTITIES[body.toLowerCase()] ?? whole\n })\n}\n\nfunction attr(tagText: string, name: string): string {\n const match = new RegExp(`${name}=\"([^\"]*)\"`, 'i').exec(tagText)\n return decodeXml(match?.[1] ?? '').trim()\n}\n\n/** Every `<Host ... />` in a `getHosts` reply, in the order the API listed them. */\nexport function parseHosts(body: string): NamecheapRecord[] {\n const records: NamecheapRecord[] = []\n const pattern = /<Host\\b([^>]*?)(?:\\/>|>)/gi\n let match = pattern.exec(body)\n while (match !== null) {\n const attributes = match[1] ?? ''\n records.push({\n name: attr(attributes, 'Name'),\n type: attr(attributes, 'Type'),\n address: attr(attributes, 'Address'),\n mxPref: attr(attributes, 'MXPref') || '10',\n ttl: attr(attributes, 'TTL') || '1800',\n })\n match = pattern.exec(body)\n }\n return records\n}\n\n/** The first `<Err1>`…`<ErrN>` a failed reply carries, as one sentence. */\nexport function describeErrors(body: string): string {\n const errors: string[] = []\n const pattern = /<Err\\d+>([\\s\\S]*?)<\\/Err\\d+>/gi\n let match = pattern.exec(body)\n while (match !== null) {\n const text = (match[1] ?? '').trim()\n if (text.length > 0)\n errors.push(text)\n match = pattern.exec(body)\n }\n return errors.length > 0 ? errors.join('; ') : 'the API refused the request'\n}\n\nfunction credentials(store: Record<string, string>): { apiUser: string, apiKey: string, userName: string, clientIp: string } | null {\n const apiUser = (store.apiUser ?? '').trim()\n const apiKey = (store.apiKey ?? '').trim()\n const userName = (store.userName ?? '').trim() || apiUser\n const clientIp = (store.clientIp ?? '').trim()\n if (apiUser.length === 0 || apiKey.length === 0 || clientIp.length === 0)\n return null\n return { apiUser, apiKey, userName, clientIp }\n}\n\n/** One XML call. Namecheap answers HTTP 200 whatever happened, so the body decides. */\nasync function call(command: string, params: Record<string, string>, context: DdnsContext): Promise<ApiReply | string> {\n const auth = credentials(context.credentials)\n if (auth === null)\n return 'namecheap needs the API user, the API key and the whitelisted client IP'\n\n const query = new URLSearchParams({\n ApiUser: auth.apiUser,\n ApiKey: auth.apiKey,\n UserName: auth.userName,\n ClientIp: auth.clientIp,\n Command: command,\n ...params,\n })\n\n try {\n const response = await context.fetch(`${ENDPOINT}?${query.toString()}`, { signal: context.signal })\n const body = await response.text()\n if (!response.ok && !body.includes('<ApiResponse'))\n return `namecheap answered HTTP ${response.status}`\n const status = /<ApiResponse[^>]*Status=\"([^\"]*)\"/i.exec(body)?.[1] ?? ''\n if (status.toUpperCase() !== 'OK')\n return describeErrors(body)\n return { status, errors: [], body }\n }\n catch (error) {\n return errorMessage(error)\n }\n}\n\n/** The registered domain split into the `SLD`/`TLD` pair the API asks for. */\nfunction apexParts(zone: string): { SLD: string, TLD: string } {\n const apex = normalizeHost(zone)\n const dot = apex.indexOf('.')\n if (dot < 0)\n return { SLD: apex, TLD: '' }\n return { SLD: apex.slice(0, dot), TLD: apex.slice(dot + 1) }\n}\n\n/** The zone's records, or a sentence saying why they could not be read. */\nasync function readHosts(zone: string, context: DdnsContext): Promise<NamecheapRecord[] | string> {\n const reply = await call('namecheap.domains.dns.getHosts', { ...apexParts(zone) }, context)\n if (typeof reply === 'string')\n return reply\n return parseHosts(reply.body)\n}\n\n/** Writes the whole record set back. */\nasync function writeHosts(zone: string, records: NamecheapRecord[], context: DdnsContext): Promise<string | null> {\n const params: Record<string, string> = { ...apexParts(zone) }\n records.forEach((record, index) => {\n const at = index + 1\n params[`HostName${at}`] = record.name\n params[`RecordType${at}`] = record.type\n params[`Address${at}`] = record.address\n params[`TTL${at}`] = record.ttl\n // The API carries MXPref on every record; sending it back unchanged keeps an\n // MX record's preference from being silently reset to the default.\n params[`MXPref${at}`] = record.mxPref\n })\n\n const reply = await call('namecheap.domains.dns.setHosts', params, context)\n return typeof reply === 'string' ? reply : null\n}\n\n/** The record name Namecheap expects for a challenge, relative to the zone. */\nfunction challengeName(fqdn: string, zone: string): string {\n const normalized = normalizeHost(fqdn)\n const apex = normalizeHost(zone)\n if (normalized === apex)\n return '@'\n return normalized.endsWith(`.${apex}`) ? normalized.slice(0, -(apex.length + 1)) : normalized\n}\n\nexport const namecheapApiProvider: DdnsProvider = {\n id: 'namecheap-api',\n label: 'Namecheap (API)',\n docsUrl: 'https://www.namecheap.com/support/api/methods/domains-dns/set-hosts/',\n // The XML API can manage any record type, but this entry exists for DNS-01:\n // address updates belong to the Dynamic DNS provider, whose password is easier\n // to live with than an IP-whitelisted API key.\n families: ['A'],\n ttl: true,\n proxied: false,\n fields: [\n { key: 'apiUser', label: 'API user', hint: 'Dashboard → Profile → Tools → Namecheap API Access. Usually your account name.', optional: false },\n { key: 'apiKey', label: 'API key', hint: 'Shown once when API access is enabled.', optional: false },\n { key: 'userName', label: 'User name', hint: 'Leave empty unless the API user differs from the account.', optional: true },\n { key: 'clientIp', label: 'Whitelisted IP', hint: 'The public IPv4 this panel calls from. It must be whitelisted under API Access, and error 1017105 means it is not.', optional: false },\n ],\n\n validate(store) {\n if (credentials(store ?? {}) !== null)\n return null\n const missing = ['apiUser', 'apiKey', 'clientIp'].filter(key => (store?.[key] ?? '').trim().length === 0)\n return missing.length === 0 ? null : `set ${missing.join(', ')}`\n },\n\n /**\n * There is no per-record update here: `setHosts` replaces everything, so this is\n * a read-modify-write of the whole zone.\n */\n async challenge(record: DdnsChallengeRecord, context: DdnsContext): Promise<DdnsChallengeResult> {\n const { zone } = splitHost(record.fqdn)\n const hosts = await readHosts(zone, context)\n if (typeof hosts === 'string')\n return { ok: false, message: hosts }\n\n const name = challengeName(record.fqdn, zone)\n const isChallenge = (host: NamecheapRecord) => host.type.toUpperCase() === 'TXT' && host.name.toLowerCase() === name.toLowerCase()\n // Scoped by value, not just by name: a second challenge for the same hostname\n // (or somebody's own TXT) must survive our cleanup.\n const isOurs = (host: NamecheapRecord) => isChallenge(host) && host.address === record.value\n\n if (record.action === 'present') {\n if (hosts.some(isOurs))\n return { ok: true, message: `${record.fqdn} already carries this value` }\n if (hosts.length >= RECORD_LIMIT) {\n return {\n ok: false,\n message: `namecheap's setHosts takes at most ${RECORD_LIMIT} host records per call and ${zone} has ${hosts.length}, so the panel cannot rewrite this zone to add a challenge record`,\n }\n }\n const failure = await writeHosts(zone, [...hosts, {\n name,\n type: 'TXT',\n address: record.value,\n mxPref: '10',\n ttl: String(CHALLENGE_TTL),\n }], context)\n if (failure !== null)\n return { ok: false, message: failure }\n return { ok: true, message: `added a TXT record for ${record.fqdn} (rewrote ${hosts.length} others)` }\n }\n\n const kept = hosts.filter(host => !isOurs(host))\n if (kept.length === hosts.length)\n return { ok: true, message: `${record.fqdn} had no challenge record to remove` }\n const failure = await writeHosts(zone, kept, context)\n if (failure !== null)\n return { ok: false, message: failure }\n return { ok: true, message: `removed the TXT record for ${record.fqdn} (rewrote ${kept.length} others)` }\n },\n}\n","import type { DdnsContext, DdnsProvider, DdnsRecord, DdnsResult } from '#src/providers/ddns/types'\nimport { describeDyndnsResponse } from '#src/providers/ddns/dyndns2'\nimport { basicAuth, failed, missingFields } from '#src/providers/ddns/types'\nimport { errorMessage } from '#src/shared/error-message'\n\nconst ENDPOINT = 'https://dynupdate.no-ip.com/nic/update'\n\n/** No-IP rate-limits clients whose User-Agent it does not recognise. */\nconst DEFAULT_AGENT = 'home-hosted/1.0 (+https://github.com/NamesMT/home-hosted)'\n\nexport const noipProvider: DdnsProvider = {\n id: 'noip',\n label: 'No-IP',\n docsUrl: 'https://www.noip.com/integrate/request',\n families: ['A', 'AAAA'],\n ttl: false,\n proxied: false,\n fields: [\n { key: 'username', label: 'Email', hint: 'Your No-IP account email.', optional: false },\n { key: 'password', label: 'Password', hint: 'Your No-IP account password.', optional: false },\n {\n key: 'userAgent',\n label: 'User-Agent override',\n hint: 'No-IP only guarantees updates for recognised clients; set an approved agent here if yours is registered.',\n optional: true,\n },\n ],\n\n validate(credentials) {\n return missingFields(credentials, ['username', 'password'])\n },\n\n async update(record: DdnsRecord, context: DdnsContext): Promise<DdnsResult> {\n const username = (context.credentials.username ?? '').trim()\n const password = (context.credentials.password ?? '').trim()\n if (username.length === 0 || password.length === 0)\n return failed('no-ip needs the account email and password')\n\n const address = record.type === 'A' ? `myip=${encodeURIComponent(record.ip)}` : `myipv6=${encodeURIComponent(record.ip)}`\n const url = `${ENDPOINT}?hostname=${encodeURIComponent(record.host)}&${address}`\n\n try {\n const response = await context.fetch(url, {\n headers: {\n 'Authorization': basicAuth(username, password),\n 'User-Agent': (context.credentials.userAgent ?? '').trim() || DEFAULT_AGENT,\n },\n signal: context.signal,\n })\n return describeDyndnsResponse(response, await response.text(), 'no-ip')\n }\n catch (error) {\n return failed(errorMessage(error))\n }\n },\n}\n","import type { DdnsContext, DdnsProvider, DdnsRecord, DdnsResult } from '#src/providers/ddns/types'\nimport { failed, missingFields, succeeded } from '#src/providers/ddns/types'\nimport { splitHost } from '#src/providers/ddns/zone'\nimport { errorMessage } from '#src/shared/error-message'\n\nconst API = 'https://api.porkbun.com/api/json/v3'\n\ninterface PorkbunEnvelope {\n status: 'SUCCESS' | 'ERROR'\n message?: string\n records?: Array<{ id: string, name: string, type: string, content: string, ttl: string }>\n warnings?: string[]\n}\n\n/** Porkbun's documented floor; `1` (automatic) maps onto it. */\nfunction porkbunTtl(ttl: number): number {\n return Math.max(600, ttl)\n}\n\nasync function post(path: string, context: DdnsContext, body: Record<string, unknown>): Promise<{ data: PorkbunEnvelope | null, error: string | null }> {\n try {\n const response = await context.fetch(`${API}${path}`, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n 'X-API-Key': context.credentials.apikey ?? '',\n 'X-Secret-API-Key': context.credentials.secretapikey ?? '',\n },\n body: JSON.stringify(body),\n signal: context.signal,\n })\n const parsed = JSON.parse(await response.text()) as PorkbunEnvelope\n if (parsed.status !== 'SUCCESS')\n return { data: parsed, error: parsed.message ?? `HTTP ${response.status}` }\n return { data: parsed, error: null }\n }\n catch (error) {\n return { data: null, error: errorMessage(error) }\n }\n}\n\nexport const porkbunProvider: DdnsProvider = {\n id: 'porkbun',\n label: 'Porkbun',\n docsUrl: 'https://porkbun.com/api/json/v3/documentation',\n families: ['A', 'AAAA'],\n ttl: true,\n proxied: false,\n fields: [\n { key: 'apikey', label: 'API key', hint: 'porkbun.com/account/api — starts with pk1_.', optional: false },\n { key: 'secretapikey', label: 'Secret API key', hint: 'Shown once when the key is created.', optional: false },\n ],\n\n validate(credentials) {\n return missingFields(credentials, ['apikey', 'secretapikey'])\n },\n\n async update(record: DdnsRecord, context: DdnsContext): Promise<DdnsResult> {\n const { zone, name: rawName } = splitHost(record.host, record.zone)\n // Porkbun uses a blank name for the apex, and `*` for a wildcard.\n const name = rawName === '@' ? '' : rawName\n const ttl = porkbunTtl(record.ttl)\n\n const listed = await post(`/dns/retrieveByNameType/${encodeURIComponent(zone)}/${record.type}/${encodeURIComponent(name)}`, context, {})\n const existing = listed.data?.records?.[0]\n if (existing !== undefined && existing.content === record.ip && Number.parseInt(existing.ttl, 10) === ttl)\n return succeeded(`already ${record.ip}`, false)\n\n const written = await post(`/dns/editByNameType/${encodeURIComponent(zone)}/${record.type}/${encodeURIComponent(name)}`, context, {\n content: record.ip,\n ttl,\n })\n if (written.error !== null)\n return failed(written.error)\n\n const warnings = written.data?.warnings ?? []\n const note = warnings.length > 0 ? ` — porkbun warns: ${warnings.join('; ')}` : ''\n return succeeded(`set ${record.host} ${record.type} to ${record.ip}${note}`, true)\n },\n}\n","import type { DdnsContext, DdnsProvider, DdnsRecord, DdnsResult } from '#src/providers/ddns/types'\nimport { errorText, failed, missingFields, succeeded, wrote } from '#src/providers/ddns/types'\nimport { splitHost } from '#src/providers/ddns/zone'\nimport { errorMessage } from '#src/shared/error-message'\n\nconst API = 'https://spaceship.dev/api/v1/dns/records'\nconst PAGE_SIZE = 500\n\ninterface SpaceshipRecord { type: string, name: string, ttl: number, address?: string }\n\nfunction spaceshipTtl(ttl: number): number {\n return Math.min(3600, Math.max(60, ttl))\n}\n\n/**\n * Spaceship has no DDNS endpoint: the DNS API upserts whole record sets by\n * (name, type) and answers 204 with no body, so the only way to report\n * \"unchanged\" is to read the records back first.\n */\nexport const spaceshipProvider: DdnsProvider = {\n id: 'spaceship',\n label: 'Spaceship',\n docsUrl: 'https://docs.spaceship.dev/',\n families: ['A', 'AAAA'],\n ttl: true,\n proxied: false,\n fields: [\n { key: 'apiKey', label: 'API key', hint: 'spaceship.com → API Manager; needs the `dnsrecords:read`/`write` scopes.', optional: false },\n { key: 'apiSecret', label: 'API secret', hint: 'Shown once with the key.', optional: false },\n ],\n\n validate(credentials) {\n return missingFields(credentials, ['apiKey', 'apiSecret'])\n },\n\n async update(record: DdnsRecord, context: DdnsContext): Promise<DdnsResult> {\n const { zone, name } = splitHost(record.host, record.zone)\n const headers = {\n 'X-API-Key': (context.credentials.apiKey ?? '').trim(),\n 'X-API-Secret': (context.credentials.apiSecret ?? '').trim(),\n 'Content-Type': 'application/json',\n }\n\n try {\n let found: SpaceshipRecord | undefined\n for (let skip = 0; skip < PAGE_SIZE * 5; skip += PAGE_SIZE) {\n const listed = await context.fetch(`${API}/${encodeURIComponent(zone)}?take=${PAGE_SIZE}&skip=${skip}`, { headers, signal: context.signal })\n if (!listed.ok)\n return failed(await errorText(listed))\n const body = await listed.json() as { items?: SpaceshipRecord[] } | SpaceshipRecord[]\n const items = Array.isArray(body) ? body : (body.items ?? [])\n found = items.find(entry => entry.name === name && entry.type === record.type)\n if (found !== undefined || items.length < PAGE_SIZE)\n break\n }\n\n if (found?.address === record.ip)\n return succeeded(`already ${record.ip}`, false)\n\n const written = await context.fetch(`${API}/${encodeURIComponent(zone)}`, {\n method: 'PUT',\n headers,\n body: JSON.stringify({ force: true, items: [{ type: record.type, name, ttl: spaceshipTtl(record.ttl), address: record.ip }] }),\n signal: context.signal,\n })\n return await wrote(written, record)\n }\n catch (error) {\n return failed(errorMessage(error))\n }\n },\n}\n","import type { DdnsProvider } from '#src/providers/ddns/types'\nimport type { DdnsConfig, DdnsProviderInfo } from '#src/shared/contracts'\nimport { cloudflareProvider } from '#src/providers/ddns/cloudflare'\nimport { desecProvider } from '#src/providers/ddns/desec'\nimport { digitaloceanProvider } from '#src/providers/ddns/digitalocean'\nimport { duckdnsProvider } from '#src/providers/ddns/duckdns'\nimport { dynuProvider } from '#src/providers/ddns/dynu'\nimport { freednsProvider } from '#src/providers/ddns/freedns'\nimport { gandiProvider } from '#src/providers/ddns/gandi'\nimport { godaddyProvider } from '#src/providers/ddns/godaddy'\nimport { henetProvider } from '#src/providers/ddns/henet'\nimport { namecheapProvider } from '#src/providers/ddns/namecheap'\nimport { namecheapApiProvider } from '#src/providers/ddns/namecheap-api'\nimport { noipProvider } from '#src/providers/ddns/noip'\nimport { porkbunProvider } from '#src/providers/ddns/porkbun'\nimport { spaceshipProvider } from '#src/providers/ddns/spaceship'\n\n/** Registry order is what the settings page offers. */\nexport const DDNS_PROVIDERS: readonly DdnsProvider[] = [\n cloudflareProvider,\n namecheapProvider,\n namecheapApiProvider,\n spaceshipProvider,\n porkbunProvider,\n godaddyProvider,\n gandiProvider,\n digitaloceanProvider,\n desecProvider,\n duckdnsProvider,\n noipProvider,\n dynuProvider,\n henetProvider,\n freednsProvider,\n]\n\nconst BY_ID = new Map(DDNS_PROVIDERS.map(provider => [provider.id, provider]))\n\nexport function ddnsProvider(id: string): DdnsProvider | null {\n return BY_ID.get(id) ?? null\n}\n\nexport function ddnsProviderInfos(): DdnsProviderInfo[] {\n return DDNS_PROVIDERS.map(provider => ({\n id: provider.id,\n label: provider.label,\n docsUrl: provider.docsUrl,\n families: provider.families,\n fields: provider.fields,\n ttl: provider.ttl,\n proxied: provider.proxied,\n txt: provider.challenge !== undefined,\n }))\n}\n\n/**\n * Cross-field problems ArkType cannot see. Credentials are deliberately not\n * required here: an account is normally added before its secret is typed in,\n * and a missing secret is reported per record instead of blocking the save.\n */\nexport function validateDdnsConfig(config: DdnsConfig): string[] {\n const errors: string[] = []\n const seenAccounts = new Set<string>()\n for (const account of config.accounts) {\n if (seenAccounts.has(account.id)) {\n errors.push(`account \"${account.id}\" is declared twice`)\n continue\n }\n seenAccounts.add(account.id)\n if (ddnsProvider(account.provider) === null)\n errors.push(`account \"${account.id}\" uses an unknown provider \"${account.provider}\"`)\n }\n\n const seenRecords = new Set<string>()\n for (const domain of config.domains) {\n const account = config.accounts.find(entry => entry.id === domain.account)\n if (account === undefined) {\n errors.push(`\"${domain.host}\" points at unknown account \"${domain.account}\"`)\n continue\n }\n // A `zone` is a short-circuit for the split heuristic, so one that does not contain the host makes\n // `splitHost` return the **whole** fqdn as the record name — GoDaddy was then asked for\n // `exmple.com/records/A/home.example.com`, a domain that is not the user's, and reported success.\n const zone = domain.zone?.trim().toLowerCase()\n if (zone !== undefined && zone.length > 0 && domain.host.toLowerCase() !== zone && !domain.host.toLowerCase().endsWith(`.${zone}`))\n errors.push(`\"${domain.host}\" has zone \"${domain.zone}\", which it is not inside — a zone is the registered domain the record lives in`)\n\n const provider = ddnsProvider(account.provider)\n if (provider !== null) {\n for (const recordType of domain.types) {\n if (!provider.families.includes(recordType))\n errors.push(`${account.label || provider.label} cannot manage ${recordType} records (\"${domain.host}\")`)\n const key = `${domain.host.toLowerCase()}|${recordType}`\n if (seenRecords.has(key))\n errors.push(`\"${domain.host}\" asks for ${recordType} twice`)\n seenRecords.add(key)\n }\n }\n }\n\n return errors\n}\n","import path from 'node:path'\nimport { readStateFile } from '#src/helpers/config-text'\nimport { errorMessage } from '#src/shared/error-message'\n\n/** `KEY=value` files, with optional `export `, `#` comments and quoted values. */\nexport function parseEnvFile(text: string): Record<string, string> {\n const env: Record<string, string> = {}\n\n for (const raw of text.split('\\n')) {\n const line = raw.trim()\n if (line.length === 0 || line.startsWith('#'))\n continue\n\n const assignment = line.startsWith('export ') ? line.slice(7) : line\n const separator = assignment.indexOf('=')\n if (separator <= 0)\n continue\n\n const key = assignment.slice(0, separator).trim()\n let value = assignment.slice(separator + 1).trim()\n if (value.length > 1 && ((value.startsWith('\"') && value.endsWith('\"')) || (value.startsWith('\\'') && value.endsWith('\\'')))) {\n value = value.slice(1, -1)\n }\n env[key] = value\n }\n\n return env\n}\n\n/**\n * Missing files are not an error: an env file is an optional override layer.\n *\n * Read through `readStateFile`: an entry's `envFile` is written by a person, not by this panel, so a\n * Windows editor's byte-order mark or UTF-16 save is the normal state of it. A `'utf8'` read made\n * every key carry a NUL — dropped by `resolveSpawn` as \"an environment key containing a null byte\" —\n * so the process started without the secret the file exists to keep out of the config.\n */\nexport function loadEnvFile(file: string): { env: Record<string, string>, path: string, error: string | null } {\n try {\n return { env: parseEnvFile(readStateFile(file)), path: file, error: null }\n }\n catch (error) {\n const code = (error as NodeJS.ErrnoException).code\n if (code === 'ENOENT')\n return { env: {}, path: file, error: null }\n return { env: {}, path: file, error: errorMessage(error) }\n }\n}\n\nconst VARIABLE = /\\$\\{([A-Z_]\\w*)\\}/gi\n\n/** Expands `${VAR}` from the given vars; unknown references are left visible. */\nexport function expandEnv(value: string, vars: Record<string, string | undefined>): string {\n return value.replace(VARIABLE, (match, name: string) => vars[name] ?? match)\n}\n\nexport function expandEnvRecord(record: Record<string, string>, vars: Record<string, string | undefined>): Record<string, string> {\n return Object.fromEntries(Object.entries(record).map(([key, value]) => [key, expandEnv(value, vars)]))\n}\n\nexport function expandEnvList(values: string[], vars: Record<string, string | undefined>): string[] {\n return values.map(value => expandEnv(value, vars))\n}\n\nexport function resolveEnvFilePath(file: string, cwd: string): string {\n if (path.isAbsolute(file))\n return file\n return path.resolve(cwd, file)\n}\n","import type { WebhookTarget } from '#src/shared/contracts'\nimport process from 'node:process'\nimport { expandEnv } from '#src/helpers/env-file'\nimport { errorMessage } from '#src/shared/error-message'\n\nexport interface WebhookOutcome {\n ok: boolean\n error?: string\n}\n\n/**\n * The general outbound transport: one HTTP request per configured target.\n *\n * `format` and `headers` are what make this able to talk to services with different contracts,\n * rather than a per-service adapter — the difference between ntfy and a JSON receiver is\n * exactly those two fields:\n *\n * - a **JSON** receiver (Discord, Slack, a bespoke endpoint) gets the event as a JSON body,\n * with the fields those services read (`text`, `content`) filled in;\n * - **ntfy** takes the plain message as the body and reads the notification's own fields from\n * headers, so a target pointing at `ntfy.sh/<topic>` sets `format: text` and\n * `headers: Title: …`, which is a configuration rather than a branch here.\n *\n * Headers are per target, so a bearer token or an API key lives in the config, not in code.\n * `${ENV}` expands in the URL and the header values, the way it does everywhere else in the\n * config — which is how a token stays **out** of `settings.json`: write `Authorization:\n * Bearer ${HH_WEBHOOK_TOKEN}` and the value comes from the panel's environment.\n */\n\nexport interface NotificationEventBody {\n title: string\n message: string\n reason: string\n serverId: string\n label: string\n}\n\nexport interface WebhookPayload {\n text: string\n content: string\n title: string\n message: string\n reason: string\n server: string | null\n label: string | null\n at: number\n}\n\n/** The JSON body for one event. Exported so a test can pin the shape without a round trip. */\nexport function webhookPayload(event: NotificationEventBody, now = Date.now()): WebhookPayload {\n const text = `${event.title}\\n${event.message}`\n return {\n text,\n // Slack reads `text`; Discord reads `content`. One body serves both.\n content: text,\n title: event.title,\n message: event.message,\n reason: event.reason,\n server: event.serverId.length > 0 ? event.serverId : null,\n label: event.label.length > 0 ? event.label : null,\n at: now,\n }\n}\n\n/**\n * What `Headers` will refuse, decided here so the refusal names the line.\n *\n * This is not a second opinion about validity: `Headers` (and Node's own `http`) throw on a name\n * holding a space or a non-ASCII letter, and on a value holding a character above `0xFF` — so\n * `Title: 🔴 server down` fails at the request with `Cannot convert argument to a ByteString …\n * value of 55357`, beside a `lastResult` a person reads as the receiver's fault. HTTP header values\n * are bytes, not text: ntfy's own answer for an emoji title is `=?UTF-8?B?…?=`. Naming both here\n * means the save is refused with the line quoted, and a config that already holds one says which\n * header it is instead of surfacing a JS engine message.\n */\nfunction headerProblem(name: string, value: string): string | null {\n // RFC 9110 `token`: visible ASCII minus the separators. A colon cannot appear (it splits the\n // line), so this is the set `Headers` accepts with the space and the high bytes taken out.\n // eslint-disable-next-line regexp/prefer-w, regexp/use-ignore-case -- the set is `token`, not a word\n if (!/^[!#$%&'*+\\-.^_`|~0-9A-Za-z]+$/.test(name))\n return `\"${name}\" is not a valid header name`\n for (const char of value) {\n if (char.codePointAt(0)! > 0xFF)\n return `the \"${name}\" value holds a character a header cannot carry (${char}) — headers are bytes, so encode it (ntfy reads \\`=?UTF-8?B?…?=\\`) or use format: json, which carries text in the body`\n }\n return null\n}\n\n/**\n * `Name: value` lines into a header map.\n *\n * The format is line-based rather than a JSON object because it is edited in a textarea, and\n * a value with a colon in it (`Authorization: Bearer a:b`) must survive: only the **first**\n * colon separates the two.\n *\n * `vars` expands `${ENV}` in the values, so a credential does not have to be written into the\n * config file. A name the panel's environment does not define is left as written, the same rule\n * `expandEnv` follows everywhere else — and `unexpanded` names those, because a leftover `${…}`\n * is not a credential.\n */\nexport function parseHeaders(\n text: string,\n vars: Record<string, string | undefined> = process.env,\n): { headers: Record<string, string>, errors: string[], unexpanded: string[] } {\n const headers: Record<string, string> = {}\n const errors: string[] = []\n const unexpanded: string[] = []\n for (const line of text.split('\\n')) {\n const trimmed = line.trim()\n if (trimmed.length === 0 || trimmed.startsWith('#'))\n continue\n const at = trimmed.indexOf(':')\n if (at <= 0) {\n errors.push(`\"${trimmed}\" is not a \"Name: value\" header`)\n continue\n }\n const name = trimmed.slice(0, at).trim()\n const value = expandEnv(trimmed.slice(at + 1).trim(), vars)\n // A `${…}` still to be expanded would only be a placeholder if it were one; validating it as\n // a byte string would report the wrong fault for a value the environment may still fill.\n if (value.includes('${')) {\n unexpanded.push(name)\n }\n else {\n const problem = headerProblem(name, value)\n if (problem !== null) {\n errors.push(problem)\n continue\n }\n }\n headers[name] = value\n }\n return { headers, errors, unexpanded }\n}\n\n/** Why a target cannot be sent to, or null when it can. Also used to validate a save. */\nexport function targetProblem(target: Pick<WebhookTarget, 'url' | 'headers'>, options: { requireUrl?: boolean } = {}): string | null {\n const url = target.url.trim()\n if (url.length === 0)\n return options.requireUrl === false ? null : 'no URL configured'\n\n let parsed: URL\n try {\n parsed = new URL(url)\n }\n catch {\n return 'the URL is not valid'\n }\n // Refused rather than attempted: a file: or javascript: target is not a receiver, and the\n // error a failed fetch gives for one does not say why.\n if (parsed.protocol !== 'http:' && parsed.protocol !== 'https:')\n return `the URL must be http or https, not ${parsed.protocol}`\n\n // A leftover `${NAME}` in a *header* is reported for the same reason the URL one is: the send\n // either succeeds with a literal `${NAME}` as the credential (a 401 the row blames on the\n // receiver) or 200s because the receiver ignored a header it could not use. The URL's check was\n // the only one, so an unset variable in `Authorization` failed silently.\n const { errors, unexpanded } = parseHeaders(target.headers)\n const problems = [...errors, ...(unexpanded.length > 0\n ? [`the ${unexpanded.map(name => `\"${name}\"`).join(', ')} header still holds an unexpanded placeholder — an environment variable in it is not set`]\n : [])]\n return problems.length > 0 ? problems.join('; ') : null\n}\n\nexport async function sendWebhook(\n target: Pick<WebhookTarget, 'url' | 'method' | 'format' | 'headers'>,\n event: NotificationEventBody,\n fetchImpl?: typeof fetch,\n): Promise<WebhookOutcome> {\n const problem = targetProblem(target)\n if (problem !== null)\n return { ok: false, error: problem }\n\n const { headers, errors } = parseHeaders(target.headers)\n if (errors.length > 0)\n return { ok: false, error: errors.join('; ') }\n\n const payload = webhookPayload(event)\n const asText = target.format === 'text'\n const body = asText ? payload.message : JSON.stringify(payload)\n\n // Expanded here and validated above, so an unset `${ENV}` in the URL is reported as such\n // rather than surfacing as a generic \"fetch failed\".\n // Every message quotes the URL as configured: the expanded one can hold the secret an `${ENV}`\n // placeholder exists to keep out of the settings file, and these messages are shown on the page.\n const configured = target.url.trim()\n const url = expandEnv(configured, process.env)\n if (url.includes('${'))\n return { ok: false, error: `the URL still holds an unexpanded placeholder: ${configured}` }\n\n // HTTP header names are case-insensitive, so a target's own `Content-Type:` must *replace* the\n // default rather than sit beside it — while keeping the spelling the person wrote, because that\n // is what a receiver's own docs quote back to them. Spreading the two objects made the config's\n // spelling a second name instead, and `Headers` folds those into one comma-joined value that no\n // receiver parses: measured against a real receiver, `Content-Type: application/json` arrived as\n // `application/json, application/json`, and the form-urlencoded override arrived as\n // `application/json, application/x-www-form-urlencoded` — the wrong one first.\n const sent: Record<string, string> = { 'content-type': asText ? 'text/plain; charset=utf-8' : 'application/json' }\n for (const [name, value] of Object.entries(headers)) {\n const key = name.toLowerCase()\n for (const existing of Object.keys(sent)) {\n if (existing.toLowerCase() === key)\n delete sent[existing]\n }\n sent[name] = value\n }\n\n try {\n const response = await (fetchImpl ?? fetch)(url, {\n method: target.method,\n headers: sent,\n body,\n // A wedged receiver must not hold a supervisor tick for ever.\n signal: AbortSignal.timeout(10_000),\n // Never followed: a redirect would carry the target's own credential headers to whatever\n // origin the receiver names, and could turn https into http.\n redirect: 'manual',\n })\n\n if (response.status >= 300 && response.status < 400) {\n const location = response.headers.get('location')\n return { ok: false, error: `answered ${response.status}, a redirect${location === null ? '' : ` to ${location.slice(0, 200)}`} — not followed; set the URL to the final address` }\n }\n if (!response.ok) {\n const detail = await response.text().catch(() => '')\n const trimmed = detail.trim().slice(0, 200)\n return { ok: false, error: `answered ${response.status}${trimmed.length > 0 ? `: ${trimmed}` : ''}` }\n }\n return { ok: true }\n }\n catch (error) {\n return { ok: false, error: errorMessage(error).replaceAll(url, configured) }\n }\n}\n","import type { ConfigMigration } from '#src/config/migrations'\nimport type { ResolvedServersFile, ResolvedWorkspaceConfig, ResolvedWorkspaceSettings } from '#src/config/schema'\nimport type {\n DdnsConfig,\n DdnsPatch,\n LogsConfig,\n NotificationsConfig,\n ServerConfig,\n ServerDefaults,\n ServerPatch,\n WorkspaceSettingsPatch,\n} from '#src/shared/contracts'\nimport fs from 'node:fs'\nimport path from 'node:path'\nimport { type } from 'arktype'\nimport { planConfigMigrations, UNSTAMPED_SCHEMA } from '#src/config/migrations'\nimport { parseServersFile, parseTolerant, parseWorkspaceSettings, stampConfig } from '#src/config/parse'\nimport { applyPatch, DDNS_MERGE_KEYS, EMPTY_MERGE_KEYS, NOTIFICATION_MERGE_KEYS, SERVER_MERGE_KEYS } from '#src/config/patch'\nimport {\n ddnsConfigSchema,\n defaultsSchema,\n logsSchema,\n mergeDefaults,\n notificationsSchema,\n serverSchema,\n serversFileSchema,\n workspaceSettingsSchema,\n} from '#src/config/schema'\nimport { SEED_SERVERS_FILE, SEED_WORKSPACE_SETTINGS } from '#src/config/seed'\nimport { assertSaveable, ConfigError } from '#src/config/settings'\nimport { writeFileAtomic } from '#src/helpers/atomic'\nimport { readStateFile } from '#src/helpers/config-text'\nimport { validateDdnsConfig } from '#src/providers/ddns'\nimport { targetProblem } from '#src/providers/webhook'\nimport { duplicateWebhookIds } from '#src/shared/contracts'\n\nexport { ConfigError }\nexport type { ResolvedServersFile, ResolvedWorkspaceSettings }\n\ninterface ReadResult {\n text: string | null\n parsed: unknown\n missing: boolean\n /** Set when the file is there but not JSON; `parsed` is null then. */\n parseError: string | null\n}\n\nfunction readFile(file: string): ReadResult {\n let text: string\n try {\n // Not `'utf8'`: a Windows editor saves these files with a BOM, and `JSON.parse` refuses\n // the invisible character — reporting a file whose JSON is fine as \"cannot parse\"\n // (`helpers/config-text.ts`).\n text = readStateFile(file)\n }\n catch (error) {\n if ((error as NodeJS.ErrnoException).code === 'ENOENT')\n return { text: null, parsed: null, missing: true, parseError: null }\n return { text: null, parsed: null, missing: false, parseError: (error as Error).message }\n }\n try {\n return { text, parsed: JSON.parse(text), missing: false, parseError: null }\n }\n catch (error) {\n return { text, parsed: null, missing: false, parseError: (error as Error).message }\n }\n}\n\n/**\n * One workspace's state: its settings file (`defaults`, `logs`, `notifications`,\n * `ddns`) and its servers file, kept apart because they are written by different\n * pages and read by different parts of the panel.\n *\n * Reads stay tolerant in both: an unknown key is reported and skipped, never\n * fatal, so a file written by a newer release still opens the page that edits it.\n * A file this release cannot even parse never replaces what is already running —\n * neither the resolved config nor the `raw` every write patches.\n */\nexport class WorkspaceStore {\n private rawSettings: Record<string, unknown> = {}\n private rawServers: Record<string, unknown> = {}\n private liveSettings: unknown = null\n private liveServers: unknown = null\n /** The bytes behind `liveSettings`/`liveServers`: the last revision that parsed. */\n private liveSettingsText: string | null = null\n private liveServersText: string | null = null\n /** The bytes behind `rawSettings`/`rawServers`, the objects a save patches: what a save may replace. */\n private trustedSettingsText: string | null = null\n private trustedServersText: string | null = null\n /** The bytes last looked at, so an unchanged file (ours, or a broken edit) is not re-read. */\n private seenSettingsText: string | null = null\n private seenServersText: string | null = null\n private resolvedConfig!: ResolvedWorkspaceConfig\n /** A JSON parse failure, kept apart from a schema problem so `apply()` cannot clear it. */\n private settingsParseError: string | null = null\n private serversParseError: string | null = null\n private settingsError: string | null = null\n private serversError: string | null = null\n private warnings: string[] = []\n private settingsSchemaVersion = UNSTAMPED_SCHEMA\n private serversSchemaVersion = UNSTAMPED_SCHEMA\n private readonly listeners = new Set<() => void>()\n private readonly conflictListeners = new Set<() => void>()\n\n constructor(\n private readonly workspaceId: string,\n private readonly settingsFile: string,\n private readonly serversFile: string,\n private readonly seedSettings: Record<string, unknown> = SEED_WORKSPACE_SETTINGS,\n private readonly seedServers: Record<string, unknown> = SEED_SERVERS_FILE,\n ) {}\n\n get id(): string {\n return this.workspaceId\n }\n\n /** The servers config; the runtime, the watcher and the docs call it that. */\n get path(): string {\n return this.serversFile\n }\n\n get settingsPath(): string {\n return this.settingsFile\n }\n\n get config(): ResolvedWorkspaceConfig {\n return this.resolvedConfig\n }\n\n get servers(): ServerConfig[] {\n return this.resolvedConfig.servers\n }\n\n get defaults(): ServerDefaults {\n return this.resolvedConfig.defaults\n }\n\n get logs(): LogsConfig {\n return this.resolvedConfig.logs\n }\n\n get notifications(): NotificationsConfig {\n return this.resolvedConfig.notifications\n }\n\n get ddns(): DdnsConfig {\n return this.resolvedConfig.ddns\n }\n\n get configError(): string | null {\n return [\n this.settingsParseError ?? this.settingsError,\n this.serversParseError ?? this.serversError,\n ].filter(error => error !== null).join('; ') || null\n }\n\n get configWarnings(): string[] {\n return [...this.warnings]\n }\n\n get configSchemaVersion(): number {\n return Math.max(this.settingsSchemaVersion, this.serversSchemaVersion)\n }\n\n /**\n * The steps a workspace's files need, counting **both** sides.\n *\n * The two files are stamped independently — a person may hand-write `servers.config.json`\n * (which is unstamped, and so reads as schema 1) beside a `settings.json` the panel wrote at\n * the current schema. `configSchemaVersion` answers `max()` because that is the shape *this\n * release* understands of the pair, but the migrations that have to run belong to the **older**\n * file: `planConfigMigrations` is monotonic, so the lower version is the one with steps.\n * Reading `max()` here reported *no* pending migration while the reader was refusing the file\n * for needing one, which left the startup branch that says `run migrate` unreachable and sent\n * the person to \"fix or install\" instead.\n *\n * A file that cannot be **parsed** is not a migration candidate, though: a schema number can only\n * be read from a file that is JSON, and `migrate` refuses one it cannot read rather than lifting\n * it. The startup guard prints this list as \"run migrate\", so a broken file must not appear\n * here — it belongs in `configError`'s \"fix …\" advice alone.\n */\n get pendingMigrations(): ConfigMigration[] {\n if (this.settingsParseError !== null || this.serversParseError !== null)\n return []\n return planConfigMigrations(Math.min(this.settingsSchemaVersion, this.serversSchemaVersion)).steps\n }\n\n onChange(listener: () => void): () => void {\n this.listeners.add(listener)\n return () => this.listeners.delete(listener)\n }\n\n /** Told when a save was refused because a file changed on disk, so its owner can reload it. */\n onConflict(listener: () => void): () => void {\n this.conflictListeners.add(listener)\n return () => this.conflictListeners.delete(listener)\n }\n\n /** How many listeners are attached; a disposed owner must not add to it. */\n get listenerCount(): number {\n return this.listeners.size\n }\n\n getServer(id: string): ServerConfig | undefined {\n return this.servers.find(server => server.id === id)\n }\n\n /** Reads both files, seeding a missing one; `{ write: false }` reads a missing file as its seed without creating it. */\n load(options: { write?: boolean } = {}): void {\n this.read(options.write !== false)\n this.apply()\n this.notify()\n }\n\n /**\n * The watcher's entry point: re-reads the files only when their bytes changed.\n *\n * `changed` means the bytes on disk differ from the last trusted read, `applied`\n * means that difference produced a usable config. A revision this release cannot\n * parse is reported in the state frame while the running config is kept, which is\n * what stops an editor's typo from stopping every server — or from bricking the\n * next Save, which patches the raw object this method must therefore leave alone.\n */\n reloadFromDisk(): { changed: boolean, applied: boolean, error: string | null } {\n const settings = readFile(this.settingsFile)\n const servers = readFile(this.serversFile)\n if (settings.missing || servers.missing) {\n this.markGone(settings.missing ? this.settingsFile : this.serversFile)\n return { changed: false, applied: false, error: this.configError }\n }\n\n let changed = false\n let applied = false\n\n for (const side of ['settings', 'servers'] as const) {\n const read = side === 'settings' ? settings : servers\n const seen = side === 'settings' ? this.seenSettingsText : this.seenServersText\n const file = side === 'settings' ? this.settingsFile : this.serversFile\n\n if (read.text === seen)\n continue\n changed = true\n if (side === 'settings')\n this.seenSettingsText = read.text\n else\n this.seenServersText = read.text\n\n if (read.parseError !== null) {\n const message = `cannot parse ${path.basename(file)}: ${read.parseError}`\n if (side === 'settings')\n this.settingsParseError = message\n else\n this.serversParseError = message\n // The live/raw values — and the bytes a save may replace — stay on the last trusted read.\n continue\n }\n\n if (side === 'settings') {\n this.settingsParseError = null\n this.liveSettings = read.parsed\n this.liveSettingsText = read.text\n }\n else {\n this.serversParseError = null\n this.liveServers = read.parsed\n this.liveServersText = read.text\n }\n applied = true\n }\n\n if (!changed && !applied && this.configError === null)\n return { changed: false, applied: false, error: null }\n\n this.apply()\n this.notify()\n return { changed, applied, error: this.configError }\n }\n\n private markGone(file: string): void {\n const message = `${path.basename(file)} is gone`\n if (file === this.settingsFile)\n this.settingsError = message\n else\n this.serversError = message\n }\n\n private read(write = true): void {\n let settings = readFile(this.settingsFile)\n if (settings.missing) {\n const seed = stampConfig(structuredClone(this.seedSettings))\n const text = `${JSON.stringify(seed, null, 2)}\\n`\n if (write)\n writeFileAtomic(this.settingsFile, text)\n settings = { text, parsed: seed, missing: false, parseError: null }\n }\n let servers = readFile(this.serversFile)\n if (servers.missing) {\n const seed = stampConfig(structuredClone(this.seedServers))\n const text = `${JSON.stringify(seed, null, 2)}\\n`\n if (write)\n writeFileAtomic(this.serversFile, text)\n servers = { text, parsed: seed, missing: false, parseError: null }\n }\n\n this.seenSettingsText = settings.text\n this.seenServersText = servers.text\n this.settingsParseError = settings.parseError === null ? null : `cannot parse ${path.basename(this.settingsFile)}: ${settings.parseError}`\n this.serversParseError = servers.parseError === null ? null : `cannot parse ${path.basename(this.serversFile)}: ${servers.parseError}`\n if (settings.parseError === null) {\n this.liveSettings = settings.parsed\n this.liveSettingsText = settings.text\n }\n if (servers.parseError === null) {\n this.liveServers = servers.parsed\n this.liveServersText = servers.text\n }\n }\n\n private notify(): void {\n for (const listener of this.listeners) listener()\n }\n\n updateServer(id: string, patch: ServerPatch): ServerConfig {\n const list = (this.rawServers.servers as Record<string, unknown>[] | undefined) ?? []\n const index = list.findIndex(entry => entry.id === id)\n if (index < 0)\n throw new ConfigError(`unknown server \"${id}\"`, 'UNKNOWN_SERVER')\n\n const draft = structuredClone(this.rawServers)\n const entry = (draft.servers as Record<string, unknown>[])[index]!\n applyPatch(entry, patch as Record<string, unknown>, SERVER_MERGE_KEYS)\n\n const validated = this.validateServer(entry, `servers[${index}]`)\n this.commitServers(draft)\n return validated\n }\n\n updateDefaults(patch: NonNullable<WorkspaceSettingsPatch['defaults']>): ServerDefaults {\n const draft = structuredClone(this.rawSettings)\n draft.defaults = { ...(draft.defaults as Record<string, unknown> ?? {}) }\n applyPatch(draft.defaults as Record<string, unknown>, patch as Record<string, unknown>, SERVER_MERGE_KEYS)\n\n const defaults = this.parseGroup<ServerDefaults>(defaultsSchema as unknown as (input: unknown) => unknown, draft.defaults as Record<string, unknown>, 'defaults')\n\n this.commitSettings(draft)\n return defaults\n }\n\n updateLogs(patch: NonNullable<WorkspaceSettingsPatch['logs']>): LogsConfig {\n const draft = structuredClone(this.rawSettings)\n draft.logs = { ...(draft.logs as Record<string, unknown> ?? {}) }\n applyPatch(draft.logs as Record<string, unknown>, patch as Record<string, unknown>, EMPTY_MERGE_KEYS)\n\n const logs = this.parseGroup<LogsConfig>(logsSchema as unknown as (input: unknown) => unknown, draft.logs as Record<string, unknown>, 'logs')\n\n this.commitSettings(draft)\n return logs\n }\n\n updateNotifications(patch: NonNullable<WorkspaceSettingsPatch['notifications']>): NotificationsConfig {\n const draft = structuredClone(this.rawSettings)\n draft.notifications = { ...(draft.notifications as Record<string, unknown> ?? {}) }\n applyPatch(draft.notifications as Record<string, unknown>, patch as Record<string, unknown>, NOTIFICATION_MERGE_KEYS)\n\n const notifications = this.parseGroup<NotificationsConfig>(notificationsSchema as unknown as (input: unknown) => unknown, draft.notifications as Record<string, unknown>, 'notifications')\n\n // The list's ids are its identity: the cooldown and the last-result record are keyed by\n // one, so two targets sharing it would behave as a single target. Refused here, where the\n // write lands, because the schema cannot express it (a predicate breaks `toJsonSchema`).\n const duplicates = duplicateWebhookIds(notifications.destinations)\n if (duplicates.length > 0)\n throw new ConfigError(`notifications: duplicate webhook id ${duplicates.map(id => `\"${id}\"`).join(', ')}`)\n\n // An enabled target with no usable URL fails every event it is asked to send, silently and\n // for ever — the page refuses to save one, but the API is a second door to the same list.\n for (const target of notifications.destinations) {\n // Only a webhook has a URL to check; a Telegram destination's failure mode is a missing token,\n // which is surfaced on the page rather than refused here (the secret may arrive later).\n if (target.kind !== 'webhook')\n continue\n const problem = targetProblem(target, { requireUrl: true })\n if (problem !== null)\n throw new ConfigError(`notifications: webhook \"${target.id}\" ${problem}`)\n }\n\n this.commitSettings(draft)\n return notifications\n }\n\n /**\n * The DDNS block merges its two nested groups and **replaces** `accounts` and\n * `domains`: those are lists, and a key-by-key merge cannot express removing a\n * hostname. A whole-block patch (the `PUT /api/ddns` route) lands the same way.\n */\n updateDdns(patch: DdnsPatch): DdnsConfig {\n const draft = structuredClone(this.rawSettings)\n draft.ddns = { ...(draft.ddns as Record<string, unknown> ?? {}) }\n applyPatch(draft.ddns as Record<string, unknown>, patch as Record<string, unknown>, DDNS_MERGE_KEYS)\n\n const parsed = this.parseGroup<DdnsConfig>(ddnsConfigSchema as unknown as (input: unknown) => unknown, draft.ddns as Record<string, unknown>, 'ddns')\n\n const problems = validateDdnsConfig(parsed)\n if (problems.length > 0)\n throw new ConfigError(`ddns: ${problems.join('; ')}`)\n\n this.commitSettings(draft)\n return parsed\n }\n\n addServer(input: Record<string, unknown>): ServerConfig {\n const draft = structuredClone(this.rawServers)\n const list = (draft.servers as Record<string, unknown>[] | undefined) ?? (draft.servers = [])\n if (list.some(entry => entry.id === input.id))\n throw new ConfigError(`server \"${String(input.id)}\" already exists`)\n\n const index = list.length\n list.push(structuredClone(input))\n const validated = this.validateServer(list[index]!, `servers[${index}]`)\n this.commitServers(draft)\n return validated\n }\n\n /**\n * Creates the entry, or replaces a same-id one outright — \"make it so\".\n *\n * `addServer` refuses a duplicate and `updateServer` only patches an existing entry, so a config\n * management pass had to GET, diff, then POST or PATCH, and a re-run of an unchanged declaration\n * got `400 INVALID_SERVER` for its trouble. A replace is what a declarative caller means: the\n * body is the whole entry, not a patch.\n *\n * Returns whether it created or replaced, so the route can answer 201 or 200 honestly.\n */\n putServer(input: Record<string, unknown>): { server: ServerConfig, created: boolean } {\n const draft = structuredClone(this.rawServers)\n const list = (draft.servers as Record<string, unknown>[] | undefined) ?? (draft.servers = [])\n const index = list.findIndex(entry => entry.id === input.id)\n const created = index < 0\n\n // Replace in place so a re-declared entry keeps its position in the list, which is the order\n // the panel shows; a create appends.\n if (created)\n list.push(structuredClone(input))\n else\n list[index] = structuredClone(input)\n\n const validated = this.validateServer(list[created ? list.length - 1 : index]!, `servers[${created ? list.length - 1 : index}]`)\n this.commitServers(draft)\n return { server: validated, created }\n }\n\n removeServer(id: string): void {\n const draft = structuredClone(this.rawServers)\n const list = (draft.servers as Record<string, unknown>[] | undefined) ?? []\n const before = list.length\n draft.servers = list.filter(entry => entry.id !== id)\n if ((draft.servers as unknown[]).length === before)\n throw new ConfigError(`unknown server \"${id}\"`, 'UNKNOWN_SERVER')\n this.commitServers(draft)\n }\n\n /**\n * Regenerates both JSON schemas for editor autocomplete, beside the files they\n * describe — derived from this store's own paths, never from a module-level\n * default, so a store over a custom root cannot write into `$HHOSTED_HOME`.\n */\n writeJsonSchema(): void {\n this.writeSchema(path.join(path.dirname(this.settingsFile), 'settings.schema.json'), workspaceSettingsSchema)\n this.writeSchema(path.join(path.dirname(this.serversFile), `${path.basename(this.serversFile, '.json')}.schema.json`), serversFileSchema)\n }\n\n private writeSchema(file: string, schema: { toJsonSchema: () => unknown }): void {\n const text = JSON.stringify(schema.toJsonSchema(), null, 2)\n const current = fs.existsSync(file) ? fs.readFileSync(file, 'utf8') : null\n if (current !== text)\n writeFileAtomic(file, text)\n }\n\n private parseGroup<T>(schema: (input: unknown) => unknown, value: Record<string, unknown>, label: string): T {\n const parsed = parseTolerant(value, schema, label, [])\n if (parsed.error !== null)\n throw new ConfigError(`${label}: ${parsed.error}`)\n return parsed.value as T\n }\n\n private validateServer(entry: Record<string, unknown>, label: string): ServerConfig {\n const parsed = serverSchema(mergeDefaults(this.defaults as unknown as Record<string, unknown>, entry))\n if (parsed instanceof type.errors)\n throw new ConfigError(`${label}: ${parsed.summary}`)\n return { ...parsed, port: parsed.port ?? null }\n }\n\n private commitSettings(draft: Record<string, unknown>): void {\n // A save patches the last trusted read, so a hand edit not yet loaded — or one that cannot be\n // loaded at all — would be overwritten.\n assertSaveable(this.settingsFile, { trusted: this.trustedSettingsText, seen: this.seenSettingsText, unusable: this.settingsParseError ?? this.settingsError }, this.conflictListeners)\n const stamped = stampConfig(draft)\n const text = `${JSON.stringify(stamped, null, 2)}\\n`\n writeFileAtomic(this.settingsFile, text)\n this.seenSettingsText = text\n this.liveSettingsText = text\n this.liveSettings = stamped\n this.settingsParseError = null\n this.apply()\n this.notify()\n }\n\n private commitServers(draft: Record<string, unknown>): void {\n assertSaveable(this.serversFile, { trusted: this.trustedServersText, seen: this.seenServersText, unusable: this.serversParseError ?? this.serversError }, this.conflictListeners)\n const stamped = stampConfig(draft)\n const text = `${JSON.stringify(stamped, null, 2)}\\n`\n writeFileAtomic(this.serversFile, text)\n this.seenServersText = text\n this.liveServersText = text\n this.liveServers = stamped\n this.serversParseError = null\n this.apply()\n this.notify()\n }\n\n private apply(): void {\n const settings = parseWorkspaceSettings(this.liveSettings)\n const haveResolved = this.resolvedConfig !== undefined\n // A settings file that fails the schema keeps the defaults already in force: resolving against\n // `{}` silently reverted every server to the code defaults while `defaults` still said otherwise.\n const defaults = settings.config?.defaults ?? (haveResolved ? this.resolvedConfig.defaults : undefined)\n const servers = parseServersFile(this.liveServers, defaults as unknown as Record<string, unknown> ?? {})\n\n this.settingsError = this.settingsParseError ?? (settings.errors.length > 0 ? settings.errors.join('; ') : null)\n this.serversError = this.serversParseError ?? (servers.errors.length > 0 ? servers.errors.join('; ') : null)\n this.settingsSchemaVersion = settings.schemaVersion\n this.serversSchemaVersion = servers.schemaVersion\n this.warnings = [\n ...settings.warnings,\n ...servers.warnings,\n ...(settings.unknownKeys.length === 0 && servers.unknownKeys.length === 0\n ? []\n : [`this workspace carries ${settings.unknownKeys.length + servers.unknownKeys.length} unrecognized key(s) this release ignores: ${[...settings.unknownKeys, ...servers.unknownKeys].join(', ')}`]),\n ]\n\n // A side this release cannot read keeps the values already running; only a\n // first load falls back to the schema defaults.\n const settingsConfig: ResolvedWorkspaceSettings = settings.config ?? (haveResolved\n ? {\n defaults: this.resolvedConfig.defaults,\n logs: this.resolvedConfig.logs,\n notifications: this.resolvedConfig.notifications,\n ddns: this.resolvedConfig.ddns,\n }\n : this.resolveSettingsFallback())\n const nextServers = servers.errors.length === 0\n ? servers.servers\n : haveResolved ? this.resolvedConfig.servers : []\n this.resolvedConfig = { ...settingsConfig, servers: nextServers }\n\n // The raw objects every write patches follow the last trusted read only.\n if (settings.config !== null) {\n this.rawSettings = structuredClone(this.liveSettings) as Record<string, unknown>\n this.trustedSettingsText = this.liveSettingsText\n }\n if (servers.errors.length === 0) {\n this.rawServers = structuredClone(this.liveServers) as Record<string, unknown>\n this.trustedServersText = this.liveServersText\n }\n }\n\n private resolveSettingsFallback(): ResolvedWorkspaceSettings {\n const defaults = defaultsSchema({})\n const logs = logsSchema({})\n const notifications = notificationsSchema({})\n const ddns = ddnsConfigSchema({})\n if (defaults instanceof type.errors || logs instanceof type.errors || notifications instanceof type.errors || ddns instanceof type.errors)\n throw new ConfigError('internal: default workspace settings failed validation')\n return { defaults, logs, notifications, ddns }\n }\n}\n","import type { EntryState } from '#src/shared/contracts'\nimport fs from 'node:fs'\nimport path from 'node:path'\nimport { type } from 'arktype'\nimport { writeFileAtomic } from '#src/helpers/atomic'\nimport { entryStateSchema } from '#src/shared/contracts'\n\n/**\n * The small slice of a server's runtime the panel has to remember across its own\n * restarts: how much of the retry budget is spent, and whether a `runOnce` bootstrap\n * already ran.\n *\n * Both lived only in memory, so a panel restart — a `restart`, a crash, a reboot —\n * handed a crash-looping server a fresh `maxRetries` and re-ran its bootstrap. The\n * retry counter has to outlive the process that increments it to bound anything.\n */\n\n/** One JSON file per entry, beside the nanny's own state. */\nexport function entryStatePath(dir: string, id: string): string {\n return path.join(dir, `${id}.run.json`)\n}\n\nexport function readEntryState(file: string): EntryState | null {\n try {\n const parsed = entryStateSchema(JSON.parse(fs.readFileSync(file, 'utf8')))\n return parsed instanceof type.errors ? null : parsed\n }\n catch {\n return null\n }\n}\n\nexport function writeEntryState(file: string, state: EntryState): void {\n try {\n writeFileAtomic(file, `${JSON.stringify(state)}\\n`)\n }\n catch {\n // Best effort, like history: no state file must never stop supervision.\n }\n}\n\nexport function clearEntryState(file: string): void {\n fs.rmSync(file, { force: true })\n}\n","import { isRecord } from '#src/shared/shape'\n\nexport type SecretScope = 'global' | 'workspace'\n\nexport interface SecretPart {\n /** The leaf id: `password`, `apiToken`, `telegram` (bot tokens by destination), `ddns`, or a future top-level key. */\n key: string\n /** The top-level file keys this part carries. `ddns` carries `['ddns', 'ddnsKdf']`. */\n fields: string[]\n scope: SecretScope\n}\n\n/** Every secret this release knows about, set or not — the view lists the slots so a person sees one. */\nexport const KNOWN_SECRET_KEYS: Record<SecretScope, string[]> = {\n global: ['password', 'apiToken'],\n workspace: ['telegram', 'ddns'],\n}\n\n/** Where a secret this release knows lives. Everything else is scoped by its own file. */\nconst KNOWN_SCOPES: Record<string, SecretScope> = {\n password: 'global',\n apiToken: 'global',\n telegram: 'workspace',\n ddns: 'workspace',\n}\n\n/** A part carrying more than its own key: `ddnsKdf` is how the sealed DDNS entries are opened. */\nconst EXTRA_FIELDS: Record<string, string[]> = { ddns: ['ddns', 'ddnsKdf'] }\n\n/**\n * The parts of one scope, in a stable order: the known parts first in the fixed order\n * password, apiToken (global) / telegram, ddns (workspace) — then any other top-level\n * key present in `present`, sorted, as its own part with `fields: [key]`.\n *\n * An unknown key is taken as belonging to the scope being asked about, because the file\n * it was read from is the only evidence of where it lives: this release does not know the\n * key, so classifying it by name would drop a future *global* secret on the floor.\n */\nexport function secretParts(scope: SecretScope, present: string[]): SecretPart[] {\n const keys = new Set(present)\n const known = KNOWN_SECRET_KEYS[scope]\n const parts = known\n .filter(key => keys.has(key))\n .map(key => ({ key, fields: EXTRA_FIELDS[key] ?? [key], scope }))\n // A key another part carries (`ddnsKdf`) is not a secret of its own; it is offered only\n // when the part that owns it is missing, so nothing in the file becomes unreachable.\n const consumed = new Set(parts.flatMap(part => part.fields))\n const rest = [...keys]\n .filter(key => KNOWN_SCOPES[key] === undefined && !known.includes(key) && !consumed.has(key))\n .sort()\n return [...parts, ...rest.map(key => ({ key, fields: [key], scope }))]\n}\n\n/** The top-level keys of a raw secrets document that hold a non-null value. */\nexport function presentSecretKeys(source: Record<string, unknown>): string[] {\n return Object.entries(source)\n .filter(([, value]) => value !== null && value !== undefined)\n .map(([key]) => key)\n}\n\n/**\n * A JSON string carrying only `fields`, taken from `source`. Returns null when `source`\n * carries none of them. Always includes a field whose value is `null` ONLY if it is\n * present as a key and non-null; a null/absent field is omitted.\n */\nexport function pickSecrets(source: Record<string, unknown>, fields: string[]): string | null {\n const picked: Record<string, unknown> = {}\n for (const field of fields) {\n const value = source[field]\n if (value !== null && value !== undefined)\n picked[field] = withoutFirstRunPassword(value)\n }\n return Object.keys(picked).length === 0 ? null : JSON.stringify(picked)\n}\n\n/**\n * Drops `password.initial` — the generated first-run password, which the live file keeps so `up` and\n * `status` can show it on the machine.\n *\n * An archive is a copy *off* the box: unencrypted unless a password was given, and the docs recommend\n * keeping it elsewhere, so carrying the plaintext there hands a reader a working credential the hash\n * beside it exists to avoid. The hash restores a password, which is all a restore needs.\n */\nfunction withoutFirstRunPassword(value: unknown): unknown {\n if (!isRecord(value) || !('initial' in value))\n return value\n const { initial: _initial, ...rest } = value\n return rest\n}\n\n/**\n * The same removal, applied to a whole secrets **document** rather than one field's value.\n *\n * `pickSecrets` already drops the field, but a backup that selects every secret copies the file\n * whole and so bypassed it. This is that whole-file path: the document keeps every other key —\n * including `null` slots and keys this release does not know — and differs only in that\n * `password.initial` is gone. Returns `null` when the text is not a JSON object, so the caller can\n * fall back to its ordinary copy.\n */\nexport function withoutInitialPassword(text: string): string | null {\n let parsed: unknown\n try {\n parsed = JSON.parse(text)\n }\n catch {\n return null\n }\n if (!isRecord(parsed))\n return null\n // A document with no `password` key is already clean; it is still returned, normalised, so a caller\n // never has to fall back to copying the original bytes — that fallback is what let a BOM'd file\n // through with the password intact.\n return `${JSON.stringify('password' in parsed ? { ...parsed, password: withoutFirstRunPassword(parsed.password) } : parsed)}\\n`\n}\n\n/** Parses a secrets document, tolerating anything: not-an-object, or broken JSON returns {}. */\nexport function parseSecrets(text: string): Record<string, unknown> {\n try {\n const parsed: unknown = JSON.parse(text)\n return isRecord(parsed) ? parsed : {}\n }\n catch {\n return {}\n }\n}\n\n/**\n * Merges `piece` into `current`, changing ONLY the fields in `fields` — every other key\n * of `current` is preserved (this is what stops restoring the Telegram token from wiping\n * the DDNS credentials). A field that is absent from `piece` is also DELETED from the\n * result, so restoring an older archive that predates a secret clears it rather than\n * leaving a stale value. Returns a new object; does not mutate its arguments.\n */\nexport function mergeSecrets(current: Record<string, unknown>, piece: Record<string, unknown>, fields: string[]): Record<string, unknown> {\n const merged = { ...current }\n for (const field of fields) {\n const value = piece[field]\n if (value === null || value === undefined)\n delete merged[field]\n else\n merged[field] = value\n }\n return merged\n}\n","import fs from 'node:fs'\nimport path from 'node:path'\nimport process from 'node:process'\nimport { writeFileAtomic } from '#src/helpers/atomic'\nimport { ensureStateDir } from '#src/helpers/paths'\n\n/**\n * A lock file that stops two restores from writing the same host at once.\n *\n * A restore replaces config and data paths in place. Two of them interleaved — or one from the CLI\n * while the panel's own restore runs — write over each other, and neither knows the other exists.\n * That is also why it has to cover **both** paths: the panel and the offline CLI take the same lock,\n * so they exclude each other rather than only themselves.\n *\n * A pid that is gone means the holder died mid-restore, which used to leave a lock nobody could\n * clear. Stale is decided the same way `up`/`down` decide it — the recorded pid *and* its start time —\n * so a recycled pid is not mistaken for a live holder.\n */\n\n/** How long a restore may hold the lock before another waits no longer on it. */\nconst STALE_AFTER_MS = 30 * 60_000\n\n/** Absorbs the one-second granularity of a birth-time reading against the moment we recorded it. */\nconst BIRTH_TOLERANCE_MS = 2000\n\nexport interface LockRecord {\n pid: number\n startedAt: number\n action: string\n /**\n * The holder's own birth time where the platform reports one.\n *\n * `startedAt` is when the lock was taken, which says nothing about whether the pid still names the\n * same process — comparing the two made a long-held lock look recycled. This is the value that\n * answers the question directly, so a stale-reader compares like with like.\n */\n birthAt?: number | null\n}\n\nexport interface RestoreLock {\n /** Releases the lock. Safe to call twice. */\n release: () => void\n /** The holder, when the lock was taken over from a dead one. */\n replaced?: LockRecord\n}\n\nfunction readRecord(file: string): LockRecord | null {\n try {\n const parsed = JSON.parse(fs.readFileSync(file, 'utf8')) as Partial<LockRecord>\n if (typeof parsed.pid !== 'number' || typeof parsed.startedAt !== 'number')\n return null\n // `birthAt` must survive the read: it is the whole basis for the recycled-pid check, and\n // dropping it here silently fell back to inferring liveness from the lock's age.\n return {\n pid: parsed.pid,\n startedAt: parsed.startedAt,\n action: typeof parsed.action === 'string' ? parsed.action : 'restore',\n birthAt: typeof parsed.birthAt === 'number' ? parsed.birthAt : null,\n }\n }\n catch {\n return null\n }\n}\n\n/**\n * Is the recorded holder still the process that took it?\n *\n * Signal 0 alone is not enough — pids are recycled, and a zombie answers it — so the process's own\n * start time is compared with the recorded one where the platform can report it. Elsewhere the pid is\n * all there is, and an alive pid is taken as alive, which errs towards \"somebody is working\" rather\n * than stealing a live lock.\n */\nfunction holderIsAlive(record: LockRecord): boolean {\n try {\n process.kill(record.pid, 0)\n }\n catch (error) {\n // EPERM means the process exists but belongs to another user — still a live holder.\n return (error as NodeJS.ErrnoException).code === 'EPERM'\n }\n const birth = processBirthSync(record.pid)\n // A platform that cannot answer keeps the cautious answer — an alive pid is a live holder.\n if (birth === null)\n return true\n // When the record carries the holder's own birth time, compare like with like: this is the direct\n // question, and a recycled pid answers it plainly.\n if (record.birthAt != null)\n return Math.abs(birth - record.birthAt) <= BIRTH_TOLERANCE_MS\n // An older record has no birth time. Fall back to the only inference available: a pid born *after*\n // the lock was recorded is a different process, and one born before it may be the holder.\n return birth <= record.startedAt + BIRTH_TOLERANCE_MS\n}\n\n/** Wall-clock start of a pid in ms, or null where the platform cannot report one. */\nexport function processBirthSync(pid: number): number | null {\n try {\n // Linux: field 22 is the start time in clock ticks since boot, and `/proc/stat` has the boot time.\n const stat = fs.readFileSync(`/proc/${pid}/stat`, 'utf8')\n const fields = stat.slice(stat.lastIndexOf(')') + 2).split(' ')\n const ticks = Number.parseFloat(fields[19] ?? '')\n if (!Number.isFinite(ticks))\n return null\n const boot = /^btime (\\d+)$/m.exec(fs.readFileSync('/proc/stat', 'utf8'))?.[1]\n if (boot === undefined)\n return null\n // 100 ticks a second on every mainstream kernel build.\n return Number.parseInt(boot, 10) * 1000 + (ticks / 100) * 1000\n }\n catch {\n return null\n }\n}\n\n/** The live holder of the restore lock, without taking it; null when nobody is restoring. */\nexport function restoreLockHolder(hhDir: string): LockRecord | null {\n const existing = readRecord(path.join(hhDir, 'restore.lock'))\n return existing !== null && isLiveHolder(existing) ? existing : null\n}\n\n/** The holder is alive and has not held the lock absurdly long. */\nfunction isLiveHolder(record: LockRecord): boolean {\n return holderIsAlive(record) && Date.now() - record.startedAt <= STALE_AFTER_MS\n}\n\n/**\n * Take the restore lock, or explain who holds it.\n *\n * `null` means somebody else is restoring. The caller reports it rather than queueing: a restore is\n * an interactive decision, and waiting on one you did not start is not what a person asked for.\n */\nexport function acquireRestoreLock(hhDir: string, action = 'restore'): RestoreLock | { heldBy: LockRecord } {\n const file = path.join(hhDir, 'restore.lock')\n ensureStateDir(hhDir)\n\n // Our record, decided once: `release()` compares against it to tell \"still mine\" from \"taken over\".\n const mine: LockRecord = { pid: process.pid, startedAt: Date.now(), action, birthAt: processBirthSync(process.pid) }\n const release = (): void => {\n const current = readRecord(file)\n if (current !== null && (current.pid !== mine.pid || current.startedAt !== mine.startedAt))\n return\n fs.rmSync(file, { force: true })\n }\n\n const existing = readRecord(file)\n if (existing !== null) {\n if (isLiveHolder(existing))\n return { heldBy: existing }\n // The holder died, or has held it absurdly long: take it over, and say so.\n writeFileAtomic(file, `${JSON.stringify(mine)}\\n`, { mode: 0o600 })\n return { release, replaced: existing }\n }\n\n try {\n // `wx` is the exclusion: creating fails if the file exists, atomically, so two starts cannot\n // both believe they created it.\n fs.writeFileSync(file, `${JSON.stringify(mine)}\\n`, { flag: 'wx', mode: 0o600 })\n }\n catch (error) {\n if ((error as NodeJS.ErrnoException).code === 'EEXIST') {\n // Somebody created it between our read and our write. Their record is the answer — and if it\n // is unreadable the honest response is to say so rather than throw a raw errno.\n const holder = readRecord(file)\n return holder === null\n ? { heldBy: { pid: 0, startedAt: Date.now(), action: 'unreadable' } }\n : { heldBy: holder }\n }\n throw error\n }\n\n let released = false\n return {\n release: () => {\n if (released)\n return\n released = true\n release()\n },\n }\n}\n","export type TemplateVars = Record<string, string | number>\n\n/**\n * Replaces `{name}` placeholders. Unknown placeholders are left untouched so a\n * typo surfaces in the child's args instead of silently becoming an empty string.\n */\nexport function resolveTemplate(value: string, vars: TemplateVars): string {\n return value.replace(/(?<!\\$)\\{([a-z][\\w-]*)\\}/gi, (match, name: string) => {\n const replacement = vars[name]\n return replacement === undefined ? match : String(replacement)\n })\n}\n\nexport function resolveTemplates<T extends string | string[]>(value: T, vars: TemplateVars): T {\n if (Array.isArray(value))\n return value.map(entry => resolveTemplate(entry, vars)) as T\n return resolveTemplate(value as string, vars) as T\n}\n\nexport function resolveRecord(record: Record<string, string>, vars: TemplateVars): Record<string, string> {\n return Object.fromEntries(\n Object.entries(record).map(([key, value]) => [key, resolveTemplate(value, vars)]),\n )\n}\n","import os from 'node:os'\n\n/**\n * How long the LAN address stays good.\n *\n * `os.networkInterfaces()` is not free: it was measured at **34–62 ms per call** on a machine\n * with three interfaces (median 51 ms, 30 calls), because libuv enumerates every interface and\n * every address each time. `lanAddress()` is called from `serverTemplateVars`, which runs once per\n * server inside a state frame — so a 40-entry panel called it 82 times per build and spent ~4.2 s\n * of a 4.3 s window blocked inside it, with the tick publishing once a second. `/healthz` took\n * 3.1–4.2 s and every `/api` route waited behind the same loop.\n *\n * A home server's LAN address changes when DHCP moves it, a cable moves, or a VPN comes up, and a\n * half-minute of staleness costs one stale \"open server\" link that the next frame corrects. So the\n * value is cached, and the cache is short enough that a network change is picked up without a\n * restart.\n */\nconst LAN_ADDRESS_TTL_MS = 30_000\n\nlet cached: { value: string | null, at: number } | null = null\n\n/**\n * This machine's first non-internal IPv4 address, or null when it has none.\n *\n * Cached for `LAN_ADDRESS_TTL_MS`: the call is expensive and its answer is read per server per\n * state frame. The cache is module state, which is acceptable here for the same reason\n * `appVersion()`'s is — the answer is a property of the host, not of a workspace, and nothing in\n * a test changes the interfaces it observes.\n */\nexport function lanAddress(now = Date.now()): string | null {\n if (cached !== null && now - cached.at < LAN_ADDRESS_TTL_MS)\n return cached.value\n\n let value: string | null = null\n for (const entries of Object.values(os.networkInterfaces())) {\n for (const entry of entries ?? []) {\n if (entry.family === 'IPv4' && !entry.internal) {\n value = entry.address\n break\n }\n }\n if (value !== null)\n break\n }\n\n cached = { value, at: now }\n return value\n}\n\n/** Forgets the cached address. A test that simulates a network change calls this first. */\nexport function forgetLanAddress(): void {\n cached = null\n}\n\nexport function bindHost(bind: string): string {\n if (bind === 'local')\n return '127.0.0.1'\n if (bind === 'lan')\n return '0.0.0.0'\n return bind\n}\n\n/** Address a human should open, which is never `0.0.0.0`. */\nexport function displayHost(bind: string): string {\n if (bind === 'local')\n return '127.0.0.1'\n if (bind === 'lan')\n return lanAddress() ?? '127.0.0.1'\n return bind\n}\n\n/** True when the bind value makes the port reachable from outside this machine. */\nexport function isExposed(bind: string): boolean {\n return bindHost(bind) !== '127.0.0.1'\n}\n","import type { TemplateVars } from '#src/helpers/template'\nimport type { ServerConfig } from '#src/shared/contracts'\nimport os from 'node:os'\nimport { bindHost, displayHost, lanAddress } from '#src/helpers/bind'\nimport { dataRoot, projectDir } from '#src/helpers/paths'\nimport { resolveCwd } from '#src/providers/process'\n\n/** The `{placeholder}` values an entry's args, env and hooks expand — the table in `docs/SERVERS.md`. */\nexport function serverTemplateVars(config: ServerConfig): TemplateVars {\n return {\n id: config.id,\n label: config.label ?? config.id,\n port: config.port ?? '',\n host: bindHost(config.bind),\n displayHost: displayHost(config.bind),\n bind: config.bind,\n lanIp: lanAddress() ?? '127.0.0.1',\n cwd: resolveCwd(config.cwd),\n projectDir,\n dataRoot,\n home: os.homedir(),\n }\n}\n","import type { Buffer } from 'node:buffer'\nimport type { ChildProcess } from 'node:child_process'\nimport type { BackupHookConfig, ServerConfig } from '#src/shared/contracts'\nimport { spawn } from 'node:child_process'\nimport process from 'node:process'\nimport { ensureStateDir } from '#src/helpers/paths'\nimport { resolveRecord, resolveTemplates } from '#src/helpers/template'\nimport { resolveCwd } from '#src/providers/process'\nimport { serverTemplateVars } from '#src/providers/server-vars'\n\n/**\n * Runs one backup hook (`dump` before capture, `load` after restore).\n *\n * Same discipline as `bootstrap`: one program plus args, never a shell string, so a path with a space\n * cannot become two arguments and nothing is interpreted. Not the same code, because the failure\n * handling is the opposite — a bootstrap is best-effort and a hook is not. A `dump` that fails must\n * refuse the backup: archiving the live data directory beside a failed dump would produce an archive\n * that looks complete and is not.\n */\n\nexport interface HookResult {\n ok: boolean\n code: number | null\n /** Bounded tail of both streams, for the plan and the error. */\n output: string\n /** Set when the process could not be started or timed out. */\n error?: string\n}\n\n/** Output kept for the error message and the plan; the rest is dropped rather than buffered. */\nconst OUTPUT_TAIL_BYTES = 8 * 1024\n\nfunction tail(previous: string, chunk: string): string {\n const next = previous + chunk\n return next.length <= OUTPUT_TAIL_BYTES ? next : next.slice(next.length - OUTPUT_TAIL_BYTES)\n}\n\n/**\n * Run a hook for one entry.\n *\n * `dumpDir` is passed in rather than templated by the caller so the same absolute path can be handed\n * to `dump` and later to `load`, which is what makes the pair symmetric.\n */\nexport async function runBackupHook(\n hook: BackupHookConfig,\n server: ServerConfig,\n dumpDir: string,\n options: { requireDumpDir?: boolean } = {},\n): Promise<HookResult> {\n const vars = { ...serverTemplateVars(server), dumpDir }\n const cwd = resolveCwd(server.cwd)\n const args = resolveTemplates(hook.args, vars)\n\n // A hook that names `{dumpDir}` must be given a directory that exists, or `mongodump` creates a\n // file at a path whose parent is missing and fails with a much less useful message.\n if (options.requireDumpDir !== false)\n ensureStateDir(dumpDir)\n\n let child: ChildProcess\n try {\n // `shell: false` is the default: the command is a program, never a command line.\n child = spawn(hook.command, args, {\n cwd,\n env: { ...process.env, ...resolveRecord(hook.env, vars) },\n stdio: ['ignore', 'pipe', 'pipe'],\n windowsHide: true,\n })\n }\n catch (error) {\n return { ok: false, code: null, output: '', error: `could not start: ${(error as Error).message}` }\n }\n\n let output = ''\n child.stdout?.on('data', (chunk: Buffer) => {\n output = tail(output, chunk.toString())\n })\n child.stderr?.on('data', (chunk: Buffer) => {\n output = tail(output, chunk.toString())\n })\n\n const outcome = await new Promise<{ code: number | null, error?: string }>((resolve) => {\n const timer = setTimeout(() => {\n try {\n child.kill('SIGKILL')\n }\n catch {\n // already gone\n }\n resolve({ code: null, error: `timed out after ${hook.timeoutMs}ms` })\n }, hook.timeoutMs)\n child.once('exit', (code) => {\n clearTimeout(timer)\n resolve({ code })\n })\n child.once('error', (error) => {\n clearTimeout(timer)\n resolve({ code: null, error: error.message })\n })\n })\n\n return {\n ok: outcome.error === undefined && outcome.code === 0,\n code: outcome.code,\n output,\n ...(outcome.error === undefined ? {} : { error: outcome.error }),\n }\n}\n\n/**\n * The line a person reads when a hook fails.\n *\n * Names the entry, the program and the last thing it said — a bare \"the backup failed\" would send\n * them to the panel's log to find out which of five databases refused.\n */\nexport function hookFailure(action: 'dump' | 'load', server: ServerConfig, result: HookResult): string {\n const detail = result.error ?? (result.code === null ? 'no exit code' : `exit ${result.code}`)\n const said = result.output.trim().split('\\n').filter(line => line.trim().length > 0).slice(-3).join(' / ')\n return `the ${action} hook for \"${server.id}\" failed (${detail})${said.length === 0 ? '' : `: ${said}`}`\n}\n","import type { BackupScope } from './contracts'\n\n/**\n * What a configured automatic scope asks a `create` for.\n *\n * `only` is `--include` and `except` is `--all --exclude`, because a schedule and a person typing\n * flags have to mean the same thing. An absent scope is the full default the schedule took before\n * it could be configured, which is what keeps an existing config exactly as it was.\n */\nexport function scopeSelection(scope: BackupScope | undefined): { include?: string[], exclude?: string[] } {\n if (scope === undefined)\n return {}\n return scope.mode === 'only' ? { include: [...scope.ids] } : { exclude: [...scope.ids] }\n}\n\n/**\n * What a selection asks for, from `include` and `exclude` together.\n *\n * One implementation for `create`, `restore`, the control channel's plan and both UIs: a second\n * copy of \"does this id count as selected\" is how an `--exclude` that works on backup silently does\n * nothing on restore, or how a page ticks a row the panel will not capture.\n *\n * `include` omitted means everything; `exclude` is applied after it, and an id under an excluded\n * entry is excluded too.\n */\nexport function selectionOf(options: { include?: readonly string[], exclude?: readonly string[] }): ((id: string) => boolean) & { isExcluded: (id: string) => boolean } {\n const wanted = options.include === undefined ? null : new Set(options.include)\n const unwanted = new Set(options.exclude ?? [])\n // `global:secrets:password` is under `global:secrets`, and `workspace:x:servers` under\n // `workspace:x`, so an exclusion covers the leaves beneath it as well as the exact id.\n const isExcluded = (id: string): boolean =>\n unwanted.has(id) || [...unwanted].some(entry => id.startsWith(`${entry}:`))\n const selects = ((id: string): boolean => {\n if (isExcluded(id))\n return false\n // Downwards only: naming `a` selects `a:b`, because a coarse id means every leaf under it.\n // It is **not** symmetric — naming `a:b` must not select `a`, or a whole-entry item would\n // replace a file the person asked to touch only one field of.\n return wanted === null || wanted.has(id) || [...wanted].some(entry => id.startsWith(`${entry}:`))\n }) as ((id: string) => boolean) & { isExcluded: (id: string) => boolean }\n selects.isExcluded = isExcluded\n return selects\n}\n\n/**\n * One entry of the capture tree as a **selection** sees it: its id, plus the short ids that name it.\n *\n * The alias is not a second way to spell the id, it is part of the item: `config` is what the person\n * ticks in a UI, `global:settings` is what the archive stores, and both name one file.\n */\nexport interface SelectableItem {\n id: string\n /** Coarse ids that select this item too (`config` for `global:settings`). */\n aliases?: readonly string[]\n}\n\n/**\n * The panel-wide entries, declared once.\n *\n * The restore's own item list and the credential guard both read this, so \"which item is the\n * credential file\" cannot be answered two ways — which it was: the guard tested the exact id while\n * the restore also honoured the alias, so `include: [\"secrets\"]` selected the item and skipped the\n * guard. A second string literal at the guard would be the same defect one rename later.\n */\nexport const GLOBAL_RESTORE_ITEMS = {\n settings: { id: 'global:settings', aliases: ['config'] },\n credentials: { id: 'global:secrets', aliases: ['secrets'] },\n tls: { id: 'global:tls', aliases: ['tls'] },\n} as const satisfies Record<string, SelectableItem>\n\n/**\n * The one rule for \"does this selection choose this item\", aliases included.\n *\n * An exclusion beats an alias (`--exclude global:secrets` must not be undone by the item's own\n * short alias selecting it back in), then any of the item's ids may select it.\n */\nexport function selectedBy(\n selects: ((id: string) => boolean) & { isExcluded: (id: string) => boolean },\n item: SelectableItem,\n): boolean {\n const aliases = item.aliases ?? []\n const excluded = selects.isExcluded(item.id) || aliases.some(alias => selects.isExcluded(alias))\n return !excluded && (selects(item.id) || aliases.some(alias => selects(alias)))\n}\n\n/**\n * Whether a selection reaches anything inside one item: the item itself, an alias, or a leaf of it.\n *\n * A leaf counts because selection is downwards only — naming `global:secrets:password` does not\n * select `global:secrets` — yet the restore still writes that one field of the same file.\n *\n * Both spellings of a leaf are recognised (`global:secrets:password` and its alias\n * `secrets:password`), because an exclusion the person wrote as `--exclude secrets` reaches the\n * leaves of that item through `selectionOf`'s prefix rule. Answering \"the item is untouched\" there\n * while the restore still wrote its leaves was a real bypass: `{\"exclude\":[\"secrets\"]}` — the\n * spelling the docs recommend to leave credentials behind — rewrote the password and token hashes.\n */\nexport function selectionTouches(\n options: { include?: readonly string[], exclude?: readonly string[] },\n item: SelectableItem,\n): boolean {\n const selects = selectionOf(options)\n const prefixes = [item.id, ...(item.aliases ?? [])]\n // A leaf the request names explicitly, and that survives exclusion.\n const namesLeaf = (options.include ?? []).some(id => prefixes.some(prefix => id.startsWith(`${prefix}:`)) && selects(id))\n if (namesLeaf)\n return true\n // Otherwise the whole item is written unless it, or an alias, is excluded.\n return selectedBy(selects, item)\n}\n\n/**\n * Whether a restore selection would write the panel's own credential store.\n *\n * `global:secrets` holds the password hash and the API token hash, so a restore that carries it can\n * replace the credentials of the panel doing the restoring. That is a legitimate move for the owner\n * (a fresh host taking its own archive back) and a panel takeover for anyone holding only a token:\n * measured, a token-only upload restore left the victim's password hash byte-identical to the\n * attacker's, and the owner locked out.\n *\n * The predicate exists so the guard has one definition rather than a string literal at each call\n * site. It answers *whether* the store is touched; who may touch it is the route's decision.\n */\nexport function selectionWritesCredentials(options: { include?: readonly string[], exclude?: readonly string[] }): boolean {\n return selectionTouches(options, GLOBAL_RESTORE_ITEMS.credentials)\n}\n\n/** One entry of the panel's two-level capture tree, with the person's ticks on it. */\nexport interface ScopeChoice {\n id: string\n selected: boolean\n /** A workspace's leaves, a secrets entry's per-key leaves, or none for a whole-entry item. */\n leaves: ReadonlyArray<{ id: string, selected: boolean }>\n}\n\n/** True when the entry contributes anything: one leaf is enough, and a leaf-less entry stands alone. */\nfunction captures(choice: ScopeChoice): boolean {\n return choice.selected && (choice.leaves.length === 0 || choice.leaves.some(leaf => leaf.selected))\n}\n\n/** True when the entry contributes everything it has. */\nfunction capturesWhole(choice: ScopeChoice): boolean {\n return choice.selected && (choice.leaves.length === 0 || choice.leaves.every(leaf => leaf.selected))\n}\n\n/** The ids the ticks capture: a wholly-ticked entry travels as its own id, a partial one by leaf. */\nexport function capturedIds(choices: readonly ScopeChoice[]): string[] {\n return choices.flatMap((choice) => {\n if (capturesWhole(choice))\n return [choice.id]\n if (!captures(choice))\n return []\n return choice.leaves.filter(leaf => leaf.selected).map(leaf => leaf.id)\n })\n}\n\n/**\n * The ids the ticks leave out — the complement, for writing the scope down as an exclusion.\n *\n * An entry no leaf of which is captured is named whole; a partly ticked one has to be spelled leaf\n * by leaf, because its other leaves are still wanted.\n */\nexport function excludedIds(choices: readonly ScopeChoice[]): string[] {\n return choices.flatMap((choice) => {\n if (!captures(choice))\n return [choice.id]\n if (capturesWhole(choice))\n return []\n return choice.leaves.filter(leaf => !leaf.selected).map(leaf => leaf.id)\n })\n}\n\n/** What a picked tree should be stored as. */\nexport type ScopeOutcome\n = | { kind: 'everything' }\n | { kind: 'nothing' }\n | { kind: 'scope', scope: BackupScope }\n\n/**\n * The scope a ticked tree describes, in the mode the person chose.\n *\n * A tree with nothing left out is stored as **no scope at all**, whatever the mode: the two capture\n * the same thing today, and only the empty setting also covers a workspace declared tomorrow.\n * Storing the full id list instead would silently narrow every future schedule.\n *\n * `nothing` is refused by the caller rather than sent: an empty `include` reads as \"everything\" to\n * the API (it is what omitting the key means) and as \"nothing\" to a person, which is the one\n * reading a backup must never get wrong.\n */\nexport function scopeOf(choices: readonly ScopeChoice[], mode: BackupScope['mode']): ScopeOutcome {\n // Nothing captured is refused whatever the mode: an `except` list of every id is as empty an\n // archive as an `only` list of none, and the service would refuse the pass for either.\n if (choices.length === 0 || capturedIds(choices).length === 0)\n return { kind: 'nothing' }\n if (excludedIds(choices).length === 0)\n return { kind: 'everything' }\n return { kind: 'scope', scope: { mode, ids: mode === 'only' ? capturedIds(choices) : excludedIds(choices) } }\n}\n\n/** One entry of the panel's two-level capture tree, as the id check needs it. */\nexport interface ScopeEntry {\n id: string\n items?: ReadonlyArray<{ id: string }>\n}\n\n/**\n * Which of `ids` name nothing the panel can capture.\n *\n * The rule `backup create --include` already applies: an id names something when it is an entry or\n * leaf id, or a prefix of one (`workspace:default` covers its leaves). A typo matters more on a\n * schedule than anywhere else — nobody is watching — and it cuts both ways: an unknown `only` id\n * silently narrows the archive, an unknown `except` id silently widens it back over what the\n * person meant to leave out.\n */\nexport function unknownBackupIds(ids: readonly string[], entries: readonly ScopeEntry[]): string[] {\n const available = entries.flatMap(entry => [entry.id, ...(entry.items ?? []).map(item => item.id)])\n const known = (id: string): boolean => available.some(candidate => candidate === id || candidate.startsWith(`${id}:`))\n return ids.filter(id => !known(id))\n}\n\n/**\n * Two scopes are the same when they name the same ids the same way.\n *\n * Both UIs diff a freshly built object against the config one, so a reference check reported the\n * scope changed on a save nobody made, and the order the panel wrote the ids in is not part of\n * what it means.\n */\nexport function sameScope(a: BackupScope | null | undefined, b: BackupScope | null | undefined): boolean {\n if (a === null || a === undefined || b === null || b === undefined)\n return (a ?? null) === (b ?? null)\n return a.mode === b.mode && [...a.ids].sort().join('\\n') === [...b.ids].sort().join('\\n')\n}\n","/**\n * Names that only ever hold build output or installed dependencies — the things\n * a `.gitignore` almost always lists.\n *\n * A backup walks a declared data directory and copies whatever it finds; on a\n * project directory that is mostly `node_modules` and framework caches, which\n * bloats the archive with content nobody needs to restore. An entry with\n * `backupIgnoreGenerated` (on by default) skips these.\n *\n * Matching is by exact name, on any segment, at any depth: `dist/` and\n * `app/node_modules/` are generated, `distributed/` and `my-node_modules/` are\n * not.\n *\n * `.git` is deliberately absent however much a `.gitignore` would not list it:\n * a package manager can reinstall `node_modules`, but nobody can restore a\n * commit that was never pushed.\n */\n\n/** Whole directories that are regenerated, never authored. */\nexport const GENERATED_DIRS: readonly string[] = [\n // Installed dependencies and package-manager stores.\n 'node_modules',\n 'bower_components',\n 'jspm_packages',\n '.yarn',\n '.pnpm',\n '.pnpm-store',\n '.npm',\n // Framework and bundler output.\n '.next',\n '.nuxt',\n '.svelte-kit',\n '.astro',\n '.output',\n '.vercel',\n '.netlify',\n '.angular',\n 'dist',\n 'build',\n 'out',\n // Caches.\n '.cache',\n '.parcel-cache',\n '.turbo',\n '.vite',\n '.rollup.cache',\n '.swc',\n // Test and coverage output.\n 'coverage',\n '.nyc_output',\n '__pycache__',\n '.pytest_cache',\n '.mypy_cache',\n '.ruff_cache',\n '.tox',\n // Other language toolchains.\n 'target',\n '.gradle',\n '.dart_tool',\n]\n\n/** One-off files worth skipping, by exact name. */\nexport const GENERATED_FILES: readonly string[] = [\n '.DS_Store',\n 'Thumbs.db',\n 'desktop.ini',\n '.eslintcache',\n '.stylelintcache',\n 'npm-debug.log',\n 'yarn-error.log',\n 'pnpm-debug.log',\n]\n\nconst DIR_NAME_SET = new Set(GENERATED_DIRS)\nconst FILE_NAME_SET = new Set(GENERATED_FILES)\n\n/**\n * True when a path *relative to the declared root* looks generated. Accepts\n * either separator, so a `path.relative` result can be passed straight in.\n */\nexport function isGeneratedPath(relative: string): boolean {\n const segments = relative.split(/[\\\\/]+/).filter(segment => segment.length > 0 && segment !== '.')\n if (segments.length === 0)\n return false\n if (FILE_NAME_SET.has(segments[segments.length - 1]!))\n return true\n return segments.some(segment => DIR_NAME_SET.has(segment))\n}\n","import type { ResolvedGlobalConfig } from '#src/config/schema'\nimport type { SecretScope } from '#src/config/secret-parts'\nimport type { TemplateVars } from '#src/helpers/template'\nimport type { BackupEntry, BackupFile, BackupsConfig, BackupSelection, BackupsView, RestoreItem, RestorePlan, RestoreSkip, ServerConfig } from '#src/shared/contracts'\nimport { createHash } from 'node:crypto'\nimport fs from 'node:fs'\nimport os from 'node:os'\nimport path from 'node:path'\nimport process from 'node:process'\nimport { DetailedError } from '@namesmt/utils'\nimport { type } from 'arktype'\nimport { applyConfigMigrations, CONFIG_SCHEMA, planConfigMigrations } from '#src/config/migrations'\nimport { parseGlobalSettings, parseServersFile, parseWorkspaceSettings, stampConfig } from '#src/config/parse'\nimport { KNOWN_SECRET_KEYS, mergeSecrets, parseSecrets, pickSecrets, presentSecretKeys, secretParts, withoutInitialPassword } from '#src/config/secret-parts'\nimport { workspacesFileSchema } from '#src/config/workspaces'\nimport { writeFileAtomic } from '#src/helpers/atomic'\nimport { readStateFile } from '#src/helpers/config-text'\nimport { copyTree } from '#src/helpers/copy-tree'\nimport { expandEnv } from '#src/helpers/env-file'\nimport { logger } from '#src/helpers/logger'\nimport { ensureStateDir, projectDir, resolveUserPath } from '#src/helpers/paths'\nimport { acquireRestoreLock, restoreLockHolder } from '#src/helpers/restore-lock'\nimport { resolveTemplate } from '#src/helpers/template'\nimport { appVersion } from '#src/helpers/version'\nimport { createZip, extractZip, isInvalidPassword, isZipArchive, listZip } from '#src/providers/archive'\nimport { hookFailure, runBackupHook } from '#src/providers/backup-hook'\nimport { isProcessAlive } from '#src/providers/port'\nimport { serverTemplateVars } from '#src/providers/server-vars'\nimport { GLOBAL_RESTORE_ITEMS, scopeSelection, selectedBy, selectionOf } from '#src/shared/backup-scope'\nimport { serverSchema, workspaceIdSchema } from '#src/shared/contracts'\nimport { errorMessage } from '#src/shared/error-message'\nimport { isGeneratedPath } from '#src/shared/generated'\nimport { isRecord } from '#src/shared/shape'\n\nconst MANIFEST = 'manifest.json'\nconst serverIdSchema = serverSchema.get('id')\n/**\n * The workspace registry inside an archive. Under `global/` because it is panel-wide, and\n * named as the live file is, so the two are recognisably the same document.\n */\nconst REGISTRY = 'workspaces.json'\n/**\n * Every file name the panel writes a secret into, in any directory.\n *\n * A secrets document must reach an archive only through `copySecrets`, which narrows the selection\n * and drops the plaintext first-run password. The **data** phase copies whole trees a person declared\n * — `{dataRoot}` is a documented template, and the docs recommend keeping archives off the box, so a\n * declared state root captured `.control-secrets.json` verbatim, password and all. That is the same\n * leak by a different door, so the raw copy refuses these names wherever they appear.\n */\nconst SECRET_FILE_NAMES = ['.control-secrets.json', '.secrets.json'] as const\n\n/**\n * The live name, or the scratch copy `writeFileAtomic` gives a write that has not been renamed yet.\n *\n * That helper removes its temp file only in its `catch`, so a crash between the write and the rename\n * leaves a **complete** secrets document on disk — plaintext first-run password included — under a\n * name no exact match catches. Matching the atomic-write shape is what makes the guarantee the docs\n * make actually hold.\n */\nconst SECRET_DOCUMENT_NAMES = new RegExp(\n // `i`, because a case-insensitive filesystem can give the hex suffix back in either case.\n `^(?:${SECRET_FILE_NAMES.map(name => name.replaceAll('.', '\\\\.')).join('|')})(?:\\\\.\\\\d+\\\\.[0-9a-f]{8}\\\\.tmp)?$`,\n 'i',\n)\n\nfunction isSecretDocument(name: string): boolean {\n return SECRET_DOCUMENT_NAMES.test(name)\n}\nconst ALLOWED_ROOTS = new Set(['global', 'workspaces', 'data', 'dumps'])\n/** Every archive this service writes is a zip, encrypted or not. */\nconst SUFFIX = '.zip'\n/** Where a restore parks a dump until the entry's next start can load it. */\nconst PENDING_LOAD = 'pending-load'\n/**\n * An archive the schedule wrote. The prefix is the only durable marker: a filename is the one\n * thing that survives a restart, and it is what lets the two retention counts stay independent.\n */\nconst AUTO_PREFIX = 'auto'\nconst MANUAL_PREFIX = 'backup'\n/** The names `create()` writes; retention counts and prunes only these, never a zip someone else put here. */\nconst ARCHIVE_NAME = new RegExp(`^(${AUTO_PREFIX}|${MANUAL_PREFIX})-\\\\d{4}(?:-\\\\d{2}){5}-\\\\d{1,3}\\\\.zip$`)\nconst ARCHIVE_STAMP = /-(\\d{4})-(\\d{2})-(\\d{2})-(\\d{2})-(\\d{2})-(\\d{2})-(\\d{1,3})\\.zip$/\n\n/**\n * When `create()` wrote an archive, read from its name (UTC, to the millisecond), or null for a name\n * it did not write. The name survives a copy, a sync tool or a restore from another disk; the mtime\n * does not, and ordering by it made retention prune the wrong archive.\n */\nfunction archiveStamp(name: string): number | null {\n if (!ARCHIVE_NAME.test(name))\n return null\n const parts = ARCHIVE_STAMP.exec(name)?.slice(1).map(Number)\n if (parts === undefined || parts.length !== 7)\n return null\n const [year, month, day, hour, minute, second, ms] = parts as [number, number, number, number, number, number, number]\n const at = Date.UTC(year, month - 1, day, hour, minute, second, ms)\n return Number.isFinite(at) ? at : null\n}\n/** A workspace leaf that carries state the panel re-reads after a restore. */\nconst RELOADABLE = /^global:settings$|^workspace:[^:]+:(?:settings|servers)$/\n\n/**\n * A staging tree's name, carrying the pid that owns it.\n *\n * The timestamp keeps two runs in one process apart; the pid is what lets a later run tell a dead\n * one's debris from a live one's capture (see `sweepStaging`). `kind` names which tree it is, so a\n * capture and a restore left by the same pid are two directories rather than one.\n */\nfunction stagingDirName(kind: 'staging' | 'restore'): string {\n return `.${kind}-${process.pid}-${Date.now()}`\n}\n\n/**\n * The pid a staging directory belongs to, or null for any other name.\n *\n * A name with no pid in it is deliberately **not** guessed at: `.staging-1793809562025` is what\n * this release wrote before the owner was recorded, and an age is not proof its writer is gone.\n * Leaving it is the honest answer, and it is why a name that carries no owner is left alone.\n */\nfunction stagingOwner(name: string): number | null {\n const match = /^\\.[a-z]+-(\\d+)-\\d+$/.exec(name)\n if (match === null)\n return null\n const pid = Number.parseInt(match[1]!, 10)\n return Number.isInteger(pid) && pid > 0 ? pid : null\n}\n\n/**\n * The English wording and catalog key of each known secret. A key missing here is still\n * selectable and restorable — it just reads as its own name, which is what keeps a\n * secret added by a later release from being silently uncapturable.\n */\nconst SECRET_LABELS: Record<string, { en: string, key: string }> = {\n password: { en: 'Password', key: 'settings.backup.secretPassword' },\n apiToken: { en: 'API token', key: 'settings.backup.secretApiToken' },\n telegram: { en: 'Telegram bot token', key: 'settings.backup.secretTelegram' },\n ddns: { en: 'DDNS credentials', key: 'settings.backup.secretDdns' },\n}\n\n/**\n * Structural allowlist for archive entries. A regex alone is not enough: `..`\n * is made of allowed characters, so segments are checked explicitly and any\n * entry that could resolve outside the staging directory aborts the restore.\n */\n/**\n * The servers an archive carries for one workspace, from its staged config.\n *\n * A restore reads this rather than `getSources()` because the live config is the *old* one at this\n * point: the files have just been overwritten, and the hooks to run belong to the machine being\n * cloned. A config that will not parse yields no servers, so the caller reports a missing hook\n * rather than throwing.\n */\nfunction readArchivedServers(staging: string, workspaceId: string, defaults: Record<string, unknown> = {}): ServerConfig[] {\n const text = readText(path.join(staging, 'workspaces', workspaceId, 'servers.config.json'))\n if (text === null)\n return []\n try {\n // `parseServersFile`, not `JSON.parse`: a raw config carries no `bind`, `restart` or `health`,\n // and the template vars read `bind` — parsing by hand threw for every entry, which is why the\n // load hook silently never ran.\n return parseServersFile(JSON.parse(text), defaults).servers\n }\n catch {\n return []\n }\n}\n\n/**\n * Whether one archive path segment is a name a filesystem will accept as-is.\n *\n * A separator moves the path, and `\\` is a separator on Windows while an archive crosses platforms;\n * `:` re-roots or opens a stream there. A control character is never a real filename and is how an\n * extractor is confused. Everything else — spaces, non-ASCII, `&`, `$`, `#`, `@` — is what a data\n * directory actually contains.\n */\nfunction isPortableSegment(segment: string): boolean {\n for (const character of segment) {\n const code = character.codePointAt(0) ?? 0\n if (character === '\\\\' || character === ':' || code < 0x20 || code === 0x7F)\n return false\n }\n return true\n}\n\nexport function isSafeArchiveEntry(entry: string): boolean {\n if (entry.startsWith('/') || entry.includes('\\0'))\n return false\n\n const cleaned = entry.replace(/^\\.\\//, '').replace(/\\/+$/, '')\n if (cleaned.length === 0)\n return true\n if (cleaned === MANIFEST)\n return true\n\n const segments = cleaned.split('/')\n if (segments.some(segment => segment.length === 0 || segment === '.' || segment === '..'))\n return false\n if (!ALLOWED_ROOTS.has(segments[0]!))\n return false\n // Not a character allowlist: a backup captures whatever the declared tree holds, and\n // `My Photos/` or `ünïcode/日本語.txt` are ordinary names in it. A `\\w` rule refused the archive\n // this panel had just written, so a restore onto a blank host — the one restore nobody can check\n // by eye — died on \"unexpected entries\" with nothing wrong with the archive. What must be refused\n // is a segment that could *move* the path: a separator (`\\` is one on Windows, and an archive\n // crosses platforms), a control character, or a drive/stream marker.\n return segments.every(isPortableSegment)\n}\n\n/**\n * The gates an archive passes before anything plans a restore from it: it is a zip at all, and\n * every entry in it is inside the layout this service writes.\n *\n * One function because there are two doors — an uploaded archive (`POST /api/backups/restore`,\n * multipart) and `backup restore --from <path>` — and the entry allowlist is the boundary that\n * stops a crafted archive writing outside the layout. A door that forgets one of these gates is\n * the defect this exists to prevent.\n *\n * The archive's **location** is not part of this. A restore reads the file it is given and writes\n * only to a fresh staging directory plus the paths the live config declares, so where the readable\n * bytes came from cannot widen what a restore may write — an arbitrary path adds a read the caller\n * already had, not a write target.\n */\nexport type ArchiveAdmission\n = | { ok: true, entries: Awaited<ReturnType<typeof listZip>> }\n | { ok: false, error: string }\n\nexport async function admitArchive(archivePath: string): Promise<ArchiveAdmission> {\n if (!isZipArchive(archivePath))\n return { ok: false, error: 'the archive is not a home-hosted backup (a zip file was expected)' }\n\n // The central directory is readable without a password, so a backup can be listed and its\n // selection offered before the password is ever entered.\n let entries: Awaited<ReturnType<typeof listZip>>\n try {\n entries = await listZip(archivePath)\n }\n catch (error) {\n return { ok: false, error: `the archive could not be read: ${errorMessage(error)}` }\n }\n\n if (entries.length === 0)\n return { ok: false, error: 'the archive is empty' }\n if (entries.length > 100_000)\n return { ok: false, error: 'the archive has too many entries' }\n\n const invalid = entries.filter(entry => !isSafeArchiveEntry(entry.name))\n if (invalid.length > 0)\n return { ok: false, error: `the archive contains unexpected entries (e.g. ${invalid.slice(0, 3).map(entry => entry.name).join(', ')})` }\n\n return { ok: true, entries }\n}\n\n/** True when `child` is `parent` itself or lives underneath it. */\nexport function isInside(parent: string, child: string): boolean {\n if (parent === child)\n return true\n // `path.relative` is case-insensitive on Windows, and empty for a case-only\n // difference — which is still the same directory.\n const relative = path.relative(parent, child)\n return !path.isAbsolute(relative) && (relative.length === 0 || !relative.startsWith('..'))\n}\n\n/** Resolves symlinks on the deepest existing ancestor, keeping the rest verbatim. */\nfunction resolveExisting(target: string): string {\n let prefix = target\n const rest: string[] = []\n for (;;) {\n try {\n return path.join(fs.realpathSync(prefix), ...rest)\n }\n catch {\n const parent = path.dirname(prefix)\n if (parent === prefix)\n return target\n rest.unshift(path.basename(prefix))\n prefix = parent\n }\n }\n}\n\n/**\n * `isInside` after resolving symlinks, so a link inside a declared path cannot stand\n * for somewhere else. `cpSync` follows links already present in the tree it writes\n * into* — a link to an uploads or cache directory is routine — which would let an\n * archive write outside the path the config declared, and on capture let a file from\n * outside it into the archive. Both sides check with this.\n */\nexport function isInsideResolved(parent: string, child: string): boolean {\n // Both sides go through `resolveExisting`, so a symlinked ancestor of either — `/var`\n // on macOS, a symlinked home — cancels out instead of making the comparison\n // asymmetric and rejecting a legitimate target.\n return isInside(resolveExisting(path.resolve(parent)), resolveExisting(path.resolve(child)))\n}\n\n/** One declared data path, with the verdict the UI shows. */\nexport interface BackupPath {\n path: string\n origin: string\n included: boolean\n note: string | null\n /**\n * The verdict as a catalog key, so a translated UI words it itself.\n *\n * The panel is the only side that knows *why* a path is excluded; the UI is the only side that\n * knows what language to say it in. `note` stays for an older UI and for `noc-console`.\n */\n noteKey?: string\n noteParams?: Record<string, string>\n ignoreGenerated: boolean\n}\n\n/** The `{…}` placeholders a *global* declared path may use. */\nexport interface BackupVars {\n projectDir: string\n dataRoot: string\n home: string\n}\n\ninterface DeclaredPath {\n path: string\n origin: string\n depth: number\n order: number\n ignoreGenerated: boolean\n}\n\n/**\n * Every path a backup should capture: the global list, then each server's\n * `backupPaths` and the values of its `dataEnvs`. A path already covered by a\n * declared parent is reported but not captured, so an entry only has to name\n * the shallowest directory it cares about.\n *\n * `vars` only feeds the global list; a server's own placeholders come from its\n * resolved config, exactly as the supervisor expands them.\n */\nexport function resolveBackupPaths(servers: ServerConfig[], includePaths: string[] = [], vars?: Partial<BackupVars>): BackupPath[] {\n const declared: DeclaredPath[] = []\n const globalVars: TemplateVars = {\n projectDir: vars?.projectDir ?? projectDir,\n // A server carries the panel's real `dataRoot`; the fallback keeps this\n // function usable on its own when nothing declared a server path.\n dataRoot: vars?.dataRoot ?? (servers[0] === undefined ? projectDir : String(serverTemplateVars(servers[0]).dataRoot ?? projectDir)),\n home: vars?.home ?? os.homedir(),\n }\n\n const add = (value: string, origin: string, templateVars: TemplateVars, ignoreGenerated: boolean): void => {\n if (value.trim().length === 0)\n return\n // Normalized, so a trailing slash or a doubled one cannot defeat the\n // parent/child comparison below.\n const resolved = path.normalize(resolveUserPath(expandEnv(resolveTemplate(value, templateVars), process.env)))\n declared.push({\n path: resolved,\n origin,\n depth: path.normalize(resolved).split(path.sep).filter(Boolean).length,\n order: declared.length,\n ignoreGenerated,\n })\n }\n\n // A global extra path is named by hand, so it is captured as it stands.\n for (const value of includePaths) add(value, 'global', globalVars, false)\n\n for (const config of servers) {\n const templateVars = serverTemplateVars(config)\n const ignoreGenerated = config.backupIgnoreGenerated !== false\n for (const [name, value] of Object.entries(config.dataEnvs)) add(value, `${config.id}:${name}`, templateVars, ignoreGenerated)\n for (const value of config.backupPaths) add(value, `${config.id}:backupPaths`, templateVars, ignoreGenerated)\n }\n\n // Shallowest first, so a parent always absorbs its descendants whatever order\n // the config declared them in; ties keep declaration order.\n const sorted = [...declared].sort((a, b) => a.depth - b.depth || a.order - b.order)\n\n return sorted.map((entry, index) => {\n const parent = sorted.slice(0, index).find(candidate => isInside(candidate.path, entry.path))\n if (parent === undefined)\n return { path: entry.path, origin: entry.origin, included: true, note: null, ignoreGenerated: entry.ignoreGenerated }\n const note = parent.path === entry.path\n ? `already declared by ${parent.origin}`\n : `covered by ${parent.path}`\n const noteKey = parent.path === entry.path\n ? 'settings.backup.noteAlreadyDeclared'\n : 'settings.backup.noteCovered'\n const noteParams: Record<string, string> = parent.path === entry.path\n ? { origin: parent.origin }\n : { path: parent.path }\n return { path: entry.path, origin: entry.origin, included: false, note, noteKey, noteParams, ignoreGenerated: entry.ignoreGenerated }\n })\n}\n\n/** One workspace's state, as the backup and restore sides both read it. */\nexport interface BackupWorkspaceSource {\n id: string\n label: string\n settingsPath: string\n serversPath: string\n secretsPath: string\n servers: ServerConfig[]\n}\n\n/** One workspace the registry names, whether or not this host has it. */\ninterface ArchivedWorkspace {\n id: string\n label: string\n}\n\nexport interface BackupSources {\n globalSettingsPath: string\n globalSecretsPath: string\n tlsDir: string\n /**\n * The workspace registry: ids and labels in selector order.\n *\n * Carried so a restore onto a blank host can *create* the workspaces an archive names,\n * with their labels. It is never written back as a file — a restore must not drop a\n * workspace this host added since, so only the missing ones are created.\n */\n registryPath: string\n /** Extra paths in every backup, in addition to each server's own. */\n includePaths: string[]\n workspaces: BackupWorkspaceSource[]\n /**\n * The servers that are running right now, so a restore can say whose data it just replaced.\n *\n * A data path is copied over while its owner keeps running: the process holds open handles to\n * files that no longer exist under it, and whatever it wrote since the archive was taken is\n * gone. `origin` on a declared path is `<serverId>:<ENV>`, which is what names the owner.\n * Optional so a test or an embedded caller can leave it out.\n */\n runningServers?: () => Array<{ workspaceId: string, serverId: string }>\n}\n\n/** A workspace as the source builder needs it: identity, its file locations, its loaded servers. */\nexport interface BackupWorkspaceInput {\n id: string\n label: string\n settingsPath: string\n serversPath: string\n secretsPath: string\n servers: ServerConfig[]\n}\n\n/**\n * What a backup captures, from a workspace list and the panel-wide paths.\n *\n * The **one** implementation, called by the running panel and by the CLI when no panel is up. A\n * second copy is how an offline backup would quietly capture something different from an online one\n * — and the archive is the thing people restore from, so a silent difference is the worst kind.\n *\n * `runningServers` stays a callback rather than a list: the panel answers it from live supervisor\n * views, and an offline caller answers it from the nanny state on disk. It is optional because a\n * caller that cannot know leaves it out; the warning it feeds is then simply absent.\n */\nexport function buildBackupSources(input: {\n globalSettingsPath: string\n globalSecretsPath: string\n tlsDir: string\n registryPath: string\n includePaths: string[]\n workspaces: BackupWorkspaceInput[]\n runningServers?: () => Array<{ workspaceId: string, serverId: string }>\n}): BackupSources {\n return {\n globalSettingsPath: input.globalSettingsPath,\n globalSecretsPath: input.globalSecretsPath,\n tlsDir: input.tlsDir,\n registryPath: input.registryPath,\n includePaths: [...input.includePaths],\n ...(input.runningServers === undefined ? {} : { runningServers: input.runningServers }),\n // Paths are **inputs**, not re-derived here: the panel answers with the paths its supervisor\n // actually reads, and a helper that assumes the default locations could archive a different file\n // than the one that is running. Passing them through is what makes this a mapper rather than a\n // second source of truth.\n workspaces: input.workspaces.map(workspace => ({\n id: workspace.id,\n label: workspace.label,\n settingsPath: workspace.settingsPath,\n serversPath: workspace.serversPath,\n secretsPath: workspace.secretsPath,\n servers: workspace.servers,\n })),\n }\n}\n\nexport interface BackupManifest {\n version: 1\n createdAt: number\n hostname: string\n /**\n * The release that wrote the archive, and the config schema it understood.\n *\n * Both are optional so an archive written before this field existed still reads.\n * They are what lets a restore say which panel an archive came from instead of\n * inferring it from the `meta` stamp inside the configs it happens to carry.\n */\n writtenBy?: string\n schema?: number\n /** `origin` and `workspace` are what let a restore land under *this* machine's paths. */\n data: Array<{ slug: string, path: string, origin?: string, workspace?: string }>\n /** Entries whose `dump` hook ran, and whose dump is under `dumps/<workspace>/<server>/`. */\n dumps?: Array<{ workspaceId: string, serverId: string }>\n}\n\nexport interface RestoreOptions {\n confirm: boolean\n /** Required for, and ignored by, archives that are not password-protected. */\n password?: string\n /** Item ids to restore; omitted means every restorable item. */\n include?: string[]\n /**\n * Item ids to leave out, applied after `include`.\n *\n * The common case is one entry, not many: `--all --exclude global:secrets` backs everything up\n * except the password and token hashes. Naming the one thing to drop beats naming everything else,\n * and it is the safe default to recommend — an archive carrying them hands whoever holds it the\n * old machine's credentials.\n */\n exclude?: string[]\n}\n\nexport type { RestorePlan }\n\n/** One place a restore may write a data path to, and what declared it. */\ninterface DataTarget {\n workspace: string\n path: string\n origin: string\n}\n\n/**\n * Pairs each archived data path with the declaration that will receive it.\n *\n * A **factory**, not a plain function: pairing consumes both lists — one target is claimed by one\n * archive entry — so the two `used` sets are the state a naive call would lose. A pair of same-origin\n * declarations is the case that needs it: a `global` include path and a second `backupPaths` value\n * share one origin, so matching by origin alone would write both onto the first candidate. Pairing by\n * order instead, because the archive wrote them in the same resolve order.\n *\n * Never across a workspace boundary: an archive entry that names a workspace is only matched against\n * that workspace's declarations. The un-scoped fallbacks exist to survive a re-labelled or re-ordered\n * config, and letting them cross workspaces wrote one workspace's data over a path another one had\n * declared. A path only one workspace declares has no candidate in the other, so the entry is\n * reported rather than guessed at.\n */\nfunction dataTargetMatcher(archiveTargets: DataTarget[], instanceTargets: DataTarget[]): (\n origin: string | undefined,\n workspace: string | undefined,\n archivedPath: string,\n) => DataTarget | undefined {\n const usedArchive = new Set<DataTarget>()\n const usedInstance = new Set<DataTarget>()\n\n const take = (list: DataTarget[], used: Set<DataTarget>, test: (target: DataTarget) => boolean): DataTarget | undefined => {\n const found = list.find(target => !used.has(target) && test(target))\n if (found === undefined)\n return undefined\n used.add(found)\n return found\n }\n\n return (origin, workspace, archivedPath) => {\n const inScope = (target: DataTarget): boolean => workspace === undefined || target.workspace === workspace\n const archive = archiveTargets.filter(inScope)\n const instance = instanceTargets.filter(inScope)\n if (origin !== undefined) {\n return take(archive, usedArchive, target => target.origin === origin)\n ?? take(instance, usedInstance, target => target.origin === origin)\n ?? take(archive, usedArchive, target => target.path === archivedPath)\n ?? take(instance, usedInstance, target => target.path === archivedPath)\n }\n return take(archive, usedArchive, target => target.path === archivedPath)\n ?? take(instance, usedInstance, target => target.path === archivedPath)\n }\n}\n\n/**\n * An archived config, lifted to the schema this release reads.\n *\n * An archive is a snapshot, so the release that wrote it is often **older** than the one restoring\n * it — the backup someone takes before an upgrade is the one they reach for afterwards. Its files\n * carry the schema they were written with, and the parsers refuse an older stamp by design, so a\n * plain readability gate discarded every config an older archive carried: measured on a real\n * 0.7.21 archive applied to a blank 0.10.0 home, it reported \"restored 4 items\" and every one of\n * them was a secrets leaf, while both workspaces and the global settings were dropped as \"not\n * valid\" — a half-restored setup that reads as a success.\n *\n * So run the same chain `migrate` runs, on the contents rather than on a file: an archive that\n * needs lifting is lifted, and one this release cannot lift is still refused. A newer archive is\n * never rewritten here — that direction is refused earlier, from the manifest's own schema.\n *\n * **Lifting needs an explicit older stamp.** A file carrying no `meta.schema` is not evidence of an\n * older release — it is a seed (written in the current shape) or a damaged file, and lifting an\n * unparseable one let `{\"not\": \"a servers file\"}` be stamped as a valid empty `servers.config.json`,\n * which would restore a workspace with every entry deleted. Only a numeric stamp this release can\n * lift qualifies; anything else is left to its own parser, which refuses it.\n *\n * `null` means \"this release cannot read it\", which stays distinguishable from \"it was fine\".\n */\nfunction liftArchived(raw: unknown): Record<string, unknown> | null {\n if (!isRecord(raw))\n return null\n const meta = isRecord(raw.meta) ? raw.meta as { schema?: unknown } : {}\n // No stamp, or one this release does not lift: hand it back untouched for the caller's parser.\n if (typeof meta.schema !== 'number')\n return raw\n const plan = planConfigMigrations(meta.schema)\n if (plan.tooNew || plan.reached !== plan.to)\n return null\n if (plan.steps.length === 0)\n return raw\n const lifted = applyConfigMigrations(raw, meta.schema).config\n // Stamped, so the file records the release that actually wrote this shape: leaving the archive's\n // `writtenBy` beside a schema it never wrote would be a false record on disk.\n return isRecord(lifted) ? stampConfig(lifted as { $schema?: string, meta?: unknown }) : null\n}\n\n/**\n * A restored settings file is accepted when this release can read it — through\n * the same tolerant parser the stores use, so an archive from a newer release\n * keeps only the keys this one understands instead of being refused outright.\n *\n * An older one is lifted first (`liftArchived`), and the **lifted** value is returned so the\n * caller writes a config this release can load rather than the stamp it could not.\n */\nfunction readableGlobalSettings(text: string | null): Record<string, unknown> | null {\n if (text === null)\n return null\n try {\n const lifted = liftArchived(JSON.parse(text))\n return lifted !== null && parseGlobalSettings(lifted).config !== null ? lifted : null\n }\n catch {\n return null\n }\n}\n\n/**\n * The workspaces an archive's registry names.\n *\n * Tolerant on purpose: an archive written before the registry was captured has no such\n * file, and a damaged one must not fail a restore whose leaves are perfectly readable.\n * The registry only contributes labels, so anything unreadable is simply dropped.\n */\nfunction readArchivedRegistry(file: string): ArchivedWorkspace[] {\n const text = readText(file)\n if (text === null)\n return []\n try {\n const parsed = workspacesFileSchema(JSON.parse(text))\n if (parsed instanceof type.errors)\n return []\n return parsed.workspaces\n }\n catch {\n return []\n }\n}\n\n/**\n * Where a workspace created by a restore keeps its three leaves.\n *\n * Derived from the service's own `dataRoot` (the `.hh` directory the panel passes) rather\n * than the module-level path helpers, so a restore writes under the state root of the panel\n * running it — not under whatever `HHOSTED_HOME` resolves to at import time.\n */\nfunction workspacePathsFor(dataRoot: string, id: string): Pick<BackupWorkspaceSource, 'settingsPath' | 'serversPath' | 'secretsPath'> {\n const dir = path.join(dataRoot, id)\n return {\n settingsPath: path.join(dir, 'settings.json'),\n serversPath: path.join(dir, 'servers.config.json'),\n secretsPath: path.join(dir, '.secrets.json'),\n }\n}\n\n/**\n * The manifest is written by us, but an uploaded archive's copy is attacker\n * controlled: never join an unvalidated slug into a path.\n */\nfunction safeSlug(slug: unknown): string | null {\n if (typeof slug !== 'string' || slug.length === 0 || slug.length > 80)\n return null\n if (!/^[\\w.-]+$/.test(slug) || slug === '.' || slug === '..')\n return null\n return slug\n}\n\n/** A flag is valid for one exact file revision, not for the name alone. */\nfunction cacheKey(file: { sizeBytes: number, createdAt: number }): string {\n return `${file.sizeBytes}:${file.createdAt}`\n}\n\n/** True when the tree at `root` contains at least one file (stops at the first). */\nfunction holdsAnyFile(root: string): boolean {\n let stats: fs.Stats | undefined\n try {\n stats = fs.lstatSync(root)\n }\n catch {\n return false\n }\n if (!stats.isDirectory())\n return stats.isFile()\n let names: string[]\n try {\n names = fs.readdirSync(root)\n }\n catch {\n return false\n }\n return names.some(name => holdsAnyFile(path.join(root, name)))\n}\n\n/**\n * Stable, filesystem-safe name for a data path inside the archive.\n *\n * The readable part alone collided — `/srv/app-data`, `/srv/app/data` and `/srv/app data` all read\n * `srv-app-data`, and every path after the first was silently left out — so it carries a short hash\n * of the resolved path. A restore reads the slug from the manifest, so archives written with the\n * hashless form still restore.\n */\nexport function slugifyPath(target: string): string {\n const hash = createHash('sha256').update(path.resolve(target)).digest('hex').slice(0, 8)\n return `${legacySlug(target).slice(-71)}-${hash}`\n}\n\n/** The hashless slug archives were written with before; only a manifest without a slug falls back to it. */\nfunction legacySlug(target: string): string {\n const cleaned = target.replace(/[^A-Z0-9]+/gi, '-').replace(/^-+|-+$/g, '')\n return cleaned.length > 0 ? cleaned.slice(-80) : 'path'\n}\n\n/**\n * A state file's text, decoded the way `readStateFile` decodes it.\n *\n * **Not** `fs.readFileSync(file, 'utf8')`: a hand-edited file arrives with whatever a Windows editor\n * wrote, and a leading BOM makes `JSON.parse` fail. Here that failure was not loud — it made\n * `withoutInitialPassword` return `null`, which the caller reads as \"this is not a document I can\n * narrow\", and the raw-copy fallback then put the plaintext first-run password into the archive. So\n * the one codec the repo already centralised for exactly this reason is the one this must use.\n */\nfunction readText(file: string): string | null {\n try {\n return readStateFile(file)\n }\n catch {\n return null\n }\n}\n\n/**\n * What every phase of a restore reads and writes.\n *\n * A record passed explicitly rather than state on `this`, so each phase's signature says which\n * parts it touches — and the two only one phase writes (`archivedServers`, `createdWorkspaces`)\n * are visible as such instead of being hidden among twenty fields.\n */\ninterface RestoreContext {\n plan: AppRestorePlan\n options: RestoreOptions\n sources: BackupSources\n /** Where the archive was unpacked; removed by `applyRestore`'s `finally`. */\n staging: string\n manifest: BackupManifest\n selects: ReturnType<typeof selectionOf>\n /**\n * The writes to run, keyed by item id in the order they were **planned**.\n *\n * Filled by `addItem` while the phases plan, then drained by `runApply` — so the iteration order\n * is the apply order, which is why the phases must add their items in the original sequence.\n */\n actions: Map<string, () => void | Promise<void>>\n /** Every archived servers file this release can read, selected or not. Written by `planWorkspaceItems`. */\n archivedServers: Map<string, ServerConfig[]>\n /** Workspaces the archive names that this host lacks. Written by `planWorkspaceItems`. */\n createdWorkspaces: Map<string, BackupWorkspaceSource>\n}\n\n/** The plan, narrowed to the fields this side always fills. */\ntype AppRestorePlan = RestorePlan & { appliedIds: string[], skippedItems: RestoreSkip[], createdWorkspaces: string[], replacedUnderRunning: NonNullable<RestorePlan['replacedUnderRunning']> }\n\n/** The two facts about the archive's own settings that the data and restart phases need. */\ninterface ArchivedGlobal {\n /** The archive's `settings.json` text, or null when it carried none. */\n settingsText: string | null\n /** The archive's settings, lifted to this release's schema, or null when unreadable. */\n parsedGlobal: ResolvedGlobalConfig | null\n}\n\n/** What `openArchive` returns once the archive is admitted, unpacked and validated. */\ninterface OpenedArchive {\n ok: true\n manifest: BackupManifest\n}\n\n/** The plan a restore starts from: every field filled, so a refusal is a plan and not a throw. */\nfunction newRestorePlan(options: RestoreOptions): AppRestorePlan {\n return {\n dryRun: !options.confirm,\n encrypted: false,\n needsPassword: false,\n items: [],\n applied: [],\n appliedIds: [],\n skipped: [],\n skippedItems: [],\n restartRequired: false,\n reloaded: false,\n createdWorkspaces: [],\n replacedUnderRunning: [],\n }\n}\n\n/**\n * Archives of the control plane's own state plus whatever paths the configs\n * declare. Two rules keep restore safe: the archive layout is an allowlist, and\n * a data path is only written back when a *config* still declares it — a current\n * one, or a workspace's servers file the same restore is about to apply.\n *\n * A backup is always a zip; a password makes it a WinZip-AES one, so the same\n * file opens in any archive manager either way.\n */\nexport class BackupService {\n /**\n * Whether an archive is encrypted is only knowable by reading its central\n * directory, which is async while `list()` is not. The flags are cached here\n * and refreshed in the background, so a state frame stays cheap.\n */\n private readonly flags = new Map<string, { key: string, encrypted: boolean }>()\n private refreshing: Promise<void> | null = null\n /** One scheduled pass at a time: a slow archive must not stack up behind itself. */\n private running = false\n private disposed = false\n /**\n * When this instance last attempted an automatic pass, whatever it wrote.\n *\n * The archive's own mtime is the durable record across a restart, but it cannot bound a\n * failed pass: nothing is written, so every panel tick would retry — once a second, for as\n * long as the failure lasts. This is the in-memory backstop for that case.\n */\n private lastAttemptAt: number | null = null\n /**\n * The newest automatic archive, remembered rather than re-listed: `tick()` and `view()` run every\n * second, and each used to `readdir` + `stat` the whole archive directory. Seeded once per\n * directory, moved forward by `create()`, dropped when an archive is removed.\n */\n private lastAutomaticSeen: { dir: string, at: number | null } | null = null\n /** Logs a pass deferred by a running restore once, not on every tick. */\n private deferredForRestore = false\n /** Why the most recent scheduled pass failed, cleared by the next that works. */\n private scheduleError: { message: string, at: number } | null = null\n\n constructor(\n private readonly options: {\n /** Relative `backups.dir` values resolve against it (the panel passes `$HHOSTED_HOME/.hh`). */\n dataRoot: string\n getConfig: () => BackupsConfig\n getSources: () => BackupSources\n /**\n * Creates a workspace the archive brought and this host lacks, registry entry and\n * runtime together. Without it a restore can only fill workspaces that already\n * exist, which is what made \"one archive is a whole setup\" false.\n */\n ensureWorkspace?: (input: { id: string, label: string }) => void\n /** Called after a restore wrote settings/server files; the panel re-reads everything. */\n onRestored?: () => void\n /** Records a dump this entry still has to load, so its next start runs the hook. */\n onLoadPending?: (workspaceId: string, serverId: string, dumpDir: string) => void\n },\n ) {}\n\n /** Reads every archive once, so the first `list()` is already accurate. */\n async warm(): Promise<void> {\n await this.refresh()\n }\n\n dispose(): void {\n this.disposed = true\n }\n\n get directory(): string {\n return this.resolveDir()\n }\n\n /**\n * The policy and the status: what the settings page shows, and what the state frame carries.\n *\n * Deliberately **not** the selection model. `entries()` reads every workspace's `.secrets.json` and\n * `list()` stats every archive on disk, so including them here made the frame's cost scale with\n * workspaces × archives on a path rebuilt ~13×/s. A dialog asks `selection()` instead.\n */\n view(): BackupsView {\n const config = this.options.getConfig()\n const sources = this.options.getSources()\n return {\n enabled: config.enabled,\n dir: this.directory,\n keep: config.keep,\n schedule: { ...config.schedule },\n lastAutomaticAt: this.lastAutomatic(),\n ...(this.scheduleError === null ? {} : { scheduleError: { ...this.scheduleError } }),\n includePaths: [...sources.includePaths],\n }\n }\n\n /**\n * The selection model: every entry a capture could include, and every archive already on disk.\n *\n * Served by `GET /api/backups` and fetched when a dialog opens, never on a per-frame path.\n */\n selection(): BackupSelection {\n return {\n dir: this.directory,\n entries: this.entries(this.options.getSources()),\n files: this.list(),\n }\n }\n\n list(): BackupFile[] {\n const files = this.scan()\n for (const file of files) {\n const cached = this.flags.get(file.name)\n if (cached === undefined || cached.key !== cacheKey(file))\n void this.scheduleRefresh()\n }\n\n return files.map((file) => {\n const cached = this.flags.get(file.name)\n return {\n ...file,\n encrypted: cached !== undefined && cached.key === cacheKey(file) ? cached.encrypted : false,\n }\n })\n }\n\n /** Validated absolute path for a download, or null when the name is not a backup. */\n resolve(name: string): string | null {\n if (!/^[A-Z0-9][\\w.-]*$/i.test(name) || name.includes('..'))\n return null\n const file = path.join(this.resolveDir(), name)\n return fs.existsSync(file) ? file : null\n }\n\n /**\n * `password` encrypts the archive; it is never stored anywhere.\n *\n * `automatic` marks an archive the schedule wrote, which is what keeps the two retention\n * counts apart: an automatic pass must never prune the backup a person took by hand, and a\n * manual one must not silently eat the history the schedule is keeping.\n */\n async create(options: { password?: string, include?: string[], exclude?: string[], automatic?: boolean } = {}): Promise<{ ok: boolean, file?: BackupFile, error?: string, warnings?: string[] }> {\n const config = this.options.getConfig()\n if (!config.enabled)\n return { ok: false, error: 'backups are disabled' }\n\n const password = options.password !== undefined && options.password.length > 0 ? options.password : null\n // Omitted means everything; an id that names nothing is ignored, as on the restore side.\n const selects = selectionOf(options)\n // The narrow-only `wanted` set is still needed for the secrets narrowing below, which asks which\n // *fields* were named rather than whether an id is in scope.\n const wanted = options.include === undefined ? null : new Set(options.include)\n const capturesGlobal = (id: string): boolean => selects(id)\n // A workspace id alone means every leaf of that workspace.\n const capturesWorkspace = (id: string, suffix: string): boolean => selects(`workspace:${id}:${suffix}`)\n /**\n * The secrets of one scope the request asked for; `null` means \"every one of them\".\n * `workspaceId` is how a bare `workspace:<id>` selection covers all of its leaves.\n */\n const selectedSecretFields = (entryId: string, path: string, scope: SecretScope, workspaceId?: string): string[] | null => {\n const present = presentSecretKeys(parseSecrets(readText(path) ?? ''))\n const parts = secretParts(scope, present)\n // Per-field, and `selects` is the wrong question here: `--include global:secrets:password` names\n // one field, so a whole-entry `selects(entryId)` would pull in every sibling. What decides a\n // field is its own ids — the group and each of its fields — minus any exclusion above them.\n const picked = parts.filter((part) => {\n if (selects.isExcluded(entryId) || selects.isExcluded(`${entryId}:${part.key}`))\n return false\n const wantedField = wanted === null\n || wanted.has(entryId)\n || (workspaceId !== undefined && wanted.has(`workspace:${workspaceId}`))\n || wanted.has(`${entryId}:${part.key}`)\n || part.fields.some(field => wanted.has(`${entryId}:${field}`))\n return wantedField\n })\n return picked.length === parts.length ? null : picked.flatMap(part => part.fields)\n }\n\n const dir = this.resolveDir()\n const sources = this.options.getSources()\n // The pid is what makes a leftover reclaimable: a `SIGKILL` during the copy returns nothing, so\n // the `catch` below never runs and its tree survives. Naming the owner is the only durable way\n // for a later run to tell debris from another run's live capture.\n const staging = path.join(dir, stagingDirName('staging'))\n const createdAt = Date.now()\n // Milliseconds matter: two backups in the same second must not collide.\n const prefix = options.automatic === true ? AUTO_PREFIX : MANUAL_PREFIX\n const name = `${prefix}-${new Date(createdAt).toISOString().replace(/[:T]/g, '-').replace(/\\.\\d+Z$/, '')}-${createdAt % 1000}${SUFFIX}`\n const destination = path.join(dir, name)\n\n try {\n ensureStateDir(staging)\n let captured = 0\n const copy = async (relative: string, source: string, ignoreGenerated = false): Promise<void> => {\n if (await this.copyInto(staging, relative, source, ignoreGenerated))\n captured++\n }\n /**\n * Captures one secrets file, narrowed to the picked secrets. Copying the whole file\n * would capture the ones that were *not* picked, so a per-secret selection writes a\n * staged document holding only those — and the restore side merges by field, which\n * is what keeps a restore from wiping a secret the archive never carried.\n */\n const copySecrets = async (relative: string, source: string, entryId: string, scope: SecretScope, workspaceId?: string): Promise<void> => {\n const text = readText(source)\n if (text === null)\n return\n const fields = selectedSecretFields(entryId, source, scope, workspaceId)\n /**\n * `fields === null` means \"every field is selected\", which is the **default** — no\n * `--include`/`--exclude`, and the automatic schedule. It is still not a licence to copy the\n * file verbatim: `withoutFirstRunPassword` lives inside `pickSecrets`, so the raw-copy branch\n * bypassed it and put `.control-secrets.json` in the zip byte for byte, plaintext first-run\n * password and all — unencrypted, in a directory the docs tell people to copy off the box.\n * The narrowing ran only on the partial path, and the sole test exercised `pickSecrets` in\n * isolation, so the suite stayed green over it.\n *\n * A whole selection still copies the whole document — null slots, unknown keys and all, which\n * is the shape the archive had before — with just that one field removed. Re-deriving the\n * fields instead would drop every `null` slot, because `presentSecretKeys` counts only\n * non-null values and `pickSecrets` then answers `null` for a file holding nothing set.\n */\n /**\n * **Never** fall back to copying the original bytes. That fallback is the whole bug: a file\n * `withoutInitialPassword` could not parse — a BOM, most realistically, which is what a\n * Windows editor writes — took the raw-copy branch and carried the plaintext password into\n * the archive. Unreadable is not \"safe to copy verbatim\"; it is a file that must not travel.\n */\n const chosen = fields === null ? withoutInitialPassword(text) : pickSecrets(parseSecrets(text), fields)\n if (chosen === null)\n return\n const target = path.join(staging, relative)\n ensureStateDir(path.dirname(target))\n // 0600, the mode the live file has: the archive is a copy *off* the box, so it must not be\n // more readable than its source (the default umask would make it 0644).\n fs.writeFileSync(target, chosen.endsWith('\\n') ? chosen : `${chosen}\\n`, { mode: 0o600 })\n captured++\n }\n\n /**\n * True when the request touches a secrets entry at all: the entry itself, one of its\n * leaves, or — for a workspace — the workspace id, which names every leaf it has.\n */\n // Through `selects`, like every other capture: a third copy of \"is this selected\" is how\n // `--exclude` came to leave the secrets in the archive it was asked to leave them out of.\n // Upwards as well as down: `--include global:secrets:password` names a leaf, and the file that\n // holds it still has to be captured — the narrowing above then keeps the sibling out.\n const touchesSecrets = (entryId: string, workspaceId?: string): boolean =>\n selects(entryId)\n || (wanted !== null && [...wanted].some(id => id.startsWith(`${entryId}:`)))\n || (workspaceId !== undefined && selects(`workspace:${workspaceId}:secrets`))\n\n if (capturesGlobal('global:settings'))\n await copy('global/settings.json', sources.globalSettingsPath)\n if (touchesSecrets('global:secrets'))\n await copySecrets('global/secrets.json', sources.globalSecretsPath, 'global:secrets', 'global')\n if (capturesGlobal('global:tls'))\n await copy('global/tls', sources.tlsDir)\n // Always, and unconditionally: the registry is what lets a restore onto a blank host\n // know a workspace exists at all, and it is a few bytes of ids and labels. Tying it\n // to a selection would make \"restore this workspace\" impossible on a host that has\n // never heard of it. Not counted as a capture — a selection that names nothing real\n // is still \"nothing was selected\", which the check below refuses.\n await this.copyInto(staging, `global/${REGISTRY}`, sources.registryPath)\n\n /**\n * The dump phase: give every entry with a `dump` hook the chance to produce a consistent copy.\n *\n * Before anything is copied, because the dump is the authoritative artifact — the raw data\n * directory beside it is a convenience, and a dump that failed must not leave an archive that\n * looks complete. The output lands in `dumps/<workspace>/<server>/`, which the restore side\n * fills again at the same path, so `{dumpDir}` means the same thing in both directions.\n */\n const dumped: Array<{ workspaceId: string, serverId: string }> = []\n for (const workspace of sources.workspaces) {\n for (const server of workspace.servers) {\n const hook = server.dump\n if (hook === undefined || hook === null)\n continue\n // The dump belongs to the entry, so the selection that names the entry includes it and an\n // exclusion that names the entry — or its dump — leaves it out. This was the last copy of\n // the selection rule that did not consult `exclude`, so `--exclude workspace:default` still\n // *ran* that workspace's dump program and archived the result.\n if (!selects(`workspace:${workspace.id}:dump:${server.id}`)) {\n continue\n }\n const relative = path.join('dumps', workspace.id, server.id)\n const dumpDir = path.join(staging, relative)\n const result = await runBackupHook(hook, server, dumpDir)\n if (!result.ok) {\n await fs.promises.rm(staging, { recursive: true, force: true })\n return { ok: false, error: hookFailure('dump', server, result) }\n }\n dumped.push({ workspaceId: workspace.id, serverId: server.id })\n }\n }\n\n const data: BackupManifest['data'] = []\n const warnings: string[] = []\n for (const workspace of sources.workspaces) {\n const root = `workspaces/${workspace.id}`\n if (capturesWorkspace(workspace.id, 'settings'))\n await copy(`${root}/settings.json`, workspace.settingsPath)\n if (capturesWorkspace(workspace.id, 'servers'))\n await copy(`${root}/servers.config.json`, workspace.serversPath)\n if (touchesSecrets(`workspace:${workspace.id}:secrets`, workspace.id))\n await copySecrets(`${root}/secrets.json`, workspace.secretsPath, `workspace:${workspace.id}:secrets`, 'workspace', workspace.id)\n\n for (const declared of this.declaredData(workspace.servers, sources.includePaths)) {\n if (!declared.included)\n continue\n if (!capturesWorkspace(workspace.id, `data:${declared.path}`))\n continue\n if (!fs.existsSync(declared.path))\n continue\n // The same directory declared by two workspaces (a global include path) is captured once.\n const resolved = path.resolve(declared.path)\n if (data.some(entry => path.resolve(entry.path) === resolved))\n continue\n const slug = slugifyPath(declared.path)\n if (!await this.copyInto(staging, path.join('data', slug), declared.path, declared.ignoreGenerated))\n continue\n captured++\n data.push({ slug, path: declared.path, origin: declared.origin, workspace: workspace.id })\n // Captured, but empty: a mount that was not up, or a tree that is all links out of itself.\n // The archive is still written — an empty directory can be legitimate — but not silently.\n if (!holdsAnyFile(path.join(staging, 'data', slug)))\n warnings.push(`\"${declared.path}\" was captured but holds no files`)\n }\n }\n\n // A selection that captured nothing would only produce a manifest — and an exclusion is a\n // selection too: `--all --exclude <everything>` wrote a 631-byte archive holding nothing but\n // the registry, which reads as a backup and restores nothing.\n if ((wanted !== null || (options.exclude?.length ?? 0) > 0) && captured === 0) {\n await fs.promises.rm(staging, { recursive: true, force: true })\n return { ok: false, error: 'nothing was selected to back up' }\n }\n\n const manifest: BackupManifest = {\n version: 1,\n createdAt,\n hostname: os.hostname(),\n writtenBy: appVersion(),\n schema: CONFIG_SCHEMA,\n data,\n // Which entries brought a dump, so a restore can tell \"this archive has no dump for it\" from\n // \"this archive was taken before the hook existed\".\n ...(dumped.length === 0 ? {} : { dumps: dumped }),\n }\n fs.writeFileSync(path.join(staging, MANIFEST), `${JSON.stringify(manifest, null, 2)}\\n`)\n\n await createZip(staging, destination, password === null ? {} : { password })\n\n await fs.promises.rm(staging, { recursive: true, force: true })\n this.prune()\n // A successful run is the one moment this service knows a dead run's tree is not in use.\n this.sweepStaging()\n\n const stats = fs.statSync(destination)\n this.flags.set(name, { key: cacheKey({ sizeBytes: stats.size, createdAt }), encrypted: password !== null })\n if (options.automatic === true && this.lastAutomaticSeen !== null && this.lastAutomaticSeen.dir === dir)\n this.lastAutomaticSeen = { dir, at: Math.max(this.lastAutomaticSeen.at ?? 0, createdAt) }\n return { ok: true, file: { name, sizeBytes: stats.size, createdAt, encrypted: password !== null }, ...(warnings.length === 0 ? {} : { warnings }) }\n }\n catch (error) {\n await fs.promises.rm(staging, { recursive: true, force: true }).catch(() => {})\n await fs.promises.rm(destination, { force: true }).catch(() => {})\n return { ok: false, error: errorMessage(error) }\n }\n }\n\n remove(name: string): boolean {\n const file = this.resolve(name)\n if (file === null)\n return false\n fs.rmSync(file, { force: true })\n this.flags.delete(name)\n if (isAutomatic({ name }))\n this.lastAutomaticSeen = null\n return true\n }\n\n /**\n * Validates an archive, then (unless `confirm` is false) applies whichever of\n * its items were selected. Data paths come from the *current* sources, or from\n * a workspace's servers file that is itself being restored — never from the\n * archive's manifest alone.\n */\n async restore(archivePath: string, options: RestoreOptions): Promise<RestorePlan> {\n // An **apply** takes the lock here, so every caller has it: the panel's route, its local control\n // channel, and the CLI working with no panel at all. A dry run writes nothing and needs none.\n // Holding it any higher up was three separate guards, and one of them was always going to be\n // forgotten — which is exactly what happened to the panel's own route.\n const lock = options.confirm ? acquireRestoreLock(this.options.dataRoot) : null\n if (lock !== null && 'heldBy' in lock) {\n throw new DetailedError(\n `another restore is running (pid ${lock.heldBy.pid}, since ${new Date(lock.heldBy.startedAt).toISOString()}) — wait for it, or remove ${path.join(this.options.dataRoot, 'restore.lock')} if it is stale`,\n { statusCode: 409, code: 'RESTORE_IN_PROGRESS' },\n )\n }\n try {\n return await this.applyRestore(archivePath, options)\n }\n finally {\n if (lock !== null && !('heldBy' in lock))\n lock.release()\n }\n }\n\n // ------------------------------------------------------------- restore\n\n private async applyRestore(archivePath: string, options: RestoreOptions): Promise<RestorePlan> {\n const password = options.password !== undefined && options.password.length > 0 ? options.password : null\n const plan = newRestorePlan(options)\n\n const admitted = await admitArchive(archivePath)\n if (!admitted.ok)\n return { ...plan, error: admitted.error }\n\n const staging = path.join(this.resolveDir(), stagingDirName('restore'))\n\n try {\n const opened = await this.openArchive(plan, admitted.entries, archivePath, staging, password)\n // A refusal before anything is written is answered, not thrown: the plan is the answer.\n if (!('ok' in opened))\n return opened\n\n const ctx = this.restoreContext(plan, options, opened.manifest, staging)\n\n const global = this.planGlobalItems(ctx)\n this.planWorkspaceItems(ctx)\n this.planDataItems(ctx, global)\n this.noteRestartRequired(ctx, global)\n\n if (!options.confirm) {\n // A dry run reports what *would* happen, so the UI can show the plan\n // and the selection before anything is written.\n plan.applied = [...ctx.actions.keys()].map(id => labelOf(plan, id))\n plan.appliedIds = [...ctx.actions.keys()]\n return plan\n }\n\n const failure = await this.runApply(ctx)\n this.registerCreatedWorkspaces(ctx)\n\n // A restore that failed partway still reloads what it wrote, so memory matches the disk.\n if (failure !== null) {\n this.reloadRestored(plan)\n throw failure\n }\n\n await this.stagePendingLoads(ctx)\n\n this.reloadRestored(plan)\n return plan\n }\n catch (error) {\n // Extraction happens before anything is written, so a rejected password has\n // changed nothing at all.\n if (isInvalidPassword(error))\n return { ...plan, encrypted: true, needsPassword: true, error: 'the password is wrong' }\n // A restore is not transactional: say what already landed, so a failure\n // cannot look like nothing happened.\n const done = plan.applied.length > 0 ? ` — already applied: ${plan.applied.join(', ')}` : ''\n return { ...plan, error: `${errorMessage(error)}${done}` }\n }\n finally {\n fs.rmSync(staging, { recursive: true, force: true })\n // Same reason as `create`'s: a killed restore leaves an unpacked archive behind, and this is\n // the next moment the directory is known not to be in use.\n this.sweepStaging()\n }\n }\n\n /** The state every phase reads and writes, built once from the plan and the live sources. */\n private restoreContext(plan: AppRestorePlan, options: RestoreOptions, manifest: BackupManifest, staging: string): RestoreContext {\n return {\n plan,\n options,\n sources: this.options.getSources(),\n staging,\n manifest,\n selects: selectionOf(options),\n actions: new Map<string, () => void | Promise<void>>(),\n archivedServers: new Map<string, ServerConfig[]>(),\n createdWorkspaces: new Map<string, BackupWorkspaceSource>(),\n }\n }\n\n /**\n * Unpacks the archive and refuses it before anything is written.\n *\n * Everything here answers with a plan rather than throwing, because a refusal at this point has\n * changed nothing — `applyRestore` passes the answer straight back. The one throw is a wrong\n * password, which `extractZip` raises and `applyRestore`'s `catch` maps to `needsPassword`.\n *\n * Returns null when the archive is usable, after unpacking it into `staging`.\n */\n private async openArchive(\n plan: AppRestorePlan,\n entries: Awaited<ReturnType<typeof listZip>>,\n archivePath: string,\n staging: string,\n password: string | null,\n ): Promise<OpenedArchive | RestorePlan> {\n plan.encrypted = entries.some(entry => entry.encrypted)\n if (plan.encrypted && password === null)\n return { ...plan, needsPassword: true, error: 'this backup is password-protected' }\n\n ensureStateDir(staging)\n const extracted = await extractZip(archivePath, staging, {\n names: entries.map(entry => entry.name),\n ...(password === null ? {} : { password }),\n })\n for (const name of extracted.skipped) {\n plan.skipped.push(`${name} (symbolic link, skipped)`)\n plan.skippedItems.push({ label: name, reasonKey: 'settings.restore.reasonSymbolicLink' })\n }\n\n const manifestPath = path.join(staging, MANIFEST)\n if (!fs.existsSync(manifestPath))\n return { ...plan, error: 'the archive has no manifest' }\n const manifest = JSON.parse(fs.readFileSync(manifestPath, 'utf8')) as BackupManifest\n\n // An archive naming a schema this release cannot read is refused outright: the\n // per-file readability gates below would each skip their own piece and report a\n // half-restored setup, which reads as a partial success rather than the refusal\n // it is. Optional, so an archive written before this stamp still restores.\n plan.archive = manifestInfo(manifest)\n if (manifest.schema !== undefined && manifest.schema > CONFIG_SCHEMA) {\n return {\n ...plan,\n error: `written by home-hosted ${manifest.writtenBy ?? 'a newer release'} (config schema ${manifest.schema}); this release understands schema ${CONFIG_SCHEMA}`,\n }\n }\n\n // The dump ids are joined into paths below, and an uploaded manifest is attacker controlled.\n const dumpsValid = manifest.dumps === undefined || (Array.isArray(manifest.dumps) && manifest.dumps.every(dump =>\n isRecord(dump) && !(workspaceIdSchema(dump.workspaceId) instanceof type.errors) && !(serverIdSchema(dump.serverId) instanceof type.errors)))\n if (!dumpsValid)\n return { ...plan, error: 'the archive\\'s manifest names a dump with an invalid workspace or server id' }\n return { ok: true, manifest }\n }\n\n /**\n * The three global slices: settings, secrets (plus one leaf per secret), and the TLS pair.\n *\n * Returns the archive's own settings for the later phases, which decide data paths and whether\n * the listener must restart.\n */\n private planGlobalItems(ctx: RestoreContext): ArchivedGlobal {\n const { plan, sources, staging, actions } = ctx\n const { secretsApply, addItem } = this.itemWriters(ctx)\n\n // ---------------------------------------------------------------- global\n const settingsText = readText(path.join(staging, 'global', 'settings.json'))\n const liftedGlobal = readableGlobalSettings(settingsText)\n const parsedGlobal = liftedGlobal === null ? null : parseGlobalSettings(liftedGlobal).config\n if (settingsText !== null && parsedGlobal === null) {\n plan.skipped.push('Global settings (the archive\\'s settings are not valid)')\n plan.skippedItems.push({ label: 'Global settings', labelKey: 'settings.backup.entryGlobalSettings', reasonKey: 'settings.restore.reasonInvalidSettings' })\n }\n if (parsedGlobal !== null && liftedGlobal !== null) {\n // The **lifted** config is what gets written: the archive's file carries the schema it was\n // written with, and writing it back verbatim restores a file this release then refuses.\n const globalText = `${JSON.stringify(liftedGlobal, null, 2)}\\n`\n addItem({ id: GLOBAL_RESTORE_ITEMS.settings.id, label: 'Global settings', labelKey: 'settings.backup.entryGlobalSettings', kind: 'settings', restorable: true, note: null }, () => {\n writeFileAtomic(sources.globalSettingsPath, globalText)\n }, [...GLOBAL_RESTORE_ITEMS.settings.aliases])\n }\n\n const globalSecrets = readText(path.join(staging, 'global', 'secrets.json'))\n if (globalSecrets !== null) {\n addItem(\n { id: GLOBAL_RESTORE_ITEMS.credentials.id, label: 'Global secrets (password, API token)', labelKey: 'settings.backup.entryGlobalSecrets', kind: 'secrets', restorable: true, note: null },\n secretsApply('global', GLOBAL_RESTORE_ITEMS.credentials.id, sources.globalSecretsPath, globalSecrets),\n [...GLOBAL_RESTORE_ITEMS.credentials.aliases],\n )\n // One item per secret the archive carries, so the password can come back without\n // the API token. Applying one merges by field: writing the whole archived file\n // would reinstate every secret in it, which is exactly what the person unpicked.\n for (const part of secretParts('global', presentSecretKeys(parseSecrets(globalSecrets)))) {\n const leafId = `${GLOBAL_RESTORE_ITEMS.credentials.id}:${part.key}`\n addItem({\n id: leafId,\n label: `Global secrets: ${SECRET_LABELS[part.key]?.en ?? part.key}`,\n labelKey: 'settings.backup.restoreItemLabel',\n labelParams: { workspace: 'global', item: part.key },\n kind: 'secrets',\n restorable: true,\n note: null,\n }, () => {\n // The whole entry, when it is applied, already merges every field this one carries.\n if (actions.has(GLOBAL_RESTORE_ITEMS.credentials.id))\n return\n mergeIntoFile(sources.globalSecretsPath, globalSecrets, part.fields)\n },\n // The leaf's own alias spelling (`secrets:password`), so `--exclude secrets` reaches this\n // leaf the same way it reaches its parent entry. Without it the parent was excluded while\n // the leaf was still written — a token-only restore could replace the password hash.\n GLOBAL_RESTORE_ITEMS.credentials.aliases.map(alias => `${alias}:${part.key}`))\n }\n }\n\n const tlsInArchive = path.join(staging, 'global', 'tls')\n if (fs.existsSync(tlsInArchive)) {\n const files = fs.readdirSync(tlsInArchive).filter(file => fs.statSync(path.join(tlsInArchive, file)).isFile())\n addItem({ id: GLOBAL_RESTORE_ITEMS.tls.id, label: 'TLS certificate', labelKey: 'settings.backup.entryTlsCertificate', kind: 'tls', restorable: true, note: null }, () => {\n ensureStateDir(sources.tlsDir)\n for (const file of files) {\n const mode = file.endsWith('.key.pem') ? { mode: 0o600 } : {}\n writeFileAtomic(path.join(sources.tlsDir, file), fs.readFileSync(path.join(tlsInArchive, file), 'utf8'), mode)\n }\n }, [...GLOBAL_RESTORE_ITEMS.tls.aliases])\n }\n return { settingsText, parsedGlobal }\n }\n\n /**\n * The two closures every planning phase writes through.\n *\n * **`addItem` fills `actions` in call order, and `runApply` drains that map in the same order** —\n * so the sequence of `addItem` calls across the phases *is* the apply order. Splitting the phases\n * did not change that order; it must not.\n */\n private itemWriters(ctx: RestoreContext): {\n secretsApply: (scope: SecretScope, entryId: string, target: string, archived: string) => () => void\n addItem: (item: Omit<RestoreItem, 'selected'>, apply: (() => void | Promise<void>) | null, aliases?: string[]) => void\n } {\n const { plan, selects, actions } = ctx\n\n /**\n * Writes one archived secrets file, **always** by field.\n *\n * Replacing the live file wholesale when nothing was excluded looked like the identity case, but\n * an archive only carries what its own selection captured: restoring `global:secrets` from an\n * archive taken with `--exclude global:secrets:apiToken` replaced the file with a document that\n * had no `apiToken` in it, silently signing every script out. The live file may also hold a secret\n * the archive predates. `mergeIntoFile` copies exactly the fields the archive carries and leaves\n * every other key of the live file alone, which is the behaviour both cases want — and what every\n * restore did before this rewrite.\n */\n const secretsApply = (scope: SecretScope, entryId: string, target: string, archived: string): (() => void) => {\n const parts = secretParts(scope, presentSecretKeys(parseSecrets(archived)))\n const take = parts.filter(part => !selects.isExcluded(`${entryId}:${part.key}`)\n && !part.fields.some(field => selects.isExcluded(`${entryId}:${field}`)))\n return (): void => {\n ensureStateDir(path.dirname(target))\n mergeIntoFile(target, archived, take.flatMap(part => part.fields))\n }\n }\n\n const addItem = (item: Omit<RestoreItem, 'selected'>, apply: (() => void | Promise<void>) | null, aliases: string[] = []): void => {\n if (apply === null) {\n plan.items.push({ ...item, selected: false })\n plan.skipped.push(`${item.label}${item.note === null ? '' : ` (${item.note})`}`)\n plan.skippedItems.push({\n label: item.label,\n ...(item.labelKey === undefined ? {} : { labelKey: item.labelKey }),\n ...(item.labelParams === undefined ? {} : { labelParams: item.labelParams }),\n // The note is already the reason when there is one; otherwise the row is simply not\n // something this instance can write back.\n reasonKey: item.noteKey ?? 'settings.restore.reasonUnrestorable',\n ...(item.noteParams === undefined ? {} : { reasonParams: item.noteParams }),\n })\n return\n }\n // Whether the selection chooses this item is `selectedBy`, the same rule the credential guard\n // asks at the route: an alias is a coarse id (`workspace:<id>`, `secrets`) and selection also\n // matches on it, so the two must not answer \"is this item selected\" differently. They did:\n // `include: [\"secrets\"]` selected the credential file here while `selectionWritesCredentials`\n // tested only `global:secrets`, so a token-only restore rewrote the panel's own credentials.\n const selected = selectedBy(selects, aliases.length === 0 ? item : { ...item, aliases })\n plan.items.push({ ...item, selected })\n if (selected) {\n actions.set(item.id, apply)\n }\n else {\n plan.skipped.push(`${item.label} (not selected)`)\n plan.skippedItems.push({\n label: item.label,\n ...(item.labelKey === undefined ? {} : { labelKey: item.labelKey }),\n ...(item.labelParams === undefined ? {} : { labelParams: item.labelParams }),\n reasonKey: 'settings.restore.reasonNotSelected',\n })\n }\n }\n return { secretsApply, addItem }\n }\n\n /**\n * One item group per workspace the archive names, plus the archived servers each carries.\n *\n * A workspace this host does not have is *created* rather than skipped: an archive is the whole\n * setup. Its directories are made only when one of its leaves is applied, so a dry run writes\n * nothing.\n */\n private planWorkspaceItems(ctx: RestoreContext): void {\n const { plan, sources, staging, actions, archivedServers, createdWorkspaces } = ctx\n /**\n * The workspaces the archive names, from its registry file.\n *\n * Optional: an archive written before the registry was captured carries none, and then every\n * archived workspace is still restorable under its own id — the label is all the registry adds.\n */\n const archivedWorkspaces = new Map<string, ArchivedWorkspace>()\n for (const entry of readArchivedRegistry(path.join(staging, 'global', REGISTRY)))\n archivedWorkspaces.set(entry.id, entry)\n const { secretsApply, addItem } = this.itemWriters(ctx)\n\n const archiveWorkspaces = path.join(staging, 'workspaces')\n if (fs.existsSync(archiveWorkspaces)) {\n for (const entry of fs.readdirSync(archiveWorkspaces, { withFileTypes: true })) {\n if (!entry.isDirectory())\n continue\n const id = entry.name\n const dir = path.join(archiveWorkspaces, id)\n const settings = readText(path.join(dir, 'settings.json'))\n const servers = readText(path.join(dir, 'servers.config.json'))\n const secrets = readText(path.join(dir, 'secrets.json'))\n // A label the archive's registry carried, else the id: the registry is the\n // only place a label lives, so an archive without it still restores under a\n // name the person can find afterwards.\n const archivedLabel = archivedWorkspaces.get(id)?.label ?? id\n\n // A workspace this host does not have is created, not skipped: an archive is the whole\n // setup. Skipping it also let the data pass match by origin alone, writing one\n // workspace's database into another's declared directory.\n const workspace = sources.workspaces.find(candidate => candidate.id === id)\n ?? createdWorkspaces.get(id)\n ?? (workspaceIdSchema(id) instanceof type.errors\n ? undefined\n : { id, label: archivedLabel, ...workspacePathsFor(this.options.dataRoot, id), servers: [] as ServerConfig[] })\n if (workspace === undefined) {\n plan.skipped.push(`${id} (not a usable workspace id)`)\n plan.skippedItems.push({ label: id, reasonKey: 'settings.restore.reasonInvalidWorkspace' })\n continue\n }\n if (!sources.workspaces.some(candidate => candidate.id === id))\n createdWorkspaces.set(id, workspace)\n\n if (settings !== null) {\n const liftedSettings = readableWorkspaceSettings(settings)\n if (liftedSettings !== null) {\n const settingsText = `${JSON.stringify(liftedSettings, null, 2)}\\n`\n addItem({ id: `workspace:${id}:settings`, label: `${workspace.label}: Settings`, labelKey: 'settings.backup.restoreItemLabel', labelParams: { workspace: workspace.label, item: 'settings' }, kind: 'settings', workspaceId: id, restorable: true, note: null }, () => {\n ensureStateDir(path.dirname(workspace.settingsPath))\n writeFileAtomic(workspace.settingsPath, settingsText)\n })\n }\n else {\n plan.skipped.push(`${workspace.label}: Settings (the archive's settings are not valid)`)\n plan.skippedItems.push({ label: `${workspace.label}: Settings`, labelKey: 'settings.backup.restoreItemLabel', labelParams: { workspace: workspace.label, item: 'settings' }, reasonKey: 'settings.restore.reasonInvalidSettings' })\n }\n }\n\n if (servers !== null) {\n const parsed = readableServersFile(servers)\n const liftedServers = parsed === null ? null : liftArchived(JSON.parse(servers))\n if (parsed !== null && liftedServers !== null) {\n const serversText = `${JSON.stringify(liftedServers, null, 2)}\\n`\n archivedServers.set(id, parsed)\n addItem({ id: `workspace:${id}:servers`, label: `${workspace.label}: Servers`, labelKey: 'settings.backup.restoreItemLabel', labelParams: { workspace: workspace.label, item: 'servers' }, kind: 'servers', workspaceId: id, restorable: true, note: null }, () => {\n ensureStateDir(path.dirname(workspace.serversPath))\n writeFileAtomic(workspace.serversPath, serversText)\n })\n }\n else {\n plan.skipped.push(`${workspace.label}: Servers (the archive's servers are not valid)`)\n plan.skippedItems.push({ label: `${workspace.label}: Servers`, labelKey: 'settings.backup.restoreItemLabel', labelParams: { workspace: workspace.label, item: 'servers' }, reasonKey: 'settings.restore.reasonInvalidServers' })\n }\n }\n\n if (secrets !== null) {\n addItem({ id: `workspace:${id}:secrets`, label: `${workspace.label}: Secrets`, labelKey: 'settings.backup.restoreItemLabel', labelParams: { workspace: workspace.label, item: 'secrets' }, kind: 'secrets', workspaceId: id, restorable: true, note: null }, secretsApply('workspace', `workspace:${id}:secrets`, workspace.secretsPath, secrets))\n for (const part of secretParts('workspace', presentSecretKeys(parseSecrets(secrets)))) {\n addItem({\n id: `workspace:${id}:secrets:${part.key}`,\n label: `${workspace.label}: ${SECRET_LABELS[part.key]?.en ?? part.key}`,\n labelKey: 'settings.backup.restoreItemLabel',\n labelParams: { workspace: workspace.label, item: part.key },\n kind: 'secrets',\n workspaceId: id,\n restorable: true,\n note: null,\n }, () => {\n if (actions.has(`workspace:${id}:secrets`))\n return\n ensureStateDir(path.dirname(workspace.secretsPath))\n mergeIntoFile(workspace.secretsPath, secrets, part.fields)\n })\n }\n }\n }\n }\n }\n\n /**\n * Data-path items and dumps.\n *\n * A data path is written to a path a *config* declares — this instance's, or the servers file the\n * archive brings and the restore is about to apply. Nothing here is guessed from the archive's\n * manifest alone.\n *\n * Runs **after** the workspace phase on purpose: it reads `archivedServers` and asks\n * `actions.has(...)` about the workspace items, both of which that phase fills.\n */\n private planDataItems(ctx: RestoreContext, global: ArchivedGlobal): void {\n const { plan, sources, staging, manifest, selects } = ctx\n const { addItem } = this.itemWriters(ctx)\n\n const { archiveAll, archiveTargets, instanceTargets } = this.collectDataTargets(ctx, global)\n\n // Where one archived data path lands. See `dataTargetMatcher` for the pairing rule.\n const matchTarget = dataTargetMatcher(archiveTargets, instanceTargets)\n\n /**\n * `workspace:serverId` for every entry running at this moment.\n *\n * Built once, before anything is copied: a data path whose owner is running is about to be\n * replaced under a live process, and the plan has to name it. Read here rather than in the\n * apply closure so a dry run reports the same list the apply would.\n */\n const runningOwners = new Set(\n (sources.runningServers?.() ?? []).map(entry => `${entry.workspaceId}:${entry.serverId}`),\n )\n\n // A dump is a restorable item in its own right: it is the thing the engine reads, and leaving\n // it out of the plan meant `--all` reported nothing to restore and the load hook never ran.\n this.planDumpItems(ctx)\n\n const archivedEntries = Array.isArray(manifest.data) ? manifest.data.filter(isRecord) : []\n for (const entry of archivedEntries) {\n const archivedPath = typeof entry.path === 'string' ? entry.path : ''\n const origin = typeof entry.origin === 'string' ? entry.origin : undefined\n const workspace = typeof entry.workspace === 'string' ? entry.workspace : undefined\n const from = path.join(staging, 'data', safeSlug(entry.slug) ?? legacySlug(archivedPath))\n const target = matchTarget(origin, workspace, archivedPath)\n const targetWorkspace = target?.workspace ?? workspace\n const base: Omit<RestoreItem, 'selected'> = {\n id: target === undefined ? `data:${archivedPath}` : `workspace:${target.workspace}:data:${target.path}`,\n label: target?.path ?? archivedPath,\n kind: 'data',\n restorable: false,\n note: null,\n ...(targetWorkspace === undefined ? {} : { workspaceId: targetWorkspace }),\n }\n const aliases = [`data:${archivedPath}`]\n\n if (target === undefined) {\n this.planUnplacedDataItem(ctx, archiveAll, { base, aliases, origin, workspace })\n continue\n }\n if (!fs.existsSync(from)) {\n addItem({ ...base, note: 'missing from the archive', noteKey: 'settings.backup.noteMissingFromArchive' }, null, aliases)\n continue\n }\n\n // The entry that declares this path, so a restore can name it if it is running.\n // Recorded at *plan* time, not inside the apply closure: a dry run has to report the\n // same list, otherwise the person cannot see what to stop before applying.\n const ownerId = target.origin.split(':')[0] ?? ''\n // The same rule `addItem` uses, so a route named by its alias is as covered as one named by\n // its id when deciding whether the apply replaces a running entry's path.\n const covered = selectedBy(selects, { ...base, aliases })\n if (covered && runningOwners.has(`${target.workspace}:${ownerId}`))\n plan.replacedUnderRunning.push({ workspaceId: target.workspace, serverId: ownerId, path: target.path })\n\n addItem(\n { ...base, restorable: true, ...(target.path === archivedPath ? { note: null } : { note: `restored from ${archivedPath}`, noteKey: 'settings.backup.noteRestoredFrom', noteParams: { path: archivedPath } }) },\n // `cpSync` follows symlinks already in the destination tree, so a link\n // standing inside the declared path would carry the archive's files out of\n // it. The destination of each entry is what is checked, because that is\n // where the link is resolved; the links themselves are never recreated,\n // which is the stated invariant.\n () => copyTree(from, target.path, (_source, destination) => isInsideResolved(target.path, destination)),\n aliases,\n )\n }\n }\n\n /**\n * A dump is a restorable item in its own right — it is the thing the engine reads.\n *\n * Leaving it out of the plan meant `--all` reported nothing to restore and the `load` hook never\n * ran. Nothing is written over this host's files when this item applies: the dump is replayed by\n * that hook after everything has landed, and the item exists so the selection can name it (and so\n * deselecting it is expressible).\n */\n private planDumpItems(ctx: RestoreContext): void {\n const { staging, manifest } = ctx\n const { addItem } = this.itemWriters(ctx)\n\n for (const dump of manifest.dumps ?? []) {\n const from = path.join(staging, 'dumps', dump.workspaceId, dump.serverId)\n if (!fs.existsSync(from))\n continue\n const id = `workspace:${dump.workspaceId}:dump:${dump.serverId}`\n addItem({\n id,\n label: `dump:${dump.serverId}`,\n kind: 'data',\n restorable: true,\n workspaceId: dump.workspaceId,\n note: null,\n }, () => {\n // Nothing is written over this host's files: the dump is replayed by the entry's `load`\n // hook, which runs after everything landed. The item exists so the selection can name it.\n })\n }\n }\n\n /**\n * How an archived data path is reported when nothing on this host will receive it.\n *\n * Two reasons, and the difference is what the person acts on: \"the backup's config declares it but\n * that config is not being restored\" says tick the servers item; \"neither config declares it\" says\n * this path has nowhere to go. Both are reported rather than skipped silently — the archive holds\n * those bytes and a restore that says nothing about them reads as a complete one.\n */\n private planUnplacedDataItem(\n ctx: RestoreContext,\n archiveAll: DataTarget[],\n placed: {\n base: Omit<RestoreItem, 'selected'>\n aliases: string[]\n origin: string | undefined\n workspace: string | undefined\n },\n ): void {\n const { addItem } = this.itemWriters(ctx)\n const { base, aliases, origin, workspace } = placed\n const declaredByBackup = archiveAll.some(candidate =>\n candidate.origin === origin && (workspace === undefined || candidate.workspace === workspace))\n addItem({\n ...base,\n note: declaredByBackup\n ? 'declared by the backup\\'s config, which is not being restored'\n : 'not declared by this config, nor by the backup',\n noteKey: declaredByBackup\n ? 'settings.backup.noteDeclaredByBackup'\n : 'settings.backup.noteNotDeclared',\n }, null, aliases)\n }\n\n /**\n * Every data path a restore could write, from both sides of the comparison.\n *\n * A data path is only ever written to a path a **config** declares: this instance's, or the servers\n * file the archive brings and this restore is about to apply. `archivedIncludePaths` follows the\n * same rule for the archive side — a `global:settings` item that is being applied brings its own\n * `backups.includePaths`, and using this host's list instead would look for the archive's paths\n * where *this* config declares them.\n *\n * `archiveAll` is the archive's declarations *whether or not* they are applied, because it answers\n * a different question: \"was this path declared by the backup's own config?\" is what tells a person\n * why an entry could not be placed. `archiveTargets` is the narrower list a restore may write to —\n * only a servers file this restore is actually applying may name a destination.\n */\n private collectDataTargets(ctx: RestoreContext, global: ArchivedGlobal): {\n archiveAll: DataTarget[]\n archiveTargets: DataTarget[]\n instanceTargets: DataTarget[]\n } {\n const { sources, actions, archivedServers } = ctx\n const { parsedGlobal } = global\n\n const instanceTargets: DataTarget[] = []\n for (const workspace of sources.workspaces) {\n for (const declared of this.declaredData(workspace.servers, sources.includePaths)) {\n if (!declared.included)\n continue\n instanceTargets.push({ workspace: workspace.id, path: declared.path, origin: declared.origin })\n }\n }\n\n const archivedIncludePaths = actions.has('global:settings') && parsedGlobal !== null\n ? parsedGlobal.backups.includePaths\n : sources.includePaths\n const archiveAll: DataTarget[] = []\n const archiveTargets: DataTarget[] = []\n for (const [id, servers] of archivedServers) {\n for (const declared of this.declaredData(servers, archivedIncludePaths)) {\n if (!declared.included)\n continue\n const target = { workspace: id, path: declared.path, origin: declared.origin }\n archiveAll.push(target)\n // Only a servers file this restore is applying may name a destination.\n if (actions.has(`workspace:${id}:servers`))\n archiveTargets.push(target)\n }\n }\n\n return { archiveAll, archiveTargets, instanceTargets }\n }\n\n /**\n * Whether the plan must say a restart is needed — computed even for a dry run.\n *\n * Only the panel's own listener does; its servers are re-read from the file.\n */\n private noteRestartRequired(ctx: RestoreContext, global: ArchivedGlobal): void {\n const { plan, sources, actions } = ctx\n const { settingsText, parsedGlobal } = global\n\n if (parsedGlobal !== null && actions.has('global:settings') && settingsText !== null) {\n const currentText = readText(sources.globalSettingsPath)\n const current = readableGlobalSettings(currentText)\n plan.restartRequired = JSON.stringify(parsedGlobal.control) !== JSON.stringify(current === null ? null : (parseGlobalSettings(current).config?.control ?? null))\n }\n }\n\n /**\n * Runs every planned write in order, stopping at the first failure.\n *\n * A partial failure records nothing for the item that failed, then hands the error back so the\n * caller can reload what did land and rethrow — a restore is not transactional, and the plan has\n * to say so.\n */\n private async runApply(ctx: RestoreContext): Promise<unknown> {\n const { plan, actions } = ctx\n\n let failure: unknown = null\n for (const [id, apply] of actions) {\n try {\n await apply()\n }\n catch (error) {\n failure = error\n break\n }\n plan.applied.push(labelOf(plan, id))\n plan.appliedIds.push(id)\n }\n return failure\n }\n\n /**\n * Registers the workspaces this restore created, once their leaves have landed.\n *\n * Last, and only for a workspace something was applied to: a workspace the panel knows about but\n * whose files were never written would be a workspace that exists and is empty, which is worse\n * than one that is plainly absent.\n */\n private registerCreatedWorkspaces(ctx: RestoreContext): void {\n const { plan, createdWorkspaces } = ctx\n\n // The registry entries come last, and only once their leaves landed: a workspace\n // the panel knows about but whose files were never written would be a workspace\n // that exists and is empty, which is worse than one that is plainly absent.\n for (const workspace of createdWorkspaces.values()) {\n if (!plan.appliedIds.some(id => id.startsWith(`workspace:${workspace.id}:`)))\n continue\n this.options.ensureWorkspace?.({ id: workspace.id, label: workspace.label })\n plan.createdWorkspaces.push(workspace.id)\n }\n }\n\n /**\n * Stages each restored dump where its entry can reach it, for that entry's own `load` hook.\n *\n * Staged rather than run: a load hook talks to a server that is answering, and this entry is\n * stopped at this point. The hook runs on its next `start`, once the port accepts a connection.\n *\n * Staged **before** the caller reloads, because the reload reads `pendingLoad` from disk.\n */\n private async stagePendingLoads(ctx: RestoreContext): Promise<void> {\n const { plan, staging, manifest, actions } = ctx\n // The archive's entries, so this cannot be confused with the `archivedServers` the planning\n // phase filled.\n const archivedDumps = manifest.dumps ?? []\n\n const pendingLoads: Array<{ workspaceId: string, serverId: string, staged: string }> = []\n for (const entry of archivedDumps) {\n if (!plan.appliedIds.some(id => id.startsWith(`workspace:${entry.workspaceId}:`)))\n continue\n // Deselecting `workspace:<id>:dump:<server>` must not load it, exactly as for any other item.\n // (`actions` is keyed by item id, and `workspace:<id>` is only ever an alias, never an item.)\n if (!actions.has(`workspace:${entry.workspaceId}:dump:${entry.serverId}`))\n continue\n // The **archive's** config, not the live one: `sources` was read before the restore wrote\n // anything, so it still describes the host as it was. The hooks being restored are the\n // archive's, which is the whole point of a migration onto a blank machine.\n const archivedServers = readArchivedServers(staging, entry.workspaceId)\n const server = archivedServers.find(candidate => candidate.id === entry.serverId)\n // The entry survives the restore (its config came from the archive) but may have no `load`\n // hook: the dump is still restored as a file, and saying so is better than silence.\n if (server?.load === undefined || server.load === null) {\n plan.skipped.push(`the dump for \"${entry.serverId}\" was restored but this entry has no load hook`)\n continue\n }\n const dumpDir = path.join(staging, 'dumps', entry.workspaceId, entry.serverId)\n if (!fs.existsSync(dumpDir)) {\n plan.skipped.push(`the dump for \"${entry.serverId}\" is missing from the archive`)\n continue\n }\n // Staged, not run. A load hook talks to a server that is answering — `mongorestore`,\n // `pg_restore`, `redis-cli` all connect — and this entry is stopped at this point. The dump\n // is copied where the entry can reach it after a restart, and its next `start` runs the hook\n // once the port accepts a connection.\n const staged = path.join(this.options.dataRoot, PENDING_LOAD, entry.workspaceId, entry.serverId)\n await copyTree(dumpDir, staged, () => true)\n pendingLoads.push({ workspaceId: entry.workspaceId, serverId: entry.serverId, staged })\n plan.hooks = [...(plan.hooks ?? []), {\n serverId: entry.serverId,\n workspaceId: entry.workspaceId,\n action: 'load',\n ok: true,\n output: 'staged — runs when this entry next starts',\n }]\n }\n\n for (const load of pendingLoads)\n this.options.onLoadPending?.(load.workspaceId, load.serverId, load.staged)\n }\n\n /** The panel re-reads the restored settings and servers, so what the archive brought exists immediately. */\n private reloadRestored(plan: RestorePlan & { appliedIds: string[] }): void {\n if (this.options.onRestored === undefined || !plan.appliedIds.some(id => RELOADABLE.test(id)))\n return\n plan.reloaded = true\n this.options.onRestored()\n }\n\n /** Selectable entries: the three global slices, then one per workspace. */\n private entries(sources: BackupSources): BackupEntry[] {\n const missing = (path: string, key: string): Pick<BackupEntry, 'note' | 'noteKey'> => {\n const absent = this.missingNote(path)\n return absent === null ? { note: null } : { note: absent, noteKey: key }\n }\n const entries: BackupEntry[] = [\n { id: 'global:settings', label: 'Global settings', labelKey: 'settings.backup.entryGlobalSettings', kind: 'settings', ...missing(sources.globalSettingsPath, 'settings.backup.noteMissing'), items: [] },\n { id: 'global:secrets', label: 'Global secrets (password, API token)', labelKey: 'settings.backup.entryGlobalSecrets', kind: 'secrets', ...missing(sources.globalSecretsPath, 'settings.backup.noteMissing'), items: this.secretItems('global', 'global:secrets', sources.globalSecretsPath) },\n { id: 'global:tls', label: 'TLS certificate', labelKey: 'settings.backup.entryTlsCertificate', kind: 'tls', ...missing(sources.tlsDir, 'settings.backup.noteMissing'), items: [] },\n ]\n\n for (const workspace of sources.workspaces) {\n entries.push({\n id: `workspace:${workspace.id}`,\n label: workspace.label,\n kind: 'workspace',\n workspaceId: workspace.id,\n note: null,\n items: this.workspaceItems(workspace, sources.includePaths),\n })\n }\n\n return entries\n }\n\n /**\n * One leaf per secret the file actually holds, so a restore can bring back the\n * password without the API token, or the Telegram token without the DDNS credentials.\n *\n * The set comes from the file's own top-level keys rather than a list here, so a\n * secret added later appears on its own — the failure mode of a second list is a\n * secret that can be captured but never restored individually.\n */\n private secretItems(scope: SecretScope, entryId: string, path: string): BackupEntry['items'] {\n const present = presentSecretKeys(parseSecrets(readText(path) ?? ''))\n const parts = secretParts(scope, present)\n // Every slot this release knows is listed, set or not: \"API token\" is a feature the panel has\n // whether or not one is minted, and hiding the row made its absence look like a missing feature\n // rather than an unset value. An unknown key in the file is listed too, as its own name.\n const known = KNOWN_SECRET_KEYS[scope]\n const missing = known.filter(key => !parts.some(part => part.key === key))\n return [\n ...parts.map(part => ({\n id: `${entryId}:${part.key}`,\n label: SECRET_LABELS[part.key]?.en ?? part.key,\n // A known secret gets a translated label and a hint saying what restoring it does;\n // an unknown one reads as its own key, which is still better than hiding it.\n ...(SECRET_LABELS[part.key] === undefined ? {} : { labelKey: SECRET_LABELS[part.key]!.key }),\n kind: 'secrets' as const,\n secret: part.key,\n included: true,\n note: null,\n })),\n ...missing.map(key => ({\n id: `${entryId}:${key}`,\n label: SECRET_LABELS[key]?.en ?? key,\n ...(SECRET_LABELS[key] === undefined ? {} : { labelKey: SECRET_LABELS[key]!.key }),\n kind: 'secrets' as const,\n secret: key,\n included: false,\n // The same wording and the same key as a missing file: both mean \"this release knows about\n // it and there is nothing here yet\". A second phrase for the same idea was the inconsistency.\n note: 'not set',\n noteKey: 'settings.backup.noteMissing',\n })),\n ]\n }\n\n private workspaceItems(workspace: BackupWorkspaceSource, includePaths: string[]): BackupEntry['items'] {\n const id = workspace.id\n const note = (path: string): Pick<BackupEntry['items'][number], 'note' | 'noteKey'> => {\n const absent = this.missingNote(path)\n return absent === null ? { note: null } : { note: absent, noteKey: 'settings.backup.noteMissing' }\n }\n const items: BackupEntry['items'] = [\n { id: `workspace:${id}:settings`, label: 'Settings', labelKey: 'settings.backup.leafSettings', kind: 'settings', included: true, ...note(workspace.settingsPath) },\n { id: `workspace:${id}:servers`, label: 'Servers', labelKey: 'settings.backup.leafServers', kind: 'servers', included: true, ...note(workspace.serversPath) },\n // The whole file keeps its own leaf — that id is what older clients send — and the\n // per-secret leaves beside it are what let one secret come back on its own.\n { id: `workspace:${id}:secrets`, label: 'Secrets', labelKey: 'settings.backup.leafSecrets', kind: 'secrets', included: true, ...note(workspace.secretsPath) },\n // One leaf per secret rather than one for the whole file, so restoring the Telegram\n // token cannot silently reinstate the DDNS credentials alongside it.\n ...this.secretItems('workspace', `workspace:${id}:secrets`, workspace.secretsPath),\n ]\n\n for (const declared of this.declaredData(workspace.servers, includePaths)) {\n items.push({\n id: `workspace:${id}:data:${declared.path}`,\n label: declared.path,\n kind: 'data',\n path: declared.path,\n origin: declared.origin,\n included: declared.included,\n note: declared.note,\n ...(declared.noteKey === undefined ? {} : { noteKey: declared.noteKey }),\n ...(declared.noteParams === undefined ? {} : { noteParams: declared.noteParams }),\n ignoreGenerated: declared.ignoreGenerated,\n })\n }\n\n return items\n }\n\n /**\n * Declared data paths with the archive-directory veto applied: capturing a\n * directory that contains the archive directory would make the archive\n * contain itself.\n */\n private declaredData(servers: ServerConfig[], includePaths: string[]): BackupPath[] {\n const archiveDir = path.resolve(this.resolveDir())\n return resolveBackupPaths(servers, includePaths, this.backupVars(servers)).map((entry) => {\n if (entry.included && isInside(entry.path, archiveDir))\n return { ...entry, included: false, note: 'contains the backup directory', noteKey: 'settings.backup.noteContainsBackupDir' }\n return entry\n })\n }\n\n /** The `{dataRoot}` a config expands to, without a module-level state root. */\n private backupVars(servers: ServerConfig[]): BackupVars {\n const first = servers[0]\n return {\n projectDir,\n // A server carries the panel's real `dataRoot`; the `.hh` directory the\n // panel hands us for `backups.dir` sits directly under it.\n dataRoot: first === undefined\n ? path.dirname(path.resolve(this.options.dataRoot))\n : String(serverTemplateVars(first).dataRoot ?? projectDir),\n home: os.homedir(),\n }\n }\n\n /**\n * Reclaims the staging trees a killed backup left behind.\n *\n * `create()` removes its staging on success and in a `catch`, which covers every failure it can\n * observe — but a `SIGKILL`, a power cut or a container stop never returns to run the `catch`.\n * Measured on a real home with a 60 MB data path: two interrupted runs left two `.staging-*`\n * trees, **121 MB** beside a single 184 B archive. `scan()` filters on `.zip` and `prune()` walks\n * `list()`, so nothing listed them and nothing removed them — the debris of a failed attempt\n * holding the free space the next one needs, on the disk that already filled.\n *\n * The owner's pid decides it, never an age: another run sharing this directory is *live*, not\n * stale, and deleting its tree would destroy a capture in progress. `isProcessAlive` is the same\n * predicate every other liveness question here asks.\n *\n * Both trees this service stages are swept — a capture and a restore — because the leak is the\n * shape, not one call site. A restore's tree holds an unpacked copy of an archive, so it is the\n * larger of the two.\n */\n private sweepStaging(): void {\n const dir = this.resolveDir()\n let names: string[]\n try {\n names = fs.readdirSync(dir)\n }\n catch {\n return\n }\n\n for (const name of names) {\n const owner = stagingOwner(name)\n if (owner === null || owner === process.pid || isProcessAlive(owner))\n continue\n try {\n fs.rmSync(path.join(dir, name), { recursive: true, force: true })\n }\n catch {\n // A tree this process may not remove is the next run's attempt, not a backup failure.\n }\n }\n }\n\n /** Newest-first listing, without the encryption flag, which needs a read. */\n private scan(): Array<Omit<BackupFile, 'encrypted'>> {\n const dir = this.resolveDir()\n let names: string[] = []\n try {\n names = fs.readdirSync(dir)\n }\n catch {\n return []\n }\n\n return names\n .filter(name => name.endsWith(SUFFIX))\n .flatMap((name) => {\n try {\n const stats = fs.statSync(path.join(dir, name))\n return [{ name, sizeBytes: stats.size, createdAt: archiveStamp(name) ?? Math.round(stats.mtimeMs) }]\n }\n catch {\n return []\n }\n })\n .sort((a, b) => b.createdAt - a.createdAt)\n }\n\n /** Single-flight: a state frame must never queue a pile of reads. */\n private scheduleRefresh(): Promise<void> {\n this.refreshing ??= this.refresh().finally(() => {\n this.refreshing = null\n })\n return this.refreshing\n }\n\n private async refresh(): Promise<void> {\n const dir = this.resolveDir()\n const listed = this.scan()\n\n for (const file of listed) {\n const key = cacheKey(file)\n if (this.flags.get(file.name)?.key === key)\n continue\n try {\n const entries = await listZip(path.join(dir, file.name))\n this.flags.set(file.name, { key, encrypted: entries.some(entry => entry.encrypted) })\n }\n catch {\n // Unreadable stays unmarked here; restoring it reports the real reason.\n this.flags.set(file.name, { key, encrypted: false })\n }\n }\n\n const present = new Set(listed.map(file => file.name))\n for (const name of [...this.flags.keys()]) {\n if (!present.has(name))\n this.flags.delete(name)\n }\n }\n\n private missingNote(target: string): string | null {\n return fs.existsSync(target) ? null : 'not set'\n }\n\n /** Copies one source into the staging tree; false when there was nothing there. */\n private async copyInto(staging: string, relative: string, source: string, ignoreGenerated = false): Promise<boolean> {\n if (!fs.existsSync(source))\n return false\n const target = path.join(staging, relative)\n ensureStateDir(path.dirname(target))\n // Never copy the archive directory into itself, however broad a declared\n // path is (the copy would walk it while writing into it). Both resolved: `copyTree` walks the\n // real path of a declared root that is itself a link.\n const archiveDir = resolveExisting(path.resolve(this.resolveDir()))\n const root = resolveExisting(path.resolve(source))\n await copyTree(source, target, (from) => {\n const resolved = path.resolve(from)\n if (isInside(archiveDir, resolved))\n return false\n // A declared tree may well contain a state directory; its secrets never travel raw, and neither\n // does the half-written copy a crashed atomic write leaves behind.\n if (isSecretDocument(path.basename(resolved)))\n return false\n if (!ignoreGenerated || resolved === root)\n return true\n return !isGeneratedPath(path.relative(root, resolved))\n })\n return true\n }\n\n /**\n * Drops the oldest archives past their own limit.\n *\n * Two budgets, because the two sources are not the same thing: `keep` is what a person\n * agreed to store, and pruning a hand-taken archive to make room for a scheduled one would\n * lose the copy they deliberately made. The scheduled pair keeps `schedule.keep` automatic\n * archives; the rest keeps `keep`.\n */\n private prune(): void {\n const config = this.options.getConfig()\n const files = this.list()\n const automatic = files.filter(isAutomatic)\n const manual = files.filter(file => ARCHIVE_NAME.exec(file.name)?.[1] === MANUAL_PREFIX)\n\n for (const file of automatic.slice(config.schedule.keep)) this.remove(file.name)\n for (const file of manual.slice(config.keep)) this.remove(file.name)\n this.sweepPartials()\n }\n\n /**\n * An archive killed mid-write leaves its `.<name>.partial` behind (`createZip` renames only on\n * success). An hour old is never a write in progress — a live one keeps touching its mtime.\n */\n private sweepPartials(now = Date.now()): void {\n const dir = this.resolveDir()\n let names: string[] = []\n try {\n names = fs.readdirSync(dir)\n }\n catch {\n return\n }\n for (const name of names.filter(entry => entry.startsWith('.') && entry.endsWith(`${SUFFIX}.partial`))) {\n const file = path.join(dir, name)\n try {\n if (now - fs.statSync(file).mtimeMs > 60 * 60_000)\n fs.rmSync(file, { force: true })\n }\n catch {\n // gone already, or not ours to remove\n }\n }\n }\n\n /** When the newest automatic archive was written, or null when there is none. */\n private lastAutomatic(): number | null {\n const dir = this.resolveDir()\n if (this.lastAutomaticSeen?.dir !== dir)\n this.lastAutomaticSeen = { dir, at: this.scan().find(isAutomatic)?.createdAt ?? null }\n return this.lastAutomaticSeen.at\n }\n\n /**\n * Runs one scheduled pass when it is due. Modelled on the DDNS pass: cheap to call on every\n * panel tick, never blocking, and never two at once.\n */\n tick(now = Date.now()): void {\n if (this.disposed || this.running)\n return\n const config = this.options.getConfig()\n if (!config.enabled || config.schedule.intervalMs <= 0)\n return\n\n // The newest archive is the durable clock; the last attempt bounds a pass that wrote none.\n const last = this.lastAutomatic()\n const latest = last === null ? this.lastAttemptAt : Math.max(last, this.lastAttemptAt ?? 0)\n if (latest !== null && now - latest < config.schedule.intervalMs)\n return\n\n // A pass now would capture a half-restored tree; wait for the restore, without spending the attempt.\n const restoring = restoreLockHolder(this.options.dataRoot)\n if (restoring !== null) {\n if (!this.deferredForRestore)\n logger.info(`the scheduled backup is waiting for the restore that is running (pid ${restoring.pid})`)\n this.deferredForRestore = true\n return\n }\n this.deferredForRestore = false\n\n this.running = true\n this.lastAttemptAt = now\n // The configured scope, in the same `include`/`exclude` spelling a person types: an omitted\n // scope is the full default this pass has always taken, so an older config captures exactly\n // what it captured before.\n //\n // An id that no longer names anything (a workspace deleted since it was written) contributes\n // nothing, which is what it means in both modes. A `only` scope that has consequently lost\n // everything still meets `create`'s \"nothing was selected\" refusal, so a schedule that stopped\n // capturing says so on the page instead of writing archive after empty archive.\n void this.create({ automatic: true, ...scopeSelection(config.schedule.scope) })\n .then((result) => {\n // Remembered, not just logged: the page has nowhere else to show this, and a schedule\n // failing silently is indistinguishable from one that has not come due.\n if (result.ok) {\n this.scheduleError = null\n for (const warning of result.warnings ?? [])\n logger.warn('the scheduled backup', warning)\n return\n }\n this.scheduleError = { message: result.error ?? 'the scheduled backup failed', at: Date.now() }\n logger.warn('the scheduled backup failed', result.error)\n })\n .catch((error: unknown) => {\n this.scheduleError = { message: errorMessage(error), at: Date.now() }\n logger.error('the scheduled backup failed', error)\n })\n .finally(() => {\n this.running = false\n })\n }\n\n private resolveDir(): string {\n const configured = this.options.getConfig().dir\n return path.isAbsolute(configured) ? configured : path.resolve(this.options.dataRoot, configured)\n }\n}\n\n/** Whether an archive came from the schedule rather than from a person. */\nfunction isAutomatic(file: { name: string }): boolean {\n return ARCHIVE_NAME.exec(file.name)?.[1] === AUTO_PREFIX\n}\n\n/** The label of one item, for `applied`; items are built before actions run. */\nfunction labelOf(plan: RestorePlan, id: string): string {\n return plan.items.find(item => item.id === id)?.label ?? id\n}\n\n/**\n * Restores only `fields` from an archived secrets document into a live one.\n *\n * The archive may predate a secret the live file holds, and the live file may hold one\n * the archive never carried: merging by field is what makes restoring the Telegram token\n * leave the DDNS credentials alone, and what clears a secret the archive does not carry\n * rather than leaving the newer value behind as if it had been restored.\n */\nfunction mergeIntoFile(target: string, archived: string, fields: string[]): void {\n const current = parseSecrets(readText(target) ?? '')\n const merged = mergeSecrets(current, parseSecrets(archived), fields)\n writeFileAtomic(target, `${JSON.stringify(merged, null, 2)}\\n`, { mode: 0o600 })\n}\n\n/**\n * What an archive says about where it came from. Both fields are absent on an archive\n * written before they existed, so a UI shows the row only when there is something to show.\n */\nfunction manifestInfo(manifest: BackupManifest): NonNullable<RestorePlan['archive']> {\n return {\n ...(manifest.writtenBy === undefined ? {} : { writtenBy: manifest.writtenBy }),\n ...(manifest.schema === undefined ? {} : { schema: manifest.schema }),\n }\n}\n\n/**\n * `servers.config.json` is only a readability gate here: the store applies the\n * workspace's own defaults on the next load, and an archive from another machine\n * need not match this one's default shapes exactly.\n *\n * An older archive is lifted to this release's schema first, so its entries are adopted rather\n * than dropped; `null` means this release cannot read it at all.\n */\nfunction readableServersFile(text: string): ServerConfig[] | null {\n try {\n const lifted = liftArchived(JSON.parse(text))\n if (lifted === null)\n return null\n const result = parseServersFile(lifted, {})\n return result.errors.length === 0 ? result.servers : null\n }\n catch {\n return null\n }\n}\n\n/** A workspace settings file is adopted only when this release can read it, lifted when older. */\nfunction readableWorkspaceSettings(text: string): Record<string, unknown> | null {\n try {\n const lifted = liftArchived(JSON.parse(text))\n return lifted !== null && parseWorkspaceSettings(lifted).config !== null ? lifted : null\n }\n catch {\n return null\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;AA0FA,SAAgB,UAAU,SAAiB,SAA8B;CACvE,OAAO;EAAE,IAAI;EAAM;EAAS;CAAQ;AACtC;AAEA,SAAgB,OAAO,OAAe,YAAY,OAAmB;CACnE,OAAO;EAAE,IAAI;EAAO,SAAS;EAAO,SAAS;EAAO;EAAO,GAAI,YAAY,EAAE,WAAW,KAAK,IAAI,CAAC;CAAG;AACvG;;;;;;;;;AAUA,eAAsB,MAAM,UAAoB,QAAyC;CACvF,IAAI,CAAC,SAAS,IACZ,OAAO,OAAO,MAAM,UAAU,QAAQ,CAAC;CACzC,OAAO,UAAU,OAAO,OAAO,KAAK,GAAG,OAAO,KAAK,MAAM,OAAO,MAAM,IAAI;AAC5E;;AAGA,SAAgB,cAAc,aAA4C,MAA+B;CACvG,MAAM,UAAU,KAAK,QAAO,SAAQ,cAAc,QAAQ,GAAA,CAAI,KAAK,CAAC,CAAC,WAAW,CAAC;CACjF,OAAO,QAAQ,WAAW,IAAI,OAAO,OAAO,QAAQ,KAAK,IAAI;AAC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