home-hosted 0.10.3 → 0.12.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 (317) hide show
  1. package/README.md +273 -628
  2. package/dist/chunks/archive-DpCwA8Nf.js +339 -0
  3. package/dist/chunks/archive-DpCwA8Nf.js.map +1 -0
  4. package/dist/chunks/atomic-CEfCUfkQ.js +25 -0
  5. package/dist/chunks/atomic-CEfCUfkQ.js.map +1 -0
  6. package/dist/chunks/backup-CPrJVPJI.js +797 -0
  7. package/dist/chunks/backup-CPrJVPJI.js.map +1 -0
  8. package/dist/chunks/backups-Bd2SF2qd.js +4346 -0
  9. package/dist/chunks/backups-Bd2SF2qd.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-ku5ypHXJ.js +2256 -0
  13. package/dist/chunks/contracts-ku5ypHXJ.js.map +1 -0
  14. package/dist/chunks/daemon-TwXk5vb8.js +215 -0
  15. package/dist/chunks/daemon-TwXk5vb8.js.map +1 -0
  16. package/dist/chunks/daemon-log-BVj8cDEo.js +241 -0
  17. package/dist/chunks/daemon-log-BVj8cDEo.js.map +1 -0
  18. package/dist/chunks/docker-CGv4Uv7w.js +436 -0
  19. package/dist/chunks/docker-CGv4Uv7w.js.map +1 -0
  20. package/dist/chunks/down-BlX5X3bm.js +378 -0
  21. package/dist/chunks/down-BlX5X3bm.js.map +1 -0
  22. package/dist/chunks/init-DdmqHVra.js +263 -0
  23. package/dist/chunks/init-DdmqHVra.js.map +1 -0
  24. package/dist/chunks/last-stop-BZ08Z89-.js +52 -0
  25. package/dist/chunks/last-stop-BZ08Z89-.js.map +1 -0
  26. package/dist/chunks/layout-D74TGUnr.js +24 -0
  27. package/dist/chunks/layout-D74TGUnr.js.map +1 -0
  28. package/dist/chunks/log-buffer-HnP0jKhZ.js +350 -0
  29. package/dist/chunks/log-buffer-HnP0jKhZ.js.map +1 -0
  30. package/dist/chunks/logger-B5U4GD3j.js +13 -0
  31. package/dist/chunks/logger-B5U4GD3j.js.map +1 -0
  32. package/dist/chunks/logs-gI_69Q1P.js +265 -0
  33. package/dist/chunks/logs-gI_69Q1P.js.map +1 -0
  34. package/dist/chunks/migrate-BTlsibvF.js +155 -0
  35. package/dist/chunks/migrate-BTlsibvF.js.map +1 -0
  36. package/dist/chunks/nanny-20aBXL1o.js +1069 -0
  37. package/dist/chunks/nanny-20aBXL1o.js.map +1 -0
  38. package/dist/chunks/nanny-CjnnrIpm.js +132 -0
  39. package/dist/chunks/nanny-CjnnrIpm.js.map +1 -0
  40. package/dist/chunks/nanny-DUaAfCV-.js +39 -0
  41. package/dist/chunks/nanny-DUaAfCV-.js.map +1 -0
  42. package/dist/chunks/nanny-sweep-Ca9kPAVi.js +104 -0
  43. package/dist/chunks/nanny-sweep-Ca9kPAVi.js.map +1 -0
  44. package/dist/chunks/nearest-6KgQEDUe.js +41 -0
  45. package/dist/chunks/nearest-6KgQEDUe.js.map +1 -0
  46. package/dist/chunks/parse-B9owE47G.js +383 -0
  47. package/dist/chunks/parse-B9owE47G.js.map +1 -0
  48. package/dist/chunks/paths-BT94q6-w.js +172 -0
  49. package/dist/chunks/paths-BT94q6-w.js.map +1 -0
  50. package/dist/chunks/port-B8WBTRMk.js +333 -0
  51. package/dist/chunks/port-B8WBTRMk.js.map +1 -0
  52. package/dist/chunks/restart-UZgeDukG.js +126 -0
  53. package/dist/chunks/restart-UZgeDukG.js.map +1 -0
  54. package/dist/chunks/rolldown-runtime-D7D4PA-g.js +13 -0
  55. package/dist/chunks/schema-o7Lgk0V1.js +102 -0
  56. package/dist/chunks/schema-o7Lgk0V1.js.map +1 -0
  57. package/dist/chunks/secrets-D7PdYh71.js +544 -0
  58. package/dist/chunks/secrets-D7PdYh71.js.map +1 -0
  59. package/dist/chunks/server-BuIeSsRu.js +169 -0
  60. package/dist/chunks/server-BuIeSsRu.js.map +1 -0
  61. package/dist/chunks/server-ids-DRuNLVCV.js +32 -0
  62. package/dist/chunks/server-ids-DRuNLVCV.js.map +1 -0
  63. package/dist/chunks/set-password-DegMumPh.js +43 -0
  64. package/dist/chunks/set-password-DegMumPh.js.map +1 -0
  65. package/dist/chunks/set-token-21d1FTDC.js +78 -0
  66. package/dist/chunks/set-token-21d1FTDC.js.map +1 -0
  67. package/dist/chunks/settings-BVSBnIwJ.js +332 -0
  68. package/dist/chunks/settings-BVSBnIwJ.js.map +1 -0
  69. package/dist/chunks/setup-temp-XiuAtiW2.js +150 -0
  70. package/dist/chunks/setup-temp-XiuAtiW2.js.map +1 -0
  71. package/dist/chunks/shape-DnTKzjQ2.js +24 -0
  72. package/dist/chunks/shape-DnTKzjQ2.js.map +1 -0
  73. package/dist/chunks/src-BL97vLVb.js +11153 -0
  74. package/dist/chunks/src-BL97vLVb.js.map +1 -0
  75. package/dist/chunks/status-EuWdRq8Q.js +119 -0
  76. package/dist/chunks/status-EuWdRq8Q.js.map +1 -0
  77. package/dist/chunks/ui-DbPuwddJ.js +323 -0
  78. package/dist/chunks/ui-DbPuwddJ.js.map +1 -0
  79. package/dist/chunks/ui-dir-CsU3uLNV.js +39 -0
  80. package/dist/chunks/ui-dir-CsU3uLNV.js.map +1 -0
  81. package/dist/chunks/ui-release-DKzVvlLd.js +312 -0
  82. package/dist/chunks/ui-release-DKzVvlLd.js.map +1 -0
  83. package/dist/chunks/ui-revert-BhqOAhmM.js +27 -0
  84. package/dist/chunks/ui-revert-BhqOAhmM.js.map +1 -0
  85. package/dist/chunks/ui-switch-CMoslPO2.js +150 -0
  86. package/dist/chunks/ui-switch-CMoslPO2.js.map +1 -0
  87. package/dist/chunks/ui-update-TTBBoDik.js +272 -0
  88. package/dist/chunks/ui-update-TTBBoDik.js.map +1 -0
  89. package/dist/chunks/up-C4H13hBw.js +196 -0
  90. package/dist/chunks/up-C4H13hBw.js.map +1 -0
  91. package/dist/chunks/usage-CSBgLRN5.js +85 -0
  92. package/dist/chunks/usage-CSBgLRN5.js.map +1 -0
  93. package/dist/chunks/workspaces-CAln2sQ7.js +221 -0
  94. package/dist/chunks/workspaces-CAln2sQ7.js.map +1 -0
  95. package/dist/chunks/wsl-temperature-BiCI4iK6.js +322 -0
  96. package/dist/chunks/wsl-temperature-BiCI4iK6.js.map +1 -0
  97. package/dist/cli.js +229 -24861
  98. package/dist/cli.js.map +1 -1
  99. package/dist/client.js +120 -0
  100. package/dist/client.js.map +1 -0
  101. package/dist/types/api/acme.d.ts +24 -0
  102. package/dist/types/api/auth/$.routes.d.ts +103 -0
  103. package/dist/types/api/backups.d.ts +179 -0
  104. package/dist/types/api/control.d.ts +469 -0
  105. package/dist/types/api/ddns.d.ts +432 -0
  106. package/dist/types/api/events.d.ts +21 -0
  107. package/dist/types/api/health.d.ts +27 -0
  108. package/dist/types/api/logs.d.ts +95 -0
  109. package/dist/types/api/metrics.d.ts +19 -0
  110. package/dist/types/api/notifications.d.ts +141 -0
  111. package/dist/types/api/proxy.d.ts +1128 -0
  112. package/dist/types/api/servers/$.routes.d.ts +1318 -0
  113. package/dist/types/api/settings.d.ts +642 -0
  114. package/dist/types/api/state.d.ts +492 -0
  115. package/dist/types/api/static.d.ts +11 -0
  116. package/dist/types/api/tls.d.ts +112 -0
  117. package/dist/types/api/workspaces/$.routes.d.ts +797 -0
  118. package/dist/types/api/wsl-temperature.d.ts +113 -0
  119. package/dist/types/app.d.ts +6080 -0
  120. package/dist/types/cli/args.d.ts +75 -0
  121. package/dist/types/cli/backup-offline.d.ts +23 -0
  122. package/dist/types/cli/backup.d.ts +79 -0
  123. package/dist/types/cli/down.d.ts +75 -0
  124. package/dist/types/cli/init.d.ts +60 -0
  125. package/dist/types/cli/io.d.ts +65 -0
  126. package/dist/types/cli/logs.d.ts +64 -0
  127. package/dist/types/cli/migrate.d.ts +33 -0
  128. package/dist/types/cli/nanny.d.ts +19 -0
  129. package/dist/types/cli/nearest.d.ts +10 -0
  130. package/dist/types/cli/restart.d.ts +42 -0
  131. package/dist/types/cli/server.d.ts +68 -0
  132. package/dist/types/cli/set-password.d.ts +14 -0
  133. package/dist/types/cli/set-token.d.ts +21 -0
  134. package/dist/types/cli/setup-temp.d.ts +65 -0
  135. package/dist/types/cli/status.d.ts +14 -0
  136. package/dist/types/cli/ui-revert.d.ts +3 -0
  137. package/dist/types/cli/ui-switch.d.ts +27 -0
  138. package/dist/types/cli/ui-update.d.ts +72 -0
  139. package/dist/types/cli/up.d.ts +90 -0
  140. package/dist/types/cli/usage.d.ts +23 -0
  141. package/dist/types/cli.d.ts +12 -0
  142. package/dist/types/client.d.ts +6284 -0
  143. package/dist/types/config/layout.d.ts +11 -0
  144. package/dist/types/config/migrations.d.ts +69 -0
  145. package/dist/types/config/parse.d.ts +54 -0
  146. package/dist/types/config/patch.d.ts +20 -0
  147. package/dist/types/config/schema.d.ts +318 -0
  148. package/dist/types/config/secret-parts.d.ts +48 -0
  149. package/dist/types/config/secrets.d.ts +206 -0
  150. package/dist/types/config/seed.d.ts +30 -0
  151. package/dist/types/config/server-ids.d.ts +14 -0
  152. package/dist/types/config/settings.d.ts +74 -0
  153. package/dist/types/config/store.d.ts +132 -0
  154. package/dist/types/config/workspaces.d.ts +96 -0
  155. package/dist/types/helpers/action-result.d.ts +46 -0
  156. package/dist/types/helpers/atomic.d.ts +9 -0
  157. package/dist/types/helpers/backoff.d.ts +7 -0
  158. package/dist/types/helpers/bind.d.ts +16 -0
  159. package/dist/types/helpers/config-text.d.ts +23 -0
  160. package/dist/types/helpers/cookies.d.ts +19 -0
  161. package/dist/types/helpers/copy-tree.d.ts +15 -0
  162. package/dist/types/helpers/daemon-log.d.ts +45 -0
  163. package/dist/types/helpers/daemon.d.ts +122 -0
  164. package/dist/types/helpers/deferred.d.ts +7 -0
  165. package/dist/types/helpers/env-file.d.ts +20 -0
  166. package/dist/types/helpers/error.d.ts +18 -0
  167. package/dist/types/helpers/factory.d.ts +6 -0
  168. package/dist/types/helpers/last-stop.d.ts +20 -0
  169. package/dist/types/helpers/logger.d.ts +7 -0
  170. package/dist/types/helpers/open.d.ts +2 -0
  171. package/dist/types/helpers/openapi.d.ts +46 -0
  172. package/dist/types/helpers/paths.d.ts +94 -0
  173. package/dist/types/helpers/restore-lock.d.ts +32 -0
  174. package/dist/types/helpers/runtime.d.ts +18 -0
  175. package/dist/types/helpers/secret-compare.d.ts +13 -0
  176. package/dist/types/helpers/shell.d.ts +19 -0
  177. package/dist/types/helpers/sse.d.ts +23 -0
  178. package/dist/types/helpers/template.d.ts +8 -0
  179. package/dist/types/helpers/ui-dir.d.ts +11 -0
  180. package/dist/types/helpers/validate.d.ts +7 -0
  181. package/dist/types/helpers/validator.d.ts +12 -0
  182. package/dist/types/helpers/version.d.ts +10 -0
  183. package/dist/types/helpers/workspace.d.ts +25 -0
  184. package/dist/types/index.d.ts +17 -0
  185. package/dist/types/middleware/auth.d.ts +37 -0
  186. package/dist/types/middleware/host.d.ts +29 -0
  187. package/dist/types/middleware/loopback.d.ts +18 -0
  188. package/dist/types/openapi-reference.d.ts +22 -0
  189. package/dist/types/openapi.d.ts +34 -0
  190. package/dist/types/providers/archive.d.ts +54 -0
  191. package/dist/types/providers/backup-hook.d.ts +34 -0
  192. package/dist/types/providers/ddns/cloudflare.d.ts +2 -0
  193. package/dist/types/providers/ddns/desec.d.ts +2 -0
  194. package/dist/types/providers/ddns/digitalocean.d.ts +2 -0
  195. package/dist/types/providers/ddns/duckdns.d.ts +2 -0
  196. package/dist/types/providers/ddns/dyndns2.d.ts +15 -0
  197. package/dist/types/providers/ddns/dynu.d.ts +2 -0
  198. package/dist/types/providers/ddns/freedns.d.ts +2 -0
  199. package/dist/types/providers/ddns/gandi.d.ts +2 -0
  200. package/dist/types/providers/ddns/godaddy.d.ts +2 -0
  201. package/dist/types/providers/ddns/henet.d.ts +3 -0
  202. package/dist/types/providers/ddns/index.d.ts +12 -0
  203. package/dist/types/providers/ddns/ip.d.ts +27 -0
  204. package/dist/types/providers/ddns/namecheap-api.d.ts +13 -0
  205. package/dist/types/providers/ddns/namecheap.d.ts +6 -0
  206. package/dist/types/providers/ddns/noip.d.ts +2 -0
  207. package/dist/types/providers/ddns/porkbun.d.ts +2 -0
  208. package/dist/types/providers/ddns/spaceship.d.ts +7 -0
  209. package/dist/types/providers/ddns/types.d.ts +98 -0
  210. package/dist/types/providers/ddns/zone.d.ts +11 -0
  211. package/dist/types/providers/docker.d.ts +117 -0
  212. package/dist/types/providers/entry-state.d.ts +15 -0
  213. package/dist/types/providers/health-check.d.ts +27 -0
  214. package/dist/types/providers/host.d.ts +147 -0
  215. package/dist/types/providers/identity.d.ts +54 -0
  216. package/dist/types/providers/log-tail.d.ts +29 -0
  217. package/dist/types/providers/nanny-sweep.d.ts +51 -0
  218. package/dist/types/providers/nanny.d.ts +94 -0
  219. package/dist/types/providers/port.d.ts +142 -0
  220. package/dist/types/providers/proc.d.ts +116 -0
  221. package/dist/types/providers/process.d.ts +61 -0
  222. package/dist/types/providers/proxy/caddy.d.ts +2 -0
  223. package/dist/types/providers/proxy/index.d.ts +7 -0
  224. package/dist/types/providers/proxy/types.d.ts +54 -0
  225. package/dist/types/providers/server-vars.d.ts +4 -0
  226. package/dist/types/providers/telegram.d.ts +32 -0
  227. package/dist/types/providers/ui-release.d.ts +113 -0
  228. package/dist/types/providers/webhook.d.ts +64 -0
  229. package/dist/types/providers/wsl-temperature.d.ts +69 -0
  230. package/dist/types/services/acme-challenge.d.ts +44 -0
  231. package/dist/types/services/auth.d.ts +145 -0
  232. package/dist/types/services/backups.d.ts +352 -0
  233. package/dist/types/services/config-watch.d.ts +40 -0
  234. package/dist/types/services/control-server.d.ts +58 -0
  235. package/dist/types/services/ddns.d.ts +67 -0
  236. package/dist/types/services/dependencies.d.ts +21 -0
  237. package/dist/types/services/events.d.ts +17 -0
  238. package/dist/types/services/exposure.d.ts +33 -0
  239. package/dist/types/services/history.d.ts +36 -0
  240. package/dist/types/services/host-monitor.d.ts +32 -0
  241. package/dist/types/services/init.d.ts +71 -0
  242. package/dist/types/services/log-buffer.d.ts +28 -0
  243. package/dist/types/services/log-files.d.ts +87 -0
  244. package/dist/types/services/log-relay.d.ts +36 -0
  245. package/dist/types/services/nanny.d.ts +14 -0
  246. package/dist/types/services/notifications.d.ts +124 -0
  247. package/dist/types/services/panel.d.ts +194 -0
  248. package/dist/types/services/proxy-config.d.ts +83 -0
  249. package/dist/types/services/proxy.d.ts +454 -0
  250. package/dist/types/services/state.d.ts +41 -0
  251. package/dist/types/services/supervisor/compose.d.ts +17 -0
  252. package/dist/types/services/supervisor/entry.d.ts +139 -0
  253. package/dist/types/services/supervisor/health.d.ts +55 -0
  254. package/dist/types/services/supervisor/pending-load.d.ts +6 -0
  255. package/dist/types/services/supervisor/persistent.d.ts +55 -0
  256. package/dist/types/services/supervisor/port-preflight.d.ts +45 -0
  257. package/dist/types/services/supervisor/records.d.ts +38 -0
  258. package/dist/types/services/supervisor/spawn.d.ts +15 -0
  259. package/dist/types/services/supervisor/view.d.ts +4 -0
  260. package/dist/types/services/supervisor.d.ts +113 -0
  261. package/dist/types/services/tls.d.ts +48 -0
  262. package/dist/types/services/ui-update.d.ts +44 -0
  263. package/dist/types/services/ui.d.ts +50 -0
  264. package/dist/types/shared/api-client.d.ts +137 -0
  265. package/dist/types/shared/backup-scope.d.ts +109 -0
  266. package/dist/types/shared/clone.d.ts +14 -0
  267. package/dist/types/shared/contracts.d.ts +4233 -0
  268. package/dist/types/shared/cpu-scale.d.ts +25 -0
  269. package/dist/types/shared/ddns-form.d.ts +62 -0
  270. package/dist/types/shared/endpoint.d.ts +8 -0
  271. package/dist/types/shared/error-message.d.ts +8 -0
  272. package/dist/types/shared/fields.d.ts +21 -0
  273. package/dist/types/shared/generated.d.ts +26 -0
  274. package/dist/types/shared/host-readings.d.ts +185 -0
  275. package/dist/types/shared/patch-diff.d.ts +94 -0
  276. package/dist/types/shared/probe-latency.d.ts +25 -0
  277. package/dist/types/shared/proxy-form.d.ts +182 -0
  278. package/dist/types/shared/server-attention.d.ts +37 -0
  279. package/dist/types/shared/server-key.d.ts +13 -0
  280. package/dist/types/shared/server-readings.d.ts +55 -0
  281. package/dist/types/shared/server-url.d.ts +43 -0
  282. package/dist/types/shared/shape.d.ts +17 -0
  283. package/dist/types/shared/ui-format.d.ts +89 -0
  284. package/docs/API.md +180 -0
  285. package/docs/BACKUPS.md +97 -0
  286. package/docs/CLI.md +122 -0
  287. package/docs/DDNS.md +12 -3
  288. package/docs/NOTIFICATIONS.md +3 -1
  289. package/docs/RESTORE_DEMO.md +6 -4
  290. package/docs/REVERSE_PROXY.md +2 -2
  291. package/docs/SECURITY.md +82 -0
  292. package/docs/SERVERS.md +47 -15
  293. package/docs/UI_CREATION.md +82 -286
  294. package/package.json +18 -9
  295. package/uis/stock/dist/assets/de-DyGrM1KK.js +1 -0
  296. package/uis/stock/dist/assets/es-BebHdc0E.js +1 -0
  297. package/uis/stock/dist/assets/fr-DsDTrxhI.js +1 -0
  298. package/uis/stock/dist/assets/index-6LANO2Ua.css +2 -0
  299. package/uis/stock/dist/assets/index-D06cUZbM.js +56 -0
  300. package/uis/stock/dist/assets/ja-D3RARJjW.js +1 -0
  301. package/uis/stock/dist/assets/ko-CKI3dFoD.js +1 -0
  302. package/uis/stock/dist/assets/ru-DEU5ujXt.js +1 -0
  303. package/uis/stock/dist/assets/vi-ULKPnasj.js +1 -0
  304. package/uis/stock/dist/assets/zh-CN-tCvnOxWy.js +1 -0
  305. package/uis/stock/dist/index.html +2 -2
  306. package/uis/stock/dist/ui.json +3 -3
  307. package/AGENTS.md +0 -403
  308. package/uis/stock/dist/assets/de-CiSKBON6.js +0 -1
  309. package/uis/stock/dist/assets/es-BgNQbboq.js +0 -1
  310. package/uis/stock/dist/assets/fr-WzBF8AXI.js +0 -1
  311. package/uis/stock/dist/assets/index-CXDl25BP.js +0 -53
  312. package/uis/stock/dist/assets/index-Cok5msAO.css +0 -2
  313. package/uis/stock/dist/assets/ja-DMQqF4ip.js +0 -1
  314. package/uis/stock/dist/assets/ko-DgfSg9v_.js +0 -1
  315. package/uis/stock/dist/assets/ru-DjIByX61.js +0 -1
  316. package/uis/stock/dist/assets/vi-DOB8nYFC.js +0 -1
  317. package/uis/stock/dist/assets/zh-CN-DZ3WlUgy.js +0 -1
@@ -0,0 +1,4346 @@
1
+ import { C as errorMessage, t as appVersion } from "../cli.js";
2
+ import { t as writeFileAtomic } from "./atomic-CEfCUfkQ.js";
3
+ import { n as readStateFile } from "./config-text-DifCHhnz.js";
4
+ import { t as logger } from "./logger-B5U4GD3j.js";
5
+ import { t as isRecord } from "./shape-DnTKzjQ2.js";
6
+ import { c as planConfigMigrations, i as parseWorkspaceSettings, n as parseServersFile, o as stampConfig, r as parseTolerant, s as applyConfigMigrations, t as parseGlobalSettings } from "./parse-B9owE47G.js";
7
+ import { A as logsSchema, J as serverSchema, P as notificationsSchema, b as duplicateWebhookIds, g as defaultsSchema, lt as workspaceIdSchema, p as ddnsConfigSchema, x as entryStateSchema } from "./contracts-ku5ypHXJ.js";
8
+ import { a as mergeDefaults, c as serversFileSchema, l as workspaceSettingsSchema } from "./schema-o7Lgk0V1.js";
9
+ import { a as SEED_WORKSPACE_SETTINGS, c as NOTIFICATION_MERGE_KEYS, d as applyPatch, i as SEED_SERVERS_FILE, o as DDNS_MERGE_KEYS, s as EMPTY_MERGE_KEYS, t as ConfigError, u as SERVER_MERGE_KEYS } from "./settings-BVSBnIwJ.js";
10
+ import { r as dataRoot, u as projectDir, y as resolveUserPath } from "./paths-BT94q6-w.js";
11
+ import { r as workspacesFileSchema } from "./workspaces-CAln2sQ7.js";
12
+ import { x as resolveCwd } from "./nanny-20aBXL1o.js";
13
+ import { r as isProcessAlive } from "./port-B8WBTRMk.js";
14
+ import { a as listZip, i as isZipArchive, n as extractZip, o as copyTree, r as isInvalidPassword, t as createZip } from "./archive-DpCwA8Nf.js";
15
+ import process from "node:process";
16
+ import path from "node:path";
17
+ import fs from "node:fs";
18
+ import { type } from "arktype";
19
+ import { Buffer } from "node:buffer";
20
+ import os from "node:os";
21
+ import { spawn } from "node:child_process";
22
+ import { DetailedError } from "@namesmt/utils";
23
+ //#region src/providers/ddns/types.ts
24
+ function succeeded(message, changed) {
25
+ return {
26
+ ok: true,
27
+ changed,
28
+ message
29
+ };
30
+ }
31
+ function failed(error, permanent = false) {
32
+ return {
33
+ ok: false,
34
+ changed: false,
35
+ message: error,
36
+ error,
37
+ ...permanent ? { permanent: true } : {}
38
+ };
39
+ }
40
+ /**
41
+ * The result of the write six providers end their `update()` with.
42
+ *
43
+ * They repeated the same two lines after their own write call, and they have to agree: a
44
+ * non-ok response is a provider error with its body attached, and an ok one is a change.
45
+ * The message names the record, because a settings page shows it as the account's last
46
+ * result and "ok" would not say what actually moved.
47
+ */
48
+ async function wrote(response, record) {
49
+ if (!response.ok) return failed(await errorText(response));
50
+ return succeeded(`set ${record.host} ${record.type} to ${record.ip}`, true);
51
+ }
52
+ /** Missing required credential keys, as a sentence for the settings page. */
53
+ function missingFields(credentials, keys) {
54
+ const missing = keys.filter((key) => (credentials?.[key] ?? "").trim().length === 0);
55
+ return missing.length === 0 ? null : `set ${missing.join(", ")}`;
56
+ }
57
+ function basicAuth(user, password) {
58
+ return `Basic ${Buffer.from(`${user}:${password}`, "utf8").toString("base64")}`;
59
+ }
60
+ /** A provider error body is useful, but never worth throwing over. */
61
+ async function errorText(response, limit = 300) {
62
+ try {
63
+ const text = (await response.text()).replace(/\s+/g, " ").trim();
64
+ return text.length === 0 ? `HTTP ${response.status}` : `HTTP ${response.status}: ${text.slice(0, limit)}`;
65
+ } catch {
66
+ return `HTTP ${response.status}`;
67
+ }
68
+ }
69
+ var NORMALIZE_DOTS = /\.$/;
70
+ /** `Sub.Domain.COM.` -> `sub.domain.com`; DuckDNS and friends are case-insensitive. */
71
+ function normalizeHost(host) {
72
+ return host.trim().toLowerCase().replace(NORMALIZE_DOTS, "");
73
+ }
74
+ //#endregion
75
+ //#region src/providers/ddns/cloudflare.ts
76
+ var API$5 = "https://api.cloudflare.com/client/v4";
77
+ function authHeaders(credentials) {
78
+ const token = (credentials.apiToken ?? "").trim();
79
+ if (token.length > 0) return { Authorization: `Bearer ${token}` };
80
+ const email = (credentials.email ?? "").trim();
81
+ const key = (credentials.apiKey ?? "").trim();
82
+ if (email.length > 0 && key.length > 0) return {
83
+ "X-Auth-Email": email,
84
+ "X-Auth-Key": key
85
+ };
86
+ return null;
87
+ }
88
+ async function call$1(path, headers, context, init = {}) {
89
+ try {
90
+ const response = await context.fetch(`${API$5}${path}`, {
91
+ ...init,
92
+ headers: {
93
+ ...headers,
94
+ "Content-Type": "application/json",
95
+ ...init.headers ?? {}
96
+ },
97
+ signal: context.signal
98
+ });
99
+ const text = await response.text();
100
+ let parsed;
101
+ try {
102
+ parsed = JSON.parse(text);
103
+ } catch {
104
+ return {
105
+ data: null,
106
+ status: response.status,
107
+ error: `cloudflare answered ${response.status}: ${text.slice(0, 200)}`
108
+ };
109
+ }
110
+ if (!response.ok || parsed.success !== true) {
111
+ const detail = (parsed.errors ?? []).map((entry) => `${entry.code} ${entry.message}`).join("; ");
112
+ return {
113
+ data: parsed,
114
+ status: response.status,
115
+ error: detail.length > 0 ? detail : `HTTP ${response.status}`
116
+ };
117
+ }
118
+ return {
119
+ data: parsed,
120
+ status: response.status,
121
+ error: null
122
+ };
123
+ } catch (error) {
124
+ return {
125
+ data: null,
126
+ status: 0,
127
+ error: errorMessage(error)
128
+ };
129
+ }
130
+ }
131
+ /**
132
+ * Walks the host's parents through `GET /zones?name=`, which is how the
133
+ * reference image resolves a zone without a pasted zone id; the id is cached in
134
+ * the panel's state file, so it usually costs nothing.
135
+ *
136
+ * A cached id is **confirmed before use**, the same way `findRecord` treats its own. It was returned
137
+ * outright, so a stale id — the zone deleted, the API token swapped to another account, a restored
138
+ * `ddns.json` — made every later call address a zone the token cannot see, and the walk that would have
139
+ * found the right one never ran: the update failed permanently, with the provider's error for a zone
140
+ * that is not even the host's. One extra request per run, and only when a cache exists.
141
+ */
142
+ async function resolveZone(host, headers, context, cached) {
143
+ if (cached !== void 0) {
144
+ const confirmed = await call$1(`/zones/${cached}`, headers, context);
145
+ if (confirmed.error === null && confirmed.data !== null) return {
146
+ id: cached,
147
+ name: host
148
+ };
149
+ if (confirmed.status === 0) throw new Error(confirmed.error ?? "could not reach Cloudflare");
150
+ }
151
+ const labels = host.split(".");
152
+ for (let index = 0; index <= labels.length - 2; index++) {
153
+ const candidate = labels.slice(index).join(".");
154
+ const { data, error } = await call$1(`/zones?name=${encodeURIComponent(candidate)}&per_page=1`, headers, context);
155
+ if (error !== null || data === null) throw new Error(error ?? "could not look up the zone");
156
+ const zone = data.result[0];
157
+ if (zone !== void 0) return zone;
158
+ }
159
+ return null;
160
+ }
161
+ async function findRecord(zoneId, record, headers, context, cached) {
162
+ if (cached !== void 0) {
163
+ const fetched = await call$1(`/zones/${zoneId}/dns_records/${cached}`, headers, context);
164
+ if (fetched.error === null && fetched.data !== null) return {
165
+ record: fetched.data.result,
166
+ error: null
167
+ };
168
+ if (fetched.status !== 404 && fetched.status !== 400) return {
169
+ record: null,
170
+ error: fetched.error
171
+ };
172
+ }
173
+ const listed = await call$1(`/zones/${zoneId}/dns_records?type=${record.type}&name=${encodeURIComponent(record.host)}&per_page=100`, headers, context);
174
+ if (listed.error !== null) return {
175
+ record: null,
176
+ error: listed.error
177
+ };
178
+ return {
179
+ record: (listed.data?.result ?? []).find((entry) => entry.id !== void 0) ?? null,
180
+ error: null
181
+ };
182
+ }
183
+ var cloudflareProvider = {
184
+ id: "cloudflare",
185
+ label: "Cloudflare",
186
+ docsUrl: "https://developers.cloudflare.com/api/resources/dns/subresources/records/",
187
+ families: ["A", "AAAA"],
188
+ ttl: true,
189
+ proxied: true,
190
+ fields: [
191
+ {
192
+ key: "apiToken",
193
+ label: "API token",
194
+ hint: "Zone → DNS → Edit (plus Zone → Zone → Read) for your zones. Preferred.",
195
+ optional: true
196
+ },
197
+ {
198
+ key: "email",
199
+ label: "Account email",
200
+ hint: "Only for the legacy Global API Key.",
201
+ optional: true
202
+ },
203
+ {
204
+ key: "apiKey",
205
+ label: "Global API key",
206
+ hint: "Legacy; prefer an API token.",
207
+ optional: true
208
+ }
209
+ ],
210
+ validate(credentials) {
211
+ if (authHeaders(credentials ?? {}) !== null) return null;
212
+ return missingFields(credentials, ["apiToken"]);
213
+ },
214
+ async update(record, context) {
215
+ const headers = authHeaders(context.credentials);
216
+ if (headers === null) return failed("cloudflare needs an API token (or the legacy email + global key)");
217
+ try {
218
+ const zone = await resolveZone(record.host, headers, context, record.cache?.zoneId);
219
+ if (zone === null) return failed(`cloudflare does not have a zone for ${record.host}`);
220
+ const ttl = record.proxied ? 1 : record.ttl;
221
+ const found = await findRecord(zone.id, record, headers, context, record.cache?.recordId);
222
+ if (found.error !== null) return failed(found.error);
223
+ const existing = found.record;
224
+ if (existing !== null && existing.content === record.ip && existing.ttl === ttl && existing.proxied === record.proxied) return {
225
+ ...succeeded(`already ${record.ip}`, false),
226
+ cache: {
227
+ zoneId: zone.id,
228
+ recordId: existing.id
229
+ }
230
+ };
231
+ const cache = {
232
+ zoneId: zone.id,
233
+ recordId: existing?.id
234
+ };
235
+ const body = JSON.stringify({
236
+ type: record.type,
237
+ name: record.host,
238
+ content: record.ip,
239
+ ttl,
240
+ proxied: record.proxied
241
+ });
242
+ const written = existing === null ? await call$1(`/zones/${zone.id}/dns_records`, headers, context, {
243
+ method: "POST",
244
+ body
245
+ }) : await call$1(`/zones/${zone.id}/dns_records/${existing.id}`, headers, context, {
246
+ method: "PATCH",
247
+ body
248
+ });
249
+ if (written.error !== null) return failed(written.error);
250
+ return {
251
+ ...succeeded(`set ${record.host} ${record.type} to ${record.ip}`, true),
252
+ cache: {
253
+ ...cache,
254
+ recordId: written.data?.result?.id ?? existing?.id
255
+ }
256
+ };
257
+ } catch (error) {
258
+ return failed(errorMessage(error));
259
+ }
260
+ },
261
+ /**
262
+ * One `_acme-challenge` TXT record, written and removed around a validation.
263
+ * Cloudflare has real per-record endpoints, so nothing else in the zone is read
264
+ * or rewritten — the failure mode that makes a whole-record-set API risky.
265
+ */
266
+ async challenge(record, context) {
267
+ const headers = authHeaders(context.credentials);
268
+ if (headers === null) return {
269
+ ok: false,
270
+ message: "cloudflare needs an API token (or the legacy email + global key)"
271
+ };
272
+ try {
273
+ const zone = await resolveZone(record.fqdn, headers, context, void 0);
274
+ if (zone === null) return {
275
+ ok: false,
276
+ message: `cloudflare does not have a zone for ${record.fqdn}`
277
+ };
278
+ const listed = await call$1(`/zones/${zone.id}/dns_records?type=TXT&name=${encodeURIComponent(record.fqdn)}&per_page=100`, headers, context);
279
+ if (listed.error !== null) return {
280
+ ok: false,
281
+ message: listed.error
282
+ };
283
+ const ours = (listed.data?.result ?? []).filter((entry) => entry.id !== void 0).filter((entry) => entry.content === record.value);
284
+ if (record.action === "present") {
285
+ if (ours.length > 0) return {
286
+ ok: true,
287
+ message: `${record.fqdn} already carries this value`
288
+ };
289
+ const written = await call$1(`/zones/${zone.id}/dns_records`, headers, context, {
290
+ method: "POST",
291
+ body: JSON.stringify({
292
+ type: "TXT",
293
+ name: record.fqdn,
294
+ content: record.value,
295
+ ttl: 1
296
+ })
297
+ });
298
+ if (written.error !== null) return {
299
+ ok: false,
300
+ message: written.error
301
+ };
302
+ return {
303
+ ok: true,
304
+ message: `wrote the TXT record for ${record.fqdn}`
305
+ };
306
+ }
307
+ for (const entry of ours) {
308
+ const removed = await call$1(`/zones/${zone.id}/dns_records/${entry.id}`, headers, context, { method: "DELETE" });
309
+ if (removed.error !== null && removed.status !== 404) return {
310
+ ok: false,
311
+ message: removed.error
312
+ };
313
+ }
314
+ if (ours.length === 0) return {
315
+ ok: true,
316
+ message: `${record.fqdn} had no challenge record to remove`
317
+ };
318
+ return {
319
+ ok: true,
320
+ message: `removed the TXT record for ${record.fqdn}`
321
+ };
322
+ } catch (error) {
323
+ return {
324
+ ok: false,
325
+ message: errorMessage(error)
326
+ };
327
+ }
328
+ }
329
+ };
330
+ //#endregion
331
+ //#region src/providers/ddns/dyndns2.ts
332
+ /**
333
+ * The dyndns2 reply vocabulary, shared by every `…/nic/update` endpoint. A
334
+ * provider that answers something else maps its own text instead.
335
+ */
336
+ var CODES = {
337
+ "good": {
338
+ ok: true,
339
+ changed: true,
340
+ message: "updated",
341
+ permanent: false
342
+ },
343
+ "nochg": {
344
+ ok: true,
345
+ changed: false,
346
+ message: "already current",
347
+ permanent: false
348
+ },
349
+ "nohost": {
350
+ ok: false,
351
+ changed: false,
352
+ message: "the provider does not know this hostname",
353
+ permanent: true
354
+ },
355
+ "notfqdn": {
356
+ ok: false,
357
+ changed: false,
358
+ message: "the provider wants a fully qualified hostname",
359
+ permanent: true
360
+ },
361
+ "numhost": {
362
+ ok: false,
363
+ changed: false,
364
+ message: "too many hostnames for this provider",
365
+ permanent: true
366
+ },
367
+ "badauth": {
368
+ ok: false,
369
+ changed: false,
370
+ message: "the provider rejected the credentials",
371
+ permanent: true
372
+ },
373
+ "badagent": {
374
+ ok: false,
375
+ changed: false,
376
+ message: "the provider rejected this client (User-Agent)",
377
+ permanent: true
378
+ },
379
+ "!donator": {
380
+ ok: false,
381
+ changed: false,
382
+ message: "this feature needs a paid provider plan",
383
+ permanent: true
384
+ },
385
+ "abuse": {
386
+ ok: false,
387
+ changed: false,
388
+ message: "the provider blocked this account for abuse",
389
+ permanent: true
390
+ },
391
+ "dnserr": {
392
+ ok: false,
393
+ changed: false,
394
+ message: "the provider had a DNS error",
395
+ permanent: false
396
+ },
397
+ "servererror": {
398
+ ok: false,
399
+ changed: false,
400
+ message: "the provider had a server error",
401
+ permanent: false
402
+ },
403
+ "911": {
404
+ ok: false,
405
+ changed: false,
406
+ message: "the provider is down; it asks you to wait about 30 minutes",
407
+ permanent: false
408
+ },
409
+ "unknown": {
410
+ ok: false,
411
+ changed: false,
412
+ message: "the provider answered with an unknown error",
413
+ permanent: false
414
+ }
415
+ };
416
+ /** The first word of the body is the code; the rest is provider detail. */
417
+ function parseDyndnsReply(body) {
418
+ const trimmed = body.trim();
419
+ const separator = trimmed.search(/\s/);
420
+ if (separator < 0) return {
421
+ code: trimmed.toLowerCase(),
422
+ detail: ""
423
+ };
424
+ return {
425
+ code: trimmed.slice(0, separator).toLowerCase(),
426
+ detail: trimmed.slice(separator).trim()
427
+ };
428
+ }
429
+ /** Maps a dyndns2 body onto the panel's result shape. */
430
+ function describeDyndnsReply(body, provider) {
431
+ const { code, detail } = parseDyndnsReply(body);
432
+ const known = CODES[code];
433
+ if (known === void 0) return failed(`${provider} answered "${(body.trim() || "an empty body").slice(0, 120)}"`);
434
+ if (known.ok) return succeeded(`${known.message}${detail.length === 0 ? "" : ` (${detail})`}`, known.changed);
435
+ return failed(`${known.message}${detail.length === 0 ? "" : `: ${detail}`}`, known.permanent);
436
+ }
437
+ /**
438
+ * A 401/400 with a non-dyndns2 body is still an answer worth quoting; a known
439
+ * code wins, because several of these endpoints report errors with HTTP 200.
440
+ */
441
+ function describeDyndnsResponse(response, body, provider) {
442
+ const { code } = parseDyndnsReply(body);
443
+ if (!response.ok && CODES[code] === void 0) {
444
+ const text = body.replace(/\s+/g, " ").trim().slice(0, 160);
445
+ return failed(`${provider} answered HTTP ${response.status}${text.length === 0 ? "" : `: ${text}`}`);
446
+ }
447
+ return describeDyndnsReply(body, provider);
448
+ }
449
+ //#endregion
450
+ //#region src/providers/ddns/desec.ts
451
+ var ENDPOINT$7 = "https://update.dedyn.io/";
452
+ var desecProvider = {
453
+ id: "desec",
454
+ label: "deSEC",
455
+ docsUrl: "https://desec.readthedocs.io/en/latest/dyndns/update-api.html",
456
+ families: ["A", "AAAA"],
457
+ ttl: false,
458
+ proxied: false,
459
+ fields: [{
460
+ key: "token",
461
+ label: "API token",
462
+ hint: "desec.io → Token management; the token must allow the RRset update.",
463
+ optional: false
464
+ }],
465
+ validate(credentials) {
466
+ return missingFields(credentials, ["token"]);
467
+ },
468
+ async update(record, context) {
469
+ const token = (context.credentials.token ?? "").trim();
470
+ if (token.length === 0) return failed("desec needs an API token");
471
+ const family = record.type === "A" ? `myipv4=${encodeURIComponent(record.ip)}` : `myipv6=${encodeURIComponent(record.ip)}`;
472
+ const url = `${ENDPOINT$7}?hostname=${encodeURIComponent(record.host)}&${family}`;
473
+ try {
474
+ const response = await context.fetch(url, {
475
+ headers: { Authorization: basicAuth(record.host, token) },
476
+ signal: context.signal
477
+ });
478
+ return describeDyndnsResponse(response, await response.text(), "desec");
479
+ } catch (error) {
480
+ return failed(errorMessage(error));
481
+ }
482
+ }
483
+ };
484
+ //#endregion
485
+ //#region src/providers/ddns/zone.ts
486
+ /**
487
+ * Public suffixes that take one extra label, so `home.example.co.uk` splits as
488
+ * `home` in `example.co.uk` instead of `home.example` in `co.uk`. A per-domain
489
+ * `zone` overrides this, which is the escape hatch for anything not listed.
490
+ */
491
+ var MULTI_LABEL_SUFFIXES = /* @__PURE__ */ new Set([
492
+ "ac.uk",
493
+ "co.in",
494
+ "co.jp",
495
+ "co.ke",
496
+ "co.kr",
497
+ "co.nz",
498
+ "co.uk",
499
+ "co.za",
500
+ "com.au",
501
+ "com.br",
502
+ "com.cn",
503
+ "com.hk",
504
+ "com.mx",
505
+ "com.sg",
506
+ "com.tr",
507
+ "com.tw",
508
+ "edu.au",
509
+ "gov.uk",
510
+ "net.au",
511
+ "net.uk",
512
+ "org.au",
513
+ "org.uk"
514
+ ]);
515
+ /**
516
+ * Splits a hostname into the zone and the record name, which is what every
517
+ * provider that has no zone lookup needs. `zone` short-circuits the heuristic.
518
+ */
519
+ function splitHost(host, zone) {
520
+ const normalized = normalizeHost(host);
521
+ const override = normalizeHost(zone ?? "");
522
+ const resolved = override.length > 0 ? override : guessZone(normalized);
523
+ if (normalized === resolved) return {
524
+ zone: resolved,
525
+ name: "@"
526
+ };
527
+ return {
528
+ zone: resolved,
529
+ name: normalized.endsWith(`.${resolved}`) ? normalized.slice(0, -(resolved.length + 1)) : normalized
530
+ };
531
+ }
532
+ function guessZone(host) {
533
+ const labels = host.split(".");
534
+ if (labels.length <= 2) return host;
535
+ const lastTwo = labels.slice(-2).join(".");
536
+ const lastThree = labels.slice(-3).join(".");
537
+ return MULTI_LABEL_SUFFIXES.has(lastTwo) ? lastThree : lastTwo;
538
+ }
539
+ //#endregion
540
+ //#region src/providers/ddns/digitalocean.ts
541
+ var API$4 = "https://api.digitalocean.com/v2/domains";
542
+ function oceanTtl(ttl) {
543
+ return Math.max(30, ttl);
544
+ }
545
+ var digitaloceanProvider = {
546
+ id: "digitalocean",
547
+ label: "DigitalOcean",
548
+ docsUrl: "https://docs.digitalocean.com/reference/api/api-reference/#tag/Domain-Records",
549
+ families: ["A", "AAAA"],
550
+ ttl: true,
551
+ proxied: false,
552
+ fields: [{
553
+ key: "token",
554
+ label: "API token",
555
+ hint: "A personal access token with the `domain` scope.",
556
+ optional: false
557
+ }],
558
+ validate(credentials) {
559
+ return missingFields(credentials, ["token"]);
560
+ },
561
+ async update(record, context) {
562
+ const { zone, name } = splitHost(record.host, record.zone);
563
+ const ttl = oceanTtl(record.ttl);
564
+ const headers = {
565
+ "Authorization": `Bearer ${(context.credentials.token ?? "").trim()}`,
566
+ "Content-Type": "application/json"
567
+ };
568
+ const collection = `${API$4}/${encodeURIComponent(zone)}/records`;
569
+ try {
570
+ const listed = await context.fetch(`${collection}?per_page=200`, {
571
+ headers,
572
+ signal: context.signal
573
+ });
574
+ if (!listed.ok) return failed(await errorText(listed));
575
+ const existing = ((await listed.json()).domain_records ?? []).find((entry) => entry.name === name && entry.type === record.type);
576
+ if (existing !== void 0 && existing.data === record.ip) return succeeded(`already ${record.ip}`, false);
577
+ return await wrote(existing === void 0 ? await context.fetch(collection, {
578
+ method: "POST",
579
+ headers,
580
+ body: JSON.stringify({
581
+ type: record.type,
582
+ name,
583
+ data: record.ip,
584
+ ttl
585
+ }),
586
+ signal: context.signal
587
+ }) : await context.fetch(`${collection}/${existing.id}`, {
588
+ method: "PUT",
589
+ headers,
590
+ body: JSON.stringify({
591
+ type: record.type,
592
+ name,
593
+ data: record.ip,
594
+ ttl
595
+ }),
596
+ signal: context.signal
597
+ }), record);
598
+ } catch (error) {
599
+ return failed(errorMessage(error));
600
+ }
601
+ }
602
+ };
603
+ //#endregion
604
+ //#region src/providers/ddns/duckdns.ts
605
+ var ENDPOINT$6 = "https://www.duckdns.org/update";
606
+ /** DuckDNS addresses one subdomain at a time, so the label is the domain. */
607
+ function subdomain(host) {
608
+ const normalized = host.trim().toLowerCase();
609
+ return normalized.endsWith(".duckdns.org") ? normalized.slice(0, -12) : normalized;
610
+ }
611
+ var duckdnsProvider = {
612
+ id: "duckdns",
613
+ label: "DuckDNS",
614
+ docsUrl: "https://www.duckdns.org/spec.jsp",
615
+ families: ["A", "AAAA"],
616
+ ttl: false,
617
+ proxied: false,
618
+ fields: [{
619
+ key: "token",
620
+ label: "Account token",
621
+ hint: "On duckdns.org after signing in. One token covers every subdomain.",
622
+ optional: false
623
+ }],
624
+ validate(credentials) {
625
+ return missingFields(credentials, ["token"]);
626
+ },
627
+ async update(record, context) {
628
+ const token = (context.credentials.token ?? "").trim();
629
+ if (token.length === 0) return failed("duckdns needs the account token");
630
+ const family = record.type === "A" ? `ip=${encodeURIComponent(record.ip)}` : `ipv6=${encodeURIComponent(record.ip)}`;
631
+ const url = `${ENDPOINT$6}?domains=${encodeURIComponent(subdomain(record.host))}&token=${encodeURIComponent(token)}&${family}`;
632
+ try {
633
+ const response = await context.fetch(url, { signal: context.signal });
634
+ const body = (await response.text()).trim();
635
+ if (body.toUpperCase() === "OK") return succeeded(`set ${record.host} ${record.type} to ${record.ip}`, true);
636
+ return failed(`duckdns answered "${body.slice(0, 120) || `HTTP ${response.status}`}"`);
637
+ } catch (error) {
638
+ return failed(errorMessage(error));
639
+ }
640
+ }
641
+ };
642
+ //#endregion
643
+ //#region src/providers/ddns/dynu.ts
644
+ var ENDPOINT$5 = "https://api.dynu.com/nic/update";
645
+ var dynuProvider = {
646
+ id: "dynu",
647
+ label: "Dynu",
648
+ docsUrl: "https://www.dynu.com/DynamicDNS/IP-Update-Protocol",
649
+ families: ["A", "AAAA"],
650
+ ttl: false,
651
+ proxied: false,
652
+ fields: [{
653
+ key: "username",
654
+ label: "Username",
655
+ hint: "Dynu username; used for HTTP Basic auth.",
656
+ optional: false
657
+ }, {
658
+ key: "password",
659
+ label: "Password",
660
+ hint: "Account password, or its SHA-256 hash.",
661
+ optional: false
662
+ }],
663
+ validate(credentials) {
664
+ return missingFields(credentials, ["username", "password"]);
665
+ },
666
+ async update(record, context) {
667
+ const username = (context.credentials.username ?? "").trim();
668
+ const password = (context.credentials.password ?? "").trim();
669
+ if (username.length === 0 || password.length === 0) return failed("dynu needs the username and password");
670
+ const address = record.type === "A" ? `myip=${encodeURIComponent(record.ip)}` : `myipv6=${encodeURIComponent(record.ip)}`;
671
+ const url = `${ENDPOINT$5}?hostname=${encodeURIComponent(record.host)}&${address}`;
672
+ try {
673
+ const response = await context.fetch(url, {
674
+ headers: { Authorization: basicAuth(username, password) },
675
+ signal: context.signal
676
+ });
677
+ return describeDyndnsResponse(response, await response.text(), "dynu");
678
+ } catch (error) {
679
+ return failed(errorMessage(error));
680
+ }
681
+ }
682
+ };
683
+ //#endregion
684
+ //#region src/providers/ddns/freedns.ts
685
+ var ENDPOINT$4 = "https://freedns.afraid.org/dynamic/update.php";
686
+ /**
687
+ * FreeDNS credentials *are* a URL: the per-record "Direct URL" hash. Both the
688
+ * bare hash and the whole URL are accepted, because that is what people copy.
689
+ */
690
+ function updateToken(credentials) {
691
+ const raw = (credentials.token ?? "").trim();
692
+ if (raw.length === 0) return "";
693
+ return (raw.includes("?") ? raw.slice(raw.indexOf("?") + 1) : raw).replace(/^https?:\/\/[^?]*\?/, "");
694
+ }
695
+ var freednsProvider = {
696
+ id: "freedns",
697
+ label: "FreeDNS (afraid.org)",
698
+ docsUrl: "https://freedns.afraid.org/faq/",
699
+ families: ["A", "AAAA"],
700
+ ttl: false,
701
+ proxied: false,
702
+ fields: [{
703
+ key: "token",
704
+ label: "Direct URL",
705
+ hint: "FreeDNS → Dynamic DNS → the per-record \"Direct URL\". Paste the whole URL or just its hash.",
706
+ optional: false
707
+ }],
708
+ validate(credentials) {
709
+ return missingFields(credentials, ["token"]);
710
+ },
711
+ async update(record, context) {
712
+ const token = updateToken(context.credentials);
713
+ if (token.length === 0) return failed("freedns needs the per-record Direct URL");
714
+ try {
715
+ const response = await context.fetch(`${ENDPOINT$4}?${token}&address=${encodeURIComponent(record.ip)}`, { signal: context.signal });
716
+ const body = (await response.text()).trim();
717
+ if (!response.ok || /^ERROR/i.test(body)) return failed(`freedns answered "${body.slice(0, 160) || `HTTP ${response.status}`}"`);
718
+ return succeeded(`set ${record.host} ${record.type} to ${record.ip}`, true);
719
+ } catch (error) {
720
+ return failed(errorMessage(error));
721
+ }
722
+ }
723
+ };
724
+ //#endregion
725
+ //#region src/providers/ddns/gandi.ts
726
+ var API$3 = "https://api.gandi.net/v5/livedns/domains";
727
+ /** Gandi's documented minimum; `1` (automatic) has no meaning here. */
728
+ function gandiTtl(ttl) {
729
+ return Math.min(2592e3, Math.max(300, ttl));
730
+ }
731
+ /** A Personal Access Token (`pat_…`) is preferred; the legacy API key is still accepted. */
732
+ function authHeader(token) {
733
+ return token.startsWith("pat_") ? `Bearer ${token}` : `Apikey ${token}`;
734
+ }
735
+ var gandiProvider = {
736
+ id: "gandi",
737
+ label: "Gandi",
738
+ docsUrl: "https://api.gandi.net/docs/livedns/",
739
+ families: ["A", "AAAA"],
740
+ ttl: true,
741
+ proxied: false,
742
+ fields: [{
743
+ key: "token",
744
+ label: "Personal access token",
745
+ hint: "A `pat_…` token from admin.gandi.net → Organizations. A legacy API key also works.",
746
+ optional: false
747
+ }],
748
+ validate(credentials) {
749
+ return missingFields(credentials, ["token"]);
750
+ },
751
+ async update(record, context) {
752
+ const token = (context.credentials.token ?? "").trim();
753
+ if (token.length === 0) return failed("gandi needs an API token");
754
+ const { zone, name } = splitHost(record.host, record.zone);
755
+ const ttl = gandiTtl(record.ttl);
756
+ const url = `${API$3}/${encodeURIComponent(zone)}/records/${encodeURIComponent(name)}/${record.type}`;
757
+ const headers = {
758
+ "Authorization": authHeader(token),
759
+ "Content-Type": "application/json"
760
+ };
761
+ try {
762
+ const current = await context.fetch(url, {
763
+ headers,
764
+ signal: context.signal
765
+ });
766
+ if (current.ok) {
767
+ const body = await current.json();
768
+ if (body.rrset_values?.length === 1 && body.rrset_values[0] === record.ip) return succeeded(`already ${record.ip}`, false);
769
+ }
770
+ return await wrote(await context.fetch(url, {
771
+ method: "PUT",
772
+ headers,
773
+ body: JSON.stringify({
774
+ rrset_values: [record.ip],
775
+ rrset_ttl: ttl
776
+ }),
777
+ signal: context.signal
778
+ }), record);
779
+ } catch (error) {
780
+ return failed(errorMessage(error));
781
+ }
782
+ }
783
+ };
784
+ //#endregion
785
+ //#region src/providers/ddns/godaddy.ts
786
+ var API$2 = "https://api.godaddy.com/v1/domains";
787
+ /** GoDaddy's floor; `1` (automatic) has no meaning here. */
788
+ function godaddyTtl(ttl) {
789
+ return Math.min(86400, Math.max(600, ttl));
790
+ }
791
+ var godaddyProvider = {
792
+ id: "godaddy",
793
+ label: "GoDaddy",
794
+ docsUrl: "https://developer.godaddy.com/doc/endpoint/dns",
795
+ families: ["A", "AAAA"],
796
+ ttl: true,
797
+ proxied: false,
798
+ fields: [
799
+ {
800
+ key: "key",
801
+ label: "API key",
802
+ hint: "developer.godaddy.com/keys.",
803
+ optional: false
804
+ },
805
+ {
806
+ key: "secret",
807
+ label: "API secret",
808
+ hint: "Shown once with the key.",
809
+ optional: false
810
+ },
811
+ {
812
+ key: "baseUrl",
813
+ label: "API base URL",
814
+ hint: "Optional; use https://api.ote-godaddy.com to rehearse against the test environment.",
815
+ optional: true
816
+ }
817
+ ],
818
+ validate(credentials) {
819
+ return missingFields(credentials, ["key", "secret"]);
820
+ },
821
+ async update(record, context) {
822
+ const { zone, name } = splitHost(record.host, record.zone);
823
+ const ttl = godaddyTtl(record.ttl);
824
+ const url = `${(context.credentials.baseUrl ?? "").trim() || API$2}/${encodeURIComponent(zone)}/records/${record.type}/${encodeURIComponent(name)}`;
825
+ const headers = {
826
+ "Authorization": `sso-key ${context.credentials.key ?? ""}:${context.credentials.secret ?? ""}`,
827
+ "Content-Type": "application/json"
828
+ };
829
+ try {
830
+ const current = await context.fetch(url, {
831
+ headers,
832
+ signal: context.signal
833
+ });
834
+ if (current.ok) {
835
+ const body = await current.json();
836
+ if (body.length === 1 && body[0]?.data === record.ip) return succeeded(`already ${record.ip}`, false);
837
+ }
838
+ return await wrote(await context.fetch(url, {
839
+ method: "PUT",
840
+ headers,
841
+ body: JSON.stringify([{
842
+ data: record.ip,
843
+ ttl
844
+ }]),
845
+ signal: context.signal
846
+ }), record);
847
+ } catch (error) {
848
+ return failed(errorMessage(error));
849
+ }
850
+ }
851
+ };
852
+ //#endregion
853
+ //#region src/providers/ddns/henet.ts
854
+ var ENDPOINT$3 = "https://dyn.dns.he.net/nic/update";
855
+ /** Hurricane Electric keeps a per-host DDNS key, shown in its DNS panel. */
856
+ var henetProvider = {
857
+ id: "henet",
858
+ label: "Hurricane Electric",
859
+ docsUrl: "https://dns.he.net/docs.html",
860
+ families: ["A", "AAAA"],
861
+ ttl: false,
862
+ proxied: false,
863
+ fields: [{
864
+ key: "key",
865
+ label: "DDNS key",
866
+ hint: "dns.he.net → the key shown next to the host when DDNS is enabled.",
867
+ optional: false
868
+ }],
869
+ validate(credentials) {
870
+ return missingFields(credentials, ["key"]);
871
+ },
872
+ async update(record, context) {
873
+ const key = (context.credentials.key ?? "").trim();
874
+ if (key.length === 0) return failed("hurricane electric needs the per-host DDNS key");
875
+ const url = `${ENDPOINT$3}?hostname=${encodeURIComponent(record.host)}&password=${encodeURIComponent(key)}&myip=${encodeURIComponent(record.ip)}`;
876
+ try {
877
+ const response = await context.fetch(url, { signal: context.signal });
878
+ return describeDyndnsResponse(response, await response.text(), "hurricane electric");
879
+ } catch (error) {
880
+ return failed(errorMessage(error));
881
+ }
882
+ }
883
+ };
884
+ //#endregion
885
+ //#region src/providers/ddns/namecheap.ts
886
+ var ENDPOINT$2 = "https://dynamicdns.park-your-domain.com/update";
887
+ function tag(body, name) {
888
+ return new RegExp(`<${name}>([\\s\\S]*?)</${name}>`, "i").exec(body)?.[1]?.trim() ?? null;
889
+ }
890
+ /**
891
+ * Namecheap's router-style Dynamic DNS: one GET, one A record, HTTP 200 even on
892
+ * failure — the XML `ErrCount` is the only truth.
893
+ */
894
+ var namecheapProvider = {
895
+ id: "namecheap",
896
+ label: "Namecheap",
897
+ docsUrl: "https://www.namecheap.com/support/knowledgebase/article.aspx/29/11/how-to-dynamically-update-the-hosts-ip-with-an-https-request/",
898
+ families: ["A"],
899
+ ttl: false,
900
+ proxied: false,
901
+ fields: [{
902
+ key: "password",
903
+ label: "Dynamic DNS password",
904
+ hint: "Dashboard → Manage domain → Advanced DNS → Dynamic DNS. Not your account password or API key.",
905
+ optional: false
906
+ }],
907
+ validate(credentials) {
908
+ return missingFields(credentials, ["password"]);
909
+ },
910
+ async update(record, context) {
911
+ const password = (context.credentials.password ?? "").trim();
912
+ if (password.length === 0) return failed("namecheap needs the Dynamic DNS password");
913
+ const { zone, name } = splitHost(record.host, record.zone);
914
+ const host = name === "@" ? "@" : name;
915
+ const url = `${ENDPOINT$2}?host=${encodeURIComponent(host)}&domain=${encodeURIComponent(zone)}&password=${encodeURIComponent(password)}&ip=${encodeURIComponent(record.ip)}`;
916
+ try {
917
+ const body = await (await context.fetch(url, { signal: context.signal })).text();
918
+ const errCount = Number.parseInt(tag(body, "ErrCount") ?? "0", 10);
919
+ const ip = tag(body, "IP");
920
+ if (errCount > 0) {
921
+ const first = tag(body, "Err1");
922
+ return failed(`namecheap rejected the update${first === null ? "" : `: ${first}`}`);
923
+ }
924
+ if (ip === null) return failed(`namecheap answered without an IP: ${body.replace(/\s+/g, " ").slice(0, 160)}`);
925
+ return succeeded(`${host === "@" ? zone : `${host}.${zone}`} now ${ip}`, ip !== record.ip);
926
+ } catch (error) {
927
+ return failed(errorMessage(error));
928
+ }
929
+ }
930
+ };
931
+ //#endregion
932
+ //#region src/providers/ddns/namecheap-api.ts
933
+ /**
934
+ * Namecheap through its XML API, which is the only way to write a `TXT` record
935
+ * there: the router-style Dynamic DNS endpoint in `namecheap.ts` updates an
936
+ * address and nothing else, and its password is not this one.
937
+ *
938
+ * The API has no "add one record" call. `setHosts` **replaces the whole record
939
+ * set**, so answering a challenge means reading every record, writing them all
940
+ * back with one added (or removed) — twice per issuance. That is why this is a
941
+ * separate provider with its own credentials rather than a mode of the other one:
942
+ * the failure mode is different in kind, and nobody should reach it by accident.
943
+ */
944
+ var ENDPOINT$1 = "https://api.namecheap.com/xml.response";
945
+ /**
946
+ * The most host records one `setHosts` call can carry. A zone with more than this
947
+ * cannot be rewritten through the API at all, which is why the guard refuses rather
948
+ * than sending a call that would silently drop the records it could not express.
949
+ */
950
+ var RECORD_LIMIT = 150;
951
+ /** TTL for the challenge record: short, because it is deleted minutes later. */
952
+ var CHALLENGE_TTL = 60;
953
+ var XML_ENTITIES = {
954
+ amp: "&",
955
+ lt: "<",
956
+ gt: ">",
957
+ quot: "\"",
958
+ apos: "'"
959
+ };
960
+ /**
961
+ * Namecheap escapes attribute values, so a value read back has to be unescaped
962
+ * before it is written out again: the whole-zone rewrite would otherwise turn
963
+ * `a&b` into `a&amp;b` on every challenge, corrupting a record we did not create.
964
+ */
965
+ function decodeXml(value) {
966
+ return value.replace(/&(#X?[0-9a-f]+|[a-z]+);/gi, (whole, body) => {
967
+ if (body.startsWith("#")) {
968
+ const hex = body[1] === "x" || body[1] === "X";
969
+ const code = Number.parseInt(hex ? body.slice(2) : body.slice(1), hex ? 16 : 10);
970
+ return Number.isInteger(code) && code >= 0 && code <= 1114111 ? String.fromCodePoint(code) : whole;
971
+ }
972
+ return XML_ENTITIES[body.toLowerCase()] ?? whole;
973
+ });
974
+ }
975
+ function attr(tagText, name) {
976
+ return decodeXml(new RegExp(`${name}="([^"]*)"`, "i").exec(tagText)?.[1] ?? "").trim();
977
+ }
978
+ /** Every `<Host ... />` in a `getHosts` reply, in the order the API listed them. */
979
+ function parseHosts(body) {
980
+ const records = [];
981
+ const pattern = /<Host\b([^>]*?)(?:\/>|>)/gi;
982
+ let match = pattern.exec(body);
983
+ while (match !== null) {
984
+ const attributes = match[1] ?? "";
985
+ records.push({
986
+ name: attr(attributes, "Name"),
987
+ type: attr(attributes, "Type"),
988
+ address: attr(attributes, "Address"),
989
+ mxPref: attr(attributes, "MXPref") || "10",
990
+ ttl: attr(attributes, "TTL") || "1800"
991
+ });
992
+ match = pattern.exec(body);
993
+ }
994
+ return records;
995
+ }
996
+ /** The first `<Err1>`…`<ErrN>` a failed reply carries, as one sentence. */
997
+ function describeErrors(body) {
998
+ const errors = [];
999
+ const pattern = /<Err\d+>([\s\S]*?)<\/Err\d+>/gi;
1000
+ let match = pattern.exec(body);
1001
+ while (match !== null) {
1002
+ const text = (match[1] ?? "").trim();
1003
+ if (text.length > 0) errors.push(text);
1004
+ match = pattern.exec(body);
1005
+ }
1006
+ return errors.length > 0 ? errors.join("; ") : "the API refused the request";
1007
+ }
1008
+ function credentials(store) {
1009
+ const apiUser = (store.apiUser ?? "").trim();
1010
+ const apiKey = (store.apiKey ?? "").trim();
1011
+ const userName = (store.userName ?? "").trim() || apiUser;
1012
+ const clientIp = (store.clientIp ?? "").trim();
1013
+ if (apiUser.length === 0 || apiKey.length === 0 || clientIp.length === 0) return null;
1014
+ return {
1015
+ apiUser,
1016
+ apiKey,
1017
+ userName,
1018
+ clientIp
1019
+ };
1020
+ }
1021
+ /** One XML call. Namecheap answers HTTP 200 whatever happened, so the body decides. */
1022
+ async function call(command, params, context) {
1023
+ const auth = credentials(context.credentials);
1024
+ if (auth === null) return "namecheap needs the API user, the API key and the whitelisted client IP";
1025
+ const query = new URLSearchParams({
1026
+ ApiUser: auth.apiUser,
1027
+ ApiKey: auth.apiKey,
1028
+ UserName: auth.userName,
1029
+ ClientIp: auth.clientIp,
1030
+ Command: command,
1031
+ ...params
1032
+ });
1033
+ try {
1034
+ const response = await context.fetch(`${ENDPOINT$1}?${query.toString()}`, { signal: context.signal });
1035
+ const body = await response.text();
1036
+ if (!response.ok && !body.includes("<ApiResponse")) return `namecheap answered HTTP ${response.status}`;
1037
+ const status = /<ApiResponse[^>]*Status="([^"]*)"/i.exec(body)?.[1] ?? "";
1038
+ if (status.toUpperCase() !== "OK") return describeErrors(body);
1039
+ return {
1040
+ status,
1041
+ errors: [],
1042
+ body
1043
+ };
1044
+ } catch (error) {
1045
+ return errorMessage(error);
1046
+ }
1047
+ }
1048
+ /** The registered domain split into the `SLD`/`TLD` pair the API asks for. */
1049
+ function apexParts(zone) {
1050
+ const apex = normalizeHost(zone);
1051
+ const dot = apex.indexOf(".");
1052
+ if (dot < 0) return {
1053
+ SLD: apex,
1054
+ TLD: ""
1055
+ };
1056
+ return {
1057
+ SLD: apex.slice(0, dot),
1058
+ TLD: apex.slice(dot + 1)
1059
+ };
1060
+ }
1061
+ /** The zone's records, or a sentence saying why they could not be read. */
1062
+ async function readHosts(zone, context) {
1063
+ const reply = await call("namecheap.domains.dns.getHosts", { ...apexParts(zone) }, context);
1064
+ if (typeof reply === "string") return reply;
1065
+ return parseHosts(reply.body);
1066
+ }
1067
+ /** Writes the whole record set back. */
1068
+ async function writeHosts(zone, records, context) {
1069
+ const params = { ...apexParts(zone) };
1070
+ records.forEach((record, index) => {
1071
+ const at = index + 1;
1072
+ params[`HostName${at}`] = record.name;
1073
+ params[`RecordType${at}`] = record.type;
1074
+ params[`Address${at}`] = record.address;
1075
+ params[`TTL${at}`] = record.ttl;
1076
+ params[`MXPref${at}`] = record.mxPref;
1077
+ });
1078
+ const reply = await call("namecheap.domains.dns.setHosts", params, context);
1079
+ return typeof reply === "string" ? reply : null;
1080
+ }
1081
+ /** The record name Namecheap expects for a challenge, relative to the zone. */
1082
+ function challengeName(fqdn, zone) {
1083
+ const normalized = normalizeHost(fqdn);
1084
+ const apex = normalizeHost(zone);
1085
+ if (normalized === apex) return "@";
1086
+ return normalized.endsWith(`.${apex}`) ? normalized.slice(0, -(apex.length + 1)) : normalized;
1087
+ }
1088
+ var namecheapApiProvider = {
1089
+ id: "namecheap-api",
1090
+ label: "Namecheap (API)",
1091
+ docsUrl: "https://www.namecheap.com/support/api/methods/domains-dns/set-hosts/",
1092
+ families: ["A"],
1093
+ ttl: true,
1094
+ proxied: false,
1095
+ fields: [
1096
+ {
1097
+ key: "apiUser",
1098
+ label: "API user",
1099
+ hint: "Dashboard → Profile → Tools → Namecheap API Access. Usually your account name.",
1100
+ optional: false
1101
+ },
1102
+ {
1103
+ key: "apiKey",
1104
+ label: "API key",
1105
+ hint: "Shown once when API access is enabled.",
1106
+ optional: false
1107
+ },
1108
+ {
1109
+ key: "userName",
1110
+ label: "User name",
1111
+ hint: "Leave empty unless the API user differs from the account.",
1112
+ optional: true
1113
+ },
1114
+ {
1115
+ key: "clientIp",
1116
+ label: "Whitelisted IP",
1117
+ hint: "The public IPv4 this panel calls from. It must be whitelisted under API Access, and error 1017105 means it is not.",
1118
+ optional: false
1119
+ }
1120
+ ],
1121
+ validate(store) {
1122
+ if (credentials(store ?? {}) !== null) return null;
1123
+ const missing = [
1124
+ "apiUser",
1125
+ "apiKey",
1126
+ "clientIp"
1127
+ ].filter((key) => (store?.[key] ?? "").trim().length === 0);
1128
+ return missing.length === 0 ? null : `set ${missing.join(", ")}`;
1129
+ },
1130
+ /**
1131
+ * There is no per-record update here: `setHosts` replaces everything, so this is
1132
+ * a read-modify-write of the whole zone.
1133
+ */
1134
+ async challenge(record, context) {
1135
+ const { zone } = splitHost(record.fqdn);
1136
+ const hosts = await readHosts(zone, context);
1137
+ if (typeof hosts === "string") return {
1138
+ ok: false,
1139
+ message: hosts
1140
+ };
1141
+ const name = challengeName(record.fqdn, zone);
1142
+ const isChallenge = (host) => host.type.toUpperCase() === "TXT" && host.name.toLowerCase() === name.toLowerCase();
1143
+ const isOurs = (host) => isChallenge(host) && host.address === record.value;
1144
+ if (record.action === "present") {
1145
+ if (hosts.some(isOurs)) return {
1146
+ ok: true,
1147
+ message: `${record.fqdn} already carries this value`
1148
+ };
1149
+ if (hosts.length >= RECORD_LIMIT) return {
1150
+ ok: false,
1151
+ 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`
1152
+ };
1153
+ const failure = await writeHosts(zone, [...hosts, {
1154
+ name,
1155
+ type: "TXT",
1156
+ address: record.value,
1157
+ mxPref: "10",
1158
+ ttl: String(CHALLENGE_TTL)
1159
+ }], context);
1160
+ if (failure !== null) return {
1161
+ ok: false,
1162
+ message: failure
1163
+ };
1164
+ return {
1165
+ ok: true,
1166
+ message: `added a TXT record for ${record.fqdn} (rewrote ${hosts.length} others)`
1167
+ };
1168
+ }
1169
+ const kept = hosts.filter((host) => !isOurs(host));
1170
+ if (kept.length === hosts.length) return {
1171
+ ok: true,
1172
+ message: `${record.fqdn} had no challenge record to remove`
1173
+ };
1174
+ const failure = await writeHosts(zone, kept, context);
1175
+ if (failure !== null) return {
1176
+ ok: false,
1177
+ message: failure
1178
+ };
1179
+ return {
1180
+ ok: true,
1181
+ message: `removed the TXT record for ${record.fqdn} (rewrote ${kept.length} others)`
1182
+ };
1183
+ }
1184
+ };
1185
+ //#endregion
1186
+ //#region src/providers/ddns/noip.ts
1187
+ var ENDPOINT = "https://dynupdate.no-ip.com/nic/update";
1188
+ /** No-IP rate-limits clients whose User-Agent it does not recognise. */
1189
+ var DEFAULT_AGENT = "home-hosted/1.0 (+https://github.com/NamesMT/home-hosted)";
1190
+ var noipProvider = {
1191
+ id: "noip",
1192
+ label: "No-IP",
1193
+ docsUrl: "https://www.noip.com/integrate/request",
1194
+ families: ["A", "AAAA"],
1195
+ ttl: false,
1196
+ proxied: false,
1197
+ fields: [
1198
+ {
1199
+ key: "username",
1200
+ label: "Email",
1201
+ hint: "Your No-IP account email.",
1202
+ optional: false
1203
+ },
1204
+ {
1205
+ key: "password",
1206
+ label: "Password",
1207
+ hint: "Your No-IP account password.",
1208
+ optional: false
1209
+ },
1210
+ {
1211
+ key: "userAgent",
1212
+ label: "User-Agent override",
1213
+ hint: "No-IP only guarantees updates for recognised clients; set an approved agent here if yours is registered.",
1214
+ optional: true
1215
+ }
1216
+ ],
1217
+ validate(credentials) {
1218
+ return missingFields(credentials, ["username", "password"]);
1219
+ },
1220
+ async update(record, context) {
1221
+ const username = (context.credentials.username ?? "").trim();
1222
+ const password = (context.credentials.password ?? "").trim();
1223
+ if (username.length === 0 || password.length === 0) return failed("no-ip needs the account email and password");
1224
+ const address = record.type === "A" ? `myip=${encodeURIComponent(record.ip)}` : `myipv6=${encodeURIComponent(record.ip)}`;
1225
+ const url = `${ENDPOINT}?hostname=${encodeURIComponent(record.host)}&${address}`;
1226
+ try {
1227
+ const response = await context.fetch(url, {
1228
+ headers: {
1229
+ "Authorization": basicAuth(username, password),
1230
+ "User-Agent": (context.credentials.userAgent ?? "").trim() || DEFAULT_AGENT
1231
+ },
1232
+ signal: context.signal
1233
+ });
1234
+ return describeDyndnsResponse(response, await response.text(), "no-ip");
1235
+ } catch (error) {
1236
+ return failed(errorMessage(error));
1237
+ }
1238
+ }
1239
+ };
1240
+ //#endregion
1241
+ //#region src/providers/ddns/porkbun.ts
1242
+ var API$1 = "https://api.porkbun.com/api/json/v3";
1243
+ /** Porkbun's documented floor; `1` (automatic) maps onto it. */
1244
+ function porkbunTtl(ttl) {
1245
+ return Math.max(600, ttl);
1246
+ }
1247
+ async function post(path, context, body) {
1248
+ try {
1249
+ const response = await context.fetch(`${API$1}${path}`, {
1250
+ method: "POST",
1251
+ headers: {
1252
+ "Content-Type": "application/json",
1253
+ "X-API-Key": context.credentials.apikey ?? "",
1254
+ "X-Secret-API-Key": context.credentials.secretapikey ?? ""
1255
+ },
1256
+ body: JSON.stringify(body),
1257
+ signal: context.signal
1258
+ });
1259
+ const parsed = JSON.parse(await response.text());
1260
+ if (parsed.status !== "SUCCESS") return {
1261
+ data: parsed,
1262
+ error: parsed.message ?? `HTTP ${response.status}`
1263
+ };
1264
+ return {
1265
+ data: parsed,
1266
+ error: null
1267
+ };
1268
+ } catch (error) {
1269
+ return {
1270
+ data: null,
1271
+ error: errorMessage(error)
1272
+ };
1273
+ }
1274
+ }
1275
+ var porkbunProvider = {
1276
+ id: "porkbun",
1277
+ label: "Porkbun",
1278
+ docsUrl: "https://porkbun.com/api/json/v3/documentation",
1279
+ families: ["A", "AAAA"],
1280
+ ttl: true,
1281
+ proxied: false,
1282
+ fields: [{
1283
+ key: "apikey",
1284
+ label: "API key",
1285
+ hint: "porkbun.com/account/api — starts with pk1_.",
1286
+ optional: false
1287
+ }, {
1288
+ key: "secretapikey",
1289
+ label: "Secret API key",
1290
+ hint: "Shown once when the key is created.",
1291
+ optional: false
1292
+ }],
1293
+ validate(credentials) {
1294
+ return missingFields(credentials, ["apikey", "secretapikey"]);
1295
+ },
1296
+ async update(record, context) {
1297
+ const { zone, name: rawName } = splitHost(record.host, record.zone);
1298
+ const name = rawName === "@" ? "" : rawName;
1299
+ const ttl = porkbunTtl(record.ttl);
1300
+ const existing = (await post(`/dns/retrieveByNameType/${encodeURIComponent(zone)}/${record.type}/${encodeURIComponent(name)}`, context, {})).data?.records?.[0];
1301
+ if (existing !== void 0 && existing.content === record.ip && Number.parseInt(existing.ttl, 10) === ttl) return succeeded(`already ${record.ip}`, false);
1302
+ const written = await post(`/dns/editByNameType/${encodeURIComponent(zone)}/${record.type}/${encodeURIComponent(name)}`, context, {
1303
+ content: record.ip,
1304
+ ttl
1305
+ });
1306
+ if (written.error !== null) return failed(written.error);
1307
+ const warnings = written.data?.warnings ?? [];
1308
+ const note = warnings.length > 0 ? ` — porkbun warns: ${warnings.join("; ")}` : "";
1309
+ return succeeded(`set ${record.host} ${record.type} to ${record.ip}${note}`, true);
1310
+ }
1311
+ };
1312
+ //#endregion
1313
+ //#region src/providers/ddns/spaceship.ts
1314
+ var API = "https://spaceship.dev/api/v1/dns/records";
1315
+ var PAGE_SIZE = 500;
1316
+ function spaceshipTtl(ttl) {
1317
+ return Math.min(3600, Math.max(60, ttl));
1318
+ }
1319
+ //#endregion
1320
+ //#region src/providers/ddns/index.ts
1321
+ /** Registry order is what the settings page offers. */
1322
+ var DDNS_PROVIDERS = [
1323
+ cloudflareProvider,
1324
+ namecheapProvider,
1325
+ namecheapApiProvider,
1326
+ {
1327
+ id: "spaceship",
1328
+ label: "Spaceship",
1329
+ docsUrl: "https://docs.spaceship.dev/",
1330
+ families: ["A", "AAAA"],
1331
+ ttl: true,
1332
+ proxied: false,
1333
+ fields: [{
1334
+ key: "apiKey",
1335
+ label: "API key",
1336
+ hint: "spaceship.com → API Manager; needs the `dnsrecords:read`/`write` scopes.",
1337
+ optional: false
1338
+ }, {
1339
+ key: "apiSecret",
1340
+ label: "API secret",
1341
+ hint: "Shown once with the key.",
1342
+ optional: false
1343
+ }],
1344
+ validate(credentials) {
1345
+ return missingFields(credentials, ["apiKey", "apiSecret"]);
1346
+ },
1347
+ async update(record, context) {
1348
+ const { zone, name } = splitHost(record.host, record.zone);
1349
+ const headers = {
1350
+ "X-API-Key": (context.credentials.apiKey ?? "").trim(),
1351
+ "X-API-Secret": (context.credentials.apiSecret ?? "").trim(),
1352
+ "Content-Type": "application/json"
1353
+ };
1354
+ try {
1355
+ let found;
1356
+ for (let skip = 0; skip < PAGE_SIZE * 5; skip += PAGE_SIZE) {
1357
+ const listed = await context.fetch(`${API}/${encodeURIComponent(zone)}?take=${PAGE_SIZE}&skip=${skip}`, {
1358
+ headers,
1359
+ signal: context.signal
1360
+ });
1361
+ if (!listed.ok) return failed(await errorText(listed));
1362
+ const body = await listed.json();
1363
+ const items = Array.isArray(body) ? body : body.items ?? [];
1364
+ found = items.find((entry) => entry.name === name && entry.type === record.type);
1365
+ if (found !== void 0 || items.length < PAGE_SIZE) break;
1366
+ }
1367
+ if (found?.address === record.ip) return succeeded(`already ${record.ip}`, false);
1368
+ return await wrote(await context.fetch(`${API}/${encodeURIComponent(zone)}`, {
1369
+ method: "PUT",
1370
+ headers,
1371
+ body: JSON.stringify({
1372
+ force: true,
1373
+ items: [{
1374
+ type: record.type,
1375
+ name,
1376
+ ttl: spaceshipTtl(record.ttl),
1377
+ address: record.ip
1378
+ }]
1379
+ }),
1380
+ signal: context.signal
1381
+ }), record);
1382
+ } catch (error) {
1383
+ return failed(errorMessage(error));
1384
+ }
1385
+ }
1386
+ },
1387
+ porkbunProvider,
1388
+ godaddyProvider,
1389
+ gandiProvider,
1390
+ digitaloceanProvider,
1391
+ desecProvider,
1392
+ duckdnsProvider,
1393
+ noipProvider,
1394
+ dynuProvider,
1395
+ henetProvider,
1396
+ freednsProvider
1397
+ ];
1398
+ var BY_ID = new Map(DDNS_PROVIDERS.map((provider) => [provider.id, provider]));
1399
+ function ddnsProvider(id) {
1400
+ return BY_ID.get(id) ?? null;
1401
+ }
1402
+ function ddnsProviderInfos() {
1403
+ return DDNS_PROVIDERS.map((provider) => ({
1404
+ id: provider.id,
1405
+ label: provider.label,
1406
+ docsUrl: provider.docsUrl,
1407
+ families: provider.families,
1408
+ fields: provider.fields,
1409
+ ttl: provider.ttl,
1410
+ proxied: provider.proxied,
1411
+ txt: provider.challenge !== void 0
1412
+ }));
1413
+ }
1414
+ /**
1415
+ * Cross-field problems ArkType cannot see. Credentials are deliberately not
1416
+ * required here: an account is normally added before its secret is typed in,
1417
+ * and a missing secret is reported per record instead of blocking the save.
1418
+ */
1419
+ function validateDdnsConfig(config) {
1420
+ const errors = [];
1421
+ const seenAccounts = /* @__PURE__ */ new Set();
1422
+ for (const account of config.accounts) {
1423
+ if (seenAccounts.has(account.id)) {
1424
+ errors.push(`account "${account.id}" is declared twice`);
1425
+ continue;
1426
+ }
1427
+ seenAccounts.add(account.id);
1428
+ if (ddnsProvider(account.provider) === null) errors.push(`account "${account.id}" uses an unknown provider "${account.provider}"`);
1429
+ }
1430
+ const seenRecords = /* @__PURE__ */ new Set();
1431
+ for (const domain of config.domains) {
1432
+ const account = config.accounts.find((entry) => entry.id === domain.account);
1433
+ if (account === void 0) {
1434
+ errors.push(`"${domain.host}" points at unknown account "${domain.account}"`);
1435
+ continue;
1436
+ }
1437
+ const zone = domain.zone?.trim().toLowerCase();
1438
+ if (zone !== void 0 && zone.length > 0 && domain.host.toLowerCase() !== zone && !domain.host.toLowerCase().endsWith(`.${zone}`)) errors.push(`"${domain.host}" has zone "${domain.zone}", which it is not inside — a zone is the registered domain the record lives in`);
1439
+ const provider = ddnsProvider(account.provider);
1440
+ if (provider !== null) for (const recordType of domain.types) {
1441
+ if (!provider.families.includes(recordType)) errors.push(`${account.label || provider.label} cannot manage ${recordType} records ("${domain.host}")`);
1442
+ const key = `${domain.host.toLowerCase()}|${recordType}`;
1443
+ if (seenRecords.has(key)) errors.push(`"${domain.host}" asks for ${recordType} twice`);
1444
+ seenRecords.add(key);
1445
+ }
1446
+ }
1447
+ return errors;
1448
+ }
1449
+ //#endregion
1450
+ //#region src/helpers/env-file.ts
1451
+ /** `KEY=value` files, with optional `export `, `#` comments and quoted values. */
1452
+ function parseEnvFile(text) {
1453
+ const env = {};
1454
+ for (const raw of text.split("\n")) {
1455
+ const line = raw.trim();
1456
+ if (line.length === 0 || line.startsWith("#")) continue;
1457
+ const assignment = line.startsWith("export ") ? line.slice(7) : line;
1458
+ const separator = assignment.indexOf("=");
1459
+ if (separator <= 0) continue;
1460
+ const key = assignment.slice(0, separator).trim();
1461
+ let value = assignment.slice(separator + 1).trim();
1462
+ if (value.length > 1 && (value.startsWith("\"") && value.endsWith("\"") || value.startsWith("'") && value.endsWith("'"))) value = value.slice(1, -1);
1463
+ env[key] = value;
1464
+ }
1465
+ return env;
1466
+ }
1467
+ /**
1468
+ * Missing files are not an error: an env file is an optional override layer.
1469
+ *
1470
+ * Read through `readStateFile`: an entry's `envFile` is written by a person, not by this panel, so a
1471
+ * Windows editor's byte-order mark or UTF-16 save is the normal state of it. A `'utf8'` read made
1472
+ * every key carry a NUL — dropped by `resolveSpawn` as "an environment key containing a null byte" —
1473
+ * so the process started without the secret the file exists to keep out of the config.
1474
+ */
1475
+ function loadEnvFile(file) {
1476
+ try {
1477
+ return {
1478
+ env: parseEnvFile(readStateFile(file)),
1479
+ path: file,
1480
+ error: null
1481
+ };
1482
+ } catch (error) {
1483
+ if (error.code === "ENOENT") return {
1484
+ env: {},
1485
+ path: file,
1486
+ error: null
1487
+ };
1488
+ return {
1489
+ env: {},
1490
+ path: file,
1491
+ error: errorMessage(error)
1492
+ };
1493
+ }
1494
+ }
1495
+ var VARIABLE = /\$\{([A-Z_]\w*)\}/gi;
1496
+ /** Expands `${VAR}` from the given vars; unknown references are left visible. */
1497
+ function expandEnv(value, vars) {
1498
+ return value.replace(VARIABLE, (match, name) => vars[name] ?? match);
1499
+ }
1500
+ function expandEnvRecord(record, vars) {
1501
+ return Object.fromEntries(Object.entries(record).map(([key, value]) => [key, expandEnv(value, vars)]));
1502
+ }
1503
+ function expandEnvList(values, vars) {
1504
+ return values.map((value) => expandEnv(value, vars));
1505
+ }
1506
+ function resolveEnvFilePath(file, cwd) {
1507
+ if (path.isAbsolute(file)) return file;
1508
+ return path.resolve(cwd, file);
1509
+ }
1510
+ //#endregion
1511
+ //#region src/providers/webhook.ts
1512
+ /** The JSON body for one event. Exported so a test can pin the shape without a round trip. */
1513
+ function webhookPayload(event, now = Date.now()) {
1514
+ const text = `${event.title}\n${event.message}`;
1515
+ return {
1516
+ text,
1517
+ content: text,
1518
+ title: event.title,
1519
+ message: event.message,
1520
+ reason: event.reason,
1521
+ server: event.serverId.length > 0 ? event.serverId : null,
1522
+ label: event.label.length > 0 ? event.label : null,
1523
+ at: now
1524
+ };
1525
+ }
1526
+ /**
1527
+ * What `Headers` will refuse, decided here so the refusal names the line.
1528
+ *
1529
+ * This is not a second opinion about validity: `Headers` (and Node's own `http`) throw on a name
1530
+ * holding a space or a non-ASCII letter, and on a value holding a character above `0xFF` — so
1531
+ * `Title: 🔴 server down` fails at the request with `Cannot convert argument to a ByteString …
1532
+ * value of 55357`, beside a `lastResult` a person reads as the receiver's fault. HTTP header values
1533
+ * are bytes, not text: ntfy's own answer for an emoji title is `=?UTF-8?B?…?=`. Naming both here
1534
+ * means the save is refused with the line quoted, and a config that already holds one says which
1535
+ * header it is instead of surfacing a JS engine message.
1536
+ */
1537
+ function headerProblem(name, value) {
1538
+ if (!/^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/.test(name)) return `"${name}" is not a valid header name`;
1539
+ for (const char of value) if (char.codePointAt(0) > 255) 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`;
1540
+ return null;
1541
+ }
1542
+ /**
1543
+ * `Name: value` lines into a header map.
1544
+ *
1545
+ * The format is line-based rather than a JSON object because it is edited in a textarea, and
1546
+ * a value with a colon in it (`Authorization: Bearer a:b`) must survive: only the **first**
1547
+ * colon separates the two.
1548
+ *
1549
+ * `vars` expands `${ENV}` in the values, so a credential does not have to be written into the
1550
+ * config file. A name the panel's environment does not define is left as written, the same rule
1551
+ * `expandEnv` follows everywhere else — and `unexpanded` names those, because a leftover `${…}`
1552
+ * is not a credential.
1553
+ */
1554
+ function parseHeaders(text, vars = process.env) {
1555
+ const headers = {};
1556
+ const errors = [];
1557
+ const unexpanded = [];
1558
+ for (const line of text.split("\n")) {
1559
+ const trimmed = line.trim();
1560
+ if (trimmed.length === 0 || trimmed.startsWith("#")) continue;
1561
+ const at = trimmed.indexOf(":");
1562
+ if (at <= 0) {
1563
+ errors.push(`"${trimmed}" is not a "Name: value" header`);
1564
+ continue;
1565
+ }
1566
+ const name = trimmed.slice(0, at).trim();
1567
+ const value = expandEnv(trimmed.slice(at + 1).trim(), vars);
1568
+ if (value.includes("${")) unexpanded.push(name);
1569
+ else {
1570
+ const problem = headerProblem(name, value);
1571
+ if (problem !== null) {
1572
+ errors.push(problem);
1573
+ continue;
1574
+ }
1575
+ }
1576
+ headers[name] = value;
1577
+ }
1578
+ return {
1579
+ headers,
1580
+ errors,
1581
+ unexpanded
1582
+ };
1583
+ }
1584
+ /** Why a target cannot be sent to, or null when it can. Also used to validate a save. */
1585
+ function targetProblem(target, options = {}) {
1586
+ const url = target.url.trim();
1587
+ if (url.length === 0) return options.requireUrl === false ? null : "no URL configured";
1588
+ let parsed;
1589
+ try {
1590
+ parsed = new URL(url);
1591
+ } catch {
1592
+ return "the URL is not valid";
1593
+ }
1594
+ if (parsed.protocol !== "http:" && parsed.protocol !== "https:") return `the URL must be http or https, not ${parsed.protocol}`;
1595
+ const { errors, unexpanded } = parseHeaders(target.headers);
1596
+ const problems = [...errors, ...unexpanded.length > 0 ? [`the ${unexpanded.map((name) => `"${name}"`).join(", ")} header still holds an unexpanded placeholder — an environment variable in it is not set`] : []];
1597
+ return problems.length > 0 ? problems.join("; ") : null;
1598
+ }
1599
+ async function sendWebhook(target, event, fetchImpl) {
1600
+ const problem = targetProblem(target);
1601
+ if (problem !== null) return {
1602
+ ok: false,
1603
+ error: problem
1604
+ };
1605
+ const { headers, errors } = parseHeaders(target.headers);
1606
+ if (errors.length > 0) return {
1607
+ ok: false,
1608
+ error: errors.join("; ")
1609
+ };
1610
+ const payload = webhookPayload(event);
1611
+ const asText = target.format === "text";
1612
+ const body = asText ? payload.message : JSON.stringify(payload);
1613
+ const url = expandEnv(target.url.trim(), process.env);
1614
+ if (url.includes("${")) return {
1615
+ ok: false,
1616
+ error: `the URL still holds an unexpanded placeholder: ${url}`
1617
+ };
1618
+ const sent = { "content-type": asText ? "text/plain; charset=utf-8" : "application/json" };
1619
+ for (const [name, value] of Object.entries(headers)) {
1620
+ const key = name.toLowerCase();
1621
+ for (const existing of Object.keys(sent)) if (existing.toLowerCase() === key) delete sent[existing];
1622
+ sent[name] = value;
1623
+ }
1624
+ try {
1625
+ const response = await (fetchImpl ?? fetch)(url, {
1626
+ method: target.method,
1627
+ headers: sent,
1628
+ body,
1629
+ signal: AbortSignal.timeout(1e4)
1630
+ });
1631
+ if (!response.ok) {
1632
+ const trimmed = (await response.text().catch(() => "")).trim().slice(0, 200);
1633
+ return {
1634
+ ok: false,
1635
+ error: `answered ${response.status}${trimmed.length > 0 ? `: ${trimmed}` : ""}`
1636
+ };
1637
+ }
1638
+ return { ok: true };
1639
+ } catch (error) {
1640
+ return {
1641
+ ok: false,
1642
+ error: errorMessage(error)
1643
+ };
1644
+ }
1645
+ }
1646
+ //#endregion
1647
+ //#region src/config/store.ts
1648
+ function readFile(file) {
1649
+ let text;
1650
+ try {
1651
+ text = readStateFile(file);
1652
+ } catch (error) {
1653
+ if (error.code === "ENOENT") return {
1654
+ text: null,
1655
+ parsed: null,
1656
+ missing: true,
1657
+ parseError: null
1658
+ };
1659
+ return {
1660
+ text: null,
1661
+ parsed: null,
1662
+ missing: false,
1663
+ parseError: error.message
1664
+ };
1665
+ }
1666
+ try {
1667
+ return {
1668
+ text,
1669
+ parsed: JSON.parse(text),
1670
+ missing: false,
1671
+ parseError: null
1672
+ };
1673
+ } catch (error) {
1674
+ return {
1675
+ text,
1676
+ parsed: null,
1677
+ missing: false,
1678
+ parseError: error.message
1679
+ };
1680
+ }
1681
+ }
1682
+ /**
1683
+ * One workspace's state: its settings file (`defaults`, `logs`, `notifications`,
1684
+ * `ddns`) and its servers file, kept apart because they are written by different
1685
+ * pages and read by different parts of the panel.
1686
+ *
1687
+ * Reads stay tolerant in both: an unknown key is reported and skipped, never
1688
+ * fatal, so a file written by a newer release still opens the page that edits it.
1689
+ * A file this release cannot even parse never replaces what is already running —
1690
+ * neither the resolved config nor the `raw` every write patches.
1691
+ */
1692
+ var WorkspaceStore = class {
1693
+ workspaceId;
1694
+ settingsFile;
1695
+ serversFile;
1696
+ seedSettings;
1697
+ seedServers;
1698
+ rawSettings = {};
1699
+ rawServers = {};
1700
+ liveSettings = null;
1701
+ liveServers = null;
1702
+ lastSettingsText = null;
1703
+ lastServersText = null;
1704
+ resolvedConfig;
1705
+ /** A JSON parse failure, kept apart from a schema problem so `apply()` cannot clear it. */
1706
+ settingsParseError = null;
1707
+ serversParseError = null;
1708
+ settingsError = null;
1709
+ serversError = null;
1710
+ warnings = [];
1711
+ settingsSchemaVersion = 1;
1712
+ serversSchemaVersion = 1;
1713
+ listeners = /* @__PURE__ */ new Set();
1714
+ constructor(workspaceId, settingsFile, serversFile, seedSettings = SEED_WORKSPACE_SETTINGS, seedServers = SEED_SERVERS_FILE) {
1715
+ this.workspaceId = workspaceId;
1716
+ this.settingsFile = settingsFile;
1717
+ this.serversFile = serversFile;
1718
+ this.seedSettings = seedSettings;
1719
+ this.seedServers = seedServers;
1720
+ }
1721
+ get id() {
1722
+ return this.workspaceId;
1723
+ }
1724
+ /** The servers config; the runtime, the watcher and the docs call it that. */
1725
+ get path() {
1726
+ return this.serversFile;
1727
+ }
1728
+ get settingsPath() {
1729
+ return this.settingsFile;
1730
+ }
1731
+ get config() {
1732
+ return this.resolvedConfig;
1733
+ }
1734
+ get servers() {
1735
+ return this.resolvedConfig.servers;
1736
+ }
1737
+ get defaults() {
1738
+ return this.resolvedConfig.defaults;
1739
+ }
1740
+ get logs() {
1741
+ return this.resolvedConfig.logs;
1742
+ }
1743
+ get notifications() {
1744
+ return this.resolvedConfig.notifications;
1745
+ }
1746
+ get ddns() {
1747
+ return this.resolvedConfig.ddns;
1748
+ }
1749
+ get configError() {
1750
+ return [this.settingsParseError ?? this.settingsError, this.serversParseError ?? this.serversError].filter((error) => error !== null).join("; ") || null;
1751
+ }
1752
+ get configWarnings() {
1753
+ return [...this.warnings];
1754
+ }
1755
+ get configSchemaVersion() {
1756
+ return Math.max(this.settingsSchemaVersion, this.serversSchemaVersion);
1757
+ }
1758
+ /**
1759
+ * The steps a workspace's files need, counting **both** sides.
1760
+ *
1761
+ * The two files are stamped independently — a person may hand-write `servers.config.json`
1762
+ * (which is unstamped, and so reads as schema 1) beside a `settings.json` the panel wrote at
1763
+ * the current schema. `configSchemaVersion` answers `max()` because that is the shape *this
1764
+ * release* understands of the pair, but the migrations that have to run belong to the **older**
1765
+ * file: `planConfigMigrations` is monotonic, so the lower version is the one with steps.
1766
+ * Reading `max()` here reported *no* pending migration while the reader was refusing the file
1767
+ * for needing one, which left the startup branch that says `run migrate` unreachable and sent
1768
+ * the person to "fix or install" instead.
1769
+ *
1770
+ * A file that cannot be **parsed** is not a migration candidate, though: a schema number can only
1771
+ * be read from a file that is JSON, and `migrate` refuses one it cannot read rather than lifting
1772
+ * it. The startup guard prints this list as "run migrate", so a broken file must not appear
1773
+ * here — it belongs in `configError`'s "fix …" advice alone.
1774
+ */
1775
+ get pendingMigrations() {
1776
+ if (this.settingsParseError !== null || this.serversParseError !== null) return [];
1777
+ return planConfigMigrations(Math.min(this.settingsSchemaVersion, this.serversSchemaVersion)).steps;
1778
+ }
1779
+ onChange(listener) {
1780
+ this.listeners.add(listener);
1781
+ return () => this.listeners.delete(listener);
1782
+ }
1783
+ /** How many listeners are attached; a disposed owner must not add to it. */
1784
+ get listenerCount() {
1785
+ return this.listeners.size;
1786
+ }
1787
+ getServer(id) {
1788
+ return this.servers.find((server) => server.id === id);
1789
+ }
1790
+ load() {
1791
+ this.read();
1792
+ this.apply();
1793
+ this.notify();
1794
+ }
1795
+ /**
1796
+ * The watcher's entry point: re-reads the files only when their bytes changed.
1797
+ *
1798
+ * `changed` means the bytes on disk differ from the last trusted read, `applied`
1799
+ * means that difference produced a usable config. A revision this release cannot
1800
+ * parse is reported in the state frame while the running config is kept, which is
1801
+ * what stops an editor's typo from stopping every server — or from bricking the
1802
+ * next Save, which patches the raw object this method must therefore leave alone.
1803
+ */
1804
+ reloadFromDisk() {
1805
+ const settings = readFile(this.settingsFile);
1806
+ const servers = readFile(this.serversFile);
1807
+ if (settings.missing || servers.missing) {
1808
+ this.markGone(settings.missing ? this.settingsFile : this.serversFile);
1809
+ return {
1810
+ changed: false,
1811
+ applied: false,
1812
+ error: this.configError
1813
+ };
1814
+ }
1815
+ let changed = false;
1816
+ let applied = false;
1817
+ for (const side of ["settings", "servers"]) {
1818
+ const read = side === "settings" ? settings : servers;
1819
+ const lastText = side === "settings" ? this.lastSettingsText : this.lastServersText;
1820
+ const file = side === "settings" ? this.settingsFile : this.serversFile;
1821
+ if (read.text !== lastText) {
1822
+ changed = true;
1823
+ if (side === "settings") this.lastSettingsText = read.text;
1824
+ else this.lastServersText = read.text;
1825
+ }
1826
+ if (read.parseError !== null) {
1827
+ const message = `cannot parse ${path.basename(file)}: ${read.parseError}`;
1828
+ if (side === "settings") this.settingsParseError = message;
1829
+ else this.serversParseError = message;
1830
+ continue;
1831
+ }
1832
+ if (read.text !== lastText) {
1833
+ if (side === "settings") {
1834
+ this.settingsParseError = null;
1835
+ this.liveSettings = read.parsed;
1836
+ } else {
1837
+ this.serversParseError = null;
1838
+ this.liveServers = read.parsed;
1839
+ }
1840
+ applied = true;
1841
+ }
1842
+ }
1843
+ if (!changed && !applied && this.configError === null) return {
1844
+ changed: false,
1845
+ applied: false,
1846
+ error: null
1847
+ };
1848
+ this.apply();
1849
+ this.notify();
1850
+ return {
1851
+ changed,
1852
+ applied,
1853
+ error: this.configError
1854
+ };
1855
+ }
1856
+ markGone(file) {
1857
+ const message = `${path.basename(file)} is gone`;
1858
+ if (file === this.settingsFile) this.settingsError = message;
1859
+ else this.serversError = message;
1860
+ }
1861
+ read() {
1862
+ let settings = readFile(this.settingsFile);
1863
+ if (settings.missing) {
1864
+ const seed = stampConfig(structuredClone(this.seedSettings));
1865
+ const text = `${JSON.stringify(seed, null, 2)}\n`;
1866
+ writeFileAtomic(this.settingsFile, text);
1867
+ settings = {
1868
+ text,
1869
+ parsed: seed,
1870
+ missing: false,
1871
+ parseError: null
1872
+ };
1873
+ }
1874
+ let servers = readFile(this.serversFile);
1875
+ if (servers.missing) {
1876
+ const seed = stampConfig(structuredClone(this.seedServers));
1877
+ const text = `${JSON.stringify(seed, null, 2)}\n`;
1878
+ writeFileAtomic(this.serversFile, text);
1879
+ servers = {
1880
+ text,
1881
+ parsed: seed,
1882
+ missing: false,
1883
+ parseError: null
1884
+ };
1885
+ }
1886
+ this.lastSettingsText = settings.text;
1887
+ this.lastServersText = servers.text;
1888
+ this.liveSettings = settings.parsed;
1889
+ this.liveServers = servers.parsed;
1890
+ this.settingsParseError = settings.parseError === null ? null : `cannot parse ${path.basename(this.settingsFile)}: ${settings.parseError}`;
1891
+ this.serversParseError = servers.parseError === null ? null : `cannot parse ${path.basename(this.serversFile)}: ${servers.parseError}`;
1892
+ if (settings.parseError === null) this.liveSettings = settings.parsed;
1893
+ if (servers.parseError === null) this.liveServers = servers.parsed;
1894
+ }
1895
+ notify() {
1896
+ for (const listener of this.listeners) listener();
1897
+ }
1898
+ updateServer(id, patch) {
1899
+ const index = (this.rawServers.servers ?? []).findIndex((entry) => entry.id === id);
1900
+ if (index < 0) throw new ConfigError(`unknown server "${id}"`, "UNKNOWN_SERVER");
1901
+ const draft = structuredClone(this.rawServers);
1902
+ const entry = draft.servers[index];
1903
+ applyPatch(entry, patch, SERVER_MERGE_KEYS);
1904
+ const validated = this.validateServer(entry, `servers[${index}]`);
1905
+ this.commitServers(draft);
1906
+ return validated;
1907
+ }
1908
+ updateDefaults(patch) {
1909
+ const draft = structuredClone(this.rawSettings);
1910
+ draft.defaults = { ...draft.defaults ?? {} };
1911
+ applyPatch(draft.defaults, patch, SERVER_MERGE_KEYS);
1912
+ const defaults = this.parseGroup(defaultsSchema, draft.defaults, "defaults");
1913
+ this.commitSettings(draft);
1914
+ return defaults;
1915
+ }
1916
+ updateLogs(patch) {
1917
+ const draft = structuredClone(this.rawSettings);
1918
+ draft.logs = { ...draft.logs ?? {} };
1919
+ applyPatch(draft.logs, patch, EMPTY_MERGE_KEYS);
1920
+ const logs = this.parseGroup(logsSchema, draft.logs, "logs");
1921
+ this.commitSettings(draft);
1922
+ return logs;
1923
+ }
1924
+ updateNotifications(patch) {
1925
+ const draft = structuredClone(this.rawSettings);
1926
+ draft.notifications = { ...draft.notifications ?? {} };
1927
+ applyPatch(draft.notifications, patch, NOTIFICATION_MERGE_KEYS);
1928
+ const notifications = this.parseGroup(notificationsSchema, draft.notifications, "notifications");
1929
+ const duplicates = duplicateWebhookIds(notifications.destinations);
1930
+ if (duplicates.length > 0) throw new ConfigError(`notifications: duplicate webhook id ${duplicates.map((id) => `"${id}"`).join(", ")}`);
1931
+ for (const target of notifications.destinations) {
1932
+ if (target.kind !== "webhook") continue;
1933
+ const problem = targetProblem(target, { requireUrl: true });
1934
+ if (problem !== null) throw new ConfigError(`notifications: webhook "${target.id}" ${problem}`);
1935
+ }
1936
+ this.commitSettings(draft);
1937
+ return notifications;
1938
+ }
1939
+ /**
1940
+ * The DDNS block merges its two nested groups and **replaces** `accounts` and
1941
+ * `domains`: those are lists, and a key-by-key merge cannot express removing a
1942
+ * hostname. A whole-block patch (the `PUT /api/ddns` route) lands the same way.
1943
+ */
1944
+ updateDdns(patch) {
1945
+ const draft = structuredClone(this.rawSettings);
1946
+ draft.ddns = { ...draft.ddns ?? {} };
1947
+ applyPatch(draft.ddns, patch, DDNS_MERGE_KEYS);
1948
+ const parsed = this.parseGroup(ddnsConfigSchema, draft.ddns, "ddns");
1949
+ const problems = validateDdnsConfig(parsed);
1950
+ if (problems.length > 0) throw new ConfigError(`ddns: ${problems.join("; ")}`);
1951
+ this.commitSettings(draft);
1952
+ return parsed;
1953
+ }
1954
+ addServer(input) {
1955
+ const draft = structuredClone(this.rawServers);
1956
+ const list = draft.servers ?? (draft.servers = []);
1957
+ if (list.some((entry) => entry.id === input.id)) throw new ConfigError(`server "${String(input.id)}" already exists`);
1958
+ const index = list.length;
1959
+ list.push(structuredClone(input));
1960
+ const validated = this.validateServer(list[index], `servers[${index}]`);
1961
+ this.commitServers(draft);
1962
+ return validated;
1963
+ }
1964
+ /**
1965
+ * Creates the entry, or replaces a same-id one outright — "make it so".
1966
+ *
1967
+ * `addServer` refuses a duplicate and `updateServer` only patches an existing entry, so a config
1968
+ * management pass had to GET, diff, then POST or PATCH, and a re-run of an unchanged declaration
1969
+ * got `400 INVALID_SERVER` for its trouble. A replace is what a declarative caller means: the
1970
+ * body is the whole entry, not a patch.
1971
+ *
1972
+ * Returns whether it created or replaced, so the route can answer 201 or 200 honestly.
1973
+ */
1974
+ putServer(input) {
1975
+ const draft = structuredClone(this.rawServers);
1976
+ const list = draft.servers ?? (draft.servers = []);
1977
+ const index = list.findIndex((entry) => entry.id === input.id);
1978
+ const created = index < 0;
1979
+ if (created) list.push(structuredClone(input));
1980
+ else list[index] = structuredClone(input);
1981
+ const validated = this.validateServer(list[created ? list.length - 1 : index], `servers[${created ? list.length - 1 : index}]`);
1982
+ this.commitServers(draft);
1983
+ return {
1984
+ server: validated,
1985
+ created
1986
+ };
1987
+ }
1988
+ removeServer(id) {
1989
+ const draft = structuredClone(this.rawServers);
1990
+ const list = draft.servers ?? [];
1991
+ const before = list.length;
1992
+ draft.servers = list.filter((entry) => entry.id !== id);
1993
+ if (draft.servers.length === before) throw new ConfigError(`unknown server "${id}"`, "UNKNOWN_SERVER");
1994
+ this.commitServers(draft);
1995
+ }
1996
+ /**
1997
+ * Regenerates both JSON schemas for editor autocomplete, beside the files they
1998
+ * describe — derived from this store's own paths, never from a module-level
1999
+ * default, so a store over a custom root cannot write into `$HHOSTED_HOME`.
2000
+ */
2001
+ writeJsonSchema() {
2002
+ this.writeSchema(path.join(path.dirname(this.settingsFile), "settings.schema.json"), workspaceSettingsSchema);
2003
+ this.writeSchema(path.join(path.dirname(this.serversFile), `${path.basename(this.serversFile, ".json")}.schema.json`), serversFileSchema);
2004
+ }
2005
+ writeSchema(file, schema) {
2006
+ const text = JSON.stringify(schema.toJsonSchema(), null, 2);
2007
+ if ((fs.existsSync(file) ? fs.readFileSync(file, "utf8") : null) !== text) writeFileAtomic(file, text);
2008
+ }
2009
+ parseGroup(schema, value, label) {
2010
+ const parsed = parseTolerant(value, schema, label, []);
2011
+ if (parsed.error !== null) throw new ConfigError(`${label}: ${parsed.error}`);
2012
+ return parsed.value;
2013
+ }
2014
+ validateServer(entry, label) {
2015
+ const parsed = serverSchema(mergeDefaults(this.defaults, entry));
2016
+ if (parsed instanceof type.errors) throw new ConfigError(`${label}: ${parsed.summary}`);
2017
+ return {
2018
+ ...parsed,
2019
+ port: parsed.port ?? null
2020
+ };
2021
+ }
2022
+ commitSettings(draft) {
2023
+ const stamped = stampConfig(draft);
2024
+ const text = `${JSON.stringify(stamped, null, 2)}\n`;
2025
+ writeFileAtomic(this.settingsFile, text);
2026
+ this.lastSettingsText = text;
2027
+ this.liveSettings = stamped;
2028
+ this.settingsParseError = null;
2029
+ this.apply();
2030
+ this.notify();
2031
+ }
2032
+ commitServers(draft) {
2033
+ const stamped = stampConfig(draft);
2034
+ const text = `${JSON.stringify(stamped, null, 2)}\n`;
2035
+ writeFileAtomic(this.serversFile, text);
2036
+ this.lastServersText = text;
2037
+ this.liveServers = stamped;
2038
+ this.serversParseError = null;
2039
+ this.apply();
2040
+ this.notify();
2041
+ }
2042
+ apply() {
2043
+ const settings = parseWorkspaceSettings(this.liveSettings);
2044
+ const servers = parseServersFile(this.liveServers, settings.config?.defaults ?? {});
2045
+ const haveResolved = this.resolvedConfig !== void 0;
2046
+ this.settingsError = this.settingsParseError ?? (settings.errors.length > 0 ? settings.errors.join("; ") : null);
2047
+ this.serversError = this.serversParseError ?? (servers.errors.length > 0 ? servers.errors.join("; ") : null);
2048
+ this.settingsSchemaVersion = settings.schemaVersion;
2049
+ this.serversSchemaVersion = servers.schemaVersion;
2050
+ this.warnings = [
2051
+ ...settings.warnings,
2052
+ ...servers.warnings,
2053
+ ...settings.unknownKeys.length === 0 && servers.unknownKeys.length === 0 ? [] : [`this workspace carries ${settings.unknownKeys.length + servers.unknownKeys.length} unrecognized key(s) this release ignores: ${[...settings.unknownKeys, ...servers.unknownKeys].join(", ")}`]
2054
+ ];
2055
+ const settingsConfig = settings.config ?? (haveResolved ? {
2056
+ defaults: this.resolvedConfig.defaults,
2057
+ logs: this.resolvedConfig.logs,
2058
+ notifications: this.resolvedConfig.notifications,
2059
+ ddns: this.resolvedConfig.ddns
2060
+ } : this.resolveSettingsFallback());
2061
+ const nextServers = servers.errors.length === 0 ? servers.servers : haveResolved ? this.resolvedConfig.servers : [];
2062
+ this.resolvedConfig = {
2063
+ ...settingsConfig,
2064
+ servers: nextServers
2065
+ };
2066
+ if (settings.config !== null) this.rawSettings = structuredClone(this.liveSettings);
2067
+ if (servers.errors.length === 0) this.rawServers = structuredClone(this.liveServers);
2068
+ }
2069
+ resolveSettingsFallback() {
2070
+ const defaults = defaultsSchema({});
2071
+ const logs = logsSchema({});
2072
+ const notifications = notificationsSchema({});
2073
+ const ddns = ddnsConfigSchema({});
2074
+ if (defaults instanceof type.errors || logs instanceof type.errors || notifications instanceof type.errors || ddns instanceof type.errors) throw new ConfigError("internal: default workspace settings failed validation");
2075
+ return {
2076
+ defaults,
2077
+ logs,
2078
+ notifications,
2079
+ ddns
2080
+ };
2081
+ }
2082
+ };
2083
+ //#endregion
2084
+ //#region src/providers/entry-state.ts
2085
+ /**
2086
+ * The small slice of a server's runtime the panel has to remember across its own
2087
+ * restarts: how much of the retry budget is spent, and whether a `runOnce` bootstrap
2088
+ * already ran.
2089
+ *
2090
+ * Both lived only in memory, so a panel restart — a `restart`, a crash, a reboot —
2091
+ * handed a crash-looping server a fresh `maxRetries` and re-ran its bootstrap. The
2092
+ * retry counter has to outlive the process that increments it to bound anything.
2093
+ */
2094
+ /** One JSON file per entry, beside the nanny's own state. */
2095
+ function entryStatePath(dir, id) {
2096
+ return path.join(dir, `${id}.run.json`);
2097
+ }
2098
+ function readEntryState(file) {
2099
+ try {
2100
+ const parsed = entryStateSchema(JSON.parse(fs.readFileSync(file, "utf8")));
2101
+ return parsed instanceof type.errors ? null : parsed;
2102
+ } catch {
2103
+ return null;
2104
+ }
2105
+ }
2106
+ function writeEntryState(file, state) {
2107
+ try {
2108
+ writeFileAtomic(file, `${JSON.stringify(state)}\n`);
2109
+ } catch {}
2110
+ }
2111
+ function clearEntryState(file) {
2112
+ fs.rmSync(file, { force: true });
2113
+ }
2114
+ //#endregion
2115
+ //#region src/config/secret-parts.ts
2116
+ /** Every secret this release knows about, set or not — the view lists the slots so a person sees one. */
2117
+ var KNOWN_SECRET_KEYS = {
2118
+ global: ["password", "apiToken"],
2119
+ workspace: ["telegram", "ddns"]
2120
+ };
2121
+ /** Where a secret this release knows lives. Everything else is scoped by its own file. */
2122
+ var KNOWN_SCOPES = {
2123
+ password: "global",
2124
+ apiToken: "global",
2125
+ telegram: "workspace",
2126
+ ddns: "workspace"
2127
+ };
2128
+ /** A part carrying more than its own key: `ddnsKdf` is how the sealed DDNS entries are opened. */
2129
+ var EXTRA_FIELDS = { ddns: ["ddns", "ddnsKdf"] };
2130
+ /**
2131
+ * The parts of one scope, in a stable order: the known parts first in the fixed order
2132
+ * password, apiToken (global) / telegram, ddns (workspace) — then any other top-level
2133
+ * key present in `present`, sorted, as its own part with `fields: [key]`.
2134
+ *
2135
+ * An unknown key is taken as belonging to the scope being asked about, because the file
2136
+ * it was read from is the only evidence of where it lives: this release does not know the
2137
+ * key, so classifying it by name would drop a future *global* secret on the floor.
2138
+ */
2139
+ function secretParts(scope, present) {
2140
+ const keys = new Set(present);
2141
+ const known = KNOWN_SECRET_KEYS[scope];
2142
+ const parts = known.filter((key) => keys.has(key)).map((key) => ({
2143
+ key,
2144
+ fields: EXTRA_FIELDS[key] ?? [key],
2145
+ scope
2146
+ }));
2147
+ const consumed = new Set(parts.flatMap((part) => part.fields));
2148
+ const rest = [...keys].filter((key) => KNOWN_SCOPES[key] === void 0 && !known.includes(key) && !consumed.has(key)).sort();
2149
+ return [...parts, ...rest.map((key) => ({
2150
+ key,
2151
+ fields: [key],
2152
+ scope
2153
+ }))];
2154
+ }
2155
+ /** The top-level keys of a raw secrets document that hold a non-null value. */
2156
+ function presentSecretKeys(source) {
2157
+ return Object.entries(source).filter(([, value]) => value !== null && value !== void 0).map(([key]) => key);
2158
+ }
2159
+ /**
2160
+ * A JSON string carrying only `fields`, taken from `source`. Returns null when `source`
2161
+ * carries none of them. Always includes a field whose value is `null` ONLY if it is
2162
+ * present as a key and non-null; a null/absent field is omitted.
2163
+ */
2164
+ function pickSecrets(source, fields) {
2165
+ const picked = {};
2166
+ for (const field of fields) {
2167
+ const value = source[field];
2168
+ if (value !== null && value !== void 0) picked[field] = withoutFirstRunPassword(value);
2169
+ }
2170
+ return Object.keys(picked).length === 0 ? null : JSON.stringify(picked);
2171
+ }
2172
+ /**
2173
+ * Drops `password.initial` — the generated first-run password, which the live file keeps so `up` and
2174
+ * `status` can show it on the machine.
2175
+ *
2176
+ * An archive is a copy *off* the box: unencrypted unless a password was given, and the docs recommend
2177
+ * keeping it elsewhere, so carrying the plaintext there hands a reader a working credential the hash
2178
+ * beside it exists to avoid. The hash restores a password, which is all a restore needs.
2179
+ */
2180
+ function withoutFirstRunPassword(value) {
2181
+ if (!isRecord(value) || !("initial" in value)) return value;
2182
+ const { initial: _initial, ...rest } = value;
2183
+ return rest;
2184
+ }
2185
+ /**
2186
+ * The same removal, applied to a whole secrets **document** rather than one field's value.
2187
+ *
2188
+ * `pickSecrets` already drops the field, but a backup that selects every secret copies the file
2189
+ * whole and so bypassed it. This is that whole-file path: the document keeps every other key —
2190
+ * including `null` slots and keys this release does not know — and differs only in that
2191
+ * `password.initial` is gone. Returns `null` when the text is not a JSON object, so the caller can
2192
+ * fall back to its ordinary copy.
2193
+ */
2194
+ function withoutInitialPassword(text) {
2195
+ let parsed;
2196
+ try {
2197
+ parsed = JSON.parse(text);
2198
+ } catch {
2199
+ return null;
2200
+ }
2201
+ if (!isRecord(parsed)) return null;
2202
+ return `${JSON.stringify("password" in parsed ? {
2203
+ ...parsed,
2204
+ password: withoutFirstRunPassword(parsed.password)
2205
+ } : parsed)}\n`;
2206
+ }
2207
+ /** Parses a secrets document, tolerating anything: not-an-object, or broken JSON returns {}. */
2208
+ function parseSecrets(text) {
2209
+ try {
2210
+ const parsed = JSON.parse(text);
2211
+ return isRecord(parsed) ? parsed : {};
2212
+ } catch {
2213
+ return {};
2214
+ }
2215
+ }
2216
+ /**
2217
+ * Merges `piece` into `current`, changing ONLY the fields in `fields` — every other key
2218
+ * of `current` is preserved (this is what stops restoring the Telegram token from wiping
2219
+ * the DDNS credentials). A field that is absent from `piece` is also DELETED from the
2220
+ * result, so restoring an older archive that predates a secret clears it rather than
2221
+ * leaving a stale value. Returns a new object; does not mutate its arguments.
2222
+ */
2223
+ function mergeSecrets(current, piece, fields) {
2224
+ const merged = { ...current };
2225
+ for (const field of fields) {
2226
+ const value = piece[field];
2227
+ if (value === null || value === void 0) delete merged[field];
2228
+ else merged[field] = value;
2229
+ }
2230
+ return merged;
2231
+ }
2232
+ //#endregion
2233
+ //#region src/helpers/restore-lock.ts
2234
+ /**
2235
+ * A lock file that stops two restores from writing the same host at once.
2236
+ *
2237
+ * A restore replaces config and data paths in place. Two of them interleaved — or one from the CLI
2238
+ * while the panel's own restore runs — write over each other, and neither knows the other exists.
2239
+ * That is also why it has to cover **both** paths: the panel and the offline CLI take the same lock,
2240
+ * so they exclude each other rather than only themselves.
2241
+ *
2242
+ * A pid that is gone means the holder died mid-restore, which used to leave a lock nobody could
2243
+ * clear. Stale is decided the same way `up`/`down` decide it — the recorded pid *and* its start time —
2244
+ * so a recycled pid is not mistaken for a live holder.
2245
+ */
2246
+ /** How long a restore may hold the lock before another waits no longer on it. */
2247
+ var STALE_AFTER_MS = 18e5;
2248
+ /** Absorbs the one-second granularity of a birth-time reading against the moment we recorded it. */
2249
+ var BIRTH_TOLERANCE_MS = 2e3;
2250
+ function readRecord(file) {
2251
+ try {
2252
+ const parsed = JSON.parse(fs.readFileSync(file, "utf8"));
2253
+ if (typeof parsed.pid !== "number" || typeof parsed.startedAt !== "number") return null;
2254
+ return {
2255
+ pid: parsed.pid,
2256
+ startedAt: parsed.startedAt,
2257
+ action: typeof parsed.action === "string" ? parsed.action : "restore",
2258
+ birthAt: typeof parsed.birthAt === "number" ? parsed.birthAt : null
2259
+ };
2260
+ } catch {
2261
+ return null;
2262
+ }
2263
+ }
2264
+ /**
2265
+ * Is the recorded holder still the process that took it?
2266
+ *
2267
+ * Signal 0 alone is not enough — pids are recycled, and a zombie answers it — so the process's own
2268
+ * start time is compared with the recorded one where the platform can report it. Elsewhere the pid is
2269
+ * all there is, and an alive pid is taken as alive, which errs towards "somebody is working" rather
2270
+ * than stealing a live lock.
2271
+ */
2272
+ function holderIsAlive(record) {
2273
+ try {
2274
+ process.kill(record.pid, 0);
2275
+ } catch (error) {
2276
+ return error.code === "EPERM";
2277
+ }
2278
+ const birth = processBirthSync(record.pid);
2279
+ if (birth === null) return true;
2280
+ if (record.birthAt != null) return Math.abs(birth - record.birthAt) <= BIRTH_TOLERANCE_MS;
2281
+ return birth <= record.startedAt + BIRTH_TOLERANCE_MS;
2282
+ }
2283
+ /** Wall-clock start of a pid in ms, or null where the platform cannot report one. */
2284
+ function processBirthSync(pid) {
2285
+ try {
2286
+ const stat = fs.readFileSync(`/proc/${pid}/stat`, "utf8");
2287
+ const fields = stat.slice(stat.lastIndexOf(")") + 2).split(" ");
2288
+ const ticks = Number.parseFloat(fields[19] ?? "");
2289
+ if (!Number.isFinite(ticks)) return null;
2290
+ const boot = /^btime (\d+)$/m.exec(fs.readFileSync("/proc/stat", "utf8"))?.[1];
2291
+ if (boot === void 0) return null;
2292
+ return Number.parseInt(boot, 10) * 1e3 + ticks / 100 * 1e3;
2293
+ } catch {
2294
+ return null;
2295
+ }
2296
+ }
2297
+ /** The live holder of the restore lock, without taking it; null when nobody is restoring. */
2298
+ function restoreLockHolder(hhDir) {
2299
+ const existing = readRecord(path.join(hhDir, "restore.lock"));
2300
+ return existing !== null && isLiveHolder(existing) ? existing : null;
2301
+ }
2302
+ /** The holder is alive and has not held the lock absurdly long. */
2303
+ function isLiveHolder(record) {
2304
+ return holderIsAlive(record) && Date.now() - record.startedAt <= STALE_AFTER_MS;
2305
+ }
2306
+ /**
2307
+ * Take the restore lock, or explain who holds it.
2308
+ *
2309
+ * `null` means somebody else is restoring. The caller reports it rather than queueing: a restore is
2310
+ * an interactive decision, and waiting on one you did not start is not what a person asked for.
2311
+ */
2312
+ function acquireRestoreLock(hhDir, action = "restore") {
2313
+ const file = path.join(hhDir, "restore.lock");
2314
+ fs.mkdirSync(hhDir, { recursive: true });
2315
+ const mine = {
2316
+ pid: process.pid,
2317
+ startedAt: Date.now(),
2318
+ action,
2319
+ birthAt: processBirthSync(process.pid)
2320
+ };
2321
+ const release = () => {
2322
+ const current = readRecord(file);
2323
+ if (current !== null && (current.pid !== mine.pid || current.startedAt !== mine.startedAt)) return;
2324
+ fs.rmSync(file, { force: true });
2325
+ };
2326
+ const existing = readRecord(file);
2327
+ if (existing !== null) {
2328
+ if (isLiveHolder(existing)) return { heldBy: existing };
2329
+ writeFileAtomic(file, `${JSON.stringify(mine)}\n`, { mode: 384 });
2330
+ return {
2331
+ release,
2332
+ replaced: existing
2333
+ };
2334
+ }
2335
+ try {
2336
+ fs.writeFileSync(file, `${JSON.stringify(mine)}\n`, {
2337
+ flag: "wx",
2338
+ mode: 384
2339
+ });
2340
+ } catch (error) {
2341
+ if (error.code === "EEXIST") {
2342
+ const holder = readRecord(file);
2343
+ return holder === null ? { heldBy: {
2344
+ pid: 0,
2345
+ startedAt: Date.now(),
2346
+ action: "unreadable"
2347
+ } } : { heldBy: holder };
2348
+ }
2349
+ throw error;
2350
+ }
2351
+ let released = false;
2352
+ return { release: () => {
2353
+ if (released) return;
2354
+ released = true;
2355
+ release();
2356
+ } };
2357
+ }
2358
+ //#endregion
2359
+ //#region src/helpers/template.ts
2360
+ /**
2361
+ * Replaces `{name}` placeholders. Unknown placeholders are left untouched so a
2362
+ * typo surfaces in the child's args instead of silently becoming an empty string.
2363
+ */
2364
+ function resolveTemplate(value, vars) {
2365
+ return value.replace(/(?<!\$)\{([a-z][\w-]*)\}/gi, (match, name) => {
2366
+ const replacement = vars[name];
2367
+ return replacement === void 0 ? match : String(replacement);
2368
+ });
2369
+ }
2370
+ function resolveTemplates(value, vars) {
2371
+ if (Array.isArray(value)) return value.map((entry) => resolveTemplate(entry, vars));
2372
+ return resolveTemplate(value, vars);
2373
+ }
2374
+ function resolveRecord(record, vars) {
2375
+ return Object.fromEntries(Object.entries(record).map(([key, value]) => [key, resolveTemplate(value, vars)]));
2376
+ }
2377
+ //#endregion
2378
+ //#region src/helpers/bind.ts
2379
+ /**
2380
+ * How long the LAN address stays good.
2381
+ *
2382
+ * `os.networkInterfaces()` is not free: it was measured at **34–62 ms per call** on a machine
2383
+ * with three interfaces (median 51 ms, 30 calls), because libuv enumerates every interface and
2384
+ * every address each time. `lanAddress()` is called from `serverTemplateVars`, which runs once per
2385
+ * server inside a state frame — so a 40-entry panel called it 82 times per build and spent ~4.2 s
2386
+ * of a 4.3 s window blocked inside it, with the tick publishing once a second. `/healthz` took
2387
+ * 3.1–4.2 s and every `/api` route waited behind the same loop.
2388
+ *
2389
+ * A home server's LAN address changes when DHCP moves it, a cable moves, or a VPN comes up, and a
2390
+ * half-minute of staleness costs one stale "open server" link that the next frame corrects. So the
2391
+ * value is cached, and the cache is short enough that a network change is picked up without a
2392
+ * restart.
2393
+ */
2394
+ var LAN_ADDRESS_TTL_MS = 3e4;
2395
+ var cached = null;
2396
+ /**
2397
+ * This machine's first non-internal IPv4 address, or null when it has none.
2398
+ *
2399
+ * Cached for `LAN_ADDRESS_TTL_MS`: the call is expensive and its answer is read per server per
2400
+ * state frame. The cache is module state, which is acceptable here for the same reason
2401
+ * `appVersion()`'s is — the answer is a property of the host, not of a workspace, and nothing in
2402
+ * a test changes the interfaces it observes.
2403
+ */
2404
+ function lanAddress(now = Date.now()) {
2405
+ if (cached !== null && now - cached.at < LAN_ADDRESS_TTL_MS) return cached.value;
2406
+ let value = null;
2407
+ for (const entries of Object.values(os.networkInterfaces())) {
2408
+ for (const entry of entries ?? []) if (entry.family === "IPv4" && !entry.internal) {
2409
+ value = entry.address;
2410
+ break;
2411
+ }
2412
+ if (value !== null) break;
2413
+ }
2414
+ cached = {
2415
+ value,
2416
+ at: now
2417
+ };
2418
+ return value;
2419
+ }
2420
+ function bindHost(bind) {
2421
+ if (bind === "local") return "127.0.0.1";
2422
+ if (bind === "lan") return "0.0.0.0";
2423
+ return bind;
2424
+ }
2425
+ /** Address a human should open, which is never `0.0.0.0`. */
2426
+ function displayHost(bind) {
2427
+ if (bind === "local") return "127.0.0.1";
2428
+ if (bind === "lan") return lanAddress() ?? "127.0.0.1";
2429
+ return bind;
2430
+ }
2431
+ /** True when the bind value makes the port reachable from outside this machine. */
2432
+ function isExposed(bind) {
2433
+ return bindHost(bind) !== "127.0.0.1";
2434
+ }
2435
+ //#endregion
2436
+ //#region src/providers/server-vars.ts
2437
+ /** The `{placeholder}` values an entry's args, env and hooks expand — the table in `docs/SERVERS.md`. */
2438
+ function serverTemplateVars(config) {
2439
+ return {
2440
+ id: config.id,
2441
+ label: config.label ?? config.id,
2442
+ port: config.port ?? "",
2443
+ host: bindHost(config.bind),
2444
+ displayHost: displayHost(config.bind),
2445
+ bind: config.bind,
2446
+ lanIp: lanAddress() ?? "127.0.0.1",
2447
+ cwd: resolveCwd(config.cwd),
2448
+ projectDir,
2449
+ dataRoot,
2450
+ home: os.homedir()
2451
+ };
2452
+ }
2453
+ //#endregion
2454
+ //#region src/providers/backup-hook.ts
2455
+ /** Output kept for the error message and the plan; the rest is dropped rather than buffered. */
2456
+ var OUTPUT_TAIL_BYTES = 8192;
2457
+ function tail(previous, chunk) {
2458
+ const next = previous + chunk;
2459
+ return next.length <= OUTPUT_TAIL_BYTES ? next : next.slice(next.length - OUTPUT_TAIL_BYTES);
2460
+ }
2461
+ /**
2462
+ * Run a hook for one entry.
2463
+ *
2464
+ * `dumpDir` is passed in rather than templated by the caller so the same absolute path can be handed
2465
+ * to `dump` and later to `load`, which is what makes the pair symmetric.
2466
+ */
2467
+ async function runBackupHook(hook, server, dumpDir, options = {}) {
2468
+ const vars = {
2469
+ ...serverTemplateVars(server),
2470
+ dumpDir
2471
+ };
2472
+ const cwd = resolveCwd(server.cwd);
2473
+ const args = resolveTemplates(hook.args, vars);
2474
+ if (options.requireDumpDir !== false) fs.mkdirSync(dumpDir, { recursive: true });
2475
+ let child;
2476
+ try {
2477
+ child = spawn(hook.command, args, {
2478
+ cwd,
2479
+ env: {
2480
+ ...process.env,
2481
+ ...resolveRecord(hook.env, vars)
2482
+ },
2483
+ stdio: [
2484
+ "ignore",
2485
+ "pipe",
2486
+ "pipe"
2487
+ ],
2488
+ windowsHide: true
2489
+ });
2490
+ } catch (error) {
2491
+ return {
2492
+ ok: false,
2493
+ code: null,
2494
+ output: "",
2495
+ error: `could not start: ${error.message}`
2496
+ };
2497
+ }
2498
+ let output = "";
2499
+ child.stdout?.on("data", (chunk) => {
2500
+ output = tail(output, chunk.toString());
2501
+ });
2502
+ child.stderr?.on("data", (chunk) => {
2503
+ output = tail(output, chunk.toString());
2504
+ });
2505
+ const outcome = await new Promise((resolve) => {
2506
+ const timer = setTimeout(() => {
2507
+ try {
2508
+ child.kill("SIGKILL");
2509
+ } catch {}
2510
+ resolve({
2511
+ code: null,
2512
+ error: `timed out after ${hook.timeoutMs}ms`
2513
+ });
2514
+ }, hook.timeoutMs);
2515
+ child.once("exit", (code) => {
2516
+ clearTimeout(timer);
2517
+ resolve({ code });
2518
+ });
2519
+ child.once("error", (error) => {
2520
+ clearTimeout(timer);
2521
+ resolve({
2522
+ code: null,
2523
+ error: error.message
2524
+ });
2525
+ });
2526
+ });
2527
+ return {
2528
+ ok: outcome.error === void 0 && outcome.code === 0,
2529
+ code: outcome.code,
2530
+ output,
2531
+ ...outcome.error === void 0 ? {} : { error: outcome.error }
2532
+ };
2533
+ }
2534
+ /**
2535
+ * The line a person reads when a hook fails.
2536
+ *
2537
+ * Names the entry, the program and the last thing it said — a bare "the backup failed" would send
2538
+ * them to the panel's log to find out which of five databases refused.
2539
+ */
2540
+ function hookFailure(action, server, result) {
2541
+ const detail = result.error ?? (result.code === null ? "no exit code" : `exit ${result.code}`);
2542
+ const said = result.output.trim().split("\n").filter((line) => line.trim().length > 0).slice(-3).join(" / ");
2543
+ return `the ${action} hook for "${server.id}" failed (${detail})${said.length === 0 ? "" : `: ${said}`}`;
2544
+ }
2545
+ //#endregion
2546
+ //#region src/shared/backup-scope.ts
2547
+ /**
2548
+ * What a configured automatic scope asks a `create` for.
2549
+ *
2550
+ * `only` is `--include` and `except` is `--all --exclude`, because a schedule and a person typing
2551
+ * flags have to mean the same thing. An absent scope is the full default the schedule took before
2552
+ * it could be configured, which is what keeps an existing config exactly as it was.
2553
+ */
2554
+ function scopeSelection(scope) {
2555
+ if (scope === void 0) return {};
2556
+ return scope.mode === "only" ? { include: [...scope.ids] } : { exclude: [...scope.ids] };
2557
+ }
2558
+ /**
2559
+ * What a selection asks for, from `include` and `exclude` together.
2560
+ *
2561
+ * One implementation for `create`, `restore`, the control channel's plan and both UIs: a second
2562
+ * copy of "does this id count as selected" is how an `--exclude` that works on backup silently does
2563
+ * nothing on restore, or how a page ticks a row the panel will not capture.
2564
+ *
2565
+ * `include` omitted means everything; `exclude` is applied after it, and an id under an excluded
2566
+ * entry is excluded too.
2567
+ */
2568
+ function selectionOf(options) {
2569
+ const wanted = options.include === void 0 ? null : new Set(options.include);
2570
+ const unwanted = new Set(options.exclude ?? []);
2571
+ const isExcluded = (id) => unwanted.has(id) || [...unwanted].some((entry) => id.startsWith(`${entry}:`));
2572
+ const selects = ((id) => {
2573
+ if (isExcluded(id)) return false;
2574
+ return wanted === null || wanted.has(id) || [...wanted].some((entry) => id.startsWith(`${entry}:`));
2575
+ });
2576
+ selects.isExcluded = isExcluded;
2577
+ return selects;
2578
+ }
2579
+ /**
2580
+ * Whether a restore selection would write the panel's own credential store.
2581
+ *
2582
+ * `global:secrets` holds the password hash and the API token hash, so a restore that carries it can
2583
+ * replace the credentials of the panel doing the restoring. That is a legitimate move for the owner
2584
+ * (a fresh host taking its own archive back) and a panel takeover for anyone holding only a token:
2585
+ * measured, a token-only upload restore left the victim's password hash byte-identical to the
2586
+ * attacker's, and the owner locked out.
2587
+ *
2588
+ * The predicate exists so the guard has one definition rather than a string literal at each call
2589
+ * site. It answers *whether* the store is touched; who may touch it is the route's decision.
2590
+ */
2591
+ function selectionWritesCredentials(options) {
2592
+ const selects = selectionOf(options);
2593
+ return selects("global:secrets") || [
2594
+ "password",
2595
+ "apiToken",
2596
+ "telegram",
2597
+ "ddns"
2598
+ ].some((key) => selects(`global:secrets:${key}`));
2599
+ }
2600
+ /**
2601
+ * Which of `ids` name nothing the panel can capture.
2602
+ *
2603
+ * The rule `backup create --include` already applies: an id names something when it is an entry or
2604
+ * leaf id, or a prefix of one (`workspace:default` covers its leaves). A typo matters more on a
2605
+ * schedule than anywhere else — nobody is watching — and it cuts both ways: an unknown `only` id
2606
+ * silently narrows the archive, an unknown `except` id silently widens it back over what the
2607
+ * person meant to leave out.
2608
+ */
2609
+ function unknownBackupIds(ids, entries) {
2610
+ const available = entries.flatMap((entry) => [entry.id, ...(entry.items ?? []).map((item) => item.id)]);
2611
+ const known = (id) => available.some((candidate) => candidate === id || candidate.startsWith(`${id}:`));
2612
+ return ids.filter((id) => !known(id));
2613
+ }
2614
+ //#endregion
2615
+ //#region src/shared/generated.ts
2616
+ /**
2617
+ * Names that only ever hold build output or installed dependencies — the things
2618
+ * a `.gitignore` almost always lists.
2619
+ *
2620
+ * A backup walks a declared data directory and copies whatever it finds; on a
2621
+ * project directory that is mostly `node_modules` and framework caches, which
2622
+ * bloats the archive with content nobody needs to restore. An entry with
2623
+ * `backupIgnoreGenerated` (on by default) skips these.
2624
+ *
2625
+ * Matching is by exact name, on any segment, at any depth: `dist/` and
2626
+ * `app/node_modules/` are generated, `distributed/` and `my-node_modules/` are
2627
+ * not.
2628
+ *
2629
+ * `.git` is deliberately absent however much a `.gitignore` would not list it:
2630
+ * a package manager can reinstall `node_modules`, but nobody can restore a
2631
+ * commit that was never pushed.
2632
+ */
2633
+ /** Whole directories that are regenerated, never authored. */
2634
+ var GENERATED_DIRS = [
2635
+ "node_modules",
2636
+ "bower_components",
2637
+ "jspm_packages",
2638
+ ".yarn",
2639
+ ".pnpm",
2640
+ ".pnpm-store",
2641
+ ".npm",
2642
+ ".next",
2643
+ ".nuxt",
2644
+ ".svelte-kit",
2645
+ ".astro",
2646
+ ".output",
2647
+ ".vercel",
2648
+ ".netlify",
2649
+ ".angular",
2650
+ "dist",
2651
+ "build",
2652
+ "out",
2653
+ ".cache",
2654
+ ".parcel-cache",
2655
+ ".turbo",
2656
+ ".vite",
2657
+ ".rollup.cache",
2658
+ ".swc",
2659
+ "coverage",
2660
+ ".nyc_output",
2661
+ "__pycache__",
2662
+ ".pytest_cache",
2663
+ ".mypy_cache",
2664
+ ".ruff_cache",
2665
+ ".tox",
2666
+ "target",
2667
+ ".gradle",
2668
+ ".dart_tool"
2669
+ ];
2670
+ /** One-off files worth skipping, by exact name. */
2671
+ var GENERATED_FILES = [
2672
+ ".DS_Store",
2673
+ "Thumbs.db",
2674
+ "desktop.ini",
2675
+ ".eslintcache",
2676
+ ".stylelintcache",
2677
+ "npm-debug.log",
2678
+ "yarn-error.log",
2679
+ "pnpm-debug.log"
2680
+ ];
2681
+ var DIR_NAME_SET = new Set(GENERATED_DIRS);
2682
+ var FILE_NAME_SET = new Set(GENERATED_FILES);
2683
+ /**
2684
+ * True when a path *relative to the declared root* looks generated. Accepts
2685
+ * either separator, so a `path.relative` result can be passed straight in.
2686
+ */
2687
+ function isGeneratedPath(relative) {
2688
+ const segments = relative.split(/[\\/]+/).filter((segment) => segment.length > 0 && segment !== ".");
2689
+ if (segments.length === 0) return false;
2690
+ if (FILE_NAME_SET.has(segments[segments.length - 1])) return true;
2691
+ return segments.some((segment) => DIR_NAME_SET.has(segment));
2692
+ }
2693
+ //#endregion
2694
+ //#region src/services/backups.ts
2695
+ var MANIFEST = "manifest.json";
2696
+ var serverIdSchema = serverSchema.get("id");
2697
+ /**
2698
+ * The workspace registry inside an archive. Under `global/` because it is panel-wide, and
2699
+ * named as the live file is, so the two are recognisably the same document.
2700
+ */
2701
+ var REGISTRY = "workspaces.json";
2702
+ /**
2703
+ * The live name, or the scratch copy `writeFileAtomic` gives a write that has not been renamed yet.
2704
+ *
2705
+ * That helper removes its temp file only in its `catch`, so a crash between the write and the rename
2706
+ * leaves a **complete** secrets document on disk — plaintext first-run password included — under a
2707
+ * name no exact match catches. Matching the atomic-write shape is what makes the guarantee the docs
2708
+ * make actually hold.
2709
+ */
2710
+ var SECRET_DOCUMENT_NAMES = new RegExp(`^(?:${[".control-secrets.json", ".secrets.json"].map((name) => name.replaceAll(".", "\\.")).join("|")})(?:\\.\\d+\\.[0-9a-f]{8}\\.tmp)?$`, "i");
2711
+ function isSecretDocument(name) {
2712
+ return SECRET_DOCUMENT_NAMES.test(name);
2713
+ }
2714
+ var ALLOWED_ROOTS = /* @__PURE__ */ new Set([
2715
+ "global",
2716
+ "workspaces",
2717
+ "data",
2718
+ "dumps"
2719
+ ]);
2720
+ /** Every archive this service writes is a zip, encrypted or not. */
2721
+ var SUFFIX = ".zip";
2722
+ /** Where a restore parks a dump until the entry's next start can load it. */
2723
+ var PENDING_LOAD = "pending-load";
2724
+ /**
2725
+ * An archive the schedule wrote. The prefix is the only durable marker: a filename is the one
2726
+ * thing that survives a restart, and it is what lets the two retention counts stay independent.
2727
+ */
2728
+ var AUTO_PREFIX = "auto";
2729
+ var MANUAL_PREFIX = "backup";
2730
+ /** The names `create()` writes; retention counts and prunes only these, never a zip someone else put here. */
2731
+ var ARCHIVE_NAME = new RegExp(`^(${AUTO_PREFIX}|${MANUAL_PREFIX})-\\d{4}(?:-\\d{2}){5}-\\d{1,3}\\.zip$`);
2732
+ /** A workspace leaf that carries state the panel re-reads after a restore. */
2733
+ var RELOADABLE = /^global:settings$|^workspace:[^:]+:(?:settings|servers)$/;
2734
+ /**
2735
+ * A staging tree's name, carrying the pid that owns it.
2736
+ *
2737
+ * The timestamp keeps two runs in one process apart; the pid is what lets a later run tell a dead
2738
+ * one's debris from a live one's capture (see `sweepStaging`). `kind` names which tree it is, so a
2739
+ * capture and a restore left by the same pid are two directories rather than one.
2740
+ */
2741
+ function stagingDirName(kind) {
2742
+ return `.${kind}-${process.pid}-${Date.now()}`;
2743
+ }
2744
+ /**
2745
+ * The pid a staging directory belongs to, or null for any other name.
2746
+ *
2747
+ * A name with no pid in it is deliberately **not** guessed at: `.staging-1793809562025` is what
2748
+ * this release wrote before the owner was recorded, and an age is not proof its writer is gone.
2749
+ * Leaving it is the honest answer, and it is why a name that carries no owner is left alone.
2750
+ */
2751
+ function stagingOwner(name) {
2752
+ const match = /^\.[a-z]+-(\d+)-\d+$/.exec(name);
2753
+ if (match === null) return null;
2754
+ const pid = Number.parseInt(match[1], 10);
2755
+ return Number.isInteger(pid) && pid > 0 ? pid : null;
2756
+ }
2757
+ /**
2758
+ * The English wording and catalog key of each known secret. A key missing here is still
2759
+ * selectable and restorable — it just reads as its own name, which is what keeps a
2760
+ * secret added by a later release from being silently uncapturable.
2761
+ */
2762
+ var SECRET_LABELS = {
2763
+ password: {
2764
+ en: "Password",
2765
+ key: "settings.backup.secretPassword"
2766
+ },
2767
+ apiToken: {
2768
+ en: "API token",
2769
+ key: "settings.backup.secretApiToken"
2770
+ },
2771
+ telegram: {
2772
+ en: "Telegram bot token",
2773
+ key: "settings.backup.secretTelegram"
2774
+ },
2775
+ ddns: {
2776
+ en: "DDNS credentials",
2777
+ key: "settings.backup.secretDdns"
2778
+ }
2779
+ };
2780
+ /**
2781
+ * Structural allowlist for archive entries. A regex alone is not enough: `..`
2782
+ * is made of allowed characters, so segments are checked explicitly and any
2783
+ * entry that could resolve outside the staging directory aborts the restore.
2784
+ */
2785
+ /**
2786
+ * The servers an archive carries for one workspace, from its staged config.
2787
+ *
2788
+ * A restore reads this rather than `getSources()` because the live config is the *old* one at this
2789
+ * point: the files have just been overwritten, and the hooks to run belong to the machine being
2790
+ * cloned. A config that will not parse yields no servers, so the caller reports a missing hook
2791
+ * rather than throwing.
2792
+ */
2793
+ function readArchivedServers(staging, workspaceId, defaults = {}) {
2794
+ const text = readText(path.join(staging, "workspaces", workspaceId, "servers.config.json"));
2795
+ if (text === null) return [];
2796
+ try {
2797
+ return parseServersFile(JSON.parse(text), defaults).servers;
2798
+ } catch {
2799
+ return [];
2800
+ }
2801
+ }
2802
+ /**
2803
+ * Whether one archive path segment is a name a filesystem will accept as-is.
2804
+ *
2805
+ * A separator moves the path, and `\` is a separator on Windows while an archive crosses platforms;
2806
+ * `:` re-roots or opens a stream there. A control character is never a real filename and is how an
2807
+ * extractor is confused. Everything else — spaces, non-ASCII, `&`, `$`, `#`, `@` — is what a data
2808
+ * directory actually contains.
2809
+ */
2810
+ function isPortableSegment(segment) {
2811
+ for (const character of segment) {
2812
+ const code = character.codePointAt(0) ?? 0;
2813
+ if (character === "\\" || character === ":" || code < 32 || code === 127) return false;
2814
+ }
2815
+ return true;
2816
+ }
2817
+ function isSafeArchiveEntry(entry) {
2818
+ if (entry.startsWith("/") || entry.includes("\0")) return false;
2819
+ const cleaned = entry.replace(/^\.\//, "").replace(/\/+$/, "");
2820
+ if (cleaned.length === 0) return true;
2821
+ if (cleaned === MANIFEST) return true;
2822
+ const segments = cleaned.split("/");
2823
+ if (segments.some((segment) => segment.length === 0 || segment === "." || segment === "..")) return false;
2824
+ if (!ALLOWED_ROOTS.has(segments[0])) return false;
2825
+ return segments.every(isPortableSegment);
2826
+ }
2827
+ async function admitArchive(archivePath) {
2828
+ if (!isZipArchive(archivePath)) return {
2829
+ ok: false,
2830
+ error: "the archive is not a home-hosted backup (a zip file was expected)"
2831
+ };
2832
+ let entries;
2833
+ try {
2834
+ entries = await listZip(archivePath);
2835
+ } catch (error) {
2836
+ return {
2837
+ ok: false,
2838
+ error: `the archive could not be read: ${errorMessage(error)}`
2839
+ };
2840
+ }
2841
+ if (entries.length === 0) return {
2842
+ ok: false,
2843
+ error: "the archive is empty"
2844
+ };
2845
+ if (entries.length > 1e5) return {
2846
+ ok: false,
2847
+ error: "the archive has too many entries"
2848
+ };
2849
+ const invalid = entries.filter((entry) => !isSafeArchiveEntry(entry.name));
2850
+ if (invalid.length > 0) return {
2851
+ ok: false,
2852
+ error: `the archive contains unexpected entries (e.g. ${invalid.slice(0, 3).map((entry) => entry.name).join(", ")})`
2853
+ };
2854
+ return {
2855
+ ok: true,
2856
+ entries
2857
+ };
2858
+ }
2859
+ /** True when `child` is `parent` itself or lives underneath it. */
2860
+ function isInside(parent, child) {
2861
+ if (parent === child) return true;
2862
+ const relative = path.relative(parent, child);
2863
+ return !path.isAbsolute(relative) && (relative.length === 0 || !relative.startsWith(".."));
2864
+ }
2865
+ /** Resolves symlinks on the deepest existing ancestor, keeping the rest verbatim. */
2866
+ function resolveExisting(target) {
2867
+ let prefix = target;
2868
+ const rest = [];
2869
+ for (;;) try {
2870
+ return path.join(fs.realpathSync(prefix), ...rest);
2871
+ } catch {
2872
+ const parent = path.dirname(prefix);
2873
+ if (parent === prefix) return target;
2874
+ rest.unshift(path.basename(prefix));
2875
+ prefix = parent;
2876
+ }
2877
+ }
2878
+ /**
2879
+ * `isInside` after resolving symlinks, so a link inside a declared path cannot stand
2880
+ * for somewhere else. `cpSync` follows links already present in the tree it writes
2881
+ * into* — a link to an uploads or cache directory is routine — which would let an
2882
+ * archive write outside the path the config declared, and on capture let a file from
2883
+ * outside it into the archive. Both sides check with this.
2884
+ */
2885
+ function isInsideResolved(parent, child) {
2886
+ return isInside(resolveExisting(path.resolve(parent)), resolveExisting(path.resolve(child)));
2887
+ }
2888
+ /**
2889
+ * Every path a backup should capture: the global list, then each server's
2890
+ * `backupPaths` and the values of its `dataEnvs`. A path already covered by a
2891
+ * declared parent is reported but not captured, so an entry only has to name
2892
+ * the shallowest directory it cares about.
2893
+ *
2894
+ * `vars` only feeds the global list; a server's own placeholders come from its
2895
+ * resolved config, exactly as the supervisor expands them.
2896
+ */
2897
+ function resolveBackupPaths(servers, includePaths = [], vars) {
2898
+ const declared = [];
2899
+ const globalVars = {
2900
+ projectDir: vars?.projectDir ?? projectDir,
2901
+ dataRoot: vars?.dataRoot ?? (servers[0] === void 0 ? projectDir : String(serverTemplateVars(servers[0]).dataRoot ?? projectDir)),
2902
+ home: vars?.home ?? os.homedir()
2903
+ };
2904
+ const add = (value, origin, templateVars, ignoreGenerated) => {
2905
+ if (value.trim().length === 0) return;
2906
+ const resolved = path.normalize(resolveUserPath(expandEnv(resolveTemplate(value, templateVars), process.env)));
2907
+ declared.push({
2908
+ path: resolved,
2909
+ origin,
2910
+ depth: path.normalize(resolved).split(path.sep).filter(Boolean).length,
2911
+ order: declared.length,
2912
+ ignoreGenerated
2913
+ });
2914
+ };
2915
+ for (const value of includePaths) add(value, "global", globalVars, false);
2916
+ for (const config of servers) {
2917
+ const templateVars = serverTemplateVars(config);
2918
+ const ignoreGenerated = config.backupIgnoreGenerated !== false;
2919
+ for (const [name, value] of Object.entries(config.dataEnvs)) add(value, `${config.id}:${name}`, templateVars, ignoreGenerated);
2920
+ for (const value of config.backupPaths) add(value, `${config.id}:backupPaths`, templateVars, ignoreGenerated);
2921
+ }
2922
+ const sorted = [...declared].sort((a, b) => a.depth - b.depth || a.order - b.order);
2923
+ return sorted.map((entry, index) => {
2924
+ const parent = sorted.slice(0, index).find((candidate) => isInside(candidate.path, entry.path));
2925
+ if (parent === void 0) return {
2926
+ path: entry.path,
2927
+ origin: entry.origin,
2928
+ included: true,
2929
+ note: null,
2930
+ ignoreGenerated: entry.ignoreGenerated
2931
+ };
2932
+ const note = parent.path === entry.path ? `already declared by ${parent.origin}` : `covered by ${parent.path}`;
2933
+ const noteKey = parent.path === entry.path ? "settings.backup.noteAlreadyDeclared" : "settings.backup.noteCovered";
2934
+ const noteParams = parent.path === entry.path ? { origin: parent.origin } : { path: parent.path };
2935
+ return {
2936
+ path: entry.path,
2937
+ origin: entry.origin,
2938
+ included: false,
2939
+ note,
2940
+ noteKey,
2941
+ noteParams,
2942
+ ignoreGenerated: entry.ignoreGenerated
2943
+ };
2944
+ });
2945
+ }
2946
+ /**
2947
+ * What a backup captures, from a workspace list and the panel-wide paths.
2948
+ *
2949
+ * The **one** implementation, called by the running panel and by the CLI when no panel is up. A
2950
+ * second copy is how an offline backup would quietly capture something different from an online one
2951
+ * — and the archive is the thing people restore from, so a silent difference is the worst kind.
2952
+ *
2953
+ * `runningServers` stays a callback rather than a list: the panel answers it from live supervisor
2954
+ * views, and an offline caller answers it from the nanny state on disk. It is optional because a
2955
+ * caller that cannot know leaves it out; the warning it feeds is then simply absent.
2956
+ */
2957
+ function buildBackupSources(input) {
2958
+ return {
2959
+ globalSettingsPath: input.globalSettingsPath,
2960
+ globalSecretsPath: input.globalSecretsPath,
2961
+ tlsDir: input.tlsDir,
2962
+ registryPath: input.registryPath,
2963
+ includePaths: [...input.includePaths],
2964
+ ...input.runningServers === void 0 ? {} : { runningServers: input.runningServers },
2965
+ workspaces: input.workspaces.map((workspace) => ({
2966
+ id: workspace.id,
2967
+ label: workspace.label,
2968
+ settingsPath: workspace.settingsPath,
2969
+ serversPath: workspace.serversPath,
2970
+ secretsPath: workspace.secretsPath,
2971
+ servers: workspace.servers
2972
+ }))
2973
+ };
2974
+ }
2975
+ /**
2976
+ * An archived config, lifted to the schema this release reads.
2977
+ *
2978
+ * An archive is a snapshot, so the release that wrote it is often **older** than the one restoring
2979
+ * it — the backup someone takes before an upgrade is the one they reach for afterwards. Its files
2980
+ * carry the schema they were written with, and the parsers refuse an older stamp by design, so a
2981
+ * plain readability gate discarded every config an older archive carried: measured on a real
2982
+ * 0.7.21 archive applied to a blank 0.10.0 home, it reported "restored 4 items" and every one of
2983
+ * them was a secrets leaf, while both workspaces and the global settings were dropped as "not
2984
+ * valid" — a half-restored setup that reads as a success.
2985
+ *
2986
+ * So run the same chain `migrate` runs, on the contents rather than on a file: an archive that
2987
+ * needs lifting is lifted, and one this release cannot lift is still refused. A newer archive is
2988
+ * never rewritten here — that direction is refused earlier, from the manifest's own schema.
2989
+ *
2990
+ * **Lifting needs an explicit older stamp.** A file carrying no `meta.schema` is not evidence of an
2991
+ * older release — it is a seed (written in the current shape) or a damaged file, and lifting an
2992
+ * unparseable one let `{"not": "a servers file"}` be stamped as a valid empty `servers.config.json`,
2993
+ * which would restore a workspace with every entry deleted. Only a numeric stamp this release can
2994
+ * lift qualifies; anything else is left to its own parser, which refuses it.
2995
+ *
2996
+ * `null` means "this release cannot read it", which stays distinguishable from "it was fine".
2997
+ */
2998
+ function liftArchived(raw) {
2999
+ if (!isRecord(raw)) return null;
3000
+ const meta = isRecord(raw.meta) ? raw.meta : {};
3001
+ if (typeof meta.schema !== "number") return raw;
3002
+ const plan = planConfigMigrations(meta.schema);
3003
+ if (plan.tooNew || plan.reached !== plan.to) return null;
3004
+ if (plan.steps.length === 0) return raw;
3005
+ const lifted = applyConfigMigrations(raw, meta.schema).config;
3006
+ return isRecord(lifted) ? stampConfig(lifted) : null;
3007
+ }
3008
+ /**
3009
+ * A restored settings file is accepted when this release can read it — through
3010
+ * the same tolerant parser the stores use, so an archive from a newer release
3011
+ * keeps only the keys this one understands instead of being refused outright.
3012
+ *
3013
+ * An older one is lifted first (`liftArchived`), and the **lifted** value is returned so the
3014
+ * caller writes a config this release can load rather than the stamp it could not.
3015
+ */
3016
+ function readableGlobalSettings(text) {
3017
+ if (text === null) return null;
3018
+ try {
3019
+ const lifted = liftArchived(JSON.parse(text));
3020
+ return lifted !== null && parseGlobalSettings(lifted).config !== null ? lifted : null;
3021
+ } catch {
3022
+ return null;
3023
+ }
3024
+ }
3025
+ /**
3026
+ * The workspaces an archive's registry names.
3027
+ *
3028
+ * Tolerant on purpose: an archive written before the registry was captured has no such
3029
+ * file, and a damaged one must not fail a restore whose leaves are perfectly readable.
3030
+ * The registry only contributes labels, so anything unreadable is simply dropped.
3031
+ */
3032
+ function readArchivedRegistry(file) {
3033
+ const text = readText(file);
3034
+ if (text === null) return [];
3035
+ try {
3036
+ const parsed = workspacesFileSchema(JSON.parse(text));
3037
+ if (parsed instanceof type.errors) return [];
3038
+ return parsed.workspaces;
3039
+ } catch {
3040
+ return [];
3041
+ }
3042
+ }
3043
+ /**
3044
+ * Where a workspace created by a restore keeps its three leaves.
3045
+ *
3046
+ * Derived from the service's own `dataRoot` (the `.hh` directory the panel passes) rather
3047
+ * than the module-level path helpers, so a restore writes under the state root of the panel
3048
+ * running it — not under whatever `HHOSTED_HOME` resolves to at import time.
3049
+ */
3050
+ function workspacePathsFor(dataRoot, id) {
3051
+ const dir = path.join(dataRoot, id);
3052
+ return {
3053
+ settingsPath: path.join(dir, "settings.json"),
3054
+ serversPath: path.join(dir, "servers.config.json"),
3055
+ secretsPath: path.join(dir, ".secrets.json")
3056
+ };
3057
+ }
3058
+ /**
3059
+ * The manifest is written by us, but an uploaded archive's copy is attacker
3060
+ * controlled: never join an unvalidated slug into a path.
3061
+ */
3062
+ function safeSlug(slug) {
3063
+ if (typeof slug !== "string" || slug.length === 0 || slug.length > 80) return null;
3064
+ if (!/^[\w.-]+$/.test(slug) || slug === "." || slug === "..") return null;
3065
+ return slug;
3066
+ }
3067
+ /** A flag is valid for one exact file revision, not for the name alone. */
3068
+ function cacheKey(file) {
3069
+ return `${file.sizeBytes}:${file.createdAt}`;
3070
+ }
3071
+ /** Stable, filesystem-safe name for a data path inside the archive. */
3072
+ function slugifyPath(target) {
3073
+ const cleaned = target.replace(/[^A-Z0-9]+/gi, "-").replace(/^-+|-+$/g, "");
3074
+ return cleaned.length > 0 ? cleaned.slice(-80) : "path";
3075
+ }
3076
+ /**
3077
+ * A state file's text, decoded the way `readStateFile` decodes it.
3078
+ *
3079
+ * **Not** `fs.readFileSync(file, 'utf8')`: a hand-edited file arrives with whatever a Windows editor
3080
+ * wrote, and a leading BOM makes `JSON.parse` fail. Here that failure was not loud — it made
3081
+ * `withoutInitialPassword` return `null`, which the caller reads as "this is not a document I can
3082
+ * narrow", and the raw-copy fallback then put the plaintext first-run password into the archive. So
3083
+ * the one codec the repo already centralised for exactly this reason is the one this must use.
3084
+ */
3085
+ function readText(file) {
3086
+ try {
3087
+ return readStateFile(file);
3088
+ } catch {
3089
+ return null;
3090
+ }
3091
+ }
3092
+ /**
3093
+ * Archives of the control plane's own state plus whatever paths the configs
3094
+ * declare. Two rules keep restore safe: the archive layout is an allowlist, and
3095
+ * a data path is only written back when a *config* still declares it — a current
3096
+ * one, or a workspace's servers file the same restore is about to apply.
3097
+ *
3098
+ * A backup is always a zip; a password makes it a WinZip-AES one, so the same
3099
+ * file opens in any archive manager either way.
3100
+ */
3101
+ var BackupService = class {
3102
+ options;
3103
+ /**
3104
+ * Whether an archive is encrypted is only knowable by reading its central
3105
+ * directory, which is async while `list()` is not. The flags are cached here
3106
+ * and refreshed in the background, so a state frame stays cheap.
3107
+ */
3108
+ flags = /* @__PURE__ */ new Map();
3109
+ refreshing = null;
3110
+ /** One scheduled pass at a time: a slow archive must not stack up behind itself. */
3111
+ running = false;
3112
+ disposed = false;
3113
+ /**
3114
+ * When this instance last attempted an automatic pass, whatever it wrote.
3115
+ *
3116
+ * The archive's own mtime is the durable record across a restart, but it cannot bound a
3117
+ * failed pass: nothing is written, so every panel tick would retry — once a second, for as
3118
+ * long as the failure lasts. This is the in-memory backstop for that case.
3119
+ */
3120
+ lastAttemptAt = null;
3121
+ /** Logs a pass deferred by a running restore once, not on every tick. */
3122
+ deferredForRestore = false;
3123
+ /** Why the most recent scheduled pass failed, cleared by the next that works. */
3124
+ scheduleError = null;
3125
+ constructor(options) {
3126
+ this.options = options;
3127
+ }
3128
+ /** Reads every archive once, so the first `list()` is already accurate. */
3129
+ async warm() {
3130
+ await this.refresh();
3131
+ }
3132
+ dispose() {
3133
+ this.disposed = true;
3134
+ }
3135
+ get directory() {
3136
+ return this.resolveDir();
3137
+ }
3138
+ /**
3139
+ * The policy and the status: what the settings page shows, and what the state frame carries.
3140
+ *
3141
+ * Deliberately **not** the selection model. `entries()` reads every workspace's `.secrets.json` and
3142
+ * `list()` stats every archive on disk, so including them here made the frame's cost scale with
3143
+ * workspaces × archives on a path rebuilt ~13×/s. A dialog asks `selection()` instead.
3144
+ */
3145
+ view() {
3146
+ const config = this.options.getConfig();
3147
+ const sources = this.options.getSources();
3148
+ return {
3149
+ enabled: config.enabled,
3150
+ dir: this.directory,
3151
+ keep: config.keep,
3152
+ schedule: { ...config.schedule },
3153
+ lastAutomaticAt: this.lastAutomatic(),
3154
+ ...this.scheduleError === null ? {} : { scheduleError: { ...this.scheduleError } },
3155
+ includePaths: [...sources.includePaths]
3156
+ };
3157
+ }
3158
+ /**
3159
+ * The selection model: every entry a capture could include, and every archive already on disk.
3160
+ *
3161
+ * Served by `GET /api/backups` and fetched when a dialog opens, never on a per-frame path.
3162
+ */
3163
+ selection() {
3164
+ return {
3165
+ dir: this.directory,
3166
+ entries: this.entries(this.options.getSources()),
3167
+ files: this.list()
3168
+ };
3169
+ }
3170
+ list() {
3171
+ const files = this.scan();
3172
+ for (const file of files) {
3173
+ const cached = this.flags.get(file.name);
3174
+ if (cached === void 0 || cached.key !== cacheKey(file)) this.scheduleRefresh();
3175
+ }
3176
+ return files.map((file) => {
3177
+ const cached = this.flags.get(file.name);
3178
+ return {
3179
+ ...file,
3180
+ encrypted: cached !== void 0 && cached.key === cacheKey(file) ? cached.encrypted : false
3181
+ };
3182
+ });
3183
+ }
3184
+ /** Validated absolute path for a download, or null when the name is not a backup. */
3185
+ resolve(name) {
3186
+ if (!/^[A-Z0-9][\w.-]*$/i.test(name) || name.includes("..")) return null;
3187
+ const file = path.join(this.resolveDir(), name);
3188
+ return fs.existsSync(file) ? file : null;
3189
+ }
3190
+ /**
3191
+ * `password` encrypts the archive; it is never stored anywhere.
3192
+ *
3193
+ * `automatic` marks an archive the schedule wrote, which is what keeps the two retention
3194
+ * counts apart: an automatic pass must never prune the backup a person took by hand, and a
3195
+ * manual one must not silently eat the history the schedule is keeping.
3196
+ */
3197
+ async create(options = {}) {
3198
+ if (!this.options.getConfig().enabled) return {
3199
+ ok: false,
3200
+ error: "backups are disabled"
3201
+ };
3202
+ const password = options.password !== void 0 && options.password.length > 0 ? options.password : null;
3203
+ const selects = selectionOf(options);
3204
+ const wanted = options.include === void 0 ? null : new Set(options.include);
3205
+ const capturesGlobal = (id) => selects(id);
3206
+ const capturesWorkspace = (id, suffix) => selects(`workspace:${id}:${suffix}`);
3207
+ /**
3208
+ * The secrets of one scope the request asked for; `null` means "every one of them".
3209
+ * `workspaceId` is how a bare `workspace:<id>` selection covers all of its leaves.
3210
+ */
3211
+ const selectedSecretFields = (entryId, path, scope, workspaceId) => {
3212
+ const parts = secretParts(scope, presentSecretKeys(parseSecrets(readText(path) ?? "")));
3213
+ const picked = parts.filter((part) => {
3214
+ if (selects.isExcluded(entryId) || selects.isExcluded(`${entryId}:${part.key}`)) return false;
3215
+ return wanted === null || wanted.has(entryId) || workspaceId !== void 0 && wanted.has(`workspace:${workspaceId}`) || wanted.has(`${entryId}:${part.key}`) || part.fields.some((field) => wanted.has(`${entryId}:${field}`));
3216
+ });
3217
+ return picked.length === parts.length ? null : picked.flatMap((part) => part.fields);
3218
+ };
3219
+ const dir = this.resolveDir();
3220
+ const sources = this.options.getSources();
3221
+ const staging = path.join(dir, stagingDirName("staging"));
3222
+ const createdAt = Date.now();
3223
+ const name = `${options.automatic === true ? AUTO_PREFIX : MANUAL_PREFIX}-${new Date(createdAt).toISOString().replace(/[:T]/g, "-").replace(/\.\d+Z$/, "")}-${createdAt % 1e3}${SUFFIX}`;
3224
+ const destination = path.join(dir, name);
3225
+ try {
3226
+ fs.mkdirSync(staging, { recursive: true });
3227
+ let captured = 0;
3228
+ const copy = async (relative, source, ignoreGenerated = false) => {
3229
+ if (await this.copyInto(staging, relative, source, ignoreGenerated)) captured++;
3230
+ };
3231
+ /**
3232
+ * Captures one secrets file, narrowed to the picked secrets. Copying the whole file
3233
+ * would capture the ones that were *not* picked, so a per-secret selection writes a
3234
+ * staged document holding only those — and the restore side merges by field, which
3235
+ * is what keeps a restore from wiping a secret the archive never carried.
3236
+ */
3237
+ const copySecrets = async (relative, source, entryId, scope, workspaceId) => {
3238
+ const text = readText(source);
3239
+ if (text === null) return;
3240
+ const fields = selectedSecretFields(entryId, source, scope, workspaceId);
3241
+ /**
3242
+ * `fields === null` means "every field is selected", which is the **default** — no
3243
+ * `--include`/`--exclude`, and the automatic schedule. It is still not a licence to copy the
3244
+ * file verbatim: `withoutFirstRunPassword` lives inside `pickSecrets`, so the raw-copy branch
3245
+ * bypassed it and put `.control-secrets.json` in the zip byte for byte, plaintext first-run
3246
+ * password and all — unencrypted, in a directory the docs tell people to copy off the box.
3247
+ * The narrowing ran only on the partial path, and the sole test exercised `pickSecrets` in
3248
+ * isolation, so the suite stayed green over it.
3249
+ *
3250
+ * A whole selection still copies the whole document — null slots, unknown keys and all, which
3251
+ * is the shape the archive had before — with just that one field removed. Re-deriving the
3252
+ * fields instead would drop every `null` slot, because `presentSecretKeys` counts only
3253
+ * non-null values and `pickSecrets` then answers `null` for a file holding nothing set.
3254
+ */
3255
+ /**
3256
+ * **Never** fall back to copying the original bytes. That fallback is the whole bug: a file
3257
+ * `withoutInitialPassword` could not parse — a BOM, most realistically, which is what a
3258
+ * Windows editor writes — took the raw-copy branch and carried the plaintext password into
3259
+ * the archive. Unreadable is not "safe to copy verbatim"; it is a file that must not travel.
3260
+ */
3261
+ const chosen = fields === null ? withoutInitialPassword(text) : pickSecrets(parseSecrets(text), fields);
3262
+ if (chosen === null) return;
3263
+ const target = path.join(staging, relative);
3264
+ fs.mkdirSync(path.dirname(target), { recursive: true });
3265
+ fs.writeFileSync(target, chosen.endsWith("\n") ? chosen : `${chosen}\n`, { mode: 384 });
3266
+ captured++;
3267
+ };
3268
+ /**
3269
+ * True when the request touches a secrets entry at all: the entry itself, one of its
3270
+ * leaves, or — for a workspace — the workspace id, which names every leaf it has.
3271
+ */
3272
+ const touchesSecrets = (entryId, workspaceId) => selects(entryId) || wanted !== null && [...wanted].some((id) => id.startsWith(`${entryId}:`)) || workspaceId !== void 0 && selects(`workspace:${workspaceId}:secrets`);
3273
+ if (capturesGlobal("global:settings")) await copy("global/settings.json", sources.globalSettingsPath);
3274
+ if (touchesSecrets("global:secrets")) await copySecrets("global/secrets.json", sources.globalSecretsPath, "global:secrets", "global");
3275
+ if (capturesGlobal("global:tls")) await copy("global/tls", sources.tlsDir);
3276
+ await this.copyInto(staging, `global/${REGISTRY}`, sources.registryPath);
3277
+ /**
3278
+ * The dump phase: give every entry with a `dump` hook the chance to produce a consistent copy.
3279
+ *
3280
+ * Before anything is copied, because the dump is the authoritative artifact — the raw data
3281
+ * directory beside it is a convenience, and a dump that failed must not leave an archive that
3282
+ * looks complete. The output lands in `dumps/<workspace>/<server>/`, which the restore side
3283
+ * fills again at the same path, so `{dumpDir}` means the same thing in both directions.
3284
+ */
3285
+ const dumped = [];
3286
+ for (const workspace of sources.workspaces) for (const server of workspace.servers) {
3287
+ const hook = server.dump;
3288
+ if (hook === void 0 || hook === null) continue;
3289
+ if (!selects(`workspace:${workspace.id}:dump:${server.id}`)) continue;
3290
+ const relative = path.join("dumps", workspace.id, server.id);
3291
+ const result = await runBackupHook(hook, server, path.join(staging, relative));
3292
+ if (!result.ok) {
3293
+ await fs.promises.rm(staging, {
3294
+ recursive: true,
3295
+ force: true
3296
+ });
3297
+ return {
3298
+ ok: false,
3299
+ error: hookFailure("dump", server, result)
3300
+ };
3301
+ }
3302
+ dumped.push({
3303
+ workspaceId: workspace.id,
3304
+ serverId: server.id
3305
+ });
3306
+ }
3307
+ const data = [];
3308
+ for (const workspace of sources.workspaces) {
3309
+ const root = `workspaces/${workspace.id}`;
3310
+ if (capturesWorkspace(workspace.id, "settings")) await copy(`${root}/settings.json`, workspace.settingsPath);
3311
+ if (capturesWorkspace(workspace.id, "servers")) await copy(`${root}/servers.config.json`, workspace.serversPath);
3312
+ if (touchesSecrets(`workspace:${workspace.id}:secrets`, workspace.id)) await copySecrets(`${root}/secrets.json`, workspace.secretsPath, `workspace:${workspace.id}:secrets`, "workspace", workspace.id);
3313
+ for (const declared of this.declaredData(workspace.servers, sources.includePaths)) {
3314
+ if (!declared.included) continue;
3315
+ if (!capturesWorkspace(workspace.id, `data:${declared.path}`)) continue;
3316
+ if (!fs.existsSync(declared.path)) continue;
3317
+ const slug = slugifyPath(declared.path);
3318
+ if (data.some((entry) => entry.slug === slug)) continue;
3319
+ if (!await this.copyInto(staging, path.join("data", slug), declared.path, declared.ignoreGenerated)) continue;
3320
+ captured++;
3321
+ data.push({
3322
+ slug,
3323
+ path: declared.path,
3324
+ origin: declared.origin,
3325
+ workspace: workspace.id
3326
+ });
3327
+ }
3328
+ }
3329
+ if ((wanted !== null || (options.exclude?.length ?? 0) > 0) && captured === 0) {
3330
+ await fs.promises.rm(staging, {
3331
+ recursive: true,
3332
+ force: true
3333
+ });
3334
+ return {
3335
+ ok: false,
3336
+ error: "nothing was selected to back up"
3337
+ };
3338
+ }
3339
+ const manifest = {
3340
+ version: 1,
3341
+ createdAt,
3342
+ hostname: os.hostname(),
3343
+ writtenBy: appVersion(),
3344
+ schema: 2,
3345
+ data,
3346
+ ...dumped.length === 0 ? {} : { dumps: dumped }
3347
+ };
3348
+ fs.writeFileSync(path.join(staging, MANIFEST), `${JSON.stringify(manifest, null, 2)}\n`);
3349
+ await createZip(staging, destination, password === null ? {} : { password });
3350
+ await fs.promises.rm(staging, {
3351
+ recursive: true,
3352
+ force: true
3353
+ });
3354
+ this.prune();
3355
+ this.sweepStaging();
3356
+ const stats = fs.statSync(destination);
3357
+ this.flags.set(name, {
3358
+ key: `${stats.size}:${Math.round(stats.mtimeMs)}`,
3359
+ encrypted: password !== null
3360
+ });
3361
+ return {
3362
+ ok: true,
3363
+ file: {
3364
+ name,
3365
+ sizeBytes: stats.size,
3366
+ createdAt,
3367
+ encrypted: password !== null
3368
+ }
3369
+ };
3370
+ } catch (error) {
3371
+ await fs.promises.rm(staging, {
3372
+ recursive: true,
3373
+ force: true
3374
+ }).catch(() => {});
3375
+ await fs.promises.rm(destination, { force: true }).catch(() => {});
3376
+ return {
3377
+ ok: false,
3378
+ error: errorMessage(error)
3379
+ };
3380
+ }
3381
+ }
3382
+ remove(name) {
3383
+ const file = this.resolve(name);
3384
+ if (file === null) return false;
3385
+ fs.rmSync(file, { force: true });
3386
+ this.flags.delete(name);
3387
+ return true;
3388
+ }
3389
+ /**
3390
+ * Validates an archive, then (unless `confirm` is false) applies whichever of
3391
+ * its items were selected. Data paths come from the *current* sources, or from
3392
+ * a workspace's servers file that is itself being restored — never from the
3393
+ * archive's manifest alone.
3394
+ */
3395
+ async restore(archivePath, options) {
3396
+ const lock = options.confirm ? acquireRestoreLock(this.options.dataRoot) : null;
3397
+ if (lock !== null && "heldBy" in lock) throw new DetailedError(`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`, {
3398
+ statusCode: 409,
3399
+ code: "RESTORE_IN_PROGRESS"
3400
+ });
3401
+ try {
3402
+ return await this.applyRestore(archivePath, options);
3403
+ } finally {
3404
+ if (lock !== null && !("heldBy" in lock)) lock.release();
3405
+ }
3406
+ }
3407
+ async applyRestore(archivePath, options) {
3408
+ const password = options.password !== void 0 && options.password.length > 0 ? options.password : null;
3409
+ const plan = {
3410
+ dryRun: !options.confirm,
3411
+ encrypted: false,
3412
+ needsPassword: false,
3413
+ items: [],
3414
+ applied: [],
3415
+ appliedIds: [],
3416
+ skipped: [],
3417
+ skippedItems: [],
3418
+ restartRequired: false,
3419
+ reloaded: false,
3420
+ createdWorkspaces: [],
3421
+ replacedUnderRunning: []
3422
+ };
3423
+ const admitted = await admitArchive(archivePath);
3424
+ if (!admitted.ok) return {
3425
+ ...plan,
3426
+ error: admitted.error
3427
+ };
3428
+ const entries = admitted.entries;
3429
+ const staging = path.join(this.resolveDir(), stagingDirName("restore"));
3430
+ try {
3431
+ plan.encrypted = entries.some((entry) => entry.encrypted);
3432
+ if (plan.encrypted && password === null) return {
3433
+ ...plan,
3434
+ needsPassword: true,
3435
+ error: "this backup is password-protected"
3436
+ };
3437
+ fs.mkdirSync(staging, { recursive: true });
3438
+ const extracted = await extractZip(archivePath, staging, {
3439
+ names: entries.map((entry) => entry.name),
3440
+ ...password === null ? {} : { password }
3441
+ });
3442
+ for (const name of extracted.skipped) {
3443
+ plan.skipped.push(`${name} (symbolic link, skipped)`);
3444
+ plan.skippedItems.push({
3445
+ label: name,
3446
+ reasonKey: "settings.restore.reasonSymbolicLink"
3447
+ });
3448
+ }
3449
+ const manifestPath = path.join(staging, MANIFEST);
3450
+ if (!fs.existsSync(manifestPath)) return {
3451
+ ...plan,
3452
+ error: "the archive has no manifest"
3453
+ };
3454
+ const manifest = JSON.parse(fs.readFileSync(manifestPath, "utf8"));
3455
+ plan.archive = manifestInfo(manifest);
3456
+ if (manifest.schema !== void 0 && manifest.schema > 2) return {
3457
+ ...plan,
3458
+ error: `written by home-hosted ${manifest.writtenBy ?? "a newer release"} (config schema ${manifest.schema}); this release understands schema 2`
3459
+ };
3460
+ if (!(manifest.dumps === void 0 || Array.isArray(manifest.dumps) && manifest.dumps.every((dump) => isRecord(dump) && !(workspaceIdSchema(dump.workspaceId) instanceof type.errors) && !(serverIdSchema(dump.serverId) instanceof type.errors)))) return {
3461
+ ...plan,
3462
+ error: "the archive's manifest names a dump with an invalid workspace or server id"
3463
+ };
3464
+ const sources = this.options.getSources();
3465
+ const selects = selectionOf(options);
3466
+ const actions = /* @__PURE__ */ new Map();
3467
+ /**
3468
+ * Writes one archived secrets file, **always** by field.
3469
+ *
3470
+ * Replacing the live file wholesale when nothing was excluded looked like the identity case, but
3471
+ * an archive only carries what its own selection captured: restoring `global:secrets` from an
3472
+ * archive taken with `--exclude global:secrets:apiToken` replaced the file with a document that
3473
+ * had no `apiToken` in it, silently signing every script out. The live file may also hold a secret
3474
+ * the archive predates. `mergeIntoFile` copies exactly the fields the archive carries and leaves
3475
+ * every other key of the live file alone, which is the behaviour both cases want — and what every
3476
+ * restore did before this rewrite.
3477
+ */
3478
+ const secretsApply = (scope, entryId, target, archived) => {
3479
+ const take = secretParts(scope, presentSecretKeys(parseSecrets(archived))).filter((part) => !selects.isExcluded(`${entryId}:${part.key}`) && !part.fields.some((field) => selects.isExcluded(`${entryId}:${field}`)));
3480
+ return () => {
3481
+ fs.mkdirSync(path.dirname(target), { recursive: true });
3482
+ mergeIntoFile(target, archived, take.flatMap((part) => part.fields));
3483
+ };
3484
+ };
3485
+ const addItem = (item, apply, aliases = []) => {
3486
+ if (apply === null) {
3487
+ plan.items.push({
3488
+ ...item,
3489
+ selected: false
3490
+ });
3491
+ plan.skipped.push(`${item.label}${item.note === null ? "" : ` (${item.note})`}`);
3492
+ plan.skippedItems.push({
3493
+ label: item.label,
3494
+ ...item.labelKey === void 0 ? {} : { labelKey: item.labelKey },
3495
+ ...item.labelParams === void 0 ? {} : { labelParams: item.labelParams },
3496
+ reasonKey: item.noteKey ?? "settings.restore.reasonUnrestorable",
3497
+ ...item.noteParams === void 0 ? {} : { reasonParams: item.noteParams }
3498
+ });
3499
+ return;
3500
+ }
3501
+ const selected = !(selects.isExcluded(item.id) || aliases.some((alias) => selects.isExcluded(alias))) && (selects(item.id) || aliases.some((alias) => selects(alias)));
3502
+ plan.items.push({
3503
+ ...item,
3504
+ selected
3505
+ });
3506
+ if (selected) actions.set(item.id, apply);
3507
+ else {
3508
+ plan.skipped.push(`${item.label} (not selected)`);
3509
+ plan.skippedItems.push({
3510
+ label: item.label,
3511
+ ...item.labelKey === void 0 ? {} : { labelKey: item.labelKey },
3512
+ ...item.labelParams === void 0 ? {} : { labelParams: item.labelParams },
3513
+ reasonKey: "settings.restore.reasonNotSelected"
3514
+ });
3515
+ }
3516
+ };
3517
+ const settingsText = readText(path.join(staging, "global", "settings.json"));
3518
+ const liftedGlobal = readableGlobalSettings(settingsText);
3519
+ const parsedGlobal = liftedGlobal === null ? null : parseGlobalSettings(liftedGlobal).config;
3520
+ if (settingsText !== null && parsedGlobal === null) {
3521
+ plan.skipped.push("Global settings (the archive's settings are not valid)");
3522
+ plan.skippedItems.push({
3523
+ label: "Global settings",
3524
+ labelKey: "settings.backup.entryGlobalSettings",
3525
+ reasonKey: "settings.restore.reasonInvalidSettings"
3526
+ });
3527
+ }
3528
+ if (parsedGlobal !== null && liftedGlobal !== null) {
3529
+ const globalText = `${JSON.stringify(liftedGlobal, null, 2)}\n`;
3530
+ addItem({
3531
+ id: "global:settings",
3532
+ label: "Global settings",
3533
+ labelKey: "settings.backup.entryGlobalSettings",
3534
+ kind: "settings",
3535
+ restorable: true,
3536
+ note: null
3537
+ }, () => {
3538
+ writeFileAtomic(sources.globalSettingsPath, globalText);
3539
+ }, ["config"]);
3540
+ }
3541
+ const globalSecrets = readText(path.join(staging, "global", "secrets.json"));
3542
+ if (globalSecrets !== null) {
3543
+ addItem({
3544
+ id: "global:secrets",
3545
+ label: "Global secrets (password, API token)",
3546
+ labelKey: "settings.backup.entryGlobalSecrets",
3547
+ kind: "secrets",
3548
+ restorable: true,
3549
+ note: null
3550
+ }, secretsApply("global", "global:secrets", sources.globalSecretsPath, globalSecrets), ["secrets"]);
3551
+ for (const part of secretParts("global", presentSecretKeys(parseSecrets(globalSecrets)))) addItem({
3552
+ id: `global:secrets:${part.key}`,
3553
+ label: `Global secrets: ${SECRET_LABELS[part.key]?.en ?? part.key}`,
3554
+ labelKey: "settings.backup.restoreItemLabel",
3555
+ labelParams: {
3556
+ workspace: "global",
3557
+ item: part.key
3558
+ },
3559
+ kind: "secrets",
3560
+ restorable: true,
3561
+ note: null
3562
+ }, () => {
3563
+ mergeIntoFile(sources.globalSecretsPath, globalSecrets, part.fields);
3564
+ });
3565
+ }
3566
+ const tlsInArchive = path.join(staging, "global", "tls");
3567
+ if (fs.existsSync(tlsInArchive)) {
3568
+ const files = fs.readdirSync(tlsInArchive).filter((file) => fs.statSync(path.join(tlsInArchive, file)).isFile());
3569
+ addItem({
3570
+ id: "global:tls",
3571
+ label: "TLS certificate",
3572
+ labelKey: "settings.backup.entryTlsCertificate",
3573
+ kind: "tls",
3574
+ restorable: true,
3575
+ note: null
3576
+ }, () => {
3577
+ fs.mkdirSync(sources.tlsDir, { recursive: true });
3578
+ for (const file of files) {
3579
+ const mode = file.endsWith(".key.pem") ? { mode: 384 } : {};
3580
+ writeFileAtomic(path.join(sources.tlsDir, file), fs.readFileSync(path.join(tlsInArchive, file), "utf8"), mode);
3581
+ }
3582
+ }, ["tls"]);
3583
+ }
3584
+ /**
3585
+ * The workspaces the archive names, from its registry file.
3586
+ *
3587
+ * Optional: an archive written before the registry was captured carries none, and
3588
+ * then every archived workspace is still restorable under its own id — the label is
3589
+ * the only thing the registry adds.
3590
+ */
3591
+ const archivedWorkspaces = /* @__PURE__ */ new Map();
3592
+ for (const entry of readArchivedRegistry(path.join(staging, "global", REGISTRY))) archivedWorkspaces.set(entry.id, entry);
3593
+ /** Every archived servers file this release can read, selected or not. */
3594
+ const archivedServers = /* @__PURE__ */ new Map();
3595
+ /**
3596
+ * Workspaces the archive names that this host does not have, with the paths a
3597
+ * restore will create them under. The directories are made only when one of
3598
+ * their leaves is actually applied, so a dry run writes nothing.
3599
+ */
3600
+ const createdWorkspaces = /* @__PURE__ */ new Map();
3601
+ const archiveWorkspaces = path.join(staging, "workspaces");
3602
+ if (fs.existsSync(archiveWorkspaces)) for (const entry of fs.readdirSync(archiveWorkspaces, { withFileTypes: true })) {
3603
+ if (!entry.isDirectory()) continue;
3604
+ const id = entry.name;
3605
+ const dir = path.join(archiveWorkspaces, id);
3606
+ const settings = readText(path.join(dir, "settings.json"));
3607
+ const servers = readText(path.join(dir, "servers.config.json"));
3608
+ const secrets = readText(path.join(dir, "secrets.json"));
3609
+ const archivedLabel = archivedWorkspaces.get(id)?.label ?? id;
3610
+ const workspace = sources.workspaces.find((candidate) => candidate.id === id) ?? createdWorkspaces.get(id) ?? (workspaceIdSchema(id) instanceof type.errors ? void 0 : {
3611
+ id,
3612
+ label: archivedLabel,
3613
+ ...workspacePathsFor(this.options.dataRoot, id),
3614
+ servers: []
3615
+ });
3616
+ if (workspace === void 0) {
3617
+ plan.skipped.push(`${id} (not a usable workspace id)`);
3618
+ plan.skippedItems.push({
3619
+ label: id,
3620
+ reasonKey: "settings.restore.reasonInvalidWorkspace"
3621
+ });
3622
+ continue;
3623
+ }
3624
+ if (!sources.workspaces.some((candidate) => candidate.id === id)) createdWorkspaces.set(id, workspace);
3625
+ if (settings !== null) {
3626
+ const liftedSettings = readableWorkspaceSettings(settings);
3627
+ if (liftedSettings !== null) {
3628
+ const settingsText = `${JSON.stringify(liftedSettings, null, 2)}\n`;
3629
+ addItem({
3630
+ id: `workspace:${id}:settings`,
3631
+ label: `${workspace.label}: Settings`,
3632
+ labelKey: "settings.backup.restoreItemLabel",
3633
+ labelParams: {
3634
+ workspace: workspace.label,
3635
+ item: "settings"
3636
+ },
3637
+ kind: "settings",
3638
+ workspaceId: id,
3639
+ restorable: true,
3640
+ note: null
3641
+ }, () => {
3642
+ fs.mkdirSync(path.dirname(workspace.settingsPath), { recursive: true });
3643
+ writeFileAtomic(workspace.settingsPath, settingsText);
3644
+ });
3645
+ } else {
3646
+ plan.skipped.push(`${workspace.label}: Settings (the archive's settings are not valid)`);
3647
+ plan.skippedItems.push({
3648
+ label: `${workspace.label}: Settings`,
3649
+ labelKey: "settings.backup.restoreItemLabel",
3650
+ labelParams: {
3651
+ workspace: workspace.label,
3652
+ item: "settings"
3653
+ },
3654
+ reasonKey: "settings.restore.reasonInvalidSettings"
3655
+ });
3656
+ }
3657
+ }
3658
+ if (servers !== null) {
3659
+ const parsed = readableServersFile(servers);
3660
+ const liftedServers = parsed === null ? null : liftArchived(JSON.parse(servers));
3661
+ if (parsed !== null && liftedServers !== null) {
3662
+ const serversText = `${JSON.stringify(liftedServers, null, 2)}\n`;
3663
+ archivedServers.set(id, parsed);
3664
+ addItem({
3665
+ id: `workspace:${id}:servers`,
3666
+ label: `${workspace.label}: Servers`,
3667
+ labelKey: "settings.backup.restoreItemLabel",
3668
+ labelParams: {
3669
+ workspace: workspace.label,
3670
+ item: "servers"
3671
+ },
3672
+ kind: "servers",
3673
+ workspaceId: id,
3674
+ restorable: true,
3675
+ note: null
3676
+ }, () => {
3677
+ fs.mkdirSync(path.dirname(workspace.serversPath), { recursive: true });
3678
+ writeFileAtomic(workspace.serversPath, serversText);
3679
+ });
3680
+ } else {
3681
+ plan.skipped.push(`${workspace.label}: Servers (the archive's servers are not valid)`);
3682
+ plan.skippedItems.push({
3683
+ label: `${workspace.label}: Servers`,
3684
+ labelKey: "settings.backup.restoreItemLabel",
3685
+ labelParams: {
3686
+ workspace: workspace.label,
3687
+ item: "servers"
3688
+ },
3689
+ reasonKey: "settings.restore.reasonInvalidServers"
3690
+ });
3691
+ }
3692
+ }
3693
+ if (secrets !== null) {
3694
+ addItem({
3695
+ id: `workspace:${id}:secrets`,
3696
+ label: `${workspace.label}: Secrets`,
3697
+ labelKey: "settings.backup.restoreItemLabel",
3698
+ labelParams: {
3699
+ workspace: workspace.label,
3700
+ item: "secrets"
3701
+ },
3702
+ kind: "secrets",
3703
+ workspaceId: id,
3704
+ restorable: true,
3705
+ note: null
3706
+ }, secretsApply("workspace", `workspace:${id}:secrets`, workspace.secretsPath, secrets));
3707
+ for (const part of secretParts("workspace", presentSecretKeys(parseSecrets(secrets)))) addItem({
3708
+ id: `workspace:${id}:secrets:${part.key}`,
3709
+ label: `${workspace.label}: ${SECRET_LABELS[part.key]?.en ?? part.key}`,
3710
+ labelKey: "settings.backup.restoreItemLabel",
3711
+ labelParams: {
3712
+ workspace: workspace.label,
3713
+ item: part.key
3714
+ },
3715
+ kind: "secrets",
3716
+ workspaceId: id,
3717
+ restorable: true,
3718
+ note: null
3719
+ }, () => {
3720
+ fs.mkdirSync(path.dirname(workspace.secretsPath), { recursive: true });
3721
+ mergeIntoFile(workspace.secretsPath, secrets, part.fields);
3722
+ });
3723
+ }
3724
+ }
3725
+ const instanceTargets = [];
3726
+ for (const workspace of sources.workspaces) for (const declared of this.declaredData(workspace.servers, sources.includePaths)) {
3727
+ if (!declared.included) continue;
3728
+ instanceTargets.push({
3729
+ workspace: workspace.id,
3730
+ path: declared.path,
3731
+ origin: declared.origin
3732
+ });
3733
+ }
3734
+ const archivedIncludePaths = actions.has("global:settings") && parsedGlobal !== null ? parsedGlobal.backups.includePaths : sources.includePaths;
3735
+ const archiveAll = [];
3736
+ const archiveTargets = [];
3737
+ for (const [id, servers] of archivedServers) for (const declared of this.declaredData(servers, archivedIncludePaths)) {
3738
+ if (!declared.included) continue;
3739
+ const target = {
3740
+ workspace: id,
3741
+ path: declared.path,
3742
+ origin: declared.origin
3743
+ };
3744
+ archiveAll.push(target);
3745
+ if (actions.has(`workspace:${id}:servers`)) archiveTargets.push(target);
3746
+ }
3747
+ const usedArchive = /* @__PURE__ */ new Set();
3748
+ const usedInstance = /* @__PURE__ */ new Set();
3749
+ const take = (list, used, test) => {
3750
+ const found = list.find((target) => !used.has(target) && test(target));
3751
+ if (found === void 0) return void 0;
3752
+ used.add(found);
3753
+ return found;
3754
+ };
3755
+ /**
3756
+ * Where one archived data path lands, never across a workspace boundary.
3757
+ *
3758
+ * An archive that names a workspace is only ever matched against that workspace's
3759
+ * declarations: the un-scoped fallbacks below exist to survive a re-labelled or
3760
+ * re-ordered config, and letting them cross workspaces wrote one workspace's data
3761
+ * over a path another one had declared. A path only one workspace declares has no
3762
+ * candidate at all in the other, so the entry is reported instead of guessed at.
3763
+ */
3764
+ const matchTarget = (origin, workspace, archivedPath) => {
3765
+ const inScope = (target) => workspace === void 0 || target.workspace === workspace;
3766
+ const archive = archiveTargets.filter(inScope);
3767
+ const instance = instanceTargets.filter(inScope);
3768
+ if (origin !== void 0) return take(archive, usedArchive, (target) => target.origin === origin) ?? take(instance, usedInstance, (target) => target.origin === origin) ?? take(archive, usedArchive, (target) => target.path === archivedPath) ?? take(instance, usedInstance, (target) => target.path === archivedPath);
3769
+ return take(archive, usedArchive, (target) => target.path === archivedPath) ?? take(instance, usedInstance, (target) => target.path === archivedPath);
3770
+ };
3771
+ /**
3772
+ * `workspace:serverId` for every entry running at this moment.
3773
+ *
3774
+ * Built once, before anything is copied: a data path whose owner is running is about to be
3775
+ * replaced under a live process, and the plan has to name it. Read here rather than in the
3776
+ * apply closure so a dry run reports the same list the apply would.
3777
+ */
3778
+ const runningOwners = new Set((sources.runningServers?.() ?? []).map((entry) => `${entry.workspaceId}:${entry.serverId}`));
3779
+ for (const dump of manifest.dumps ?? []) {
3780
+ const from = path.join(staging, "dumps", dump.workspaceId, dump.serverId);
3781
+ if (!fs.existsSync(from)) continue;
3782
+ addItem({
3783
+ id: `workspace:${dump.workspaceId}:dump:${dump.serverId}`,
3784
+ label: `dump:${dump.serverId}`,
3785
+ kind: "data",
3786
+ restorable: true,
3787
+ workspaceId: dump.workspaceId,
3788
+ note: null
3789
+ }, () => {});
3790
+ }
3791
+ const archivedEntries = Array.isArray(manifest.data) ? manifest.data.filter(isRecord) : [];
3792
+ for (const entry of archivedEntries) {
3793
+ const archivedPath = typeof entry.path === "string" ? entry.path : "";
3794
+ const origin = typeof entry.origin === "string" ? entry.origin : void 0;
3795
+ const workspace = typeof entry.workspace === "string" ? entry.workspace : void 0;
3796
+ const from = path.join(staging, "data", safeSlug(entry.slug) ?? slugifyPath(archivedPath));
3797
+ const target = matchTarget(origin, workspace, archivedPath);
3798
+ const targetWorkspace = target?.workspace ?? workspace;
3799
+ const base = {
3800
+ id: target === void 0 ? `data:${archivedPath}` : `workspace:${target.workspace}:data:${target.path}`,
3801
+ label: target?.path ?? archivedPath,
3802
+ kind: "data",
3803
+ restorable: false,
3804
+ note: null,
3805
+ ...targetWorkspace === void 0 ? {} : { workspaceId: targetWorkspace }
3806
+ };
3807
+ const aliases = [`data:${archivedPath}`];
3808
+ if (target === void 0) {
3809
+ const declaredByBackup = archiveAll.some((candidate) => candidate.origin === origin && (workspace === void 0 || candidate.workspace === workspace));
3810
+ addItem({
3811
+ ...base,
3812
+ note: declaredByBackup ? "declared by the backup's config, which is not being restored" : "not declared by this config, nor by the backup",
3813
+ noteKey: declaredByBackup ? "settings.backup.noteDeclaredByBackup" : "settings.backup.noteNotDeclared"
3814
+ }, null, aliases);
3815
+ continue;
3816
+ }
3817
+ if (!fs.existsSync(from)) {
3818
+ addItem({
3819
+ ...base,
3820
+ note: "missing from the archive",
3821
+ noteKey: "settings.backup.noteMissingFromArchive"
3822
+ }, null, aliases);
3823
+ continue;
3824
+ }
3825
+ const ownerId = target.origin.split(":")[0] ?? "";
3826
+ if (!selects.isExcluded(base.id) && (selects(base.id) || aliases.some((alias) => selects(alias))) && runningOwners.has(`${target.workspace}:${ownerId}`)) plan.replacedUnderRunning.push({
3827
+ workspaceId: target.workspace,
3828
+ serverId: ownerId,
3829
+ path: target.path
3830
+ });
3831
+ addItem({
3832
+ ...base,
3833
+ restorable: true,
3834
+ ...target.path === archivedPath ? { note: null } : {
3835
+ note: `restored from ${archivedPath}`,
3836
+ noteKey: "settings.backup.noteRestoredFrom",
3837
+ noteParams: { path: archivedPath }
3838
+ }
3839
+ }, () => copyTree(from, target.path, (_source, destination) => isInsideResolved(target.path, destination)), aliases);
3840
+ }
3841
+ if (parsedGlobal !== null && actions.has("global:settings") && settingsText !== null) {
3842
+ const current = readableGlobalSettings(readText(sources.globalSettingsPath));
3843
+ plan.restartRequired = JSON.stringify(parsedGlobal.control) !== JSON.stringify(current === null ? null : parseGlobalSettings(current).config?.control ?? null);
3844
+ }
3845
+ if (!options.confirm) {
3846
+ plan.applied = [...actions.keys()].map((id) => labelOf(plan, id));
3847
+ plan.appliedIds = [...actions.keys()];
3848
+ return plan;
3849
+ }
3850
+ let failure = null;
3851
+ for (const [id, apply] of actions) {
3852
+ try {
3853
+ await apply();
3854
+ } catch (error) {
3855
+ failure = error;
3856
+ break;
3857
+ }
3858
+ plan.applied.push(labelOf(plan, id));
3859
+ plan.appliedIds.push(id);
3860
+ }
3861
+ for (const workspace of createdWorkspaces.values()) {
3862
+ if (!plan.appliedIds.some((id) => id.startsWith(`workspace:${workspace.id}:`))) continue;
3863
+ this.options.ensureWorkspace?.({
3864
+ id: workspace.id,
3865
+ label: workspace.label
3866
+ });
3867
+ plan.createdWorkspaces.push(workspace.id);
3868
+ }
3869
+ if (failure !== null) {
3870
+ this.reloadRestored(plan);
3871
+ throw failure;
3872
+ }
3873
+ /**
3874
+ * The load phase: let each restored entry put its own dump back.
3875
+ *
3876
+ * After the files landed and before the panel reloads, so the engine reads a config this
3877
+ * release has just written rather than the one it replaced. Only the entries the archive
3878
+ * actually brought a dump for — an archive taken before the hook existed has none, and running
3879
+ * `mongorestore` on a directory that is not there fails the whole restore for no reason.
3880
+ */
3881
+ const archivedDumps = manifest.dumps ?? [];
3882
+ const pendingLoads = [];
3883
+ for (const entry of archivedDumps) {
3884
+ if (!plan.appliedIds.some((id) => id.startsWith(`workspace:${entry.workspaceId}:`))) continue;
3885
+ if (!actions.has(`workspace:${entry.workspaceId}:dump:${entry.serverId}`) && !actions.has(`workspace:${entry.workspaceId}`)) continue;
3886
+ const server = readArchivedServers(staging, entry.workspaceId).find((candidate) => candidate.id === entry.serverId);
3887
+ if (server?.load === void 0 || server.load === null) {
3888
+ plan.skipped.push(`the dump for "${entry.serverId}" was restored but this entry has no load hook`);
3889
+ continue;
3890
+ }
3891
+ const dumpDir = path.join(staging, "dumps", entry.workspaceId, entry.serverId);
3892
+ if (!fs.existsSync(dumpDir)) {
3893
+ plan.skipped.push(`the dump for "${entry.serverId}" is missing from the archive`);
3894
+ continue;
3895
+ }
3896
+ const staged = path.join(this.options.dataRoot, PENDING_LOAD, entry.workspaceId, entry.serverId);
3897
+ await copyTree(dumpDir, staged, () => true);
3898
+ pendingLoads.push({
3899
+ workspaceId: entry.workspaceId,
3900
+ serverId: entry.serverId,
3901
+ staged
3902
+ });
3903
+ plan.hooks = [...plan.hooks ?? [], {
3904
+ serverId: entry.serverId,
3905
+ workspaceId: entry.workspaceId,
3906
+ action: "load",
3907
+ ok: true,
3908
+ output: "staged — runs when this entry next starts"
3909
+ }];
3910
+ }
3911
+ for (const load of pendingLoads) this.options.onLoadPending?.(load.workspaceId, load.serverId, load.staged);
3912
+ this.reloadRestored(plan);
3913
+ return plan;
3914
+ } catch (error) {
3915
+ if (isInvalidPassword(error)) return {
3916
+ ...plan,
3917
+ encrypted: true,
3918
+ needsPassword: true,
3919
+ error: "the password is wrong"
3920
+ };
3921
+ const done = plan.applied.length > 0 ? ` — already applied: ${plan.applied.join(", ")}` : "";
3922
+ return {
3923
+ ...plan,
3924
+ error: `${errorMessage(error)}${done}`
3925
+ };
3926
+ } finally {
3927
+ fs.rmSync(staging, {
3928
+ recursive: true,
3929
+ force: true
3930
+ });
3931
+ this.sweepStaging();
3932
+ }
3933
+ }
3934
+ /** The panel re-reads the restored settings and servers, so what the archive brought exists immediately. */
3935
+ reloadRestored(plan) {
3936
+ if (this.options.onRestored === void 0 || !plan.appliedIds.some((id) => RELOADABLE.test(id))) return;
3937
+ plan.reloaded = true;
3938
+ this.options.onRestored();
3939
+ }
3940
+ /** Selectable entries: the three global slices, then one per workspace. */
3941
+ entries(sources) {
3942
+ const missing = (path, key) => {
3943
+ const absent = this.missingNote(path);
3944
+ return absent === null ? { note: null } : {
3945
+ note: absent,
3946
+ noteKey: key
3947
+ };
3948
+ };
3949
+ const entries = [
3950
+ {
3951
+ id: "global:settings",
3952
+ label: "Global settings",
3953
+ labelKey: "settings.backup.entryGlobalSettings",
3954
+ kind: "settings",
3955
+ ...missing(sources.globalSettingsPath, "settings.backup.noteMissing"),
3956
+ items: []
3957
+ },
3958
+ {
3959
+ id: "global:secrets",
3960
+ label: "Global secrets (password, API token)",
3961
+ labelKey: "settings.backup.entryGlobalSecrets",
3962
+ kind: "secrets",
3963
+ ...missing(sources.globalSecretsPath, "settings.backup.noteMissing"),
3964
+ items: this.secretItems("global", "global:secrets", sources.globalSecretsPath)
3965
+ },
3966
+ {
3967
+ id: "global:tls",
3968
+ label: "TLS certificate",
3969
+ labelKey: "settings.backup.entryTlsCertificate",
3970
+ kind: "tls",
3971
+ ...missing(sources.tlsDir, "settings.backup.noteMissing"),
3972
+ items: []
3973
+ }
3974
+ ];
3975
+ for (const workspace of sources.workspaces) entries.push({
3976
+ id: `workspace:${workspace.id}`,
3977
+ label: workspace.label,
3978
+ kind: "workspace",
3979
+ workspaceId: workspace.id,
3980
+ note: null,
3981
+ items: this.workspaceItems(workspace, sources.includePaths)
3982
+ });
3983
+ return entries;
3984
+ }
3985
+ /**
3986
+ * One leaf per secret the file actually holds, so a restore can bring back the
3987
+ * password without the API token, or the Telegram token without the DDNS credentials.
3988
+ *
3989
+ * The set comes from the file's own top-level keys rather than a list here, so a
3990
+ * secret added later appears on its own — the failure mode of a second list is a
3991
+ * secret that can be captured but never restored individually.
3992
+ */
3993
+ secretItems(scope, entryId, path) {
3994
+ const parts = secretParts(scope, presentSecretKeys(parseSecrets(readText(path) ?? "")));
3995
+ const missing = KNOWN_SECRET_KEYS[scope].filter((key) => !parts.some((part) => part.key === key));
3996
+ return [...parts.map((part) => ({
3997
+ id: `${entryId}:${part.key}`,
3998
+ label: SECRET_LABELS[part.key]?.en ?? part.key,
3999
+ ...SECRET_LABELS[part.key] === void 0 ? {} : { labelKey: SECRET_LABELS[part.key].key },
4000
+ kind: "secrets",
4001
+ secret: part.key,
4002
+ included: true,
4003
+ note: null
4004
+ })), ...missing.map((key) => ({
4005
+ id: `${entryId}:${key}`,
4006
+ label: SECRET_LABELS[key]?.en ?? key,
4007
+ ...SECRET_LABELS[key] === void 0 ? {} : { labelKey: SECRET_LABELS[key].key },
4008
+ kind: "secrets",
4009
+ secret: key,
4010
+ included: false,
4011
+ note: "not set",
4012
+ noteKey: "settings.backup.noteMissing"
4013
+ }))];
4014
+ }
4015
+ workspaceItems(workspace, includePaths) {
4016
+ const id = workspace.id;
4017
+ const note = (path) => {
4018
+ const absent = this.missingNote(path);
4019
+ return absent === null ? { note: null } : {
4020
+ note: absent,
4021
+ noteKey: "settings.backup.noteMissing"
4022
+ };
4023
+ };
4024
+ const items = [
4025
+ {
4026
+ id: `workspace:${id}:settings`,
4027
+ label: "Settings",
4028
+ labelKey: "settings.backup.leafSettings",
4029
+ kind: "settings",
4030
+ included: true,
4031
+ ...note(workspace.settingsPath)
4032
+ },
4033
+ {
4034
+ id: `workspace:${id}:servers`,
4035
+ label: "Servers",
4036
+ labelKey: "settings.backup.leafServers",
4037
+ kind: "servers",
4038
+ included: true,
4039
+ ...note(workspace.serversPath)
4040
+ },
4041
+ {
4042
+ id: `workspace:${id}:secrets`,
4043
+ label: "Secrets",
4044
+ labelKey: "settings.backup.leafSecrets",
4045
+ kind: "secrets",
4046
+ included: true,
4047
+ ...note(workspace.secretsPath)
4048
+ },
4049
+ ...this.secretItems("workspace", `workspace:${id}:secrets`, workspace.secretsPath)
4050
+ ];
4051
+ for (const declared of this.declaredData(workspace.servers, includePaths)) items.push({
4052
+ id: `workspace:${id}:data:${declared.path}`,
4053
+ label: declared.path,
4054
+ kind: "data",
4055
+ path: declared.path,
4056
+ origin: declared.origin,
4057
+ included: declared.included,
4058
+ note: declared.note,
4059
+ ...declared.noteKey === void 0 ? {} : { noteKey: declared.noteKey },
4060
+ ...declared.noteParams === void 0 ? {} : { noteParams: declared.noteParams },
4061
+ ignoreGenerated: declared.ignoreGenerated
4062
+ });
4063
+ return items;
4064
+ }
4065
+ /**
4066
+ * Declared data paths with the archive-directory veto applied: capturing a
4067
+ * directory that contains the archive directory would make the archive
4068
+ * contain itself.
4069
+ */
4070
+ declaredData(servers, includePaths) {
4071
+ const archiveDir = path.resolve(this.resolveDir());
4072
+ return resolveBackupPaths(servers, includePaths, this.backupVars(servers)).map((entry) => {
4073
+ if (entry.included && isInside(entry.path, archiveDir)) return {
4074
+ ...entry,
4075
+ included: false,
4076
+ note: "contains the backup directory",
4077
+ noteKey: "settings.backup.noteContainsBackupDir"
4078
+ };
4079
+ return entry;
4080
+ });
4081
+ }
4082
+ /** The `{dataRoot}` a config expands to, without a module-level state root. */
4083
+ backupVars(servers) {
4084
+ const first = servers[0];
4085
+ return {
4086
+ projectDir,
4087
+ dataRoot: first === void 0 ? path.dirname(path.resolve(this.options.dataRoot)) : String(serverTemplateVars(first).dataRoot ?? projectDir),
4088
+ home: os.homedir()
4089
+ };
4090
+ }
4091
+ /**
4092
+ * Reclaims the staging trees a killed backup left behind.
4093
+ *
4094
+ * `create()` removes its staging on success and in a `catch`, which covers every failure it can
4095
+ * observe — but a `SIGKILL`, a power cut or a container stop never returns to run the `catch`.
4096
+ * Measured on a real home with a 60 MB data path: two interrupted runs left two `.staging-*`
4097
+ * trees, **121 MB** beside a single 184 B archive. `scan()` filters on `.zip` and `prune()` walks
4098
+ * `list()`, so nothing listed them and nothing removed them — the debris of a failed attempt
4099
+ * holding the free space the next one needs, on the disk that already filled.
4100
+ *
4101
+ * The owner's pid decides it, never an age: another run sharing this directory is *live*, not
4102
+ * stale, and deleting its tree would destroy a capture in progress. `isProcessAlive` is the same
4103
+ * predicate every other liveness question here asks.
4104
+ *
4105
+ * Both trees this service stages are swept — a capture and a restore — because the leak is the
4106
+ * shape, not one call site. A restore's tree holds an unpacked copy of an archive, so it is the
4107
+ * larger of the two.
4108
+ */
4109
+ sweepStaging() {
4110
+ const dir = this.resolveDir();
4111
+ let names;
4112
+ try {
4113
+ names = fs.readdirSync(dir);
4114
+ } catch {
4115
+ return;
4116
+ }
4117
+ for (const name of names) {
4118
+ const owner = stagingOwner(name);
4119
+ if (owner === null || owner === process.pid || isProcessAlive(owner)) continue;
4120
+ try {
4121
+ fs.rmSync(path.join(dir, name), {
4122
+ recursive: true,
4123
+ force: true
4124
+ });
4125
+ } catch {}
4126
+ }
4127
+ }
4128
+ /** Newest-first listing, without the encryption flag, which needs a read. */
4129
+ scan() {
4130
+ const dir = this.resolveDir();
4131
+ let names = [];
4132
+ try {
4133
+ names = fs.readdirSync(dir);
4134
+ } catch {
4135
+ return [];
4136
+ }
4137
+ return names.filter((name) => name.endsWith(SUFFIX)).flatMap((name) => {
4138
+ try {
4139
+ const stats = fs.statSync(path.join(dir, name));
4140
+ return [{
4141
+ name,
4142
+ sizeBytes: stats.size,
4143
+ createdAt: Math.round(stats.mtimeMs)
4144
+ }];
4145
+ } catch {
4146
+ return [];
4147
+ }
4148
+ }).sort((a, b) => b.createdAt - a.createdAt);
4149
+ }
4150
+ /** Single-flight: a state frame must never queue a pile of reads. */
4151
+ scheduleRefresh() {
4152
+ this.refreshing ??= this.refresh().finally(() => {
4153
+ this.refreshing = null;
4154
+ });
4155
+ return this.refreshing;
4156
+ }
4157
+ async refresh() {
4158
+ const dir = this.resolveDir();
4159
+ const listed = this.scan();
4160
+ for (const file of listed) {
4161
+ const key = cacheKey(file);
4162
+ if (this.flags.get(file.name)?.key === key) continue;
4163
+ try {
4164
+ const entries = await listZip(path.join(dir, file.name));
4165
+ this.flags.set(file.name, {
4166
+ key,
4167
+ encrypted: entries.some((entry) => entry.encrypted)
4168
+ });
4169
+ } catch {
4170
+ this.flags.set(file.name, {
4171
+ key,
4172
+ encrypted: false
4173
+ });
4174
+ }
4175
+ }
4176
+ const present = new Set(listed.map((file) => file.name));
4177
+ for (const name of [...this.flags.keys()]) if (!present.has(name)) this.flags.delete(name);
4178
+ }
4179
+ missingNote(target) {
4180
+ return fs.existsSync(target) ? null : "not set";
4181
+ }
4182
+ /** Copies one source into the staging tree; false when there was nothing there. */
4183
+ async copyInto(staging, relative, source, ignoreGenerated = false) {
4184
+ if (!fs.existsSync(source)) return false;
4185
+ const target = path.join(staging, relative);
4186
+ fs.mkdirSync(path.dirname(target), { recursive: true });
4187
+ const archiveDir = path.resolve(this.resolveDir());
4188
+ const root = path.resolve(source);
4189
+ await copyTree(source, target, (from) => {
4190
+ const resolved = path.resolve(from);
4191
+ if (isInside(archiveDir, resolved)) return false;
4192
+ if (isSecretDocument(path.basename(resolved))) return false;
4193
+ if (!ignoreGenerated || resolved === root) return true;
4194
+ return !isGeneratedPath(path.relative(root, resolved));
4195
+ });
4196
+ return true;
4197
+ }
4198
+ /**
4199
+ * Drops the oldest archives past their own limit.
4200
+ *
4201
+ * Two budgets, because the two sources are not the same thing: `keep` is what a person
4202
+ * agreed to store, and pruning a hand-taken archive to make room for a scheduled one would
4203
+ * lose the copy they deliberately made. The scheduled pair keeps `schedule.keep` automatic
4204
+ * archives; the rest keeps `keep`.
4205
+ */
4206
+ prune() {
4207
+ const config = this.options.getConfig();
4208
+ const files = this.list();
4209
+ const automatic = files.filter(isAutomatic);
4210
+ const manual = files.filter((file) => ARCHIVE_NAME.exec(file.name)?.[1] === MANUAL_PREFIX);
4211
+ for (const file of automatic.slice(config.schedule.keep)) this.remove(file.name);
4212
+ for (const file of manual.slice(config.keep)) this.remove(file.name);
4213
+ this.sweepPartials();
4214
+ }
4215
+ /**
4216
+ * An archive killed mid-write leaves its `.<name>.partial` behind (`createZip` renames only on
4217
+ * success). An hour old is never a write in progress — a live one keeps touching its mtime.
4218
+ */
4219
+ sweepPartials(now = Date.now()) {
4220
+ const dir = this.resolveDir();
4221
+ let names = [];
4222
+ try {
4223
+ names = fs.readdirSync(dir);
4224
+ } catch {
4225
+ return;
4226
+ }
4227
+ for (const name of names.filter((entry) => entry.startsWith(".") && entry.endsWith(`${SUFFIX}.partial`))) {
4228
+ const file = path.join(dir, name);
4229
+ try {
4230
+ if (now - fs.statSync(file).mtimeMs > 36e5) fs.rmSync(file, { force: true });
4231
+ } catch {}
4232
+ }
4233
+ }
4234
+ /** When the newest automatic archive was written, or null when there is none. */
4235
+ lastAutomatic() {
4236
+ return this.list().find(isAutomatic)?.createdAt ?? null;
4237
+ }
4238
+ /**
4239
+ * Runs one scheduled pass when it is due. Modelled on the DDNS pass: cheap to call on every
4240
+ * panel tick, never blocking, and never two at once.
4241
+ */
4242
+ tick(now = Date.now()) {
4243
+ if (this.disposed || this.running) return;
4244
+ const config = this.options.getConfig();
4245
+ if (!config.enabled || config.schedule.intervalMs <= 0) return;
4246
+ const last = this.lastAutomatic();
4247
+ const latest = last === null ? this.lastAttemptAt : Math.max(last, this.lastAttemptAt ?? 0);
4248
+ if (latest !== null && now - latest < config.schedule.intervalMs) return;
4249
+ const restoring = restoreLockHolder(this.options.dataRoot);
4250
+ if (restoring !== null) {
4251
+ if (!this.deferredForRestore) logger.info(`the scheduled backup is waiting for the restore that is running (pid ${restoring.pid})`);
4252
+ this.deferredForRestore = true;
4253
+ return;
4254
+ }
4255
+ this.deferredForRestore = false;
4256
+ this.running = true;
4257
+ this.lastAttemptAt = now;
4258
+ this.create({
4259
+ automatic: true,
4260
+ ...scopeSelection(config.schedule.scope)
4261
+ }).then((result) => {
4262
+ if (result.ok) {
4263
+ this.scheduleError = null;
4264
+ return;
4265
+ }
4266
+ this.scheduleError = {
4267
+ message: result.error ?? "the scheduled backup failed",
4268
+ at: Date.now()
4269
+ };
4270
+ logger.warn("the scheduled backup failed", result.error);
4271
+ }).catch((error) => {
4272
+ this.scheduleError = {
4273
+ message: errorMessage(error),
4274
+ at: Date.now()
4275
+ };
4276
+ logger.error("the scheduled backup failed", error);
4277
+ }).finally(() => {
4278
+ this.running = false;
4279
+ });
4280
+ }
4281
+ resolveDir() {
4282
+ const configured = this.options.getConfig().dir;
4283
+ return path.isAbsolute(configured) ? configured : path.resolve(this.options.dataRoot, configured);
4284
+ }
4285
+ };
4286
+ /** Whether an archive came from the schedule rather than from a person. */
4287
+ function isAutomatic(file) {
4288
+ return ARCHIVE_NAME.exec(file.name)?.[1] === AUTO_PREFIX;
4289
+ }
4290
+ /** The label of one item, for `applied`; items are built before actions run. */
4291
+ function labelOf(plan, id) {
4292
+ return plan.items.find((item) => item.id === id)?.label ?? id;
4293
+ }
4294
+ /**
4295
+ * Restores only `fields` from an archived secrets document into a live one.
4296
+ *
4297
+ * The archive may predate a secret the live file holds, and the live file may hold one
4298
+ * the archive never carried: merging by field is what makes restoring the Telegram token
4299
+ * leave the DDNS credentials alone, and what clears a secret the archive does not carry
4300
+ * rather than leaving the newer value behind as if it had been restored.
4301
+ */
4302
+ function mergeIntoFile(target, archived, fields) {
4303
+ const merged = mergeSecrets(parseSecrets(readText(target) ?? ""), parseSecrets(archived), fields);
4304
+ writeFileAtomic(target, `${JSON.stringify(merged, null, 2)}\n`, { mode: 384 });
4305
+ }
4306
+ /**
4307
+ * What an archive says about where it came from. Both fields are absent on an archive
4308
+ * written before they existed, so a UI shows the row only when there is something to show.
4309
+ */
4310
+ function manifestInfo(manifest) {
4311
+ return {
4312
+ ...manifest.writtenBy === void 0 ? {} : { writtenBy: manifest.writtenBy },
4313
+ ...manifest.schema === void 0 ? {} : { schema: manifest.schema }
4314
+ };
4315
+ }
4316
+ /**
4317
+ * `servers.config.json` is only a readability gate here: the store applies the
4318
+ * workspace's own defaults on the next load, and an archive from another machine
4319
+ * need not match this one's default shapes exactly.
4320
+ *
4321
+ * An older archive is lifted to this release's schema first, so its entries are adopted rather
4322
+ * than dropped; `null` means this release cannot read it at all.
4323
+ */
4324
+ function readableServersFile(text) {
4325
+ try {
4326
+ const lifted = liftArchived(JSON.parse(text));
4327
+ if (lifted === null) return null;
4328
+ const result = parseServersFile(lifted, {});
4329
+ return result.errors.length === 0 ? result.servers : null;
4330
+ } catch {
4331
+ return null;
4332
+ }
4333
+ }
4334
+ /** A workspace settings file is adopted only when this release can read it, lifted when older. */
4335
+ function readableWorkspaceSettings(text) {
4336
+ try {
4337
+ const lifted = liftArchived(JSON.parse(text));
4338
+ return lifted !== null && parseWorkspaceSettings(lifted).config !== null ? lifted : null;
4339
+ } catch {
4340
+ return null;
4341
+ }
4342
+ }
4343
+ //#endregion
4344
+ export { normalizeHost as A, expandEnvList as C, ddnsProvider as D, resolveEnvFilePath as E, ddnsProviderInfos as O, targetProblem as S, loadEnvFile as T, entryStatePath as _, unknownBackupIds as a, WorkspaceStore as b, serverTemplateVars as c, isExposed as d, lanAddress as f, clearEntryState as g, resolveTemplates as h, selectionWritesCredentials as i, validateDdnsConfig as k, bindHost as l, resolveTemplate as m, buildBackupSources as n, hookFailure as o, resolveRecord as p, selectionOf as r, runBackupHook as s, BackupService as t, displayHost as u, readEntryState as v, expandEnvRecord as w, sendWebhook as x, writeEntryState as y };
4345
+
4346
+ //# sourceMappingURL=backups-Bd2SF2qd.js.map