@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/dist/swarm.js CHANGED
@@ -7,18 +7,21 @@ import { CID } from "multiformats/cid";
7
7
  import { sha256 } from "multiformats/hashes/sha2";
8
8
  import { encodeSchema, openBundle } from "@ipab/bundle";
9
9
  import { encodeBundleCar, memoryTree, streamChunks, } from "@ipab/bundle-builder";
10
- import { ScopeClient, ScopeApiError, issueScopeCertificate, uniqueId, verifyScopeCertificate, valueCid, } from "@ipab/bundle/pointer/scope";
10
+ import { ContentError } from "@ipab/ipfs-store";
11
+ import { ScopeClient, ScopeApiError, RESOURCE_ID_PATTERN, issueScopeCertificate, uniqueId, verifyScopeCertificate, valueCid, } from "@ipab/bundle/pointer/scope";
11
12
  import { canonicalService, isCanonicalPublicKey, POINTER_ID_PATTERN, } from "@ipab/bundle/pointer/protocol";
12
13
  import { importPrivateKeyPkcs8, importPublicKeyRaw, keyId, signEd25519, verifyEd25519, } from "@ipab/bundle/pointer/crypto";
13
14
  import { HostError, object, message } from "./errors.js";
14
15
  import { accountIdentity } from "./identity.js";
16
+ import { swarmUrl as canonicalSwarmUrl } from "./config.js";
15
17
  import { bundleJson, provideContent } from "./content-provider.js";
16
18
  import { bytes, relativePath } from "./space.js";
17
19
  import { appSchemaCid } from "./app-definition.js";
18
20
  import { State } from "./state.js";
19
21
  import { privateDirectory, readPrivate, withPrivateLock, writePrivate, } from "./swarm-files.js";
20
22
  import { encryptionIdentity, openApproval, sealApproval, parseEnvelope, } from "./swarm-envelope.js";
21
- import { kuboSource, peerId, peerProof, prepareNode, startNode, validateAddress, } from "./kubo.js";
23
+ import { checkCachedNode, kuboSource, peerId, peerProof, prepareNode, startNode, validateAddress, } from "./kubo.js";
24
+ import { memberPeers } from "./kubo-peering.js";
22
25
  async function contextIdentity(context, initialize = false) {
23
26
  context.identity ??= await accountIdentity(context.env, initialize);
24
27
  return context.identity;
@@ -48,20 +51,7 @@ function withState(context, operation) {
48
51
  state.close();
49
52
  }
50
53
  }
51
- export function canonicalSwarmUrl(value) {
52
- if (!/^https?:\/\//.test(value))
53
- throw new HostError("Swarm requires a configuration URL; old Swarm CID protocol is unsupported.");
54
- const url = new URL(value);
55
- canonicalService(url.origin);
56
- if (url.search ||
57
- url.hash ||
58
- url.username ||
59
- url.password ||
60
- url.toString() !== value ||
61
- !/^\/v1\/[A-Za-z0-9_-]{43}\/[A-Za-z0-9_-]{43}$/.test(url.pathname))
62
- throw new HostError("Swarm must be an exact Scope configuration URL; old Swarm CID protocol is unsupported.");
63
- return value;
64
- }
54
+ export { canonicalSwarmUrl };
65
55
  function coordinates(configUrl) {
66
56
  const url = new URL(canonicalSwarmUrl(configUrl));
67
57
  const [, , scopeId, configId] = url.pathname.split("/");
@@ -112,7 +102,7 @@ function parseOrganization(value, configUrl) {
112
102
  typeof data.description !== "string" ||
113
103
  data.description.length > 2048 ||
114
104
  typeof data.headId !== "string" ||
115
- !POINTER_ID_PATTERN.test(data.headId) ||
105
+ !RESOURCE_ID_PATTERN.test(data.headId) ||
116
106
  typeof data.epoch !== "number" ||
117
107
  !Number.isSafeInteger(data.epoch) ||
118
108
  data.epoch < 1 ||
@@ -133,7 +123,7 @@ function parseOrganization(value, configUrl) {
133
123
  member.encryptionKey.length > 256 ||
134
124
  typeof member.peerId !== "string" ||
135
125
  typeof member.profileId !== "string" ||
136
- !POINTER_ID_PATTERN.test(member.profileId) ||
126
+ !RESOURCE_ID_PATTERN.test(member.profileId) ||
137
127
  typeof member.requestId !== "string" ||
138
128
  !POINTER_ID_PATTERN.test(member.requestId) ||
139
129
  identities.has(member.publicKey) ||
@@ -194,11 +184,12 @@ function parseProfile(value, expectedPeer) {
194
184
  }
195
185
  return { name: data.name, addresses, updatedAt: data.updatedAt };
196
186
  }
197
- async function fetchConfig(context, configUrl) {
187
+ async function fetchConfig(context, configUrl, signal) {
198
188
  const c = coordinates(configUrl), api = client(context, c.service);
189
+ const options = signal ? { signal } : {};
199
190
  const [variable, scope] = await Promise.all([
200
- api.read(c.scopeId, c.configId),
201
- api.send("GET", c.scopeId),
191
+ api.read(c.scopeId, c.configId, options),
192
+ api.send("GET", c.scopeId, "", undefined, options),
202
193
  ]);
203
194
  const config = parseOrganization(variable.value, configUrl);
204
195
  if (scope.owner !== config.owner)
@@ -233,7 +224,7 @@ async function validateMembershipSecret(record, config, member) {
233
224
  throw new HostError("Membership package must grant exactly HEAD and this member's profile.");
234
225
  }
235
226
  }
236
- async function activate(context, record) {
227
+ async function privateSource(context, record, signal) {
237
228
  const config = record.config, secret = record.secret;
238
229
  const identity = await contextIdentity(context);
239
230
  const self = config.members.find((member) => member.publicKey === identity.publicKey);
@@ -244,43 +235,70 @@ async function activate(context, record) {
244
235
  await verifyScopeCertificate(secret.certificate, config.owner, c.service, c.scopeId, config.headId, identity.publicKey);
245
236
  await verifyScopeCertificate(secret.certificate, config.owner, c.service, c.scopeId, self.profileId, identity.publicKey);
246
237
  }
247
- const addresses = [...config.bootstrap];
238
+ const addresses = new Map();
248
239
  const api = client(context, c.service);
249
240
  let selfProfile;
250
- for (const member of config.members) {
251
- const profile = await api.read(c.scopeId, member.profileId);
241
+ const profiles = await Promise.allSettled(config.members.map((member) => api.read(c.scopeId, member.profileId, signal ? { signal } : {})));
242
+ for (const [index, member] of config.members.entries()) {
243
+ const result = profiles[index];
244
+ if (result.status === "rejected")
245
+ throw result.reason;
246
+ const profile = result.value;
252
247
  const value = parseProfile(profile.value, member.peerId);
253
248
  if (member.publicKey === identity.publicKey)
254
249
  selfProfile = { profile: value, cid: profile.cid };
255
- addresses.push(...value.addresses);
250
+ addresses.set(member.peerId, value.addresses);
256
251
  }
257
- const node = await startNode(context.stateDir, nodeScope(c.service, config.scopeId), secret.swarmKey, config.epoch, [...new Set(addresses)], context.diagnostic);
252
+ const desired = memberPeers(self.peerId, addresses, config.bootstrap);
253
+ signal?.throwIfAborted();
254
+ const node = await startNode(context.stateDir, nodeScope(c.service, config.scopeId), secret.swarmKey, config.epoch, context.listen, { self: self.peerId, peers: desired, ...(signal ? { signal } : {}) });
258
255
  if (node.peerId !== self.peerId)
259
256
  throw new HostError("Approved PeerID differs from this local Request's Kubo identity.");
260
- if (context.node?.api !== node.api) {
261
- const store = context.store.withLocalSource(kuboSource(node));
262
- await context.store.close();
263
- context.store = store;
264
- }
265
- context.node = node;
266
- if (selfProfile && selfProfile.profile.addresses.length === 0) {
257
+ const peers = desired.flatMap(({ ID, Addrs }) => Addrs.map((addr) => `${addr}/p2p/${ID}`));
258
+ signal?.throwIfAborted();
259
+ if (!node.addresses.length && !selfProfile?.profile.addresses.length)
260
+ context.diagnostic?.("No private LAN/VPN IPv4 address to advertise. Connect a routed interface or set your own address with swarm profile --address.");
261
+ if (node.addresses.length &&
262
+ selfProfile &&
263
+ selfProfile.profile.addresses.length === 0) {
267
264
  const writer = client(context, c.service, identity, identity.publicKey === config.owner ? undefined : secret);
268
265
  const profile = {
269
266
  ...selfProfile.profile,
270
267
  addresses: node.addresses,
271
268
  updatedAt: new Date().toISOString(),
272
269
  };
273
- await writer.write(c.scopeId, self.profileId, profile, selfProfile.cid, uniqueId());
270
+ await writer.write(c.scopeId, self.profileId, profile, selfProfile.cid, uniqueId(), signal ? { signal } : {});
271
+ }
272
+ return {
273
+ node,
274
+ peers,
275
+ source: kuboSource(node, peers, context.diagnostic, context.env.IPAB_SWARM_DIAL_DEBUG === "1"),
276
+ };
277
+ }
278
+ async function activate(context, record) {
279
+ const { node, peers, source } = await privateSource(context, record);
280
+ if (context.node?.api !== node.api ||
281
+ context.sourcePeers?.length !== peers.length ||
282
+ peers.some((peer, i) => context.sourcePeers?.[i] !== peer)) {
283
+ const store = context.store.withLocalSource(source);
284
+ await context.store.close();
285
+ context.store = store;
286
+ context.sourcePeers = peers;
274
287
  }
288
+ context.node = node;
275
289
  }
276
- async function refresh(context, configUrl) {
290
+ async function localForRead(context, configUrl) {
277
291
  const record = await local(context, configUrl);
278
292
  if (record.account === record.owner) {
279
293
  const transition = await readPrivate(await directory(context), `transition-${localName(configUrl)}`);
280
294
  if (transition && !transition.completed)
281
295
  throw new HostError("Organization switch incomplete; only Owner can continue with swarm resume.");
282
296
  }
283
- const { config } = await fetchConfig(context, configUrl);
297
+ return record;
298
+ }
299
+ async function approvedMembership(context, configUrl, signal) {
300
+ const record = await localForRead(context, configUrl);
301
+ const { config } = await fetchConfig(context, configUrl, signal);
284
302
  if (config.owner !== record.owner)
285
303
  throw new HostError("Pinned Owner changed; refusing configuration.");
286
304
  if (record.config && config.epoch < record.config.epoch)
@@ -300,17 +318,16 @@ async function refresh(context, configUrl) {
300
318
  throw new HostError("Owner key/Swarm key lost: no system recovery is available.");
301
319
  record.config = config;
302
320
  await validateMembershipSecret(record, config, member);
321
+ return record;
322
+ }
323
+ async function refresh(context, configUrl) {
324
+ const record = await approvedMembership(context, configUrl);
303
325
  await saveLocal(context, record);
304
326
  await activate(context, record);
305
327
  return record;
306
328
  }
307
329
  async function readyMembership(context, configUrl) {
308
- const record = await local(context, configUrl);
309
- if (record.account === record.owner) {
310
- const transition = await readPrivate(await directory(context), `transition-${localName(configUrl)}`);
311
- if (transition && !transition.completed)
312
- throw new HostError("Organization switch incomplete; run swarm resume before normal Owner operations.");
313
- }
330
+ const record = await localForRead(context, configUrl);
314
331
  if (!record.config || !record.secret)
315
332
  return refresh(context, configUrl);
316
333
  if (!context.node ||
@@ -339,7 +356,9 @@ function headValue(head) {
339
356
  };
340
357
  }
341
358
  export async function pointer(context, configUrl) {
342
- let record = await readyMembership(context, configUrl);
359
+ return boundPointer(context, configUrl, await readyMembership(context, configUrl));
360
+ }
361
+ async function boundPointer(context, configUrl, record) {
343
362
  const identity = await contextIdentity(context), c = coordinates(configUrl);
344
363
  const operation = async (write, root, cid, key) => {
345
364
  for (let attempt = 0;; attempt++) {
@@ -463,34 +482,47 @@ async function publication(store, state, previous) {
463
482
  await store.put(cid, data);
464
483
  return cid.toString();
465
484
  }
485
+ export async function sharedSwarmStatus(context, configUrl) {
486
+ const { config } = await fetchConfig(context, configUrl);
487
+ const c = coordinates(configUrl);
488
+ const head = headValue(await client(context, c.service).read(c.scopeId, config.headId));
489
+ let snapshot;
490
+ try {
491
+ snapshot = await readSnapshot(context.store, head.root);
492
+ }
493
+ catch (cause) {
494
+ if (!(cause instanceof ContentError) || cause.code !== "missing_block")
495
+ throw cause;
496
+ const registered = withState(context, (state) => state.swarms().some((entry) => entry.cid === configUrl));
497
+ if (!registered)
498
+ throw cause;
499
+ context.diagnostic?.("Shared State is missing locally; connecting the registered Swarm content source.");
500
+ return swarmHeader(context, configUrl, true);
501
+ }
502
+ return {
503
+ head,
504
+ snapshot,
505
+ config,
506
+ source: "network",
507
+ verifiedAt: new Date().toISOString(),
508
+ };
509
+ }
466
510
  export async function swarmHeader(context, configUrl, force = context.forceRefresh ?? false) {
467
511
  canonicalSwarmUrl(configUrl);
468
512
  let record = force
469
513
  ? await refresh(context, configUrl)
470
514
  : await readyMembership(context, configUrl);
471
- const ttl = context.cacheTtl ?? 300;
472
- const cached = force
473
- ? undefined
474
- : withState(context, (state) => state.swarmHeader(record.account, configUrl));
475
- if (cached &&
476
- cached.headId === record.config.headId &&
477
- Date.now() >= cached.verifiedAt &&
478
- Date.now() - cached.verifiedAt < ttl * 1000)
479
- return {
480
- head: headValue(cached.head),
481
- snapshot: decodeSnapshot(Buffer.from(cached.snapshot, "base64")),
482
- config: record.config,
483
- source: "cache",
484
- verifiedAt: new Date(cached.verifiedAt).toISOString(),
485
- };
486
- let head = await (await pointer(context, configUrl)).read();
515
+ const cached = !force && cachedHeader(context, record);
516
+ if (cached)
517
+ return cached;
518
+ let head = await (await boundPointer(context, configUrl, record)).read();
487
519
  let snapshot;
488
520
  try {
489
521
  snapshot = await readSnapshot(context.store, head.root);
490
522
  }
491
523
  catch {
492
524
  record = await refresh(context, configUrl);
493
- head = await (await pointer(context, configUrl)).read();
525
+ head = await (await boundPointer(context, configUrl, record)).read();
494
526
  snapshot = await readSnapshot(context.store, head.root);
495
527
  }
496
528
  const current = await local(context, configUrl), verifiedAt = Date.now();
@@ -500,6 +532,7 @@ export async function swarmHeader(context, configUrl, force = context.forceRefre
500
532
  snapshot: Buffer.from(dagCbor.encode(snapshot)).toString("base64"),
501
533
  verifiedAt,
502
534
  headId: current.config.headId,
535
+ epoch: current.config.epoch,
503
536
  });
504
537
  });
505
538
  return {
@@ -510,6 +543,93 @@ export async function swarmHeader(context, configUrl, force = context.forceRefre
510
543
  verifiedAt: new Date(verifiedAt).toISOString(),
511
544
  };
512
545
  }
546
+ function cachedHeader(context, record) {
547
+ const config = record.config;
548
+ if (!config || !record.secret)
549
+ return;
550
+ const cached = withState(context, (state) => state.swarmHeader(record.account, record.configUrl));
551
+ const age = cached ? Date.now() - cached.verifiedAt : NaN;
552
+ if (!cached ||
553
+ cached.headId !== config.headId ||
554
+ (cached.epoch !== undefined && cached.epoch !== config.epoch) ||
555
+ !(age >= 0 && age < (context.cacheTtl ?? 300) * 1000))
556
+ return;
557
+ return {
558
+ head: headValue(cached.head),
559
+ snapshot: decodeSnapshot(Buffer.from(cached.snapshot, "base64")),
560
+ config,
561
+ source: "cache",
562
+ verifiedAt: new Date(cached.verifiedAt).toISOString(),
563
+ };
564
+ }
565
+ async function localHeader(context, url) {
566
+ if (context.forceRefresh)
567
+ return;
568
+ canonicalSwarmUrl(url);
569
+ const record = await localForRead(context, url);
570
+ const header = cachedHeader(context, record);
571
+ if (!header)
572
+ return;
573
+ const config = parseOrganization(header.config, url);
574
+ const member = config.members.find((item) => item.publicKey === record.account);
575
+ if (!member || config.owner !== record.owner)
576
+ throw new HostError("Cached membership no longer matches the account or Owner.");
577
+ if (record.account !== config.owner &&
578
+ (!record.request ||
579
+ record.request.id !== member.requestId ||
580
+ record.request.peerId !== member.peerId ||
581
+ !member.approval))
582
+ throw new HostError("Cached membership does not match the saved Request.");
583
+ await validateMembershipSecret(record, config, member);
584
+ const c = coordinates(url);
585
+ await checkCachedNode(context.stateDir, nodeScope(c.service, c.scopeId), config.epoch, member.peerId);
586
+ return { header, account: record.account };
587
+ }
588
+ // SharedContent invokes this source only after a genuine local ENOENT. Its
589
+ // store is not replaced from inside its own pending read (which would deadlock).
590
+ async function lazyPrivateSource(context, url, account, basis) {
591
+ const lifetime = new AbortController();
592
+ let pending;
593
+ const load = async (signal) => {
594
+ const scoped = { ...context };
595
+ // Re-read the protected HOME binding and live approval on the first miss;
596
+ // do not serve an old resolved Name through a different epoch or identity.
597
+ delete scoped.identity;
598
+ const authorize = async () => {
599
+ const record = await approvedMembership(scoped, url, signal);
600
+ signal.throwIfAborted();
601
+ if (record.account !== account ||
602
+ record.config.owner !== basis.owner ||
603
+ record.config.epoch !== basis.epoch ||
604
+ record.config.headId !== basis.headId)
605
+ throw new HostError("Swarm membership changed since this cached HEAD; retry with --force.");
606
+ return (await privateSource(scoped, record, signal)).source;
607
+ };
608
+ // Same lock order as Owner rotation: credentials first, then the node.
609
+ return withPrivateLock(await directory(scoped), authorize, signal);
610
+ };
611
+ const store = context.store.withLocalSource({
612
+ block: {
613
+ async get(cid, options = {}) {
614
+ const signal = options.signal
615
+ ? AbortSignal.any([lifetime.signal, options.signal])
616
+ : lifetime.signal;
617
+ signal.throwIfAborted();
618
+ const source = await (pending ??= load(signal));
619
+ signal.throwIfAborted();
620
+ return source.block.get(cid, { signal });
621
+ },
622
+ },
623
+ });
624
+ await context.store.close();
625
+ context.store = store;
626
+ delete context.node;
627
+ delete context.sourcePeers;
628
+ context.finishRead = async () => {
629
+ lifetime.abort();
630
+ await pending?.catch(() => { });
631
+ };
632
+ }
513
633
  export async function addSwarm(context, url, alias) {
514
634
  canonicalSwarmUrl(url);
515
635
  await readyMembership(context, url);
@@ -560,7 +680,7 @@ export async function createSwarm(context, options = {}) {
560
680
  record.scopeId = (await api.createScope(`${op}.scope`)).id;
561
681
  await save();
562
682
  }
563
- const node = await prepareNode(context.stateDir, nodeScope(service, record.scopeId));
683
+ const node = await prepareNode(context.stateDir, nodeScope(service, record.scopeId), context.listen);
564
684
  if (!record.headId) {
565
685
  const root = await publication(context.store, await writeSnapshot(context.store, { v: 2, names: {} }));
566
686
  record.headId = (await api.create(record.scopeId, { root }, `${op}.head`)).id;
@@ -667,7 +787,7 @@ export async function requestMembership(context, url, options) {
667
787
  withState(context, (state) => state.registerSwarm(url, options.alias));
668
788
  return;
669
789
  }
670
- const node = await prepareNode(context.stateDir, nodeScope(coordinates(url).service, config.scopeId)), encryption = encryptionIdentity();
790
+ const node = await prepareNode(context.stateDir, nodeScope(coordinates(url).service, config.scopeId), context.listen), encryption = encryptionIdentity();
671
791
  const body = {
672
792
  v: 1,
673
793
  id: uniqueId(),
@@ -1041,33 +1161,55 @@ export function formalName(name) {
1041
1161
  throw new HostError("Invalid formal Name.");
1042
1162
  return name;
1043
1163
  }
1164
+ function decodeNameComponent(value, part) {
1165
+ try {
1166
+ return decodeURIComponent(value);
1167
+ }
1168
+ catch {
1169
+ throw new HostError(`Malformed percent-encoding in IPAB URI ${part}; use valid UTF-8 escapes or copy the reference from ipab search.`);
1170
+ }
1171
+ }
1044
1172
  export function parseNameReference(reference) {
1045
1173
  if (/^name:/i.test(reference))
1046
1174
  throw new HostError("name: is unsupported; use ipab://ALIAS/PATH.");
1047
1175
  if (!/^ipab:/i.test(reference))
1048
1176
  return undefined;
1049
- const match = /^ipab:\/\/([^/]*)\/([^?#\s]*)$/i.exec(reference);
1177
+ if (/^ipab:\/\/https?:\/\//i.test(reference))
1178
+ throw new HostError("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.");
1179
+ const match = /^ipab:\/\/([^/]*)\/(.*)$/is.exec(reference);
1050
1180
  if (!match)
1051
1181
  throw new HostError("Invalid IPAB URI; percent-encode the configuration URL authority and each path segment.");
1052
- const authority = decodeURIComponent(match[1]);
1053
- if (authority && !/^[A-Za-z0-9][A-Za-z0-9._-]*$/.test(authority))
1182
+ const authority = decodeNameComponent(match[1], "authority");
1183
+ if (authority && !/^[A-Za-z0-9][A-Za-z0-9._-]*$/.test(authority)) {
1184
+ if (!/^https?:\/\//i.test(authority))
1185
+ throw new HostError("Invalid IPAB URI authority; use a registered alias or the percent-encoded configuration URL.");
1054
1186
  canonicalSwarmUrl(authority);
1187
+ }
1188
+ if (/[?#\s]/.test(match[2]))
1189
+ throw new HostError("Invalid IPAB URI path; percent-encode each Name path segment. Queries and fragments are not supported.");
1055
1190
  const segments = match[2].split("/").map((segment) => {
1056
- const decoded = decodeURIComponent(segment);
1057
- if (decoded.includes("/"))
1058
- throw new HostError("Encoded path separators are unsupported.");
1191
+ const decoded = decodeNameComponent(segment, "path");
1192
+ if (/[/\\]/.test(decoded))
1193
+ throw new HostError("Invalid IPAB URI path separator; use literal / between Name segments, never an encoded slash or backslash.");
1059
1194
  return decoded;
1060
1195
  });
1061
- return {
1062
- ...(authority ? { swarm: authority } : {}),
1063
- name: formalName(segments.join("/")),
1064
- };
1196
+ try {
1197
+ return {
1198
+ ...(authority ? { swarm: authority } : {}),
1199
+ name: formalName(segments.join("/")),
1200
+ };
1201
+ }
1202
+ catch (error) {
1203
+ if (!(error instanceof HostError))
1204
+ throw error;
1205
+ throw new HostError("Invalid IPAB URI path; use a safe relative Name of at most 256 characters without empty, . or .. segments.", error.exitCode, error.code, error.phase);
1206
+ }
1065
1207
  }
1066
- function referenceFor(url, name) {
1208
+ export function formatNameReference(swarm, name) {
1067
1209
  const segment = (value) => encodeURIComponent(value).replace(/[!'()*]/g, (char) => `%${char.charCodeAt(0).toString(16).toUpperCase()}`);
1068
- return `ipab://${segment(url)}/${name.split("/").map(segment).join("/")}`;
1210
+ return `ipab://${segment(swarm)}/${name.split("/").map(segment).join("/")}`;
1069
1211
  }
1070
- export async function resolveReference(context, reference, swarm, local, raw = false) {
1212
+ export async function resolveReference(context, reference, swarm, local, raw = false, mode = "active") {
1071
1213
  const shared = parseNameReference(reference);
1072
1214
  let targetCid;
1073
1215
  if (shared) {
@@ -1076,7 +1218,8 @@ export async function resolveReference(context, reference, swarm, local, raw = f
1076
1218
  : swarm;
1077
1219
  if (!selected)
1078
1220
  throw new HostError("Select a configuration URL/alias using --swarm or swarm use.");
1079
- let header = await swarmHeader(context, selected);
1221
+ const warm = mode === "local-first" ? await localHeader(context, selected) : undefined;
1222
+ let header = warm?.header ?? (await swarmHeader(context, selected));
1080
1223
  let link = Object.hasOwn(header.snapshot.names, shared.name)
1081
1224
  ? header.snapshot.names[shared.name]
1082
1225
  : undefined;
@@ -1088,6 +1231,8 @@ export async function resolveReference(context, reference, swarm, local, raw = f
1088
1231
  }
1089
1232
  if (!link)
1090
1233
  throw new HostError(`Formal Name "${shared.name}" was not found after refreshing HEAD.`);
1234
+ if (warm && header === warm.header)
1235
+ await lazyPrivateSource(context, selected, warm.account, header.config);
1091
1236
  targetCid = link.toString();
1092
1237
  }
1093
1238
  else {
@@ -1120,7 +1265,8 @@ export async function searchNames(context, query, swarms) {
1120
1265
  const matches = [];
1121
1266
  const searched = [];
1122
1267
  for (const swarm of swarms) {
1123
- const header = await swarmHeader(context, swarm.cid);
1268
+ const header = (await localHeader(context, swarm.cid))?.header ??
1269
+ (await swarmHeader(context, swarm.cid));
1124
1270
  searched.push({
1125
1271
  configUrl: swarm.cid,
1126
1272
  source: header.source,
@@ -1134,7 +1280,7 @@ export async function searchNames(context, query, swarms) {
1134
1280
  swarm: swarm.cid,
1135
1281
  alias: swarm.alias,
1136
1282
  name,
1137
- reference: referenceFor(swarm.cid, name),
1283
+ reference: formatNameReference(swarm.cid, name),
1138
1284
  targetCid: header.snapshot.names[name].toString(),
1139
1285
  });
1140
1286
  }