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