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.
- package/README.md +117 -322
- package/bin/home-hosted.mjs +41 -0
- package/dist/chunks/account-DiLrSyww.js +359 -0
- package/dist/chunks/account-DiLrSyww.js.map +1 -0
- package/dist/chunks/add-DEIYVkNK.js +183 -0
- package/dist/chunks/add-DEIYVkNK.js.map +1 -0
- package/dist/chunks/{archive-DP-XQR8X.js → archive-DFi3qK1c.js} +25 -73
- package/dist/chunks/archive-DFi3qK1c.js.map +1 -0
- package/dist/chunks/{atomic-C1PfJpE7.js → atomic-SZUwDtGD.js} +3 -6
- package/dist/chunks/atomic-SZUwDtGD.js.map +1 -0
- package/dist/chunks/{backup-CZcVca2a.js → backup-DnyxIzw0.js} +110 -190
- package/dist/chunks/backup-DnyxIzw0.js.map +1 -0
- package/dist/chunks/backups-BrrN6cwW.js +2203 -0
- package/dist/chunks/backups-BrrN6cwW.js.map +1 -0
- package/dist/chunks/bind-DIxrnUst.js +43 -0
- package/dist/chunks/bind-DIxrnUst.js.map +1 -0
- package/dist/chunks/config-text-DxMOQQnk.js +34 -0
- package/dist/chunks/config-text-DxMOQQnk.js.map +1 -0
- package/dist/chunks/{contracts-CMBD1TF9.js → contracts-CxZ7u1L3.js} +1239 -1454
- package/dist/chunks/contracts-CxZ7u1L3.js.map +1 -0
- package/dist/chunks/daemon-BAAYUYQC.js +211 -0
- package/dist/chunks/daemon-BAAYUYQC.js.map +1 -0
- package/dist/chunks/daemon-log-Ccu-69vB.js +179 -0
- package/dist/chunks/daemon-log-Ccu-69vB.js.map +1 -0
- package/dist/chunks/deploy-CggSOEkq.js +144 -0
- package/dist/chunks/deploy-CggSOEkq.js.map +1 -0
- package/dist/chunks/{docker-Cy9Lyvda.js → docker--Un0uLfF.js} +32 -68
- package/dist/chunks/docker--Un0uLfF.js.map +1 -0
- package/dist/chunks/{down-pKbGCW9d.js → down-CpIN7LEQ.js} +34 -94
- package/dist/chunks/down-CpIN7LEQ.js.map +1 -0
- package/dist/chunks/exposure-CDJNvOCK.js +229 -0
- package/dist/chunks/exposure-CDJNvOCK.js.map +1 -0
- package/dist/chunks/import-Bd4VZH0f.js +205 -0
- package/dist/chunks/import-Bd4VZH0f.js.map +1 -0
- package/dist/chunks/import-plan--fDS_l5r.js +147 -0
- package/dist/chunks/import-plan--fDS_l5r.js.map +1 -0
- package/dist/chunks/import-write-BTfbeV26.js +42 -0
- package/dist/chunks/import-write-BTfbeV26.js.map +1 -0
- package/dist/chunks/{init-BZ7hK9Vf.js → init-Bv3oH65x.js} +14 -50
- package/dist/chunks/init-Bv3oH65x.js.map +1 -0
- package/dist/chunks/job-CYOdN6Ub.js +341 -0
- package/dist/chunks/job-CYOdN6Ub.js.map +1 -0
- package/dist/chunks/jobs-BX4ahcfh.js +489 -0
- package/dist/chunks/jobs-BX4ahcfh.js.map +1 -0
- package/dist/chunks/last-stop-DD3lHwo_.js +42 -0
- package/dist/chunks/last-stop-DD3lHwo_.js.map +1 -0
- package/dist/chunks/layout-D0ysDNav.js +18 -0
- package/dist/chunks/layout-D0ysDNav.js.map +1 -0
- package/dist/chunks/lazy-kfcBNeqj.js +48 -0
- package/dist/chunks/lazy-kfcBNeqj.js.map +1 -0
- package/dist/chunks/log-buffer-B7jmn7ts.js +110 -0
- package/dist/chunks/log-buffer-B7jmn7ts.js.map +1 -0
- package/dist/chunks/log-files-CZL2UhuE.js +488 -0
- package/dist/chunks/log-files-CZL2UhuE.js.map +1 -0
- package/dist/chunks/{logger-B5U4GD3j.js → logger-BnrKTBHQ.js} +2 -6
- package/dist/chunks/logger-BnrKTBHQ.js.map +1 -0
- package/dist/chunks/{logs---TI_bxM.js → logs-DxKI6OW2.js} +23 -73
- package/dist/chunks/logs-DxKI6OW2.js.map +1 -0
- package/dist/chunks/ls-BseUHy_m.js +128 -0
- package/dist/chunks/ls-BseUHy_m.js.map +1 -0
- package/dist/chunks/migrate-D4w_dXDm.js +268 -0
- package/dist/chunks/migrate-D4w_dXDm.js.map +1 -0
- package/dist/chunks/{nanny-B-Eu0sFW.js → nanny-BWh7nuvv.js} +21 -14
- package/dist/chunks/nanny-BWh7nuvv.js.map +1 -0
- package/dist/chunks/{nanny-ChMtq1Zl.js → nanny-BjF2-1pv.js} +3 -3
- package/dist/chunks/{nanny-ChMtq1Zl.js.map → nanny-BjF2-1pv.js.map} +1 -1
- package/dist/chunks/nanny-DGTXVq5d.js +806 -0
- package/dist/chunks/nanny-DGTXVq5d.js.map +1 -0
- package/dist/chunks/{nanny-sweep-DErnlPY1.js → nanny-sweep-hjmZ_p7S.js} +14 -24
- package/dist/chunks/nanny-sweep-hjmZ_p7S.js.map +1 -0
- package/dist/chunks/{nearest-6KgQEDUe.js → nearest-DOx4jySJ.js} +2 -10
- package/dist/chunks/nearest-DOx4jySJ.js.map +1 -0
- package/dist/chunks/{parse-DhmG26fI.js → parse-DVMPLUDe.js} +47 -72
- package/dist/chunks/parse-DVMPLUDe.js.map +1 -0
- package/dist/chunks/password-policy-Clq6PGE-.js +9 -0
- package/dist/chunks/password-policy-Clq6PGE-.js.map +1 -0
- package/dist/chunks/{paths-CGlGDrOU.js → paths-C34-TJLh.js} +32 -56
- package/dist/chunks/paths-C34-TJLh.js.map +1 -0
- package/dist/chunks/{port-B8WBTRMk.js → port-CnsrxKNR.js} +27 -71
- package/dist/chunks/port-CnsrxKNR.js.map +1 -0
- package/dist/chunks/process-CboOFPU_.js +192 -0
- package/dist/chunks/process-CboOFPU_.js.map +1 -0
- package/dist/chunks/{restart-Des4DrAN.js → restart-C0J8dZ2L.js} +11 -29
- package/dist/chunks/restart-C0J8dZ2L.js.map +1 -0
- package/dist/chunks/run-deploy-DoNDvwT4.js +91 -0
- package/dist/chunks/run-deploy-DoNDvwT4.js.map +1 -0
- package/dist/chunks/{schema-B240VXcV.js → schema-CZ6f-PHD.js} +7 -20
- package/dist/chunks/schema-CZ6f-PHD.js.map +1 -0
- package/dist/chunks/secret-MY397r90.js +219 -0
- package/dist/chunks/secret-MY397r90.js.map +1 -0
- package/dist/chunks/secrets-CG5N4lwY.js +1061 -0
- package/dist/chunks/secrets-CG5N4lwY.js.map +1 -0
- package/dist/chunks/server-Dm_dXfTW.js +255 -0
- package/dist/chunks/server-Dm_dXfTW.js.map +1 -0
- package/dist/chunks/server-attention-UQwYXqKe.js +10 -0
- package/dist/chunks/server-attention-UQwYXqKe.js.map +1 -0
- package/dist/chunks/server-create-D7nvhgBd.js +96 -0
- package/dist/chunks/server-create-D7nvhgBd.js.map +1 -0
- package/dist/chunks/server-ids-BEQD2rFz.js +23 -0
- package/dist/chunks/server-ids-BEQD2rFz.js.map +1 -0
- package/dist/chunks/server-vars-DMYmHutL.js +27 -0
- package/dist/chunks/server-vars-DMYmHutL.js.map +1 -0
- package/dist/chunks/service-C8l-ewNA.js +585 -0
- package/dist/chunks/service-C8l-ewNA.js.map +1 -0
- package/dist/chunks/{settings-xu-XTfWg.js → settings-CtYDs5PX.js} +62 -78
- package/dist/chunks/settings-CtYDs5PX.js.map +1 -0
- package/dist/chunks/{setup-temp-CAN4_bA-.js → setup-temp-TAtDmMMU.js} +43 -37
- package/dist/chunks/setup-temp-TAtDmMMU.js.map +1 -0
- package/dist/chunks/shape-CDGeYl_J.js +9 -0
- package/dist/chunks/shape-CDGeYl_J.js.map +1 -0
- package/dist/chunks/{src-BtWMFmzZ.js → src-BnzkVy_M.js} +12548 -10576
- package/dist/chunks/src-BnzkVy_M.js.map +1 -0
- package/dist/chunks/{status-DT1EsA-B.js → status-efbbfYZQ.js} +53 -26
- package/dist/chunks/status-efbbfYZQ.js.map +1 -0
- package/dist/chunks/store-Bs_Lljjm.js +2082 -0
- package/dist/chunks/store-Bs_Lljjm.js.map +1 -0
- package/dist/chunks/template-xan58bJh.js +28 -0
- package/dist/chunks/template-xan58bJh.js.map +1 -0
- package/dist/chunks/token-DDeWfZA4.js +142 -0
- package/dist/chunks/token-DDeWfZA4.js.map +1 -0
- package/dist/chunks/{ui-D562aqw5.js → ui-BcIAtyxE.js} +68 -79
- package/dist/chunks/ui-BcIAtyxE.js.map +1 -0
- package/dist/chunks/{ui-dir-CsU3uLNV.js → ui-dir-ClCzVRc3.js} +3 -7
- package/dist/chunks/ui-dir-ClCzVRc3.js.map +1 -0
- package/dist/chunks/ui-format-CDvvqOoi.js +53 -0
- package/dist/chunks/ui-format-CDvvqOoi.js.map +1 -0
- package/dist/chunks/{ui-release-DKzVvlLd.js → ui-release-XbJ85pYI.js} +36 -38
- package/dist/chunks/ui-release-XbJ85pYI.js.map +1 -0
- package/dist/chunks/{ui-revert-EkBBwRTt.js → ui-revert-Dgawq7ze.js} +4 -4
- package/dist/chunks/ui-revert-Dgawq7ze.js.map +1 -0
- package/dist/chunks/{ui-switch-BnZTdMDd.js → ui-switch-CfQMbZ0g.js} +31 -38
- package/dist/chunks/ui-switch-CfQMbZ0g.js.map +1 -0
- package/dist/chunks/{ui-update-_xryLYxw.js → ui-update-B3PPivUm.js} +30 -48
- package/dist/chunks/ui-update-B3PPivUm.js.map +1 -0
- package/dist/chunks/ui-update-CAiH2tFb.js +109 -0
- package/dist/chunks/ui-update-CAiH2tFb.js.map +1 -0
- package/dist/chunks/{up-Pdz-l6IH.js → up-BQSnYxYd.js} +47 -53
- package/dist/chunks/up-BQSnYxYd.js.map +1 -0
- package/dist/chunks/{usage-DFrCVXpT.js → usage-KG8TeOio.js} +7 -20
- package/dist/chunks/usage-KG8TeOio.js.map +1 -0
- package/dist/chunks/{workspaces-DYcfvKV_.js → workspaces-D9akpzU8.js} +80 -68
- package/dist/chunks/workspaces-D9akpzU8.js.map +1 -0
- package/dist/chunks/{wsl-temperature-BiCI4iK6.js → wsl-temperature-D-_d4Yk1.js} +47 -42
- package/dist/chunks/wsl-temperature-D-_d4Yk1.js.map +1 -0
- package/dist/cli.js +306 -238
- package/dist/cli.js.map +1 -1
- package/dist/client.js +76 -29
- package/dist/client.js.map +1 -1
- package/dist/types/api/acme.d.ts +3 -7
- package/dist/types/api/auth/$.routes.d.ts +107 -16
- package/dist/types/api/backups.d.ts +5 -5
- package/dist/types/api/control.d.ts +747 -38
- package/dist/types/api/ddns.d.ts +13 -18
- package/dist/types/api/events.d.ts +9 -3
- package/dist/types/api/health.d.ts +2 -4
- package/dist/types/api/jobs.d.ts +438 -0
- package/dist/types/api/logs.d.ts +20 -0
- package/dist/types/api/metrics.d.ts +2 -5
- package/dist/types/api/notifications.d.ts +3 -6
- package/dist/types/api/proxy.d.ts +63 -23
- package/dist/types/api/server-ops.d.ts +17 -0
- package/dist/types/api/servers/$.routes.d.ts +418 -186
- package/dist/types/api/session-required.d.ts +16 -0
- package/dist/types/api/settings.d.ts +7 -7
- package/dist/types/api/state.d.ts +100 -10
- package/dist/types/api/static.d.ts +2 -2
- package/dist/types/api/tls.d.ts +2 -5
- package/dist/types/api/workspaces/$.routes.d.ts +186 -12
- package/dist/types/api/wsl-temperature.d.ts +4 -10
- package/dist/types/app.d.ts +4511 -2778
- package/dist/types/cli/account.d.ts +23 -0
- package/dist/types/cli/add.d.ts +96 -0
- package/dist/types/cli/args.d.ts +24 -35
- package/dist/types/cli/backup-offline.d.ts +2 -8
- package/dist/types/cli/backup.d.ts +12 -21
- package/dist/types/cli/down.d.ts +15 -41
- package/dist/types/cli/import-plan.d.ts +55 -0
- package/dist/types/cli/import-write.d.ts +5 -0
- package/dist/types/cli/import.d.ts +86 -0
- package/dist/types/cli/io.d.ts +26 -35
- package/dist/types/cli/job.d.ts +99 -0
- package/dist/types/cli/logs.d.ts +1 -10
- package/dist/types/cli/ls.d.ts +57 -0
- package/dist/types/cli/migrate.d.ts +31 -8
- package/dist/types/cli/nearest.d.ts +1 -9
- package/dist/types/cli/run-deploy.d.ts +36 -0
- package/dist/types/cli/secret.d.ts +90 -0
- package/dist/types/cli/server.d.ts +6 -15
- package/dist/types/cli/service.d.ts +135 -0
- package/dist/types/cli/setup-temp.d.ts +17 -13
- package/dist/types/cli/status.d.ts +7 -1
- package/dist/types/cli/token.d.ts +6 -0
- package/dist/types/cli/ui-switch.d.ts +3 -14
- package/dist/types/cli/ui-update.d.ts +3 -16
- package/dist/types/cli/up.d.ts +9 -22
- package/dist/types/cli/usage.d.ts +2 -6
- package/dist/types/cli.d.ts +1 -10
- package/dist/types/client.d.ts +4099 -1142
- package/dist/types/config/accounts.d.ts +16 -0
- package/dist/types/config/jobs.d.ts +68 -0
- package/dist/types/config/layout.d.ts +2 -8
- package/dist/types/config/migrations.d.ts +9 -41
- package/dist/types/config/parse.d.ts +8 -13
- package/dist/types/config/patch.d.ts +1 -6
- package/dist/types/config/schema.d.ts +16 -18
- package/dist/types/config/secret-parts.d.ts +6 -27
- package/dist/types/config/secrets.d.ts +167 -88
- package/dist/types/config/seed.d.ts +1 -6
- package/dist/types/config/server-ids.d.ts +2 -11
- package/dist/types/config/settings.d.ts +13 -49
- package/dist/types/config/store.d.ts +17 -54
- package/dist/types/config/workspaces.d.ts +24 -56
- package/dist/types/helpers/action-result.d.ts +18 -32
- package/dist/types/helpers/atomic.d.ts +1 -4
- package/dist/types/helpers/backoff.d.ts +0 -1
- package/dist/types/helpers/bind.d.ts +3 -11
- package/dist/types/helpers/config-text.d.ts +4 -19
- package/dist/types/helpers/cookies.d.ts +2 -7
- package/dist/types/helpers/copy-tree.d.ts +4 -12
- package/dist/types/helpers/daemon-log.d.ts +8 -33
- package/dist/types/helpers/daemon.d.ts +20 -70
- package/dist/types/helpers/deferred.d.ts +2 -4
- package/dist/types/helpers/env-file.d.ts +2 -7
- package/dist/types/helpers/error.d.ts +3 -14
- package/dist/types/helpers/event-stream.d.ts +18 -10
- package/dist/types/helpers/factory.d.ts +2 -3
- package/dist/types/helpers/last-stop.d.ts +5 -12
- package/dist/types/helpers/logger.d.ts +1 -5
- package/dist/types/helpers/open.d.ts +0 -1
- package/dist/types/helpers/openapi.d.ts +19 -5
- package/dist/types/helpers/paths.d.ts +18 -53
- package/dist/types/helpers/restore-lock.d.ts +2 -17
- package/dist/types/helpers/runtime.d.ts +3 -13
- package/dist/types/helpers/secret-compare.d.ts +2 -10
- package/dist/types/helpers/server-create.d.ts +15 -0
- package/dist/types/helpers/shell.d.ts +2 -16
- package/dist/types/helpers/sse.d.ts +8 -6
- package/dist/types/helpers/ui-dir.d.ts +1 -5
- package/dist/types/helpers/utf8-chunks.d.ts +2 -8
- package/dist/types/helpers/validate.d.ts +2 -4
- package/dist/types/helpers/validator.d.ts +8 -4
- package/dist/types/helpers/version.d.ts +1 -6
- package/dist/types/helpers/workspace.d.ts +24 -16
- package/dist/types/index.d.ts +2 -3
- package/dist/types/middleware/auth.d.ts +8 -27
- package/dist/types/middleware/body-limit.d.ts +10 -0
- package/dist/types/middleware/host.d.ts +4 -23
- package/dist/types/middleware/loopback.d.ts +1 -8
- package/dist/types/middleware/token-scope.d.ts +34 -0
- package/dist/types/node-compat.d.ts +43 -0
- package/dist/types/openapi-reference.d.ts +4 -19
- package/dist/types/openapi.d.ts +5 -8
- package/dist/types/providers/archive.d.ts +8 -25
- package/dist/types/providers/backup-hook.d.ts +4 -19
- package/dist/types/providers/ddns/dyndns2.d.ts +0 -3
- package/dist/types/providers/ddns/index.d.ts +2 -3
- package/dist/types/providers/ddns/ip.d.ts +2 -12
- package/dist/types/providers/ddns/namecheap-api.d.ts +3 -2
- package/dist/types/providers/ddns/types.d.ts +6 -32
- package/dist/types/providers/ddns/zone.d.ts +1 -4
- package/dist/types/providers/docker.d.ts +18 -45
- package/dist/types/providers/entry-state.d.ts +4 -9
- package/dist/types/providers/health-check.d.ts +1 -5
- package/dist/types/providers/host.d.ts +33 -108
- package/dist/types/providers/identity.d.ts +9 -34
- package/dist/types/providers/log-tail.d.ts +14 -24
- package/dist/types/providers/nanny-sweep.d.ts +8 -25
- package/dist/types/providers/nanny.d.ts +16 -58
- package/dist/types/providers/port.d.ts +28 -83
- package/dist/types/providers/proc.d.ts +22 -80
- package/dist/types/providers/process.d.ts +12 -36
- package/dist/types/providers/proxy/admin.d.ts +11 -0
- package/dist/types/providers/proxy/types.d.ts +4 -16
- package/dist/types/providers/telegram.d.ts +1 -17
- package/dist/types/providers/ui-release.d.ts +15 -25
- package/dist/types/providers/webhook.d.ts +8 -29
- package/dist/types/providers/wsl-temperature.d.ts +13 -22
- package/dist/types/services/acme-challenge.d.ts +2 -16
- package/dist/types/services/auth.d.ts +65 -80
- package/dist/types/services/backups/archive-safety.d.ts +30 -0
- package/dist/types/services/backups/paths.d.ts +31 -0
- package/dist/types/services/backups.d.ts +61 -271
- package/dist/types/services/config-watch.d.ts +3 -15
- package/dist/types/services/control-server.d.ts +6 -10
- package/dist/types/services/ddns.d.ts +12 -13
- package/dist/types/services/dependencies.d.ts +3 -14
- package/dist/types/services/deploy.d.ts +34 -0
- package/dist/types/services/events.d.ts +15 -9
- package/dist/types/services/exposure.d.ts +13 -63
- package/dist/types/services/history.d.ts +5 -14
- package/dist/types/services/host-monitor.d.ts +6 -11
- package/dist/types/services/init.d.ts +5 -35
- package/dist/types/services/job-ledger.d.ts +27 -0
- package/dist/types/services/jobs.d.ts +113 -0
- package/dist/types/services/log-buffer.d.ts +7 -8
- package/dist/types/services/log-files.d.ts +12 -42
- package/dist/types/services/log-relay.d.ts +3 -13
- package/dist/types/services/nanny.d.ts +3 -10
- package/dist/types/services/notifications.d.ts +31 -61
- package/dist/types/services/panel.d.ts +32 -78
- package/dist/types/services/proxy-certificates/certificates.d.ts +31 -69
- package/dist/types/services/proxy-config.d.ts +15 -36
- package/dist/types/services/proxy-dns01.d.ts +14 -0
- package/dist/types/services/proxy.d.ts +73 -254
- package/dist/types/services/scheduler.d.ts +46 -0
- package/dist/types/services/state.d.ts +17 -8
- package/dist/types/services/supervisor/compose.d.ts +2 -6
- package/dist/types/services/supervisor/entry.d.ts +29 -32
- package/dist/types/services/supervisor/health.d.ts +8 -31
- package/dist/types/services/supervisor/job-run.d.ts +36 -0
- package/dist/types/services/supervisor/output.d.ts +13 -77
- package/dist/types/services/supervisor/persistent.d.ts +5 -11
- package/dist/types/services/supervisor/port-preflight.d.ts +4 -10
- package/dist/types/services/supervisor/records.d.ts +27 -60
- package/dist/types/services/supervisor/restart-required.d.ts +13 -0
- package/dist/types/services/supervisor/spawn.d.ts +3 -5
- package/dist/types/services/supervisor/view.d.ts +3 -1
- package/dist/types/services/supervisor.d.ts +31 -43
- package/dist/types/services/tls.d.ts +6 -17
- package/dist/types/services/ui-update.d.ts +19 -17
- package/dist/types/services/ui.d.ts +10 -19
- package/dist/types/shared/action-outcome.d.ts +2 -7
- package/dist/types/shared/api-client.d.ts +133 -177
- package/dist/types/shared/api-scopes.d.ts +17 -0
- package/dist/types/shared/backup-scope.d.ts +16 -90
- package/dist/types/shared/clone.d.ts +2 -11
- package/dist/types/shared/contracts/accounts.d.ts +99 -0
- package/dist/types/shared/contracts/backups.d.ts +219 -0
- package/dist/types/shared/contracts/ddns.d.ts +208 -0
- package/dist/types/shared/contracts/frames.d.ts +1395 -0
- package/dist/types/shared/contracts/index.d.ts +3 -0
- package/dist/types/shared/contracts/logs.d.ts +107 -0
- package/dist/types/shared/contracts/proxy.d.ts +303 -0
- package/dist/types/shared/contracts.d.ts +852 -1982
- package/dist/types/shared/cpu-scale.d.ts +3 -19
- package/dist/types/shared/crash-cause.d.ts +8 -0
- package/dist/types/shared/cron.d.ts +70 -0
- package/dist/types/shared/ddns-form.d.ts +9 -43
- package/dist/types/shared/endpoint.d.ts +1 -7
- package/dist/types/shared/error-codes.d.ts +438 -0
- package/dist/types/shared/error-message.d.ts +1 -7
- package/dist/types/shared/fields.d.ts +7 -17
- package/dist/types/shared/form-repair.d.ts +1 -5
- package/dist/types/shared/generated.d.ts +3 -19
- package/dist/types/shared/host-readings.d.ts +25 -128
- package/dist/types/shared/lazy.d.ts +1 -1
- package/dist/types/shared/live-frames.d.ts +2 -8
- package/dist/types/shared/live-series.d.ts +2 -8
- package/dist/types/shared/live-store.d.ts +4 -8
- package/dist/types/shared/log-download.d.ts +6 -0
- package/dist/types/shared/meta.d.ts +6 -0
- package/dist/types/shared/password-policy.d.ts +10 -0
- package/dist/types/shared/patch-diff.d.ts +13 -72
- package/dist/types/shared/port-reading.d.ts +18 -0
- package/dist/types/shared/probe-latency.d.ts +3 -21
- package/dist/types/shared/proxy-form.d.ts +33 -74
- package/dist/types/shared/proxy-validate.d.ts +11 -0
- package/dist/types/shared/query-params.d.ts +8 -0
- package/dist/types/shared/server-attention.d.ts +2 -27
- package/dist/types/shared/server-form.d.ts +15 -54
- package/dist/types/shared/server-key.d.ts +1 -12
- package/dist/types/shared/server-readings.d.ts +7 -32
- package/dist/types/shared/server-url.d.ts +9 -31
- package/dist/types/shared/shape.d.ts +1 -16
- package/dist/types/shared/stream-access.d.ts +2 -8
- package/dist/types/shared/ui-format.d.ts +25 -65
- package/docs/API.md +315 -107
- package/docs/BACKUPS.md +61 -56
- package/docs/CLI.md +255 -49
- package/docs/DDNS.md +35 -49
- package/docs/JOBS.md +129 -0
- package/docs/NOTIFICATIONS.md +58 -90
- package/docs/REVERSE_PROXY.md +116 -188
- package/docs/SECURITY.md +126 -44
- package/docs/SERVERS.md +282 -409
- package/docs/UI_CREATION.md +90 -47
- package/docs/demo/blank-host-restore.sh +31 -7
- package/package.json +15 -6
- package/scripts/prepare.mjs +47 -0
- package/uis/stock/dist/assets/CopyButton-8mliL0xi.js +1 -0
- package/uis/stock/dist/assets/GlobalSettingsView-BINXY77E.js +1 -0
- package/uis/stock/dist/assets/LogViewer-kiSnTwdY.js +1 -0
- package/uis/stock/dist/assets/LogsView-DDXf_ONs.js +1 -0
- package/uis/stock/dist/assets/Modal-lrUuViF2.js +39 -0
- package/uis/stock/dist/assets/ProxyView-uXMaJdSQ.js +1 -0
- package/uis/stock/dist/assets/ServerDetailView-CW0Vb_c0.js +4 -0
- package/uis/stock/dist/assets/SettingsShell-B135xWjJ.js +1 -0
- package/uis/stock/dist/assets/SettingsView-BLtWxVkl.js +2 -0
- package/uis/stock/dist/assets/de-BIoTrHBQ.js +1 -0
- package/uis/stock/dist/assets/es-x4-ih8lH.js +1 -0
- package/uis/stock/dist/assets/fr-DatqBBkO.js +1 -0
- package/uis/stock/dist/assets/index-CnojaKcA.css +2 -0
- package/uis/stock/dist/assets/index-D-CiZReu.js +16 -0
- package/uis/stock/dist/assets/ja-CW1703Gw.js +1 -0
- package/uis/stock/dist/assets/ko-wFbT4XtK.js +1 -0
- package/uis/stock/dist/assets/ru-C1p5C4VN.js +1 -0
- package/uis/stock/dist/assets/useUnsavedGuard-BcsXsfCC.js +9 -0
- package/uis/stock/dist/assets/vi-CDqr0uie.js +1 -0
- package/uis/stock/dist/assets/zh-CN-BJ7iit-X.js +1 -0
- package/uis/stock/dist/index.html +4 -3
- package/uis/stock/dist/ui.json +3 -3
- package/dist/chunks/archive-DP-XQR8X.js.map +0 -1
- package/dist/chunks/atomic-C1PfJpE7.js.map +0 -1
- package/dist/chunks/backup-CZcVca2a.js.map +0 -1
- package/dist/chunks/backups-CFRaWe_m.js +0 -4691
- package/dist/chunks/backups-CFRaWe_m.js.map +0 -1
- package/dist/chunks/config-text-DifCHhnz.js +0 -50
- package/dist/chunks/config-text-DifCHhnz.js.map +0 -1
- package/dist/chunks/contracts-CMBD1TF9.js.map +0 -1
- package/dist/chunks/daemon-log-BVj8cDEo.js +0 -241
- package/dist/chunks/daemon-log-BVj8cDEo.js.map +0 -1
- package/dist/chunks/daemon-qKVECISl.js +0 -247
- package/dist/chunks/daemon-qKVECISl.js.map +0 -1
- package/dist/chunks/docker-Cy9Lyvda.js.map +0 -1
- package/dist/chunks/down-pKbGCW9d.js.map +0 -1
- package/dist/chunks/init-BZ7hK9Vf.js.map +0 -1
- package/dist/chunks/last-stop-C-BXz_XI.js +0 -53
- package/dist/chunks/last-stop-C-BXz_XI.js.map +0 -1
- package/dist/chunks/layout-DwTtmund.js +0 -24
- package/dist/chunks/layout-DwTtmund.js.map +0 -1
- package/dist/chunks/lazy-Ce5zEAq1.js +0 -66
- package/dist/chunks/lazy-Ce5zEAq1.js.map +0 -1
- package/dist/chunks/log-buffer-Dy9HHDMD.js +0 -414
- package/dist/chunks/log-buffer-Dy9HHDMD.js.map +0 -1
- package/dist/chunks/logger-B5U4GD3j.js.map +0 -1
- package/dist/chunks/logs---TI_bxM.js.map +0 -1
- package/dist/chunks/migrate-Cfoq-Vgh.js +0 -155
- package/dist/chunks/migrate-Cfoq-Vgh.js.map +0 -1
- package/dist/chunks/nanny-B-Eu0sFW.js.map +0 -1
- package/dist/chunks/nanny-BtWfy0QH.js +0 -1167
- package/dist/chunks/nanny-BtWfy0QH.js.map +0 -1
- package/dist/chunks/nanny-sweep-DErnlPY1.js.map +0 -1
- package/dist/chunks/nearest-6KgQEDUe.js.map +0 -1
- package/dist/chunks/parse-DhmG26fI.js.map +0 -1
- package/dist/chunks/paths-CGlGDrOU.js.map +0 -1
- package/dist/chunks/port-B8WBTRMk.js.map +0 -1
- package/dist/chunks/restart-Des4DrAN.js.map +0 -1
- package/dist/chunks/schema-B240VXcV.js.map +0 -1
- package/dist/chunks/secrets-BieELnZh.js +0 -562
- package/dist/chunks/secrets-BieELnZh.js.map +0 -1
- package/dist/chunks/server-Bge2r2qQ.js +0 -169
- package/dist/chunks/server-Bge2r2qQ.js.map +0 -1
- package/dist/chunks/server-ids-DRuNLVCV.js +0 -32
- package/dist/chunks/server-ids-DRuNLVCV.js.map +0 -1
- package/dist/chunks/set-password-D5vZqqSX.js +0 -43
- package/dist/chunks/set-password-D5vZqqSX.js.map +0 -1
- package/dist/chunks/set-token-obPiEJYk.js +0 -78
- package/dist/chunks/set-token-obPiEJYk.js.map +0 -1
- package/dist/chunks/settings-xu-XTfWg.js.map +0 -1
- package/dist/chunks/setup-temp-CAN4_bA-.js.map +0 -1
- package/dist/chunks/shape-DnTKzjQ2.js +0 -24
- package/dist/chunks/shape-DnTKzjQ2.js.map +0 -1
- package/dist/chunks/src-BtWMFmzZ.js.map +0 -1
- package/dist/chunks/status-DT1EsA-B.js.map +0 -1
- package/dist/chunks/ui-D562aqw5.js.map +0 -1
- package/dist/chunks/ui-dir-CsU3uLNV.js.map +0 -1
- package/dist/chunks/ui-release-DKzVvlLd.js.map +0 -1
- package/dist/chunks/ui-revert-EkBBwRTt.js.map +0 -1
- package/dist/chunks/ui-switch-BnZTdMDd.js.map +0 -1
- package/dist/chunks/ui-update-_xryLYxw.js.map +0 -1
- package/dist/chunks/up-Pdz-l6IH.js.map +0 -1
- package/dist/chunks/usage-DFrCVXpT.js.map +0 -1
- package/dist/chunks/workspaces-DYcfvKV_.js.map +0 -1
- package/dist/chunks/wsl-temperature-BiCI4iK6.js.map +0 -1
- package/dist/types/cli/set-password.d.ts +0 -14
- package/dist/types/cli/set-token.d.ts +0 -21
- package/uis/stock/dist/assets/CopyButton-BUBKRJyY.js +0 -1
- package/uis/stock/dist/assets/GlobalSettingsView-yYMcRWvt.js +0 -1
- package/uis/stock/dist/assets/LogViewer-DIliXy62.js +0 -1
- package/uis/stock/dist/assets/LogsView-B7Z-7RNg.js +0 -1
- package/uis/stock/dist/assets/Modal-DmKa5Qpp.js +0 -39
- package/uis/stock/dist/assets/ProxyView-DvZiNkwb.js +0 -1
- package/uis/stock/dist/assets/ServerDetailView-6idGT_EX.js +0 -2
- package/uis/stock/dist/assets/SettingsShell-CeGtleYI.js +0 -1
- package/uis/stock/dist/assets/SettingsView-BrhJIrmk.js +0 -2
- package/uis/stock/dist/assets/de-BRITeb0H.js +0 -1
- package/uis/stock/dist/assets/es-B2zIEssV.js +0 -1
- package/uis/stock/dist/assets/fr-s0ZOBEqh.js +0 -1
- package/uis/stock/dist/assets/index-C1MehbKy.css +0 -2
- package/uis/stock/dist/assets/index-CnBN54wF.js +0 -15
- package/uis/stock/dist/assets/ja-CU7MR85V.js +0 -1
- package/uis/stock/dist/assets/ko-tL5Me6d-.js +0 -1
- package/uis/stock/dist/assets/ru-92yrvkNJ.js +0 -1
- package/uis/stock/dist/assets/vi-CzvY16k2.js +0 -1
- package/uis/stock/dist/assets/zh-CN-DDwFW_uW.js +0 -1
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"backups-BrrN6cwW.js","names":[],"sources":["../../src/providers/entry-state.ts","../../src/config/secret-parts.ts","../../src/helpers/restore-lock.ts","../../src/providers/backup-hook.ts","../../src/services/backups/archive-safety.ts","../../src/services/backups/paths.ts","../../src/shared/backup-scope.ts","../../src/shared/generated.ts","../../src/services/backups.ts"],"sourcesContent":["import type { EntryState } from '#src/shared/contracts'\nimport fs from 'node:fs'\nimport path from 'node:path'\nimport { type } from 'arktype'\nimport { writeFileAtomic } from '#src/helpers/atomic'\nimport { logger } from '#src/helpers/logger'\nimport { entryStateSchema } from '#src/shared/contracts'\n\n/**\n * The runtime the panel must remember across its own restarts: the spent retry budget and whether a\n * `runOnce` bootstrap ran. In memory only, a restart reset a crash loop's `maxRetries`.\n */\n\nexport function entryStatePath(dir: string, id: string): string {\n return path.join(dir, `${id}.run.json`)\n}\n\nexport function readEntryState(file: string): EntryState | null {\n try {\n const parsed = entryStateSchema(JSON.parse(fs.readFileSync(file, 'utf8')))\n return parsed instanceof type.errors ? null : parsed\n }\n catch {\n return null\n }\n}\n\n/** `path:code` pairs already warned about, so a read-only disk logs once per file, not once per save. */\nconst warned = new Set<string>()\n\n/** Best effort, like history: no state file must never stop supervision. False when the write failed. */\nexport function writeEntryState(file: string, state: EntryState): boolean {\n try {\n writeFileAtomic(file, `${JSON.stringify(state)}\\n`)\n return true\n }\n catch (error) {\n const code = (error as NodeJS.ErrnoException).code ?? 'unknown'\n const key = `${file}:${code}`\n if (!warned.has(key)) {\n warned.add(key)\n logger.warn(`could not save ${path.basename(file)} (${code}): the retry budget and pending load will not survive a panel restart`)\n }\n return false\n }\n}\n\nexport function clearEntryState(file: string): void {\n fs.rmSync(file, { force: true })\n}\n","import { isRecord } from '#src/shared/shape'\n\nexport type SecretScope = 'global' | 'workspace'\n\nexport interface SecretPart {\n /** The leaf id: `password`, `apiToken`, `telegram` (bot tokens by destination), `ddns`, or a future top-level key. */\n key: string\n /** The top-level file keys this part carries. `ddns` carries `['ddns', 'ddnsKdf']`. */\n fields: string[]\n scope: SecretScope\n}\n\n/** Every secret this release knows about, set or not — the view lists the slots so a person sees one. */\nexport const KNOWN_SECRET_KEYS: Record<SecretScope, string[]> = {\n global: ['password', 'apiToken'],\n workspace: ['telegram', 'ddns'],\n}\n\n/** Where a secret this release knows lives. Everything else is scoped by its own file. */\nconst KNOWN_SCOPES: Record<string, SecretScope> = {\n password: 'global',\n apiToken: 'global',\n telegram: 'workspace',\n ddns: 'workspace',\n}\n\n/** A part carrying more than its own key: `ddnsKdf` is how the sealed DDNS entries are opened. */\nconst EXTRA_FIELDS: Record<string, string[]> = { ddns: ['ddns', 'ddnsKdf'] }\n\n/**\n * The parts of one scope: known parts first in a fixed order, then any other key present, sorted.\n * An unknown key belongs to the scope asked about, since its file is the only evidence of where it lives.\n */\nexport function secretParts(scope: SecretScope, present: string[]): SecretPart[] {\n const keys = new Set(present)\n const known = KNOWN_SECRET_KEYS[scope]\n const parts = known\n .filter(key => keys.has(key))\n .map(key => ({ key, fields: EXTRA_FIELDS[key] ?? [key], scope }))\n // A key another part carries (`ddnsKdf`) is offered alone only when its owner is missing.\n const consumed = new Set(parts.flatMap(part => part.fields))\n const rest = [...keys]\n .filter(key => KNOWN_SCOPES[key] === undefined && !known.includes(key) && !consumed.has(key))\n .sort()\n return [...parts, ...rest.map(key => ({ key, fields: [key], scope }))]\n}\n\n/** Collections a fresh secrets file carries empty; empty, they hold nothing to back up or restore. */\nconst COLLECTION_KEYS = new Set(['accounts', 'apiTokens', 'serverEnv', 'jobEnv'])\n\nexport function presentSecretKeys(source: Record<string, unknown>): string[] {\n return Object.entries(source)\n .filter(([key, value]) => {\n if (value === null || value === undefined)\n return false\n if (!COLLECTION_KEYS.has(key))\n return true\n return Array.isArray(value) ? value.length > 0 : !isRecord(value) || Object.keys(value).length > 0\n })\n .map(([key]) => key)\n}\n\n/** A JSON string carrying only the non-null `fields` of `source`, or null when it carries none. */\nexport function pickSecrets(source: Record<string, unknown>, fields: string[]): string | null {\n const picked: Record<string, unknown> = {}\n for (const field of fields) {\n const value = source[field]\n if (value !== null && value !== undefined)\n picked[field] = withoutFirstRunPassword(value)\n }\n return Object.keys(picked).length === 0 ? null : JSON.stringify(picked)\n}\n\n/** Drops `password.initial`: an archive leaves the box, and the hash alone restores the password. */\nfunction withoutFirstRunPassword(value: unknown): unknown {\n if (!isRecord(value) || !('initial' in value))\n return value\n const { initial: _initial, ...rest } = value\n return rest\n}\n\n/** The same removal over a whole secrets document; `null` when the text is not a JSON object. */\nexport function withoutInitialPassword(text: string): string | null {\n let parsed: unknown\n try {\n parsed = JSON.parse(text)\n }\n catch {\n return null\n }\n if (!isRecord(parsed))\n return null\n // Returned normalised even when clean, so a caller never falls back to copying the original bytes.\n return `${JSON.stringify('password' in parsed ? { ...parsed, password: withoutFirstRunPassword(parsed.password) } : parsed)}\\n`\n}\n\n/** Parses a secrets document, tolerating anything: not-an-object, or broken JSON returns {}. */\nexport function parseSecrets(text: string): Record<string, unknown> {\n try {\n const parsed: unknown = JSON.parse(text)\n return isRecord(parsed) ? parsed : {}\n }\n catch {\n return {}\n }\n}\n\n/**\n * Merges `piece` into `current`, changing only `fields`; a field absent from `piece` is deleted, so an\n * older archive clears a secret it predates. Does not mutate its arguments.\n */\nexport function mergeSecrets(current: Record<string, unknown>, piece: Record<string, unknown>, fields: string[]): Record<string, unknown> {\n const merged = { ...current }\n for (const field of fields) {\n const value = piece[field]\n if (value === null || value === undefined)\n delete merged[field]\n else\n merged[field] = value\n }\n return merged\n}\n","import fs from 'node:fs'\nimport path from 'node:path'\nimport process from 'node:process'\nimport { writeFileAtomic } from '#src/helpers/atomic'\nimport { ensureStateDir } from '#src/helpers/paths'\n\n/**\n * A lock file that stops two restores — the panel's and the offline CLI's alike — from writing the\n * same host at once. A dead holder is detected by pid *and* start time, so a recycled pid is not\n * mistaken for a live one.\n */\n\n/** How long a restore may hold the lock before another waits no longer on it. */\nconst STALE_AFTER_MS = 30 * 60_000\n\n/** Absorbs the one-second granularity of a birth-time reading against the moment we recorded it. */\nconst BIRTH_TOLERANCE_MS = 2000\n\nexport interface LockRecord {\n pid: number\n startedAt: number\n action: string\n /** The holder's own birth time, where the platform reports one. */\n birthAt?: number | null\n}\n\nexport interface RestoreLock {\n release: () => void\n replaced?: LockRecord\n}\n\nfunction readRecord(file: string): LockRecord | null {\n try {\n const parsed = JSON.parse(fs.readFileSync(file, 'utf8')) as Partial<LockRecord>\n if (typeof parsed.pid !== 'number' || typeof parsed.startedAt !== 'number')\n return null\n // `birthAt` must survive the read: it is the basis of the recycled-pid check.\n return {\n pid: parsed.pid,\n startedAt: parsed.startedAt,\n action: typeof parsed.action === 'string' ? parsed.action : 'restore',\n birthAt: typeof parsed.birthAt === 'number' ? parsed.birthAt : null,\n }\n }\n catch {\n return null\n }\n}\n\n/**\n * Is the recorded holder still the process that took it? Where no start time is available an alive\n * pid is taken as alive, erring towards not stealing a live lock.\n */\nfunction holderIsAlive(record: LockRecord): boolean {\n try {\n process.kill(record.pid, 0)\n }\n catch (error) {\n // EPERM means the process exists but belongs to another user — still a live holder.\n return (error as NodeJS.ErrnoException).code === 'EPERM'\n }\n const birth = processBirthSync(record.pid)\n if (birth === null)\n return true\n if (record.birthAt != null)\n return Math.abs(birth - record.birthAt) <= BIRTH_TOLERANCE_MS\n // An older record has no birth time: a pid born after the lock was taken is a different process.\n return birth <= record.startedAt + BIRTH_TOLERANCE_MS\n}\n\nexport function processBirthSync(pid: number): number | null {\n try {\n // Linux: field 22 is the start time in clock ticks since boot, and `/proc/stat` has the boot time.\n const stat = fs.readFileSync(`/proc/${pid}/stat`, 'utf8')\n const fields = stat.slice(stat.lastIndexOf(')') + 2).split(' ')\n const ticks = Number.parseFloat(fields[19] ?? '')\n if (!Number.isFinite(ticks))\n return null\n const boot = /^btime (\\d+)$/m.exec(fs.readFileSync('/proc/stat', 'utf8'))?.[1]\n if (boot === undefined)\n return null\n // 100 ticks a second on every mainstream kernel build.\n return Number.parseInt(boot, 10) * 1000 + (ticks / 100) * 1000\n }\n catch {\n return null\n }\n}\n\nexport function restoreLockHolder(hhDir: string): LockRecord | null {\n const existing = readRecord(path.join(hhDir, 'restore.lock'))\n return existing !== null && isLiveHolder(existing) ? existing : null\n}\n\nfunction isLiveHolder(record: LockRecord): boolean {\n return holderIsAlive(record) && Date.now() - record.startedAt <= STALE_AFTER_MS\n}\n\n/** Take the restore lock, or `null` when somebody else holds it (the caller reports, never queues). */\nexport function acquireRestoreLock(hhDir: string, action = 'restore'): RestoreLock | { heldBy: LockRecord } {\n const file = path.join(hhDir, 'restore.lock')\n ensureStateDir(hhDir)\n\n const mine: LockRecord = { pid: process.pid, startedAt: Date.now(), action, birthAt: processBirthSync(process.pid) }\n const release = (): void => {\n const current = readRecord(file)\n if (current !== null && (current.pid !== mine.pid || current.startedAt !== mine.startedAt))\n return\n fs.rmSync(file, { force: true })\n }\n\n const existing = readRecord(file)\n if (existing !== null) {\n if (isLiveHolder(existing))\n return { heldBy: existing }\n // The holder died, or has held it absurdly long: take it over, and say so.\n writeFileAtomic(file, `${JSON.stringify(mine)}\\n`, { mode: 0o600 })\n return { release, replaced: existing }\n }\n\n try {\n // `wx` is the exclusion: creation fails atomically if the file exists.\n fs.writeFileSync(file, `${JSON.stringify(mine)}\\n`, { flag: 'wx', mode: 0o600 })\n }\n catch (error) {\n if ((error as NodeJS.ErrnoException).code === 'EEXIST') {\n // Somebody created it between our read and our write; their record is the answer.\n const holder = readRecord(file)\n return holder === null\n ? { heldBy: { pid: 0, startedAt: Date.now(), action: 'unreadable' } }\n : { heldBy: holder }\n }\n throw error\n }\n\n let released = false\n return {\n release: () => {\n if (released)\n return\n released = true\n release()\n },\n }\n}\n","import type { Buffer } from 'node:buffer'\nimport type { ChildProcess } from 'node:child_process'\nimport type { BackupHookConfig, ServerConfig } from '#src/shared/contracts'\nimport { spawn } from 'node:child_process'\nimport process from 'node:process'\nimport { ensureStateDir } from '#src/helpers/paths'\nimport { resolveRecord, resolveTemplates } from '#src/helpers/template'\nimport { resolveCwd } from '#src/providers/process'\nimport { serverTemplateVars } from '#src/providers/server-vars'\n\n/**\n * Runs one backup hook (`dump` before capture, `load` after restore): one program plus args, never a\n * shell string. Unlike `bootstrap` it is not best-effort — a failed `dump` must refuse the backup.\n */\n\nexport interface HookResult {\n ok: boolean\n code: number | null\n /** Bounded tail of both streams, for the plan and the error. */\n output: string\n /** Set when the process could not be started or timed out. */\n error?: string\n}\n\nconst OUTPUT_TAIL_BYTES = 8 * 1024\n\nfunction tail(previous: string, chunk: string): string {\n const next = previous + chunk\n return next.length <= OUTPUT_TAIL_BYTES ? next : next.slice(next.length - OUTPUT_TAIL_BYTES)\n}\n\n/** Run a hook for one entry. `dumpDir` is passed in so `dump` and `load` get the same absolute path. */\nexport async function runBackupHook(\n hook: BackupHookConfig,\n server: ServerConfig,\n dumpDir: string,\n options: { requireDumpDir?: boolean } = {},\n): Promise<HookResult> {\n const vars = { ...serverTemplateVars(server), dumpDir }\n const cwd = resolveCwd(server.cwd)\n const args = resolveTemplates(hook.args, vars)\n\n // A hook naming `{dumpDir}` gets a directory that exists, or the tool fails with a worse message.\n if (options.requireDumpDir !== false)\n ensureStateDir(dumpDir)\n\n let child: ChildProcess\n try {\n child = spawn(hook.command, args, {\n cwd,\n env: { ...process.env, ...resolveRecord(hook.env, vars) },\n stdio: ['ignore', 'pipe', 'pipe'],\n windowsHide: true,\n })\n }\n catch (error) {\n return { ok: false, code: null, output: '', error: `could not start: ${(error as Error).message}` }\n }\n\n let output = ''\n child.stdout?.on('data', (chunk: Buffer) => {\n output = tail(output, chunk.toString())\n })\n child.stderr?.on('data', (chunk: Buffer) => {\n output = tail(output, chunk.toString())\n })\n\n const outcome = await new Promise<{ code: number | null, error?: string }>((resolve) => {\n const timer = setTimeout(() => {\n try {\n child.kill('SIGKILL')\n }\n catch {\n }\n resolve({ code: null, error: `timed out after ${hook.timeoutMs}ms` })\n }, hook.timeoutMs)\n child.once('exit', (code) => {\n clearTimeout(timer)\n resolve({ code })\n })\n child.once('error', (error) => {\n clearTimeout(timer)\n // The same sentence as the `catch` above: `ENOENT` for a missing binary arrives on this event.\n resolve({ code: null, error: `could not start: ${error.message}` })\n })\n })\n\n return {\n ok: outcome.error === undefined && outcome.code === 0,\n code: outcome.code,\n output,\n ...(outcome.error === undefined ? {} : { error: outcome.error }),\n }\n}\n\n/** The line a person reads when a hook fails: the entry, the program and its last output. */\nexport function hookFailure(action: 'dump' | 'load', server: ServerConfig, result: HookResult): string {\n const detail = result.error ?? (result.code === null ? 'no exit code' : `exit ${result.code}`)\n const said = result.output.trim().split('\\n').filter(line => line.trim().length > 0).slice(-3).join(' / ')\n return `the ${action} hook for \"${server.id}\" failed (${detail})${said.length === 0 ? '' : `: ${said}`}`\n}\n","import fs from 'node:fs'\nimport path from 'node:path'\nimport { isZipArchive, listZip } from '#src/providers/archive'\nimport { errorMessage } from '#src/shared/error-message'\n\n/** What an archive may hold and where a restore may write: the path-safety gates of backup and restore. */\n\nexport const MANIFEST = 'manifest.json'\nconst ALLOWED_ROOTS = new Set(['global', 'workspaces', 'data', 'dumps'])\n\n/**\n * Whether one archive path segment is a name a filesystem will accept as-is: no separator (`\\` on\n * Windows), no `:` (drive/stream), no control character.\n */\nfunction isPortableSegment(segment: string): boolean {\n for (const character of segment) {\n const code = character.codePointAt(0) ?? 0\n if (character === '\\\\' || character === ':' || code < 0x20 || code === 0x7F)\n return false\n }\n return true\n}\n\n/**\n * Structural allowlist for archive entries. A regex alone is not enough: `..`\n * is made of allowed characters, so segments are checked explicitly and any\n * entry that could resolve outside the staging directory aborts the restore.\n */\nexport function isSafeArchiveEntry(entry: string): boolean {\n if (entry.startsWith('/') || entry.includes('\\0'))\n return false\n\n const cleaned = entry.replace(/^\\.\\//, '').replace(/\\/+$/, '')\n if (cleaned.length === 0)\n return true\n if (cleaned === MANIFEST)\n return true\n\n const segments = cleaned.split('/')\n if (segments.some(segment => segment.length === 0 || segment === '.' || segment === '..'))\n return false\n if (!ALLOWED_ROOTS.has(segments[0]!))\n return false\n // Not a character allowlist: a declared tree holds arbitrary names; only a segment that could move\n // the path is refused.\n return segments.every(isPortableSegment)\n}\n\n/**\n * The gates an archive passes before a restore is planned from it: it is a zip, and every entry is\n * inside the layout this service writes. Shared by the upload route and `backup restore --from`.\n */\nexport type ArchiveAdmission\n = | { ok: true, entries: Awaited<ReturnType<typeof listZip>> }\n | { ok: false, error: string }\n\nexport async function admitArchive(archivePath: string): Promise<ArchiveAdmission> {\n if (!isZipArchive(archivePath))\n return { ok: false, error: 'the archive is not a home-hosted backup (a zip file was expected)' }\n\n // The central directory is readable without a password, so a backup can be listed and its\n // selection offered before the password is ever entered.\n let entries: Awaited<ReturnType<typeof listZip>>\n try {\n entries = await listZip(archivePath)\n }\n catch (error) {\n return { ok: false, error: `the archive could not be read: ${errorMessage(error)}` }\n }\n\n if (entries.length === 0)\n return { ok: false, error: 'the archive is empty' }\n if (entries.length > 100_000)\n return { ok: false, error: 'the archive has too many entries' }\n\n const invalid = entries.filter(entry => !isSafeArchiveEntry(entry.name))\n if (invalid.length > 0)\n return { ok: false, error: `the archive contains unexpected entries (e.g. ${invalid.slice(0, 3).map(entry => entry.name).join(', ')})` }\n\n return { ok: true, entries }\n}\n\n/** True when `child` is `parent` itself or lives underneath it. */\nexport function isInside(parent: string, child: string): boolean {\n if (parent === child)\n return true\n // `path.relative` is case-insensitive on Windows and empty for a case-only difference.\n const relative = path.relative(parent, child)\n return !path.isAbsolute(relative) && (relative.length === 0 || !relative.startsWith('..'))\n}\n\n/** Resolves symlinks on the deepest existing ancestor, keeping the rest verbatim. */\nexport function resolveExisting(target: string): string {\n let prefix = target\n const rest: string[] = []\n for (;;) {\n try {\n return path.join(fs.realpathSync(prefix), ...rest)\n }\n catch {\n const parent = path.dirname(prefix)\n if (parent === prefix)\n return target\n rest.unshift(path.basename(prefix))\n prefix = parent\n }\n }\n}\n\n/**\n * `isInside` after resolving symlinks, so a link inside a declared path cannot stand for somewhere\n * else on either capture or restore.\n */\nexport function isInsideResolved(parent: string, child: string): boolean {\n // Both sides resolve, so a symlinked ancestor (`/var` on macOS) cancels out.\n return isInside(resolveExisting(path.resolve(parent)), resolveExisting(path.resolve(child)))\n}\n","import type { TemplateVars } from '#src/helpers/template'\nimport type { ServerConfig } from '#src/shared/contracts'\nimport { createHash } from 'node:crypto'\nimport os from 'node:os'\nimport path from 'node:path'\nimport process from 'node:process'\nimport { expandEnv } from '#src/helpers/env-file'\nimport { projectDir, resolveUserPath } from '#src/helpers/paths'\nimport { resolveTemplate } from '#src/helpers/template'\nimport { serverTemplateVars } from '#src/providers/server-vars'\nimport { isInside } from '#src/services/backups/archive-safety'\n\n/** One declared data path, with the verdict the UI shows. */\nexport interface BackupPath {\n path: string\n origin: string\n included: boolean\n note: string | null\n /** The verdict as a catalog key; `note` stays for older UIs and `noc-console`. */\n noteKey?: string\n noteParams?: Record<string, string>\n ignoreGenerated: boolean\n}\n\n/** The `{…}` placeholders a *global* declared path may use. */\nexport interface BackupVars {\n projectDir: string\n dataRoot: string\n home: string\n}\n\ninterface DeclaredPath {\n path: string\n origin: string\n depth: number\n order: number\n ignoreGenerated: boolean\n}\n\n/**\n * Every path a backup should capture: the global list, then each server's `backupPaths` and\n * `dataEnvs` values. A path covered by a declared parent is reported but not captured.\n * `vars` only feeds the global list.\n */\nexport function resolveBackupPaths(servers: ServerConfig[], includePaths: string[] = [], vars?: Partial<BackupVars>): BackupPath[] {\n const declared: DeclaredPath[] = []\n const globalVars: TemplateVars = {\n projectDir: vars?.projectDir ?? projectDir,\n dataRoot: vars?.dataRoot ?? (servers[0] === undefined ? projectDir : String(serverTemplateVars(servers[0]).dataRoot ?? projectDir)),\n home: vars?.home ?? os.homedir(),\n }\n\n const add = (value: string, origin: string, templateVars: TemplateVars, ignoreGenerated: boolean): void => {\n if (value.trim().length === 0)\n return\n // Normalized, so a trailing or doubled slash cannot defeat the parent/child comparison.\n const resolved = path.normalize(resolveUserPath(expandEnv(resolveTemplate(value, templateVars), process.env)))\n declared.push({\n path: resolved,\n origin,\n depth: path.normalize(resolved).split(path.sep).filter(Boolean).length,\n order: declared.length,\n ignoreGenerated,\n })\n }\n\n // A global extra path is named by hand, so it is captured as it stands.\n for (const value of includePaths) add(value, 'global', globalVars, false)\n\n for (const config of servers) {\n const templateVars = serverTemplateVars(config)\n const ignoreGenerated = config.backupIgnoreGenerated !== false\n for (const [name, value] of Object.entries(config.dataEnvs)) add(value, `${config.id}:${name}`, templateVars, ignoreGenerated)\n for (const value of config.backupPaths) add(value, `${config.id}:backupPaths`, templateVars, ignoreGenerated)\n }\n\n // Shallowest first, so a parent absorbs its descendants; ties keep declaration order.\n const sorted = [...declared].sort((a, b) => a.depth - b.depth || a.order - b.order)\n\n return sorted.map((entry, index) => {\n const parent = sorted.slice(0, index).find(candidate => isInside(candidate.path, entry.path))\n if (parent === undefined)\n return { path: entry.path, origin: entry.origin, included: true, note: null, ignoreGenerated: entry.ignoreGenerated }\n const note = parent.path === entry.path\n ? `already declared by ${parent.origin}`\n : `covered by ${parent.path}`\n const noteKey = parent.path === entry.path\n ? 'settings.backup.noteAlreadyDeclared'\n : 'settings.backup.noteCovered'\n const noteParams: Record<string, string> = parent.path === entry.path\n ? { origin: parent.origin }\n : { path: parent.path }\n return { path: entry.path, origin: entry.origin, included: false, note, noteKey, noteParams, ignoreGenerated: entry.ignoreGenerated }\n })\n}\n\n/**\n * Stable, filesystem-safe name for a data path inside the archive. The hash keeps paths whose\n * readable parts collide apart; a restore reads the slug from the manifest.\n */\nexport function slugifyPath(target: string): string {\n const hash = createHash('sha256').update(path.resolve(target)).digest('hex').slice(0, 8)\n return `${legacySlug(target).slice(-71)}-${hash}`\n}\n\n/** The hashless slug archives were written with before; only a manifest without a slug falls back to it. */\nexport function legacySlug(target: string): string {\n const cleaned = target.replace(/[^A-Z0-9]+/gi, '-').replace(/^-+|-+$/g, '')\n return cleaned.length > 0 ? cleaned.slice(-80) : 'path'\n}\n","import type { BackupScope } from './contracts'\n\n/** `only` is `--include` and `except` is `--all --exclude`; an absent scope is the full default. */\nexport function scopeSelection(scope: BackupScope | undefined): { include?: string[], exclude?: string[] } {\n if (scope === undefined)\n return {}\n return scope.mode === 'only' ? { include: [...scope.ids] } : { exclude: [...scope.ids] }\n}\n\n/**\n * The one \"is this id selected\" rule for create, restore, the control plan and both UIs. `include`\n * omitted means everything; `exclude` applies after it, and covers every id beneath an excluded one.\n */\nexport function selectionOf(options: { include?: readonly string[], exclude?: readonly string[] }): ((id: string) => boolean) & { isExcluded: (id: string) => boolean } {\n const wanted = options.include === undefined ? null : new Set(options.include)\n const unwanted = new Set(options.exclude ?? [])\n const isExcluded = (id: string): boolean =>\n unwanted.has(id) || [...unwanted].some(entry => id.startsWith(`${entry}:`))\n const selects = ((id: string): boolean => {\n if (isExcluded(id))\n return false\n // Downwards only: naming `a` selects `a:b`, never the reverse, or a whole-entry item would\n // replace a file the person asked to touch one field of.\n return wanted === null || wanted.has(id) || [...wanted].some(entry => id.startsWith(`${entry}:`))\n }) as ((id: string) => boolean) & { isExcluded: (id: string) => boolean }\n selects.isExcluded = isExcluded\n return selects\n}\n\n/** A capture-tree entry as a selection sees it; an alias (`config`) names the same item as its id. */\nexport interface SelectableItem {\n id: string\n /** Coarse ids that select this item too (`config` for `global:settings`). */\n aliases?: readonly string[]\n}\n\n/** The panel-wide entries, declared once so the credential guard and the restore agree on aliases. */\nexport const GLOBAL_RESTORE_ITEMS = {\n settings: { id: 'global:settings', aliases: ['config'] },\n credentials: { id: 'global:secrets', aliases: ['secrets'] },\n tls: { id: 'global:tls', aliases: ['tls'] },\n} as const satisfies Record<string, SelectableItem>\n\n/** Whether a selection chooses this item: an exclusion beats an alias, then any of its ids selects it. */\nexport function selectedBy(\n selects: ((id: string) => boolean) & { isExcluded: (id: string) => boolean },\n item: SelectableItem,\n): boolean {\n const aliases = item.aliases ?? []\n const excluded = selects.isExcluded(item.id) || aliases.some(alias => selects.isExcluded(alias))\n return !excluded && (selects(item.id) || aliases.some(alias => selects(alias)))\n}\n\n/** Whether a selection reaches anything inside one item: the item, an alias, or a leaf of it. */\nexport function selectionTouches(\n options: { include?: readonly string[], exclude?: readonly string[] },\n item: SelectableItem,\n): boolean {\n const selects = selectionOf(options)\n const prefixes = [item.id, ...(item.aliases ?? [])]\n const namesLeaf = (options.include ?? []).some(id => prefixes.some(prefix => id.startsWith(`${prefix}:`)) && selects(id))\n if (namesLeaf)\n return true\n return selectedBy(selects, item)\n}\n\n/**\n * Whether a restore would write the credential store (password and token hashes). Who may do that is\n * the route's decision.\n */\nexport function selectionWritesCredentials(options: { include?: readonly string[], exclude?: readonly string[] }): boolean {\n return selectionTouches(options, GLOBAL_RESTORE_ITEMS.credentials)\n}\n\nexport interface ScopeChoice {\n id: string\n selected: boolean\n /** A workspace's leaves, a secrets entry's per-key leaves, or none for a whole-entry item. */\n leaves: ReadonlyArray<{ id: string, selected: boolean }>\n}\n\n/** One leaf is enough, and a leaf-less entry stands alone. */\nfunction captures(choice: ScopeChoice): boolean {\n return choice.selected && (choice.leaves.length === 0 || choice.leaves.some(leaf => leaf.selected))\n}\n\nfunction capturesWhole(choice: ScopeChoice): boolean {\n return choice.selected && (choice.leaves.length === 0 || choice.leaves.every(leaf => leaf.selected))\n}\n\n/** A wholly-ticked entry travels as its own id, a partial one by leaf. */\nexport function capturedIds(choices: readonly ScopeChoice[]): string[] {\n return choices.flatMap((choice) => {\n if (capturesWhole(choice))\n return [choice.id]\n if (!captures(choice))\n return []\n return choice.leaves.filter(leaf => leaf.selected).map(leaf => leaf.id)\n })\n}\n\n/** The complement, for an exclusion scope: an untouched entry whole, a partial one leaf by leaf. */\nexport function excludedIds(choices: readonly ScopeChoice[]): string[] {\n return choices.flatMap((choice) => {\n if (!captures(choice))\n return [choice.id]\n if (capturesWhole(choice))\n return []\n return choice.leaves.filter(leaf => !leaf.selected).map(leaf => leaf.id)\n })\n}\n\nexport type ScopeOutcome\n = | { kind: 'everything' }\n | { kind: 'nothing' }\n | { kind: 'scope', scope: BackupScope }\n\n/**\n * A tree with nothing left out is stored as **no scope**, so a workspace declared later is covered too.\n * `nothing` is refused by the caller: an empty `include` means \"everything\" to the API.\n */\nexport function scopeOf(choices: readonly ScopeChoice[], mode: BackupScope['mode']): ScopeOutcome {\n if (choices.length === 0 || capturedIds(choices).length === 0)\n return { kind: 'nothing' }\n if (excludedIds(choices).length === 0)\n return { kind: 'everything' }\n return { kind: 'scope', scope: { mode, ids: mode === 'only' ? capturedIds(choices) : excludedIds(choices) } }\n}\n\nexport interface ScopeEntry {\n id: string\n items?: ReadonlyArray<{ id: string }>\n}\n\n/**\n * Which of `ids` name nothing capturable (an id may be a prefix of one). On a schedule a typo silently\n * narrows (`only`) or widens (`except`) the archive.\n */\nexport function unknownBackupIds(ids: readonly string[], entries: readonly ScopeEntry[]): string[] {\n const available = entries.flatMap(entry => [entry.id, ...(entry.items ?? []).map(item => item.id)])\n const known = (id: string): boolean => available.some(candidate => candidate === id || candidate.startsWith(`${id}:`))\n return ids.filter(id => !known(id))\n}\n\n/** Same ids, same mode, order ignored. */\nexport function sameScope(a: BackupScope | null | undefined, b: BackupScope | null | undefined): boolean {\n if (a === null || a === undefined || b === null || b === undefined)\n return (a ?? null) === (b ?? null)\n return a.mode === b.mode && [...a.ids].sort().join('\\n') === [...b.ids].sort().join('\\n')\n}\n","/**\n * Names that only hold build output or installed dependencies, skipped by `backupIgnoreGenerated`.\n * Matched by exact name on any segment. `.git` is deliberately absent: an unpushed commit is not regenerable.\n */\n\n/** Whole directories that are regenerated, never authored. */\nexport const GENERATED_DIRS: readonly string[] = [\n // Installed dependencies and package-manager stores.\n 'node_modules',\n 'bower_components',\n 'jspm_packages',\n '.yarn',\n '.pnpm',\n '.pnpm-store',\n '.npm',\n // Framework and bundler output.\n '.next',\n '.nuxt',\n '.svelte-kit',\n '.astro',\n '.output',\n '.vercel',\n '.netlify',\n '.angular',\n 'dist',\n 'build',\n 'out',\n // Caches.\n '.cache',\n '.parcel-cache',\n '.turbo',\n '.vite',\n '.rollup.cache',\n '.swc',\n // Test and coverage output.\n 'coverage',\n '.nyc_output',\n '__pycache__',\n '.pytest_cache',\n '.mypy_cache',\n '.ruff_cache',\n '.tox',\n // Other language toolchains.\n 'target',\n '.gradle',\n '.dart_tool',\n]\n\n/** One-off files worth skipping, by exact name. */\nexport const GENERATED_FILES: readonly string[] = [\n '.DS_Store',\n 'Thumbs.db',\n 'desktop.ini',\n '.eslintcache',\n '.stylelintcache',\n 'npm-debug.log',\n 'yarn-error.log',\n 'pnpm-debug.log',\n]\n\nconst DIR_NAME_SET = new Set(GENERATED_DIRS)\nconst FILE_NAME_SET = new Set(GENERATED_FILES)\n\n/** `relative` is to the declared root; either separator. */\nexport function isGeneratedPath(relative: string): boolean {\n const segments = relative.split(/[\\\\/]+/).filter(segment => segment.length > 0 && segment !== '.')\n if (segments.length === 0)\n return false\n if (FILE_NAME_SET.has(segments[segments.length - 1]!))\n return true\n return segments.some(segment => DIR_NAME_SET.has(segment))\n}\n","import type { ResolvedGlobalConfig } from '#src/config/schema'\nimport type { SecretScope } from '#src/config/secret-parts'\nimport type { BackupPath, BackupVars } from '#src/services/backups/paths'\nimport type { BackupEntry, BackupFile, BackupsConfig, BackupSelection, BackupsView, RestoreItem, RestorePlan, RestoreSkip, ServerConfig } from '#src/shared/contracts'\nimport fs from 'node:fs'\nimport os from 'node:os'\nimport path from 'node:path'\nimport process from 'node:process'\nimport { DetailedError } from '@namesmt/utils'\nimport { type } from 'arktype'\nimport { jobProblems, liftJobsDocument } from '#src/config/jobs'\nimport { applyConfigMigrations, CONFIG_SCHEMA, planConfigMigrations } from '#src/config/migrations'\nimport { parseGlobalSettings, parseServersFile, parseWorkspaceSettings, stampConfig } from '#src/config/parse'\nimport { KNOWN_SECRET_KEYS, mergeSecrets, parseSecrets, pickSecrets, presentSecretKeys, secretParts, withoutInitialPassword } from '#src/config/secret-parts'\nimport { parseWorkspacesFile } from '#src/config/workspaces'\nimport { writeFileAtomic } from '#src/helpers/atomic'\nimport { readStateFile } from '#src/helpers/config-text'\nimport { copyTree } from '#src/helpers/copy-tree'\nimport { logger } from '#src/helpers/logger'\nimport { ensureStateDir, projectDir } from '#src/helpers/paths'\nimport { acquireRestoreLock, restoreLockHolder } from '#src/helpers/restore-lock'\nimport { appVersion } from '#src/helpers/version'\nimport { createZip, extractZip, isInvalidPassword, listZip } from '#src/providers/archive'\nimport { hookFailure, runBackupHook } from '#src/providers/backup-hook'\nimport { isProcessAlive } from '#src/providers/port'\nimport { serverTemplateVars } from '#src/providers/server-vars'\nimport { admitArchive, isInside, isInsideResolved, MANIFEST, resolveExisting } from '#src/services/backups/archive-safety'\nimport { legacySlug, resolveBackupPaths, slugifyPath } from '#src/services/backups/paths'\nimport { GLOBAL_RESTORE_ITEMS, scopeSelection, selectedBy, selectionOf } from '#src/shared/backup-scope'\nimport { jobsFileSchema, serverSchema, workspaceIdSchema } from '#src/shared/contracts'\nimport { errorMessage } from '#src/shared/error-message'\nimport { isGeneratedPath } from '#src/shared/generated'\nimport { isRecord } from '#src/shared/shape'\n\nexport type { ArchiveAdmission } from '#src/services/backups/archive-safety'\nexport { admitArchive, isInside, isInsideResolved, isSafeArchiveEntry } from '#src/services/backups/archive-safety'\nexport type { BackupPath, BackupVars } from '#src/services/backups/paths'\nexport { resolveBackupPaths, slugifyPath } from '#src/services/backups/paths'\n\nconst serverIdSchema = serverSchema.get('id')\n/** The workspace registry inside an archive, under `global/`. */\nconst REGISTRY = 'workspaces.json'\n/**\n * Every file name the panel writes a secret into. A secrets document reaches an archive only through\n * `copySecrets`, so the raw data copy refuses these names wherever a declared tree holds them.\n */\nconst SECRET_FILE_NAMES = ['.control-secrets.json', '.secrets.json'] as const\n\n/** The live name, or the temp name `writeFileAtomic` leaves behind if it crashed before the rename. */\nconst SECRET_DOCUMENT_NAMES = new RegExp(\n // `i`, because a case-insensitive filesystem can give the hex suffix back in either case.\n `^(?:${SECRET_FILE_NAMES.map(name => name.replaceAll('.', '\\\\.')).join('|')})(?:\\\\.\\\\d+\\\\.[0-9a-f]{8}\\\\.tmp)?$`,\n 'i',\n)\n\nfunction isSecretDocument(name: string): boolean {\n return SECRET_DOCUMENT_NAMES.test(name)\n}\n/** Every archive this service writes is a zip, encrypted or not. */\nconst SUFFIX = '.zip'\n/** Where a restore parks a dump until the entry's next start can load it. */\nconst PENDING_LOAD = 'pending-load'\n/**\n * An archive the schedule wrote. The prefix is the only durable marker: a filename is the one\n * thing that survives a restart, and it is what lets the two retention counts stay independent.\n */\nconst AUTO_PREFIX = 'auto'\nconst MANUAL_PREFIX = 'backup'\n/** The names `create()` writes; retention counts and prunes only these, never a zip someone else put here. */\nconst ARCHIVE_NAME = new RegExp(`^(${AUTO_PREFIX}|${MANUAL_PREFIX})-\\\\d{4}(?:-\\\\d{2}){5}-\\\\d{1,3}\\\\.zip$`)\nconst ARCHIVE_STAMP = /-(\\d{4})-(\\d{2})-(\\d{2})-(\\d{2})-(\\d{2})-(\\d{2})-(\\d{1,3})\\.zip$/\n\n/**\n * When `create()` wrote an archive, read from its name (UTC, to the millisecond), or null for a name\n * it did not write. The name survives a copy; the mtime does not.\n */\nfunction archiveStamp(name: string): number | null {\n if (!ARCHIVE_NAME.test(name))\n return null\n const parts = ARCHIVE_STAMP.exec(name)?.slice(1).map(Number)\n if (parts === undefined || parts.length !== 7)\n return null\n const [year, month, day, hour, minute, second, ms] = parts as [number, number, number, number, number, number, number]\n const at = Date.UTC(year, month - 1, day, hour, minute, second, ms)\n return Number.isFinite(at) ? at : null\n}\n/** A workspace leaf that carries state the panel re-reads after a restore. */\nconst RELOADABLE = /^global:settings$|^workspace:[^:]+:(?:settings|servers)$/\n\n/** A staging tree's name, carrying the owning pid so a later run can tell dead debris from a live capture. */\nfunction stagingDirName(kind: 'staging' | 'restore'): string {\n return `.${kind}-${process.pid}-${Date.now()}`\n}\n\n/** The pid a staging directory belongs to, or null — a name with no pid is never guessed at. */\nfunction stagingOwner(name: string): number | null {\n const match = /^\\.[a-z]+-(\\d+)-\\d+$/.exec(name)\n if (match === null)\n return null\n const pid = Number.parseInt(match[1]!, 10)\n return Number.isInteger(pid) && pid > 0 ? pid : null\n}\n\n/** Wording and catalog key of each known secret; an unlisted key reads as its own name. */\nconst SECRET_LABELS: Record<string, { en: string, key?: string }> = {\n password: { en: 'Password (before 0.14)', key: 'settings.backup.secretPassword' },\n apiToken: { en: 'API token (before 0.14)', key: 'settings.backup.secretApiToken' },\n telegram: { en: 'Telegram bot token', key: 'settings.backup.secretTelegram' },\n ddns: { en: 'DDNS credentials', key: 'settings.backup.secretDdns' },\n accounts: { en: 'Accounts', key: 'settings.backup.secretAccounts' },\n apiTokens: { en: 'API tokens', key: 'settings.backup.secretApiTokens' },\n serverEnv: { en: 'Server secret environment', key: 'settings.backup.secretServerEnv' },\n jobEnv: { en: 'Job secret environment', key: 'settings.backup.secretJobEnv' },\n}\n\n/** Pre-accounts slots: an upgraded file no longer has them, so an absent one is not worth a row. */\nconst LEGACY_SECRET_SLOTS = new Set(['password', 'apiToken'])\n\n/**\n * The servers an archive carries for one workspace, from its staged config — the live config is\n * the old one at this point. An unparseable config yields no servers.\n */\nfunction readArchivedServers(staging: string, workspaceId: string, defaults: Record<string, unknown> = {}): ServerConfig[] {\n const text = readText(path.join(staging, 'workspaces', workspaceId, 'servers.config.json'))\n if (text === null)\n return []\n try {\n // `parseServersFile`, not `JSON.parse`: the template vars need the defaults it fills in.\n return parseServersFile(JSON.parse(text), defaults).servers\n }\n catch {\n return []\n }\n}\n\n/** One workspace's state, as the backup and restore sides both read it. */\nexport interface BackupWorkspaceSource {\n id: string\n label: string\n settingsPath: string\n serversPath: string\n /** The workspace's `jobs.config.json`. */\n jobsPath: string\n secretsPath: string\n servers: ServerConfig[]\n}\n\n/** One workspace the registry names, whether or not this host has it. */\ninterface ArchivedWorkspace {\n id: string\n label: string\n}\n\nexport interface BackupSources {\n globalSettingsPath: string\n globalSecretsPath: string\n tlsDir: string\n /**\n * The workspace registry. Never written back whole: a restore only creates the workspaces missing here.\n */\n registryPath: string\n /** Extra paths in every backup, in addition to each server's own. */\n includePaths: string[]\n workspaces: BackupWorkspaceSource[]\n /**\n * The servers running now, so a restore can name whose data it replaced under them. Optional.\n */\n runningServers?: () => Array<{ workspaceId: string, serverId: string }>\n}\n\n/** A workspace as the source builder needs it: identity, its file locations, its loaded servers. */\nexport interface BackupWorkspaceInput {\n id: string\n label: string\n settingsPath: string\n serversPath: string\n jobsPath: string\n secretsPath: string\n servers: ServerConfig[]\n}\n\n/**\n * What a backup captures. The one implementation, shared by the panel and the offline CLI so both\n * capture the same thing.\n */\nexport function buildBackupSources(input: {\n globalSettingsPath: string\n globalSecretsPath: string\n tlsDir: string\n registryPath: string\n includePaths: string[]\n workspaces: BackupWorkspaceInput[]\n runningServers?: () => Array<{ workspaceId: string, serverId: string }>\n}): BackupSources {\n return {\n globalSettingsPath: input.globalSettingsPath,\n globalSecretsPath: input.globalSecretsPath,\n tlsDir: input.tlsDir,\n registryPath: input.registryPath,\n includePaths: [...input.includePaths],\n ...(input.runningServers === undefined ? {} : { runningServers: input.runningServers }),\n // Paths are inputs, never re-derived: they must be the files the supervisor actually reads.\n workspaces: input.workspaces.map(workspace => ({\n id: workspace.id,\n label: workspace.label,\n settingsPath: workspace.settingsPath,\n serversPath: workspace.serversPath,\n jobsPath: workspace.jobsPath,\n secretsPath: workspace.secretsPath,\n servers: workspace.servers,\n })),\n }\n}\n\nexport interface BackupManifest {\n version: 1\n createdAt: number\n hostname: string\n /** The release that wrote the archive and its config schema; absent in older archives. */\n writtenBy?: string\n schema?: number\n /** `origin` and `workspace` are what let a restore land under *this* machine's paths. */\n data: Array<{ slug: string, path: string, origin?: string, workspace?: string }>\n /** Entries whose `dump` hook ran, and whose dump is under `dumps/<workspace>/<server>/`. */\n dumps?: Array<{ workspaceId: string, serverId: string }>\n}\n\nexport interface RestoreCommandOptions {\n confirm: boolean\n /** Required for, and ignored by, archives that are not password-protected. */\n password?: string\n /** Item ids to restore; omitted means every restorable item. */\n include?: string[]\n /** Item ids to leave out, applied after `include` (e.g. `--exclude global:secrets`). */\n exclude?: string[]\n}\n\nexport type { RestorePlan }\n\n/** One place a restore may write a data path to, and what declared it. */\ninterface DataTarget {\n workspace: string\n path: string\n origin: string\n}\n\n/**\n * Pairs each archived data path with the declaration that will receive it. Stateful: one target is\n * claimed by one entry, so same-origin declarations pair in resolve order. Never crosses a\n * workspace boundary.\n */\nfunction dataTargetMatcher(archiveTargets: DataTarget[], instanceTargets: DataTarget[]): (\n origin: string | undefined,\n workspace: string | undefined,\n archivedPath: string,\n) => DataTarget | undefined {\n const usedArchive = new Set<DataTarget>()\n const usedInstance = new Set<DataTarget>()\n\n const take = (list: DataTarget[], used: Set<DataTarget>, test: (target: DataTarget) => boolean): DataTarget | undefined => {\n const found = list.find(target => !used.has(target) && test(target))\n if (found === undefined)\n return undefined\n used.add(found)\n return found\n }\n\n return (origin, workspace, archivedPath) => {\n const inScope = (target: DataTarget): boolean => workspace === undefined || target.workspace === workspace\n const archive = archiveTargets.filter(inScope)\n const instance = instanceTargets.filter(inScope)\n if (origin !== undefined) {\n return take(archive, usedArchive, target => target.origin === origin)\n ?? take(instance, usedInstance, target => target.origin === origin)\n ?? take(archive, usedArchive, target => target.path === archivedPath)\n ?? take(instance, usedInstance, target => target.path === archivedPath)\n }\n return take(archive, usedArchive, target => target.path === archivedPath)\n ?? take(instance, usedInstance, target => target.path === archivedPath)\n }\n}\n\n/**\n * An archived config, lifted to the schema this release reads (an archive is often older than the\n * release restoring it). Lifting needs an explicit numeric `meta.schema`: an unstamped file is a seed\n * or damage, not an older release. `null` means this release cannot read it.\n */\nfunction liftArchived(raw: unknown): Record<string, unknown> | null {\n if (!isRecord(raw))\n return null\n const meta = isRecord(raw.meta) ? raw.meta as { schema?: unknown } : {}\n if (typeof meta.schema !== 'number')\n return null\n const plan = planConfigMigrations(meta.schema)\n if (plan.tooNew || plan.reached !== plan.to)\n return null\n if (plan.steps.length === 0)\n return raw\n const lifted = applyConfigMigrations(raw, meta.schema).config\n // Stamped, so the file records the release that actually wrote this shape.\n return isRecord(lifted) ? stampConfig(lifted as { $schema?: string, meta?: unknown }) : null\n}\n\n/**\n * A restored settings file is accepted when this release can read it through the stores' tolerant\n * parser. The lifted value is returned, so the caller writes a config this release can load.\n */\nfunction readableGlobalSettings(text: string | null): Record<string, unknown> | null {\n if (text === null)\n return null\n try {\n const lifted = liftArchived(JSON.parse(text))\n return lifted !== null && parseGlobalSettings(lifted).config !== null ? lifted : null\n }\n catch {\n return null\n }\n}\n\n/** The workspaces an archive's registry names. Tolerant: the registry only contributes labels. */\nfunction readArchivedRegistry(file: string): ArchivedWorkspace[] {\n const text = readText(file)\n if (text === null)\n return []\n try {\n return parseWorkspacesFile(JSON.parse(text)).workspaces ?? []\n }\n catch {\n return []\n }\n}\n\n/**\n * Where a workspace created by a restore keeps its leaves, under the service's own `dataRoot` rather\n * than the import-time path helpers.\n */\nfunction workspacePathsFor(dataRoot: string, id: string): Pick<BackupWorkspaceSource, 'settingsPath' | 'serversPath' | 'jobsPath' | 'secretsPath'> {\n const dir = path.join(dataRoot, id)\n return {\n settingsPath: path.join(dir, 'settings.json'),\n serversPath: path.join(dir, 'servers.config.json'),\n jobsPath: path.join(dir, 'jobs.config.json'),\n secretsPath: path.join(dir, '.secrets.json'),\n }\n}\n\n/**\n * The manifest is written by us, but an uploaded archive's copy is attacker\n * controlled: never join an unvalidated slug into a path.\n */\nfunction safeSlug(slug: unknown): string | null {\n if (typeof slug !== 'string' || slug.length === 0 || slug.length > 80)\n return null\n if (!/^[\\w.-]+$/.test(slug) || slug === '.' || slug === '..')\n return null\n return slug\n}\n\n/** A flag is valid for one exact file revision, not for the name alone. */\nfunction cacheKey(file: { sizeBytes: number, createdAt: number }): string {\n return `${file.sizeBytes}:${file.createdAt}`\n}\n\n/** True when the tree at `root` contains at least one file (stops at the first). */\nfunction holdsAnyFile(root: string): boolean {\n let stats: fs.Stats | undefined\n try {\n stats = fs.lstatSync(root)\n }\n catch {\n return false\n }\n if (!stats.isDirectory())\n return stats.isFile()\n let names: string[]\n try {\n names = fs.readdirSync(root)\n }\n catch {\n return false\n }\n return names.some(name => holdsAnyFile(path.join(root, name)))\n}\n\n/**\n * A state file's text, decoded by `readStateFile`: a BOM must not make a secrets file unparseable,\n * because that is what would let it fall through to a raw copy.\n */\nfunction readText(file: string): string | null {\n try {\n return readStateFile(file)\n }\n catch {\n return null\n }\n}\n\n/** What every phase of a restore reads and writes, passed explicitly so each phase shows what it touches. */\ninterface RestoreContext {\n plan: AppRestorePlan\n options: RestoreCommandOptions\n sources: BackupSources\n /** Where the archive was unpacked; removed by `applyRestore`'s `finally`. */\n staging: string\n manifest: BackupManifest\n selects: ReturnType<typeof selectionOf>\n /** The writes to run, keyed by item id; insertion order is the apply order. */\n actions: Map<string, () => void | Promise<void>>\n /** Every archived servers file this release can read, selected or not. Written by `planWorkspaceItems`. */\n archivedServers: Map<string, ServerConfig[]>\n /** Workspaces the archive names that this host lacks. Written by `planWorkspaceItems`. */\n createdWorkspaces: Map<string, BackupWorkspaceSource>\n}\n\n/** The plan, narrowed to the fields this side always fills. */\ntype AppRestorePlan = RestorePlan & { appliedIds: string[], skippedItems: RestoreSkip[], createdWorkspaces: string[], replacedUnderRunning: NonNullable<RestorePlan['replacedUnderRunning']> }\n\n/** The two facts about the archive's own settings that the data and restart phases need. */\ninterface ArchivedGlobal {\n /** The archive's `settings.json` text, or null when it carried none. */\n settingsText: string | null\n /** The archive's settings, lifted to this release's schema, or null when unreadable. */\n parsedGlobal: ResolvedGlobalConfig | null\n}\n\n/** What `openArchive` returns once the archive is admitted, unpacked and validated. */\ninterface OpenedArchive {\n ok: true\n manifest: BackupManifest\n}\n\n/** The plan a restore starts from: every field filled, so a refusal is a plan and not a throw. */\nfunction newRestorePlan(options: RestoreCommandOptions): AppRestorePlan {\n return {\n dryRun: !options.confirm,\n encrypted: false,\n needsPassword: false,\n items: [],\n applied: [],\n appliedIds: [],\n skipped: [],\n skippedItems: [],\n restartRequired: false,\n reloaded: false,\n createdWorkspaces: [],\n replacedUnderRunning: [],\n }\n}\n\n/**\n * Archives of the control plane's own state plus whatever paths the configs declare. Restore stays\n * safe by two rules: the archive layout is an allowlist, and a data path is written back only when a\n * config (current, or one the same restore applies) declares it. A password makes the zip WinZip-AES.\n */\nexport class BackupService {\n /** Encrypted flags, cached because reading a central directory is async; refreshed in the background. */\n private readonly flags = new Map<string, { key: string, encrypted: boolean }>()\n private refreshing: Promise<void> | null = null\n /** One scheduled pass at a time: a slow archive must not stack up behind itself. */\n private running = false\n private disposed = false\n /** When this instance last attempted an automatic pass; bounds retries of a pass that wrote nothing. */\n private lastAttemptAt: number | null = null\n /** The newest automatic archive, cached so the per-second `tick()`/`view()` do not rescan the directory. */\n private lastAutomaticSeen: { dir: string, at: number | null } | null = null\n /** Logs a pass deferred by a running restore once, not on every tick. */\n private deferredForRestore = false\n /** Why the most recent scheduled pass failed, cleared by the next that works. */\n private scheduleError: { message: string, at: number } | null = null\n\n constructor(\n private readonly options: {\n /** Relative `backups.dir` values resolve against it (the panel passes `$HHOSTED_HOME/.hh`). */\n dataRoot: string\n getConfig: () => BackupsConfig\n getSources: () => BackupSources\n /** Creates a workspace the archive brought and this host lacks (registry entry and runtime). */\n ensureWorkspace?: (input: { id: string, label: string }) => void\n /** Called after a restore wrote settings/server files; the panel re-reads everything. */\n onRestored?: () => void\n /** Records a dump this entry still has to load, so its next start runs the hook. */\n onLoadPending?: (workspaceId: string, serverId: string, dumpDir: string) => void\n },\n ) {}\n\n /** Reads every archive once, so the first `list()` is already accurate. */\n async warm(): Promise<void> {\n await this.refresh()\n }\n\n dispose(): void {\n this.disposed = true\n }\n\n get directory(): string {\n return this.resolveDir()\n }\n\n /**\n * The policy and the status, carried in the state frame. Not the selection model: that reads every\n * secrets file and stats every archive, which is too costly per frame.\n */\n view(): BackupsView {\n const config = this.options.getConfig()\n const sources = this.options.getSources()\n return {\n enabled: config.enabled,\n dir: this.directory,\n keep: config.keep,\n schedule: { ...config.schedule },\n lastAutomaticAt: this.lastAutomatic(),\n ...(this.scheduleError === null ? {} : { scheduleError: { ...this.scheduleError } }),\n includePaths: [...sources.includePaths],\n }\n }\n\n /** The selection model: every capturable entry and every archive on disk. Never on a per-frame path. */\n selection(): BackupSelection {\n return {\n dir: this.directory,\n entries: this.entries(this.options.getSources()),\n files: this.list(),\n }\n }\n\n list(): BackupFile[] {\n const files = this.scan()\n for (const file of files) {\n const cached = this.flags.get(file.name)\n if (cached === undefined || cached.key !== cacheKey(file))\n void this.scheduleRefresh()\n }\n\n return files.map((file) => {\n const cached = this.flags.get(file.name)\n return {\n ...file,\n encrypted: cached !== undefined && cached.key === cacheKey(file) ? cached.encrypted : false,\n }\n })\n }\n\n /** Validated absolute path for a download, or null when the name is not a backup. */\n resolve(name: string): string | null {\n if (!/^[A-Z0-9][\\w.-]*$/i.test(name) || name.includes('..'))\n return null\n const file = path.join(this.resolveDir(), name)\n return fs.existsSync(file) ? file : null\n }\n\n /**\n * `password` encrypts the archive; it is never stored. `automatic` keeps the two retention counts\n * apart, so a scheduled pass never prunes a manual backup.\n */\n async create(options: { password?: string, include?: string[], exclude?: string[], automatic?: boolean } = {}): Promise<{ ok: boolean, file?: BackupFile, error?: string, warnings?: string[] }> {\n const config = this.options.getConfig()\n if (!config.enabled)\n return { ok: false, error: 'backups are disabled' }\n\n const password = options.password !== undefined && options.password.length > 0 ? options.password : null\n const selects = selectionOf(options)\n // `wanted` answers which fields were named, for the secrets narrowing below.\n const wanted = options.include === undefined ? null : new Set(options.include)\n const capturesGlobal = (id: string): boolean => selects(id)\n // A workspace id alone means every leaf of that workspace.\n const capturesWorkspace = (id: string, suffix: string): boolean => selects(`workspace:${id}:${suffix}`)\n /** The secrets of one scope the request asked for; `null` means every one of them. */\n const selectedSecretFields = (entryId: string, path: string, scope: SecretScope, workspaceId?: string): string[] | null => {\n const present = presentSecretKeys(parseSecrets(readText(path) ?? ''))\n const parts = secretParts(scope, present)\n // Per field: `--include global:secrets:password` names one field, not its siblings.\n const picked = parts.filter((part) => {\n if (selects.isExcluded(entryId) || selects.isExcluded(`${entryId}:${part.key}`))\n return false\n const wantedField = wanted === null\n || wanted.has(entryId)\n || (workspaceId !== undefined && wanted.has(`workspace:${workspaceId}`))\n || wanted.has(`${entryId}:${part.key}`)\n || part.fields.some(field => wanted.has(`${entryId}:${field}`))\n return wantedField\n })\n return picked.length === parts.length ? null : picked.flatMap(part => part.fields)\n }\n\n const dir = this.resolveDir()\n const sources = this.options.getSources()\n // The pid lets a later run reclaim a tree a SIGKILL left behind.\n const staging = path.join(dir, stagingDirName('staging'))\n const createdAt = Date.now()\n // Milliseconds matter: two backups in the same second must not collide.\n const prefix = options.automatic === true ? AUTO_PREFIX : MANUAL_PREFIX\n const name = `${prefix}-${new Date(createdAt).toISOString().replace(/[:T]/g, '-').replace(/\\.\\d+Z$/, '')}-${createdAt % 1000}${SUFFIX}`\n const destination = path.join(dir, name)\n\n try {\n ensureStateDir(staging)\n let captured = 0\n const copy = async (relative: string, source: string, ignoreGenerated = false): Promise<void> => {\n if (await this.copyInto(staging, relative, source, ignoreGenerated))\n captured++\n }\n /**\n * Captures one secrets file, narrowed to the picked secrets; the restore side merges by field.\n */\n const copySecrets = async (relative: string, source: string, entryId: string, scope: SecretScope, workspaceId?: string): Promise<void> => {\n const text = readText(source)\n if (text === null)\n return\n const fields = selectedSecretFields(entryId, source, scope, workspaceId)\n // A whole selection still strips the plaintext first-run password. Never fall back to copying the\n // original bytes: unreadable is not safe to copy verbatim.\n const chosen = fields === null ? withoutInitialPassword(text) : pickSecrets(parseSecrets(text), fields)\n if (chosen === null)\n return\n const target = path.join(staging, relative)\n ensureStateDir(path.dirname(target))\n // 0600, as the live file: the archive must not be more readable than its source.\n fs.writeFileSync(target, chosen.endsWith('\\n') ? chosen : `${chosen}\\n`, { mode: 0o600 })\n captured++\n }\n\n // True when the request touches a secrets entry, one of its leaves, or (for a workspace) the\n // workspace id. Upwards too: a named leaf still needs its file captured.\n const touchesSecrets = (entryId: string, workspaceId?: string): boolean =>\n selects(entryId)\n || (wanted !== null && [...wanted].some(id => id.startsWith(`${entryId}:`)))\n || (workspaceId !== undefined && selects(`workspace:${workspaceId}:secrets`))\n\n if (capturesGlobal('global:settings'))\n await copy('global/settings.json', sources.globalSettingsPath)\n if (touchesSecrets('global:secrets'))\n await copySecrets('global/secrets.json', sources.globalSecretsPath, 'global:secrets', 'global')\n if (capturesGlobal('global:tls'))\n await copy('global/tls', sources.tlsDir)\n // Always: the registry is how a restore onto a blank host learns a workspace exists. Not counted as\n // a capture, so an empty selection is still refused below.\n await this.copyInto(staging, `global/${REGISTRY}`, sources.registryPath)\n\n /**\n * The dump phase, before anything is copied: the dump is the authoritative artifact, and a failed\n * one must not leave an archive that looks complete. Output lands in `dumps/<workspace>/<server>/`.\n */\n const dumped: Array<{ workspaceId: string, serverId: string }> = []\n for (const workspace of sources.workspaces) {\n for (const server of workspace.servers) {\n const hook = server.dump\n if (hook === undefined || hook === null)\n continue\n // The dump belongs to the entry: an exclusion of the entry or its dump skips running the hook.\n if (!selects(`workspace:${workspace.id}:dump:${server.id}`)) {\n continue\n }\n const relative = path.join('dumps', workspace.id, server.id)\n const dumpDir = path.join(staging, relative)\n const result = await runBackupHook(hook, server, dumpDir)\n if (!result.ok) {\n await fs.promises.rm(staging, { recursive: true, force: true })\n return { ok: false, error: hookFailure('dump', server, result) }\n }\n dumped.push({ workspaceId: workspace.id, serverId: server.id })\n }\n }\n\n const data: BackupManifest['data'] = []\n const warnings: string[] = []\n for (const workspace of sources.workspaces) {\n const root = `workspaces/${workspace.id}`\n if (capturesWorkspace(workspace.id, 'settings'))\n await copy(`${root}/settings.json`, workspace.settingsPath)\n if (capturesWorkspace(workspace.id, 'servers'))\n await copy(`${root}/servers.config.json`, workspace.serversPath)\n // Skipped when absent, so a workspace with no jobs gains no empty `jobs.config.json` on restore.\n if (capturesWorkspace(workspace.id, 'jobs'))\n await copy(`${root}/jobs.config.json`, workspace.jobsPath)\n if (touchesSecrets(`workspace:${workspace.id}:secrets`, workspace.id))\n await copySecrets(`${root}/secrets.json`, workspace.secretsPath, `workspace:${workspace.id}:secrets`, 'workspace', workspace.id)\n\n for (const declared of this.declaredData(workspace.servers, sources.includePaths)) {\n if (!declared.included)\n continue\n if (!capturesWorkspace(workspace.id, `data:${declared.path}`))\n continue\n if (!fs.existsSync(declared.path))\n continue\n // The same directory declared by two workspaces (a global include path) is captured once.\n const resolved = path.resolve(declared.path)\n if (data.some(entry => path.resolve(entry.path) === resolved))\n continue\n const slug = slugifyPath(declared.path)\n if (!await this.copyInto(staging, path.join('data', slug), declared.path, declared.ignoreGenerated))\n continue\n captured++\n data.push({ slug, path: declared.path, origin: declared.origin, workspace: workspace.id })\n // Captured but empty (an unmounted volume?): still written, but not silently.\n if (!holdsAnyFile(path.join(staging, 'data', slug)))\n warnings.push(`\"${declared.path}\" was captured but holds no files`)\n }\n }\n\n // A selection (an exclusion is one too) that captured nothing would only produce a manifest.\n if ((wanted !== null || (options.exclude?.length ?? 0) > 0) && captured === 0) {\n await fs.promises.rm(staging, { recursive: true, force: true })\n return { ok: false, error: 'nothing was selected to back up' }\n }\n\n const manifest: BackupManifest = {\n version: 1,\n createdAt,\n hostname: os.hostname(),\n writtenBy: appVersion(),\n schema: CONFIG_SCHEMA,\n data,\n // Distinguishes \"no dump for it\" from \"taken before the hook existed\".\n ...(dumped.length === 0 ? {} : { dumps: dumped }),\n }\n fs.writeFileSync(path.join(staging, MANIFEST), `${JSON.stringify(manifest, null, 2)}\\n`)\n\n await createZip(staging, destination, password === null ? {} : { password })\n\n await fs.promises.rm(staging, { recursive: true, force: true })\n this.prune()\n // A successful run is the one moment this service knows a dead run's tree is not in use.\n this.sweepStaging()\n\n const stats = fs.statSync(destination)\n this.flags.set(name, { key: cacheKey({ sizeBytes: stats.size, createdAt }), encrypted: password !== null })\n if (options.automatic === true && this.lastAutomaticSeen !== null && this.lastAutomaticSeen.dir === dir)\n this.lastAutomaticSeen = { dir, at: Math.max(this.lastAutomaticSeen.at ?? 0, createdAt) }\n return { ok: true, file: { name, sizeBytes: stats.size, createdAt, encrypted: password !== null }, ...(warnings.length === 0 ? {} : { warnings }) }\n }\n catch (error) {\n await fs.promises.rm(staging, { recursive: true, force: true }).catch(() => {})\n await fs.promises.rm(destination, { force: true }).catch(() => {})\n return { ok: false, error: errorMessage(error) }\n }\n }\n\n remove(name: string): boolean {\n const file = this.resolve(name)\n if (file === null)\n return false\n fs.rmSync(file, { force: true })\n this.flags.delete(name)\n if (isAutomatic({ name }))\n this.lastAutomaticSeen = null\n return true\n }\n\n /**\n * Validates an archive, then (when `confirm`) applies the selected items. Data paths come from the\n * current sources or a servers file the same restore applies — never from the manifest alone.\n */\n async restore(archivePath: string, options: RestoreCommandOptions): Promise<RestorePlan> {\n // The lock is taken here so every caller (route, control channel, offline CLI) holds it; a dry run\n // writes nothing and needs none.\n const lock = options.confirm ? acquireRestoreLock(this.options.dataRoot) : null\n if (lock !== null && 'heldBy' in lock) {\n throw new DetailedError(\n `another restore is running (pid ${lock.heldBy.pid}, since ${new Date(lock.heldBy.startedAt).toISOString()}) — wait for it, or remove ${path.join(this.options.dataRoot, 'restore.lock')} if it is stale`,\n { statusCode: 409, code: 'RESTORE_IN_PROGRESS' },\n )\n }\n try {\n return await this.applyRestore(archivePath, options)\n }\n finally {\n if (lock !== null && !('heldBy' in lock))\n lock.release()\n }\n }\n\n // ------------------------------------------------------------- restore\n\n private async applyRestore(archivePath: string, options: RestoreCommandOptions): Promise<RestorePlan> {\n const password = options.password !== undefined && options.password.length > 0 ? options.password : null\n const plan = newRestorePlan(options)\n\n const admitted = await admitArchive(archivePath)\n if (!admitted.ok)\n return { ...plan, error: admitted.error }\n\n const staging = path.join(this.resolveDir(), stagingDirName('restore'))\n\n try {\n const opened = await this.openArchive(plan, admitted.entries, archivePath, staging, password)\n // A refusal before anything is written is answered, not thrown: the plan is the answer.\n if (!('ok' in opened))\n return opened\n\n const ctx = this.restoreContext(plan, options, opened.manifest, staging)\n\n const global = this.planGlobalItems(ctx)\n this.planWorkspaceItems(ctx)\n this.planDataItems(ctx, global)\n this.noteRestartRequired(ctx, global)\n\n if (!options.confirm) {\n // A dry run reports what would happen, before anything is written.\n plan.applied = [...ctx.actions.keys()].map(id => labelOf(plan, id))\n plan.appliedIds = [...ctx.actions.keys()]\n return plan\n }\n\n const failure = await this.runApply(ctx)\n this.registerCreatedWorkspaces(ctx)\n\n // A restore that failed partway still reloads what it wrote, so memory matches the disk.\n if (failure !== null) {\n this.reloadRestored(plan)\n throw failure\n }\n\n await this.stagePendingLoads(ctx)\n\n this.reloadRestored(plan)\n return plan\n }\n catch (error) {\n // Extraction precedes every write, so a rejected password changed nothing.\n if (isInvalidPassword(error))\n return { ...plan, encrypted: true, needsPassword: true, error: 'the password is wrong' }\n // Not transactional: say what already landed.\n const done = plan.applied.length > 0 ? ` — already applied: ${plan.applied.join(', ')}` : ''\n return { ...plan, error: `${errorMessage(error)}${done}` }\n }\n finally {\n fs.rmSync(staging, { recursive: true, force: true })\n // A killed restore leaves an unpacked tree; now the directory is known not to be in use.\n this.sweepStaging()\n }\n }\n\n /** The state every phase reads and writes, built once from the plan and the live sources. */\n private restoreContext(plan: AppRestorePlan, options: RestoreCommandOptions, manifest: BackupManifest, staging: string): RestoreContext {\n return {\n plan,\n options,\n sources: this.options.getSources(),\n staging,\n manifest,\n selects: selectionOf(options),\n actions: new Map<string, () => void | Promise<void>>(),\n archivedServers: new Map<string, ServerConfig[]>(),\n createdWorkspaces: new Map<string, BackupWorkspaceSource>(),\n }\n }\n\n /**\n * Unpacks the archive and refuses it before anything is written. A refusal is answered as a plan;\n * the one throw is a wrong password, which `applyRestore` maps to `needsPassword`.\n */\n private async openArchive(\n plan: AppRestorePlan,\n entries: Awaited<ReturnType<typeof listZip>>,\n archivePath: string,\n staging: string,\n password: string | null,\n ): Promise<OpenedArchive | RestorePlan> {\n plan.encrypted = entries.some(entry => entry.encrypted)\n if (plan.encrypted && password === null)\n return { ...plan, needsPassword: true, error: 'this backup is password-protected' }\n\n ensureStateDir(staging)\n const extracted = await extractZip(archivePath, staging, {\n names: entries.map(entry => entry.name),\n ...(password === null ? {} : { password }),\n })\n for (const name of extracted.skipped) {\n plan.skipped.push(`${name} (symbolic link, skipped)`)\n plan.skippedItems.push({ label: name, reasonKey: 'settings.restore.reasonSymbolicLink' })\n }\n\n const manifestPath = path.join(staging, MANIFEST)\n if (!fs.existsSync(manifestPath))\n return { ...plan, error: 'the archive has no manifest' }\n const manifest = JSON.parse(fs.readFileSync(manifestPath, 'utf8')) as BackupManifest\n\n // A newer schema is refused outright rather than reported as a half-restored setup.\n plan.archive = manifestInfo(manifest)\n if (manifest.schema !== undefined && manifest.schema > CONFIG_SCHEMA) {\n return {\n ...plan,\n error: `written by home-hosted ${manifest.writtenBy ?? 'a newer release'} (config schema ${manifest.schema}); this release understands schema ${CONFIG_SCHEMA}`,\n }\n }\n\n // The dump ids are joined into paths below, and an uploaded manifest is attacker controlled.\n const dumpsValid = manifest.dumps === undefined || (Array.isArray(manifest.dumps) && manifest.dumps.every(dump =>\n isRecord(dump) && !(workspaceIdSchema(dump.workspaceId) instanceof type.errors) && !(serverIdSchema(dump.serverId) instanceof type.errors)))\n if (!dumpsValid)\n return { ...plan, error: 'the archive\\'s manifest names a dump with an invalid workspace or server id' }\n return { ok: true, manifest }\n }\n\n /**\n * The global slices: settings, secrets (plus one leaf per secret), and the TLS pair. Returns the\n * archive's own settings for the later phases.\n */\n private planGlobalItems(ctx: RestoreContext): ArchivedGlobal {\n const { plan, sources, staging, actions } = ctx\n const { secretsApply, addItem } = this.itemWriters(ctx)\n\n // ---------------------------------------------------------------- global\n const settingsText = readText(path.join(staging, 'global', 'settings.json'))\n const liftedGlobal = readableGlobalSettings(settingsText)\n const parsedGlobal = liftedGlobal === null ? null : parseGlobalSettings(liftedGlobal).config\n if (settingsText !== null && parsedGlobal === null) {\n plan.skipped.push('Global settings (the archive\\'s settings are not valid)')\n plan.skippedItems.push({ label: 'Global settings', labelKey: 'settings.backup.entryGlobalSettings', reasonKey: 'settings.restore.reasonInvalidSettings' })\n }\n if (parsedGlobal !== null && liftedGlobal !== null) {\n // The lifted config is written: the archived file's stamp is one this release refuses.\n const globalText = `${JSON.stringify(liftedGlobal, null, 2)}\\n`\n addItem({ id: GLOBAL_RESTORE_ITEMS.settings.id, label: 'Global settings', labelKey: 'settings.backup.entryGlobalSettings', kind: 'settings', restorable: true, note: null }, () => {\n writeFileAtomic(sources.globalSettingsPath, globalText)\n }, [...GLOBAL_RESTORE_ITEMS.settings.aliases])\n }\n\n const globalSecrets = readText(path.join(staging, 'global', 'secrets.json'))\n if (globalSecrets !== null) {\n addItem(\n { id: GLOBAL_RESTORE_ITEMS.credentials.id, label: 'Global secrets (accounts, API tokens)', labelKey: 'settings.backup.entryGlobalSecrets', kind: 'secrets', restorable: true, note: null },\n secretsApply('global', GLOBAL_RESTORE_ITEMS.credentials.id, sources.globalSecretsPath, globalSecrets),\n [...GLOBAL_RESTORE_ITEMS.credentials.aliases],\n )\n // One item per secret, so the password can come back without the API token; each merges by field.\n for (const part of secretParts('global', presentSecretKeys(parseSecrets(globalSecrets)))) {\n const leafId = `${GLOBAL_RESTORE_ITEMS.credentials.id}:${part.key}`\n addItem({\n id: leafId,\n label: `Global secrets: ${SECRET_LABELS[part.key]?.en ?? part.key}`,\n labelKey: 'settings.backup.restoreItemLabel',\n labelParams: { workspace: 'global', item: part.key },\n kind: 'secrets',\n restorable: true,\n note: null,\n }, () => {\n // The whole entry, when it is applied, already merges every field this one carries.\n if (actions.has(GLOBAL_RESTORE_ITEMS.credentials.id))\n return\n mergeIntoFile(sources.globalSecretsPath, globalSecrets, part.fields)\n },\n // The leaf's alias spelling (`secrets:password`), so `--exclude secrets` reaches it like its parent.\n GLOBAL_RESTORE_ITEMS.credentials.aliases.map(alias => `${alias}:${part.key}`))\n }\n }\n\n const tlsInArchive = path.join(staging, 'global', 'tls')\n if (fs.existsSync(tlsInArchive)) {\n const files = fs.readdirSync(tlsInArchive).filter(file => fs.statSync(path.join(tlsInArchive, file)).isFile())\n addItem({ id: GLOBAL_RESTORE_ITEMS.tls.id, label: 'TLS certificate', labelKey: 'settings.backup.entryTlsCertificate', kind: 'tls', restorable: true, note: null }, () => {\n ensureStateDir(sources.tlsDir)\n for (const file of files) {\n const mode = file.endsWith('.key.pem') ? { mode: 0o600 } : {}\n writeFileAtomic(path.join(sources.tlsDir, file), fs.readFileSync(path.join(tlsInArchive, file), 'utf8'), mode)\n }\n }, [...GLOBAL_RESTORE_ITEMS.tls.aliases])\n }\n return { settingsText, parsedGlobal }\n }\n\n /**\n * The two closures every planning phase writes through. `addItem` fills `actions` in call order and\n * `runApply` drains it in that order, so the sequence of `addItem` calls is the apply order.\n */\n private itemWriters(ctx: RestoreContext): {\n secretsApply: (scope: SecretScope, entryId: string, target: string, archived: string) => () => void\n addItem: (item: Omit<RestoreItem, 'selected'>, apply: (() => void | Promise<void>) | null, aliases?: string[]) => void\n } {\n const { plan, selects, actions } = ctx\n\n /**\n * Writes one archived secrets file, always by field: an archive carries only what its selection\n * captured, and the live file may hold secrets the archive predates.\n */\n const secretsApply = (scope: SecretScope, entryId: string, target: string, archived: string): (() => void) => {\n const parts = secretParts(scope, presentSecretKeys(parseSecrets(archived)))\n const take = parts.filter(part => !selects.isExcluded(`${entryId}:${part.key}`)\n && !part.fields.some(field => selects.isExcluded(`${entryId}:${field}`)))\n return (): void => {\n ensureStateDir(path.dirname(target))\n mergeIntoFile(target, archived, take.flatMap(part => part.fields))\n }\n }\n\n const addItem = (item: Omit<RestoreItem, 'selected'>, apply: (() => void | Promise<void>) | null, aliases: string[] = []): void => {\n if (apply === null) {\n plan.items.push({ ...item, selected: false })\n plan.skipped.push(`${item.label}${item.note === null ? '' : ` (${item.note})`}`)\n plan.skippedItems.push({\n label: item.label,\n ...(item.labelKey === undefined ? {} : { labelKey: item.labelKey }),\n ...(item.labelParams === undefined ? {} : { labelParams: item.labelParams }),\n // The note is the reason when there is one.\n reasonKey: item.noteKey ?? 'settings.restore.reasonUnrestorable',\n ...(item.noteParams === undefined ? {} : { reasonParams: item.noteParams }),\n })\n return\n }\n // `selectedBy`, the same rule the route's credential guard asks, so aliases are honoured alike.\n const selected = selectedBy(selects, aliases.length === 0 ? item : { ...item, aliases })\n plan.items.push({ ...item, selected })\n if (selected) {\n actions.set(item.id, apply)\n }\n else {\n plan.skipped.push(`${item.label} (not selected)`)\n plan.skippedItems.push({\n label: item.label,\n ...(item.labelKey === undefined ? {} : { labelKey: item.labelKey }),\n ...(item.labelParams === undefined ? {} : { labelParams: item.labelParams }),\n reasonKey: 'settings.restore.reasonNotSelected',\n })\n }\n }\n return { secretsApply, addItem }\n }\n\n /**\n * One item group per workspace the archive names. A workspace this host lacks is created, not\n * skipped; its directories are made only when a leaf applies, so a dry run writes nothing.\n */\n private planWorkspaceItems(ctx: RestoreContext): void {\n const { plan, sources, staging, actions, archivedServers, createdWorkspaces } = ctx\n // Optional: without a registry each workspace still restores under its own id.\n const archivedWorkspaces = new Map<string, ArchivedWorkspace>()\n for (const entry of readArchivedRegistry(path.join(staging, 'global', REGISTRY)))\n archivedWorkspaces.set(entry.id, entry)\n const { secretsApply, addItem } = this.itemWriters(ctx)\n\n const archiveWorkspaces = path.join(staging, 'workspaces')\n if (fs.existsSync(archiveWorkspaces)) {\n for (const entry of fs.readdirSync(archiveWorkspaces, { withFileTypes: true })) {\n if (!entry.isDirectory())\n continue\n const id = entry.name\n const dir = path.join(archiveWorkspaces, id)\n const settings = readText(path.join(dir, 'settings.json'))\n const servers = readText(path.join(dir, 'servers.config.json'))\n const jobs = readText(path.join(dir, 'jobs.config.json'))\n const secrets = readText(path.join(dir, 'secrets.json'))\n // The registry is the only place a label lives; fall back to the id.\n const archivedLabel = archivedWorkspaces.get(id)?.label ?? id\n\n // Created rather than skipped, so the data pass never matches across workspaces.\n const workspace = sources.workspaces.find(candidate => candidate.id === id)\n ?? createdWorkspaces.get(id)\n ?? (workspaceIdSchema(id) instanceof type.errors\n ? undefined\n : { id, label: archivedLabel, ...workspacePathsFor(this.options.dataRoot, id), servers: [] as ServerConfig[] })\n if (workspace === undefined) {\n plan.skipped.push(`${id} (not a usable workspace id)`)\n plan.skippedItems.push({ label: id, reasonKey: 'settings.restore.reasonInvalidWorkspace' })\n continue\n }\n if (!sources.workspaces.some(candidate => candidate.id === id))\n createdWorkspaces.set(id, workspace)\n\n if (settings !== null) {\n const liftedSettings = readableWorkspaceSettings(settings)\n if (liftedSettings !== null) {\n const settingsText = `${JSON.stringify(liftedSettings, null, 2)}\\n`\n addItem({ id: `workspace:${id}:settings`, label: `${workspace.label}: Settings`, labelKey: 'settings.backup.restoreItemLabel', labelParams: { workspace: workspace.label, item: 'settings' }, kind: 'settings', workspaceId: id, restorable: true, note: null }, () => {\n ensureStateDir(path.dirname(workspace.settingsPath))\n writeFileAtomic(workspace.settingsPath, settingsText)\n })\n }\n else {\n plan.skipped.push(`${workspace.label}: Settings (the archive's settings are not valid)`)\n plan.skippedItems.push({ label: `${workspace.label}: Settings`, labelKey: 'settings.backup.restoreItemLabel', labelParams: { workspace: workspace.label, item: 'settings' }, reasonKey: 'settings.restore.reasonInvalidSettings' })\n }\n }\n\n if (servers !== null) {\n const parsed = readableServersFile(servers)\n const liftedServers = parsed === null ? null : liftArchived(JSON.parse(servers))\n if (parsed !== null && liftedServers !== null) {\n const serversText = `${JSON.stringify(liftedServers, null, 2)}\\n`\n archivedServers.set(id, parsed)\n addItem({ id: `workspace:${id}:servers`, label: `${workspace.label}: Servers`, labelKey: 'settings.backup.restoreItemLabel', labelParams: { workspace: workspace.label, item: 'servers' }, kind: 'servers', workspaceId: id, restorable: true, note: null }, () => {\n ensureStateDir(path.dirname(workspace.serversPath))\n writeFileAtomic(workspace.serversPath, serversText)\n })\n }\n else {\n plan.skipped.push(`${workspace.label}: Servers (the archive's servers are not valid)`)\n plan.skippedItems.push({ label: `${workspace.label}: Servers`, labelKey: 'settings.backup.restoreItemLabel', labelParams: { workspace: workspace.label, item: 'servers' }, reasonKey: 'settings.restore.reasonInvalidServers' })\n }\n }\n\n if (jobs !== null) {\n const liftedJobs = readableJobsFile(jobs)\n if (liftedJobs !== null) {\n const jobsText = `${JSON.stringify(liftedJobs, null, 2)}\\n`\n addItem({ id: `workspace:${id}:jobs`, label: `${workspace.label}: Jobs`, labelKey: 'settings.backup.restoreItemLabel', labelParams: { workspace: workspace.label, item: 'jobs' }, kind: 'jobs', workspaceId: id, restorable: true, note: null }, () => {\n writeRestoredJobs(workspace.jobsPath, jobsText)\n })\n }\n else {\n plan.skipped.push(`${workspace.label}: Jobs (the archive's jobs are not valid)`)\n plan.skippedItems.push({ label: `${workspace.label}: Jobs`, labelKey: 'settings.backup.restoreItemLabel', labelParams: { workspace: workspace.label, item: 'jobs' }, reasonKey: 'settings.restore.reasonInvalidJobs' })\n }\n }\n\n if (secrets !== null) {\n addItem({ id: `workspace:${id}:secrets`, label: `${workspace.label}: Secrets`, labelKey: 'settings.backup.restoreItemLabel', labelParams: { workspace: workspace.label, item: 'secrets' }, kind: 'secrets', workspaceId: id, restorable: true, note: null }, secretsApply('workspace', `workspace:${id}:secrets`, workspace.secretsPath, secrets))\n for (const part of secretParts('workspace', presentSecretKeys(parseSecrets(secrets)))) {\n addItem({\n id: `workspace:${id}:secrets:${part.key}`,\n label: `${workspace.label}: ${SECRET_LABELS[part.key]?.en ?? part.key}`,\n labelKey: 'settings.backup.restoreItemLabel',\n labelParams: { workspace: workspace.label, item: part.key },\n kind: 'secrets',\n workspaceId: id,\n restorable: true,\n note: null,\n }, () => {\n if (actions.has(`workspace:${id}:secrets`))\n return\n ensureStateDir(path.dirname(workspace.secretsPath))\n mergeIntoFile(workspace.secretsPath, secrets, part.fields)\n })\n }\n }\n }\n }\n }\n\n /**\n * Data-path items and dumps. A data path is written only to a path a config declares. Runs after\n * the workspace phase: it reads `archivedServers` and the workspace items in `actions`.\n */\n private planDataItems(ctx: RestoreContext, global: ArchivedGlobal): void {\n const { plan, sources, staging, manifest, selects } = ctx\n const { addItem } = this.itemWriters(ctx)\n\n const { archiveAll, archiveTargets, instanceTargets } = this.collectDataTargets(ctx, global)\n\n const matchTarget = dataTargetMatcher(archiveTargets, instanceTargets)\n\n // Running entries, read at plan time so a dry run names the same paths the apply replaces.\n const runningOwners = new Set(\n (sources.runningServers?.() ?? []).map(entry => `${entry.workspaceId}:${entry.serverId}`),\n )\n\n this.planDumpItems(ctx)\n\n const archivedEntries = Array.isArray(manifest.data) ? manifest.data.filter(isRecord) : []\n for (const entry of archivedEntries) {\n const archivedPath = typeof entry.path === 'string' ? entry.path : ''\n const origin = typeof entry.origin === 'string' ? entry.origin : undefined\n const workspace = typeof entry.workspace === 'string' ? entry.workspace : undefined\n const from = path.join(staging, 'data', safeSlug(entry.slug) ?? legacySlug(archivedPath))\n const target = matchTarget(origin, workspace, archivedPath)\n const targetWorkspace = target?.workspace ?? workspace\n const base: Omit<RestoreItem, 'selected'> = {\n id: target === undefined ? `data:${archivedPath}` : `workspace:${target.workspace}:data:${target.path}`,\n label: target?.path ?? archivedPath,\n kind: 'data',\n restorable: false,\n note: null,\n ...(targetWorkspace === undefined ? {} : { workspaceId: targetWorkspace }),\n }\n const aliases = [`data:${archivedPath}`]\n\n if (target === undefined) {\n this.planUnplacedDataItem(ctx, archiveAll, { base, aliases, origin, workspace })\n continue\n }\n if (!fs.existsSync(from)) {\n addItem({ ...base, note: 'missing from the archive', noteKey: 'settings.backup.noteMissingFromArchive' }, null, aliases)\n continue\n }\n\n // Recorded at plan time, so a dry run shows what to stop before applying.\n const ownerId = target.origin.split(':')[0] ?? ''\n // The same rule as `addItem`, so an alias counts as covering the path.\n const covered = selectedBy(selects, { ...base, aliases })\n if (covered && runningOwners.has(`${target.workspace}:${ownerId}`))\n plan.replacedUnderRunning.push({ workspaceId: target.workspace, serverId: ownerId, path: target.path })\n\n addItem(\n { ...base, restorable: true, ...(target.path === archivedPath ? { note: null } : { note: `restored from ${archivedPath}`, noteKey: 'settings.backup.noteRestoredFrom', noteParams: { path: archivedPath } }) },\n // `cpSync` follows symlinks already in the destination, so each destination is checked where the\n // link resolves; links themselves are never recreated.\n () => copyTree(from, target.path, (_source, destination) => isInsideResolved(target.path, destination)),\n aliases,\n )\n }\n }\n\n /**\n * A dump is a restorable item so the selection can name it. Applying it writes nothing: the `load`\n * hook replays it after everything has landed.\n */\n private planDumpItems(ctx: RestoreContext): void {\n const { staging, manifest } = ctx\n const { addItem } = this.itemWriters(ctx)\n\n for (const dump of manifest.dumps ?? []) {\n const from = path.join(staging, 'dumps', dump.workspaceId, dump.serverId)\n if (!fs.existsSync(from))\n continue\n const id = `workspace:${dump.workspaceId}:dump:${dump.serverId}`\n addItem({\n id,\n label: `dump:${dump.serverId}`,\n kind: 'data',\n restorable: true,\n workspaceId: dump.workspaceId,\n note: null,\n }, () => {\n // Nothing to write here: the entry's `load` hook replays the dump.\n })\n }\n }\n\n /**\n * An archived data path nothing on this host will receive, reported with why: the backup's config\n * declares it but is not being restored, or neither config does.\n */\n private planUnplacedDataItem(\n ctx: RestoreContext,\n archiveAll: DataTarget[],\n placed: {\n base: Omit<RestoreItem, 'selected'>\n aliases: string[]\n origin: string | undefined\n workspace: string | undefined\n },\n ): void {\n const { addItem } = this.itemWriters(ctx)\n const { base, aliases, origin, workspace } = placed\n const declaredByBackup = archiveAll.some(candidate =>\n candidate.origin === origin && (workspace === undefined || candidate.workspace === workspace))\n addItem({\n ...base,\n note: declaredByBackup\n ? 'declared by the backup\\'s config, which is not being restored'\n : 'not declared by this config, nor by the backup',\n noteKey: declaredByBackup\n ? 'settings.backup.noteDeclaredByBackup'\n : 'settings.backup.noteNotDeclared',\n }, null, aliases)\n }\n\n /**\n * Every data path a restore could write. `archiveAll` answers \"did the backup's config declare it?\"\n * for the report; `archiveTargets` holds only those from a servers file this restore applies.\n * An applied `global:settings` brings its own `includePaths`.\n */\n private collectDataTargets(ctx: RestoreContext, global: ArchivedGlobal): {\n archiveAll: DataTarget[]\n archiveTargets: DataTarget[]\n instanceTargets: DataTarget[]\n } {\n const { sources, actions, archivedServers } = ctx\n const { parsedGlobal } = global\n\n const instanceTargets: DataTarget[] = []\n for (const workspace of sources.workspaces) {\n for (const declared of this.declaredData(workspace.servers, sources.includePaths)) {\n if (!declared.included)\n continue\n instanceTargets.push({ workspace: workspace.id, path: declared.path, origin: declared.origin })\n }\n }\n\n const archivedIncludePaths = actions.has('global:settings') && parsedGlobal !== null\n ? parsedGlobal.backups.includePaths\n : sources.includePaths\n const archiveAll: DataTarget[] = []\n const archiveTargets: DataTarget[] = []\n for (const [id, servers] of archivedServers) {\n for (const declared of this.declaredData(servers, archivedIncludePaths)) {\n if (!declared.included)\n continue\n const target = { workspace: id, path: declared.path, origin: declared.origin }\n archiveAll.push(target)\n if (actions.has(`workspace:${id}:servers`))\n archiveTargets.push(target)\n }\n }\n\n return { archiveAll, archiveTargets, instanceTargets }\n }\n\n /** Whether the panel's own listener must restart — computed even for a dry run. */\n private noteRestartRequired(ctx: RestoreContext, global: ArchivedGlobal): void {\n const { plan, sources, actions } = ctx\n const { settingsText, parsedGlobal } = global\n\n if (parsedGlobal !== null && actions.has('global:settings') && settingsText !== null) {\n const currentText = readText(sources.globalSettingsPath)\n const current = readableGlobalSettings(currentText)\n plan.restartRequired = JSON.stringify(parsedGlobal.control) !== JSON.stringify(current === null ? null : (parseGlobalSettings(current).config?.control ?? null))\n }\n }\n\n /**\n * Runs every planned write in order, stopping at the first failure, which is returned for the\n * caller to reload what landed and rethrow.\n */\n private async runApply(ctx: RestoreContext): Promise<unknown> {\n const { plan, actions } = ctx\n\n let failure: unknown = null\n for (const [id, apply] of actions) {\n try {\n await apply()\n }\n catch (error) {\n failure = error\n break\n }\n plan.applied.push(labelOf(plan, id))\n plan.appliedIds.push(id)\n }\n return failure\n }\n\n /**\n * Registers the workspaces this restore created — last, and only those something was applied to:\n * a known but empty workspace is worse than an absent one.\n */\n private registerCreatedWorkspaces(ctx: RestoreContext): void {\n const { plan, createdWorkspaces } = ctx\n\n for (const workspace of createdWorkspaces.values()) {\n if (!plan.appliedIds.some(id => id.startsWith(`workspace:${workspace.id}:`)))\n continue\n this.options.ensureWorkspace?.({ id: workspace.id, label: workspace.label })\n plan.createdWorkspaces.push(workspace.id)\n }\n }\n\n /**\n * Stages each restored dump for its entry's own `load` hook, which runs on the entry's next start\n * (the hook needs a server that answers). Staged before the caller reloads, which reads `pendingLoad`.\n */\n private async stagePendingLoads(ctx: RestoreContext): Promise<void> {\n const { plan, staging, manifest, actions } = ctx\n const archivedDumps = manifest.dumps ?? []\n\n const pendingLoads: Array<{ workspaceId: string, serverId: string, staged: string }> = []\n for (const entry of archivedDumps) {\n if (!plan.appliedIds.some(id => id.startsWith(`workspace:${entry.workspaceId}:`)))\n continue\n // Deselecting `workspace:<id>:dump:<server>` must not load it.\n if (!actions.has(`workspace:${entry.workspaceId}:dump:${entry.serverId}`))\n continue\n // The archive's config, not the live one: `sources` still describes the host as it was.\n const archivedServers = readArchivedServers(staging, entry.workspaceId)\n const server = archivedServers.find(candidate => candidate.id === entry.serverId)\n // The dump is still restored as a file when the entry has no `load` hook; say so.\n if (server?.load === undefined || server.load === null) {\n plan.skipped.push(`the dump for \"${entry.serverId}\" was restored but this entry has no load hook`)\n continue\n }\n const dumpDir = path.join(staging, 'dumps', entry.workspaceId, entry.serverId)\n if (!fs.existsSync(dumpDir)) {\n plan.skipped.push(`the dump for \"${entry.serverId}\" is missing from the archive`)\n continue\n }\n const staged = path.join(this.options.dataRoot, PENDING_LOAD, entry.workspaceId, entry.serverId)\n await copyTree(dumpDir, staged, () => true)\n pendingLoads.push({ workspaceId: entry.workspaceId, serverId: entry.serverId, staged })\n plan.hooks = [...(plan.hooks ?? []), {\n serverId: entry.serverId,\n workspaceId: entry.workspaceId,\n action: 'load',\n ok: true,\n output: 'staged — runs when this entry next starts',\n }]\n }\n\n for (const load of pendingLoads)\n this.options.onLoadPending?.(load.workspaceId, load.serverId, load.staged)\n }\n\n /** The panel re-reads the restored settings and servers, so what the archive brought exists immediately. */\n private reloadRestored(plan: RestorePlan & { appliedIds: string[] }): void {\n if (this.options.onRestored === undefined || !plan.appliedIds.some(id => RELOADABLE.test(id)))\n return\n plan.reloaded = true\n this.options.onRestored()\n }\n\n /** Selectable entries: the three global slices, then one per workspace. */\n private entries(sources: BackupSources): BackupEntry[] {\n const missing = (path: string, key: string): Pick<BackupEntry, 'note' | 'noteKey'> => {\n const absent = this.missingNote(path)\n return absent === null ? { note: null } : { note: absent, noteKey: key }\n }\n const entries: BackupEntry[] = [\n { id: 'global:settings', label: 'Global settings', labelKey: 'settings.backup.entryGlobalSettings', kind: 'settings', ...missing(sources.globalSettingsPath, 'settings.backup.noteMissing'), items: [] },\n { id: 'global:secrets', label: 'Global secrets (accounts, API tokens)', labelKey: 'settings.backup.entryGlobalSecrets', kind: 'secrets', ...missing(sources.globalSecretsPath, 'settings.backup.noteMissing'), items: this.secretItems('global', 'global:secrets', sources.globalSecretsPath) },\n { id: 'global:tls', label: 'TLS certificate', labelKey: 'settings.backup.entryTlsCertificate', kind: 'tls', ...missing(sources.tlsDir, 'settings.backup.noteMissing'), items: [] },\n ]\n\n for (const workspace of sources.workspaces) {\n entries.push({\n id: `workspace:${workspace.id}`,\n label: workspace.label,\n kind: 'workspace',\n workspaceId: workspace.id,\n note: null,\n items: this.workspaceItems(workspace, sources.includePaths),\n })\n }\n\n return entries\n }\n\n /**\n * One leaf per secret, so one can come back without the others. Derived from the file's own keys,\n * so a secret added later appears without a second list.\n */\n private secretItems(scope: SecretScope, entryId: string, path: string): BackupEntry['items'] {\n const present = presentSecretKeys(parseSecrets(readText(path) ?? ''))\n const parts = secretParts(scope, present)\n // Every known slot is listed, set or not; an unknown key in the file is listed as its own name.\n const known = KNOWN_SECRET_KEYS[scope]\n const missing = known.filter(key => !parts.some(part => part.key === key) && !LEGACY_SECRET_SLOTS.has(key))\n return [\n ...parts.map(part => ({\n id: `${entryId}:${part.key}`,\n label: SECRET_LABELS[part.key]?.en ?? part.key,\n ...(SECRET_LABELS[part.key]?.key === undefined ? {} : { labelKey: SECRET_LABELS[part.key]!.key }),\n kind: 'secrets' as const,\n secret: part.key,\n included: true,\n note: null,\n })),\n ...missing.map(key => ({\n id: `${entryId}:${key}`,\n label: SECRET_LABELS[key]?.en ?? key,\n ...(SECRET_LABELS[key]?.key === undefined ? {} : { labelKey: SECRET_LABELS[key]!.key }),\n kind: 'secrets' as const,\n secret: key,\n included: false,\n // The same wording and key as a missing file.\n note: 'not set',\n noteKey: 'settings.backup.noteMissing',\n })),\n ]\n }\n\n private workspaceItems(workspace: BackupWorkspaceSource, includePaths: string[]): BackupEntry['items'] {\n const id = workspace.id\n const note = (path: string): Pick<BackupEntry['items'][number], 'note' | 'noteKey'> => {\n const absent = this.missingNote(path)\n return absent === null ? { note: null } : { note: absent, noteKey: 'settings.backup.noteMissing' }\n }\n const items: BackupEntry['items'] = [\n { id: `workspace:${id}:settings`, label: 'Settings', labelKey: 'settings.backup.leafSettings', kind: 'settings', included: true, ...note(workspace.settingsPath) },\n { id: `workspace:${id}:servers`, label: 'Servers', labelKey: 'settings.backup.leafServers', kind: 'servers', included: true, ...note(workspace.serversPath) },\n { id: `workspace:${id}:jobs`, label: 'Jobs', labelKey: 'settings.backup.leafJobs', kind: 'jobs', included: true, ...note(workspace.jobsPath) },\n // The whole-file leaf is what older clients send; the per-secret leaves follow it.\n { id: `workspace:${id}:secrets`, label: 'Secrets', labelKey: 'settings.backup.leafSecrets', kind: 'secrets', included: true, ...note(workspace.secretsPath) },\n ...this.secretItems('workspace', `workspace:${id}:secrets`, workspace.secretsPath),\n ]\n\n for (const declared of this.declaredData(workspace.servers, includePaths)) {\n items.push({\n id: `workspace:${id}:data:${declared.path}`,\n label: declared.path,\n kind: 'data',\n path: declared.path,\n origin: declared.origin,\n included: declared.included,\n note: declared.note,\n ...(declared.noteKey === undefined ? {} : { noteKey: declared.noteKey }),\n ...(declared.noteParams === undefined ? {} : { noteParams: declared.noteParams }),\n ignoreGenerated: declared.ignoreGenerated,\n })\n }\n\n return items\n }\n\n /** Declared data paths, vetoing any that contains the archive directory (it would contain itself). */\n private declaredData(servers: ServerConfig[], includePaths: string[]): BackupPath[] {\n const archiveDir = path.resolve(this.resolveDir())\n return resolveBackupPaths(servers, includePaths, this.backupVars(servers)).map((entry) => {\n if (entry.included && isInside(entry.path, archiveDir))\n return { ...entry, included: false, note: 'contains the backup directory', noteKey: 'settings.backup.noteContainsBackupDir' }\n return entry\n })\n }\n\n /** The `{dataRoot}` a config expands to, without a module-level state root. */\n private backupVars(servers: ServerConfig[]): BackupVars {\n const first = servers[0]\n return {\n projectDir,\n // The `.hh` directory the panel passes sits directly under the real `dataRoot`.\n dataRoot: first === undefined\n ? path.dirname(path.resolve(this.options.dataRoot))\n : String(serverTemplateVars(first).dataRoot ?? projectDir),\n home: os.homedir(),\n }\n }\n\n /**\n * Reclaims staging trees (capture or restore) a killed run left behind, where no `catch` ran. The\n * owner's pid decides, never an age: another live run's tree is a capture in progress.\n */\n private sweepStaging(): void {\n const dir = this.resolveDir()\n let names: string[]\n try {\n names = fs.readdirSync(dir)\n }\n catch {\n return\n }\n\n for (const name of names) {\n const owner = stagingOwner(name)\n if (owner === null || owner === process.pid || isProcessAlive(owner))\n continue\n try {\n fs.rmSync(path.join(dir, name), { recursive: true, force: true })\n }\n catch {\n // A tree this process may not remove is the next run's attempt, not a backup failure.\n }\n }\n }\n\n /** Newest-first listing, without the encryption flag, which needs a read. */\n private scan(): Array<Omit<BackupFile, 'encrypted'>> {\n const dir = this.resolveDir()\n let names: string[] = []\n try {\n names = fs.readdirSync(dir)\n }\n catch {\n return []\n }\n\n return names\n .filter(name => name.endsWith(SUFFIX))\n .flatMap((name) => {\n try {\n const stats = fs.statSync(path.join(dir, name))\n return [{ name, sizeBytes: stats.size, createdAt: archiveStamp(name) ?? Math.round(stats.mtimeMs) }]\n }\n catch {\n return []\n }\n })\n .sort((a, b) => b.createdAt - a.createdAt)\n }\n\n /** Single-flight: a state frame must never queue a pile of reads. */\n private scheduleRefresh(): Promise<void> {\n this.refreshing ??= this.refresh().finally(() => {\n this.refreshing = null\n })\n return this.refreshing\n }\n\n private async refresh(): Promise<void> {\n const dir = this.resolveDir()\n const listed = this.scan()\n\n for (const file of listed) {\n const key = cacheKey(file)\n if (this.flags.get(file.name)?.key === key)\n continue\n try {\n const entries = await listZip(path.join(dir, file.name))\n this.flags.set(file.name, { key, encrypted: entries.some(entry => entry.encrypted) })\n }\n catch {\n // Unreadable stays unmarked here; restoring it reports the real reason.\n this.flags.set(file.name, { key, encrypted: false })\n }\n }\n\n const present = new Set(listed.map(file => file.name))\n for (const name of [...this.flags.keys()]) {\n if (!present.has(name))\n this.flags.delete(name)\n }\n }\n\n private missingNote(target: string): string | null {\n return fs.existsSync(target) ? null : 'not set'\n }\n\n /** Copies one source into the staging tree; false when there was nothing there. */\n private async copyInto(staging: string, relative: string, source: string, ignoreGenerated = false): Promise<boolean> {\n if (!fs.existsSync(source))\n return false\n const target = path.join(staging, relative)\n ensureStateDir(path.dirname(target))\n // Never copy the archive directory into itself. Both sides resolved: `copyTree` walks the real path\n // of a declared root that is itself a link.\n const archiveDir = resolveExisting(path.resolve(this.resolveDir()))\n const root = resolveExisting(path.resolve(source))\n await copyTree(source, target, (from) => {\n const resolved = path.resolve(from)\n if (isInside(archiveDir, resolved))\n return false\n // Secrets never travel raw, nor the temp copy a crashed atomic write leaves.\n if (isSecretDocument(path.basename(resolved)))\n return false\n if (!ignoreGenerated || resolved === root)\n return true\n return !isGeneratedPath(path.relative(root, resolved))\n })\n return true\n }\n\n /**\n * Drops the oldest archives past their own limit: `schedule.keep` for automatic ones, `keep` for\n * the rest, so a scheduled pass never prunes a hand-taken archive.\n */\n private prune(): void {\n const config = this.options.getConfig()\n const files = this.list()\n const automatic = files.filter(isAutomatic)\n const manual = files.filter(file => ARCHIVE_NAME.exec(file.name)?.[1] === MANUAL_PREFIX)\n\n for (const file of automatic.slice(config.schedule.keep)) this.remove(file.name)\n for (const file of manual.slice(config.keep)) this.remove(file.name)\n this.sweepPartials()\n }\n\n /**\n * An archive killed mid-write leaves its `.<name>.partial` behind (`createZip` renames only on\n * success). An hour old is never a write in progress — a live one keeps touching its mtime.\n */\n private sweepPartials(now = Date.now()): void {\n const dir = this.resolveDir()\n let names: string[] = []\n try {\n names = fs.readdirSync(dir)\n }\n catch {\n return\n }\n for (const name of names.filter(entry => entry.startsWith('.') && entry.endsWith(`${SUFFIX}.partial`))) {\n const file = path.join(dir, name)\n try {\n if (now - fs.statSync(file).mtimeMs > 60 * 60_000)\n fs.rmSync(file, { force: true })\n }\n catch {\n // gone already, or not ours to remove\n }\n }\n }\n\n /** When the newest automatic archive was written, or null when there is none. */\n private lastAutomatic(): number | null {\n const dir = this.resolveDir()\n if (this.lastAutomaticSeen?.dir !== dir)\n this.lastAutomaticSeen = { dir, at: this.scan().find(isAutomatic)?.createdAt ?? null }\n return this.lastAutomaticSeen.at\n }\n\n /** Runs one scheduled pass when it is due: cheap on every panel tick, never blocking, never two at once. */\n tick(now = Date.now()): void {\n if (this.disposed || this.running)\n return\n const config = this.options.getConfig()\n if (!config.enabled || config.schedule.intervalMs <= 0)\n return\n\n // The newest archive is the durable clock; the last attempt bounds a pass that wrote none.\n const last = this.lastAutomatic()\n const latest = last === null ? this.lastAttemptAt : Math.max(last, this.lastAttemptAt ?? 0)\n if (latest !== null && now - latest < config.schedule.intervalMs)\n return\n\n // A pass now would capture a half-restored tree; wait for the restore, without spending the attempt.\n const restoring = restoreLockHolder(this.options.dataRoot)\n if (restoring !== null) {\n if (!this.deferredForRestore)\n logger.info(`the scheduled backup is waiting for the restore that is running (pid ${restoring.pid})`)\n this.deferredForRestore = true\n return\n }\n this.deferredForRestore = false\n\n this.running = true\n this.lastAttemptAt = now\n // The configured scope; omitted is the full default. A scope that lost everything meets `create`'s\n // \"nothing was selected\" refusal, so it shows on the page instead of writing empty archives.\n void this.create({ automatic: true, ...scopeSelection(config.schedule.scope) })\n .then((result) => {\n // Remembered for the page: a silent failure looks like a schedule not yet due.\n if (result.ok) {\n this.scheduleError = null\n for (const warning of result.warnings ?? [])\n logger.warn('the scheduled backup', warning)\n return\n }\n this.scheduleError = { message: result.error ?? 'the scheduled backup failed', at: Date.now() }\n logger.warn('the scheduled backup failed', result.error)\n })\n .catch((error: unknown) => {\n this.scheduleError = { message: errorMessage(error), at: Date.now() }\n logger.error('the scheduled backup failed', error)\n })\n .finally(() => {\n this.running = false\n })\n }\n\n private resolveDir(): string {\n const configured = this.options.getConfig().dir\n return path.isAbsolute(configured) ? configured : path.resolve(this.options.dataRoot, configured)\n }\n}\n\n/** Whether an archive came from the schedule rather than from a person. */\nfunction isAutomatic(file: { name: string }): boolean {\n return ARCHIVE_NAME.exec(file.name)?.[1] === AUTO_PREFIX\n}\n\n/** The label of one item, for `applied`; items are built before actions run. */\nfunction labelOf(plan: RestorePlan, id: string): string {\n return plan.items.find(item => item.id === id)?.label ?? id\n}\n\n/**\n * Restores only `fields` from an archived secrets document into a live one, leaving other keys alone\n * and clearing a selected field the archive does not carry.\n */\nfunction mergeIntoFile(target: string, archived: string, fields: string[]): void {\n const current = parseSecrets(readText(target) ?? '')\n const merged = mergeSecrets(current, parseSecrets(archived), fields)\n writeFileAtomic(target, `${JSON.stringify(merged, null, 2)}\\n`, { mode: 0o600 })\n}\n\n/** What an archive says about where it came from; both fields absent on older archives. */\nfunction manifestInfo(manifest: BackupManifest): NonNullable<RestorePlan['archive']> {\n return {\n ...(manifest.writtenBy === undefined ? {} : { writtenBy: manifest.writtenBy }),\n ...(manifest.schema === undefined ? {} : { schema: manifest.schema }),\n }\n}\n\n/**\n * `servers.config.json` as a readability gate, lifted first when older; the store applies the\n * workspace's own defaults on the next load. `null` means unreadable.\n */\nfunction readableServersFile(text: string): ServerConfig[] | null {\n try {\n const lifted = liftArchived(JSON.parse(text))\n if (lifted === null)\n return null\n const result = parseServersFile(lifted, {})\n return result.errors.length === 0 ? result.servers : null\n }\n catch {\n return null\n }\n}\n\n/** A workspace settings file is adopted only when this release can read it, lifted when older. */\nfunction readableWorkspaceSettings(text: string): Record<string, unknown> | null {\n try {\n const lifted = liftArchived(JSON.parse(text))\n return lifted !== null && parseWorkspaceSettings(lifted).config !== null ? lifted : null\n }\n catch {\n return null\n }\n}\n\n/**\n * `jobs.config.json` under the same gate as the servers file. One unrunnable job refuses the file:\n * a half-applied schedule fires some jobs and says nothing about the rest.\n */\nfunction readableJobsFile(text: string): Record<string, unknown> | null {\n try {\n const lifted = liftArchived(JSON.parse(text))\n if (lifted === null)\n return null\n // An archive from before 0.20 says `timeoutMs`; the store would lift it on read, so lift it here.\n const document = liftJobsDocument(lifted).document\n const parsed = jobsFileSchema(document)\n if (parsed instanceof type.errors)\n return null\n for (const job of parsed.jobs) {\n if (jobProblems(job).length > 0)\n return null\n }\n return document\n }\n catch {\n return null\n }\n}\n\n/**\n * Writes a restored `jobs.config.json`, keeping the replaced file as `<file>.bak` (the name\n * `migrate` uses) when there was one.\n */\nfunction writeRestoredJobs(file: string, text: string): void {\n if (fs.existsSync(file))\n fs.copyFileSync(file, `${file}.bak`)\n writeFileAtomic(file, text)\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAaA,SAAgB,eAAe,KAAa,IAAoB;CAC9D,OAAO,KAAK,KAAK,KAAK,GAAG,GAAG,UAAU;AACxC;AAEA,SAAgB,eAAe,MAAiC;CAC9D,IAAI;EACF,MAAM,SAAS,iBAAiB,KAAK,MAAM,GAAG,aAAa,MAAM,MAAM,CAAC,CAAC;EACzE,OAAO,kBAAkB,KAAK,SAAS,OAAO;CAChD,QACM;EACJ,OAAO;CACT;AACF;;AAGA,IAAM,yBAAS,IAAI,IAAY;;AAG/B,SAAgB,gBAAgB,MAAc,OAA4B;CACxE,IAAI;EACF,gBAAgB,MAAM,GAAG,KAAK,UAAU,KAAK,EAAE,GAAG;EAClD,OAAO;CACT,SACO,OAAO;EACZ,MAAM,OAAQ,MAAgC,QAAQ;EACt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AAE,QAAQ,SAAS,OAAO;CACrE;AACF;;;;;AAMA,SAAS,oBAAoB,MAAqC;CAChE,IAAI;EACF,MAAM,SAAS,aAAa,KAAK,MAAM,IAAI,CAAC;EAC5C,IAAI,WAAW,MACb,OAAO;EACT,MAAM,SAAS,iBAAiB,QAAQ,CAAC,CAAC;EAC1C,OAAO,OAAO,OAAO,WAAW,IAAI,OAAO,UAAU;CACvD,QACM;EACJ,OAAO;CACT;AACF;;AAGA,SAAS,0BAA0B,MAA8C;CAC/E,IAAI;EACF,MAAM,SAAS,aAAa,KAAK,MAAM,IAAI,CAAC;EAC5C,OAAO,WAAW,QAAQ,uBAAuB,MAAM,CAAC,CAAC,WAAW,OAAO,SAAS;CACtF,QACM;EACJ,OAAO;CACT;AACF;;;;;AAMA,SAAS,iBAAiB,MAA8C;CACtE,IAAI;EACF,MAAM,SAAS,aAAa,KAAK,MAAM,IAAI,CAAC;EAC5C,IAAI,WAAW,MACb,OAAO;EAET,MAAM,WAAW,iBAAiB,MAAM,CAAC,CAAC;EAC1C,MAAM,SAAS,eAAe,QAAQ;EACtC,IAAI,kBAAkB,KAAK,QACzB,OAAO;EACT,KAAK,MAAM,OAAO,OAAO,MACvB,IAAI,YAAY,GAAG,CAAC,CAAC,SAAS,GAC5B,OAAO;EAEX,OAAO;CACT,QACM;EACJ,OAAO;CACT;AACF;;;;;AAMA,SAAS,kBAAkB,MAAc,MAAoB;CAC3D,IAAI,GAAG,WAAW,IAAI,GACpB,GAAG,aAAa,MAAM,GAAG,KAAK,KAAK;CACrC,gBAAgB,MAAM,IAAI;AAC5B"}
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
import os from "node:os";
|
|
2
|
+
//#region src/helpers/bind.ts
|
|
3
|
+
/** `os.networkInterfaces()` is slow and `lanAddress()` runs per server per state frame, so it is cached. */
|
|
4
|
+
var LAN_ADDRESS_TTL_MS = 3e4;
|
|
5
|
+
var cached = null;
|
|
6
|
+
/** This machine's first non-internal IPv4 address, or null; cached for `LAN_ADDRESS_TTL_MS`. */
|
|
7
|
+
function lanAddress(now = Date.now()) {
|
|
8
|
+
if (cached !== null && now - cached.at < LAN_ADDRESS_TTL_MS) return cached.value;
|
|
9
|
+
let value = null;
|
|
10
|
+
for (const entries of Object.values(os.networkInterfaces())) {
|
|
11
|
+
for (const entry of entries ?? []) if (entry.family === "IPv4" && !entry.internal) {
|
|
12
|
+
value = entry.address;
|
|
13
|
+
break;
|
|
14
|
+
}
|
|
15
|
+
if (value !== null) break;
|
|
16
|
+
}
|
|
17
|
+
cached = {
|
|
18
|
+
value,
|
|
19
|
+
at: now
|
|
20
|
+
};
|
|
21
|
+
return value;
|
|
22
|
+
}
|
|
23
|
+
/** The address a local client dials for a listener bound to `bound`: wildcard binds answer on loopback. */
|
|
24
|
+
function dialHost(bound) {
|
|
25
|
+
return bound === "0.0.0.0" || bound === "::" || bound.length === 0 ? "127.0.0.1" : bound;
|
|
26
|
+
}
|
|
27
|
+
function bindHost(bind) {
|
|
28
|
+
if (bind === "local") return "127.0.0.1";
|
|
29
|
+
if (bind === "lan") return "0.0.0.0";
|
|
30
|
+
return bind;
|
|
31
|
+
}
|
|
32
|
+
function displayHost(bind) {
|
|
33
|
+
if (bind === "local") return "127.0.0.1";
|
|
34
|
+
if (bind === "lan") return lanAddress() ?? "127.0.0.1";
|
|
35
|
+
return bind;
|
|
36
|
+
}
|
|
37
|
+
function isExposed(bind) {
|
|
38
|
+
return bindHost(bind) !== "127.0.0.1";
|
|
39
|
+
}
|
|
40
|
+
//#endregion
|
|
41
|
+
export { lanAddress as a, isExposed as i, dialHost as n, displayHost as r, bindHost as t };
|
|
42
|
+
|
|
43
|
+
//# sourceMappingURL=bind-DIxrnUst.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"bind-DIxrnUst.js","names":[],"sources":["../../src/helpers/bind.ts"],"sourcesContent":["import os from 'node:os'\n\n/** `os.networkInterfaces()` is slow and `lanAddress()` runs per server per state frame, so it is cached. */\nconst LAN_ADDRESS_TTL_MS = 30_000\n\nlet cached: { value: string | null, at: number } | null = null\n\n/** This machine's first non-internal IPv4 address, or null; cached for `LAN_ADDRESS_TTL_MS`. */\nexport function lanAddress(now = Date.now()): string | null {\n if (cached !== null && now - cached.at < LAN_ADDRESS_TTL_MS)\n return cached.value\n\n let value: string | null = null\n for (const entries of Object.values(os.networkInterfaces())) {\n for (const entry of entries ?? []) {\n if (entry.family === 'IPv4' && !entry.internal) {\n value = entry.address\n break\n }\n }\n if (value !== null)\n break\n }\n\n cached = { value, at: now }\n return value\n}\n\nexport function forgetLanAddress(): void {\n cached = null\n}\n\n/** The address a local client dials for a listener bound to `bound`: wildcard binds answer on loopback. */\nexport function dialHost(bound: string): string {\n return bound === '0.0.0.0' || bound === '::' || bound.length === 0 ? '127.0.0.1' : bound\n}\n\nexport function bindHost(bind: string): string {\n if (bind === 'local')\n return '127.0.0.1'\n if (bind === 'lan')\n return '0.0.0.0'\n return bind\n}\n\nexport function displayHost(bind: string): string {\n if (bind === 'local')\n return '127.0.0.1'\n if (bind === 'lan')\n return lanAddress() ?? '127.0.0.1'\n return bind\n}\n\nexport function isExposed(bind: string): boolean {\n return bindHost(bind) !== '127.0.0.1'\n}\n"],"mappings":";;;AAGA,IAAM,qBAAqB;AAE3B,IAAI,SAAsD;;AAG1D,SAAgB,WAAW,MAAM,KAAK,IAAI,GAAkB;CAC1D,IAAI,WAAW,QAAQ,MAAM,OAAO,KAAK,oBACvC,OAAO,OAAO;CAEhB,IAAI,QAAuB;CAC3B,KAAK,MAAM,WAAW,OAAO,OAAO,GAAG,kBAAkB,CAAC,GAAG;EAC3D,KAAK,MAAM,SAAS,WAAW,CAAC,GAC9B,IAAI,MAAM,WAAW,UAAU,CAAC,MAAM,UAAU;GAC9C,QAAQ,MAAM;GACd;EACF;EAEF,IAAI,UAAU,MACZ;CACJ;CAEA,SAAS;EAAE;EAAO,IAAI;CAAI;CAC1B,OAAO;AACT;;AAOA,SAAgB,SAAS,OAAuB;CAC9C,OAAO,UAAU,aAAa,UAAU,QAAQ,MAAM,WAAW,IAAI,cAAc;AACrF;AAEA,SAAgB,SAAS,MAAsB;CAC7C,IAAI,SAAS,SACX,OAAO;CACT,IAAI,SAAS,OACX,OAAO;CACT,OAAO;AACT;AAEA,SAAgB,YAAY,MAAsB;CAChD,IAAI,SAAS,SACX,OAAO;CACT,IAAI,SAAS,OACX,OAAO,WAAW,KAAK;CACzB,OAAO;AACT;AAEA,SAAgB,UAAU,MAAuB;CAC/C,OAAO,SAAS,IAAI,MAAM;AAC5B"}
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
import { t as __exportAll } from "./rolldown-runtime-D7D4PA-g.js";
|
|
2
|
+
import fs from "node:fs";
|
|
3
|
+
import { Buffer } from "node:buffer";
|
|
4
|
+
//#region src/helpers/config-text.ts
|
|
5
|
+
var config_text_exports = /* @__PURE__ */ __exportAll({
|
|
6
|
+
decodeStateFile: () => decodeStateFile,
|
|
7
|
+
readStateFile: () => readStateFile
|
|
8
|
+
});
|
|
9
|
+
/**
|
|
10
|
+
* Decodes a hand-editable state file as Windows editors save it: a UTF-8 BOM is stripped and
|
|
11
|
+
* UTF-16 (what `>` produces in PowerShell) is decoded. Takes a `Buffer` because a `'utf8'` read
|
|
12
|
+
* has already lost what tells them apart.
|
|
13
|
+
*/
|
|
14
|
+
function decodeStateFile(bytes) {
|
|
15
|
+
if (bytes.length >= 2) {
|
|
16
|
+
if (bytes[0] === 255 && bytes[1] === 254) return stripBom(bytes.subarray(2).toString("utf16le"));
|
|
17
|
+
if (bytes[0] === 254 && bytes[1] === 255) {
|
|
18
|
+
const swapped = Buffer.from(bytes.subarray(2));
|
|
19
|
+
swapped.swap16();
|
|
20
|
+
return stripBom(swapped.toString("utf16le"));
|
|
21
|
+
}
|
|
22
|
+
}
|
|
23
|
+
return stripBom(bytes.toString("utf8"));
|
|
24
|
+
}
|
|
25
|
+
function stripBom(text) {
|
|
26
|
+
return text.charCodeAt(0) === 65279 ? text.slice(1) : text;
|
|
27
|
+
}
|
|
28
|
+
function readStateFile(file) {
|
|
29
|
+
return decodeStateFile(fs.readFileSync(file));
|
|
30
|
+
}
|
|
31
|
+
//#endregion
|
|
32
|
+
export { readStateFile as n, config_text_exports as t };
|
|
33
|
+
|
|
34
|
+
//# sourceMappingURL=config-text-DxMOQQnk.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"config-text-DxMOQQnk.js","names":[],"sources":["../../src/helpers/config-text.ts"],"sourcesContent":["import { Buffer } from 'node:buffer'\nimport fs from 'node:fs'\n\n/**\n * Decodes a hand-editable state file as Windows editors save it: a UTF-8 BOM is stripped and\n * UTF-16 (what `>` produces in PowerShell) is decoded. Takes a `Buffer` because a `'utf8'` read\n * has already lost what tells them apart.\n */\nexport function decodeStateFile(bytes: Buffer): string {\n if (bytes.length >= 2) {\n if (bytes[0] === 0xFF && bytes[1] === 0xFE)\n return stripBom(bytes.subarray(2).toString('utf16le'))\n if (bytes[0] === 0xFE && bytes[1] === 0xFF) {\n // UTF-16BE: swap into LE, the only order Node decodes.\n const swapped = Buffer.from(bytes.subarray(2))\n swapped.swap16()\n return stripBom(swapped.toString('utf16le'))\n }\n }\n return stripBom(bytes.toString('utf8'))\n}\n\nfunction stripBom(text: string): string {\n return text.charCodeAt(0) === 0xFEFF ? text.slice(1) : text\n}\n\nexport function readStateFile(file: string): string {\n return decodeStateFile(fs.readFileSync(file))\n}\n"],"mappings":";;;;;;;;;;;;;AAQA,SAAgB,gBAAgB,OAAuB;CACrD,IAAI,MAAM,UAAU,GAAG;EACrB,IAAI,MAAM,OAAO,OAAQ,MAAM,OAAO,KACpC,OAAO,SAAS,MAAM,SAAS,CAAC,CAAC,CAAC,SAAS,SAAS,CAAC;EACvD,IAAI,MAAM,OAAO,OAAQ,MAAM,OAAO,KAAM;GAE1C,MAAM,UAAU,OAAO,KAAK,MAAM,SAAS,CAAC,CAAC;GAC7C,QAAQ,OAAO;GACf,OAAO,SAAS,QAAQ,SAAS,SAAS,CAAC;EAC7C;CACF;CACA,OAAO,SAAS,MAAM,SAAS,MAAM,CAAC;AACxC;AAEA,SAAS,SAAS,MAAsB;CACtC,OAAO,KAAK,WAAW,CAAC,MAAM,QAAS,KAAK,MAAM,CAAC,IAAI;AACzD;AAEA,SAAgB,cAAc,MAAsB;CAClD,OAAO,gBAAgB,GAAG,aAAa,IAAI,CAAC;AAC9C"}
|