home-hosted 0.9.5 → 0.9.6

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
@@ -4085,6 +4085,16 @@ function createControlRoute(deps) {
4085
4085
  assertLocalCall(c, "create a backup");
4086
4086
  const password = c.req.query("password");
4087
4087
  const include = c.req.query("include")?.split(",").filter((part) => part.length > 0);
4088
+ if (c.req.query("confirm") !== "true") {
4089
+ const view = buildBackupsView(deps.backups);
4090
+ const wanted = include === void 0 ? null : new Set(include);
4091
+ const entries = view.entries.filter((entry) => wanted === null || wanted.has(entry.id) || entry.workspaceId !== void 0 && wanted.has(`workspace:${entry.workspaceId}`));
4092
+ return c.json({
4093
+ apply: false,
4094
+ entries,
4095
+ includePaths: view.includePaths
4096
+ });
4097
+ }
4088
4098
  const result = await deps.backups.create({
4089
4099
  password,
4090
4100
  include
@@ -12599,6 +12609,113 @@ var init_secret_parts = __esmMin((() => {
12599
12609
  EXTRA_FIELDS = { ddns: ["ddns", "ddnsKdf"] };
12600
12610
  }));
12601
12611
  //#endregion
12612
+ //#region src/helpers/restore-lock.ts
12613
+ function readRecord(file) {
12614
+ try {
12615
+ const parsed = JSON.parse(fs.readFileSync(file, "utf8"));
12616
+ if (typeof parsed.pid !== "number" || typeof parsed.startedAt !== "number") return null;
12617
+ return {
12618
+ pid: parsed.pid,
12619
+ startedAt: parsed.startedAt,
12620
+ action: typeof parsed.action === "string" ? parsed.action : "restore",
12621
+ birthAt: typeof parsed.birthAt === "number" ? parsed.birthAt : null
12622
+ };
12623
+ } catch {
12624
+ return null;
12625
+ }
12626
+ }
12627
+ /**
12628
+ * Is the recorded holder still the process that took it?
12629
+ *
12630
+ * Signal 0 alone is not enough — pids are recycled, and a zombie answers it — so the process's own
12631
+ * start time is compared with the recorded one where the platform can report it. Elsewhere the pid is
12632
+ * all there is, and an alive pid is taken as alive, which errs towards "somebody is working" rather
12633
+ * than stealing a live lock.
12634
+ */
12635
+ function holderIsAlive(record) {
12636
+ try {
12637
+ process.kill(record.pid, 0);
12638
+ } catch (error) {
12639
+ return error.code === "EPERM";
12640
+ }
12641
+ const birth = processBirthSync(record.pid);
12642
+ if (birth === null) return true;
12643
+ if (record.birthAt != null) return Math.abs(birth - record.birthAt) <= BIRTH_TOLERANCE_MS;
12644
+ return birth <= record.startedAt + BIRTH_TOLERANCE_MS;
12645
+ }
12646
+ /** Wall-clock start of a pid in ms, or null where the platform cannot report one. */
12647
+ function processBirthSync(pid) {
12648
+ try {
12649
+ const stat = fs.readFileSync(`/proc/${pid}/stat`, "utf8");
12650
+ const fields = stat.slice(stat.lastIndexOf(")") + 2).split(" ");
12651
+ const ticks = Number.parseFloat(fields[19] ?? "");
12652
+ if (!Number.isFinite(ticks)) return null;
12653
+ const boot = /^btime (\d+)$/m.exec(fs.readFileSync("/proc/stat", "utf8"))?.[1];
12654
+ if (boot === void 0) return null;
12655
+ return Number.parseInt(boot, 10) * 1e3 + ticks / 100 * 1e3;
12656
+ } catch {
12657
+ return null;
12658
+ }
12659
+ }
12660
+ /**
12661
+ * Take the restore lock, or explain who holds it.
12662
+ *
12663
+ * `null` means somebody else is restoring. The caller reports it rather than queueing: a restore is
12664
+ * an interactive decision, and waiting on one you did not start is not what a person asked for.
12665
+ */
12666
+ function acquireRestoreLock(hhDir, action = "restore") {
12667
+ const file = path.join(hhDir, "restore.lock");
12668
+ fs.mkdirSync(hhDir, { recursive: true });
12669
+ const mine = {
12670
+ pid: process.pid,
12671
+ startedAt: Date.now(),
12672
+ action,
12673
+ birthAt: processBirthSync(process.pid)
12674
+ };
12675
+ const release = () => {
12676
+ const current = readRecord(file);
12677
+ if (current !== null && (current.pid !== mine.pid || current.startedAt !== mine.startedAt)) return;
12678
+ fs.rmSync(file, { force: true });
12679
+ };
12680
+ const existing = readRecord(file);
12681
+ if (existing !== null) {
12682
+ if (!(!holderIsAlive(existing) || Date.now() - existing.startedAt > STALE_AFTER_MS)) return { heldBy: existing };
12683
+ writeFileAtomic(file, `${JSON.stringify(mine)}\n`, { mode: 384 });
12684
+ return {
12685
+ release,
12686
+ replaced: existing
12687
+ };
12688
+ }
12689
+ try {
12690
+ fs.writeFileSync(file, `${JSON.stringify(mine)}\n`, {
12691
+ flag: "wx",
12692
+ mode: 384
12693
+ });
12694
+ } catch (error) {
12695
+ if (error.code === "EEXIST") {
12696
+ const holder = readRecord(file);
12697
+ return holder === null ? { heldBy: {
12698
+ pid: 0,
12699
+ startedAt: Date.now(),
12700
+ action: "unreadable"
12701
+ } } : { heldBy: holder };
12702
+ }
12703
+ throw error;
12704
+ }
12705
+ let released = false;
12706
+ return { release: () => {
12707
+ if (released) return;
12708
+ released = true;
12709
+ release();
12710
+ } };
12711
+ }
12712
+ var STALE_AFTER_MS, BIRTH_TOLERANCE_MS;
12713
+ var init_restore_lock = __esmMin((() => {
12714
+ init_atomic();
12715
+ STALE_AFTER_MS = 18e5;
12716
+ BIRTH_TOLERANCE_MS = 2e3;
12717
+ }));
12718
+ //#endregion
12602
12719
  //#region src/providers/archive.ts
12603
12720
  /** Recognised by content, never by the file's name. */
12604
12721
  function isZipArchive(file) {
@@ -15271,6 +15388,35 @@ function resolveBackupPaths(servers, includePaths = [], vars) {
15271
15388
  });
15272
15389
  }
15273
15390
  /**
15391
+ * What a backup captures, from a workspace list and the panel-wide paths.
15392
+ *
15393
+ * The **one** implementation, called by the running panel and by the CLI when no panel is up. A
15394
+ * second copy is how an offline backup would quietly capture something different from an online one
15395
+ * — and the archive is the thing people restore from, so a silent difference is the worst kind.
15396
+ *
15397
+ * `runningServers` stays a callback rather than a list: the panel answers it from live supervisor
15398
+ * views, and an offline caller answers it from the nanny state on disk. It is optional because a
15399
+ * caller that cannot know leaves it out; the warning it feeds is then simply absent.
15400
+ */
15401
+ function buildBackupSources(input) {
15402
+ return {
15403
+ globalSettingsPath: input.globalSettingsPath,
15404
+ globalSecretsPath: input.globalSecretsPath,
15405
+ tlsDir: input.tlsDir,
15406
+ registryPath: input.registryPath,
15407
+ includePaths: [...input.includePaths],
15408
+ ...input.runningServers === void 0 ? {} : { runningServers: input.runningServers },
15409
+ workspaces: input.workspaces.map((workspace) => ({
15410
+ id: workspace.id,
15411
+ label: workspace.label,
15412
+ settingsPath: workspace.settingsPath,
15413
+ serversPath: workspace.serversPath,
15414
+ secretsPath: workspace.secretsPath,
15415
+ servers: workspace.servers
15416
+ }))
15417
+ };
15418
+ }
15419
+ /**
15274
15420
  * A restored settings file is accepted when this release can read it — through
15275
15421
  * the same tolerant parser the stores use, so an archive from a newer release
15276
15422
  * keeps only the keys this one understands instead of being refused outright.
@@ -15402,6 +15548,7 @@ var init_backups = __esmMin((() => {
15402
15548
  init_env_file();
15403
15549
  init_logger();
15404
15550
  init_paths();
15551
+ init_restore_lock();
15405
15552
  init_template();
15406
15553
  init_version();
15407
15554
  init_archive();
@@ -15664,6 +15811,18 @@ var init_backups = __esmMin((() => {
15664
15811
  * archive's manifest alone.
15665
15812
  */
15666
15813
  async restore(archivePath, options) {
15814
+ const lock = options.confirm ? acquireRestoreLock(this.options.dataRoot) : null;
15815
+ if (lock !== null && "heldBy" in lock) throw new DetailedError(`another restore is running (pid ${lock.heldBy.pid}, since ${new Date(lock.heldBy.startedAt).toISOString()}) — wait for it, or remove ${path.join(this.options.dataRoot, "restore.lock")} if it is stale`, {
15816
+ statusCode: 409,
15817
+ code: "RESTORE_IN_PROGRESS"
15818
+ });
15819
+ try {
15820
+ return await this.applyRestore(archivePath, options);
15821
+ } finally {
15822
+ if (lock !== null && !("heldBy" in lock)) lock.release();
15823
+ }
15824
+ }
15825
+ async applyRestore(archivePath, options) {
15667
15826
  const password = options.password !== void 0 && options.password.length > 0 ? options.password : null;
15668
15827
  const plan = {
15669
15828
  dryRun: !options.confirm,
@@ -17992,6 +18151,7 @@ var init_panel = __esmMin((() => {
17992
18151
  init_paths();
17993
18152
  init_version();
17994
18153
  init_ddns$2();
18154
+ init_backups();
17995
18155
  init_config_watch();
17996
18156
  init_ddns();
17997
18157
  init_history();
@@ -18110,7 +18270,7 @@ var init_panel = __esmMin((() => {
18110
18270
  }
18111
18271
  /** The sources a backup archive is built from and restored into. */
18112
18272
  backupSources() {
18113
- return {
18273
+ return buildBackupSources({
18114
18274
  globalSettingsPath: this.options.settings.path,
18115
18275
  globalSecretsPath: this.options.secrets.path,
18116
18276
  tlsDir: this.options.tls.directory,
@@ -18128,7 +18288,7 @@ var init_panel = __esmMin((() => {
18128
18288
  secretsPath: runtime.secrets.path,
18129
18289
  servers: runtime.store.servers
18130
18290
  }))
18131
- };
18291
+ });
18132
18292
  }
18133
18293
  create(input) {
18134
18294
  const workspace = this.options.registry.create(input);
@@ -20971,6 +21131,130 @@ var init_ui_revert = __esmMin((() => {
20971
21131
  });
20972
21132
  }));
20973
21133
  //#endregion
21134
+ //#region src/cli/backup-offline.ts
21135
+ /**
21136
+ * A backup service for a host whose panel is **not running**.
21137
+ *
21138
+ * `backup` used to need the daemon because the service is built inside it, so backing up or
21139
+ * restoring meant leaving the panel up — the opposite of what someone migrating a machine wants.
21140
+ * Nothing in the service needs the daemon: every source is a file, and the one live fact it wants
21141
+ * (which entries are running) is on disk as the nanny state each entry writes.
21142
+ *
21143
+ * This builds the same sources the panel does, through the same `buildBackupSources`, so an offline
21144
+ * archive cannot differ from an online one. `runningServers` is answered from `.state/*.json` rather
21145
+ * than from supervisor views: a *persistent* entry keeps running when the panel stops, so "no panel"
21146
+ * does not mean "nothing is running", and the restore warning has to keep telling the truth.
21147
+ */
21148
+ /** The workspace ids this host knows, from the registry on disk. */
21149
+ function workspaceIds(registry) {
21150
+ return registry.all().map((workspace) => ({
21151
+ id: workspace.id,
21152
+ label: workspace.label
21153
+ }));
21154
+ }
21155
+ /**
21156
+ * Entries whose nanny is alive right now, read from the state files they rewrite.
21157
+ *
21158
+ * Every path comes from `hhDir`, never from the module-level helpers: those resolve from this
21159
+ * process's own `HHOSTED_HOME`, so a caller passing `--home` elsewhere would read a different host's
21160
+ * state — which is exactly how a test came to depend on the developer's real `~/.home-hosted`.
21161
+ */
21162
+ function runningFromDisk(hhDir, ids) {
21163
+ const running = [];
21164
+ for (const workspaceId of ids) {
21165
+ const stateDir = path.join(hhDir, workspaceId, ".state");
21166
+ let names;
21167
+ try {
21168
+ names = fs.readdirSync(stateDir);
21169
+ } catch {
21170
+ continue;
21171
+ }
21172
+ for (const name of names) {
21173
+ if (!name.endsWith(".json") || name.endsWith(".spec.json") || name.endsWith(".tmp")) continue;
21174
+ const serverId = name.replace(/\.run\.json$|\.json$/, "");
21175
+ if (serverId.length === 0) continue;
21176
+ const state = readNannyState(path.join(stateDir, name));
21177
+ if (state === null) continue;
21178
+ if (Date.now() - state.heartbeatAt <= 3e4) running.push({
21179
+ workspaceId,
21180
+ serverId
21181
+ });
21182
+ }
21183
+ }
21184
+ return running;
21185
+ }
21186
+ /**
21187
+ * Build the service against this host's files.
21188
+ *
21189
+ * `ensureWorkspace` and `onRestored` are the two panel hooks, and both are deliberately absent: with
21190
+ * no daemon there is nothing to reload, and a restore that brings a workspace this host lacks leaves
21191
+ * it on disk for the next `up` to pick up. The registry is written by the service itself, which is
21192
+ * what makes that work.
21193
+ */
21194
+ function createOfflineBackup(options = {}) {
21195
+ const hhDir$1 = options.hhDir ?? hhDir;
21196
+ const settingsPath = options.settingsPath ?? globalSettingsPath;
21197
+ const registryPath = path.join(hhDir$1, path.basename(workspacesPath));
21198
+ const settings = new GlobalSettingsStore(settingsPath);
21199
+ settings.load();
21200
+ const registry = new WorkspaceRegistry(registryPath);
21201
+ registry.load();
21202
+ const workspaces = workspaceIds(registry);
21203
+ const ids = workspaces.map((workspace) => workspace.id);
21204
+ const loaded = workspaces.map((workspace) => {
21205
+ const dir = path.join(hhDir$1, workspace.id);
21206
+ const settingsPath = path.join(dir, "settings.json");
21207
+ const serversPath = path.join(dir, "servers.config.json");
21208
+ const secretsPath = path.join(dir, ".secrets.json");
21209
+ const store = new WorkspaceStore(workspace.id, settingsPath, serversPath);
21210
+ store.load();
21211
+ return {
21212
+ id: workspace.id,
21213
+ label: workspace.label,
21214
+ settingsPath,
21215
+ serversPath,
21216
+ secretsPath,
21217
+ servers: store.servers
21218
+ };
21219
+ });
21220
+ return {
21221
+ service: new BackupService({
21222
+ dataRoot: hhDir$1,
21223
+ getConfig: () => settings.backups,
21224
+ /**
21225
+ * Register a workspace the archive brought.
21226
+ *
21227
+ * A panel-only hook in the running case, because the panel creates the runtime itself. With no
21228
+ * panel there is nobody to do it, so the registry is written here — otherwise a restored
21229
+ * workspace's files land on disk unreachable, and the next `up` never looks at them.
21230
+ */
21231
+ ensureWorkspace: (input) => {
21232
+ if (registry.has(input.id)) return;
21233
+ registry.create(input);
21234
+ },
21235
+ getSources: () => buildBackupSources({
21236
+ globalSettingsPath: settings.path,
21237
+ globalSecretsPath: path.join(hhDir$1, path.basename(globalSecretsPath)),
21238
+ tlsDir: path.join(hhDir$1, path.basename(tlsDir)),
21239
+ registryPath,
21240
+ includePaths: settings.backups.includePaths,
21241
+ runningServers: () => runningFromDisk(hhDir$1, ids),
21242
+ workspaces: loaded
21243
+ })
21244
+ }),
21245
+ workspaceIds: ids,
21246
+ runningNow: () => runningFromDisk(hhDir$1, ids)
21247
+ };
21248
+ }
21249
+ var init_backup_offline = __esmMin((() => {
21250
+ init_settings$1();
21251
+ init_store();
21252
+ init_workspaces();
21253
+ init_paths();
21254
+ init_nanny$2();
21255
+ init_backups();
21256
+ }));
21257
+ //#endregion
20974
21258
  //#region src/cli/backup.ts
20975
21259
  var backup_exports = /* @__PURE__ */ __exportAll({
20976
21260
  backupCommand: () => backupCommand,
@@ -20989,74 +21273,330 @@ async function livePanel() {
20989
21273
  const runtime = daemon.readRuntime();
20990
21274
  if (runtime === null || !await daemon.runtimeIsAlive(runtime)) {
20991
21275
  if (runtime !== null && await daemon.runtimeIsGone(runtime)) daemon.clearRuntime();
20992
- fail(`home-hosted is not running — start it with \`${invocation()} up\`, then run this again`);
21276
+ return null;
20993
21277
  }
20994
21278
  return Object.assign(runtime, { request: daemon.requestControl });
20995
21279
  }
21280
+ /**
21281
+ * Whether to talk to a panel or work on the files directly.
21282
+ *
21283
+ * Both paths run the same service, so the only question is who owns the state: a live panel is the
21284
+ * authority on what is running, and a stopped one has no opinion to disagree with.
21285
+ */
21286
+ async function usesPanel() {
21287
+ const daemon = await Promise.resolve().then(() => (init_daemon(), daemon_exports));
21288
+ const runtime = daemon.readRuntime();
21289
+ if (runtime === null || !await daemon.runtimeIsAlive(runtime)) return false;
21290
+ return (await daemon.probeRuntime(runtime)).reachable;
21291
+ }
21292
+ /**
21293
+ * The offline service.
21294
+ *
21295
+ * `--config` is an `up`-only flag: it is not written to settings, and `run.json`'s `configPath` is the
21296
+ * state directory, not a servers file. So an offline run cannot know about one, and reads the default
21297
+ * workspace's `servers.config.json` — the same file the panel reads when started without `--config`.
21298
+ * A `--config` project has to start the panel first, which is the honest limit rather than a silent
21299
+ * difference between the two paths.
21300
+ */
21301
+ async function offlineBackup() {
21302
+ return createOfflineBackup();
21303
+ }
20996
21304
  /** Turn a non-200 control answer into the panel's own message, or the status. */
20997
21305
  function refusal(answer) {
20998
21306
  const body = answer.body;
20999
21307
  if (body?.message !== void 0) fail(body.message);
21000
21308
  fail(`the panel answered ${answer.status}`);
21001
21309
  }
21310
+ /**
21311
+ * The flag combination, as far as it can be judged without asking the panel.
21312
+ *
21313
+ * `null` means "neither flag", which only the caller can resolve — it lists the available ids, and
21314
+ * that needs a panel. Every other case is decided here, before any lookup, so a typo is refused
21315
+ * whether or not anything is running.
21316
+ */
21317
+ function parseScope(all, raw) {
21318
+ if (all && raw !== void 0) fail("--include and --all are exclusive — pass one or the other");
21319
+ if (all) return { kind: "all" };
21320
+ if (raw === void 0) return null;
21321
+ const ids = raw.split(",").map((part) => part.trim()).filter((part) => part.length > 0);
21322
+ if (ids.length === 0) fail("--include is empty — name the ids to act on, or pass --all for everything");
21323
+ return {
21324
+ kind: "include",
21325
+ ids
21326
+ };
21327
+ }
21328
+ /**
21329
+ * Neither flag given. Refused outright — the ids are a *bonus*, not the reason.
21330
+ *
21331
+ * The refusal must not depend on a panel being up: a mistyped command deserves the flag error, not
21332
+ * "home-hosted is not running". So the list is best-effort, and a failure to produce it is silent.
21333
+ */
21334
+ async function refuseWithoutScope(action, suffix) {
21335
+ const ids = await availableIdsFor(action, suffix).catch(() => []);
21336
+ fail(`name what to act on — pass --include <ids> or --all${ids.length === 0 ? "" : `\n\navailable:\n${ids.map((id) => ` ${id}`).join("\n")}`}`);
21337
+ }
21338
+ /**
21339
+ * The ids this action could be scoped to.
21340
+ *
21341
+ * `create` asks what the entries declare; `restore` asks what the archive holds. Both come from the
21342
+ * panel, so the list in a refusal is the real one rather than a hardcoded guess. A panel that cannot
21343
+ * be reached yields no ids — the refusal still fires, it just cannot enumerate.
21344
+ */
21345
+ async function availableIdsFor(action, suffix) {
21346
+ const daemon = await Promise.resolve().then(() => (init_daemon(), daemon_exports));
21347
+ const runtime = daemon.readRuntime();
21348
+ if (runtime === null) return [];
21349
+ const path = action === "create" ? "/_hh/backups" : "/_hh/backups/restore";
21350
+ const answer = await daemon.requestControl(runtime, `${path}${suffix}`, 12e4);
21351
+ if (answer === null || answer.status !== 200) return [];
21352
+ const body = answer.body;
21353
+ return ((action === "create" ? body?.entries : body?.items) ?? []).map((item) => item.id).filter((id) => typeof id === "string");
21354
+ }
21355
+ /** `?a=b`, or `''`. */
21356
+ function suffixOf(query) {
21357
+ return query.size === 0 ? "" : `?${query.toString()}`;
21358
+ }
21359
+ /** Appends one query parameter, keeping the `?`/`&` right. */
21360
+ function withParam(suffix, key, value) {
21361
+ return `${suffix}${suffix === "" ? "?" : "&"}${key}=${encodeURIComponent(value)}`;
21362
+ }
21363
+ /**
21364
+ * Ask before writing.
21365
+ *
21366
+ * A session that cannot be asked gets the plan and a one-line instruction — not a silent write, and
21367
+ * not a silent no-op that looks like one.
21368
+ */
21369
+ async function consent(question) {
21370
+ if (process.stdin.isTTY !== true) {
21371
+ process.stdout.write("\nnot applied — this session cannot ask. Re-run with `--confirm` to apply.\n");
21372
+ return false;
21373
+ }
21374
+ const answer = await prompt(`${question} [y/N] `);
21375
+ if (/^yes$|^y$/i.test(answer.trim())) {
21376
+ process.stdout.write("\n");
21377
+ return true;
21378
+ }
21379
+ process.stdout.write("cancelled — nothing was written\n");
21380
+ return false;
21381
+ }
21382
+ /**
21383
+ * Run against the panel when one is up, and against the files when it is not.
21384
+ *
21385
+ * Both run the same `BackupService`, so the archive cannot differ; only the authority on what is
21386
+ * running changes. A stopped panel is exactly when someone wants to back up or restore — the services
21387
+ * are down because they stopped them on purpose.
21388
+ */
21002
21389
  async function runBackupList(json) {
21003
- const runtime = await livePanel();
21004
- const answer = await runtime.request(runtime, "/_hh/backups", 3e4, "GET");
21005
- if (answer === null) fail(`the control panel is not answering on ${runtime.probeUrl}`);
21006
- if (answer.status !== 200) refusal(answer);
21007
- const view = answer.body;
21390
+ if (await usesPanel()) {
21391
+ const runtime = await livePanel();
21392
+ if (runtime !== null) {
21393
+ const answer = await runtime.request(runtime, "/_hh/backups", 3e4, "GET");
21394
+ if (answer === null) fail(`the control panel is not answering on ${runtime.probeUrl}`);
21395
+ if (answer.status !== 200) refusal(answer);
21396
+ printList(answer.body, json);
21397
+ return;
21398
+ }
21399
+ }
21400
+ const { service } = await offlineBackup();
21401
+ await service.warm();
21402
+ printList(service.view(), json);
21403
+ }
21404
+ function printList(view, json) {
21008
21405
  const files = view?.files ?? [];
21009
21406
  if (json) {
21010
21407
  process.stdout.write(`${JSON.stringify(view, null, 2)}\n`);
21011
21408
  return;
21012
21409
  }
21013
21410
  if (files.length === 0) {
21014
- process.stdout.write(`no backups yet — \`${invocation()} backup create\` takes one\n`);
21411
+ process.stdout.write(`no backups yet — \`${invocation()} backup create --all\` takes one\n`);
21015
21412
  return;
21016
21413
  }
21017
21414
  const noun = files.length === 1 ? "archive" : "archives";
21018
21415
  process.stdout.write(`${bold(String(files.length))} ${noun}${view?.dir === void 0 ? "" : ` in ${dim(view.dir)}`}\n`);
21019
21416
  for (const file of files) {
21020
- const when = file.createdAt === null ? "" : new Date(file.createdAt).toISOString().replace("T", " ").slice(0, 16);
21417
+ const when = file.createdAt == null ? "" : new Date(file.createdAt).toISOString().replace("T", " ").slice(0, 16);
21021
21418
  process.stdout.write(` ${file.name.padEnd(36)} ${human(file.sizeBytes).padStart(8)} ${dim(when)}${file.automatic ? dim(" auto") : ""}\n`);
21022
21419
  }
21023
21420
  }
21421
+ /**
21422
+ * Name the entries still running, without blocking.
21423
+ *
21424
+ * A **persistent** entry keeps running while the panel is stopped, so "panel off" is not "services
21425
+ * off" — and its data being captured mid-write is worth knowing before it is relied on. Warned rather
21426
+ * than refused: the user may know, and the panel's own backup has always proceeded here.
21427
+ */
21428
+ function warnRunning(entries) {
21429
+ if (entries.length === 0) return;
21430
+ const named = entries.map((entry) => entry.serverId ?? entry.id ?? "").filter((name) => name.length > 0);
21431
+ const isOne = named.length === 1;
21432
+ process.stdout.write(`${dim(`! ${named.length} entr${isOne ? "y is" : "ies are"} still running (${named.join(", ")}) — its data may be captured mid-write`)}\n`);
21433
+ }
21024
21434
  async function runBackupCreate(options) {
21025
- const runtime = await livePanel();
21026
- const query = new URLSearchParams();
21027
- if (options.password !== void 0 && options.password.length > 0) query.set("password", options.password);
21028
- if (options.include !== void 0 && options.include.length > 0) query.set("include", options.include.join(","));
21029
- const suffix = query.size === 0 ? "" : `?${query.toString()}`;
21030
- const answer = await runtime.request(runtime, `/_hh/backups${suffix}`, 6e5);
21031
- if (answer === null) fail(`the control panel is not answering on ${runtime.probeUrl}`);
21032
- if (answer.status !== 200) refusal(answer);
21033
- const file = answer.body?.file;
21034
- if (file === void 0) fail("the panel reported success but named no archive");
21435
+ const scope = options.scope;
21436
+ const online = await usesPanel();
21437
+ const entries = await (async () => {
21438
+ if (online) {
21439
+ const runtime = await livePanel();
21440
+ if (runtime !== null) {
21441
+ const answer = await runtime.request(runtime, "/_hh/backups", 12e4);
21442
+ if (answer === null) fail(`the control panel is not answering on ${runtime.probeUrl}`);
21443
+ if (answer.status !== 200) refusal(answer);
21444
+ return answer.body?.entries ?? [];
21445
+ }
21446
+ }
21447
+ const { service } = await offlineBackup();
21448
+ await service.warm();
21449
+ return service.view().entries;
21450
+ })();
21451
+ const wanted = scope.kind === "all" ? entries : entries.filter((entry) => scope.ids.some((id) => entry.id === id || id.startsWith(`${entry.id}:`)));
21452
+ if (!options.confirm) {
21453
+ if (options.json) {
21454
+ process.stdout.write(`${JSON.stringify({
21455
+ action: "create",
21456
+ apply: false,
21457
+ entries: wanted
21458
+ }, null, 2)}\n`);
21459
+ return;
21460
+ }
21461
+ process.stdout.write(`${bold("Plan")} — what a backup would capture; nothing has been written yet\n`);
21462
+ for (const entry of wanted) {
21463
+ process.stdout.write(` ${String(entry.kind ?? "entry").padEnd(10)} ${entry.id}${entry.note == null ? "" : ` ${dim(`(${entry.note})`)}`}\n`);
21464
+ for (const item of entry.items ?? []) process.stdout.write(` ${dim("-")} ${item.id}\n`);
21465
+ }
21466
+ if (wanted.length === 0) {
21467
+ process.stdout.write(" (nothing matched — check --include, or what the entries declare)\n");
21468
+ return;
21469
+ }
21470
+ warnRunning(await runningEntries());
21471
+ if (!await consent("Take this backup?")) return;
21472
+ }
21473
+ const include = scope.kind === "include" ? scope.ids : void 0;
21474
+ const file = (await (async () => {
21475
+ if (online) {
21476
+ const runtime = await livePanel();
21477
+ if (runtime !== null) {
21478
+ const query = new URLSearchParams();
21479
+ if (options.password !== void 0 && options.password.length > 0) query.set("password", options.password);
21480
+ if (include !== void 0) query.set("include", include.join(","));
21481
+ const answer = await runtime.request(runtime, `/_hh/backups${withParam(suffixOf(query), "confirm", "true")}`, 6e5);
21482
+ if (answer === null) fail(`the control panel is not answering on ${runtime.probeUrl}`);
21483
+ if (answer.status !== 200) refusal(answer);
21484
+ return answer.body;
21485
+ }
21486
+ }
21487
+ const { service } = await offlineBackup();
21488
+ await service.warm();
21489
+ const result = await service.create({
21490
+ password: options.password,
21491
+ include
21492
+ });
21493
+ if (!result.ok) fail(result.error ?? "the backup failed");
21494
+ return { file: result.file };
21495
+ })())?.file;
21496
+ if (file === void 0) fail("the backup reported success but named no archive");
21497
+ if (options.json) {
21498
+ process.stdout.write(`${JSON.stringify({
21499
+ action: "create",
21500
+ apply: true,
21501
+ file
21502
+ }, null, 2)}\n`);
21503
+ return;
21504
+ }
21035
21505
  process.stdout.write(`${green("backup created")} ${file.name} ${dim(`(${human(file.sizeBytes)})`)}\n`);
21036
21506
  }
21507
+ /**
21508
+ * The entries running right now.
21509
+ *
21510
+ * Read from the state files in **both** cases: the panel's own backup view has no per-entry running
21511
+ * flag to read, and the state files are the same witness the panel's supervisor would give — a
21512
+ * persistent entry keeps its nanny alive and rewrites that file whether or not the panel is up.
21513
+ */
21514
+ async function runningEntries() {
21515
+ return (await offlineBackup()).runningNow();
21516
+ }
21037
21517
  async function runBackupRestore(options) {
21038
- const runtime = await livePanel();
21039
- const query = new URLSearchParams({ name: options.name });
21040
- if (options.password !== void 0 && options.password.length > 0) query.set("password", options.password);
21041
- if (options.include !== void 0 && options.include.length > 0) query.set("include", options.include.join(","));
21042
- if (options.confirm) query.set("confirm", "true");
21043
- const answer = await runtime.request(runtime, `/_hh/backups/restore?${query.toString()}`, 6e5);
21044
- if (answer === null) fail(`the control panel is not answering on ${runtime.probeUrl}`);
21045
- if (answer.status !== 200) refusal(answer);
21046
- const plan = answer.body;
21047
- const items = plan?.items ?? [];
21048
- if (!options.confirm) {
21518
+ const scope = options.scope;
21519
+ const service = await usesPanel() ? null : (await offlineBackup()).service;
21520
+ if (service !== null) await service.warm();
21521
+ const plan = await (async () => {
21522
+ if (service !== null) {
21523
+ const archive = service.resolve(options.name);
21524
+ if (archive === null) fail(`no backup named "${options.name}" — \`${invocation()} backup list\` shows them`);
21525
+ return await service.restore(archive, {
21526
+ confirm: false,
21527
+ password: options.password,
21528
+ include: scope.kind === "include" ? scope.ids : void 0
21529
+ });
21530
+ }
21531
+ const runtime = await livePanel();
21532
+ if (runtime === null) fail(`the control panel is not answering — try again once it is up`);
21533
+ const base = new URLSearchParams({ name: options.name });
21534
+ if (options.password !== void 0 && options.password.length > 0) base.set("password", options.password);
21535
+ if (scope.kind === "include") base.set("include", scope.ids.join(","));
21536
+ const answer = await runtime.request(runtime, `/_hh/backups/restore${suffixOf(base)}`, 12e4);
21537
+ if (answer === null) fail(`the control panel is not answering at ${runtime.probeUrl}`);
21538
+ if (answer.status !== 200) refusal(answer);
21539
+ return answer.body;
21540
+ })();
21541
+ const items = (plan?.items ?? []).filter((item) => item.selected !== false);
21542
+ if (options.json && !options.confirm) {
21543
+ process.stdout.write(`${JSON.stringify({
21544
+ action: "restore",
21545
+ apply: false,
21546
+ name: options.name,
21547
+ items,
21548
+ warnings: plan?.warnings ?? []
21549
+ }, null, 2)}\n`);
21550
+ return;
21551
+ }
21552
+ if (!options.json) {
21049
21553
  process.stdout.write(`${bold("Plan")} for ${options.name} — nothing has been written yet\n`);
21050
- for (const item of items) process.stdout.write(` ${item.kind.padEnd(10)} ${item.id}\n`);
21554
+ for (const item of items) process.stdout.write(` ${String(item.kind ?? "item").padEnd(10)} ${item.id ?? item.label ?? ""}\n`);
21051
21555
  for (const warning of plan?.warnings ?? []) process.stdout.write(` ${dim("!")} ${warning}\n`);
21052
- process.stdout.write(`\napply it with \`${invocation()} backup restore ${options.name} --confirm\`\n`);
21053
- return;
21556
+ if (items.length === 0) {
21557
+ process.stdout.write(" (nothing to restore — check --include, or what this host declares)\n");
21558
+ return;
21559
+ }
21560
+ }
21561
+ if (!options.confirm && !await consent(`Restore these ${items.length} item(s) over this host?`)) return;
21562
+ {
21563
+ const applied = await (async () => {
21564
+ if (service !== null) {
21565
+ const archive = service.resolve(options.name);
21566
+ return ((await service.restore(archive, {
21567
+ confirm: true,
21568
+ password: options.password,
21569
+ include: scope.kind === "include" ? scope.ids : void 0
21570
+ })).items ?? []).filter((item) => item.selected !== false);
21571
+ }
21572
+ const runtime = await livePanel();
21573
+ if (runtime === null) fail("the control panel stopped answering — nothing further was written");
21574
+ const base = new URLSearchParams({ name: options.name });
21575
+ if (options.password !== void 0 && options.password.length > 0) base.set("password", options.password);
21576
+ if (scope.kind === "include") base.set("include", scope.ids.join(","));
21577
+ const answer = await runtime.request(runtime, `/_hh/backups/restore${withParam(suffixOf(base), "confirm", "true")}`, 6e5);
21578
+ if (answer === null) fail(`the control panel is not answering at ${runtime.probeUrl}`);
21579
+ if (answer.status !== 200) refusal(answer);
21580
+ return (answer.body?.items ?? plan?.items ?? []).filter((item) => item.selected !== false);
21581
+ })();
21582
+ if (options.json) {
21583
+ process.stdout.write(`${JSON.stringify({
21584
+ action: "restore",
21585
+ apply: true,
21586
+ name: options.name,
21587
+ items: applied,
21588
+ warnings: plan?.warnings ?? []
21589
+ }, null, 2)}\n`);
21590
+ return;
21591
+ }
21592
+ process.stdout.write(`${green("restored")} ${applied.length} ${applied.length === 1 ? "item" : "items"} from ${options.name}\n`);
21593
+ for (const warning of plan?.warnings ?? []) process.stdout.write(` ${dim("!")} ${warning}\n`);
21594
+ if (service !== null) process.stdout.write(dim(`the panel is not running, so nothing was reloaded — the next \`${invocation()} up\` reads what was restored\n`));
21054
21595
  }
21055
- process.stdout.write(`${green("restored")} ${items.length} ${items.length === 1 ? "item" : "items"} from ${options.name}\n`);
21056
- for (const warning of plan?.warnings ?? []) process.stdout.write(` ${dim("!")} ${warning}\n`);
21057
21596
  }
21058
21597
  var backupCommand;
21059
21598
  var init_backup = __esmMin((() => {
21599
+ init_backup_offline();
21060
21600
  init_io();
21061
21601
  init_error_message();
21062
21602
  backupCommand = defineCommand({
@@ -21078,33 +21618,43 @@ var init_backup = __esmMin((() => {
21078
21618
  },
21079
21619
  include: {
21080
21620
  type: "string",
21081
- description: "comma-separated item ids to capture, or to restore"
21621
+ description: "comma-separated item ids to act on"
21622
+ },
21623
+ all: {
21624
+ type: "boolean",
21625
+ description: "act on everything, rather than naming ids"
21082
21626
  },
21083
21627
  confirm: {
21084
21628
  type: "boolean",
21085
- description: "apply a restore instead of only planning it"
21629
+ description: "apply without asking (a restore writes over live data)"
21086
21630
  },
21087
21631
  json: {
21088
21632
  type: "boolean",
21089
- description: "print machine-readable JSON (list)"
21633
+ description: "print the plan or the result as JSON"
21090
21634
  }
21091
21635
  },
21092
21636
  async run({ args }) {
21093
21637
  try {
21094
- const include = args.include === void 0 ? void 0 : args.include.split(",").filter((part) => part.length > 0);
21095
21638
  const action = args.action === void 0 || args.action.length === 0 ? "list" : args.action;
21639
+ const parsed = action === "create" || action === "restore" ? parseScope(args.all === true, args.include) : null;
21096
21640
  if (action === "list") await runBackupList(args.json === true);
21097
- else if (action === "create") await runBackupCreate({
21098
- password: args.password,
21099
- include
21100
- });
21101
- else if (action === "restore") {
21641
+ else if (action === "create") {
21642
+ const scope = parsed ?? await refuseWithoutScope("create", "");
21643
+ await runBackupCreate({
21644
+ password: args.password,
21645
+ scope,
21646
+ confirm: args.confirm === true,
21647
+ json: args.json === true
21648
+ });
21649
+ } else if (action === "restore") {
21102
21650
  if (args.target === void 0 || args.target.length === 0) fail("restore needs the archive name — `backup list` shows them");
21651
+ const scope = parsed ?? await refuseWithoutScope("restore", `?name=${encodeURIComponent(args.target)}`);
21103
21652
  await runBackupRestore({
21104
21653
  name: args.target,
21105
21654
  password: args.password,
21106
- include,
21107
- confirm: args.confirm === true
21655
+ scope,
21656
+ confirm: args.confirm === true,
21657
+ json: args.json === true
21108
21658
  });
21109
21659
  } else fail(`unknown action "${action}" — use list, create or restore`);
21110
21660
  } catch (error) {
@@ -21357,10 +21907,11 @@ var BACKUP_SECTION = {
21357
21907
  lines: [
21358
21908
  ["list | create | restore", "what to do (default: list)"],
21359
21909
  ["<name>", "the archive, for restore — `backup list` shows them"],
21910
+ ["--include <ids>", "comma-separated item ids to act on (required for create/restore)"],
21911
+ ["--all", "act on everything; one of --include or --all is required"],
21360
21912
  ["--password <text>", "encrypt a new archive, or unlock one on restore"],
21361
- ["--include <ids>", "comma-separated item ids to capture, or to restore"],
21362
- ["--confirm", "apply a restore instead of only planning it"],
21363
- ["--json", "machine-readable output (list)"]
21913
+ ["--confirm", "apply without asking (create and restore plan first)"],
21914
+ ["--json", "print the plan or the result as JSON"]
21364
21915
  ]
21365
21916
  };
21366
21917
  var SERVER_SECTION = {