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

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 (128) hide show
  1. package/README.md +88 -16
  2. package/dist/app-templates.js +1 -1
  3. package/dist/app-templates.js.map +1 -1
  4. package/dist/builtins/skill.ipab.car +0 -0
  5. package/dist/builtins/template.node.car +0 -0
  6. package/dist/builtins/template.web-app.car +0 -0
  7. package/dist/cli.d.ts +6 -2
  8. package/dist/cli.d.ts.map +1 -1
  9. package/dist/cli.js +656 -278
  10. package/dist/cli.js.map +1 -1
  11. package/dist/config-secret.d.ts +1 -1
  12. package/dist/config-secret.d.ts.map +1 -1
  13. package/dist/config-secret.js +2 -73
  14. package/dist/config-secret.js.map +1 -1
  15. package/dist/config.d.ts +1 -0
  16. package/dist/config.d.ts.map +1 -1
  17. package/dist/config.js +12 -1
  18. package/dist/config.js.map +1 -1
  19. package/dist/content-provider.d.ts +1 -1
  20. package/dist/content-provider.d.ts.map +1 -1
  21. package/dist/content-provider.js +4 -3
  22. package/dist/content-provider.js.map +1 -1
  23. package/dist/context-types.d.ts +12 -0
  24. package/dist/context-types.d.ts.map +1 -0
  25. package/dist/context-types.js +2 -0
  26. package/dist/context-types.js.map +1 -0
  27. package/dist/context.d.ts +6 -1
  28. package/dist/context.d.ts.map +1 -1
  29. package/dist/context.js +24 -9
  30. package/dist/context.js.map +1 -1
  31. package/dist/doctor.d.ts +29 -0
  32. package/dist/doctor.d.ts.map +1 -0
  33. package/dist/doctor.js +576 -0
  34. package/dist/doctor.js.map +1 -0
  35. package/dist/identity.d.ts +1 -1
  36. package/dist/identity.d.ts.map +1 -1
  37. package/dist/identity.js +9 -9
  38. package/dist/identity.js.map +1 -1
  39. package/dist/ipc.d.ts +3 -2
  40. package/dist/ipc.d.ts.map +1 -1
  41. package/dist/ipc.js +33 -9
  42. package/dist/ipc.js.map +1 -1
  43. package/dist/kubo-install.d.ts +26 -0
  44. package/dist/kubo-install.d.ts.map +1 -0
  45. package/dist/kubo-install.js +724 -0
  46. package/dist/kubo-install.js.map +1 -0
  47. package/dist/kubo-peering.d.ts +11 -0
  48. package/dist/kubo-peering.d.ts.map +1 -0
  49. package/dist/kubo-peering.js +93 -0
  50. package/dist/kubo-peering.js.map +1 -0
  51. package/dist/kubo-peers.d.ts +12 -0
  52. package/dist/kubo-peers.d.ts.map +1 -0
  53. package/dist/kubo-peers.js +118 -0
  54. package/dist/kubo-peers.js.map +1 -0
  55. package/dist/kubo-release.d.ts +22 -0
  56. package/dist/kubo-release.d.ts.map +1 -0
  57. package/dist/kubo-release.js +176 -0
  58. package/dist/kubo-release.js.map +1 -0
  59. package/dist/kubo.d.ts +12 -4
  60. package/dist/kubo.d.ts.map +1 -1
  61. package/dist/kubo.js +218 -259
  62. package/dist/kubo.js.map +1 -1
  63. package/dist/pins.d.ts +15 -17
  64. package/dist/pins.d.ts.map +1 -1
  65. package/dist/pins.js +144 -106
  66. package/dist/pins.js.map +1 -1
  67. package/dist/publish-source.d.ts +3 -0
  68. package/dist/publish-source.d.ts.map +1 -0
  69. package/dist/publish-source.js +85 -0
  70. package/dist/publish-source.js.map +1 -0
  71. package/dist/runtime.d.ts +2 -0
  72. package/dist/runtime.d.ts.map +1 -1
  73. package/dist/runtime.js +4 -2
  74. package/dist/runtime.js.map +1 -1
  75. package/dist/state-storage-windows.d.ts +2 -0
  76. package/dist/state-storage-windows.d.ts.map +1 -0
  77. package/dist/state-storage-windows.js +114 -0
  78. package/dist/state-storage-windows.js.map +1 -0
  79. package/dist/state-storage.d.ts +5 -0
  80. package/dist/state-storage.d.ts.map +1 -0
  81. package/dist/state-storage.js +330 -0
  82. package/dist/state-storage.js.map +1 -0
  83. package/dist/state.d.ts +42 -8
  84. package/dist/state.d.ts.map +1 -1
  85. package/dist/state.js +254 -98
  86. package/dist/state.js.map +1 -1
  87. package/dist/swarm-envelope.d.ts +1 -0
  88. package/dist/swarm-envelope.d.ts.map +1 -1
  89. package/dist/swarm-envelope.js +12 -0
  90. package/dist/swarm-envelope.js.map +1 -1
  91. package/dist/swarm-files.d.ts +1 -1
  92. package/dist/swarm-files.d.ts.map +1 -1
  93. package/dist/swarm-files.js +4 -1
  94. package/dist/swarm-files.js.map +1 -1
  95. package/dist/swarm.d.ts +70 -11
  96. package/dist/swarm.d.ts.map +1 -1
  97. package/dist/swarm.js +1033 -167
  98. package/dist/swarm.js.map +1 -1
  99. package/package.json +4 -4
  100. package/src/app-templates.ts +1 -1
  101. package/src/cli.ts +827 -356
  102. package/src/config-secret.ts +2 -84
  103. package/src/config.ts +14 -1
  104. package/src/content-provider.ts +4 -2
  105. package/src/context-types.ts +11 -0
  106. package/src/context.ts +39 -9
  107. package/src/doctor.ts +902 -0
  108. package/src/identity.ts +10 -10
  109. package/src/ipc.ts +49 -8
  110. package/src/kubo-install.ts +936 -0
  111. package/src/kubo-peering.ts +126 -0
  112. package/src/kubo-peers.ts +145 -0
  113. package/src/kubo-release.ts +230 -0
  114. package/src/kubo.ts +302 -336
  115. package/src/pins.ts +188 -126
  116. package/src/publish-source.ts +103 -0
  117. package/src/runtime.ts +10 -2
  118. package/src/state-storage-windows.ts +134 -0
  119. package/src/state-storage.ts +375 -0
  120. package/src/state.ts +410 -118
  121. package/src/swarm-envelope.ts +14 -0
  122. package/src/swarm-files.ts +4 -0
  123. package/src/swarm.ts +1482 -207
  124. package/dist/setup.d.ts +0 -7
  125. package/dist/setup.d.ts.map +0 -1
  126. package/dist/setup.js +0 -22
  127. package/dist/setup.js.map +0 -1
  128. package/src/setup.ts +0 -21
package/src/swarm.ts CHANGED
@@ -1,11 +1,19 @@
1
- import { lstat, open, readFile } from "node:fs/promises";
1
+ import { createReadStream } from "node:fs";
2
+ import { lstat, mkdir, open } from "node:fs/promises";
3
+ import { homedir } from "node:os";
4
+ import { join, resolve } from "node:path";
2
5
  import { createHash, randomBytes } from "node:crypto";
3
6
  import { stringify } from "yaml";
4
7
  import { CarBlockIterator } from "@ipld/car/iterator";
5
8
  import * as dagCbor from "@ipld/dag-cbor";
6
9
  import { CID } from "multiformats/cid";
7
10
  import { sha256 } from "multiformats/hashes/sha2";
8
- import { encodeSchema, openBundle, type BundleType } from "@ipab/bundle";
11
+ import {
12
+ ContentBundleError,
13
+ encodeSchema,
14
+ openBundle,
15
+ type BundleType,
16
+ } from "@ipab/bundle";
9
17
  import {
10
18
  encodeBundleCar,
11
19
  memoryTree,
@@ -35,11 +43,31 @@ import {
35
43
  verifyEd25519,
36
44
  } from "@ipab/bundle/pointer/crypto";
37
45
  import { HostError, object, message } from "./errors.js";
38
- import { accountIdentity, type Identity } from "./identity.js";
46
+ import {
47
+ accountIdentity,
48
+ protectedPath,
49
+ secureNew,
50
+ type Identity,
51
+ } from "./identity.js";
52
+ import { nodeError } from "./authoring.js";
53
+ import { swarmUrl as canonicalSwarmUrl } from "./config.js";
39
54
  import { bundleJson, provideContent } from "./content-provider.js";
55
+ import {
56
+ failedPin,
57
+ pinCid,
58
+ refreshPinClaim,
59
+ reservePin,
60
+ retainPin,
61
+ } from "./pins.js";
40
62
  import { bytes, relativePath } from "./space.js";
41
63
  import { appSchemaCid } from "./app-definition.js";
42
- import { State } from "./state.js";
64
+ import {
65
+ State,
66
+ createAssociation,
67
+ exactCid,
68
+ type Association,
69
+ type SwarmProjection,
70
+ } from "./state.js";
43
71
  import {
44
72
  privateDirectory,
45
73
  readPrivate,
@@ -55,8 +83,10 @@ import {
55
83
  type EnvelopeBinding,
56
84
  type MembershipSecret,
57
85
  parseEnvelope,
86
+ validateEncryptionIdentity,
58
87
  } from "./swarm-envelope.js";
59
88
  import {
89
+ checkCachedNode,
60
90
  kuboSource,
61
91
  peerId,
62
92
  peerProof,
@@ -66,8 +96,10 @@ import {
66
96
  type KuboNode,
67
97
  type ListenMode,
68
98
  } from "./kubo.js";
99
+ import { memberPeers } from "./kubo-peering.js";
69
100
 
70
101
  export interface Member {
102
+ memberId?: string;
71
103
  publicKey: string;
72
104
  encryptionKey: string;
73
105
  peerId: string;
@@ -76,7 +108,7 @@ export interface Member {
76
108
  approval: Envelope | null;
77
109
  }
78
110
  export interface Organization {
79
- v: 1;
111
+ v: 1 | 2;
80
112
  scopeId: string;
81
113
  owner: string;
82
114
  name: string;
@@ -88,12 +120,20 @@ export interface Organization {
88
120
  }
89
121
  export interface Profile {
90
122
  name: string;
123
+ description?: string;
91
124
  addresses: string[];
92
125
  updatedAt: string;
93
126
  }
127
+ export interface AccountProfile {
128
+ publicKey: string;
129
+ name: string;
130
+ description: string;
131
+ updatedAt: string | null;
132
+ }
94
133
  export interface Snapshot {
95
134
  v: 2;
96
135
  names: Record<string, CID>;
136
+ registrations?: Record<string, { appCid: CID; argv: string[] }>;
97
137
  }
98
138
  export interface MembershipRequest {
99
139
  v: 1;
@@ -122,6 +162,8 @@ export interface SwarmContext {
122
162
  forceRefresh?: boolean;
123
163
  diagnostic?: (text: string) => void;
124
164
  node?: KuboNode;
165
+ sourcePeers?: readonly string[];
166
+ finishRead?: () => Promise<void>;
125
167
  identity?: Identity;
126
168
  listen?: ListenMode;
127
169
  }
@@ -141,6 +183,67 @@ interface LocalMembership {
141
183
  config?: Organization;
142
184
  secret?: MembershipSecret;
143
185
  }
186
+ export async function inspectLocalMembership(
187
+ input: unknown,
188
+ account: string | undefined,
189
+ ) {
190
+ const value = object(input, "local membership");
191
+ if (
192
+ typeof value.configUrl !== "string" ||
193
+ !isCanonicalPublicKey(value.owner) ||
194
+ !isCanonicalPublicKey(value.account) ||
195
+ value.account !== account
196
+ )
197
+ throw new HostError(
198
+ "Stored membership is inconsistent with HOME identity.",
199
+ );
200
+ const configUrl = canonicalSwarmUrl(value.configUrl);
201
+ if (configUrl !== value.configUrl)
202
+ throw new HostError("Noncanonical membership URL.");
203
+ const encryption = object(value.encryption, "encryption identity");
204
+ if (
205
+ typeof encryption.privateKey !== "string" ||
206
+ typeof encryption.publicKey !== "string"
207
+ )
208
+ throw new HostError("Invalid encryption identity.");
209
+ validateEncryptionIdentity({
210
+ privateKey: encryption.privateKey,
211
+ publicKey: encryption.publicKey,
212
+ });
213
+ const request =
214
+ value.request === undefined
215
+ ? undefined
216
+ : await verifyRequest(value.request);
217
+ if (
218
+ request &&
219
+ (request.configUrl !== configUrl ||
220
+ request.member !== account ||
221
+ request.owner !== value.owner ||
222
+ request.encryptionKey !== encryption.publicKey)
223
+ )
224
+ throw new HostError("Stored Request binding mismatch.");
225
+ const config =
226
+ value.config === undefined
227
+ ? undefined
228
+ : parseOrganization(value.config, configUrl);
229
+ if (config && config.owner !== value.owner)
230
+ throw new HostError("Stored Owner binding mismatch.");
231
+ let peer = request?.peerId;
232
+ if (value.secret !== undefined) {
233
+ if (!config)
234
+ throw new HostError("Stored secret has no configuration binding.");
235
+ const member = config.members.find(
236
+ (member) => member.publicKey === account,
237
+ );
238
+ if (!member)
239
+ throw new HostError("Stored membership lacks its member binding.");
240
+ const record = value as unknown as LocalMembership;
241
+ await validateMembershipSecret(record, config, member);
242
+ peer = member.peerId;
243
+ }
244
+ const c = coordinates(configUrl);
245
+ return { configUrl, scope: nodeScope(c.service, c.scopeId), peer };
246
+ }
144
247
  const cidField = { type: "string", minLength: 1, maxLength: 128 } as const;
145
248
  export const artifactType: BundleType = {
146
249
  contentType: "application/json",
@@ -172,26 +275,7 @@ function withState<T>(
172
275
  state.close();
173
276
  }
174
277
  }
175
- export function canonicalSwarmUrl(value: string): string {
176
- if (!/^https?:\/\//.test(value))
177
- throw new HostError(
178
- "Swarm requires a configuration URL; old Swarm CID protocol is unsupported.",
179
- );
180
- const url = new URL(value);
181
- canonicalService(url.origin);
182
- if (
183
- url.search ||
184
- url.hash ||
185
- url.username ||
186
- url.password ||
187
- url.toString() !== value ||
188
- !/^\/v1\/[a-f0-9]{16}\/[a-f0-9]{16}$/.test(url.pathname)
189
- )
190
- throw new HostError(
191
- "Swarm must be an exact Scope configuration URL; old Swarm CID protocol is unsupported.",
192
- );
193
- return value;
194
- }
278
+ export { canonicalSwarmUrl };
195
279
  function coordinates(configUrl: string): {
196
280
  service: string;
197
281
  scopeId: string;
@@ -263,7 +347,7 @@ function parseOrganization(value: unknown, configUrl: string): Organization {
263
347
  if (
264
348
  Object.keys(data).sort().join() !==
265
349
  "bootstrap,description,epoch,headId,members,name,owner,scopeId,v" ||
266
- data.v !== 1 ||
350
+ (data.v !== 1 && data.v !== 2) ||
267
351
  data.scopeId !== scopeId ||
268
352
  !isCanonicalPublicKey(data.owner) ||
269
353
  typeof data.name !== "string" ||
@@ -279,7 +363,7 @@ function parseOrganization(value: unknown, configUrl: string): Organization {
279
363
  data.bootstrap.length > 64 ||
280
364
  !Array.isArray(data.members) ||
281
365
  data.members.length < 1 ||
282
- data.members.length > 16
366
+ data.members.length > 256
283
367
  )
284
368
  throw new HostError("Invalid Scope organization configuration.");
285
369
  const identities = new Set<string>(),
@@ -289,8 +373,14 @@ function parseOrganization(value: unknown, configUrl: string): Organization {
289
373
  for (const raw of data.members) {
290
374
  const member = object(raw, "member");
291
375
  if (
292
- Object.keys(member).sort().join() !==
376
+ Object.keys(member)
377
+ .filter((key) => key !== "memberId")
378
+ .sort()
379
+ .join() !==
293
380
  "approval,encryptionKey,peerId,profileId,publicKey,requestId" ||
381
+ (member.memberId !== undefined &&
382
+ (typeof member.memberId !== "string" ||
383
+ !RESOURCE_ID_PATTERN.test(member.memberId))) ||
294
384
  !isCanonicalPublicKey(member.publicKey) ||
295
385
  typeof member.encryptionKey !== "string" ||
296
386
  member.encryptionKey.length > 256 ||
@@ -310,6 +400,9 @@ function parseOrganization(value: unknown, configUrl: string): Organization {
310
400
  peers.add(member.peerId);
311
401
  profiles.add(member.profileId);
312
402
  members.push({
403
+ ...(typeof member.memberId === "string"
404
+ ? { memberId: member.memberId }
405
+ : {}),
313
406
  publicKey: member.publicKey,
314
407
  encryptionKey: member.encryptionKey,
315
408
  peerId: member.peerId,
@@ -331,7 +424,7 @@ function parseOrganization(value: unknown, configUrl: string): Organization {
331
424
  bootstrap.push(address);
332
425
  }
333
426
  return {
334
- v: 1,
427
+ v: data.v,
335
428
  scopeId,
336
429
  owner: data.owner,
337
430
  name: data.name,
@@ -345,9 +438,15 @@ function parseOrganization(value: unknown, configUrl: string): Organization {
345
438
  function parseProfile(value: unknown, expectedPeer: string): Profile {
346
439
  const data = object(value, "member profile");
347
440
  if (
348
- Object.keys(data).sort().join() !== "addresses,name,updatedAt" ||
441
+ ![
442
+ "addresses,name,updatedAt",
443
+ "addresses,description,name,updatedAt",
444
+ ].includes(Object.keys(data).sort().join()) ||
349
445
  typeof data.name !== "string" ||
350
446
  data.name.length > 256 ||
447
+ (data.description !== undefined &&
448
+ (typeof data.description !== "string" ||
449
+ data.description.length > 2048)) ||
351
450
  typeof data.updatedAt !== "string" ||
352
451
  !Number.isFinite(Date.parse(data.updatedAt)) ||
353
452
  !Array.isArray(data.addresses) ||
@@ -361,24 +460,348 @@ function parseProfile(value: unknown, expectedPeer: string): Profile {
361
460
  validateAddress(address, expectedPeer);
362
461
  addresses.push(address);
363
462
  }
364
- return { name: data.name, addresses, updatedAt: data.updatedAt };
463
+ return {
464
+ name: data.name,
465
+ ...(typeof data.description === "string"
466
+ ? { description: data.description }
467
+ : {}),
468
+ addresses,
469
+ updatedAt: data.updatedAt,
470
+ };
471
+ }
472
+ export async function swarmMembers(context: SwarmContext, url: string) {
473
+ const { config } = await fetchConfig(context, canonicalSwarmUrl(url));
474
+ const c = coordinates(url),
475
+ api = client(context, c.service);
476
+ const members = await boundedMap(config.members, async (member) => {
477
+ const profile = parseProfile(
478
+ (await api.read(c.scopeId, member.profileId)).value,
479
+ member.peerId,
480
+ );
481
+ return {
482
+ publicKey: member.publicKey,
483
+ role: member.publicKey === config.owner ? "owner" : "member",
484
+ name: profile.name,
485
+ description: profile.description ?? "",
486
+ };
487
+ });
488
+ return { configUrl: url, members };
489
+ }
490
+
491
+ function accountProfileLocation(context: SwarmContext, publicKey: string) {
492
+ return {
493
+ parent: join(
494
+ resolve(context.env.HOME ?? context.env.USERPROFILE ?? homedir()),
495
+ ".ipab",
496
+ ),
497
+ name: `${createHash("sha256").update(publicKey).digest("hex")}.json`,
498
+ };
499
+ }
500
+ async function storedAccountProfile(
501
+ context: SwarmContext,
502
+ ): Promise<AccountProfile | undefined> {
503
+ const identity = await contextIdentity(context);
504
+ const { parent, name } = accountProfileLocation(context, identity.publicKey);
505
+ try {
506
+ await lstat(join(parent, "profiles"));
507
+ } catch (cause) {
508
+ if (nodeError(cause, "ENOENT")) return undefined;
509
+ throw cause;
510
+ }
511
+ await protectedPath(parent, true);
512
+ await protectedPath(join(parent, "profiles"), true);
513
+ const value = await readPrivate<unknown>(join(parent, "profiles"), name);
514
+ if (value === undefined) return undefined;
515
+ const data = object(value, "account profile");
516
+ if (
517
+ Object.keys(data).sort().join() !==
518
+ "description,name,publicKey,updatedAt" ||
519
+ data.publicKey !== identity.publicKey ||
520
+ typeof data.name !== "string" ||
521
+ data.name.length > 256 ||
522
+ typeof data.description !== "string" ||
523
+ data.description.length > 2048 ||
524
+ typeof data.updatedAt !== "string" ||
525
+ !Number.isFinite(Date.parse(data.updatedAt))
526
+ )
527
+ throw new HostError(
528
+ "Invalid protected account profile; restore the existing profile file.",
529
+ );
530
+ return {
531
+ publicKey: identity.publicKey,
532
+ name: data.name,
533
+ description: data.description,
534
+ updatedAt: data.updatedAt,
535
+ };
536
+ }
537
+ async function accountProfileDirectory(
538
+ context: SwarmContext,
539
+ publicKey: string,
540
+ ) {
541
+ const { parent } = accountProfileLocation(context, publicKey);
542
+ try {
543
+ await lstat(parent);
544
+ } catch (cause) {
545
+ if (!nodeError(cause, "ENOENT")) throw cause;
546
+ await mkdir(parent, { mode: 0o700 });
547
+ await secureNew(parent, true);
548
+ }
549
+ await protectedPath(parent, true);
550
+ return privateDirectory(parent, "profiles");
551
+ }
552
+ async function initialAccountProfile(
553
+ context: SwarmContext,
554
+ changes: { name?: string; description?: string } = {},
555
+ ): Promise<AccountProfile> {
556
+ const identity = await contextIdentity(context);
557
+ if (changes.name !== undefined && changes.description !== undefined)
558
+ return {
559
+ publicKey: identity.publicKey,
560
+ name: changes.name,
561
+ description: changes.description,
562
+ updatedAt: null,
563
+ };
564
+ const legacy: Profile[] = [];
565
+ for (const entry of withState(context, (state) => state.swarms())) {
566
+ const { config } = await fetchConfig(context, entry.cid);
567
+ const self = config.members.find(
568
+ (member) => member.publicKey === identity.publicKey,
569
+ );
570
+ if (!self) continue; // Pending requests have no public profile yet.
571
+ const c = coordinates(entry.cid);
572
+ legacy.push(
573
+ parseProfile(
574
+ (await client(context, c.service).read(c.scopeId, self.profileId))
575
+ .value,
576
+ self.peerId,
577
+ ),
578
+ );
579
+ }
580
+ const field = (key: "name" | "description") => {
581
+ if (changes[key] !== undefined) return changes[key];
582
+ const values = new Set(legacy.map((profile) => profile[key] ?? ""));
583
+ if (values.size > 1)
584
+ throw new HostError(
585
+ `Legacy Swarm profiles disagree on ${key}. Run ipab profile --${key} TEXT to choose your account-wide value; no profile has been saved.`,
586
+ );
587
+ return values.values().next().value ?? "";
588
+ };
589
+ return {
590
+ publicKey: identity.publicKey,
591
+ name: field("name"),
592
+ description: field("description"),
593
+ updatedAt: null,
594
+ };
595
+ }
596
+ export async function accountProfile(
597
+ context: SwarmContext,
598
+ ): Promise<AccountProfile> {
599
+ return (
600
+ (await storedAccountProfile(context)) ??
601
+ (await initialAccountProfile(context))
602
+ );
603
+ }
604
+ async function ensureAccountProfile(
605
+ context: SwarmContext,
606
+ changes: { name?: string; description?: string } = {},
607
+ ) {
608
+ const identity = await contextIdentity(context);
609
+ const dir = await accountProfileDirectory(context, identity.publicKey);
610
+ return withPrivateLock(dir, async () => {
611
+ const existing = await storedAccountProfile(context);
612
+ if (
613
+ existing &&
614
+ changes.name === undefined &&
615
+ changes.description === undefined
616
+ )
617
+ return existing;
618
+ const profile = {
619
+ ...(existing ?? (await initialAccountProfile(context, changes))),
620
+ ...changes,
621
+ updatedAt: new Date().toISOString(),
622
+ };
623
+ await writePrivate(
624
+ dir,
625
+ accountProfileLocation(context, identity.publicKey).name,
626
+ profile,
627
+ );
628
+ return profile;
629
+ });
630
+ }
631
+ async function syncAccountProfile(
632
+ context: SwarmContext,
633
+ record: LocalMembership,
634
+ personal: AccountProfile,
635
+ fetched?: { profile: Profile; cid: string },
636
+ ): Promise<Profile> {
637
+ const identity = await contextIdentity(context),
638
+ c = coordinates(record.configUrl);
639
+ const self = record.config!.members.find(
640
+ (member) => member.publicKey === identity.publicKey,
641
+ )!;
642
+ const api = client(
643
+ context,
644
+ c.service,
645
+ identity,
646
+ identity.publicKey === record.owner ? undefined : record.secret,
647
+ );
648
+ let existing = fetched;
649
+ if (!existing) {
650
+ const variable = await api.read(c.scopeId, self.profileId);
651
+ existing = {
652
+ profile: parseProfile(variable.value, self.peerId),
653
+ cid: variable.cid,
654
+ };
655
+ }
656
+ const old = existing.profile;
657
+ if (old.name === personal.name && old.description === personal.description)
658
+ return old;
659
+ const profile = {
660
+ ...old,
661
+ name: personal.name,
662
+ description: personal.description,
663
+ updatedAt: new Date().toISOString(),
664
+ };
665
+ await api.write(c.scopeId, self.profileId, profile, existing.cid, uniqueId());
666
+ return profile;
667
+ }
668
+ export async function updateAccountProfile(
669
+ context: SwarmContext,
670
+ changes: { name?: string; description?: string },
671
+ ) {
672
+ if (
673
+ (changes.name?.length ?? 0) > 256 ||
674
+ (changes.description?.length ?? 0) > 2048
675
+ )
676
+ throw new HostError("Profile name/description limit exceeded.");
677
+ await contextIdentity(context, true);
678
+ let profile: AccountProfile;
679
+ try {
680
+ profile = await ensureAccountProfile(context, changes);
681
+ } catch (cause) {
682
+ throw new HostError(
683
+ `Personal profile local persistence failed: ${message(cause)}. No Swarm synchronization was attempted.`,
684
+ );
685
+ }
686
+ const swarms: { configUrl: string; synchronized: boolean; error?: string }[] =
687
+ [];
688
+ for (const entry of withState(context, (state) => state.swarms())) {
689
+ try {
690
+ const record = await approvedMembership(context, entry.cid);
691
+ await syncAccountProfile(context, record, profile);
692
+ swarms.push({ configUrl: entry.cid, synchronized: true });
693
+ } catch (cause) {
694
+ swarms.push({
695
+ configUrl: entry.cid,
696
+ synchronized: false,
697
+ error: message(cause),
698
+ });
699
+ }
700
+ }
701
+ return { profile, localPersisted: true, swarms };
365
702
  }
366
703
  async function fetchConfig(
367
704
  context: SwarmContext,
368
705
  configUrl: string,
706
+ signal?: AbortSignal,
369
707
  ): Promise<{ config: Organization; variable: Variable }> {
370
708
  const c = coordinates(configUrl),
371
709
  api = client(context, c.service);
710
+ const options = signal ? { signal } : {};
372
711
  const [variable, scope] = await Promise.all([
373
- api.read(c.scopeId, c.configId),
374
- api.send<{ owner: string }>("GET", c.scopeId),
712
+ api.read(c.scopeId, c.configId, options),
713
+ api.send<{ owner: string }>("GET", c.scopeId, "", undefined, options),
375
714
  ]);
376
- const config = parseOrganization(variable.value, configUrl);
377
- if (scope.owner !== config.owner)
715
+ const raw = object(variable.value, "organization configuration");
716
+ if (scope.owner !== raw.owner)
378
717
  throw new HostError(
379
718
  "Organization Owner does not match the immutable Scope trust root.",
380
719
  );
381
- return { config, variable };
720
+ if (raw.v === 2) {
721
+ if (
722
+ !Array.isArray(raw.members) ||
723
+ raw.members.length < 1 ||
724
+ raw.members.length > 256
725
+ )
726
+ throw new HostError("Invalid organization member directory.");
727
+ const ids = new Set<string>(),
728
+ identities = new Set<string>();
729
+ const directory = raw.members.map((item: unknown) => {
730
+ const member = object(item, "member directory entry");
731
+ if (
732
+ Object.keys(member).sort().join() !== "memberId,publicKey" ||
733
+ !isCanonicalPublicKey(member.publicKey) ||
734
+ typeof member.memberId !== "string" ||
735
+ !RESOURCE_ID_PATTERN.test(member.memberId) ||
736
+ ids.has(member.memberId) ||
737
+ identities.has(member.publicKey)
738
+ )
739
+ throw new HostError("Invalid or duplicate member directory entry.");
740
+ ids.add(member.memberId);
741
+ identities.add(member.publicKey);
742
+ return { publicKey: member.publicKey, memberId: member.memberId };
743
+ });
744
+ const members = await boundedMap(directory, async (entry) => {
745
+ const member = object(
746
+ (await api.read(c.scopeId, entry.memberId, options)).value,
747
+ "member record",
748
+ );
749
+ if (member.publicKey !== entry.publicKey)
750
+ throw new HostError(
751
+ "Member record does not match its directory identity.",
752
+ );
753
+ return { ...member, memberId: entry.memberId };
754
+ });
755
+ return {
756
+ config: parseOrganization({ ...raw, members }, configUrl),
757
+ variable,
758
+ };
759
+ }
760
+ return { config: parseOrganization(raw, configUrl), variable };
761
+ }
762
+ async function boundedMap<T, U>(
763
+ items: readonly T[],
764
+ operation: (item: T) => Promise<U>,
765
+ ): Promise<U[]> {
766
+ const results: U[] = [];
767
+ for (let offset = 0; offset < items.length; offset += 16) {
768
+ const batch = await Promise.allSettled(
769
+ items.slice(offset, offset + 16).map(operation),
770
+ );
771
+ for (const result of batch) {
772
+ if (result.status === "rejected") throw result.reason;
773
+ results.push(result.value);
774
+ }
775
+ }
776
+ return results;
777
+ }
778
+ function configValue(config: Organization): unknown {
779
+ if (config.v === 1) return config;
780
+ return {
781
+ ...config,
782
+ members: config.members.map((member) => {
783
+ if (!member.memberId)
784
+ throw new HostError("Member directory is missing its record ID.");
785
+ return { publicKey: member.publicKey, memberId: member.memberId };
786
+ }),
787
+ };
788
+ }
789
+ async function createMemberRecord(
790
+ api: ScopeClient,
791
+ scopeId: string,
792
+ member: Member,
793
+ key: string,
794
+ ): Promise<Member> {
795
+ const value = {
796
+ publicKey: member.publicKey,
797
+ encryptionKey: member.encryptionKey,
798
+ peerId: member.peerId,
799
+ profileId: member.profileId,
800
+ requestId: member.requestId,
801
+ approval: member.approval,
802
+ };
803
+ const created = await api.create(scopeId, value, key);
804
+ return { ...value, memberId: created.id };
382
805
  }
383
806
  function binding(
384
807
  configUrl: string,
@@ -436,10 +859,11 @@ async function validateMembershipSecret(
436
859
  );
437
860
  }
438
861
  }
439
- async function activate(
862
+ async function privateSource(
440
863
  context: SwarmContext,
441
864
  record: LocalMembership,
442
- ): Promise<void> {
865
+ signal?: AbortSignal,
866
+ ) {
443
867
  const config = record.config!,
444
868
  secret = record.secret!;
445
869
  const identity = await contextIdentity(context);
@@ -469,41 +893,56 @@ async function activate(
469
893
  identity.publicKey,
470
894
  );
471
895
  }
472
- const addresses = [...config.bootstrap];
896
+ const personal = await storedAccountProfile(context);
897
+ const addresses = new Map<string, readonly string[]>();
473
898
  const api = client(context, c.service);
474
899
  let selfProfile: { profile: Profile; cid: string } | undefined;
475
- const profiles = await Promise.allSettled(
476
- config.members.map((member) => api.read(c.scopeId, member.profileId)),
900
+ const profiles = await boundedMap(config.members, (member) =>
901
+ api.read(c.scopeId, member.profileId, signal ? { signal } : {}),
477
902
  );
478
903
  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;
904
+ const profile = profiles[index]!;
482
905
  const value = parseProfile(profile.value, member.peerId);
483
906
  if (member.publicKey === identity.publicKey)
484
907
  selfProfile = { profile: value, cid: profile.cid };
485
- addresses.push(...value.addresses);
908
+ addresses.set(member.peerId, value.addresses);
486
909
  }
910
+ if (personal && selfProfile) {
911
+ selfProfile.profile = await syncAccountProfile(
912
+ context,
913
+ record,
914
+ personal,
915
+ selfProfile,
916
+ );
917
+ selfProfile.cid = await valueCid(selfProfile.profile);
918
+ }
919
+ const desired = memberPeers(self.peerId, addresses, config.bootstrap);
920
+ signal?.throwIfAborted();
487
921
  const node = await startNode(
488
922
  context.stateDir,
489
923
  nodeScope(c.service, config.scopeId),
490
924
  secret.swarmKey,
491
925
  config.epoch,
492
- [...new Set(addresses)],
493
- context.diagnostic,
494
926
  context.listen,
927
+ { self: self.peerId, peers: desired, ...(signal ? { signal } : {}) },
495
928
  );
496
929
  if (node.peerId !== self.peerId)
497
930
  throw new HostError(
498
931
  "Approved PeerID differs from this local Request's Kubo identity.",
499
932
  );
500
- if (context.node?.api !== node.api) {
501
- const store = context.store.withLocalSource(kuboSource(node));
502
- await context.store.close();
503
- context.store = store;
504
- }
505
- context.node = node;
506
- if (selfProfile && selfProfile.profile.addresses.length === 0) {
933
+ const peers = desired.flatMap(({ ID, Addrs }) =>
934
+ Addrs.map((addr) => `${addr}/p2p/${ID}`),
935
+ );
936
+ signal?.throwIfAborted();
937
+ if (!node.addresses.length && !selfProfile?.profile.addresses.length)
938
+ context.diagnostic?.(
939
+ "No private LAN/VPN IPv4 address to advertise. Connect a routed interface or set your own address with swarm profile --address.",
940
+ );
941
+ if (
942
+ node.addresses.length &&
943
+ selfProfile &&
944
+ selfProfile.profile.addresses.length === 0
945
+ ) {
507
946
  const writer = client(
508
947
  context,
509
948
  c.service,
@@ -521,10 +960,35 @@ async function activate(
521
960
  profile,
522
961
  selfProfile.cid,
523
962
  uniqueId(),
963
+ signal ? { signal } : {},
524
964
  );
525
965
  }
966
+ return {
967
+ node,
968
+ peers,
969
+ source: kuboSource(
970
+ node,
971
+ peers,
972
+ context.diagnostic,
973
+ context.env.IPAB_SWARM_DIAL_DEBUG === "1",
974
+ ),
975
+ };
976
+ }
977
+ async function activate(context: SwarmContext, record: LocalMembership) {
978
+ const { node, peers, source } = await privateSource(context, record);
979
+ if (
980
+ context.node?.api !== node.api ||
981
+ context.sourcePeers?.length !== peers.length ||
982
+ peers.some((peer, i) => context.sourcePeers?.[i] !== peer)
983
+ ) {
984
+ const store = context.store.withLocalSource(source);
985
+ await context.store.close();
986
+ context.store = store;
987
+ context.sourcePeers = peers;
988
+ }
989
+ context.node = node;
526
990
  }
527
- async function refresh(
991
+ async function localForRead(
528
992
  context: SwarmContext,
529
993
  configUrl: string,
530
994
  ): Promise<LocalMembership> {
@@ -539,7 +1003,15 @@ async function refresh(
539
1003
  "Organization switch incomplete; only Owner can continue with swarm resume.",
540
1004
  );
541
1005
  }
542
- const { config } = await fetchConfig(context, configUrl);
1006
+ return record;
1007
+ }
1008
+ async function approvedMembership(
1009
+ context: SwarmContext,
1010
+ configUrl: string,
1011
+ signal?: AbortSignal,
1012
+ ) {
1013
+ const record = await localForRead(context, configUrl);
1014
+ const { config } = await fetchConfig(context, configUrl, signal);
543
1015
  if (config.owner !== record.owner)
544
1016
  throw new HostError("Pinned Owner changed; refusing configuration.");
545
1017
  if (record.config && config.epoch < record.config.epoch)
@@ -573,6 +1045,10 @@ async function refresh(
573
1045
  );
574
1046
  record.config = config;
575
1047
  await validateMembershipSecret(record, config, member);
1048
+ return record;
1049
+ }
1050
+ async function refresh(context: SwarmContext, configUrl: string) {
1051
+ const record = await approvedMembership(context, configUrl);
576
1052
  await saveLocal(context, record);
577
1053
  await activate(context, record);
578
1054
  return record;
@@ -581,17 +1057,7 @@ async function readyMembership(
581
1057
  context: SwarmContext,
582
1058
  configUrl: string,
583
1059
  ): Promise<LocalMembership> {
584
- const record = await local(context, configUrl);
585
- if (record.account === record.owner) {
586
- const transition = await readPrivate<Removal>(
587
- await directory(context),
588
- `transition-${localName(configUrl)}`,
589
- );
590
- if (transition && !transition.completed)
591
- throw new HostError(
592
- "Organization switch incomplete; run swarm resume before normal Owner operations.",
593
- );
594
- }
1060
+ const record = await localForRead(context, configUrl);
595
1061
  if (!record.config || !record.secret) return refresh(context, configUrl);
596
1062
  if (
597
1063
  !context.node ||
@@ -608,6 +1074,9 @@ async function readyMembership(
608
1074
  return refresh(context, configUrl);
609
1075
  throw cause;
610
1076
  }
1077
+ } else {
1078
+ const personal = await storedAccountProfile(context);
1079
+ if (personal) await syncAccountProfile(context, record, personal);
611
1080
  }
612
1081
  return record;
613
1082
  }
@@ -760,15 +1229,49 @@ export async function writeSnapshot(
760
1229
  store: IpfsStore,
761
1230
  snapshot: Snapshot,
762
1231
  ): Promise<string> {
763
- const encoded = dagCbor.encode(snapshot),
764
- cid = CID.createV1(dagCbor.code, await sha256.digest(encoded));
765
- await store.put(cid, encoded);
766
- return cid.toString();
1232
+ const put = async (value: unknown) => {
1233
+ const encoded = dagCbor.encode(value);
1234
+ const cid = CID.createV1(dagCbor.code, await sha256.digest(encoded));
1235
+ await store.put(cid, encoded);
1236
+ return cid;
1237
+ };
1238
+ const names = await put(snapshot.names);
1239
+ const registrations = await put(snapshot.registrations ?? {});
1240
+ return (await put({ v: 3, names, registrations })).toString();
1241
+ }
1242
+ async function readState(store: IpfsStore, cid: CID): Promise<Snapshot> {
1243
+ const data = await store.block.get(cid.toString());
1244
+ const root = object(dagCbor.decode(data), "State");
1245
+ if (root.v !== 3) return decodeSnapshot(data);
1246
+ const names = CID.asCID(root.names),
1247
+ registrations = CID.asCID(root.registrations);
1248
+ if (
1249
+ !names ||
1250
+ !registrations ||
1251
+ Object.keys(root).sort().join() !== "names,registrations,v"
1252
+ )
1253
+ throw new HostError("Invalid State index roots.");
1254
+ const [namesBlock, registrationsBlock] = await Promise.all([
1255
+ store.block.get(names.toString()),
1256
+ store.block.get(registrations.toString()),
1257
+ ]);
1258
+ return decodeSnapshot(
1259
+ dagCbor.encode({
1260
+ v: 2,
1261
+ names: dagCbor.decode(namesBlock),
1262
+ registrations: dagCbor.decode(registrationsBlock),
1263
+ }),
1264
+ );
767
1265
  }
768
1266
  function decodeSnapshot(data: Uint8Array): Snapshot {
769
1267
  const value = object(dagCbor.decode(data), "State"),
770
1268
  names = object(value.names, "Names");
771
- if (value.v !== 2 || Object.keys(value).sort().join() !== "names,v")
1269
+ if (
1270
+ value.v !== 2 ||
1271
+ Object.keys(value).some(
1272
+ (key) => !["v", "names", "registrations"].includes(key),
1273
+ )
1274
+ )
772
1275
  throw new HostError("Unsupported old State; rebuild the Swarm.");
773
1276
  const links: [string, CID][] = [];
774
1277
  for (const [name, link] of Object.entries(names)) {
@@ -777,14 +1280,53 @@ function decodeSnapshot(data: Uint8Array): Snapshot {
777
1280
  if (!cid) throw new HostError("Names must link CIDs.");
778
1281
  links.push([name, cid]);
779
1282
  }
780
- return { v: 2, names: Object.fromEntries(links) };
1283
+ const registrations: NonNullable<Snapshot["registrations"]> = {};
1284
+ if (value.registrations !== undefined) {
1285
+ for (const [schema, raw] of Object.entries(
1286
+ object(value.registrations, "Registrations"),
1287
+ )) {
1288
+ const item = object(raw, "Association");
1289
+ const appCid = CID.asCID(item.appCid);
1290
+ if (
1291
+ Object.keys(item).sort().join() !== "appCid,argv" ||
1292
+ !appCid ||
1293
+ !Array.isArray(item.argv) ||
1294
+ !item.argv.every(
1295
+ (argument): argument is string => typeof argument === "string",
1296
+ )
1297
+ )
1298
+ throw new HostError("Invalid shared Association.");
1299
+ const association = createAssociation(
1300
+ schema,
1301
+ appCid.toString(),
1302
+ item.argv,
1303
+ );
1304
+ if (association.schemaCid !== schema)
1305
+ throw new HostError(
1306
+ "Shared Association requires a canonical type CID.",
1307
+ );
1308
+ registrations[schema] = { appCid, argv: association.argv };
1309
+ }
1310
+ }
1311
+ return {
1312
+ v: 2,
1313
+ names: Object.fromEntries(links),
1314
+ ...(value.registrations !== undefined ? { registrations } : {}),
1315
+ };
781
1316
  }
782
1317
  export async function readSnapshot(
783
1318
  store: IpfsStore,
784
1319
  root: string,
785
1320
  ): Promise<Snapshot> {
786
1321
  const publication = await readPublication(store, root);
787
- return decodeSnapshot(await store.block.get(publication.state.toString()));
1322
+ return readState(store, publication.state);
1323
+ }
1324
+ async function readHeaderSnapshot(store: IpfsStore, root: string) {
1325
+ const publication = await readPublication(store, root);
1326
+ return {
1327
+ snapshot: await readState(store, publication.state),
1328
+ stateCid: publication.state.toString(),
1329
+ };
788
1330
  }
789
1331
  async function readPublication(
790
1332
  store: IpfsStore,
@@ -832,6 +1374,9 @@ export interface SwarmHeader {
832
1374
  config: Organization;
833
1375
  source: "cache" | "network";
834
1376
  verifiedAt: string;
1377
+ stateCid: string;
1378
+ projection?: SwarmProjection;
1379
+ localSourceReady?: boolean;
835
1380
  }
836
1381
  export async function sharedSwarmStatus(
837
1382
  context: SwarmContext,
@@ -842,9 +1387,9 @@ export async function sharedSwarmStatus(
842
1387
  const head = headValue(
843
1388
  await client(context, c.service).read(c.scopeId, config.headId),
844
1389
  );
845
- let snapshot: Snapshot;
1390
+ let content: Awaited<ReturnType<typeof readHeaderSnapshot>>;
846
1391
  try {
847
- snapshot = await readSnapshot(context.store, head.root);
1392
+ content = await readHeaderSnapshot(context.store, head.root);
848
1393
  } catch (cause) {
849
1394
  if (!(cause instanceof ContentError) || cause.code !== "missing_block")
850
1395
  throw cause;
@@ -857,74 +1402,297 @@ export async function sharedSwarmStatus(
857
1402
  );
858
1403
  return swarmHeader(context, configUrl, true);
859
1404
  }
860
- return {
1405
+ const header: SwarmHeader = {
861
1406
  head,
862
- snapshot,
1407
+ ...content,
863
1408
  config,
864
1409
  source: "network",
865
1410
  verifiedAt: new Date().toISOString(),
866
1411
  };
1412
+ if (
1413
+ withState(context, (state) =>
1414
+ state
1415
+ .contentPins()
1416
+ .some((pin) => pin.swarm === configUrl && pin.status !== "deleting"),
1417
+ )
1418
+ ) {
1419
+ const record = await localForRead(context, configUrl);
1420
+ await lazyPrivateSource(context, configUrl, record.account, config);
1421
+ await refreshNamePins(context, configUrl, header);
1422
+ }
1423
+ return header;
867
1424
  }
868
1425
  export async function swarmHeader(
869
1426
  context: SwarmContext,
870
1427
  configUrl: string,
871
1428
  force = context.forceRefresh ?? false,
1429
+ mode: "active" | "local-first" = "active",
1430
+ ): Promise<SwarmHeader> {
1431
+ try {
1432
+ return await readSwarmHeader(context, configUrl, force, mode);
1433
+ } catch (cause) {
1434
+ withState(context, (state) => {
1435
+ for (const pin of state.contentPins())
1436
+ if (pin.swarm === configUrl && pin.status !== "deleting")
1437
+ state.saveContentPin({
1438
+ ...pin,
1439
+ freshness: "stale",
1440
+ error: message(cause),
1441
+ });
1442
+ });
1443
+ throw cause;
1444
+ }
1445
+ }
1446
+ async function readSwarmHeader(
1447
+ context: SwarmContext,
1448
+ configUrl: string,
1449
+ force = context.forceRefresh ?? false,
1450
+ mode: "active" | "local-first" = "active",
872
1451
  ): Promise<SwarmHeader> {
873
1452
  canonicalSwarmUrl(configUrl);
874
- let record = force
875
- ? await refresh(context, configUrl)
876
- : await readyMembership(context, configUrl);
877
- const ttl = context.cacheTtl ?? 300;
878
- const cached = force
879
- ? undefined
880
- : (withState(context, (state) =>
881
- state.swarmHeader(record.account, configUrl),
882
- ) as
883
- | {
884
- head: Variable;
885
- snapshot: string;
886
- verifiedAt: number;
887
- headId: string;
888
- }
889
- | undefined);
890
- if (
891
- cached &&
892
- cached.headId === record.config!.headId &&
893
- Date.now() >= cached.verifiedAt &&
894
- Date.now() - cached.verifiedAt < ttl * 1000
895
- )
896
- return {
897
- head: headValue(cached.head),
898
- snapshot: decodeSnapshot(Buffer.from(cached.snapshot, "base64")),
899
- config: record.config!,
900
- source: "cache",
901
- verifiedAt: new Date(cached.verifiedAt).toISOString(),
902
- };
903
- let head = await (await boundPointer(context, configUrl, record)).read();
904
- let snapshot: Snapshot;
1453
+ let record =
1454
+ mode === "local-first"
1455
+ ? await approvedMembership(context, configUrl)
1456
+ : force
1457
+ ? await refresh(context, configUrl)
1458
+ : await readyMembership(context, configUrl);
1459
+ const cached = !force && (await cachedHeader(context, record));
1460
+ if (cached) {
1461
+ projectHeader(context, record, cached);
1462
+ await refreshNamePins(context, configUrl, cached);
1463
+ return cached;
1464
+ }
1465
+ if (mode === "local-first") {
1466
+ await saveLocal(context, record);
1467
+ await lazyPrivateSource(context, configUrl, record.account, record.config!);
1468
+ }
1469
+ const c = coordinates(configUrl);
1470
+ let head =
1471
+ mode === "local-first"
1472
+ ? headValue(
1473
+ await client(context, c.service).read(
1474
+ c.scopeId,
1475
+ record.config!.headId,
1476
+ ),
1477
+ )
1478
+ : await (await boundPointer(context, configUrl, record)).read();
1479
+ let content: Awaited<ReturnType<typeof readHeaderSnapshot>>;
905
1480
  try {
906
- snapshot = await readSnapshot(context.store, head.root);
907
- } catch {
1481
+ content = await readHeaderSnapshot(context.store, head.root);
1482
+ } catch (cause) {
1483
+ if (mode === "local-first") throw cause;
908
1484
  record = await refresh(context, configUrl);
909
1485
  head = await (await boundPointer(context, configUrl, record)).read();
910
- snapshot = await readSnapshot(context.store, head.root);
1486
+ content = await readHeaderSnapshot(context.store, head.root);
911
1487
  }
912
1488
  const current = await local(context, configUrl),
913
1489
  verifiedAt = Date.now();
914
1490
  withState(context, (state) => {
915
1491
  state.saveSwarmHeader(record.account, configUrl, {
916
1492
  head,
917
- snapshot: Buffer.from(dagCbor.encode(snapshot)).toString("base64"),
1493
+ snapshot: Buffer.from(dagCbor.encode(content.snapshot)).toString(
1494
+ "base64",
1495
+ ),
1496
+ stateCid: content.stateCid,
918
1497
  verifiedAt,
919
1498
  headId: current.config!.headId,
1499
+ epoch: current.config!.epoch,
920
1500
  });
921
1501
  });
922
- return {
923
- head,
924
- snapshot,
925
- config: current.config!,
926
- source: "network",
927
- verifiedAt: new Date(verifiedAt).toISOString(),
1502
+ const header: SwarmHeader = {
1503
+ head,
1504
+ ...content,
1505
+ config: current.config!,
1506
+ source: "network",
1507
+ verifiedAt: new Date(verifiedAt).toISOString(),
1508
+ };
1509
+ projectHeader(context, current, header);
1510
+ await refreshNamePins(context, configUrl, header);
1511
+ return header;
1512
+ }
1513
+ async function cachedHeader(
1514
+ context: SwarmContext,
1515
+ record: LocalMembership,
1516
+ ): Promise<SwarmHeader | undefined> {
1517
+ const config = record.config;
1518
+ if (!config || !record.secret) return;
1519
+ const cached = withState(context, (state) =>
1520
+ state.swarmHeader(record.account, record.configUrl),
1521
+ ) as
1522
+ | {
1523
+ head: Variable;
1524
+ snapshot: string;
1525
+ verifiedAt: number;
1526
+ headId: string;
1527
+ epoch?: number;
1528
+ stateCid?: string;
1529
+ }
1530
+ | undefined;
1531
+ const age = cached ? Date.now() - cached.verifiedAt : NaN;
1532
+ if (
1533
+ !cached ||
1534
+ cached.headId !== config.headId ||
1535
+ (cached.epoch !== undefined && cached.epoch !== config.epoch) ||
1536
+ !(age >= 0 && age < (context.cacheTtl ?? 300) * 1000)
1537
+ )
1538
+ return;
1539
+ const snapshot = decodeSnapshot(Buffer.from(cached.snapshot, "base64"));
1540
+ let stateCid = cached.stateCid;
1541
+ if (!stateCid) {
1542
+ try {
1543
+ stateCid = (
1544
+ await readPublication(context.store, headValue(cached.head).root)
1545
+ ).state.toString();
1546
+ } catch (cause) {
1547
+ if (cause instanceof ContentError && cause.code === "missing_block")
1548
+ return;
1549
+ throw cause;
1550
+ }
1551
+ }
1552
+ return {
1553
+ head: headValue(cached.head),
1554
+ snapshot,
1555
+ stateCid,
1556
+ config,
1557
+ source: "cache",
1558
+ verifiedAt: new Date(cached.verifiedAt).toISOString(),
1559
+ };
1560
+ }
1561
+ function projectHeader(
1562
+ context: SwarmContext,
1563
+ record: LocalMembership,
1564
+ header: SwarmHeader,
1565
+ ): void {
1566
+ const member = header.config.members.find(
1567
+ (item) => item.publicKey === record.account,
1568
+ );
1569
+ if (!member || record.owner !== header.config.owner)
1570
+ throw new HostError(
1571
+ "Projection membership does not match the verified account.",
1572
+ );
1573
+ const binding: SwarmProjection = {
1574
+ account: record.account,
1575
+ swarm: record.configUrl,
1576
+ stateCid: header.stateCid,
1577
+ root: header.head.root,
1578
+ valueCid: header.head.cid,
1579
+ verifiedAt: Date.parse(header.verifiedAt),
1580
+ headId: header.config.headId,
1581
+ epoch: header.config.epoch,
1582
+ membership: JSON.stringify({ owner: record.owner, member }),
1583
+ };
1584
+ withState(context, (state) => {
1585
+ state.projectSwarm(binding, header.snapshot.names, () =>
1586
+ snapshotAssociations(header.snapshot),
1587
+ );
1588
+ });
1589
+ header.projection = binding;
1590
+ }
1591
+ function headerProjection(header: SwarmHeader): SwarmProjection {
1592
+ if (!header.projection)
1593
+ throw new HostError("A verified account projection is required.");
1594
+ return header.projection;
1595
+ }
1596
+ async function localHeader(context: SwarmContext, url: string) {
1597
+ if (context.forceRefresh) return;
1598
+ canonicalSwarmUrl(url);
1599
+ const record = await localForRead(context, url);
1600
+ const header = await cachedHeader(context, record);
1601
+ if (!header) return;
1602
+ const config = parseOrganization(header.config, url);
1603
+ const member = config.members.find(
1604
+ (item) => item.publicKey === record.account,
1605
+ );
1606
+ if (!member || config.owner !== record.owner)
1607
+ throw new HostError(
1608
+ "Cached membership no longer matches the account or Owner.",
1609
+ );
1610
+ if (
1611
+ record.account !== config.owner &&
1612
+ (!record.request ||
1613
+ record.request.id !== member.requestId ||
1614
+ record.request.peerId !== member.peerId ||
1615
+ !member.approval)
1616
+ )
1617
+ throw new HostError("Cached membership does not match the saved Request.");
1618
+ await validateMembershipSecret(record, config, member);
1619
+ const c = coordinates(url);
1620
+ await checkCachedNode(
1621
+ context.stateDir,
1622
+ nodeScope(c.service, c.scopeId),
1623
+ config.epoch,
1624
+ member.peerId,
1625
+ );
1626
+ projectHeader(context, record, header);
1627
+ if (
1628
+ withState(context, (state) =>
1629
+ state
1630
+ .contentPins()
1631
+ .some((pin) => pin.swarm === url && pin.status !== "deleting"),
1632
+ )
1633
+ ) {
1634
+ await lazyPrivateSource(context, url, record.account, header.config);
1635
+ header.localSourceReady = true;
1636
+ await refreshNamePins(context, url, header);
1637
+ }
1638
+ return { header, account: record.account };
1639
+ }
1640
+
1641
+ // SharedContent invokes this source only after a genuine local ENOENT. Its
1642
+ // store is not replaced from inside its own pending read (which would deadlock).
1643
+ async function lazyPrivateSource(
1644
+ context: SwarmContext,
1645
+ url: string,
1646
+ account: string,
1647
+ basis: Organization,
1648
+ ) {
1649
+ const finishPrevious = context.finishRead;
1650
+ delete context.finishRead;
1651
+ await finishPrevious?.();
1652
+ const lifetime = new AbortController();
1653
+ let pending: Promise<ReturnType<typeof kuboSource>> | undefined;
1654
+ const load = async (signal: AbortSignal) => {
1655
+ const scoped: SwarmContext = { ...context };
1656
+ // Re-read the protected HOME binding and live approval on the first miss;
1657
+ // do not serve an old resolved Name through a different epoch or identity.
1658
+ delete scoped.identity;
1659
+ const authorize = async () => {
1660
+ const record = await approvedMembership(scoped, url, signal);
1661
+ signal.throwIfAborted();
1662
+ if (
1663
+ record.account !== account ||
1664
+ record.config!.owner !== basis.owner ||
1665
+ record.config!.epoch !== basis.epoch ||
1666
+ record.config!.headId !== basis.headId
1667
+ )
1668
+ throw new HostError(
1669
+ "Swarm membership changed since this cached HEAD; retry with --force.",
1670
+ );
1671
+ return (await privateSource(scoped, record, signal)).source;
1672
+ };
1673
+ // Same lock order as Owner rotation: credentials first, then the node.
1674
+ return withPrivateLock(await directory(scoped), authorize, signal);
1675
+ };
1676
+ const store = context.store.withLocalSource({
1677
+ block: {
1678
+ async get(cid, options = {}) {
1679
+ const signal = options.signal
1680
+ ? AbortSignal.any([lifetime.signal, options.signal])
1681
+ : lifetime.signal;
1682
+ signal.throwIfAborted();
1683
+ const source = await (pending ??= load(signal));
1684
+ signal.throwIfAborted();
1685
+ return source.block.get(cid, { signal });
1686
+ },
1687
+ },
1688
+ });
1689
+ await context.store.close();
1690
+ context.store = store;
1691
+ delete context.node;
1692
+ delete context.sourcePeers;
1693
+ context.finishRead = async () => {
1694
+ lifetime.abort();
1695
+ await pending?.catch(() => {});
928
1696
  };
929
1697
  }
930
1698
  export async function addSwarm(
@@ -944,6 +1712,8 @@ interface Creation {
944
1712
  name: string;
945
1713
  description: string;
946
1714
  createdAt: string;
1715
+ personal?: { name: string; description: string };
1716
+ profile?: Profile;
947
1717
  scopeId?: string;
948
1718
  headId?: string;
949
1719
  profileId?: string;
@@ -979,6 +1749,7 @@ export async function createSwarm(
979
1749
  const identity = await contextIdentity(context, true),
980
1750
  op = options.resume ?? uniqueId(),
981
1751
  dir = await directory(context);
1752
+ const personal = await ensureAccountProfile(context);
982
1753
  if (!POINTER_ID_PATTERN.test(op))
983
1754
  throw new HostError("Invalid creation resume ID.");
984
1755
  return withPrivateLock(dir, async () => {
@@ -1002,6 +1773,7 @@ export async function createSwarm(
1002
1773
  name: options.properties?.name ?? "",
1003
1774
  description: options.properties?.description ?? "",
1004
1775
  createdAt: new Date().toISOString(),
1776
+ personal: { name: personal.name, description: personal.description },
1005
1777
  };
1006
1778
  await writePrivate(dir, `creation-${op}.json`, record);
1007
1779
  }
@@ -1030,20 +1802,38 @@ export async function createSwarm(
1030
1802
  await save();
1031
1803
  }
1032
1804
  if (!record.profileId) {
1033
- const addresses = options.addresses ?? node.addresses;
1034
- for (const address of addresses) validateAddress(address, node.peerId);
1805
+ if (!record.profile) {
1806
+ const addresses = options.addresses ?? node.addresses;
1807
+ for (const address of addresses)
1808
+ validateAddress(address, node.peerId);
1809
+ record.profile = {
1810
+ ...(record.personal ?? { name: record.name }),
1811
+ addresses,
1812
+ updatedAt: record.createdAt,
1813
+ };
1814
+ await save();
1815
+ }
1035
1816
  record.profileId = (
1036
- await api.create(
1037
- record.scopeId,
1038
- { name: record.name, addresses, updatedAt: record.createdAt },
1039
- `${op}.profile`,
1040
- )
1817
+ await api.create(record.scopeId, record.profile, `${op}.profile`)
1041
1818
  ).id;
1042
1819
  await save();
1043
1820
  }
1044
1821
  if (!record.config) {
1822
+ const member = await createMemberRecord(
1823
+ api,
1824
+ record.scopeId,
1825
+ {
1826
+ publicKey: identity.publicKey,
1827
+ encryptionKey: record.encryption.publicKey,
1828
+ peerId: node.peerId,
1829
+ profileId: record.profileId,
1830
+ requestId: op,
1831
+ approval: null,
1832
+ },
1833
+ `${op}.member`,
1834
+ );
1045
1835
  record.config = {
1046
- v: 1,
1836
+ v: 2,
1047
1837
  scopeId: record.scopeId,
1048
1838
  owner: identity.publicKey,
1049
1839
  name: record.name,
@@ -1051,22 +1841,17 @@ export async function createSwarm(
1051
1841
  headId: record.headId,
1052
1842
  epoch: 1,
1053
1843
  bootstrap: options.addresses ?? node.addresses,
1054
- members: [
1055
- {
1056
- publicKey: identity.publicKey,
1057
- encryptionKey: record.encryption.publicKey,
1058
- peerId: node.peerId,
1059
- profileId: record.profileId,
1060
- requestId: op,
1061
- approval: null,
1062
- },
1063
- ],
1844
+ members: [member],
1064
1845
  };
1065
1846
  await save();
1066
1847
  }
1067
1848
  if (!record.configId) {
1068
1849
  record.configId = (
1069
- await api.create(record.scopeId, record.config, `${op}.config`)
1850
+ await api.create(
1851
+ record.scopeId,
1852
+ configValue(record.config),
1853
+ `${op}.config`,
1854
+ )
1070
1855
  ).id;
1071
1856
  await save();
1072
1857
  }
@@ -1133,21 +1918,23 @@ export async function requestMembership(
1133
1918
  context: SwarmContext,
1134
1919
  url: string,
1135
1920
  options: {
1136
- ownerFingerprint: string;
1137
- name?: string;
1138
1921
  alias?: string;
1139
1922
  output?: string;
1140
1923
  },
1141
- ): Promise<string> {
1142
- if ((options.name?.length ?? 0) > 256)
1143
- throw new HostError("Request name exceeds 256 characters.");
1924
+ ): Promise<{
1925
+ requestId: string;
1926
+ ownerFingerprint: string;
1927
+ request: MembershipRequest;
1928
+ file?: string;
1929
+ }> {
1930
+ if ("name" in options)
1931
+ throw new HostError(
1932
+ "Set your account-wide name with ipab profile --name NAME before requesting membership.",
1933
+ );
1144
1934
  canonicalSwarmUrl(url);
1145
1935
  const identity = await contextIdentity(context, true);
1146
1936
  const { config } = await fetchConfig(context, url);
1147
- if (options.ownerFingerprint !== (await keyId(config.owner)))
1148
- throw new HostError(
1149
- `Trusted Owner fingerprint required; observed ${await keyId(config.owner)}. Verify through an independent trusted channel.`,
1150
- );
1937
+ const personal = await ensureAccountProfile(context);
1151
1938
  const dir = await directory(context);
1152
1939
  await withPrivateLock(dir, async () => {
1153
1940
  if (options.alias !== undefined)
@@ -1181,7 +1968,7 @@ export async function requestMembership(
1181
1968
  configUrl: url,
1182
1969
  scopeId: config.scopeId,
1183
1970
  owner: config.owner,
1184
- name: options.name ?? "",
1971
+ name: personal.name,
1185
1972
  member: identity.publicKey,
1186
1973
  encryptionKey: encryption.publicKey,
1187
1974
  peerId: node.peerId,
@@ -1207,15 +1994,46 @@ export async function requestMembership(
1207
1994
  });
1208
1995
  withState(context, (state) => state.registerSwarm(url, options.alias));
1209
1996
  });
1210
- if (options.output) await exportRequest(context, url, options.output);
1211
- return (await local(context, url)).request!.id;
1997
+ const file =
1998
+ options.output === undefined ? undefined : resolve(options.output);
1999
+ if (file !== undefined) await exportRequest(context, url, file);
2000
+ const record = await local(context, url);
2001
+ return {
2002
+ requestId: record.request!.id,
2003
+ ownerFingerprint: await keyId(record.owner),
2004
+ request: record.request!,
2005
+ ...(file === undefined ? {} : { file }),
2006
+ };
1212
2007
  }
1213
2008
  export async function verifiedRequest(
1214
2009
  path: string,
1215
2010
  ): Promise<MembershipRequest> {
1216
2011
  if ((await lstat(path)).size > 16 * 1024)
1217
2012
  throw new HostError("Request file exceeds 16 KiB.");
1218
- return verifyRequest(JSON.parse(await readFile(path, "utf8")) as unknown);
2013
+ return verifiedRequestStream(createReadStream(path));
2014
+ }
2015
+ export async function verifiedRequestStream(
2016
+ input: AsyncIterable<string | Uint8Array>,
2017
+ ): Promise<MembershipRequest> {
2018
+ const chunks: Uint8Array[] = [];
2019
+ let size = 0;
2020
+ for await (const chunk of input) {
2021
+ const bytes = typeof chunk === "string" ? Buffer.from(chunk) : chunk;
2022
+ size += bytes.byteLength;
2023
+ if (size > 16 * 1024) throw new HostError("Request input exceeds 16 KiB.");
2024
+ chunks.push(bytes);
2025
+ }
2026
+ let value: unknown;
2027
+ try {
2028
+ value = JSON.parse(
2029
+ Buffer.concat(chunks)
2030
+ .toString("utf8")
2031
+ .replace(/^\uFEFF/, ""),
2032
+ );
2033
+ } catch (cause) {
2034
+ throw new HostError(`Invalid Request JSON: ${message(cause)}.`);
2035
+ }
2036
+ return verifyRequest(value);
1219
2037
  }
1220
2038
  async function verifyRequest(input: unknown): Promise<MembershipRequest> {
1221
2039
  const fields = object(input, "Request");
@@ -1417,6 +2235,7 @@ export async function approveMembership(
1417
2235
  c.scopeId,
1418
2236
  {
1419
2237
  name: request.name,
2238
+ description: "",
1420
2239
  addresses: [],
1421
2240
  updatedAt: operation.createdAt,
1422
2241
  },
@@ -1436,6 +2255,7 @@ export async function approveMembership(
1436
2255
  };
1437
2256
  const config = {
1438
2257
  ...fetched.config,
2258
+ v: 2 as const,
1439
2259
  members: fetched.config.members.filter(
1440
2260
  (m) => m.publicKey !== request.member,
1441
2261
  ),
@@ -1444,8 +2264,8 @@ export async function approveMembership(
1444
2264
  throw new HostError("PeerID is already assigned to another member.");
1445
2265
  if (request.member === identity.publicKey)
1446
2266
  throw new HostError("Owner cannot request member approval.");
1447
- if (config.members.length >= 16)
1448
- throw new HostError("Organization member limit is 16.");
2267
+ if (config.members.length >= 256)
2268
+ throw new HostError("Organization member limit is 256.");
1449
2269
  const certificate = await issueScopeCertificate(
1450
2270
  {
1451
2271
  v: 1,
@@ -1466,12 +2286,28 @@ export async function approveMembership(
1466
2286
  operation.baseline = fetched.variable.cid;
1467
2287
  await save();
1468
2288
  }
2289
+ if (operation.value.v === 2) {
2290
+ for (const member of operation.value.members) {
2291
+ if (!member.memberId) {
2292
+ Object.assign(
2293
+ member,
2294
+ await createMemberRecord(
2295
+ api,
2296
+ c.scopeId,
2297
+ member,
2298
+ `${operation.operation}.${member.publicKey}.member`,
2299
+ ),
2300
+ );
2301
+ await save();
2302
+ }
2303
+ }
2304
+ }
1469
2305
  const observed = await api.read(c.scopeId, c.configId);
1470
- if (observed.cid !== (await valueCid(operation.value)))
2306
+ if (observed.cid !== (await valueCid(configValue(operation.value))))
1471
2307
  await api.write(
1472
2308
  c.scopeId,
1473
2309
  c.configId,
1474
- operation.value,
2310
+ configValue(operation.value),
1475
2311
  operation.baseline!,
1476
2312
  `${operation.operation}.publish`,
1477
2313
  );
@@ -1501,7 +2337,7 @@ export async function updateSwarm(
1501
2337
  const result = await client(context, c.service, identity).write(
1502
2338
  c.scopeId,
1503
2339
  c.configId,
1504
- config,
2340
+ configValue(config),
1505
2341
  fetched.variable.cid,
1506
2342
  uniqueId(),
1507
2343
  );
@@ -1517,12 +2353,18 @@ export async function updateSwarm(
1517
2353
  export async function updateProfile(
1518
2354
  context: SwarmContext,
1519
2355
  url: string,
1520
- changes: { name?: string; addresses?: string[] },
2356
+ changes: { addresses?: string[] },
1521
2357
  ): Promise<Profile> {
1522
- if (changes.name !== undefined && changes.name.length > 256)
1523
- throw new HostError("Profile name exceeds 256 characters.");
2358
+ if ("name" in changes || "description" in changes)
2359
+ throw new HostError(
2360
+ "Use ipab profile --name NAME --description TEXT for personal data; swarm profile configures network addresses only.",
2361
+ );
1524
2362
  if ((changes.addresses?.length ?? 0) > 16)
1525
2363
  throw new HostError("Profile address limit is 16.");
2364
+ if (changes.addresses === undefined)
2365
+ throw new HostError(
2366
+ "swarm profile requires --address MULTIADDR; use ipab profile to read personal data.",
2367
+ );
1526
2368
  const record = await readyMembership(context, url),
1527
2369
  identity = await contextIdentity(context),
1528
2370
  c = coordinates(url);
@@ -1667,6 +2509,7 @@ export async function resumeRemoval(
1667
2509
  if (!record.nextConfig) {
1668
2510
  const config = {
1669
2511
  ...record.oldConfig,
2512
+ v: 2 as const,
1670
2513
  headId: record.newHeadId,
1671
2514
  epoch: record.oldConfig.epoch + 1,
1672
2515
  members: structuredClone(
@@ -1698,10 +2541,27 @@ export async function resumeRemoval(
1698
2541
  { certificate, swarmKey: record.newKey },
1699
2542
  identity,
1700
2543
  );
2544
+ delete member.memberId;
1701
2545
  }
1702
2546
  record.nextConfig = config;
1703
2547
  await save();
1704
2548
  }
2549
+ if (record.nextConfig.v === 2) {
2550
+ for (const member of record.nextConfig.members) {
2551
+ if (!member.memberId) {
2552
+ Object.assign(
2553
+ member,
2554
+ await createMemberRecord(
2555
+ api,
2556
+ c.scopeId,
2557
+ member,
2558
+ `${record.operation}.${member.publicKey}.member`,
2559
+ ),
2560
+ );
2561
+ await save();
2562
+ }
2563
+ }
2564
+ }
1705
2565
  const leaving = record.oldConfig.members.find(
1706
2566
  (m) => m.publicKey === record.member,
1707
2567
  )!;
@@ -1728,11 +2588,11 @@ export async function resumeRemoval(
1728
2588
  }
1729
2589
  if (!record.published) {
1730
2590
  const observed = await api.read(c.scopeId, c.configId);
1731
- if (observed.cid !== (await valueCid(record.nextConfig)))
2591
+ if (observed.cid !== (await valueCid(configValue(record.nextConfig))))
1732
2592
  await api.write(
1733
2593
  c.scopeId,
1734
2594
  c.configId,
1735
- record.nextConfig,
2595
+ configValue(record.nextConfig),
1736
2596
  record.configCid,
1737
2597
  `${record.operation}.config`,
1738
2598
  );
@@ -1761,6 +2621,34 @@ export async function resumeRemoval(
1761
2621
  if (!(cause instanceof ScopeApiError) || cause.status !== 410)
1762
2622
  throw cause;
1763
2623
  }
2624
+ for (const member of record.oldConfig.members) {
2625
+ if (
2626
+ member.memberId &&
2627
+ !record.nextConfig.members.some(
2628
+ (next) => next.memberId === member.memberId,
2629
+ )
2630
+ ) {
2631
+ for (const action of ["freeze", "delete"] as const) {
2632
+ try {
2633
+ if (action === "freeze")
2634
+ await api.freeze(
2635
+ c.scopeId,
2636
+ member.memberId,
2637
+ `${record.operation}.${member.publicKey}.freeze`,
2638
+ );
2639
+ else
2640
+ await api.delete(
2641
+ c.scopeId,
2642
+ member.memberId,
2643
+ `${record.operation}.${member.publicKey}.delete`,
2644
+ );
2645
+ } catch (cause) {
2646
+ if (!(cause instanceof ScopeApiError) || cause.status !== 410)
2647
+ throw cause;
2648
+ }
2649
+ }
2650
+ }
2651
+ }
1764
2652
  record.completed = true;
1765
2653
  await save();
1766
2654
  withState(context, (state) => {
@@ -1779,38 +2667,75 @@ export function formalName(name: string): string {
1779
2667
  throw new HostError("Invalid formal Name.");
1780
2668
  return name;
1781
2669
  }
2670
+ function decodeNameComponent(
2671
+ value: string,
2672
+ part: "authority" | "path",
2673
+ ): string {
2674
+ try {
2675
+ return decodeURIComponent(value);
2676
+ } catch {
2677
+ throw new HostError(
2678
+ `Malformed percent-encoding in IPAB URI ${part}; use valid UTF-8 escapes or copy the reference from ipab search.`,
2679
+ );
2680
+ }
2681
+ }
1782
2682
  export function parseNameReference(
1783
2683
  reference: string,
1784
2684
  ): { swarm?: string; name: string } | undefined {
1785
2685
  if (/^name:/i.test(reference))
1786
2686
  throw new HostError("name: is unsupported; use ipab://ALIAS/PATH.");
1787
2687
  if (!/^ipab:/i.test(reference)) return undefined;
1788
- const match = /^ipab:\/\/([^/]*)\/([^?#\s]*)$/i.exec(reference);
2688
+ if (/^ipab:\/\/https?:\/\//i.test(reference))
2689
+ throw new HostError(
2690
+ "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.",
2691
+ );
2692
+ const match = /^ipab:\/\/([^/]*)\/(.*)$/is.exec(reference);
1789
2693
  if (!match)
1790
2694
  throw new HostError(
1791
2695
  "Invalid IPAB URI; percent-encode the configuration URL authority and each path segment.",
1792
2696
  );
1793
- const authority = decodeURIComponent(match[1]!);
1794
- if (authority && !/^[A-Za-z0-9][A-Za-z0-9._-]*$/.test(authority))
2697
+ const authority = decodeNameComponent(match[1]!, "authority");
2698
+ if (authority && !/^[A-Za-z0-9][A-Za-z0-9._-]*$/.test(authority)) {
2699
+ if (!/^https?:\/\//i.test(authority))
2700
+ throw new HostError(
2701
+ "Invalid IPAB URI authority; use a registered alias or the percent-encoded configuration URL.",
2702
+ );
1795
2703
  canonicalSwarmUrl(authority);
2704
+ }
2705
+ if (/[?#\s]/.test(match[2]!))
2706
+ throw new HostError(
2707
+ "Invalid IPAB URI path; percent-encode each Name path segment. Queries and fragments are not supported.",
2708
+ );
1796
2709
  const segments = match[2]!.split("/").map((segment) => {
1797
- const decoded = decodeURIComponent(segment);
1798
- if (decoded.includes("/"))
1799
- throw new HostError("Encoded path separators are unsupported.");
2710
+ const decoded = decodeNameComponent(segment, "path");
2711
+ if (/[/\\]/.test(decoded))
2712
+ throw new HostError(
2713
+ "Invalid IPAB URI path separator; use literal / between Name segments, never an encoded slash or backslash.",
2714
+ );
1800
2715
  return decoded;
1801
2716
  });
1802
- return {
1803
- ...(authority ? { swarm: authority } : {}),
1804
- name: formalName(segments.join("/")),
1805
- };
2717
+ try {
2718
+ return {
2719
+ ...(authority ? { swarm: authority } : {}),
2720
+ name: formalName(segments.join("/")),
2721
+ };
2722
+ } catch (error) {
2723
+ if (!(error instanceof HostError)) throw error;
2724
+ throw new HostError(
2725
+ "Invalid IPAB URI path; use a safe relative Name of at most 256 characters without empty, . or .. segments.",
2726
+ error.exitCode,
2727
+ error.code,
2728
+ error.phase,
2729
+ );
2730
+ }
1806
2731
  }
1807
- function referenceFor(url: string, name: string): string {
2732
+ export function formatNameReference(swarm: string, name: string): string {
1808
2733
  const segment = (value: string) =>
1809
2734
  encodeURIComponent(value).replace(
1810
2735
  /[!'()*]/g,
1811
2736
  (char) => `%${char.charCodeAt(0).toString(16).toUpperCase()}`,
1812
2737
  );
1813
- return `ipab://${segment(url)}/${name.split("/").map(segment).join("/")}`;
2738
+ return `ipab://${segment(swarm)}/${name.split("/").map(segment).join("/")}`;
1814
2739
  }
1815
2740
  export async function resolveReference(
1816
2741
  context: SwarmContext,
@@ -1818,6 +2743,7 @@ export async function resolveReference(
1818
2743
  swarm: string | undefined,
1819
2744
  local: (reference: string) => string,
1820
2745
  raw = false,
2746
+ mode: "active" | "local-first" = "active",
1821
2747
  ): Promise<{ targetCid: string; cid: string }> {
1822
2748
  const shared = parseNameReference(reference);
1823
2749
  let targetCid: string;
@@ -1829,7 +2755,9 @@ export async function resolveReference(
1829
2755
  throw new HostError(
1830
2756
  "Select a configuration URL/alias using --swarm or swarm use.",
1831
2757
  );
1832
- let header = await swarmHeader(context, selected);
2758
+ const warm =
2759
+ mode === "local-first" ? await localHeader(context, selected) : undefined;
2760
+ let header = warm?.header ?? (await swarmHeader(context, selected));
1833
2761
  let link = Object.hasOwn(header.snapshot.names, shared.name)
1834
2762
  ? header.snapshot.names[shared.name]
1835
2763
  : undefined;
@@ -1843,31 +2771,219 @@ export async function resolveReference(
1843
2771
  throw new HostError(
1844
2772
  `Formal Name "${shared.name}" was not found after refreshing HEAD.`,
1845
2773
  );
2774
+ if (warm && header === warm.header && !header.localSourceReady)
2775
+ await lazyPrivateSource(context, selected, warm.account, header.config);
1846
2776
  targetCid = link.toString();
1847
2777
  } else {
1848
2778
  if (swarm) await readyMembership(context, swarm);
1849
2779
  targetCid = local(reference);
1850
2780
  }
2781
+ const cid = raw ? targetCid : await artifactValue(context.store, targetCid);
2782
+ return { targetCid, cid };
2783
+ }
2784
+ async function artifactValue(
2785
+ store: IpfsStore,
2786
+ targetCid: string,
2787
+ ): Promise<string> {
1851
2788
  let cid = targetCid;
1852
2789
  const visited = new Set<string>();
1853
- for (let depth = 0; !raw; depth++) {
2790
+ for (let depth = 0; ; depth++) {
1854
2791
  if (depth >= 64 || visited.has(cid))
1855
2792
  throw new HostError(
1856
2793
  "Artifact resolution exceeds limits or contains a cycle.",
1857
2794
  );
1858
2795
  visited.add(cid);
1859
2796
  const bundle = await openBundle(CID.parse(cid), {
1860
- resolveCid: (cid) => context.store.block.get(cid.toString()),
2797
+ resolveCid: (cid) => store.block.get(cid.toString()),
1861
2798
  });
1862
2799
  if (bundle.schemaKey !== (await encodeSchema(artifactType)).cid.toString())
1863
2800
  break;
1864
2801
  cid = CID.parse(
1865
- parseArtifact(await typedJson(context.store, cid, artifactType)).value,
2802
+ parseArtifact(await typedJson(store, cid, artifactType)).value,
1866
2803
  )
1867
2804
  .toV1()
1868
2805
  .toString();
1869
2806
  }
1870
- return { targetCid, cid };
2807
+ return cid;
2808
+ }
2809
+ export function pinReference(
2810
+ state: State,
2811
+ reference: string,
2812
+ selected?: string,
2813
+ ): { reference: string; swarm?: string; name?: string } {
2814
+ const shared = parseNameReference(reference);
2815
+ if (!shared) return { reference: exactCid(reference) };
2816
+ const swarm = shared.swarm ? state.resolveSwarm(shared.swarm) : selected;
2817
+ if (!swarm)
2818
+ throw new HostError(
2819
+ "Pinning a shared Name requires --swarm or swarm use, or a Swarm authority in the IPAB URI.",
2820
+ );
2821
+ return {
2822
+ reference: formatNameReference(swarm, shared.name),
2823
+ swarm,
2824
+ name: shared.name,
2825
+ };
2826
+ }
2827
+ export async function pinNameSubscription(
2828
+ context: SwarmContext,
2829
+ reference: string,
2830
+ selected?: string,
2831
+ ) {
2832
+ const canonical = withState(context, (state) =>
2833
+ pinReference(state, reference, selected),
2834
+ );
2835
+ if (!canonical.swarm || !canonical.name) {
2836
+ let roots: string[];
2837
+ try {
2838
+ roots = [
2839
+ ...(await currentDependencies(context.store, canonical.reference)),
2840
+ ];
2841
+ } catch (cause) {
2842
+ let failure: unknown = cause;
2843
+ for (
2844
+ let depth = 0;
2845
+ depth < 8 && failure instanceof ContentBundleError;
2846
+ depth++
2847
+ )
2848
+ failure = failure.cause;
2849
+ if (
2850
+ !selected ||
2851
+ !(failure instanceof ContentError) ||
2852
+ failure.code !== "missing_block"
2853
+ )
2854
+ throw cause;
2855
+ const swarm = withState(context, (state) => state.resolveSwarm(selected));
2856
+ await readyMembership(context, swarm);
2857
+ roots = [
2858
+ ...(await currentDependencies(context.store, canonical.reference)),
2859
+ ];
2860
+ }
2861
+ return withStateAsync(context, (state) =>
2862
+ pinCid(state, canonical.reference, context.store, roots),
2863
+ );
2864
+ }
2865
+ const resolved = await resolveReference(
2866
+ context,
2867
+ canonical.reference,
2868
+ canonical.swarm,
2869
+ exactCid,
2870
+ false,
2871
+ "local-first",
2872
+ );
2873
+ const roots = await currentDependencies(context.store, resolved.targetCid);
2874
+ const pin = withState(context, (state) =>
2875
+ reservePin(state, canonical.reference, context.store.configuration, {
2876
+ swarm: canonical.swarm!,
2877
+ name: canonical.name!,
2878
+ }),
2879
+ );
2880
+ return withStateAsync(context, (state) =>
2881
+ retainPin(state, pin, context.store, { ...resolved, roots: [...roots] }),
2882
+ );
2883
+ }
2884
+ async function withStateAsync<T>(
2885
+ context: SwarmContext,
2886
+ operation: (state: State) => Promise<T>,
2887
+ ): Promise<T> {
2888
+ if (context.state) return operation(context.state);
2889
+ const state = new State(context.stateDir);
2890
+ try {
2891
+ return await operation(state);
2892
+ } finally {
2893
+ state.close();
2894
+ }
2895
+ }
2896
+ export async function refreshNamePins(
2897
+ context: SwarmContext,
2898
+ url: string,
2899
+ header: Pick<SwarmHeader, "snapshot">,
2900
+ ): Promise<void> {
2901
+ const pins = withState(context, (state) =>
2902
+ state
2903
+ .contentPins()
2904
+ .filter((pin) => pin.swarm === url && pin.status !== "deleting"),
2905
+ );
2906
+ const failures: string[] = [];
2907
+ for (const saved of pins) {
2908
+ const target = Object.hasOwn(header.snapshot.names, saved.name!)
2909
+ ? header.snapshot.names[saved.name!]!.toString()
2910
+ : undefined;
2911
+ if (!target) {
2912
+ withState(context, (state) => {
2913
+ failedPin(
2914
+ state,
2915
+ saved.reference,
2916
+ new Error(
2917
+ "Shared Name is missing; keeping its last verified version.",
2918
+ ),
2919
+ true,
2920
+ );
2921
+ });
2922
+ context.diagnostic?.(
2923
+ `Pin ${saved.reference} is missing; its last verified version remains retained.`,
2924
+ );
2925
+ continue;
2926
+ }
2927
+ let claimed = false;
2928
+ try {
2929
+ // A cached HEAD can differ from the saved subscription after publication or a failed refresh.
2930
+ if (
2931
+ saved.targetCid === target &&
2932
+ saved.status === "ready" &&
2933
+ saved.freshness === "current"
2934
+ )
2935
+ continue;
2936
+ const pin = withState(context, (state) => refreshPinClaim(state, saved));
2937
+ if (!pin) continue;
2938
+ claimed = true;
2939
+ const cid = await artifactValue(context.store, target);
2940
+ const roots = [...(await currentDependencies(context.store, target))];
2941
+ await withStateAsync(context, (state) =>
2942
+ retainPin(state, pin, context.store, { cid, targetCid: target, roots }),
2943
+ );
2944
+ } catch (cause) {
2945
+ if (claimed)
2946
+ withState(context, (state) => {
2947
+ failedPin(state, saved.reference, cause);
2948
+ });
2949
+ failures.push(`${saved.reference}: ${message(cause)}`);
2950
+ }
2951
+ }
2952
+ if (failures.length)
2953
+ throw new HostError(
2954
+ `Name subscription refresh failed; prior verified versions remain retained:\n${failures.join("\n")}`,
2955
+ 1,
2956
+ "PIN_STALE",
2957
+ );
2958
+ }
2959
+ async function currentDependencies(
2960
+ store: IpfsStore,
2961
+ root: string,
2962
+ found = new Set<string>(),
2963
+ ): Promise<Set<string>> {
2964
+ if (found.has(root)) return found;
2965
+ if (found.size >= 64)
2966
+ throw new HostError("Current pin dependency limit exceeded.");
2967
+ found.add(root);
2968
+ const bundle = await openBundle(CID.parse(root), {
2969
+ resolveCid: (cid) => store.block.get(cid.toString()),
2970
+ });
2971
+ if (bundle.schemaKey === (await encodeSchema(artifactType)).cid.toString()) {
2972
+ await currentDependencies(
2973
+ store,
2974
+ parseArtifact(await typedJson(store, root, artifactType)).value,
2975
+ found,
2976
+ );
2977
+ } else if (bundle.schemaKey === appSchemaCid.toString()) {
2978
+ const app = object((await bundleJson(store, root)).value, "App");
2979
+ if (app.source) {
2980
+ const source = object(app.source, "source");
2981
+ if (typeof source.cid !== "string")
2982
+ throw new HostError("Invalid App source association.");
2983
+ await currentDependencies(store, source.cid, found);
2984
+ }
2985
+ }
2986
+ return found;
1871
2987
  }
1872
2988
  export async function searchNames(
1873
2989
  context: SwarmContext,
@@ -1899,7 +3015,14 @@ export async function searchNames(
1899
3015
  verifiedAt: string;
1900
3016
  }[] = [];
1901
3017
  for (const swarm of swarms) {
1902
- const header = await swarmHeader(context, swarm.cid);
3018
+ const header =
3019
+ (await localHeader(context, swarm.cid))?.header ??
3020
+ (await swarmHeader(
3021
+ context,
3022
+ swarm.cid,
3023
+ context.forceRefresh,
3024
+ "local-first",
3025
+ ));
1903
3026
  searched.push({
1904
3027
  configUrl: swarm.cid,
1905
3028
  source: header.source,
@@ -1907,18 +3030,167 @@ export async function searchNames(
1907
3030
  valueCid: header.head.cid,
1908
3031
  verifiedAt: header.verifiedAt,
1909
3032
  });
1910
- for (const name of Object.keys(header.snapshot.names).sort())
1911
- if (name.toLowerCase().includes(query.toLowerCase()))
1912
- matches.push({
1913
- swarm: swarm.cid,
1914
- alias: swarm.alias,
1915
- name,
1916
- reference: referenceFor(swarm.cid, name),
1917
- targetCid: header.snapshot.names[name]!.toString(),
1918
- });
3033
+ for (const { name, targetCid } of withState(context, (state) =>
3034
+ state.searchSwarmNames(headerProjection(header), query),
3035
+ ))
3036
+ matches.push({
3037
+ swarm: swarm.cid,
3038
+ alias: swarm.alias,
3039
+ name,
3040
+ reference: formatNameReference(swarm.cid, name),
3041
+ targetCid,
3042
+ });
1919
3043
  }
1920
3044
  return { matches, swarms: searched };
1921
3045
  }
3046
+ function snapshotAssociations(snapshot: Snapshot): Association[] {
3047
+ return Object.entries(snapshot.registrations ?? {})
3048
+ .sort(([left], [right]) => left.localeCompare(right))
3049
+ .map(([schemaCid, item]) => ({
3050
+ schemaCid,
3051
+ appCid: item.appCid.toString(),
3052
+ argv: [...item.argv],
3053
+ }));
3054
+ }
3055
+ export async function swarmRegistrations(
3056
+ context: SwarmContext,
3057
+ configUrl: string,
3058
+ ): Promise<Association[]> {
3059
+ const header = await swarmHeader(context, configUrl);
3060
+ return withState(context, (state) =>
3061
+ state.projectedSwarmRegistrations(headerProjection(header)),
3062
+ );
3063
+ }
3064
+ export async function swarmAssociation(
3065
+ context: SwarmContext,
3066
+ configUrl: string,
3067
+ schemaCid: string,
3068
+ mode: "active" | "local-first" = "active",
3069
+ ): Promise<Association | undefined> {
3070
+ let header =
3071
+ (mode === "local-first"
3072
+ ? (await localHeader(context, configUrl))?.header
3073
+ : undefined) ?? (await swarmHeader(context, configUrl));
3074
+ let association = withState(
3075
+ context,
3076
+ (state) =>
3077
+ state.projectedSwarmRegistrations(headerProjection(header), schemaCid)[0],
3078
+ );
3079
+ if (!association && header.source === "cache") {
3080
+ header = await swarmHeader(context, configUrl, true);
3081
+ association = withState(
3082
+ context,
3083
+ (state) =>
3084
+ state.projectedSwarmRegistrations(
3085
+ headerProjection(header),
3086
+ schemaCid,
3087
+ )[0],
3088
+ );
3089
+ }
3090
+ return association;
3091
+ }
3092
+ async function editSwarmAssociation(
3093
+ context: SwarmContext,
3094
+ configUrl: string,
3095
+ schemaCid: string,
3096
+ association: Association | undefined,
3097
+ replace: boolean,
3098
+ ): Promise<void> {
3099
+ const head = await pointer(context, configUrl);
3100
+ const roots = association
3101
+ ? await dependencies(context.store, association.appCid)
3102
+ : new Set<string>();
3103
+ for (let attempt = 0; attempt < 8; attempt++) {
3104
+ const currentHead = await head.read();
3105
+ const current = await readSnapshot(context.store, currentHead.root);
3106
+ const old = snapshotAssociations(current).find(
3107
+ (item) => item.schemaCid === schemaCid,
3108
+ );
3109
+ if (association) {
3110
+ if (
3111
+ old &&
3112
+ old.appCid === association.appCid &&
3113
+ JSON.stringify(old.argv) === JSON.stringify(association.argv)
3114
+ )
3115
+ return;
3116
+ if (old && !replace)
3117
+ throw new HostError(
3118
+ "Schema has another association; use --replace before --.",
3119
+ );
3120
+ } else if (!old) {
3121
+ throw new HostError(
3122
+ "No association exists for this Schema. Run ipab register list --swarm URL_OR_ALIAS.",
3123
+ );
3124
+ }
3125
+ const registrations = { ...current.registrations };
3126
+ if (association)
3127
+ registrations[schemaCid] = {
3128
+ appCid: CID.parse(association.appCid),
3129
+ argv: association.argv,
3130
+ };
3131
+ else delete registrations[schemaCid];
3132
+ const next = await publication(
3133
+ context.store,
3134
+ await writeSnapshot(context.store, { ...current, registrations }),
3135
+ currentHead.root,
3136
+ );
3137
+ await provideContent(
3138
+ context.store,
3139
+ [next, ...roots],
3140
+ context.node!.api,
3141
+ context.fetch,
3142
+ context.node!.auth,
3143
+ );
3144
+ withState(context, (state) => {
3145
+ state.invalidateSwarmHeader(configUrl);
3146
+ });
3147
+ try {
3148
+ await head.write(next, currentHead.cid, uniqueId());
3149
+ return;
3150
+ } catch (cause) {
3151
+ if (!(cause instanceof ScopeApiError) || cause.status !== 412)
3152
+ throw new HostError(
3153
+ `Registry publication unconfirmed for ${configUrl}: ${message(cause)}. Inspect the Swarm registry before retry.`,
3154
+ 1,
3155
+ "HEAD_UNCONFIRMED",
3156
+ "publication",
3157
+ );
3158
+ continue;
3159
+ }
3160
+ }
3161
+ throw new HostError(
3162
+ `HEAD is busy for ${configUrl}; retry the registry edit.`,
3163
+ );
3164
+ }
3165
+ export async function setSwarmAssociation(
3166
+ context: SwarmContext,
3167
+ configUrl: string,
3168
+ value: Association,
3169
+ replace = false,
3170
+ ): Promise<Association> {
3171
+ const association = createAssociation(
3172
+ value.schemaCid,
3173
+ value.appCid,
3174
+ value.argv,
3175
+ );
3176
+ await editSwarmAssociation(
3177
+ context,
3178
+ configUrl,
3179
+ association.schemaCid,
3180
+ association,
3181
+ replace,
3182
+ );
3183
+ return association;
3184
+ }
3185
+ export async function removeSwarmAssociation(
3186
+ context: SwarmContext,
3187
+ configUrl: string,
3188
+ schemaCid: string,
3189
+ ): Promise<string> {
3190
+ const schema = exactCid(schemaCid, true);
3191
+ await editSwarmAssociation(context, configUrl, schema, undefined, false);
3192
+ return schema;
3193
+ }
1922
3194
  async function dependencies(
1923
3195
  store: IpfsStore,
1924
3196
  root: string,
@@ -1967,11 +3239,11 @@ export async function frozenPublicationClosure(
1967
3239
  );
1968
3240
  publications.add(current);
1969
3241
  const publication = await readPublication(store, current);
1970
- const snapshot = decodeSnapshot(
1971
- await store.block.get(publication.state.toString()),
1972
- );
3242
+ const snapshot = await readState(store, publication.state);
1973
3243
  for (const target of Object.values(snapshot.names))
1974
3244
  await dependencies(store, target.toString(), content);
3245
+ for (const association of Object.values(snapshot.registrations ?? {}))
3246
+ await dependencies(store, association.appCid.toString(), content);
1975
3247
  current = publication.previous?.toString();
1976
3248
  }
1977
3249
  return [
@@ -1986,7 +3258,7 @@ export async function publish(
1986
3258
  content: string,
1987
3259
  options: {
1988
3260
  swarm?: string;
1989
- name?: string;
3261
+ name: string;
1990
3262
  expect?: string;
1991
3263
  snapshot?: boolean;
1992
3264
  },
@@ -1997,19 +3269,10 @@ export async function publish(
1997
3269
  );
1998
3270
  const head = await pointer(context, options.swarm);
1999
3271
  const roots = await dependencies(context.store, content);
2000
- if (!options.name) {
2001
- if (options.expect || options.snapshot)
2002
- throw new HostError("--expect/--snapshot require --name.");
2003
- await head.read();
2004
- await provideContent(
2005
- context.store,
2006
- [...roots],
2007
- context.node!.api,
2008
- context.fetch,
2009
- context.node!.auth,
2010
- );
2011
- return content;
2012
- }
3272
+ const currentRoots = [...(await currentDependencies(context.store, content))];
3273
+ await withStateAsync(context, (state) =>
3274
+ pinCid(state, content, context.store, currentRoots),
3275
+ );
2013
3276
  const name = formalName(options.name);
2014
3277
  if (options.snapshot && options.expect)
2015
3278
  throw new HostError("Snapshots cannot replace an occupied Name.");
@@ -2038,7 +3301,7 @@ export async function publish(
2038
3301
  : undefined) !== expected
2039
3302
  )
2040
3303
  throw new HostError(
2041
- `Edit conflict for ${name}; candidate ${candidate} remains retained. Choose an explicit baseline.`,
3304
+ `Edit conflict for ${name}; content ${content} remains pinned. Occupied Names require --expect EXACT_OLD_ARTIFACT_CID; inspect the current Name before retrying.`,
2042
3305
  3,
2043
3306
  "EDIT_CONFLICT",
2044
3307
  "publication",
@@ -2057,13 +3320,13 @@ export async function publish(
2057
3320
  context.node!.api,
2058
3321
  context.fetch,
2059
3322
  context.node!.auth,
3323
+ [next, ...(expected ? await dependencies(context.store, expected) : [])],
2060
3324
  );
2061
3325
  withState(context, (state) => {
2062
3326
  state.invalidateSwarmHeader(options.swarm!);
2063
3327
  });
2064
3328
  try {
2065
3329
  await head.write(next, currentHead.cid, uniqueId());
2066
- return candidate;
2067
3330
  } catch (cause) {
2068
3331
  if (!(cause instanceof ScopeApiError) || cause.status !== 412)
2069
3332
  throw new HostError(
@@ -2072,7 +3335,19 @@ export async function publish(
2072
3335
  "HEAD_UNCONFIRMED",
2073
3336
  "publication",
2074
3337
  );
3338
+ continue;
3339
+ }
3340
+ try {
3341
+ await swarmHeader(context, options.swarm, true);
3342
+ } catch (cause) {
3343
+ throw new HostError(
3344
+ `Publication committed as ${candidate}, but its HEAD/subscription refresh failed: ${message(cause)}. Published content remains pinned; inspect HEAD and retry the affected Name pin.`,
3345
+ 1,
3346
+ "PIN_STALE",
3347
+ "publication",
3348
+ );
2075
3349
  }
3350
+ return candidate;
2076
3351
  }
2077
3352
  throw new HostError(`HEAD is busy; candidate ${candidate} remains retained.`);
2078
3353
  }