@ipab/cli 0.1.0-rc.3 → 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 (97) hide show
  1. package/README.md +21 -10
  2. package/dist/cli.d.ts +3 -1
  3. package/dist/cli.d.ts.map +1 -1
  4. package/dist/cli.js +188 -46
  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 +2 -1
  11. package/dist/config.d.ts.map +1 -1
  12. package/dist/config.js +23 -3
  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/identity.d.ts +5 -0
  23. package/dist/identity.d.ts.map +1 -1
  24. package/dist/identity.js +5 -0
  25. package/dist/identity.js.map +1 -1
  26. package/dist/ipc.d.ts +3 -1
  27. package/dist/ipc.d.ts.map +1 -1
  28. package/dist/ipc.js +34 -1
  29. package/dist/ipc.js.map +1 -1
  30. package/dist/kubo-install.d.ts +9 -0
  31. package/dist/kubo-install.d.ts.map +1 -0
  32. package/dist/kubo-install.js +361 -0
  33. package/dist/kubo-install.js.map +1 -0
  34. package/dist/kubo-peering.d.ts +11 -0
  35. package/dist/kubo-peering.d.ts.map +1 -0
  36. package/dist/kubo-peering.js +93 -0
  37. package/dist/kubo-peering.js.map +1 -0
  38. package/dist/kubo-peers.d.ts +12 -0
  39. package/dist/kubo-peers.d.ts.map +1 -0
  40. package/dist/kubo-peers.js +118 -0
  41. package/dist/kubo-peers.js.map +1 -0
  42. package/dist/kubo-release.d.ts +3 -0
  43. package/dist/kubo-release.d.ts.map +1 -0
  44. package/dist/kubo-release.js +12 -0
  45. package/dist/kubo-release.js.map +1 -0
  46. package/dist/kubo.d.ts +14 -5
  47. package/dist/kubo.d.ts.map +1 -1
  48. package/dist/kubo.js +186 -206
  49. package/dist/kubo.js.map +1 -1
  50. package/dist/runtime.d.ts +2 -0
  51. package/dist/runtime.d.ts.map +1 -1
  52. package/dist/runtime.js +6 -2
  53. package/dist/runtime.js.map +1 -1
  54. package/dist/setup.d.ts +2 -1
  55. package/dist/setup.d.ts.map +1 -1
  56. package/dist/setup.js +23 -18
  57. package/dist/setup.js.map +1 -1
  58. package/dist/state-storage-windows.d.ts +2 -0
  59. package/dist/state-storage-windows.d.ts.map +1 -0
  60. package/dist/state-storage-windows.js +114 -0
  61. package/dist/state-storage-windows.js.map +1 -0
  62. package/dist/state-storage.d.ts +3 -0
  63. package/dist/state-storage.d.ts.map +1 -0
  64. package/dist/state-storage.js +299 -0
  65. package/dist/state-storage.js.map +1 -0
  66. package/dist/state.d.ts +5 -3
  67. package/dist/state.d.ts.map +1 -1
  68. package/dist/state.js +64 -30
  69. package/dist/state.js.map +1 -1
  70. package/dist/swarm-files.d.ts +3 -2
  71. package/dist/swarm-files.d.ts.map +1 -1
  72. package/dist/swarm-files.js +25 -9
  73. package/dist/swarm-files.js.map +1 -1
  74. package/dist/swarm.d.ts +10 -5
  75. package/dist/swarm.d.ts.map +1 -1
  76. package/dist/swarm.js +225 -79
  77. package/dist/swarm.js.map +1 -1
  78. package/package.json +4 -4
  79. package/src/cli.ts +224 -60
  80. package/src/config-secret.ts +2 -84
  81. package/src/config.ts +25 -3
  82. package/src/context-types.ts +11 -0
  83. package/src/context.ts +40 -0
  84. package/src/identity.ts +13 -0
  85. package/src/ipc.ts +50 -1
  86. package/src/kubo-install.ts +452 -0
  87. package/src/kubo-peering.ts +126 -0
  88. package/src/kubo-peers.ts +145 -0
  89. package/src/kubo-release.ts +17 -0
  90. package/src/kubo.ts +254 -275
  91. package/src/runtime.ts +12 -1
  92. package/src/setup.ts +30 -17
  93. package/src/state-storage-windows.ts +134 -0
  94. package/src/state-storage.ts +329 -0
  95. package/src/state.ts +76 -35
  96. package/src/swarm-files.ts +26 -6
  97. package/src/swarm.ts +316 -97
@@ -0,0 +1,3 @@
1
+ export declare const KUBO_VERSION = "0.43.2";
2
+ export declare const releaseDigests: Readonly<Record<string, string>>;
3
+ //# sourceMappingURL=kubo-release.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"kubo-release.d.ts","sourceRoot":"","sources":["../src/kubo-release.ts"],"names":[],"mappings":"AAEA,eAAO,MAAM,YAAY,WAAW,CAAC;AACrC,eAAO,MAAM,cAAc,EAAE,QAAQ,CAAC,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAa3D,CAAC"}
@@ -0,0 +1,12 @@
1
+ // Reviewed from https://api.github.com/repos/ipfs/kubo/releases/tags/v0.43.2.
2
+ // The full asset name binds each SHA-256 to a version, OS, architecture and format.
3
+ export const KUBO_VERSION = "0.43.2";
4
+ export const releaseDigests = {
5
+ "kubo_v0.43.2_darwin-amd64.tar.gz": "134fd3c2923936ff0b725986a86123d7d735fc6847cfc0f9a14881207f03a169",
6
+ "kubo_v0.43.2_darwin-arm64.tar.gz": "62a0d2cdfdc831bb9e21b89d8d6c7cd1f3187ab42efc8a359482e7d9be75679a",
7
+ "kubo_v0.43.2_linux-amd64.tar.gz": "94b3199660350530438be8bebf51e1e995d0bfae57184294c2f35b9a128378ca",
8
+ "kubo_v0.43.2_linux-arm64.tar.gz": "5a9115f2d2ce64c60c3a9d0743c3e47d723bcd9b0fff76af730eab0b49c0be62",
9
+ "kubo_v0.43.2_windows-amd64.zip": "cca66dedb6bd80d5d6c7ca6b08e574f3a9c74a0f7057f8ddf18f2bb7b073f59f",
10
+ "kubo_v0.43.2_windows-arm64.zip": "7607e6f884fe4d4a4e2ebf8c76b58ca8ddb9c3b1cb84dddc29a799f7b99c4266",
11
+ };
12
+ //# sourceMappingURL=kubo-release.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"kubo-release.js","sourceRoot":"","sources":["../src/kubo-release.ts"],"names":[],"mappings":"AAAA,8EAA8E;AAC9E,oFAAoF;AACpF,MAAM,CAAC,MAAM,YAAY,GAAG,QAAQ,CAAC;AACrC,MAAM,CAAC,MAAM,cAAc,GAAqC;IAC9D,kCAAkC,EAChC,kEAAkE;IACpE,kCAAkC,EAChC,kEAAkE;IACpE,iCAAiC,EAC/B,kEAAkE;IACpE,iCAAiC,EAC/B,kEAAkE;IACpE,gCAAgC,EAC9B,kEAAkE;IACpE,gCAAgC,EAC9B,kEAAkE;CACrE,CAAC"}
package/dist/kubo.d.ts CHANGED
@@ -1,4 +1,8 @@
1
- export declare const KUBO_VERSION = "0.43.2";
1
+ import { type PeeringPeer } from "./kubo-peering.js";
2
+ import { kuboBinary } from "./kubo-install.js";
3
+ export { kuboBinary };
4
+ export { KUBO_VERSION } from "./kubo-release.js";
5
+ export type ListenMode = "lan" | "loopback";
2
6
  export interface NodeRecord {
3
7
  scope: string;
4
8
  peerId: string;
@@ -8,6 +12,7 @@ export interface NodeRecord {
8
12
  auth: string;
9
13
  epoch?: number;
10
14
  pid?: number;
15
+ listen?: ListenMode;
11
16
  }
12
17
  export interface KuboNode {
13
18
  repo: string;
@@ -18,17 +23,21 @@ export interface KuboNode {
18
23
  auth: string;
19
24
  pid?: number;
20
25
  }
21
- export declare function kuboBinary(stateDir: string): Promise<string>;
22
- export declare function prepareNode(stateDir: string, scope: string): Promise<KuboNode>;
26
+ export declare function prepareNode(stateDir: string, scope: string, listen?: ListenMode): Promise<KuboNode>;
27
+ export declare function checkCachedNode(stateDir: string, scope: string, epoch: number, peer: string): Promise<void>;
23
28
  export declare function peerProof(node: KuboNode, message: string): Promise<{
24
29
  publicKey: string;
25
30
  signature: string;
26
31
  }>;
27
32
  export declare function peerId(raw: string): string;
28
33
  export declare function stopNode(node: KuboNode): Promise<void>;
29
- export declare function startNode(stateDir: string, scope: string, key: string, epoch: number, addresses: readonly string[], diagnostic?: (text: string) => void): Promise<KuboNode>;
34
+ export declare function startNode(stateDir: string, scope: string, key: string, epoch: number, listen?: ListenMode, membership?: {
35
+ self: string;
36
+ peers: readonly PeeringPeer[];
37
+ signal?: AbortSignal;
38
+ }): Promise<KuboNode>;
30
39
  export declare function validateAddress(address: string, expectedPeer?: string): void;
31
- export declare function kuboSource(node: KuboNode): {
40
+ export declare function kuboSource(node: KuboNode, addresses?: readonly string[], diagnostic?: (line: string) => void, detailed?: boolean): {
32
41
  block: {
33
42
  get(cid: string, options?: {
34
43
  signal?: AbortSignal;
@@ -1 +1 @@
1
- {"version":3,"file":"kubo.d.ts","sourceRoot":"","sources":["../src/kubo.ts"],"names":[],"mappings":"AAgCA,eAAO,MAAM,YAAY,WAAW,CAAC;AAQrC,MAAM,WAAW,UAAU;IACzB,KAAK,EAAE,MAAM,CAAC;IACd,MAAM,EAAE,MAAM,CAAC;IACf,GAAG,EAAE,MAAM,CAAC;IACZ,OAAO,EAAE,MAAM,CAAC;IAChB,KAAK,EAAE,MAAM,CAAC;IACd,IAAI,EAAE,MAAM,CAAC;IACb,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,GAAG,CAAC,EAAE,MAAM,CAAC;CACd;AACD,MAAM,WAAW,QAAQ;IACvB,IAAI,EAAE,MAAM,CAAC;IACb,MAAM,EAAE,MAAM,CAAC;IACf,GAAG,EAAE,MAAM,CAAC;IACZ,OAAO,EAAE,MAAM,CAAC;IAChB,SAAS,EAAE,MAAM,EAAE,CAAC;IACpB,IAAI,EAAE,MAAM,CAAC;IACb,GAAG,CAAC,EAAE,MAAM,CAAC;CACd;AAiDD,wBAAsB,UAAU,CAAC,QAAQ,EAAE,MAAM,GAAG,OAAO,CAAC,MAAM,CAAC,CA2IlE;AAmBD,wBAAsB,WAAW,CAC/B,QAAQ,EAAE,MAAM,EAChB,KAAK,EAAE,MAAM,GACZ,OAAO,CAAC,QAAQ,CAAC,CAKnB;AAy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K,EAAE,SAAS,WAAW,EAAE,CAAC;IAC9B,MAAM,CAAC,EAAE,WAAW,CAAC;CACtB,GACA,OAAO,CAAC,QAAQ,CAAC,CAmHnB;AACD,wBAAgB,eAAe,CAAC,OAAO,EAAE,MAAM,EAAE,YAAY,CAAC,EAAE,MAAM,GAAG,IAAI,CAc5E;AACD,wBAAgB,UAAU,CACxB,IAAI,EAAE,QAAQ,EACd,SAAS,GAAE,SAAS,MAAM,EAAO,EACjC,UAAU,CAAC,EAAE,CAAC,IAAI,EAAE,MAAM,KAAK,IAAI,EACnC,QAAQ,UAAQ;;iBAwDL,MAAM,YACF;YAAE,MAAM,CAAC,EAAE,WAAW,CAAA;SAAE,GAChC,OAAO,CAAC,UAAU,CAAC;;EAoE3B"}
package/dist/kubo.js CHANGED
@@ -1,22 +1,27 @@
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
- import { protectedPath, secureNew } from "./identity.js";
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 } from "./kubo-install.js";
16
+ export { kuboBinary };
17
+ export { KUBO_VERSION } from "./kubo-release.js";
18
+ function swarmAddress(listen, port) {
19
+ return `/ip4/${listen === "loopback" ? "127.0.0.1" : "0.0.0.0"}/tcp/${port}`;
20
+ }
15
21
  const run = promisify(execFile);
16
- const hash = (data) => createHash("sha256").update(data).digest("hex");
17
22
  function nodeRecord(value, scope) {
18
23
  const record = object(value, "protected managed-node record");
19
- const { peerId, api, gateway, swarm, auth, pid, epoch } = record;
24
+ const { peerId, api, gateway, swarm, auth, pid, epoch, listen } = record;
20
25
  if (Object.keys(record).some((key) => ![
21
26
  "scope",
22
27
  "peerId",
@@ -26,6 +31,7 @@ function nodeRecord(value, scope) {
26
31
  "auth",
27
32
  "pid",
28
33
  "epoch",
34
+ "listen",
29
35
  ].includes(key)) ||
30
36
  record.scope !== scope ||
31
37
  typeof peerId !== "string" ||
@@ -40,7 +46,10 @@ function nodeRecord(value, scope) {
40
46
  (pid !== undefined &&
41
47
  (typeof pid !== "number" || !Number.isSafeInteger(pid) || pid <= 0)) ||
42
48
  (epoch !== undefined &&
43
- (typeof epoch !== "number" || !Number.isSafeInteger(epoch) || epoch < 1)))
49
+ (typeof epoch !== "number" ||
50
+ !Number.isSafeInteger(epoch) ||
51
+ epoch < 1)) ||
52
+ (listen !== undefined && listen !== "lan" && listen !== "loopback"))
44
53
  throw new HostError("Invalid protected managed-node record; old node formats are unsupported.");
45
54
  return {
46
55
  scope,
@@ -51,116 +60,9 @@ function nodeRecord(value, scope) {
51
60
  auth,
52
61
  ...(pid !== undefined ? { pid } : {}),
53
62
  ...(epoch !== undefined ? { epoch } : {}),
63
+ ...(listen !== undefined ? { listen } : {}),
54
64
  };
55
65
  }
56
- export async function kuboBinary(stateDir) {
57
- const directory = await privateDirectory(stateDir, "kubo-bin");
58
- return withPrivateLock(directory, async () => {
59
- const executable = join(directory, process.platform === "win32" ? "ipfs.exe" : "ipfs");
60
- const installed = await readPrivate(directory, "installation.json");
61
- if (installed) {
62
- await protectedPath(executable);
63
- if (installed.version !== KUBO_VERSION ||
64
- installed.hash !== hash(await readFile(executable)))
65
- throw new HostError("Kubo installation integrity mismatch; do not use this binary.");
66
- return executable;
67
- }
68
- const platforms = {
69
- win32: "windows",
70
- darwin: "darwin",
71
- linux: "linux",
72
- };
73
- const platform = platforms[process.platform];
74
- if (!platform || !["x64", "arm64"].includes(process.arch))
75
- throw new HostError("Unsupported Kubo platform.");
76
- const arch = process.arch === "x64" ? "amd64" : "arm64";
77
- const filename = `kubo_v${KUBO_VERSION}_${platform}-${arch}.${platform === "windows" ? "zip" : "tar.gz"}`;
78
- // Official release metadata supplies the immutable archive digest; HTTPS is the trust boundary.
79
- const release = await fetch(`https://api.github.com/repos/ipfs/kubo/releases/tags/v${KUBO_VERSION}`, {
80
- redirect: "error",
81
- signal: AbortSignal.timeout(30_000),
82
- headers: { accept: "application/vnd.github+json" },
83
- });
84
- if (!release.ok)
85
- throw new HostError(`Could not verify official Kubo release (HTTP ${release.status}).`);
86
- const metadata = JSON.parse(await boundedText(release));
87
- const asset = metadata.assets.find((item) => item.name === filename);
88
- if (metadata.draft ||
89
- metadata.prerelease ||
90
- !asset ||
91
- !/^sha256:[a-f0-9]{64}$/.test(asset.digest) ||
92
- asset.browser_download_url !==
93
- `https://github.com/ipfs/kubo/releases/download/v${KUBO_VERSION}/${filename}`)
94
- throw new HostError("Official stable Kubo archive/digest unavailable.");
95
- const archive = join(directory, `${uniqueId()}.${platform === "windows" ? "zip" : "tar.gz"}`);
96
- const stage = await privateDirectory(directory, `extract-${uniqueId()}`);
97
- try {
98
- const response = await fetch(asset.browser_download_url, {
99
- signal: AbortSignal.timeout(180_000),
100
- });
101
- if (!response.ok || !response.body)
102
- throw new HostError("Kubo download failed.");
103
- const handle = await open(archive, "wx", 0o600);
104
- let total = 0;
105
- const digest = createHash("sha256");
106
- try {
107
- await secureNew(archive);
108
- const stream = response.body;
109
- for await (const chunk of stream) {
110
- total += chunk.length;
111
- if (total > 150 * 1024 * 1024)
112
- throw new HostError("Kubo archive exceeds limit.");
113
- digest.update(chunk);
114
- await handle.write(chunk);
115
- }
116
- await handle.sync();
117
- }
118
- finally {
119
- await handle.close();
120
- }
121
- if (`sha256:${digest.digest("hex")}` !== asset.digest)
122
- throw new HostError("Kubo archive checksum mismatch.");
123
- const listing = await run("tar", ["-tf", archive], {
124
- timeout: 30_000,
125
- maxBuffer: 1024 * 1024,
126
- windowsHide: true,
127
- });
128
- if (listing.stdout
129
- .split(/\r?\n/)
130
- .filter(Boolean)
131
- .some((path) => !/^kubo\/[A-Za-z0-9._/-]+$/.test(path) ||
132
- path.split("/").includes("..")))
133
- throw new HostError("Unsafe Kubo archive layout.");
134
- await run("tar", ["-xf", archive, "-C", stage], {
135
- timeout: 30_000,
136
- windowsHide: true,
137
- });
138
- const extracted = join(stage, "kubo", process.platform === "win32" ? "ipfs.exe" : "ipfs");
139
- if (!(await lstat(extracted)).isFile() ||
140
- (await lstat(extracted)).isSymbolicLink())
141
- throw new HostError("Invalid Kubo executable.");
142
- await secureNew(extracted);
143
- if (process.platform !== "win32")
144
- await chmod(extracted, 0o700);
145
- const version = await run(extracted, ["version", "--number"], {
146
- timeout: 10_000,
147
- windowsHide: true,
148
- });
149
- if (version.stdout.trim() !== KUBO_VERSION)
150
- throw new HostError("Kubo executable version mismatch.");
151
- await rename(extracted, executable);
152
- await writePrivate(directory, "installation.json", {
153
- version: KUBO_VERSION,
154
- hash: hash(await readFile(executable)),
155
- });
156
- return executable;
157
- }
158
- finally {
159
- await rm(stage, { recursive: true, force: true });
160
- await rm(archive, { force: true });
161
- }
162
- });
163
- }
164
66
  async function freePort() {
165
67
  const server = createServer();
166
68
  return new Promise((resolve, reject) => {
@@ -181,18 +83,40 @@ async function freePort() {
181
83
  });
182
84
  });
183
85
  }
184
- export async function prepareNode(stateDir, scope) {
86
+ export async function prepareNode(stateDir, scope, listen = "lan") {
185
87
  if (!/^[a-f0-9]{64}$/.test(scope))
186
88
  throw new HostError("Invalid service-bound local Scope identity.");
187
89
  const binary = await kuboBinary(stateDir);
188
- return prepareWithBinary(stateDir, scope, binary);
90
+ return prepareWithBinary(stateDir, scope, binary, listen);
91
+ }
92
+ export async function checkCachedNode(stateDir, scope, epoch, peer) {
93
+ if (!/^[a-f0-9]{64}$/.test(scope))
94
+ throw new HostError("Invalid service-bound local Scope identity.");
95
+ const saved = await readPrivate(join(stateDir, "swarm-nodes", scope), "node.json");
96
+ if (saved === undefined)
97
+ return;
98
+ const node = nodeRecord(saved, scope);
99
+ if (node.peerId !== peer || (node.epoch !== undefined && node.epoch > epoch))
100
+ throw new HostError("Cached membership does not match the recorded node identity or epoch; retry with --force.");
189
101
  }
190
- async function prepareWithBinary(stateDir, scope, binary) {
191
- const parent = await privateDirectory(stateDir, "swarm-nodes");
192
- const directory = await privateDirectory(parent, scope);
193
- return withPrivateLock(directory, async () => {
194
- const repo = await privateDirectory(directory, "repo");
195
- let record = await readPrivate(directory, "node.json");
102
+ async function prepareWithBinary(stateDir, scope, binary, listen, signal) {
103
+ const parent = join(stateDir, "swarm-nodes");
104
+ const directory = join(parent, scope);
105
+ const repo = join(directory, "repo");
106
+ try {
107
+ await protectedPaths([parent, directory, repo].map((path) => ({ path, directory: true })));
108
+ }
109
+ catch (cause) {
110
+ if (!nodeError(cause, "ENOENT"))
111
+ throw cause;
112
+ await privateDirectory(stateDir, "swarm-nodes");
113
+ await privateDirectory(parent, scope);
114
+ await privateDirectory(directory, "repo");
115
+ }
116
+ const prepare = async () => {
117
+ let record = await readPrivate(directory, "node.json", [
118
+ { path: join(repo, "config") },
119
+ ]);
196
120
  if (record === undefined) {
197
121
  try {
198
122
  await lstat(join(repo, "swarm.key"));
@@ -211,6 +135,7 @@ async function prepareWithBinary(stateDir, scope, binary) {
211
135
  throw cause;
212
136
  await run(binary, ["init", "--profile=server"], {
213
137
  env,
138
+ signal,
214
139
  timeout: 30_000,
215
140
  windowsHide: true,
216
141
  });
@@ -223,11 +148,12 @@ async function prepareWithBinary(stateDir, scope, binary) {
223
148
  gateway: await freePort(),
224
149
  swarm: await freePort(),
225
150
  auth: uniqueId(),
151
+ listen,
226
152
  };
227
153
  config.Addresses = {
228
154
  API: `/ip4/127.0.0.1/tcp/${record.api}`,
229
155
  Gateway: `/ip4/127.0.0.1/tcp/${record.gateway}`,
230
- Swarm: [`/ip4/0.0.0.0/tcp/${record.swarm}`],
156
+ Swarm: [swarmAddress(listen, record.swarm)],
231
157
  };
232
158
  config.Bootstrap = [];
233
159
  config.Swarm.AddrFilters = [];
@@ -257,15 +183,13 @@ async function prepareWithBinary(stateDir, scope, binary) {
257
183
  });
258
184
  await secureNew(join(repo, "config"));
259
185
  await writePrivate(directory, "node.json", record);
186
+ await protectedPath(join(repo, "config"));
260
187
  }
261
- await protectedPath(join(repo, "config"));
262
188
  record = nodeRecord(record, scope);
263
- const local = Object.values(networkInterfaces())
264
- .flatMap((items) => items ?? [])
265
- .filter((item) => item.family === "IPv4" &&
266
- /^(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))
267
- .map((item) => item.address)
268
- .slice(0, 15);
189
+ // A repo created before listen modes existed binds 0.0.0.0, so it is LAN.
190
+ record.listen ??= "lan";
191
+ if (record.listen !== listen)
192
+ throw new HostError("Managed node already listens in a different mode; existing repos are not rebound.");
269
193
  return {
270
194
  repo,
271
195
  peerId: record.peerId,
@@ -273,9 +197,10 @@ async function prepareWithBinary(stateDir, scope, binary) {
273
197
  gateway: `http://127.0.0.1:${record.gateway}`,
274
198
  auth: record.auth,
275
199
  ...(record.pid !== undefined ? { pid: record.pid } : {}),
276
- addresses: [...new Set([...local, "127.0.0.1"])].map((ip) => `/ip4/${ip}/tcp/${record.swarm}/p2p/${record.peerId}`),
200
+ addresses: advertisedIps(record.listen).map((ip) => `/ip4/${ip}/tcp/${record.swarm}/p2p/${record.peerId}`),
277
201
  };
278
- });
202
+ };
203
+ return withPrivateLock(directory, prepare, signal);
279
204
  }
280
205
  export async function peerProof(node, message) {
281
206
  await protectedPath(join(node.repo, "config"));
@@ -320,9 +245,9 @@ async function rpc(node, command, signal, timeout = 5000) {
320
245
  : AbortSignal.timeout(timeout),
321
246
  });
322
247
  }
323
- async function ready(node) {
248
+ async function ready(node, signal) {
324
249
  try {
325
- const response = await rpc(node, "id");
250
+ const response = await rpc(node, "id", signal);
326
251
  if (response.status === 401 || response.status === 403) {
327
252
  await response.body?.cancel();
328
253
  throw new HostError("Owned Kubo API authorization failed; refusing control.");
@@ -337,6 +262,7 @@ async function ready(node) {
337
262
  return true;
338
263
  }
339
264
  catch (cause) {
265
+ signal?.throwIfAborted();
340
266
  if (cause instanceof HostError)
341
267
  throw cause;
342
268
  return false;
@@ -365,18 +291,39 @@ export async function stopNode(node) {
365
291
  }
366
292
  throw new HostError("Owned Kubo node did not stop.");
367
293
  }
368
- export async function startNode(stateDir, scope, key, epoch, addresses, diagnostic) {
294
+ export async function startNode(stateDir, scope, key, epoch, listen = "lan", membership) {
369
295
  if (!/^[a-f0-9]{64}$/.test(scope))
370
296
  throw new HostError("Invalid service-bound local Scope identity.");
371
297
  if (!/^[a-f0-9]{64}$/.test(key))
372
298
  throw new HostError("Invalid Swarm key.");
373
- const binary = await kuboBinary(stateDir);
374
- const node = await prepareWithBinary(stateDir, scope, binary);
299
+ const signal = membership?.signal;
300
+ signal?.throwIfAborted();
301
+ const binary = await kuboBinary(stateDir, signal ? { signal } : {});
302
+ signal?.throwIfAborted();
303
+ const node = await prepareWithBinary(stateDir, scope, binary, listen, signal);
304
+ if (membership && node.peerId !== membership.self)
305
+ throw new HostError("Approved PeerID differs from this local Request's Kubo identity.");
375
306
  const directory = join(stateDir, "swarm-nodes", scope);
376
- return withPrivateLock(directory, async () => {
307
+ const start = async () => {
308
+ signal?.throwIfAborted();
377
309
  const record = (await readPrivate(directory, "node.json"));
310
+ if (record.epoch !== undefined && record.epoch > epoch)
311
+ throw new HostError("Refusing to restore an older Swarm epoch; refresh membership.");
378
312
  if (record.epoch !== undefined && record.epoch !== epoch)
379
313
  await stopNode(node);
314
+ const online = await ready(node, signal);
315
+ if (!online && record.pid !== undefined) {
316
+ try {
317
+ process.kill(record.pid, 0);
318
+ throw new HostError("Owned node process is still running but not ready; retry before changing its configuration.");
319
+ }
320
+ catch (cause) {
321
+ if (!nodeError(cause, "ESRCH"))
322
+ throw cause;
323
+ }
324
+ }
325
+ const call = (command, budget) => rpc(node, command, signal ? AbortSignal.any([signal, budget]) : budget);
326
+ const desired = membership?.peers ?? [];
380
327
  const keyPath = join(node.repo, "swarm.key");
381
328
  if (record.epoch === epoch) {
382
329
  await protectedPath(keyPath);
@@ -385,12 +332,16 @@ export async function startNode(stateDir, scope, key, epoch, addresses, diagnost
385
332
  throw new HostError("Swarm key file does not match approved epoch.");
386
333
  }
387
334
  else {
335
+ await persistPeers(node.repo, desired, online ? call : undefined);
388
336
  await writeFile(keyPath, `/key/swarm/psk/1.0.0/\n/base16/\n${key}\n`, {
389
337
  mode: 0o600,
390
338
  });
391
339
  await secureNew(keyPath);
392
340
  }
393
- if (!(await ready(node))) {
341
+ if (record.epoch === epoch)
342
+ await persistPeers(node.repo, desired, online ? call : undefined);
343
+ if (!online) {
344
+ signal?.throwIfAborted();
394
345
  const logfile = join(directory, "daemon.log");
395
346
  const log = await open(logfile, "a", 0o600);
396
347
  await secureNew(logfile);
@@ -419,9 +370,10 @@ export async function startNode(stateDir, scope, key, epoch, addresses, diagnost
419
370
  await writePrivate(directory, "node.json", record);
420
371
  }
421
372
  for (let i = 0;; i++) {
373
+ signal?.throwIfAborted();
422
374
  if (failure)
423
375
  throw failure;
424
- if (await ready(node))
376
+ if (await ready(node, signal))
425
377
  break;
426
378
  if (i >= 150 || child.exitCode !== null)
427
379
  throw new HostError("Owned Kubo startup failed; inspect protected daemon.log.");
@@ -442,42 +394,10 @@ export async function startNode(stateDir, scope, key, epoch, addresses, diagnost
442
394
  }
443
395
  record.epoch = epoch;
444
396
  await writePrivate(directory, "node.json", record);
445
- const groups = new Map();
446
- for (const address of addresses) {
447
- validateAddress(address);
448
- const target = address.split("/").at(-1);
449
- if (target === node.peerId)
450
- continue;
451
- const group = groups.get(target) ?? [];
452
- if (group.length < 16 && !group.includes(address))
453
- group.push(address);
454
- groups.set(target, group);
455
- }
456
- const budget = AbortSignal.timeout(10_000);
457
- await Promise.all([...groups.values()].map(async (group) => {
458
- const connected = new AbortController();
459
- await Promise.all(group.map(async (address) => {
460
- try {
461
- const response = await rpc(node, `swarm/connect?arg=${encodeURIComponent(address)}`, AbortSignal.any([budget, connected.signal]));
462
- const ok = response.ok;
463
- if (!ok) {
464
- const reason = JSON.parse(await boundedText(response));
465
- diagnostic?.(`Swarm peer dial failed at ${address}: ${reason.Message?.slice(0, 512) ?? `HTTP ${response.status}`}`);
466
- }
467
- await response.body?.cancel();
468
- if (ok)
469
- connected.abort();
470
- }
471
- catch (cause) {
472
- if (!connected.signal.aborted)
473
- diagnostic?.(`Swarm peer dial unavailable at ${address}: ${cause instanceof Error ? cause.message : "network error"}`);
474
- // An offline address must not hide a reachable address of the same PeerID.
475
- // Content reads still report actual network failure, not authorization failure.
476
- }
477
- }));
478
- }));
397
+ await reconcilePeers(call, desired);
479
398
  return node;
480
- });
399
+ };
400
+ return withPrivateLock(directory, start, signal);
481
401
  }
482
402
  export function validateAddress(address, expectedPeer) {
483
403
  const match = /^\/ip4\/(\d+\.\d+\.\d+\.\d+)\/tcp\/([1-9]\d{0,4})\/p2p\/([A-Za-z0-9]+)$/.exec(address);
@@ -487,40 +407,100 @@ export function validateAddress(address, expectedPeer) {
487
407
  (expectedPeer && match[3] !== expectedPeer))
488
408
  throw new HostError("LAN/VPN profile requires IPv4 TCP multiaddr bound to its PeerID.");
489
409
  }
490
- export function kuboSource(node) {
410
+ export function kuboSource(node, addresses = [], diagnostic, detailed = false) {
411
+ const groups = new Map();
412
+ for (const address of new Set(addresses)) {
413
+ validateAddress(address);
414
+ const target = address.split("/").at(-1);
415
+ if (target === node.peerId)
416
+ continue;
417
+ const group = groups.get(target) ?? [];
418
+ if (group.length < 16)
419
+ group.push(address.slice(0, -`/p2p/${target}`.length));
420
+ groups.set(target, group);
421
+ }
422
+ let fallbackUsed = false;
423
+ const connected = async (signal) => {
424
+ const response = await rpc(node, "swarm/peers", signal);
425
+ if (!response.ok) {
426
+ await response.body?.cancel();
427
+ throw new HostError(`HTTP ${response.status}`);
428
+ }
429
+ const data = object(JSON.parse(await boundedText(response)), "owned Kubo connections");
430
+ if (data.Peers === null)
431
+ return new Set();
432
+ if (!Array.isArray(data.Peers))
433
+ throw new HostError("Invalid owned Kubo connections.");
434
+ return new Set(data.Peers.map((entry) => {
435
+ const { Peer } = object(entry, "owned Kubo connection");
436
+ if (typeof Peer !== "string")
437
+ throw new HostError("Invalid owned Kubo connection.");
438
+ return Peer;
439
+ }));
440
+ };
441
+ const connect = async (id, addrs, signal) => {
442
+ const response = await rpc(node, `swarm/connect?${peerArguments(id, addrs)}`, signal);
443
+ try {
444
+ if (!response.ok)
445
+ throw new HostError(`HTTP ${response.status}`);
446
+ // swarm/connect may stream the result. Do not treat headers alone as success.
447
+ await boundedText(response);
448
+ }
449
+ finally {
450
+ await response.body?.cancel();
451
+ }
452
+ };
491
453
  return {
492
454
  block: {
493
455
  async get(cid, options = {}) {
494
- const response = await rpc(node, `block/get?arg=${encodeURIComponent(cid)}`, options.signal, 30_000);
495
- if (!response.ok || !response.body)
496
- throw new HostError(`Swarm block unavailable (HTTP ${response.status}).`);
497
- const stream = response.body;
498
- const reader = stream.getReader();
499
- const chunks = [];
500
- let size = 0;
501
- try {
502
- for (;;) {
503
- const part = await reader.read();
504
- if (part.done)
505
- break;
506
- size += part.value.length;
507
- if (size > 2 * 1024 * 1024) {
508
- await reader.cancel();
509
- throw new HostError("Kubo block exceeds limit.");
456
+ return readWithPeers(groups, async (signal, offline) => {
457
+ const response = await rpc(node, `block/get?arg=${encodeURIComponent(cid)}${offline ? "&offline=true" : ""}`, signal, 30_000);
458
+ if (!response.ok || !response.body) {
459
+ const error = `Swarm block unavailable (HTTP ${response.status}).`;
460
+ if (offline && [404, 500].includes(response.status)) {
461
+ const detail = object(JSON.parse(await boundedText(response)), "owned Kubo block error").Message;
462
+ if (typeof detail === "string" &&
463
+ detail.startsWith("block was not found locally (offline):"))
464
+ throw new BlockUnavailable(error);
510
465
  }
511
- chunks.push(part.value);
466
+ await response.body?.cancel();
467
+ if (!offline && [404, 500].includes(response.status))
468
+ throw new BlockUnavailable(error);
469
+ throw new HostError(error);
512
470
  }
513
- }
514
- finally {
515
- reader.releaseLock();
516
- }
517
- const bytes = new Uint8Array(size);
518
- let offset = 0;
519
- for (const chunk of chunks) {
520
- bytes.set(chunk, offset);
521
- offset += chunk.length;
522
- }
523
- return bytes;
471
+ const stream = response.body;
472
+ const reader = stream.getReader();
473
+ const chunks = [];
474
+ let size = 0;
475
+ try {
476
+ for (;;) {
477
+ const part = await reader.read();
478
+ if (part.done)
479
+ break;
480
+ size += part.value.length;
481
+ if (size > 2 * 1024 * 1024) {
482
+ await reader.cancel();
483
+ throw new HostError("Kubo block exceeds limit.");
484
+ }
485
+ chunks.push(part.value);
486
+ }
487
+ }
488
+ finally {
489
+ reader.releaseLock();
490
+ }
491
+ const bytes = new Uint8Array(size);
492
+ let offset = 0;
493
+ for (const chunk of chunks) {
494
+ bytes.set(chunk, offset);
495
+ offset += chunk.length;
496
+ }
497
+ return bytes;
498
+ }, connected, connect, () => {
499
+ if (fallbackUsed)
500
+ return false;
501
+ fallbackUsed = true;
502
+ return true;
503
+ }, options.signal, diagnostic, detailed);
524
504
  },
525
505
  },
526
506
  };