home-hosted 0.9.8 → 0.9.9

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/AGENTS.md CHANGED
@@ -111,6 +111,10 @@ workspace config guard, so a busy default port turns config tests red for the wr
111
111
  - **A bounded read stays bounded.** `logs --lines 1e3` falls back to the default and `0x10` is not the
112
112
  "whole log" sentinel (`src/cli/logs.ts`); `--lines N` reads a tail, never the whole file
113
113
  (`test/cli/logs.test.ts`).
114
+ - **A metric with no reading is absent, never zero.** A scrape has no page to qualify a number, so an
115
+ alerted-on gauge published as `0` from an unsampled view is indistinguishable from a healthy one
116
+ and silences the rule that exists to catch it. Omit the series (`src/api/metrics.ts`), and never
117
+ suffix `_total` a value that a user action resets.
114
118
  - **Conventional commits** — changelogen derives the changelog and `scripts/check-release-version.mjs`
115
119
  the version bump. Below 1.0 the **minor is the breaking channel**: a fix is a patch, a minor means
116
120
  someone has to read the release notes and act — ask what the user has to do, not whether the commit
package/README.md CHANGED
@@ -241,13 +241,24 @@ default workspace.
241
241
  | `PUT`/`DELETE /api/notifications/destinations/:id/token`, `POST /api/notifications/destinations/:id/{test,detect-chats}`, `POST /api/notifications/test-webhook` | one destination's bot credential, and a test send | ✅ |
242
242
  | `GET`/`PATCH /api/settings/workspace` | server defaults, logs, notifications | ✅ |
243
243
  | `GET`/`PATCH /api/settings` | panel-wide: listener, authentication, TLS, host vitals, backups | ❌ |
244
- | `GET`/`POST /api/backups`, restore | archives | ❌ |
244
+ | `GET`/`POST /api/backups`, restore | archives; a create or restore body selects with `include` and/or `exclude` | ❌ |
245
245
  | `GET`/`PATCH /api/proxy`, `POST /api/proxy/{engine,start,stop,apply,revert}`, `PUT`/`DELETE /api/proxy/certificates/:id` | the reverse proxy: its engine, its route table, and its uploaded certificates | ❌ |
246
246
  | `GET /healthz` | no session needed — the one an external monitor wants (its per-server detail needs a credential) | ❌ |
247
- | `GET /api/metrics` | Prometheus text (needs a token or session, like every `/api` route) | ❌ |
247
+ | `GET /api/metrics` | Prometheus text (needs a token or session, like every `/api` route) — scrape it with a bearer token | ❌ |
248
248
 
249
249
  ✅ takes `?workspace=<id>`; ❌ is panel-wide. Omitting `?workspace` means `default` workspace is used.
250
250
 
251
+ **Scraping it.** Point your scraper at `/api/metrics` with the token from `home-hosted set-token
252
+ --generate` as `Authorization: Bearer …`, because it lives under `/api` like every other route.
253
+ `hh_host_cpu_used_percent` is the machine's own CPU share (0–100) — the figure to alert on.
254
+ `hh_host_load1_per_cpu` beside it is a **count of runnable tasks per core**, not a percentage:
255
+ `1.0` means one core's worth of work waiting, so it is fine on a busy box and not comparable with the
256
+ percentage above. A host gauge appears only once the host has been sampled, so a series that is
257
+ *absent* means "no reading", never "zero": do not let a dashboard fill that in. `hh_server_restarts_total`
258
+ counts the retry attempts spent on a server's **current** crash sequence and drops back to `0` when
259
+ someone starts it, so it is a state, not a counter to `rate()` — `hh_server_crashes_24h` is the one
260
+ that only grows within its window.
261
+
251
262
  `GET /openapi/spec.json` describes all of it, `/openapi/ui` is the browsable version, and every error
252
263
  comes back as one envelope (`{ message, code, detail }`) with a stable `code` a tool can branch on. The
253
264
  document declares its own `securitySchemes` (`bearerAuth`), every documented 2xx carries a schema, and
@@ -449,11 +460,14 @@ Everything binds `127.0.0.1` until you say otherwise.
449
460
 
450
461
  - **A password is required to expose the panel.** Replace the default, then bind to `lan` — in the
451
462
  UI, in the config, or with `--host lan`. The same guard applies in all three places.
452
- - **Sessions** live in memory only; the cookie is `HttpOnly` and `SameSite=Strict`, and the login
453
- route locks out repeated failures per IP — see the `trustProxy` note below for when that is advisory.
463
+ - **Sessions** live in memory only; the cookie is `HttpOnly` and `SameSite=Strict`, and it is an
464
+ **idle** timeout — every request slides both the session and the cookie, so a panel in regular use
465
+ stays signed in and one left alone for the configured lifetime does not. The login route locks out
466
+ repeated failures per IP — see the `trustProxy` note below for when that is advisory.
454
467
  - **API tokens** for scripts and agents: `home-hosted set-token --generate` prints one once, and a
455
468
  request proves itself with `Authorization: Bearer …` — the same access as a signed-in browser,
456
- stored as a SHA-256 hash, revoked with `set-token --clear`.
469
+ stored as a SHA-256 hash, revoked with `set-token --clear`. Changing the panel password does
470
+ **not** revoke a token, so rotate it with `set-token --generate` if one may have leaked.
457
471
  - **Port conflicts** are named — `port 4010 is already in use (pid 4242)` — and can be resolved from
458
472
  a confirmation popover on that banner or card. The process is looked up again at that moment,
459
473
  never taken from the message, and anything the panel supervises is refused, not killed. A server
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",
@@ -2856,6 +2881,39 @@ var init_auth$1 = __esmMin((() => {
2856
2881
  session.expiresAt = now + this.getConfig().sessionTtlMs;
2857
2882
  return session;
2858
2883
  }
2884
+ /**
2885
+ * How far the session deadline may slide past the deadline the browser was last told about before
2886
+ * the cookie is re-sent.
2887
+ *
2888
+ * The cookie is only re-issued when it has fallen this far behind, so a panel in constant use keeps
2889
+ * a live cookie without a `Set-Cookie` on every request — an SSE stream opens one connection and
2890
+ * holds it. Quarter of the idle window, floored at 30 s so a short TTL still refreshes usefully and
2891
+ * capped at an hour so a week-long one costs at most one header an hour.
2892
+ */
2893
+ cookieRefreshThresholdMs() {
2894
+ const ttl = this.getConfig().sessionTtlMs;
2895
+ return Math.max(3e4, Math.min(ttl / 4, 36e5));
2896
+ }
2897
+ /**
2898
+ * The `Max-Age` to send, when this request should slide the *cookie* forward too; otherwise null.
2899
+ *
2900
+ * `validate()` slides `expiresAt` on every request, which makes the lifetime an idle timeout — but
2901
+ * a browser drops a cookie at the `Max-Age` it was issued with, and nothing was re-issuing it. So
2902
+ * the server kept a session a week after login while the browser had thrown its half away: a panel
2903
+ * used every ten seconds was still signed out at the configured lifetime, which is the opposite of
2904
+ * what the login page promises. Marking the deadline actually sent makes the two agree, and only
2905
+ * when it has moved enough to matter.
2906
+ */
2907
+ refreshCookie(session) {
2908
+ const now = Date.now();
2909
+ if (session.expiresAt - session.cookieExpiresAt < this.cookieRefreshThresholdMs()) return null;
2910
+ session.cookieExpiresAt = session.expiresAt;
2911
+ return Math.max(0, session.expiresAt - now);
2912
+ }
2913
+ /** The cookie policy the guard and the login route must agree on. */
2914
+ get cookieSecureMode() {
2915
+ return this.getConfig().cookieSecure;
2916
+ }
2859
2917
  verifyCurrentPassword(password) {
2860
2918
  const record = this.secrets.password;
2861
2919
  if (record === null) return false;
@@ -2910,10 +2968,12 @@ var init_auth$1 = __esmMin((() => {
2910
2968
  if (oldest) this.sessions.delete(oldest.token);
2911
2969
  }
2912
2970
  const token = crypto.randomBytes(32).toString("base64url");
2971
+ const expiresAt = now + config.sessionTtlMs;
2913
2972
  this.sessions.set(token, {
2914
2973
  token,
2915
2974
  passwordRevision: this.secrets.passwordUpdatedAt,
2916
- expiresAt: now + config.sessionTtlMs,
2975
+ expiresAt,
2976
+ cookieExpiresAt: expiresAt,
2917
2977
  lastSeenAt: now,
2918
2978
  ip
2919
2979
  });
@@ -3033,6 +3093,20 @@ function createAuthGuard(deps) {
3033
3093
  code: AUTH_REQUIRED_CODE
3034
3094
  });
3035
3095
  }
3096
+ /**
3097
+ * An active session slides forward, so the browser's copy of the deadline has to slide with
3098
+ * it — otherwise it is dropped at the lifetime measured from *login*, whatever the person
3099
+ * did in between, and the panel signs its owner out mid-use.
3100
+ */
3101
+ if (identity.method === "cookie" && identity.session !== null) {
3102
+ const maxAgeMs = deps.auth.refreshCookie(identity.session);
3103
+ if (maxAgeMs !== null) c.header("Set-Cookie", serializeCookie(SESSION_COOKIE, identity.session.token, {
3104
+ maxAgeMs,
3105
+ secure: secureCookieFor(deps.auth.cookieSecureMode, new URL(c.req.url).protocol),
3106
+ sameSite: "Strict",
3107
+ httpOnly: true
3108
+ }));
3109
+ }
3036
3110
  } else if (deps.auth.isEnabled()) {
3037
3111
  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
3112
  statusCode: 401,
@@ -3054,6 +3128,7 @@ function requestActor(c, auth) {
3054
3128
  }
3055
3129
  var PUBLIC_PATHS, AUTH_REQUIRED_CODE;
3056
3130
  var init_auth = __esmMin((() => {
3131
+ init_cookies();
3057
3132
  init_loopback();
3058
3133
  init_auth$1();
3059
3134
  PUBLIC_PATHS = /* @__PURE__ */ new Set(["/api/auth/login", "/api/auth/session"]);
@@ -3155,10 +3230,7 @@ var init_exposure = __esmMin((() => {
3155
3230
  //#region src/api/auth/$.routes.ts
3156
3231
  /** `Secure` only helps over TLS, and would break plain http on a LAN. */
3157
3232
  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:";
3233
+ return secureCookieFor(deps.auth.cookieSecureMode, new URL(c.req.url).protocol);
3162
3234
  }
3163
3235
  function createAuthRoute(deps) {
3164
3236
  return appFactory.createApp().get("/auth/session", describeRoute({
@@ -3611,6 +3683,10 @@ function createBackupsRoute(deps) {
3611
3683
  describeRoute({
3612
3684
  tags: ["backups"],
3613
3685
  summary: "Plan or apply a restore from a stored or uploaded archive",
3686
+ requestBody: {
3687
+ required: false,
3688
+ content: { "application/json": { schema: resolver(restoreRequestSchema) } }
3689
+ },
3614
3690
  responses: {
3615
3691
  200: {
3616
3692
  description: "The plan",
@@ -3667,19 +3743,24 @@ function createBackupsRoute(deps) {
3667
3743
  uploadedTo = path.join(uploads, `upload-${crypto.randomUUID()}.zip`);
3668
3744
  fs.writeFileSync(uploadedTo, Buffer$1.from(await file.arrayBuffer()), { mode: 384 });
3669
3745
  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
- }
3746
+ const jsonField = (key) => {
3747
+ const raw = typeof body[key] === "string" && body[key].length > 0 ? body[key] : null;
3748
+ if (raw === null) return void 0;
3749
+ try {
3750
+ return JSON.parse(raw);
3751
+ } catch {
3752
+ throw new DetailedError(`\`${key}\` must be a JSON array of item ids`, {
3753
+ statusCode: 400,
3754
+ code: key === "include" ? "INVALID_INCLUDE" : "INVALID_EXCLUDE"
3755
+ });
3756
+ }
3757
+ };
3758
+ const include = jsonField("include");
3759
+ const exclude = jsonField("exclude");
3680
3760
  request = parseOrThrow(restoreRequestSchema, {
3681
3761
  ...typeof body.password === "string" ? { password: body.password } : {},
3682
- ...rawInclude === null ? {} : { include }
3762
+ ...include === void 0 ? {} : { include },
3763
+ ...exclude === void 0 ? {} : { exclude }
3683
3764
  }, "body");
3684
3765
  } else {
3685
3766
  request = parseOrThrow(restoreRequestSchema, await c.req.json().catch(() => ({})), "body");
@@ -3696,7 +3777,8 @@ function createBackupsRoute(deps) {
3696
3777
  const plan = await deps.backups.restore(archive, {
3697
3778
  confirm,
3698
3779
  password: request.password,
3699
- include: request.include
3780
+ include: request.include,
3781
+ exclude: request.exclude
3700
3782
  });
3701
3783
  if (plan.needsPassword) return c.json(plan);
3702
3784
  if (plan.error !== void 0) throw new DetailedError(plan.error, {
@@ -6553,11 +6635,13 @@ function webhookPayload(event, now = Date.now()) {
6553
6635
  *
6554
6636
  * `vars` expands `${ENV}` in the values, so a credential does not have to be written into the
6555
6637
  * config file. A name the panel's environment does not define is left as written, the same rule
6556
- * `expandEnv` follows everywhere else.
6638
+ * `expandEnv` follows everywhere else — and `unexpanded` names those, because a leftover `${…}`
6639
+ * is not a credential.
6557
6640
  */
6558
6641
  function parseHeaders(text, vars = process.env) {
6559
6642
  const headers = {};
6560
6643
  const errors = [];
6644
+ const unexpanded = [];
6561
6645
  for (const line of text.split("\n")) {
6562
6646
  const trimmed = line.trim();
6563
6647
  if (trimmed.length === 0 || trimmed.startsWith("#")) continue;
@@ -6566,11 +6650,15 @@ function parseHeaders(text, vars = process.env) {
6566
6650
  errors.push(`"${trimmed}" is not a "Name: value" header`);
6567
6651
  continue;
6568
6652
  }
6569
- headers[trimmed.slice(0, at).trim()] = expandEnv(trimmed.slice(at + 1).trim(), vars);
6653
+ const name = trimmed.slice(0, at).trim();
6654
+ const value = expandEnv(trimmed.slice(at + 1).trim(), vars);
6655
+ if (value.includes("${")) unexpanded.push(name);
6656
+ headers[name] = value;
6570
6657
  }
6571
6658
  return {
6572
6659
  headers,
6573
- errors
6660
+ errors,
6661
+ unexpanded
6574
6662
  };
6575
6663
  }
6576
6664
  /** Why a target cannot be sent to, or null when it can. Also used to validate a save. */
@@ -6584,8 +6672,9 @@ function targetProblem(target, options = {}) {
6584
6672
  return "the URL is not valid";
6585
6673
  }
6586
6674
  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;
6675
+ const { errors, unexpanded } = parseHeaders(target.headers);
6676
+ 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`] : []];
6677
+ return problems.length > 0 ? problems.join("; ") : null;
6589
6678
  }
6590
6679
  async function sendWebhook(target, event, fetchImpl) {
6591
6680
  const problem = targetProblem(target);
@@ -7517,16 +7606,19 @@ function createMetricsRoute(deps) {
7517
7606
  metric("hh_control_up", "Control plane is serving", ["hh_control_up 1"]);
7518
7607
  metric("hh_servers_total", "Configured servers", [`hh_servers_total ${servers.length}`]);
7519
7608
  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}`));
7609
+ 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
7610
  metric("hh_server_crashes_24h", "Crashes in the last 24 hours", servers.map((server) => `hh_server_crashes_24h{${labels(server)}} ${server.history.crashes}`));
7522
7611
  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
7612
  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
7613
  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
7614
  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)}`]);
7615
+ if (host.sampledAt !== null) {
7616
+ 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)}`));
7617
+ 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)}`]);
7618
+ metric("hh_host_memory_used_percent", "Memory usage percent", [`hh_host_memory_used_percent ${host.memoryUsedPercent.toFixed(2)}`]);
7619
+ metric("hh_host_swap_used_percent", "Swap usage percent", [`hh_host_swap_used_percent ${host.swapUsedPercent.toFixed(2)}`]);
7620
+ 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)}`]);
7621
+ }
7530
7622
  return c.text(`${lines.join("\n")}\n`, 200, { "Content-Type": "text/plain; version=0.0.4; charset=utf-8" });
7531
7623
  });
7532
7624
  }
@@ -7693,10 +7785,13 @@ function createNotificationsRoute(deps) {
7693
7785
  400: ERROR_RESPONSES[400]
7694
7786
  }
7695
7787
  }), 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"));
7788
+ const runtime = runtimeFor(c.req.valid("query").workspace);
7789
+ const id = c.req.valid("param").id;
7790
+ const kind = runtime.notifications.destinations().find((destination) => destination.id === id)?.kind;
7791
+ const result = await runtime.notifications.sendTest(id, c.req.valid("json"));
7697
7792
  if (!result.ok) throw new DetailedError(result.error ?? "the test message failed", {
7698
7793
  statusCode: 400,
7699
- code: "TELEGRAM_SEND_FAILED"
7794
+ code: kind === "webhook" ? "WEBHOOK_SEND_FAILED" : "TELEGRAM_SEND_FAILED"
7700
7795
  });
7701
7796
  return c.json(result);
7702
7797
  }).post("/notifications/test-webhook", describeRoute({