@ipab/cli 0.1.0-rc.4 → 0.1.0-rc.5

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 (92) hide show
  1. package/README.md +12 -7
  2. package/dist/cli.d.ts +3 -1
  3. package/dist/cli.d.ts.map +1 -1
  4. package/dist/cli.js +114 -25
  5. package/dist/cli.js.map +1 -1
  6. package/dist/config-secret.d.ts +1 -1
  7. package/dist/config-secret.d.ts.map +1 -1
  8. package/dist/config-secret.js +2 -73
  9. package/dist/config-secret.js.map +1 -1
  10. package/dist/config.d.ts +1 -0
  11. package/dist/config.d.ts.map +1 -1
  12. package/dist/config.js +12 -1
  13. package/dist/config.js.map +1 -1
  14. package/dist/context-types.d.ts +12 -0
  15. package/dist/context-types.d.ts.map +1 -0
  16. package/dist/context-types.js +2 -0
  17. package/dist/context-types.js.map +1 -0
  18. package/dist/context.d.ts +6 -0
  19. package/dist/context.d.ts.map +1 -1
  20. package/dist/context.js +25 -0
  21. package/dist/context.js.map +1 -1
  22. package/dist/ipc.d.ts +3 -1
  23. package/dist/ipc.d.ts.map +1 -1
  24. package/dist/ipc.js +34 -1
  25. package/dist/ipc.js.map +1 -1
  26. package/dist/kubo-install.d.ts +9 -0
  27. package/dist/kubo-install.d.ts.map +1 -0
  28. package/dist/kubo-install.js +361 -0
  29. package/dist/kubo-install.js.map +1 -0
  30. package/dist/kubo-peering.d.ts +11 -0
  31. package/dist/kubo-peering.d.ts.map +1 -0
  32. package/dist/kubo-peering.js +93 -0
  33. package/dist/kubo-peering.js.map +1 -0
  34. package/dist/kubo-peers.d.ts +12 -0
  35. package/dist/kubo-peers.d.ts.map +1 -0
  36. package/dist/kubo-peers.js +118 -0
  37. package/dist/kubo-peers.js.map +1 -0
  38. package/dist/kubo-release.d.ts +3 -0
  39. package/dist/kubo-release.d.ts.map +1 -0
  40. package/dist/kubo-release.js +12 -0
  41. package/dist/kubo-release.js.map +1 -0
  42. package/dist/kubo.d.ts +11 -4
  43. package/dist/kubo.d.ts.map +1 -1
  44. package/dist/kubo.js +150 -197
  45. package/dist/kubo.js.map +1 -1
  46. package/dist/runtime.d.ts +2 -0
  47. package/dist/runtime.d.ts.map +1 -1
  48. package/dist/runtime.js +6 -2
  49. package/dist/runtime.js.map +1 -1
  50. package/dist/setup.d.ts +2 -1
  51. package/dist/setup.d.ts.map +1 -1
  52. package/dist/setup.js +23 -18
  53. package/dist/setup.js.map +1 -1
  54. package/dist/state-storage-windows.d.ts +2 -0
  55. package/dist/state-storage-windows.d.ts.map +1 -0
  56. package/dist/state-storage-windows.js +114 -0
  57. package/dist/state-storage-windows.js.map +1 -0
  58. package/dist/state-storage.d.ts +3 -0
  59. package/dist/state-storage.d.ts.map +1 -0
  60. package/dist/state-storage.js +299 -0
  61. package/dist/state-storage.js.map +1 -0
  62. package/dist/state.d.ts +2 -2
  63. package/dist/state.d.ts.map +1 -1
  64. package/dist/state.js +59 -29
  65. package/dist/state.js.map +1 -1
  66. package/dist/swarm-files.d.ts +1 -1
  67. package/dist/swarm-files.d.ts.map +1 -1
  68. package/dist/swarm-files.js +4 -1
  69. package/dist/swarm-files.js.map +1 -1
  70. package/dist/swarm.d.ts +6 -3
  71. package/dist/swarm.d.ts.map +1 -1
  72. package/dist/swarm.js +184 -70
  73. package/dist/swarm.js.map +1 -1
  74. package/package.json +4 -4
  75. package/src/cli.ts +146 -39
  76. package/src/config-secret.ts +2 -84
  77. package/src/config.ts +14 -1
  78. package/src/context-types.ts +11 -0
  79. package/src/context.ts +40 -0
  80. package/src/ipc.ts +50 -1
  81. package/src/kubo-install.ts +452 -0
  82. package/src/kubo-peering.ts +126 -0
  83. package/src/kubo-peers.ts +145 -0
  84. package/src/kubo-release.ts +17 -0
  85. package/src/kubo.ts +207 -269
  86. package/src/runtime.ts +12 -1
  87. package/src/setup.ts +30 -17
  88. package/src/state-storage-windows.ts +134 -0
  89. package/src/state-storage.ts +329 -0
  90. package/src/state.ts +68 -35
  91. package/src/swarm-files.ts +4 -0
  92. package/src/swarm.ts +256 -90
@@ -0,0 +1,452 @@
1
+ import { execFile } from "node:child_process";
2
+ import { createHash, randomUUID } from "node:crypto";
3
+ import { constants } from "node:fs";
4
+ import {
5
+ access,
6
+ chmod,
7
+ link,
8
+ lstat,
9
+ mkdir,
10
+ open,
11
+ readdir,
12
+ rename,
13
+ rm,
14
+ } from "node:fs/promises";
15
+ import { join } from "node:path";
16
+ import { promisify } from "node:util";
17
+ import { boundedText } from "@ipab/bundle/pointer/scope";
18
+ import { nodeError } from "./authoring.js";
19
+ import { HostError } from "./errors.js";
20
+ import { protectedPath, secureNew } from "./identity.js";
21
+ import { KUBO_VERSION, releaseDigests } from "./kubo-release.js";
22
+ import {
23
+ privateDirectory,
24
+ readPrivate,
25
+ withPrivateLock,
26
+ writePrivate,
27
+ } from "./swarm-files.js";
28
+
29
+ const run = promisify(execFile);
30
+ const MAX_ARCHIVE = 150 * 1024 * 1024;
31
+ const journal = "installing.json";
32
+ const record = "installation.json";
33
+ interface Installation {
34
+ version: string;
35
+ hash: string;
36
+ }
37
+ export interface InstallOptions {
38
+ archive?: string;
39
+ diagnostic?: (line: string, progress?: boolean) => void;
40
+ signal?: AbortSignal;
41
+ }
42
+
43
+ function failure(cause: unknown): string {
44
+ if (cause instanceof HostError) return cause.message;
45
+ const queue = [cause];
46
+ const codes = new Set<string>();
47
+ for (let i = 0; i < queue.length && i < 8; i++) {
48
+ const error = queue[i];
49
+ if (!(error instanceof Error)) continue;
50
+ if (
51
+ "code" in error &&
52
+ typeof error.code === "string" &&
53
+ /^[A-Z][A-Z0-9_]{1,39}$/.test(error.code)
54
+ )
55
+ codes.add(error.code);
56
+ if (
57
+ "cmd" in error &&
58
+ "code" in error &&
59
+ typeof error.code === "number" &&
60
+ Number.isSafeInteger(error.code)
61
+ )
62
+ codes.add(`process exit ${error.code}`);
63
+ if (error.name === "TimeoutError" || error.name === "AbortError")
64
+ codes.add(error.name);
65
+ if (error.cause) queue.push(error.cause);
66
+ if (error instanceof AggregateError)
67
+ queue.push(...(error.errors as unknown[]).slice(0, 4));
68
+ }
69
+ if (codes.size) return [...codes].join(", ");
70
+ if (cause instanceof SyntaxError) return "invalid data";
71
+ if (
72
+ cause instanceof Error &&
73
+ /permission|account.only|current (?:OS )?account/i.test(cause.message)
74
+ )
75
+ return "permission denied or unsafe ownership";
76
+ return "operation failed";
77
+ }
78
+ export function setupFailure(
79
+ phase: string,
80
+ source: string,
81
+ cause: unknown,
82
+ ): HostError {
83
+ 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.`,
85
+ 1,
86
+ "KUBO_SETUP_FAILED",
87
+ phase,
88
+ );
89
+ }
90
+ async function exists(path: string) {
91
+ try {
92
+ await lstat(path);
93
+ return true;
94
+ } catch (cause) {
95
+ if (nodeError(cause, "ENOENT")) return false;
96
+ throw cause;
97
+ }
98
+ }
99
+ async function* fileBytes(path: string, limit: number) {
100
+ const stat = await lstat(path);
101
+ if (!stat.isFile())
102
+ throw new HostError("Expected a regular file, not a link or directory.");
103
+ if (stat.size > limit) throw new HostError("Kubo file exceeds limit.");
104
+ const handle = await open(path, "r");
105
+ try {
106
+ const buffer = Buffer.alloc(128 * 1024);
107
+ let total = 0;
108
+ for (;;) {
109
+ const { bytesRead } = await handle.read(buffer);
110
+ if (!bytesRead) return;
111
+ total += bytesRead;
112
+ if (total > limit) throw new HostError("Kubo file exceeds limit.");
113
+ yield buffer.subarray(0, bytesRead);
114
+ }
115
+ } finally {
116
+ await handle.close();
117
+ }
118
+ }
119
+ async function digest(path: string, limit: number) {
120
+ const hash = createHash("sha256");
121
+ for await (const chunk of fileBytes(path, limit)) hash.update(chunk);
122
+ return hash.digest("hex");
123
+ }
124
+ async function verifyProgram(executable: string, installed: Installation) {
125
+ if (
126
+ installed.version !== KUBO_VERSION ||
127
+ installed.hash !== (await digest(executable, 512 * 1024 * 1024))
128
+ )
129
+ throw new HostError(
130
+ "Kubo installation integrity mismatch; do not use this binary.",
131
+ );
132
+ if (process.platform !== "win32") await access(executable, constants.X_OK);
133
+ }
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,
141
+ 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();
153
+ throw new HostError(
154
+ `Could not verify official Kubo release (HTTP ${release.status}).`,
155
+ );
156
+ }
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
+ 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
180
+ )
181
+ throw new HostError(
182
+ "Official stable Kubo archive/digest/size unavailable or inconsistent with the bundled release.",
183
+ );
184
+ return { url, size: assets[0].size };
185
+ }
186
+ async function transfer(
187
+ target: string,
188
+ source: { archive: string } | { url: string; size: number },
189
+ options: InstallOptions,
190
+ ) {
191
+ const handle = await open(target, "wx", 0o600);
192
+ const controller = new AbortController();
193
+ const signal = options.signal
194
+ ? AbortSignal.any([options.signal, controller.signal])
195
+ : controller.signal;
196
+ let progress: ReturnType<typeof setInterval> | undefined;
197
+ let total = 0;
198
+ let receivedAt = Date.now();
199
+ let startedAt: number | undefined;
200
+ try {
201
+ await secureNew(target);
202
+ let stream: AsyncIterable<Uint8Array>;
203
+ if ("archive" in source) stream = fileBytes(source.archive, MAX_ARCHIVE);
204
+ else {
205
+ const totalMiB = (source.size / (1024 * 1024)).toFixed(1);
206
+ options.diagnostic?.(
207
+ `Downloading ${source.url.split("/").at(-1)} from GitHub (${totalMiB} MiB)...`,
208
+ );
209
+ if (options.diagnostic)
210
+ progress = setInterval(() => {
211
+ try {
212
+ const now = Date.now();
213
+ const idle = Math.floor((now - receivedAt) / 1000);
214
+ const waiting =
215
+ idle >= 5 ? `; waiting for data (${idle}s without new data)` : "";
216
+ const elapsed =
217
+ startedAt === undefined ? 0 : (now - startedAt) / 1000;
218
+ let eta = idle >= 5 ? "unavailable" : "estimating";
219
+ if (total > 0 && elapsed > 0 && idle < 5) {
220
+ const seconds = Math.ceil(
221
+ (Math.max(0, source.size - total) * elapsed) / total,
222
+ );
223
+ eta = `~${seconds < 60 ? `${seconds}s` : `${Math.floor(seconds / 60)}m ${seconds % 60}s`}`;
224
+ }
225
+ options.diagnostic?.(
226
+ `Kubo: ${(total / (1024 * 1024)).toFixed(1)}/${totalMiB} MiB (${((total * 100) / source.size).toFixed(1)}%); ETA ${eta}${waiting}`,
227
+ true,
228
+ );
229
+ } catch (cause) {
230
+ controller.abort(cause);
231
+ }
232
+ }, 5_000);
233
+ const response = await fetch(source.url, {
234
+ signal,
235
+ });
236
+ if (!response.ok || !response.body) {
237
+ await response.body?.cancel();
238
+ throw new HostError(`Kubo download failed (HTTP ${response.status}).`);
239
+ }
240
+ startedAt = Date.now();
241
+ stream = response.body as ReadableStream<Uint8Array>;
242
+ }
243
+ for await (const chunk of stream) {
244
+ signal.throwIfAborted();
245
+ total += chunk.byteLength;
246
+ if (total > MAX_ARCHIVE)
247
+ throw new HostError("Kubo archive exceeds limit.");
248
+ await handle.writeFile(chunk);
249
+ receivedAt = Date.now();
250
+ }
251
+ signal.throwIfAborted();
252
+ if ("url" in source && total !== source.size)
253
+ throw new HostError("Kubo archive size mismatch.");
254
+ await handle.sync();
255
+ } catch (cause) {
256
+ signal.throwIfAborted();
257
+ throw cause;
258
+ } finally {
259
+ clearInterval(progress);
260
+ await handle.close();
261
+ }
262
+ return total;
263
+ }
264
+ async function clean(directory: string, stage: string) {
265
+ await rm(stage, { recursive: true, force: true });
266
+ await rm(join(directory, journal));
267
+ }
268
+ async function recover(
269
+ directory: string,
270
+ executable: string,
271
+ installed: Installation | undefined,
272
+ ) {
273
+ const intent = await readPrivate<unknown>(directory, journal);
274
+ if (intent === undefined) return installed;
275
+ if (
276
+ typeof intent !== "object" ||
277
+ intent === null ||
278
+ !("stage" in intent) ||
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
+ throw new HostError(
283
+ "Unrecognized Kubo installation journal; inspect it manually.",
284
+ );
285
+ const stage = join(directory, intent.stage);
286
+ if (await exists(stage)) await protectedPath(stage, true);
287
+ if (!installed && (await exists(executable))) {
288
+ const pending = await readPrivate<Installation>(stage, record, [
289
+ { path: executable },
290
+ ]);
291
+ if (!pending)
292
+ throw new HostError(
293
+ "Unrecorded Kubo executable; move it aside manually. It was not adopted.",
294
+ );
295
+ await verifyProgram(executable, pending);
296
+ await rename(join(stage, record), join(directory, record));
297
+ installed = pending;
298
+ }
299
+ await clean(directory, stage);
300
+ return installed;
301
+ }
302
+ export async function kuboBinary(
303
+ stateDir: string,
304
+ options: InstallOptions = {},
305
+ ): Promise<string> {
306
+ let phase = "installation",
307
+ source = "protected local installation";
308
+ try {
309
+ options.signal?.throwIfAborted();
310
+ const directory = await privateDirectory(stateDir, "kubo-bin");
311
+ options.diagnostic?.(
312
+ "Checking the Kubo installation (local lock wait: up to 30s)...",
313
+ );
314
+ const platform =
315
+ process.platform === "win32" ? "windows" : process.platform;
316
+ if (
317
+ !["windows", "darwin", "linux"].includes(platform) ||
318
+ !["x64", "arm64"].includes(process.arch)
319
+ )
320
+ 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
+ const program = platform === "windows" ? "ipfs.exe" : "ipfs";
329
+ const executable = join(directory, program);
330
+ const install = async () => {
331
+ let installed = await readPrivate<Installation>(directory, record, [
332
+ { path: executable },
333
+ ]);
334
+ if (installed !== undefined) {
335
+ options.diagnostic?.(`Verifying installed Kubo ${KUBO_VERSION}...`);
336
+ await verifyProgram(executable, installed);
337
+ }
338
+ installed = await recover(directory, executable, installed);
339
+ if (
340
+ options.diagnostic &&
341
+ (await readdir(directory)).some((name) =>
342
+ /^(?:extract-[\w-]{43}|[\w-]{43}\.(?:zip|tar\.gz)|(?:install-|\.write-)[a-f0-9-]{36})$/.test(
343
+ name,
344
+ ),
345
+ )
346
+ )
347
+ options.diagnostic(
348
+ "Untracked Kubo staging files were left untouched. Inspect kubo-bin manually; do not delete the verified installation.",
349
+ );
350
+ if (installed) {
351
+ if (options.archive !== undefined) {
352
+ phase = "archive verification";
353
+ source = "local archive";
354
+ if ((await digest(options.archive, MAX_ARCHIVE)) !== expected)
355
+ throw new HostError("Kubo archive checksum mismatch.");
356
+ }
357
+ return executable;
358
+ }
359
+ if (await exists(executable))
360
+ throw new HostError(
361
+ "Unrecorded Kubo executable; move it aside manually. It was not adopted.",
362
+ );
363
+ let input: { archive: string } | { url: string; size: number };
364
+ if (options.archive !== undefined) input = { archive: options.archive };
365
+ else {
366
+ phase = "release metadata";
367
+ source = "api.github.com/ipfs/kubo";
368
+ options.diagnostic?.(
369
+ `Checking official Kubo ${KUBO_VERSION} release (timeout: 30s)...`,
370
+ );
371
+ input = await officialAsset(filename, expected, options.signal);
372
+ }
373
+ phase = "installation";
374
+ source = "protected local staging";
375
+ const name = `install-${randomUUID()}`,
376
+ stage = join(directory, name);
377
+ if (await exists(stage))
378
+ throw new HostError("Staging path already exists; retry setup.");
379
+ await writePrivate(directory, journal, { stage: name });
380
+ let placed = false,
381
+ created = false;
382
+ try {
383
+ await mkdir(stage, { mode: 0o700 });
384
+ created = true;
385
+ await secureNew(stage, true);
386
+ const archive = join(stage, filename);
387
+ phase = "archive transfer";
388
+ source = "archive" in input ? "local archive" : "github.com/ipfs/kubo";
389
+ if ("archive" in input)
390
+ options.diagnostic?.("Copying the local Kubo archive...");
391
+ const total = await transfer(archive, input, options);
392
+ phase = "archive verification";
393
+ options.diagnostic?.(
394
+ `Kubo download complete: ${(total / (1024 * 1024)).toFixed(1)} MiB. Verifying checksum...`,
395
+ );
396
+ if ((await digest(archive, MAX_ARCHIVE)) !== expected)
397
+ throw new HostError("Kubo archive checksum mismatch.");
398
+ phase = "extraction";
399
+ source = "verified release archive";
400
+ options.diagnostic?.("Extracting and verifying the Kubo executable...");
401
+ const member = `kubo/${program}`;
402
+ await run("tar", ["-xf", archive, "-C", stage, member], {
403
+ signal: options.signal,
404
+ timeout: 30_000,
405
+ windowsHide: true,
406
+ });
407
+ const extracted = join(stage, "kubo", program);
408
+ if (!(await lstat(extracted)).isFile())
409
+ throw new HostError("Invalid Kubo executable.");
410
+ await secureNew(extracted);
411
+ if (platform !== "windows") await chmod(extracted, 0o700);
412
+ phase = "executable verification";
413
+ source = "staged Kubo program";
414
+ const version = await run(extracted, ["version", "--number"], {
415
+ signal: options.signal,
416
+ env: {
417
+ ...process.env,
418
+ HOME: stage,
419
+ USERPROFILE: stage,
420
+ IPFS_PATH: join(stage, "version-repo"),
421
+ },
422
+ timeout: 10_000,
423
+ windowsHide: true,
424
+ });
425
+ if (version.stdout.trim() !== KUBO_VERSION)
426
+ throw new HostError("Kubo executable version mismatch.");
427
+ const verified = {
428
+ version: KUBO_VERSION,
429
+ hash: await digest(extracted, 512 * 1024 * 1024),
430
+ };
431
+ phase = "installation";
432
+ source = "protected local installation";
433
+ await writePrivate(stage, record, verified);
434
+ // Atomic and exclusive: never overwrite a binary placed by another actor.
435
+ await link(extracted, executable);
436
+ placed = true;
437
+ await rename(join(stage, record), join(directory, record));
438
+ placed = false;
439
+ return executable;
440
+ } finally {
441
+ // If rollback itself fails, retain the journal and verified candidate record for recovery.
442
+ if (placed) await rm(executable);
443
+ if (created) await clean(directory, stage);
444
+ else await rm(join(directory, journal));
445
+ }
446
+ };
447
+ return await withPrivateLock(directory, install, options.signal);
448
+ } catch (cause) {
449
+ options.signal?.throwIfAborted();
450
+ throw setupFailure(phase, source, cause);
451
+ }
452
+ }
@@ -0,0 +1,126 @@
1
+ import { boundedText } from "@ipab/bundle/pointer/scope";
2
+ import { HostError, object } from "./errors.js";
3
+ import { readPrivate, writePrivate } from "./swarm-files.js";
4
+
5
+ export interface PeeringPeer {
6
+ ID: string;
7
+ Addrs: string[];
8
+ }
9
+ export function memberPeers(
10
+ self: string,
11
+ profiles: ReadonlyMap<string, readonly string[]>,
12
+ bootstrap: readonly string[],
13
+ ): PeeringPeer[] {
14
+ const desired: PeeringPeer[] = [];
15
+ for (const [ID, profile] of profiles) {
16
+ if (ID === self) continue;
17
+ const suffix = `/p2p/${ID}`;
18
+ // A nonempty member-published profile supersedes bootstrap hints for that ID;
19
+ // otherwise a stale hint would survive an explicit address replacement.
20
+ const addresses = profile.length
21
+ ? profile
22
+ : bootstrap.filter((addr) => addr.endsWith(suffix));
23
+ const Addrs = [
24
+ ...new Set(
25
+ addresses.map((addr) => {
26
+ if (!addr.endsWith(suffix))
27
+ throw new HostError("Approved peer address binding changed.");
28
+ return addr.slice(0, -suffix.length);
29
+ }),
30
+ ),
31
+ ]
32
+ .slice(0, 16)
33
+ .sort();
34
+ if (Addrs.length) desired.push({ ID, Addrs });
35
+ }
36
+ return desired.sort((a, b) => a.ID.localeCompare(b.ID));
37
+ }
38
+ type Rpc = (command: string, signal: AbortSignal) => Promise<Response>;
39
+ async function localRpc(rpc: Rpc, command: string, signal: AbortSignal) {
40
+ const response = await rpc(command, signal);
41
+ if (!response.ok) {
42
+ await response.body?.cancel();
43
+ throw new HostError(
44
+ `Owned Kubo peering reconciliation failed (HTTP ${response.status}); retry Swarm activation.`,
45
+ );
46
+ }
47
+ return boundedText(response);
48
+ }
49
+ function peers(value: unknown): PeeringPeer[] {
50
+ if (value === undefined || value === null) return [];
51
+ if (!Array.isArray(value))
52
+ throw new HostError("Invalid owned Kubo peering list.");
53
+ return value
54
+ .map((item: unknown) => {
55
+ const { ID, Addrs } = object(item, "peering entry");
56
+ if (
57
+ typeof ID !== "string" ||
58
+ !/^[A-Za-z0-9]{1,128}$/.test(ID) ||
59
+ (Addrs !== null &&
60
+ (!Array.isArray(Addrs) ||
61
+ !Addrs.every((addr) => typeof addr === "string")))
62
+ )
63
+ throw new HostError("Invalid owned Kubo peering entry.");
64
+ return { ID, Addrs: [...new Set(Addrs ?? [])].sort() };
65
+ })
66
+ .sort((a, b) => a.ID.localeCompare(b.ID));
67
+ }
68
+ export async function persistPeers(
69
+ repo: string,
70
+ desired: readonly PeeringPeer[],
71
+ online?: Rpc,
72
+ ) {
73
+ const config = await readPrivate<Record<string, unknown>>(repo, "config");
74
+ if (!config) throw new HostError("Missing protected Kubo configuration.");
75
+ const peering = object(config.Peering ?? {}, "Kubo Peering configuration");
76
+ if (JSON.stringify(peers(peering.Peers)) === JSON.stringify(desired)) return;
77
+ if (online) {
78
+ await localRpc(
79
+ online,
80
+ `config?arg=Peering.Peers&arg=${encodeURIComponent(JSON.stringify(desired))}&json=true`,
81
+ AbortSignal.timeout(5_000),
82
+ );
83
+ } else {
84
+ await writePrivate(repo, "config", {
85
+ ...config,
86
+ Peering: { ...peering, Peers: desired },
87
+ });
88
+ }
89
+ }
90
+ export async function reconcilePeers(
91
+ rpc: Rpc,
92
+ desired: readonly PeeringPeer[],
93
+ ) {
94
+ const signal = AbortSignal.timeout(10_000);
95
+ const result = object(
96
+ JSON.parse(await localRpc(rpc, "swarm/peering/ls", signal)) as unknown,
97
+ "owned Kubo peering response",
98
+ );
99
+ if (!Object.hasOwn(result, "Peers"))
100
+ throw new HostError("Invalid owned Kubo peering response.");
101
+ const actual = peers(result.Peers);
102
+ for (const { ID } of actual)
103
+ if (!desired.some((peer) => peer.ID === ID))
104
+ await localRpc(
105
+ rpc,
106
+ `swarm/peering/rm?arg=${encodeURIComponent(ID)}`,
107
+ signal,
108
+ );
109
+ for (const { ID, Addrs } of desired) {
110
+ if (
111
+ JSON.stringify(actual.find((peer) => peer.ID === ID)?.Addrs) ===
112
+ JSON.stringify(Addrs)
113
+ )
114
+ continue;
115
+ await localRpc(
116
+ rpc,
117
+ `swarm/peering/add?${peerArguments(ID, Addrs)}`,
118
+ signal,
119
+ );
120
+ }
121
+ }
122
+ export function peerArguments(id: string, addresses: readonly string[]) {
123
+ return addresses
124
+ .map((addr) => `arg=${encodeURIComponent(`${addr}/p2p/${id}`)}`)
125
+ .join("&");
126
+ }