@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
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 } 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;
@@ -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) => {
@@ -288,11 +141,31 @@ export async function prepareNode(
288
141
  const binary = await kuboBinary(stateDir);
289
142
  return prepareWithBinary(stateDir, scope, binary, listen);
290
143
  }
144
+ export async function checkCachedNode(
145
+ stateDir: string,
146
+ scope: string,
147
+ epoch: number,
148
+ peer: string,
149
+ ) {
150
+ if (!/^[a-f0-9]{64}$/.test(scope))
151
+ throw new HostError("Invalid service-bound local Scope identity.");
152
+ const saved = await readPrivate<unknown>(
153
+ join(stateDir, "swarm-nodes", scope),
154
+ "node.json",
155
+ );
156
+ if (saved === undefined) return;
157
+ const node = nodeRecord(saved, scope);
158
+ if (node.peerId !== peer || (node.epoch !== undefined && node.epoch > epoch))
159
+ throw new HostError(
160
+ "Cached membership does not match the recorded node identity or epoch; retry with --force.",
161
+ );
162
+ }
291
163
  async function prepareWithBinary(
292
164
  stateDir: string,
293
165
  scope: string,
294
166
  binary: string,
295
167
  listen: ListenMode,
168
+ signal?: AbortSignal,
296
169
  ): Promise<KuboNode> {
297
170
  const parent = join(stateDir, "swarm-nodes");
298
171
  const directory = join(parent, scope);
@@ -307,7 +180,7 @@ async function prepareWithBinary(
307
180
  await privateDirectory(parent, scope);
308
181
  await privateDirectory(directory, "repo");
309
182
  }
310
- return withPrivateLock(directory, async () => {
183
+ const prepare = async () => {
311
184
  let record = await readPrivate<NodeRecord>(directory, "node.json", [
312
185
  { path: join(repo, "config") },
313
186
  ]);
@@ -327,6 +200,7 @@ async function prepareWithBinary(
327
200
  if (!nodeError(cause, "ENOENT")) throw cause;
328
201
  await run(binary, ["init", "--profile=server"], {
329
202
  env,
203
+ signal,
330
204
  timeout: 30_000,
331
205
  windowsHide: true,
332
206
  });
@@ -404,21 +278,6 @@ async function prepareWithBinary(
404
278
  throw new HostError(
405
279
  "Managed node already listens in a different mode; existing repos are not rebound.",
406
280
  );
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
281
  return {
423
282
  repo,
424
283
  peerId: record.peerId,
@@ -426,11 +285,12 @@ async function prepareWithBinary(
426
285
  gateway: `http://127.0.0.1:${record.gateway}`,
427
286
  auth: record.auth,
428
287
  ...(record.pid !== undefined ? { pid: record.pid } : {}),
429
- addresses: [...new Set(reachable)].map(
288
+ addresses: advertisedIps(record.listen).map(
430
289
  (ip) => `/ip4/${ip}/tcp/${record.swarm}/p2p/${record.peerId}`,
431
290
  ),
432
291
  };
433
- });
292
+ };
293
+ return withPrivateLock(directory, prepare, signal);
434
294
  }
435
295
  export async function peerProof(
436
296
  node: KuboNode,
@@ -491,9 +351,9 @@ async function rpc(
491
351
  : AbortSignal.timeout(timeout),
492
352
  });
493
353
  }
494
- async function ready(node: KuboNode): Promise<boolean> {
354
+ async function ready(node: KuboNode, signal?: AbortSignal): Promise<boolean> {
495
355
  try {
496
- const response = await rpc(node, "id");
356
+ const response = await rpc(node, "id", signal);
497
357
  if (response.status === 401 || response.status === 403) {
498
358
  await response.body?.cancel();
499
359
  throw new HostError(
@@ -511,6 +371,7 @@ async function ready(node: KuboNode): Promise<boolean> {
511
371
  );
512
372
  return true;
513
373
  } catch (cause) {
374
+ signal?.throwIfAborted();
514
375
  if (cause instanceof HostError) throw cause;
515
376
  return false;
516
377
  }
@@ -539,20 +400,49 @@ export async function startNode(
539
400
  scope: string,
540
401
  key: string,
541
402
  epoch: number,
542
- addresses: readonly string[],
543
- diagnostic?: (text: string) => void,
544
403
  listen: ListenMode = "lan",
404
+ membership?: {
405
+ self: string;
406
+ peers: readonly PeeringPeer[];
407
+ signal?: AbortSignal;
408
+ },
545
409
  ): Promise<KuboNode> {
546
410
  if (!/^[a-f0-9]{64}$/.test(scope))
547
411
  throw new HostError("Invalid service-bound local Scope identity.");
548
412
  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);
413
+ const signal = membership?.signal;
414
+ signal?.throwIfAborted();
415
+ const binary = await kuboBinary(stateDir, signal ? { signal } : {});
416
+ signal?.throwIfAborted();
417
+ const node = await prepareWithBinary(stateDir, scope, binary, listen, signal);
418
+ if (membership && node.peerId !== membership.self)
419
+ throw new HostError(
420
+ "Approved PeerID differs from this local Request's Kubo identity.",
421
+ );
551
422
  const directory = join(stateDir, "swarm-nodes", scope);
552
- return withPrivateLock(directory, async () => {
423
+ const start = async () => {
424
+ signal?.throwIfAborted();
553
425
  const record = (await readPrivate<NodeRecord>(directory, "node.json"))!;
426
+ if (record.epoch !== undefined && record.epoch > epoch)
427
+ throw new HostError(
428
+ "Refusing to restore an older Swarm epoch; refresh membership.",
429
+ );
554
430
  if (record.epoch !== undefined && record.epoch !== epoch)
555
431
  await stopNode(node);
432
+ const online = await ready(node, signal);
433
+ if (!online && record.pid !== undefined) {
434
+ try {
435
+ process.kill(record.pid, 0);
436
+ throw new HostError(
437
+ "Owned node process is still running but not ready; retry before changing its configuration.",
438
+ );
439
+ } catch (cause) {
440
+ if (!nodeError(cause, "ESRCH")) throw cause;
441
+ }
442
+ }
443
+ const call = (command: string, budget: AbortSignal) =>
444
+ rpc(node, command, signal ? AbortSignal.any([signal, budget]) : budget);
445
+ const desired = membership?.peers ?? [];
556
446
  const keyPath = join(node.repo, "swarm.key");
557
447
  if (record.epoch === epoch) {
558
448
  await protectedPath(keyPath);
@@ -562,12 +452,16 @@ export async function startNode(
562
452
  )
563
453
  throw new HostError("Swarm key file does not match approved epoch.");
564
454
  } else {
455
+ await persistPeers(node.repo, desired, online ? call : undefined);
565
456
  await writeFile(keyPath, `/key/swarm/psk/1.0.0/\n/base16/\n${key}\n`, {
566
457
  mode: 0o600,
567
458
  });
568
459
  await secureNew(keyPath);
569
460
  }
570
- if (!(await ready(node))) {
461
+ if (record.epoch === epoch)
462
+ await persistPeers(node.repo, desired, online ? call : undefined);
463
+ if (!online) {
464
+ signal?.throwIfAborted();
571
465
  const logfile = join(directory, "daemon.log");
572
466
  const log = await open(logfile, "a", 0o600);
573
467
  await secureNew(logfile);
@@ -600,8 +494,9 @@ export async function startNode(
600
494
  await writePrivate(directory, "node.json", record);
601
495
  }
602
496
  for (let i = 0; ; i++) {
497
+ signal?.throwIfAborted();
603
498
  if (failure) throw failure;
604
- if (await ready(node)) break;
499
+ if (await ready(node, signal)) break;
605
500
  if (i >= 150 || child.exitCode !== null)
606
501
  throw new HostError(
607
502
  "Owned Kubo startup failed; inspect protected daemon.log.",
@@ -622,52 +517,10 @@ export async function startNode(
622
517
  }
623
518
  record.epoch = epoch;
624
519
  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"}`,
661
- );
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.
664
- }
665
- }),
666
- );
667
- }),
668
- );
520
+ await reconcilePeers(call, desired);
669
521
  return node;
670
- });
522
+ };
523
+ return withPrivateLock(directory, start, signal);
671
524
  }
672
525
  export function validateAddress(address: string, expectedPeer?: string): void {
673
526
  const match =
@@ -684,48 +537,133 @@ export function validateAddress(address: string, expectedPeer?: string): void {
684
537
  "LAN/VPN profile requires IPv4 TCP multiaddr bound to its PeerID.",
685
538
  );
686
539
  }
687
- export function kuboSource(node: KuboNode) {
540
+ export function kuboSource(
541
+ node: KuboNode,
542
+ addresses: readonly string[] = [],
543
+ diagnostic?: (line: string) => void,
544
+ detailed = false,
545
+ ) {
546
+ const groups = new Map<string, string[]>();
547
+ for (const address of new Set(addresses)) {
548
+ validateAddress(address);
549
+ const target = address.split("/").at(-1)!;
550
+ if (target === node.peerId) continue;
551
+ const group = groups.get(target) ?? [];
552
+ if (group.length < 16)
553
+ group.push(address.slice(0, -`/p2p/${target}`.length));
554
+ groups.set(target, group);
555
+ }
556
+ let fallbackUsed = false;
557
+ const connected = async (signal: AbortSignal) => {
558
+ const response = await rpc(node, "swarm/peers", signal);
559
+ if (!response.ok) {
560
+ await response.body?.cancel();
561
+ throw new HostError(`HTTP ${response.status}`);
562
+ }
563
+ const data = object(
564
+ JSON.parse(await boundedText(response)) as unknown,
565
+ "owned Kubo connections",
566
+ );
567
+ if (data.Peers === null) return new Set<string>();
568
+ if (!Array.isArray(data.Peers))
569
+ throw new HostError("Invalid owned Kubo connections.");
570
+ return new Set(
571
+ data.Peers.map((entry: unknown) => {
572
+ const { Peer } = object(entry, "owned Kubo connection");
573
+ if (typeof Peer !== "string")
574
+ throw new HostError("Invalid owned Kubo connection.");
575
+ return Peer;
576
+ }),
577
+ );
578
+ };
579
+ const connect = async (
580
+ id: string,
581
+ addrs: readonly string[],
582
+ signal: AbortSignal,
583
+ ) => {
584
+ const response = await rpc(
585
+ node,
586
+ `swarm/connect?${peerArguments(id, addrs)}`,
587
+ signal,
588
+ );
589
+ try {
590
+ if (!response.ok) throw new HostError(`HTTP ${response.status}`);
591
+ // swarm/connect may stream the result. Do not treat headers alone as success.
592
+ await boundedText(response);
593
+ } finally {
594
+ await response.body?.cancel();
595
+ }
596
+ };
688
597
  return {
689
598
  block: {
690
599
  async get(
691
600
  cid: string,
692
601
  options: { signal?: AbortSignal } = {},
693
602
  ): Promise<Uint8Array> {
694
- const response = await rpc(
695
- node,
696
- `block/get?arg=${encodeURIComponent(cid)}`,
603
+ return readWithPeers(
604
+ groups,
605
+ async (signal, offline) => {
606
+ const response = await rpc(
607
+ node,
608
+ `block/get?arg=${encodeURIComponent(cid)}${offline ? "&offline=true" : ""}`,
609
+ signal,
610
+ 30_000,
611
+ );
612
+ if (!response.ok || !response.body) {
613
+ const error = `Swarm block unavailable (HTTP ${response.status}).`;
614
+ if (offline && [404, 500].includes(response.status)) {
615
+ const detail = object(
616
+ JSON.parse(await boundedText(response)) as unknown,
617
+ "owned Kubo block error",
618
+ ).Message;
619
+ if (
620
+ typeof detail === "string" &&
621
+ detail.startsWith("block was not found locally (offline):")
622
+ )
623
+ throw new BlockUnavailable(error);
624
+ }
625
+ await response.body?.cancel();
626
+ if (!offline && [404, 500].includes(response.status))
627
+ throw new BlockUnavailable(error);
628
+ throw new HostError(error);
629
+ }
630
+ const stream: ReadableStream<Uint8Array> = response.body;
631
+ const reader = stream.getReader();
632
+ const chunks: Uint8Array[] = [];
633
+ let size = 0;
634
+ try {
635
+ for (;;) {
636
+ const part = await reader.read();
637
+ if (part.done) break;
638
+ size += part.value.length;
639
+ if (size > 2 * 1024 * 1024) {
640
+ await reader.cancel();
641
+ throw new HostError("Kubo block exceeds limit.");
642
+ }
643
+ chunks.push(part.value);
644
+ }
645
+ } finally {
646
+ reader.releaseLock();
647
+ }
648
+ const bytes = new Uint8Array(size);
649
+ let offset = 0;
650
+ for (const chunk of chunks) {
651
+ bytes.set(chunk, offset);
652
+ offset += chunk.length;
653
+ }
654
+ return bytes;
655
+ },
656
+ connected,
657
+ connect,
658
+ () => {
659
+ if (fallbackUsed) return false;
660
+ fallbackUsed = true;
661
+ return true;
662
+ },
697
663
  options.signal,
698
- 30_000,
664
+ diagnostic,
665
+ detailed,
699
666
  );
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
667
  },
730
668
  },
731
669
  };
package/src/runtime.ts CHANGED
@@ -10,6 +10,8 @@ import { ContextServer } from "./ipc.js";
10
10
  import { loadApp, OutputSpace } from "./space.js";
11
11
  import type { RunRecord, State } from "./state.js";
12
12
  import { ExecutionLogs } from "./logs.js";
13
+ import { verifyStateStorage } from "./state-storage.js";
14
+ import type { BundleInspection } from "./context.js";
13
15
 
14
16
  export interface Invocation {
15
17
  origin: "exec" | "open";
@@ -23,6 +25,11 @@ export interface ExecutionOptions {
23
25
  log?: boolean;
24
26
  signal?: AbortSignal;
25
27
  inputSchema?: string;
28
+ resolveBundleReference?: (
29
+ reference: string,
30
+ signal: AbortSignal,
31
+ swarm?: string,
32
+ ) => Promise<Pick<BundleInspection, "cid" | "targetCid" | "swarm">>;
26
33
  }
27
34
 
28
35
  export async function execute(
@@ -114,7 +121,10 @@ export async function execute(
114
121
  "validation",
115
122
  );
116
123
  phase = "startup";
117
- await mkdir(directory, { recursive: true });
124
+ const runtime = join(state.directory, "runtime");
125
+ verifyStateStorage(state.directory);
126
+ await mkdir(runtime, { recursive: true, mode: 0o700 });
127
+ await mkdir(directory, { mode: 0o700 });
118
128
  directoryCreated = true;
119
129
  await writeFile(entry, app.source, { flag: "wx", mode: 0o600 });
120
130
  entryCreated = true;
@@ -162,6 +172,7 @@ export async function execute(
162
172
  },
163
173
  invocation.appCid,
164
174
  (name) => state.resolvePin(name),
175
+ options.resolveBundleReference,
165
176
  );
166
177
  const result = await new Promise<{
167
178
  code: number | null;