home-hosted 0.12.0 → 0.13.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (221) hide show
  1. package/README.md +95 -49
  2. package/dist/chunks/{archive-DpCwA8Nf.js → archive-DP-XQR8X.js} +15 -2
  3. package/dist/chunks/archive-DP-XQR8X.js.map +1 -0
  4. package/dist/chunks/{atomic-CEfCUfkQ.js → atomic-C1PfJpE7.js} +3 -2
  5. package/dist/chunks/atomic-C1PfJpE7.js.map +1 -0
  6. package/dist/chunks/{backup-CPrJVPJI.js → backup-CZcVca2a.js} +101 -76
  7. package/dist/chunks/backup-CZcVca2a.js.map +1 -0
  8. package/dist/chunks/{backups-Bd2SF2qd.js → backups-CFRaWe_m.js} +881 -536
  9. package/dist/chunks/backups-CFRaWe_m.js.map +1 -0
  10. package/dist/chunks/{contracts-ku5ypHXJ.js → contracts-CMBD1TF9.js} +381 -407
  11. package/dist/chunks/contracts-CMBD1TF9.js.map +1 -0
  12. package/dist/chunks/{daemon-TwXk5vb8.js → daemon-qKVECISl.js} +52 -20
  13. package/dist/chunks/daemon-qKVECISl.js.map +1 -0
  14. package/dist/chunks/{docker-CGv4Uv7w.js → docker-Cy9Lyvda.js} +4 -3
  15. package/dist/chunks/docker-Cy9Lyvda.js.map +1 -0
  16. package/dist/chunks/{down-BlX5X3bm.js → down-pKbGCW9d.js} +22 -17
  17. package/dist/chunks/down-pKbGCW9d.js.map +1 -0
  18. package/dist/chunks/{init-DdmqHVra.js → init-BZ7hK9Vf.js} +19 -6
  19. package/dist/chunks/init-BZ7hK9Vf.js.map +1 -0
  20. package/dist/chunks/{last-stop-BZ08Z89-.js → last-stop-C-BXz_XI.js} +6 -5
  21. package/dist/chunks/last-stop-C-BXz_XI.js.map +1 -0
  22. package/dist/chunks/{layout-D74TGUnr.js → layout-DwTtmund.js} +2 -2
  23. package/dist/chunks/{layout-D74TGUnr.js.map → layout-DwTtmund.js.map} +1 -1
  24. package/dist/chunks/lazy-Ce5zEAq1.js +66 -0
  25. package/dist/chunks/lazy-Ce5zEAq1.js.map +1 -0
  26. package/dist/chunks/{log-buffer-HnP0jKhZ.js → log-buffer-Dy9HHDMD.js} +114 -50
  27. package/dist/chunks/log-buffer-Dy9HHDMD.js.map +1 -0
  28. package/dist/chunks/{logs-gI_69Q1P.js → logs---TI_bxM.js} +23 -21
  29. package/dist/chunks/logs---TI_bxM.js.map +1 -0
  30. package/dist/chunks/{migrate-BTlsibvF.js → migrate-Cfoq-Vgh.js} +5 -5
  31. package/dist/chunks/{migrate-BTlsibvF.js.map → migrate-Cfoq-Vgh.js.map} +1 -1
  32. package/dist/chunks/{nanny-CjnnrIpm.js → nanny-B-Eu0sFW.js} +3 -3
  33. package/dist/chunks/{nanny-CjnnrIpm.js.map → nanny-B-Eu0sFW.js.map} +1 -1
  34. package/dist/chunks/{nanny-20aBXL1o.js → nanny-BtWfy0QH.js} +121 -23
  35. package/dist/chunks/nanny-BtWfy0QH.js.map +1 -0
  36. package/dist/chunks/{nanny-DUaAfCV-.js → nanny-ChMtq1Zl.js} +3 -3
  37. package/dist/chunks/{nanny-DUaAfCV-.js.map → nanny-ChMtq1Zl.js.map} +1 -1
  38. package/dist/chunks/{nanny-sweep-Ca9kPAVi.js → nanny-sweep-DErnlPY1.js} +5 -4
  39. package/dist/chunks/nanny-sweep-DErnlPY1.js.map +1 -0
  40. package/dist/chunks/{parse-B9owE47G.js → parse-DhmG26fI.js} +4 -4
  41. package/dist/chunks/{parse-B9owE47G.js.map → parse-DhmG26fI.js.map} +1 -1
  42. package/dist/chunks/{paths-BT94q6-w.js → paths-CGlGDrOU.js} +36 -2
  43. package/dist/chunks/paths-CGlGDrOU.js.map +1 -0
  44. package/dist/chunks/{restart-UZgeDukG.js → restart-Des4DrAN.js} +25 -59
  45. package/dist/chunks/restart-Des4DrAN.js.map +1 -0
  46. package/dist/chunks/{schema-o7Lgk0V1.js → schema-B240VXcV.js} +11 -10
  47. package/dist/chunks/schema-B240VXcV.js.map +1 -0
  48. package/dist/chunks/{secrets-D7PdYh71.js → secrets-BieELnZh.js} +22 -4
  49. package/dist/chunks/secrets-BieELnZh.js.map +1 -0
  50. package/dist/chunks/{server-BuIeSsRu.js → server-Bge2r2qQ.js} +3 -3
  51. package/dist/chunks/{server-BuIeSsRu.js.map → server-Bge2r2qQ.js.map} +1 -1
  52. package/dist/chunks/{set-password-DegMumPh.js → set-password-D5vZqqSX.js} +7 -7
  53. package/dist/chunks/set-password-D5vZqqSX.js.map +1 -0
  54. package/dist/chunks/{set-token-21d1FTDC.js → set-token-obPiEJYk.js} +7 -7
  55. package/dist/chunks/set-token-obPiEJYk.js.map +1 -0
  56. package/dist/chunks/{settings-BVSBnIwJ.js → settings-xu-XTfWg.js} +126 -35
  57. package/dist/chunks/settings-xu-XTfWg.js.map +1 -0
  58. package/dist/chunks/{setup-temp-XiuAtiW2.js → setup-temp-CAN4_bA-.js} +6 -6
  59. package/dist/chunks/setup-temp-CAN4_bA-.js.map +1 -0
  60. package/dist/chunks/{src-BL97vLVb.js → src-BtWMFmzZ.js} +2246 -1061
  61. package/dist/chunks/src-BtWMFmzZ.js.map +1 -0
  62. package/dist/chunks/{status-EuWdRq8Q.js → status-DT1EsA-B.js} +12 -8
  63. package/dist/chunks/status-DT1EsA-B.js.map +1 -0
  64. package/dist/chunks/{ui-DbPuwddJ.js → ui-D562aqw5.js} +9 -7
  65. package/dist/chunks/ui-D562aqw5.js.map +1 -0
  66. package/dist/chunks/{ui-revert-BhqOAhmM.js → ui-revert-EkBBwRTt.js} +3 -3
  67. package/dist/chunks/{ui-revert-BhqOAhmM.js.map → ui-revert-EkBBwRTt.js.map} +1 -1
  68. package/dist/chunks/{ui-switch-CMoslPO2.js → ui-switch-BnZTdMDd.js} +3 -3
  69. package/dist/chunks/{ui-switch-CMoslPO2.js.map → ui-switch-BnZTdMDd.js.map} +1 -1
  70. package/dist/chunks/{ui-update-TTBBoDik.js → ui-update-_xryLYxw.js} +5 -5
  71. package/dist/chunks/{ui-update-TTBBoDik.js.map → ui-update-_xryLYxw.js.map} +1 -1
  72. package/dist/chunks/{up-C4H13hBw.js → up-Pdz-l6IH.js} +25 -11
  73. package/dist/chunks/up-Pdz-l6IH.js.map +1 -0
  74. package/dist/chunks/{usage-CSBgLRN5.js → usage-DFrCVXpT.js} +29 -3
  75. package/dist/chunks/usage-DFrCVXpT.js.map +1 -0
  76. package/dist/chunks/{workspaces-CAln2sQ7.js → workspaces-DYcfvKV_.js} +16 -8
  77. package/dist/chunks/workspaces-DYcfvKV_.js.map +1 -0
  78. package/dist/chunks/wsl-temperature-BiCI4iK6.js.map +1 -1
  79. package/dist/cli.js +80 -70
  80. package/dist/cli.js.map +1 -1
  81. package/dist/client.js +25 -1
  82. package/dist/client.js.map +1 -1
  83. package/dist/types/api/backups.d.ts +8 -3
  84. package/dist/types/api/control.d.ts +4 -3
  85. package/dist/types/api/events.d.ts +2 -1
  86. package/dist/types/api/health.d.ts +1 -0
  87. package/dist/types/api/metrics.d.ts +3 -1
  88. package/dist/types/api/settings.d.ts +2 -2
  89. package/dist/types/api/state.d.ts +8 -2
  90. package/dist/types/app.d.ts +26 -11
  91. package/dist/types/cli/backup.d.ts +7 -0
  92. package/dist/types/cli/down.d.ts +5 -0
  93. package/dist/types/cli/logs.d.ts +14 -2
  94. package/dist/types/cli/restart.d.ts +0 -1
  95. package/dist/types/cli/set-password.d.ts +2 -2
  96. package/dist/types/cli/up.d.ts +8 -2
  97. package/dist/types/client.d.ts +5618 -11
  98. package/dist/types/config/secrets.d.ts +2 -0
  99. package/dist/types/config/settings.d.ts +54 -8
  100. package/dist/types/config/store.d.ts +16 -3
  101. package/dist/types/config/workspaces.d.ts +4 -1
  102. package/dist/types/helpers/copy-tree.d.ts +5 -0
  103. package/dist/types/helpers/daemon.d.ts +20 -7
  104. package/dist/types/helpers/error.d.ts +8 -0
  105. package/dist/types/helpers/event-stream.d.ts +21 -0
  106. package/dist/types/helpers/openapi.d.ts +12 -24
  107. package/dist/types/helpers/paths.d.ts +18 -0
  108. package/dist/types/helpers/utf8-chunks.d.ts +15 -0
  109. package/dist/types/middleware/auth.d.ts +19 -3
  110. package/dist/types/providers/host.d.ts +1 -1
  111. package/dist/types/providers/log-tail.d.ts +27 -0
  112. package/dist/types/providers/nanny-sweep.d.ts +3 -0
  113. package/dist/types/providers/nanny.d.ts +10 -0
  114. package/dist/types/providers/proc.d.ts +9 -0
  115. package/dist/types/providers/process.d.ts +17 -0
  116. package/dist/types/providers/telegram.d.ts +45 -3
  117. package/dist/types/providers/wsl-temperature.d.ts +0 -4
  118. package/dist/types/services/auth.d.ts +36 -4
  119. package/dist/types/services/backups.d.ts +125 -1
  120. package/dist/types/services/ddns.d.ts +5 -0
  121. package/dist/types/services/exposure.d.ts +54 -1
  122. package/dist/types/services/history.d.ts +1 -0
  123. package/dist/types/services/host-monitor.d.ts +1 -0
  124. package/dist/types/services/log-buffer.d.ts +11 -0
  125. package/dist/types/services/log-files.d.ts +1 -11
  126. package/dist/types/services/log-relay.d.ts +0 -1
  127. package/dist/types/services/panel.d.ts +19 -0
  128. package/dist/types/services/proxy-certificates/certificates.d.ts +116 -0
  129. package/dist/types/services/proxy.d.ts +46 -69
  130. package/dist/types/services/state.d.ts +0 -3
  131. package/dist/types/services/supervisor/entry.d.ts +10 -0
  132. package/dist/types/services/supervisor/health.d.ts +3 -2
  133. package/dist/types/services/supervisor/output.d.ts +126 -0
  134. package/dist/types/services/supervisor/persistent.d.ts +4 -1
  135. package/dist/types/services/supervisor/records.d.ts +81 -1
  136. package/dist/types/services/supervisor.d.ts +32 -0
  137. package/dist/types/shared/action-outcome.d.ts +25 -0
  138. package/dist/types/shared/api-client.d.ts +218 -4
  139. package/dist/types/shared/backup-scope.d.ts +58 -0
  140. package/dist/types/shared/contracts.d.ts +142 -200
  141. package/dist/types/shared/ddns-form.d.ts +13 -0
  142. package/dist/types/shared/form-repair.d.ts +6 -0
  143. package/dist/types/shared/lazy.d.ts +4 -0
  144. package/dist/types/shared/live-frames.d.ts +22 -0
  145. package/dist/types/shared/live-series.d.ts +21 -0
  146. package/dist/types/shared/live-store.d.ts +72 -0
  147. package/dist/types/shared/patch-diff.d.ts +13 -2
  148. package/dist/types/shared/proxy-form.d.ts +2 -0
  149. package/dist/types/shared/server-form.d.ts +121 -0
  150. package/dist/types/shared/stream-access.d.ts +20 -0
  151. package/docs/API.md +45 -16
  152. package/docs/BACKUPS.md +31 -11
  153. package/docs/CLI.md +34 -61
  154. package/docs/DDNS.md +3 -1
  155. package/docs/NOTIFICATIONS.md +7 -1
  156. package/docs/REVERSE_PROXY.md +7 -1
  157. package/docs/SECURITY.md +21 -10
  158. package/docs/SERVERS.md +102 -23
  159. package/docs/UI_CREATION.md +10 -1
  160. package/docs/demo/blank-host-restore.sh +4 -3
  161. package/package.json +5 -7
  162. package/uis/stock/dist/assets/CopyButton-BUBKRJyY.js +1 -0
  163. package/uis/stock/dist/assets/GlobalSettingsView-yYMcRWvt.js +1 -0
  164. package/uis/stock/dist/assets/LogViewer-DIliXy62.js +1 -0
  165. package/uis/stock/dist/assets/LogsView-B7Z-7RNg.js +1 -0
  166. package/uis/stock/dist/assets/Modal-DmKa5Qpp.js +39 -0
  167. package/uis/stock/dist/assets/ProxyView-DvZiNkwb.js +1 -0
  168. package/uis/stock/dist/assets/ServerDetailView-6idGT_EX.js +2 -0
  169. package/uis/stock/dist/assets/SettingsShell-CeGtleYI.js +1 -0
  170. package/uis/stock/dist/assets/SettingsView-BrhJIrmk.js +2 -0
  171. package/uis/stock/dist/assets/de-BRITeb0H.js +1 -0
  172. package/uis/stock/dist/assets/es-B2zIEssV.js +1 -0
  173. package/uis/stock/dist/assets/fr-s0ZOBEqh.js +1 -0
  174. package/uis/stock/dist/assets/index-C1MehbKy.css +2 -0
  175. package/uis/stock/dist/assets/index-CnBN54wF.js +15 -0
  176. package/uis/stock/dist/assets/ja-CU7MR85V.js +1 -0
  177. package/uis/stock/dist/assets/ko-tL5Me6d-.js +1 -0
  178. package/uis/stock/dist/assets/ru-92yrvkNJ.js +1 -0
  179. package/uis/stock/dist/assets/vi-CzvY16k2.js +1 -0
  180. package/uis/stock/dist/assets/zh-CN-DDwFW_uW.js +1 -0
  181. package/uis/stock/dist/index.html +3 -2
  182. package/uis/stock/dist/ui.json +3 -3
  183. package/dist/chunks/archive-DpCwA8Nf.js.map +0 -1
  184. package/dist/chunks/atomic-CEfCUfkQ.js.map +0 -1
  185. package/dist/chunks/backup-CPrJVPJI.js.map +0 -1
  186. package/dist/chunks/backups-Bd2SF2qd.js.map +0 -1
  187. package/dist/chunks/contracts-ku5ypHXJ.js.map +0 -1
  188. package/dist/chunks/daemon-TwXk5vb8.js.map +0 -1
  189. package/dist/chunks/docker-CGv4Uv7w.js.map +0 -1
  190. package/dist/chunks/down-BlX5X3bm.js.map +0 -1
  191. package/dist/chunks/init-DdmqHVra.js.map +0 -1
  192. package/dist/chunks/last-stop-BZ08Z89-.js.map +0 -1
  193. package/dist/chunks/log-buffer-HnP0jKhZ.js.map +0 -1
  194. package/dist/chunks/logs-gI_69Q1P.js.map +0 -1
  195. package/dist/chunks/nanny-20aBXL1o.js.map +0 -1
  196. package/dist/chunks/nanny-sweep-Ca9kPAVi.js.map +0 -1
  197. package/dist/chunks/paths-BT94q6-w.js.map +0 -1
  198. package/dist/chunks/restart-UZgeDukG.js.map +0 -1
  199. package/dist/chunks/schema-o7Lgk0V1.js.map +0 -1
  200. package/dist/chunks/secrets-D7PdYh71.js.map +0 -1
  201. package/dist/chunks/set-password-DegMumPh.js.map +0 -1
  202. package/dist/chunks/set-token-21d1FTDC.js.map +0 -1
  203. package/dist/chunks/settings-BVSBnIwJ.js.map +0 -1
  204. package/dist/chunks/setup-temp-XiuAtiW2.js.map +0 -1
  205. package/dist/chunks/src-BL97vLVb.js.map +0 -1
  206. package/dist/chunks/status-EuWdRq8Q.js.map +0 -1
  207. package/dist/chunks/ui-DbPuwddJ.js.map +0 -1
  208. package/dist/chunks/up-C4H13hBw.js.map +0 -1
  209. package/dist/chunks/usage-CSBgLRN5.js.map +0 -1
  210. package/dist/chunks/workspaces-CAln2sQ7.js.map +0 -1
  211. package/docs/RESTORE_DEMO.md +0 -306
  212. package/uis/stock/dist/assets/de-DyGrM1KK.js +0 -1
  213. package/uis/stock/dist/assets/es-BebHdc0E.js +0 -1
  214. package/uis/stock/dist/assets/fr-DsDTrxhI.js +0 -1
  215. package/uis/stock/dist/assets/index-6LANO2Ua.css +0 -2
  216. package/uis/stock/dist/assets/index-D06cUZbM.js +0 -56
  217. package/uis/stock/dist/assets/ja-D3RARJjW.js +0 -1
  218. package/uis/stock/dist/assets/ko-CKI3dFoD.js +0 -1
  219. package/uis/stock/dist/assets/ru-DEU5ujXt.js +0 -1
  220. package/uis/stock/dist/assets/vi-ULKPnasj.js +0 -1
  221. package/uis/stock/dist/assets/zh-CN-tCvnOxWy.js +0 -1
package/README.md CHANGED
@@ -10,8 +10,10 @@
10
10
 
11
11
  Point it at the things you run — a gateway, a media server, a bot, a database — and it starts them,
12
12
  watches them, restarts what dies, and shows you one page of what is going on. Split them into
13
- [workspaces](#-workspaces) when one panel holds more than one setup, and
14
- [bring your own UI](#-bring-your-own-ui-byou) when you want one that fits you exactly.
13
+ [workspaces](#-workspaces) when one panel holds more than one setup (a workspace is just a named
14
+ group that owns its own servers, secrets and logs), and
15
+ [bring your own UI](#-bring-your-own-ui-byou) (BYOU: a static site the panel serves instead of the
16
+ stock one) when you want one that fits you exactly.
15
17
 
16
18
  [![npm](https://img.shields.io/npm/v/home-hosted.svg)](https://www.npmjs.com/package/home-hosted)
17
19
  [![Downloads](https://img.shields.io/npm/dm/home-hosted.svg)](https://www.npmjs.com/package/home-hosted)
@@ -90,7 +92,19 @@ npx home-hosted down # stop the panel *and* everything it started
90
92
  ```
91
93
 
92
94
  Open **<http://127.0.0.1:3999>**, sign in with the printed password, and change it under **Global
93
- settings → Authentication**. <sub>Needs Node 24+. `pnpm dlx home-hosted …` works too.</sub>
95
+ settings → Authentication**. Then supervise something: **➕ Add server** in the panel, or add an entry
96
+ to `~/.home-hosted/.hh/default/servers.config.json` and run `npx home-hosted start <id>`.
97
+ <sub>Needs Node 24+. `pnpm dlx home-hosted …` works too. `--port`/`--host` on `up` are saved to
98
+ `settings.json`, so the next plain `up` binds the same way.</sub>
99
+
100
+ > [!IMPORTANT]
101
+ > **Before you expose it to anything but this machine.** It listens on `127.0.0.1` until you say
102
+ > otherwise, and it refuses to bind further — or to be put behind its own reverse proxy — while it
103
+ > still has the generated password. So: set your own password first, *then* bind to `lan` (UI,
104
+ > `settings.json`, or `up --host lan`). And an API token is **full admin**: it can create and start a
105
+ > server entry, and an entry runs any command as the panel's user. Changing the password does **not**
106
+ > revoke a token — rotate it with `set-token --generate`. The whole model, including which actions a
107
+ > token is refused: [SECURITY.md](./docs/SECURITY.md).
94
108
 
95
109
  <details>
96
110
  <summary><b>📦 Install it instead of npx-ing it</b></summary>
@@ -170,11 +184,12 @@ curl -N -H "Authorization: Bearer hh_…" http://127.0.0.1:3999/api/events
170
184
  home-hosted status --json # where everything is
171
185
  ```
172
186
 
173
- Building in TypeScript? `import { createClient } from 'home-hosted/client'` — a ~3 KB client typed
174
- from the panel's own routes, with the live event stream ([API.md](./docs/API.md#the-typescript-client)).
175
- Any other language: `GET /openapi/spec.json` describes all of it (browse at `/openapi/ui`), so an
176
- OpenAPI generator gives you a typed client. `GET /healthz` needs no credential and is `503` while any server needs attention —
177
- point your uptime monitor at it.
187
+ Building in TypeScript? `import { createClient } from 'home-hosted/client'` — a ~2 KB gzipped client
188
+ (5.2 KB raw) typed from the panel's own routes, with the live event stream
189
+ ([API.md](./docs/API.md#the-typescript-client)).
190
+ Any other language: `GET /openapi/spec.json` documents every API route and its bodies (browse at
191
+ `/openapi/ui`), so an OpenAPI generator gives you a typed client. `GET /healthz` needs no credential
192
+ and is `503` while any server needs attention — point your uptime monitor at it.
178
193
 
179
194
  > [!WARNING]
180
195
  > **A token is full admin.** It can create and start server entries, which run commands as the
@@ -189,19 +204,11 @@ point your uptime monitor at it.
189
204
  | --- | --- | --- |
190
205
  | `GET /api/state` | the full snapshot: settings, every workspace and server, host vitals | ❌ |
191
206
  | `GET /api/events` | SSE: `hello` (full state), then `state`, `server`, `log`, `ping` | optional |
192
- | `GET`/`POST /api/workspaces`, `PATCH`/`DELETE /api/workspaces/:id` | the workspace registry | ❌ |
193
- | `GET`/`POST /api/servers`, `GET`/`PUT`/`PATCH`/`DELETE /api/servers/:id` | entries — `PUT` is create-or-replace, so a re-run converges | ✅ |
194
- | `POST /api/servers/:id/{start,stop,restart,free-port}`, `/api/servers/{start-all,stop-all}` | lifecycle | ✅ |
195
- | `GET /api/servers/:id/logs`, `/api/servers/:id/stream`, `/api/logs/:id` | buffered lines, one server's SSE, files on disk | ✅ |
196
- | `GET`/`PATCH /api/settings`, `GET`/`PATCH /api/settings/workspace` | panel-wide / per-workspace settings | ❌ / ✅ |
197
- | `/api/backups`, `/api/proxy`, `/api/ddns`, `/api/notifications/…` | backups, reverse proxy, dynamic DNS, alerts | ❌ ❌ ✅ ✅ |
198
- | `GET /api/metrics` | Prometheus text, with a bearer token | ❌ |
199
- | `GET /healthz` | no credential needed — for your monitor | ❌ |
207
+ | `GET`/`PUT`/`PATCH`/`DELETE /api/servers/:id` | entries — `PUT` is create-or-replace, so a re-run converges | ✅ |
208
+ | `POST /api/servers/:id/{start,stop,restart,free-port}` | lifecycle | ✅ |
200
209
 
201
210
  Every error is one envelope — `{ "message", "code", "detail"? }` — with a stable `code` to branch on.
202
- On a **workspace-scoped** route an undeclared query key is refused (`400`), so a typo like `?worspace=`
203
- never acts on the default workspace. Full reference, SSE frames, metrics and compatibility rules:
204
- **[API.md](./docs/API.md)**.
211
+ Every endpoint, SSE frames, metrics and compatibility rules: **[API.md](./docs/API.md)**.
205
212
 
206
213
  </details>
207
214
 
@@ -221,15 +228,27 @@ Give it four things and it can run your home server without guessing:
221
228
 
222
229
  ## ✨ Features
223
230
 
231
+ ### What a plain supervisor does not do
232
+
233
+ | | |
234
+ | --- | --- |
235
+ | ♾️ **`persistent: true` survives the panel** | The entry runs under its own tiny supervisor (a **nanny** — this same CLI in a hidden mode) that owns its pipes and log file, so `down`, an upgrade or a crash leaves it serving; the next panel re-attaches |
236
+ | 🔗 **`dependsOn` waits for *healthy*** | A dependent is held until the health probe of what it needs has passed — not until that process merely exists — so a web app never binds before its database accepts connections |
237
+ | 🔄 **`onPortConflict: follow` adopts a self-restarting program** | A plugin that re-execs, or an updater that hands over to a new detached process, is recognised as *this entry's own successor* and taken over — pid, health, resources, stop — instead of blocking on its own port |
238
+ | 👻 **The orphan list** | A process this panel started that no entry owns any more — a renamed or removed entry left it behind — is listed under **Servers** by id, pid and start time, with a **Stop it** button. Nothing is killed on a guess |
239
+
240
+ The rest, one line each:
241
+
242
+ <details>
243
+ <summary><b>📋 The full feature list</b></summary>
244
+
224
245
  | | |
225
246
  | --- | --- |
226
247
  | 🗂 **Workspaces** | One panel, many setups. Each owns its servers, secrets, logs and settings; listener, auth, backups, TLS and UI stay panel-wide |
227
- | 🚦 **Lifecycle** | Start, stop, restart from the panel, the CLI or the API; `autostart` entries come up with it. A process left behind by a renamed entry is listed with a stop button |
228
- | 📝 **Hand edits welcome** | Edit `servers.config.json` in an editor or `git checkout` — picked up in seconds. A file it cannot read is reported, and running servers are left alone |
248
+ | 🚦 **Lifecycle** | Start, stop, restart from the panel, the CLI or the API; `autostart` entries come up with it |
249
+ | 📝 **Hand edits welcome** | Edit `servers.config.json` or the panel's `settings.json` in an editor or `git checkout` — picked up in seconds. A file it cannot read is reported in the UI, and what is running is left alone |
229
250
  | ♻️ **Auto-restart** | Exponential backoff on crash, with a retry budget that survives a panel restart |
230
- | 🩺 **Health that acts** | TCP or HTTP probes: warn, then force a restart. Ports checked before starting; a program that restarts itself can be [followed](./docs/SERVERS.md#when-a-program-restarts-itself) |
231
- | 🔗 **Ordered startup** | `dependsOn` waits for a dependency to be *healthy*, not just spawned; `down` stops dependents first |
232
- | ♾️ **Persistent entries** | A server that keeps running — and logging — while the panel restarts or upgrades |
251
+ | 🩺 **Health that acts** | TCP or HTTP probes: a card warns after `unhealthyThreshold` failed probes (default 3). Forcing a restart after a set time is **opt-in** — `forceRestartAfterMs` defaults to `0`, which never fires. Ports are checked before starting, and a program that restarts itself can be [followed](./docs/SERVERS.md#when-a-program-restarts-itself) |
233
252
  | 📜 **Logs** | Live stream, rotated files, search, download, clear |
234
253
  | 📈 **Resources** | CPU and memory per process tree (summed containers for compose), with an optional memory ceiling |
235
254
  | 🌡️ **Host vitals** | CPU, memory, swap, disk, temperature and load, with thresholds that alert once and again on recovery |
@@ -242,6 +261,8 @@ Give it four things and it can run your home server without guessing:
242
261
  | 🌍 **Translated** | English, Vietnamese, Chinese, Japanese, Spanish, Korean, Russian, French, German |
243
262
  | 🖥 **Cross-platform** | Linux, macOS and Windows — no shell utilities assumed |
244
263
 
264
+ </details>
265
+
245
266
  ---
246
267
 
247
268
  ## 🗂 Workspaces
@@ -301,14 +322,14 @@ Compose and more fill the form — or write it into the workspace's `servers.con
301
322
 
302
323
  | command | |
303
324
  | --- | --- |
304
- | `home-hosted up` | start the panel detached (already running? says where, exits 0) |
325
+ | `home-hosted up` | start the panel detached. With one already running: says where and exits `0` — **if the flags agree**. `--port`/`--host` naming something else is refused (exit `1`, "`--port X` was not honoured"), because a re-run must not report success for a move it did not make |
305
326
  | `home-hosted down` | stop it and everything it started — persistent entries stay unless `--with-persistent` |
306
327
  | `home-hosted restart [<id>]` | the panel (`down` then `up`), or just one server, leaving the panel up |
307
328
  | `home-hosted status` | running? where? how many servers up? every path (`--json`) |
308
- | `home-hosted start <id>` / `stop <id>` | one server, and what it `dependsOn` (`-w <workspace>`, `--free-port`) |
329
+ | `home-hosted start <id>` / `stop <id>` | one server — `start` brings up what it `dependsOn` first; `stop` stops only that one (`-w <workspace>`, `--free-port`) |
309
330
  | `home-hosted free-port <id>` | ask whatever holds that server's port to stop; supervised holders are refused |
310
331
  | `home-hosted logs [<id>]` | the panel's console, or one server's log (`--lines`, `--follow`, `--json`) |
311
- | `home-hosted usage` | CPU and memory per server, loudest first |
332
+ | `home-hosted usage` | CPU and memory per server, loudest first, plus starts and crashes over the history window |
312
333
  | `home-hosted backup` | `list`, `create`, `restore` — works with the panel stopped |
313
334
  | `home-hosted set-password` / `set-token` | credentials, without a browser |
314
335
  | `home-hosted migrate` | bring configs up to this release's schema (`--dry-run`) |
@@ -321,6 +342,7 @@ Compose and more fill the form — or write it into the workspace's `servers.con
321
342
 
322
343
  ```text
323
344
  up -p/--port <port> --host <local|lan|ipv4> --open --no-autostart --foreground --print-config
345
+ (--port and --host are saved to settings.json)
324
346
  down --with-persistent
325
347
  restart (no id) down, then up: up's flags plus --with-persistent
326
348
  restart <id> one server through the panel: [-w/--workspace <id>] — up's flags are refused here
@@ -328,12 +350,13 @@ status --json
328
350
  start <id> [-w/--workspace <id>] [--free-port]
329
351
  stop <id> [-w/--workspace <id>]
330
352
  free-port <id> [-w/--workspace <id>]
331
- logs [<id>] --lines <n|all> --follow --json [-w/--workspace <id>]
353
+ logs [<id>] --lines <n≥1|all> --follow --json [-w/--workspace <id>]
332
354
  usage --json
333
- backup [list|create|restore] [<name> | --from <path>] (--include <ids> | --all) [--exclude <ids>]
334
- --password <text> --confirm --json
355
+ backup list --json
356
+ backup create (--include <ids> | --all) [--exclude <ids>] --password <text> --confirm --json
357
+ backup restore (<name> | --from <path>) (--include <ids> | --all) [--exclude <ids>] --password <text> --confirm --json
335
358
  init --dir <dir> --name <name> --pm <pnpm|npm|yarn|bun> --no-install -y/--yes
336
- set-password --clear (HHOSTED_PASSWORD for a script)
359
+ set-password --clear (HHOSTED_PASSWORD for a script; --clear locks every sign-in out)
337
360
  set-token --generate --clear (HHOSTED_TOKEN for a script)
338
361
  migrate --dry-run -y/--yes (HHOSTED_MIGRATE=allow for a script)
339
362
  ui-switch --repo <owner/name> --tag <tag> --asset <name> --file <path|url> --list --token <token> -y/--yes
@@ -342,11 +365,15 @@ ui-revert (no flags)
342
365
  setup-temp --wsl [--download | --no-download] | --clear
343
366
 
344
367
  every command --home <dir> --project <dir> -h/--help -v/--version (or $HHOSTED_HOME, $HHOSTED_PROJECT)
368
+ help <command> the same as <command> --help
345
369
  environment HHOSTED_PASSWORD, HHOSTED_TOKEN, HHOSTED_MIGRATE=allow, HHOSTED_DDNS_SECRET,
346
370
  GITHUB_TOKEN / GH_TOKEN (ui-switch, ui-update)
347
371
  ```
348
372
 
349
373
  - `--json` prints one document on stdout or nothing; refusals go to stderr. Branch on the exit code.
374
+ The exception is a stream: `logs --follow --json` prints one `{ path, line }` object per line.
375
+ - A flag a command cannot honour is refused, and `backup create`/`restore` without a terminal need
376
+ `--confirm` (without it they show the plan and exit 1). Depth: [CLI.md](./docs/CLI.md).
350
377
  - Piping into `head`/`grep -q` exits 0, so `set -o pipefail` is safe.
351
378
  - `start web && curl …` works: `start` waits to confirm the process stayed up.
352
379
  - A misspelled command or flag suggests the one you meant.
@@ -371,10 +398,11 @@ upgrade needs from you. **Coming from 0.6.x:** run the latest 0.7.x once first.
371
398
  <details>
372
399
  <summary><b>🤔 What <code>status --json</code> tells you</b></summary>
373
400
 
374
- It always carries `running` and `liveness`: `live` (it is this panel), `unknown` (alive, start time
375
- unavailable — counted as running), `gone`, or `recycled` (the pid now belongs to another process —
376
- nothing is signalled). `answering: false` means the process exists but does not respond;
377
- `exitedCleanly` says whether someone ran `down` or it died. More: [CLI.md](./docs/CLI.md).
401
+ `running` and `liveness` are always present. `liveness` is `live` (it is this panel), `unknown`
402
+ (alive, start time unavailable — counted as running), `gone`, or `recycled` (the pid now belongs to
403
+ another process — nothing is signalled). Then `answering: false` means the process exists but does not
404
+ respond, and `exitedCleanly` says whether someone ran `down` or it died. There is more in that
405
+ document (paths, ports, the missing-record cases) — [CLI.md](./docs/CLI.md#what-status-tells-you).
378
406
 
379
407
  </details>
380
408
 
@@ -391,7 +419,7 @@ set your own password.
391
419
 
392
420
  1. **Set your own password before exposing it**, then bind to `lan` (UI, config, or `up --host lan`).
393
421
  2. **Treat an API token as the account it runs as** — changing the password does *not* revoke it.
394
- 3. **Forgot the password?** `home-hosted set-password --clear` on the machine; no login needed.
422
+ 3. **Forgot the password?** Run `home-hosted set-password` on the machine to set a new one; no login needed.
395
423
 
396
424
  </details>
397
425
 
@@ -402,10 +430,11 @@ set your own password.
402
430
  | --- | --- |
403
431
  | **Host** | an IP, `localhost`, a local name (`.local`, `.lan`, `homeserver`, …), a panel proxy route, or listed in `control.allowedHosts` — otherwise `421`. This blocks DNS-rebinding attacks from web pages you visit |
404
432
  | **Origin** | a cookie-authenticated write must be same-origin; bearer-token requests are exempt (browsers never attach one by themselves) |
405
- | **"This machine"** | a loopback peer with **no** forwarding header — so nothing relayed by a proxy, the panel's own included, gets local trust |
433
+ | **"This machine"** | a loopback peer that also carries **none** of `Forwarded`, `X-Forwarded-For`, `X-Real-IP` or the `X-Forwarded-Proto`/`-Host`/`-Port`/`-Prefix` family. That is right for the panel's own reverse proxy and for any proxy that adds at least one of them — but it is a **heuristic, not a guarantee**: a proxy that strips them all is indistinguishable from a local client. Set `trustProxy` deliberately and never put the panel behind a header-stripping proxy |
406
434
  | **Lockout** | repeated failures lock out per client address; `trustProxy: "loopback"` (default) reads the real address from a proxy on this machine |
407
435
 
408
- Secrets never go in a config file: every secret file is `0600`, the state directory `0700`. DDNS
436
+ Secrets never go in a config file: every secret file is `0600`, and `.hh` is `0700` from the moment
437
+ any command creates it. DDNS
409
438
  credentials are also sealed under `HHOSTED_DDNS_SECRET` — set your own if you commit or share `.hh/`.
410
439
  Details: [SECURITY.md](./docs/SECURITY.md).
411
440
 
@@ -461,15 +490,16 @@ way in; archives from a newer release are refused.
461
490
  <details>
462
491
  <summary><b>⏱️ Schedules, and what not to restore</b></summary>
463
492
 
464
- - A schedule writes an `auto-…` archive every N hours with its own retention; it never prunes your
465
- manual ones, nor zips the panel did not write.
493
+ - A schedule writes an `auto-…` archive every N hours with its own retention, and never prunes the
494
+ ones you took by hand.
466
495
  - Pick per item: whole workspaces, or one secret, one data directory.
467
496
  - **The password and token hashes are secrets too** — restoring them reinstates the old machine's
468
497
  credentials. Leave `global:secrets` unticked, or rotate afterwards.
469
498
  - **A live database copied file by file can be torn.** Stop it around the backup, or declare
470
499
  `dump`/`load` hooks so the engine writes the backup itself.
471
500
 
472
- Everything else — what comes back, what does not: [BACKUPS.md](./docs/BACKUPS.md).
501
+ That is the whole of what you have to decide before ticking a box. What an id selects, how retention
502
+ counts, which paths follow a new host: [BACKUPS.md](./docs/BACKUPS.md).
473
503
 
474
504
  </details>
475
505
 
@@ -512,8 +542,11 @@ home-hosted usage # what is eating the machine
512
542
  <summary><b>What happens to my servers when the panel stops?</b></summary>
513
543
 
514
544
  `down`, `SIGTERM` and `SIGINT` stop every server the panel started. `persistent` entries keep running
515
- under their own small supervisor and are re-attached by the next panel; `down --with-persistent`
516
- stops them too.
545
+ under their **nanny** (the small supervisor described [above](#-features)) and are re-attached by the
546
+ next panel; `down --with-persistent` stops them too.
547
+
548
+ Being **killed** is the other case: a panel that dies hard cannot stop anything, so its servers keep
549
+ running and the next panel adopts them — [SERVERS.md](./docs/SERVERS.md#orphaned-processes).
517
550
 
518
551
  </details>
519
552
 
@@ -564,14 +597,27 @@ Yes: process trees from Win32_Process, `taskkill` for stopping, `.cmd` shims res
564
597
  ```bash
565
598
  pnpm install
566
599
  pnpm dev # panel :6000 + stock UI dev server :6001, state in .dev-state/ (password: dev)
567
- pnpm run check # lint, types, doc links and the full test suite
600
+ pnpm run check:fast # while working: lint/types (cached) + only the tests your changes reach
601
+ pnpm run check # before pushing: lint, types, doc links and the full suite with coverage
568
602
  ```
569
603
 
570
604
  ```text
571
- src/ the panel: cli/, api/ (routes), services/ (stateful), providers/ (OS/vendor leaves),
572
- config/, middleware/, shared/ (schemas + client code the UIs import too)
573
- uis/ stock (ships in the package) and noc-console — Vite + Vue, static output
574
- docs/ user docs, mockups and media test/ vitest
605
+ src/ the panel. Top level: app.ts (Hono root), cli.ts, index.ts (all wiring),
606
+ client.ts (the published client), openapi.ts + openapi-reference.ts.
607
+ Then one directory per layer:
608
+ cli/ (one module per command) api/ (one route factory per URL group)
609
+ services/ (stateful) providers/ (OS/vendor leaves, plain data)
610
+ config/ (stores, parsing, migrations) middleware/ (host, auth, loopback)
611
+ helpers/ (cross-layer utilities) shared/ (schemas + code the UIs import too;
612
+ no Vue, no node:)
613
+ uis/ stock (ships in the package) and noc-console — Vite + Vue, static output.
614
+ Shared by both: vite.shared.ts (config, aliases, dev proxy) and tap-targets.css
615
+ test/ vitest; one directory per src/ layer, plus support/ (harnesses), fixtures/
616
+ and scripts/ (tests that drive a script in scripts/)
617
+ docs/ user docs, mockups/, media/, branding/, demo/
618
+ scripts/ build, release and check helpers — quickcheck.mjs is the gate
619
+ .agentDocs/ internals docs for agents; not published
620
+ bin/ the published `home-hosted` / `hh` entry point
575
621
  ```
576
622
 
577
623
  | if you want to… | read |
@@ -579,7 +625,7 @@ docs/ user docs, mockups and media test/ vitest
579
625
  | declare a server: every field, placeholders, port conflicts | [SERVERS.md](./docs/SERVERS.md) |
580
626
  | drive it from code: endpoints, SSE, errors, metrics | [API.md](./docs/API.md) |
581
627
  | every CLI command and what `status` means | [CLI.md](./docs/CLI.md) |
582
- | backups and restores in depth | [BACKUPS.md](./docs/BACKUPS.md) · [RESTORE_DEMO.md](./docs/RESTORE_DEMO.md) |
628
+ | backups and restores in depth | [BACKUPS.md](./docs/BACKUPS.md) |
583
629
  | hostnames and HTTPS | [REVERSE_PROXY.md](./docs/REVERSE_PROXY.md) · [DDNS.md](./docs/DDNS.md) |
584
630
  | alerts | [NOTIFICATIONS.md](./docs/NOTIFICATIONS.md) |
585
631
  | the security model | [SECURITY.md](./docs/SECURITY.md) |
@@ -31,6 +31,11 @@ function eventLoopSlicer() {
31
31
  * Every non-directory entry is still copied by `cpSync`, so links, modes and special files behave as
32
32
  * they did; only the directory recursion is here, in cp's order — a directory this call creates gets
33
33
  * its source mode after its contents are written.
34
+ *
35
+ * The two roots are dereferenced: a declared `data -> /mnt/disk/data` *is* the data, so it is copied
36
+ * as its target rather than as a link (which the archive walk then drops as outside the tree, leaving
37
+ * an empty capture), and a restore writes into the directory a linked target names instead of
38
+ * refusing it as a non-directory. Links *below* the roots are untouched.
34
39
  */
35
40
  async function copyTree(source, target, filter) {
36
41
  const slice = eventLoopSlicer();
@@ -52,7 +57,15 @@ async function copyTree(source, target, filter) {
52
57
  if (existing === void 0) fs.chmodSync(to, stats.mode);
53
58
  };
54
59
  fs.mkdirSync(path.dirname(target), { recursive: true });
55
- await visit(source, target);
60
+ await visit(realpathOr(source), realpathOr(target));
61
+ }
62
+ /** The path a link names, or the path itself when it does not resolve (absent, dangling). */
63
+ function realpathOr(target) {
64
+ try {
65
+ return fs.realpathSync(target);
66
+ } catch {
67
+ return target;
68
+ }
56
69
  }
57
70
  //#endregion
58
71
  //#region src/providers/archive.ts
@@ -336,4 +349,4 @@ async function walk(root) {
336
349
  //#endregion
337
350
  export { listZip as a, isZipArchive as i, extractZip as n, copyTree as o, isInvalidPassword as r, createZip as t };
338
351
 
339
- //# sourceMappingURL=archive-DpCwA8Nf.js.map
352
+ //# sourceMappingURL=archive-DP-XQR8X.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"archive-DP-XQR8X.js","names":[],"sources":["../../src/helpers/copy-tree.ts","../../src/providers/archive.ts"],"sourcesContent":["import fs from 'node:fs'\nimport path from 'node:path'\nimport { performance } from 'node:perf_hooks'\nimport { setImmediate } from 'node:timers/promises'\nimport { DetailedError } from '@namesmt/utils'\n\n/** How long a tree operation may hold the event loop before the panel gets a turn. */\nconst SLICE_MS = 10\n\n/**\n * A checkpoint that yields to the event loop once `SLICE_MS` of synchronous work has passed.\n *\n * Sync calls in slices, not `fs.promises`: every async call is a thread-pool round trip, which made a\n * tree of small files 10-20x slower to copy and walk than the sync calls it replaced.\n */\nexport function eventLoopSlicer(): () => Promise<void> {\n let since = performance.now()\n return async () => {\n if (performance.now() - since < SLICE_MS)\n return\n await setImmediate()\n since = performance.now()\n }\n}\n\n/**\n * `fs.cpSync(source, target, { recursive: true, force: true, filter })`, yielding between entries.\n *\n * Every non-directory entry is still copied by `cpSync`, so links, modes and special files behave as\n * they did; only the directory recursion is here, in cp's order — a directory this call creates gets\n * its source mode after its contents are written.\n *\n * The two roots are dereferenced: a declared `data -> /mnt/disk/data` *is* the data, so it is copied\n * as its target rather than as a link (which the archive walk then drops as outside the tree, leaving\n * an empty capture), and a restore writes into the directory a linked target names instead of\n * refusing it as a non-directory. Links *below* the roots are untouched.\n */\nexport async function copyTree(source: string, target: string, filter: (source: string, target: string) => boolean): Promise<void> {\n const slice = eventLoopSlicer()\n const visit = async (from: string, to: string): Promise<void> => {\n if (!filter(from, to))\n return\n await slice()\n const stats = fs.lstatSync(from)\n if (!stats.isDirectory()) {\n // `recursive` as before: a link to a directory is still copied as the link.\n fs.cpSync(from, to, { recursive: true, force: true })\n return\n }\n const existing = fs.lstatSync(to, { throwIfNoEntry: false })\n if (existing !== undefined && !existing.isDirectory())\n throw new DetailedError(`cannot overwrite non-directory ${to} with directory ${from}`, { code: 'ERR_FS_CP_DIR_TO_NON_DIR' })\n if (existing === undefined)\n fs.mkdirSync(to)\n for (const name of fs.readdirSync(from))\n await visit(path.join(from, name), path.join(to, name))\n if (existing === undefined)\n fs.chmodSync(to, stats.mode)\n }\n fs.mkdirSync(path.dirname(target), { recursive: true })\n await visit(realpathOr(source), realpathOr(target))\n}\n\n/** The path a link names, or the path itself when it does not resolve (absent, dangling). */\nfunction realpathOr(target: string): string {\n try {\n return fs.realpathSync(target)\n }\n catch {\n return target\n }\n}\n","import type { FileEntry } from '@zip.js/zip.js'\nimport { Buffer } from 'node:buffer'\nimport fs from 'node:fs'\nimport path from 'node:path'\nimport process from 'node:process'\nimport { Readable, Writable } from 'node:stream'\nimport { finished } from 'node:stream/promises'\nimport { BlobReader, configure, ZipReader, ZipWriter } from '@zip.js/zip.js'\nimport { eventLoopSlicer } from '#src/helpers/copy-tree'\n\n/**\n * `Readable.toWeb` is typed against `node:stream/web`, while zip.js declares the\n * global `ReadableStream` — the same objects under two declarations, and which\n * one wins depends on the tsconfig (the SPA's adds lib.dom). These aliases take\n * the type zip.js expects, whichever it is where this file is compiled.\n */\ntype ZipInput = Parameters<ZipWriter<unknown>['add']>[1]\ntype ZipOutput = ConstructorParameters<typeof ZipWriter>[0] & { abort: (reason?: unknown) => Promise<void> }\ntype ZipDataOutput = Parameters<FileEntry['getData']>[0]\n\n/**\n * Backups are ordinary zip files: the same container whether or not they are\n * password-protected, openable by any archive manager (including the one built\n * into Windows and macOS), and produced without a native binary — zip.js is pure\n * JavaScript.\n *\n * A password means WinZip AES-256 (`encryptionStrength: 3`, AE-2): strong, and\n * still standard, unlike the legacy ZipCrypto encryption.\n */\n\n// Deterministic, in-process codecs: a bundled CLI has no worker file to load.\nconfigure({ useWebWorkers: false })\n\nconst ZIPS = [\n [0x50, 0x4B, 0x03, 0x04],\n [0x50, 0x4B, 0x05, 0x06],\n [0x50, 0x4B, 0x07, 0x08],\n]\n\n/** Recognised by content, never by the file's name. */\nexport function isZipArchive(file: string): boolean {\n let fd: number | null = null\n try {\n fd = fs.openSync(file, 'r')\n const head = Buffer.alloc(4)\n const read = fs.readSync(fd, head, 0, 4, 0)\n return read === 4 && ZIPS.some(magic => magic.every((byte, index) => head[index] === byte))\n }\n catch {\n return false\n }\n finally {\n if (fd !== null)\n fs.closeSync(fd)\n }\n}\n\nexport interface ArchiveEntry {\n /** Forward-slash path inside the archive; directories end with `/`. */\n name: string\n directory: boolean\n encrypted: boolean\n symlink: boolean\n /** Uncompressed size, for callers that cap what they will extract. */\n size: number\n /** The Unix mode the entry carries, when the archive recorded one. */\n mode?: number\n}\n\n/** The central directory is not encrypted, so this works without a password. */\nexport async function listZip(file: string): Promise<ArchiveEntry[]> {\n const reader = await open(file)\n try {\n const entries = await reader.getEntries()\n return entries.map(entry => ({\n name: entry.filename,\n directory: entry.directory === true,\n encrypted: entry.encrypted === true,\n symlink: entry.symlink === true,\n size: entry.uncompressedSize ?? 0,\n ...(entry.unixMode === undefined ? {} : { mode: entry.unixMode }),\n }))\n }\n finally {\n await reader.close()\n }\n}\n\n/**\n * True when the archive rejected the password we used.\n *\n * Matched on the wording zip.js raises for a bad password, not on the word alone: the message is\n * `Invalid password`, while a *file it cannot open* produces `ENOENT: … stat '/tmp/…/my-password-\n * backup.zip'` — which carries the word because the caller named the archive that. A substring test\n * read that as a wrong password and told the person to re-enter one, when the archive was simply\n * not there. (Caught by CI, where Node's fs message names the path; the local run said\n * `Unable to open file as blob`, so the same call looked fine.)\n */\nexport function isInvalidPassword(error: unknown): boolean {\n return error instanceof Error && /invalid password/i.test(error.message)\n}\n\n/**\n * Writes the contents of `sourceDir` into `destination`, preserving the tree and each\n * entry's permission bits.\n *\n * The mode is captured because the tree is somebody's data directory: a `0600` key, a `0700`\n * directory and a `0755` script are all routine there, and a backup that restores them as `0644`\n * changes who can read the data it was taken to protect. What a symlink may bring in is bounded by\n * the tree itself (`walk`): the target has to be inside it, so a declared path cannot capture bytes\n * from outside itself. Streams from disk to disk: nothing is buffered whole.\n */\nexport async function createZip(sourceDir: string, destination: string, options: { password?: string } = {}): Promise<void> {\n // Written beside the destination and renamed on success, so an interrupted run never leaves a\n // `.zip` that reads as a finished archive.\n const partial = path.join(path.dirname(destination), `.${path.basename(destination)}.partial`)\n const output = fs.createWriteStream(partial, { mode: 0o600 })\n // Attached up front: the fd closes as part of the web stream ending, so a\n // listener added afterwards would wait forever.\n const flushed = finished(output)\n const writer = Writable.toWeb(output) as unknown as ZipOutput\n const zip = new ZipWriter(writer, {\n ...(options.password === undefined ? {} : { password: options.password, encryptionStrength: 3 as const }),\n level: 6,\n keepOrder: true,\n })\n\n try {\n for (const item of await walk(sourceDir)) {\n const mode = item.mode === null ? {} : { unixMode: item.mode }\n if (item.directory)\n await zip.add(item.name, null, { directory: true, ...mode })\n else if (item.size === 0)\n // An empty file carries no content to protect, and leaving it as a plain\n // AE-2 entry makes older tools (p7zip 16.02) report a CRC failure on it.\n await zip.add(item.name, null, { directory: false, ...mode })\n else\n await zip.add(item.name, Readable.toWeb(fs.createReadStream(item.absolute)) as unknown as ZipInput, mode)\n }\n await zip.close()\n await flushed\n await fs.promises.rename(partial, destination)\n }\n catch (error) {\n await writer.abort(error).catch(() => {})\n // The file stream also fails here (a full disk, a directory in the way), and\n // an unobserved rejection would take the whole control plane down.\n await flushed.catch(() => {})\n await fs.promises.rm(partial, { force: true }).catch(() => {})\n throw error\n }\n}\n\n/**\n * Extracts the given entries (already validated by the caller) into\n * `destination`. Symbolic links are never recreated — an archive is not allowed\n * to make the filesystem point somewhere else.\n *\n * An entry's permission bits are applied after it lands. The file is created under a restrictive\n * mode first, so a `0600` secret never exists world-readable between two calls, and a mode the\n * current umask would widen is set with an explicit `chmod` rather than left to the create.\n */\nexport async function extractZip(\n file: string,\n destination: string,\n options: { names: string[], password?: string },\n): Promise<{ skipped: string[] }> {\n const reader = await open(file, options.password)\n const skipped: string[] = []\n /** Directory modes, applied after their contents: a `0700` dir cannot be written into. */\n const pendingDirModes: Array<{ target: string, mode: number }> = []\n\n try {\n const entries = new Map((await reader.getEntries()).map(entry => [entry.filename, entry]))\n\n for (const name of options.names) {\n const entry = entries.get(name)\n if (entry === undefined) {\n skipped.push(name)\n continue\n }\n\n const target = path.join(destination, name)\n if (entry.directory) {\n fs.mkdirSync(target, { recursive: true })\n // A directory's mode is applied after the files under it are written, otherwise it would\n // close itself to the writes that have not happened yet. `mkdir` gives it the umask's\n // mode; this is the one the archive carried.\n const mode = permissionBits(entry.unixMode)\n if (mode !== null)\n pendingDirModes.push({ target, mode })\n continue\n }\n if (entry.symlink) {\n skipped.push(name)\n continue\n }\n\n fs.mkdirSync(path.dirname(target), { recursive: true })\n await entry.getData(Writable.toWeb(fs.createWriteStream(target, { mode: 0o600 })) as unknown as ZipDataOutput, writeOptions(entry, options.password))\n const mode = permissionBits(entry.unixMode)\n if (mode !== null) {\n try {\n fs.chmodSync(target, mode)\n }\n catch {\n // A filesystem without POSIX modes (a mounted FAT drive, a Windows share) keeps the file\n // it wrote — refusing the whole restore over metadata would lose the data to save the bit.\n }\n }\n }\n }\n finally {\n await reader.close()\n // Deepest first, so a `0700` parent cannot lock out a child that has not been chmodded yet.\n for (const { target, mode } of pendingDirModes.sort((left, right) => right.target.length - left.target.length)) {\n try {\n fs.chmodSync(target, mode)\n }\n catch {}\n }\n pendingDirModes.length = 0\n }\n\n return { skipped }\n}\n\nfunction writeOptions(entry: FileEntry, password: string | undefined): { password?: string } {\n return entry.encrypted && password !== undefined ? { password } : {}\n}\n\nasync function open(file: string, password?: string): Promise<ZipReader<unknown>> {\n // A lazily-read Blob keeps a multi-gigabyte archive out of memory: zip.js only\n // pulls the byte ranges it needs.\n const blob = await fs.openAsBlob(file, { type: 'application/zip' })\n return password === undefined\n ? new ZipReader(new BlobReader(blob))\n : new ZipReader(new BlobReader(blob), { password })\n}\n\ninterface WalkedFile {\n name: string\n absolute: string\n directory: boolean\n size: number\n /** The permission bits to write into the archive, or `null` where the platform has none. */\n mode: number | null\n}\n\n/**\n * The `st_mode` an entry should carry, or `null` where the platform does not report one.\n *\n * Only the permission bits and the file type are kept: the archive records a mode, not an owner,\n * because a restore runs as whoever restores it and a foreign uid would be a worse lie than the\n * restoring user's own.\n */\nfunction archiveMode(stats: fs.Stats): number | null {\n const bits = stats.mode & 0o777\n if (process.platform === 'win32' || bits === 0)\n return null\n return (stats.isDirectory() ? 0o040000 : 0o100000) | bits\n}\n\n/**\n * The permission bits an extracted entry should be given, or `null` when the archive carries none.\n *\n * Zip stores the type in the same field, so the file type is dropped: the entry is written as the\n * ordinary file or directory this call is creating, never as a fifo or a device node an archive\n * could name. The setuid/setgid/sticky bits are dropped too — an archive from another host does not\n * get to install a privileged binary here.\n */\nfunction permissionBits(unixMode: number | undefined): number | null {\n if (unixMode === undefined || unixMode === 0)\n return null\n const bits = unixMode & 0o777\n return bits === 0 ? null : bits\n}\n\n/** True when `child` is `parent` itself or lives underneath it, after resolving both. */\nfunction isUnderResolved(parent: string, child: string): boolean {\n const relative = path.relative(parent, child)\n return relative === '' || (!path.isAbsolute(relative) && !relative.startsWith('..'))\n}\n\n/**\n * Sorted, deterministic walk with directory loops broken and the declared tree respected.\n *\n * Every read is best-effort: a directory that vanishes mid-walk (a rotated log, a\n * build directory being cleaned, a container being torn down) must leave it out of\n * the archive rather than reject `createZip` and turn a backup into a failure.\n *\n * A link that resolves **outside** `root` is left out rather than followed. `root` is a copy of the\n * declared path, so a link inside it points back at the live tree — following one captured bytes\n * from outside the path the person declared (a `media -> /mnt/nas` symlink pulled the whole share\n * into the archive), and it captured the *live* copy of anything the copy had already frozen. A\n * restore never recreates links anyway, so the link itself has nothing to restore; its content, if\n * it is wanted, is declared as its own path.\n */\nasync function walk(root: string): Promise<WalkedFile[]> {\n const files: WalkedFile[] = []\n const seen = new Set<string>()\n const slice = eventLoopSlicer()\n let realRoot: string\n try {\n realRoot = fs.realpathSync(root)\n }\n catch {\n return files\n }\n\n const readDir = (absolute: string): string[] => {\n try {\n return fs.readdirSync(absolute).sort()\n }\n catch {\n return []\n }\n }\n\n const visit = async (absolute: string, name: string): Promise<void> => {\n await slice()\n let stats: fs.Stats\n try {\n stats = fs.statSync(absolute)\n }\n catch {\n return\n }\n\n let real: string\n try {\n real = fs.realpathSync(absolute)\n }\n catch {\n // A link whose target went away; there is nothing to capture.\n return\n }\n if (!isUnderResolved(realRoot, real))\n return\n\n if (stats.isDirectory()) {\n if (seen.has(real))\n return\n seen.add(real)\n files.push({ name: `${name}/`, absolute, directory: true, size: 0, mode: archiveMode(stats) })\n for (const child of readDir(absolute))\n await visit(path.join(absolute, child), `${name}/${child}`)\n return\n }\n\n if (stats.isFile())\n files.push({ name, absolute, directory: false, size: stats.size, mode: archiveMode(stats) })\n }\n\n for (const child of readDir(root))\n await visit(path.join(root, child), child)\n\n return files\n}\n"],"mappings":";;;;;;;;;;;;AAOA,IAAM,WAAW;;;;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;IAAE,MAAM,GAAG,KAAK;IAAI;IAAU,WAAW;IAAM,MAAM;IAAG,MAAM,YAAY,KAAK;GAAE,CAAC;GAC7F,KAAK,MAAM,SAAS,QAAQ,QAAQ,GAClC,MAAM,MAAM,KAAK,KAAK,UAAU,KAAK,GAAG,GAAG,KAAK,GAAG,OAAO;GAC5D;EACF;EAEA,IAAI,MAAM,OAAO,GACf,MAAM,KAAK;GAAE;GAAM;GAAU,WAAW;GAAO,MAAM,MAAM;GAAM,MAAM,YAAY,KAAK;EAAE,CAAC;CAC/F;CAEA,KAAK,MAAM,SAAS,QAAQ,IAAI,GAC9B,MAAM,MAAM,KAAK,KAAK,MAAM,KAAK,GAAG,KAAK;CAE3C,OAAO;AACT"}
@@ -1,3 +1,4 @@
1
+ import { i as ensureStateDir } from "./paths-CGlGDrOU.js";
1
2
  import process from "node:process";
2
3
  import path from "node:path";
3
4
  import fs from "node:fs";
@@ -8,7 +9,7 @@ import { randomBytes } from "node:crypto";
8
9
  * half-written file, and a crash cannot truncate the previous config.
9
10
  */
10
11
  function writeFileAtomic(file, content, options = {}) {
11
- fs.mkdirSync(path.dirname(file), { recursive: true });
12
+ ensureStateDir(path.dirname(file));
12
13
  const tmp = `${file}.${process.pid}.${randomBytes(4).toString("hex")}.tmp`;
13
14
  try {
14
15
  fs.writeFileSync(tmp, content, options.mode === void 0 ? void 0 : { mode: options.mode });
@@ -22,4 +23,4 @@ function writeFileAtomic(file, content, options = {}) {
22
23
  //#endregion
23
24
  export { writeFileAtomic as t };
24
25
 
25
- //# sourceMappingURL=atomic-CEfCUfkQ.js.map
26
+ //# sourceMappingURL=atomic-C1PfJpE7.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"atomic-C1PfJpE7.js","names":[],"sources":["../../src/helpers/atomic.ts"],"sourcesContent":["import { randomBytes } from 'node:crypto'\nimport fs from 'node:fs'\nimport path from 'node:path'\nimport process from 'node:process'\nimport { ensureStateDir } from '#src/helpers/paths'\n\nexport interface WriteFileOptions {\n /** Applied to the temp file before the rename, so secrets never exist world-readable. */\n mode?: number\n}\n\n/**\n * Write via a temp file in the same directory, then rename: readers never see a\n * half-written file, and a crash cannot truncate the previous config.\n */\nexport function writeFileAtomic(file: string, content: string, options: WriteFileOptions = {}): void {\n ensureStateDir(path.dirname(file))\n // Unique per call, not just per process: two writes to the same file in one\n // process would otherwise share a temp name and the second rename would fail.\n const tmp = `${file}.${process.pid}.${randomBytes(4).toString('hex')}.tmp`\n try {\n fs.writeFileSync(tmp, content, options.mode === undefined ? undefined : { mode: options.mode })\n if (options.mode !== undefined)\n fs.chmodSync(tmp, options.mode)\n fs.renameSync(tmp, file)\n }\n catch (error) {\n // The temp name is unique per call, so a failed write would otherwise litter the\n // directory with a file nothing will ever reuse.\n fs.rmSync(tmp, { force: true })\n throw error\n }\n}\n"],"mappings":";;;;;;;;;;AAeA,SAAgB,gBAAgB,MAAc,SAAiB,UAA4B,CAAC,GAAS;CACnG,eAAe,KAAK,QAAQ,IAAI,CAAC;CAGjC,MAAM,MAAM,GAAG,KAAK,GAAG,QAAQ,IAAI,GAAG,YAAY,CAAC,CAAC,CAAC,SAAS,KAAK,EAAE;CACrE,IAAI;EACF,GAAG,cAAc,KAAK,SAAS,QAAQ,SAAS,KAAA,IAAY,KAAA,IAAY,EAAE,MAAM,QAAQ,KAAK,CAAC;EAC9F,IAAI,QAAQ,SAAS,KAAA,GACnB,GAAG,UAAU,KAAK,QAAQ,IAAI;EAChC,GAAG,WAAW,KAAK,IAAI;CACzB,SACO,OAAO;EAGZ,GAAG,OAAO,KAAK,EAAE,OAAO,KAAK,CAAC;EAC9B,MAAM;CACR;AACF"}