home-hosted 0.13.0 → 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-CZcVca2a.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-pKbGCW9d.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-B-Eu0sFW.js → nanny-BWh7nuvv.js} +21 -14
  64. package/dist/chunks/nanny-BWh7nuvv.js.map +1 -0
  65. package/dist/chunks/{nanny-ChMtq1Zl.js → nanny-BjF2-1pv.js} +3 -3
  66. package/dist/chunks/{nanny-ChMtq1Zl.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-DErnlPY1.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-B8WBTRMk.js → port-CnsrxKNR.js} +27 -71
  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-Des4DrAN.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-BtWMFmzZ.js → src-BnzkVy_M.js} +12548 -10576
  112. package/dist/chunks/src-BnzkVy_M.js.map +1 -0
  113. package/dist/chunks/{status-DT1EsA-B.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-Pdz-l6IH.js → up-BQSnYxYd.js} +47 -53
  138. package/dist/chunks/up-BQSnYxYd.js.map +1 -0
  139. package/dist/chunks/{usage-DFrCVXpT.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-CZcVca2a.js.map +0 -1
  405. package/dist/chunks/backups-CFRaWe_m.js +0 -4691
  406. package/dist/chunks/backups-CFRaWe_m.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-log-BVj8cDEo.js +0 -241
  411. package/dist/chunks/daemon-log-BVj8cDEo.js.map +0 -1
  412. package/dist/chunks/daemon-qKVECISl.js +0 -247
  413. package/dist/chunks/daemon-qKVECISl.js.map +0 -1
  414. package/dist/chunks/docker-Cy9Lyvda.js.map +0 -1
  415. package/dist/chunks/down-pKbGCW9d.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-B-Eu0sFW.js.map +0 -1
  430. package/dist/chunks/nanny-BtWfy0QH.js +0 -1167
  431. package/dist/chunks/nanny-BtWfy0QH.js.map +0 -1
  432. package/dist/chunks/nanny-sweep-DErnlPY1.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-B8WBTRMk.js.map +0 -1
  437. package/dist/chunks/restart-Des4DrAN.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-Bge2r2qQ.js +0 -169
  442. package/dist/chunks/server-Bge2r2qQ.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-obPiEJYk.js +0 -78
  448. package/dist/chunks/set-token-obPiEJYk.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-BtWMFmzZ.js.map +0 -1
  454. package/dist/chunks/status-DT1EsA-B.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-Pdz-l6IH.js.map +0 -1
  462. package/dist/chunks/usage-DFrCVXpT.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
@@ -0,0 +1,2203 @@
1
+ import { E as errorMessage, t as appVersion } from "../cli.js";
2
+ import { f as projectDir, i as ensureStateDir, x as resolveUserPath } from "./paths-C34-TJLh.js";
3
+ import { t as writeFileAtomic } from "./atomic-SZUwDtGD.js";
4
+ import { n as readStateFile } from "./config-text-DxMOQQnk.js";
5
+ import { t as logger } from "./logger-BnrKTBHQ.js";
6
+ import { t as isRecord } from "./shape-CDGeYl_J.js";
7
+ import { c as applyConfigMigrations, i as parseWorkspaceSettings, l as planConfigMigrations, n as parseServersFile, s as stampConfig, t as parseGlobalSettings } from "./parse-DVMPLUDe.js";
8
+ import { A as jobsFileSchema, W as serverSchema, st as workspaceIdSchema, v as entryStateSchema } from "./contracts-CxZ7u1L3.js";
9
+ import { a as expandEnv } from "./store-Bs_Lljjm.js";
10
+ import { r as parseWorkspacesFile } from "./workspaces-D9akpzU8.js";
11
+ import { r as isProcessAlive } from "./port-CnsrxKNR.js";
12
+ import { i as resolveCwd } from "./process-CboOFPU_.js";
13
+ import { i as liftJobsDocument, n as jobProblems } from "./jobs-BX4ahcfh.js";
14
+ import { a as listZip, i as isZipArchive, n as extractZip, o as copyTree, r as isInvalidPassword, t as createZip } from "./archive-DFi3qK1c.js";
15
+ import { n as resolveTemplate, r as resolveTemplates, t as resolveRecord } from "./template-xan58bJh.js";
16
+ import { t as serverTemplateVars } from "./server-vars-DMYmHutL.js";
17
+ import process from "node:process";
18
+ import path from "node:path";
19
+ import fs from "node:fs";
20
+ import { createHash } from "node:crypto";
21
+ import os from "node:os";
22
+ import { type } from "arktype";
23
+ import { spawn } from "node:child_process";
24
+ import { DetailedError } from "@namesmt/utils";
25
+ //#region src/providers/entry-state.ts
26
+ /**
27
+ * The runtime the panel must remember across its own restarts: the spent retry budget and whether a
28
+ * `runOnce` bootstrap ran. In memory only, a restart reset a crash loop's `maxRetries`.
29
+ */
30
+ function entryStatePath(dir, id) {
31
+ return path.join(dir, `${id}.run.json`);
32
+ }
33
+ function readEntryState(file) {
34
+ try {
35
+ const parsed = entryStateSchema(JSON.parse(fs.readFileSync(file, "utf8")));
36
+ return parsed instanceof type.errors ? null : parsed;
37
+ } catch {
38
+ return null;
39
+ }
40
+ }
41
+ /** `path:code` pairs already warned about, so a read-only disk logs once per file, not once per save. */
42
+ var warned = /* @__PURE__ */ new Set();
43
+ /** Best effort, like history: no state file must never stop supervision. False when the write failed. */
44
+ function writeEntryState(file, state) {
45
+ try {
46
+ writeFileAtomic(file, `${JSON.stringify(state)}\n`);
47
+ return true;
48
+ } catch (error) {
49
+ const code = error.code ?? "unknown";
50
+ const key = `${file}:${code}`;
51
+ if (!warned.has(key)) {
52
+ warned.add(key);
53
+ logger.warn(`could not save ${path.basename(file)} (${code}): the retry budget and pending load will not survive a panel restart`);
54
+ }
55
+ return false;
56
+ }
57
+ }
58
+ function clearEntryState(file) {
59
+ fs.rmSync(file, { force: true });
60
+ }
61
+ //#endregion
62
+ //#region src/config/secret-parts.ts
63
+ /** Every secret this release knows about, set or not — the view lists the slots so a person sees one. */
64
+ var KNOWN_SECRET_KEYS = {
65
+ global: ["password", "apiToken"],
66
+ workspace: ["telegram", "ddns"]
67
+ };
68
+ /** Where a secret this release knows lives. Everything else is scoped by its own file. */
69
+ var KNOWN_SCOPES = {
70
+ password: "global",
71
+ apiToken: "global",
72
+ telegram: "workspace",
73
+ ddns: "workspace"
74
+ };
75
+ /** A part carrying more than its own key: `ddnsKdf` is how the sealed DDNS entries are opened. */
76
+ var EXTRA_FIELDS = { ddns: ["ddns", "ddnsKdf"] };
77
+ /**
78
+ * The parts of one scope: known parts first in a fixed order, then any other key present, sorted.
79
+ * An unknown key belongs to the scope asked about, since its file is the only evidence of where it lives.
80
+ */
81
+ function secretParts(scope, present) {
82
+ const keys = new Set(present);
83
+ const known = KNOWN_SECRET_KEYS[scope];
84
+ const parts = known.filter((key) => keys.has(key)).map((key) => ({
85
+ key,
86
+ fields: EXTRA_FIELDS[key] ?? [key],
87
+ scope
88
+ }));
89
+ const consumed = new Set(parts.flatMap((part) => part.fields));
90
+ const rest = [...keys].filter((key) => KNOWN_SCOPES[key] === void 0 && !known.includes(key) && !consumed.has(key)).sort();
91
+ return [...parts, ...rest.map((key) => ({
92
+ key,
93
+ fields: [key],
94
+ scope
95
+ }))];
96
+ }
97
+ /** Collections a fresh secrets file carries empty; empty, they hold nothing to back up or restore. */
98
+ var COLLECTION_KEYS = /* @__PURE__ */ new Set([
99
+ "accounts",
100
+ "apiTokens",
101
+ "serverEnv",
102
+ "jobEnv"
103
+ ]);
104
+ function presentSecretKeys(source) {
105
+ return Object.entries(source).filter(([key, value]) => {
106
+ if (value === null || value === void 0) return false;
107
+ if (!COLLECTION_KEYS.has(key)) return true;
108
+ return Array.isArray(value) ? value.length > 0 : !isRecord(value) || Object.keys(value).length > 0;
109
+ }).map(([key]) => key);
110
+ }
111
+ /** A JSON string carrying only the non-null `fields` of `source`, or null when it carries none. */
112
+ function pickSecrets(source, fields) {
113
+ const picked = {};
114
+ for (const field of fields) {
115
+ const value = source[field];
116
+ if (value !== null && value !== void 0) picked[field] = withoutFirstRunPassword(value);
117
+ }
118
+ return Object.keys(picked).length === 0 ? null : JSON.stringify(picked);
119
+ }
120
+ /** Drops `password.initial`: an archive leaves the box, and the hash alone restores the password. */
121
+ function withoutFirstRunPassword(value) {
122
+ if (!isRecord(value) || !("initial" in value)) return value;
123
+ const { initial: _initial, ...rest } = value;
124
+ return rest;
125
+ }
126
+ /** The same removal over a whole secrets document; `null` when the text is not a JSON object. */
127
+ function withoutInitialPassword(text) {
128
+ let parsed;
129
+ try {
130
+ parsed = JSON.parse(text);
131
+ } catch {
132
+ return null;
133
+ }
134
+ if (!isRecord(parsed)) return null;
135
+ return `${JSON.stringify("password" in parsed ? {
136
+ ...parsed,
137
+ password: withoutFirstRunPassword(parsed.password)
138
+ } : parsed)}\n`;
139
+ }
140
+ /** Parses a secrets document, tolerating anything: not-an-object, or broken JSON returns {}. */
141
+ function parseSecrets(text) {
142
+ try {
143
+ const parsed = JSON.parse(text);
144
+ return isRecord(parsed) ? parsed : {};
145
+ } catch {
146
+ return {};
147
+ }
148
+ }
149
+ /**
150
+ * Merges `piece` into `current`, changing only `fields`; a field absent from `piece` is deleted, so an
151
+ * older archive clears a secret it predates. Does not mutate its arguments.
152
+ */
153
+ function mergeSecrets(current, piece, fields) {
154
+ const merged = { ...current };
155
+ for (const field of fields) {
156
+ const value = piece[field];
157
+ if (value === null || value === void 0) delete merged[field];
158
+ else merged[field] = value;
159
+ }
160
+ return merged;
161
+ }
162
+ //#endregion
163
+ //#region src/helpers/restore-lock.ts
164
+ /**
165
+ * A lock file that stops two restores — the panel's and the offline CLI's alike — from writing the
166
+ * same host at once. A dead holder is detected by pid *and* start time, so a recycled pid is not
167
+ * mistaken for a live one.
168
+ */
169
+ /** How long a restore may hold the lock before another waits no longer on it. */
170
+ var STALE_AFTER_MS = 18e5;
171
+ /** Absorbs the one-second granularity of a birth-time reading against the moment we recorded it. */
172
+ var BIRTH_TOLERANCE_MS = 2e3;
173
+ function readRecord(file) {
174
+ try {
175
+ const parsed = JSON.parse(fs.readFileSync(file, "utf8"));
176
+ if (typeof parsed.pid !== "number" || typeof parsed.startedAt !== "number") return null;
177
+ return {
178
+ pid: parsed.pid,
179
+ startedAt: parsed.startedAt,
180
+ action: typeof parsed.action === "string" ? parsed.action : "restore",
181
+ birthAt: typeof parsed.birthAt === "number" ? parsed.birthAt : null
182
+ };
183
+ } catch {
184
+ return null;
185
+ }
186
+ }
187
+ /**
188
+ * Is the recorded holder still the process that took it? Where no start time is available an alive
189
+ * pid is taken as alive, erring towards not stealing a live lock.
190
+ */
191
+ function holderIsAlive(record) {
192
+ try {
193
+ process.kill(record.pid, 0);
194
+ } catch (error) {
195
+ return error.code === "EPERM";
196
+ }
197
+ const birth = processBirthSync(record.pid);
198
+ if (birth === null) return true;
199
+ if (record.birthAt != null) return Math.abs(birth - record.birthAt) <= BIRTH_TOLERANCE_MS;
200
+ return birth <= record.startedAt + BIRTH_TOLERANCE_MS;
201
+ }
202
+ function processBirthSync(pid) {
203
+ try {
204
+ const stat = fs.readFileSync(`/proc/${pid}/stat`, "utf8");
205
+ const fields = stat.slice(stat.lastIndexOf(")") + 2).split(" ");
206
+ const ticks = Number.parseFloat(fields[19] ?? "");
207
+ if (!Number.isFinite(ticks)) return null;
208
+ const boot = /^btime (\d+)$/m.exec(fs.readFileSync("/proc/stat", "utf8"))?.[1];
209
+ if (boot === void 0) return null;
210
+ return Number.parseInt(boot, 10) * 1e3 + ticks / 100 * 1e3;
211
+ } catch {
212
+ return null;
213
+ }
214
+ }
215
+ function restoreLockHolder(hhDir) {
216
+ const existing = readRecord(path.join(hhDir, "restore.lock"));
217
+ return existing !== null && isLiveHolder(existing) ? existing : null;
218
+ }
219
+ function isLiveHolder(record) {
220
+ return holderIsAlive(record) && Date.now() - record.startedAt <= STALE_AFTER_MS;
221
+ }
222
+ /** Take the restore lock, or `null` when somebody else holds it (the caller reports, never queues). */
223
+ function acquireRestoreLock(hhDir, action = "restore") {
224
+ const file = path.join(hhDir, "restore.lock");
225
+ ensureStateDir(hhDir);
226
+ const mine = {
227
+ pid: process.pid,
228
+ startedAt: Date.now(),
229
+ action,
230
+ birthAt: processBirthSync(process.pid)
231
+ };
232
+ const release = () => {
233
+ const current = readRecord(file);
234
+ if (current !== null && (current.pid !== mine.pid || current.startedAt !== mine.startedAt)) return;
235
+ fs.rmSync(file, { force: true });
236
+ };
237
+ const existing = readRecord(file);
238
+ if (existing !== null) {
239
+ if (isLiveHolder(existing)) return { heldBy: existing };
240
+ writeFileAtomic(file, `${JSON.stringify(mine)}\n`, { mode: 384 });
241
+ return {
242
+ release,
243
+ replaced: existing
244
+ };
245
+ }
246
+ try {
247
+ fs.writeFileSync(file, `${JSON.stringify(mine)}\n`, {
248
+ flag: "wx",
249
+ mode: 384
250
+ });
251
+ } catch (error) {
252
+ if (error.code === "EEXIST") {
253
+ const holder = readRecord(file);
254
+ return holder === null ? { heldBy: {
255
+ pid: 0,
256
+ startedAt: Date.now(),
257
+ action: "unreadable"
258
+ } } : { heldBy: holder };
259
+ }
260
+ throw error;
261
+ }
262
+ let released = false;
263
+ return { release: () => {
264
+ if (released) return;
265
+ released = true;
266
+ release();
267
+ } };
268
+ }
269
+ //#endregion
270
+ //#region src/providers/backup-hook.ts
271
+ var OUTPUT_TAIL_BYTES = 8192;
272
+ function tail(previous, chunk) {
273
+ const next = previous + chunk;
274
+ return next.length <= OUTPUT_TAIL_BYTES ? next : next.slice(next.length - OUTPUT_TAIL_BYTES);
275
+ }
276
+ /** Run a hook for one entry. `dumpDir` is passed in so `dump` and `load` get the same absolute path. */
277
+ async function runBackupHook(hook, server, dumpDir, options = {}) {
278
+ const vars = {
279
+ ...serverTemplateVars(server),
280
+ dumpDir
281
+ };
282
+ const cwd = resolveCwd(server.cwd);
283
+ const args = resolveTemplates(hook.args, vars);
284
+ if (options.requireDumpDir !== false) ensureStateDir(dumpDir);
285
+ let child;
286
+ try {
287
+ child = spawn(hook.command, args, {
288
+ cwd,
289
+ env: {
290
+ ...process.env,
291
+ ...resolveRecord(hook.env, vars)
292
+ },
293
+ stdio: [
294
+ "ignore",
295
+ "pipe",
296
+ "pipe"
297
+ ],
298
+ windowsHide: true
299
+ });
300
+ } catch (error) {
301
+ return {
302
+ ok: false,
303
+ code: null,
304
+ output: "",
305
+ error: `could not start: ${error.message}`
306
+ };
307
+ }
308
+ let output = "";
309
+ child.stdout?.on("data", (chunk) => {
310
+ output = tail(output, chunk.toString());
311
+ });
312
+ child.stderr?.on("data", (chunk) => {
313
+ output = tail(output, chunk.toString());
314
+ });
315
+ const outcome = await new Promise((resolve) => {
316
+ const timer = setTimeout(() => {
317
+ try {
318
+ child.kill("SIGKILL");
319
+ } catch {}
320
+ resolve({
321
+ code: null,
322
+ error: `timed out after ${hook.timeoutMs}ms`
323
+ });
324
+ }, hook.timeoutMs);
325
+ child.once("exit", (code) => {
326
+ clearTimeout(timer);
327
+ resolve({ code });
328
+ });
329
+ child.once("error", (error) => {
330
+ clearTimeout(timer);
331
+ resolve({
332
+ code: null,
333
+ error: `could not start: ${error.message}`
334
+ });
335
+ });
336
+ });
337
+ return {
338
+ ok: outcome.error === void 0 && outcome.code === 0,
339
+ code: outcome.code,
340
+ output,
341
+ ...outcome.error === void 0 ? {} : { error: outcome.error }
342
+ };
343
+ }
344
+ /** The line a person reads when a hook fails: the entry, the program and its last output. */
345
+ function hookFailure(action, server, result) {
346
+ const detail = result.error ?? (result.code === null ? "no exit code" : `exit ${result.code}`);
347
+ const said = result.output.trim().split("\n").filter((line) => line.trim().length > 0).slice(-3).join(" / ");
348
+ return `the ${action} hook for "${server.id}" failed (${detail})${said.length === 0 ? "" : `: ${said}`}`;
349
+ }
350
+ //#endregion
351
+ //#region src/services/backups/archive-safety.ts
352
+ /** What an archive may hold and where a restore may write: the path-safety gates of backup and restore. */
353
+ var MANIFEST = "manifest.json";
354
+ var ALLOWED_ROOTS = /* @__PURE__ */ new Set([
355
+ "global",
356
+ "workspaces",
357
+ "data",
358
+ "dumps"
359
+ ]);
360
+ /**
361
+ * Whether one archive path segment is a name a filesystem will accept as-is: no separator (`\` on
362
+ * Windows), no `:` (drive/stream), no control character.
363
+ */
364
+ function isPortableSegment(segment) {
365
+ for (const character of segment) {
366
+ const code = character.codePointAt(0) ?? 0;
367
+ if (character === "\\" || character === ":" || code < 32 || code === 127) return false;
368
+ }
369
+ return true;
370
+ }
371
+ /**
372
+ * Structural allowlist for archive entries. A regex alone is not enough: `..`
373
+ * is made of allowed characters, so segments are checked explicitly and any
374
+ * entry that could resolve outside the staging directory aborts the restore.
375
+ */
376
+ function isSafeArchiveEntry(entry) {
377
+ if (entry.startsWith("/") || entry.includes("\0")) return false;
378
+ const cleaned = entry.replace(/^\.\//, "").replace(/\/+$/, "");
379
+ if (cleaned.length === 0) return true;
380
+ if (cleaned === "manifest.json") return true;
381
+ const segments = cleaned.split("/");
382
+ if (segments.some((segment) => segment.length === 0 || segment === "." || segment === "..")) return false;
383
+ if (!ALLOWED_ROOTS.has(segments[0])) return false;
384
+ return segments.every(isPortableSegment);
385
+ }
386
+ async function admitArchive(archivePath) {
387
+ if (!isZipArchive(archivePath)) return {
388
+ ok: false,
389
+ error: "the archive is not a home-hosted backup (a zip file was expected)"
390
+ };
391
+ let entries;
392
+ try {
393
+ entries = await listZip(archivePath);
394
+ } catch (error) {
395
+ return {
396
+ ok: false,
397
+ error: `the archive could not be read: ${errorMessage(error)}`
398
+ };
399
+ }
400
+ if (entries.length === 0) return {
401
+ ok: false,
402
+ error: "the archive is empty"
403
+ };
404
+ if (entries.length > 1e5) return {
405
+ ok: false,
406
+ error: "the archive has too many entries"
407
+ };
408
+ const invalid = entries.filter((entry) => !isSafeArchiveEntry(entry.name));
409
+ if (invalid.length > 0) return {
410
+ ok: false,
411
+ error: `the archive contains unexpected entries (e.g. ${invalid.slice(0, 3).map((entry) => entry.name).join(", ")})`
412
+ };
413
+ return {
414
+ ok: true,
415
+ entries
416
+ };
417
+ }
418
+ /** True when `child` is `parent` itself or lives underneath it. */
419
+ function isInside(parent, child) {
420
+ if (parent === child) return true;
421
+ const relative = path.relative(parent, child);
422
+ return !path.isAbsolute(relative) && (relative.length === 0 || !relative.startsWith(".."));
423
+ }
424
+ /** Resolves symlinks on the deepest existing ancestor, keeping the rest verbatim. */
425
+ function resolveExisting(target) {
426
+ let prefix = target;
427
+ const rest = [];
428
+ for (;;) try {
429
+ return path.join(fs.realpathSync(prefix), ...rest);
430
+ } catch {
431
+ const parent = path.dirname(prefix);
432
+ if (parent === prefix) return target;
433
+ rest.unshift(path.basename(prefix));
434
+ prefix = parent;
435
+ }
436
+ }
437
+ /**
438
+ * `isInside` after resolving symlinks, so a link inside a declared path cannot stand for somewhere
439
+ * else on either capture or restore.
440
+ */
441
+ function isInsideResolved(parent, child) {
442
+ return isInside(resolveExisting(path.resolve(parent)), resolveExisting(path.resolve(child)));
443
+ }
444
+ //#endregion
445
+ //#region src/services/backups/paths.ts
446
+ /**
447
+ * Every path a backup should capture: the global list, then each server's `backupPaths` and
448
+ * `dataEnvs` values. A path covered by a declared parent is reported but not captured.
449
+ * `vars` only feeds the global list.
450
+ */
451
+ function resolveBackupPaths(servers, includePaths = [], vars) {
452
+ const declared = [];
453
+ const globalVars = {
454
+ projectDir: vars?.projectDir ?? projectDir,
455
+ dataRoot: vars?.dataRoot ?? (servers[0] === void 0 ? projectDir : String(serverTemplateVars(servers[0]).dataRoot ?? projectDir)),
456
+ home: vars?.home ?? os.homedir()
457
+ };
458
+ const add = (value, origin, templateVars, ignoreGenerated) => {
459
+ if (value.trim().length === 0) return;
460
+ const resolved = path.normalize(resolveUserPath(expandEnv(resolveTemplate(value, templateVars), process.env)));
461
+ declared.push({
462
+ path: resolved,
463
+ origin,
464
+ depth: path.normalize(resolved).split(path.sep).filter(Boolean).length,
465
+ order: declared.length,
466
+ ignoreGenerated
467
+ });
468
+ };
469
+ for (const value of includePaths) add(value, "global", globalVars, false);
470
+ for (const config of servers) {
471
+ const templateVars = serverTemplateVars(config);
472
+ const ignoreGenerated = config.backupIgnoreGenerated !== false;
473
+ for (const [name, value] of Object.entries(config.dataEnvs)) add(value, `${config.id}:${name}`, templateVars, ignoreGenerated);
474
+ for (const value of config.backupPaths) add(value, `${config.id}:backupPaths`, templateVars, ignoreGenerated);
475
+ }
476
+ const sorted = [...declared].sort((a, b) => a.depth - b.depth || a.order - b.order);
477
+ return sorted.map((entry, index) => {
478
+ const parent = sorted.slice(0, index).find((candidate) => isInside(candidate.path, entry.path));
479
+ if (parent === void 0) return {
480
+ path: entry.path,
481
+ origin: entry.origin,
482
+ included: true,
483
+ note: null,
484
+ ignoreGenerated: entry.ignoreGenerated
485
+ };
486
+ const note = parent.path === entry.path ? `already declared by ${parent.origin}` : `covered by ${parent.path}`;
487
+ const noteKey = parent.path === entry.path ? "settings.backup.noteAlreadyDeclared" : "settings.backup.noteCovered";
488
+ const noteParams = parent.path === entry.path ? { origin: parent.origin } : { path: parent.path };
489
+ return {
490
+ path: entry.path,
491
+ origin: entry.origin,
492
+ included: false,
493
+ note,
494
+ noteKey,
495
+ noteParams,
496
+ ignoreGenerated: entry.ignoreGenerated
497
+ };
498
+ });
499
+ }
500
+ /**
501
+ * Stable, filesystem-safe name for a data path inside the archive. The hash keeps paths whose
502
+ * readable parts collide apart; a restore reads the slug from the manifest.
503
+ */
504
+ function slugifyPath(target) {
505
+ const hash = createHash("sha256").update(path.resolve(target)).digest("hex").slice(0, 8);
506
+ return `${legacySlug(target).slice(-71)}-${hash}`;
507
+ }
508
+ /** The hashless slug archives were written with before; only a manifest without a slug falls back to it. */
509
+ function legacySlug(target) {
510
+ const cleaned = target.replace(/[^A-Z0-9]+/gi, "-").replace(/^-+|-+$/g, "");
511
+ return cleaned.length > 0 ? cleaned.slice(-80) : "path";
512
+ }
513
+ //#endregion
514
+ //#region src/shared/backup-scope.ts
515
+ /** `only` is `--include` and `except` is `--all --exclude`; an absent scope is the full default. */
516
+ function scopeSelection(scope) {
517
+ if (scope === void 0) return {};
518
+ return scope.mode === "only" ? { include: [...scope.ids] } : { exclude: [...scope.ids] };
519
+ }
520
+ /**
521
+ * The one "is this id selected" rule for create, restore, the control plan and both UIs. `include`
522
+ * omitted means everything; `exclude` applies after it, and covers every id beneath an excluded one.
523
+ */
524
+ function selectionOf(options) {
525
+ const wanted = options.include === void 0 ? null : new Set(options.include);
526
+ const unwanted = new Set(options.exclude ?? []);
527
+ const isExcluded = (id) => unwanted.has(id) || [...unwanted].some((entry) => id.startsWith(`${entry}:`));
528
+ const selects = ((id) => {
529
+ if (isExcluded(id)) return false;
530
+ return wanted === null || wanted.has(id) || [...wanted].some((entry) => id.startsWith(`${entry}:`));
531
+ });
532
+ selects.isExcluded = isExcluded;
533
+ return selects;
534
+ }
535
+ /** The panel-wide entries, declared once so the credential guard and the restore agree on aliases. */
536
+ var GLOBAL_RESTORE_ITEMS = {
537
+ settings: {
538
+ id: "global:settings",
539
+ aliases: ["config"]
540
+ },
541
+ credentials: {
542
+ id: "global:secrets",
543
+ aliases: ["secrets"]
544
+ },
545
+ tls: {
546
+ id: "global:tls",
547
+ aliases: ["tls"]
548
+ }
549
+ };
550
+ /** Whether a selection chooses this item: an exclusion beats an alias, then any of its ids selects it. */
551
+ function selectedBy(selects, item) {
552
+ const aliases = item.aliases ?? [];
553
+ return !(selects.isExcluded(item.id) || aliases.some((alias) => selects.isExcluded(alias))) && (selects(item.id) || aliases.some((alias) => selects(alias)));
554
+ }
555
+ /** Whether a selection reaches anything inside one item: the item, an alias, or a leaf of it. */
556
+ function selectionTouches(options, item) {
557
+ const selects = selectionOf(options);
558
+ const prefixes = [item.id, ...item.aliases ?? []];
559
+ if ((options.include ?? []).some((id) => prefixes.some((prefix) => id.startsWith(`${prefix}:`)) && selects(id))) return true;
560
+ return selectedBy(selects, item);
561
+ }
562
+ /**
563
+ * Whether a restore would write the credential store (password and token hashes). Who may do that is
564
+ * the route's decision.
565
+ */
566
+ function selectionWritesCredentials(options) {
567
+ return selectionTouches(options, GLOBAL_RESTORE_ITEMS.credentials);
568
+ }
569
+ /**
570
+ * Which of `ids` name nothing capturable (an id may be a prefix of one). On a schedule a typo silently
571
+ * narrows (`only`) or widens (`except`) the archive.
572
+ */
573
+ function unknownBackupIds(ids, entries) {
574
+ const available = entries.flatMap((entry) => [entry.id, ...(entry.items ?? []).map((item) => item.id)]);
575
+ const known = (id) => available.some((candidate) => candidate === id || candidate.startsWith(`${id}:`));
576
+ return ids.filter((id) => !known(id));
577
+ }
578
+ //#endregion
579
+ //#region src/shared/generated.ts
580
+ /**
581
+ * Names that only hold build output or installed dependencies, skipped by `backupIgnoreGenerated`.
582
+ * Matched by exact name on any segment. `.git` is deliberately absent: an unpushed commit is not regenerable.
583
+ */
584
+ /** Whole directories that are regenerated, never authored. */
585
+ var GENERATED_DIRS = [
586
+ "node_modules",
587
+ "bower_components",
588
+ "jspm_packages",
589
+ ".yarn",
590
+ ".pnpm",
591
+ ".pnpm-store",
592
+ ".npm",
593
+ ".next",
594
+ ".nuxt",
595
+ ".svelte-kit",
596
+ ".astro",
597
+ ".output",
598
+ ".vercel",
599
+ ".netlify",
600
+ ".angular",
601
+ "dist",
602
+ "build",
603
+ "out",
604
+ ".cache",
605
+ ".parcel-cache",
606
+ ".turbo",
607
+ ".vite",
608
+ ".rollup.cache",
609
+ ".swc",
610
+ "coverage",
611
+ ".nyc_output",
612
+ "__pycache__",
613
+ ".pytest_cache",
614
+ ".mypy_cache",
615
+ ".ruff_cache",
616
+ ".tox",
617
+ "target",
618
+ ".gradle",
619
+ ".dart_tool"
620
+ ];
621
+ /** One-off files worth skipping, by exact name. */
622
+ var GENERATED_FILES = [
623
+ ".DS_Store",
624
+ "Thumbs.db",
625
+ "desktop.ini",
626
+ ".eslintcache",
627
+ ".stylelintcache",
628
+ "npm-debug.log",
629
+ "yarn-error.log",
630
+ "pnpm-debug.log"
631
+ ];
632
+ var DIR_NAME_SET = new Set(GENERATED_DIRS);
633
+ var FILE_NAME_SET = new Set(GENERATED_FILES);
634
+ /** `relative` is to the declared root; either separator. */
635
+ function isGeneratedPath(relative) {
636
+ const segments = relative.split(/[\\/]+/).filter((segment) => segment.length > 0 && segment !== ".");
637
+ if (segments.length === 0) return false;
638
+ if (FILE_NAME_SET.has(segments[segments.length - 1])) return true;
639
+ return segments.some((segment) => DIR_NAME_SET.has(segment));
640
+ }
641
+ //#endregion
642
+ //#region src/services/backups.ts
643
+ var serverIdSchema = serverSchema.get("id");
644
+ /** The workspace registry inside an archive, under `global/`. */
645
+ var REGISTRY = "workspaces.json";
646
+ /** The live name, or the temp name `writeFileAtomic` leaves behind if it crashed before the rename. */
647
+ var SECRET_DOCUMENT_NAMES = new RegExp(`^(?:${[".control-secrets.json", ".secrets.json"].map((name) => name.replaceAll(".", "\\.")).join("|")})(?:\\.\\d+\\.[0-9a-f]{8}\\.tmp)?$`, "i");
648
+ function isSecretDocument(name) {
649
+ return SECRET_DOCUMENT_NAMES.test(name);
650
+ }
651
+ /** Every archive this service writes is a zip, encrypted or not. */
652
+ var SUFFIX = ".zip";
653
+ /** Where a restore parks a dump until the entry's next start can load it. */
654
+ var PENDING_LOAD = "pending-load";
655
+ /**
656
+ * An archive the schedule wrote. The prefix is the only durable marker: a filename is the one
657
+ * thing that survives a restart, and it is what lets the two retention counts stay independent.
658
+ */
659
+ var AUTO_PREFIX = "auto";
660
+ var MANUAL_PREFIX = "backup";
661
+ /** The names `create()` writes; retention counts and prunes only these, never a zip someone else put here. */
662
+ var ARCHIVE_NAME = new RegExp(`^(${AUTO_PREFIX}|${MANUAL_PREFIX})-\\d{4}(?:-\\d{2}){5}-\\d{1,3}\\.zip$`);
663
+ var ARCHIVE_STAMP = /-(\d{4})-(\d{2})-(\d{2})-(\d{2})-(\d{2})-(\d{2})-(\d{1,3})\.zip$/;
664
+ /**
665
+ * When `create()` wrote an archive, read from its name (UTC, to the millisecond), or null for a name
666
+ * it did not write. The name survives a copy; the mtime does not.
667
+ */
668
+ function archiveStamp(name) {
669
+ if (!ARCHIVE_NAME.test(name)) return null;
670
+ const parts = ARCHIVE_STAMP.exec(name)?.slice(1).map(Number);
671
+ if (parts === void 0 || parts.length !== 7) return null;
672
+ const [year, month, day, hour, minute, second, ms] = parts;
673
+ const at = Date.UTC(year, month - 1, day, hour, minute, second, ms);
674
+ return Number.isFinite(at) ? at : null;
675
+ }
676
+ /** A workspace leaf that carries state the panel re-reads after a restore. */
677
+ var RELOADABLE = /^global:settings$|^workspace:[^:]+:(?:settings|servers)$/;
678
+ /** A staging tree's name, carrying the owning pid so a later run can tell dead debris from a live capture. */
679
+ function stagingDirName(kind) {
680
+ return `.${kind}-${process.pid}-${Date.now()}`;
681
+ }
682
+ /** The pid a staging directory belongs to, or null — a name with no pid is never guessed at. */
683
+ function stagingOwner(name) {
684
+ const match = /^\.[a-z]+-(\d+)-\d+$/.exec(name);
685
+ if (match === null) return null;
686
+ const pid = Number.parseInt(match[1], 10);
687
+ return Number.isInteger(pid) && pid > 0 ? pid : null;
688
+ }
689
+ /** Wording and catalog key of each known secret; an unlisted key reads as its own name. */
690
+ var SECRET_LABELS = {
691
+ password: {
692
+ en: "Password (before 0.14)",
693
+ key: "settings.backup.secretPassword"
694
+ },
695
+ apiToken: {
696
+ en: "API token (before 0.14)",
697
+ key: "settings.backup.secretApiToken"
698
+ },
699
+ telegram: {
700
+ en: "Telegram bot token",
701
+ key: "settings.backup.secretTelegram"
702
+ },
703
+ ddns: {
704
+ en: "DDNS credentials",
705
+ key: "settings.backup.secretDdns"
706
+ },
707
+ accounts: {
708
+ en: "Accounts",
709
+ key: "settings.backup.secretAccounts"
710
+ },
711
+ apiTokens: {
712
+ en: "API tokens",
713
+ key: "settings.backup.secretApiTokens"
714
+ },
715
+ serverEnv: {
716
+ en: "Server secret environment",
717
+ key: "settings.backup.secretServerEnv"
718
+ },
719
+ jobEnv: {
720
+ en: "Job secret environment",
721
+ key: "settings.backup.secretJobEnv"
722
+ }
723
+ };
724
+ /** Pre-accounts slots: an upgraded file no longer has them, so an absent one is not worth a row. */
725
+ var LEGACY_SECRET_SLOTS = /* @__PURE__ */ new Set(["password", "apiToken"]);
726
+ /**
727
+ * The servers an archive carries for one workspace, from its staged config — the live config is
728
+ * the old one at this point. An unparseable config yields no servers.
729
+ */
730
+ function readArchivedServers(staging, workspaceId, defaults = {}) {
731
+ const text = readText(path.join(staging, "workspaces", workspaceId, "servers.config.json"));
732
+ if (text === null) return [];
733
+ try {
734
+ return parseServersFile(JSON.parse(text), defaults).servers;
735
+ } catch {
736
+ return [];
737
+ }
738
+ }
739
+ /**
740
+ * What a backup captures. The one implementation, shared by the panel and the offline CLI so both
741
+ * capture the same thing.
742
+ */
743
+ function buildBackupSources(input) {
744
+ return {
745
+ globalSettingsPath: input.globalSettingsPath,
746
+ globalSecretsPath: input.globalSecretsPath,
747
+ tlsDir: input.tlsDir,
748
+ registryPath: input.registryPath,
749
+ includePaths: [...input.includePaths],
750
+ ...input.runningServers === void 0 ? {} : { runningServers: input.runningServers },
751
+ workspaces: input.workspaces.map((workspace) => ({
752
+ id: workspace.id,
753
+ label: workspace.label,
754
+ settingsPath: workspace.settingsPath,
755
+ serversPath: workspace.serversPath,
756
+ jobsPath: workspace.jobsPath,
757
+ secretsPath: workspace.secretsPath,
758
+ servers: workspace.servers
759
+ }))
760
+ };
761
+ }
762
+ /**
763
+ * Pairs each archived data path with the declaration that will receive it. Stateful: one target is
764
+ * claimed by one entry, so same-origin declarations pair in resolve order. Never crosses a
765
+ * workspace boundary.
766
+ */
767
+ function dataTargetMatcher(archiveTargets, instanceTargets) {
768
+ const usedArchive = /* @__PURE__ */ new Set();
769
+ const usedInstance = /* @__PURE__ */ new Set();
770
+ const take = (list, used, test) => {
771
+ const found = list.find((target) => !used.has(target) && test(target));
772
+ if (found === void 0) return void 0;
773
+ used.add(found);
774
+ return found;
775
+ };
776
+ return (origin, workspace, archivedPath) => {
777
+ const inScope = (target) => workspace === void 0 || target.workspace === workspace;
778
+ const archive = archiveTargets.filter(inScope);
779
+ const instance = instanceTargets.filter(inScope);
780
+ 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);
781
+ return take(archive, usedArchive, (target) => target.path === archivedPath) ?? take(instance, usedInstance, (target) => target.path === archivedPath);
782
+ };
783
+ }
784
+ /**
785
+ * An archived config, lifted to the schema this release reads (an archive is often older than the
786
+ * release restoring it). Lifting needs an explicit numeric `meta.schema`: an unstamped file is a seed
787
+ * or damage, not an older release. `null` means this release cannot read it.
788
+ */
789
+ function liftArchived(raw) {
790
+ if (!isRecord(raw)) return null;
791
+ const meta = isRecord(raw.meta) ? raw.meta : {};
792
+ if (typeof meta.schema !== "number") return null;
793
+ const plan = planConfigMigrations(meta.schema);
794
+ if (plan.tooNew || plan.reached !== plan.to) return null;
795
+ if (plan.steps.length === 0) return raw;
796
+ const lifted = applyConfigMigrations(raw, meta.schema).config;
797
+ return isRecord(lifted) ? stampConfig(lifted) : null;
798
+ }
799
+ /**
800
+ * A restored settings file is accepted when this release can read it through the stores' tolerant
801
+ * parser. The lifted value is returned, so the caller writes a config this release can load.
802
+ */
803
+ function readableGlobalSettings(text) {
804
+ if (text === null) return null;
805
+ try {
806
+ const lifted = liftArchived(JSON.parse(text));
807
+ return lifted !== null && parseGlobalSettings(lifted).config !== null ? lifted : null;
808
+ } catch {
809
+ return null;
810
+ }
811
+ }
812
+ /** The workspaces an archive's registry names. Tolerant: the registry only contributes labels. */
813
+ function readArchivedRegistry(file) {
814
+ const text = readText(file);
815
+ if (text === null) return [];
816
+ try {
817
+ return parseWorkspacesFile(JSON.parse(text)).workspaces ?? [];
818
+ } catch {
819
+ return [];
820
+ }
821
+ }
822
+ /**
823
+ * Where a workspace created by a restore keeps its leaves, under the service's own `dataRoot` rather
824
+ * than the import-time path helpers.
825
+ */
826
+ function workspacePathsFor(dataRoot, id) {
827
+ const dir = path.join(dataRoot, id);
828
+ return {
829
+ settingsPath: path.join(dir, "settings.json"),
830
+ serversPath: path.join(dir, "servers.config.json"),
831
+ jobsPath: path.join(dir, "jobs.config.json"),
832
+ secretsPath: path.join(dir, ".secrets.json")
833
+ };
834
+ }
835
+ /**
836
+ * The manifest is written by us, but an uploaded archive's copy is attacker
837
+ * controlled: never join an unvalidated slug into a path.
838
+ */
839
+ function safeSlug(slug) {
840
+ if (typeof slug !== "string" || slug.length === 0 || slug.length > 80) return null;
841
+ if (!/^[\w.-]+$/.test(slug) || slug === "." || slug === "..") return null;
842
+ return slug;
843
+ }
844
+ /** A flag is valid for one exact file revision, not for the name alone. */
845
+ function cacheKey(file) {
846
+ return `${file.sizeBytes}:${file.createdAt}`;
847
+ }
848
+ /** True when the tree at `root` contains at least one file (stops at the first). */
849
+ function holdsAnyFile(root) {
850
+ let stats;
851
+ try {
852
+ stats = fs.lstatSync(root);
853
+ } catch {
854
+ return false;
855
+ }
856
+ if (!stats.isDirectory()) return stats.isFile();
857
+ let names;
858
+ try {
859
+ names = fs.readdirSync(root);
860
+ } catch {
861
+ return false;
862
+ }
863
+ return names.some((name) => holdsAnyFile(path.join(root, name)));
864
+ }
865
+ /**
866
+ * A state file's text, decoded by `readStateFile`: a BOM must not make a secrets file unparseable,
867
+ * because that is what would let it fall through to a raw copy.
868
+ */
869
+ function readText(file) {
870
+ try {
871
+ return readStateFile(file);
872
+ } catch {
873
+ return null;
874
+ }
875
+ }
876
+ /** The plan a restore starts from: every field filled, so a refusal is a plan and not a throw. */
877
+ function newRestorePlan(options) {
878
+ return {
879
+ dryRun: !options.confirm,
880
+ encrypted: false,
881
+ needsPassword: false,
882
+ items: [],
883
+ applied: [],
884
+ appliedIds: [],
885
+ skipped: [],
886
+ skippedItems: [],
887
+ restartRequired: false,
888
+ reloaded: false,
889
+ createdWorkspaces: [],
890
+ replacedUnderRunning: []
891
+ };
892
+ }
893
+ /**
894
+ * Archives of the control plane's own state plus whatever paths the configs declare. Restore stays
895
+ * safe by two rules: the archive layout is an allowlist, and a data path is written back only when a
896
+ * config (current, or one the same restore applies) declares it. A password makes the zip WinZip-AES.
897
+ */
898
+ var BackupService = class {
899
+ options;
900
+ /** Encrypted flags, cached because reading a central directory is async; refreshed in the background. */
901
+ flags = /* @__PURE__ */ new Map();
902
+ refreshing = null;
903
+ /** One scheduled pass at a time: a slow archive must not stack up behind itself. */
904
+ running = false;
905
+ disposed = false;
906
+ /** When this instance last attempted an automatic pass; bounds retries of a pass that wrote nothing. */
907
+ lastAttemptAt = null;
908
+ /** The newest automatic archive, cached so the per-second `tick()`/`view()` do not rescan the directory. */
909
+ lastAutomaticSeen = null;
910
+ /** Logs a pass deferred by a running restore once, not on every tick. */
911
+ deferredForRestore = false;
912
+ /** Why the most recent scheduled pass failed, cleared by the next that works. */
913
+ scheduleError = null;
914
+ constructor(options) {
915
+ this.options = options;
916
+ }
917
+ /** Reads every archive once, so the first `list()` is already accurate. */
918
+ async warm() {
919
+ await this.refresh();
920
+ }
921
+ dispose() {
922
+ this.disposed = true;
923
+ }
924
+ get directory() {
925
+ return this.resolveDir();
926
+ }
927
+ /**
928
+ * The policy and the status, carried in the state frame. Not the selection model: that reads every
929
+ * secrets file and stats every archive, which is too costly per frame.
930
+ */
931
+ view() {
932
+ const config = this.options.getConfig();
933
+ const sources = this.options.getSources();
934
+ return {
935
+ enabled: config.enabled,
936
+ dir: this.directory,
937
+ keep: config.keep,
938
+ schedule: { ...config.schedule },
939
+ lastAutomaticAt: this.lastAutomatic(),
940
+ ...this.scheduleError === null ? {} : { scheduleError: { ...this.scheduleError } },
941
+ includePaths: [...sources.includePaths]
942
+ };
943
+ }
944
+ /** The selection model: every capturable entry and every archive on disk. Never on a per-frame path. */
945
+ selection() {
946
+ return {
947
+ dir: this.directory,
948
+ entries: this.entries(this.options.getSources()),
949
+ files: this.list()
950
+ };
951
+ }
952
+ list() {
953
+ const files = this.scan();
954
+ for (const file of files) {
955
+ const cached = this.flags.get(file.name);
956
+ if (cached === void 0 || cached.key !== cacheKey(file)) this.scheduleRefresh();
957
+ }
958
+ return files.map((file) => {
959
+ const cached = this.flags.get(file.name);
960
+ return {
961
+ ...file,
962
+ encrypted: cached !== void 0 && cached.key === cacheKey(file) ? cached.encrypted : false
963
+ };
964
+ });
965
+ }
966
+ /** Validated absolute path for a download, or null when the name is not a backup. */
967
+ resolve(name) {
968
+ if (!/^[A-Z0-9][\w.-]*$/i.test(name) || name.includes("..")) return null;
969
+ const file = path.join(this.resolveDir(), name);
970
+ return fs.existsSync(file) ? file : null;
971
+ }
972
+ /**
973
+ * `password` encrypts the archive; it is never stored. `automatic` keeps the two retention counts
974
+ * apart, so a scheduled pass never prunes a manual backup.
975
+ */
976
+ async create(options = {}) {
977
+ if (!this.options.getConfig().enabled) return {
978
+ ok: false,
979
+ error: "backups are disabled"
980
+ };
981
+ const password = options.password !== void 0 && options.password.length > 0 ? options.password : null;
982
+ const selects = selectionOf(options);
983
+ const wanted = options.include === void 0 ? null : new Set(options.include);
984
+ const capturesGlobal = (id) => selects(id);
985
+ const capturesWorkspace = (id, suffix) => selects(`workspace:${id}:${suffix}`);
986
+ /** The secrets of one scope the request asked for; `null` means every one of them. */
987
+ const selectedSecretFields = (entryId, path, scope, workspaceId) => {
988
+ const parts = secretParts(scope, presentSecretKeys(parseSecrets(readText(path) ?? "")));
989
+ const picked = parts.filter((part) => {
990
+ if (selects.isExcluded(entryId) || selects.isExcluded(`${entryId}:${part.key}`)) return false;
991
+ 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}`));
992
+ });
993
+ return picked.length === parts.length ? null : picked.flatMap((part) => part.fields);
994
+ };
995
+ const dir = this.resolveDir();
996
+ const sources = this.options.getSources();
997
+ const staging = path.join(dir, stagingDirName("staging"));
998
+ const createdAt = Date.now();
999
+ const name = `${options.automatic === true ? AUTO_PREFIX : MANUAL_PREFIX}-${new Date(createdAt).toISOString().replace(/[:T]/g, "-").replace(/\.\d+Z$/, "")}-${createdAt % 1e3}${SUFFIX}`;
1000
+ const destination = path.join(dir, name);
1001
+ try {
1002
+ ensureStateDir(staging);
1003
+ let captured = 0;
1004
+ const copy = async (relative, source, ignoreGenerated = false) => {
1005
+ if (await this.copyInto(staging, relative, source, ignoreGenerated)) captured++;
1006
+ };
1007
+ /**
1008
+ * Captures one secrets file, narrowed to the picked secrets; the restore side merges by field.
1009
+ */
1010
+ const copySecrets = async (relative, source, entryId, scope, workspaceId) => {
1011
+ const text = readText(source);
1012
+ if (text === null) return;
1013
+ const fields = selectedSecretFields(entryId, source, scope, workspaceId);
1014
+ const chosen = fields === null ? withoutInitialPassword(text) : pickSecrets(parseSecrets(text), fields);
1015
+ if (chosen === null) return;
1016
+ const target = path.join(staging, relative);
1017
+ ensureStateDir(path.dirname(target));
1018
+ fs.writeFileSync(target, chosen.endsWith("\n") ? chosen : `${chosen}\n`, { mode: 384 });
1019
+ captured++;
1020
+ };
1021
+ const touchesSecrets = (entryId, workspaceId) => selects(entryId) || wanted !== null && [...wanted].some((id) => id.startsWith(`${entryId}:`)) || workspaceId !== void 0 && selects(`workspace:${workspaceId}:secrets`);
1022
+ if (capturesGlobal("global:settings")) await copy("global/settings.json", sources.globalSettingsPath);
1023
+ if (touchesSecrets("global:secrets")) await copySecrets("global/secrets.json", sources.globalSecretsPath, "global:secrets", "global");
1024
+ if (capturesGlobal("global:tls")) await copy("global/tls", sources.tlsDir);
1025
+ await this.copyInto(staging, `global/${REGISTRY}`, sources.registryPath);
1026
+ /**
1027
+ * The dump phase, before anything is copied: the dump is the authoritative artifact, and a failed
1028
+ * one must not leave an archive that looks complete. Output lands in `dumps/<workspace>/<server>/`.
1029
+ */
1030
+ const dumped = [];
1031
+ for (const workspace of sources.workspaces) for (const server of workspace.servers) {
1032
+ const hook = server.dump;
1033
+ if (hook === void 0 || hook === null) continue;
1034
+ if (!selects(`workspace:${workspace.id}:dump:${server.id}`)) continue;
1035
+ const relative = path.join("dumps", workspace.id, server.id);
1036
+ const result = await runBackupHook(hook, server, path.join(staging, relative));
1037
+ if (!result.ok) {
1038
+ await fs.promises.rm(staging, {
1039
+ recursive: true,
1040
+ force: true
1041
+ });
1042
+ return {
1043
+ ok: false,
1044
+ error: hookFailure("dump", server, result)
1045
+ };
1046
+ }
1047
+ dumped.push({
1048
+ workspaceId: workspace.id,
1049
+ serverId: server.id
1050
+ });
1051
+ }
1052
+ const data = [];
1053
+ const warnings = [];
1054
+ for (const workspace of sources.workspaces) {
1055
+ const root = `workspaces/${workspace.id}`;
1056
+ if (capturesWorkspace(workspace.id, "settings")) await copy(`${root}/settings.json`, workspace.settingsPath);
1057
+ if (capturesWorkspace(workspace.id, "servers")) await copy(`${root}/servers.config.json`, workspace.serversPath);
1058
+ if (capturesWorkspace(workspace.id, "jobs")) await copy(`${root}/jobs.config.json`, workspace.jobsPath);
1059
+ if (touchesSecrets(`workspace:${workspace.id}:secrets`, workspace.id)) await copySecrets(`${root}/secrets.json`, workspace.secretsPath, `workspace:${workspace.id}:secrets`, "workspace", workspace.id);
1060
+ for (const declared of this.declaredData(workspace.servers, sources.includePaths)) {
1061
+ if (!declared.included) continue;
1062
+ if (!capturesWorkspace(workspace.id, `data:${declared.path}`)) continue;
1063
+ if (!fs.existsSync(declared.path)) continue;
1064
+ const resolved = path.resolve(declared.path);
1065
+ if (data.some((entry) => path.resolve(entry.path) === resolved)) continue;
1066
+ const slug = slugifyPath(declared.path);
1067
+ if (!await this.copyInto(staging, path.join("data", slug), declared.path, declared.ignoreGenerated)) continue;
1068
+ captured++;
1069
+ data.push({
1070
+ slug,
1071
+ path: declared.path,
1072
+ origin: declared.origin,
1073
+ workspace: workspace.id
1074
+ });
1075
+ if (!holdsAnyFile(path.join(staging, "data", slug))) warnings.push(`"${declared.path}" was captured but holds no files`);
1076
+ }
1077
+ }
1078
+ if ((wanted !== null || (options.exclude?.length ?? 0) > 0) && captured === 0) {
1079
+ await fs.promises.rm(staging, {
1080
+ recursive: true,
1081
+ force: true
1082
+ });
1083
+ return {
1084
+ ok: false,
1085
+ error: "nothing was selected to back up"
1086
+ };
1087
+ }
1088
+ const manifest = {
1089
+ version: 1,
1090
+ createdAt,
1091
+ hostname: os.hostname(),
1092
+ writtenBy: appVersion(),
1093
+ schema: 2,
1094
+ data,
1095
+ ...dumped.length === 0 ? {} : { dumps: dumped }
1096
+ };
1097
+ fs.writeFileSync(path.join(staging, MANIFEST), `${JSON.stringify(manifest, null, 2)}\n`);
1098
+ await createZip(staging, destination, password === null ? {} : { password });
1099
+ await fs.promises.rm(staging, {
1100
+ recursive: true,
1101
+ force: true
1102
+ });
1103
+ this.prune();
1104
+ this.sweepStaging();
1105
+ const stats = fs.statSync(destination);
1106
+ this.flags.set(name, {
1107
+ key: cacheKey({
1108
+ sizeBytes: stats.size,
1109
+ createdAt
1110
+ }),
1111
+ encrypted: password !== null
1112
+ });
1113
+ if (options.automatic === true && this.lastAutomaticSeen !== null && this.lastAutomaticSeen.dir === dir) this.lastAutomaticSeen = {
1114
+ dir,
1115
+ at: Math.max(this.lastAutomaticSeen.at ?? 0, createdAt)
1116
+ };
1117
+ return {
1118
+ ok: true,
1119
+ file: {
1120
+ name,
1121
+ sizeBytes: stats.size,
1122
+ createdAt,
1123
+ encrypted: password !== null
1124
+ },
1125
+ ...warnings.length === 0 ? {} : { warnings }
1126
+ };
1127
+ } catch (error) {
1128
+ await fs.promises.rm(staging, {
1129
+ recursive: true,
1130
+ force: true
1131
+ }).catch(() => {});
1132
+ await fs.promises.rm(destination, { force: true }).catch(() => {});
1133
+ return {
1134
+ ok: false,
1135
+ error: errorMessage(error)
1136
+ };
1137
+ }
1138
+ }
1139
+ remove(name) {
1140
+ const file = this.resolve(name);
1141
+ if (file === null) return false;
1142
+ fs.rmSync(file, { force: true });
1143
+ this.flags.delete(name);
1144
+ if (isAutomatic({ name })) this.lastAutomaticSeen = null;
1145
+ return true;
1146
+ }
1147
+ /**
1148
+ * Validates an archive, then (when `confirm`) applies the selected items. Data paths come from the
1149
+ * current sources or a servers file the same restore applies — never from the manifest alone.
1150
+ */
1151
+ async restore(archivePath, options) {
1152
+ const lock = options.confirm ? acquireRestoreLock(this.options.dataRoot) : null;
1153
+ 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`, {
1154
+ statusCode: 409,
1155
+ code: "RESTORE_IN_PROGRESS"
1156
+ });
1157
+ try {
1158
+ return await this.applyRestore(archivePath, options);
1159
+ } finally {
1160
+ if (lock !== null && !("heldBy" in lock)) lock.release();
1161
+ }
1162
+ }
1163
+ async applyRestore(archivePath, options) {
1164
+ const password = options.password !== void 0 && options.password.length > 0 ? options.password : null;
1165
+ const plan = newRestorePlan(options);
1166
+ const admitted = await admitArchive(archivePath);
1167
+ if (!admitted.ok) return {
1168
+ ...plan,
1169
+ error: admitted.error
1170
+ };
1171
+ const staging = path.join(this.resolveDir(), stagingDirName("restore"));
1172
+ try {
1173
+ const opened = await this.openArchive(plan, admitted.entries, archivePath, staging, password);
1174
+ if (!("ok" in opened)) return opened;
1175
+ const ctx = this.restoreContext(plan, options, opened.manifest, staging);
1176
+ const global = this.planGlobalItems(ctx);
1177
+ this.planWorkspaceItems(ctx);
1178
+ this.planDataItems(ctx, global);
1179
+ this.noteRestartRequired(ctx, global);
1180
+ if (!options.confirm) {
1181
+ plan.applied = [...ctx.actions.keys()].map((id) => labelOf(plan, id));
1182
+ plan.appliedIds = [...ctx.actions.keys()];
1183
+ return plan;
1184
+ }
1185
+ const failure = await this.runApply(ctx);
1186
+ this.registerCreatedWorkspaces(ctx);
1187
+ if (failure !== null) {
1188
+ this.reloadRestored(plan);
1189
+ throw failure;
1190
+ }
1191
+ await this.stagePendingLoads(ctx);
1192
+ this.reloadRestored(plan);
1193
+ return plan;
1194
+ } catch (error) {
1195
+ if (isInvalidPassword(error)) return {
1196
+ ...plan,
1197
+ encrypted: true,
1198
+ needsPassword: true,
1199
+ error: "the password is wrong"
1200
+ };
1201
+ const done = plan.applied.length > 0 ? ` — already applied: ${plan.applied.join(", ")}` : "";
1202
+ return {
1203
+ ...plan,
1204
+ error: `${errorMessage(error)}${done}`
1205
+ };
1206
+ } finally {
1207
+ fs.rmSync(staging, {
1208
+ recursive: true,
1209
+ force: true
1210
+ });
1211
+ this.sweepStaging();
1212
+ }
1213
+ }
1214
+ /** The state every phase reads and writes, built once from the plan and the live sources. */
1215
+ restoreContext(plan, options, manifest, staging) {
1216
+ return {
1217
+ plan,
1218
+ options,
1219
+ sources: this.options.getSources(),
1220
+ staging,
1221
+ manifest,
1222
+ selects: selectionOf(options),
1223
+ actions: /* @__PURE__ */ new Map(),
1224
+ archivedServers: /* @__PURE__ */ new Map(),
1225
+ createdWorkspaces: /* @__PURE__ */ new Map()
1226
+ };
1227
+ }
1228
+ /**
1229
+ * Unpacks the archive and refuses it before anything is written. A refusal is answered as a plan;
1230
+ * the one throw is a wrong password, which `applyRestore` maps to `needsPassword`.
1231
+ */
1232
+ async openArchive(plan, entries, archivePath, staging, password) {
1233
+ plan.encrypted = entries.some((entry) => entry.encrypted);
1234
+ if (plan.encrypted && password === null) return {
1235
+ ...plan,
1236
+ needsPassword: true,
1237
+ error: "this backup is password-protected"
1238
+ };
1239
+ ensureStateDir(staging);
1240
+ const extracted = await extractZip(archivePath, staging, {
1241
+ names: entries.map((entry) => entry.name),
1242
+ ...password === null ? {} : { password }
1243
+ });
1244
+ for (const name of extracted.skipped) {
1245
+ plan.skipped.push(`${name} (symbolic link, skipped)`);
1246
+ plan.skippedItems.push({
1247
+ label: name,
1248
+ reasonKey: "settings.restore.reasonSymbolicLink"
1249
+ });
1250
+ }
1251
+ const manifestPath = path.join(staging, MANIFEST);
1252
+ if (!fs.existsSync(manifestPath)) return {
1253
+ ...plan,
1254
+ error: "the archive has no manifest"
1255
+ };
1256
+ const manifest = JSON.parse(fs.readFileSync(manifestPath, "utf8"));
1257
+ plan.archive = manifestInfo(manifest);
1258
+ if (manifest.schema !== void 0 && manifest.schema > 2) return {
1259
+ ...plan,
1260
+ error: `written by home-hosted ${manifest.writtenBy ?? "a newer release"} (config schema ${manifest.schema}); this release understands schema 2`
1261
+ };
1262
+ 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 {
1263
+ ...plan,
1264
+ error: "the archive's manifest names a dump with an invalid workspace or server id"
1265
+ };
1266
+ return {
1267
+ ok: true,
1268
+ manifest
1269
+ };
1270
+ }
1271
+ /**
1272
+ * The global slices: settings, secrets (plus one leaf per secret), and the TLS pair. Returns the
1273
+ * archive's own settings for the later phases.
1274
+ */
1275
+ planGlobalItems(ctx) {
1276
+ const { plan, sources, staging, actions } = ctx;
1277
+ const { secretsApply, addItem } = this.itemWriters(ctx);
1278
+ const settingsText = readText(path.join(staging, "global", "settings.json"));
1279
+ const liftedGlobal = readableGlobalSettings(settingsText);
1280
+ const parsedGlobal = liftedGlobal === null ? null : parseGlobalSettings(liftedGlobal).config;
1281
+ if (settingsText !== null && parsedGlobal === null) {
1282
+ plan.skipped.push("Global settings (the archive's settings are not valid)");
1283
+ plan.skippedItems.push({
1284
+ label: "Global settings",
1285
+ labelKey: "settings.backup.entryGlobalSettings",
1286
+ reasonKey: "settings.restore.reasonInvalidSettings"
1287
+ });
1288
+ }
1289
+ if (parsedGlobal !== null && liftedGlobal !== null) {
1290
+ const globalText = `${JSON.stringify(liftedGlobal, null, 2)}\n`;
1291
+ addItem({
1292
+ id: GLOBAL_RESTORE_ITEMS.settings.id,
1293
+ label: "Global settings",
1294
+ labelKey: "settings.backup.entryGlobalSettings",
1295
+ kind: "settings",
1296
+ restorable: true,
1297
+ note: null
1298
+ }, () => {
1299
+ writeFileAtomic(sources.globalSettingsPath, globalText);
1300
+ }, [...GLOBAL_RESTORE_ITEMS.settings.aliases]);
1301
+ }
1302
+ const globalSecrets = readText(path.join(staging, "global", "secrets.json"));
1303
+ if (globalSecrets !== null) {
1304
+ addItem({
1305
+ id: GLOBAL_RESTORE_ITEMS.credentials.id,
1306
+ label: "Global secrets (accounts, API tokens)",
1307
+ labelKey: "settings.backup.entryGlobalSecrets",
1308
+ kind: "secrets",
1309
+ restorable: true,
1310
+ note: null
1311
+ }, secretsApply("global", GLOBAL_RESTORE_ITEMS.credentials.id, sources.globalSecretsPath, globalSecrets), [...GLOBAL_RESTORE_ITEMS.credentials.aliases]);
1312
+ for (const part of secretParts("global", presentSecretKeys(parseSecrets(globalSecrets)))) addItem({
1313
+ id: `${GLOBAL_RESTORE_ITEMS.credentials.id}:${part.key}`,
1314
+ label: `Global secrets: ${SECRET_LABELS[part.key]?.en ?? part.key}`,
1315
+ labelKey: "settings.backup.restoreItemLabel",
1316
+ labelParams: {
1317
+ workspace: "global",
1318
+ item: part.key
1319
+ },
1320
+ kind: "secrets",
1321
+ restorable: true,
1322
+ note: null
1323
+ }, () => {
1324
+ if (actions.has(GLOBAL_RESTORE_ITEMS.credentials.id)) return;
1325
+ mergeIntoFile(sources.globalSecretsPath, globalSecrets, part.fields);
1326
+ }, GLOBAL_RESTORE_ITEMS.credentials.aliases.map((alias) => `${alias}:${part.key}`));
1327
+ }
1328
+ const tlsInArchive = path.join(staging, "global", "tls");
1329
+ if (fs.existsSync(tlsInArchive)) {
1330
+ const files = fs.readdirSync(tlsInArchive).filter((file) => fs.statSync(path.join(tlsInArchive, file)).isFile());
1331
+ addItem({
1332
+ id: GLOBAL_RESTORE_ITEMS.tls.id,
1333
+ label: "TLS certificate",
1334
+ labelKey: "settings.backup.entryTlsCertificate",
1335
+ kind: "tls",
1336
+ restorable: true,
1337
+ note: null
1338
+ }, () => {
1339
+ ensureStateDir(sources.tlsDir);
1340
+ for (const file of files) {
1341
+ const mode = file.endsWith(".key.pem") ? { mode: 384 } : {};
1342
+ writeFileAtomic(path.join(sources.tlsDir, file), fs.readFileSync(path.join(tlsInArchive, file), "utf8"), mode);
1343
+ }
1344
+ }, [...GLOBAL_RESTORE_ITEMS.tls.aliases]);
1345
+ }
1346
+ return {
1347
+ settingsText,
1348
+ parsedGlobal
1349
+ };
1350
+ }
1351
+ /**
1352
+ * The two closures every planning phase writes through. `addItem` fills `actions` in call order and
1353
+ * `runApply` drains it in that order, so the sequence of `addItem` calls is the apply order.
1354
+ */
1355
+ itemWriters(ctx) {
1356
+ const { plan, selects, actions } = ctx;
1357
+ /**
1358
+ * Writes one archived secrets file, always by field: an archive carries only what its selection
1359
+ * captured, and the live file may hold secrets the archive predates.
1360
+ */
1361
+ const secretsApply = (scope, entryId, target, archived) => {
1362
+ const take = secretParts(scope, presentSecretKeys(parseSecrets(archived))).filter((part) => !selects.isExcluded(`${entryId}:${part.key}`) && !part.fields.some((field) => selects.isExcluded(`${entryId}:${field}`)));
1363
+ return () => {
1364
+ ensureStateDir(path.dirname(target));
1365
+ mergeIntoFile(target, archived, take.flatMap((part) => part.fields));
1366
+ };
1367
+ };
1368
+ const addItem = (item, apply, aliases = []) => {
1369
+ if (apply === null) {
1370
+ plan.items.push({
1371
+ ...item,
1372
+ selected: false
1373
+ });
1374
+ plan.skipped.push(`${item.label}${item.note === null ? "" : ` (${item.note})`}`);
1375
+ plan.skippedItems.push({
1376
+ label: item.label,
1377
+ ...item.labelKey === void 0 ? {} : { labelKey: item.labelKey },
1378
+ ...item.labelParams === void 0 ? {} : { labelParams: item.labelParams },
1379
+ reasonKey: item.noteKey ?? "settings.restore.reasonUnrestorable",
1380
+ ...item.noteParams === void 0 ? {} : { reasonParams: item.noteParams }
1381
+ });
1382
+ return;
1383
+ }
1384
+ const selected = selectedBy(selects, aliases.length === 0 ? item : {
1385
+ ...item,
1386
+ aliases
1387
+ });
1388
+ plan.items.push({
1389
+ ...item,
1390
+ selected
1391
+ });
1392
+ if (selected) actions.set(item.id, apply);
1393
+ else {
1394
+ plan.skipped.push(`${item.label} (not selected)`);
1395
+ plan.skippedItems.push({
1396
+ label: item.label,
1397
+ ...item.labelKey === void 0 ? {} : { labelKey: item.labelKey },
1398
+ ...item.labelParams === void 0 ? {} : { labelParams: item.labelParams },
1399
+ reasonKey: "settings.restore.reasonNotSelected"
1400
+ });
1401
+ }
1402
+ };
1403
+ return {
1404
+ secretsApply,
1405
+ addItem
1406
+ };
1407
+ }
1408
+ /**
1409
+ * One item group per workspace the archive names. A workspace this host lacks is created, not
1410
+ * skipped; its directories are made only when a leaf applies, so a dry run writes nothing.
1411
+ */
1412
+ planWorkspaceItems(ctx) {
1413
+ const { plan, sources, staging, actions, archivedServers, createdWorkspaces } = ctx;
1414
+ const archivedWorkspaces = /* @__PURE__ */ new Map();
1415
+ for (const entry of readArchivedRegistry(path.join(staging, "global", REGISTRY))) archivedWorkspaces.set(entry.id, entry);
1416
+ const { secretsApply, addItem } = this.itemWriters(ctx);
1417
+ const archiveWorkspaces = path.join(staging, "workspaces");
1418
+ if (fs.existsSync(archiveWorkspaces)) for (const entry of fs.readdirSync(archiveWorkspaces, { withFileTypes: true })) {
1419
+ if (!entry.isDirectory()) continue;
1420
+ const id = entry.name;
1421
+ const dir = path.join(archiveWorkspaces, id);
1422
+ const settings = readText(path.join(dir, "settings.json"));
1423
+ const servers = readText(path.join(dir, "servers.config.json"));
1424
+ const jobs = readText(path.join(dir, "jobs.config.json"));
1425
+ const secrets = readText(path.join(dir, "secrets.json"));
1426
+ const archivedLabel = archivedWorkspaces.get(id)?.label ?? id;
1427
+ const workspace = sources.workspaces.find((candidate) => candidate.id === id) ?? createdWorkspaces.get(id) ?? (workspaceIdSchema(id) instanceof type.errors ? void 0 : {
1428
+ id,
1429
+ label: archivedLabel,
1430
+ ...workspacePathsFor(this.options.dataRoot, id),
1431
+ servers: []
1432
+ });
1433
+ if (workspace === void 0) {
1434
+ plan.skipped.push(`${id} (not a usable workspace id)`);
1435
+ plan.skippedItems.push({
1436
+ label: id,
1437
+ reasonKey: "settings.restore.reasonInvalidWorkspace"
1438
+ });
1439
+ continue;
1440
+ }
1441
+ if (!sources.workspaces.some((candidate) => candidate.id === id)) createdWorkspaces.set(id, workspace);
1442
+ if (settings !== null) {
1443
+ const liftedSettings = readableWorkspaceSettings(settings);
1444
+ if (liftedSettings !== null) {
1445
+ const settingsText = `${JSON.stringify(liftedSettings, null, 2)}\n`;
1446
+ addItem({
1447
+ id: `workspace:${id}:settings`,
1448
+ label: `${workspace.label}: Settings`,
1449
+ labelKey: "settings.backup.restoreItemLabel",
1450
+ labelParams: {
1451
+ workspace: workspace.label,
1452
+ item: "settings"
1453
+ },
1454
+ kind: "settings",
1455
+ workspaceId: id,
1456
+ restorable: true,
1457
+ note: null
1458
+ }, () => {
1459
+ ensureStateDir(path.dirname(workspace.settingsPath));
1460
+ writeFileAtomic(workspace.settingsPath, settingsText);
1461
+ });
1462
+ } else {
1463
+ plan.skipped.push(`${workspace.label}: Settings (the archive's settings are not valid)`);
1464
+ plan.skippedItems.push({
1465
+ label: `${workspace.label}: Settings`,
1466
+ labelKey: "settings.backup.restoreItemLabel",
1467
+ labelParams: {
1468
+ workspace: workspace.label,
1469
+ item: "settings"
1470
+ },
1471
+ reasonKey: "settings.restore.reasonInvalidSettings"
1472
+ });
1473
+ }
1474
+ }
1475
+ if (servers !== null) {
1476
+ const parsed = readableServersFile(servers);
1477
+ const liftedServers = parsed === null ? null : liftArchived(JSON.parse(servers));
1478
+ if (parsed !== null && liftedServers !== null) {
1479
+ const serversText = `${JSON.stringify(liftedServers, null, 2)}\n`;
1480
+ archivedServers.set(id, parsed);
1481
+ addItem({
1482
+ id: `workspace:${id}:servers`,
1483
+ label: `${workspace.label}: Servers`,
1484
+ labelKey: "settings.backup.restoreItemLabel",
1485
+ labelParams: {
1486
+ workspace: workspace.label,
1487
+ item: "servers"
1488
+ },
1489
+ kind: "servers",
1490
+ workspaceId: id,
1491
+ restorable: true,
1492
+ note: null
1493
+ }, () => {
1494
+ ensureStateDir(path.dirname(workspace.serversPath));
1495
+ writeFileAtomic(workspace.serversPath, serversText);
1496
+ });
1497
+ } else {
1498
+ plan.skipped.push(`${workspace.label}: Servers (the archive's servers are not valid)`);
1499
+ plan.skippedItems.push({
1500
+ label: `${workspace.label}: Servers`,
1501
+ labelKey: "settings.backup.restoreItemLabel",
1502
+ labelParams: {
1503
+ workspace: workspace.label,
1504
+ item: "servers"
1505
+ },
1506
+ reasonKey: "settings.restore.reasonInvalidServers"
1507
+ });
1508
+ }
1509
+ }
1510
+ if (jobs !== null) {
1511
+ const liftedJobs = readableJobsFile(jobs);
1512
+ if (liftedJobs !== null) {
1513
+ const jobsText = `${JSON.stringify(liftedJobs, null, 2)}\n`;
1514
+ addItem({
1515
+ id: `workspace:${id}:jobs`,
1516
+ label: `${workspace.label}: Jobs`,
1517
+ labelKey: "settings.backup.restoreItemLabel",
1518
+ labelParams: {
1519
+ workspace: workspace.label,
1520
+ item: "jobs"
1521
+ },
1522
+ kind: "jobs",
1523
+ workspaceId: id,
1524
+ restorable: true,
1525
+ note: null
1526
+ }, () => {
1527
+ writeRestoredJobs(workspace.jobsPath, jobsText);
1528
+ });
1529
+ } else {
1530
+ plan.skipped.push(`${workspace.label}: Jobs (the archive's jobs are not valid)`);
1531
+ plan.skippedItems.push({
1532
+ label: `${workspace.label}: Jobs`,
1533
+ labelKey: "settings.backup.restoreItemLabel",
1534
+ labelParams: {
1535
+ workspace: workspace.label,
1536
+ item: "jobs"
1537
+ },
1538
+ reasonKey: "settings.restore.reasonInvalidJobs"
1539
+ });
1540
+ }
1541
+ }
1542
+ if (secrets !== null) {
1543
+ addItem({
1544
+ id: `workspace:${id}:secrets`,
1545
+ label: `${workspace.label}: Secrets`,
1546
+ labelKey: "settings.backup.restoreItemLabel",
1547
+ labelParams: {
1548
+ workspace: workspace.label,
1549
+ item: "secrets"
1550
+ },
1551
+ kind: "secrets",
1552
+ workspaceId: id,
1553
+ restorable: true,
1554
+ note: null
1555
+ }, secretsApply("workspace", `workspace:${id}:secrets`, workspace.secretsPath, secrets));
1556
+ for (const part of secretParts("workspace", presentSecretKeys(parseSecrets(secrets)))) addItem({
1557
+ id: `workspace:${id}:secrets:${part.key}`,
1558
+ label: `${workspace.label}: ${SECRET_LABELS[part.key]?.en ?? part.key}`,
1559
+ labelKey: "settings.backup.restoreItemLabel",
1560
+ labelParams: {
1561
+ workspace: workspace.label,
1562
+ item: part.key
1563
+ },
1564
+ kind: "secrets",
1565
+ workspaceId: id,
1566
+ restorable: true,
1567
+ note: null
1568
+ }, () => {
1569
+ if (actions.has(`workspace:${id}:secrets`)) return;
1570
+ ensureStateDir(path.dirname(workspace.secretsPath));
1571
+ mergeIntoFile(workspace.secretsPath, secrets, part.fields);
1572
+ });
1573
+ }
1574
+ }
1575
+ }
1576
+ /**
1577
+ * Data-path items and dumps. A data path is written only to a path a config declares. Runs after
1578
+ * the workspace phase: it reads `archivedServers` and the workspace items in `actions`.
1579
+ */
1580
+ planDataItems(ctx, global) {
1581
+ const { plan, sources, staging, manifest, selects } = ctx;
1582
+ const { addItem } = this.itemWriters(ctx);
1583
+ const { archiveAll, archiveTargets, instanceTargets } = this.collectDataTargets(ctx, global);
1584
+ const matchTarget = dataTargetMatcher(archiveTargets, instanceTargets);
1585
+ const runningOwners = new Set((sources.runningServers?.() ?? []).map((entry) => `${entry.workspaceId}:${entry.serverId}`));
1586
+ this.planDumpItems(ctx);
1587
+ const archivedEntries = Array.isArray(manifest.data) ? manifest.data.filter(isRecord) : [];
1588
+ for (const entry of archivedEntries) {
1589
+ const archivedPath = typeof entry.path === "string" ? entry.path : "";
1590
+ const origin = typeof entry.origin === "string" ? entry.origin : void 0;
1591
+ const workspace = typeof entry.workspace === "string" ? entry.workspace : void 0;
1592
+ const from = path.join(staging, "data", safeSlug(entry.slug) ?? legacySlug(archivedPath));
1593
+ const target = matchTarget(origin, workspace, archivedPath);
1594
+ const targetWorkspace = target?.workspace ?? workspace;
1595
+ const base = {
1596
+ id: target === void 0 ? `data:${archivedPath}` : `workspace:${target.workspace}:data:${target.path}`,
1597
+ label: target?.path ?? archivedPath,
1598
+ kind: "data",
1599
+ restorable: false,
1600
+ note: null,
1601
+ ...targetWorkspace === void 0 ? {} : { workspaceId: targetWorkspace }
1602
+ };
1603
+ const aliases = [`data:${archivedPath}`];
1604
+ if (target === void 0) {
1605
+ this.planUnplacedDataItem(ctx, archiveAll, {
1606
+ base,
1607
+ aliases,
1608
+ origin,
1609
+ workspace
1610
+ });
1611
+ continue;
1612
+ }
1613
+ if (!fs.existsSync(from)) {
1614
+ addItem({
1615
+ ...base,
1616
+ note: "missing from the archive",
1617
+ noteKey: "settings.backup.noteMissingFromArchive"
1618
+ }, null, aliases);
1619
+ continue;
1620
+ }
1621
+ const ownerId = target.origin.split(":")[0] ?? "";
1622
+ if (selectedBy(selects, {
1623
+ ...base,
1624
+ aliases
1625
+ }) && runningOwners.has(`${target.workspace}:${ownerId}`)) plan.replacedUnderRunning.push({
1626
+ workspaceId: target.workspace,
1627
+ serverId: ownerId,
1628
+ path: target.path
1629
+ });
1630
+ addItem({
1631
+ ...base,
1632
+ restorable: true,
1633
+ ...target.path === archivedPath ? { note: null } : {
1634
+ note: `restored from ${archivedPath}`,
1635
+ noteKey: "settings.backup.noteRestoredFrom",
1636
+ noteParams: { path: archivedPath }
1637
+ }
1638
+ }, () => copyTree(from, target.path, (_source, destination) => isInsideResolved(target.path, destination)), aliases);
1639
+ }
1640
+ }
1641
+ /**
1642
+ * A dump is a restorable item so the selection can name it. Applying it writes nothing: the `load`
1643
+ * hook replays it after everything has landed.
1644
+ */
1645
+ planDumpItems(ctx) {
1646
+ const { staging, manifest } = ctx;
1647
+ const { addItem } = this.itemWriters(ctx);
1648
+ for (const dump of manifest.dumps ?? []) {
1649
+ const from = path.join(staging, "dumps", dump.workspaceId, dump.serverId);
1650
+ if (!fs.existsSync(from)) continue;
1651
+ addItem({
1652
+ id: `workspace:${dump.workspaceId}:dump:${dump.serverId}`,
1653
+ label: `dump:${dump.serverId}`,
1654
+ kind: "data",
1655
+ restorable: true,
1656
+ workspaceId: dump.workspaceId,
1657
+ note: null
1658
+ }, () => {});
1659
+ }
1660
+ }
1661
+ /**
1662
+ * An archived data path nothing on this host will receive, reported with why: the backup's config
1663
+ * declares it but is not being restored, or neither config does.
1664
+ */
1665
+ planUnplacedDataItem(ctx, archiveAll, placed) {
1666
+ const { addItem } = this.itemWriters(ctx);
1667
+ const { base, aliases, origin, workspace } = placed;
1668
+ const declaredByBackup = archiveAll.some((candidate) => candidate.origin === origin && (workspace === void 0 || candidate.workspace === workspace));
1669
+ addItem({
1670
+ ...base,
1671
+ note: declaredByBackup ? "declared by the backup's config, which is not being restored" : "not declared by this config, nor by the backup",
1672
+ noteKey: declaredByBackup ? "settings.backup.noteDeclaredByBackup" : "settings.backup.noteNotDeclared"
1673
+ }, null, aliases);
1674
+ }
1675
+ /**
1676
+ * Every data path a restore could write. `archiveAll` answers "did the backup's config declare it?"
1677
+ * for the report; `archiveTargets` holds only those from a servers file this restore applies.
1678
+ * An applied `global:settings` brings its own `includePaths`.
1679
+ */
1680
+ collectDataTargets(ctx, global) {
1681
+ const { sources, actions, archivedServers } = ctx;
1682
+ const { parsedGlobal } = global;
1683
+ const instanceTargets = [];
1684
+ for (const workspace of sources.workspaces) for (const declared of this.declaredData(workspace.servers, sources.includePaths)) {
1685
+ if (!declared.included) continue;
1686
+ instanceTargets.push({
1687
+ workspace: workspace.id,
1688
+ path: declared.path,
1689
+ origin: declared.origin
1690
+ });
1691
+ }
1692
+ const archivedIncludePaths = actions.has("global:settings") && parsedGlobal !== null ? parsedGlobal.backups.includePaths : sources.includePaths;
1693
+ const archiveAll = [];
1694
+ const archiveTargets = [];
1695
+ for (const [id, servers] of archivedServers) for (const declared of this.declaredData(servers, archivedIncludePaths)) {
1696
+ if (!declared.included) continue;
1697
+ const target = {
1698
+ workspace: id,
1699
+ path: declared.path,
1700
+ origin: declared.origin
1701
+ };
1702
+ archiveAll.push(target);
1703
+ if (actions.has(`workspace:${id}:servers`)) archiveTargets.push(target);
1704
+ }
1705
+ return {
1706
+ archiveAll,
1707
+ archiveTargets,
1708
+ instanceTargets
1709
+ };
1710
+ }
1711
+ /** Whether the panel's own listener must restart — computed even for a dry run. */
1712
+ noteRestartRequired(ctx, global) {
1713
+ const { plan, sources, actions } = ctx;
1714
+ const { settingsText, parsedGlobal } = global;
1715
+ if (parsedGlobal !== null && actions.has("global:settings") && settingsText !== null) {
1716
+ const current = readableGlobalSettings(readText(sources.globalSettingsPath));
1717
+ plan.restartRequired = JSON.stringify(parsedGlobal.control) !== JSON.stringify(current === null ? null : parseGlobalSettings(current).config?.control ?? null);
1718
+ }
1719
+ }
1720
+ /**
1721
+ * Runs every planned write in order, stopping at the first failure, which is returned for the
1722
+ * caller to reload what landed and rethrow.
1723
+ */
1724
+ async runApply(ctx) {
1725
+ const { plan, actions } = ctx;
1726
+ let failure = null;
1727
+ for (const [id, apply] of actions) {
1728
+ try {
1729
+ await apply();
1730
+ } catch (error) {
1731
+ failure = error;
1732
+ break;
1733
+ }
1734
+ plan.applied.push(labelOf(plan, id));
1735
+ plan.appliedIds.push(id);
1736
+ }
1737
+ return failure;
1738
+ }
1739
+ /**
1740
+ * Registers the workspaces this restore created — last, and only those something was applied to:
1741
+ * a known but empty workspace is worse than an absent one.
1742
+ */
1743
+ registerCreatedWorkspaces(ctx) {
1744
+ const { plan, createdWorkspaces } = ctx;
1745
+ for (const workspace of createdWorkspaces.values()) {
1746
+ if (!plan.appliedIds.some((id) => id.startsWith(`workspace:${workspace.id}:`))) continue;
1747
+ this.options.ensureWorkspace?.({
1748
+ id: workspace.id,
1749
+ label: workspace.label
1750
+ });
1751
+ plan.createdWorkspaces.push(workspace.id);
1752
+ }
1753
+ }
1754
+ /**
1755
+ * Stages each restored dump for its entry's own `load` hook, which runs on the entry's next start
1756
+ * (the hook needs a server that answers). Staged before the caller reloads, which reads `pendingLoad`.
1757
+ */
1758
+ async stagePendingLoads(ctx) {
1759
+ const { plan, staging, manifest, actions } = ctx;
1760
+ const archivedDumps = manifest.dumps ?? [];
1761
+ const pendingLoads = [];
1762
+ for (const entry of archivedDumps) {
1763
+ if (!plan.appliedIds.some((id) => id.startsWith(`workspace:${entry.workspaceId}:`))) continue;
1764
+ if (!actions.has(`workspace:${entry.workspaceId}:dump:${entry.serverId}`)) continue;
1765
+ const server = readArchivedServers(staging, entry.workspaceId).find((candidate) => candidate.id === entry.serverId);
1766
+ if (server?.load === void 0 || server.load === null) {
1767
+ plan.skipped.push(`the dump for "${entry.serverId}" was restored but this entry has no load hook`);
1768
+ continue;
1769
+ }
1770
+ const dumpDir = path.join(staging, "dumps", entry.workspaceId, entry.serverId);
1771
+ if (!fs.existsSync(dumpDir)) {
1772
+ plan.skipped.push(`the dump for "${entry.serverId}" is missing from the archive`);
1773
+ continue;
1774
+ }
1775
+ const staged = path.join(this.options.dataRoot, PENDING_LOAD, entry.workspaceId, entry.serverId);
1776
+ await copyTree(dumpDir, staged, () => true);
1777
+ pendingLoads.push({
1778
+ workspaceId: entry.workspaceId,
1779
+ serverId: entry.serverId,
1780
+ staged
1781
+ });
1782
+ plan.hooks = [...plan.hooks ?? [], {
1783
+ serverId: entry.serverId,
1784
+ workspaceId: entry.workspaceId,
1785
+ action: "load",
1786
+ ok: true,
1787
+ output: "staged — runs when this entry next starts"
1788
+ }];
1789
+ }
1790
+ for (const load of pendingLoads) this.options.onLoadPending?.(load.workspaceId, load.serverId, load.staged);
1791
+ }
1792
+ /** The panel re-reads the restored settings and servers, so what the archive brought exists immediately. */
1793
+ reloadRestored(plan) {
1794
+ if (this.options.onRestored === void 0 || !plan.appliedIds.some((id) => RELOADABLE.test(id))) return;
1795
+ plan.reloaded = true;
1796
+ this.options.onRestored();
1797
+ }
1798
+ /** Selectable entries: the three global slices, then one per workspace. */
1799
+ entries(sources) {
1800
+ const missing = (path, key) => {
1801
+ const absent = this.missingNote(path);
1802
+ return absent === null ? { note: null } : {
1803
+ note: absent,
1804
+ noteKey: key
1805
+ };
1806
+ };
1807
+ const entries = [
1808
+ {
1809
+ id: "global:settings",
1810
+ label: "Global settings",
1811
+ labelKey: "settings.backup.entryGlobalSettings",
1812
+ kind: "settings",
1813
+ ...missing(sources.globalSettingsPath, "settings.backup.noteMissing"),
1814
+ items: []
1815
+ },
1816
+ {
1817
+ id: "global:secrets",
1818
+ label: "Global secrets (accounts, API tokens)",
1819
+ labelKey: "settings.backup.entryGlobalSecrets",
1820
+ kind: "secrets",
1821
+ ...missing(sources.globalSecretsPath, "settings.backup.noteMissing"),
1822
+ items: this.secretItems("global", "global:secrets", sources.globalSecretsPath)
1823
+ },
1824
+ {
1825
+ id: "global:tls",
1826
+ label: "TLS certificate",
1827
+ labelKey: "settings.backup.entryTlsCertificate",
1828
+ kind: "tls",
1829
+ ...missing(sources.tlsDir, "settings.backup.noteMissing"),
1830
+ items: []
1831
+ }
1832
+ ];
1833
+ for (const workspace of sources.workspaces) entries.push({
1834
+ id: `workspace:${workspace.id}`,
1835
+ label: workspace.label,
1836
+ kind: "workspace",
1837
+ workspaceId: workspace.id,
1838
+ note: null,
1839
+ items: this.workspaceItems(workspace, sources.includePaths)
1840
+ });
1841
+ return entries;
1842
+ }
1843
+ /**
1844
+ * One leaf per secret, so one can come back without the others. Derived from the file's own keys,
1845
+ * so a secret added later appears without a second list.
1846
+ */
1847
+ secretItems(scope, entryId, path) {
1848
+ const parts = secretParts(scope, presentSecretKeys(parseSecrets(readText(path) ?? "")));
1849
+ const missing = KNOWN_SECRET_KEYS[scope].filter((key) => !parts.some((part) => part.key === key) && !LEGACY_SECRET_SLOTS.has(key));
1850
+ return [...parts.map((part) => ({
1851
+ id: `${entryId}:${part.key}`,
1852
+ label: SECRET_LABELS[part.key]?.en ?? part.key,
1853
+ ...SECRET_LABELS[part.key]?.key === void 0 ? {} : { labelKey: SECRET_LABELS[part.key].key },
1854
+ kind: "secrets",
1855
+ secret: part.key,
1856
+ included: true,
1857
+ note: null
1858
+ })), ...missing.map((key) => ({
1859
+ id: `${entryId}:${key}`,
1860
+ label: SECRET_LABELS[key]?.en ?? key,
1861
+ ...SECRET_LABELS[key]?.key === void 0 ? {} : { labelKey: SECRET_LABELS[key].key },
1862
+ kind: "secrets",
1863
+ secret: key,
1864
+ included: false,
1865
+ note: "not set",
1866
+ noteKey: "settings.backup.noteMissing"
1867
+ }))];
1868
+ }
1869
+ workspaceItems(workspace, includePaths) {
1870
+ const id = workspace.id;
1871
+ const note = (path) => {
1872
+ const absent = this.missingNote(path);
1873
+ return absent === null ? { note: null } : {
1874
+ note: absent,
1875
+ noteKey: "settings.backup.noteMissing"
1876
+ };
1877
+ };
1878
+ const items = [
1879
+ {
1880
+ id: `workspace:${id}:settings`,
1881
+ label: "Settings",
1882
+ labelKey: "settings.backup.leafSettings",
1883
+ kind: "settings",
1884
+ included: true,
1885
+ ...note(workspace.settingsPath)
1886
+ },
1887
+ {
1888
+ id: `workspace:${id}:servers`,
1889
+ label: "Servers",
1890
+ labelKey: "settings.backup.leafServers",
1891
+ kind: "servers",
1892
+ included: true,
1893
+ ...note(workspace.serversPath)
1894
+ },
1895
+ {
1896
+ id: `workspace:${id}:jobs`,
1897
+ label: "Jobs",
1898
+ labelKey: "settings.backup.leafJobs",
1899
+ kind: "jobs",
1900
+ included: true,
1901
+ ...note(workspace.jobsPath)
1902
+ },
1903
+ {
1904
+ id: `workspace:${id}:secrets`,
1905
+ label: "Secrets",
1906
+ labelKey: "settings.backup.leafSecrets",
1907
+ kind: "secrets",
1908
+ included: true,
1909
+ ...note(workspace.secretsPath)
1910
+ },
1911
+ ...this.secretItems("workspace", `workspace:${id}:secrets`, workspace.secretsPath)
1912
+ ];
1913
+ for (const declared of this.declaredData(workspace.servers, includePaths)) items.push({
1914
+ id: `workspace:${id}:data:${declared.path}`,
1915
+ label: declared.path,
1916
+ kind: "data",
1917
+ path: declared.path,
1918
+ origin: declared.origin,
1919
+ included: declared.included,
1920
+ note: declared.note,
1921
+ ...declared.noteKey === void 0 ? {} : { noteKey: declared.noteKey },
1922
+ ...declared.noteParams === void 0 ? {} : { noteParams: declared.noteParams },
1923
+ ignoreGenerated: declared.ignoreGenerated
1924
+ });
1925
+ return items;
1926
+ }
1927
+ /** Declared data paths, vetoing any that contains the archive directory (it would contain itself). */
1928
+ declaredData(servers, includePaths) {
1929
+ const archiveDir = path.resolve(this.resolveDir());
1930
+ return resolveBackupPaths(servers, includePaths, this.backupVars(servers)).map((entry) => {
1931
+ if (entry.included && isInside(entry.path, archiveDir)) return {
1932
+ ...entry,
1933
+ included: false,
1934
+ note: "contains the backup directory",
1935
+ noteKey: "settings.backup.noteContainsBackupDir"
1936
+ };
1937
+ return entry;
1938
+ });
1939
+ }
1940
+ /** The `{dataRoot}` a config expands to, without a module-level state root. */
1941
+ backupVars(servers) {
1942
+ const first = servers[0];
1943
+ return {
1944
+ projectDir,
1945
+ dataRoot: first === void 0 ? path.dirname(path.resolve(this.options.dataRoot)) : String(serverTemplateVars(first).dataRoot ?? projectDir),
1946
+ home: os.homedir()
1947
+ };
1948
+ }
1949
+ /**
1950
+ * Reclaims staging trees (capture or restore) a killed run left behind, where no `catch` ran. The
1951
+ * owner's pid decides, never an age: another live run's tree is a capture in progress.
1952
+ */
1953
+ sweepStaging() {
1954
+ const dir = this.resolveDir();
1955
+ let names;
1956
+ try {
1957
+ names = fs.readdirSync(dir);
1958
+ } catch {
1959
+ return;
1960
+ }
1961
+ for (const name of names) {
1962
+ const owner = stagingOwner(name);
1963
+ if (owner === null || owner === process.pid || isProcessAlive(owner)) continue;
1964
+ try {
1965
+ fs.rmSync(path.join(dir, name), {
1966
+ recursive: true,
1967
+ force: true
1968
+ });
1969
+ } catch {}
1970
+ }
1971
+ }
1972
+ /** Newest-first listing, without the encryption flag, which needs a read. */
1973
+ scan() {
1974
+ const dir = this.resolveDir();
1975
+ let names = [];
1976
+ try {
1977
+ names = fs.readdirSync(dir);
1978
+ } catch {
1979
+ return [];
1980
+ }
1981
+ return names.filter((name) => name.endsWith(SUFFIX)).flatMap((name) => {
1982
+ try {
1983
+ const stats = fs.statSync(path.join(dir, name));
1984
+ return [{
1985
+ name,
1986
+ sizeBytes: stats.size,
1987
+ createdAt: archiveStamp(name) ?? Math.round(stats.mtimeMs)
1988
+ }];
1989
+ } catch {
1990
+ return [];
1991
+ }
1992
+ }).sort((a, b) => b.createdAt - a.createdAt);
1993
+ }
1994
+ /** Single-flight: a state frame must never queue a pile of reads. */
1995
+ scheduleRefresh() {
1996
+ this.refreshing ??= this.refresh().finally(() => {
1997
+ this.refreshing = null;
1998
+ });
1999
+ return this.refreshing;
2000
+ }
2001
+ async refresh() {
2002
+ const dir = this.resolveDir();
2003
+ const listed = this.scan();
2004
+ for (const file of listed) {
2005
+ const key = cacheKey(file);
2006
+ if (this.flags.get(file.name)?.key === key) continue;
2007
+ try {
2008
+ const entries = await listZip(path.join(dir, file.name));
2009
+ this.flags.set(file.name, {
2010
+ key,
2011
+ encrypted: entries.some((entry) => entry.encrypted)
2012
+ });
2013
+ } catch {
2014
+ this.flags.set(file.name, {
2015
+ key,
2016
+ encrypted: false
2017
+ });
2018
+ }
2019
+ }
2020
+ const present = new Set(listed.map((file) => file.name));
2021
+ for (const name of [...this.flags.keys()]) if (!present.has(name)) this.flags.delete(name);
2022
+ }
2023
+ missingNote(target) {
2024
+ return fs.existsSync(target) ? null : "not set";
2025
+ }
2026
+ /** Copies one source into the staging tree; false when there was nothing there. */
2027
+ async copyInto(staging, relative, source, ignoreGenerated = false) {
2028
+ if (!fs.existsSync(source)) return false;
2029
+ const target = path.join(staging, relative);
2030
+ ensureStateDir(path.dirname(target));
2031
+ const archiveDir = resolveExisting(path.resolve(this.resolveDir()));
2032
+ const root = resolveExisting(path.resolve(source));
2033
+ await copyTree(source, target, (from) => {
2034
+ const resolved = path.resolve(from);
2035
+ if (isInside(archiveDir, resolved)) return false;
2036
+ if (isSecretDocument(path.basename(resolved))) return false;
2037
+ if (!ignoreGenerated || resolved === root) return true;
2038
+ return !isGeneratedPath(path.relative(root, resolved));
2039
+ });
2040
+ return true;
2041
+ }
2042
+ /**
2043
+ * Drops the oldest archives past their own limit: `schedule.keep` for automatic ones, `keep` for
2044
+ * the rest, so a scheduled pass never prunes a hand-taken archive.
2045
+ */
2046
+ prune() {
2047
+ const config = this.options.getConfig();
2048
+ const files = this.list();
2049
+ const automatic = files.filter(isAutomatic);
2050
+ const manual = files.filter((file) => ARCHIVE_NAME.exec(file.name)?.[1] === MANUAL_PREFIX);
2051
+ for (const file of automatic.slice(config.schedule.keep)) this.remove(file.name);
2052
+ for (const file of manual.slice(config.keep)) this.remove(file.name);
2053
+ this.sweepPartials();
2054
+ }
2055
+ /**
2056
+ * An archive killed mid-write leaves its `.<name>.partial` behind (`createZip` renames only on
2057
+ * success). An hour old is never a write in progress — a live one keeps touching its mtime.
2058
+ */
2059
+ sweepPartials(now = Date.now()) {
2060
+ const dir = this.resolveDir();
2061
+ let names = [];
2062
+ try {
2063
+ names = fs.readdirSync(dir);
2064
+ } catch {
2065
+ return;
2066
+ }
2067
+ for (const name of names.filter((entry) => entry.startsWith(".") && entry.endsWith(`${SUFFIX}.partial`))) {
2068
+ const file = path.join(dir, name);
2069
+ try {
2070
+ if (now - fs.statSync(file).mtimeMs > 36e5) fs.rmSync(file, { force: true });
2071
+ } catch {}
2072
+ }
2073
+ }
2074
+ /** When the newest automatic archive was written, or null when there is none. */
2075
+ lastAutomatic() {
2076
+ const dir = this.resolveDir();
2077
+ if (this.lastAutomaticSeen?.dir !== dir) this.lastAutomaticSeen = {
2078
+ dir,
2079
+ at: this.scan().find(isAutomatic)?.createdAt ?? null
2080
+ };
2081
+ return this.lastAutomaticSeen.at;
2082
+ }
2083
+ /** Runs one scheduled pass when it is due: cheap on every panel tick, never blocking, never two at once. */
2084
+ tick(now = Date.now()) {
2085
+ if (this.disposed || this.running) return;
2086
+ const config = this.options.getConfig();
2087
+ if (!config.enabled || config.schedule.intervalMs <= 0) return;
2088
+ const last = this.lastAutomatic();
2089
+ const latest = last === null ? this.lastAttemptAt : Math.max(last, this.lastAttemptAt ?? 0);
2090
+ if (latest !== null && now - latest < config.schedule.intervalMs) return;
2091
+ const restoring = restoreLockHolder(this.options.dataRoot);
2092
+ if (restoring !== null) {
2093
+ if (!this.deferredForRestore) logger.info(`the scheduled backup is waiting for the restore that is running (pid ${restoring.pid})`);
2094
+ this.deferredForRestore = true;
2095
+ return;
2096
+ }
2097
+ this.deferredForRestore = false;
2098
+ this.running = true;
2099
+ this.lastAttemptAt = now;
2100
+ this.create({
2101
+ automatic: true,
2102
+ ...scopeSelection(config.schedule.scope)
2103
+ }).then((result) => {
2104
+ if (result.ok) {
2105
+ this.scheduleError = null;
2106
+ for (const warning of result.warnings ?? []) logger.warn("the scheduled backup", warning);
2107
+ return;
2108
+ }
2109
+ this.scheduleError = {
2110
+ message: result.error ?? "the scheduled backup failed",
2111
+ at: Date.now()
2112
+ };
2113
+ logger.warn("the scheduled backup failed", result.error);
2114
+ }).catch((error) => {
2115
+ this.scheduleError = {
2116
+ message: errorMessage(error),
2117
+ at: Date.now()
2118
+ };
2119
+ logger.error("the scheduled backup failed", error);
2120
+ }).finally(() => {
2121
+ this.running = false;
2122
+ });
2123
+ }
2124
+ resolveDir() {
2125
+ const configured = this.options.getConfig().dir;
2126
+ return path.isAbsolute(configured) ? configured : path.resolve(this.options.dataRoot, configured);
2127
+ }
2128
+ };
2129
+ /** Whether an archive came from the schedule rather than from a person. */
2130
+ function isAutomatic(file) {
2131
+ return ARCHIVE_NAME.exec(file.name)?.[1] === AUTO_PREFIX;
2132
+ }
2133
+ /** The label of one item, for `applied`; items are built before actions run. */
2134
+ function labelOf(plan, id) {
2135
+ return plan.items.find((item) => item.id === id)?.label ?? id;
2136
+ }
2137
+ /**
2138
+ * Restores only `fields` from an archived secrets document into a live one, leaving other keys alone
2139
+ * and clearing a selected field the archive does not carry.
2140
+ */
2141
+ function mergeIntoFile(target, archived, fields) {
2142
+ const merged = mergeSecrets(parseSecrets(readText(target) ?? ""), parseSecrets(archived), fields);
2143
+ writeFileAtomic(target, `${JSON.stringify(merged, null, 2)}\n`, { mode: 384 });
2144
+ }
2145
+ /** What an archive says about where it came from; both fields absent on older archives. */
2146
+ function manifestInfo(manifest) {
2147
+ return {
2148
+ ...manifest.writtenBy === void 0 ? {} : { writtenBy: manifest.writtenBy },
2149
+ ...manifest.schema === void 0 ? {} : { schema: manifest.schema }
2150
+ };
2151
+ }
2152
+ /**
2153
+ * `servers.config.json` as a readability gate, lifted first when older; the store applies the
2154
+ * workspace's own defaults on the next load. `null` means unreadable.
2155
+ */
2156
+ function readableServersFile(text) {
2157
+ try {
2158
+ const lifted = liftArchived(JSON.parse(text));
2159
+ if (lifted === null) return null;
2160
+ const result = parseServersFile(lifted, {});
2161
+ return result.errors.length === 0 ? result.servers : null;
2162
+ } catch {
2163
+ return null;
2164
+ }
2165
+ }
2166
+ /** A workspace settings file is adopted only when this release can read it, lifted when older. */
2167
+ function readableWorkspaceSettings(text) {
2168
+ try {
2169
+ const lifted = liftArchived(JSON.parse(text));
2170
+ return lifted !== null && parseWorkspaceSettings(lifted).config !== null ? lifted : null;
2171
+ } catch {
2172
+ return null;
2173
+ }
2174
+ }
2175
+ /**
2176
+ * `jobs.config.json` under the same gate as the servers file. One unrunnable job refuses the file:
2177
+ * a half-applied schedule fires some jobs and says nothing about the rest.
2178
+ */
2179
+ function readableJobsFile(text) {
2180
+ try {
2181
+ const lifted = liftArchived(JSON.parse(text));
2182
+ if (lifted === null) return null;
2183
+ const document = liftJobsDocument(lifted).document;
2184
+ const parsed = jobsFileSchema(document);
2185
+ if (parsed instanceof type.errors) return null;
2186
+ for (const job of parsed.jobs) if (jobProblems(job).length > 0) return null;
2187
+ return document;
2188
+ } catch {
2189
+ return null;
2190
+ }
2191
+ }
2192
+ /**
2193
+ * Writes a restored `jobs.config.json`, keeping the replaced file as `<file>.bak` (the name
2194
+ * `migrate` uses) when there was one.
2195
+ */
2196
+ function writeRestoredJobs(file, text) {
2197
+ if (fs.existsSync(file)) fs.copyFileSync(file, `${file}.bak`);
2198
+ writeFileAtomic(file, text);
2199
+ }
2200
+ //#endregion
2201
+ export { unknownBackupIds as a, clearEntryState as c, writeEntryState as d, selectionWritesCredentials as i, entryStatePath as l, buildBackupSources as n, hookFailure as o, selectionOf as r, runBackupHook as s, BackupService as t, readEntryState as u };
2202
+
2203
+ //# sourceMappingURL=backups-BrrN6cwW.js.map