@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
package/src/config.ts CHANGED
@@ -1,11 +1,13 @@
1
1
  import { homedir } from "node:os";
2
2
  import { join, resolve } from "node:path";
3
+ import { CID } from "multiformats/cid";
3
4
  import { readContentConfiguration } from "@ipab/ipfs-store/node";
4
5
  import type { StoreConfiguration } from "@ipab/ipfs-store";
5
6
  import { HostError, object, syntax } from "./errors.js";
6
7
 
7
8
  export type ConfigKey =
8
9
  | "swarm.default"
10
+ | "swarm.listen"
9
11
  | "swarm.cacheTtl"
10
12
  | "swarm.forceRefresh"
11
13
  | "store.gateway"
@@ -30,6 +32,7 @@ export interface ConfigItem {
30
32
  }
31
33
  export const defaults: Record<ConfigKey, ConfigValue> = {
32
34
  "swarm.default": null,
35
+ "swarm.listen": "lan",
33
36
  "swarm.cacheTtl": 300,
34
37
  "swarm.forceRefresh": false,
35
38
  "store.gateway": null,
@@ -41,6 +44,7 @@ export const defaults: Record<ConfigKey, ConfigValue> = {
41
44
  "bundle.outputDir": "dist",
42
45
  };
43
46
  const environments: Partial<Record<ConfigKey, string>> = {
47
+ "swarm.listen": "IPAB_SWARM_LISTEN",
44
48
  "swarm.cacheTtl": "IPAB_SWARM_CACHE_TTL",
45
49
  "swarm.forceRefresh": "IPAB_SWARM_FORCE_REFRESH",
46
50
  "store.gateway": "IPAB_STORE_GATEWAY",
@@ -121,7 +125,9 @@ export function parseValue(
121
125
  ): ConfigValue {
122
126
  if (text && typeof value === "string") {
123
127
  if (key.startsWith("swarm.") && value === "default")
124
- return key === "swarm.cacheTtl" || key === "swarm.forceRefresh"
128
+ return key === "swarm.cacheTtl" ||
129
+ key === "swarm.forceRefresh" ||
130
+ key === "swarm.listen"
125
131
  ? defaults[key]
126
132
  : null;
127
133
  if (key === "history.enabled" || key === "swarm.forceRefresh") {
@@ -175,6 +181,10 @@ export function parseValue(
175
181
  if (typeof value === "boolean") return value;
176
182
  syntax("swarm.forceRefresh requires true or false.");
177
183
  }
184
+ if (key === "swarm.listen") {
185
+ if (value === "lan" || value === "loopback") return value;
186
+ syntax("swarm.listen requires lan or loopback.");
187
+ }
178
188
  if (key.startsWith("swarm.") && value === null) return null;
179
189
  if (key === "swarm.default" && typeof value === "string") {
180
190
  return swarmUrl(value);
@@ -214,6 +224,17 @@ export function parseValue(
214
224
  );
215
225
  }
216
226
 
227
+ export function rejectLegacySwarmCid(value: string): void {
228
+ try {
229
+ CID.parse(value);
230
+ } catch {
231
+ return;
232
+ }
233
+ throw new HostError(
234
+ "The old Swarm CID protocol is unsupported. Ask the Owner for the Swarm configuration URL.",
235
+ );
236
+ }
237
+
217
238
  export function swarmUrl(value: string): string {
218
239
  try {
219
240
  const url = new URL(value);
@@ -224,13 +245,14 @@ export function swarmUrl(value: string): string {
224
245
  url.search ||
225
246
  url.hash ||
226
247
  url.toString() !== value ||
227
- !/^\/v1\/[A-Za-z0-9_-]{43}\/[A-Za-z0-9_-]{43}$/.test(url.pathname)
248
+ !/^\/v1\/[a-f0-9]{16}\/[a-f0-9]{16}$/.test(url.pathname)
228
249
  )
229
250
  throw new Error();
230
251
  return value;
231
252
  } catch {
253
+ rejectLegacySwarmCid(value);
232
254
  return syntax(
233
- "Swarm requires an exact /v1/{scope}/{variable} configuration URL; old CID protocol is unsupported.",
255
+ "Swarm requires an exact /v1/{scope}/{variable} configuration URL (HTTPS or HTTP loopback), with two 16-character lowercase hex IDs and no credentials, query or fragment.",
234
256
  );
235
257
  }
236
258
  }
@@ -0,0 +1,11 @@
1
+ export interface BundleInspection {
2
+ targetCid: string;
3
+ cid: string;
4
+ title: string;
5
+ description: string;
6
+ entry: string;
7
+ contentType: string;
8
+ schemaCid: string;
9
+ files: string[];
10
+ swarm?: string;
11
+ }
package/src/context.ts CHANGED
@@ -1,9 +1,16 @@
1
1
  import { HostError } from "./errors.js";
2
2
  import { CHUNK_BYTES, relativePath } from "./space.js";
3
3
 
4
+ import type { BundleInspection } from "./context-types.js";
5
+ export type { BundleInspection } from "./context-types.js";
6
+
4
7
  export interface AppContext {
5
8
  readonly appCid: string;
6
9
  resolvePin(name: string): Promise<string | undefined>;
10
+ inspectBundle(
11
+ reference: string,
12
+ options?: { signal?: AbortSignal; swarm?: string },
13
+ ): Promise<BundleInspection>;
7
14
  readFile(
8
15
  rootCid: string,
9
16
  path: string,
@@ -127,6 +134,39 @@ export function createContext(port: Port): {
127
134
  }
128
135
  };
129
136
  const context: AppContext = {
137
+ async inspectBundle(reference, options = {}) {
138
+ if (!reference || reference.length > 2048)
139
+ throw new HostError(
140
+ "Bundle reference must contain 1..2048 characters.",
141
+ );
142
+ const result = await rpc(
143
+ "inspectBundle",
144
+ {
145
+ reference,
146
+ ...(options.swarm ? { swarm: options.swarm } : {}),
147
+ },
148
+ options.signal,
149
+ );
150
+ if (!result || typeof result !== "object")
151
+ throw new HostError("Invalid Bundle inspection response.");
152
+ const data = result as Partial<BundleInspection>;
153
+ if (
154
+ ![
155
+ "targetCid",
156
+ "cid",
157
+ "title",
158
+ "description",
159
+ "entry",
160
+ "contentType",
161
+ "schemaCid",
162
+ ].every((key) => typeof Reflect.get(data, key) === "string") ||
163
+ !Array.isArray(data.files) ||
164
+ !data.files.every((path) => typeof path === "string") ||
165
+ (data.swarm !== undefined && typeof data.swarm !== "string")
166
+ )
167
+ throw new HostError("Invalid Bundle inspection response.");
168
+ return data as BundleInspection;
169
+ },
130
170
  async resolvePin(name) {
131
171
  if (!name || name.length > 256)
132
172
  throw new HostError("Pin name must contain 1..256 characters.");
package/src/identity.ts CHANGED
@@ -29,6 +29,19 @@ export async function protectedPath(
29
29
  await requireAccountOnly(path);
30
30
  }
31
31
 
32
+ export interface ProtectedPath {
33
+ path: string;
34
+ directory?: boolean;
35
+ }
36
+
37
+ export async function protectedPaths(
38
+ paths: readonly ProtectedPath[],
39
+ ): Promise<void> {
40
+ for (const entry of paths)
41
+ await regularPath(entry.path, entry.directory ?? false);
42
+ await requireAccountOnlyMany(paths.map((entry) => entry.path));
43
+ }
44
+
32
45
  async function regularPath(path: string, directory: boolean): Promise<void> {
33
46
  const stat = await lstat(path);
34
47
  if (
package/src/ipc.ts CHANGED
@@ -1,8 +1,9 @@
1
1
  import type { ChildProcess } from "node:child_process";
2
2
  import type { IpfsStore } from "@ipab/ipfs-store";
3
+ import { openBundle } from "@ipab/bundle";
3
4
  import { CID } from "multiformats/cid";
4
5
  import { HostError, message, object } from "./errors.js";
5
- import { requestFrame, type Reply } from "./context.js";
6
+ import { requestFrame, type BundleInspection, type Reply } from "./context.js";
6
7
  import { CHUNK_BYTES, type OutputSpace, relativePath } from "./space.js";
7
8
  import type { Ownership } from "./history.js";
8
9
 
@@ -78,6 +79,11 @@ export class ContextServer {
78
79
  readonly resolvePin: (name: string) => string | undefined = () => {
79
80
  throw new HostError("Pin lookup is unavailable in this context.");
80
81
  },
82
+ readonly resolveBundleReference?: (
83
+ reference: string,
84
+ signal: AbortSignal,
85
+ swarm?: string,
86
+ ) => Promise<Pick<BundleInspection, "cid" | "targetCid" | "swarm">>,
81
87
  ) {
82
88
  child.on("message", this.receive);
83
89
  }
@@ -156,6 +162,49 @@ export class ContextServer {
156
162
  ): Promise<unknown> {
157
163
  signal.throwIfAborted();
158
164
  if (operation === "identity") return this.appCid;
165
+ if (operation === "inspectBundle") {
166
+ const request = object(args, "Bundle inspection request");
167
+ if (
168
+ typeof request.reference !== "string" ||
169
+ !request.reference ||
170
+ request.reference.length > 2048
171
+ )
172
+ throw new HostError(
173
+ "Bundle reference must contain 1..2048 characters.",
174
+ );
175
+ if (
176
+ request.swarm !== undefined &&
177
+ (typeof request.swarm !== "string" || request.swarm.length > 2048)
178
+ )
179
+ throw new HostError("Invalid Bundle inspection Swarm.");
180
+ if (!this.resolveBundleReference)
181
+ throw new HostError(
182
+ "Bundle inspection is unavailable in this context.",
183
+ );
184
+ const resolved = await this.resolveBundleReference(
185
+ request.reference,
186
+ signal,
187
+ request.swarm,
188
+ );
189
+ await this.owner.retain([resolved.targetCid, resolved.cid], signal);
190
+ const bundle = await openBundle(CID.parse(resolved.cid), {
191
+ signal,
192
+ resolveCid: (cid, options) =>
193
+ this.store.block.get(cid.toString(), options),
194
+ });
195
+ const result: BundleInspection = {
196
+ ...resolved,
197
+ title: bundle.manifest.title,
198
+ description: bundle.manifest.description,
199
+ entry: bundle.manifest.entry,
200
+ contentType: bundle.schema.type.contentType,
201
+ schemaCid: bundle.schemaKey,
202
+ files: [...bundle.files],
203
+ };
204
+ if (Buffer.byteLength(JSON.stringify(result)) > 1024 * 1024)
205
+ throw new HostError("Bundle inspection exceeds 1 MiB.");
206
+ return result;
207
+ }
159
208
  if (operation === "resolvePin") {
160
209
  if (typeof args !== "string" || !args || args.length > 256)
161
210
  throw new HostError("Pin name must contain 1..256 characters.");
@@ -0,0 +1,452 @@
1
+ import { execFile } from "node:child_process";
2
+ import { createHash, randomUUID } from "node:crypto";
3
+ import { constants } from "node:fs";
4
+ import {
5
+ access,
6
+ chmod,
7
+ link,
8
+ lstat,
9
+ mkdir,
10
+ open,
11
+ readdir,
12
+ rename,
13
+ rm,
14
+ } from "node:fs/promises";
15
+ import { join } from "node:path";
16
+ import { promisify } from "node:util";
17
+ import { boundedText } from "@ipab/bundle/pointer/scope";
18
+ import { nodeError } from "./authoring.js";
19
+ import { HostError } from "./errors.js";
20
+ import { protectedPath, secureNew } from "./identity.js";
21
+ import { KUBO_VERSION, releaseDigests } from "./kubo-release.js";
22
+ import {
23
+ privateDirectory,
24
+ readPrivate,
25
+ withPrivateLock,
26
+ writePrivate,
27
+ } from "./swarm-files.js";
28
+
29
+ const run = promisify(execFile);
30
+ const MAX_ARCHIVE = 150 * 1024 * 1024;
31
+ const journal = "installing.json";
32
+ const record = "installation.json";
33
+ interface Installation {
34
+ version: string;
35
+ hash: string;
36
+ }
37
+ export interface InstallOptions {
38
+ archive?: string;
39
+ diagnostic?: (line: string, progress?: boolean) => void;
40
+ signal?: AbortSignal;
41
+ }
42
+
43
+ function failure(cause: unknown): string {
44
+ if (cause instanceof HostError) return cause.message;
45
+ const queue = [cause];
46
+ const codes = new Set<string>();
47
+ for (let i = 0; i < queue.length && i < 8; i++) {
48
+ const error = queue[i];
49
+ if (!(error instanceof Error)) continue;
50
+ if (
51
+ "code" in error &&
52
+ typeof error.code === "string" &&
53
+ /^[A-Z][A-Z0-9_]{1,39}$/.test(error.code)
54
+ )
55
+ codes.add(error.code);
56
+ if (
57
+ "cmd" in error &&
58
+ "code" in error &&
59
+ typeof error.code === "number" &&
60
+ Number.isSafeInteger(error.code)
61
+ )
62
+ codes.add(`process exit ${error.code}`);
63
+ if (error.name === "TimeoutError" || error.name === "AbortError")
64
+ codes.add(error.name);
65
+ if (error.cause) queue.push(error.cause);
66
+ if (error instanceof AggregateError)
67
+ queue.push(...(error.errors as unknown[]).slice(0, 4));
68
+ }
69
+ if (codes.size) return [...codes].join(", ");
70
+ if (cause instanceof SyntaxError) return "invalid data";
71
+ if (
72
+ cause instanceof Error &&
73
+ /permission|account.only|current (?:OS )?account/i.test(cause.message)
74
+ )
75
+ return "permission denied or unsafe ownership";
76
+ return "operation failed";
77
+ }
78
+ export function setupFailure(
79
+ phase: string,
80
+ source: string,
81
+ cause: unknown,
82
+ ): HostError {
83
+ return new HostError(
84
+ `Kubo ${KUBO_VERSION} ${process.platform}-${process.arch}, ${phase} (${source}): ${failure(cause)}. Check the indicated source or account permissions and retry setup.`,
85
+ 1,
86
+ "KUBO_SETUP_FAILED",
87
+ phase,
88
+ );
89
+ }
90
+ async function exists(path: string) {
91
+ try {
92
+ await lstat(path);
93
+ return true;
94
+ } catch (cause) {
95
+ if (nodeError(cause, "ENOENT")) return false;
96
+ throw cause;
97
+ }
98
+ }
99
+ async function* fileBytes(path: string, limit: number) {
100
+ const stat = await lstat(path);
101
+ if (!stat.isFile())
102
+ throw new HostError("Expected a regular file, not a link or directory.");
103
+ if (stat.size > limit) throw new HostError("Kubo file exceeds limit.");
104
+ const handle = await open(path, "r");
105
+ try {
106
+ const buffer = Buffer.alloc(128 * 1024);
107
+ let total = 0;
108
+ for (;;) {
109
+ const { bytesRead } = await handle.read(buffer);
110
+ if (!bytesRead) return;
111
+ total += bytesRead;
112
+ if (total > limit) throw new HostError("Kubo file exceeds limit.");
113
+ yield buffer.subarray(0, bytesRead);
114
+ }
115
+ } finally {
116
+ await handle.close();
117
+ }
118
+ }
119
+ async function digest(path: string, limit: number) {
120
+ const hash = createHash("sha256");
121
+ for await (const chunk of fileBytes(path, limit)) hash.update(chunk);
122
+ return hash.digest("hex");
123
+ }
124
+ async function verifyProgram(executable: string, installed: Installation) {
125
+ if (
126
+ installed.version !== KUBO_VERSION ||
127
+ installed.hash !== (await digest(executable, 512 * 1024 * 1024))
128
+ )
129
+ throw new HostError(
130
+ "Kubo installation integrity mismatch; do not use this binary.",
131
+ );
132
+ if (process.platform !== "win32") await access(executable, constants.X_OK);
133
+ }
134
+ function deadline(ms: number, signal?: AbortSignal) {
135
+ const timeout = AbortSignal.timeout(ms);
136
+ return signal ? AbortSignal.any([signal, timeout]) : timeout;
137
+ }
138
+ async function officialAsset(
139
+ filename: string,
140
+ expected: string,
141
+ signal?: AbortSignal,
142
+ ) {
143
+ const release = await fetch(
144
+ `https://api.github.com/repos/ipfs/kubo/releases/tags/v${KUBO_VERSION}`,
145
+ {
146
+ redirect: "error",
147
+ signal: deadline(30_000, signal),
148
+ headers: { accept: "application/vnd.github+json" },
149
+ },
150
+ );
151
+ if (!release.ok) {
152
+ await release.body?.cancel();
153
+ throw new HostError(
154
+ `Could not verify official Kubo release (HTTP ${release.status}).`,
155
+ );
156
+ }
157
+ const metadata = JSON.parse(await boundedText(release)) as {
158
+ tag_name: string;
159
+ draft: boolean;
160
+ prerelease: boolean;
161
+ assets: {
162
+ name: string;
163
+ digest: string;
164
+ size: number;
165
+ browser_download_url: string;
166
+ }[];
167
+ };
168
+ const url = `https://github.com/ipfs/kubo/releases/download/v${KUBO_VERSION}/${filename}`;
169
+ const assets = metadata.assets.filter((item) => item.name === filename);
170
+ if (
171
+ metadata.tag_name !== `v${KUBO_VERSION}` ||
172
+ metadata.draft !== false ||
173
+ metadata.prerelease !== false ||
174
+ assets.length !== 1 ||
175
+ assets[0]?.digest !== `sha256:${expected}` ||
176
+ !Number.isSafeInteger(assets[0].size) ||
177
+ assets[0].size <= 0 ||
178
+ assets[0].size > MAX_ARCHIVE ||
179
+ assets[0].browser_download_url !== url
180
+ )
181
+ throw new HostError(
182
+ "Official stable Kubo archive/digest/size unavailable or inconsistent with the bundled release.",
183
+ );
184
+ return { url, size: assets[0].size };
185
+ }
186
+ async function transfer(
187
+ target: string,
188
+ source: { archive: string } | { url: string; size: number },
189
+ options: InstallOptions,
190
+ ) {
191
+ const handle = await open(target, "wx", 0o600);
192
+ const controller = new AbortController();
193
+ const signal = options.signal
194
+ ? AbortSignal.any([options.signal, controller.signal])
195
+ : controller.signal;
196
+ let progress: ReturnType<typeof setInterval> | undefined;
197
+ let total = 0;
198
+ let receivedAt = Date.now();
199
+ let startedAt: number | undefined;
200
+ try {
201
+ await secureNew(target);
202
+ let stream: AsyncIterable<Uint8Array>;
203
+ if ("archive" in source) stream = fileBytes(source.archive, MAX_ARCHIVE);
204
+ else {
205
+ const totalMiB = (source.size / (1024 * 1024)).toFixed(1);
206
+ options.diagnostic?.(
207
+ `Downloading ${source.url.split("/").at(-1)} from GitHub (${totalMiB} MiB)...`,
208
+ );
209
+ if (options.diagnostic)
210
+ progress = setInterval(() => {
211
+ try {
212
+ const now = Date.now();
213
+ const idle = Math.floor((now - receivedAt) / 1000);
214
+ const waiting =
215
+ idle >= 5 ? `; waiting for data (${idle}s without new data)` : "";
216
+ const elapsed =
217
+ startedAt === undefined ? 0 : (now - startedAt) / 1000;
218
+ let eta = idle >= 5 ? "unavailable" : "estimating";
219
+ if (total > 0 && elapsed > 0 && idle < 5) {
220
+ const seconds = Math.ceil(
221
+ (Math.max(0, source.size - total) * elapsed) / total,
222
+ );
223
+ eta = `~${seconds < 60 ? `${seconds}s` : `${Math.floor(seconds / 60)}m ${seconds % 60}s`}`;
224
+ }
225
+ options.diagnostic?.(
226
+ `Kubo: ${(total / (1024 * 1024)).toFixed(1)}/${totalMiB} MiB (${((total * 100) / source.size).toFixed(1)}%); ETA ${eta}${waiting}`,
227
+ true,
228
+ );
229
+ } catch (cause) {
230
+ controller.abort(cause);
231
+ }
232
+ }, 5_000);
233
+ const response = await fetch(source.url, {
234
+ signal,
235
+ });
236
+ if (!response.ok || !response.body) {
237
+ await response.body?.cancel();
238
+ throw new HostError(`Kubo download failed (HTTP ${response.status}).`);
239
+ }
240
+ startedAt = Date.now();
241
+ stream = response.body as ReadableStream<Uint8Array>;
242
+ }
243
+ for await (const chunk of stream) {
244
+ signal.throwIfAborted();
245
+ total += chunk.byteLength;
246
+ if (total > MAX_ARCHIVE)
247
+ throw new HostError("Kubo archive exceeds limit.");
248
+ await handle.writeFile(chunk);
249
+ receivedAt = Date.now();
250
+ }
251
+ signal.throwIfAborted();
252
+ if ("url" in source && total !== source.size)
253
+ throw new HostError("Kubo archive size mismatch.");
254
+ await handle.sync();
255
+ } catch (cause) {
256
+ signal.throwIfAborted();
257
+ throw cause;
258
+ } finally {
259
+ clearInterval(progress);
260
+ await handle.close();
261
+ }
262
+ return total;
263
+ }
264
+ async function clean(directory: string, stage: string) {
265
+ await rm(stage, { recursive: true, force: true });
266
+ await rm(join(directory, journal));
267
+ }
268
+ async function recover(
269
+ directory: string,
270
+ executable: string,
271
+ installed: Installation | undefined,
272
+ ) {
273
+ const intent = await readPrivate<unknown>(directory, journal);
274
+ if (intent === undefined) return installed;
275
+ if (
276
+ typeof intent !== "object" ||
277
+ intent === null ||
278
+ !("stage" in intent) ||
279
+ typeof intent.stage !== "string" ||
280
+ !/^install-[a-f0-9]{8}(?:-[a-f0-9]{4}){3}-[a-f0-9]{12}$/.test(intent.stage)
281
+ )
282
+ throw new HostError(
283
+ "Unrecognized Kubo installation journal; inspect it manually.",
284
+ );
285
+ const stage = join(directory, intent.stage);
286
+ if (await exists(stage)) await protectedPath(stage, true);
287
+ if (!installed && (await exists(executable))) {
288
+ const pending = await readPrivate<Installation>(stage, record, [
289
+ { path: executable },
290
+ ]);
291
+ if (!pending)
292
+ throw new HostError(
293
+ "Unrecorded Kubo executable; move it aside manually. It was not adopted.",
294
+ );
295
+ await verifyProgram(executable, pending);
296
+ await rename(join(stage, record), join(directory, record));
297
+ installed = pending;
298
+ }
299
+ await clean(directory, stage);
300
+ return installed;
301
+ }
302
+ export async function kuboBinary(
303
+ stateDir: string,
304
+ options: InstallOptions = {},
305
+ ): Promise<string> {
306
+ let phase = "installation",
307
+ source = "protected local installation";
308
+ try {
309
+ options.signal?.throwIfAborted();
310
+ const directory = await privateDirectory(stateDir, "kubo-bin");
311
+ options.diagnostic?.(
312
+ "Checking the Kubo installation (local lock wait: up to 30s)...",
313
+ );
314
+ const platform =
315
+ process.platform === "win32" ? "windows" : process.platform;
316
+ if (
317
+ !["windows", "darwin", "linux"].includes(platform) ||
318
+ !["x64", "arm64"].includes(process.arch)
319
+ )
320
+ throw new HostError("Unsupported Kubo platform.");
321
+ const arch = process.arch === "x64" ? "amd64" : "arm64";
322
+ const filename = `kubo_v${KUBO_VERSION}_${platform}-${arch}.${platform === "windows" ? "zip" : "tar.gz"}`;
323
+ const expected = releaseDigests[filename];
324
+ if (!expected || !/^[a-f0-9]{64}$/.test(expected))
325
+ throw new HostError(
326
+ "No trusted archive digest for this release/platform.",
327
+ );
328
+ const program = platform === "windows" ? "ipfs.exe" : "ipfs";
329
+ const executable = join(directory, program);
330
+ const install = async () => {
331
+ let installed = await readPrivate<Installation>(directory, record, [
332
+ { path: executable },
333
+ ]);
334
+ if (installed !== undefined) {
335
+ options.diagnostic?.(`Verifying installed Kubo ${KUBO_VERSION}...`);
336
+ await verifyProgram(executable, installed);
337
+ }
338
+ installed = await recover(directory, executable, installed);
339
+ if (
340
+ options.diagnostic &&
341
+ (await readdir(directory)).some((name) =>
342
+ /^(?:extract-[\w-]{43}|[\w-]{43}\.(?:zip|tar\.gz)|(?:install-|\.write-)[a-f0-9-]{36})$/.test(
343
+ name,
344
+ ),
345
+ )
346
+ )
347
+ options.diagnostic(
348
+ "Untracked Kubo staging files were left untouched. Inspect kubo-bin manually; do not delete the verified installation.",
349
+ );
350
+ if (installed) {
351
+ if (options.archive !== undefined) {
352
+ phase = "archive verification";
353
+ source = "local archive";
354
+ if ((await digest(options.archive, MAX_ARCHIVE)) !== expected)
355
+ throw new HostError("Kubo archive checksum mismatch.");
356
+ }
357
+ return executable;
358
+ }
359
+ if (await exists(executable))
360
+ throw new HostError(
361
+ "Unrecorded Kubo executable; move it aside manually. It was not adopted.",
362
+ );
363
+ let input: { archive: string } | { url: string; size: number };
364
+ if (options.archive !== undefined) input = { archive: options.archive };
365
+ else {
366
+ phase = "release metadata";
367
+ source = "api.github.com/ipfs/kubo";
368
+ options.diagnostic?.(
369
+ `Checking official Kubo ${KUBO_VERSION} release (timeout: 30s)...`,
370
+ );
371
+ input = await officialAsset(filename, expected, options.signal);
372
+ }
373
+ phase = "installation";
374
+ source = "protected local staging";
375
+ const name = `install-${randomUUID()}`,
376
+ stage = join(directory, name);
377
+ if (await exists(stage))
378
+ throw new HostError("Staging path already exists; retry setup.");
379
+ await writePrivate(directory, journal, { stage: name });
380
+ let placed = false,
381
+ created = false;
382
+ try {
383
+ await mkdir(stage, { mode: 0o700 });
384
+ created = true;
385
+ await secureNew(stage, true);
386
+ const archive = join(stage, filename);
387
+ phase = "archive transfer";
388
+ source = "archive" in input ? "local archive" : "github.com/ipfs/kubo";
389
+ if ("archive" in input)
390
+ options.diagnostic?.("Copying the local Kubo archive...");
391
+ const total = await transfer(archive, input, options);
392
+ phase = "archive verification";
393
+ options.diagnostic?.(
394
+ `Kubo download complete: ${(total / (1024 * 1024)).toFixed(1)} MiB. Verifying checksum...`,
395
+ );
396
+ if ((await digest(archive, MAX_ARCHIVE)) !== expected)
397
+ throw new HostError("Kubo archive checksum mismatch.");
398
+ phase = "extraction";
399
+ source = "verified release archive";
400
+ options.diagnostic?.("Extracting and verifying the Kubo executable...");
401
+ const member = `kubo/${program}`;
402
+ await run("tar", ["-xf", archive, "-C", stage, member], {
403
+ signal: options.signal,
404
+ timeout: 30_000,
405
+ windowsHide: true,
406
+ });
407
+ const extracted = join(stage, "kubo", program);
408
+ if (!(await lstat(extracted)).isFile())
409
+ throw new HostError("Invalid Kubo executable.");
410
+ await secureNew(extracted);
411
+ if (platform !== "windows") await chmod(extracted, 0o700);
412
+ phase = "executable verification";
413
+ source = "staged Kubo program";
414
+ const version = await run(extracted, ["version", "--number"], {
415
+ signal: options.signal,
416
+ env: {
417
+ ...process.env,
418
+ HOME: stage,
419
+ USERPROFILE: stage,
420
+ IPFS_PATH: join(stage, "version-repo"),
421
+ },
422
+ timeout: 10_000,
423
+ windowsHide: true,
424
+ });
425
+ if (version.stdout.trim() !== KUBO_VERSION)
426
+ throw new HostError("Kubo executable version mismatch.");
427
+ const verified = {
428
+ version: KUBO_VERSION,
429
+ hash: await digest(extracted, 512 * 1024 * 1024),
430
+ };
431
+ phase = "installation";
432
+ source = "protected local installation";
433
+ await writePrivate(stage, record, verified);
434
+ // Atomic and exclusive: never overwrite a binary placed by another actor.
435
+ await link(extracted, executable);
436
+ placed = true;
437
+ await rename(join(stage, record), join(directory, record));
438
+ placed = false;
439
+ return executable;
440
+ } finally {
441
+ // If rollback itself fails, retain the journal and verified candidate record for recovery.
442
+ if (placed) await rm(executable);
443
+ if (created) await clean(directory, stage);
444
+ else await rm(join(directory, journal));
445
+ }
446
+ };
447
+ return await withPrivateLock(directory, install, options.signal);
448
+ } catch (cause) {
449
+ options.signal?.throwIfAborted();
450
+ throw setupFailure(phase, source, cause);
451
+ }
452
+ }