@ipab/cli 0.1.0-rc.4 → 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 (128) hide show
  1. package/README.md +88 -16
  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 +6 -2
  8. package/dist/cli.d.ts.map +1 -1
  9. package/dist/cli.js +656 -278
  10. package/dist/cli.js.map +1 -1
  11. package/dist/config-secret.d.ts +1 -1
  12. package/dist/config-secret.d.ts.map +1 -1
  13. package/dist/config-secret.js +2 -73
  14. package/dist/config-secret.js.map +1 -1
  15. package/dist/config.d.ts +1 -0
  16. package/dist/config.d.ts.map +1 -1
  17. package/dist/config.js +12 -1
  18. package/dist/config.js.map +1 -1
  19. package/dist/content-provider.d.ts +1 -1
  20. package/dist/content-provider.d.ts.map +1 -1
  21. package/dist/content-provider.js +4 -3
  22. package/dist/content-provider.js.map +1 -1
  23. package/dist/context-types.d.ts +12 -0
  24. package/dist/context-types.d.ts.map +1 -0
  25. package/dist/context-types.js +2 -0
  26. package/dist/context-types.js.map +1 -0
  27. package/dist/context.d.ts +6 -1
  28. package/dist/context.d.ts.map +1 -1
  29. package/dist/context.js +24 -9
  30. package/dist/context.js.map +1 -1
  31. package/dist/doctor.d.ts +29 -0
  32. package/dist/doctor.d.ts.map +1 -0
  33. package/dist/doctor.js +576 -0
  34. package/dist/doctor.js.map +1 -0
  35. package/dist/identity.d.ts +1 -1
  36. package/dist/identity.d.ts.map +1 -1
  37. package/dist/identity.js +9 -9
  38. package/dist/identity.js.map +1 -1
  39. package/dist/ipc.d.ts +3 -2
  40. package/dist/ipc.d.ts.map +1 -1
  41. package/dist/ipc.js +33 -9
  42. package/dist/ipc.js.map +1 -1
  43. package/dist/kubo-install.d.ts +26 -0
  44. package/dist/kubo-install.d.ts.map +1 -0
  45. package/dist/kubo-install.js +724 -0
  46. package/dist/kubo-install.js.map +1 -0
  47. package/dist/kubo-peering.d.ts +11 -0
  48. package/dist/kubo-peering.d.ts.map +1 -0
  49. package/dist/kubo-peering.js +93 -0
  50. package/dist/kubo-peering.js.map +1 -0
  51. package/dist/kubo-peers.d.ts +12 -0
  52. package/dist/kubo-peers.d.ts.map +1 -0
  53. package/dist/kubo-peers.js +118 -0
  54. package/dist/kubo-peers.js.map +1 -0
  55. package/dist/kubo-release.d.ts +22 -0
  56. package/dist/kubo-release.d.ts.map +1 -0
  57. package/dist/kubo-release.js +176 -0
  58. package/dist/kubo-release.js.map +1 -0
  59. package/dist/kubo.d.ts +12 -4
  60. package/dist/kubo.d.ts.map +1 -1
  61. package/dist/kubo.js +218 -259
  62. package/dist/kubo.js.map +1 -1
  63. package/dist/pins.d.ts +15 -17
  64. package/dist/pins.d.ts.map +1 -1
  65. package/dist/pins.js +144 -106
  66. package/dist/pins.js.map +1 -1
  67. package/dist/publish-source.d.ts +3 -0
  68. package/dist/publish-source.d.ts.map +1 -0
  69. package/dist/publish-source.js +85 -0
  70. package/dist/publish-source.js.map +1 -0
  71. package/dist/runtime.d.ts +2 -0
  72. package/dist/runtime.d.ts.map +1 -1
  73. package/dist/runtime.js +4 -2
  74. package/dist/runtime.js.map +1 -1
  75. package/dist/state-storage-windows.d.ts +2 -0
  76. package/dist/state-storage-windows.d.ts.map +1 -0
  77. package/dist/state-storage-windows.js +114 -0
  78. package/dist/state-storage-windows.js.map +1 -0
  79. package/dist/state-storage.d.ts +5 -0
  80. package/dist/state-storage.d.ts.map +1 -0
  81. package/dist/state-storage.js +330 -0
  82. package/dist/state-storage.js.map +1 -0
  83. package/dist/state.d.ts +42 -8
  84. package/dist/state.d.ts.map +1 -1
  85. package/dist/state.js +254 -98
  86. package/dist/state.js.map +1 -1
  87. package/dist/swarm-envelope.d.ts +1 -0
  88. package/dist/swarm-envelope.d.ts.map +1 -1
  89. package/dist/swarm-envelope.js +12 -0
  90. package/dist/swarm-envelope.js.map +1 -1
  91. package/dist/swarm-files.d.ts +1 -1
  92. package/dist/swarm-files.d.ts.map +1 -1
  93. package/dist/swarm-files.js +4 -1
  94. package/dist/swarm-files.js.map +1 -1
  95. package/dist/swarm.d.ts +70 -11
  96. package/dist/swarm.d.ts.map +1 -1
  97. package/dist/swarm.js +1033 -167
  98. package/dist/swarm.js.map +1 -1
  99. package/package.json +4 -4
  100. package/src/app-templates.ts +1 -1
  101. package/src/cli.ts +827 -356
  102. package/src/config-secret.ts +2 -84
  103. package/src/config.ts +14 -1
  104. package/src/content-provider.ts +4 -2
  105. package/src/context-types.ts +11 -0
  106. package/src/context.ts +39 -9
  107. package/src/doctor.ts +902 -0
  108. package/src/identity.ts +10 -10
  109. package/src/ipc.ts +49 -8
  110. package/src/kubo-install.ts +936 -0
  111. package/src/kubo-peering.ts +126 -0
  112. package/src/kubo-peers.ts +145 -0
  113. package/src/kubo-release.ts +230 -0
  114. package/src/kubo.ts +302 -336
  115. package/src/pins.ts +188 -126
  116. package/src/publish-source.ts +103 -0
  117. package/src/runtime.ts +10 -2
  118. package/src/state-storage-windows.ts +134 -0
  119. package/src/state-storage.ts +375 -0
  120. package/src/state.ts +410 -118
  121. package/src/swarm-envelope.ts +14 -0
  122. package/src/swarm-files.ts +4 -0
  123. package/src/swarm.ts +1482 -207
  124. package/dist/setup.d.ts +0 -7
  125. package/dist/setup.d.ts.map +0 -1
  126. package/dist/setup.js +0 -22
  127. package/dist/setup.js.map +0 -1
  128. package/src/setup.ts +0 -21
package/dist/kubo.js CHANGED
@@ -1,23 +1,25 @@
1
1
  import { execFile, spawn } from "node:child_process";
2
2
  import { promisify } from "node:util";
3
- import { createHash, createPrivateKey, createPublicKey, sign, } from "node:crypto";
4
- import { chmod, lstat, open, readFile, rename, rm, writeFile, } from "node:fs/promises";
3
+ import { createPrivateKey, createPublicKey, sign } from "node:crypto";
4
+ import { lstat, open, readFile, writeFile } from "node:fs/promises";
5
5
  import { join } from "node:path";
6
6
  import { createServer } from "node:net";
7
- import { networkInterfaces } from "node:os";
7
+ import { advertisedIps, BlockUnavailable, readWithPeers, } from "./kubo-peers.js";
8
8
  import { base58btc } from "multiformats/bases/base58";
9
9
  import { boundedText, uniqueId } from "@ipab/bundle/pointer/scope";
10
10
  import { protectedPath, protectedPaths, secureNew } from "./identity.js";
11
11
  import { privateDirectory, readPrivate, withPrivateLock, writePrivate, } from "./swarm-files.js";
12
12
  import { HostError, object } from "./errors.js";
13
13
  import { nodeError } from "./authoring.js";
14
- export const KUBO_VERSION = "0.43.2";
14
+ import { peerArguments, persistPeers, reconcilePeers, } from "./kubo-peering.js";
15
+ import { kuboBinary, withKuboProgram } from "./kubo-install.js";
16
+ export { kuboBinary };
17
+ export { KUBO_VERSION } from "./kubo-release.js";
15
18
  function swarmAddress(listen, port) {
16
19
  return `/ip4/${listen === "loopback" ? "127.0.0.1" : "0.0.0.0"}/tcp/${port}`;
17
20
  }
18
21
  const run = promisify(execFile);
19
- const hash = (data) => createHash("sha256").update(data).digest("hex");
20
- function nodeRecord(value, scope) {
22
+ export function nodeRecord(value, scope) {
21
23
  const record = object(value, "protected managed-node record");
22
24
  const { peerId, api, gateway, swarm, auth, pid, epoch, listen } = record;
23
25
  if (Object.keys(record).some((key) => ![
@@ -61,113 +63,6 @@ function nodeRecord(value, scope) {
61
63
  ...(listen !== undefined ? { listen } : {}),
62
64
  };
63
65
  }
64
- export async function kuboBinary(stateDir) {
65
- const directory = await privateDirectory(stateDir, "kubo-bin");
66
- return withPrivateLock(directory, async () => {
67
- const executable = join(directory, process.platform === "win32" ? "ipfs.exe" : "ipfs");
68
- const installed = await readPrivate(directory, "installation.json", [{ path: executable }]);
69
- if (installed) {
70
- if (installed.version !== KUBO_VERSION ||
71
- installed.hash !== hash(await readFile(executable)))
72
- throw new HostError("Kubo installation integrity mismatch; do not use this binary.");
73
- return executable;
74
- }
75
- const platforms = {
76
- win32: "windows",
77
- darwin: "darwin",
78
- linux: "linux",
79
- };
80
- const platform = platforms[process.platform];
81
- if (!platform || !["x64", "arm64"].includes(process.arch))
82
- throw new HostError("Unsupported Kubo platform.");
83
- const arch = process.arch === "x64" ? "amd64" : "arm64";
84
- const filename = `kubo_v${KUBO_VERSION}_${platform}-${arch}.${platform === "windows" ? "zip" : "tar.gz"}`;
85
- // Official release metadata supplies the immutable archive digest; HTTPS is the trust boundary.
86
- const release = await fetch(`https://api.github.com/repos/ipfs/kubo/releases/tags/v${KUBO_VERSION}`, {
87
- redirect: "error",
88
- signal: AbortSignal.timeout(30_000),
89
- headers: { accept: "application/vnd.github+json" },
90
- });
91
- if (!release.ok)
92
- throw new HostError(`Could not verify official Kubo release (HTTP ${release.status}).`);
93
- const metadata = JSON.parse(await boundedText(release));
94
- const asset = metadata.assets.find((item) => item.name === filename);
95
- if (metadata.draft ||
96
- metadata.prerelease ||
97
- !asset ||
98
- !/^sha256:[a-f0-9]{64}$/.test(asset.digest) ||
99
- asset.browser_download_url !==
100
- `https://github.com/ipfs/kubo/releases/download/v${KUBO_VERSION}/${filename}`)
101
- throw new HostError("Official stable Kubo archive/digest unavailable.");
102
- const archive = join(directory, `${uniqueId()}.${platform === "windows" ? "zip" : "tar.gz"}`);
103
- const stage = await privateDirectory(directory, `extract-${uniqueId()}`);
104
- try {
105
- const response = await fetch(asset.browser_download_url, {
106
- signal: AbortSignal.timeout(180_000),
107
- });
108
- if (!response.ok || !response.body)
109
- throw new HostError("Kubo download failed.");
110
- const handle = await open(archive, "wx", 0o600);
111
- let total = 0;
112
- const digest = createHash("sha256");
113
- try {
114
- await secureNew(archive);
115
- const stream = response.body;
116
- for await (const chunk of stream) {
117
- total += chunk.length;
118
- if (total > 150 * 1024 * 1024)
119
- throw new HostError("Kubo archive exceeds limit.");
120
- digest.update(chunk);
121
- await handle.write(chunk);
122
- }
123
- await handle.sync();
124
- }
125
- finally {
126
- await handle.close();
127
- }
128
- if (`sha256:${digest.digest("hex")}` !== asset.digest)
129
- throw new HostError("Kubo archive checksum mismatch.");
130
- const listing = await run("tar", ["-tf", archive], {
131
- timeout: 30_000,
132
- maxBuffer: 1024 * 1024,
133
- windowsHide: true,
134
- });
135
- if (listing.stdout
136
- .split(/\r?\n/)
137
- .filter(Boolean)
138
- .some((path) => !/^kubo\/[A-Za-z0-9._/-]+$/.test(path) ||
139
- path.split("/").includes("..")))
140
- throw new HostError("Unsafe Kubo archive layout.");
141
- await run("tar", ["-xf", archive, "-C", stage], {
142
- timeout: 30_000,
143
- windowsHide: true,
144
- });
145
- const extracted = join(stage, "kubo", process.platform === "win32" ? "ipfs.exe" : "ipfs");
146
- if (!(await lstat(extracted)).isFile() ||
147
- (await lstat(extracted)).isSymbolicLink())
148
- throw new HostError("Invalid Kubo executable.");
149
- await secureNew(extracted);
150
- if (process.platform !== "win32")
151
- await chmod(extracted, 0o700);
152
- const version = await run(extracted, ["version", "--number"], {
153
- timeout: 10_000,
154
- windowsHide: true,
155
- });
156
- if (version.stdout.trim() !== KUBO_VERSION)
157
- throw new HostError("Kubo executable version mismatch.");
158
- await rename(extracted, executable);
159
- await writePrivate(directory, "installation.json", {
160
- version: KUBO_VERSION,
161
- hash: hash(await readFile(executable)),
162
- });
163
- return executable;
164
- }
165
- finally {
166
- await rm(stage, { recursive: true, force: true });
167
- await rm(archive, { force: true });
168
- }
169
- });
170
- }
171
66
  async function freePort() {
172
67
  const server = createServer();
173
68
  return new Promise((resolve, reject) => {
@@ -191,10 +86,19 @@ async function freePort() {
191
86
  export async function prepareNode(stateDir, scope, listen = "lan") {
192
87
  if (!/^[a-f0-9]{64}$/.test(scope))
193
88
  throw new HostError("Invalid service-bound local Scope identity.");
194
- const binary = await kuboBinary(stateDir);
195
- return prepareWithBinary(stateDir, scope, binary, listen);
89
+ return withKuboProgram(stateDir, (binary) => prepareWithBinary(stateDir, scope, binary, listen));
196
90
  }
197
- async function prepareWithBinary(stateDir, scope, binary, listen) {
91
+ export async function checkCachedNode(stateDir, scope, epoch, peer) {
92
+ if (!/^[a-f0-9]{64}$/.test(scope))
93
+ throw new HostError("Invalid service-bound local Scope identity.");
94
+ const saved = await readPrivate(join(stateDir, "swarm-nodes", scope), "node.json");
95
+ if (saved === undefined)
96
+ return;
97
+ const node = nodeRecord(saved, scope);
98
+ if (node.peerId !== peer || (node.epoch !== undefined && node.epoch > epoch))
99
+ throw new HostError("Cached membership does not match the recorded node identity or epoch; retry with --force.");
100
+ }
101
+ async function prepareWithBinary(stateDir, scope, binary, listen, signal) {
198
102
  const parent = join(stateDir, "swarm-nodes");
199
103
  const directory = join(parent, scope);
200
104
  const repo = join(directory, "repo");
@@ -208,7 +112,7 @@ async function prepareWithBinary(stateDir, scope, binary, listen) {
208
112
  await privateDirectory(parent, scope);
209
113
  await privateDirectory(directory, "repo");
210
114
  }
211
- return withPrivateLock(directory, async () => {
115
+ const prepare = async () => {
212
116
  let record = await readPrivate(directory, "node.json", [
213
117
  { path: join(repo, "config") },
214
118
  ]);
@@ -230,6 +134,7 @@ async function prepareWithBinary(stateDir, scope, binary, listen) {
230
134
  throw cause;
231
135
  await run(binary, ["init", "--profile=server"], {
232
136
  env,
137
+ signal,
233
138
  timeout: 30_000,
234
139
  windowsHide: true,
235
140
  });
@@ -284,15 +189,6 @@ async function prepareWithBinary(stateDir, scope, binary, listen) {
284
189
  record.listen ??= "lan";
285
190
  if (record.listen !== listen)
286
191
  throw new HostError("Managed node already listens in a different mode; existing repos are not rebound.");
287
- const local = Object.values(networkInterfaces())
288
- .flatMap((items) => items ?? [])
289
- .filter((item) => item.family === "IPv4" &&
290
- /^(10\.|192\.168\.|172\.(1[6-9]|2\d|3[01])\.|100\.(6[4-9]|[7-9]\d|1[01]\d|12[0-7])\.)/.test(item.address))
291
- .map((item) => item.address)
292
- .slice(0, 15);
293
- // A loopback-only listener is reachable exclusively from this device, so it
294
- // advertises just loopback; a LAN listener advertises its private IPv4 IPs.
295
- const reachable = record.listen === "loopback" ? ["127.0.0.1"] : [...local, "127.0.0.1"];
296
192
  return {
297
193
  repo,
298
194
  peerId: record.peerId,
@@ -300,9 +196,10 @@ async function prepareWithBinary(stateDir, scope, binary, listen) {
300
196
  gateway: `http://127.0.0.1:${record.gateway}`,
301
197
  auth: record.auth,
302
198
  ...(record.pid !== undefined ? { pid: record.pid } : {}),
303
- addresses: [...new Set(reachable)].map((ip) => `/ip4/${ip}/tcp/${record.swarm}/p2p/${record.peerId}`),
199
+ addresses: advertisedIps(record.listen).map((ip) => `/ip4/${ip}/tcp/${record.swarm}/p2p/${record.peerId}`),
304
200
  };
305
- });
201
+ };
202
+ return withPrivateLock(directory, prepare, signal);
306
203
  }
307
204
  export async function peerProof(node, message) {
308
205
  await protectedPath(join(node.repo, "config"));
@@ -347,9 +244,9 @@ async function rpc(node, command, signal, timeout = 5000) {
347
244
  : AbortSignal.timeout(timeout),
348
245
  });
349
246
  }
350
- async function ready(node) {
247
+ async function ready(node, signal) {
351
248
  try {
352
- const response = await rpc(node, "id");
249
+ const response = await rpc(node, "id", signal);
353
250
  if (response.status === 401 || response.status === 403) {
354
251
  await response.body?.cancel();
355
252
  throw new HostError("Owned Kubo API authorization failed; refusing control.");
@@ -364,6 +261,7 @@ async function ready(node) {
364
261
  return true;
365
262
  }
366
263
  catch (cause) {
264
+ signal?.throwIfAborted();
367
265
  if (cause instanceof HostError)
368
266
  throw cause;
369
267
  return false;
@@ -392,119 +290,120 @@ export async function stopNode(node) {
392
290
  }
393
291
  throw new HostError("Owned Kubo node did not stop.");
394
292
  }
395
- export async function startNode(stateDir, scope, key, epoch, addresses, diagnostic, listen = "lan") {
293
+ export async function startNode(stateDir, scope, key, epoch, listen = "lan", membership) {
396
294
  if (!/^[a-f0-9]{64}$/.test(scope))
397
295
  throw new HostError("Invalid service-bound local Scope identity.");
398
296
  if (!/^[a-f0-9]{64}$/.test(key))
399
297
  throw new HostError("Invalid Swarm key.");
400
- const binary = await kuboBinary(stateDir);
401
- const node = await prepareWithBinary(stateDir, scope, binary, listen);
402
- const directory = join(stateDir, "swarm-nodes", scope);
403
- return withPrivateLock(directory, async () => {
404
- const record = (await readPrivate(directory, "node.json"));
405
- if (record.epoch !== undefined && record.epoch !== epoch)
406
- await stopNode(node);
407
- const keyPath = join(node.repo, "swarm.key");
408
- if (record.epoch === epoch) {
409
- await protectedPath(keyPath);
410
- if ((await readFile(keyPath, "utf8")) !==
411
- `/key/swarm/psk/1.0.0/\n/base16/\n${key}\n`)
412
- throw new HostError("Swarm key file does not match approved epoch.");
413
- }
414
- else {
415
- await writeFile(keyPath, `/key/swarm/psk/1.0.0/\n/base16/\n${key}\n`, {
416
- mode: 0o600,
417
- });
418
- await secureNew(keyPath);
419
- }
420
- if (!(await ready(node))) {
421
- const logfile = join(directory, "daemon.log");
422
- const log = await open(logfile, "a", 0o600);
423
- await secureNew(logfile);
424
- const child = spawn(binary, ["daemon", "--enable-gc=false", "--migrate=false"], {
425
- env: { ...process.env, IPFS_PATH: node.repo, LIBP2P_FORCE_PNET: "1" },
426
- detached: true,
427
- windowsHide: true,
428
- stdio: ["ignore", log.fd, log.fd],
429
- });
430
- let failure;
431
- child.once("error", (error) => {
432
- failure = error;
433
- });
434
- const closed = new Promise((resolve) => {
435
- child.once("close", () => {
436
- resolve();
437
- });
438
- });
439
- child.unref();
440
- await log.close();
441
- try {
442
- if (child.pid !== undefined) {
443
- record.pid = child.pid;
444
- node.pid = child.pid;
445
- record.epoch = epoch;
446
- await writePrivate(directory, "node.json", record);
298
+ const signal = membership?.signal;
299
+ signal?.throwIfAborted();
300
+ return withKuboProgram(stateDir, async (binary) => {
301
+ signal?.throwIfAborted();
302
+ const node = await prepareWithBinary(stateDir, scope, binary, listen, signal);
303
+ if (membership && node.peerId !== membership.self)
304
+ throw new HostError("Approved PeerID differs from this local Request's Kubo identity.");
305
+ const directory = join(stateDir, "swarm-nodes", scope);
306
+ const start = async () => {
307
+ signal?.throwIfAborted();
308
+ const record = (await readPrivate(directory, "node.json"));
309
+ if (record.epoch !== undefined && record.epoch > epoch)
310
+ throw new HostError("Refusing to restore an older Swarm epoch; refresh membership.");
311
+ if (record.epoch !== undefined && record.epoch !== epoch)
312
+ await stopNode(node);
313
+ const online = await ready(node, signal);
314
+ if (!online && record.pid !== undefined) {
315
+ try {
316
+ process.kill(record.pid, 0);
317
+ throw new HostError("Owned node process is still running but not ready; retry before changing its configuration.");
447
318
  }
448
- for (let i = 0;; i++) {
449
- if (failure)
450
- throw failure;
451
- if (await ready(node))
452
- break;
453
- if (i >= 150 || child.exitCode !== null)
454
- throw new HostError("Owned Kubo startup failed; inspect protected daemon.log.");
455
- await new Promise((resolve) => setTimeout(resolve, 100));
319
+ catch (cause) {
320
+ if (!nodeError(cause, "ESRCH"))
321
+ throw cause;
456
322
  }
457
323
  }
458
- catch (cause) {
459
- child.kill();
460
- await Promise.race([
461
- closed,
462
- new Promise((resolve) => setTimeout(resolve, 5000)),
463
- ]);
464
- if (child.exitCode === null && child.signalCode === null)
465
- child.kill("SIGKILL");
466
- await closed;
467
- throw cause;
324
+ const call = (command, budget) => rpc(node, command, signal ? AbortSignal.any([signal, budget]) : budget);
325
+ const desired = membership?.peers ?? [];
326
+ const keyPath = join(node.repo, "swarm.key");
327
+ if (record.epoch === epoch) {
328
+ await protectedPath(keyPath);
329
+ if ((await readFile(keyPath, "utf8")) !==
330
+ `/key/swarm/psk/1.0.0/\n/base16/\n${key}\n`)
331
+ throw new HostError("Swarm key file does not match approved epoch.");
468
332
  }
469
- }
470
- record.epoch = epoch;
471
- await writePrivate(directory, "node.json", record);
472
- const groups = new Map();
473
- for (const address of addresses) {
474
- validateAddress(address);
475
- const target = address.split("/").at(-1);
476
- if (target === node.peerId)
477
- continue;
478
- const group = groups.get(target) ?? [];
479
- if (group.length < 16 && !group.includes(address))
480
- group.push(address);
481
- groups.set(target, group);
482
- }
483
- const budget = AbortSignal.timeout(10_000);
484
- await Promise.all([...groups.values()].map(async (group) => {
485
- const connected = new AbortController();
486
- await Promise.all(group.map(async (address) => {
333
+ else {
334
+ await persistPeers(node.repo, desired, online ? call : undefined);
335
+ await writeFile(keyPath, `/key/swarm/psk/1.0.0/\n/base16/\n${key}\n`, {
336
+ mode: 0o600,
337
+ });
338
+ await secureNew(keyPath);
339
+ }
340
+ if (record.epoch === epoch)
341
+ await persistPeers(node.repo, desired, online ? call : undefined);
342
+ if (!online) {
343
+ signal?.throwIfAborted();
344
+ const logfile = join(directory, "daemon.log");
345
+ const log = await open(logfile, "a", 0o600);
346
+ await secureNew(logfile);
347
+ const child = spawn(binary, ["daemon", "--enable-gc=false", "--migrate=false"], {
348
+ env: {
349
+ ...process.env,
350
+ IPFS_PATH: node.repo,
351
+ LIBP2P_FORCE_PNET: "1",
352
+ },
353
+ detached: true,
354
+ windowsHide: true,
355
+ stdio: ["ignore", log.fd, log.fd],
356
+ });
357
+ let failure;
358
+ child.once("error", (error) => {
359
+ failure = error;
360
+ });
361
+ const closed = new Promise((resolve) => {
362
+ child.once("close", () => {
363
+ resolve();
364
+ });
365
+ });
366
+ child.unref();
367
+ await log.close();
487
368
  try {
488
- const response = await rpc(node, `swarm/connect?arg=${encodeURIComponent(address)}`, AbortSignal.any([budget, connected.signal]));
489
- const ok = response.ok;
490
- if (!ok) {
491
- const reason = JSON.parse(await boundedText(response));
492
- diagnostic?.(`Swarm peer dial failed at ${address}: ${reason.Message?.slice(0, 512) ?? `HTTP ${response.status}`}`);
369
+ if (child.pid !== undefined) {
370
+ record.pid = child.pid;
371
+ node.pid = child.pid;
372
+ record.epoch = epoch;
373
+ await writePrivate(directory, "node.json", record);
374
+ }
375
+ for (let i = 0;; i++) {
376
+ signal?.throwIfAborted();
377
+ if (failure)
378
+ throw failure;
379
+ if (await ready(node, signal))
380
+ break;
381
+ if (i >= 150 || child.exitCode !== null)
382
+ throw new HostError("Owned Kubo startup failed; inspect protected daemon.log.");
383
+ await new Promise((resolve) => setTimeout(resolve, 100));
493
384
  }
494
- await response.body?.cancel();
495
- if (ok)
496
- connected.abort();
497
385
  }
498
386
  catch (cause) {
499
- if (!connected.signal.aborted)
500
- diagnostic?.(`Swarm peer dial unavailable at ${address}: ${cause instanceof Error ? cause.message : "network error"}`);
501
- // An offline address must not hide a reachable address of the same PeerID.
502
- // Content reads still report actual network failure, not authorization failure.
387
+ child.kill();
388
+ await Promise.race([
389
+ closed,
390
+ new Promise((resolve) => setTimeout(resolve, 5000)),
391
+ ]);
392
+ if (child.exitCode === null && child.signalCode === null)
393
+ child.kill("SIGKILL");
394
+ await closed;
395
+ throw cause;
503
396
  }
504
- }));
505
- }));
506
- return node;
507
- });
397
+ }
398
+ if (record.epoch !== epoch) {
399
+ record.epoch = epoch;
400
+ await writePrivate(directory, "node.json", record);
401
+ }
402
+ await reconcilePeers(call, desired);
403
+ return node;
404
+ };
405
+ return withPrivateLock(directory, start, signal);
406
+ }, signal);
508
407
  }
509
408
  export function validateAddress(address, expectedPeer) {
510
409
  const match = /^\/ip4\/(\d+\.\d+\.\d+\.\d+)\/tcp\/([1-9]\d{0,4})\/p2p\/([A-Za-z0-9]+)$/.exec(address);
@@ -514,40 +413,100 @@ export function validateAddress(address, expectedPeer) {
514
413
  (expectedPeer && match[3] !== expectedPeer))
515
414
  throw new HostError("LAN/VPN profile requires IPv4 TCP multiaddr bound to its PeerID.");
516
415
  }
517
- export function kuboSource(node) {
416
+ export function kuboSource(node, addresses = [], diagnostic, detailed = false) {
417
+ const groups = new Map();
418
+ for (const address of new Set(addresses)) {
419
+ validateAddress(address);
420
+ const target = address.split("/").at(-1);
421
+ if (target === node.peerId)
422
+ continue;
423
+ const group = groups.get(target) ?? [];
424
+ if (group.length < 16)
425
+ group.push(address.slice(0, -`/p2p/${target}`.length));
426
+ groups.set(target, group);
427
+ }
428
+ let fallbackUsed = false;
429
+ const connected = async (signal) => {
430
+ const response = await rpc(node, "swarm/peers", signal);
431
+ if (!response.ok) {
432
+ await response.body?.cancel();
433
+ throw new HostError(`HTTP ${response.status}`);
434
+ }
435
+ const data = object(JSON.parse(await boundedText(response)), "owned Kubo connections");
436
+ if (data.Peers === null)
437
+ return new Set();
438
+ if (!Array.isArray(data.Peers))
439
+ throw new HostError("Invalid owned Kubo connections.");
440
+ return new Set(data.Peers.map((entry) => {
441
+ const { Peer } = object(entry, "owned Kubo connection");
442
+ if (typeof Peer !== "string")
443
+ throw new HostError("Invalid owned Kubo connection.");
444
+ return Peer;
445
+ }));
446
+ };
447
+ const connect = async (id, addrs, signal) => {
448
+ const response = await rpc(node, `swarm/connect?${peerArguments(id, addrs)}`, signal);
449
+ try {
450
+ if (!response.ok)
451
+ throw new HostError(`HTTP ${response.status}`);
452
+ // swarm/connect may stream the result. Do not treat headers alone as success.
453
+ await boundedText(response);
454
+ }
455
+ finally {
456
+ await response.body?.cancel();
457
+ }
458
+ };
518
459
  return {
519
460
  block: {
520
461
  async get(cid, options = {}) {
521
- const response = await rpc(node, `block/get?arg=${encodeURIComponent(cid)}`, options.signal, 30_000);
522
- if (!response.ok || !response.body)
523
- throw new HostError(`Swarm block unavailable (HTTP ${response.status}).`);
524
- const stream = response.body;
525
- const reader = stream.getReader();
526
- const chunks = [];
527
- let size = 0;
528
- try {
529
- for (;;) {
530
- const part = await reader.read();
531
- if (part.done)
532
- break;
533
- size += part.value.length;
534
- if (size > 2 * 1024 * 1024) {
535
- await reader.cancel();
536
- throw new HostError("Kubo block exceeds limit.");
462
+ return readWithPeers(groups, async (signal, offline) => {
463
+ const response = await rpc(node, `block/get?arg=${encodeURIComponent(cid)}${offline ? "&offline=true" : ""}`, signal, 30_000);
464
+ if (!response.ok || !response.body) {
465
+ const error = `Swarm block unavailable (HTTP ${response.status}).`;
466
+ if (offline && [404, 500].includes(response.status)) {
467
+ const detail = object(JSON.parse(await boundedText(response)), "owned Kubo block error").Message;
468
+ if (typeof detail === "string" &&
469
+ detail.startsWith("block was not found locally (offline):"))
470
+ throw new BlockUnavailable(error);
537
471
  }
538
- chunks.push(part.value);
472
+ await response.body?.cancel();
473
+ if (!offline && [404, 500].includes(response.status))
474
+ throw new BlockUnavailable(error);
475
+ throw new HostError(error);
539
476
  }
540
- }
541
- finally {
542
- reader.releaseLock();
543
- }
544
- const bytes = new Uint8Array(size);
545
- let offset = 0;
546
- for (const chunk of chunks) {
547
- bytes.set(chunk, offset);
548
- offset += chunk.length;
549
- }
550
- return bytes;
477
+ const stream = response.body;
478
+ const reader = stream.getReader();
479
+ const chunks = [];
480
+ let size = 0;
481
+ try {
482
+ for (;;) {
483
+ const part = await reader.read();
484
+ if (part.done)
485
+ break;
486
+ size += part.value.length;
487
+ if (size > 2 * 1024 * 1024) {
488
+ await reader.cancel();
489
+ throw new HostError("Kubo block exceeds limit.");
490
+ }
491
+ chunks.push(part.value);
492
+ }
493
+ }
494
+ finally {
495
+ reader.releaseLock();
496
+ }
497
+ const bytes = new Uint8Array(size);
498
+ let offset = 0;
499
+ for (const chunk of chunks) {
500
+ bytes.set(chunk, offset);
501
+ offset += chunk.length;
502
+ }
503
+ return bytes;
504
+ }, connected, connect, () => {
505
+ if (fallbackUsed)
506
+ return false;
507
+ fallbackUsed = true;
508
+ return true;
509
+ }, options.signal, diagnostic, detailed);
551
510
  },
552
511
  },
553
512
  };