@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/src/kubo.ts CHANGED
@@ -1,23 +1,14 @@
1
1
  import { execFile, spawn } from "node:child_process";
2
2
  import { promisify } from "node:util";
3
- import {
4
- createHash,
5
- createPrivateKey,
6
- createPublicKey,
7
- sign,
8
- } from "node:crypto";
9
- import {
10
- chmod,
11
- lstat,
12
- open,
13
- readFile,
14
- rename,
15
- rm,
16
- writeFile,
17
- } from "node:fs/promises";
3
+ import { createPrivateKey, createPublicKey, sign } from "node:crypto";
4
+ import { lstat, open, readFile, writeFile } from "node:fs/promises";
18
5
  import { join } from "node:path";
19
6
  import { createServer } from "node:net";
20
- import { networkInterfaces } from "node:os";
7
+ import {
8
+ advertisedIps,
9
+ BlockUnavailable,
10
+ readWithPeers,
11
+ } from "./kubo-peers.js";
21
12
  import { base58btc } from "multiformats/bases/base58";
22
13
  import { boundedText, uniqueId } from "@ipab/bundle/pointer/scope";
23
14
  import { protectedPath, protectedPaths, secureNew } from "./identity.js";
@@ -29,8 +20,16 @@ import {
29
20
  } from "./swarm-files.js";
30
21
  import { HostError, object } from "./errors.js";
31
22
  import { nodeError } from "./authoring.js";
23
+ import {
24
+ peerArguments,
25
+ persistPeers,
26
+ reconcilePeers,
27
+ type PeeringPeer,
28
+ } from "./kubo-peering.js";
32
29
 
33
- export const KUBO_VERSION = "0.43.2";
30
+ import { kuboBinary, withKuboProgram } from "./kubo-install.js";
31
+ export { kuboBinary };
32
+ export { KUBO_VERSION } from "./kubo-release.js";
34
33
  // Windows Firewall creates an inbound rule for every program that listens on a
35
34
  // non-loopback address, so each new managed binary location prompts for
36
35
  // authorization. Binding only 127.0.0.1 creates no rule at all, which keeps
@@ -41,12 +40,6 @@ function swarmAddress(listen: ListenMode, port: number): string {
41
40
  return `/ip4/${listen === "loopback" ? "127.0.0.1" : "0.0.0.0"}/tcp/${port}`;
42
41
  }
43
42
  const run = promisify(execFile);
44
- const hash = (data: Uint8Array) =>
45
- createHash("sha256").update(data).digest("hex");
46
- interface Installation {
47
- version: string;
48
- hash: string;
49
- }
50
43
  export interface NodeRecord {
51
44
  scope: string;
52
45
  peerId: string;
@@ -67,7 +60,7 @@ export interface KuboNode {
67
60
  auth: string;
68
61
  pid?: number;
69
62
  }
70
- function nodeRecord(value: unknown, scope: string): NodeRecord {
63
+ export function nodeRecord(value: unknown, scope: string): NodeRecord {
71
64
  const record = object(value, "protected managed-node record");
72
65
  const { peerId, api, gateway, swarm, auth, pid, epoch, listen } = record;
73
66
  if (
@@ -120,146 +113,6 @@ function nodeRecord(value: unknown, scope: string): NodeRecord {
120
113
  ...(listen !== undefined ? { listen } : {}),
121
114
  };
122
115
  }
123
- export async function kuboBinary(stateDir: string): Promise<string> {
124
- const directory = await privateDirectory(stateDir, "kubo-bin");
125
- return withPrivateLock(directory, async () => {
126
- const executable = join(
127
- directory,
128
- process.platform === "win32" ? "ipfs.exe" : "ipfs",
129
- );
130
- const installed = await readPrivate<Installation>(
131
- directory,
132
- "installation.json",
133
- [{ path: executable }],
134
- );
135
- if (installed) {
136
- if (
137
- installed.version !== KUBO_VERSION ||
138
- installed.hash !== hash(await readFile(executable))
139
- )
140
- throw new HostError(
141
- "Kubo installation integrity mismatch; do not use this binary.",
142
- );
143
- return executable;
144
- }
145
- const platforms: Partial<Record<NodeJS.Platform, string>> = {
146
- win32: "windows",
147
- darwin: "darwin",
148
- linux: "linux",
149
- };
150
- const platform = platforms[process.platform];
151
- if (!platform || !["x64", "arm64"].includes(process.arch))
152
- throw new HostError("Unsupported Kubo platform.");
153
- const arch = process.arch === "x64" ? "amd64" : "arm64";
154
- const filename = `kubo_v${KUBO_VERSION}_${platform}-${arch}.${platform === "windows" ? "zip" : "tar.gz"}`;
155
- // Official release metadata supplies the immutable archive digest; HTTPS is the trust boundary.
156
- const release = await fetch(
157
- `https://api.github.com/repos/ipfs/kubo/releases/tags/v${KUBO_VERSION}`,
158
- {
159
- redirect: "error",
160
- signal: AbortSignal.timeout(30_000),
161
- headers: { accept: "application/vnd.github+json" },
162
- },
163
- );
164
- if (!release.ok)
165
- throw new HostError(
166
- `Could not verify official Kubo release (HTTP ${release.status}).`,
167
- );
168
- const metadata = JSON.parse(await boundedText(release)) as {
169
- draft: boolean;
170
- prerelease: boolean;
171
- assets: { name: string; digest: string; browser_download_url: string }[];
172
- };
173
- const asset = metadata.assets.find((item) => item.name === filename);
174
- if (
175
- metadata.draft ||
176
- metadata.prerelease ||
177
- !asset ||
178
- !/^sha256:[a-f0-9]{64}$/.test(asset.digest) ||
179
- asset.browser_download_url !==
180
- `https://github.com/ipfs/kubo/releases/download/v${KUBO_VERSION}/${filename}`
181
- )
182
- throw new HostError("Official stable Kubo archive/digest unavailable.");
183
- const archive = join(
184
- directory,
185
- `${uniqueId()}.${platform === "windows" ? "zip" : "tar.gz"}`,
186
- );
187
- const stage = await privateDirectory(directory, `extract-${uniqueId()}`);
188
- try {
189
- const response = await fetch(asset.browser_download_url, {
190
- signal: AbortSignal.timeout(180_000),
191
- });
192
- if (!response.ok || !response.body)
193
- throw new HostError("Kubo download failed.");
194
- const handle = await open(archive, "wx", 0o600);
195
- let total = 0;
196
- const digest = createHash("sha256");
197
- try {
198
- await secureNew(archive);
199
- const stream: ReadableStream<Uint8Array> = response.body;
200
- for await (const chunk of stream) {
201
- total += chunk.length;
202
- if (total > 150 * 1024 * 1024)
203
- throw new HostError("Kubo archive exceeds limit.");
204
- digest.update(chunk);
205
- await handle.write(chunk);
206
- }
207
- await handle.sync();
208
- } finally {
209
- await handle.close();
210
- }
211
- if (`sha256:${digest.digest("hex")}` !== asset.digest)
212
- throw new HostError("Kubo archive checksum mismatch.");
213
- const listing = await run("tar", ["-tf", archive], {
214
- timeout: 30_000,
215
- maxBuffer: 1024 * 1024,
216
- windowsHide: true,
217
- });
218
- if (
219
- listing.stdout
220
- .split(/\r?\n/)
221
- .filter(Boolean)
222
- .some(
223
- (path) =>
224
- !/^kubo\/[A-Za-z0-9._/-]+$/.test(path) ||
225
- path.split("/").includes(".."),
226
- )
227
- )
228
- throw new HostError("Unsafe Kubo archive layout.");
229
- await run("tar", ["-xf", archive, "-C", stage], {
230
- timeout: 30_000,
231
- windowsHide: true,
232
- });
233
- const extracted = join(
234
- stage,
235
- "kubo",
236
- process.platform === "win32" ? "ipfs.exe" : "ipfs",
237
- );
238
- if (
239
- !(await lstat(extracted)).isFile() ||
240
- (await lstat(extracted)).isSymbolicLink()
241
- )
242
- throw new HostError("Invalid Kubo executable.");
243
- await secureNew(extracted);
244
- if (process.platform !== "win32") await chmod(extracted, 0o700);
245
- const version = await run(extracted, ["version", "--number"], {
246
- timeout: 10_000,
247
- windowsHide: true,
248
- });
249
- if (version.stdout.trim() !== KUBO_VERSION)
250
- throw new HostError("Kubo executable version mismatch.");
251
- await rename(extracted, executable);
252
- await writePrivate(directory, "installation.json", {
253
- version: KUBO_VERSION,
254
- hash: hash(await readFile(executable)),
255
- });
256
- return executable;
257
- } finally {
258
- await rm(stage, { recursive: true, force: true });
259
- await rm(archive, { force: true });
260
- }
261
- });
262
- }
263
116
  async function freePort(): Promise<number> {
264
117
  const server = createServer();
265
118
  return new Promise((resolve, reject) => {
@@ -285,14 +138,35 @@ export async function prepareNode(
285
138
  ): Promise<KuboNode> {
286
139
  if (!/^[a-f0-9]{64}$/.test(scope))
287
140
  throw new HostError("Invalid service-bound local Scope identity.");
288
- const binary = await kuboBinary(stateDir);
289
- return prepareWithBinary(stateDir, scope, binary, listen);
141
+ return withKuboProgram(stateDir, (binary) =>
142
+ prepareWithBinary(stateDir, scope, binary, listen),
143
+ );
144
+ }
145
+ export async function checkCachedNode(
146
+ stateDir: string,
147
+ scope: string,
148
+ epoch: number,
149
+ peer: string,
150
+ ) {
151
+ if (!/^[a-f0-9]{64}$/.test(scope))
152
+ throw new HostError("Invalid service-bound local Scope identity.");
153
+ const saved = await readPrivate<unknown>(
154
+ join(stateDir, "swarm-nodes", scope),
155
+ "node.json",
156
+ );
157
+ if (saved === undefined) return;
158
+ const node = nodeRecord(saved, scope);
159
+ if (node.peerId !== peer || (node.epoch !== undefined && node.epoch > epoch))
160
+ throw new HostError(
161
+ "Cached membership does not match the recorded node identity or epoch; retry with --force.",
162
+ );
290
163
  }
291
164
  async function prepareWithBinary(
292
165
  stateDir: string,
293
166
  scope: string,
294
167
  binary: string,
295
168
  listen: ListenMode,
169
+ signal?: AbortSignal,
296
170
  ): Promise<KuboNode> {
297
171
  const parent = join(stateDir, "swarm-nodes");
298
172
  const directory = join(parent, scope);
@@ -307,7 +181,7 @@ async function prepareWithBinary(
307
181
  await privateDirectory(parent, scope);
308
182
  await privateDirectory(directory, "repo");
309
183
  }
310
- return withPrivateLock(directory, async () => {
184
+ const prepare = async () => {
311
185
  let record = await readPrivate<NodeRecord>(directory, "node.json", [
312
186
  { path: join(repo, "config") },
313
187
  ]);
@@ -327,6 +201,7 @@ async function prepareWithBinary(
327
201
  if (!nodeError(cause, "ENOENT")) throw cause;
328
202
  await run(binary, ["init", "--profile=server"], {
329
203
  env,
204
+ signal,
330
205
  timeout: 30_000,
331
206
  windowsHide: true,
332
207
  });
@@ -404,21 +279,6 @@ async function prepareWithBinary(
404
279
  throw new HostError(
405
280
  "Managed node already listens in a different mode; existing repos are not rebound.",
406
281
  );
407
- const local = Object.values(networkInterfaces())
408
- .flatMap((items) => items ?? [])
409
- .filter(
410
- (item) =>
411
- item.family === "IPv4" &&
412
- /^(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(
413
- item.address,
414
- ),
415
- )
416
- .map((item) => item.address)
417
- .slice(0, 15);
418
- // A loopback-only listener is reachable exclusively from this device, so it
419
- // advertises just loopback; a LAN listener advertises its private IPv4 IPs.
420
- const reachable =
421
- record.listen === "loopback" ? ["127.0.0.1"] : [...local, "127.0.0.1"];
422
282
  return {
423
283
  repo,
424
284
  peerId: record.peerId,
@@ -426,11 +286,12 @@ async function prepareWithBinary(
426
286
  gateway: `http://127.0.0.1:${record.gateway}`,
427
287
  auth: record.auth,
428
288
  ...(record.pid !== undefined ? { pid: record.pid } : {}),
429
- addresses: [...new Set(reachable)].map(
289
+ addresses: advertisedIps(record.listen).map(
430
290
  (ip) => `/ip4/${ip}/tcp/${record.swarm}/p2p/${record.peerId}`,
431
291
  ),
432
292
  };
433
- });
293
+ };
294
+ return withPrivateLock(directory, prepare, signal);
434
295
  }
435
296
  export async function peerProof(
436
297
  node: KuboNode,
@@ -491,9 +352,9 @@ async function rpc(
491
352
  : AbortSignal.timeout(timeout),
492
353
  });
493
354
  }
494
- async function ready(node: KuboNode): Promise<boolean> {
355
+ async function ready(node: KuboNode, signal?: AbortSignal): Promise<boolean> {
495
356
  try {
496
- const response = await rpc(node, "id");
357
+ const response = await rpc(node, "id", signal);
497
358
  if (response.status === 401 || response.status === 403) {
498
359
  await response.body?.cancel();
499
360
  throw new HostError(
@@ -511,6 +372,7 @@ async function ready(node: KuboNode): Promise<boolean> {
511
372
  );
512
373
  return true;
513
374
  } catch (cause) {
375
+ signal?.throwIfAborted();
514
376
  if (cause instanceof HostError) throw cause;
515
377
  return false;
516
378
  }
@@ -539,135 +401,154 @@ export async function startNode(
539
401
  scope: string,
540
402
  key: string,
541
403
  epoch: number,
542
- addresses: readonly string[],
543
- diagnostic?: (text: string) => void,
544
404
  listen: ListenMode = "lan",
405
+ membership?: {
406
+ self: string;
407
+ peers: readonly PeeringPeer[];
408
+ signal?: AbortSignal;
409
+ },
545
410
  ): Promise<KuboNode> {
546
411
  if (!/^[a-f0-9]{64}$/.test(scope))
547
412
  throw new HostError("Invalid service-bound local Scope identity.");
548
413
  if (!/^[a-f0-9]{64}$/.test(key)) throw new HostError("Invalid Swarm key.");
549
- const binary = await kuboBinary(stateDir);
550
- const node = await prepareWithBinary(stateDir, scope, binary, listen);
551
- const directory = join(stateDir, "swarm-nodes", scope);
552
- return withPrivateLock(directory, async () => {
553
- const record = (await readPrivate<NodeRecord>(directory, "node.json"))!;
554
- if (record.epoch !== undefined && record.epoch !== epoch)
555
- await stopNode(node);
556
- const keyPath = join(node.repo, "swarm.key");
557
- if (record.epoch === epoch) {
558
- await protectedPath(keyPath);
559
- if (
560
- (await readFile(keyPath, "utf8")) !==
561
- `/key/swarm/psk/1.0.0/\n/base16/\n${key}\n`
562
- )
563
- throw new HostError("Swarm key file does not match approved epoch.");
564
- } else {
565
- await writeFile(keyPath, `/key/swarm/psk/1.0.0/\n/base16/\n${key}\n`, {
566
- mode: 0o600,
567
- });
568
- await secureNew(keyPath);
569
- }
570
- if (!(await ready(node))) {
571
- const logfile = join(directory, "daemon.log");
572
- const log = await open(logfile, "a", 0o600);
573
- await secureNew(logfile);
574
- const child = spawn(
414
+ const signal = membership?.signal;
415
+ signal?.throwIfAborted();
416
+ return withKuboProgram(
417
+ stateDir,
418
+ async (binary) => {
419
+ signal?.throwIfAborted();
420
+ const node = await prepareWithBinary(
421
+ stateDir,
422
+ scope,
575
423
  binary,
576
- ["daemon", "--enable-gc=false", "--migrate=false"],
577
- {
578
- env: { ...process.env, IPFS_PATH: node.repo, LIBP2P_FORCE_PNET: "1" },
579
- detached: true,
580
- windowsHide: true,
581
- stdio: ["ignore", log.fd, log.fd],
582
- },
424
+ listen,
425
+ signal,
583
426
  );
584
- let failure: Error | undefined;
585
- child.once("error", (error) => {
586
- failure = error;
587
- });
588
- const closed = new Promise<void>((resolve) => {
589
- child.once("close", () => {
590
- resolve();
591
- });
592
- });
593
- child.unref();
594
- await log.close();
595
- try {
596
- if (child.pid !== undefined) {
597
- record.pid = child.pid;
598
- node.pid = child.pid;
599
- record.epoch = epoch;
600
- await writePrivate(directory, "node.json", record);
427
+ if (membership && node.peerId !== membership.self)
428
+ throw new HostError(
429
+ "Approved PeerID differs from this local Request's Kubo identity.",
430
+ );
431
+ const directory = join(stateDir, "swarm-nodes", scope);
432
+ const start = async () => {
433
+ signal?.throwIfAborted();
434
+ const record = (await readPrivate<NodeRecord>(directory, "node.json"))!;
435
+ if (record.epoch !== undefined && record.epoch > epoch)
436
+ throw new HostError(
437
+ "Refusing to restore an older Swarm epoch; refresh membership.",
438
+ );
439
+ if (record.epoch !== undefined && record.epoch !== epoch)
440
+ await stopNode(node);
441
+ const online = await ready(node, signal);
442
+ if (!online && record.pid !== undefined) {
443
+ try {
444
+ process.kill(record.pid, 0);
445
+ throw new HostError(
446
+ "Owned node process is still running but not ready; retry before changing its configuration.",
447
+ );
448
+ } catch (cause) {
449
+ if (!nodeError(cause, "ESRCH")) throw cause;
450
+ }
601
451
  }
602
- for (let i = 0; ; i++) {
603
- if (failure) throw failure;
604
- if (await ready(node)) break;
605
- if (i >= 150 || child.exitCode !== null)
452
+ const call = (command: string, budget: AbortSignal) =>
453
+ rpc(
454
+ node,
455
+ command,
456
+ signal ? AbortSignal.any([signal, budget]) : budget,
457
+ );
458
+ const desired = membership?.peers ?? [];
459
+ const keyPath = join(node.repo, "swarm.key");
460
+ if (record.epoch === epoch) {
461
+ await protectedPath(keyPath);
462
+ if (
463
+ (await readFile(keyPath, "utf8")) !==
464
+ `/key/swarm/psk/1.0.0/\n/base16/\n${key}\n`
465
+ )
606
466
  throw new HostError(
607
- "Owned Kubo startup failed; inspect protected daemon.log.",
467
+ "Swarm key file does not match approved epoch.",
608
468
  );
609
- await new Promise((resolve) => setTimeout(resolve, 100));
469
+ } else {
470
+ await persistPeers(node.repo, desired, online ? call : undefined);
471
+ await writeFile(
472
+ keyPath,
473
+ `/key/swarm/psk/1.0.0/\n/base16/\n${key}\n`,
474
+ {
475
+ mode: 0o600,
476
+ },
477
+ );
478
+ await secureNew(keyPath);
610
479
  }
611
- } catch (cause) {
612
- child.kill();
613
- await Promise.race([
614
- closed,
615
- new Promise<void>((resolve) => setTimeout(resolve, 5000)),
616
- ]);
617
- if (child.exitCode === null && child.signalCode === null)
618
- child.kill("SIGKILL");
619
- await closed;
620
- throw cause;
621
- }
622
- }
623
- record.epoch = epoch;
624
- await writePrivate(directory, "node.json", record);
625
- const groups = new Map<string, string[]>();
626
- for (const address of addresses) {
627
- validateAddress(address);
628
- const target = address.split("/").at(-1)!;
629
- if (target === node.peerId) continue;
630
- const group = groups.get(target) ?? [];
631
- if (group.length < 16 && !group.includes(address)) group.push(address);
632
- groups.set(target, group);
633
- }
634
- const budget = AbortSignal.timeout(10_000);
635
- await Promise.all(
636
- [...groups.values()].map(async (group) => {
637
- const connected = new AbortController();
638
- await Promise.all(
639
- group.map(async (address) => {
640
- try {
641
- const response = await rpc(
642
- node,
643
- `swarm/connect?arg=${encodeURIComponent(address)}`,
644
- AbortSignal.any([budget, connected.signal]),
645
- );
646
- const ok = response.ok;
647
- if (!ok) {
648
- const reason = JSON.parse(await boundedText(response)) as {
649
- Message?: string;
650
- };
651
- diagnostic?.(
652
- `Swarm peer dial failed at ${address}: ${reason.Message?.slice(0, 512) ?? `HTTP ${response.status}`}`,
653
- );
654
- }
655
- await response.body?.cancel();
656
- if (ok) connected.abort();
657
- } catch (cause) {
658
- if (!connected.signal.aborted)
659
- diagnostic?.(
660
- `Swarm peer dial unavailable at ${address}: ${cause instanceof Error ? cause.message : "network error"}`,
480
+ if (record.epoch === epoch)
481
+ await persistPeers(node.repo, desired, online ? call : undefined);
482
+ if (!online) {
483
+ signal?.throwIfAborted();
484
+ const logfile = join(directory, "daemon.log");
485
+ const log = await open(logfile, "a", 0o600);
486
+ await secureNew(logfile);
487
+ const child = spawn(
488
+ binary,
489
+ ["daemon", "--enable-gc=false", "--migrate=false"],
490
+ {
491
+ env: {
492
+ ...process.env,
493
+ IPFS_PATH: node.repo,
494
+ LIBP2P_FORCE_PNET: "1",
495
+ },
496
+ detached: true,
497
+ windowsHide: true,
498
+ stdio: ["ignore", log.fd, log.fd],
499
+ },
500
+ );
501
+ let failure: Error | undefined;
502
+ child.once("error", (error) => {
503
+ failure = error;
504
+ });
505
+ const closed = new Promise<void>((resolve) => {
506
+ child.once("close", () => {
507
+ resolve();
508
+ });
509
+ });
510
+ child.unref();
511
+ await log.close();
512
+ try {
513
+ if (child.pid !== undefined) {
514
+ record.pid = child.pid;
515
+ node.pid = child.pid;
516
+ record.epoch = epoch;
517
+ await writePrivate(directory, "node.json", record);
518
+ }
519
+ for (let i = 0; ; i++) {
520
+ signal?.throwIfAborted();
521
+ if (failure) throw failure;
522
+ if (await ready(node, signal)) break;
523
+ if (i >= 150 || child.exitCode !== null)
524
+ throw new HostError(
525
+ "Owned Kubo startup failed; inspect protected daemon.log.",
661
526
  );
662
- // An offline address must not hide a reachable address of the same PeerID.
663
- // Content reads still report actual network failure, not authorization failure.
527
+ await new Promise((resolve) => setTimeout(resolve, 100));
664
528
  }
665
- }),
666
- );
667
- }),
668
- );
669
- return node;
670
- });
529
+ } catch (cause) {
530
+ child.kill();
531
+ await Promise.race([
532
+ closed,
533
+ new Promise<void>((resolve) => setTimeout(resolve, 5000)),
534
+ ]);
535
+ if (child.exitCode === null && child.signalCode === null)
536
+ child.kill("SIGKILL");
537
+ await closed;
538
+ throw cause;
539
+ }
540
+ }
541
+ if (record.epoch !== epoch) {
542
+ record.epoch = epoch;
543
+ await writePrivate(directory, "node.json", record);
544
+ }
545
+ await reconcilePeers(call, desired);
546
+ return node;
547
+ };
548
+ return withPrivateLock(directory, start, signal);
549
+ },
550
+ signal,
551
+ );
671
552
  }
672
553
  export function validateAddress(address: string, expectedPeer?: string): void {
673
554
  const match =
@@ -684,48 +565,133 @@ export function validateAddress(address: string, expectedPeer?: string): void {
684
565
  "LAN/VPN profile requires IPv4 TCP multiaddr bound to its PeerID.",
685
566
  );
686
567
  }
687
- export function kuboSource(node: KuboNode) {
568
+ export function kuboSource(
569
+ node: KuboNode,
570
+ addresses: readonly string[] = [],
571
+ diagnostic?: (line: string) => void,
572
+ detailed = false,
573
+ ) {
574
+ const groups = new Map<string, string[]>();
575
+ for (const address of new Set(addresses)) {
576
+ validateAddress(address);
577
+ const target = address.split("/").at(-1)!;
578
+ if (target === node.peerId) continue;
579
+ const group = groups.get(target) ?? [];
580
+ if (group.length < 16)
581
+ group.push(address.slice(0, -`/p2p/${target}`.length));
582
+ groups.set(target, group);
583
+ }
584
+ let fallbackUsed = false;
585
+ const connected = async (signal: AbortSignal) => {
586
+ const response = await rpc(node, "swarm/peers", signal);
587
+ if (!response.ok) {
588
+ await response.body?.cancel();
589
+ throw new HostError(`HTTP ${response.status}`);
590
+ }
591
+ const data = object(
592
+ JSON.parse(await boundedText(response)) as unknown,
593
+ "owned Kubo connections",
594
+ );
595
+ if (data.Peers === null) return new Set<string>();
596
+ if (!Array.isArray(data.Peers))
597
+ throw new HostError("Invalid owned Kubo connections.");
598
+ return new Set(
599
+ data.Peers.map((entry: unknown) => {
600
+ const { Peer } = object(entry, "owned Kubo connection");
601
+ if (typeof Peer !== "string")
602
+ throw new HostError("Invalid owned Kubo connection.");
603
+ return Peer;
604
+ }),
605
+ );
606
+ };
607
+ const connect = async (
608
+ id: string,
609
+ addrs: readonly string[],
610
+ signal: AbortSignal,
611
+ ) => {
612
+ const response = await rpc(
613
+ node,
614
+ `swarm/connect?${peerArguments(id, addrs)}`,
615
+ signal,
616
+ );
617
+ try {
618
+ if (!response.ok) throw new HostError(`HTTP ${response.status}`);
619
+ // swarm/connect may stream the result. Do not treat headers alone as success.
620
+ await boundedText(response);
621
+ } finally {
622
+ await response.body?.cancel();
623
+ }
624
+ };
688
625
  return {
689
626
  block: {
690
627
  async get(
691
628
  cid: string,
692
629
  options: { signal?: AbortSignal } = {},
693
630
  ): Promise<Uint8Array> {
694
- const response = await rpc(
695
- node,
696
- `block/get?arg=${encodeURIComponent(cid)}`,
631
+ return readWithPeers(
632
+ groups,
633
+ async (signal, offline) => {
634
+ const response = await rpc(
635
+ node,
636
+ `block/get?arg=${encodeURIComponent(cid)}${offline ? "&offline=true" : ""}`,
637
+ signal,
638
+ 30_000,
639
+ );
640
+ if (!response.ok || !response.body) {
641
+ const error = `Swarm block unavailable (HTTP ${response.status}).`;
642
+ if (offline && [404, 500].includes(response.status)) {
643
+ const detail = object(
644
+ JSON.parse(await boundedText(response)) as unknown,
645
+ "owned Kubo block error",
646
+ ).Message;
647
+ if (
648
+ typeof detail === "string" &&
649
+ detail.startsWith("block was not found locally (offline):")
650
+ )
651
+ throw new BlockUnavailable(error);
652
+ }
653
+ await response.body?.cancel();
654
+ if (!offline && [404, 500].includes(response.status))
655
+ throw new BlockUnavailable(error);
656
+ throw new HostError(error);
657
+ }
658
+ const stream: ReadableStream<Uint8Array> = response.body;
659
+ const reader = stream.getReader();
660
+ const chunks: Uint8Array[] = [];
661
+ let size = 0;
662
+ try {
663
+ for (;;) {
664
+ const part = await reader.read();
665
+ if (part.done) break;
666
+ size += part.value.length;
667
+ if (size > 2 * 1024 * 1024) {
668
+ await reader.cancel();
669
+ throw new HostError("Kubo block exceeds limit.");
670
+ }
671
+ chunks.push(part.value);
672
+ }
673
+ } finally {
674
+ reader.releaseLock();
675
+ }
676
+ const bytes = new Uint8Array(size);
677
+ let offset = 0;
678
+ for (const chunk of chunks) {
679
+ bytes.set(chunk, offset);
680
+ offset += chunk.length;
681
+ }
682
+ return bytes;
683
+ },
684
+ connected,
685
+ connect,
686
+ () => {
687
+ if (fallbackUsed) return false;
688
+ fallbackUsed = true;
689
+ return true;
690
+ },
697
691
  options.signal,
698
- 30_000,
692
+ diagnostic,
693
+ detailed,
699
694
  );
700
- if (!response.ok || !response.body)
701
- throw new HostError(
702
- `Swarm block unavailable (HTTP ${response.status}).`,
703
- );
704
- const stream: ReadableStream<Uint8Array> = response.body;
705
- const reader = stream.getReader();
706
- const chunks: Uint8Array[] = [];
707
- let size = 0;
708
- try {
709
- for (;;) {
710
- const part = await reader.read();
711
- if (part.done) break;
712
- size += part.value.length;
713
- if (size > 2 * 1024 * 1024) {
714
- await reader.cancel();
715
- throw new HostError("Kubo block exceeds limit.");
716
- }
717
- chunks.push(part.value);
718
- }
719
- } finally {
720
- reader.releaseLock();
721
- }
722
- const bytes = new Uint8Array(size);
723
- let offset = 0;
724
- for (const chunk of chunks) {
725
- bytes.set(chunk, offset);
726
- offset += chunk.length;
727
- }
728
- return bytes;
729
695
  },
730
696
  },
731
697
  };