home-hosted 0.9.11 → 0.10.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/cli.js CHANGED
@@ -3368,20 +3368,34 @@ function createAuthRoute(deps) {
3368
3368
  });
3369
3369
  }).delete("/auth/password", describeRoute({
3370
3370
  tags: ["auth"],
3371
- summary: "Clear the password and turn authentication off",
3371
+ summary: "Clear the password and turn authentication off (signed-in session required)",
3372
3372
  responses: {
3373
3373
  200: {
3374
3374
  description: "Cleared",
3375
3375
  content: jsonBody(okResponseSchema)
3376
3376
  },
3377
3377
  400: ERROR_RESPONSES[400],
3378
- 401: ERROR_RESPONSES[401]
3378
+ 401: ERROR_RESPONSES[401],
3379
+ 403: { description: "An API token may not clear the password" }
3379
3380
  }
3380
3381
  }), (c) => {
3381
- if (!requestIdentity(c, deps.auth).authenticated) throw new DetailedError("authentication required", {
3382
+ const identity = requestIdentity(c, deps.auth);
3383
+ if (!identity.authenticated) throw new DetailedError("authentication required", {
3382
3384
  statusCode: 401,
3383
3385
  code: AUTH_REQUIRED_CODE
3384
3386
  });
3387
+ /**
3388
+ * A **session**, not merely an identity, because clearing the password is the other way
3389
+ * authentication goes away. A bearer token must not be able to do it: `POST` refuses to
3390
+ * rewrite a password it already has without `currentPassword` (so a stolen token cannot
3391
+ * arm the panel), and a token that could `DELETE` instead would reach the same end —
3392
+ * `DELETE`, then `POST` a new password with none set, needing no current one. The refusal
3393
+ * names the two real paths, both of which the person can follow.
3394
+ */
3395
+ if (identity.method !== "cookie") throw new DetailedError("clearing the panel password needs a signed-in session, not an API token — sign in at the panel, or run `home-hosted set-password --clear` on the machine", {
3396
+ statusCode: 403,
3397
+ code: "SESSION_REQUIRED"
3398
+ });
3385
3399
  if (checkExposure(deps.panel.settings.control, false).exposed) throw new DetailedError("refusing to clear the password while the control panel is bound beyond loopback — set the bind back to local first", {
3386
3400
  statusCode: 400,
3387
3401
  code: "EXPOSED_WITHOUT_PASSWORD"
@@ -3643,6 +3657,76 @@ var init_state$1 = __esmMin((() => {
3643
3657
  init_exposure();
3644
3658
  }));
3645
3659
  //#endregion
3660
+ //#region src/shared/backup-scope.ts
3661
+ /**
3662
+ * What a configured automatic scope asks a `create` for.
3663
+ *
3664
+ * `only` is `--include` and `except` is `--all --exclude`, because a schedule and a person typing
3665
+ * flags have to mean the same thing. An absent scope is the full default the schedule took before
3666
+ * it could be configured, which is what keeps an existing config exactly as it was.
3667
+ */
3668
+ function scopeSelection(scope) {
3669
+ if (scope === void 0) return {};
3670
+ return scope.mode === "only" ? { include: [...scope.ids] } : { exclude: [...scope.ids] };
3671
+ }
3672
+ /**
3673
+ * What a selection asks for, from `include` and `exclude` together.
3674
+ *
3675
+ * One implementation for `create`, `restore`, the control channel's plan and both UIs: a second
3676
+ * copy of "does this id count as selected" is how an `--exclude` that works on backup silently does
3677
+ * nothing on restore, or how a page ticks a row the panel will not capture.
3678
+ *
3679
+ * `include` omitted means everything; `exclude` is applied after it, and an id under an excluded
3680
+ * entry is excluded too.
3681
+ */
3682
+ function selectionOf(options) {
3683
+ const wanted = options.include === void 0 ? null : new Set(options.include);
3684
+ const unwanted = new Set(options.exclude ?? []);
3685
+ const isExcluded = (id) => unwanted.has(id) || [...unwanted].some((entry) => id.startsWith(`${entry}:`));
3686
+ const selects = ((id) => {
3687
+ if (isExcluded(id)) return false;
3688
+ return wanted === null || wanted.has(id) || [...wanted].some((entry) => id.startsWith(`${entry}:`));
3689
+ });
3690
+ selects.isExcluded = isExcluded;
3691
+ return selects;
3692
+ }
3693
+ /**
3694
+ * Whether a restore selection would write the panel's own credential store.
3695
+ *
3696
+ * `global:secrets` holds the password hash and the API token hash, so a restore that carries it can
3697
+ * replace the credentials of the panel doing the restoring. That is a legitimate move for the owner
3698
+ * (a fresh host taking its own archive back) and a panel takeover for anyone holding only a token:
3699
+ * measured, a token-only upload restore left the victim's password hash byte-identical to the
3700
+ * attacker's, and the owner locked out.
3701
+ *
3702
+ * The predicate exists so the guard has one definition rather than a string literal at each call
3703
+ * site. It answers *whether* the store is touched; who may touch it is the route's decision.
3704
+ */
3705
+ function selectionWritesCredentials(options) {
3706
+ const selects = selectionOf(options);
3707
+ return selects("global:secrets") || [
3708
+ "password",
3709
+ "apiToken",
3710
+ "telegram",
3711
+ "ddns"
3712
+ ].some((key) => selects(`global:secrets:${key}`));
3713
+ }
3714
+ /**
3715
+ * Which of `ids` name nothing the panel can capture.
3716
+ *
3717
+ * The rule `backup create --include` already applies: an id names something when it is an entry or
3718
+ * leaf id, or a prefix of one (`workspace:default` covers its leaves). A typo matters more on a
3719
+ * schedule than anywhere else — nobody is watching — and it cuts both ways: an unknown `only` id
3720
+ * silently narrows the archive, an unknown `except` id silently widens it back over what the
3721
+ * person meant to leave out.
3722
+ */
3723
+ function unknownBackupIds(ids, entries) {
3724
+ const available = entries.flatMap((entry) => [entry.id, ...(entry.items ?? []).map((item) => item.id)]);
3725
+ const known = (id) => available.some((candidate) => candidate === id || candidate.startsWith(`${id}:`));
3726
+ return ids.filter((id) => !known(id));
3727
+ }
3728
+ var init_backup_scope = __esmMin((() => {}));
3729
+ //#endregion
3646
3730
  //#region src/api/backups.ts
3647
3731
  /** A backup that failed to be created is a bad request, not a server fault. */
3648
3732
  function backupFailed(error) {
@@ -3815,6 +3899,15 @@ function createBackupsRoute(deps) {
3815
3899
  code: "UNKNOWN_BACKUP"
3816
3900
  });
3817
3901
  }
3902
+ if (confirm && selectionWritesCredentials({
3903
+ include: request.include,
3904
+ exclude: request.exclude
3905
+ })) {
3906
+ if (requestIdentity(c, deps.auth).method !== "cookie") throw new DetailedError("restoring the panel's own credentials needs a signed-in session, not an API token — sign in, or run this from the machine with `home-hosted backup restore`", {
3907
+ statusCode: 403,
3908
+ code: "SESSION_REQUIRED"
3909
+ });
3910
+ }
3818
3911
  const plan = await deps.backups.restore(archive, {
3819
3912
  confirm,
3820
3913
  password: request.password,
@@ -3846,7 +3939,9 @@ var init_backups$1 = __esmMin((() => {
3846
3939
  init_openapi$1();
3847
3940
  init_validate();
3848
3941
  init_validator();
3942
+ init_auth();
3849
3943
  init_state$1();
3944
+ init_backup_scope();
3850
3945
  init_contracts();
3851
3946
  MAX_UPLOAD_BYTES = 268435456;
3852
3947
  nameParam = type({ name: "string >= 1" });
@@ -4183,55 +4278,6 @@ var init_workspace = __esmMin((() => {
4183
4278
  workspaceQuerySchema = type({ "workspace?": "string" });
4184
4279
  }));
4185
4280
  //#endregion
4186
- //#region src/shared/backup-scope.ts
4187
- /**
4188
- * What a configured automatic scope asks a `create` for.
4189
- *
4190
- * `only` is `--include` and `except` is `--all --exclude`, because a schedule and a person typing
4191
- * flags have to mean the same thing. An absent scope is the full default the schedule took before
4192
- * it could be configured, which is what keeps an existing config exactly as it was.
4193
- */
4194
- function scopeSelection(scope) {
4195
- if (scope === void 0) return {};
4196
- return scope.mode === "only" ? { include: [...scope.ids] } : { exclude: [...scope.ids] };
4197
- }
4198
- /**
4199
- * What a selection asks for, from `include` and `exclude` together.
4200
- *
4201
- * One implementation for `create`, `restore`, the control channel's plan and both UIs: a second
4202
- * copy of "does this id count as selected" is how an `--exclude` that works on backup silently does
4203
- * nothing on restore, or how a page ticks a row the panel will not capture.
4204
- *
4205
- * `include` omitted means everything; `exclude` is applied after it, and an id under an excluded
4206
- * entry is excluded too.
4207
- */
4208
- function selectionOf(options) {
4209
- const wanted = options.include === void 0 ? null : new Set(options.include);
4210
- const unwanted = new Set(options.exclude ?? []);
4211
- const isExcluded = (id) => unwanted.has(id) || [...unwanted].some((entry) => id.startsWith(`${entry}:`));
4212
- const selects = ((id) => {
4213
- if (isExcluded(id)) return false;
4214
- return wanted === null || wanted.has(id) || [...wanted].some((entry) => id.startsWith(`${entry}:`));
4215
- });
4216
- selects.isExcluded = isExcluded;
4217
- return selects;
4218
- }
4219
- /**
4220
- * Which of `ids` name nothing the panel can capture.
4221
- *
4222
- * The rule `backup create --include` already applies: an id names something when it is an entry or
4223
- * leaf id, or a prefix of one (`workspace:default` covers its leaves). A typo matters more on a
4224
- * schedule than anywhere else — nobody is watching — and it cuts both ways: an unknown `only` id
4225
- * silently narrows the archive, an unknown `except` id silently widens it back over what the
4226
- * person meant to leave out.
4227
- */
4228
- function unknownBackupIds(ids, entries) {
4229
- const available = entries.flatMap((entry) => [entry.id, ...(entry.items ?? []).map((item) => item.id)]);
4230
- const known = (id) => available.some((candidate) => candidate === id || candidate.startsWith(`${id}:`));
4231
- return ids.filter((id) => !known(id));
4232
- }
4233
- var init_backup_scope = __esmMin((() => {}));
4234
- //#endregion
4235
4281
  //#region src/api/control.ts
4236
4282
  /**
4237
4283
  * The local control channel used by `home-hosted down` and `home-hosted start|stop`.
@@ -4312,6 +4358,22 @@ function createControlRoute(deps) {
4312
4358
  assertLocalCall(c, "restart a server");
4313
4359
  const result = await requireWorkspace(deps.panel.requireWorkspace.bind(deps.panel), c.req.valid("query").workspace).supervisor.restart(c.req.param("id"), { actor: "user" });
4314
4360
  return c.json(result, statusForAction(result));
4361
+ }).post("/servers/:id/free-port", describeRoute({
4362
+ tags: ["panel"],
4363
+ summary: "Free one server's port, without a session (local token required)",
4364
+ responses: {
4365
+ 200: {
4366
+ description: "What was signalled",
4367
+ content: jsonBody(freePortResultSchema)
4368
+ },
4369
+ 403: { description: "Bad token, or not a local caller" },
4370
+ 404: { description: "No such server" },
4371
+ 409: { description: "Nothing to free, or the holder is supervised by this panel" }
4372
+ }
4373
+ }), validate("query", workspaceQuerySchema), async (c) => {
4374
+ assertLocalCall(c, "free a server's port");
4375
+ const result = await requireWorkspace(deps.panel.requireWorkspace.bind(deps.panel), c.req.valid("query").workspace).supervisor.freePort(c.req.param("id"));
4376
+ return c.json(result, statusForAction(result));
4315
4377
  }).get("/backups", describeRoute({
4316
4378
  tags: ["panel"],
4317
4379
  summary: "List the stored backup archives (local token required)",
@@ -4373,7 +4435,7 @@ function createControlRoute(deps) {
4373
4435
  });
4374
4436
  }).post("/backups/restore", describeRoute({
4375
4437
  tags: ["panel"],
4376
- summary: "Plan or apply a restore from a stored archive (local token required)",
4438
+ summary: "Plan or apply a restore from a stored archive or a file on this machine (local token required)",
4377
4439
  responses: {
4378
4440
  200: {
4379
4441
  description: "The plan",
@@ -4387,18 +4449,37 @@ function createControlRoute(deps) {
4387
4449
  assertLocalCall(c, "restore a backup");
4388
4450
  const confirm = c.req.query("confirm") === "true";
4389
4451
  const name = c.req.query("name");
4390
- if (name === void 0 || name.length === 0) throw new DetailedError("name is required", {
4452
+ const from = c.req.query("from");
4453
+ if (from !== void 0 && from.length > 0 && name !== void 0 && name.length > 0) throw new DetailedError("pass name or from, not both", {
4391
4454
  statusCode: 400,
4392
- code: "MISSING_NAME"
4455
+ code: "NAME_AND_FROM"
4393
4456
  });
4394
- const archive = deps.backups.resolve(name);
4395
- if (archive === null) throw new DetailedError(`no backup named "${name}"`, {
4396
- statusCode: 404,
4397
- code: "BACKUP_NOT_FOUND"
4457
+ if (from === void 0 || from.length === 0) {
4458
+ if (name === void 0 || name.length === 0) throw new DetailedError("name is required", {
4459
+ statusCode: 400,
4460
+ code: "MISSING_NAME"
4461
+ });
4462
+ const archive = deps.backups.resolve(name);
4463
+ if (archive === null) throw new DetailedError(`no backup named "${name}"`, {
4464
+ statusCode: 404,
4465
+ code: "BACKUP_NOT_FOUND"
4466
+ });
4467
+ const include = c.req.query("include")?.split(",").filter((part) => part.length > 0);
4468
+ const exclude = c.req.query("exclude")?.split(",").filter((part) => part.length > 0);
4469
+ return c.json(await deps.backups.restore(archive, {
4470
+ confirm,
4471
+ password: c.req.query("password"),
4472
+ include,
4473
+ exclude
4474
+ }));
4475
+ }
4476
+ if (!path.isAbsolute(from)) throw new DetailedError("from must be an absolute path — the panel would resolve a relative one against its own directory", {
4477
+ statusCode: 400,
4478
+ code: "FROM_NOT_ABSOLUTE"
4398
4479
  });
4399
4480
  const include = c.req.query("include")?.split(",").filter((part) => part.length > 0);
4400
4481
  const exclude = c.req.query("exclude")?.split(",").filter((part) => part.length > 0);
4401
- return c.json(await deps.backups.restore(archive, {
4482
+ return c.json(await deps.backups.restore(from, {
4402
4483
  confirm,
4403
4484
  password: c.req.query("password"),
4404
4485
  include,
@@ -7666,14 +7747,14 @@ function createMetricsRoute(deps) {
7666
7747
  lines.push(`# HELP ${name} ${help}`, `# TYPE ${name} gauge`, ...samples);
7667
7748
  };
7668
7749
  metric("hh_control_up", "Control plane is serving", ["hh_control_up 1"]);
7669
- metric("hh_servers_total", "Configured servers", [`hh_servers_total ${servers.length}`]);
7750
+ metric("hh_servers", "Configured servers", [`hh_servers ${servers.length}`]);
7670
7751
  metric("hh_server_up", "Server process is running", servers.map((server) => `hh_server_up{${labels(server)}} ${server.status === "running" ? 1 : 0}`));
7671
- metric("hh_server_restarts_total", "Restart attempts spent on the current crash sequence, reset by a start someone asked for", servers.map((server) => `hh_server_restarts_total{${labels(server)}} ${server.restarts}`));
7752
+ metric("hh_server_restarts", "Restart attempts spent on the current crash sequence; a start someone asked for resets it to 0", servers.map((server) => `hh_server_restarts{${labels(server)}} ${server.restarts}`));
7672
7753
  metric("hh_server_crashes_24h", "Crashes in the last 24 hours", servers.map((server) => `hh_server_crashes_24h{${labels(server)}} ${server.history.crashes}`));
7673
7754
  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)}`));
7674
7755
  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}`));
7675
- metric("hh_server_rss_bytes", "RSS of the server process tree", servers.filter((server) => server.resources?.rssBytes != null).map((server) => `hh_server_rss_bytes{${labels(server)}} ${server.resources.rssBytes}`));
7676
- metric("hh_server_cpu_percent", "CPU percent of the server process tree", servers.filter((server) => server.resources?.cpuPercent != null).map((server) => `hh_server_cpu_percent{${labels(server)}} ${server.resources.cpuPercent}`));
7756
+ metric("hh_server_rss_bytes", "RSS of the server process tree, or the summed containers of a compose entry", servers.filter((server) => server.resources?.rssBytes != null).map((server) => `hh_server_rss_bytes{${labels(server)}} ${server.resources.rssBytes}`));
7757
+ metric("hh_server_cpu_percent", "CPU percent of the server process tree, or the summed containers of a compose entry", servers.filter((server) => server.resources?.cpuPercent != null).map((server) => `hh_server_cpu_percent{${labels(server)}} ${server.resources.cpuPercent}`));
7677
7758
  if (host.sampledAt !== null) {
7678
7759
  metric("hh_host_disk_used_percent", "Disk usage percent per configured path", host.disks.map((disk) => `hh_host_disk_used_percent{mount="${labelValue(disk.path)}"} ${disk.usedPercent.toFixed(2)}`));
7679
7760
  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)}`]);
@@ -7953,7 +8034,7 @@ function parseWindowsCsv(text) {
7953
8034
  async function getClockTicks() {
7954
8035
  if (clockTicks !== null) return clockTicks;
7955
8036
  try {
7956
- const { stdout } = await execFileAsync$4("getconf", ["CLK_TCK"], { timeout: 2e3 });
8037
+ const { stdout } = await execFileAsync$5("getconf", ["CLK_TCK"], { timeout: 2e3 });
7957
8038
  const parsed = Number.parseInt(stdout.trim(), 10);
7958
8039
  clockTicks = Number.isFinite(parsed) && parsed > 0 ? parsed : 100;
7959
8040
  } catch {
@@ -8005,7 +8086,7 @@ async function readLinux() {
8005
8086
  return rows;
8006
8087
  }
8007
8088
  async function readPosix() {
8008
- const { stdout } = await execFileAsync$4("ps", ["-Ao", "pid=,ppid=,rss=,%cpu="], {
8089
+ const { stdout } = await execFileAsync$5("ps", ["-Ao", "pid=,ppid=,rss=,%cpu="], {
8009
8090
  timeout: 5e3,
8010
8091
  maxBuffer: 16777216
8011
8092
  });
@@ -8014,7 +8095,7 @@ async function readPosix() {
8014
8095
  async function readWindows() {
8015
8096
  const script = "Get-CimInstance Win32_Process | Select-Object ProcessId,ParentProcessId,WorkingSetSize,KernelModeTime,UserModeTime | ConvertTo-Csv -NoTypeInformation";
8016
8097
  try {
8017
- const { stdout } = await execFileAsync$4("powershell.exe", [
8098
+ const { stdout } = await execFileAsync$5("powershell.exe", [
8018
8099
  "-NoProfile",
8019
8100
  "-NonInteractive",
8020
8101
  "-Command",
@@ -8026,7 +8107,7 @@ async function readWindows() {
8026
8107
  return parseWindowsCsv(stdout);
8027
8108
  } catch {
8028
8109
  try {
8029
- const { stdout } = await execFileAsync$4("wmic", [
8110
+ const { stdout } = await execFileAsync$5("wmic", [
8030
8111
  "process",
8031
8112
  "get",
8032
8113
  "ProcessId,ParentProcessId,WorkingSetSize,KernelModeTime,UserModeTime",
@@ -8147,7 +8228,7 @@ async function processCarriesServerId(pid, serverId) {
8147
8228
  return false;
8148
8229
  }
8149
8230
  if (process.platform === "darwin") try {
8150
- const { stdout } = await execFileAsync$4("ps", [
8231
+ const { stdout } = await execFileAsync$5("ps", [
8151
8232
  "-p",
8152
8233
  String(pid),
8153
8234
  "-E",
@@ -8161,9 +8242,9 @@ async function processCarriesServerId(pid, serverId) {
8161
8242
  }
8162
8243
  return false;
8163
8244
  }
8164
- var execFileAsync$4, clockTicks, ProcessSampler;
8245
+ var execFileAsync$5, clockTicks, ProcessSampler;
8165
8246
  var init_proc = __esmMin((() => {
8166
- execFileAsync$4 = promisify(execFile);
8247
+ execFileAsync$5 = promisify(execFile);
8167
8248
  clockTicks = null;
8168
8249
  ProcessSampler = class {
8169
8250
  /**
@@ -8388,7 +8469,7 @@ async function processArgv(pid) {
8388
8469
  return null;
8389
8470
  }
8390
8471
  try {
8391
- const { stdout } = await execFileAsync$3("ps", [
8472
+ const { stdout } = await execFileAsync$4("ps", [
8392
8473
  "-p",
8393
8474
  String(pid),
8394
8475
  "-ww",
@@ -8459,7 +8540,7 @@ async function windowsProcessInfo(pid) {
8459
8540
  if (!windowsFilter.test(String(pid))) return null;
8460
8541
  try {
8461
8542
  const script = `Get-CimInstance Win32_Process -Filter "ProcessId=${pid}" | Select-Object CommandLine,ExecutablePath | ConvertTo-Csv -NoTypeInformation`;
8462
- const { stdout } = await execFileAsync$3("powershell", [
8543
+ const { stdout } = await execFileAsync$4("powershell", [
8463
8544
  "-NoProfile",
8464
8545
  "-NonInteractive",
8465
8546
  "-Command",
@@ -8510,10 +8591,10 @@ async function identifyHolders(serverId, spawn, pids) {
8510
8591
  }
8511
8592
  return found;
8512
8593
  }
8513
- var execFileAsync$3, windowsFilter;
8594
+ var execFileAsync$4, windowsFilter;
8514
8595
  var init_identity = __esmMin((() => {
8515
8596
  init_proc();
8516
- execFileAsync$3 = promisify(execFile);
8597
+ execFileAsync$4 = promisify(execFile);
8517
8598
  windowsFilter = /^\d+$/;
8518
8599
  }));
8519
8600
  //#endregion
@@ -8635,7 +8716,7 @@ async function processBirth(pid) {
8635
8716
  }
8636
8717
  if (process.platform === "win32") try {
8637
8718
  const script = `$p = Get-CimInstance Win32_Process -Filter "ProcessId=${pid}"; if ($p) { $p.CreationDate.ToFileTimeUtc() }`;
8638
- const { stdout } = await execFileAsync$2("powershell", [
8719
+ const { stdout } = await execFileAsync$3("powershell", [
8639
8720
  "-NoProfile",
8640
8721
  "-NonInteractive",
8641
8722
  "-Command",
@@ -8653,7 +8734,7 @@ async function processBirth(pid) {
8653
8734
  return null;
8654
8735
  }
8655
8736
  try {
8656
- const { stdout } = await execFileAsync$2("ps", [
8737
+ const { stdout } = await execFileAsync$3("ps", [
8657
8738
  "-p",
8658
8739
  String(pid),
8659
8740
  "-o",
@@ -8735,7 +8816,7 @@ function parseNetstatListeners(output, port) {
8735
8816
  }
8736
8817
  async function findDockerPortHolder(port) {
8737
8818
  try {
8738
- const { stdout } = await execFileAsync$2("docker", [
8819
+ const { stdout } = await execFileAsync$3("docker", [
8739
8820
  "ps",
8740
8821
  "--filter",
8741
8822
  `publish=${port}`,
@@ -8765,7 +8846,7 @@ async function findDockerPortHolder(port) {
8765
8846
  */
8766
8847
  async function releaseDockerPort(holder, timeoutMs = 2e4) {
8767
8848
  try {
8768
- await execFileAsync$2("docker", ["stop", holder.container], { timeout: timeoutMs });
8849
+ await execFileAsync$3("docker", ["stop", holder.container], { timeout: timeoutMs });
8769
8850
  return true;
8770
8851
  } catch {
8771
8852
  return false;
@@ -8773,7 +8854,7 @@ async function releaseDockerPort(holder, timeoutMs = 2e4) {
8773
8854
  }
8774
8855
  async function listPortHolders(port) {
8775
8856
  if (process.platform === "win32") try {
8776
- const { stdout } = await execFileAsync$2("netstat", [
8857
+ const { stdout } = await execFileAsync$3("netstat", [
8777
8858
  "-ano",
8778
8859
  "-p",
8779
8860
  "tcp"
@@ -8783,7 +8864,7 @@ async function listPortHolders(port) {
8783
8864
  return [];
8784
8865
  }
8785
8866
  try {
8786
- const { stdout } = await execFileAsync$2("lsof", [
8867
+ const { stdout } = await execFileAsync$3("lsof", [
8787
8868
  "-ti",
8788
8869
  `tcp:${port}`,
8789
8870
  "-sTCP:LISTEN"
@@ -8791,7 +8872,7 @@ async function listPortHolders(port) {
8791
8872
  return parsePids(stdout);
8792
8873
  } catch {}
8793
8874
  try {
8794
- const { stdout } = await execFileAsync$2("fuser", [`${port}/tcp`], { timeout: 3e3 });
8875
+ const { stdout } = await execFileAsync$3("fuser", [`${port}/tcp`], { timeout: 3e3 });
8795
8876
  return parsePids(stdout);
8796
8877
  } catch {
8797
8878
  return [];
@@ -8808,9 +8889,9 @@ async function listPortHolders(port) {
8808
8889
  function parsePids(stdout) {
8809
8890
  return [...new Set(stdout.split(/\s+/).map((entry) => Number.parseInt(entry, 10)).filter((pid) => Number.isInteger(pid) && pid > 0 && pid !== process.pid))];
8810
8891
  }
8811
- var execFileAsync$2, LINUX_HZ, FILETIME_UNIX_OFFSET_MS;
8892
+ var execFileAsync$3, LINUX_HZ, FILETIME_UNIX_OFFSET_MS;
8812
8893
  var init_port = __esmMin((() => {
8813
- execFileAsync$2 = promisify(execFile);
8894
+ execFileAsync$3 = promisify(execFile);
8814
8895
  LINUX_HZ = 100;
8815
8896
  FILETIME_UNIX_OFFSET_MS = 0xa9730b66800;
8816
8897
  }));
@@ -8905,7 +8986,7 @@ async function terminate(child, options) {
8905
8986
  */
8906
8987
  async function killTreeWindows(pid) {
8907
8988
  try {
8908
- await execFileAsync$1("taskkill", [
8989
+ await execFileAsync$2("taskkill", [
8909
8990
  "/pid",
8910
8991
  String(pid),
8911
8992
  "/T",
@@ -8972,11 +9053,11 @@ function waitForExit$1(child, timeoutMs) {
8972
9053
  child.once("exit", onExit);
8973
9054
  });
8974
9055
  }
8975
- var execFileAsync$1, WINDOWS_SHIM_EXTENSIONS;
9056
+ var execFileAsync$2, WINDOWS_SHIM_EXTENSIONS;
8976
9057
  var init_process = __esmMin((() => {
8977
9058
  init_paths();
8978
9059
  init_port();
8979
- execFileAsync$1 = promisify(execFile);
9060
+ execFileAsync$2 = promisify(execFile);
8980
9061
  WINDOWS_SHIM_EXTENSIONS = [
8981
9062
  ".exe",
8982
9063
  ".cmd",
@@ -12167,6 +12248,10 @@ function createSettingsRoute(deps) {
12167
12248
  statusCode: 400,
12168
12249
  code: "PROXY_EXPOSURE_BLOCKED"
12169
12250
  });
12251
+ if (patch.control?.auth?.enabled === false && requestIdentity(c, deps.auth).method !== "cookie") throw new DetailedError("switching authentication off needs a signed-in session, not an API token — sign in, or run `home-hosted set-password --clear` on the machine", {
12252
+ statusCode: 403,
12253
+ code: "SESSION_REQUIRED"
12254
+ });
12170
12255
  const scope = patch.backups?.schedule?.scope;
12171
12256
  if (scope !== void 0 && scope !== null) {
12172
12257
  const unknown = unknownBackupIds(scope.ids, deps.backups.view().entries);
@@ -12350,6 +12435,7 @@ var init_settings = __esmMin((() => {
12350
12435
  init_openapi$1();
12351
12436
  init_validator();
12352
12437
  init_workspace();
12438
+ init_auth();
12353
12439
  init_exposure();
12354
12440
  init_state$1();
12355
12441
  init_backup_scope();
@@ -13513,6 +13599,340 @@ function computeBackoff(attempt, options) {
13513
13599
  }
13514
13600
  var init_backoff = __esmMin((() => {}));
13515
13601
  //#endregion
13602
+ //#region src/providers/docker.ts
13603
+ /** `816KiB` -> bytes. Docker prints binary units for memory, and `0B` for a container that is not running. */
13604
+ function parseHumanBytes(value) {
13605
+ const match = /^([\d.]+)\s*([a-z]+)$/i.exec(value.trim());
13606
+ if (match === null) return null;
13607
+ const amount = Number.parseFloat(match[1]);
13608
+ const scale = BYTE_SCALES[match[2].toLowerCase()];
13609
+ if (scale === void 0 || !Number.isFinite(amount)) return null;
13610
+ return amount * scale;
13611
+ }
13612
+ /** `MemUsage` is `used / limit`; only the used part measures this stack. */
13613
+ function parseMemUsage(value) {
13614
+ const [used = ""] = value.split("/");
13615
+ return parseHumanBytes(used);
13616
+ }
13617
+ /** `99.61%` -> 99.61. `--` is docker's "no reading", which must not become a zero. */
13618
+ function parsePercent(value) {
13619
+ const match = /^([\d.]+)%$/.exec(value.trim());
13620
+ if (match === null) return null;
13621
+ const parsed = Number.parseFloat(match[1]);
13622
+ return Number.isFinite(parsed) ? parsed : null;
13623
+ }
13624
+ /** The containers docker reports, from the tab-separated `--format` above. */
13625
+ function parseDockerPs(text) {
13626
+ const rows = [];
13627
+ for (const line of text.split(/\r?\n/)) {
13628
+ if (line.trim().length === 0) continue;
13629
+ const [id = "", name = "", project = "", files = ""] = line.split(" ");
13630
+ if (id.trim().length === 0) continue;
13631
+ rows.push({
13632
+ id: id.trim(),
13633
+ name: name.trim(),
13634
+ project: project.trim().length > 0 ? project.trim() : null,
13635
+ configFiles: files.split(",").map((entry) => entry.trim()).filter((entry) => entry.length > 0)
13636
+ });
13637
+ }
13638
+ return rows;
13639
+ }
13640
+ /** Per-container readings from `docker stats --no-stream --format json`, keyed by container id. */
13641
+ function parseDockerStats(text) {
13642
+ const readings = /* @__PURE__ */ new Map();
13643
+ for (const line of text.split(/\r?\n/)) {
13644
+ if (line.trim().length === 0) continue;
13645
+ let raw;
13646
+ try {
13647
+ raw = JSON.parse(line);
13648
+ } catch {
13649
+ continue;
13650
+ }
13651
+ const parsed = statsLineSchema(raw);
13652
+ if (parsed instanceof type.errors) continue;
13653
+ const cpuPercent = parsePercent(parsed.CPUPerc);
13654
+ const rssBytes = parseMemUsage(parsed.MemUsage);
13655
+ const processes = Number.parseInt(parsed.PIDs, 10);
13656
+ if (cpuPercent === null || rssBytes === null || !Number.isInteger(processes)) continue;
13657
+ if (processes === 0) continue;
13658
+ readings.set(parsed.ID, {
13659
+ cpuPercent,
13660
+ rssBytes: Math.round(rssBytes),
13661
+ processes
13662
+ });
13663
+ }
13664
+ return readings;
13665
+ }
13666
+ /** Same file, on a platform whose paths are case-insensitive. */
13667
+ function samePath(left, right) {
13668
+ const a = path.resolve(left);
13669
+ const b = path.resolve(right);
13670
+ return process.platform === "win32" ? a.toLowerCase() === b.toLowerCase() : a === b;
13671
+ }
13672
+ /** The argv of the compose command this entry runs, or null when the entry is not docker-backed. */
13673
+ function composeArgv(command, args) {
13674
+ const name = path.basename(command).toLowerCase().replace(/\.exe$/, "");
13675
+ if (name === "docker-compose") return args;
13676
+ if (name !== "docker") return null;
13677
+ for (let index = 0; index < args.length; index++) {
13678
+ const arg = args[index];
13679
+ if (arg === "compose") return args.slice(index + 1);
13680
+ if (arg.startsWith("-")) {
13681
+ if (DOCKER_VALUE_FLAGS.has(arg) && !arg.includes("=")) index += 1;
13682
+ continue;
13683
+ }
13684
+ return null;
13685
+ }
13686
+ return null;
13687
+ }
13688
+ /**
13689
+ * The compose options before the subcommand, and where the subcommand starts.
13690
+ *
13691
+ * Compose requires its global options **before** the subcommand — it answers `unknown shorthand
13692
+ * flag: 'p'` for `up -p x` — so only this leading run can carry the project name or the file.
13693
+ */
13694
+ function parseComposeHead(args) {
13695
+ const result = {
13696
+ subcommandAt: args.length,
13697
+ projectName: null,
13698
+ files: [],
13699
+ projectDirectory: null
13700
+ };
13701
+ for (let index = 0; index < args.length; index++) {
13702
+ const arg = args[index];
13703
+ if (!arg.startsWith("-")) {
13704
+ result.subcommandAt = index;
13705
+ return result;
13706
+ }
13707
+ if (arg.startsWith("--") && arg.includes("=")) {
13708
+ const [flag, value = ""] = [arg.slice(0, arg.indexOf("=")), arg.slice(arg.indexOf("=") + 1)];
13709
+ if (flag === "--project-name" || flag === "--file" || flag === "--project-directory") {
13710
+ if (flag === "--project-name") result.projectName = value;
13711
+ else if (flag === "--file") result.files.push(value);
13712
+ else result.projectDirectory = value;
13713
+ }
13714
+ continue;
13715
+ }
13716
+ if (!arg.startsWith("--") && arg.length > 2 && COMPOSE_VALUE_FLAGS.has(arg.slice(0, 2))) {
13717
+ const value = arg.slice(2);
13718
+ if (arg.startsWith("-p")) result.projectName = value;
13719
+ else if (arg.startsWith("-f")) result.files.push(value);
13720
+ continue;
13721
+ }
13722
+ if (COMPOSE_VALUELESS_FLAGS.has(arg)) continue;
13723
+ if (!COMPOSE_VALUE_FLAGS.has(arg)) continue;
13724
+ const value = args[index + 1];
13725
+ if (value === void 0) return result;
13726
+ index += 1;
13727
+ if (arg === "-p" || arg === "--project-name") result.projectName = value;
13728
+ else if (arg === "-f" || arg === "--file") result.files.push(value);
13729
+ else if (arg === "--project-directory") result.projectDirectory = value;
13730
+ }
13731
+ return result;
13732
+ }
13733
+ /** The compose file compose would pick: the first known name here or in a parent directory. */
13734
+ function findComposeFile(from) {
13735
+ let dir = path.resolve(from);
13736
+ for (;;) {
13737
+ for (const name of COMPOSE_FILES) {
13738
+ const candidate = path.join(dir, name);
13739
+ try {
13740
+ if (fs.statSync(candidate).isFile()) return [candidate];
13741
+ } catch {}
13742
+ }
13743
+ const parent = path.dirname(dir);
13744
+ if (parent === dir) return [];
13745
+ dir = parent;
13746
+ }
13747
+ }
13748
+ /**
13749
+ * The compose project an entry runs, from evidence in its own config: the command it spawns, its
13750
+ * argv, its cwd and its environment. `null` means "sample the process tree", which is the right
13751
+ * answer for every entry this cannot attribute honestly — see the module comment for the limits.
13752
+ */
13753
+ function composeTarget(input) {
13754
+ const composeArgs = composeArgv(input.command, input.args);
13755
+ if (composeArgs === null) return null;
13756
+ const head = parseComposeHead(composeArgs);
13757
+ const project = head.projectName ?? (input.env?.COMPOSE_PROJECT_NAME !== void 0 && input.env.COMPOSE_PROJECT_NAME.length > 0 ? input.env.COMPOSE_PROJECT_NAME : null);
13758
+ const directory = head.projectDirectory === null ? input.cwd : path.resolve(input.cwd, head.projectDirectory);
13759
+ const configFiles = head.files.length > 0 ? head.files.map((file) => path.resolve(directory, file)) : findComposeFile(directory);
13760
+ if (project === null && configFiles.length === 0) return null;
13761
+ return {
13762
+ key: project === null ? `files:${configFiles.join("\0")}` : `project:${project}`,
13763
+ project,
13764
+ configFiles
13765
+ };
13766
+ }
13767
+ /**
13768
+ * The containers belonging to one target, or `null` when that cannot be decided.
13769
+ *
13770
+ * `null` is the ambiguity refusal: two projects sharing a compose file can only be told apart by an
13771
+ * explicit project name, so picking one would report another stack's CPU and RSS as this entry's.
13772
+ */
13773
+ function attributeContainers(target, rows) {
13774
+ if (target.project !== null) return rows.filter((row) => row.project === target.project);
13775
+ const matched = rows.filter((row) => row.configFiles.some((file) => target.configFiles.some((own) => samePath(file, own))));
13776
+ return new Set(matched.map((row) => row.project)).size <= 1 ? matched : null;
13777
+ }
13778
+ /**
13779
+ * The sum over one project's containers.
13780
+ *
13781
+ * Exported so the arithmetic is testable against the shapes docker actually prints; the class below
13782
+ * only decides when to spawn. `null` for no containers, and for a listed container without a
13783
+ * reading — an under-report is the one direction a memory ceiling must not miss.
13784
+ */
13785
+ function sumContainers(rows, readings) {
13786
+ if (rows.length === 0) return null;
13787
+ let cpuPercent = 0;
13788
+ let rssBytes = 0;
13789
+ let processes = 0;
13790
+ for (const row of rows) {
13791
+ const reading = readings.get(row.id);
13792
+ if (reading === void 0) return null;
13793
+ cpuPercent += reading.cpuPercent;
13794
+ rssBytes += reading.rssBytes;
13795
+ processes += reading.processes;
13796
+ }
13797
+ return {
13798
+ cpuPercent: Math.round(cpuPercent * 10) / 10,
13799
+ rssBytes: Math.round(rssBytes),
13800
+ processes,
13801
+ containers: rows.length
13802
+ };
13803
+ }
13804
+ var execFileAsync$1, DOCKER_CACHE_MS, COMPOSE_FILES, COMPOSE_VALUE_FLAGS, COMPOSE_VALUELESS_FLAGS, DOCKER_VALUE_FLAGS, PS_FORMAT, EMPTY, statsLineSchema, BYTE_SCALES, DockerMetrics;
13805
+ var init_docker = __esmMin((() => {
13806
+ execFileAsync$1 = promisify(execFile);
13807
+ DOCKER_CACHE_MS = 1e4;
13808
+ COMPOSE_FILES = [
13809
+ "compose.yaml",
13810
+ "compose.yml",
13811
+ "docker-compose.yaml",
13812
+ "docker-compose.yml"
13813
+ ];
13814
+ COMPOSE_VALUE_FLAGS = /* @__PURE__ */ new Set([
13815
+ "-p",
13816
+ "--project-name",
13817
+ "-f",
13818
+ "--file",
13819
+ "--project-directory",
13820
+ "--env-file",
13821
+ "--profile",
13822
+ "--ansi",
13823
+ "--progress",
13824
+ "--parallel"
13825
+ ]);
13826
+ COMPOSE_VALUELESS_FLAGS = /* @__PURE__ */ new Set([
13827
+ "--compatibility",
13828
+ "--dry-run",
13829
+ "--no-ansi",
13830
+ "--verbose",
13831
+ "-h",
13832
+ "--help"
13833
+ ]);
13834
+ DOCKER_VALUE_FLAGS = /* @__PURE__ */ new Set([
13835
+ "-c",
13836
+ "--context",
13837
+ "-H",
13838
+ "--host",
13839
+ "-l",
13840
+ "--log-level",
13841
+ "--config"
13842
+ ]);
13843
+ PS_FORMAT = "{{.ID}} {{.Names}} {{.Label \"com.docker.compose.project\"}} {{.Label \"com.docker.compose.project.config_files\"}}";
13844
+ EMPTY = /* @__PURE__ */ new Map();
13845
+ statsLineSchema = type({
13846
+ "CPUPerc": "string",
13847
+ "ID": "string",
13848
+ "MemUsage": "string",
13849
+ "PIDs": "string",
13850
+ "+": "ignore"
13851
+ });
13852
+ BYTE_SCALES = {
13853
+ b: 1,
13854
+ kb: 1e3,
13855
+ kib: 1024,
13856
+ mb: 1e3 ** 2,
13857
+ mib: 1024 ** 2,
13858
+ gb: 1e3 ** 3,
13859
+ gib: 1024 ** 3,
13860
+ tb: 1e3 ** 4,
13861
+ tib: 1024 ** 4
13862
+ };
13863
+ DockerMetrics = class {
13864
+ cache = null;
13865
+ refreshing = null;
13866
+ /**
13867
+ * The last completed readings, and a refresh started when they are stale.
13868
+ *
13869
+ * Deliberately synchronous: the spawn takes seconds, and awaiting it here would stretch the
13870
+ * supervisor tick that publishes the whole state frame. A fresh reading lands on a later tick.
13871
+ */
13872
+ readings(targets, now = Date.now()) {
13873
+ if (!(this.cache !== null && now >= this.cache.at && now - this.cache.at < DOCKER_CACHE_MS) && targets.length > 0 && this.refreshing === null) this.refreshing = this.refresh(targets, now).finally(() => {
13874
+ this.refreshing = null;
13875
+ });
13876
+ return this.cache?.byKey ?? EMPTY;
13877
+ }
13878
+ /** Resolves once the refresh in flight, if any, has finished. */
13879
+ async settle() {
13880
+ await this.refreshing;
13881
+ }
13882
+ /** One listing and one batched stats call; replaces the cache only with a complete answer. */
13883
+ async refresh(targets, now = Date.now()) {
13884
+ const byKey = /* @__PURE__ */ new Map();
13885
+ try {
13886
+ const rows = parseDockerPs((await execFileAsync$1("docker", [
13887
+ "ps",
13888
+ "--filter",
13889
+ "label=com.docker.compose.project",
13890
+ "--format",
13891
+ PS_FORMAT
13892
+ ], {
13893
+ timeout: 5e3,
13894
+ maxBuffer: 4194304
13895
+ })).stdout);
13896
+ const perTarget = /* @__PURE__ */ new Map();
13897
+ const ids = /* @__PURE__ */ new Set();
13898
+ for (const target of targets) {
13899
+ const matched = attributeContainers(target, rows);
13900
+ if (matched === null || matched.length === 0) continue;
13901
+ perTarget.set(target.key, matched);
13902
+ for (const row of matched) ids.add(row.id);
13903
+ }
13904
+ if (ids.size === 0) {
13905
+ this.cache = {
13906
+ at: now,
13907
+ byKey
13908
+ };
13909
+ return;
13910
+ }
13911
+ const readings = parseDockerStats((await execFileAsync$1("docker", [
13912
+ "stats",
13913
+ "--no-stream",
13914
+ "--format",
13915
+ "json",
13916
+ ...ids
13917
+ ], {
13918
+ timeout: 15e3,
13919
+ maxBuffer: 8388608
13920
+ })).stdout);
13921
+ for (const [key, matched] of perTarget) {
13922
+ const summed = sumContainers(matched, readings);
13923
+ if (summed !== null) byKey.set(key, summed);
13924
+ }
13925
+ } catch {
13926
+ byKey.clear();
13927
+ }
13928
+ this.cache = {
13929
+ at: now,
13930
+ byKey
13931
+ };
13932
+ }
13933
+ };
13934
+ }));
13935
+ //#endregion
13516
13936
  //#region src/providers/entry-state.ts
13517
13937
  /**
13518
13938
  * The small slice of a server's runtime the panel has to remember across its own
@@ -14130,6 +14550,7 @@ var init_supervisor = __esmMin((() => {
14130
14550
  init_runtime();
14131
14551
  init_template();
14132
14552
  init_backup_hook();
14553
+ init_docker();
14133
14554
  init_entry_state();
14134
14555
  init_health_check();
14135
14556
  init_identity();
@@ -14153,6 +14574,8 @@ var init_supervisor = __esmMin((() => {
14153
14574
  hub;
14154
14575
  options;
14155
14576
  sampler = new ProcessSampler();
14577
+ /** Container readings for docker-backed entries, batched across the workspace. */
14578
+ docker = new DockerMetrics();
14156
14579
  /**
14157
14580
  * Live output of persistent entries. A normal entry's logs arrive down the pipe the
14158
14581
  * panel owns; a persistent one's are written by its nanny, so they are read back.
@@ -14326,6 +14749,8 @@ var init_supervisor = __esmMin((() => {
14326
14749
  ok: false,
14327
14750
  error: `server "${id}" is stopping`
14328
14751
  };
14752
+ const resolved = this.resolveSpawn(entry);
14753
+ this.detectCompose(entry, resolved);
14329
14754
  entry.lastError = null;
14330
14755
  entry.status = "starting";
14331
14756
  this.resetHealth(entry);
@@ -14354,7 +14779,7 @@ var init_supervisor = __esmMin((() => {
14354
14779
  error: conflict.error
14355
14780
  };
14356
14781
  if (conflict.kind === "adopt") return this.adoptEntry(entry, conflict.pid, `a detached restart of this entry is already serving port ${entry.config.port}`);
14357
- const started = this.spawnEntry(entry);
14782
+ const started = this.spawnEntry(entry, resolved);
14358
14783
  if (entry.pendingLoad !== null) this.runPendingLoad(entry);
14359
14784
  return started;
14360
14785
  } finally {
@@ -14805,6 +15230,7 @@ var init_supervisor = __esmMin((() => {
14805
15230
  responseMs: null,
14806
15231
  resources: null,
14807
15232
  resourcesSampledAt: 0,
15233
+ compose: null,
14808
15234
  historyCache: null
14809
15235
  };
14810
15236
  }
@@ -15129,6 +15555,23 @@ var init_supervisor = __esmMin((() => {
15129
15555
  else if (code !== null) this.log(entry, "system", `bootstrap exited with code ${code} — continuing anyway`);
15130
15556
  }
15131
15557
  /**
15558
+ * Whether this entry runs a compose stack, from what it would actually spawn.
15559
+ *
15560
+ * `command`/`args` are read through the same `resolveSpawn` the spawn itself uses, so the
15561
+ * detection and the process cannot disagree about the argv. A `null` result is the common case:
15562
+ * every entry that is not `docker compose` keeps the process-tree sample, including one whose
15563
+ * shell happens to run docker — that is not detectable, and guessing would attribute a
15564
+ * stranger's containers to this entry. See `src/providers/docker.ts` for the full limits.
15565
+ */
15566
+ detectCompose(entry, resolved) {
15567
+ entry.compose = composeTarget({
15568
+ command: resolved.command,
15569
+ args: resolved.args,
15570
+ cwd: resolved.cwd,
15571
+ env: resolved.env
15572
+ });
15573
+ }
15574
+ /**
15132
15575
  * Everything `spawn` needs for an entry: the resolved image, the expanded argv, the
15133
15576
  * cwd and the environment. The argv is also what the preflight recognizes the entry's
15134
15577
  * own detached successor by, so spawn and identification must never resolve it twice
@@ -15172,11 +15615,11 @@ var init_supervisor = __esmMin((() => {
15172
15615
  loggedArgs: resolveTemplates(entry.config.args, vars)
15173
15616
  };
15174
15617
  }
15175
- spawnEntry(entry) {
15176
- return entry.config.persistent ? this.spawnNanny(entry) : this.spawnDirect(entry);
15618
+ spawnEntry(entry, resolved) {
15619
+ return entry.config.persistent ? this.spawnNanny(entry, resolved) : this.spawnDirect(entry, resolved);
15177
15620
  }
15178
- spawnDirect(entry) {
15179
- const { command, args, env, cwd, loggedArgs } = this.resolveSpawn(entry);
15621
+ spawnDirect(entry, resolved) {
15622
+ const { command, args, env, cwd, loggedArgs } = resolved;
15180
15623
  this.log(entry, "system", `start: ${command} ${loggedArgs.join(" ")}`);
15181
15624
  let child;
15182
15625
  try {
@@ -15205,8 +15648,8 @@ var init_supervisor = __esmMin((() => {
15205
15648
  * event drives the normal lifecycle (backoff, history, notifications) — while the
15206
15649
  * real exit cause is read back from the state file the nanny leaves behind.
15207
15650
  */
15208
- spawnNanny(entry) {
15209
- const { command, args, env, cwd, loggedArgs } = this.resolveSpawn(entry);
15651
+ spawnNanny(entry, resolved) {
15652
+ const { command, args, env, cwd, loggedArgs } = resolved;
15210
15653
  this.log(entry, "system", `start (persistent): ${command} ${loggedArgs.join(" ")}`);
15211
15654
  const entryPoint = nannyEntryPoint();
15212
15655
  if (entryPoint.length === 0) return this.failSpawn(entry, "cannot locate this CLI to start a persistent entry");
@@ -15575,14 +16018,32 @@ var init_supervisor = __esmMin((() => {
15575
16018
  }
15576
16019
  this.publishState();
15577
16020
  }
15578
- /** One scan of /proc covers every server; only live processes are sampled. */
16021
+ /**
16022
+ * One scan of /proc covers every server; only live processes are sampled.
16023
+ *
16024
+ * A docker-backed entry is measured through docker instead, and the two paths are exclusive: its
16025
+ * containers are not descendants of the wrapper, so the tree sample would report the wrapper —
16026
+ * `cpuPercent: 0` for a stack burning a core, and an RSS a memory ceiling can never trip. When
16027
+ * docker has no reading for it (no running container, or docker unreachable) the tree sample is
16028
+ * kept, because it is at least true of the process the panel did start.
16029
+ */
15579
16030
  async sampleResources(now) {
15580
16031
  const due = [...this.entries.values()].filter((entry) => entry.pid !== null && (entry.child !== null || entry.adopted) && now - entry.resourcesSampledAt >= RESOURCE_SAMPLE_INTERVAL_MS);
15581
16032
  if (due.length === 0) return;
15582
16033
  for (const entry of due) entry.resourcesSampledAt = now;
16034
+ const composeTargets = due.flatMap((entry) => entry.compose === null ? [] : [entry.compose]);
16035
+ const containerReadings = this.docker.readings(composeTargets, now);
15583
16036
  try {
15584
16037
  const samples = await this.sampler.sampleMany(due.map((entry) => entry.pid));
15585
- for (const entry of due) entry.resources = samples.get(entry.pid) ?? null;
16038
+ for (const entry of due) {
16039
+ const summed = entry.compose === null ? void 0 : containerReadings.get(entry.compose.key);
16040
+ entry.resources = summed === void 0 ? samples.get(entry.pid) ?? null : {
16041
+ cpuPercent: summed.cpuPercent,
16042
+ rssBytes: summed.rssBytes,
16043
+ processes: summed.processes,
16044
+ sampledAt: now
16045
+ };
16046
+ }
15586
16047
  } catch {}
15587
16048
  }
15588
16049
  async probeEntry(entry, now) {
@@ -15635,11 +16096,19 @@ var init_supervisor = __esmMin((() => {
15635
16096
  entry.probing = false;
15636
16097
  }
15637
16098
  }
16099
+ /**
16100
+ * The memory ceiling, on the numbers the entry's sample actually carries.
16101
+ *
16102
+ * For a docker-backed entry `resources` is the summed RSS of its containers, so this fires on
16103
+ * their growth — the wrapper never grows, which is why the check could never fire for a leaking
16104
+ * container before. The sentence names what was measured, because "process tree" would send
16105
+ * someone to `ps` for a figure that lives in `docker stats`.
16106
+ */
15638
16107
  async enforceMemoryLimit(entry) {
15639
16108
  const limit = entry.config.resources.maxRssBytes;
15640
16109
  const rss = entry.resources?.rssBytes ?? null;
15641
16110
  if (limit <= 0 || rss === null || entry.child === null || entry.status !== "running" || rss <= limit) return false;
15642
- const detail = `process tree uses ${Math.round(rss / 1024 / 1024)}MB, over the ${Math.round(limit / 1024 / 1024)}MB limit`;
16111
+ const detail = `${entry.compose === null ? "process tree" : "containers"} use ${Math.round(rss / 1024 / 1024)}MB, over the ${Math.round(limit / 1024 / 1024)}MB limit`;
15643
16112
  this.log(entry, "system", `${detail} — restarting`);
15644
16113
  this.options.history.record(entry.config.id, {
15645
16114
  type: "forced-restart",
@@ -15984,6 +16453,38 @@ function isSafeArchiveEntry(entry) {
15984
16453
  if (!ALLOWED_ROOTS.has(segments[0])) return false;
15985
16454
  return segments.every((segment) => /^[\w.-]+$/.test(segment));
15986
16455
  }
16456
+ async function admitArchive(archivePath) {
16457
+ if (!isZipArchive(archivePath)) return {
16458
+ ok: false,
16459
+ error: "the archive is not a home-hosted backup (a zip file was expected)"
16460
+ };
16461
+ let entries;
16462
+ try {
16463
+ entries = await listZip(archivePath);
16464
+ } catch (error) {
16465
+ return {
16466
+ ok: false,
16467
+ error: `the archive could not be read: ${errorMessage(error)}`
16468
+ };
16469
+ }
16470
+ if (entries.length === 0) return {
16471
+ ok: false,
16472
+ error: "the archive is empty"
16473
+ };
16474
+ if (entries.length > 1e5) return {
16475
+ ok: false,
16476
+ error: "the archive has too many entries"
16477
+ };
16478
+ const invalid = entries.filter((entry) => !isSafeArchiveEntry(entry.name));
16479
+ if (invalid.length > 0) return {
16480
+ ok: false,
16481
+ error: `the archive contains unexpected entries (e.g. ${invalid.slice(0, 3).map((entry) => entry.name).join(", ")})`
16482
+ };
16483
+ return {
16484
+ ok: true,
16485
+ entries
16486
+ };
16487
+ }
15987
16488
  /** True when `child` is `parent` itself or lives underneath it. */
15988
16489
  function isInside(parent, child) {
15989
16490
  if (parent === child) return true;
@@ -16560,40 +17061,20 @@ var init_backups = __esmMin((() => {
16560
17061
  createdWorkspaces: [],
16561
17062
  replacedUnderRunning: []
16562
17063
  };
16563
- if (!isZipArchive(archivePath)) return {
17064
+ const admitted = await admitArchive(archivePath);
17065
+ if (!admitted.ok) return {
16564
17066
  ...plan,
16565
- error: "the archive is not a home-hosted backup (a zip file was expected)"
17067
+ error: admitted.error
16566
17068
  };
17069
+ const entries = admitted.entries;
16567
17070
  const staging = path.join(this.resolveDir(), `.restore-${Date.now()}`);
16568
17071
  try {
16569
- let entries;
16570
- try {
16571
- entries = await listZip(archivePath);
16572
- } catch (error) {
16573
- return {
16574
- ...plan,
16575
- error: `the archive could not be read: ${errorMessage(error)}`
16576
- };
16577
- }
16578
17072
  plan.encrypted = entries.some((entry) => entry.encrypted);
16579
17073
  if (plan.encrypted && password === null) return {
16580
17074
  ...plan,
16581
17075
  needsPassword: true,
16582
17076
  error: "this backup is password-protected"
16583
17077
  };
16584
- if (entries.length === 0) return {
16585
- ...plan,
16586
- error: "the archive is empty"
16587
- };
16588
- if (entries.length > 1e5) return {
16589
- ...plan,
16590
- error: "the archive has too many entries"
16591
- };
16592
- const invalid = entries.filter((entry) => !isSafeArchiveEntry(entry.name));
16593
- if (invalid.length > 0) return {
16594
- ...plan,
16595
- error: `the archive contains unexpected entries (e.g. ${invalid.slice(0, 3).map((entry) => entry.name).join(", ")})`
16596
- };
16597
17078
  fs.mkdirSync(staging, { recursive: true });
16598
17079
  const extracted = await extractZip(archivePath, staging, {
16599
17080
  names: entries.map((entry) => entry.name),
@@ -20730,11 +21211,20 @@ var init_down = __esmMin((() => {
20730
21211
  //#endregion
20731
21212
  //#region src/cli/server.ts
20732
21213
  var server_exports = /* @__PURE__ */ __exportAll({
21214
+ freePortCommand: () => freePortCommand,
21215
+ runFreePort: () => runFreePort,
20733
21216
  runServerAction: () => runServerAction,
20734
21217
  startCommand: () => startCommand,
20735
21218
  stopCommand: () => stopCommand
20736
21219
  });
20737
- async function runServerAction(action, id, workspace) {
21220
+ /**
21221
+ * Asks the running panel to do one thing to one entry, and turns its answer into an exit code.
21222
+ *
21223
+ * Shared by every per-server command so the "the panel is not running", "it does not know this
21224
+ * command" and "it refused, here is why" sentences exist once. Returns the body, so a caller can
21225
+ * say more about what happened; a refusal never returns at all.
21226
+ */
21227
+ async function callServerAction(action, id, workspace, options = {}) {
20738
21228
  const { clearRuntime, readRuntime, requestControl, runtimeIsAlive, runtimeIsGone } = await Promise.resolve().then(() => (init_daemon(), daemon_exports));
20739
21229
  const runtime = readRuntime();
20740
21230
  if (runtime === null || !await runtimeIsAlive(runtime)) {
@@ -20747,14 +21237,65 @@ async function runServerAction(action, id, workspace) {
20747
21237
  const body = answer.body ?? {};
20748
21238
  if (body.ok !== true) {
20749
21239
  const reason = body.error ?? body.message;
21240
+ if (options.tolerateFree === true && reason !== void 0 && NOTHING_LISTENING.test(reason)) return {
21241
+ ...body,
21242
+ ok: true
21243
+ };
20750
21244
  if (reason !== void 0) fail(reason);
20751
21245
  if (answer.status === 404) fail(`the panel on ${runtime.url} is home-hosted ${runtime.version}, which does not know this command — restart it on this release`);
20752
21246
  fail(`the panel answered ${answer.status}`);
20753
21247
  }
21248
+ return body;
21249
+ }
21250
+ /** `workspace/id`, or `id` in the default workspace. */
21251
+ function label(id, workspace) {
21252
+ return workspace === void 0 ? id : `${workspace}/${id}`;
21253
+ }
21254
+ async function runServerAction(action, id, workspace) {
21255
+ await callServerAction(action, id, workspace);
20754
21256
  const verb = action === "start" ? "started" : action === "stop" ? "stopped" : "restarted";
20755
- process.stdout.write(`${green(verb)} ${workspace === void 0 ? "" : `${workspace}/`}${id}\n`);
21257
+ process.stdout.write(`${green(verb)} ${label(id, workspace)}\n`);
21258
+ }
21259
+ /**
21260
+ * `free-port` — ask whatever holds this entry's port to stop, then say what actually happened.
21261
+ *
21262
+ * The panel refuses what it supervises rather than signalling it, so a success is not simply
21263
+ * "ok": the report distinguishes the pids that left, the ones that ignored SIGTERM and had to be
21264
+ * killed, and any this panel owns that were deliberately left alone.
21265
+ */
21266
+ async function runFreePort(id, workspace, options = {}) {
21267
+ const body = await callServerAction("free-port", id, workspace, { tolerateFree: options.tolerateFree });
21268
+ const port = body.port ?? null;
21269
+ const where = label(id, workspace);
21270
+ const terminated = body.terminated ?? [];
21271
+ const forced = body.forced ?? [];
21272
+ const skipped = body.skipped ?? [];
21273
+ const parts = [];
21274
+ if (terminated.length > 0) parts.push(`pid ${terminated.join(", ")} stopped`);
21275
+ if (forced.length > 0) parts.push(`pid ${forced.join(", ")} had to be killed`);
21276
+ if (skipped.length > 0) parts.push(`pid ${skipped.join(", ")} left alone (this panel supervises it)`);
21277
+ const idle = terminated.length === 0 && forced.length === 0 && skipped.length === 0;
21278
+ if (port === null || idle) {
21279
+ process.stdout.write(`${green("port is free")} ${where}${port === null ? "" : ` on ${port}`}\n`);
21280
+ return;
21281
+ }
21282
+ const detail = idle ? "nothing was listening" : parts.join("; ");
21283
+ if (body.free === true) {
21284
+ process.stdout.write(`${green("freed")} port ${port} for ${where} — ${detail}\n`);
21285
+ return;
21286
+ }
21287
+ fail(`port ${port} is still in use for ${where} — ${detail}`);
20756
21288
  }
21289
+ /**
21290
+ * `start`, and `start --free-port`.
21291
+ *
21292
+ * `--free-port` frees the port first, then starts — the one sequence a person actually wants after
21293
+ * reading "port 4010 is already in use". It is a flag on `start` rather than only a command because
21294
+ * the two calls it saves are the common case; `free-port` on its own still exists for when the intent
21295
+ * is only to unblock a port.
21296
+ */
20757
21297
  function serverCommand(action) {
21298
+ const withFreePort = action === "start";
20758
21299
  return defineCommand({
20759
21300
  meta: { name: action },
20760
21301
  args: {
@@ -20767,18 +21308,45 @@ function serverCommand(action) {
20767
21308
  type: "string",
20768
21309
  alias: "w",
20769
21310
  description: "the workspace to act in (default: the panel's default workspace)"
20770
- }
21311
+ },
21312
+ ...withFreePort ? { "free-port": {
21313
+ type: "boolean",
21314
+ description: "free the port first, then start (what the panel's Free port button does)"
21315
+ } } : {}
20771
21316
  },
20772
21317
  run: async ({ args }) => {
20773
21318
  const id = typeof args.id === "string" ? args.id.trim() : "";
20774
21319
  if (id.length === 0) fail(`${action} needs a server id — see \`${invocation()} status\` or the workspace's servers.config.json`);
20775
- await runServerAction(action, id, typeof args.workspace === "string" ? args.workspace.trim() : void 0);
21320
+ const workspace = typeof args.workspace === "string" ? args.workspace.trim() : void 0;
21321
+ if (withFreePort && args["free-port"] === true) await runFreePort(id, workspace, { tolerateFree: true });
21322
+ await runServerAction(action, id, workspace);
20776
21323
  }
20777
21324
  });
20778
21325
  }
20779
- var startCommand, stopCommand;
21326
+ var NOTHING_LISTENING, freePortCommand, startCommand, stopCommand;
20780
21327
  var init_server = __esmMin((() => {
20781
21328
  init_io();
21329
+ NOTHING_LISTENING = /^nothing is listening on port \d+ any more$/;
21330
+ freePortCommand = defineCommand({
21331
+ meta: { name: "free-port" },
21332
+ args: {
21333
+ id: {
21334
+ type: "positional",
21335
+ required: false,
21336
+ description: "the server whose port should be freed"
21337
+ },
21338
+ workspace: {
21339
+ type: "string",
21340
+ alias: "w",
21341
+ description: "the workspace to act in (default: the panel's default workspace)"
21342
+ }
21343
+ },
21344
+ run: async ({ args }) => {
21345
+ const id = typeof args.id === "string" ? args.id.trim() : "";
21346
+ if (id.length === 0) fail(`free-port needs a server id — see \`${invocation()} status\` or the workspace's servers.config.json`);
21347
+ await runFreePort(id, typeof args.workspace === "string" ? args.workspace.trim() : void 0);
21348
+ }
21349
+ });
20782
21350
  startCommand = serverCommand("start");
20783
21351
  stopCommand = serverCommand("stop");
20784
21352
  }));
@@ -21135,7 +21703,8 @@ async function runSetToken(generate, clear) {
21135
21703
  }
21136
21704
  process.stdout.write(`Use it from a script or an agent:\n`);
21137
21705
  process.stdout.write(` ${bold(`curl -H "Authorization: Bearer ${generate ? token : "<token>"}" ${base}/api/state`)}\n`);
21138
- process.stdout.write(`${dim("It needs no restart, outlives sessions, and holds the same access as a signed-in browser.")}\n`);
21706
+ process.stdout.write(`${dim("It needs no restart and outlives sessions, and it holds the same access as a signed-in browser — except clearing the panel password, which a token may not do.")}\n`);
21707
+ process.stdout.write(`${dim("Changing the password does NOT revoke it: `set-password` drops sessions and leaves the token working. Rotate with this command if it may have leaked.")}\n`);
21139
21708
  process.stdout.write(`${dim("Remove it any time with: home-hosted set-token --clear")}\n`);
21140
21709
  if (store.usingDefaultPassword) process.stdout.write(`${dim("The panel password is still the default — change it before the panel is reachable beyond loopback.")}\n`);
21141
21710
  }
@@ -22323,9 +22892,10 @@ async function availableRowsFromDisk(action, suffix) {
22323
22892
  const { service } = await offlineBackup();
22324
22893
  await service.warm();
22325
22894
  if (action === "create") return service.view().entries;
22326
- const name = new URLSearchParams(suffix.startsWith("?") ? suffix.slice(1) : suffix).get("name");
22327
- if (name === null || name.length === 0) return [];
22328
- const archive = service.resolve(name);
22895
+ const query = new URLSearchParams(suffix.startsWith("?") ? suffix.slice(1) : suffix);
22896
+ const from = query.get("from");
22897
+ const name = query.get("name");
22898
+ const archive = from !== null && from.length > 0 ? fs.existsSync(from) && fs.statSync(from).isFile() ? from : null : name === null || name.length === 0 ? null : service.resolve(name);
22329
22899
  if (archive === null) return [];
22330
22900
  return ((await service.restore(archive, { confirm: false })).items ?? []).filter((item) => item.selected !== false);
22331
22901
  } catch {
@@ -22541,12 +23111,40 @@ function restoreNotes(plan) {
22541
23111
  }
22542
23112
  async function runBackupRestore(options) {
22543
23113
  const scope = options.scope;
22544
- const service = await usesPanel() ? null : (await offlineBackup()).service;
23114
+ const online = await usesPanel();
23115
+ /**
23116
+ * What this restore reads from: an archive **name** in the backups directory, or a **path**.
23117
+ *
23118
+ * A name is an allowlist entry, which is why it is the default. `--from` is for the blank host
23119
+ * where the archive is on a USB stick: it names the file to read, not a directory to write in.
23120
+ * The two are refused together rather than one quietly winning — on the one command that
23121
+ * overwrites live data, a guess about which archive was meant is the wrong default.
23122
+ *
23123
+ * The path is resolved against *this* process's directory; the panel would resolve a relative
23124
+ * one against its own cwd, which is a different directory and so a different file.
23125
+ */
23126
+ const source = options.from !== void 0 ? {
23127
+ kind: "from",
23128
+ path: resolveUserPath(options.from)
23129
+ } : {
23130
+ kind: "name",
23131
+ name: options.name ?? ""
23132
+ };
23133
+ /** What to call it in the plan and the result: the file it read, name or path. */
23134
+ const label = source.kind === "from" ? path.basename(source.path) : source.name;
23135
+ if (source.kind === "from" && (!fs.existsSync(source.path) || !fs.statSync(source.path).isFile())) fail(`no file at ${source.path} — \`--from\` takes the path to an archive on this machine`);
23136
+ const service = online ? null : (await offlineBackup()).service;
22545
23137
  if (service !== null) await service.warm();
22546
23138
  const plan = await (async () => {
22547
23139
  if (service !== null) {
22548
- const archive = service.resolve(options.name);
22549
- if (archive === null) fail(`no backup named "${options.name}" in ${service.directory} — a restore takes the archive's file name, not a path; copy it there first (\`${invocation()} backup list\` shows what is there)`);
23140
+ if (source.kind === "from") return await service.restore(source.path, {
23141
+ confirm: false,
23142
+ password: options.password,
23143
+ include: scope.kind === "include" ? scope.ids : void 0,
23144
+ exclude: options.exclude
23145
+ });
23146
+ const archive = service.resolve(source.name);
23147
+ if (archive === null) fail(`no backup named "${source.name}" in ${service.directory} — a restore takes the archive's file name, not a path; pass --from <path> to read the file where it is, or copy it into that directory (\`${invocation()} backup list\` shows what is there)`);
22550
23148
  return await service.restore(archive, {
22551
23149
  confirm: false,
22552
23150
  password: options.password,
@@ -22556,7 +23154,7 @@ async function runBackupRestore(options) {
22556
23154
  }
22557
23155
  const runtime = await livePanel();
22558
23156
  if (runtime === null) fail(`the control panel is not answering — try again once it is up`);
22559
- const base = restoreQuery(options, scope);
23157
+ const base = restoreQuery(source, options, scope);
22560
23158
  const answer = await runtime.request(runtime, `/_hh/backups/restore${suffixOf(base)}`, 12e4);
22561
23159
  if (answer === null) fail(`the control panel is not answering at ${runtime.probeUrl}`);
22562
23160
  if (answer.status !== 200) refusal(answer);
@@ -22567,7 +23165,7 @@ async function runBackupRestore(options) {
22567
23165
  if (options.json) process.stdout.write(`${JSON.stringify({
22568
23166
  action: "restore",
22569
23167
  apply: false,
22570
- name: options.name,
23168
+ name: label,
22571
23169
  error: refused
22572
23170
  }, null, 2)}\n`);
22573
23171
  fail(refused);
@@ -22580,14 +23178,14 @@ async function runBackupRestore(options) {
22580
23178
  process.stdout.write(`${JSON.stringify({
22581
23179
  action: "restore",
22582
23180
  apply: false,
22583
- name: options.name,
23181
+ name: label,
22584
23182
  items,
22585
23183
  skipped: restoreNotes(plan)
22586
23184
  }, null, 2)}\n`);
22587
23185
  return;
22588
23186
  }
22589
23187
  if (!options.json) {
22590
- process.stdout.write(options.confirm ? `${bold("Plan")} for ${options.name} — applying it now\n` : `${bold("Plan")} for ${options.name} — nothing has been written yet\n`);
23188
+ process.stdout.write(options.confirm ? `${bold("Plan")} for ${label} — applying it now\n` : `${bold("Plan")} for ${label} — nothing has been written yet\n`);
22591
23189
  printPlanTree(items.map((item) => ({
22592
23190
  id: item.id,
22593
23191
  note: item.note ?? null
@@ -22602,7 +23200,7 @@ async function runBackupRestore(options) {
22602
23200
  {
22603
23201
  const outcome = await (async () => {
22604
23202
  if (service !== null) {
22605
- const archive = service.resolve(options.name);
23203
+ const archive = source.kind === "from" ? source.path : service.resolve(source.name);
22606
23204
  const result = await service.restore(archive, {
22607
23205
  confirm: true,
22608
23206
  password: options.password,
@@ -22616,7 +23214,7 @@ async function runBackupRestore(options) {
22616
23214
  }
22617
23215
  const runtime = await livePanel();
22618
23216
  if (runtime === null) fail("the control panel stopped answering — nothing further was written");
22619
- const base = restoreQuery(options, scope);
23217
+ const base = restoreQuery(source, options, scope);
22620
23218
  const answer = await runtime.request(runtime, `/_hh/backups/restore${withParam(suffixOf(base), "confirm", "true")}`, 6e5);
22621
23219
  if (answer === null) fail(`the control panel is not answering at ${runtime.probeUrl}`);
22622
23220
  if (answer.status !== 200) refusal(answer);
@@ -22632,7 +23230,7 @@ async function runBackupRestore(options) {
22632
23230
  if (options.json) process.stdout.write(`${JSON.stringify({
22633
23231
  action: "restore",
22634
23232
  apply: true,
22635
- name: options.name,
23233
+ name: label,
22636
23234
  error: applyRefused
22637
23235
  }, null, 2)}\n`);
22638
23236
  fail(applyRefused);
@@ -22644,7 +23242,7 @@ async function runBackupRestore(options) {
22644
23242
  process.stdout.write(`${JSON.stringify({
22645
23243
  action: "restore",
22646
23244
  apply: true,
22647
- name: options.name,
23245
+ name: label,
22648
23246
  items: applied,
22649
23247
  hooks,
22650
23248
  skipped: notes,
@@ -22655,7 +23253,7 @@ async function runBackupRestore(options) {
22655
23253
  return;
22656
23254
  }
22657
23255
  if (applied.length === 0) process.stdout.write(`${green("restored")} nothing — the archive carried no item this host can take\n`);
22658
- else process.stdout.write(`${green("restored")} ${applied.length} ${applied.length === 1 ? "item" : "items"} from ${options.name}\n`);
23256
+ else process.stdout.write(`${green("restored")} ${applied.length} ${applied.length === 1 ? "item" : "items"} from ${label}\n`);
22659
23257
  for (const hook of hooks) process.stdout.write(` ${dim(`load ${hook.serverId}: ${hook.output ?? "staged"}`)}\n`);
22660
23258
  for (const note of notes) process.stdout.write(` ${dim("!")} ${note}\n`);
22661
23259
  if (outcome.restartRequired === true) process.stdout.write(` ${dim(`! the panel's listener changed — restart it so it binds where the archive says (\`${invocation()} restart\`)`)}\n`);
@@ -22669,8 +23267,8 @@ async function runBackupRestore(options) {
22669
23267
  * One builder, because the two requests must agree: a password or a selection on the plan and not on
22670
23268
  * the apply made the apply answer about different items than the person approved.
22671
23269
  */
22672
- function restoreQuery(options, scope) {
22673
- const base = new URLSearchParams({ name: options.name });
23270
+ function restoreQuery(source, options, scope) {
23271
+ const base = source.kind === "from" ? new URLSearchParams({ from: source.path }) : new URLSearchParams({ name: source.name });
22674
23272
  if (options.password !== void 0 && options.password.length > 0) base.set("password", options.password);
22675
23273
  if (scope.kind === "include") base.set("include", scope.ids.join(","));
22676
23274
  if (options.exclude !== void 0) base.set("exclude", options.exclude.join(","));
@@ -22680,6 +23278,7 @@ var backupCommand;
22680
23278
  var init_backup = __esmMin((() => {
22681
23279
  init_backup_offline();
22682
23280
  init_io();
23281
+ init_paths();
22683
23282
  init_backup_scope();
22684
23283
  init_error_message();
22685
23284
  backupCommand = defineCommand({
@@ -22695,6 +23294,10 @@ var init_backup = __esmMin((() => {
22695
23294
  description: "the archive name, for restore",
22696
23295
  required: false
22697
23296
  },
23297
+ from: {
23298
+ type: "string",
23299
+ description: "restore from this archive file anywhere on the machine, instead of a name in the backups directory"
23300
+ },
22698
23301
  password: {
22699
23302
  type: "string",
22700
23303
  description: "encrypt the archive, or unlock it on restore"
@@ -22725,6 +23328,7 @@ var init_backup = __esmMin((() => {
22725
23328
  const action = args.action === void 0 || args.action.length === 0 ? "list" : args.action;
22726
23329
  const parsed = action === "create" || action === "restore" ? parseScope(args.all === true, args.include) : null;
22727
23330
  const exclude = action === "create" || action === "restore" ? parseExclude(args.exclude) : void 0;
23331
+ if (action !== "restore" && args.from !== void 0 && args.from.length > 0) fail(`--from is for restore — \`${invocation()} backup ${action}\` takes none`);
22728
23332
  if (action === "list") await runBackupList(args.json === true);
22729
23333
  else if (action === "create") {
22730
23334
  const scope = parsed ?? await refuseWithoutScope("create", "");
@@ -22736,10 +23340,16 @@ var init_backup = __esmMin((() => {
22736
23340
  json: args.json === true
22737
23341
  });
22738
23342
  } else if (action === "restore") {
22739
- if (args.target === void 0 || args.target.length === 0) fail("restore needs the archive name — `backup list` shows them");
22740
- const scope = parsed ?? await refuseWithoutScope("restore", `?name=${encodeURIComponent(args.target)}`);
23343
+ const from = args.from !== void 0 && args.from.length > 0 ? args.from : void 0;
23344
+ const name = args.target !== void 0 && args.target.length > 0 ? args.target : void 0;
23345
+ if (from !== void 0 && name !== void 0) fail("pass an archive name or --from <path>, not both — they name two different archives");
23346
+ if (from === void 0 && name === void 0) fail("restore needs an archive — a name (`backup list` shows them), or --from <path> for a file anywhere on this machine");
23347
+ const suffix = from !== void 0 ? `?from=${encodeURIComponent(resolveUserPath(from))}` : `?name=${encodeURIComponent(name)}`;
23348
+ if (from !== void 0 && parsed === null && !(fs.existsSync(resolveUserPath(from)) && fs.statSync(resolveUserPath(from)).isFile())) fail(`no file at ${resolveUserPath(from)} — \`--from\` takes the path to an archive on this machine`);
23349
+ const scope = parsed ?? await refuseWithoutScope("restore", suffix);
22741
23350
  await runBackupRestore({
22742
- name: args.target,
23351
+ ...name === void 0 ? {} : { name },
23352
+ ...from === void 0 ? {} : { from },
22743
23353
  password: args.password,
22744
23354
  scope,
22745
23355
  exclude,
@@ -22939,8 +23549,9 @@ var SYNOPSIS = {
22939
23549
  "status": "home-hosted status [--json]",
22940
23550
  "logs": "home-hosted logs [--lines <n>] [--follow] [--json]",
22941
23551
  "backup": "home-hosted backup [list|create|restore] [options]",
22942
- "start": "home-hosted start <id> [--workspace <id>]",
23552
+ "start": "home-hosted start <id> [--workspace <id>] [--free-port]",
22943
23553
  "stop": "home-hosted stop <id> [--workspace <id>]",
23554
+ "free-port": "home-hosted free-port <id> [--workspace <id>]",
22944
23555
  "set-password": "home-hosted set-password",
22945
23556
  "set-token": "home-hosted set-token",
22946
23557
  "migrate": "home-hosted migrate",
@@ -22958,6 +23569,7 @@ var SUMMARIES = {
22958
23569
  "backup": "list, create or restore a backup archive",
22959
23570
  "start": "start one server, leaving the panel up",
22960
23571
  "stop": "stop one server, leaving the panel up",
23572
+ "free-port": "free the port a server needs, so it can start",
22961
23573
  "set-password": "set the panel password without the API",
22962
23574
  "set-token": "set the API token that scripts and agents use",
22963
23575
  "migrate": "bring the config up to this release's schema",
@@ -22996,6 +23608,7 @@ var BACKUP_SECTION = {
22996
23608
  lines: [
22997
23609
  ["list | create | restore", "what to do (default: list)"],
22998
23610
  ["<name>", "the archive, for restore — `backup list` shows them"],
23611
+ ["--from <path>", "restore from an archive file anywhere on this machine, instead of a name"],
22999
23612
  ["--include <ids>", "comma-separated item ids to act on (required for create/restore)"],
23000
23613
  ["--all", "act on everything; one of --include or --all is required"],
23001
23614
  ["--exclude <ids>", "leave these out; --all --exclude global:secrets keeps the password and token out of the archive"],
@@ -23005,9 +23618,17 @@ var BACKUP_SECTION = {
23005
23618
  ]
23006
23619
  };
23007
23620
  var SERVER_SECTION = {
23008
- heading: "Arguments for start/stop",
23621
+ heading: "Arguments for start/stop/free-port",
23009
23622
  lines: [["<id>", "the server id from servers.config.json"], ["-w, --workspace <id>", "the workspace to act in (default: the default workspace)"]]
23010
23623
  };
23624
+ var START_SECTION = {
23625
+ heading: "Arguments for start",
23626
+ lines: [
23627
+ ["<id>", "the server id from servers.config.json"],
23628
+ ["-w, --workspace <id>", "the workspace to act in (default: the default workspace)"],
23629
+ ["--free-port", "free the port first, then start — the panel's Free port button"]
23630
+ ]
23631
+ };
23011
23632
  var RESTART_SECTION = {
23012
23633
  heading: "Options for restart",
23013
23634
  lines: [
@@ -23145,8 +23766,9 @@ var SECTIONS = {
23145
23766
  "logs": LOGS_SECTION,
23146
23767
  "backup": BACKUP_SECTION,
23147
23768
  "restart": RESTART_SECTION,
23148
- "start": SERVER_SECTION,
23769
+ "start": START_SECTION,
23149
23770
  "stop": SERVER_SECTION,
23771
+ "free-port": SERVER_SECTION,
23150
23772
  "set-password": SET_PASSWORD_SECTION,
23151
23773
  "set-token": SET_TOKEN_SECTION,
23152
23774
  "migrate": MIGRATE_SECTION,
@@ -23189,6 +23811,7 @@ var COMMANDS = {
23189
23811
  "logs": () => Promise.resolve().then(() => (init_logs(), logs_exports)).then((module) => module.logsCommand),
23190
23812
  "start": () => Promise.resolve().then(() => (init_server(), server_exports)).then((module) => module.startCommand),
23191
23813
  "stop": () => Promise.resolve().then(() => (init_server(), server_exports)).then((module) => module.stopCommand),
23814
+ "free-port": () => Promise.resolve().then(() => (init_server(), server_exports)).then((module) => module.freePortCommand),
23192
23815
  "set-password": () => Promise.resolve().then(() => (init_set_password(), set_password_exports)).then((module) => module.setPasswordCommand),
23193
23816
  "set-token": () => Promise.resolve().then(() => (init_set_token(), set_token_exports)).then((module) => module.setTokenCommand),
23194
23817
  "migrate": () => Promise.resolve().then(() => (init_migrate(), migrate_exports)).then((module) => module.migrateCommand),