home-hosted 0.9.8 → 0.9.10

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/dist/cli.js CHANGED
@@ -715,6 +715,19 @@ function serializeCookie(name, value, options = {}) {
715
715
  if (options.secure) parts.push("Secure");
716
716
  return parts.join("; ");
717
717
  }
718
+ /**
719
+ * Whether this response's cookie may carry `Secure`, from the configured policy and the protocol the
720
+ * request actually arrived on.
721
+ *
722
+ * One home, because two responses now set the session cookie — the login route and the guard that
723
+ * slides an active session forward. `auto` is the proxy case: behind TLS the panel sees `https:` only
724
+ * because srvx rewrote it from `x-forwarded-proto` (see `.agentDocs/GOTCHAS.md`).
725
+ */
726
+ function secureCookieFor(mode, protocol) {
727
+ if (mode === "always") return true;
728
+ if (mode === "never") return false;
729
+ return protocol === "https:";
730
+ }
718
731
  var init_cookies = __esmMin((() => {}));
719
732
  //#endregion
720
733
  //#region src/shared/contracts.ts
@@ -1857,7 +1870,19 @@ maxRssBytes: "number.integer >= 0 = 0" }).onUndeclaredKey("reject");
1857
1870
  name: "string?",
1858
1871
  password: passwordValueSchema.optional(),
1859
1872
  /** Item ids to restore; omitted means every restorable item. */
1860
- include: type("string[]").optional()
1873
+ include: type("string[]").optional(),
1874
+ /**
1875
+ * Item ids to leave out, applied after `include` — the CLI's `--exclude` on the same command.
1876
+ *
1877
+ * `BackupService.restore()` has always taken it and the local channel has always sent it, but this
1878
+ * schema declared only `name`/`password`/`include` **and rejects undeclared keys**, so the same
1879
+ * request over `/api` answered `exclude must be removed`: a script or either UI could only say
1880
+ * "these items", never "everything except these", on the one path that overwrites a live host.
1881
+ *
1882
+ * Empty is refused for the same reason it is on a create — it reads as "nothing" to a person and
1883
+ * as "everything" to the reader, so it must not be sent at all.
1884
+ */
1885
+ exclude: type("string[] >= 1").optional()
1861
1886
  }).onUndeclaredKey("reject");
1862
1887
  serverViewSchema = type({
1863
1888
  "id": "string",
@@ -2224,6 +2249,46 @@ function writeFileAtomic(file, content, options = {}) {
2224
2249
  }
2225
2250
  var init_atomic = __esmMin((() => {}));
2226
2251
  //#endregion
2252
+ //#region src/helpers/config-text.ts
2253
+ /**
2254
+ * Decodes a hand-editable state file the way the editors that write them save it.
2255
+ *
2256
+ * Every file the panel invites a person to hand-edit is JSON, and `JSON.parse` refuses a
2257
+ * **byte-order mark**: PowerShell's `Set-Content -Encoding UTF8` (5.1) and `Out-File`/`>`
2258
+ * (UTF-16LE) both prepend one, and Notepad writes one for a "UTF-8 with BOM" save. The
2259
+ * refusal is a parse error naming an invisible character — `Unexpected token '\uFEFF'` — so the
2260
+ * person is told their JSON is broken when it is not, and is invited to
2261
+ * fix a file the editor will re-encode identically on the next save.
2262
+ *
2263
+ * Stripping the mark is not a silent coercion: a BOM is not content, and a file whose real
2264
+ * content is unchanged parses to the same object with or without it. UTF-16 is decoded rather
2265
+ * than refused because that is what `>` produces on Windows, and it is recognisable from its
2266
+ * own prefix — a wrong guess would still fail loudly on `JSON.parse`.
2267
+ *
2268
+ * Read as a `Buffer`, never with `'utf8'`: a `'utf8'` read of UTF-16LE text has already lost
2269
+ * the information this needs to tell them apart.
2270
+ */
2271
+ function decodeStateFile(bytes) {
2272
+ if (bytes.length >= 2) {
2273
+ if (bytes[0] === 255 && bytes[1] === 254) return stripBom(bytes.subarray(2).toString("utf16le"));
2274
+ if (bytes[0] === 254 && bytes[1] === 255) {
2275
+ const swapped = Buffer$1.from(bytes.subarray(2));
2276
+ swapped.swap16();
2277
+ return stripBom(swapped.toString("utf16le"));
2278
+ }
2279
+ }
2280
+ return stripBom(bytes.toString("utf8"));
2281
+ }
2282
+ /** A UTF-8 BOM is three bytes; Node decodes it to the one `\uFEFF` character. */
2283
+ function stripBom(text) {
2284
+ return text.charCodeAt(0) === 65279 ? text.slice(1) : text;
2285
+ }
2286
+ /** `decodeStateFile` for a path. Missing files still throw `ENOENT`, as a caller expects. */
2287
+ function readStateFile(file) {
2288
+ return decodeStateFile(fs.readFileSync(file));
2289
+ }
2290
+ var init_config_text = __esmMin((() => {}));
2291
+ //#endregion
2227
2292
  //#region src/shared/shape.ts
2228
2293
  /**
2229
2294
  * A plain object, and nothing else: not `null`, and not an array.
@@ -2406,6 +2471,7 @@ function openDdns(accountId, sealed, key) {
2406
2471
  var COST, KEYLEN, SALT_BYTES, LEGACY_TELEGRAM_ID, DDNS_KEYLEN, DDNS_IV_BYTES, DDNS_AAD_PREFIX, DDNS_SEALED_ALGO, API_TOKEN_BYTES, API_TOKEN_HINT_CHARS, SecretsStore;
2407
2472
  var init_secrets = __esmMin((() => {
2408
2473
  init_atomic();
2474
+ init_config_text();
2409
2475
  init_logger();
2410
2476
  init_error_message();
2411
2477
  init_shape();
@@ -2668,7 +2734,7 @@ var init_secrets = __esmMin((() => {
2668
2734
  if (!fs.existsSync(this.file)) return this.inScope(empty);
2669
2735
  let text;
2670
2736
  try {
2671
- text = fs.readFileSync(this.file, "utf8");
2737
+ text = readStateFile(this.file);
2672
2738
  } catch (error) {
2673
2739
  this.error = `cannot read ${this.file}: ${errorMessage(error)}`;
2674
2740
  return this.inScope(empty);
@@ -2856,6 +2922,39 @@ var init_auth$1 = __esmMin((() => {
2856
2922
  session.expiresAt = now + this.getConfig().sessionTtlMs;
2857
2923
  return session;
2858
2924
  }
2925
+ /**
2926
+ * How far the session deadline may slide past the deadline the browser was last told about before
2927
+ * the cookie is re-sent.
2928
+ *
2929
+ * The cookie is only re-issued when it has fallen this far behind, so a panel in constant use keeps
2930
+ * a live cookie without a `Set-Cookie` on every request — an SSE stream opens one connection and
2931
+ * holds it. Quarter of the idle window, floored at 30 s so a short TTL still refreshes usefully and
2932
+ * capped at an hour so a week-long one costs at most one header an hour.
2933
+ */
2934
+ cookieRefreshThresholdMs() {
2935
+ const ttl = this.getConfig().sessionTtlMs;
2936
+ return Math.max(3e4, Math.min(ttl / 4, 36e5));
2937
+ }
2938
+ /**
2939
+ * The `Max-Age` to send, when this request should slide the *cookie* forward too; otherwise null.
2940
+ *
2941
+ * `validate()` slides `expiresAt` on every request, which makes the lifetime an idle timeout — but
2942
+ * a browser drops a cookie at the `Max-Age` it was issued with, and nothing was re-issuing it. So
2943
+ * the server kept a session a week after login while the browser had thrown its half away: a panel
2944
+ * used every ten seconds was still signed out at the configured lifetime, which is the opposite of
2945
+ * what the login page promises. Marking the deadline actually sent makes the two agree, and only
2946
+ * when it has moved enough to matter.
2947
+ */
2948
+ refreshCookie(session) {
2949
+ const now = Date.now();
2950
+ if (session.expiresAt - session.cookieExpiresAt < this.cookieRefreshThresholdMs()) return null;
2951
+ session.cookieExpiresAt = session.expiresAt;
2952
+ return Math.max(0, session.expiresAt - now);
2953
+ }
2954
+ /** The cookie policy the guard and the login route must agree on. */
2955
+ get cookieSecureMode() {
2956
+ return this.getConfig().cookieSecure;
2957
+ }
2859
2958
  verifyCurrentPassword(password) {
2860
2959
  const record = this.secrets.password;
2861
2960
  if (record === null) return false;
@@ -2910,10 +3009,12 @@ var init_auth$1 = __esmMin((() => {
2910
3009
  if (oldest) this.sessions.delete(oldest.token);
2911
3010
  }
2912
3011
  const token = crypto.randomBytes(32).toString("base64url");
3012
+ const expiresAt = now + config.sessionTtlMs;
2913
3013
  this.sessions.set(token, {
2914
3014
  token,
2915
3015
  passwordRevision: this.secrets.passwordUpdatedAt,
2916
- expiresAt: now + config.sessionTtlMs,
3016
+ expiresAt,
3017
+ cookieExpiresAt: expiresAt,
2917
3018
  lastSeenAt: now,
2918
3019
  ip
2919
3020
  });
@@ -3033,6 +3134,20 @@ function createAuthGuard(deps) {
3033
3134
  code: AUTH_REQUIRED_CODE
3034
3135
  });
3035
3136
  }
3137
+ /**
3138
+ * An active session slides forward, so the browser's copy of the deadline has to slide with
3139
+ * it — otherwise it is dropped at the lifetime measured from *login*, whatever the person
3140
+ * did in between, and the panel signs its owner out mid-use.
3141
+ */
3142
+ if (identity.method === "cookie" && identity.session !== null) {
3143
+ const maxAgeMs = deps.auth.refreshCookie(identity.session);
3144
+ if (maxAgeMs !== null) c.header("Set-Cookie", serializeCookie(SESSION_COOKIE, identity.session.token, {
3145
+ maxAgeMs,
3146
+ secure: secureCookieFor(deps.auth.cookieSecureMode, new URL(c.req.url).protocol),
3147
+ sameSite: "Strict",
3148
+ httpOnly: true
3149
+ }));
3150
+ }
3036
3151
  } else if (deps.auth.isEnabled()) {
3037
3152
  if (!identity.authenticated && !isLoopbackRequest(c)) throw new DetailedError("authentication is enabled but no password is set — set one from the machine running the panel", {
3038
3153
  statusCode: 401,
@@ -3054,6 +3169,7 @@ function requestActor(c, auth) {
3054
3169
  }
3055
3170
  var PUBLIC_PATHS, AUTH_REQUIRED_CODE;
3056
3171
  var init_auth = __esmMin((() => {
3172
+ init_cookies();
3057
3173
  init_loopback();
3058
3174
  init_auth$1();
3059
3175
  PUBLIC_PATHS = /* @__PURE__ */ new Set(["/api/auth/login", "/api/auth/session"]);
@@ -3155,10 +3271,7 @@ var init_exposure = __esmMin((() => {
3155
3271
  //#region src/api/auth/$.routes.ts
3156
3272
  /** `Secure` only helps over TLS, and would break plain http on a LAN. */
3157
3273
  function secureCookie(c, deps) {
3158
- const mode = deps.panel.settings.control.auth.cookieSecure;
3159
- if (mode === "always") return true;
3160
- if (mode === "never") return false;
3161
- return new URL(c.req.url).protocol === "https:";
3274
+ return secureCookieFor(deps.auth.cookieSecureMode, new URL(c.req.url).protocol);
3162
3275
  }
3163
3276
  function createAuthRoute(deps) {
3164
3277
  return appFactory.createApp().get("/auth/session", describeRoute({
@@ -3611,6 +3724,10 @@ function createBackupsRoute(deps) {
3611
3724
  describeRoute({
3612
3725
  tags: ["backups"],
3613
3726
  summary: "Plan or apply a restore from a stored or uploaded archive",
3727
+ requestBody: {
3728
+ required: false,
3729
+ content: { "application/json": { schema: resolver(restoreRequestSchema) } }
3730
+ },
3614
3731
  responses: {
3615
3732
  200: {
3616
3733
  description: "The plan",
@@ -3667,19 +3784,24 @@ function createBackupsRoute(deps) {
3667
3784
  uploadedTo = path.join(uploads, `upload-${crypto.randomUUID()}.zip`);
3668
3785
  fs.writeFileSync(uploadedTo, Buffer$1.from(await file.arrayBuffer()), { mode: 384 });
3669
3786
  archive = uploadedTo;
3670
- const rawInclude = typeof body.include === "string" && body.include.length > 0 ? body.include : null;
3671
- let include;
3672
- if (rawInclude !== null) try {
3673
- include = JSON.parse(rawInclude);
3674
- } catch {
3675
- throw new DetailedError("`include` must be a JSON array of item ids", {
3676
- statusCode: 400,
3677
- code: "INVALID_INCLUDE"
3678
- });
3679
- }
3787
+ const jsonField = (key) => {
3788
+ const raw = typeof body[key] === "string" && body[key].length > 0 ? body[key] : null;
3789
+ if (raw === null) return void 0;
3790
+ try {
3791
+ return JSON.parse(raw);
3792
+ } catch {
3793
+ throw new DetailedError(`\`${key}\` must be a JSON array of item ids`, {
3794
+ statusCode: 400,
3795
+ code: key === "include" ? "INVALID_INCLUDE" : "INVALID_EXCLUDE"
3796
+ });
3797
+ }
3798
+ };
3799
+ const include = jsonField("include");
3800
+ const exclude = jsonField("exclude");
3680
3801
  request = parseOrThrow(restoreRequestSchema, {
3681
3802
  ...typeof body.password === "string" ? { password: body.password } : {},
3682
- ...rawInclude === null ? {} : { include }
3803
+ ...include === void 0 ? {} : { include },
3804
+ ...exclude === void 0 ? {} : { exclude }
3683
3805
  }, "body");
3684
3806
  } else {
3685
3807
  request = parseOrThrow(restoreRequestSchema, await c.req.json().catch(() => ({})), "body");
@@ -3696,7 +3818,8 @@ function createBackupsRoute(deps) {
3696
3818
  const plan = await deps.backups.restore(archive, {
3697
3819
  confirm,
3698
3820
  password: request.password,
3699
- include: request.include
3821
+ include: request.include,
3822
+ exclude: request.exclude
3700
3823
  });
3701
3824
  if (plan.needsPassword) return c.json(plan);
3702
3825
  if (plan.error !== void 0) throw new DetailedError(plan.error, {
@@ -3905,6 +4028,7 @@ var workspacesFileSchema, WorkspaceError, seed, WorkspaceRegistry;
3905
4028
  var init_workspaces = __esmMin((() => {
3906
4029
  init_schema();
3907
4030
  init_atomic();
4031
+ init_config_text();
3908
4032
  init_paths();
3909
4033
  init_version();
3910
4034
  init_contracts();
@@ -3960,7 +4084,7 @@ var init_workspaces = __esmMin((() => {
3960
4084
  load() {
3961
4085
  let parsed;
3962
4086
  try {
3963
- parsed = JSON.parse(fs.readFileSync(this.file, "utf8"));
4087
+ parsed = JSON.parse(readStateFile(this.file));
3964
4088
  } catch (error) {
3965
4089
  if (error.code === "ENOENT") {
3966
4090
  this.commit(seed());
@@ -4758,6 +4882,7 @@ var init_settings$1 = __esmMin((() => {
4758
4882
  init_schema();
4759
4883
  init_seed();
4760
4884
  init_atomic();
4885
+ init_config_text();
4761
4886
  init_paths();
4762
4887
  ConfigError = class extends Error {
4763
4888
  name = "ConfigError";
@@ -4833,7 +4958,7 @@ var init_settings$1 = __esmMin((() => {
4833
4958
  reloadFromDisk() {
4834
4959
  let text;
4835
4960
  try {
4836
- text = fs.readFileSync(this.file, "utf8");
4961
+ text = readStateFile(this.file);
4837
4962
  } catch {
4838
4963
  this.error = `${path.basename(this.file)} is gone`;
4839
4964
  return {
@@ -4874,7 +4999,7 @@ var init_settings$1 = __esmMin((() => {
4874
4999
  let text;
4875
5000
  let parsed;
4876
5001
  try {
4877
- text = fs.readFileSync(this.file, "utf8");
5002
+ text = readStateFile(this.file);
4878
5003
  parsed = JSON.parse(text);
4879
5004
  } catch (error) {
4880
5005
  this.error = `cannot parse ${path.basename(this.file)}: ${error.message}`;
@@ -6553,11 +6678,13 @@ function webhookPayload(event, now = Date.now()) {
6553
6678
  *
6554
6679
  * `vars` expands `${ENV}` in the values, so a credential does not have to be written into the
6555
6680
  * config file. A name the panel's environment does not define is left as written, the same rule
6556
- * `expandEnv` follows everywhere else.
6681
+ * `expandEnv` follows everywhere else — and `unexpanded` names those, because a leftover `${…}`
6682
+ * is not a credential.
6557
6683
  */
6558
6684
  function parseHeaders(text, vars = process.env) {
6559
6685
  const headers = {};
6560
6686
  const errors = [];
6687
+ const unexpanded = [];
6561
6688
  for (const line of text.split("\n")) {
6562
6689
  const trimmed = line.trim();
6563
6690
  if (trimmed.length === 0 || trimmed.startsWith("#")) continue;
@@ -6566,11 +6693,15 @@ function parseHeaders(text, vars = process.env) {
6566
6693
  errors.push(`"${trimmed}" is not a "Name: value" header`);
6567
6694
  continue;
6568
6695
  }
6569
- headers[trimmed.slice(0, at).trim()] = expandEnv(trimmed.slice(at + 1).trim(), vars);
6696
+ const name = trimmed.slice(0, at).trim();
6697
+ const value = expandEnv(trimmed.slice(at + 1).trim(), vars);
6698
+ if (value.includes("${")) unexpanded.push(name);
6699
+ headers[name] = value;
6570
6700
  }
6571
6701
  return {
6572
6702
  headers,
6573
- errors
6703
+ errors,
6704
+ unexpanded
6574
6705
  };
6575
6706
  }
6576
6707
  /** Why a target cannot be sent to, or null when it can. Also used to validate a save. */
@@ -6584,8 +6715,9 @@ function targetProblem(target, options = {}) {
6584
6715
  return "the URL is not valid";
6585
6716
  }
6586
6717
  if (parsed.protocol !== "http:" && parsed.protocol !== "https:") return `the URL must be http or https, not ${parsed.protocol}`;
6587
- const { errors } = parseHeaders(target.headers);
6588
- return errors.length > 0 ? errors.join("; ") : null;
6718
+ const { errors, unexpanded } = parseHeaders(target.headers);
6719
+ const problems = [...errors, ...unexpanded.length > 0 ? [`the ${unexpanded.map((name) => `"${name}"`).join(", ")} header still holds an unexpanded placeholder — an environment variable in it is not set`] : []];
6720
+ return problems.length > 0 ? problems.join("; ") : null;
6589
6721
  }
6590
6722
  async function sendWebhook(target, event, fetchImpl) {
6591
6723
  const problem = targetProblem(target);
@@ -6640,7 +6772,7 @@ var init_webhook = __esmMin((() => {
6640
6772
  function readFile(file) {
6641
6773
  let text;
6642
6774
  try {
6643
- text = fs.readFileSync(file, "utf8");
6775
+ text = readStateFile(file);
6644
6776
  } catch (error) {
6645
6777
  if (error.code === "ENOENT") return {
6646
6778
  text: null,
@@ -6680,6 +6812,7 @@ var init_store = __esmMin((() => {
6680
6812
  init_seed();
6681
6813
  init_settings$1();
6682
6814
  init_atomic();
6815
+ init_config_text();
6683
6816
  init_ddns$2();
6684
6817
  init_webhook();
6685
6818
  init_contracts();
@@ -6749,8 +6882,26 @@ var init_store = __esmMin((() => {
6749
6882
  get configSchemaVersion() {
6750
6883
  return Math.max(this.settingsSchemaVersion, this.serversSchemaVersion);
6751
6884
  }
6885
+ /**
6886
+ * The steps a workspace's files need, counting **both** sides.
6887
+ *
6888
+ * The two files are stamped independently — a person may hand-write `servers.config.json`
6889
+ * (which is unstamped, and so reads as schema 1) beside a `settings.json` the panel wrote at
6890
+ * the current schema. `configSchemaVersion` answers `max()` because that is the shape *this
6891
+ * release* understands of the pair, but the migrations that have to run belong to the **older**
6892
+ * file: `planConfigMigrations` is monotonic, so the lower version is the one with steps.
6893
+ * Reading `max()` here reported *no* pending migration while the reader was refusing the file
6894
+ * for needing one, which left the startup branch that says `run migrate` unreachable and sent
6895
+ * the person to "fix or install" instead.
6896
+ *
6897
+ * A file that cannot be **parsed** is not a migration candidate, though: a schema number can only
6898
+ * be read from a file that is JSON, and `migrate` refuses one it cannot read rather than lifting
6899
+ * it. The startup guard prints this list as "run migrate", so a broken file must not appear
6900
+ * here — it belongs in `configError`'s "fix …" advice alone.
6901
+ */
6752
6902
  get pendingMigrations() {
6753
- return planConfigMigrations(this.configSchemaVersion).steps;
6903
+ if (this.settingsParseError !== null || this.serversParseError !== null) return [];
6904
+ return planConfigMigrations(Math.min(this.settingsSchemaVersion, this.serversSchemaVersion)).steps;
6754
6905
  }
6755
6906
  onChange(listener) {
6756
6907
  this.listeners.add(listener);
@@ -7517,16 +7668,19 @@ function createMetricsRoute(deps) {
7517
7668
  metric("hh_control_up", "Control plane is serving", ["hh_control_up 1"]);
7518
7669
  metric("hh_servers_total", "Configured servers", [`hh_servers_total ${servers.length}`]);
7519
7670
  metric("hh_server_up", "Server process is running", servers.map((server) => `hh_server_up{${labels(server)}} ${server.status === "running" ? 1 : 0}`));
7520
- metric("hh_server_restarts_total", "Restarts since the control plane started", servers.map((server) => `hh_server_restarts_total{${labels(server)}} ${server.restarts}`));
7671
+ metric("hh_server_restarts_total", "Restart attempts spent on the current crash sequence, reset by a start someone asked for", servers.map((server) => `hh_server_restarts_total{${labels(server)}} ${server.restarts}`));
7521
7672
  metric("hh_server_crashes_24h", "Crashes in the last 24 hours", servers.map((server) => `hh_server_crashes_24h{${labels(server)}} ${server.history.crashes}`));
7522
7673
  metric("hh_server_uptime_ratio_24h", "Share of the last 24 hours the server was up", servers.filter((server) => server.history.uptimeRatio !== null).map((server) => `hh_server_uptime_ratio_24h{${labels(server)}} ${server.history.uptimeRatio.toFixed(4)}`));
7523
7674
  metric("hh_server_response_ms", "Last health probe latency in milliseconds", servers.filter((server) => server.responseMs !== null).map((server) => `hh_server_response_ms{${labels(server)}} ${server.responseMs}`));
7524
7675
  metric("hh_server_rss_bytes", "RSS of the server process tree", servers.filter((server) => server.resources?.rssBytes != null).map((server) => `hh_server_rss_bytes{${labels(server)}} ${server.resources.rssBytes}`));
7525
7676
  metric("hh_server_cpu_percent", "CPU percent of the server process tree", servers.filter((server) => server.resources?.cpuPercent != null).map((server) => `hh_server_cpu_percent{${labels(server)}} ${server.resources.cpuPercent}`));
7526
- metric("hh_host_disk_used_percent", "Disk usage percent per configured path", host.disks.map((disk) => `hh_host_disk_used_percent{mount="${labelValue(disk.path)}"} ${disk.usedPercent.toFixed(2)}`));
7527
- metric("hh_host_memory_used_percent", "Memory usage percent", [`hh_host_memory_used_percent ${host.memoryUsedPercent.toFixed(2)}`]);
7528
- metric("hh_host_swap_used_percent", "Swap usage percent", [`hh_host_swap_used_percent ${host.swapUsedPercent.toFixed(2)}`]);
7529
- metric("hh_host_load1_per_cpu", "1 minute load average per cpu", [`hh_host_load1_per_cpu ${((host.loadAvg[0] ?? 0) / Math.max(1, host.cpus)).toFixed(3)}`]);
7677
+ if (host.sampledAt !== null) {
7678
+ metric("hh_host_disk_used_percent", "Disk usage percent per configured path", host.disks.map((disk) => `hh_host_disk_used_percent{mount="${labelValue(disk.path)}"} ${disk.usedPercent.toFixed(2)}`));
7679
+ metric("hh_host_cpu_used_percent", "Share of this machine's CPU capacity in use, 0-100", host.cpuUsedPercent == null ? [] : [`hh_host_cpu_used_percent ${host.cpuUsedPercent.toFixed(2)}`]);
7680
+ metric("hh_host_memory_used_percent", "Memory usage percent", [`hh_host_memory_used_percent ${host.memoryUsedPercent.toFixed(2)}`]);
7681
+ metric("hh_host_swap_used_percent", "Swap usage percent", [`hh_host_swap_used_percent ${host.swapUsedPercent.toFixed(2)}`]);
7682
+ metric("hh_host_load1_per_cpu", "1 minute load average per cpu", [`hh_host_load1_per_cpu ${((host.loadAvg[0] ?? 0) / Math.max(1, host.cpus)).toFixed(3)}`]);
7683
+ }
7530
7684
  return c.text(`${lines.join("\n")}\n`, 200, { "Content-Type": "text/plain; version=0.0.4; charset=utf-8" });
7531
7685
  });
7532
7686
  }
@@ -7693,10 +7847,13 @@ function createNotificationsRoute(deps) {
7693
7847
  400: ERROR_RESPONSES[400]
7694
7848
  }
7695
7849
  }), validate("query", workspaceQuerySchema), validate("param", destinationIdParamSchema), validate("json", notificationActionSchema), async (c) => {
7696
- const result = await runtimeFor(c.req.valid("query").workspace).notifications.sendTest(c.req.valid("param").id, c.req.valid("json"));
7850
+ const runtime = runtimeFor(c.req.valid("query").workspace);
7851
+ const id = c.req.valid("param").id;
7852
+ const kind = runtime.notifications.destinations().find((destination) => destination.id === id)?.kind;
7853
+ const result = await runtime.notifications.sendTest(id, c.req.valid("json"));
7697
7854
  if (!result.ok) throw new DetailedError(result.error ?? "the test message failed", {
7698
7855
  statusCode: 400,
7699
- code: "TELEGRAM_SEND_FAILED"
7856
+ code: kind === "webhook" ? "WEBHOOK_SEND_FAILED" : "TELEGRAM_SEND_FAILED"
7700
7857
  });
7701
7858
  return c.json(result);
7702
7859
  }).post("/notifications/test-webhook", describeRoute({
@@ -8658,6 +8815,176 @@ var init_port = __esmMin((() => {
8658
8815
  FILETIME_UNIX_OFFSET_MS = 0xa9730b66800;
8659
8816
  }));
8660
8817
  //#endregion
8818
+ //#region src/providers/process.ts
8819
+ /**
8820
+ * Resolves a bare command through the entry's own directory and the project's
8821
+ * `node_modules/.bin` first, so a server installed as a project dependency is
8822
+ * found even when the launcher's PATH has no pnpm-injected bin dir.
8823
+ */
8824
+ function resolveCommand(command, ...searchDirs) {
8825
+ if (command.includes("/") || command.includes("\\")) return command;
8826
+ const candidates = process.platform === "win32" && path.extname(command) === "" ? WINDOWS_SHIM_EXTENSIONS.map((extension) => `${command}${extension}`) : [command];
8827
+ for (const dir of searchDirs) for (const candidate of candidates) {
8828
+ const local = path.join(dir, "node_modules", ".bin", candidate);
8829
+ if (fs.existsSync(local)) return local;
8830
+ }
8831
+ return command;
8832
+ }
8833
+ /**
8834
+ * Does this program exist where `spawn` would look it up, and where?
8835
+ *
8836
+ * Used only to tell a **pasted command line** apart from a missing program: `spawn` answers both
8837
+ * with the same `ENOENT`, and the two have opposite fixes. `null` means it was not found anywhere
8838
+ * this process would search.
8839
+ *
8840
+ * A bare name is searched on `PATH` (plus `.exe`/`.cmd`/`.bat` on Windows, because that is what
8841
+ * the OS appends); anything with a separator is a path and is stat'd as written.
8842
+ */
8843
+ function findProgram(command, cwd = projectDir) {
8844
+ if (command.includes("/") || command.includes("\\")) {
8845
+ const resolved = path.resolve(cwd, command);
8846
+ return isExecutable(resolved) ? resolved : null;
8847
+ }
8848
+ const extensions = process.platform === "win32" ? ["", ...WINDOWS_SHIM_EXTENSIONS] : [""];
8849
+ const dirs = (process.env.PATH ?? "").split(path.delimiter).filter((dir) => dir.length > 0);
8850
+ for (const dir of dirs) for (const extension of extensions) {
8851
+ const candidate = path.join(dir, `${command}${extension}`);
8852
+ if (isExecutable(candidate)) return candidate;
8853
+ }
8854
+ return null;
8855
+ }
8856
+ /** A file this user may run. A directory named like a program is not one. */
8857
+ function isExecutable(file) {
8858
+ try {
8859
+ if (!fs.statSync(file).isFile()) return false;
8860
+ if (process.platform === "win32") return true;
8861
+ fs.accessSync(file, fs.constants.X_OK);
8862
+ return true;
8863
+ } catch {
8864
+ return false;
8865
+ }
8866
+ }
8867
+ /** Relative entry paths belong to the project that launched the panel. */
8868
+ function resolveCwd(cwd, base = projectDir) {
8869
+ return path.resolve(base, cwd);
8870
+ }
8871
+ /** Node cannot spawn a Windows `.cmd`/`.bat` shim without a shell (EINVAL). */
8872
+ function needsShell(command) {
8873
+ return process.platform === "win32" && /\.(?:cmd|bat)$/i.test(command);
8874
+ }
8875
+ function spawnManaged(spec, options = {}) {
8876
+ return spawn(spec.command, spec.args, {
8877
+ cwd: spec.cwd,
8878
+ env: {
8879
+ ...process.env,
8880
+ ...spec.env
8881
+ },
8882
+ detached: options.detached ?? true,
8883
+ stdio: [
8884
+ "ignore",
8885
+ "pipe",
8886
+ "pipe"
8887
+ ],
8888
+ shell: needsShell(spec.command),
8889
+ windowsHide: true
8890
+ });
8891
+ }
8892
+ /** SIGTERM (default) to the child, escalating to SIGKILL after the grace period. */
8893
+ async function terminate(child, options) {
8894
+ if (child.exitCode !== null || child.signalCode !== null) return "exited";
8895
+ const exited = waitForExit$1(child, options.graceMs);
8896
+ signalChild(child, options.signal, options.killGroup);
8897
+ if (await exited) return "exited";
8898
+ signalChild(child, "SIGKILL", options.killGroup);
8899
+ await waitForExit$1(child, 2e3);
8900
+ return "force-killed";
8901
+ }
8902
+ /**
8903
+ * Windows has no process groups and no SIGTERM: `taskkill /T` walks the tree and
8904
+ * `/F` is the only reliable way to stop a console process.
8905
+ */
8906
+ async function killTreeWindows(pid) {
8907
+ try {
8908
+ await execFileAsync$1("taskkill", [
8909
+ "/pid",
8910
+ String(pid),
8911
+ "/T",
8912
+ "/F"
8913
+ ], { timeout: 5e3 });
8914
+ } catch {}
8915
+ }
8916
+ function signalChild(child, signal, killGroup) {
8917
+ const pid = child.pid;
8918
+ if (pid === void 0) return;
8919
+ signalPid(pid, signal, killGroup);
8920
+ }
8921
+ function signalPid(pid, signal, killGroup) {
8922
+ if (process.platform === "win32") {
8923
+ if (killGroup) killTreeWindows(pid);
8924
+ else try {
8925
+ process.kill(pid, signal);
8926
+ } catch {}
8927
+ return;
8928
+ }
8929
+ if (killGroup) try {
8930
+ process.kill(-pid, signal);
8931
+ return;
8932
+ } catch {}
8933
+ try {
8934
+ process.kill(pid, signal);
8935
+ } catch {}
8936
+ }
8937
+ /**
8938
+ * The same shutdown a supervised child gets, for a process we adopted instead of
8939
+ * spawned: a detached successor is not our child, so it is signalled by pid (and
8940
+ * by process group when asked) and its exit is polled rather than awaited.
8941
+ *
8942
+ * Liveness comes from `isProcessAlive`, never a local signal-0 copy: a second definition returned
8943
+ * `false` for `EPERM`, so a process that was there but not ours to signal read as "exited" and
8944
+ * `'force-killed'` was returned for one still running. One predicate, one answer.
8945
+ */
8946
+ async function terminatePid(pid, options) {
8947
+ if (!isProcessAlive(pid)) return "exited";
8948
+ signalPid(pid, options.signal, options.killGroup);
8949
+ const deadline = Date.now() + Math.max(0, options.graceMs);
8950
+ while (Date.now() < deadline && isProcessAlive(pid)) await delay$1(50);
8951
+ if (!isProcessAlive(pid)) return "exited";
8952
+ signalPid(pid, "SIGKILL", options.killGroup);
8953
+ const hardDeadline = Date.now() + 2e3;
8954
+ while (Date.now() < hardDeadline && isProcessAlive(pid)) await delay$1(50);
8955
+ return "force-killed";
8956
+ }
8957
+ function delay$1(ms) {
8958
+ return new Promise((resolve) => setTimeout(resolve, ms));
8959
+ }
8960
+ function waitForExit$1(child, timeoutMs) {
8961
+ if (child.exitCode !== null || child.signalCode !== null) return Promise.resolve(true);
8962
+ if (timeoutMs <= 0) return Promise.resolve(false);
8963
+ return new Promise((resolve) => {
8964
+ const timer = setTimeout(() => {
8965
+ child.removeListener("exit", onExit);
8966
+ resolve(false);
8967
+ }, timeoutMs);
8968
+ function onExit() {
8969
+ clearTimeout(timer);
8970
+ resolve(true);
8971
+ }
8972
+ child.once("exit", onExit);
8973
+ });
8974
+ }
8975
+ var execFileAsync$1, WINDOWS_SHIM_EXTENSIONS;
8976
+ var init_process = __esmMin((() => {
8977
+ init_paths();
8978
+ init_port();
8979
+ execFileAsync$1 = promisify(execFile);
8980
+ WINDOWS_SHIM_EXTENSIONS = [
8981
+ ".exe",
8982
+ ".cmd",
8983
+ ".bat",
8984
+ ".ps1"
8985
+ ];
8986
+ }));
8987
+ //#endregion
8661
8988
  //#region src/providers/nanny.ts
8662
8989
  var nanny_exports$2 = /* @__PURE__ */ __exportAll({
8663
8990
  HEARTBEAT_STALE_MS: () => HEARTBEAT_STALE_MS,
@@ -8787,12 +9114,54 @@ function exitCodeHint(code) {
8787
9114
  *
8788
9115
  * `command` is the configured program, so the two cases can be told apart: if a bare name has no
8789
9116
  * path separator, the shell would have searched `PATH` and this one did not.
9117
+ *
9118
+ * A **missing working directory** is the third cause of the same errno, and it is the one a
9119
+ * deployment hits: `spawn` resolves `cwd` before it looks for the program, so an entry whose `cwd`
9120
+ * does not exist *under this launch directory* fails exactly like an uninstalled program. That read
9121
+ * sent a person to `which node` while `node` was fine and only the relative path was wrong (a unit
9122
+ * file with no `WorkingDirectory=`, a container started from `/`). `cwd` is therefore checked first:
9123
+ * if it is not an existing directory, nothing else about the spawn could have worked.
8790
9124
  */
8791
- function describeSpawnError(error, command) {
8792
- if (error.code === "ENOENT") return command.includes("/") || command.includes("\\") ? `\`${command}\` does not exist — check the path, and any directory on the way to it` : `\`${command}\` was not found — is it installed, and is it on PATH for the user running the panel?`;
9125
+ function describeSpawnError(error, command, cwd) {
9126
+ const missingDir = cwd === void 0 ? null : describeMissingDir(cwd);
9127
+ if (missingDir !== null && (error.code === "ENOENT" || error.code === "ENOTDIR")) return missingDir;
9128
+ if (error.code === "ENOENT") {
9129
+ const pasted = describePastedCommandLine(command, cwd);
9130
+ if (pasted !== null) return pasted;
9131
+ return command.includes("/") || command.includes("\\") ? `\`${command}\` does not exist — check the path, and any directory on the way to it` : `\`${command}\` was not found — is it installed, and is it on PATH for the user running the panel?`;
9132
+ }
8793
9133
  if (error.code === "EACCES") return `\`${command}\` exists but is not executable — check its permissions (chmod +x)`;
8794
9134
  return `${error.message} (while running \`${command}\`)`;
8795
9135
  }
9136
+ /**
9137
+ * The first mistake the Add-server form invites: a whole command line typed into `Command`.
9138
+ *
9139
+ * `Command` is spawned **without a shell** and `Arguments` is a separate field, so `node server.js`
9140
+ * names a program called `node server.js`. The fix is to split it — and the sentence has to say so,
9141
+ * because the alternative reading ("node is not installed") is what sends someone to `which node`
9142
+ * while `node` is right there.
9143
+ *
9144
+ * Only claimed when the evidence is unambiguous: the field has whitespace, and the program it opens
9145
+ * with **does** resolve. So a genuinely missing program keeps the message about PATH, and a path with
9146
+ * a space in it is never split (it has no bare first word that resolves). See `findProgram`.
9147
+ */
9148
+ function describePastedCommandLine(command, cwd) {
9149
+ const words = command.trim().split(/\s+/);
9150
+ if (words.length < 2) return null;
9151
+ const program = words[0];
9152
+ if (findProgram(program, cwd) === null) return null;
9153
+ return `\`${command}\` is a whole command line, but \`Command\` is spawned without a shell — this release looks for a program named \`${command}\`. Put \`${program}\` in \`Command\` and the rest in \`Arguments\`, one argument per line`;
9154
+ }
9155
+ /** Why a working directory cannot be used, in one sentence, or null when it can. */
9156
+ function describeMissingDir(cwd) {
9157
+ try {
9158
+ if (fs.statSync(cwd).isDirectory()) return null;
9159
+ return `the working directory \`${cwd}\` is not a directory — a relative \`cwd\` resolves against the directory the panel was started from`;
9160
+ } catch (error) {
9161
+ if (error.code === "ENOENT") return `the working directory \`${cwd}\` does not exist — a relative \`cwd\` resolves against the directory the panel was started from, so a service started from elsewhere (systemd, docker, a login shell) looks in a different place`;
9162
+ return `the working directory \`${cwd}\` cannot be read — check its permissions`;
9163
+ }
9164
+ }
8796
9165
  /** `SIGKILL` for 9, or null when the number names nothing. */
8797
9166
  function signalName(number) {
8798
9167
  for (const [name, value] of Object.entries(os.constants.signals)) if (value === number) return name;
@@ -8818,6 +9187,7 @@ var init_nanny$2 = __esmMin((() => {
8818
9187
  init_identity();
8819
9188
  init_port();
8820
9189
  init_proc();
9190
+ init_process();
8821
9191
  init_contracts();
8822
9192
  SPEC_MODE = 384;
8823
9193
  SPEC_SUFFIX = ".spec.json";
@@ -13133,142 +13503,6 @@ var init_archive = __esmMin((() => {
13133
13503
  ];
13134
13504
  }));
13135
13505
  //#endregion
13136
- //#region src/providers/process.ts
13137
- /**
13138
- * Resolves a bare command through the entry's own directory and the project's
13139
- * `node_modules/.bin` first, so a server installed as a project dependency is
13140
- * found even when the launcher's PATH has no pnpm-injected bin dir.
13141
- */
13142
- function resolveCommand(command, ...searchDirs) {
13143
- if (command.includes("/") || command.includes("\\")) return command;
13144
- const candidates = process.platform === "win32" && path.extname(command) === "" ? [command, ...WINDOWS_SHIM_EXTENSIONS.map((extension) => `${command}${extension}`)] : [command];
13145
- for (const dir of searchDirs) for (const candidate of candidates) {
13146
- const local = path.join(dir, "node_modules", ".bin", candidate);
13147
- if (fs.existsSync(local)) return local;
13148
- }
13149
- return command;
13150
- }
13151
- /** Relative entry paths belong to the project that launched the panel. */
13152
- function resolveCwd(cwd, base = projectDir) {
13153
- return path.resolve(base, cwd);
13154
- }
13155
- /** Node cannot spawn a Windows `.cmd`/`.bat` shim without a shell (EINVAL). */
13156
- function needsShell(command) {
13157
- return process.platform === "win32" && /\.(?:cmd|bat)$/i.test(command);
13158
- }
13159
- function spawnManaged(spec, options = {}) {
13160
- return spawn(spec.command, spec.args, {
13161
- cwd: spec.cwd,
13162
- env: {
13163
- ...process.env,
13164
- ...spec.env
13165
- },
13166
- detached: options.detached ?? true,
13167
- stdio: [
13168
- "ignore",
13169
- "pipe",
13170
- "pipe"
13171
- ],
13172
- shell: needsShell(spec.command),
13173
- windowsHide: true
13174
- });
13175
- }
13176
- /** SIGTERM (default) to the child, escalating to SIGKILL after the grace period. */
13177
- async function terminate(child, options) {
13178
- if (child.exitCode !== null || child.signalCode !== null) return "exited";
13179
- const exited = waitForExit$1(child, options.graceMs);
13180
- signalChild(child, options.signal, options.killGroup);
13181
- if (await exited) return "exited";
13182
- signalChild(child, "SIGKILL", options.killGroup);
13183
- await waitForExit$1(child, 2e3);
13184
- return "force-killed";
13185
- }
13186
- /**
13187
- * Windows has no process groups and no SIGTERM: `taskkill /T` walks the tree and
13188
- * `/F` is the only reliable way to stop a console process.
13189
- */
13190
- async function killTreeWindows(pid) {
13191
- try {
13192
- await execFileAsync$1("taskkill", [
13193
- "/pid",
13194
- String(pid),
13195
- "/T",
13196
- "/F"
13197
- ], { timeout: 5e3 });
13198
- } catch {}
13199
- }
13200
- function signalChild(child, signal, killGroup) {
13201
- const pid = child.pid;
13202
- if (pid === void 0) return;
13203
- signalPid(pid, signal, killGroup);
13204
- }
13205
- function signalPid(pid, signal, killGroup) {
13206
- if (process.platform === "win32") {
13207
- if (killGroup) killTreeWindows(pid);
13208
- else try {
13209
- process.kill(pid, signal);
13210
- } catch {}
13211
- return;
13212
- }
13213
- if (killGroup) try {
13214
- process.kill(-pid, signal);
13215
- return;
13216
- } catch {}
13217
- try {
13218
- process.kill(pid, signal);
13219
- } catch {}
13220
- }
13221
- /**
13222
- * The same shutdown a supervised child gets, for a process we adopted instead of
13223
- * spawned: a detached successor is not our child, so it is signalled by pid (and
13224
- * by process group when asked) and its exit is polled rather than awaited.
13225
- *
13226
- * Liveness comes from `isProcessAlive`, never a local signal-0 copy: a second definition returned
13227
- * `false` for `EPERM`, so a process that was there but not ours to signal read as "exited" and
13228
- * `'force-killed'` was returned for one still running. One predicate, one answer.
13229
- */
13230
- async function terminatePid(pid, options) {
13231
- if (!isProcessAlive(pid)) return "exited";
13232
- signalPid(pid, options.signal, options.killGroup);
13233
- const deadline = Date.now() + Math.max(0, options.graceMs);
13234
- while (Date.now() < deadline && isProcessAlive(pid)) await delay$1(50);
13235
- if (!isProcessAlive(pid)) return "exited";
13236
- signalPid(pid, "SIGKILL", options.killGroup);
13237
- const hardDeadline = Date.now() + 2e3;
13238
- while (Date.now() < hardDeadline && isProcessAlive(pid)) await delay$1(50);
13239
- return "force-killed";
13240
- }
13241
- function delay$1(ms) {
13242
- return new Promise((resolve) => setTimeout(resolve, ms));
13243
- }
13244
- function waitForExit$1(child, timeoutMs) {
13245
- if (child.exitCode !== null || child.signalCode !== null) return Promise.resolve(true);
13246
- if (timeoutMs <= 0) return Promise.resolve(false);
13247
- return new Promise((resolve) => {
13248
- const timer = setTimeout(() => {
13249
- child.removeListener("exit", onExit);
13250
- resolve(false);
13251
- }, timeoutMs);
13252
- function onExit() {
13253
- clearTimeout(timer);
13254
- resolve(true);
13255
- }
13256
- child.once("exit", onExit);
13257
- });
13258
- }
13259
- var execFileAsync$1, WINDOWS_SHIM_EXTENSIONS;
13260
- var init_process = __esmMin((() => {
13261
- init_paths();
13262
- init_port();
13263
- execFileAsync$1 = promisify(execFile);
13264
- WINDOWS_SHIM_EXTENSIONS = [
13265
- ".cmd",
13266
- ".exe",
13267
- ".bat",
13268
- ".ps1"
13269
- ];
13270
- }));
13271
- //#endregion
13272
13506
  //#region src/helpers/backoff.ts
13273
13507
  /** Exponential backoff: base * factor^(attempt - 1), capped at maxDelayMs. */
13274
13508
  function computeBackoff(attempt, options) {
@@ -14896,7 +15130,7 @@ var init_supervisor = __esmMin((() => {
14896
15130
  const stderr = new LineSplitter((stream, text) => this.log(entry, stream, text));
14897
15131
  child.stdout?.on("data", (chunk) => stdout.push("stdout", chunk));
14898
15132
  child.stderr?.on("data", (chunk) => stderr.push("stderr", chunk));
14899
- this.attachChild(entry, child, `${command} ${args.join(" ")}`.trim(), () => {
15133
+ this.attachChild(entry, child, `${command} ${args.join(" ")}`.trim(), cwd, () => {
14900
15134
  stdout.flush("stdout");
14901
15135
  stderr.flush("stderr");
14902
15136
  });
@@ -14950,7 +15184,7 @@ var init_supervisor = __esmMin((() => {
14950
15184
  return this.failSpawn(entry, error.message);
14951
15185
  }
14952
15186
  child.unref();
14953
- this.attachChild(entry, child, `nanny → ${command} ${args.join(" ")}`.trim());
15187
+ this.attachChild(entry, child, `nanny → ${command} ${args.join(" ")}`.trim(), cwd);
14954
15188
  this.followPersistent(entry);
14955
15189
  return { ok: true };
14956
15190
  }
@@ -14964,8 +15198,14 @@ var init_supervisor = __esmMin((() => {
14964
15198
  error: message
14965
15199
  };
14966
15200
  }
14967
- /** The bookkeeping every spawn shares, plus the exit events that end it. */
14968
- attachChild(entry, child, detail, flush) {
15201
+ /**
15202
+ * The bookkeeping every spawn shares, plus the exit events that end it.
15203
+ *
15204
+ * `cwd` is the directory the child was spawned in. A spawn that fails with `ENOENT` may have
15205
+ * failed because the *working directory* is missing rather than the program — `spawn` resolves
15206
+ * one before it looks for the other — so `describeSpawnError` needs it to name the real cause.
15207
+ */
15208
+ attachChild(entry, child, detail, cwd, flush) {
14969
15209
  entry.child = child;
14970
15210
  entry.pid = child.pid ?? null;
14971
15211
  entry.startedAt = Date.now();
@@ -14989,7 +15229,7 @@ var init_supervisor = __esmMin((() => {
14989
15229
  entry.unhealthySince = null;
14990
15230
  this.publishServer(entry);
14991
15231
  child.once("error", (error) => {
14992
- entry.lastError = describeSpawnError(error, entry.config.command);
15232
+ entry.lastError = describeSpawnError(error, entry.config.command, cwd);
14993
15233
  this.log(entry, "system", `process error: ${entry.lastError}`);
14994
15234
  flush?.();
14995
15235
  this.handleExit(entry, child, null, null);
@@ -19834,16 +20074,16 @@ async function runControlPlane(options) {
19834
20074
  const settings = new GlobalSettingsStore();
19835
20075
  settings.load();
19836
20076
  settings.writeJsonSchema();
19837
- if (settings.configError !== null) {
19838
- logger.error(`refusing to start: ${settings.configError}`);
19839
- logger.info(`fix ${settings.path}, or install the release that wrote it`);
19840
- process.exit(1);
19841
- }
19842
20077
  if (settings.pendingMigrations.length > 0) {
19843
20078
  logger.error(`refusing to start: ${settings.path} needs ${settings.pendingMigrations.length} migration(s) before ${appVersion()} can use it`);
19844
20079
  logger.info("run `home-hosted migrate` to see and apply them");
19845
20080
  process.exit(1);
19846
20081
  }
20082
+ if (settings.configError !== null) {
20083
+ logger.error(`refusing to start: ${settings.configError}`);
20084
+ logger.info(`fix ${settings.path}, or install the release that wrote it`);
20085
+ process.exit(1);
20086
+ }
19847
20087
  const registry = new WorkspaceRegistry();
19848
20088
  registry.load();
19849
20089
  if (registry.configError !== null) {
@@ -19998,6 +20238,11 @@ async function runControlPlane(options) {
19998
20238
  });
19999
20239
  for (const workspace of panel.workspaces()) {
20000
20240
  const store = workspace.store;
20241
+ if (store.pendingMigrations.length > 0) {
20242
+ logger.error(`refusing to start: workspace "${workspace.id}" needs ${store.pendingMigrations.length} migration(s) before ${appVersion()} can use it`);
20243
+ logger.info("run `home-hosted migrate` to see and apply them");
20244
+ process.exit(1);
20245
+ }
20001
20246
  if (store.configError !== null) {
20002
20247
  logger.error(`refusing to start: workspace "${workspace.id}": ${store.configError}`);
20003
20248
  logger.info(`fix ${store.path} and ${store.settingsPath}, or install the release that wrote them`);
@@ -20008,11 +20253,6 @@ async function runControlPlane(options) {
20008
20253
  logger.info("fix or restore the file, or move it aside to start fresh — starting fresh discards it");
20009
20254
  process.exit(1);
20010
20255
  }
20011
- if (store.pendingMigrations.length > 0) {
20012
- logger.error(`refusing to start: workspace "${workspace.id}" needs ${store.pendingMigrations.length} migration(s) before ${appVersion()} can use it`);
20013
- logger.info("run `home-hosted migrate` to see and apply them");
20014
- process.exit(1);
20015
- }
20016
20256
  }
20017
20257
  let shuttingDown = false;
20018
20258
  const shutdown = async (reason) => {
@@ -20890,7 +21130,7 @@ function targets() {
20890
21130
  validate: (raw) => {
20891
21131
  let defaults = {};
20892
21132
  try {
20893
- const settingsRaw = JSON.parse(fs.readFileSync(workspaceSettingsPath(workspace.id), "utf8"));
21133
+ const settingsRaw = JSON.parse(readStateFile(workspaceSettingsPath(workspace.id)));
20894
21134
  const meta = typeof settingsRaw.meta === "object" && settingsRaw.meta !== null ? settingsRaw.meta : {};
20895
21135
  const from = typeof meta.schema === "number" ? meta.schema : 1;
20896
21136
  defaults = (planConfigMigrations(from).steps.length > 0 ? applyConfigMigrations(settingsRaw, from).config : settingsRaw)?.defaults ?? {};
@@ -20909,7 +21149,7 @@ async function runMigrate(dryRun, yes) {
20909
21149
  for (const target of existing) {
20910
21150
  let raw;
20911
21151
  try {
20912
- raw = JSON.parse(fs.readFileSync(target.file, "utf8"));
21152
+ raw = JSON.parse(readStateFile(target.file));
20913
21153
  } catch (error) {
20914
21154
  fail(`cannot read ${target.file}: ${errorMessage(error)}`);
20915
21155
  }
@@ -20970,6 +21210,7 @@ var init_migrate = __esmMin((() => {
20970
21210
  init_parse();
20971
21211
  init_workspaces();
20972
21212
  init_atomic();
21213
+ init_config_text();
20973
21214
  init_paths();
20974
21215
  init_version();
20975
21216
  init_error_message();
@@ -21081,6 +21322,23 @@ function detectPackageManager(exists) {
21081
21322
  function runCommand$1(pm, script) {
21082
21323
  return pm === "npm" ? `npm run ${script}` : `${pm} run ${script}`;
21083
21324
  }
21325
+ /**
21326
+ * The `cd` that reaches a scaffolded project, quoted for the shell it will be pasted into.
21327
+ *
21328
+ * The directory is the person's choice, and a space in it is ordinary — `C:\Users\Ann Lee`,
21329
+ * `/srv/my apps`, and the default `./my-servers` all sit under one on some machine. Unquoted,
21330
+ * the line `init` printed as its own "Next:" step was `cd my servers && npm run up`, which the
21331
+ * shell answers `cd: too many arguments` — an error naming a command the person did not
21332
+ * compose, on the one line the scaffold exists to hand them.
21333
+ *
21334
+ * POSIX gets single quotes, with an embedded quote closed and reopened (`'\''`), which is the
21335
+ * one form that is safe inside a single-quoted string. Windows' `cmd.exe` has no single-quote
21336
+ * quoting at all, so it gets double quotes: that is what it understands, and a path whose name
21337
+ * contains a `"` is not representable there either way.
21338
+ */
21339
+ function cdCommand(where) {
21340
+ return `cd ${process.platform === "win32" ? `"${where}"` : `'${where.replace(/'/g, `'\\''`)}'`} && `;
21341
+ }
21084
21342
  /** Install arguments for a scaffolded project (the manifest already lists the dependency). */
21085
21343
  function installArgs(pm) {
21086
21344
  return pm === "yarn" ? [] : ["install"];
@@ -21153,7 +21411,7 @@ async function runInit(options) {
21153
21411
  }
21154
21412
  const relative = path.relative(process.cwd(), target);
21155
21413
  const where = relative.length === 0 || relative.startsWith("..") ? target : relative;
21156
- const cd = relative.length === 0 ? "" : `cd ${where} && `;
21414
+ const cd = relative.length === 0 ? "" : cdCommand(where);
21157
21415
  process.stdout.write(`\nNext:\n`);
21158
21416
  process.stdout.write(` ${bold(`${cd}${runCommand$1(pm, "up")}`)} start the panel (default password \`hh\`)\n`);
21159
21417
  process.stdout.write(` ${dim("then change that password under Settings → Authentication, and add your servers")}\n`);
@@ -21946,11 +22204,18 @@ function filterEntries(entries, scope, exclude) {
21946
22204
  * An id that matches nothing is silently ignored by the service, which is right for an archive that
21947
22205
  * simply does not carry something — and wrong for a typo: `--exclude global:secret` excludes nothing
21948
22206
  * and says nothing, so the archive carries the credentials the person believed they had dropped.
22207
+ *
22208
+ * `action` decides the hint, because the two directions list their ids from different places: a
22209
+ * create plan lists what this host declares, a restore plan lists what the archive holds — and the
22210
+ * command that prints that one is a restore, not a create.
21949
22211
  */
21950
- function assertKnown(ids, entries, flag) {
22212
+ function assertKnown(ids, entries, flag, action) {
21951
22213
  if (ids === void 0) return;
21952
22214
  const unknown = unknownBackupIds(ids, entries);
21953
- if (unknown.length > 0) fail(`${flag} names ${unknown.map((id) => `"${id}"`).join(", ")}, which ${unknown.length === 1 ? "is" : "are"} not in this plan — \`backup create\` with no flags lists the ids`);
22215
+ if (unknown.length > 0) {
22216
+ const hint = action === "create" ? `\`backup create\` with no flags lists the ids` : `\`backup restore <name>\` with no --include/--exclude lists the ids the archive holds`;
22217
+ fail(`${flag} names ${unknown.map((id) => `"${id}"`).join(", ")}, which ${unknown.length === 1 ? "is" : "are"} not in this plan — ${hint}`);
22218
+ }
21954
22219
  }
21955
22220
  /** `--exclude` parsed. An empty value is a mistake, not "exclude nothing". */
21956
22221
  function parseExclude(raw) {
@@ -22107,8 +22372,8 @@ async function runBackupCreate(options) {
22107
22372
  await service.warm();
22108
22373
  return service.view().entries;
22109
22374
  })();
22110
- assertKnown(options.exclude, entries, "--exclude");
22111
- assertKnown(scope.kind === "include" ? scope.ids : void 0, entries, "--include");
22375
+ assertKnown(options.exclude, entries, "--exclude", "create");
22376
+ assertKnown(scope.kind === "include" ? scope.ids : void 0, entries, "--include", "create");
22112
22377
  const wanted = filterEntries(entries, scope, options.exclude);
22113
22378
  if (!options.confirm) {
22114
22379
  if (options.json) {
@@ -22175,6 +22440,32 @@ async function runBackupCreate(options) {
22175
22440
  async function runningEntries() {
22176
22441
  return (await offlineBackup()).runningNow();
22177
22442
  }
22443
+ /**
22444
+ * Why a restore plan is not something to apply, or `null`.
22445
+ *
22446
+ * The service answers a plan for every archive, including ones it refuses to read: `error` carries
22447
+ * the refusal and `items` is empty. A caller that reads only `items` sees a tidy empty restore — and
22448
+ * on a blank host, `restored 0 items` printed with exit 0 is the worst possible answer, because
22449
+ * nothing distinguishes "this archive was empty" from "this archive could not be opened".
22450
+ *
22451
+ * `needsPassword` is its own case: it is the one refusal the person can fix from the same command.
22452
+ */
22453
+ function planRefusal(plan) {
22454
+ if (plan === null) return null;
22455
+ if (plan.needsPassword === true) return `${plan.error ?? "this backup is password-protected"} — add \`--password <text>\` to unlock it`;
22456
+ if (plan.error !== void 0 && plan.error.length > 0) return plan.error;
22457
+ return null;
22458
+ }
22459
+ /**
22460
+ * The plan's refusals and per-item skips, as lines a person can act on.
22461
+ *
22462
+ * `skipped` is the same list the UI draws, and it is the only thing that says a piece of an
22463
+ * otherwise successful restore was left behind — an unreadable `servers.config.json`, a data path
22464
+ * whose declaration changed. Printing only the applied count reported such a restore as complete.
22465
+ */
22466
+ function restoreNotes(plan) {
22467
+ return plan?.skipped ?? [];
22468
+ }
22178
22469
  async function runBackupRestore(options) {
22179
22470
  const scope = options.scope;
22180
22471
  const service = await usesPanel() ? null : (await offlineBackup()).service;
@@ -22182,7 +22473,7 @@ async function runBackupRestore(options) {
22182
22473
  const plan = await (async () => {
22183
22474
  if (service !== null) {
22184
22475
  const archive = service.resolve(options.name);
22185
- if (archive === null) fail(`no backup named "${options.name}" — \`${invocation()} backup list\` shows them`);
22476
+ if (archive === null) fail(`no backup named "${options.name}" in ${service.directory} — a restore takes the archive's file name, not a path; copy it there first (\`${invocation()} backup list\` shows what is there)`);
22186
22477
  return await service.restore(archive, {
22187
22478
  confirm: false,
22188
22479
  password: options.password,
@@ -22192,33 +22483,43 @@ async function runBackupRestore(options) {
22192
22483
  }
22193
22484
  const runtime = await livePanel();
22194
22485
  if (runtime === null) fail(`the control panel is not answering — try again once it is up`);
22195
- const base = new URLSearchParams({ name: options.name });
22196
- if (options.password !== void 0 && options.password.length > 0) base.set("password", options.password);
22197
- if (scope.kind === "include") base.set("include", scope.ids.join(","));
22198
- if (options.exclude !== void 0) base.set("exclude", options.exclude.join(","));
22486
+ const base = restoreQuery(options, scope);
22199
22487
  const answer = await runtime.request(runtime, `/_hh/backups/restore${suffixOf(base)}`, 12e4);
22200
22488
  if (answer === null) fail(`the control panel is not answering at ${runtime.probeUrl}`);
22201
22489
  if (answer.status !== 200) refusal(answer);
22202
22490
  return answer.body;
22203
22491
  })();
22492
+ const refused = planRefusal(plan);
22493
+ if (refused !== null) {
22494
+ if (options.json) process.stdout.write(`${JSON.stringify({
22495
+ action: "restore",
22496
+ apply: false,
22497
+ name: options.name,
22498
+ error: refused
22499
+ }, null, 2)}\n`);
22500
+ fail(refused);
22501
+ }
22204
22502
  const items = (plan?.items ?? []).filter((item) => item.selected !== false);
22503
+ const archiveItems = plan?.items ?? [];
22504
+ if (options.exclude !== void 0) assertKnown(options.exclude, archiveItems, "--exclude", "restore");
22505
+ if (scope.kind === "include") assertKnown(scope.ids, archiveItems, "--include", "restore");
22205
22506
  if (options.json && !options.confirm) {
22206
22507
  process.stdout.write(`${JSON.stringify({
22207
22508
  action: "restore",
22208
22509
  apply: false,
22209
22510
  name: options.name,
22210
22511
  items,
22211
- warnings: plan?.warnings ?? []
22512
+ skipped: restoreNotes(plan)
22212
22513
  }, null, 2)}\n`);
22213
22514
  return;
22214
22515
  }
22215
22516
  if (!options.json) {
22216
- process.stdout.write(`${bold("Plan")} for ${options.name} — nothing has been written yet\n`);
22517
+ process.stdout.write(options.confirm ? `${bold("Plan")} for ${options.name} — applying it now\n` : `${bold("Plan")} for ${options.name} — nothing has been written yet\n`);
22217
22518
  printPlanTree(items.map((item) => ({
22218
22519
  id: item.id,
22219
22520
  note: item.note ?? null
22220
22521
  })));
22221
- for (const warning of plan?.warnings ?? []) process.stdout.write(` ${dim("!")} ${warning}\n`);
22522
+ if (!options.confirm) for (const note of restoreNotes(plan)) process.stdout.write(` ${dim("!")} ${note}\n`);
22222
22523
  if (items.length === 0) {
22223
22524
  process.stdout.write(" (nothing to restore — check --include, or what this host declares)\n");
22224
22525
  return;
@@ -22236,43 +22537,72 @@ async function runBackupRestore(options) {
22236
22537
  exclude: options.exclude
22237
22538
  });
22238
22539
  return {
22239
- items: (result.items ?? []).filter((item) => item.selected !== false),
22240
- hooks: (result.hooks ?? []).filter((hook) => hook.action === "load")
22540
+ ...result,
22541
+ items: (result.items ?? []).filter((item) => item.selected !== false)
22241
22542
  };
22242
22543
  }
22243
22544
  const runtime = await livePanel();
22244
22545
  if (runtime === null) fail("the control panel stopped answering — nothing further was written");
22245
- const base = new URLSearchParams({ name: options.name });
22246
- if (options.password !== void 0 && options.password.length > 0) base.set("password", options.password);
22247
- if (scope.kind === "include") base.set("include", scope.ids.join(","));
22248
- if (options.exclude !== void 0) base.set("exclude", options.exclude.join(","));
22546
+ const base = restoreQuery(options, scope);
22249
22547
  const answer = await runtime.request(runtime, `/_hh/backups/restore${withParam(suffixOf(base), "confirm", "true")}`, 6e5);
22250
22548
  if (answer === null) fail(`the control panel is not answering at ${runtime.probeUrl}`);
22251
22549
  if (answer.status !== 200) refusal(answer);
22252
22550
  const result = answer.body;
22253
22551
  return {
22552
+ ...result,
22254
22553
  items: (result?.items ?? plan?.items ?? []).filter((item) => item.selected !== false),
22255
- hooks: (result?.hooks ?? plan?.hooks ?? []).filter((hook) => hook.action === "load")
22554
+ ...result?.hooks === void 0 && plan?.hooks !== void 0 ? { hooks: plan.hooks } : {}
22256
22555
  };
22257
22556
  })();
22258
- const applied = outcome.items;
22557
+ const applyRefused = planRefusal(outcome);
22558
+ if (applyRefused !== null) {
22559
+ if (options.json) process.stdout.write(`${JSON.stringify({
22560
+ action: "restore",
22561
+ apply: true,
22562
+ name: options.name,
22563
+ error: applyRefused
22564
+ }, null, 2)}\n`);
22565
+ fail(applyRefused);
22566
+ }
22567
+ const applied = (outcome.items ?? []).filter((item) => item.selected !== false);
22568
+ const hooks = (outcome.hooks ?? []).filter((hook) => hook.action === "load");
22569
+ const notes = restoreNotes(plan);
22259
22570
  if (options.json) {
22260
22571
  process.stdout.write(`${JSON.stringify({
22261
22572
  action: "restore",
22262
22573
  apply: true,
22263
22574
  name: options.name,
22264
22575
  items: applied,
22265
- hooks: outcome.hooks,
22266
- warnings: plan?.warnings ?? []
22576
+ hooks,
22577
+ skipped: notes,
22578
+ ...outcome.restartRequired === true ? { restartRequired: true } : {},
22579
+ ...(outcome.createdWorkspaces ?? []).length === 0 ? {} : { createdWorkspaces: outcome.createdWorkspaces },
22580
+ ...(outcome.replacedUnderRunning ?? []).length === 0 ? {} : { replacedUnderRunning: outcome.replacedUnderRunning }
22267
22581
  }, null, 2)}\n`);
22268
22582
  return;
22269
22583
  }
22270
- process.stdout.write(`${green("restored")} ${applied.length} ${applied.length === 1 ? "item" : "items"} from ${options.name}\n`);
22271
- for (const hook of outcome.hooks) process.stdout.write(` ${dim(`load ${hook.serverId}: ${hook.output ?? "staged"}`)}\n`);
22272
- for (const warning of plan?.warnings ?? []) process.stdout.write(` ${dim("!")} ${warning}\n`);
22584
+ if (applied.length === 0) process.stdout.write(`${green("restored")} nothing — the archive carried no item this host can take\n`);
22585
+ else process.stdout.write(`${green("restored")} ${applied.length} ${applied.length === 1 ? "item" : "items"} from ${options.name}\n`);
22586
+ for (const hook of hooks) process.stdout.write(` ${dim(`load ${hook.serverId}: ${hook.output ?? "staged"}`)}\n`);
22587
+ for (const note of notes) process.stdout.write(` ${dim("!")} ${note}\n`);
22588
+ if (outcome.restartRequired === true) process.stdout.write(` ${dim(`! the panel's listener changed — restart it so it binds where the archive says (\`${invocation()} restart\`)`)}\n`);
22589
+ if ((outcome.createdWorkspaces ?? []).length > 0) process.stdout.write(` ${dim(`! created ${outcome.createdWorkspaces.join(", ")}, which this host did not have`)}\n`);
22273
22590
  if (service !== null) process.stdout.write(dim(`the panel is not running, so nothing was reloaded — the next \`${invocation()} up\` reads what was restored\n`));
22274
22591
  }
22275
22592
  }
22593
+ /**
22594
+ * The restore query both the plan and the apply send.
22595
+ *
22596
+ * One builder, because the two requests must agree: a password or a selection on the plan and not on
22597
+ * the apply made the apply answer about different items than the person approved.
22598
+ */
22599
+ function restoreQuery(options, scope) {
22600
+ const base = new URLSearchParams({ name: options.name });
22601
+ if (options.password !== void 0 && options.password.length > 0) base.set("password", options.password);
22602
+ if (scope.kind === "include") base.set("include", scope.ids.join(","));
22603
+ if (options.exclude !== void 0) base.set("exclude", options.exclude.join(","));
22604
+ return base;
22605
+ }
22276
22606
  var backupCommand;
22277
22607
  var init_backup = __esmMin((() => {
22278
22608
  init_backup_offline();
@@ -22453,7 +22783,7 @@ async function runNanny(spec, statePath) {
22453
22783
  };
22454
22784
  child.once("exit", (code, signal) => finish(code, signal, Date.now() - startedAt));
22455
22785
  child.once("error", (error) => {
22456
- finish(null, null, 0, `persistent: could not start the entry: ${error.message}`);
22786
+ finish(null, null, 0, `persistent: could not start the entry: ${describeSpawnError(error, spec.command, spec.cwd)}`);
22457
22787
  });
22458
22788
  });
22459
22789
  process.exit(exitCode);