@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
@@ -14,11 +14,23 @@ import {
14
14
  } from "node:fs/promises";
15
15
  import { join } from "node:path";
16
16
  import { promisify } from "node:util";
17
- import { boundedText } from "@ipab/bundle/pointer/scope";
18
17
  import { nodeError } from "./authoring.js";
19
18
  import { HostError } from "./errors.js";
20
19
  import { protectedPath, secureNew } from "./identity.js";
21
- import { KUBO_VERSION, releaseDigests } from "./kubo-release.js";
20
+ import {
21
+ assetName,
22
+ compatibleVersion,
23
+ compareKuboVersions,
24
+ enumeratedRelease,
25
+ latestKuboRelease,
26
+ officialDownloadUrl,
27
+ KUBO_REPO_VERSION,
28
+ KUBO_VERSION,
29
+ releaseDigests,
30
+ type KuboArchive,
31
+ type KuboRelease,
32
+ } from "./kubo-release.js";
33
+ import { requireAccountOnlyMany } from "@ipab/bundle/pointer/protected-files";
22
34
  import {
23
35
  privateDirectory,
24
36
  readPrivate,
@@ -33,11 +45,15 @@ const record = "installation.json";
33
45
  interface Installation {
34
46
  version: string;
35
47
  hash: string;
48
+ archiveDigest?: string;
49
+ provenance?: boolean;
36
50
  }
37
51
  export interface InstallOptions {
38
52
  archive?: string;
39
53
  diagnostic?: (line: string, progress?: boolean) => void;
40
54
  signal?: AbortSignal;
55
+ release?: KuboRelease;
56
+ upgrade?: boolean;
41
57
  }
42
58
 
43
59
  function failure(cause: unknown): string {
@@ -79,9 +95,10 @@ export function setupFailure(
79
95
  phase: string,
80
96
  source: string,
81
97
  cause: unknown,
98
+ version = KUBO_VERSION,
82
99
  ): HostError {
83
100
  return new HostError(
84
- `Kubo ${KUBO_VERSION} ${process.platform}-${process.arch}, ${phase} (${source}): ${failure(cause)}. Check the indicated source or account permissions and retry setup.`,
101
+ `Kubo ${version} ${process.platform}-${process.arch}, ${phase} (${source}): ${failure(cause)}. Check the indicated source or account permissions and retry ipab doctor --fix.`,
85
102
  1,
86
103
  "KUBO_SETUP_FAILED",
87
104
  phase,
@@ -116,14 +133,14 @@ async function* fileBytes(path: string, limit: number) {
116
133
  await handle.close();
117
134
  }
118
135
  }
119
- async function digest(path: string, limit: number) {
136
+ export async function digest(path: string, limit: number) {
120
137
  const hash = createHash("sha256");
121
138
  for await (const chunk of fileBytes(path, limit)) hash.update(chunk);
122
139
  return hash.digest("hex");
123
140
  }
124
141
  async function verifyProgram(executable: string, installed: Installation) {
125
142
  if (
126
- installed.version !== KUBO_VERSION ||
143
+ !compatibleVersion(installed.version) ||
127
144
  installed.hash !== (await digest(executable, 512 * 1024 * 1024))
128
145
  )
129
146
  throw new HostError(
@@ -131,61 +148,201 @@ async function verifyProgram(executable: string, installed: Installation) {
131
148
  );
132
149
  if (process.platform !== "win32") await access(executable, constants.X_OK);
133
150
  }
134
- function deadline(ms: number, signal?: AbortSignal) {
135
- const timeout = AbortSignal.timeout(ms);
136
- return signal ? AbortSignal.any([signal, timeout]) : timeout;
137
- }
138
- async function officialAsset(
139
- filename: string,
140
- expected: string,
151
+ export async function inspectKubo(
152
+ stateDir: string,
153
+ release?: KuboRelease,
141
154
  signal?: AbortSignal,
142
- ) {
143
- const release = await fetch(
144
- `https://api.github.com/repos/ipfs/kubo/releases/tags/v${KUBO_VERSION}`,
145
- {
146
- redirect: "error",
147
- signal: deadline(30_000, signal),
148
- headers: { accept: "application/vnd.github+json" },
149
- },
150
- );
151
- if (!release.ok) {
152
- await release.body?.cancel();
155
+ verification?: KuboArchive,
156
+ ): Promise<Installation | undefined> {
157
+ signal?.throwIfAborted();
158
+ if (await exists(stateDir)) await protectedPath(stateDir, true);
159
+ const directory = join(stateDir, "kubo-bin");
160
+ if (!(await exists(directory))) return;
161
+ await protectedPath(directory, true);
162
+ const names = await readdir(directory);
163
+ if (!names.length || names.every((name) => name === "operation.sqlite"))
164
+ return;
165
+ if (names.includes(journal))
153
166
  throw new HostError(
154
- `Could not verify official Kubo release (HTTP ${release.status}).`,
167
+ "Kubo installation is interrupted; inspect the installation journal before repair.",
155
168
  );
169
+ const executable = join(
170
+ directory,
171
+ process.platform === "win32" ? "ipfs.exe" : "ipfs",
172
+ );
173
+ const installed = await readPrivate<Installation>(directory, record, [
174
+ { path: executable },
175
+ ]);
176
+ if (!installed)
177
+ throw new HostError("Unrecorded Kubo installation; it was not adopted.");
178
+ await requireAccountOnlyMany([
179
+ directory,
180
+ executable,
181
+ join(directory, record),
182
+ ]);
183
+ await verifyProgram(executable, installed);
184
+ const filename = assetName(installed.version);
185
+ const source =
186
+ verification?.version === installed.version
187
+ ? verification
188
+ : enumeratedRelease(release, installed.version);
189
+ const expected =
190
+ installed.version === KUBO_VERSION
191
+ ? releaseDigests[filename]
192
+ : source?.digest;
193
+ if (!expected) {
194
+ return { ...installed, provenance: false };
156
195
  }
157
- const metadata = JSON.parse(await boundedText(release)) as {
158
- tag_name: string;
159
- draft: boolean;
160
- prerelease: boolean;
161
- assets: {
162
- name: string;
163
- digest: string;
164
- size: number;
165
- browser_download_url: string;
166
- }[];
167
- };
168
- const url = `https://github.com/ipfs/kubo/releases/download/v${KUBO_VERSION}/${filename}`;
169
- const assets = metadata.assets.filter((item) => item.name === filename);
170
196
  if (
171
- metadata.tag_name !== `v${KUBO_VERSION}` ||
172
- metadata.draft !== false ||
173
- metadata.prerelease !== false ||
174
- assets.length !== 1 ||
175
- assets[0]?.digest !== `sha256:${expected}` ||
176
- !Number.isSafeInteger(assets[0].size) ||
177
- assets[0].size <= 0 ||
178
- assets[0].size > MAX_ARCHIVE ||
179
- assets[0].browser_download_url !== url
197
+ installed.archiveDigest !== undefined &&
198
+ installed.archiveDigest !== expected
180
199
  )
181
200
  throw new HostError(
182
- "Official stable Kubo archive/digest/size unavailable or inconsistent with the bundled release.",
201
+ "Installed Kubo receipt conflicts with the trusted official archive digest.",
183
202
  );
184
- return { url, size: assets[0].size };
203
+ const cache = join(stateDir, "kubo-cache", filename);
204
+ if (!(await exists(cache))) return { ...installed, provenance: false };
205
+ await verifyCache(cache, expected);
206
+ {
207
+ // Stream an existing verified archive member to memory, never unpack files
208
+ // or fetch an archive while inspecting the installation.
209
+ const extracted = await run(
210
+ "tar",
211
+ [
212
+ "-xOf",
213
+ cache,
214
+ `kubo/${process.platform === "win32" ? "ipfs.exe" : "ipfs"}`,
215
+ ],
216
+ {
217
+ encoding: "buffer",
218
+ signal,
219
+ maxBuffer: 512 * 1024 * 1024,
220
+ timeout: 30_000,
221
+ windowsHide: true,
222
+ },
223
+ );
224
+ if (!extracted.stdout.length)
225
+ throw new HostError(
226
+ "The official archive did not provide a nonempty Kubo executable member.",
227
+ );
228
+ if (
229
+ createHash("sha256").update(extracted.stdout).digest("hex") !==
230
+ installed.hash
231
+ )
232
+ throw new HostError(
233
+ "Installed Kubo does not match the verified official archive.",
234
+ );
235
+ }
236
+ signal?.throwIfAborted();
237
+ return { ...installed, provenance: true };
238
+ }
239
+ async function verifyCache(path: string, expected: string): Promise<void> {
240
+ try {
241
+ await requireAccountOnlyMany([join(path, ".."), path]);
242
+ if ((await digest(path, MAX_ARCHIVE)) !== expected)
243
+ throw new HostError(
244
+ "Kubo archive cache checksum mismatch; inspect the cache manually.",
245
+ 1,
246
+ "KUBO_CACHE_INVALID",
247
+ );
248
+ } catch (cause) {
249
+ if (cause instanceof HostError && cause.code === "KUBO_CACHE_INVALID")
250
+ throw cause;
251
+ throw new HostError(
252
+ "Kubo archive cache is invalid or unprotected; inspect it manually.",
253
+ 1,
254
+ "KUBO_CACHE_INVALID",
255
+ );
256
+ }
257
+ }
258
+ export async function inspectKuboCache(
259
+ stateDir: string,
260
+ release: KuboArchive,
261
+ ): Promise<boolean> {
262
+ const directory = join(stateDir, "kubo-cache");
263
+ if (!(await exists(directory))) return false;
264
+ await protectedPath(directory, true);
265
+ await requireAccountOnlyMany([directory]);
266
+ const cache = join(directory, assetName(release.version));
267
+ if (!(await exists(cache))) return false;
268
+ await verifyCache(cache, release.digest);
269
+ return true;
270
+ }
271
+ export async function recoverableInstallation(
272
+ stateDir: string,
273
+ ): Promise<boolean> {
274
+ const directory = join(stateDir, "kubo-bin");
275
+ if (!(await exists(directory))) return false;
276
+ const intent = await readPrivate<{ stage?: unknown }>(directory, journal);
277
+ if (!intent) return false;
278
+ if (
279
+ typeof intent.stage !== "string" ||
280
+ !/^install-[a-f0-9]{8}(?:-[a-f0-9]{4}){3}-[a-f0-9]{12}$/.test(intent.stage)
281
+ )
282
+ return false;
283
+ await requireAccountOnlyMany([directory, join(directory, journal)]);
284
+ const stage = join(directory, intent.stage);
285
+ if (await exists(stage)) {
286
+ await protectedPath(stage, true);
287
+ await requireAccountOnlyMany([stage]);
288
+ }
289
+ const executable = join(
290
+ directory,
291
+ process.platform === "win32" ? "ipfs.exe" : "ipfs",
292
+ );
293
+ const installed = await readPrivate<Installation>(directory, record);
294
+ const original = await readPrivate<Installation>(stage, "original.json");
295
+ if (original) {
296
+ await requireAccountOnlyMany([
297
+ join(stage, "original"),
298
+ join(stage, "original.json"),
299
+ ]);
300
+ await verifyProgram(join(stage, "original"), original);
301
+ if (!installed) return false;
302
+ if (
303
+ installed.hash !== original.hash ||
304
+ installed.version !== original.version
305
+ )
306
+ await verifyProgram(executable, installed);
307
+ } else if (installed) {
308
+ await requireAccountOnlyMany([executable, join(directory, record)]);
309
+ await verifyProgram(executable, installed);
310
+ } else if (await exists(executable)) {
311
+ const pending = await readPrivate<Installation>(stage, record);
312
+ if (!pending) return false;
313
+ await requireAccountOnlyMany([executable, join(stage, record)]);
314
+ await verifyProgram(executable, pending);
315
+ }
316
+ return true;
317
+ }
318
+ export async function runningManagedNodes(stateDir: string): Promise<boolean> {
319
+ const directory = join(stateDir, "swarm-nodes");
320
+ if (!(await exists(directory))) return false;
321
+ await protectedPath(directory, true);
322
+ for (const name of await readdir(directory)) {
323
+ const root = join(directory, name);
324
+ await protectedPath(root, true);
325
+ const record = await readPrivate<{ pid?: unknown }>(root, "node.json");
326
+ if (record?.pid !== undefined) {
327
+ if (!Number.isSafeInteger(record.pid) || Number(record.pid) <= 0)
328
+ throw new HostError(
329
+ "Invalid managed node process record; upgrade is blocked.",
330
+ );
331
+ try {
332
+ process.kill(Number(record.pid), 0);
333
+ return true;
334
+ } catch (cause) {
335
+ if (!nodeError(cause, "ESRCH")) return true;
336
+ }
337
+ }
338
+ // A repo lock without a trustworthy process record is not proof of a stopped node.
339
+ if (await exists(join(root, "repo", "repo.lock"))) return true;
340
+ }
341
+ return false;
185
342
  }
186
343
  async function transfer(
187
344
  target: string,
188
- source: { archive: string } | { url: string; size: number },
345
+ source: { archive: string } | { url: string; size?: number },
189
346
  options: InstallOptions,
190
347
  ) {
191
348
  const handle = await open(target, "wx", 0o600);
@@ -202,9 +359,12 @@ async function transfer(
202
359
  let stream: AsyncIterable<Uint8Array>;
203
360
  if ("archive" in source) stream = fileBytes(source.archive, MAX_ARCHIVE);
204
361
  else {
205
- const totalMiB = (source.size / (1024 * 1024)).toFixed(1);
362
+ const totalMiB =
363
+ source.size === undefined
364
+ ? undefined
365
+ : (source.size / (1024 * 1024)).toFixed(1);
206
366
  options.diagnostic?.(
207
- `Downloading ${source.url.split("/").at(-1)} from GitHub (${totalMiB} MiB)...`,
367
+ `Downloading ${source.url.split("/").at(-1)} from GitHub (${totalMiB ? `${totalMiB} MiB` : "total size unavailable; bounded to 150 MiB"})...`,
208
368
  );
209
369
  if (options.diagnostic)
210
370
  progress = setInterval(() => {
@@ -216,14 +376,21 @@ async function transfer(
216
376
  const elapsed =
217
377
  startedAt === undefined ? 0 : (now - startedAt) / 1000;
218
378
  let eta = idle >= 5 ? "unavailable" : "estimating";
219
- if (total > 0 && elapsed > 0 && idle < 5) {
379
+ if (
380
+ source.size !== undefined &&
381
+ total > 0 &&
382
+ elapsed > 0 &&
383
+ idle < 5
384
+ ) {
220
385
  const seconds = Math.ceil(
221
386
  (Math.max(0, source.size - total) * elapsed) / total,
222
387
  );
223
388
  eta = `~${seconds < 60 ? `${seconds}s` : `${Math.floor(seconds / 60)}m ${seconds % 60}s`}`;
224
389
  }
225
390
  options.diagnostic?.(
226
- `Kubo: ${(total / (1024 * 1024)).toFixed(1)}/${totalMiB} MiB (${((total * 100) / source.size).toFixed(1)}%); ETA ${eta}${waiting}`,
391
+ source.size === undefined
392
+ ? `Kubo: ${(total / (1024 * 1024)).toFixed(1)} MiB received; total size unavailable${waiting}`
393
+ : `Kubo: ${(total / (1024 * 1024)).toFixed(1)}/${totalMiB} MiB (${((total * 100) / source.size).toFixed(1)}%); ETA ${eta}${waiting}`,
227
394
  true,
228
395
  );
229
396
  } catch (cause) {
@@ -249,7 +416,7 @@ async function transfer(
249
416
  receivedAt = Date.now();
250
417
  }
251
418
  signal.throwIfAborted();
252
- if ("url" in source && total !== source.size)
419
+ if ("url" in source && source.size !== undefined && total !== source.size)
253
420
  throw new HostError("Kubo archive size mismatch.");
254
421
  await handle.sync();
255
422
  } catch (cause) {
@@ -261,6 +428,160 @@ async function transfer(
261
428
  }
262
429
  return total;
263
430
  }
431
+ const verificationJournal = "verification.json";
432
+ async function recoverVerification(directory: string): Promise<void> {
433
+ const intent = await readPrivate<unknown>(directory, verificationJournal);
434
+ if (intent === undefined) return;
435
+ if (
436
+ typeof intent !== "object" ||
437
+ intent === null ||
438
+ Object.keys(intent).length !== 1 ||
439
+ !("stage" in intent) ||
440
+ typeof intent.stage !== "string" ||
441
+ !/^verify-[a-f0-9]{8}(?:-[a-f0-9]{4}){3}-[a-f0-9]{12}$/.test(intent.stage)
442
+ )
443
+ throw new HostError(
444
+ "Unrecognized archive verification journal; inspect it manually.",
445
+ );
446
+ await requireAccountOnlyMany([
447
+ directory,
448
+ join(directory, verificationJournal),
449
+ ]);
450
+ const stage = join(directory, intent.stage);
451
+ if (await exists(stage)) {
452
+ await protectedPath(stage, true);
453
+ await requireAccountOnlyMany([stage]);
454
+ await rm(stage, { recursive: true });
455
+ }
456
+ await rm(join(directory, verificationJournal));
457
+ }
458
+ async function cacheVerificationArchive(
459
+ stateDir: string,
460
+ source: KuboArchive,
461
+ options: InstallOptions,
462
+ ): Promise<void> {
463
+ const directory = await privateDirectory(stateDir, "kubo-cache");
464
+ await requireAccountOnlyMany([directory]);
465
+ await recoverVerification(directory);
466
+ const target = join(directory, source.filename);
467
+ if (await exists(target)) {
468
+ await verifyCache(target, source.digest);
469
+ return;
470
+ }
471
+ const name = `verify-${randomUUID()}`,
472
+ stage = join(directory, name);
473
+ if (await exists(stage))
474
+ throw new HostError("Verification staging path exists; retry later.");
475
+ await writePrivate(directory, verificationJournal, { stage: name });
476
+ let created = false;
477
+ try {
478
+ await mkdir(stage, { mode: 0o700 });
479
+ created = true;
480
+ await secureNew(stage, true);
481
+ const temporary = join(stage, source.filename);
482
+ await transfer(
483
+ temporary,
484
+ options.archive
485
+ ? { archive: options.archive }
486
+ : {
487
+ url: source.url,
488
+ ...(source.size === undefined ? {} : { size: source.size }),
489
+ },
490
+ options,
491
+ );
492
+ if ((await digest(temporary, MAX_ARCHIVE)) !== source.digest)
493
+ throw new HostError(
494
+ "Official verification archive checksum mismatch; no cache or executable was replaced.",
495
+ );
496
+ options.signal?.throwIfAborted();
497
+ try {
498
+ await link(temporary, target);
499
+ } catch (cause) {
500
+ if (!nodeError(cause, "EEXIST")) throw cause;
501
+ await verifyCache(target, source.digest);
502
+ }
503
+ } finally {
504
+ if (created) await rm(stage, { recursive: true, force: true });
505
+ await rm(join(directory, verificationJournal));
506
+ }
507
+ }
508
+ export async function verifyExistingKuboArchive(
509
+ stateDir: string,
510
+ source: KuboArchive,
511
+ options: InstallOptions = {},
512
+ ): Promise<string> {
513
+ try {
514
+ options.signal?.throwIfAborted();
515
+ if (
516
+ !compatibleVersion(source.version) ||
517
+ source.filename !== assetName(source.version) ||
518
+ source.url !== officialDownloadUrl(source.version, source.filename) ||
519
+ !/^[a-f0-9]{64}$/.test(source.digest) ||
520
+ (source.size !== undefined &&
521
+ (!Number.isSafeInteger(source.size) ||
522
+ source.size <= 0 ||
523
+ source.size > MAX_ARCHIVE)) ||
524
+ (source.version === KUBO_VERSION
525
+ ? source.digest !== releaseDigests[source.filename]
526
+ : source.size === undefined)
527
+ )
528
+ throw new HostError(
529
+ "A trusted official same-version archive is required for verification.",
530
+ );
531
+ const directory = join(stateDir, "kubo-bin");
532
+ await protectedPath(stateDir, true);
533
+ await protectedPath(directory, true);
534
+ await requireAccountOnlyMany([stateDir, directory]);
535
+ return await withPrivateLock(
536
+ directory,
537
+ async () => {
538
+ const installed = await inspectKubo(
539
+ stateDir,
540
+ options.release,
541
+ options.signal,
542
+ source,
543
+ );
544
+ if (!installed || installed.version !== source.version)
545
+ throw new HostError(
546
+ "Installed Kubo changed since authorization; no program was replaced.",
547
+ );
548
+ const executable = join(
549
+ directory,
550
+ process.platform === "win32" ? "ipfs.exe" : "ipfs",
551
+ );
552
+ if (installed.provenance) return executable;
553
+ options.diagnostic?.(
554
+ `Caching the official Kubo ${source.version} archive for byte verification only; no reinstall or node stopping.`,
555
+ );
556
+ await cacheVerificationArchive(stateDir, source, options);
557
+ const verified = await inspectKubo(
558
+ stateDir,
559
+ options.release,
560
+ options.signal,
561
+ source,
562
+ );
563
+ if (!verified?.provenance || verified.version !== source.version)
564
+ throw new HostError(
565
+ "Official archive verification did not establish provenance; no program was replaced.",
566
+ );
567
+ options.signal?.throwIfAborted();
568
+ options.diagnostic?.(
569
+ `Existing Kubo ${source.version} matches the official archive; reused without reinstall or node stopping.`,
570
+ );
571
+ return executable;
572
+ },
573
+ options.signal,
574
+ );
575
+ } catch (cause) {
576
+ options.signal?.throwIfAborted();
577
+ throw setupFailure(
578
+ "same-version archive verification",
579
+ "official archive cache and existing program",
580
+ cause,
581
+ source.version,
582
+ );
583
+ }
584
+ }
264
585
  async function clean(directory: string, stage: string) {
265
586
  await rm(stage, { recursive: true, force: true });
266
587
  await rm(join(directory, journal));
@@ -284,6 +605,23 @@ async function recover(
284
605
  );
285
606
  const stage = join(directory, intent.stage);
286
607
  if (await exists(stage)) await protectedPath(stage, true);
608
+ const original = await readPrivate<Installation>(stage, "original.json");
609
+ if (original) {
610
+ const backup = join(stage, "original");
611
+ await verifyProgram(backup, original);
612
+ if (
613
+ installed?.hash === original.hash &&
614
+ installed.version === original.version
615
+ ) {
616
+ await rename(backup, executable);
617
+ await rename(join(stage, "original.json"), join(directory, record));
618
+ installed = original;
619
+ } else if (installed) await verifyProgram(executable, installed);
620
+ else
621
+ throw new HostError(
622
+ "Interrupted Kubo upgrade has an inconsistent receipt; inspect it manually.",
623
+ );
624
+ }
287
625
  if (!installed && (await exists(executable))) {
288
626
  const pending = await readPrivate<Installation>(stage, record, [
289
627
  { path: executable },
@@ -305,6 +643,7 @@ export async function kuboBinary(
305
643
  ): Promise<string> {
306
644
  let phase = "installation",
307
645
  source = "protected local installation";
646
+ let targetVersion = options.release?.version ?? KUBO_VERSION;
308
647
  try {
309
648
  options.signal?.throwIfAborted();
310
649
  const directory = await privateDirectory(stateDir, "kubo-bin");
@@ -318,24 +657,19 @@ export async function kuboBinary(
318
657
  !["x64", "arm64"].includes(process.arch)
319
658
  )
320
659
  throw new HostError("Unsupported Kubo platform.");
321
- const arch = process.arch === "x64" ? "amd64" : "arm64";
322
- const filename = `kubo_v${KUBO_VERSION}_${platform}-${arch}.${platform === "windows" ? "zip" : "tar.gz"}`;
323
- const expected = releaseDigests[filename];
324
- if (!expected || !/^[a-f0-9]{64}$/.test(expected))
325
- throw new HostError(
326
- "No trusted archive digest for this release/platform.",
327
- );
328
660
  const program = platform === "windows" ? "ipfs.exe" : "ipfs";
329
661
  const executable = join(directory, program);
330
662
  const install = async () => {
331
663
  let installed = await readPrivate<Installation>(directory, record, [
332
664
  { path: executable },
333
665
  ]);
666
+ installed = await recover(directory, executable, installed);
334
667
  if (installed !== undefined) {
335
- options.diagnostic?.(`Verifying installed Kubo ${KUBO_VERSION}...`);
668
+ options.diagnostic?.(
669
+ `Verifying installed Kubo ${installed.version}...`,
670
+ );
336
671
  await verifyProgram(executable, installed);
337
672
  }
338
- installed = await recover(directory, executable, installed);
339
673
  if (
340
674
  options.diagnostic &&
341
675
  (await readdir(directory)).some((name) =>
@@ -347,35 +681,83 @@ export async function kuboBinary(
347
681
  options.diagnostic(
348
682
  "Untracked Kubo staging files were left untouched. Inspect kubo-bin manually; do not delete the verified installation.",
349
683
  );
350
- if (installed) {
684
+ if (
685
+ installed &&
686
+ (!options.upgrade ||
687
+ (options.release &&
688
+ compareKuboVersions(options.release.version, installed.version) <=
689
+ 0))
690
+ ) {
351
691
  if (options.archive !== undefined) {
352
692
  phase = "archive verification";
353
693
  source = "local archive";
694
+ const expected =
695
+ options.release?.digest ?? releaseDigests[assetName(KUBO_VERSION)];
354
696
  if ((await digest(options.archive, MAX_ARCHIVE)) !== expected)
355
697
  throw new HostError("Kubo archive checksum mismatch.");
356
698
  }
699
+ options.diagnostic?.(
700
+ `Kubo ${installed.version} bytes match the protected installation receipt; reusing the existing installation. No download or reinstall needed. Cryptographic archive provenance requires doctor verification.`,
701
+ );
357
702
  return executable;
358
703
  }
359
- if (await exists(executable))
704
+ if (!installed && (await exists(executable)))
360
705
  throw new HostError(
361
706
  "Unrecorded Kubo executable; move it aside manually. It was not adopted.",
362
707
  );
363
- let input: { archive: string } | { url: string; size: number };
364
- if (options.archive !== undefined) input = { archive: options.archive };
365
- else {
708
+ let selected = options.release;
709
+ if (!selected && options.archive === undefined) {
366
710
  phase = "release metadata";
367
711
  source = "api.github.com/ipfs/kubo";
368
712
  options.diagnostic?.(
369
- `Checking official Kubo ${KUBO_VERSION} release (timeout: 30s)...`,
713
+ "Selecting the latest verified compatible official Kubo release...",
370
714
  );
371
- input = await officialAsset(filename, expected, options.signal);
715
+ selected = await latestKuboRelease(options.signal);
372
716
  }
717
+ const version = selected?.version ?? KUBO_VERSION;
718
+ targetVersion = version;
719
+ if (!compatibleVersion(version))
720
+ throw new HostError("Unsupported Kubo version.");
721
+ const filename = assetName(version);
722
+ const expected = selected?.digest ?? releaseDigests[filename];
723
+ if (!expected || !/^[a-f0-9]{64}$/.test(expected))
724
+ throw new HostError(
725
+ "No trusted archive digest for this release/platform.",
726
+ );
727
+ let input: { archive: string } | { url: string; size: number };
728
+ if (
729
+ installed &&
730
+ (compareKuboVersions(version, installed.version) <= 0 ||
731
+ (await runningManagedNodes(stateDir)))
732
+ )
733
+ throw new HostError(
734
+ "Kubo upgrade is blocked; managed nodes must be stopped by their operator before switching.",
735
+ );
736
+ const cacheDirectory = await privateDirectory(stateDir, "kubo-cache");
737
+ await requireAccountOnlyMany([cacheDirectory]);
738
+ const cached = join(cacheDirectory, filename);
739
+ if (await exists(cached)) {
740
+ phase = "cache verification";
741
+ await verifyCache(cached, expected);
742
+ options.diagnostic?.(
743
+ "Reusing the verified official Kubo archive cache.",
744
+ );
745
+ input = { archive: cached };
746
+ } else if (options.archive !== undefined)
747
+ input = { archive: options.archive };
748
+ else if (selected) input = selected;
749
+ else
750
+ throw new HostError(
751
+ "A verified latest compatible Kubo target is required.",
752
+ );
373
753
  phase = "installation";
374
754
  source = "protected local staging";
375
755
  const name = `install-${randomUUID()}`,
376
756
  stage = join(directory, name);
377
757
  if (await exists(stage))
378
- throw new HostError("Staging path already exists; retry setup.");
758
+ throw new HostError(
759
+ "Staging path already exists; retry ipab doctor --fix.",
760
+ );
379
761
  await writePrivate(directory, journal, { stage: name });
380
762
  let placed = false,
381
763
  created = false;
@@ -395,6 +777,9 @@ export async function kuboBinary(
395
777
  );
396
778
  if ((await digest(archive, MAX_ARCHIVE)) !== expected)
397
779
  throw new HostError("Kubo archive checksum mismatch.");
780
+ if (!(await exists(cached))) {
781
+ await link(archive, cached);
782
+ } else await verifyCache(cached, expected);
398
783
  phase = "extraction";
399
784
  source = "verified release archive";
400
785
  options.diagnostic?.("Extracting and verifying the Kubo executable...");
@@ -422,24 +807,96 @@ export async function kuboBinary(
422
807
  timeout: 10_000,
423
808
  windowsHide: true,
424
809
  });
425
- if (version.stdout.trim() !== KUBO_VERSION)
810
+ const reportedVersion = version.stdout.trim();
811
+ if (
812
+ !compatibleVersion(reportedVersion) ||
813
+ compareKuboVersions(
814
+ reportedVersion,
815
+ selected?.version ?? KUBO_VERSION,
816
+ ) !== 0
817
+ )
426
818
  throw new HostError("Kubo executable version mismatch.");
819
+ const runtimeOptions = {
820
+ signal: options.signal,
821
+ env: {
822
+ ...process.env,
823
+ HOME: stage,
824
+ USERPROFILE: stage,
825
+ IPFS_PATH: join(stage, "version-repo"),
826
+ },
827
+ timeout: 10_000,
828
+ windowsHide: true,
829
+ };
830
+ const repoVersion = await run(
831
+ extracted,
832
+ ["version", "--repo"],
833
+ runtimeOptions,
834
+ );
835
+ if (repoVersion.stdout.trim() !== KUBO_REPO_VERSION)
836
+ throw new HostError(
837
+ "Kubo candidate requires an unsupported repo version; no migration or upgrade was performed.",
838
+ );
839
+ const commands = await run(extracted, ["commands"], runtimeOptions);
840
+ const available = new Set(
841
+ commands.stdout
842
+ .trim()
843
+ .split(/\r?\n/)
844
+ .map((line) => line.trim()),
845
+ );
846
+ if (
847
+ [
848
+ "id",
849
+ "swarm connect",
850
+ "swarm peering ls",
851
+ "dag import",
852
+ "dag export",
853
+ "pin add",
854
+ "block get",
855
+ "config",
856
+ ].some((name) => !available.has(`ipfs ${name}`))
857
+ )
858
+ throw new HostError(
859
+ "Kubo candidate lacks required IPAB runtime commands; the existing installation was retained.",
860
+ );
427
861
  const verified = {
428
- version: KUBO_VERSION,
862
+ version: selected?.version ?? KUBO_VERSION,
429
863
  hash: await digest(extracted, 512 * 1024 * 1024),
864
+ archiveDigest: expected,
430
865
  };
431
866
  phase = "installation";
432
867
  source = "protected local installation";
433
868
  await writePrivate(stage, record, verified);
434
- // Atomic and exclusive: never overwrite a binary placed by another actor.
435
- await link(extracted, executable);
869
+ if (installed) {
870
+ // Keep the original executable and receipt until the candidate is fully verified.
871
+ if (await runningManagedNodes(stateDir))
872
+ throw new HostError(
873
+ "Managed node started during inspection; upgrade is blocked.",
874
+ );
875
+ await link(executable, join(stage, "original"));
876
+ await writePrivate(stage, "original.json", installed);
877
+ await rename(extracted, executable);
878
+ } else await link(extracted, executable);
436
879
  placed = true;
437
- await rename(join(stage, record), join(directory, record));
880
+ try {
881
+ await rename(join(stage, record), join(directory, record));
882
+ } catch (cause) {
883
+ if (installed) {
884
+ await rename(join(stage, "original"), executable);
885
+ await rename(join(stage, "original.json"), join(directory, record));
886
+ placed = false;
887
+ }
888
+ throw cause;
889
+ }
438
890
  placed = false;
439
891
  return executable;
440
892
  } finally {
441
893
  // If rollback itself fails, retain the journal and verified candidate record for recovery.
442
- if (placed) await rm(executable);
894
+ if (placed) {
895
+ if (installed) {
896
+ await rename(join(stage, "original"), executable);
897
+ await rename(join(stage, "original.json"), join(directory, record));
898
+ } else await rm(executable);
899
+ }
443
900
  if (created) await clean(directory, stage);
444
901
  else await rm(join(directory, journal));
445
902
  }
@@ -447,6 +904,33 @@ export async function kuboBinary(
447
904
  return await withPrivateLock(directory, install, options.signal);
448
905
  } catch (cause) {
449
906
  options.signal?.throwIfAborted();
450
- throw setupFailure(phase, source, cause);
907
+ throw setupFailure(phase, source, cause, targetVersion);
451
908
  }
452
909
  }
910
+
911
+ export async function withKuboProgram<T>(
912
+ stateDir: string,
913
+ operation: (binary: string) => Promise<T>,
914
+ signal?: AbortSignal,
915
+ ): Promise<T> {
916
+ const binary = await kuboBinary(stateDir, signal ? { signal } : {});
917
+ // Node preparation/startup shares the install lock through PID persistence,
918
+ // preventing a node launch racing the final upgrade/switch check.
919
+ return withPrivateLock(
920
+ join(stateDir, "kubo-bin"),
921
+ async () => {
922
+ const installed = await readPrivate<Installation>(
923
+ join(stateDir, "kubo-bin"),
924
+ record,
925
+ [{ path: binary }],
926
+ );
927
+ if (!installed)
928
+ throw new HostError(
929
+ "Managed Kubo installation disappeared before node startup.",
930
+ );
931
+ await verifyProgram(binary, installed);
932
+ return operation(binary);
933
+ },
934
+ signal,
935
+ );
936
+ }