home-hosted 0.9.7 → 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/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
@@ -738,7 +751,7 @@ function duplicateWebhookIds(targets) {
738
751
  }
739
752
  return [...duplicates];
740
753
  }
741
- var bindSchema, workspaceIdSchema, workspaceSchema, workspaceCreateSchema, workspaceRenameSchema, portSchema, onPortConflictSchema, onPortConflictDefaultSchema, restartSchema, httpCheckSchema, resourcesSchema, healthSchema, stopSchema, bootstrapSchema, bootstrapOrNullSchema, backupHookSchema, backupHookOrNullSchema, labelOrNullSchema, logBufferLinesSchema, serverSchema, authSchema, notificationPolicyShape, notificationDefaultsSchema, notificationDefaultsViewSchema, useOwnSettingsSchema, telegramDestinationSchema, webhookTargetSchema, notificationTargetSchema, destinationListSchema, notificationsSchema, logsSchema, tlsSchema, hostSchema, ddnsRecordTypeSchema, ddnsAccountSchema, ddnsDomainSchema, ddnsIpv4Schema, ddnsIpv6Schema, ddnsConfigSchema, ddnsRecordStateSchema, ddnsRecordViewSchema, ddnsStatusSchema, ddnsProviderFieldSchema, ddnsProviderInfoSchema, ddnsViewSchema, ddnsCredentialsSchema, backupScheduleSchema, backupsSchema, controlSchema, defaultsSchema, restartPatchSchema, httpCheckPatchSchema, resourcesPatchSchema, healthPatchSchema, stopPatchSchema, authPatchSchema, notificationPolicyPatchShape, destinationPatchSchema, notificationsPatchSchema, hostPatchSchema, backupSchedulePatchSchema, backupsPatchSchema, logsPatchSchema, tlsPatchSchema, controlPatchSchema, defaultsPatchSchema, editableFields, serverPatchSchema, serverCreateSchema, nannySpecSchema, nannyExitSchema, nannyStateSchema, entryStateSchema, settingsPatchSchema, workspaceSettingsPatchSchema, authStatusSchema, tlsStatusSchema, proxyEngineSchema, proxyTargetSchema, proxyTlsModeSchema, proxyRouteSchema, proxyCertificateSchema, proxyCertificateStateSchema, proxyDns01Schema, proxyConfigSchema, proxyEngineSourceSchema, proxyEngineStatusSchema, proxyEngineInfoSchema, proxyRouteStatusSchema, proxyRouteViewSchema, proxyRunStateSchema, proxyStatusSchema, proxyCertificateViewSchema, proxyDnsAccountViewSchema, proxyViewSchema, proxyRoutePatchSchema, proxyPatchSchema, proxyCertificateUploadSchema, proxyEngineInstallSchema, notificationPolicyStatusShape, destinationStatusSchema, telegramChatsSchema, notificationViewSchema, sessionViewSchema, loginSchema, passwordValueSchema, passwordSchema, serverStatusSchema, healthStateSchema, portStateSchema, logStreamSchema, logLineSchema, historyActorSchema, historyEventSchema, serverHistorySchema, processResourcesSchema, hostDiskSchema, hostViewSchema, backupFileSchema, backupEntrySchema, backupsViewSchema, restoreItemSchema, restoreSkipSchema, restorePlanSchema, backupCreateSchema, restoreRequestSchema, serverViewSchema, healthResponseSchema, controlViewSchema, uiMetaSchema, uiStatusSchema, serverOrphanSchema, workspaceViewSchema, appStateSchema, logQuerySchema, actionResultSchema, deliveryResultSchema, passwordSetResponseSchema, tlsReviewResponseSchema, okResponseSchema, backupFilesResponseSchema, uiInstallResponseSchema, backupCreatedResponseSchema, logLinesResponseSchema, freePortResultSchema, logHistoryQuerySchema, logFileInfoSchema, logServerViewSchema, logServersViewSchema, notificationActionSchema, destinationIdParamSchema, destinationTestSchema, telegramTokenSchema, apiErrorSchema, tlsUploadSchema, settingsViewSchema, settingsSavedSchema, workspaceSettingsViewSchema, workspaceSettingsSavedSchema;
754
+ var bindSchema, workspaceIdSchema, workspaceSchema, workspaceCreateSchema, workspaceRenameSchema, portSchema, onPortConflictSchema, onPortConflictDefaultSchema, restartSchema, httpCheckSchema, resourcesSchema, healthSchema, stopSchema, bootstrapSchema, bootstrapOrNullSchema, backupHookSchema, backupHookOrNullSchema, labelOrNullSchema, logBufferLinesSchema, serverSchema, authSchema, notificationPolicyShape, notificationDefaultsSchema, notificationDefaultsViewSchema, useOwnSettingsSchema, telegramDestinationSchema, webhookTargetSchema, notificationTargetSchema, destinationListSchema, notificationsSchema, logsSchema, tlsSchema, hostSchema, ddnsRecordTypeSchema, ddnsAccountSchema, ddnsDomainSchema, ddnsIpv4Schema, ddnsIpv6Schema, ddnsConfigSchema, ddnsRecordStateSchema, ddnsRecordViewSchema, ddnsStatusSchema, ddnsProviderFieldSchema, ddnsProviderInfoSchema, ddnsViewSchema, ddnsCredentialsSchema, backupScopeSchema, backupScheduleSchema, backupsSchema, controlSchema, defaultsSchema, restartPatchSchema, httpCheckPatchSchema, resourcesPatchSchema, healthPatchSchema, stopPatchSchema, authPatchSchema, notificationPolicyPatchShape, destinationPatchSchema, notificationsPatchSchema, hostPatchSchema, backupSchedulePatchSchema, backupsPatchSchema, logsPatchSchema, tlsPatchSchema, controlPatchSchema, defaultsPatchSchema, editableFields, serverPatchSchema, serverCreateSchema, nannySpecSchema, nannyExitSchema, nannyStateSchema, entryStateSchema, settingsPatchSchema, workspaceSettingsPatchSchema, authStatusSchema, tlsStatusSchema, proxyEngineSchema, proxyTargetSchema, proxyTlsModeSchema, proxyRouteSchema, proxyCertificateSchema, proxyCertificateStateSchema, proxyDns01Schema, proxyConfigSchema, proxyEngineSourceSchema, proxyEngineStatusSchema, proxyEngineInfoSchema, proxyRouteStatusSchema, proxyRouteViewSchema, proxyRunStateSchema, proxyStatusSchema, proxyCertificateViewSchema, proxyDnsAccountViewSchema, proxyViewSchema, proxyRoutePatchSchema, proxyPatchSchema, proxyCertificateUploadSchema, proxyEngineInstallSchema, notificationPolicyStatusShape, destinationStatusSchema, telegramChatsSchema, notificationViewSchema, sessionViewSchema, loginSchema, passwordValueSchema, passwordSchema, serverStatusSchema, healthStateSchema, portStateSchema, logStreamSchema, logLineSchema, historyActorSchema, historyEventSchema, serverHistorySchema, processResourcesSchema, hostDiskSchema, hostViewSchema, backupFileSchema, backupEntrySchema, backupScheduleViewSchema, backupsViewSchema, restoreItemSchema, restoreSkipSchema, restorePlanSchema, backupCreateSchema, restoreRequestSchema, serverViewSchema, healthResponseSchema, controlViewSchema, uiMetaSchema, uiStatusSchema, serverOrphanSchema, workspaceViewSchema, appStateSchema, logQuerySchema, actionResultSchema, deliveryResultSchema, passwordSetResponseSchema, tlsReviewResponseSchema, okResponseSchema, backupFilesResponseSchema, uiInstallResponseSchema, backupCreatedResponseSchema, logLinesResponseSchema, freePortResultSchema, logHistoryQuerySchema, logFileInfoSchema, logServerViewSchema, logServersViewSchema, notificationActionSchema, destinationIdParamSchema, destinationTestSchema, telegramTokenSchema, apiErrorSchema, tlsUploadSchema, settingsViewSchema, settingsSavedSchema, workspaceSettingsViewSchema, workspaceSettingsSavedSchema;
742
755
  var init_contracts = __esmMin((() => {
743
756
  bindSchema = type("\"local\" | \"lan\" | /^\\d{1,3}(?:\\.\\d{1,3}){3}$/");
744
757
  workspaceIdSchema = type("/^[a-z0-9][a-z0-9_-]*$/");
@@ -1064,11 +1077,21 @@ maxRssBytes: "number.integer >= 0 = 0" }).onUndeclaredKey("reject");
1064
1077
  accounts: ddnsAccountSchema.array().optional(),
1065
1078
  domains: ddnsDomainSchema.array().optional()
1066
1079
  }).onUndeclaredKey("reject");
1080
+ backupScopeSchema = type({
1081
+ mode: "\"only\" | \"except\"",
1082
+ ids: type("string >= 1").array().atLeastLength(1)
1083
+ }).onUndeclaredKey("reject");
1067
1084
  backupScheduleSchema = type({
1068
1085
  /** 0 turns the schedule off; otherwise the gap between automatic archives. */
1069
1086
  intervalMs: "number.integer >= 0 = 0",
1070
1087
  /** How many automatic archives to keep. Manual ones are never pruned by it. */
1071
- keep: "number.integer >= 1 = 7"
1088
+ keep: "number.integer >= 1 = 7",
1089
+ /**
1090
+ * Absent means the whole default scope — every workspace and `includePaths`. Deliberately not
1091
+ * defaulted to an explicit value: a reader cannot tell an untouched file from one that chose
1092
+ * "everything", and a default here would rewrite every existing schedule on its first save.
1093
+ */
1094
+ scope: backupScopeSchema.optional()
1072
1095
  }).onUndeclaredKey("reject");
1073
1096
  backupsSchema = type({
1074
1097
  enabled: "boolean = true",
@@ -1191,7 +1214,12 @@ maxRssBytes: "number.integer >= 0 = 0" }).onUndeclaredKey("reject");
1191
1214
  }).onUndeclaredKey("reject");
1192
1215
  backupSchedulePatchSchema = type({
1193
1216
  intervalMs: "number.integer >= 0?",
1194
- keep: "number.integer >= 1?"
1217
+ keep: "number.integer >= 1?",
1218
+ /**
1219
+ * No defaults, like every patch: `null` clears it back to the full default scope, which is the
1220
+ * only way to spell "forget the choice I made" — an omitted key means "leave it as it is".
1221
+ */
1222
+ scope: backupScopeSchema.or(type("null")).optional()
1195
1223
  }).onUndeclaredKey("reject");
1196
1224
  backupsPatchSchema = type({
1197
1225
  enabled: "boolean?",
@@ -1642,17 +1670,25 @@ maxRssBytes: "number.integer >= 0 = 0" }).onUndeclaredKey("reject");
1642
1670
  usedPercent: "number"
1643
1671
  });
1644
1672
  hostViewSchema = type({
1645
- enabled: "boolean",
1646
- cpus: "number",
1647
- loadAvg: type("number[]"),
1648
- uptimeMs: "number",
1649
- memoryUsedPercent: "number",
1650
- swapUsedPercent: "number",
1651
- tempCelsius: "number | null",
1652
- disks: hostDiskSchema.array(),
1673
+ "enabled": "boolean",
1674
+ "cpus": "number",
1675
+ "loadAvg": type("number[]"),
1676
+ /**
1677
+ * Share of this machine's CPU capacity in use over the last sampling interval, 0–100.
1678
+ *
1679
+ * Optional: an older panel sends no such field, and a required one rejects the whole frame and
1680
+ * blanks the UI that panel is serving. `null` on the first sample, which has no window to
1681
+ * measure yet — a number there would be invented.
1682
+ */
1683
+ "cpuUsedPercent?": "number | null",
1684
+ "uptimeMs": "number",
1685
+ "memoryUsedPercent": "number",
1686
+ "swapUsedPercent": "number",
1687
+ "tempCelsius": "number | null",
1688
+ "disks": hostDiskSchema.array(),
1653
1689
  /** Human readable threshold breaches, for the banner and notifications. */
1654
- alerts: type("string[]"),
1655
- sampledAt: "number | null"
1690
+ "alerts": type("string[]"),
1691
+ "sampledAt": "number | null"
1656
1692
  });
1657
1693
  backupFileSchema = type({
1658
1694
  name: "string",
@@ -1698,6 +1734,7 @@ maxRssBytes: "number.integer >= 0 = 0" }).onUndeclaredKey("reject");
1698
1734
  "ignoreGenerated?": "boolean"
1699
1735
  }).array()
1700
1736
  });
1737
+ backupScheduleViewSchema = backupScheduleSchema.onDeepUndeclaredKey("ignore");
1701
1738
  backupsViewSchema = type({
1702
1739
  "enabled": "boolean",
1703
1740
  "dir": "string",
@@ -1709,7 +1746,7 @@ maxRssBytes: "number.integer >= 0 = 0" }).onUndeclaredKey("reject");
1709
1746
  * and a required field would blank the settings page for that panel. The page reads it as
1710
1747
  * "off, keep 7" when absent — the schema defaults — so nothing changes for it.
1711
1748
  */
1712
- "schedule?": backupScheduleSchema,
1749
+ "schedule?": backupScheduleViewSchema,
1713
1750
  /** When the last automatic archive was written; null until one has run. Optional for the same reason. */
1714
1751
  "lastAutomaticAt?": "number | null",
1715
1752
  /**
@@ -1819,13 +1856,33 @@ maxRssBytes: "number.integer >= 0 = 0" }).onUndeclaredKey("reject");
1819
1856
  /** Optional: encrypts the archive. Never stored. */
1820
1857
  password: passwordValueSchema.optional(),
1821
1858
  /** Leaf ids to capture (`global:settings`, `workspace:<id>:servers`, `data:<path>`, ...); omitted means everything. */
1822
- include: type("string[] >= 1").optional()
1859
+ include: type("string[] >= 1").optional(),
1860
+ /**
1861
+ * Leaf ids to leave out, applied after `include` — the CLI's `--exclude`, and the one thing to
1862
+ * name when the archive should carry everything but the credentials.
1863
+ *
1864
+ * Empty is refused for the same reason `include` refuses it: an empty list reads as "nothing" to
1865
+ * a person and as "everything" to a reader, so it must not be sent at all.
1866
+ */
1867
+ exclude: type("string[] >= 1").optional()
1823
1868
  }).onUndeclaredKey("reject");
1824
1869
  restoreRequestSchema = type({
1825
1870
  name: "string?",
1826
1871
  password: passwordValueSchema.optional(),
1827
1872
  /** Item ids to restore; omitted means every restorable item. */
1828
- 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()
1829
1886
  }).onUndeclaredKey("reject");
1830
1887
  serverViewSchema = type({
1831
1888
  "id": "string",
@@ -2824,6 +2881,39 @@ var init_auth$1 = __esmMin((() => {
2824
2881
  session.expiresAt = now + this.getConfig().sessionTtlMs;
2825
2882
  return session;
2826
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
+ }
2827
2917
  verifyCurrentPassword(password) {
2828
2918
  const record = this.secrets.password;
2829
2919
  if (record === null) return false;
@@ -2878,10 +2968,12 @@ var init_auth$1 = __esmMin((() => {
2878
2968
  if (oldest) this.sessions.delete(oldest.token);
2879
2969
  }
2880
2970
  const token = crypto.randomBytes(32).toString("base64url");
2971
+ const expiresAt = now + config.sessionTtlMs;
2881
2972
  this.sessions.set(token, {
2882
2973
  token,
2883
2974
  passwordRevision: this.secrets.passwordUpdatedAt,
2884
- expiresAt: now + config.sessionTtlMs,
2975
+ expiresAt,
2976
+ cookieExpiresAt: expiresAt,
2885
2977
  lastSeenAt: now,
2886
2978
  ip
2887
2979
  });
@@ -3001,6 +3093,20 @@ function createAuthGuard(deps) {
3001
3093
  code: AUTH_REQUIRED_CODE
3002
3094
  });
3003
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
+ }
3004
3110
  } else if (deps.auth.isEnabled()) {
3005
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", {
3006
3112
  statusCode: 401,
@@ -3022,6 +3128,7 @@ function requestActor(c, auth) {
3022
3128
  }
3023
3129
  var PUBLIC_PATHS, AUTH_REQUIRED_CODE;
3024
3130
  var init_auth = __esmMin((() => {
3131
+ init_cookies();
3025
3132
  init_loopback();
3026
3133
  init_auth$1();
3027
3134
  PUBLIC_PATHS = /* @__PURE__ */ new Set(["/api/auth/login", "/api/auth/session"]);
@@ -3123,10 +3230,7 @@ var init_exposure = __esmMin((() => {
3123
3230
  //#region src/api/auth/$.routes.ts
3124
3231
  /** `Secure` only helps over TLS, and would break plain http on a LAN. */
3125
3232
  function secureCookie(c, deps) {
3126
- const mode = deps.panel.settings.control.auth.cookieSecure;
3127
- if (mode === "always") return true;
3128
- if (mode === "never") return false;
3129
- return new URL(c.req.url).protocol === "https:";
3233
+ return secureCookieFor(deps.auth.cookieSecureMode, new URL(c.req.url).protocol);
3130
3234
  }
3131
3235
  function createAuthRoute(deps) {
3132
3236
  return appFactory.createApp().get("/auth/session", describeRoute({
@@ -3528,7 +3632,8 @@ function createBackupsRoute(deps) {
3528
3632
  const body = c.req.valid("json");
3529
3633
  const result = await deps.backups.create({
3530
3634
  password: body.password,
3531
- include: body.include
3635
+ include: body.include,
3636
+ exclude: body.exclude
3532
3637
  });
3533
3638
  if (!result.ok) throw backupFailed(result.error);
3534
3639
  return c.json({
@@ -3578,6 +3683,10 @@ function createBackupsRoute(deps) {
3578
3683
  describeRoute({
3579
3684
  tags: ["backups"],
3580
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
+ },
3581
3690
  responses: {
3582
3691
  200: {
3583
3692
  description: "The plan",
@@ -3634,19 +3743,24 @@ function createBackupsRoute(deps) {
3634
3743
  uploadedTo = path.join(uploads, `upload-${crypto.randomUUID()}.zip`);
3635
3744
  fs.writeFileSync(uploadedTo, Buffer$1.from(await file.arrayBuffer()), { mode: 384 });
3636
3745
  archive = uploadedTo;
3637
- const rawInclude = typeof body.include === "string" && body.include.length > 0 ? body.include : null;
3638
- let include;
3639
- if (rawInclude !== null) try {
3640
- include = JSON.parse(rawInclude);
3641
- } catch {
3642
- throw new DetailedError("`include` must be a JSON array of item ids", {
3643
- statusCode: 400,
3644
- code: "INVALID_INCLUDE"
3645
- });
3646
- }
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");
3647
3760
  request = parseOrThrow(restoreRequestSchema, {
3648
3761
  ...typeof body.password === "string" ? { password: body.password } : {},
3649
- ...rawInclude === null ? {} : { include }
3762
+ ...include === void 0 ? {} : { include },
3763
+ ...exclude === void 0 ? {} : { exclude }
3650
3764
  }, "body");
3651
3765
  } else {
3652
3766
  request = parseOrThrow(restoreRequestSchema, await c.req.json().catch(() => ({})), "body");
@@ -3663,7 +3777,8 @@ function createBackupsRoute(deps) {
3663
3777
  const plan = await deps.backups.restore(archive, {
3664
3778
  confirm,
3665
3779
  password: request.password,
3666
- include: request.include
3780
+ include: request.include,
3781
+ exclude: request.exclude
3667
3782
  });
3668
3783
  if (plan.needsPassword) return c.json(plan);
3669
3784
  if (plan.error !== void 0) throw new DetailedError(plan.error, {
@@ -4026,6 +4141,55 @@ var init_workspace = __esmMin((() => {
4026
4141
  workspaceQuerySchema = type({ "workspace?": "string" });
4027
4142
  }));
4028
4143
  //#endregion
4144
+ //#region src/shared/backup-scope.ts
4145
+ /**
4146
+ * What a configured automatic scope asks a `create` for.
4147
+ *
4148
+ * `only` is `--include` and `except` is `--all --exclude`, because a schedule and a person typing
4149
+ * flags have to mean the same thing. An absent scope is the full default the schedule took before
4150
+ * it could be configured, which is what keeps an existing config exactly as it was.
4151
+ */
4152
+ function scopeSelection(scope) {
4153
+ if (scope === void 0) return {};
4154
+ return scope.mode === "only" ? { include: [...scope.ids] } : { exclude: [...scope.ids] };
4155
+ }
4156
+ /**
4157
+ * What a selection asks for, from `include` and `exclude` together.
4158
+ *
4159
+ * One implementation for `create`, `restore`, the control channel's plan and both UIs: a second
4160
+ * copy of "does this id count as selected" is how an `--exclude` that works on backup silently does
4161
+ * nothing on restore, or how a page ticks a row the panel will not capture.
4162
+ *
4163
+ * `include` omitted means everything; `exclude` is applied after it, and an id under an excluded
4164
+ * entry is excluded too.
4165
+ */
4166
+ function selectionOf(options) {
4167
+ const wanted = options.include === void 0 ? null : new Set(options.include);
4168
+ const unwanted = new Set(options.exclude ?? []);
4169
+ const isExcluded = (id) => unwanted.has(id) || [...unwanted].some((entry) => id.startsWith(`${entry}:`));
4170
+ const selects = ((id) => {
4171
+ if (isExcluded(id)) return false;
4172
+ return wanted === null || wanted.has(id) || [...wanted].some((entry) => id.startsWith(`${entry}:`));
4173
+ });
4174
+ selects.isExcluded = isExcluded;
4175
+ return selects;
4176
+ }
4177
+ /**
4178
+ * Which of `ids` name nothing the panel can capture.
4179
+ *
4180
+ * The rule `backup create --include` already applies: an id names something when it is an entry or
4181
+ * leaf id, or a prefix of one (`workspace:default` covers its leaves). A typo matters more on a
4182
+ * schedule than anywhere else — nobody is watching — and it cuts both ways: an unknown `only` id
4183
+ * silently narrows the archive, an unknown `except` id silently widens it back over what the
4184
+ * person meant to leave out.
4185
+ */
4186
+ function unknownBackupIds(ids, entries) {
4187
+ const available = entries.flatMap((entry) => [entry.id, ...(entry.items ?? []).map((item) => item.id)]);
4188
+ const known = (id) => available.some((candidate) => candidate === id || candidate.startsWith(`${id}:`));
4189
+ return ids.filter((id) => !known(id));
4190
+ }
4191
+ var init_backup_scope = __esmMin((() => {}));
4192
+ //#endregion
4029
4193
  //#region src/api/control.ts
4030
4194
  /**
4031
4195
  * The local control channel used by `home-hosted down` and `home-hosted start|stop`.
@@ -4134,10 +4298,18 @@ function createControlRoute(deps) {
4134
4298
  assertLocalCall(c, "create a backup");
4135
4299
  const password = c.req.query("password");
4136
4300
  const include = c.req.query("include")?.split(",").filter((part) => part.length > 0);
4301
+ const exclude = c.req.query("exclude")?.split(",").filter((part) => part.length > 0);
4137
4302
  if (c.req.query("confirm") !== "true") {
4138
4303
  const view = buildBackupsView(deps.backups);
4139
- const wanted = include === void 0 ? null : new Set(include);
4140
- const entries = view.entries.filter((entry) => wanted === null || wanted.has(entry.id) || entry.workspaceId !== void 0 && wanted.has(`workspace:${entry.workspaceId}`));
4304
+ const selects = selectionOf({
4305
+ include,
4306
+ exclude
4307
+ });
4308
+ const namesLeafOf = (id) => include !== void 0 && include.some((entry) => entry.startsWith(`${id}:`));
4309
+ const entries = view.entries.filter((entry) => selects(entry.id) || namesLeafOf(entry.id)).map((entry) => ({
4310
+ ...entry,
4311
+ items: entry.items.filter((item) => selects(item.id))
4312
+ }));
4141
4313
  return c.json({
4142
4314
  apply: false,
4143
4315
  entries,
@@ -4146,7 +4318,8 @@ function createControlRoute(deps) {
4146
4318
  }
4147
4319
  const result = await deps.backups.create({
4148
4320
  password,
4149
- include
4321
+ include,
4322
+ exclude
4150
4323
  });
4151
4324
  if (!result.ok) throw new DetailedError(result.error ?? "the backup failed", {
4152
4325
  statusCode: 400,
@@ -4182,10 +4355,12 @@ function createControlRoute(deps) {
4182
4355
  code: "BACKUP_NOT_FOUND"
4183
4356
  });
4184
4357
  const include = c.req.query("include")?.split(",").filter((part) => part.length > 0);
4358
+ const exclude = c.req.query("exclude")?.split(",").filter((part) => part.length > 0);
4185
4359
  return c.json(await deps.backups.restore(archive, {
4186
4360
  confirm,
4187
4361
  password: c.req.query("password"),
4188
- include
4362
+ include,
4363
+ exclude
4189
4364
  }));
4190
4365
  });
4191
4366
  }
@@ -4200,6 +4375,7 @@ var init_control = __esmMin((() => {
4200
4375
  init_workspace();
4201
4376
  init_loopback();
4202
4377
  init_state$1();
4378
+ init_backup_scope();
4203
4379
  init_contracts();
4204
4380
  }));
4205
4381
  //#endregion
@@ -6459,11 +6635,13 @@ function webhookPayload(event, now = Date.now()) {
6459
6635
  *
6460
6636
  * `vars` expands `${ENV}` in the values, so a credential does not have to be written into the
6461
6637
  * config file. A name the panel's environment does not define is left as written, the same rule
6462
- * `expandEnv` follows everywhere else.
6638
+ * `expandEnv` follows everywhere else — and `unexpanded` names those, because a leftover `${…}`
6639
+ * is not a credential.
6463
6640
  */
6464
6641
  function parseHeaders(text, vars = process.env) {
6465
6642
  const headers = {};
6466
6643
  const errors = [];
6644
+ const unexpanded = [];
6467
6645
  for (const line of text.split("\n")) {
6468
6646
  const trimmed = line.trim();
6469
6647
  if (trimmed.length === 0 || trimmed.startsWith("#")) continue;
@@ -6472,11 +6650,15 @@ function parseHeaders(text, vars = process.env) {
6472
6650
  errors.push(`"${trimmed}" is not a "Name: value" header`);
6473
6651
  continue;
6474
6652
  }
6475
- 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;
6476
6657
  }
6477
6658
  return {
6478
6659
  headers,
6479
- errors
6660
+ errors,
6661
+ unexpanded
6480
6662
  };
6481
6663
  }
6482
6664
  /** Why a target cannot be sent to, or null when it can. Also used to validate a save. */
@@ -6490,8 +6672,9 @@ function targetProblem(target, options = {}) {
6490
6672
  return "the URL is not valid";
6491
6673
  }
6492
6674
  if (parsed.protocol !== "http:" && parsed.protocol !== "https:") return `the URL must be http or https, not ${parsed.protocol}`;
6493
- const { errors } = parseHeaders(target.headers);
6494
- 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;
6495
6678
  }
6496
6679
  async function sendWebhook(target, event, fetchImpl) {
6497
6680
  const problem = targetProblem(target);
@@ -7423,16 +7606,19 @@ function createMetricsRoute(deps) {
7423
7606
  metric("hh_control_up", "Control plane is serving", ["hh_control_up 1"]);
7424
7607
  metric("hh_servers_total", "Configured servers", [`hh_servers_total ${servers.length}`]);
7425
7608
  metric("hh_server_up", "Server process is running", servers.map((server) => `hh_server_up{${labels(server)}} ${server.status === "running" ? 1 : 0}`));
7426
- 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}`));
7427
7610
  metric("hh_server_crashes_24h", "Crashes in the last 24 hours", servers.map((server) => `hh_server_crashes_24h{${labels(server)}} ${server.history.crashes}`));
7428
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)}`));
7429
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}`));
7430
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}`));
7431
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}`));
7432
- 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)}`));
7433
- metric("hh_host_memory_used_percent", "Memory usage percent", [`hh_host_memory_used_percent ${host.memoryUsedPercent.toFixed(2)}`]);
7434
- metric("hh_host_swap_used_percent", "Swap usage percent", [`hh_host_swap_used_percent ${host.swapUsedPercent.toFixed(2)}`]);
7435
- 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
+ }
7436
7622
  return c.text(`${lines.join("\n")}\n`, 200, { "Content-Type": "text/plain; version=0.0.4; charset=utf-8" });
7437
7623
  });
7438
7624
  }
@@ -7599,10 +7785,13 @@ function createNotificationsRoute(deps) {
7599
7785
  400: ERROR_RESPONSES[400]
7600
7786
  }
7601
7787
  }), validate("query", workspaceQuerySchema), validate("param", destinationIdParamSchema), validate("json", notificationActionSchema), async (c) => {
7602
- 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"));
7603
7792
  if (!result.ok) throw new DetailedError(result.error ?? "the test message failed", {
7604
7793
  statusCode: 400,
7605
- code: "TELEGRAM_SEND_FAILED"
7794
+ code: kind === "webhook" ? "WEBHOOK_SEND_FAILED" : "TELEGRAM_SEND_FAILED"
7606
7795
  });
7607
7796
  return c.json(result);
7608
7797
  }).post("/notifications/test-webhook", describeRoute({
@@ -7809,6 +7998,48 @@ function collectTree(rootPid, children) {
7809
7998
  return pids;
7810
7999
  }
7811
8000
  /**
8001
+ * CPU time a tree used over one interval, from per-pid cumulative counters.
8002
+ *
8003
+ * Pure, and separated from the scan because this is where both CPU bugs lived — and a scan of the
8004
+ * live process table cannot pin arithmetic that depends on a child appearing or vanishing between
8005
+ * two reads.
8006
+ *
8007
+ * `previous` is the **whole process table** of the prior scan, not just this tree: that is what
8008
+ * lets a process which joins the tree later be charged only its interval, and what the caller
8009
+ * guarantees.
8010
+ *
8011
+ * Three rules make the answer a real interval:
8012
+ *
8013
+ * - A pid in both maps contributes the difference. `next >= previous` is required: a recycled pid
8014
+ * reports less than the process that used to hold it, and that is not a delta.
8015
+ * - A pid only in `next` was **born inside the window**, so its whole counter accrued in it.
8016
+ * - A pid only in `previous` **exited inside the window**; its time is already accounted for by the
8017
+ * samples where it was alive, and it contributes nothing. The old code summed the tree on both
8018
+ * sides, so an exit made the total *drop*, the delta went negative and the reading was discarded
8019
+ * — the gap. Summing only pids present in `next` is what removes it.
8020
+ *
8021
+ * `null` when the map has nothing usable, so a caller reports "unknown" instead of `0`.
8022
+ */
8023
+ function treeCpuUsedSeconds(previous, next, treePids) {
8024
+ let used = 0;
8025
+ let sawAny = false;
8026
+ for (const pid of treePids) {
8027
+ const current = next.get(pid);
8028
+ if (current === void 0) continue;
8029
+ const before = previous.get(pid);
8030
+ if (before === void 0) {
8031
+ used += current;
8032
+ sawAny = true;
8033
+ continue;
8034
+ }
8035
+ if (current >= before) {
8036
+ used += current - before;
8037
+ sawAny = true;
8038
+ }
8039
+ }
8040
+ return sawAny ? used : null;
8041
+ }
8042
+ /**
7812
8043
  * The roots and every descendant of theirs, from one scan of the process table.
7813
8044
  *
7814
8045
  * Ownership has to mean the *tree*: a persistent entry runs under a nanny, and a
@@ -7873,7 +8104,30 @@ var init_proc = __esmMin((() => {
7873
8104
  execFileAsync$4 = promisify(execFile);
7874
8105
  clockTicks = null;
7875
8106
  ProcessSampler = class {
7876
- previous = /* @__PURE__ */ new Map();
8107
+ /**
8108
+ * Cumulative CPU seconds per pid, from the **whole process table** of the last scan.
8109
+ *
8110
+ * A tree is not a fixed set of processes: a wrapper spawns and reaps children continuously, so
8111
+ * "the sum over whatever is in the tree now" is not comparable with the previous sum. Measuring
8112
+ * that rule against a wrapper respawning a 1.5 s worker, **two samples in every three were
8113
+ * discarded**: the child's exit made the sum drop, the delta went negative, and the reading was
8114
+ * thrown away — the gaps a person sees on a live server.
8115
+ *
8116
+ * Baselining every pid the scan saw, rather than only the tree's, is what makes each delta a
8117
+ * real interval. A process that was already running has a previous counter even if it only
8118
+ * joined this tree afterwards, so it cannot be charged its whole lifetime; and a pid absent from
8119
+ * the previous scan was born inside the window, so its counter really did accrue in it.
8120
+ */
8121
+ previousTable = null;
8122
+ /**
8123
+ * Roots whose next sample must not be differenced, stamped with when they were forgotten.
8124
+ *
8125
+ * `forget` is called when an entry stops, exits or is restarted: the pid is gone, so the reading
8126
+ * after it must be `null` rather than a delta against a previous life. The baseline is one table
8127
+ * for the whole scan, so this is the per-root suppression. Pruned at each scan, which bounds it
8128
+ * to the restarts that happened since the last one.
8129
+ */
8130
+ forgotten = /* @__PURE__ */ new Map();
7877
8131
  async sample(rootPid, now = Date.now()) {
7878
8132
  return (await this.sampleMany([rootPid], now)).get(rootPid) ?? null;
7879
8133
  }
@@ -7893,41 +8147,31 @@ var init_proc = __esmMin((() => {
7893
8147
  siblings.push(row.pid);
7894
8148
  children.set(row.ppid, siblings);
7895
8149
  }
8150
+ const before = this.previousTable;
8151
+ const elapsedSeconds = before === null ? 0 : (now - before.at) / 1e3;
8152
+ const ticks = process.platform === "linux" ? await getClockTicks() : 1;
8153
+ const tableCpuSeconds = /* @__PURE__ */ new Map();
8154
+ for (const row of rows) if (row.cpuSeconds !== void 0) tableCpuSeconds.set(row.pid, row.cpuSeconds / ticks);
7896
8155
  for (const rootPid of rootPids) {
7897
8156
  if (!byPid.has(rootPid)) {
7898
- this.previous.delete(rootPid);
7899
8157
  results.set(rootPid, null);
7900
8158
  continue;
7901
8159
  }
8160
+ const wasForgotten = this.forgotten.delete(rootPid);
7902
8161
  const pids = collectTree(rootPid, children);
7903
8162
  let rssKb = 0;
7904
- let cpuSeconds = 0;
7905
8163
  let percentAverage = null;
8164
+ const treeSeconds = /* @__PURE__ */ new Map();
7906
8165
  for (const pid of pids) {
7907
8166
  const row = byPid.get(pid);
7908
8167
  if (!row) continue;
7909
8168
  rssKb += row.rssKb;
7910
- if (row.cpuSeconds === void 0) cpuSeconds = null;
7911
- else if (cpuSeconds !== null) cpuSeconds += row.cpuSeconds;
7912
8169
  if (row.cpuPercent !== void 0) percentAverage = (percentAverage ?? 0) + row.cpuPercent;
8170
+ if (row.cpuSeconds !== void 0) treeSeconds.set(pid, row.cpuSeconds / ticks);
7913
8171
  }
8172
+ const usedSeconds = before === null ? null : treeCpuUsedSeconds(before.cpuSeconds, treeSeconds, pids);
7914
8173
  let cpuPercent = percentAverage;
7915
- if (cpuPercent === null && cpuSeconds !== null) {
7916
- if (process.platform === "linux") {
7917
- const ticks = await getClockTicks();
7918
- cpuSeconds /= ticks;
7919
- }
7920
- const before = this.previous.get(rootPid);
7921
- if (before !== void 0 && now > before.at) {
7922
- const elapsedSeconds = (now - before.at) / 1e3;
7923
- const usedSeconds = cpuSeconds - before.cpuSeconds;
7924
- if (elapsedSeconds > 0 && usedSeconds >= 0) cpuPercent = usedSeconds / elapsedSeconds * 100;
7925
- }
7926
- this.previous.set(rootPid, {
7927
- cpuSeconds,
7928
- at: now
7929
- });
7930
- } else this.previous.delete(rootPid);
8174
+ if (cpuPercent === null && !wasForgotten && usedSeconds !== null && elapsedSeconds > 0) cpuPercent = usedSeconds / elapsedSeconds * 100;
7931
8175
  results.set(rootPid, {
7932
8176
  cpuPercent: cpuPercent === null ? null : Math.round(cpuPercent * 10) / 10,
7933
8177
  rssBytes: Math.round(rssKb * 1024),
@@ -7935,10 +8179,22 @@ var init_proc = __esmMin((() => {
7935
8179
  sampledAt: now
7936
8180
  });
7937
8181
  }
8182
+ this.previousTable = {
8183
+ at: now,
8184
+ cpuSeconds: tableCpuSeconds
8185
+ };
7938
8186
  return results;
7939
8187
  }
8188
+ /**
8189
+ * Marks a root's next reading as the first of a new life.
8190
+ *
8191
+ * Called when an entry stops, exits or is restarted. Without it a recycled pid — or the very
8192
+ * next sample of the same root — would be differenced against a counter from the previous run,
8193
+ * which is not an interval. The scan-wide table cannot be cleared per root, so the suppression
8194
+ * is remembered here and consumed by that root's next sample.
8195
+ */
7940
8196
  forget(rootPid) {
7941
- this.previous.delete(rootPid);
8197
+ this.forgotten.set(rootPid, Date.now());
7942
8198
  }
7943
8199
  };
7944
8200
  }));
@@ -11636,6 +11892,14 @@ function createSettingsRoute(deps) {
11636
11892
  statusCode: 400,
11637
11893
  code: "PROXY_EXPOSURE_BLOCKED"
11638
11894
  });
11895
+ const scope = patch.backups?.schedule?.scope;
11896
+ if (scope !== void 0 && scope !== null) {
11897
+ const unknown = unknownBackupIds(scope.ids, deps.backups.view().entries);
11898
+ if (unknown.length > 0) throw new DetailedError(`the automatic backup scope names ${unknown.map((id) => `"${id}"`).join(", ")}, which this panel cannot capture`, {
11899
+ statusCode: 400,
11900
+ code: "INVALID_SETTINGS"
11901
+ });
11902
+ }
11639
11903
  const previous = {
11640
11904
  trustProxy: current.auth.trustProxy,
11641
11905
  tlsEnabled: current.tls.enabled
@@ -11813,6 +12077,7 @@ var init_settings = __esmMin((() => {
11813
12077
  init_workspace();
11814
12078
  init_exposure();
11815
12079
  init_state$1();
12080
+ init_backup_scope();
11816
12081
  init_contracts();
11817
12082
  MAX_UI_UPLOAD_BYTES = 134217728;
11818
12083
  }));
@@ -12586,7 +12851,7 @@ var init_acme_challenge = __esmMin((() => {
12586
12851
  */
12587
12852
  function secretParts(scope, present) {
12588
12853
  const keys = new Set(present);
12589
- const known = KNOWN[scope];
12854
+ const known = KNOWN_SECRET_KEYS[scope];
12590
12855
  const parts = known.filter((key) => keys.has(key)).map((key) => ({
12591
12856
  key,
12592
12857
  fields: EXTRA_FIELDS[key] ?? [key],
@@ -12642,10 +12907,10 @@ function mergeSecrets(current, piece, fields) {
12642
12907
  }
12643
12908
  return merged;
12644
12909
  }
12645
- var KNOWN, KNOWN_SCOPES, EXTRA_FIELDS;
12910
+ var KNOWN_SECRET_KEYS, KNOWN_SCOPES, EXTRA_FIELDS;
12646
12911
  var init_secret_parts = __esmMin((() => {
12647
12912
  init_shape();
12648
- KNOWN = {
12913
+ KNOWN_SECRET_KEYS = {
12649
12914
  global: ["password", "apiToken"],
12650
12915
  workspace: ["telegram", "ddns"]
12651
12916
  };
@@ -15771,6 +16036,7 @@ var init_backups = __esmMin((() => {
15771
16036
  init_archive();
15772
16037
  init_backup_hook();
15773
16038
  init_supervisor();
16039
+ init_backup_scope();
15774
16040
  init_contracts();
15775
16041
  init_error_message();
15776
16042
  init_generated();
@@ -15889,17 +16155,20 @@ var init_backups = __esmMin((() => {
15889
16155
  error: "backups are disabled"
15890
16156
  };
15891
16157
  const password = options.password !== void 0 && options.password.length > 0 ? options.password : null;
16158
+ const selects = selectionOf(options);
15892
16159
  const wanted = options.include === void 0 ? null : new Set(options.include);
15893
- const capturesGlobal = (id) => wanted === null || wanted.has(id);
15894
- const capturesWorkspace = (id, suffix) => wanted === null || wanted.has(`workspace:${id}`) || wanted.has(`workspace:${id}:${suffix}`);
16160
+ const capturesGlobal = (id) => selects(id);
16161
+ const capturesWorkspace = (id, suffix) => selects(`workspace:${id}:${suffix}`);
15895
16162
  /**
15896
16163
  * The secrets of one scope the request asked for; `null` means "every one of them".
15897
16164
  * `workspaceId` is how a bare `workspace:<id>` selection covers all of its leaves.
15898
16165
  */
15899
16166
  const selectedSecretFields = (entryId, path, scope, workspaceId) => {
15900
16167
  const parts = secretParts(scope, presentSecretKeys(parseSecrets(readText(path) ?? "")));
15901
- const coversEntry = wanted === null || wanted.has(entryId) || workspaceId !== void 0 && wanted.has(`workspace:${workspaceId}`);
15902
- const picked = parts.filter((part) => coversEntry || wanted.has(`${entryId}:${part.key}`) || part.fields.some((field) => wanted.has(`${entryId}:${field}`)));
16168
+ const picked = parts.filter((part) => {
16169
+ if (selects.isExcluded(entryId) || selects.isExcluded(`${entryId}:${part.key}`)) return false;
16170
+ return wanted === null || wanted.has(entryId) || workspaceId !== void 0 && wanted.has(`workspace:${workspaceId}`) || wanted.has(`${entryId}:${part.key}`) || part.fields.some((field) => wanted.has(`${entryId}:${field}`));
16171
+ });
15903
16172
  return picked.length === parts.length ? null : picked.flatMap((part) => part.fields);
15904
16173
  };
15905
16174
  const dir = this.resolveDir();
@@ -15939,9 +16208,9 @@ var init_backups = __esmMin((() => {
15939
16208
  * True when the request touches a secrets entry at all: the entry itself, one of its
15940
16209
  * leaves, or — for a workspace — the workspace id, which names every leaf it has.
15941
16210
  */
15942
- const capturesSecrets = (entryId, workspaceId) => wanted === null || wanted.has(entryId) || workspaceId !== void 0 && wanted.has(`workspace:${workspaceId}`) || [...wanted].some((id) => id.startsWith(`${entryId}:`));
16211
+ const touchesSecrets = (entryId, workspaceId) => selects(entryId) || wanted !== null && [...wanted].some((id) => id.startsWith(`${entryId}:`)) || workspaceId !== void 0 && selects(`workspace:${workspaceId}:secrets`);
15943
16212
  if (capturesGlobal("global:settings")) copy("global/settings.json", sources.globalSettingsPath);
15944
- if (capturesSecrets("global:secrets")) copySecrets("global/secrets.json", sources.globalSecretsPath, "global:secrets", "global");
16213
+ if (touchesSecrets("global:secrets")) copySecrets("global/secrets.json", sources.globalSecretsPath, "global:secrets", "global");
15945
16214
  if (capturesGlobal("global:tls")) copy("global/tls", sources.tlsDir);
15946
16215
  this.copyInto(staging, `global/${REGISTRY}`, sources.registryPath);
15947
16216
  /**
@@ -15956,7 +16225,7 @@ var init_backups = __esmMin((() => {
15956
16225
  for (const workspace of sources.workspaces) for (const server of workspace.servers) {
15957
16226
  const hook = server.dump;
15958
16227
  if (hook === void 0 || hook === null) continue;
15959
- if (wanted !== null && !wanted.has(`workspace:${workspace.id}`) && !wanted.has(`workspace:${workspace.id}:dump:${server.id}`)) continue;
16228
+ if (!selects(`workspace:${workspace.id}:dump:${server.id}`)) continue;
15960
16229
  const relative = path.join("dumps", workspace.id, server.id);
15961
16230
  const result = await runBackupHook(hook, server, path.join(staging, relative));
15962
16231
  if (!result.ok) {
@@ -15979,7 +16248,7 @@ var init_backups = __esmMin((() => {
15979
16248
  const root = `workspaces/${workspace.id}`;
15980
16249
  if (capturesWorkspace(workspace.id, "settings")) copy(`${root}/settings.json`, workspace.settingsPath);
15981
16250
  if (capturesWorkspace(workspace.id, "servers")) copy(`${root}/servers.config.json`, workspace.serversPath);
15982
- if (capturesSecrets(`workspace:${workspace.id}:secrets`, workspace.id)) copySecrets(`${root}/secrets.json`, workspace.secretsPath, `workspace:${workspace.id}:secrets`, "workspace", workspace.id);
16251
+ if (touchesSecrets(`workspace:${workspace.id}:secrets`, workspace.id)) copySecrets(`${root}/secrets.json`, workspace.secretsPath, `workspace:${workspace.id}:secrets`, "workspace", workspace.id);
15983
16252
  for (const declared of this.declaredData(workspace.servers, sources.includePaths)) {
15984
16253
  if (!declared.included) continue;
15985
16254
  if (!capturesWorkspace(workspace.id, `data:${declared.path}`)) continue;
@@ -15996,7 +16265,7 @@ var init_backups = __esmMin((() => {
15996
16265
  });
15997
16266
  }
15998
16267
  }
15999
- if (wanted !== null && captured === 0) {
16268
+ if ((wanted !== null || (options.exclude?.length ?? 0) > 0) && captured === 0) {
16000
16269
  fs.rmSync(staging, {
16001
16270
  recursive: true,
16002
16271
  force: true
@@ -16147,7 +16416,7 @@ var init_backups = __esmMin((() => {
16147
16416
  error: `written by home-hosted ${manifest.writtenBy ?? "a newer release"} (config schema ${manifest.schema}); this release understands schema 2`
16148
16417
  };
16149
16418
  const sources = this.options.getSources();
16150
- const selectedIds = options.include === void 0 ? null : new Set(options.include);
16419
+ const selects = selectionOf(options);
16151
16420
  const actions = /* @__PURE__ */ new Map();
16152
16421
  const addItem = (item, apply, aliases = []) => {
16153
16422
  if (apply === null) {
@@ -16165,7 +16434,7 @@ var init_backups = __esmMin((() => {
16165
16434
  });
16166
16435
  return;
16167
16436
  }
16168
- const selected = selectedIds === null || selectedIds.has(item.id) || aliases.some((alias) => selectedIds.has(alias));
16437
+ const selected = !(selects.isExcluded(item.id) || aliases.some((alias) => selects.isExcluded(alias))) && (selects(item.id) || aliases.some((alias) => selects(alias)));
16169
16438
  plan.items.push({
16170
16439
  ...item,
16171
16440
  selected
@@ -16203,6 +16472,7 @@ var init_backups = __esmMin((() => {
16203
16472
  }, ["config"]);
16204
16473
  const globalSecrets = readText(path.join(staging, "global", "secrets.json"));
16205
16474
  if (globalSecrets !== null) {
16475
+ const globalSecretKeys = presentSecretKeys(parseSecrets(globalSecrets));
16206
16476
  addItem({
16207
16477
  id: "global:secrets",
16208
16478
  label: "Global secrets (password, API token)",
@@ -16210,8 +16480,9 @@ var init_backups = __esmMin((() => {
16210
16480
  kind: "secrets",
16211
16481
  restorable: true,
16212
16482
  note: null
16213
- }, () => {
16214
- writeFileAtomic(sources.globalSecretsPath, globalSecrets, { mode: 384 });
16483
+ }, secretParts("global", globalSecretKeys).every((part) => !selects.isExcluded(`global:secrets:${part.key}`) && !part.fields.some((field) => selects.isExcluded(`global:secrets:${field}`))) ? () => writeFileAtomic(sources.globalSecretsPath, globalSecrets, { mode: 384 }) : () => {
16484
+ const take = secretParts("global", globalSecretKeys).filter((part) => !selects.isExcluded(`global:secrets:${part.key}`) && !part.fields.some((field) => selects.isExcluded(`global:secrets:${field}`))).flatMap((part) => part.fields);
16485
+ mergeIntoFile(sources.globalSecretsPath, globalSecrets, take);
16215
16486
  }, ["secrets"]);
16216
16487
  for (const part of secretParts("global", presentSecretKeys(parseSecrets(globalSecrets)))) addItem({
16217
16488
  id: `global:secrets:${part.key}`,
@@ -16486,7 +16757,7 @@ var init_backups = __esmMin((() => {
16486
16757
  continue;
16487
16758
  }
16488
16759
  const ownerId = target.origin.split(":")[0] ?? "";
16489
- if ((selectedIds === null || selectedIds.has(base.id) || aliases.includes(base.id)) && runningOwners.has(`${target.workspace}:${ownerId}`)) plan.replacedUnderRunning.push({
16760
+ if (!selects.isExcluded(base.id) && (selects(base.id) || aliases.some((alias) => selects(alias))) && runningOwners.has(`${target.workspace}:${ownerId}`)) plan.replacedUnderRunning.push({
16490
16761
  workspaceId: target.workspace,
16491
16762
  serverId: ownerId,
16492
16763
  path: target.path
@@ -16651,9 +16922,9 @@ var init_backups = __esmMin((() => {
16651
16922
  * secret that can be captured but never restored individually.
16652
16923
  */
16653
16924
  secretItems(scope, entryId, path) {
16654
- const present = presentSecretKeys(parseSecrets(readText(path) ?? ""));
16655
- if (present.length === 0) return [];
16656
- return secretParts(scope, present).map((part) => ({
16925
+ const parts = secretParts(scope, presentSecretKeys(parseSecrets(readText(path) ?? "")));
16926
+ const missing = KNOWN_SECRET_KEYS[scope].filter((key) => !parts.some((part) => part.key === key));
16927
+ return [...parts.map((part) => ({
16657
16928
  id: `${entryId}:${part.key}`,
16658
16929
  label: SECRET_LABELS[part.key]?.en ?? part.key,
16659
16930
  ...SECRET_LABELS[part.key] === void 0 ? {} : { labelKey: SECRET_LABELS[part.key].key },
@@ -16661,7 +16932,16 @@ var init_backups = __esmMin((() => {
16661
16932
  secret: part.key,
16662
16933
  included: true,
16663
16934
  note: null
16664
- }));
16935
+ })), ...missing.map((key) => ({
16936
+ id: `${entryId}:${key}`,
16937
+ label: SECRET_LABELS[key]?.en ?? key,
16938
+ ...SECRET_LABELS[key] === void 0 ? {} : { labelKey: SECRET_LABELS[key].key },
16939
+ kind: "secrets",
16940
+ secret: key,
16941
+ included: false,
16942
+ note: "not set",
16943
+ noteKey: "settings.backup.noteMissing"
16944
+ }))];
16665
16945
  }
16666
16946
  workspaceItems(workspace, includePaths) {
16667
16947
  const id = workspace.id;
@@ -16791,7 +17071,7 @@ var init_backups = __esmMin((() => {
16791
17071
  for (const name of [...this.flags.keys()]) if (!present.has(name)) this.flags.delete(name);
16792
17072
  }
16793
17073
  missingNote(target) {
16794
- return fs.existsSync(target) ? null : "does not exist yet";
17074
+ return fs.existsSync(target) ? null : "not set";
16795
17075
  }
16796
17076
  /** Copies one source into the staging tree; false when there was nothing there. */
16797
17077
  copyInto(staging, relative, source, ignoreGenerated = false) {
@@ -16845,7 +17125,10 @@ var init_backups = __esmMin((() => {
16845
17125
  if (latest !== null && now - latest < config.schedule.intervalMs) return;
16846
17126
  this.running = true;
16847
17127
  this.lastAttemptAt = now;
16848
- this.create({ automatic: true }).then((result) => {
17128
+ this.create({
17129
+ automatic: true,
17130
+ ...scopeSelection(config.schedule.scope)
17131
+ }).then((result) => {
16849
17132
  if (result.ok) {
16850
17133
  this.scheduleError = null;
16851
17134
  return;
@@ -17128,6 +17411,35 @@ async function readSwapUsedPercent() {
17128
17411
  }
17129
17412
  return 0;
17130
17413
  }
17414
+ function cpuTimesSnapshot(cpus = os.cpus()) {
17415
+ let busyMs = 0;
17416
+ let totalMs = 0;
17417
+ for (const cpu of cpus) {
17418
+ const times = cpu.times;
17419
+ const idle = times.idle;
17420
+ const busy = times.user + (times.nice ?? 0) + times.sys + (times.irq ?? 0);
17421
+ busyMs += busy;
17422
+ totalMs += busy + idle;
17423
+ }
17424
+ return {
17425
+ busyMs,
17426
+ totalMs
17427
+ };
17428
+ }
17429
+ /**
17430
+ * Share of the machine's CPU capacity in use between two snapshots, 0–100.
17431
+ *
17432
+ * `null` when the window is empty or the counters went backwards (a suspended host, a clock
17433
+ * resync), because "no reading" is honest while a fabricated 0 reads as "idle". Pure, so the
17434
+ * arithmetic is testable against snapshots a runner can construct rather than only the one its
17435
+ * own scheduler happens to produce.
17436
+ */
17437
+ function cpuUsedPercent(previous, next) {
17438
+ const totalDelta = next.totalMs - previous.totalMs;
17439
+ const busyDelta = next.busyMs - previous.busyMs;
17440
+ if (!(totalDelta > 0) || busyDelta < 0) return null;
17441
+ return Math.max(0, Math.min(100, busyDelta / totalDelta * 100));
17442
+ }
17131
17443
  /**
17132
17444
  * Memory used, as a percentage of what the machine actually has.
17133
17445
  *
@@ -17290,6 +17602,9 @@ async function sampleHost(config, resolvePath) {
17290
17602
  const cpus = os.cpus().length || 1;
17291
17603
  const loadAvg = os.loadavg();
17292
17604
  const memory = memoryInfo();
17605
+ const cpuTimes = cpuTimesSnapshot();
17606
+ const cpuUsedPercentNow = previousCpuTimes === null ? null : cpuUsedPercent(previousCpuTimes, cpuTimes);
17607
+ previousCpuTimes = cpuTimes;
17293
17608
  if (process.platform === "win32") loadAvg.fill(0);
17294
17609
  if (memory.swapUsedPercent === 0 && process.platform !== "linux") memory.swapUsedPercent = await swapUsedPercent();
17295
17610
  const tempCelsius = cpuTemperature();
@@ -17305,6 +17620,7 @@ async function sampleHost(config, resolvePath) {
17305
17620
  enabled: config.enabled,
17306
17621
  cpus,
17307
17622
  loadAvg: [...loadAvg],
17623
+ cpuUsedPercent: cpuUsedPercentNow,
17308
17624
  uptimeMs: os.uptime() * 1e3,
17309
17625
  memoryUsedPercent: memory.memoryUsedPercent,
17310
17626
  swapUsedPercent: memory.swapUsedPercent,
@@ -17323,6 +17639,7 @@ function emptyHostView(config) {
17323
17639
  0,
17324
17640
  0
17325
17641
  ],
17642
+ cpuUsedPercent: null,
17326
17643
  uptimeMs: os.uptime() * 1e3,
17327
17644
  memoryUsedPercent: 0,
17328
17645
  swapUsedPercent: 0,
@@ -17332,11 +17649,12 @@ function emptyHostView(config) {
17332
17649
  sampledAt: null
17333
17650
  };
17334
17651
  }
17335
- var execFileAsync, SWAP_CACHE_MS, swapCache;
17652
+ var execFileAsync, SWAP_CACHE_MS, swapCache, previousCpuTimes;
17336
17653
  var init_host = __esmMin((() => {
17337
17654
  execFileAsync = promisify(execFile);
17338
17655
  SWAP_CACHE_MS = 6e4;
17339
17656
  swapCache = null;
17657
+ previousCpuTimes = null;
17340
17658
  }));
17341
17659
  //#endregion
17342
17660
  //#region src/services/host-monitor.ts
@@ -21588,6 +21906,49 @@ var backup_exports = /* @__PURE__ */ __exportAll({
21588
21906
  runBackupList: () => runBackupList,
21589
21907
  runBackupRestore: () => runBackupRestore
21590
21908
  });
21909
+ /**
21910
+ * Render plan ids as the tree they already are.
21911
+ *
21912
+ * Every id is a colon-separated path, so the hierarchy is in the data and the renderer's only job is
21913
+ * to show it: one row per prefix, each one level deeper than its parent. Depth is whatever the id
21914
+ * says, not a fixed number of columns — `workspace:default:secrets:telegram` sits three deep, and a
21915
+ * renderer that assumed two printed it beside its own parent.
21916
+ *
21917
+ * Both directions print through this, and so does the "what could I act on" list, so the three read
21918
+ * alike. A row's note is the panel's own wording, passed through untouched.
21919
+ */
21920
+ function printPlanTree(rows) {
21921
+ const known = new Set(rows.map((row) => row.id));
21922
+ const nodes = /* @__PURE__ */ new Map();
21923
+ const ensure = (id) => {
21924
+ const existing = nodes.get(id);
21925
+ if (existing !== void 0) return existing;
21926
+ const created = {
21927
+ note: null,
21928
+ children: /* @__PURE__ */ new Set()
21929
+ };
21930
+ nodes.set(id, created);
21931
+ return created;
21932
+ };
21933
+ for (const row of rows) {
21934
+ const segments = row.id.split(":");
21935
+ for (let depth = 1; depth <= segments.length; depth++) {
21936
+ const id = segments.slice(0, depth).join(":");
21937
+ const node = ensure(id);
21938
+ if (depth > 1) ensure(segments.slice(0, depth - 1).join(":")).children.add(id);
21939
+ if (depth === segments.length && known.has(row.id)) node.note = row.note ?? null;
21940
+ }
21941
+ }
21942
+ const roots = [...nodes.keys()].filter((id) => !id.includes(":"));
21943
+ const write = (id, depth) => {
21944
+ const node = nodes.get(id);
21945
+ if (node === void 0) return;
21946
+ const padding = " ".repeat(depth);
21947
+ process.stdout.write(`${padding}${depth === 1 ? "" : "- "}${id}${node.note === null ? "" : ` ${dim(`(${node.note})`)}`}\n`);
21948
+ for (const child of node.children) write(child, depth + 1);
21949
+ };
21950
+ for (const root of roots) write(root, 1);
21951
+ }
21591
21952
  function human(bytes) {
21592
21953
  if (bytes < 1024) return `${bytes} B`;
21593
21954
  if (bytes < 1048576) return `${Math.round(bytes / 1024)} KB`;
@@ -21650,14 +22011,83 @@ function parseScope(all, raw) {
21650
22011
  };
21651
22012
  }
21652
22013
  /**
22014
+ * The plan rows a scope selects, and an exclusion drops.
22015
+ *
22016
+ * `kind` is deliberately not part of this: it is the panel's label for a row, not an id, and every id
22017
+ * the plan prints is already prefixed with it (`global:settings`, `workspace:default:servers`).
22018
+ */
22019
+ /** Flatten a nested plan into the rows the tree renders. */
22020
+ function flattenRows(rows) {
22021
+ return rows.flatMap((row) => [{
22022
+ id: row.id,
22023
+ note: row.note ?? null
22024
+ }, ...(row.items ?? []).map((leaf) => ({
22025
+ id: leaf.id,
22026
+ note: leaf.note ?? null
22027
+ }))]);
22028
+ }
22029
+ function filterEntries(entries, scope, exclude) {
22030
+ const unwanted = exclude ?? [];
22031
+ const excluded = (id) => unwanted.some((entry) => id === entry || id.startsWith(`${entry}:`));
22032
+ const named = (id) => scope.kind === "all" || scope.ids.some((entry) => id === entry || id.startsWith(`${entry}:`) || entry.startsWith(`${id}:`));
22033
+ return entries.filter((entry) => named(entry.id) && !excluded(entry.id)).map((entry) => entry.items === void 0 ? entry : {
22034
+ ...entry,
22035
+ items: entry.items.filter((leaf) => named(leaf.id) && !excluded(leaf.id))
22036
+ });
22037
+ }
22038
+ /**
22039
+ * Refuse an id the plan does not have.
22040
+ *
22041
+ * An id that matches nothing is silently ignored by the service, which is right for an archive that
22042
+ * simply does not carry something — and wrong for a typo: `--exclude global:secret` excludes nothing
22043
+ * and says nothing, so the archive carries the credentials the person believed they had dropped.
22044
+ */
22045
+ function assertKnown(ids, entries, flag) {
22046
+ if (ids === void 0) return;
22047
+ const unknown = unknownBackupIds(ids, entries);
22048
+ 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`);
22049
+ }
22050
+ /** `--exclude` parsed. An empty value is a mistake, not "exclude nothing". */
22051
+ function parseExclude(raw) {
22052
+ if (raw === void 0) return void 0;
22053
+ const ids = raw.split(",").map((part) => part.trim()).filter((part) => part.length > 0);
22054
+ if (ids.length === 0) fail("--exclude is empty — name the ids to leave out, or drop the flag");
22055
+ return ids;
22056
+ }
22057
+ /**
21653
22058
  * Neither flag given. Refused outright — the ids are a *bonus*, not the reason.
21654
22059
  *
21655
22060
  * The refusal must not depend on a panel being up: a mistyped command deserves the flag error, not
21656
22061
  * "home-hosted is not running". So the list is best-effort, and a failure to produce it is silent.
21657
22062
  */
21658
22063
  async function refuseWithoutScope(action, suffix) {
21659
- const ids = await availableIdsFor(action, suffix).catch(() => []);
21660
- fail(`name what to act on — pass --include <ids> or --all${ids.length === 0 ? "" : `\n\navailable:\n${ids.map((id) => ` ${id}`).join("\n")}`}`);
22064
+ const rows = await availableRows(action, suffix).catch(() => []);
22065
+ if (rows.length === 0) fail("name what to act on — pass --include <ids> or --all");
22066
+ process.stderr.write(`${paint("31", "error")} name what to act on — pass --include <ids> or --all\n\n`);
22067
+ process.stderr.write("available (or narrow it):\n");
22068
+ printPlanTree(flattenRows(rows));
22069
+ process.stderr.write("\n--exclude <ids> leaves those out: --all --exclude global:secrets\n");
22070
+ process.exit(1);
22071
+ }
22072
+ /**
22073
+ * The ids an offline run could act on, read from the state files.
22074
+ *
22075
+ * The refusal has to name real ids whether or not a panel is up — an empty list is the one answer
22076
+ * worse than no list, because it reads as "there is nothing to back up".
22077
+ */
22078
+ async function availableRowsFromDisk(action, suffix) {
22079
+ try {
22080
+ const { service } = await offlineBackup();
22081
+ await service.warm();
22082
+ if (action === "create") return service.view().entries;
22083
+ const name = new URLSearchParams(suffix.startsWith("?") ? suffix.slice(1) : suffix).get("name");
22084
+ if (name === null || name.length === 0) return [];
22085
+ const archive = service.resolve(name);
22086
+ if (archive === null) return [];
22087
+ return ((await service.restore(archive, { confirm: false })).items ?? []).filter((item) => item.selected !== false);
22088
+ } catch {
22089
+ return [];
22090
+ }
21661
22091
  }
21662
22092
  /**
21663
22093
  * The ids this action could be scoped to.
@@ -21666,15 +22096,15 @@ async function refuseWithoutScope(action, suffix) {
21666
22096
  * panel, so the list in a refusal is the real one rather than a hardcoded guess. A panel that cannot
21667
22097
  * be reached yields no ids — the refusal still fires, it just cannot enumerate.
21668
22098
  */
21669
- async function availableIdsFor(action, suffix) {
22099
+ async function availableRows(action, suffix) {
21670
22100
  const daemon = await Promise.resolve().then(() => (init_daemon(), daemon_exports));
21671
22101
  const runtime = daemon.readRuntime();
21672
- if (runtime === null) return [];
22102
+ if (runtime === null || !await daemon.runtimeIsAlive(runtime)) return await availableRowsFromDisk(action, suffix);
21673
22103
  const path = action === "create" ? "/_hh/backups" : "/_hh/backups/restore";
21674
22104
  const answer = await daemon.requestControl(runtime, `${path}${suffix}`, 12e4);
21675
22105
  if (answer === null || answer.status !== 200) return [];
21676
22106
  const body = answer.body;
21677
- return ((action === "create" ? body?.entries : body?.items) ?? []).map((item) => item.id).filter((id) => typeof id === "string");
22107
+ return action === "create" ? body?.entries ?? [] : body?.items ?? [];
21678
22108
  }
21679
22109
  /** `?a=b`, or `''`. */
21680
22110
  function suffixOf(query) {
@@ -21772,7 +22202,9 @@ async function runBackupCreate(options) {
21772
22202
  await service.warm();
21773
22203
  return service.view().entries;
21774
22204
  })();
21775
- const wanted = scope.kind === "all" ? entries : entries.filter((entry) => scope.ids.some((id) => entry.id === id || id.startsWith(`${entry.id}:`)));
22205
+ assertKnown(options.exclude, entries, "--exclude");
22206
+ assertKnown(scope.kind === "include" ? scope.ids : void 0, entries, "--include");
22207
+ const wanted = filterEntries(entries, scope, options.exclude);
21776
22208
  if (!options.confirm) {
21777
22209
  if (options.json) {
21778
22210
  process.stdout.write(`${JSON.stringify({
@@ -21783,10 +22215,7 @@ async function runBackupCreate(options) {
21783
22215
  return;
21784
22216
  }
21785
22217
  process.stdout.write(`${bold("Plan")} — what a backup would capture; nothing has been written yet\n`);
21786
- for (const entry of wanted) {
21787
- process.stdout.write(` ${String(entry.kind ?? "entry").padEnd(10)} ${entry.id}${entry.note == null ? "" : ` ${dim(`(${entry.note})`)}`}\n`);
21788
- for (const item of entry.items ?? []) process.stdout.write(` ${dim("-")} ${item.id}\n`);
21789
- }
22218
+ printPlanTree(flattenRows(wanted));
21790
22219
  if (wanted.length === 0) {
21791
22220
  process.stdout.write(" (nothing matched — check --include, or what the entries declare)\n");
21792
22221
  return;
@@ -21795,6 +22224,7 @@ async function runBackupCreate(options) {
21795
22224
  if (!await consent("Take this backup?")) return;
21796
22225
  }
21797
22226
  const include = scope.kind === "include" ? scope.ids : void 0;
22227
+ const exclude = options.exclude;
21798
22228
  const file = (await (async () => {
21799
22229
  if (online) {
21800
22230
  const runtime = await livePanel();
@@ -21802,6 +22232,7 @@ async function runBackupCreate(options) {
21802
22232
  const query = new URLSearchParams();
21803
22233
  if (options.password !== void 0 && options.password.length > 0) query.set("password", options.password);
21804
22234
  if (include !== void 0) query.set("include", include.join(","));
22235
+ if (exclude !== void 0) query.set("exclude", exclude.join(","));
21805
22236
  const answer = await runtime.request(runtime, `/_hh/backups${withParam(suffixOf(query), "confirm", "true")}`, 6e5);
21806
22237
  if (answer === null) fail(`the control panel is not answering on ${runtime.probeUrl}`);
21807
22238
  if (answer.status !== 200) refusal(answer);
@@ -21812,7 +22243,8 @@ async function runBackupCreate(options) {
21812
22243
  await service.warm();
21813
22244
  const result = await service.create({
21814
22245
  password: options.password,
21815
- include
22246
+ include,
22247
+ exclude
21816
22248
  });
21817
22249
  if (!result.ok) fail(result.error ?? "the backup failed");
21818
22250
  return { file: result.file };
@@ -21849,7 +22281,8 @@ async function runBackupRestore(options) {
21849
22281
  return await service.restore(archive, {
21850
22282
  confirm: false,
21851
22283
  password: options.password,
21852
- include: scope.kind === "include" ? scope.ids : void 0
22284
+ include: scope.kind === "include" ? scope.ids : void 0,
22285
+ exclude: options.exclude
21853
22286
  });
21854
22287
  }
21855
22288
  const runtime = await livePanel();
@@ -21857,6 +22290,7 @@ async function runBackupRestore(options) {
21857
22290
  const base = new URLSearchParams({ name: options.name });
21858
22291
  if (options.password !== void 0 && options.password.length > 0) base.set("password", options.password);
21859
22292
  if (scope.kind === "include") base.set("include", scope.ids.join(","));
22293
+ if (options.exclude !== void 0) base.set("exclude", options.exclude.join(","));
21860
22294
  const answer = await runtime.request(runtime, `/_hh/backups/restore${suffixOf(base)}`, 12e4);
21861
22295
  if (answer === null) fail(`the control panel is not answering at ${runtime.probeUrl}`);
21862
22296
  if (answer.status !== 200) refusal(answer);
@@ -21875,7 +22309,10 @@ async function runBackupRestore(options) {
21875
22309
  }
21876
22310
  if (!options.json) {
21877
22311
  process.stdout.write(`${bold("Plan")} for ${options.name} — nothing has been written yet\n`);
21878
- for (const item of items) process.stdout.write(` ${String(item.kind ?? "item").padEnd(10)} ${item.id ?? item.label ?? ""}\n`);
22312
+ printPlanTree(items.map((item) => ({
22313
+ id: item.id,
22314
+ note: item.note ?? null
22315
+ })));
21879
22316
  for (const warning of plan?.warnings ?? []) process.stdout.write(` ${dim("!")} ${warning}\n`);
21880
22317
  if (items.length === 0) {
21881
22318
  process.stdout.write(" (nothing to restore — check --include, or what this host declares)\n");
@@ -21890,7 +22327,8 @@ async function runBackupRestore(options) {
21890
22327
  const result = await service.restore(archive, {
21891
22328
  confirm: true,
21892
22329
  password: options.password,
21893
- include: scope.kind === "include" ? scope.ids : void 0
22330
+ include: scope.kind === "include" ? scope.ids : void 0,
22331
+ exclude: options.exclude
21894
22332
  });
21895
22333
  return {
21896
22334
  items: (result.items ?? []).filter((item) => item.selected !== false),
@@ -21902,6 +22340,7 @@ async function runBackupRestore(options) {
21902
22340
  const base = new URLSearchParams({ name: options.name });
21903
22341
  if (options.password !== void 0 && options.password.length > 0) base.set("password", options.password);
21904
22342
  if (scope.kind === "include") base.set("include", scope.ids.join(","));
22343
+ if (options.exclude !== void 0) base.set("exclude", options.exclude.join(","));
21905
22344
  const answer = await runtime.request(runtime, `/_hh/backups/restore${withParam(suffixOf(base), "confirm", "true")}`, 6e5);
21906
22345
  if (answer === null) fail(`the control panel is not answering at ${runtime.probeUrl}`);
21907
22346
  if (answer.status !== 200) refusal(answer);
@@ -21933,6 +22372,7 @@ var backupCommand;
21933
22372
  var init_backup = __esmMin((() => {
21934
22373
  init_backup_offline();
21935
22374
  init_io();
22375
+ init_backup_scope();
21936
22376
  init_error_message();
21937
22377
  backupCommand = defineCommand({
21938
22378
  meta: { name: "backup" },
@@ -21955,6 +22395,10 @@ var init_backup = __esmMin((() => {
21955
22395
  type: "string",
21956
22396
  description: "comma-separated item ids to act on"
21957
22397
  },
22398
+ exclude: {
22399
+ type: "string",
22400
+ description: "comma-separated item ids to leave out, applied after --include"
22401
+ },
21958
22402
  all: {
21959
22403
  type: "boolean",
21960
22404
  description: "act on everything, rather than naming ids"
@@ -21972,12 +22416,14 @@ var init_backup = __esmMin((() => {
21972
22416
  try {
21973
22417
  const action = args.action === void 0 || args.action.length === 0 ? "list" : args.action;
21974
22418
  const parsed = action === "create" || action === "restore" ? parseScope(args.all === true, args.include) : null;
22419
+ const exclude = action === "create" || action === "restore" ? parseExclude(args.exclude) : void 0;
21975
22420
  if (action === "list") await runBackupList(args.json === true);
21976
22421
  else if (action === "create") {
21977
22422
  const scope = parsed ?? await refuseWithoutScope("create", "");
21978
22423
  await runBackupCreate({
21979
22424
  password: args.password,
21980
22425
  scope,
22426
+ exclude,
21981
22427
  confirm: args.confirm === true,
21982
22428
  json: args.json === true
21983
22429
  });
@@ -21988,6 +22434,7 @@ var init_backup = __esmMin((() => {
21988
22434
  name: args.target,
21989
22435
  password: args.password,
21990
22436
  scope,
22437
+ exclude,
21991
22438
  confirm: args.confirm === true,
21992
22439
  json: args.json === true
21993
22440
  });
@@ -22243,6 +22690,7 @@ var BACKUP_SECTION = {
22243
22690
  ["<name>", "the archive, for restore — `backup list` shows them"],
22244
22691
  ["--include <ids>", "comma-separated item ids to act on (required for create/restore)"],
22245
22692
  ["--all", "act on everything; one of --include or --all is required"],
22693
+ ["--exclude <ids>", "leave these out; --all --exclude global:secrets keeps the password and token out of the archive"],
22246
22694
  ["--password <text>", "encrypt a new archive, or unlock one on restore"],
22247
22695
  ["--confirm", "apply without asking (create and restore plan first)"],
22248
22696
  ["--json", "print the plan or the result as JSON"]