@ipab/cli 0.1.0-rc.11 → 0.1.0-rc.13

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 (151) hide show
  1. package/README.md +15 -10
  2. package/dist/authoring.d.ts +6 -2
  3. package/dist/authoring.d.ts.map +1 -1
  4. package/dist/authoring.js +65 -18
  5. package/dist/authoring.js.map +1 -1
  6. package/dist/builtins/skill.ipab.car +0 -0
  7. package/dist/cli-daemon.d.ts +14 -0
  8. package/dist/cli-daemon.d.ts.map +1 -0
  9. package/dist/cli-daemon.js +400 -0
  10. package/dist/cli-daemon.js.map +1 -0
  11. package/dist/cli.d.ts +2 -1
  12. package/dist/cli.d.ts.map +1 -1
  13. package/dist/cli.js +1631 -1100
  14. package/dist/cli.js.map +1 -1
  15. package/dist/config-secret.js +1 -1
  16. package/dist/config-secret.js.map +1 -1
  17. package/dist/daemon-api.d.ts +80 -0
  18. package/dist/daemon-api.d.ts.map +1 -0
  19. package/dist/daemon-api.js +2411 -0
  20. package/dist/daemon-api.js.map +1 -0
  21. package/dist/daemon-client.d.ts +322 -0
  22. package/dist/daemon-client.d.ts.map +1 -0
  23. package/dist/daemon-client.js +400 -0
  24. package/dist/daemon-client.js.map +1 -0
  25. package/dist/daemon-protocol.d.ts +22 -0
  26. package/dist/daemon-protocol.d.ts.map +1 -0
  27. package/dist/daemon-protocol.js +39 -0
  28. package/dist/daemon-protocol.js.map +1 -0
  29. package/dist/daemon-telemetry.d.ts +86 -0
  30. package/dist/daemon-telemetry.d.ts.map +1 -0
  31. package/dist/daemon-telemetry.js +502 -0
  32. package/dist/daemon-telemetry.js.map +1 -0
  33. package/dist/daemon-ui.d.ts +69 -0
  34. package/dist/daemon-ui.d.ts.map +1 -1
  35. package/dist/daemon-ui.js +285 -4
  36. package/dist/daemon-ui.js.map +1 -1
  37. package/dist/daemon.d.ts +10 -0
  38. package/dist/daemon.d.ts.map +1 -1
  39. package/dist/daemon.js +289 -38
  40. package/dist/daemon.js.map +1 -1
  41. package/dist/history.d.ts +3 -1
  42. package/dist/history.d.ts.map +1 -1
  43. package/dist/history.js +16 -1
  44. package/dist/history.js.map +1 -1
  45. package/dist/identity.d.ts.map +1 -1
  46. package/dist/identity.js +7 -2
  47. package/dist/identity.js.map +1 -1
  48. package/dist/ipc.d.ts +19 -7
  49. package/dist/ipc.d.ts.map +1 -1
  50. package/dist/ipc.js +96 -70
  51. package/dist/ipc.js.map +1 -1
  52. package/dist/kubo-topology.d.ts +2 -0
  53. package/dist/kubo-topology.d.ts.map +1 -1
  54. package/dist/kubo-topology.js +17 -20
  55. package/dist/kubo-topology.js.map +1 -1
  56. package/dist/kubo.d.ts +5 -3
  57. package/dist/kubo.d.ts.map +1 -1
  58. package/dist/kubo.js +83 -13
  59. package/dist/kubo.js.map +1 -1
  60. package/dist/name-reference.d.ts +8 -0
  61. package/dist/name-reference.d.ts.map +1 -0
  62. package/dist/name-reference.js +63 -0
  63. package/dist/name-reference.js.map +1 -0
  64. package/dist/pins.d.ts.map +1 -1
  65. package/dist/pins.js +18 -3
  66. package/dist/pins.js.map +1 -1
  67. package/dist/pivot-rpc.d.ts +37 -2
  68. package/dist/pivot-rpc.d.ts.map +1 -1
  69. package/dist/pivot-rpc.js +188 -8
  70. package/dist/pivot-rpc.js.map +1 -1
  71. package/dist/search-index.d.ts.map +1 -1
  72. package/dist/search-index.js +1 -0
  73. package/dist/search-index.js.map +1 -1
  74. package/dist/skill-definition.d.ts +9 -0
  75. package/dist/skill-definition.d.ts.map +1 -1
  76. package/dist/skill-definition.js +26 -2
  77. package/dist/skill-definition.js.map +1 -1
  78. package/dist/skill-source.d.ts +1 -0
  79. package/dist/skill-source.d.ts.map +1 -1
  80. package/dist/skill-source.js +10 -4
  81. package/dist/skill-source.js.map +1 -1
  82. package/dist/skills.d.ts +8 -2
  83. package/dist/skills.d.ts.map +1 -1
  84. package/dist/skills.js +31 -2
  85. package/dist/skills.js.map +1 -1
  86. package/dist/state-storage.d.ts.map +1 -1
  87. package/dist/state-storage.js +2 -1
  88. package/dist/state-storage.js.map +1 -1
  89. package/dist/state.d.ts +1 -1
  90. package/dist/state.d.ts.map +1 -1
  91. package/dist/state.js +3 -2
  92. package/dist/state.js.map +1 -1
  93. package/dist/swarm-files.d.ts.map +1 -1
  94. package/dist/swarm-files.js +7 -2
  95. package/dist/swarm-files.js.map +1 -1
  96. package/dist/swarm-fs-core.d.ts +217 -0
  97. package/dist/swarm-fs-core.d.ts.map +1 -0
  98. package/dist/swarm-fs-core.js +885 -0
  99. package/dist/swarm-fs-core.js.map +1 -0
  100. package/dist/swarm-fs-path.d.ts +17 -0
  101. package/dist/swarm-fs-path.d.ts.map +1 -0
  102. package/dist/swarm-fs-path.js +46 -0
  103. package/dist/swarm-fs-path.js.map +1 -0
  104. package/dist/swarm-fs.d.ts +9 -0
  105. package/dist/swarm-fs.d.ts.map +1 -0
  106. package/dist/swarm-fs.js +21 -0
  107. package/dist/swarm-fs.js.map +1 -0
  108. package/dist/swarm-observations.d.ts +6 -0
  109. package/dist/swarm-observations.d.ts.map +1 -1
  110. package/dist/swarm-observations.js +28 -8
  111. package/dist/swarm-observations.js.map +1 -1
  112. package/dist/swarm.d.ts +134 -18
  113. package/dist/swarm.d.ts.map +1 -1
  114. package/dist/swarm.js +1293 -484
  115. package/dist/swarm.js.map +1 -1
  116. package/dist/unixfs-tree.d.ts +55 -0
  117. package/dist/unixfs-tree.d.ts.map +1 -1
  118. package/dist/unixfs-tree.js +361 -2
  119. package/dist/unixfs-tree.js.map +1 -1
  120. package/package.json +5 -5
  121. package/src/authoring.ts +88 -28
  122. package/src/cli-daemon.ts +482 -0
  123. package/src/cli.ts +2080 -1464
  124. package/src/config-secret.ts +1 -1
  125. package/src/daemon-api.ts +3148 -0
  126. package/src/daemon-client.ts +975 -0
  127. package/src/daemon-protocol.ts +61 -0
  128. package/src/daemon-telemetry.ts +656 -0
  129. package/src/daemon-ui.ts +364 -4
  130. package/src/daemon.ts +337 -43
  131. package/src/history.ts +26 -1
  132. package/src/identity.ts +10 -2
  133. package/src/ipc.ts +113 -79
  134. package/src/kubo-topology.ts +25 -22
  135. package/src/kubo.ts +127 -9
  136. package/src/name-reference.ts +91 -0
  137. package/src/pins.ts +23 -3
  138. package/src/pivot-rpc.ts +272 -14
  139. package/src/search-index.ts +1 -0
  140. package/src/skill-definition.ts +45 -3
  141. package/src/skill-source.ts +10 -4
  142. package/src/skills.ts +43 -2
  143. package/src/state-storage.ts +5 -1
  144. package/src/state.ts +3 -1
  145. package/src/swarm-files.ts +10 -2
  146. package/src/swarm-fs-core.ts +1461 -0
  147. package/src/swarm-fs-path.ts +68 -0
  148. package/src/swarm-fs.ts +104 -0
  149. package/src/swarm-observations.ts +40 -14
  150. package/src/swarm.ts +2149 -1033
  151. package/src/unixfs-tree.ts +447 -2
package/src/ipc.ts CHANGED
@@ -67,21 +67,17 @@ interface WriteStream {
67
67
  writing: boolean;
68
68
  }
69
69
 
70
- export class ContextServer {
71
- private readonly requests = new Map<number, AbortController>();
70
+ export class ContextHandler {
72
71
  private readonly reads = new Map<number, ReadStream>();
73
72
  private readonly writes = new Map<number, WriteStream>();
74
- private readonly tasks = new Set<Promise<void>>();
75
73
  private readonly shallowRoots = new Set<string>();
76
74
  private openingReads = 0;
77
75
  private sequence = 0;
78
76
  private closed = false;
79
77
  constructor(
80
- readonly child: ChildProcess,
81
78
  readonly store: IpfsStore,
82
79
  readonly owner: Ownership,
83
80
  readonly output: OutputSpace,
84
- readonly fatal: (error: Error) => void,
85
81
  readonly appCid: string,
86
82
  readonly resolveBundleReference?: (
87
83
  reference: string,
@@ -89,74 +85,8 @@ export class ContextServer {
89
85
  swarm?: string,
90
86
  ) => Promise<Pick<BundleInspection, "cid" | "targetCid" | "swarm">>,
91
87
  readonly supportedTypes?: ReadonlySet<string>,
92
- ) {
93
- child.on("message", this.receive);
94
- }
95
- private reply(frame: Reply): void {
96
- if (this.child.connected)
97
- this.child.send(frame, (error) => {
98
- if (error && !this.closed) this.fatal(error);
99
- });
100
- }
101
- private receive = (frame: unknown): void => {
102
- if (!requestFrame(frame)) {
103
- this.fatal(new HostError("Invalid IPAB context frame."));
104
- return;
105
- }
106
- if (this.closed) {
107
- this.reply({
108
- version: 1,
109
- id: frame.id,
110
- error: "Context server is closed.",
111
- });
112
- return;
113
- }
114
- if (frame.operation === "cancel") {
115
- this.requests
116
- .get(Number(frame.args))
117
- ?.abort(new HostError("Context operation cancelled."));
118
- return;
119
- }
120
- if (this.requests.size >= 32 || this.requests.has(frame.id)) {
121
- this.fatal(
122
- new HostError("Context request capacity or identity violation."),
123
- );
124
- return;
125
- }
126
- const controller = new AbortController();
127
- this.requests.set(frame.id, controller);
128
- const task = this.handle(frame.operation, frame.args, controller.signal)
129
- .then(async (result) => {
130
- if (controller.signal.aborted) {
131
- if (frame.operation === "read")
132
- await this.cancelRead(Number(result), controller.signal.reason);
133
- if (
134
- ["link", "beginOpenSession", "cancelOpenSession"].includes(
135
- frame.operation,
136
- )
137
- )
138
- this.output.fail(controller.signal.reason);
139
- if (frame.operation === "submitBundleResult")
140
- this.output.discardBundleResult();
141
- controller.signal.throwIfAborted();
142
- }
143
- return result;
144
- })
145
- .then(
146
- (result) => {
147
- this.reply({ version: 1, id: frame.id, result });
148
- },
149
- (error: unknown) => {
150
- this.reply({ version: 1, id: frame.id, error: message(error) });
151
- },
152
- )
153
- .finally(() => {
154
- this.requests.delete(frame.id);
155
- this.tasks.delete(task);
156
- });
157
- this.tasks.add(task);
158
- };
159
- private async cancelRead(id: number, reason: unknown): Promise<void> {
88
+ ) {}
89
+ async cancelRead(id: number, reason: unknown): Promise<void> {
160
90
  const stream = this.reads.get(id);
161
91
  if (!stream) return;
162
92
  stream.controller.abort(reason);
@@ -166,11 +96,12 @@ export class ContextServer {
166
96
  this.reads.delete(id);
167
97
  }
168
98
  }
169
- private async handle(
99
+ async handle(
170
100
  operation: string,
171
101
  args: unknown,
172
102
  signal: AbortSignal,
173
103
  ): Promise<unknown> {
104
+ if (this.closed) throw new HostError("Context handler is closed.");
174
105
  signal.throwIfAborted();
175
106
  if (operation === "identity") return this.appCid;
176
107
  if (operation === "readBlock") {
@@ -483,11 +414,8 @@ export class ContextServer {
483
414
  }
484
415
  throw new HostError("Unknown context operation.");
485
416
  }
486
- async close(): Promise<void> {
417
+ async close(extraTasks: Iterable<Promise<void>> = []): Promise<void> {
487
418
  this.closed = true;
488
- this.child.off("message", this.receive);
489
- for (const request of this.requests.values())
490
- request.abort(new HostError("App finished."));
491
419
  for (const stream of this.writes.values()) {
492
420
  const error = new HostError(
493
421
  "App exited with unfinished output writes.",
@@ -501,7 +429,7 @@ export class ContextServer {
501
429
  for (const stream of this.reads.values())
502
430
  stream.controller.abort(new HostError("App finished."));
503
431
  await Promise.allSettled([
504
- ...this.tasks,
432
+ ...extraTasks,
505
433
  ...[...this.writes.values()].map((stream) => stream.task),
506
434
  ]);
507
435
  await Promise.all(
@@ -513,3 +441,109 @@ export class ContextServer {
513
441
  this.writes.clear();
514
442
  }
515
443
  }
444
+
445
+ export class ContextServer {
446
+ private readonly requests = new Map<number, AbortController>();
447
+ private readonly tasks = new Set<Promise<void>>();
448
+ private readonly handler: ContextHandler;
449
+ private closed = false;
450
+ constructor(
451
+ readonly child: ChildProcess,
452
+ readonly store: IpfsStore,
453
+ readonly owner: Ownership,
454
+ readonly output: OutputSpace,
455
+ readonly fatal: (error: Error) => void,
456
+ readonly appCid: string,
457
+ readonly resolveBundleReference?: (
458
+ reference: string,
459
+ signal: AbortSignal,
460
+ swarm?: string,
461
+ ) => Promise<Pick<BundleInspection, "cid" | "targetCid" | "swarm">>,
462
+ readonly supportedTypes?: ReadonlySet<string>,
463
+ ) {
464
+ this.handler = new ContextHandler(
465
+ store,
466
+ owner,
467
+ output,
468
+ appCid,
469
+ resolveBundleReference,
470
+ supportedTypes,
471
+ );
472
+ child.on("message", this.receive);
473
+ }
474
+ private reply(frame: Reply): void {
475
+ if (this.child.connected)
476
+ this.child.send(frame, (error) => {
477
+ if (error && !this.closed) this.fatal(error);
478
+ });
479
+ }
480
+ private receive = (frame: unknown): void => {
481
+ if (!requestFrame(frame)) {
482
+ this.fatal(new HostError("Invalid IPAB context frame."));
483
+ return;
484
+ }
485
+ if (this.closed) {
486
+ this.reply({
487
+ version: 1,
488
+ id: frame.id,
489
+ error: "Context server is closed.",
490
+ });
491
+ return;
492
+ }
493
+ if (frame.operation === "cancel") {
494
+ this.requests
495
+ .get(Number(frame.args))
496
+ ?.abort(new HostError("Context operation cancelled."));
497
+ return;
498
+ }
499
+ if (this.requests.size >= 32 || this.requests.has(frame.id)) {
500
+ this.fatal(
501
+ new HostError("Context request capacity or identity violation."),
502
+ );
503
+ return;
504
+ }
505
+ const controller = new AbortController();
506
+ this.requests.set(frame.id, controller);
507
+ const task = this.handler
508
+ .handle(frame.operation, frame.args, controller.signal)
509
+ .then(async (result) => {
510
+ if (controller.signal.aborted) {
511
+ if (frame.operation === "read")
512
+ await this.handler.cancelRead(
513
+ Number(result),
514
+ controller.signal.reason,
515
+ );
516
+ if (
517
+ ["link", "beginOpenSession", "cancelOpenSession"].includes(
518
+ frame.operation,
519
+ )
520
+ )
521
+ this.output.fail(controller.signal.reason);
522
+ if (frame.operation === "submitBundleResult")
523
+ this.output.discardBundleResult();
524
+ controller.signal.throwIfAborted();
525
+ }
526
+ return result;
527
+ })
528
+ .then(
529
+ (result) => {
530
+ this.reply({ version: 1, id: frame.id, result });
531
+ },
532
+ (error: unknown) => {
533
+ this.reply({ version: 1, id: frame.id, error: message(error) });
534
+ },
535
+ )
536
+ .finally(() => {
537
+ this.requests.delete(frame.id);
538
+ this.tasks.delete(task);
539
+ });
540
+ this.tasks.add(task);
541
+ };
542
+ async close(): Promise<void> {
543
+ this.closed = true;
544
+ this.child.off("message", this.receive);
545
+ for (const request of this.requests.values())
546
+ request.abort(new HostError("App finished."));
547
+ await this.handler.close(this.tasks);
548
+ }
549
+ }
@@ -1,6 +1,24 @@
1
1
  import { object } from "./errors.js";
2
2
  import type { PeeringPeer } from "./kubo-peering.js";
3
3
 
4
+ export function bootstrapAddresses(peers: readonly PeeringPeer[]): string[] {
5
+ return [
6
+ ...new Set(
7
+ peers.flatMap(({ ID, Addrs }) =>
8
+ Addrs.map((address) => `${address}/p2p/${ID}`),
9
+ ),
10
+ ),
11
+ ].sort();
12
+ }
13
+
14
+ export function withoutBootstrap(
15
+ config: Record<string, unknown>,
16
+ ): Record<string, unknown> {
17
+ const rest = { ...config };
18
+ delete rest.Bootstrap;
19
+ return rest;
20
+ }
21
+
4
22
  export function topologyConfig(
5
23
  config: Record<string, unknown>,
6
24
  pivot: boolean,
@@ -8,17 +26,10 @@ export function topologyConfig(
8
26
  loopback: boolean,
9
27
  ): Record<string, unknown> {
10
28
  const swarm = object(config.Swarm, "Kubo Swarm configuration");
11
- const addresses = peers
12
- .flatMap(({ ID, Addrs }) => Addrs.map((address) => `${address}/p2p/${ID}`))
13
- .sort();
14
29
  return {
15
30
  ...config,
16
- Bootstrap: addresses,
17
- Peering: {
18
- Peers: pivot
19
- ? peers.map(({ ID, Addrs }) => ({ ID, Addrs: [...Addrs] }))
20
- : [],
21
- },
31
+ Bootstrap: bootstrapAddresses(peers),
32
+ Peering: { Peers: [] },
22
33
  AutoConf: { Enabled: false },
23
34
  AutoTLS: { Enabled: false },
24
35
  AutoNAT: { ServiceMode: "disabled" },
@@ -33,8 +44,7 @@ export function topologyConfig(
33
44
  },
34
45
  Internal: {
35
46
  ...object(config.Internal ?? {}, "Kubo Internal configuration"),
36
- // Private swarms cannot use public AutoNAT to activate their hop service.
37
- // This is a role declaration, not a verified Internet reachability claim.
47
+ // Private swarms cannot use public AutoNAT; keep static role declaration.
38
48
  Libp2pForceReachability: pivot ? "public" : "private",
39
49
  NonPublicAddrPublishing: true,
40
50
  },
@@ -45,21 +55,14 @@ export function topologyConfig(
45
55
  Discovery: { MDNS: { Enabled: false } },
46
56
  Swarm: {
47
57
  ...swarm,
48
- EnableHolePunching: true,
58
+ EnableHolePunching: false,
49
59
  RelayClient: {
50
- Enabled: true,
51
- // libp2p counts static entries before grouping candidates by PeerID.
52
- // One entry per ID avoids a three-minute wait for duplicate candidates;
53
- // Bootstrap supplies the complete address set to the same peerstore.
54
- StaticRelays: peers
55
- .flatMap(({ ID, Addrs }) =>
56
- Addrs[0] ? [`${Addrs[0]}/p2p/${ID}`] : [],
57
- )
58
- .sort(),
60
+ Enabled: false,
61
+ StaticRelays: [],
59
62
  },
60
63
  RelayService: {
61
64
  ...object(swarm.RelayService ?? {}, "Kubo relay service"),
62
- Enabled: pivot,
65
+ Enabled: false,
63
66
  },
64
67
  },
65
68
  };
package/src/kubo.ts CHANGED
@@ -31,7 +31,11 @@ import {
31
31
  import { HostError, object } from "./errors.js";
32
32
  import { nodeError } from "./authoring.js";
33
33
  import { peerArguments, type PeeringPeer } from "./kubo-peering.js";
34
- import { topologyConfig } from "./kubo-topology.js";
34
+ import {
35
+ bootstrapAddresses,
36
+ topologyConfig,
37
+ withoutBootstrap,
38
+ } from "./kubo-topology.js";
35
39
 
36
40
  import { kuboBinary, withKuboProgram } from "./kubo-install.js";
37
41
  export { kuboBinary };
@@ -405,9 +409,13 @@ async function rpc(
405
409
  : AbortSignal.timeout(timeout),
406
410
  });
407
411
  }
408
- async function ready(node: KuboNode, signal?: AbortSignal): Promise<boolean> {
412
+ async function ready(
413
+ node: KuboNode,
414
+ signal?: AbortSignal,
415
+ fetcher: typeof fetch = fetch,
416
+ ): Promise<boolean> {
409
417
  try {
410
- const response = await rpc(node, "id", signal);
418
+ const response = await rpc(node, "id", signal, 5000, fetcher);
411
419
  if (response.status === 401 || response.status === 403) {
412
420
  await response.body?.cancel();
413
421
  throw new HostError(
@@ -430,6 +438,66 @@ async function ready(node: KuboNode, signal?: AbortSignal): Promise<boolean> {
430
438
  return false;
431
439
  }
432
440
  }
441
+ export async function nodeReady(
442
+ node: KuboNode,
443
+ signal?: AbortSignal,
444
+ fetcher: typeof fetch = fetch,
445
+ ): Promise<boolean> {
446
+ return ready(node, signal, fetcher);
447
+ }
448
+ function normalizeAddresses(value: unknown): string[] | null {
449
+ if (value === null || value === undefined) return [];
450
+ if (!Array.isArray(value)) return null;
451
+ const items = value as unknown[];
452
+ if (!items.every((item) => typeof item === "string")) return null;
453
+ return [...new Set(items)].sort();
454
+ }
455
+ async function reconcileBootstrap(
456
+ node: KuboNode,
457
+ desired: readonly string[],
458
+ signal?: AbortSignal,
459
+ ): Promise<void> {
460
+ const listResponse = await rpc(node, "bootstrap/list", signal, 5_000);
461
+ if (!listResponse.ok) {
462
+ await listResponse.body?.cancel();
463
+ throw new HostError(
464
+ `Owned Kubo bootstrap reconciliation failed (HTTP ${listResponse.status}); retry Swarm activation.`,
465
+ );
466
+ }
467
+ const listed = object(
468
+ JSON.parse(await boundedText(listResponse)) as unknown,
469
+ "owned Kubo bootstrap response",
470
+ );
471
+ const actual = normalizeAddresses(listed.Peers);
472
+ if (actual === null)
473
+ throw new HostError("Invalid owned Kubo bootstrap response.");
474
+ const actualSet = new Set(actual);
475
+ const desiredSet = new Set(desired);
476
+ const toRemove = actual.filter((address) => !desiredSet.has(address));
477
+ const toAdd = desired.filter((address) => !actualSet.has(address));
478
+ if (toRemove.length) {
479
+ const query = toRemove
480
+ .map((address) => `arg=${encodeURIComponent(address)}`)
481
+ .join("&");
482
+ const response = await rpc(node, `bootstrap/rm?${query}`, signal, 5_000);
483
+ await response.body?.cancel();
484
+ if (!response.ok)
485
+ throw new HostError(
486
+ `Owned Kubo bootstrap reconciliation failed (HTTP ${response.status}); retry Swarm activation.`,
487
+ );
488
+ }
489
+ if (toAdd.length) {
490
+ const query = toAdd
491
+ .map((address) => `arg=${encodeURIComponent(address)}`)
492
+ .join("&");
493
+ const response = await rpc(node, `bootstrap/add?${query}`, signal, 5_000);
494
+ await response.body?.cancel();
495
+ if (!response.ok)
496
+ throw new HostError(
497
+ `Owned Kubo bootstrap reconciliation failed (HTTP ${response.status}); retry Swarm activation.`,
498
+ );
499
+ }
500
+ }
433
501
  export async function stopNode(node: KuboNode): Promise<void> {
434
502
  if (!(await ready(node))) return;
435
503
  await (await rpc(node, "shutdown")).body?.cancel();
@@ -526,13 +594,29 @@ export async function startNode(
526
594
  desired,
527
595
  listen === "loopback",
528
596
  );
529
- if (!isDeepStrictEqual(config, nextConfig)) {
597
+ const staticChanged = !isDeepStrictEqual(
598
+ withoutBootstrap(config),
599
+ withoutBootstrap(nextConfig),
600
+ );
601
+ const desiredBootstrap = bootstrapAddresses(desired);
602
+ const currentBootstrap = normalizeAddresses(config.Bootstrap);
603
+ const bootstrapChanged =
604
+ currentBootstrap === null ||
605
+ !isDeepStrictEqual(currentBootstrap, desiredBootstrap);
606
+ if (staticChanged) {
530
607
  await invalidateTopology();
531
608
  if (online) {
532
609
  await stopNode(node);
533
610
  online = false;
534
611
  }
535
612
  await writePrivate(node.repo, "config", nextConfig);
613
+ } else if (bootstrapChanged) {
614
+ await invalidateTopology();
615
+ if (online) {
616
+ await reconcileBootstrap(node, desiredBootstrap, signal);
617
+ } else {
618
+ await writePrivate(node.repo, "config", nextConfig);
619
+ }
536
620
  }
537
621
  const keyPath = join(node.repo, "swarm.key");
538
622
  if (record.epoch === epoch) {
@@ -862,8 +946,9 @@ export interface KuboP2pListener {
862
946
  export async function p2pList(
863
947
  node: KuboNode,
864
948
  signal?: AbortSignal,
949
+ fetcher: typeof fetch = fetch,
865
950
  ): Promise<KuboP2pListener[]> {
866
- const response = await rpc(node, "p2p/ls", signal, 10_000);
951
+ const response = await rpc(node, "p2p/ls", signal, 10_000, fetcher);
867
952
  if (!response.ok) {
868
953
  await response.body?.cancel();
869
954
  throw new HostError(`Owned Kubo p2p/ls failed (HTTP ${response.status}).`);
@@ -899,6 +984,7 @@ export async function p2pClose(
899
984
  targetAddress?: string;
900
985
  },
901
986
  signal?: AbortSignal,
987
+ fetcher: typeof fetch = fetch,
902
988
  ): Promise<void> {
903
989
  const query = new URLSearchParams();
904
990
  if (options.protocol !== undefined) query.set("protocol", options.protocol);
@@ -912,6 +998,7 @@ export async function p2pClose(
912
998
  qs ? `p2p/close?${qs}` : "p2p/close",
913
999
  signal,
914
1000
  10_000,
1001
+ fetcher,
915
1002
  );
916
1003
  if (!response.ok) {
917
1004
  await response.body?.cancel();
@@ -927,23 +1014,30 @@ export async function p2pListen(
927
1014
  protocol: string,
928
1015
  targetAddress: string,
929
1016
  signal?: AbortSignal,
930
- ): Promise<void> {
1017
+ fetcher: typeof fetch = fetch,
1018
+ ): Promise<boolean> {
931
1019
  const selfListen = `/p2p/${node.peerId}`;
932
- const existing = await p2pList(node, signal);
1020
+ const existing = await p2pList(node, signal, fetcher);
933
1021
  const matching = existing.filter(
934
1022
  (entry) =>
935
1023
  entry.protocol === protocol && entry.listenAddress === selfListen,
936
1024
  );
937
1025
  if (matching.length === 1 && matching[0]!.targetAddress === targetAddress)
938
- return;
1026
+ return false;
939
1027
  if (matching.length > 0) {
940
- await p2pClose(node, { protocol, listenAddress: selfListen }, signal);
1028
+ await p2pClose(
1029
+ node,
1030
+ { protocol, listenAddress: selfListen },
1031
+ signal,
1032
+ fetcher,
1033
+ );
941
1034
  }
942
1035
  const response = await rpc(
943
1036
  node,
944
1037
  `p2p/listen?arg=${encodeURIComponent(protocol)}&arg=${encodeURIComponent(targetAddress)}`,
945
1038
  signal,
946
1039
  10_000,
1040
+ fetcher,
947
1041
  );
948
1042
  if (!response.ok) {
949
1043
  const detail = await boundedText(response).catch(() => "");
@@ -952,6 +1046,7 @@ export async function p2pListen(
952
1046
  );
953
1047
  }
954
1048
  await response.body?.cancel();
1049
+ return true;
955
1050
  }
956
1051
 
957
1052
  function parseLoopbackMultiaddr(address: string): {
@@ -1044,6 +1139,29 @@ export async function p2pForward(
1044
1139
  };
1045
1140
  }
1046
1141
 
1142
+ export async function isRecursivelyPinned(
1143
+ node: KuboNode,
1144
+ cid: string,
1145
+ signal?: AbortSignal,
1146
+ fetcher: typeof fetch = fetch,
1147
+ ): Promise<boolean> {
1148
+ const response = await rpc(
1149
+ node,
1150
+ "pin/ls?type=recursive",
1151
+ signal,
1152
+ 15_000,
1153
+ fetcher,
1154
+ );
1155
+ if (!response.ok)
1156
+ throw new HostError(`Owned Kubo pin/ls failed (HTTP ${response.status}).`);
1157
+ const data = object(JSON.parse(await boundedText(response)), "Kubo pins");
1158
+ const keys = object(data.Keys, "Kubo pin keys");
1159
+ return (
1160
+ Object.hasOwn(keys, cid) &&
1161
+ object(keys[cid], "Kubo pin").Type === "recursive"
1162
+ );
1163
+ }
1164
+
1047
1165
  export async function pinAdd(
1048
1166
  node: KuboNode,
1049
1167
  cid: string,
@@ -0,0 +1,91 @@
1
+ import { swarmUrl } from "./config.js";
2
+ import { HostError } from "./host-error.js";
3
+ import { relativePath } from "./space-path.js";
4
+
5
+ export function formalName(name: string): string {
6
+ relativePath(name);
7
+ if (name.length > 256 || name.startsWith("builtin:"))
8
+ throw new HostError("Invalid formal Name.");
9
+ return name;
10
+ }
11
+
12
+ function decodeNameComponent(
13
+ value: string,
14
+ part: "authority" | "path",
15
+ ): string {
16
+ try {
17
+ return decodeURIComponent(value);
18
+ } catch {
19
+ throw new HostError(
20
+ `Malformed percent-encoding in IPAB URI ${part}; use valid UTF-8 escapes or copy the reference from ipab search.`,
21
+ );
22
+ }
23
+ }
24
+
25
+ export function parseNameReference(
26
+ reference: string,
27
+ ): { swarm?: string; name: string } | undefined {
28
+ if (/^name:/i.test(reference))
29
+ throw new HostError("name: is unsupported; use ipab://ALIAS/PATH.");
30
+ if (!/^ipab:/i.test(reference)) return undefined;
31
+ if (/^ipab:\/\/https?:\/\//i.test(reference))
32
+ throw new HostError(
33
+ "Unencoded configuration URL in IPAB URI. Percent-encode the entire configuration URL and each Name path segment separately, or copy the reference from ipab search.",
34
+ );
35
+ const match = /^ipab:\/\/([^/]*)\/(.*)$/is.exec(reference);
36
+ if (!match)
37
+ throw new HostError(
38
+ "Invalid IPAB URI; percent-encode the configuration URL authority and each path segment.",
39
+ );
40
+ const authority = decodeNameComponent(match[1]!, "authority");
41
+ if (authority && !/^[A-Za-z0-9][A-Za-z0-9._-]*$/.test(authority)) {
42
+ if (!/^https?:\/\//i.test(authority))
43
+ throw new HostError(
44
+ "Invalid IPAB URI authority; use a registered alias or the percent-encoded configuration URL.",
45
+ );
46
+ swarmUrl(authority);
47
+ }
48
+ if (/[?#\s]/.test(match[2]!))
49
+ throw new HostError(
50
+ "Invalid IPAB URI path; percent-encode each Name path segment. Queries and fragments are not supported.",
51
+ );
52
+ const segments = match[2]!.split("/").map((segment) => {
53
+ const decoded = decodeNameComponent(segment, "path");
54
+ if (/[/\\]/.test(decoded))
55
+ throw new HostError(
56
+ "Invalid IPAB URI path separator; use literal / between Name segments, never an encoded slash or backslash.",
57
+ );
58
+ return decoded;
59
+ });
60
+ try {
61
+ return {
62
+ ...(authority ? { swarm: authority } : {}),
63
+ name: match[2] === "" ? "" : formalName(segments.join("/")),
64
+ };
65
+ } catch (error) {
66
+ if (!(error instanceof HostError)) throw error;
67
+ throw new HostError(
68
+ "Invalid IPAB URI path; use a safe relative Name of at most 256 characters without empty, . or .. segments.",
69
+ error.exitCode,
70
+ error.code,
71
+ error.phase,
72
+ );
73
+ }
74
+ }
75
+
76
+ export function formatNameReference(swarm: string, name: string): string {
77
+ const segment = (value: string) =>
78
+ encodeURIComponent(value).replace(
79
+ /[!'()*]/g,
80
+ (char) => `%${char.charCodeAt(0).toString(16).toUpperCase()}`,
81
+ );
82
+ return `ipab://${segment(swarm)}/${name.split("/").map(segment).join("/")}`;
83
+ }
84
+
85
+ export function templateName(name: string): string {
86
+ if (name.includes(":"))
87
+ throw new HostError(
88
+ "Template NAME must be a safe relative Name, not a URI.",
89
+ );
90
+ return formalName(name);
91
+ }
package/src/pins.ts CHANGED
@@ -50,6 +50,24 @@ export function refreshPinClaim(
50
50
  });
51
51
  }
52
52
 
53
+ function persistentStoreBackend(
54
+ configuration: IpfsStore["configuration"],
55
+ ): IpfsStore["configuration"] {
56
+ return {
57
+ backend: configuration.backend,
58
+ dataDir: configuration.dataDir,
59
+ ...(configuration.coordinationDir !== undefined
60
+ ? { coordinationDir: configuration.coordinationDir }
61
+ : {}),
62
+ ...(configuration.gateway !== undefined
63
+ ? { gateway: configuration.gateway }
64
+ : {}),
65
+ ...(configuration.limits !== undefined
66
+ ? { limits: configuration.limits }
67
+ : {}),
68
+ };
69
+ }
70
+
53
71
  export function reservePin(
54
72
  state: State,
55
73
  reference: string,
@@ -78,7 +96,7 @@ export function reservePin(
78
96
  state.saveContentPin(pin);
79
97
  state.saveHold({
80
98
  owner: pin.owner,
81
- backend: configuration,
99
+ backend: persistentStoreBackend(configuration),
82
100
  roots: [],
83
101
  pid: process.pid,
84
102
  session: null,
@@ -99,14 +117,16 @@ export async function retainPin(
99
117
  let base: IpfsStore | undefined;
100
118
  let original: IpfsStore | undefined;
101
119
  try {
102
- if (JSON.stringify(backend) !== JSON.stringify(store.configuration)) {
120
+ if (
121
+ JSON.stringify(persistentStoreBackend(backend)) !==
122
+ JSON.stringify(persistentStoreBackend(store.configuration))
123
+ ) {
103
124
  base = new IpfsStore(backend);
104
125
  original = base.withLocalSource({
105
126
  block: { get: (cid, options) => store.block.get(cid, options) },
106
127
  });
107
128
  }
108
129
  const retainedStore = original ?? store;
109
- await base?.close();
110
130
  await retainedStore.recoverOwner(
111
131
  pin.owner,
112
132
  () => state.hold(pin.owner)!.roots,