@ipab/cli 0.1.0-rc.5 → 0.1.0-rc.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.
Files changed (94) hide show
  1. package/README.md +82 -15
  2. package/dist/app-templates.js +1 -1
  3. package/dist/app-templates.js.map +1 -1
  4. package/dist/builtins/skill.ipab.car +0 -0
  5. package/dist/builtins/template.node.car +0 -0
  6. package/dist/builtins/template.web-app.car +0 -0
  7. package/dist/cli.d.ts +3 -1
  8. package/dist/cli.d.ts.map +1 -1
  9. package/dist/cli.js +561 -272
  10. package/dist/cli.js.map +1 -1
  11. package/dist/content-provider.d.ts +1 -1
  12. package/dist/content-provider.d.ts.map +1 -1
  13. package/dist/content-provider.js +4 -3
  14. package/dist/content-provider.js.map +1 -1
  15. package/dist/context.d.ts +0 -1
  16. package/dist/context.d.ts.map +1 -1
  17. package/dist/context.js +0 -10
  18. package/dist/context.js.map +1 -1
  19. package/dist/doctor.d.ts +29 -0
  20. package/dist/doctor.d.ts.map +1 -0
  21. package/dist/doctor.js +576 -0
  22. package/dist/doctor.js.map +1 -0
  23. package/dist/identity.d.ts +1 -1
  24. package/dist/identity.d.ts.map +1 -1
  25. package/dist/identity.js +9 -9
  26. package/dist/identity.js.map +1 -1
  27. package/dist/ipc.d.ts +1 -2
  28. package/dist/ipc.d.ts.map +1 -1
  29. package/dist/ipc.js +1 -10
  30. package/dist/ipc.js.map +1 -1
  31. package/dist/kubo-install.d.ts +18 -1
  32. package/dist/kubo-install.d.ts.map +1 -1
  33. package/dist/kubo-install.js +424 -61
  34. package/dist/kubo-install.js.map +1 -1
  35. package/dist/kubo-release.d.ts +19 -0
  36. package/dist/kubo-release.d.ts.map +1 -1
  37. package/dist/kubo-release.js +164 -0
  38. package/dist/kubo-release.js.map +1 -1
  39. package/dist/kubo.d.ts +1 -0
  40. package/dist/kubo.d.ts.map +1 -1
  41. package/dist/kubo.js +102 -96
  42. package/dist/kubo.js.map +1 -1
  43. package/dist/pins.d.ts +15 -17
  44. package/dist/pins.d.ts.map +1 -1
  45. package/dist/pins.js +144 -106
  46. package/dist/pins.js.map +1 -1
  47. package/dist/publish-source.d.ts +3 -0
  48. package/dist/publish-source.d.ts.map +1 -0
  49. package/dist/publish-source.js +85 -0
  50. package/dist/publish-source.js.map +1 -0
  51. package/dist/runtime.d.ts.map +1 -1
  52. package/dist/runtime.js +1 -3
  53. package/dist/runtime.js.map +1 -1
  54. package/dist/state-storage-windows.js +1 -1
  55. package/dist/state-storage.d.ts +3 -1
  56. package/dist/state-storage.d.ts.map +1 -1
  57. package/dist/state-storage.js +38 -7
  58. package/dist/state-storage.js.map +1 -1
  59. package/dist/state.d.ts +40 -6
  60. package/dist/state.d.ts.map +1 -1
  61. package/dist/state.js +208 -82
  62. package/dist/state.js.map +1 -1
  63. package/dist/swarm-envelope.d.ts +1 -0
  64. package/dist/swarm-envelope.d.ts.map +1 -1
  65. package/dist/swarm-envelope.js +12 -0
  66. package/dist/swarm-envelope.js.map +1 -1
  67. package/dist/swarm.d.ts +64 -8
  68. package/dist/swarm.d.ts.map +1 -1
  69. package/dist/swarm.js +858 -106
  70. package/dist/swarm.js.map +1 -1
  71. package/package.json +4 -4
  72. package/src/app-templates.ts +1 -1
  73. package/src/cli.ts +702 -338
  74. package/src/content-provider.ts +4 -2
  75. package/src/context.ts +0 -10
  76. package/src/doctor.ts +902 -0
  77. package/src/identity.ts +10 -10
  78. package/src/ipc.ts +0 -8
  79. package/src/kubo-install.ts +562 -78
  80. package/src/kubo-release.ts +213 -0
  81. package/src/kubo.ts +134 -106
  82. package/src/pins.ts +188 -126
  83. package/src/publish-source.ts +103 -0
  84. package/src/runtime.ts +0 -3
  85. package/src/state-storage-windows.ts +1 -1
  86. package/src/state-storage.ts +53 -7
  87. package/src/state.ts +357 -98
  88. package/src/swarm-envelope.ts +14 -0
  89. package/src/swarm.ts +1234 -125
  90. package/dist/setup.d.ts +0 -8
  91. package/dist/setup.d.ts.map +0 -1
  92. package/dist/setup.js +0 -27
  93. package/dist/setup.js.map +0 -1
  94. package/src/setup.ts +0 -34
@@ -4,11 +4,11 @@ import { constants } from "node:fs";
4
4
  import { access, chmod, link, lstat, mkdir, open, readdir, rename, rm, } from "node:fs/promises";
5
5
  import { join } from "node:path";
6
6
  import { promisify } from "node:util";
7
- import { boundedText } from "@ipab/bundle/pointer/scope";
8
7
  import { nodeError } from "./authoring.js";
9
8
  import { HostError } from "./errors.js";
10
9
  import { protectedPath, secureNew } from "./identity.js";
11
- import { KUBO_VERSION, releaseDigests } from "./kubo-release.js";
10
+ import { assetName, compatibleVersion, compareKuboVersions, enumeratedRelease, latestKuboRelease, officialDownloadUrl, KUBO_REPO_VERSION, KUBO_VERSION, releaseDigests, } from "./kubo-release.js";
11
+ import { requireAccountOnlyMany } from "@ipab/bundle/pointer/protected-files";
12
12
  import { privateDirectory, readPrivate, withPrivateLock, writePrivate, } from "./swarm-files.js";
13
13
  const run = promisify(execFile);
14
14
  const MAX_ARCHIVE = 150 * 1024 * 1024;
@@ -48,8 +48,8 @@ function failure(cause) {
48
48
  return "permission denied or unsafe ownership";
49
49
  return "operation failed";
50
50
  }
51
- export function setupFailure(phase, source, cause) {
52
- return new HostError(`Kubo ${KUBO_VERSION} ${process.platform}-${process.arch}, ${phase} (${source}): ${failure(cause)}. Check the indicated source or account permissions and retry setup.`, 1, "KUBO_SETUP_FAILED", phase);
51
+ export function setupFailure(phase, source, cause, version = KUBO_VERSION) {
52
+ return new HostError(`Kubo ${version} ${process.platform}-${process.arch}, ${phase} (${source}): ${failure(cause)}. Check the indicated source or account permissions and retry ipab doctor --fix.`, 1, "KUBO_SETUP_FAILED", phase);
53
53
  }
54
54
  async function exists(path) {
55
55
  try {
@@ -86,47 +86,178 @@ async function* fileBytes(path, limit) {
86
86
  await handle.close();
87
87
  }
88
88
  }
89
- async function digest(path, limit) {
89
+ export async function digest(path, limit) {
90
90
  const hash = createHash("sha256");
91
91
  for await (const chunk of fileBytes(path, limit))
92
92
  hash.update(chunk);
93
93
  return hash.digest("hex");
94
94
  }
95
95
  async function verifyProgram(executable, installed) {
96
- if (installed.version !== KUBO_VERSION ||
96
+ if (!compatibleVersion(installed.version) ||
97
97
  installed.hash !== (await digest(executable, 512 * 1024 * 1024)))
98
98
  throw new HostError("Kubo installation integrity mismatch; do not use this binary.");
99
99
  if (process.platform !== "win32")
100
100
  await access(executable, constants.X_OK);
101
101
  }
102
- function deadline(ms, signal) {
103
- const timeout = AbortSignal.timeout(ms);
104
- return signal ? AbortSignal.any([signal, timeout]) : timeout;
102
+ export async function inspectKubo(stateDir, release, signal, verification) {
103
+ signal?.throwIfAborted();
104
+ if (await exists(stateDir))
105
+ await protectedPath(stateDir, true);
106
+ const directory = join(stateDir, "kubo-bin");
107
+ if (!(await exists(directory)))
108
+ return;
109
+ await protectedPath(directory, true);
110
+ const names = await readdir(directory);
111
+ if (!names.length || names.every((name) => name === "operation.sqlite"))
112
+ return;
113
+ if (names.includes(journal))
114
+ throw new HostError("Kubo installation is interrupted; inspect the installation journal before repair.");
115
+ const executable = join(directory, process.platform === "win32" ? "ipfs.exe" : "ipfs");
116
+ const installed = await readPrivate(directory, record, [
117
+ { path: executable },
118
+ ]);
119
+ if (!installed)
120
+ throw new HostError("Unrecorded Kubo installation; it was not adopted.");
121
+ await requireAccountOnlyMany([
122
+ directory,
123
+ executable,
124
+ join(directory, record),
125
+ ]);
126
+ await verifyProgram(executable, installed);
127
+ const filename = assetName(installed.version);
128
+ const source = verification?.version === installed.version
129
+ ? verification
130
+ : enumeratedRelease(release, installed.version);
131
+ const expected = installed.version === KUBO_VERSION
132
+ ? releaseDigests[filename]
133
+ : source?.digest;
134
+ if (!expected) {
135
+ return { ...installed, provenance: false };
136
+ }
137
+ if (installed.archiveDigest !== undefined &&
138
+ installed.archiveDigest !== expected)
139
+ throw new HostError("Installed Kubo receipt conflicts with the trusted official archive digest.");
140
+ const cache = join(stateDir, "kubo-cache", filename);
141
+ if (!(await exists(cache)))
142
+ return { ...installed, provenance: false };
143
+ await verifyCache(cache, expected);
144
+ {
145
+ // Stream an existing verified archive member to memory, never unpack files
146
+ // or fetch an archive while inspecting the installation.
147
+ const extracted = await run("tar", [
148
+ "-xOf",
149
+ cache,
150
+ `kubo/${process.platform === "win32" ? "ipfs.exe" : "ipfs"}`,
151
+ ], {
152
+ encoding: "buffer",
153
+ signal,
154
+ maxBuffer: 512 * 1024 * 1024,
155
+ timeout: 30_000,
156
+ windowsHide: true,
157
+ });
158
+ if (!extracted.stdout.length)
159
+ throw new HostError("The official archive did not provide a nonempty Kubo executable member.");
160
+ if (createHash("sha256").update(extracted.stdout).digest("hex") !==
161
+ installed.hash)
162
+ throw new HostError("Installed Kubo does not match the verified official archive.");
163
+ }
164
+ signal?.throwIfAborted();
165
+ return { ...installed, provenance: true };
105
166
  }
106
- async function officialAsset(filename, expected, signal) {
107
- const release = await fetch(`https://api.github.com/repos/ipfs/kubo/releases/tags/v${KUBO_VERSION}`, {
108
- redirect: "error",
109
- signal: deadline(30_000, signal),
110
- headers: { accept: "application/vnd.github+json" },
111
- });
112
- if (!release.ok) {
113
- await release.body?.cancel();
114
- throw new HostError(`Could not verify official Kubo release (HTTP ${release.status}).`);
167
+ async function verifyCache(path, expected) {
168
+ try {
169
+ await requireAccountOnlyMany([join(path, ".."), path]);
170
+ if ((await digest(path, MAX_ARCHIVE)) !== expected)
171
+ throw new HostError("Kubo archive cache checksum mismatch; inspect the cache manually.", 1, "KUBO_CACHE_INVALID");
115
172
  }
116
- const metadata = JSON.parse(await boundedText(release));
117
- const url = `https://github.com/ipfs/kubo/releases/download/v${KUBO_VERSION}/${filename}`;
118
- const assets = metadata.assets.filter((item) => item.name === filename);
119
- if (metadata.tag_name !== `v${KUBO_VERSION}` ||
120
- metadata.draft !== false ||
121
- metadata.prerelease !== false ||
122
- assets.length !== 1 ||
123
- assets[0]?.digest !== `sha256:${expected}` ||
124
- !Number.isSafeInteger(assets[0].size) ||
125
- assets[0].size <= 0 ||
126
- assets[0].size > MAX_ARCHIVE ||
127
- assets[0].browser_download_url !== url)
128
- throw new HostError("Official stable Kubo archive/digest/size unavailable or inconsistent with the bundled release.");
129
- return { url, size: assets[0].size };
173
+ catch (cause) {
174
+ if (cause instanceof HostError && cause.code === "KUBO_CACHE_INVALID")
175
+ throw cause;
176
+ throw new HostError("Kubo archive cache is invalid or unprotected; inspect it manually.", 1, "KUBO_CACHE_INVALID");
177
+ }
178
+ }
179
+ export async function inspectKuboCache(stateDir, release) {
180
+ const directory = join(stateDir, "kubo-cache");
181
+ if (!(await exists(directory)))
182
+ return false;
183
+ await protectedPath(directory, true);
184
+ await requireAccountOnlyMany([directory]);
185
+ const cache = join(directory, assetName(release.version));
186
+ if (!(await exists(cache)))
187
+ return false;
188
+ await verifyCache(cache, release.digest);
189
+ return true;
190
+ }
191
+ export async function recoverableInstallation(stateDir) {
192
+ const directory = join(stateDir, "kubo-bin");
193
+ if (!(await exists(directory)))
194
+ return false;
195
+ const intent = await readPrivate(directory, journal);
196
+ if (!intent)
197
+ return false;
198
+ if (typeof intent.stage !== "string" ||
199
+ !/^install-[a-f0-9]{8}(?:-[a-f0-9]{4}){3}-[a-f0-9]{12}$/.test(intent.stage))
200
+ return false;
201
+ await requireAccountOnlyMany([directory, join(directory, journal)]);
202
+ const stage = join(directory, intent.stage);
203
+ if (await exists(stage)) {
204
+ await protectedPath(stage, true);
205
+ await requireAccountOnlyMany([stage]);
206
+ }
207
+ const executable = join(directory, process.platform === "win32" ? "ipfs.exe" : "ipfs");
208
+ const installed = await readPrivate(directory, record);
209
+ const original = await readPrivate(stage, "original.json");
210
+ if (original) {
211
+ await requireAccountOnlyMany([
212
+ join(stage, "original"),
213
+ join(stage, "original.json"),
214
+ ]);
215
+ await verifyProgram(join(stage, "original"), original);
216
+ if (!installed)
217
+ return false;
218
+ if (installed.hash !== original.hash ||
219
+ installed.version !== original.version)
220
+ await verifyProgram(executable, installed);
221
+ }
222
+ else if (installed) {
223
+ await requireAccountOnlyMany([executable, join(directory, record)]);
224
+ await verifyProgram(executable, installed);
225
+ }
226
+ else if (await exists(executable)) {
227
+ const pending = await readPrivate(stage, record);
228
+ if (!pending)
229
+ return false;
230
+ await requireAccountOnlyMany([executable, join(stage, record)]);
231
+ await verifyProgram(executable, pending);
232
+ }
233
+ return true;
234
+ }
235
+ export async function runningManagedNodes(stateDir) {
236
+ const directory = join(stateDir, "swarm-nodes");
237
+ if (!(await exists(directory)))
238
+ return false;
239
+ await protectedPath(directory, true);
240
+ for (const name of await readdir(directory)) {
241
+ const root = join(directory, name);
242
+ await protectedPath(root, true);
243
+ const record = await readPrivate(root, "node.json");
244
+ if (record?.pid !== undefined) {
245
+ if (!Number.isSafeInteger(record.pid) || Number(record.pid) <= 0)
246
+ throw new HostError("Invalid managed node process record; upgrade is blocked.");
247
+ try {
248
+ process.kill(Number(record.pid), 0);
249
+ return true;
250
+ }
251
+ catch (cause) {
252
+ if (!nodeError(cause, "ESRCH"))
253
+ return true;
254
+ }
255
+ }
256
+ // A repo lock without a trustworthy process record is not proof of a stopped node.
257
+ if (await exists(join(root, "repo", "repo.lock")))
258
+ return true;
259
+ }
260
+ return false;
130
261
  }
131
262
  async function transfer(target, source, options) {
132
263
  const handle = await open(target, "wx", 0o600);
@@ -144,8 +275,10 @@ async function transfer(target, source, options) {
144
275
  if ("archive" in source)
145
276
  stream = fileBytes(source.archive, MAX_ARCHIVE);
146
277
  else {
147
- const totalMiB = (source.size / (1024 * 1024)).toFixed(1);
148
- options.diagnostic?.(`Downloading ${source.url.split("/").at(-1)} from GitHub (${totalMiB} MiB)...`);
278
+ const totalMiB = source.size === undefined
279
+ ? undefined
280
+ : (source.size / (1024 * 1024)).toFixed(1);
281
+ options.diagnostic?.(`Downloading ${source.url.split("/").at(-1)} from GitHub (${totalMiB ? `${totalMiB} MiB` : "total size unavailable; bounded to 150 MiB"})...`);
149
282
  if (options.diagnostic)
150
283
  progress = setInterval(() => {
151
284
  try {
@@ -154,11 +287,16 @@ async function transfer(target, source, options) {
154
287
  const waiting = idle >= 5 ? `; waiting for data (${idle}s without new data)` : "";
155
288
  const elapsed = startedAt === undefined ? 0 : (now - startedAt) / 1000;
156
289
  let eta = idle >= 5 ? "unavailable" : "estimating";
157
- if (total > 0 && elapsed > 0 && idle < 5) {
290
+ if (source.size !== undefined &&
291
+ total > 0 &&
292
+ elapsed > 0 &&
293
+ idle < 5) {
158
294
  const seconds = Math.ceil((Math.max(0, source.size - total) * elapsed) / total);
159
295
  eta = `~${seconds < 60 ? `${seconds}s` : `${Math.floor(seconds / 60)}m ${seconds % 60}s`}`;
160
296
  }
161
- options.diagnostic?.(`Kubo: ${(total / (1024 * 1024)).toFixed(1)}/${totalMiB} MiB (${((total * 100) / source.size).toFixed(1)}%); ETA ${eta}${waiting}`, true);
297
+ options.diagnostic?.(source.size === undefined
298
+ ? `Kubo: ${(total / (1024 * 1024)).toFixed(1)} MiB received; total size unavailable${waiting}`
299
+ : `Kubo: ${(total / (1024 * 1024)).toFixed(1)}/${totalMiB} MiB (${((total * 100) / source.size).toFixed(1)}%); ETA ${eta}${waiting}`, true);
162
300
  }
163
301
  catch (cause) {
164
302
  controller.abort(cause);
@@ -183,7 +321,7 @@ async function transfer(target, source, options) {
183
321
  receivedAt = Date.now();
184
322
  }
185
323
  signal.throwIfAborted();
186
- if ("url" in source && total !== source.size)
324
+ if ("url" in source && source.size !== undefined && total !== source.size)
187
325
  throw new HostError("Kubo archive size mismatch.");
188
326
  await handle.sync();
189
327
  }
@@ -197,6 +335,114 @@ async function transfer(target, source, options) {
197
335
  }
198
336
  return total;
199
337
  }
338
+ const verificationJournal = "verification.json";
339
+ async function recoverVerification(directory) {
340
+ const intent = await readPrivate(directory, verificationJournal);
341
+ if (intent === undefined)
342
+ return;
343
+ if (typeof intent !== "object" ||
344
+ intent === null ||
345
+ Object.keys(intent).length !== 1 ||
346
+ !("stage" in intent) ||
347
+ typeof intent.stage !== "string" ||
348
+ !/^verify-[a-f0-9]{8}(?:-[a-f0-9]{4}){3}-[a-f0-9]{12}$/.test(intent.stage))
349
+ throw new HostError("Unrecognized archive verification journal; inspect it manually.");
350
+ await requireAccountOnlyMany([
351
+ directory,
352
+ join(directory, verificationJournal),
353
+ ]);
354
+ const stage = join(directory, intent.stage);
355
+ if (await exists(stage)) {
356
+ await protectedPath(stage, true);
357
+ await requireAccountOnlyMany([stage]);
358
+ await rm(stage, { recursive: true });
359
+ }
360
+ await rm(join(directory, verificationJournal));
361
+ }
362
+ async function cacheVerificationArchive(stateDir, source, options) {
363
+ const directory = await privateDirectory(stateDir, "kubo-cache");
364
+ await requireAccountOnlyMany([directory]);
365
+ await recoverVerification(directory);
366
+ const target = join(directory, source.filename);
367
+ if (await exists(target)) {
368
+ await verifyCache(target, source.digest);
369
+ return;
370
+ }
371
+ const name = `verify-${randomUUID()}`, stage = join(directory, name);
372
+ if (await exists(stage))
373
+ throw new HostError("Verification staging path exists; retry later.");
374
+ await writePrivate(directory, verificationJournal, { stage: name });
375
+ let created = false;
376
+ try {
377
+ await mkdir(stage, { mode: 0o700 });
378
+ created = true;
379
+ await secureNew(stage, true);
380
+ const temporary = join(stage, source.filename);
381
+ await transfer(temporary, options.archive
382
+ ? { archive: options.archive }
383
+ : {
384
+ url: source.url,
385
+ ...(source.size === undefined ? {} : { size: source.size }),
386
+ }, options);
387
+ if ((await digest(temporary, MAX_ARCHIVE)) !== source.digest)
388
+ throw new HostError("Official verification archive checksum mismatch; no cache or executable was replaced.");
389
+ options.signal?.throwIfAborted();
390
+ try {
391
+ await link(temporary, target);
392
+ }
393
+ catch (cause) {
394
+ if (!nodeError(cause, "EEXIST"))
395
+ throw cause;
396
+ await verifyCache(target, source.digest);
397
+ }
398
+ }
399
+ finally {
400
+ if (created)
401
+ await rm(stage, { recursive: true, force: true });
402
+ await rm(join(directory, verificationJournal));
403
+ }
404
+ }
405
+ export async function verifyExistingKuboArchive(stateDir, source, options = {}) {
406
+ try {
407
+ options.signal?.throwIfAborted();
408
+ if (!compatibleVersion(source.version) ||
409
+ source.filename !== assetName(source.version) ||
410
+ source.url !== officialDownloadUrl(source.version, source.filename) ||
411
+ !/^[a-f0-9]{64}$/.test(source.digest) ||
412
+ (source.size !== undefined &&
413
+ (!Number.isSafeInteger(source.size) ||
414
+ source.size <= 0 ||
415
+ source.size > MAX_ARCHIVE)) ||
416
+ (source.version === KUBO_VERSION
417
+ ? source.digest !== releaseDigests[source.filename]
418
+ : source.size === undefined))
419
+ throw new HostError("A trusted official same-version archive is required for verification.");
420
+ const directory = join(stateDir, "kubo-bin");
421
+ await protectedPath(stateDir, true);
422
+ await protectedPath(directory, true);
423
+ await requireAccountOnlyMany([stateDir, directory]);
424
+ return await withPrivateLock(directory, async () => {
425
+ const installed = await inspectKubo(stateDir, options.release, options.signal, source);
426
+ if (!installed || installed.version !== source.version)
427
+ throw new HostError("Installed Kubo changed since authorization; no program was replaced.");
428
+ const executable = join(directory, process.platform === "win32" ? "ipfs.exe" : "ipfs");
429
+ if (installed.provenance)
430
+ return executable;
431
+ options.diagnostic?.(`Caching the official Kubo ${source.version} archive for byte verification only; no reinstall or node stopping.`);
432
+ await cacheVerificationArchive(stateDir, source, options);
433
+ const verified = await inspectKubo(stateDir, options.release, options.signal, source);
434
+ if (!verified?.provenance || verified.version !== source.version)
435
+ throw new HostError("Official archive verification did not establish provenance; no program was replaced.");
436
+ options.signal?.throwIfAborted();
437
+ options.diagnostic?.(`Existing Kubo ${source.version} matches the official archive; reused without reinstall or node stopping.`);
438
+ return executable;
439
+ }, options.signal);
440
+ }
441
+ catch (cause) {
442
+ options.signal?.throwIfAborted();
443
+ throw setupFailure("same-version archive verification", "official archive cache and existing program", cause, source.version);
444
+ }
445
+ }
200
446
  async function clean(directory, stage) {
201
447
  await rm(stage, { recursive: true, force: true });
202
448
  await rm(join(directory, journal));
@@ -214,6 +460,21 @@ async function recover(directory, executable, installed) {
214
460
  const stage = join(directory, intent.stage);
215
461
  if (await exists(stage))
216
462
  await protectedPath(stage, true);
463
+ const original = await readPrivate(stage, "original.json");
464
+ if (original) {
465
+ const backup = join(stage, "original");
466
+ await verifyProgram(backup, original);
467
+ if (installed?.hash === original.hash &&
468
+ installed.version === original.version) {
469
+ await rename(backup, executable);
470
+ await rename(join(stage, "original.json"), join(directory, record));
471
+ installed = original;
472
+ }
473
+ else if (installed)
474
+ await verifyProgram(executable, installed);
475
+ else
476
+ throw new HostError("Interrupted Kubo upgrade has an inconsistent receipt; inspect it manually.");
477
+ }
217
478
  if (!installed && (await exists(executable))) {
218
479
  const pending = await readPrivate(stage, record, [
219
480
  { path: executable },
@@ -229,6 +490,7 @@ async function recover(directory, executable, installed) {
229
490
  }
230
491
  export async function kuboBinary(stateDir, options = {}) {
231
492
  let phase = "installation", source = "protected local installation";
493
+ let targetVersion = options.release?.version ?? KUBO_VERSION;
232
494
  try {
233
495
  options.signal?.throwIfAborted();
234
496
  const directory = await privateDirectory(stateDir, "kubo-bin");
@@ -237,50 +499,77 @@ export async function kuboBinary(stateDir, options = {}) {
237
499
  if (!["windows", "darwin", "linux"].includes(platform) ||
238
500
  !["x64", "arm64"].includes(process.arch))
239
501
  throw new HostError("Unsupported Kubo platform.");
240
- const arch = process.arch === "x64" ? "amd64" : "arm64";
241
- const filename = `kubo_v${KUBO_VERSION}_${platform}-${arch}.${platform === "windows" ? "zip" : "tar.gz"}`;
242
- const expected = releaseDigests[filename];
243
- if (!expected || !/^[a-f0-9]{64}$/.test(expected))
244
- throw new HostError("No trusted archive digest for this release/platform.");
245
502
  const program = platform === "windows" ? "ipfs.exe" : "ipfs";
246
503
  const executable = join(directory, program);
247
504
  const install = async () => {
248
505
  let installed = await readPrivate(directory, record, [
249
506
  { path: executable },
250
507
  ]);
508
+ installed = await recover(directory, executable, installed);
251
509
  if (installed !== undefined) {
252
- options.diagnostic?.(`Verifying installed Kubo ${KUBO_VERSION}...`);
510
+ options.diagnostic?.(`Verifying installed Kubo ${installed.version}...`);
253
511
  await verifyProgram(executable, installed);
254
512
  }
255
- installed = await recover(directory, executable, installed);
256
513
  if (options.diagnostic &&
257
514
  (await readdir(directory)).some((name) => /^(?:extract-[\w-]{43}|[\w-]{43}\.(?:zip|tar\.gz)|(?:install-|\.write-)[a-f0-9-]{36})$/.test(name)))
258
515
  options.diagnostic("Untracked Kubo staging files were left untouched. Inspect kubo-bin manually; do not delete the verified installation.");
259
- if (installed) {
516
+ if (installed &&
517
+ (!options.upgrade ||
518
+ (options.release &&
519
+ compareKuboVersions(options.release.version, installed.version) <=
520
+ 0))) {
260
521
  if (options.archive !== undefined) {
261
522
  phase = "archive verification";
262
523
  source = "local archive";
524
+ const expected = options.release?.digest ?? releaseDigests[assetName(KUBO_VERSION)];
263
525
  if ((await digest(options.archive, MAX_ARCHIVE)) !== expected)
264
526
  throw new HostError("Kubo archive checksum mismatch.");
265
527
  }
528
+ options.diagnostic?.(`Kubo ${installed.version} bytes match the protected installation receipt; reusing the existing installation. No download or reinstall needed. Cryptographic archive provenance requires doctor verification.`);
266
529
  return executable;
267
530
  }
268
- if (await exists(executable))
531
+ if (!installed && (await exists(executable)))
269
532
  throw new HostError("Unrecorded Kubo executable; move it aside manually. It was not adopted.");
270
- let input;
271
- if (options.archive !== undefined)
272
- input = { archive: options.archive };
273
- else {
533
+ let selected = options.release;
534
+ if (!selected && options.archive === undefined) {
274
535
  phase = "release metadata";
275
536
  source = "api.github.com/ipfs/kubo";
276
- options.diagnostic?.(`Checking official Kubo ${KUBO_VERSION} release (timeout: 30s)...`);
277
- input = await officialAsset(filename, expected, options.signal);
537
+ options.diagnostic?.("Selecting the latest verified compatible official Kubo release...");
538
+ selected = await latestKuboRelease(options.signal);
278
539
  }
540
+ const version = selected?.version ?? KUBO_VERSION;
541
+ targetVersion = version;
542
+ if (!compatibleVersion(version))
543
+ throw new HostError("Unsupported Kubo version.");
544
+ const filename = assetName(version);
545
+ const expected = selected?.digest ?? releaseDigests[filename];
546
+ if (!expected || !/^[a-f0-9]{64}$/.test(expected))
547
+ throw new HostError("No trusted archive digest for this release/platform.");
548
+ let input;
549
+ if (installed &&
550
+ (compareKuboVersions(version, installed.version) <= 0 ||
551
+ (await runningManagedNodes(stateDir))))
552
+ throw new HostError("Kubo upgrade is blocked; managed nodes must be stopped by their operator before switching.");
553
+ const cacheDirectory = await privateDirectory(stateDir, "kubo-cache");
554
+ await requireAccountOnlyMany([cacheDirectory]);
555
+ const cached = join(cacheDirectory, filename);
556
+ if (await exists(cached)) {
557
+ phase = "cache verification";
558
+ await verifyCache(cached, expected);
559
+ options.diagnostic?.("Reusing the verified official Kubo archive cache.");
560
+ input = { archive: cached };
561
+ }
562
+ else if (options.archive !== undefined)
563
+ input = { archive: options.archive };
564
+ else if (selected)
565
+ input = selected;
566
+ else
567
+ throw new HostError("A verified latest compatible Kubo target is required.");
279
568
  phase = "installation";
280
569
  source = "protected local staging";
281
570
  const name = `install-${randomUUID()}`, stage = join(directory, name);
282
571
  if (await exists(stage))
283
- throw new HostError("Staging path already exists; retry setup.");
572
+ throw new HostError("Staging path already exists; retry ipab doctor --fix.");
284
573
  await writePrivate(directory, journal, { stage: name });
285
574
  let placed = false, created = false;
286
575
  try {
@@ -297,6 +586,11 @@ export async function kuboBinary(stateDir, options = {}) {
297
586
  options.diagnostic?.(`Kubo download complete: ${(total / (1024 * 1024)).toFixed(1)} MiB. Verifying checksum...`);
298
587
  if ((await digest(archive, MAX_ARCHIVE)) !== expected)
299
588
  throw new HostError("Kubo archive checksum mismatch.");
589
+ if (!(await exists(cached))) {
590
+ await link(archive, cached);
591
+ }
592
+ else
593
+ await verifyCache(cached, expected);
300
594
  phase = "extraction";
301
595
  source = "verified release archive";
302
596
  options.diagnostic?.("Extracting and verifying the Kubo executable...");
@@ -325,26 +619,83 @@ export async function kuboBinary(stateDir, options = {}) {
325
619
  timeout: 10_000,
326
620
  windowsHide: true,
327
621
  });
328
- if (version.stdout.trim() !== KUBO_VERSION)
622
+ const reportedVersion = version.stdout.trim();
623
+ if (!compatibleVersion(reportedVersion) ||
624
+ compareKuboVersions(reportedVersion, selected?.version ?? KUBO_VERSION) !== 0)
329
625
  throw new HostError("Kubo executable version mismatch.");
626
+ const runtimeOptions = {
627
+ signal: options.signal,
628
+ env: {
629
+ ...process.env,
630
+ HOME: stage,
631
+ USERPROFILE: stage,
632
+ IPFS_PATH: join(stage, "version-repo"),
633
+ },
634
+ timeout: 10_000,
635
+ windowsHide: true,
636
+ };
637
+ const repoVersion = await run(extracted, ["version", "--repo"], runtimeOptions);
638
+ if (repoVersion.stdout.trim() !== KUBO_REPO_VERSION)
639
+ throw new HostError("Kubo candidate requires an unsupported repo version; no migration or upgrade was performed.");
640
+ const commands = await run(extracted, ["commands"], runtimeOptions);
641
+ const available = new Set(commands.stdout
642
+ .trim()
643
+ .split(/\r?\n/)
644
+ .map((line) => line.trim()));
645
+ if ([
646
+ "id",
647
+ "swarm connect",
648
+ "swarm peering ls",
649
+ "dag import",
650
+ "dag export",
651
+ "pin add",
652
+ "block get",
653
+ "config",
654
+ ].some((name) => !available.has(`ipfs ${name}`)))
655
+ throw new HostError("Kubo candidate lacks required IPAB runtime commands; the existing installation was retained.");
330
656
  const verified = {
331
- version: KUBO_VERSION,
657
+ version: selected?.version ?? KUBO_VERSION,
332
658
  hash: await digest(extracted, 512 * 1024 * 1024),
659
+ archiveDigest: expected,
333
660
  };
334
661
  phase = "installation";
335
662
  source = "protected local installation";
336
663
  await writePrivate(stage, record, verified);
337
- // Atomic and exclusive: never overwrite a binary placed by another actor.
338
- await link(extracted, executable);
664
+ if (installed) {
665
+ // Keep the original executable and receipt until the candidate is fully verified.
666
+ if (await runningManagedNodes(stateDir))
667
+ throw new HostError("Managed node started during inspection; upgrade is blocked.");
668
+ await link(executable, join(stage, "original"));
669
+ await writePrivate(stage, "original.json", installed);
670
+ await rename(extracted, executable);
671
+ }
672
+ else
673
+ await link(extracted, executable);
339
674
  placed = true;
340
- await rename(join(stage, record), join(directory, record));
675
+ try {
676
+ await rename(join(stage, record), join(directory, record));
677
+ }
678
+ catch (cause) {
679
+ if (installed) {
680
+ await rename(join(stage, "original"), executable);
681
+ await rename(join(stage, "original.json"), join(directory, record));
682
+ placed = false;
683
+ }
684
+ throw cause;
685
+ }
341
686
  placed = false;
342
687
  return executable;
343
688
  }
344
689
  finally {
345
690
  // If rollback itself fails, retain the journal and verified candidate record for recovery.
346
- if (placed)
347
- await rm(executable);
691
+ if (placed) {
692
+ if (installed) {
693
+ await rename(join(stage, "original"), executable);
694
+ await rename(join(stage, "original.json"), join(directory, record));
695
+ }
696
+ else
697
+ await rm(executable);
698
+ }
348
699
  if (created)
349
700
  await clean(directory, stage);
350
701
  else
@@ -355,7 +706,19 @@ export async function kuboBinary(stateDir, options = {}) {
355
706
  }
356
707
  catch (cause) {
357
708
  options.signal?.throwIfAborted();
358
- throw setupFailure(phase, source, cause);
709
+ throw setupFailure(phase, source, cause, targetVersion);
359
710
  }
360
711
  }
712
+ export async function withKuboProgram(stateDir, operation, signal) {
713
+ const binary = await kuboBinary(stateDir, signal ? { signal } : {});
714
+ // Node preparation/startup shares the install lock through PID persistence,
715
+ // preventing a node launch racing the final upgrade/switch check.
716
+ return withPrivateLock(join(stateDir, "kubo-bin"), async () => {
717
+ const installed = await readPrivate(join(stateDir, "kubo-bin"), record, [{ path: binary }]);
718
+ if (!installed)
719
+ throw new HostError("Managed Kubo installation disappeared before node startup.");
720
+ await verifyProgram(binary, installed);
721
+ return operation(binary);
722
+ }, signal);
723
+ }
361
724
  //# sourceMappingURL=kubo-install.js.map