@ipab/cli 0.1.0-rc.3 → 0.1.0-rc.4

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.
package/src/config.ts CHANGED
@@ -6,6 +6,7 @@ import { HostError, object, syntax } from "./errors.js";
6
6
 
7
7
  export type ConfigKey =
8
8
  | "swarm.default"
9
+ | "swarm.listen"
9
10
  | "swarm.cacheTtl"
10
11
  | "swarm.forceRefresh"
11
12
  | "store.gateway"
@@ -30,6 +31,7 @@ export interface ConfigItem {
30
31
  }
31
32
  export const defaults: Record<ConfigKey, ConfigValue> = {
32
33
  "swarm.default": null,
34
+ "swarm.listen": "lan",
33
35
  "swarm.cacheTtl": 300,
34
36
  "swarm.forceRefresh": false,
35
37
  "store.gateway": null,
@@ -41,6 +43,7 @@ export const defaults: Record<ConfigKey, ConfigValue> = {
41
43
  "bundle.outputDir": "dist",
42
44
  };
43
45
  const environments: Partial<Record<ConfigKey, string>> = {
46
+ "swarm.listen": "IPAB_SWARM_LISTEN",
44
47
  "swarm.cacheTtl": "IPAB_SWARM_CACHE_TTL",
45
48
  "swarm.forceRefresh": "IPAB_SWARM_FORCE_REFRESH",
46
49
  "store.gateway": "IPAB_STORE_GATEWAY",
@@ -121,7 +124,9 @@ export function parseValue(
121
124
  ): ConfigValue {
122
125
  if (text && typeof value === "string") {
123
126
  if (key.startsWith("swarm.") && value === "default")
124
- return key === "swarm.cacheTtl" || key === "swarm.forceRefresh"
127
+ return key === "swarm.cacheTtl" ||
128
+ key === "swarm.forceRefresh" ||
129
+ key === "swarm.listen"
125
130
  ? defaults[key]
126
131
  : null;
127
132
  if (key === "history.enabled" || key === "swarm.forceRefresh") {
@@ -175,6 +180,10 @@ export function parseValue(
175
180
  if (typeof value === "boolean") return value;
176
181
  syntax("swarm.forceRefresh requires true or false.");
177
182
  }
183
+ if (key === "swarm.listen") {
184
+ if (value === "lan" || value === "loopback") return value;
185
+ syntax("swarm.listen requires lan or loopback.");
186
+ }
178
187
  if (key.startsWith("swarm.") && value === null) return null;
179
188
  if (key === "swarm.default" && typeof value === "string") {
180
189
  return swarmUrl(value);
@@ -224,7 +233,7 @@ export function swarmUrl(value: string): string {
224
233
  url.search ||
225
234
  url.hash ||
226
235
  url.toString() !== value ||
227
- !/^\/v1\/[A-Za-z0-9_-]{43}\/[A-Za-z0-9_-]{43}$/.test(url.pathname)
236
+ !/^\/v1\/[a-f0-9]{16}\/[a-f0-9]{16}$/.test(url.pathname)
228
237
  )
229
238
  throw new Error();
230
239
  return value;
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/kubo.ts CHANGED
@@ -20,7 +20,7 @@ import { createServer } from "node:net";
20
20
  import { networkInterfaces } from "node:os";
21
21
  import { base58btc } from "multiformats/bases/base58";
22
22
  import { boundedText, uniqueId } from "@ipab/bundle/pointer/scope";
23
- import { protectedPath, secureNew } from "./identity.js";
23
+ import { protectedPath, protectedPaths, secureNew } from "./identity.js";
24
24
  import {
25
25
  privateDirectory,
26
26
  readPrivate,
@@ -31,6 +31,15 @@ import { HostError, object } from "./errors.js";
31
31
  import { nodeError } from "./authoring.js";
32
32
 
33
33
  export const KUBO_VERSION = "0.43.2";
34
+ // Windows Firewall creates an inbound rule for every program that listens on a
35
+ // non-loopback address, so each new managed binary location prompts for
36
+ // authorization. Binding only 127.0.0.1 creates no rule at all, which keeps
37
+ // same-host private networks (and automated tests) unattended. A LAN swarms
38
+ // still advertises private IPv4 addresses as peers dial *in* to that listener.
39
+ export type ListenMode = "lan" | "loopback";
40
+ function swarmAddress(listen: ListenMode, port: number): string {
41
+ return `/ip4/${listen === "loopback" ? "127.0.0.1" : "0.0.0.0"}/tcp/${port}`;
42
+ }
34
43
  const run = promisify(execFile);
35
44
  const hash = (data: Uint8Array) =>
36
45
  createHash("sha256").update(data).digest("hex");
@@ -47,6 +56,7 @@ export interface NodeRecord {
47
56
  auth: string;
48
57
  epoch?: number;
49
58
  pid?: number;
59
+ listen?: ListenMode;
50
60
  }
51
61
  export interface KuboNode {
52
62
  repo: string;
@@ -59,7 +69,7 @@ export interface KuboNode {
59
69
  }
60
70
  function nodeRecord(value: unknown, scope: string): NodeRecord {
61
71
  const record = object(value, "protected managed-node record");
62
- const { peerId, api, gateway, swarm, auth, pid, epoch } = record;
72
+ const { peerId, api, gateway, swarm, auth, pid, epoch, listen } = record;
63
73
  if (
64
74
  Object.keys(record).some(
65
75
  (key) =>
@@ -72,6 +82,7 @@ function nodeRecord(value: unknown, scope: string): NodeRecord {
72
82
  "auth",
73
83
  "pid",
74
84
  "epoch",
85
+ "listen",
75
86
  ].includes(key),
76
87
  ) ||
77
88
  record.scope !== scope ||
@@ -89,7 +100,10 @@ function nodeRecord(value: unknown, scope: string): NodeRecord {
89
100
  (pid !== undefined &&
90
101
  (typeof pid !== "number" || !Number.isSafeInteger(pid) || pid <= 0)) ||
91
102
  (epoch !== undefined &&
92
- (typeof epoch !== "number" || !Number.isSafeInteger(epoch) || epoch < 1))
103
+ (typeof epoch !== "number" ||
104
+ !Number.isSafeInteger(epoch) ||
105
+ epoch < 1)) ||
106
+ (listen !== undefined && listen !== "lan" && listen !== "loopback")
93
107
  )
94
108
  throw new HostError(
95
109
  "Invalid protected managed-node record; old node formats are unsupported.",
@@ -103,6 +117,7 @@ function nodeRecord(value: unknown, scope: string): NodeRecord {
103
117
  auth,
104
118
  ...(pid !== undefined ? { pid } : {}),
105
119
  ...(epoch !== undefined ? { epoch } : {}),
120
+ ...(listen !== undefined ? { listen } : {}),
106
121
  };
107
122
  }
108
123
  export async function kuboBinary(stateDir: string): Promise<string> {
@@ -115,9 +130,9 @@ export async function kuboBinary(stateDir: string): Promise<string> {
115
130
  const installed = await readPrivate<Installation>(
116
131
  directory,
117
132
  "installation.json",
133
+ [{ path: executable }],
118
134
  );
119
135
  if (installed) {
120
- await protectedPath(executable);
121
136
  if (
122
137
  installed.version !== KUBO_VERSION ||
123
138
  installed.hash !== hash(await readFile(executable))
@@ -266,22 +281,36 @@ async function freePort(): Promise<number> {
266
281
  export async function prepareNode(
267
282
  stateDir: string,
268
283
  scope: string,
284
+ listen: ListenMode = "lan",
269
285
  ): Promise<KuboNode> {
270
286
  if (!/^[a-f0-9]{64}$/.test(scope))
271
287
  throw new HostError("Invalid service-bound local Scope identity.");
272
288
  const binary = await kuboBinary(stateDir);
273
- return prepareWithBinary(stateDir, scope, binary);
289
+ return prepareWithBinary(stateDir, scope, binary, listen);
274
290
  }
275
291
  async function prepareWithBinary(
276
292
  stateDir: string,
277
293
  scope: string,
278
294
  binary: string,
295
+ listen: ListenMode,
279
296
  ): Promise<KuboNode> {
280
- const parent = await privateDirectory(stateDir, "swarm-nodes");
281
- const directory = await privateDirectory(parent, scope);
297
+ const parent = join(stateDir, "swarm-nodes");
298
+ const directory = join(parent, scope);
299
+ const repo = join(directory, "repo");
300
+ try {
301
+ await protectedPaths(
302
+ [parent, directory, repo].map((path) => ({ path, directory: true })),
303
+ );
304
+ } catch (cause) {
305
+ if (!nodeError(cause, "ENOENT")) throw cause;
306
+ await privateDirectory(stateDir, "swarm-nodes");
307
+ await privateDirectory(parent, scope);
308
+ await privateDirectory(directory, "repo");
309
+ }
282
310
  return withPrivateLock(directory, async () => {
283
- const repo = await privateDirectory(directory, "repo");
284
- let record = await readPrivate<NodeRecord>(directory, "node.json");
311
+ let record = await readPrivate<NodeRecord>(directory, "node.json", [
312
+ { path: join(repo, "config") },
313
+ ]);
285
314
  if (record === undefined) {
286
315
  try {
287
316
  await lstat(join(repo, "swarm.key"));
@@ -334,11 +363,12 @@ async function prepareWithBinary(
334
363
  gateway: await freePort(),
335
364
  swarm: await freePort(),
336
365
  auth: uniqueId(),
366
+ listen,
337
367
  };
338
368
  config.Addresses = {
339
369
  API: `/ip4/127.0.0.1/tcp/${record.api}`,
340
370
  Gateway: `/ip4/127.0.0.1/tcp/${record.gateway}`,
341
- Swarm: [`/ip4/0.0.0.0/tcp/${record.swarm}`],
371
+ Swarm: [swarmAddress(listen, record.swarm)],
342
372
  };
343
373
  config.Bootstrap = [];
344
374
  config.Swarm.AddrFilters = [];
@@ -365,9 +395,15 @@ async function prepareWithBinary(
365
395
  });
366
396
  await secureNew(join(repo, "config"));
367
397
  await writePrivate(directory, "node.json", record);
398
+ await protectedPath(join(repo, "config"));
368
399
  }
369
- await protectedPath(join(repo, "config"));
370
400
  record = nodeRecord(record, scope);
401
+ // A repo created before listen modes existed binds 0.0.0.0, so it is LAN.
402
+ record.listen ??= "lan";
403
+ if (record.listen !== listen)
404
+ throw new HostError(
405
+ "Managed node already listens in a different mode; existing repos are not rebound.",
406
+ );
371
407
  const local = Object.values(networkInterfaces())
372
408
  .flatMap((items) => items ?? [])
373
409
  .filter(
@@ -379,6 +415,10 @@ async function prepareWithBinary(
379
415
  )
380
416
  .map((item) => item.address)
381
417
  .slice(0, 15);
418
+ // A loopback-only listener is reachable exclusively from this device, so it
419
+ // advertises just loopback; a LAN listener advertises its private IPv4 IPs.
420
+ const reachable =
421
+ record.listen === "loopback" ? ["127.0.0.1"] : [...local, "127.0.0.1"];
382
422
  return {
383
423
  repo,
384
424
  peerId: record.peerId,
@@ -386,7 +426,7 @@ async function prepareWithBinary(
386
426
  gateway: `http://127.0.0.1:${record.gateway}`,
387
427
  auth: record.auth,
388
428
  ...(record.pid !== undefined ? { pid: record.pid } : {}),
389
- addresses: [...new Set([...local, "127.0.0.1"])].map(
429
+ addresses: [...new Set(reachable)].map(
390
430
  (ip) => `/ip4/${ip}/tcp/${record.swarm}/p2p/${record.peerId}`,
391
431
  ),
392
432
  };
@@ -501,12 +541,13 @@ export async function startNode(
501
541
  epoch: number,
502
542
  addresses: readonly string[],
503
543
  diagnostic?: (text: string) => void,
544
+ listen: ListenMode = "lan",
504
545
  ): Promise<KuboNode> {
505
546
  if (!/^[a-f0-9]{64}$/.test(scope))
506
547
  throw new HostError("Invalid service-bound local Scope identity.");
507
548
  if (!/^[a-f0-9]{64}$/.test(key)) throw new HostError("Invalid Swarm key.");
508
549
  const binary = await kuboBinary(stateDir);
509
- const node = await prepareWithBinary(stateDir, scope, binary);
550
+ const node = await prepareWithBinary(stateDir, scope, binary, listen);
510
551
  const directory = join(stateDir, "swarm-nodes", scope);
511
552
  return withPrivateLock(directory, async () => {
512
553
  const record = (await readPrivate<NodeRecord>(directory, "node.json"))!;
package/src/state.ts CHANGED
@@ -180,8 +180,16 @@ export class State {
180
180
  throw error;
181
181
  }
182
182
  }
183
- config(): Partial<Record<ConfigKey, ConfigValue>> {
184
- const entries = this.db.prepare("SELECT key,value FROM config").all();
183
+ config({ includeSecrets = true }: { includeSecrets?: boolean } = {}): Partial<
184
+ Record<ConfigKey, ConfigValue>
185
+ > {
186
+ const entries = this.db
187
+ .prepare(
188
+ includeSecrets
189
+ ? "SELECT key,value FROM config"
190
+ : "SELECT key,value FROM config WHERE key != 'pointers.apiKey'",
191
+ )
192
+ .all();
185
193
  if (
186
194
  entries.some(
187
195
  (row) => row.key === "pointers.apiKey" && row.value !== "null",
@@ -2,7 +2,12 @@ import { lstat, mkdir, open, readFile, rename, unlink } from "node:fs/promises";
2
2
  import { join } from "node:path";
3
3
  import { randomUUID } from "node:crypto";
4
4
  import { DatabaseSync } from "node:sqlite";
5
- import { protectedPath, secureNew } from "./identity.js";
5
+ import {
6
+ protectedPath,
7
+ protectedPaths,
8
+ secureNew,
9
+ type ProtectedPath,
10
+ } from "./identity.js";
6
11
  import { nodeError } from "./authoring.js";
7
12
  import { HostError } from "./errors.js";
8
13
 
@@ -24,13 +29,24 @@ export async function privateDirectory(
24
29
  export async function readPrivate<T>(
25
30
  directory: string,
26
31
  name: string,
32
+ additionalPaths: readonly ProtectedPath[] = [],
27
33
  ): Promise<T | undefined> {
28
34
  const path = join(directory, name);
29
- try {
30
- await protectedPath(path);
31
- } catch (cause) {
32
- if (nodeError(cause, "ENOENT")) return undefined;
33
- throw cause;
35
+ if (additionalPaths.length) {
36
+ try {
37
+ await lstat(path);
38
+ } catch (cause) {
39
+ if (nodeError(cause, "ENOENT")) return undefined;
40
+ throw cause;
41
+ }
42
+ await protectedPaths([{ path }, ...additionalPaths]);
43
+ } else {
44
+ try {
45
+ await protectedPath(path);
46
+ } catch (cause) {
47
+ if (nodeError(cause, "ENOENT")) return undefined;
48
+ throw cause;
49
+ }
34
50
  }
35
51
  if ((await lstat(path)).size > 2 * 1024 * 1024)
36
52
  throw new HostError("Protected state is oversized.");
package/src/swarm.ts CHANGED
@@ -11,10 +11,11 @@ import {
11
11
  memoryTree,
12
12
  streamChunks,
13
13
  } from "@ipab/bundle-builder";
14
- import type { IpfsStore } from "@ipab/ipfs-store";
14
+ import { ContentError, type IpfsStore } from "@ipab/ipfs-store";
15
15
  import {
16
16
  ScopeClient,
17
17
  ScopeApiError,
18
+ RESOURCE_ID_PATTERN,
18
19
  issueScopeCertificate,
19
20
  uniqueId,
20
21
  verifyScopeCertificate,
@@ -63,6 +64,7 @@ import {
63
64
  startNode,
64
65
  validateAddress,
65
66
  type KuboNode,
67
+ type ListenMode,
66
68
  } from "./kubo.js";
67
69
 
68
70
  export interface Member {
@@ -121,6 +123,7 @@ export interface SwarmContext {
121
123
  diagnostic?: (text: string) => void;
122
124
  node?: KuboNode;
123
125
  identity?: Identity;
126
+ listen?: ListenMode;
124
127
  }
125
128
  async function contextIdentity(
126
129
  context: SwarmContext,
@@ -182,7 +185,7 @@ export function canonicalSwarmUrl(value: string): string {
182
185
  url.username ||
183
186
  url.password ||
184
187
  url.toString() !== value ||
185
- !/^\/v1\/[A-Za-z0-9_-]{43}\/[A-Za-z0-9_-]{43}$/.test(url.pathname)
188
+ !/^\/v1\/[a-f0-9]{16}\/[a-f0-9]{16}$/.test(url.pathname)
186
189
  )
187
190
  throw new HostError(
188
191
  "Swarm must be an exact Scope configuration URL; old Swarm CID protocol is unsupported.",
@@ -268,7 +271,7 @@ function parseOrganization(value: unknown, configUrl: string): Organization {
268
271
  typeof data.description !== "string" ||
269
272
  data.description.length > 2048 ||
270
273
  typeof data.headId !== "string" ||
271
- !POINTER_ID_PATTERN.test(data.headId) ||
274
+ !RESOURCE_ID_PATTERN.test(data.headId) ||
272
275
  typeof data.epoch !== "number" ||
273
276
  !Number.isSafeInteger(data.epoch) ||
274
277
  data.epoch < 1 ||
@@ -293,7 +296,7 @@ function parseOrganization(value: unknown, configUrl: string): Organization {
293
296
  member.encryptionKey.length > 256 ||
294
297
  typeof member.peerId !== "string" ||
295
298
  typeof member.profileId !== "string" ||
296
- !POINTER_ID_PATTERN.test(member.profileId) ||
299
+ !RESOURCE_ID_PATTERN.test(member.profileId) ||
297
300
  typeof member.requestId !== "string" ||
298
301
  !POINTER_ID_PATTERN.test(member.requestId) ||
299
302
  identities.has(member.publicKey) ||
@@ -469,8 +472,13 @@ async function activate(
469
472
  const addresses = [...config.bootstrap];
470
473
  const api = client(context, c.service);
471
474
  let selfProfile: { profile: Profile; cid: string } | undefined;
472
- for (const member of config.members) {
473
- const profile = await api.read(c.scopeId, member.profileId);
475
+ const profiles = await Promise.allSettled(
476
+ config.members.map((member) => api.read(c.scopeId, member.profileId)),
477
+ );
478
+ for (const [index, member] of config.members.entries()) {
479
+ const result = profiles[index]!;
480
+ if (result.status === "rejected") throw result.reason;
481
+ const profile = result.value;
474
482
  const value = parseProfile(profile.value, member.peerId);
475
483
  if (member.publicKey === identity.publicKey)
476
484
  selfProfile = { profile: value, cid: profile.cid };
@@ -483,6 +491,7 @@ async function activate(
483
491
  config.epoch,
484
492
  [...new Set(addresses)],
485
493
  context.diagnostic,
494
+ context.listen,
486
495
  );
487
496
  if (node.peerId !== self.peerId)
488
497
  throw new HostError(
@@ -620,7 +629,17 @@ export async function pointer(
620
629
  context: SwarmContext,
621
630
  configUrl: string,
622
631
  ): Promise<BoundHead> {
623
- let record = await readyMembership(context, configUrl);
632
+ return boundPointer(
633
+ context,
634
+ configUrl,
635
+ await readyMembership(context, configUrl),
636
+ );
637
+ }
638
+ async function boundPointer(
639
+ context: SwarmContext,
640
+ configUrl: string,
641
+ record: LocalMembership,
642
+ ): Promise<BoundHead> {
624
643
  const identity = await contextIdentity(context),
625
644
  c = coordinates(configUrl);
626
645
  const operation = async (
@@ -814,6 +833,38 @@ export interface SwarmHeader {
814
833
  source: "cache" | "network";
815
834
  verifiedAt: string;
816
835
  }
836
+ export async function sharedSwarmStatus(
837
+ context: SwarmContext,
838
+ configUrl: string,
839
+ ): Promise<SwarmHeader> {
840
+ const { config } = await fetchConfig(context, configUrl);
841
+ const c = coordinates(configUrl);
842
+ const head = headValue(
843
+ await client(context, c.service).read(c.scopeId, config.headId),
844
+ );
845
+ let snapshot: Snapshot;
846
+ try {
847
+ snapshot = await readSnapshot(context.store, head.root);
848
+ } catch (cause) {
849
+ if (!(cause instanceof ContentError) || cause.code !== "missing_block")
850
+ throw cause;
851
+ const registered = withState(context, (state) =>
852
+ state.swarms().some((entry) => entry.cid === configUrl),
853
+ );
854
+ if (!registered) throw cause;
855
+ context.diagnostic?.(
856
+ "Shared State is missing locally; connecting the registered Swarm content source.",
857
+ );
858
+ return swarmHeader(context, configUrl, true);
859
+ }
860
+ return {
861
+ head,
862
+ snapshot,
863
+ config,
864
+ source: "network",
865
+ verifiedAt: new Date().toISOString(),
866
+ };
867
+ }
817
868
  export async function swarmHeader(
818
869
  context: SwarmContext,
819
870
  configUrl: string,
@@ -849,13 +900,13 @@ export async function swarmHeader(
849
900
  source: "cache",
850
901
  verifiedAt: new Date(cached.verifiedAt).toISOString(),
851
902
  };
852
- let head = await (await pointer(context, configUrl)).read();
903
+ let head = await (await boundPointer(context, configUrl, record)).read();
853
904
  let snapshot: Snapshot;
854
905
  try {
855
906
  snapshot = await readSnapshot(context.store, head.root);
856
907
  } catch {
857
908
  record = await refresh(context, configUrl);
858
- head = await (await pointer(context, configUrl)).read();
909
+ head = await (await boundPointer(context, configUrl, record)).read();
859
910
  snapshot = await readSnapshot(context.store, head.root);
860
911
  }
861
912
  const current = await local(context, configUrl),
@@ -966,6 +1017,7 @@ export async function createSwarm(
966
1017
  const node = await prepareNode(
967
1018
  context.stateDir,
968
1019
  nodeScope(service, record.scopeId),
1020
+ context.listen,
969
1021
  );
970
1022
  if (!record.headId) {
971
1023
  const root = await publication(
@@ -1119,6 +1171,7 @@ export async function requestMembership(
1119
1171
  const node = await prepareNode(
1120
1172
  context.stateDir,
1121
1173
  nodeScope(coordinates(url).service, config.scopeId),
1174
+ context.listen,
1122
1175
  ),
1123
1176
  encryption = encryptionIdentity();
1124
1177
  const body = {