home-hosted 0.9.10 → 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.
@@ -14317,8 +14740,7 @@ var init_supervisor = __esmMin((() => {
14317
14740
  entry.restarts = 0;
14318
14741
  if (entry.actor !== "policy") entry.healthRestarts = 0;
14319
14742
  if (entry.actor !== "policy") entry.pendingRestart = null;
14320
- entry.healthFailures = 0;
14321
- entry.unhealthySince = null;
14743
+ this.resetHealth(entry);
14322
14744
  this.persistEntryState(entry);
14323
14745
  }
14324
14746
  try {
@@ -14327,9 +14749,11 @@ var init_supervisor = __esmMin((() => {
14327
14749
  ok: false,
14328
14750
  error: `server "${id}" is stopping`
14329
14751
  };
14752
+ const resolved = this.resolveSpawn(entry);
14753
+ this.detectCompose(entry, resolved);
14330
14754
  entry.lastError = null;
14331
14755
  entry.status = "starting";
14332
- entry.health = entry.config.health.enabled ? "unknown" : "disabled";
14756
+ this.resetHealth(entry);
14333
14757
  this.publishServer(entry);
14334
14758
  if (entry.config.persistent && await this.resumePersistent(entry)) return { ok: true };
14335
14759
  if (!entry.config.persistent) {
@@ -14355,7 +14779,7 @@ var init_supervisor = __esmMin((() => {
14355
14779
  error: conflict.error
14356
14780
  };
14357
14781
  if (conflict.kind === "adopt") return this.adoptEntry(entry, conflict.pid, `a detached restart of this entry is already serving port ${entry.config.port}`);
14358
- const started = this.spawnEntry(entry);
14782
+ const started = this.spawnEntry(entry, resolved);
14359
14783
  if (entry.pendingLoad !== null) this.runPendingLoad(entry);
14360
14784
  return started;
14361
14785
  } finally {
@@ -14451,7 +14875,7 @@ var init_supervisor = __esmMin((() => {
14451
14875
  port,
14452
14876
  error: `server "${id}" is busy — try again in a moment`
14453
14877
  };
14454
- const { ours, foreign } = await this.portHolders(port);
14878
+ const { ours, foreign, siblings } = await this.portHolders(port);
14455
14879
  if ([...ours, ...foreign].length === 0) {
14456
14880
  const docker = await findDockerPortHolder(port);
14457
14881
  if (docker !== null) {
@@ -14491,15 +14915,12 @@ var init_supervisor = __esmMin((() => {
14491
14915
  error: `nothing is listening on port ${port} any more`
14492
14916
  };
14493
14917
  }
14494
- if (foreign.length === 0) {
14495
- const reason = `port ${port} is held by pid ${ours.join(", ")}, which this panel supervises — stop that server instead`;
14496
- return {
14497
- ...empty,
14498
- port,
14499
- error: reason,
14500
- skipped: ours
14501
- };
14502
- }
14918
+ if (foreign.length === 0) return {
14919
+ ...empty,
14920
+ port,
14921
+ error: this.heldByOurs(port, ours, siblings),
14922
+ skipped: ours
14923
+ };
14503
14924
  this.log(entry, "system", `freeing port ${port}: asking pid ${foreign.join(", ")} to stop`);
14504
14925
  const { stopped, forced } = await terminatePids(foreign, { graceMs: entry.config.stop.graceMs });
14505
14926
  if (forced.length > 0) this.log(entry, "system", `pid ${forced.join(", ")} ignored SIGTERM and was killed`);
@@ -14533,14 +14954,27 @@ var init_supervisor = __esmMin((() => {
14533
14954
  * in an old banner from killing a recycled pid.
14534
14955
  */
14535
14956
  async portHolders(port) {
14536
- const supervised = await this.supervisedPids();
14957
+ const { pids: supervised, siblings } = await this.supervisedPids();
14537
14958
  const holders = await listPortHolders(port);
14538
14959
  return {
14539
14960
  ours: holders.filter((pid) => supervised.has(pid)),
14540
- foreign: holders.filter((pid) => !supervised.has(pid))
14961
+ foreign: holders.filter((pid) => !supervised.has(pid)),
14962
+ siblings
14541
14963
  };
14542
14964
  }
14543
14965
  /**
14966
+ * The sentence a refused port prints: names the holder, and where it lives when that is another
14967
+ * workspace, because "stop that server instead" is not actionable from a page that cannot show it.
14968
+ *
14969
+ * A sibling whose pid is one we refused is matched by pid, the one fact both sides agree on — a
14970
+ * same-named entry in this workspace would have been a different pid.
14971
+ */
14972
+ heldByOurs(port, ours, siblings) {
14973
+ const owners = siblings.filter((sibling) => ours.includes(sibling.pid));
14974
+ const place = owners.length === 0 ? "" : ` on ${[...new Set(owners.map((owner) => `${owner.workspaceId}/${owner.serverId}`))].join(", ")}`;
14975
+ return `port ${port} is held by pid ${ours.join(", ")}, which this panel supervises${place} — stop that server instead`;
14976
+ }
14977
+ /**
14544
14978
  * Pids of the processes this panel owns, plus itself — the whole *tree* of every
14545
14979
  * entry, not just the pid it recorded.
14546
14980
  *
@@ -14557,9 +14991,14 @@ var init_supervisor = __esmMin((() => {
14557
14991
  const roots = [];
14558
14992
  for (const entry of this.entries.values()) if (entry.pid !== null) roots.push(entry.pid);
14559
14993
  else if (entry.child?.pid !== void 0) roots.push(entry.child.pid);
14994
+ const siblings = [...await this.options.siblingServers?.() ?? []];
14995
+ roots.push(...siblings.map((sibling) => sibling.pid));
14560
14996
  const pids = await processTreePids(roots);
14561
14997
  pids.add(process.pid);
14562
- return pids;
14998
+ return {
14999
+ pids,
15000
+ siblings
15001
+ };
14563
15002
  }
14564
15003
  /** The port's own answer, with the same short recheck the preflight uses. */
14565
15004
  async waitForPortRelease(entry, port) {
@@ -14668,7 +15107,7 @@ var init_supervisor = __esmMin((() => {
14668
15107
  });
14669
15108
  const { port, stop } = entry.config;
14670
15109
  if (stop.killPortHolders && port !== null) {
14671
- const leftover = await killPortHolders(port, await this.supervisedPids());
15110
+ const leftover = await killPortHolders(port, (await this.supervisedPids()).pids);
14672
15111
  if (leftover.length > 0) this.log(entry, "system", `port ${port} was still held by pid ${leftover.join(", ")} — killed`);
14673
15112
  }
14674
15113
  const survivor = entry.config.persistent && entry.pid !== null && isProcessAlive(entry.pid) ? entry.pid : null;
@@ -14681,9 +15120,10 @@ var init_supervisor = __esmMin((() => {
14681
15120
  }
14682
15121
  entry.stopping = false;
14683
15122
  entry.child = null;
14684
- entry.pid = null;
14685
- entry.adopted = false;
15123
+ this.endProcessReadings(entry);
14686
15124
  entry.nannyExit = null;
15125
+ this.endHealthStreak(entry);
15126
+ if (survivor === null || !entry.config.health.enabled) this.resetHealth(entry);
14687
15127
  if (entry.lastChild !== null && !isProcessAlive(entry.lastChild.pid)) {
14688
15128
  entry.lastChild = null;
14689
15129
  this.persistEntryState(entry);
@@ -14697,6 +15137,56 @@ var init_supervisor = __esmMin((() => {
14697
15137
  error: entry.lastError
14698
15138
  };
14699
15139
  }
15140
+ /**
15141
+ * The health state, together with the streak that produced it.
15142
+ *
15143
+ * `healthFailures` and `unhealthySince` describe one **process's** run: the failures since it
15144
+ * began, and the moment that streak turned unhealthy. They move with `health` for one reason —
15145
+ * a caller that set one and forgot the other left a duration counting up while nothing was
15146
+ * measured. Measured on the built panel: an entry that crashed while unhealthy reported
15147
+ * `status=crashed health=unknown` beside `Unhealthy for 3m 17s` and a `Not Probed` row, the
15148
+ * identical shape an explicit stop had before round 13 fixed that one path. Anything other
15149
+ * than `unhealthy` therefore ends the streak.
15150
+ */
15151
+ setHealth(entry, health) {
15152
+ entry.health = health;
15153
+ if (health !== "unhealthy") this.endHealthStreak(entry);
15154
+ }
15155
+ /**
15156
+ * Forgets the streak without deciding the verdict.
15157
+ *
15158
+ * A refused stop is the one place the two differ: the process survived, so its `conflict`
15159
+ * outcome stays, while the duration that described the run cannot keep counting from a probe
15160
+ * that is no longer taken.
15161
+ */
15162
+ endHealthStreak(entry) {
15163
+ entry.healthFailures = 0;
15164
+ entry.unhealthySince = null;
15165
+ }
15166
+ /** The health of an entry nothing is probing: `disabled` with the probe off, else `unknown`. */
15167
+ resetHealth(entry) {
15168
+ this.setHealth(entry, entry.config.health.enabled ? "unknown" : "disabled");
15169
+ }
15170
+ /**
15171
+ * The measurements one process produced, dropped when that process is gone.
15172
+ *
15173
+ * `pid`, `responseMs` and `resources` describe *one* run: the probe's last latency and the
15174
+ * sampler's last reading are that process's numbers, and nothing measured them again just
15175
+ * because the pid left. Both exit paths cleared them; an adopted entry has no exit event of its
15176
+ * own, so a stopped successor kept a live-looking CPU, RSS and probe beside `Status Stopped /
15177
+ * Health Not Probed` — and the sampler never corrects them, because it only visits entries with
15178
+ * a pid. The same numbers reached `/api/metrics`, where a stopped server published a real
15179
+ * `hh_server_cpu_percent` and `hh_server_rss_bytes`.
15180
+ *
15181
+ * `adopted` goes with them: it says *this pid* is a successor we took over, and there is no pid
15182
+ * left to say it of.
15183
+ */
15184
+ endProcessReadings(entry) {
15185
+ entry.pid = null;
15186
+ entry.adopted = false;
15187
+ entry.responseMs = null;
15188
+ entry.resources = null;
15189
+ }
14700
15190
  createEntry(config) {
14701
15191
  const persisted = readEntryState(entryStatePath(this.options.nannyDir, config.id));
14702
15192
  const lastPid = persisted?.lastPid ?? null;
@@ -14740,6 +15230,7 @@ var init_supervisor = __esmMin((() => {
14740
15230
  responseMs: null,
14741
15231
  resources: null,
14742
15232
  resourcesSampledAt: 0,
15233
+ compose: null,
14743
15234
  historyCache: null
14744
15235
  };
14745
15236
  }
@@ -14831,7 +15322,7 @@ var init_supervisor = __esmMin((() => {
14831
15322
  }
14832
15323
  entry.portState = free ? "free" : "in-use";
14833
15324
  if (free) return { kind: "free" };
14834
- const { ours, foreign } = await this.portHolders(port);
15325
+ const { ours, foreign, siblings } = await this.portHolders(port);
14835
15326
  const holders = [...ours, ...foreign];
14836
15327
  const own = await this.ownPortHolder(entry, foreign);
14837
15328
  const docker = holders.length === 0 ? await findDockerPortHolder(port) : null;
@@ -14839,7 +15330,7 @@ var init_supervisor = __esmMin((() => {
14839
15330
  if (entry.config.onPortConflict === "kill") {
14840
15331
  if (ours.length > 0) {
14841
15332
  entry.status = "conflict";
14842
- entry.lastError = `port ${port} is held by pid ${ours.join(", ")}, which this panel supervises — stop that server instead`;
15333
+ entry.lastError = this.heldByOurs(port, ours, siblings);
14843
15334
  this.log(entry, "system", `${entry.lastError} — not starting (onPortConflict: kill)`);
14844
15335
  this.publishServer(entry);
14845
15336
  return {
@@ -14874,9 +15365,10 @@ var init_supervisor = __esmMin((() => {
14874
15365
  return await this.stopPortHolders(entry, [own], port, "replacing", freeOnAll);
14875
15366
  }
14876
15367
  const hint = own !== null ? ` — pid ${own} is a detached restart of this entry: set onPortConflict to "follow" to adopt it, "reclaim" to replace it with a supervised process, or "kill" to stop whatever holds the port` : docker === null ? "" : ` — it is published by a docker container, which \`kill\` stops through docker; \`block\` and \`warn\` leave it alone`;
15368
+ const blockedError = ours.length > 0 ? this.heldByOurs(port, ours, siblings) : `port ${port} is already in use${suffix}${hint}`;
14877
15369
  if (entry.config.onPortConflict !== "warn") {
14878
15370
  entry.status = "conflict";
14879
- entry.lastError = `port ${port} is already in use${suffix}${hint}`;
15371
+ entry.lastError = blockedError;
14880
15372
  this.log(entry, "system", `${entry.lastError} — not starting (onPortConflict: ${entry.config.onPortConflict})`);
14881
15373
  this.publishServer(entry);
14882
15374
  return {
@@ -14884,7 +15376,7 @@ var init_supervisor = __esmMin((() => {
14884
15376
  error: entry.lastError
14885
15377
  };
14886
15378
  }
14887
- this.log(entry, "system", `warning: port ${port} is already in use${suffix}${hint} — starting anyway`);
15379
+ this.log(entry, "system", `warning: ${blockedError} — starting anyway`);
14888
15380
  return { kind: "free" };
14889
15381
  }
14890
15382
  /**
@@ -14931,7 +15423,7 @@ var init_supervisor = __esmMin((() => {
14931
15423
  entry.pid = pid;
14932
15424
  entry.child = null;
14933
15425
  entry.status = "running";
14934
- entry.health = entry.config.health.enabled ? "unknown" : "disabled";
15426
+ this.resetHealth(entry);
14935
15427
  entry.startedAt = Date.now();
14936
15428
  entry.lastError = null;
14937
15429
  if (entry.config.persistent) this.followPersistent(entry, true);
@@ -14994,12 +15486,9 @@ var init_supervisor = __esmMin((() => {
14994
15486
  const ranForMs = entry.nannyExit?.runtimeMs ?? (entry.startedAt === null ? 0 : Date.now() - entry.startedAt);
14995
15487
  const detail = entry.nannyExit === null ? "adopted process exited" : describeNannyExit(entry.nannyExit);
14996
15488
  entry.nannyExit = null;
14997
- entry.adopted = false;
14998
- entry.pid = null;
14999
15489
  this.forgetRecordedChild(entry, adoptedPid);
15000
- entry.resources = null;
15001
- entry.responseMs = null;
15002
- entry.health = entry.config.health.enabled ? "unknown" : "disabled";
15490
+ this.endProcessReadings(entry);
15491
+ this.resetHealth(entry);
15003
15492
  entry.exitCode = null;
15004
15493
  entry.exitSignal = null;
15005
15494
  if (!entry.removed) this.options.history.record(entry.config.id, {
@@ -15066,6 +15555,23 @@ var init_supervisor = __esmMin((() => {
15066
15555
  else if (code !== null) this.log(entry, "system", `bootstrap exited with code ${code} — continuing anyway`);
15067
15556
  }
15068
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
+ /**
15069
15575
  * Everything `spawn` needs for an entry: the resolved image, the expanded argv, the
15070
15576
  * cwd and the environment. The argv is also what the preflight recognizes the entry's
15071
15577
  * own detached successor by, so spawn and identification must never resolve it twice
@@ -15109,11 +15615,11 @@ var init_supervisor = __esmMin((() => {
15109
15615
  loggedArgs: resolveTemplates(entry.config.args, vars)
15110
15616
  };
15111
15617
  }
15112
- spawnEntry(entry) {
15113
- 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);
15114
15620
  }
15115
- spawnDirect(entry) {
15116
- const { command, args, env, cwd, loggedArgs } = this.resolveSpawn(entry);
15621
+ spawnDirect(entry, resolved) {
15622
+ const { command, args, env, cwd, loggedArgs } = resolved;
15117
15623
  this.log(entry, "system", `start: ${command} ${loggedArgs.join(" ")}`);
15118
15624
  let child;
15119
15625
  try {
@@ -15142,8 +15648,8 @@ var init_supervisor = __esmMin((() => {
15142
15648
  * event drives the normal lifecycle (backoff, history, notifications) — while the
15143
15649
  * real exit cause is read back from the state file the nanny leaves behind.
15144
15650
  */
15145
- spawnNanny(entry) {
15146
- const { command, args, env, cwd, loggedArgs } = this.resolveSpawn(entry);
15651
+ spawnNanny(entry, resolved) {
15652
+ const { command, args, env, cwd, loggedArgs } = resolved;
15147
15653
  this.log(entry, "system", `start (persistent): ${command} ${loggedArgs.join(" ")}`);
15148
15654
  const entryPoint = nannyEntryPoint();
15149
15655
  if (entryPoint.length === 0) return this.failSpawn(entry, "cannot locate this CLI to start a persistent entry");
@@ -15225,8 +15731,7 @@ var init_supervisor = __esmMin((() => {
15225
15731
  entry.exitSignal = null;
15226
15732
  entry.nannyExit = null;
15227
15733
  entry.lastProbeAt = 0;
15228
- entry.healthFailures = 0;
15229
- entry.unhealthySince = null;
15734
+ this.resetHealth(entry);
15230
15735
  this.publishServer(entry);
15231
15736
  child.once("error", (error) => {
15232
15737
  entry.lastError = describeSpawnError(error, entry.config.command, cwd);
@@ -15301,7 +15806,7 @@ var init_supervisor = __esmMin((() => {
15301
15806
  entry.pid = state.nannyPid;
15302
15807
  entry.startedAt = state.startedAt;
15303
15808
  entry.status = "running";
15304
- entry.health = entry.config.health.enabled ? "unknown" : "disabled";
15809
+ this.resetHealth(entry);
15305
15810
  entry.portState = entry.config.port === null ? "unknown" : "in-use";
15306
15811
  entry.lastError = null;
15307
15812
  entry.nannyExit = null;
@@ -15384,7 +15889,7 @@ var init_supervisor = __esmMin((() => {
15384
15889
  if (port === null) {
15385
15890
  if (entry.child !== child || entry.status !== "starting") return;
15386
15891
  entry.status = "running";
15387
- entry.health = health.enabled ? "unknown" : "disabled";
15892
+ this.setHealth(entry, health.enabled ? "unknown" : "disabled");
15388
15893
  this.log(entry, "system", "running (no port configured; readiness assumed on spawn)");
15389
15894
  this.settleRestart(entry, "it spawned and is running");
15390
15895
  this.publishServer(entry);
@@ -15395,7 +15900,7 @@ var init_supervisor = __esmMin((() => {
15395
15900
  if (entry.child !== child || entry.status !== "starting" || this.disposed) return;
15396
15901
  if (await this.portAccepts(entry, port, Math.min(health.timeoutMs, 1e3))) {
15397
15902
  entry.portState = "in-use";
15398
- entry.health = !health.enabled ? "disabled" : health.mode === "http" ? "unknown" : "healthy";
15903
+ this.setHealth(entry, !health.enabled ? "disabled" : health.mode === "http" ? "unknown" : "healthy");
15399
15904
  entry.status = "running";
15400
15905
  entry.lastProbeAt = 0;
15401
15906
  this.log(entry, "system", `accepting connections on port ${port}`);
@@ -15407,7 +15912,7 @@ var init_supervisor = __esmMin((() => {
15407
15912
  }
15408
15913
  if (entry.child === child && entry.status === "starting") {
15409
15914
  entry.status = "running";
15410
- entry.health = "unhealthy";
15915
+ this.setHealth(entry, "unhealthy");
15411
15916
  entry.unhealthySince = Date.now();
15412
15917
  this.log(entry, "system", `no connection on port ${port} after ${health.startTimeoutMs}ms — supervising anyway`);
15413
15918
  this.publishServer(entry);
@@ -15420,11 +15925,8 @@ var init_supervisor = __esmMin((() => {
15420
15925
  const nannyExit = entry.nannyExit;
15421
15926
  entry.nannyExit = null;
15422
15927
  entry.child = null;
15423
- entry.pid = null;
15424
- entry.adopted = false;
15425
- entry.resources = null;
15426
- entry.responseMs = null;
15427
- entry.health = entry.config.health.enabled ? "unknown" : "disabled";
15928
+ this.endProcessReadings(entry);
15929
+ this.resetHealth(entry);
15428
15930
  entry.exitCode = code;
15429
15931
  entry.exitSignal = signal;
15430
15932
  this.forgetRecordedChild(entry, child.pid ?? null);
@@ -15516,14 +16018,32 @@ var init_supervisor = __esmMin((() => {
15516
16018
  }
15517
16019
  this.publishState();
15518
16020
  }
15519
- /** 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
+ */
15520
16030
  async sampleResources(now) {
15521
16031
  const due = [...this.entries.values()].filter((entry) => entry.pid !== null && (entry.child !== null || entry.adopted) && now - entry.resourcesSampledAt >= RESOURCE_SAMPLE_INTERVAL_MS);
15522
16032
  if (due.length === 0) return;
15523
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);
15524
16036
  try {
15525
16037
  const samples = await this.sampler.sampleMany(due.map((entry) => entry.pid));
15526
- 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
+ }
15527
16047
  } catch {}
15528
16048
  }
15529
16049
  async probeEntry(entry, now) {
@@ -15551,9 +16071,7 @@ var init_supervisor = __esmMin((() => {
15551
16071
  this.notify(entry, "recovered", probe.detail);
15552
16072
  }
15553
16073
  this.settleRestart(entry, `${probe.detail} (${probe.ms}ms)`);
15554
- entry.health = "healthy";
15555
- entry.healthFailures = 0;
15556
- entry.unhealthySince = null;
16074
+ this.setHealth(entry, "healthy");
15557
16075
  const servedForMs = entry.startedAt === null ? 0 : Date.now() - entry.startedAt;
15558
16076
  if (entry.healthRestarts > 0 && servedForMs >= entry.config.restart.resetAfterMs) {
15559
16077
  entry.healthRestarts = 0;
@@ -15572,17 +16090,25 @@ var init_supervisor = __esmMin((() => {
15572
16090
  });
15573
16091
  this.notify(entry, "unhealthy", probe.detail);
15574
16092
  }
15575
- entry.health = "unhealthy";
16093
+ this.setHealth(entry, "unhealthy");
15576
16094
  }
15577
16095
  } finally {
15578
16096
  entry.probing = false;
15579
16097
  }
15580
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
+ */
15581
16107
  async enforceMemoryLimit(entry) {
15582
16108
  const limit = entry.config.resources.maxRssBytes;
15583
16109
  const rss = entry.resources?.rssBytes ?? null;
15584
16110
  if (limit <= 0 || rss === null || entry.child === null || entry.status !== "running" || rss <= limit) return false;
15585
- 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`;
15586
16112
  this.log(entry, "system", `${detail} — restarting`);
15587
16113
  this.options.history.record(entry.config.id, {
15588
16114
  type: "forced-restart",
@@ -15927,6 +16453,38 @@ function isSafeArchiveEntry(entry) {
15927
16453
  if (!ALLOWED_ROOTS.has(segments[0])) return false;
15928
16454
  return segments.every((segment) => /^[\w.-]+$/.test(segment));
15929
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
+ }
15930
16488
  /** True when `child` is `parent` itself or lives underneath it. */
15931
16489
  function isInside(parent, child) {
15932
16490
  if (parent === child) return true;
@@ -16503,40 +17061,20 @@ var init_backups = __esmMin((() => {
16503
17061
  createdWorkspaces: [],
16504
17062
  replacedUnderRunning: []
16505
17063
  };
16506
- if (!isZipArchive(archivePath)) return {
17064
+ const admitted = await admitArchive(archivePath);
17065
+ if (!admitted.ok) return {
16507
17066
  ...plan,
16508
- error: "the archive is not a home-hosted backup (a zip file was expected)"
17067
+ error: admitted.error
16509
17068
  };
17069
+ const entries = admitted.entries;
16510
17070
  const staging = path.join(this.resolveDir(), `.restore-${Date.now()}`);
16511
17071
  try {
16512
- let entries;
16513
- try {
16514
- entries = await listZip(archivePath);
16515
- } catch (error) {
16516
- return {
16517
- ...plan,
16518
- error: `the archive could not be read: ${errorMessage(error)}`
16519
- };
16520
- }
16521
17072
  plan.encrypted = entries.some((entry) => entry.encrypted);
16522
17073
  if (plan.encrypted && password === null) return {
16523
17074
  ...plan,
16524
17075
  needsPassword: true,
16525
17076
  error: "this backup is password-protected"
16526
17077
  };
16527
- if (entries.length === 0) return {
16528
- ...plan,
16529
- error: "the archive is empty"
16530
- };
16531
- if (entries.length > 1e5) return {
16532
- ...plan,
16533
- error: "the archive has too many entries"
16534
- };
16535
- const invalid = entries.filter((entry) => !isSafeArchiveEntry(entry.name));
16536
- if (invalid.length > 0) return {
16537
- ...plan,
16538
- error: `the archive contains unexpected entries (e.g. ${invalid.slice(0, 3).map((entry) => entry.name).join(", ")})`
16539
- };
16540
17078
  fs.mkdirSync(staging, { recursive: true });
16541
17079
  const extracted = await extractZip(archivePath, staging, {
16542
17080
  names: entries.map((entry) => entry.name),
@@ -19024,6 +19562,21 @@ var init_panel = __esmMin((() => {
19024
19562
  if (workspaceId !== void 0) return this.runtimes.get(workspaceId)?.supervisor.views() ?? [];
19025
19563
  return this.workspaces().flatMap((runtime) => runtime.supervisor.views());
19026
19564
  }
19565
+ /**
19566
+ * The running servers of every workspace *except* `except`, so one supervisor can recognize a
19567
+ * sibling workspace's process as one the panel owns rather than a stranger to signal — and can
19568
+ * name it when it refuses.
19569
+ *
19570
+ * Read from the live views rather than from nanny state: an adopted entry has no child record,
19571
+ * and a persistent one's pid is the nanny's, whose tree the supervisor walks itself.
19572
+ */
19573
+ siblingServers(except) {
19574
+ return this.workspaces().filter((runtime) => runtime.id !== except).flatMap((runtime) => runtime.supervisor.views().filter((view) => view.pid !== null).map((view) => ({
19575
+ pid: view.pid,
19576
+ workspaceId: runtime.id,
19577
+ serverId: view.id
19578
+ })));
19579
+ }
19027
19580
  getState() {
19028
19581
  const proxy = this.options.proxy();
19029
19582
  return {
@@ -19214,7 +19767,8 @@ var init_panel = __esmMin((() => {
19214
19767
  logFiles,
19215
19768
  notifications,
19216
19769
  onStateChange: () => this.scheduleState(),
19217
- nannyDir: workspaceStateDir(id)
19770
+ nannyDir: workspaceStateDir(id),
19771
+ siblingServers: async () => this.siblingServers(id)
19218
19772
  });
19219
19773
  const runtime = {
19220
19774
  id,
@@ -20657,11 +21211,20 @@ var init_down = __esmMin((() => {
20657
21211
  //#endregion
20658
21212
  //#region src/cli/server.ts
20659
21213
  var server_exports = /* @__PURE__ */ __exportAll({
21214
+ freePortCommand: () => freePortCommand,
21215
+ runFreePort: () => runFreePort,
20660
21216
  runServerAction: () => runServerAction,
20661
21217
  startCommand: () => startCommand,
20662
21218
  stopCommand: () => stopCommand
20663
21219
  });
20664
- 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 = {}) {
20665
21228
  const { clearRuntime, readRuntime, requestControl, runtimeIsAlive, runtimeIsGone } = await Promise.resolve().then(() => (init_daemon(), daemon_exports));
20666
21229
  const runtime = readRuntime();
20667
21230
  if (runtime === null || !await runtimeIsAlive(runtime)) {
@@ -20674,14 +21237,65 @@ async function runServerAction(action, id, workspace) {
20674
21237
  const body = answer.body ?? {};
20675
21238
  if (body.ok !== true) {
20676
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
+ };
20677
21244
  if (reason !== void 0) fail(reason);
20678
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`);
20679
21246
  fail(`the panel answered ${answer.status}`);
20680
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);
20681
21256
  const verb = action === "start" ? "started" : action === "stop" ? "stopped" : "restarted";
20682
- process.stdout.write(`${green(verb)} ${workspace === void 0 ? "" : `${workspace}/`}${id}\n`);
21257
+ process.stdout.write(`${green(verb)} ${label(id, workspace)}\n`);
20683
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}`);
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
+ */
20684
21297
  function serverCommand(action) {
21298
+ const withFreePort = action === "start";
20685
21299
  return defineCommand({
20686
21300
  meta: { name: action },
20687
21301
  args: {
@@ -20694,18 +21308,45 @@ function serverCommand(action) {
20694
21308
  type: "string",
20695
21309
  alias: "w",
20696
21310
  description: "the workspace to act in (default: the panel's default workspace)"
20697
- }
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
+ } } : {}
20698
21316
  },
20699
21317
  run: async ({ args }) => {
20700
21318
  const id = typeof args.id === "string" ? args.id.trim() : "";
20701
21319
  if (id.length === 0) fail(`${action} needs a server id — see \`${invocation()} status\` or the workspace's servers.config.json`);
20702
- 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);
20703
21323
  }
20704
21324
  });
20705
21325
  }
20706
- var startCommand, stopCommand;
21326
+ var NOTHING_LISTENING, freePortCommand, startCommand, stopCommand;
20707
21327
  var init_server = __esmMin((() => {
20708
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
+ });
20709
21350
  startCommand = serverCommand("start");
20710
21351
  stopCommand = serverCommand("stop");
20711
21352
  }));
@@ -21062,7 +21703,8 @@ async function runSetToken(generate, clear) {
21062
21703
  }
21063
21704
  process.stdout.write(`Use it from a script or an agent:\n`);
21064
21705
  process.stdout.write(` ${bold(`curl -H "Authorization: Bearer ${generate ? token : "<token>"}" ${base}/api/state`)}\n`);
21065
- 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`);
21066
21708
  process.stdout.write(`${dim("Remove it any time with: home-hosted set-token --clear")}\n`);
21067
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`);
21068
21710
  }
@@ -22250,9 +22892,10 @@ async function availableRowsFromDisk(action, suffix) {
22250
22892
  const { service } = await offlineBackup();
22251
22893
  await service.warm();
22252
22894
  if (action === "create") return service.view().entries;
22253
- const name = new URLSearchParams(suffix.startsWith("?") ? suffix.slice(1) : suffix).get("name");
22254
- if (name === null || name.length === 0) return [];
22255
- 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);
22256
22899
  if (archive === null) return [];
22257
22900
  return ((await service.restore(archive, { confirm: false })).items ?? []).filter((item) => item.selected !== false);
22258
22901
  } catch {
@@ -22468,12 +23111,40 @@ function restoreNotes(plan) {
22468
23111
  }
22469
23112
  async function runBackupRestore(options) {
22470
23113
  const scope = options.scope;
22471
- 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;
22472
23137
  if (service !== null) await service.warm();
22473
23138
  const plan = await (async () => {
22474
23139
  if (service !== null) {
22475
- const archive = service.resolve(options.name);
22476
- if (archive === null) fail(`no backup named "${options.name}" in ${service.directory} — a restore takes the archive's file name, not a path; copy it there first (\`${invocation()} backup list\` shows what is there)`);
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)`);
22477
23148
  return await service.restore(archive, {
22478
23149
  confirm: false,
22479
23150
  password: options.password,
@@ -22483,7 +23154,7 @@ async function runBackupRestore(options) {
22483
23154
  }
22484
23155
  const runtime = await livePanel();
22485
23156
  if (runtime === null) fail(`the control panel is not answering — try again once it is up`);
22486
- const base = restoreQuery(options, scope);
23157
+ const base = restoreQuery(source, options, scope);
22487
23158
  const answer = await runtime.request(runtime, `/_hh/backups/restore${suffixOf(base)}`, 12e4);
22488
23159
  if (answer === null) fail(`the control panel is not answering at ${runtime.probeUrl}`);
22489
23160
  if (answer.status !== 200) refusal(answer);
@@ -22494,7 +23165,7 @@ async function runBackupRestore(options) {
22494
23165
  if (options.json) process.stdout.write(`${JSON.stringify({
22495
23166
  action: "restore",
22496
23167
  apply: false,
22497
- name: options.name,
23168
+ name: label,
22498
23169
  error: refused
22499
23170
  }, null, 2)}\n`);
22500
23171
  fail(refused);
@@ -22507,14 +23178,14 @@ async function runBackupRestore(options) {
22507
23178
  process.stdout.write(`${JSON.stringify({
22508
23179
  action: "restore",
22509
23180
  apply: false,
22510
- name: options.name,
23181
+ name: label,
22511
23182
  items,
22512
23183
  skipped: restoreNotes(plan)
22513
23184
  }, null, 2)}\n`);
22514
23185
  return;
22515
23186
  }
22516
23187
  if (!options.json) {
22517
- process.stdout.write(options.confirm ? `${bold("Plan")} for ${options.name} — applying it now\n` : `${bold("Plan")} for ${options.name} — nothing has been written yet\n`);
23188
+ process.stdout.write(options.confirm ? `${bold("Plan")} for ${label} — applying it now\n` : `${bold("Plan")} for ${label} — nothing has been written yet\n`);
22518
23189
  printPlanTree(items.map((item) => ({
22519
23190
  id: item.id,
22520
23191
  note: item.note ?? null
@@ -22529,7 +23200,7 @@ async function runBackupRestore(options) {
22529
23200
  {
22530
23201
  const outcome = await (async () => {
22531
23202
  if (service !== null) {
22532
- const archive = service.resolve(options.name);
23203
+ const archive = source.kind === "from" ? source.path : service.resolve(source.name);
22533
23204
  const result = await service.restore(archive, {
22534
23205
  confirm: true,
22535
23206
  password: options.password,
@@ -22543,7 +23214,7 @@ async function runBackupRestore(options) {
22543
23214
  }
22544
23215
  const runtime = await livePanel();
22545
23216
  if (runtime === null) fail("the control panel stopped answering — nothing further was written");
22546
- const base = restoreQuery(options, scope);
23217
+ const base = restoreQuery(source, options, scope);
22547
23218
  const answer = await runtime.request(runtime, `/_hh/backups/restore${withParam(suffixOf(base), "confirm", "true")}`, 6e5);
22548
23219
  if (answer === null) fail(`the control panel is not answering at ${runtime.probeUrl}`);
22549
23220
  if (answer.status !== 200) refusal(answer);
@@ -22559,7 +23230,7 @@ async function runBackupRestore(options) {
22559
23230
  if (options.json) process.stdout.write(`${JSON.stringify({
22560
23231
  action: "restore",
22561
23232
  apply: true,
22562
- name: options.name,
23233
+ name: label,
22563
23234
  error: applyRefused
22564
23235
  }, null, 2)}\n`);
22565
23236
  fail(applyRefused);
@@ -22571,7 +23242,7 @@ async function runBackupRestore(options) {
22571
23242
  process.stdout.write(`${JSON.stringify({
22572
23243
  action: "restore",
22573
23244
  apply: true,
22574
- name: options.name,
23245
+ name: label,
22575
23246
  items: applied,
22576
23247
  hooks,
22577
23248
  skipped: notes,
@@ -22582,7 +23253,7 @@ async function runBackupRestore(options) {
22582
23253
  return;
22583
23254
  }
22584
23255
  if (applied.length === 0) process.stdout.write(`${green("restored")} nothing — the archive carried no item this host can take\n`);
22585
- else process.stdout.write(`${green("restored")} ${applied.length} ${applied.length === 1 ? "item" : "items"} from ${options.name}\n`);
23256
+ else process.stdout.write(`${green("restored")} ${applied.length} ${applied.length === 1 ? "item" : "items"} from ${label}\n`);
22586
23257
  for (const hook of hooks) process.stdout.write(` ${dim(`load ${hook.serverId}: ${hook.output ?? "staged"}`)}\n`);
22587
23258
  for (const note of notes) process.stdout.write(` ${dim("!")} ${note}\n`);
22588
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`);
@@ -22596,8 +23267,8 @@ async function runBackupRestore(options) {
22596
23267
  * One builder, because the two requests must agree: a password or a selection on the plan and not on
22597
23268
  * the apply made the apply answer about different items than the person approved.
22598
23269
  */
22599
- function restoreQuery(options, scope) {
22600
- 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 });
22601
23272
  if (options.password !== void 0 && options.password.length > 0) base.set("password", options.password);
22602
23273
  if (scope.kind === "include") base.set("include", scope.ids.join(","));
22603
23274
  if (options.exclude !== void 0) base.set("exclude", options.exclude.join(","));
@@ -22607,6 +23278,7 @@ var backupCommand;
22607
23278
  var init_backup = __esmMin((() => {
22608
23279
  init_backup_offline();
22609
23280
  init_io();
23281
+ init_paths();
22610
23282
  init_backup_scope();
22611
23283
  init_error_message();
22612
23284
  backupCommand = defineCommand({
@@ -22622,6 +23294,10 @@ var init_backup = __esmMin((() => {
22622
23294
  description: "the archive name, for restore",
22623
23295
  required: false
22624
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
+ },
22625
23301
  password: {
22626
23302
  type: "string",
22627
23303
  description: "encrypt the archive, or unlock it on restore"
@@ -22652,6 +23328,7 @@ var init_backup = __esmMin((() => {
22652
23328
  const action = args.action === void 0 || args.action.length === 0 ? "list" : args.action;
22653
23329
  const parsed = action === "create" || action === "restore" ? parseScope(args.all === true, args.include) : null;
22654
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`);
22655
23332
  if (action === "list") await runBackupList(args.json === true);
22656
23333
  else if (action === "create") {
22657
23334
  const scope = parsed ?? await refuseWithoutScope("create", "");
@@ -22663,10 +23340,16 @@ var init_backup = __esmMin((() => {
22663
23340
  json: args.json === true
22664
23341
  });
22665
23342
  } else if (action === "restore") {
22666
- if (args.target === void 0 || args.target.length === 0) fail("restore needs the archive name — `backup list` shows them");
22667
- 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);
22668
23350
  await runBackupRestore({
22669
- name: args.target,
23351
+ ...name === void 0 ? {} : { name },
23352
+ ...from === void 0 ? {} : { from },
22670
23353
  password: args.password,
22671
23354
  scope,
22672
23355
  exclude,
@@ -22866,8 +23549,9 @@ var SYNOPSIS = {
22866
23549
  "status": "home-hosted status [--json]",
22867
23550
  "logs": "home-hosted logs [--lines <n>] [--follow] [--json]",
22868
23551
  "backup": "home-hosted backup [list|create|restore] [options]",
22869
- "start": "home-hosted start <id> [--workspace <id>]",
23552
+ "start": "home-hosted start <id> [--workspace <id>] [--free-port]",
22870
23553
  "stop": "home-hosted stop <id> [--workspace <id>]",
23554
+ "free-port": "home-hosted free-port <id> [--workspace <id>]",
22871
23555
  "set-password": "home-hosted set-password",
22872
23556
  "set-token": "home-hosted set-token",
22873
23557
  "migrate": "home-hosted migrate",
@@ -22885,6 +23569,7 @@ var SUMMARIES = {
22885
23569
  "backup": "list, create or restore a backup archive",
22886
23570
  "start": "start one server, leaving the panel up",
22887
23571
  "stop": "stop one server, leaving the panel up",
23572
+ "free-port": "free the port a server needs, so it can start",
22888
23573
  "set-password": "set the panel password without the API",
22889
23574
  "set-token": "set the API token that scripts and agents use",
22890
23575
  "migrate": "bring the config up to this release's schema",
@@ -22923,6 +23608,7 @@ var BACKUP_SECTION = {
22923
23608
  lines: [
22924
23609
  ["list | create | restore", "what to do (default: list)"],
22925
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"],
22926
23612
  ["--include <ids>", "comma-separated item ids to act on (required for create/restore)"],
22927
23613
  ["--all", "act on everything; one of --include or --all is required"],
22928
23614
  ["--exclude <ids>", "leave these out; --all --exclude global:secrets keeps the password and token out of the archive"],
@@ -22932,9 +23618,17 @@ var BACKUP_SECTION = {
22932
23618
  ]
22933
23619
  };
22934
23620
  var SERVER_SECTION = {
22935
- heading: "Arguments for start/stop",
23621
+ heading: "Arguments for start/stop/free-port",
22936
23622
  lines: [["<id>", "the server id from servers.config.json"], ["-w, --workspace <id>", "the workspace to act in (default: the default workspace)"]]
22937
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
+ };
22938
23632
  var RESTART_SECTION = {
22939
23633
  heading: "Options for restart",
22940
23634
  lines: [
@@ -23072,8 +23766,9 @@ var SECTIONS = {
23072
23766
  "logs": LOGS_SECTION,
23073
23767
  "backup": BACKUP_SECTION,
23074
23768
  "restart": RESTART_SECTION,
23075
- "start": SERVER_SECTION,
23769
+ "start": START_SECTION,
23076
23770
  "stop": SERVER_SECTION,
23771
+ "free-port": SERVER_SECTION,
23077
23772
  "set-password": SET_PASSWORD_SECTION,
23078
23773
  "set-token": SET_TOKEN_SECTION,
23079
23774
  "migrate": MIGRATE_SECTION,
@@ -23116,6 +23811,7 @@ var COMMANDS = {
23116
23811
  "logs": () => Promise.resolve().then(() => (init_logs(), logs_exports)).then((module) => module.logsCommand),
23117
23812
  "start": () => Promise.resolve().then(() => (init_server(), server_exports)).then((module) => module.startCommand),
23118
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),
23119
23815
  "set-password": () => Promise.resolve().then(() => (init_set_password(), set_password_exports)).then((module) => module.setPasswordCommand),
23120
23816
  "set-token": () => Promise.resolve().then(() => (init_set_token(), set_token_exports)).then((module) => module.setTokenCommand),
23121
23817
  "migrate": () => Promise.resolve().then(() => (init_migrate(), migrate_exports)).then((module) => module.migrateCommand),