@ipab/cli 0.1.0-rc.5 → 0.1.0-rc.7

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 (157) hide show
  1. package/README.md +128 -22
  2. package/dist/app-authoring.d.ts +5 -0
  3. package/dist/app-authoring.d.ts.map +1 -1
  4. package/dist/app-authoring.js +4 -1
  5. package/dist/app-authoring.js.map +1 -1
  6. package/dist/app-templates.d.ts +0 -1
  7. package/dist/app-templates.d.ts.map +1 -1
  8. package/dist/app-templates.js +6 -45
  9. package/dist/app-templates.js.map +1 -1
  10. package/dist/builtins/skill.ipab.car +0 -0
  11. package/dist/builtins/template.bundle-viewer.car +0 -0
  12. package/dist/builtins/template.check.car +0 -0
  13. package/dist/builtins/template.node.car +0 -0
  14. package/dist/builtins/template.web-app.car +0 -0
  15. package/dist/builtins.d.ts.map +1 -1
  16. package/dist/builtins.js +1 -39
  17. package/dist/builtins.js.map +1 -1
  18. package/dist/cli.d.ts +4 -1
  19. package/dist/cli.d.ts.map +1 -1
  20. package/dist/cli.js +934 -336
  21. package/dist/cli.js.map +1 -1
  22. package/dist/content-provider.d.ts +1 -1
  23. package/dist/content-provider.d.ts.map +1 -1
  24. package/dist/content-provider.js +4 -3
  25. package/dist/content-provider.js.map +1 -1
  26. package/dist/context.d.ts +16 -1
  27. package/dist/context.d.ts.map +1 -1
  28. package/dist/context.js +20 -10
  29. package/dist/context.js.map +1 -1
  30. package/dist/doctor.d.ts +29 -0
  31. package/dist/doctor.d.ts.map +1 -0
  32. package/dist/doctor.js +576 -0
  33. package/dist/doctor.js.map +1 -0
  34. package/dist/identity.d.ts +1 -1
  35. package/dist/identity.d.ts.map +1 -1
  36. package/dist/identity.js +9 -9
  37. package/dist/identity.js.map +1 -1
  38. package/dist/ipc.d.ts +2 -2
  39. package/dist/ipc.d.ts.map +1 -1
  40. package/dist/ipc.js +44 -12
  41. package/dist/ipc.js.map +1 -1
  42. package/dist/kubo-install.d.ts +18 -1
  43. package/dist/kubo-install.d.ts.map +1 -1
  44. package/dist/kubo-install.js +424 -61
  45. package/dist/kubo-install.js.map +1 -1
  46. package/dist/kubo-release.d.ts +19 -0
  47. package/dist/kubo-release.d.ts.map +1 -1
  48. package/dist/kubo-release.js +164 -0
  49. package/dist/kubo-release.js.map +1 -1
  50. package/dist/kubo.d.ts +1 -0
  51. package/dist/kubo.d.ts.map +1 -1
  52. package/dist/kubo.js +102 -96
  53. package/dist/kubo.js.map +1 -1
  54. package/dist/pins.d.ts +15 -17
  55. package/dist/pins.d.ts.map +1 -1
  56. package/dist/pins.js +144 -106
  57. package/dist/pins.js.map +1 -1
  58. package/dist/publish-source.d.ts +3 -0
  59. package/dist/publish-source.d.ts.map +1 -0
  60. package/dist/publish-source.js +85 -0
  61. package/dist/publish-source.js.map +1 -0
  62. package/dist/runtime.d.ts.map +1 -1
  63. package/dist/runtime.js +6 -5
  64. package/dist/runtime.js.map +1 -1
  65. package/dist/skill-definition.d.ts +6 -0
  66. package/dist/skill-definition.d.ts.map +1 -0
  67. package/dist/skill-definition.js +38 -0
  68. package/dist/skill-definition.js.map +1 -0
  69. package/dist/skill-source.d.ts +5 -0
  70. package/dist/skill-source.d.ts.map +1 -0
  71. package/dist/skill-source.js +12 -0
  72. package/dist/skill-source.js.map +1 -0
  73. package/dist/skills.d.ts +84 -0
  74. package/dist/skills.d.ts.map +1 -0
  75. package/dist/skills.js +736 -0
  76. package/dist/skills.js.map +1 -0
  77. package/dist/space.d.ts +15 -2
  78. package/dist/space.d.ts.map +1 -1
  79. package/dist/space.js +153 -3
  80. package/dist/space.js.map +1 -1
  81. package/dist/state-storage-windows.js +1 -1
  82. package/dist/state-storage.d.ts +3 -1
  83. package/dist/state-storage.d.ts.map +1 -1
  84. package/dist/state-storage.js +38 -7
  85. package/dist/state-storage.js.map +1 -1
  86. package/dist/state.d.ts +40 -6
  87. package/dist/state.d.ts.map +1 -1
  88. package/dist/state.js +208 -82
  89. package/dist/state.js.map +1 -1
  90. package/dist/swarm-envelope.d.ts +1 -0
  91. package/dist/swarm-envelope.d.ts.map +1 -1
  92. package/dist/swarm-envelope.js +12 -0
  93. package/dist/swarm-envelope.js.map +1 -1
  94. package/dist/swarm-files.d.ts +1 -1
  95. package/dist/swarm-files.d.ts.map +1 -1
  96. package/dist/swarm-files.js +2 -2
  97. package/dist/swarm-files.js.map +1 -1
  98. package/dist/swarm-meta.d.ts +17 -0
  99. package/dist/swarm-meta.d.ts.map +1 -0
  100. package/dist/swarm-meta.js +96 -0
  101. package/dist/swarm-meta.js.map +1 -0
  102. package/dist/swarm.d.ts +117 -8
  103. package/dist/swarm.d.ts.map +1 -1
  104. package/dist/swarm.js +1275 -131
  105. package/dist/swarm.js.map +1 -1
  106. package/dist/template-paths.d.ts +7 -0
  107. package/dist/template-paths.d.ts.map +1 -0
  108. package/dist/template-paths.js +23 -0
  109. package/dist/template-paths.js.map +1 -0
  110. package/dist/template-presentation.d.ts +20 -0
  111. package/dist/template-presentation.d.ts.map +1 -0
  112. package/dist/template-presentation.js +133 -0
  113. package/dist/template-presentation.js.map +1 -0
  114. package/dist/template-source.d.ts +2 -1
  115. package/dist/template-source.d.ts.map +1 -1
  116. package/dist/template-source.js +7 -1
  117. package/dist/template-source.js.map +1 -1
  118. package/dist/templates.d.ts +11 -0
  119. package/dist/templates.d.ts.map +1 -0
  120. package/dist/templates.js +53 -0
  121. package/dist/templates.js.map +1 -0
  122. package/package.json +7 -6
  123. package/src/app-authoring.ts +18 -2
  124. package/src/app-templates.ts +8 -72
  125. package/src/builtins.ts +2 -48
  126. package/src/cli.ts +1154 -387
  127. package/src/content-provider.ts +4 -2
  128. package/src/context.ts +45 -10
  129. package/src/doctor.ts +902 -0
  130. package/src/identity.ts +10 -10
  131. package/src/ipc.ts +63 -10
  132. package/src/kubo-install.ts +562 -78
  133. package/src/kubo-release.ts +213 -0
  134. package/src/kubo.ts +134 -106
  135. package/src/pins.ts +188 -126
  136. package/src/publish-source.ts +103 -0
  137. package/src/runtime.ts +6 -5
  138. package/src/skill-definition.ts +53 -0
  139. package/src/skill-source.ts +15 -0
  140. package/src/skills.ts +1005 -0
  141. package/src/space.ts +214 -5
  142. package/src/state-storage-windows.ts +1 -1
  143. package/src/state-storage.ts +53 -7
  144. package/src/state.ts +357 -98
  145. package/src/swarm-envelope.ts +14 -0
  146. package/src/swarm-files.ts +2 -1
  147. package/src/swarm-meta.ts +109 -0
  148. package/src/swarm.ts +1877 -175
  149. package/src/template-paths.ts +43 -0
  150. package/src/template-presentation.ts +151 -0
  151. package/src/template-source.ts +9 -2
  152. package/src/templates.ts +77 -0
  153. package/dist/setup.d.ts +0 -8
  154. package/dist/setup.d.ts.map +0 -1
  155. package/dist/setup.js +0 -27
  156. package/dist/setup.js.map +0 -1
  157. package/src/setup.ts +0 -34
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,12 +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";
39
53
  import { swarmUrl as canonicalSwarmUrl } from "./config.js";
40
- import { bundleJson, provideContent } from "./content-provider.js";
54
+ import { bundleJson, contentCar, provideContent } from "./content-provider.js";
55
+ import {
56
+ failedPin,
57
+ pinCid,
58
+ refreshPinClaim,
59
+ reservePin,
60
+ retainPin,
61
+ } from "./pins.js";
41
62
  import { bytes, relativePath } from "./space.js";
42
63
  import { appSchemaCid } from "./app-definition.js";
43
- import { State } from "./state.js";
64
+ import {
65
+ State,
66
+ createAssociation,
67
+ exactCid,
68
+ type Association,
69
+ type SwarmProjection,
70
+ } from "./state.js";
44
71
  import {
45
72
  privateDirectory,
46
73
  readPrivate,
@@ -56,6 +83,7 @@ import {
56
83
  type EnvelopeBinding,
57
84
  type MembershipSecret,
58
85
  parseEnvelope,
86
+ validateEncryptionIdentity,
59
87
  } from "./swarm-envelope.js";
60
88
  import {
61
89
  checkCachedNode,
@@ -69,8 +97,25 @@ import {
69
97
  type ListenMode,
70
98
  } from "./kubo.js";
71
99
  import { memberPeers } from "./kubo-peering.js";
100
+ import { seedTemplateNames, seedTemplateSource } from "./template-source.js";
101
+ import { inspectTemplate, templatePublicationSource } from "./templates.js";
102
+ import { seedSkillSource } from "./skill-source.js";
103
+ import { skillIdentity, skillSchema } from "./skill-definition.js";
104
+ import {
105
+ parseSwarmMeta,
106
+ swarmMetaType,
107
+ swarmMetaSchema,
108
+ swarmStateType,
109
+ legacySwarmStateType,
110
+ legacySwarmStateSchema,
111
+ isSwarmStateSchema,
112
+ type SwarmMeta,
113
+ legacySwarmMetaType,
114
+ legacySwarmMetaSchema,
115
+ } from "./swarm-meta.js";
72
116
 
73
117
  export interface Member {
118
+ memberId?: string;
74
119
  publicKey: string;
75
120
  encryptionKey: string;
76
121
  peerId: string;
@@ -79,7 +124,7 @@ export interface Member {
79
124
  approval: Envelope | null;
80
125
  }
81
126
  export interface Organization {
82
- v: 1;
127
+ v: 1 | 2;
83
128
  scopeId: string;
84
129
  owner: string;
85
130
  name: string;
@@ -91,12 +136,21 @@ export interface Organization {
91
136
  }
92
137
  export interface Profile {
93
138
  name: string;
139
+ description?: string;
94
140
  addresses: string[];
95
141
  updatedAt: string;
96
142
  }
143
+ export interface AccountProfile {
144
+ publicKey: string;
145
+ name: string;
146
+ description: string;
147
+ updatedAt: string | null;
148
+ }
97
149
  export interface Snapshot {
98
150
  v: 2;
99
151
  names: Record<string, CID>;
152
+ registrations?: Record<string, { appCid: CID; argv: string[] }>;
153
+ stateBundle?: { meta: SwarmMeta; cid: string };
100
154
  }
101
155
  export interface MembershipRequest {
102
156
  v: 1;
@@ -146,6 +200,67 @@ interface LocalMembership {
146
200
  config?: Organization;
147
201
  secret?: MembershipSecret;
148
202
  }
203
+ export async function inspectLocalMembership(
204
+ input: unknown,
205
+ account: string | undefined,
206
+ ) {
207
+ const value = object(input, "local membership");
208
+ if (
209
+ typeof value.configUrl !== "string" ||
210
+ !isCanonicalPublicKey(value.owner) ||
211
+ !isCanonicalPublicKey(value.account) ||
212
+ value.account !== account
213
+ )
214
+ throw new HostError(
215
+ "Stored membership is inconsistent with HOME identity.",
216
+ );
217
+ const configUrl = canonicalSwarmUrl(value.configUrl);
218
+ if (configUrl !== value.configUrl)
219
+ throw new HostError("Noncanonical membership URL.");
220
+ const encryption = object(value.encryption, "encryption identity");
221
+ if (
222
+ typeof encryption.privateKey !== "string" ||
223
+ typeof encryption.publicKey !== "string"
224
+ )
225
+ throw new HostError("Invalid encryption identity.");
226
+ validateEncryptionIdentity({
227
+ privateKey: encryption.privateKey,
228
+ publicKey: encryption.publicKey,
229
+ });
230
+ const request =
231
+ value.request === undefined
232
+ ? undefined
233
+ : await verifyRequest(value.request);
234
+ if (
235
+ request &&
236
+ (request.configUrl !== configUrl ||
237
+ request.member !== account ||
238
+ request.owner !== value.owner ||
239
+ request.encryptionKey !== encryption.publicKey)
240
+ )
241
+ throw new HostError("Stored Request binding mismatch.");
242
+ const config =
243
+ value.config === undefined
244
+ ? undefined
245
+ : parseOrganization(value.config, configUrl);
246
+ if (config && config.owner !== value.owner)
247
+ throw new HostError("Stored Owner binding mismatch.");
248
+ let peer = request?.peerId;
249
+ if (value.secret !== undefined) {
250
+ if (!config)
251
+ throw new HostError("Stored secret has no configuration binding.");
252
+ const member = config.members.find(
253
+ (member) => member.publicKey === account,
254
+ );
255
+ if (!member)
256
+ throw new HostError("Stored membership lacks its member binding.");
257
+ const record = value as unknown as LocalMembership;
258
+ await validateMembershipSecret(record, config, member);
259
+ peer = member.peerId;
260
+ }
261
+ const c = coordinates(configUrl);
262
+ return { configUrl, scope: nodeScope(c.service, c.scopeId), peer };
263
+ }
149
264
  const cidField = { type: "string", minLength: 1, maxLength: 128 } as const;
150
265
  export const artifactType: BundleType = {
151
266
  contentType: "application/json",
@@ -249,7 +364,7 @@ function parseOrganization(value: unknown, configUrl: string): Organization {
249
364
  if (
250
365
  Object.keys(data).sort().join() !==
251
366
  "bootstrap,description,epoch,headId,members,name,owner,scopeId,v" ||
252
- data.v !== 1 ||
367
+ (data.v !== 1 && data.v !== 2) ||
253
368
  data.scopeId !== scopeId ||
254
369
  !isCanonicalPublicKey(data.owner) ||
255
370
  typeof data.name !== "string" ||
@@ -265,7 +380,7 @@ function parseOrganization(value: unknown, configUrl: string): Organization {
265
380
  data.bootstrap.length > 64 ||
266
381
  !Array.isArray(data.members) ||
267
382
  data.members.length < 1 ||
268
- data.members.length > 16
383
+ data.members.length > 256
269
384
  )
270
385
  throw new HostError("Invalid Scope organization configuration.");
271
386
  const identities = new Set<string>(),
@@ -275,8 +390,14 @@ function parseOrganization(value: unknown, configUrl: string): Organization {
275
390
  for (const raw of data.members) {
276
391
  const member = object(raw, "member");
277
392
  if (
278
- Object.keys(member).sort().join() !==
393
+ Object.keys(member)
394
+ .filter((key) => key !== "memberId")
395
+ .sort()
396
+ .join() !==
279
397
  "approval,encryptionKey,peerId,profileId,publicKey,requestId" ||
398
+ (member.memberId !== undefined &&
399
+ (typeof member.memberId !== "string" ||
400
+ !RESOURCE_ID_PATTERN.test(member.memberId))) ||
280
401
  !isCanonicalPublicKey(member.publicKey) ||
281
402
  typeof member.encryptionKey !== "string" ||
282
403
  member.encryptionKey.length > 256 ||
@@ -296,6 +417,9 @@ function parseOrganization(value: unknown, configUrl: string): Organization {
296
417
  peers.add(member.peerId);
297
418
  profiles.add(member.profileId);
298
419
  members.push({
420
+ ...(typeof member.memberId === "string"
421
+ ? { memberId: member.memberId }
422
+ : {}),
299
423
  publicKey: member.publicKey,
300
424
  encryptionKey: member.encryptionKey,
301
425
  peerId: member.peerId,
@@ -317,7 +441,7 @@ function parseOrganization(value: unknown, configUrl: string): Organization {
317
441
  bootstrap.push(address);
318
442
  }
319
443
  return {
320
- v: 1,
444
+ v: data.v,
321
445
  scopeId,
322
446
  owner: data.owner,
323
447
  name: data.name,
@@ -331,9 +455,15 @@ function parseOrganization(value: unknown, configUrl: string): Organization {
331
455
  function parseProfile(value: unknown, expectedPeer: string): Profile {
332
456
  const data = object(value, "member profile");
333
457
  if (
334
- Object.keys(data).sort().join() !== "addresses,name,updatedAt" ||
458
+ ![
459
+ "addresses,name,updatedAt",
460
+ "addresses,description,name,updatedAt",
461
+ ].includes(Object.keys(data).sort().join()) ||
335
462
  typeof data.name !== "string" ||
336
463
  data.name.length > 256 ||
464
+ (data.description !== undefined &&
465
+ (typeof data.description !== "string" ||
466
+ data.description.length > 2048)) ||
337
467
  typeof data.updatedAt !== "string" ||
338
468
  !Number.isFinite(Date.parse(data.updatedAt)) ||
339
469
  !Array.isArray(data.addresses) ||
@@ -347,7 +477,245 @@ function parseProfile(value: unknown, expectedPeer: string): Profile {
347
477
  validateAddress(address, expectedPeer);
348
478
  addresses.push(address);
349
479
  }
350
- return { name: data.name, addresses, updatedAt: data.updatedAt };
480
+ return {
481
+ name: data.name,
482
+ ...(typeof data.description === "string"
483
+ ? { description: data.description }
484
+ : {}),
485
+ addresses,
486
+ updatedAt: data.updatedAt,
487
+ };
488
+ }
489
+ export async function swarmMembers(context: SwarmContext, url: string) {
490
+ const { config } = await fetchConfig(context, canonicalSwarmUrl(url));
491
+ const c = coordinates(url),
492
+ api = client(context, c.service);
493
+ const members = await boundedMap(config.members, async (member) => {
494
+ const profile = parseProfile(
495
+ (await api.read(c.scopeId, member.profileId)).value,
496
+ member.peerId,
497
+ );
498
+ return {
499
+ publicKey: member.publicKey,
500
+ role: member.publicKey === config.owner ? "owner" : "member",
501
+ name: profile.name,
502
+ description: profile.description ?? "",
503
+ };
504
+ });
505
+ return { configUrl: url, members };
506
+ }
507
+
508
+ function accountProfileLocation(context: SwarmContext, publicKey: string) {
509
+ return {
510
+ parent: join(
511
+ resolve(context.env.HOME ?? context.env.USERPROFILE ?? homedir()),
512
+ ".ipab",
513
+ ),
514
+ name: `${createHash("sha256").update(publicKey).digest("hex")}.json`,
515
+ };
516
+ }
517
+ async function storedAccountProfile(
518
+ context: SwarmContext,
519
+ ): Promise<AccountProfile | undefined> {
520
+ const identity = await contextIdentity(context);
521
+ const { parent, name } = accountProfileLocation(context, identity.publicKey);
522
+ try {
523
+ await lstat(join(parent, "profiles"));
524
+ } catch (cause) {
525
+ if (nodeError(cause, "ENOENT")) return undefined;
526
+ throw cause;
527
+ }
528
+ await protectedPath(parent, true);
529
+ await protectedPath(join(parent, "profiles"), true);
530
+ const value = await readPrivate<unknown>(join(parent, "profiles"), name);
531
+ if (value === undefined) return undefined;
532
+ const data = object(value, "account profile");
533
+ if (
534
+ Object.keys(data).sort().join() !==
535
+ "description,name,publicKey,updatedAt" ||
536
+ data.publicKey !== identity.publicKey ||
537
+ typeof data.name !== "string" ||
538
+ data.name.length > 256 ||
539
+ typeof data.description !== "string" ||
540
+ data.description.length > 2048 ||
541
+ typeof data.updatedAt !== "string" ||
542
+ !Number.isFinite(Date.parse(data.updatedAt))
543
+ )
544
+ throw new HostError(
545
+ "Invalid protected account profile; restore the existing profile file.",
546
+ );
547
+ return {
548
+ publicKey: identity.publicKey,
549
+ name: data.name,
550
+ description: data.description,
551
+ updatedAt: data.updatedAt,
552
+ };
553
+ }
554
+ async function accountProfileDirectory(
555
+ context: SwarmContext,
556
+ publicKey: string,
557
+ ) {
558
+ const { parent } = accountProfileLocation(context, publicKey);
559
+ try {
560
+ await lstat(parent);
561
+ } catch (cause) {
562
+ if (!nodeError(cause, "ENOENT")) throw cause;
563
+ await mkdir(parent, { mode: 0o700 });
564
+ await secureNew(parent, true);
565
+ }
566
+ await protectedPath(parent, true);
567
+ return privateDirectory(parent, "profiles");
568
+ }
569
+ async function initialAccountProfile(
570
+ context: SwarmContext,
571
+ changes: { name?: string; description?: string } = {},
572
+ ): Promise<AccountProfile> {
573
+ const identity = await contextIdentity(context);
574
+ if (changes.name !== undefined && changes.description !== undefined)
575
+ return {
576
+ publicKey: identity.publicKey,
577
+ name: changes.name,
578
+ description: changes.description,
579
+ updatedAt: null,
580
+ };
581
+ const legacy: Profile[] = [];
582
+ for (const entry of withState(context, (state) => state.swarms())) {
583
+ const { config } = await fetchConfig(context, entry.cid);
584
+ const self = config.members.find(
585
+ (member) => member.publicKey === identity.publicKey,
586
+ );
587
+ if (!self) continue; // Pending requests have no public profile yet.
588
+ const c = coordinates(entry.cid);
589
+ legacy.push(
590
+ parseProfile(
591
+ (await client(context, c.service).read(c.scopeId, self.profileId))
592
+ .value,
593
+ self.peerId,
594
+ ),
595
+ );
596
+ }
597
+ const field = (key: "name" | "description") => {
598
+ if (changes[key] !== undefined) return changes[key];
599
+ const values = new Set(legacy.map((profile) => profile[key] ?? ""));
600
+ if (values.size > 1)
601
+ throw new HostError(
602
+ `Legacy Swarm profiles disagree on ${key}. Run ipab profile --${key} TEXT to choose your account-wide value; no profile has been saved.`,
603
+ );
604
+ return values.values().next().value ?? "";
605
+ };
606
+ return {
607
+ publicKey: identity.publicKey,
608
+ name: field("name"),
609
+ description: field("description"),
610
+ updatedAt: null,
611
+ };
612
+ }
613
+ export async function accountProfile(
614
+ context: SwarmContext,
615
+ ): Promise<AccountProfile> {
616
+ return (
617
+ (await storedAccountProfile(context)) ??
618
+ (await initialAccountProfile(context))
619
+ );
620
+ }
621
+ async function ensureAccountProfile(
622
+ context: SwarmContext,
623
+ changes: { name?: string; description?: string } = {},
624
+ ) {
625
+ const identity = await contextIdentity(context);
626
+ const dir = await accountProfileDirectory(context, identity.publicKey);
627
+ return withPrivateLock(dir, async () => {
628
+ const existing = await storedAccountProfile(context);
629
+ if (
630
+ existing &&
631
+ changes.name === undefined &&
632
+ changes.description === undefined
633
+ )
634
+ return existing;
635
+ const profile = {
636
+ ...(existing ?? (await initialAccountProfile(context, changes))),
637
+ ...changes,
638
+ updatedAt: new Date().toISOString(),
639
+ };
640
+ await writePrivate(
641
+ dir,
642
+ accountProfileLocation(context, identity.publicKey).name,
643
+ profile,
644
+ );
645
+ return profile;
646
+ });
647
+ }
648
+ async function syncAccountProfile(
649
+ context: SwarmContext,
650
+ record: LocalMembership,
651
+ personal: AccountProfile,
652
+ fetched?: { profile: Profile; cid: string },
653
+ ): Promise<Profile> {
654
+ const identity = await contextIdentity(context),
655
+ c = coordinates(record.configUrl);
656
+ const self = record.config!.members.find(
657
+ (member) => member.publicKey === identity.publicKey,
658
+ )!;
659
+ const api = client(
660
+ context,
661
+ c.service,
662
+ identity,
663
+ identity.publicKey === record.owner ? undefined : record.secret,
664
+ );
665
+ let existing = fetched;
666
+ if (!existing) {
667
+ const variable = await api.read(c.scopeId, self.profileId);
668
+ existing = {
669
+ profile: parseProfile(variable.value, self.peerId),
670
+ cid: variable.cid,
671
+ };
672
+ }
673
+ const old = existing.profile;
674
+ if (old.name === personal.name && old.description === personal.description)
675
+ return old;
676
+ const profile = {
677
+ ...old,
678
+ name: personal.name,
679
+ description: personal.description,
680
+ updatedAt: new Date().toISOString(),
681
+ };
682
+ await api.write(c.scopeId, self.profileId, profile, existing.cid, uniqueId());
683
+ return profile;
684
+ }
685
+ export async function updateAccountProfile(
686
+ context: SwarmContext,
687
+ changes: { name?: string; description?: string },
688
+ ) {
689
+ if (
690
+ (changes.name?.length ?? 0) > 256 ||
691
+ (changes.description?.length ?? 0) > 2048
692
+ )
693
+ throw new HostError("Profile name/description limit exceeded.");
694
+ await contextIdentity(context, true);
695
+ let profile: AccountProfile;
696
+ try {
697
+ profile = await ensureAccountProfile(context, changes);
698
+ } catch (cause) {
699
+ throw new HostError(
700
+ `Personal profile local persistence failed: ${message(cause)}. No Swarm synchronization was attempted.`,
701
+ );
702
+ }
703
+ const swarms: { configUrl: string; synchronized: boolean; error?: string }[] =
704
+ [];
705
+ for (const entry of withState(context, (state) => state.swarms())) {
706
+ try {
707
+ const record = await approvedMembership(context, entry.cid);
708
+ await syncAccountProfile(context, record, profile);
709
+ swarms.push({ configUrl: entry.cid, synchronized: true });
710
+ } catch (cause) {
711
+ swarms.push({
712
+ configUrl: entry.cid,
713
+ synchronized: false,
714
+ error: message(cause),
715
+ });
716
+ }
717
+ }
718
+ return { profile, localPersisted: true, swarms };
351
719
  }
352
720
  async function fetchConfig(
353
721
  context: SwarmContext,
@@ -361,12 +729,96 @@ async function fetchConfig(
361
729
  api.read(c.scopeId, c.configId, options),
362
730
  api.send<{ owner: string }>("GET", c.scopeId, "", undefined, options),
363
731
  ]);
364
- const config = parseOrganization(variable.value, configUrl);
365
- if (scope.owner !== config.owner)
732
+ const raw = object(variable.value, "organization configuration");
733
+ if (scope.owner !== raw.owner)
366
734
  throw new HostError(
367
735
  "Organization Owner does not match the immutable Scope trust root.",
368
736
  );
369
- return { config, variable };
737
+ if (raw.v === 2) {
738
+ if (
739
+ !Array.isArray(raw.members) ||
740
+ raw.members.length < 1 ||
741
+ raw.members.length > 256
742
+ )
743
+ throw new HostError("Invalid organization member directory.");
744
+ const ids = new Set<string>(),
745
+ identities = new Set<string>();
746
+ const directory = raw.members.map((item: unknown) => {
747
+ const member = object(item, "member directory entry");
748
+ if (
749
+ Object.keys(member).sort().join() !== "memberId,publicKey" ||
750
+ !isCanonicalPublicKey(member.publicKey) ||
751
+ typeof member.memberId !== "string" ||
752
+ !RESOURCE_ID_PATTERN.test(member.memberId) ||
753
+ ids.has(member.memberId) ||
754
+ identities.has(member.publicKey)
755
+ )
756
+ throw new HostError("Invalid or duplicate member directory entry.");
757
+ ids.add(member.memberId);
758
+ identities.add(member.publicKey);
759
+ return { publicKey: member.publicKey, memberId: member.memberId };
760
+ });
761
+ const members = await boundedMap(directory, async (entry) => {
762
+ const member = object(
763
+ (await api.read(c.scopeId, entry.memberId, options)).value,
764
+ "member record",
765
+ );
766
+ if (member.publicKey !== entry.publicKey)
767
+ throw new HostError(
768
+ "Member record does not match its directory identity.",
769
+ );
770
+ return { ...member, memberId: entry.memberId };
771
+ });
772
+ return {
773
+ config: parseOrganization({ ...raw, members }, configUrl),
774
+ variable,
775
+ };
776
+ }
777
+ return { config: parseOrganization(raw, configUrl), variable };
778
+ }
779
+ async function boundedMap<T, U>(
780
+ items: readonly T[],
781
+ operation: (item: T) => Promise<U>,
782
+ ): Promise<U[]> {
783
+ const results: U[] = [];
784
+ for (let offset = 0; offset < items.length; offset += 16) {
785
+ const batch = await Promise.allSettled(
786
+ items.slice(offset, offset + 16).map(operation),
787
+ );
788
+ for (const result of batch) {
789
+ if (result.status === "rejected") throw result.reason;
790
+ results.push(result.value);
791
+ }
792
+ }
793
+ return results;
794
+ }
795
+ function configValue(config: Organization): unknown {
796
+ if (config.v === 1) return config;
797
+ return {
798
+ ...config,
799
+ members: config.members.map((member) => {
800
+ if (!member.memberId)
801
+ throw new HostError("Member directory is missing its record ID.");
802
+ return { publicKey: member.publicKey, memberId: member.memberId };
803
+ }),
804
+ };
805
+ }
806
+ async function createMemberRecord(
807
+ api: ScopeClient,
808
+ scopeId: string,
809
+ member: Member,
810
+ key: string,
811
+ ): Promise<Member> {
812
+ const value = {
813
+ publicKey: member.publicKey,
814
+ encryptionKey: member.encryptionKey,
815
+ peerId: member.peerId,
816
+ profileId: member.profileId,
817
+ requestId: member.requestId,
818
+ approval: member.approval,
819
+ };
820
+ const created = await api.create(scopeId, value, key);
821
+ return { ...value, memberId: created.id };
370
822
  }
371
823
  function binding(
372
824
  configUrl: string,
@@ -458,23 +910,29 @@ async function privateSource(
458
910
  identity.publicKey,
459
911
  );
460
912
  }
913
+ const personal = await storedAccountProfile(context);
461
914
  const addresses = new Map<string, readonly string[]>();
462
915
  const api = client(context, c.service);
463
916
  let selfProfile: { profile: Profile; cid: string } | undefined;
464
- const profiles = await Promise.allSettled(
465
- config.members.map((member) =>
466
- api.read(c.scopeId, member.profileId, signal ? { signal } : {}),
467
- ),
917
+ const profiles = await boundedMap(config.members, (member) =>
918
+ api.read(c.scopeId, member.profileId, signal ? { signal } : {}),
468
919
  );
469
920
  for (const [index, member] of config.members.entries()) {
470
- const result = profiles[index]!;
471
- if (result.status === "rejected") throw result.reason;
472
- const profile = result.value;
921
+ const profile = profiles[index]!;
473
922
  const value = parseProfile(profile.value, member.peerId);
474
923
  if (member.publicKey === identity.publicKey)
475
924
  selfProfile = { profile: value, cid: profile.cid };
476
925
  addresses.set(member.peerId, value.addresses);
477
926
  }
927
+ if (personal && selfProfile) {
928
+ selfProfile.profile = await syncAccountProfile(
929
+ context,
930
+ record,
931
+ personal,
932
+ selfProfile,
933
+ );
934
+ selfProfile.cid = await valueCid(selfProfile.profile);
935
+ }
478
936
  const desired = memberPeers(self.peerId, addresses, config.bootstrap);
479
937
  signal?.throwIfAborted();
480
938
  const node = await startNode(
@@ -633,6 +1091,9 @@ async function readyMembership(
633
1091
  return refresh(context, configUrl);
634
1092
  throw cause;
635
1093
  }
1094
+ } else {
1095
+ const personal = await storedAccountProfile(context);
1096
+ if (personal) await syncAccountProfile(context, record, personal);
636
1097
  }
637
1098
  return record;
638
1099
  }
@@ -781,19 +1242,125 @@ export async function jsonBundle(
781
1242
  await encoded.close();
782
1243
  }
783
1244
  }
1245
+ async function writeStateBundle(
1246
+ store: IpfsStore,
1247
+ configuration: SwarmMeta,
1248
+ targets: Record<string, CID>,
1249
+ ): Promise<string> {
1250
+ const meta = parseSwarmMeta(configuration);
1251
+ const names = Object.fromEntries(
1252
+ Object.entries(targets).map(([name, cid]) => [
1253
+ formalName(name),
1254
+ cid.toString(),
1255
+ ]),
1256
+ );
1257
+ return jsonBundle(
1258
+ store,
1259
+ meta.skillPath === undefined ? legacySwarmStateType : swarmStateType,
1260
+ { v: 5, ...meta, names },
1261
+ );
1262
+ }
784
1263
  export async function writeSnapshot(
785
1264
  store: IpfsStore,
786
1265
  snapshot: Snapshot,
787
1266
  ): Promise<string> {
788
- const encoded = dagCbor.encode(snapshot),
789
- cid = CID.createV1(dagCbor.code, await sha256.digest(encoded));
790
- await store.put(cid, encoded);
791
- return cid.toString();
1267
+ if (snapshot.stateBundle) {
1268
+ if (Object.keys(snapshot.registrations ?? {}).length)
1269
+ throw new HostError("State Bundles cannot contain legacy registrations.");
1270
+ return writeStateBundle(store, snapshot.stateBundle.meta, snapshot.names);
1271
+ }
1272
+ const put = async (value: unknown) => {
1273
+ const encoded = dagCbor.encode(value);
1274
+ const cid = CID.createV1(dagCbor.code, await sha256.digest(encoded));
1275
+ await store.put(cid, encoded);
1276
+ return cid;
1277
+ };
1278
+ const names = await put(snapshot.names);
1279
+ if (Object.keys(snapshot.registrations ?? {}).length) {
1280
+ const registrations = await put(snapshot.registrations);
1281
+ return (await put({ v: 3, names, registrations })).toString();
1282
+ }
1283
+ return (await put({ v: 4, names })).toString();
1284
+ }
1285
+ async function readState(store: IpfsStore, cid: CID): Promise<Snapshot> {
1286
+ if (cid.code !== dagCbor.code) {
1287
+ const bundle = await openBundle(cid, {
1288
+ resolveCid: (key) => store.block.get(key.toString()),
1289
+ });
1290
+ const type =
1291
+ bundle.schemaKey === legacySwarmStateSchema.cid.toString()
1292
+ ? legacySwarmStateType
1293
+ : swarmStateType;
1294
+ const value = object(
1295
+ await typedJson(store, cid.toString(), type),
1296
+ "State Bundle",
1297
+ );
1298
+ if (
1299
+ value.v !== 5 ||
1300
+ Object.keys(value).sort().join() !==
1301
+ (type === legacySwarmStateType
1302
+ ? "names,registryPath,templatePath,v"
1303
+ : "names,registryPath,skillPath,templatePath,v")
1304
+ )
1305
+ throw new HostError("Invalid State Bundle entry.");
1306
+ const meta = parseSwarmMeta({
1307
+ templatePath: value.templatePath,
1308
+ registryPath: value.registryPath,
1309
+ ...(type === legacySwarmStateType ? {} : { skillPath: value.skillPath }),
1310
+ });
1311
+ const names = Object.fromEntries(
1312
+ Object.entries(object(value.names, "Names")).map(([name, target]) => {
1313
+ formalName(name);
1314
+ if (typeof target !== "string" || exactCid(target) !== target)
1315
+ throw new HostError("State Names require exact canonical CIDs.");
1316
+ return [name, CID.parse(target)];
1317
+ }),
1318
+ );
1319
+ return { v: 2, names, stateBundle: { meta, cid: cid.toString() } };
1320
+ }
1321
+ const data = await store.block.get(cid.toString());
1322
+ const root = object(dagCbor.decode(data), "State");
1323
+ if (root.v === 4) {
1324
+ const names = CID.asCID(root.names);
1325
+ if (!names || Object.keys(root).sort().join() !== "names,v")
1326
+ throw new HostError("Invalid State Names root.");
1327
+ return decodeSnapshot(
1328
+ dagCbor.encode({
1329
+ v: 2,
1330
+ names: dagCbor.decode(await store.block.get(names.toString())),
1331
+ }),
1332
+ );
1333
+ }
1334
+ if (root.v !== 3) return decodeSnapshot(data);
1335
+ const names = CID.asCID(root.names),
1336
+ registrations = CID.asCID(root.registrations);
1337
+ if (
1338
+ !names ||
1339
+ !registrations ||
1340
+ Object.keys(root).sort().join() !== "names,registrations,v"
1341
+ )
1342
+ throw new HostError("Invalid State index roots.");
1343
+ const [namesBlock, registrationsBlock] = await Promise.all([
1344
+ store.block.get(names.toString()),
1345
+ store.block.get(registrations.toString()),
1346
+ ]);
1347
+ return decodeSnapshot(
1348
+ dagCbor.encode({
1349
+ v: 2,
1350
+ names: dagCbor.decode(namesBlock),
1351
+ registrations: dagCbor.decode(registrationsBlock),
1352
+ }),
1353
+ );
792
1354
  }
793
1355
  function decodeSnapshot(data: Uint8Array): Snapshot {
794
1356
  const value = object(dagCbor.decode(data), "State"),
795
1357
  names = object(value.names, "Names");
796
- if (value.v !== 2 || Object.keys(value).sort().join() !== "names,v")
1358
+ if (
1359
+ value.v !== 2 ||
1360
+ Object.keys(value).some(
1361
+ (key) => !["v", "names", "registrations"].includes(key),
1362
+ )
1363
+ )
797
1364
  throw new HostError("Unsupported old State; rebuild the Swarm.");
798
1365
  const links: [string, CID][] = [];
799
1366
  for (const [name, link] of Object.entries(names)) {
@@ -802,14 +1369,53 @@ function decodeSnapshot(data: Uint8Array): Snapshot {
802
1369
  if (!cid) throw new HostError("Names must link CIDs.");
803
1370
  links.push([name, cid]);
804
1371
  }
805
- return { v: 2, names: Object.fromEntries(links) };
1372
+ const registrations: NonNullable<Snapshot["registrations"]> = {};
1373
+ if (value.registrations !== undefined) {
1374
+ for (const [schema, raw] of Object.entries(
1375
+ object(value.registrations, "Registrations"),
1376
+ )) {
1377
+ const item = object(raw, "Association");
1378
+ const appCid = CID.asCID(item.appCid);
1379
+ if (
1380
+ Object.keys(item).sort().join() !== "appCid,argv" ||
1381
+ !appCid ||
1382
+ !Array.isArray(item.argv) ||
1383
+ !item.argv.every(
1384
+ (argument): argument is string => typeof argument === "string",
1385
+ )
1386
+ )
1387
+ throw new HostError("Invalid shared Association.");
1388
+ const association = createAssociation(
1389
+ schema,
1390
+ appCid.toString(),
1391
+ item.argv,
1392
+ );
1393
+ if (association.schemaCid !== schema)
1394
+ throw new HostError(
1395
+ "Shared Association requires a canonical type CID.",
1396
+ );
1397
+ registrations[schema] = { appCid, argv: association.argv };
1398
+ }
1399
+ }
1400
+ return {
1401
+ v: 2,
1402
+ names: Object.fromEntries(links),
1403
+ ...(value.registrations !== undefined ? { registrations } : {}),
1404
+ };
806
1405
  }
807
1406
  export async function readSnapshot(
808
1407
  store: IpfsStore,
809
1408
  root: string,
810
1409
  ): Promise<Snapshot> {
811
1410
  const publication = await readPublication(store, root);
812
- return decodeSnapshot(await store.block.get(publication.state.toString()));
1411
+ return readState(store, publication.state);
1412
+ }
1413
+ async function readHeaderSnapshot(store: IpfsStore, root: string) {
1414
+ const publication = await readPublication(store, root);
1415
+ return {
1416
+ snapshot: await readState(store, publication.state),
1417
+ stateCid: publication.state.toString(),
1418
+ };
813
1419
  }
814
1420
  async function readPublication(
815
1421
  store: IpfsStore,
@@ -857,6 +1463,19 @@ export interface SwarmHeader {
857
1463
  config: Organization;
858
1464
  source: "cache" | "network";
859
1465
  verifiedAt: string;
1466
+ stateCid: string;
1467
+ projection?: SwarmProjection;
1468
+ localSourceReady?: boolean;
1469
+ }
1470
+ function missingContent(cause: unknown): boolean {
1471
+ let failure: unknown = cause;
1472
+ for (
1473
+ let depth = 0;
1474
+ depth < 8 && failure instanceof ContentBundleError;
1475
+ depth++
1476
+ )
1477
+ failure = failure.cause;
1478
+ return failure instanceof ContentError && failure.code === "missing_block";
860
1479
  }
861
1480
  export async function sharedSwarmStatus(
862
1481
  context: SwarmContext,
@@ -867,12 +1486,11 @@ export async function sharedSwarmStatus(
867
1486
  const head = headValue(
868
1487
  await client(context, c.service).read(c.scopeId, config.headId),
869
1488
  );
870
- let snapshot: Snapshot;
1489
+ let content: Awaited<ReturnType<typeof readHeaderSnapshot>>;
871
1490
  try {
872
- snapshot = await readSnapshot(context.store, head.root);
1491
+ content = await readHeaderSnapshot(context.store, head.root);
873
1492
  } catch (cause) {
874
- if (!(cause instanceof ContentError) || cause.code !== "missing_block")
875
- throw cause;
1493
+ if (!missingContent(cause)) throw cause;
876
1494
  const registered = withState(context, (state) =>
877
1495
  state.swarms().some((entry) => entry.cid === configUrl),
878
1496
  );
@@ -882,57 +1500,118 @@ export async function sharedSwarmStatus(
882
1500
  );
883
1501
  return swarmHeader(context, configUrl, true);
884
1502
  }
885
- return {
1503
+ const header: SwarmHeader = {
886
1504
  head,
887
- snapshot,
1505
+ ...content,
888
1506
  config,
889
1507
  source: "network",
890
1508
  verifiedAt: new Date().toISOString(),
891
1509
  };
1510
+ if (
1511
+ withState(context, (state) =>
1512
+ state
1513
+ .contentPins()
1514
+ .some((pin) => pin.swarm === configUrl && pin.status !== "deleting"),
1515
+ )
1516
+ ) {
1517
+ const record = await localForRead(context, configUrl);
1518
+ await lazyPrivateSource(context, configUrl, record.account, config);
1519
+ await refreshNamePins(context, configUrl, header);
1520
+ }
1521
+ return header;
892
1522
  }
893
1523
  export async function swarmHeader(
894
1524
  context: SwarmContext,
895
1525
  configUrl: string,
896
1526
  force = context.forceRefresh ?? false,
1527
+ mode: "active" | "local-first" = "active",
1528
+ ): Promise<SwarmHeader> {
1529
+ try {
1530
+ return await readSwarmHeader(context, configUrl, force, mode);
1531
+ } catch (cause) {
1532
+ withState(context, (state) => {
1533
+ for (const pin of state.contentPins())
1534
+ if (pin.swarm === configUrl && pin.status !== "deleting")
1535
+ state.saveContentPin({
1536
+ ...pin,
1537
+ freshness: "stale",
1538
+ error: message(cause),
1539
+ });
1540
+ });
1541
+ throw cause;
1542
+ }
1543
+ }
1544
+ async function readSwarmHeader(
1545
+ context: SwarmContext,
1546
+ configUrl: string,
1547
+ force = context.forceRefresh ?? false,
1548
+ mode: "active" | "local-first" = "active",
897
1549
  ): Promise<SwarmHeader> {
898
1550
  canonicalSwarmUrl(configUrl);
899
- let record = force
900
- ? await refresh(context, configUrl)
901
- : await readyMembership(context, configUrl);
902
- const cached = !force && cachedHeader(context, record);
903
- if (cached) return cached;
904
- let head = await (await boundPointer(context, configUrl, record)).read();
905
- let snapshot: Snapshot;
1551
+ let record =
1552
+ mode === "local-first"
1553
+ ? await approvedMembership(context, configUrl)
1554
+ : force
1555
+ ? await refresh(context, configUrl)
1556
+ : await readyMembership(context, configUrl);
1557
+ const cached = !force && (await cachedHeader(context, record));
1558
+ if (cached) {
1559
+ projectHeader(context, record, cached);
1560
+ await refreshNamePins(context, configUrl, cached);
1561
+ return cached;
1562
+ }
1563
+ if (mode === "local-first") {
1564
+ await saveLocal(context, record);
1565
+ await lazyPrivateSource(context, configUrl, record.account, record.config!);
1566
+ }
1567
+ const c = coordinates(configUrl);
1568
+ let head =
1569
+ mode === "local-first"
1570
+ ? headValue(
1571
+ await client(context, c.service).read(
1572
+ c.scopeId,
1573
+ record.config!.headId,
1574
+ ),
1575
+ )
1576
+ : await (await boundPointer(context, configUrl, record)).read();
1577
+ let content: Awaited<ReturnType<typeof readHeaderSnapshot>>;
906
1578
  try {
907
- snapshot = await readSnapshot(context.store, head.root);
908
- } catch {
1579
+ content = await readHeaderSnapshot(context.store, head.root);
1580
+ } catch (cause) {
1581
+ if (mode === "local-first") throw cause;
909
1582
  record = await refresh(context, configUrl);
910
1583
  head = await (await boundPointer(context, configUrl, record)).read();
911
- snapshot = await readSnapshot(context.store, head.root);
1584
+ content = await readHeaderSnapshot(context.store, head.root);
912
1585
  }
913
1586
  const current = await local(context, configUrl),
914
1587
  verifiedAt = Date.now();
915
1588
  withState(context, (state) => {
916
1589
  state.saveSwarmHeader(record.account, configUrl, {
917
1590
  head,
918
- snapshot: Buffer.from(dagCbor.encode(snapshot)).toString("base64"),
1591
+ snapshot: Buffer.from(dagCbor.encode(content.snapshot)).toString(
1592
+ "base64",
1593
+ ),
1594
+ stateCid: content.stateCid,
919
1595
  verifiedAt,
920
1596
  headId: current.config!.headId,
921
1597
  epoch: current.config!.epoch,
922
1598
  });
923
1599
  });
924
- return {
1600
+ const header: SwarmHeader = {
925
1601
  head,
926
- snapshot,
1602
+ ...content,
927
1603
  config: current.config!,
928
1604
  source: "network",
929
1605
  verifiedAt: new Date(verifiedAt).toISOString(),
930
1606
  };
1607
+ projectHeader(context, current, header);
1608
+ await refreshNamePins(context, configUrl, header);
1609
+ return header;
931
1610
  }
932
- function cachedHeader(
1611
+ async function cachedHeader(
933
1612
  context: SwarmContext,
934
1613
  record: LocalMembership,
935
- ): SwarmHeader | undefined {
1614
+ ): Promise<SwarmHeader | undefined> {
936
1615
  const config = record.config;
937
1616
  if (!config || !record.secret) return;
938
1617
  const cached = withState(context, (state) =>
@@ -944,6 +1623,7 @@ function cachedHeader(
944
1623
  verifiedAt: number;
945
1624
  headId: string;
946
1625
  epoch?: number;
1626
+ stateCid?: string;
947
1627
  }
948
1628
  | undefined;
949
1629
  const age = cached ? Date.now() - cached.verifiedAt : NaN;
@@ -954,21 +1634,84 @@ function cachedHeader(
954
1634
  !(age >= 0 && age < (context.cacheTtl ?? 300) * 1000)
955
1635
  )
956
1636
  return;
1637
+ const cachedSnapshot = object(
1638
+ dagCbor.decode(Buffer.from(cached.snapshot, "base64")),
1639
+ "cached State",
1640
+ );
1641
+ const { stateBundle, ...legacySnapshot } = cachedSnapshot;
1642
+ const snapshot = decodeSnapshot(dagCbor.encode(legacySnapshot));
1643
+ if (stateBundle !== undefined) {
1644
+ const data = object(stateBundle, "cached State Bundle");
1645
+ if (
1646
+ Object.keys(data).sort().join() !== "cid,meta" ||
1647
+ typeof data.cid !== "string" ||
1648
+ exactCid(data.cid) !== data.cid ||
1649
+ (cached.stateCid !== undefined && data.cid !== cached.stateCid)
1650
+ )
1651
+ throw new HostError("Invalid cached State Bundle.");
1652
+ snapshot.stateBundle = { meta: parseSwarmMeta(data.meta), cid: data.cid };
1653
+ }
1654
+ let stateCid = cached.stateCid;
1655
+ if (!stateCid) {
1656
+ try {
1657
+ stateCid = (
1658
+ await readPublication(context.store, headValue(cached.head).root)
1659
+ ).state.toString();
1660
+ } catch (cause) {
1661
+ if (cause instanceof ContentError && cause.code === "missing_block")
1662
+ return;
1663
+ throw cause;
1664
+ }
1665
+ }
957
1666
  return {
958
1667
  head: headValue(cached.head),
959
- snapshot: decodeSnapshot(Buffer.from(cached.snapshot, "base64")),
1668
+ snapshot,
1669
+ stateCid,
960
1670
  config,
961
1671
  source: "cache",
962
1672
  verifiedAt: new Date(cached.verifiedAt).toISOString(),
963
1673
  };
964
1674
  }
965
- async function localHeader(context: SwarmContext, url: string) {
966
- if (context.forceRefresh) return;
967
- canonicalSwarmUrl(url);
968
- const record = await localForRead(context, url);
969
- const header = cachedHeader(context, record);
970
- if (!header) return;
971
- const config = parseOrganization(header.config, url);
1675
+ function projectHeader(
1676
+ context: SwarmContext,
1677
+ record: LocalMembership,
1678
+ header: SwarmHeader,
1679
+ ): void {
1680
+ const member = header.config.members.find(
1681
+ (item) => item.publicKey === record.account,
1682
+ );
1683
+ if (!member || record.owner !== header.config.owner)
1684
+ throw new HostError(
1685
+ "Projection membership does not match the verified account.",
1686
+ );
1687
+ const binding: SwarmProjection = {
1688
+ account: record.account,
1689
+ swarm: record.configUrl,
1690
+ stateCid: header.stateCid,
1691
+ root: header.head.root,
1692
+ valueCid: header.head.cid,
1693
+ verifiedAt: Date.parse(header.verifiedAt),
1694
+ headId: header.config.headId,
1695
+ epoch: header.config.epoch,
1696
+ membership: JSON.stringify({ owner: record.owner, member }),
1697
+ };
1698
+ withState(context, (state) => {
1699
+ state.projectSwarm(binding, header.snapshot.names, () => []);
1700
+ });
1701
+ header.projection = binding;
1702
+ }
1703
+ function headerProjection(header: SwarmHeader): SwarmProjection {
1704
+ if (!header.projection)
1705
+ throw new HostError("A verified account projection is required.");
1706
+ return header.projection;
1707
+ }
1708
+ async function localHeader(context: SwarmContext, url: string) {
1709
+ if (context.forceRefresh) return;
1710
+ canonicalSwarmUrl(url);
1711
+ const record = await localForRead(context, url);
1712
+ const header = await cachedHeader(context, record);
1713
+ if (!header) return;
1714
+ const config = parseOrganization(header.config, url);
972
1715
  const member = config.members.find(
973
1716
  (item) => item.publicKey === record.account,
974
1717
  );
@@ -992,6 +1735,18 @@ async function localHeader(context: SwarmContext, url: string) {
992
1735
  config.epoch,
993
1736
  member.peerId,
994
1737
  );
1738
+ projectHeader(context, record, header);
1739
+ if (
1740
+ withState(context, (state) =>
1741
+ state
1742
+ .contentPins()
1743
+ .some((pin) => pin.swarm === url && pin.status !== "deleting"),
1744
+ )
1745
+ ) {
1746
+ await lazyPrivateSource(context, url, record.account, header.config);
1747
+ header.localSourceReady = true;
1748
+ await refreshNamePins(context, url, header);
1749
+ }
995
1750
  return { header, account: record.account };
996
1751
  }
997
1752
 
@@ -1003,6 +1758,9 @@ async function lazyPrivateSource(
1003
1758
  account: string,
1004
1759
  basis: Organization,
1005
1760
  ) {
1761
+ const finishPrevious = context.finishRead;
1762
+ delete context.finishRead;
1763
+ await finishPrevious?.();
1006
1764
  const lifetime = new AbortController();
1007
1765
  let pending: Promise<ReturnType<typeof kuboSource>> | undefined;
1008
1766
  const load = async (signal: AbortSignal) => {
@@ -1066,11 +1824,14 @@ interface Creation {
1066
1824
  name: string;
1067
1825
  description: string;
1068
1826
  createdAt: string;
1827
+ personal?: { name: string; description: string };
1828
+ profile?: Profile;
1069
1829
  scopeId?: string;
1070
1830
  headId?: string;
1071
1831
  profileId?: string;
1072
1832
  configId?: string;
1073
1833
  config?: Organization;
1834
+ seed?: { root: string; car: string; roots: string[] };
1074
1835
  }
1075
1836
  export async function createSwarm(
1076
1837
  context: SwarmContext,
@@ -1101,6 +1862,7 @@ export async function createSwarm(
1101
1862
  const identity = await contextIdentity(context, true),
1102
1863
  op = options.resume ?? uniqueId(),
1103
1864
  dir = await directory(context);
1865
+ const personal = await ensureAccountProfile(context);
1104
1866
  if (!POINTER_ID_PATTERN.test(op))
1105
1867
  throw new HostError("Invalid creation resume ID.");
1106
1868
  return withPrivateLock(dir, async () => {
@@ -1124,6 +1886,7 @@ export async function createSwarm(
1124
1886
  name: options.properties?.name ?? "",
1125
1887
  description: options.properties?.description ?? "",
1126
1888
  createdAt: new Date().toISOString(),
1889
+ personal: { name: personal.name, description: personal.description },
1127
1890
  };
1128
1891
  await writePrivate(dir, `creation-${op}.json`, record);
1129
1892
  }
@@ -1132,6 +1895,50 @@ export async function createSwarm(
1132
1895
  const save = () => writePrivate(dir, `creation-${op}.json`, record);
1133
1896
  const api = client(context, service, identity);
1134
1897
  try {
1898
+ if (!record.seed) {
1899
+ if (record.headId)
1900
+ throw new HostError(
1901
+ "Legacy creation has an unseeded HEAD. Preserve this recovery record and explicitly migrate the Swarm; it cannot complete as a newly seeded Swarm.",
1902
+ );
1903
+ const names: Record<string, CID> = {};
1904
+ for (const selector of seedTemplateNames) {
1905
+ const template = await seedTemplateSource(selector);
1906
+ for (const [cid, data] of template.blocks)
1907
+ await context.store.put(CID.parse(cid), data);
1908
+ names[`ipab/template/${selector}`] = CID.parse(template.cid);
1909
+ }
1910
+ const skill = await seedSkillSource();
1911
+ for (const [cid, data] of skill.blocks)
1912
+ await context.store.put(CID.parse(cid), data);
1913
+ names["ipab/skills/ipab"] = CID.parse(skill.cid);
1914
+ const root = await publication(
1915
+ context.store,
1916
+ await writeStateBundle(
1917
+ context.store,
1918
+ {
1919
+ templatePath: "ipab/template",
1920
+ registryPath: "ipab/registry",
1921
+ skillPath: "ipab/skills",
1922
+ },
1923
+ names,
1924
+ ),
1925
+ );
1926
+ const roots = await frozenPublicationClosure(context.store, root);
1927
+ record.seed = {
1928
+ root,
1929
+ roots,
1930
+ car: Buffer.from(await contentCar(context.store, roots)).toString(
1931
+ "base64",
1932
+ ),
1933
+ };
1934
+ await save();
1935
+ }
1936
+ const seedBytes = Buffer.from(record.seed.car, "base64");
1937
+ const seed = await CarBlockIterator.fromIterable(
1938
+ streamChunks(new Blob([seedBytes]).stream()),
1939
+ );
1940
+ for await (const block of seed)
1941
+ await context.store.put(block.cid, block.bytes);
1135
1942
  if (!record.scopeId) {
1136
1943
  record.scopeId = (await api.createScope(`${op}.scope`)).id;
1137
1944
  await save();
@@ -1142,30 +1949,48 @@ export async function createSwarm(
1142
1949
  context.listen,
1143
1950
  );
1144
1951
  if (!record.headId) {
1145
- const root = await publication(
1146
- context.store,
1147
- await writeSnapshot(context.store, { v: 2, names: {} }),
1148
- );
1149
1952
  record.headId = (
1150
- await api.create(record.scopeId, { root }, `${op}.head`)
1953
+ await api.create(
1954
+ record.scopeId,
1955
+ { root: record.seed.root },
1956
+ `${op}.head`,
1957
+ )
1151
1958
  ).id;
1152
1959
  await save();
1153
1960
  }
1154
1961
  if (!record.profileId) {
1155
- const addresses = options.addresses ?? node.addresses;
1156
- for (const address of addresses) validateAddress(address, node.peerId);
1962
+ if (!record.profile) {
1963
+ const addresses = options.addresses ?? node.addresses;
1964
+ for (const address of addresses)
1965
+ validateAddress(address, node.peerId);
1966
+ record.profile = {
1967
+ ...(record.personal ?? { name: record.name }),
1968
+ addresses,
1969
+ updatedAt: record.createdAt,
1970
+ };
1971
+ await save();
1972
+ }
1157
1973
  record.profileId = (
1158
- await api.create(
1159
- record.scopeId,
1160
- { name: record.name, addresses, updatedAt: record.createdAt },
1161
- `${op}.profile`,
1162
- )
1974
+ await api.create(record.scopeId, record.profile, `${op}.profile`)
1163
1975
  ).id;
1164
1976
  await save();
1165
1977
  }
1166
1978
  if (!record.config) {
1979
+ const member = await createMemberRecord(
1980
+ api,
1981
+ record.scopeId,
1982
+ {
1983
+ publicKey: identity.publicKey,
1984
+ encryptionKey: record.encryption.publicKey,
1985
+ peerId: node.peerId,
1986
+ profileId: record.profileId,
1987
+ requestId: op,
1988
+ approval: null,
1989
+ },
1990
+ `${op}.member`,
1991
+ );
1167
1992
  record.config = {
1168
- v: 1,
1993
+ v: 2,
1169
1994
  scopeId: record.scopeId,
1170
1995
  owner: identity.publicKey,
1171
1996
  name: record.name,
@@ -1173,22 +1998,17 @@ export async function createSwarm(
1173
1998
  headId: record.headId,
1174
1999
  epoch: 1,
1175
2000
  bootstrap: options.addresses ?? node.addresses,
1176
- members: [
1177
- {
1178
- publicKey: identity.publicKey,
1179
- encryptionKey: record.encryption.publicKey,
1180
- peerId: node.peerId,
1181
- profileId: record.profileId,
1182
- requestId: op,
1183
- approval: null,
1184
- },
1185
- ],
2001
+ members: [member],
1186
2002
  };
1187
2003
  await save();
1188
2004
  }
1189
2005
  if (!record.configId) {
1190
2006
  record.configId = (
1191
- await api.create(record.scopeId, record.config, `${op}.config`)
2007
+ await api.create(
2008
+ record.scopeId,
2009
+ configValue(record.config),
2010
+ `${op}.config`,
2011
+ )
1192
2012
  ).id;
1193
2013
  await save();
1194
2014
  }
@@ -1216,7 +2036,7 @@ export async function createSwarm(
1216
2036
  const head = await api.read(record.scopeId, record.headId);
1217
2037
  await provideContent(
1218
2038
  context.store,
1219
- [headValue(head).root],
2039
+ [...new Set([headValue(head).root, ...record.seed.roots])],
1220
2040
  context.node!.api,
1221
2041
  context.fetch,
1222
2042
  context.node!.auth,
@@ -1255,21 +2075,23 @@ export async function requestMembership(
1255
2075
  context: SwarmContext,
1256
2076
  url: string,
1257
2077
  options: {
1258
- ownerFingerprint: string;
1259
- name?: string;
1260
2078
  alias?: string;
1261
2079
  output?: string;
1262
2080
  },
1263
- ): Promise<string> {
1264
- if ((options.name?.length ?? 0) > 256)
1265
- throw new HostError("Request name exceeds 256 characters.");
2081
+ ): Promise<{
2082
+ requestId: string;
2083
+ ownerFingerprint: string;
2084
+ request: MembershipRequest;
2085
+ file?: string;
2086
+ }> {
2087
+ if ("name" in options)
2088
+ throw new HostError(
2089
+ "Set your account-wide name with ipab profile --name NAME before requesting membership.",
2090
+ );
1266
2091
  canonicalSwarmUrl(url);
1267
2092
  const identity = await contextIdentity(context, true);
1268
2093
  const { config } = await fetchConfig(context, url);
1269
- if (options.ownerFingerprint !== (await keyId(config.owner)))
1270
- throw new HostError(
1271
- `Trusted Owner fingerprint required; observed ${await keyId(config.owner)}. Verify through an independent trusted channel.`,
1272
- );
2094
+ const personal = await ensureAccountProfile(context);
1273
2095
  const dir = await directory(context);
1274
2096
  await withPrivateLock(dir, async () => {
1275
2097
  if (options.alias !== undefined)
@@ -1303,7 +2125,7 @@ export async function requestMembership(
1303
2125
  configUrl: url,
1304
2126
  scopeId: config.scopeId,
1305
2127
  owner: config.owner,
1306
- name: options.name ?? "",
2128
+ name: personal.name,
1307
2129
  member: identity.publicKey,
1308
2130
  encryptionKey: encryption.publicKey,
1309
2131
  peerId: node.peerId,
@@ -1329,15 +2151,46 @@ export async function requestMembership(
1329
2151
  });
1330
2152
  withState(context, (state) => state.registerSwarm(url, options.alias));
1331
2153
  });
1332
- if (options.output) await exportRequest(context, url, options.output);
1333
- return (await local(context, url)).request!.id;
2154
+ const file =
2155
+ options.output === undefined ? undefined : resolve(options.output);
2156
+ if (file !== undefined) await exportRequest(context, url, file);
2157
+ const record = await local(context, url);
2158
+ return {
2159
+ requestId: record.request!.id,
2160
+ ownerFingerprint: await keyId(record.owner),
2161
+ request: record.request!,
2162
+ ...(file === undefined ? {} : { file }),
2163
+ };
1334
2164
  }
1335
2165
  export async function verifiedRequest(
1336
2166
  path: string,
1337
2167
  ): Promise<MembershipRequest> {
1338
2168
  if ((await lstat(path)).size > 16 * 1024)
1339
2169
  throw new HostError("Request file exceeds 16 KiB.");
1340
- return verifyRequest(JSON.parse(await readFile(path, "utf8")) as unknown);
2170
+ return verifiedRequestStream(createReadStream(path));
2171
+ }
2172
+ export async function verifiedRequestStream(
2173
+ input: AsyncIterable<string | Uint8Array>,
2174
+ ): Promise<MembershipRequest> {
2175
+ const chunks: Uint8Array[] = [];
2176
+ let size = 0;
2177
+ for await (const chunk of input) {
2178
+ const bytes = typeof chunk === "string" ? Buffer.from(chunk) : chunk;
2179
+ size += bytes.byteLength;
2180
+ if (size > 16 * 1024) throw new HostError("Request input exceeds 16 KiB.");
2181
+ chunks.push(bytes);
2182
+ }
2183
+ let value: unknown;
2184
+ try {
2185
+ value = JSON.parse(
2186
+ Buffer.concat(chunks)
2187
+ .toString("utf8")
2188
+ .replace(/^\uFEFF/, ""),
2189
+ );
2190
+ } catch (cause) {
2191
+ throw new HostError(`Invalid Request JSON: ${message(cause)}.`);
2192
+ }
2193
+ return verifyRequest(value);
1341
2194
  }
1342
2195
  async function verifyRequest(input: unknown): Promise<MembershipRequest> {
1343
2196
  const fields = object(input, "Request");
@@ -1539,6 +2392,7 @@ export async function approveMembership(
1539
2392
  c.scopeId,
1540
2393
  {
1541
2394
  name: request.name,
2395
+ description: "",
1542
2396
  addresses: [],
1543
2397
  updatedAt: operation.createdAt,
1544
2398
  },
@@ -1558,6 +2412,7 @@ export async function approveMembership(
1558
2412
  };
1559
2413
  const config = {
1560
2414
  ...fetched.config,
2415
+ v: 2 as const,
1561
2416
  members: fetched.config.members.filter(
1562
2417
  (m) => m.publicKey !== request.member,
1563
2418
  ),
@@ -1566,8 +2421,8 @@ export async function approveMembership(
1566
2421
  throw new HostError("PeerID is already assigned to another member.");
1567
2422
  if (request.member === identity.publicKey)
1568
2423
  throw new HostError("Owner cannot request member approval.");
1569
- if (config.members.length >= 16)
1570
- throw new HostError("Organization member limit is 16.");
2424
+ if (config.members.length >= 256)
2425
+ throw new HostError("Organization member limit is 256.");
1571
2426
  const certificate = await issueScopeCertificate(
1572
2427
  {
1573
2428
  v: 1,
@@ -1588,12 +2443,28 @@ export async function approveMembership(
1588
2443
  operation.baseline = fetched.variable.cid;
1589
2444
  await save();
1590
2445
  }
2446
+ if (operation.value.v === 2) {
2447
+ for (const member of operation.value.members) {
2448
+ if (!member.memberId) {
2449
+ Object.assign(
2450
+ member,
2451
+ await createMemberRecord(
2452
+ api,
2453
+ c.scopeId,
2454
+ member,
2455
+ `${operation.operation}.${member.publicKey}.member`,
2456
+ ),
2457
+ );
2458
+ await save();
2459
+ }
2460
+ }
2461
+ }
1591
2462
  const observed = await api.read(c.scopeId, c.configId);
1592
- if (observed.cid !== (await valueCid(operation.value)))
2463
+ if (observed.cid !== (await valueCid(configValue(operation.value))))
1593
2464
  await api.write(
1594
2465
  c.scopeId,
1595
2466
  c.configId,
1596
- operation.value,
2467
+ configValue(operation.value),
1597
2468
  operation.baseline!,
1598
2469
  `${operation.operation}.publish`,
1599
2470
  );
@@ -1623,7 +2494,7 @@ export async function updateSwarm(
1623
2494
  const result = await client(context, c.service, identity).write(
1624
2495
  c.scopeId,
1625
2496
  c.configId,
1626
- config,
2497
+ configValue(config),
1627
2498
  fetched.variable.cid,
1628
2499
  uniqueId(),
1629
2500
  );
@@ -1639,12 +2510,18 @@ export async function updateSwarm(
1639
2510
  export async function updateProfile(
1640
2511
  context: SwarmContext,
1641
2512
  url: string,
1642
- changes: { name?: string; addresses?: string[] },
2513
+ changes: { addresses?: string[] },
1643
2514
  ): Promise<Profile> {
1644
- if (changes.name !== undefined && changes.name.length > 256)
1645
- throw new HostError("Profile name exceeds 256 characters.");
2515
+ if ("name" in changes || "description" in changes)
2516
+ throw new HostError(
2517
+ "Use ipab profile --name NAME --description TEXT for personal data; swarm profile configures network addresses only.",
2518
+ );
1646
2519
  if ((changes.addresses?.length ?? 0) > 16)
1647
2520
  throw new HostError("Profile address limit is 16.");
2521
+ if (changes.addresses === undefined)
2522
+ throw new HostError(
2523
+ "swarm profile requires --address MULTIADDR; use ipab profile to read personal data.",
2524
+ );
1648
2525
  const record = await readyMembership(context, url),
1649
2526
  identity = await contextIdentity(context),
1650
2527
  c = coordinates(url);
@@ -1789,6 +2666,7 @@ export async function resumeRemoval(
1789
2666
  if (!record.nextConfig) {
1790
2667
  const config = {
1791
2668
  ...record.oldConfig,
2669
+ v: 2 as const,
1792
2670
  headId: record.newHeadId,
1793
2671
  epoch: record.oldConfig.epoch + 1,
1794
2672
  members: structuredClone(
@@ -1820,10 +2698,27 @@ export async function resumeRemoval(
1820
2698
  { certificate, swarmKey: record.newKey },
1821
2699
  identity,
1822
2700
  );
2701
+ delete member.memberId;
1823
2702
  }
1824
2703
  record.nextConfig = config;
1825
2704
  await save();
1826
2705
  }
2706
+ if (record.nextConfig.v === 2) {
2707
+ for (const member of record.nextConfig.members) {
2708
+ if (!member.memberId) {
2709
+ Object.assign(
2710
+ member,
2711
+ await createMemberRecord(
2712
+ api,
2713
+ c.scopeId,
2714
+ member,
2715
+ `${record.operation}.${member.publicKey}.member`,
2716
+ ),
2717
+ );
2718
+ await save();
2719
+ }
2720
+ }
2721
+ }
1827
2722
  const leaving = record.oldConfig.members.find(
1828
2723
  (m) => m.publicKey === record.member,
1829
2724
  )!;
@@ -1850,11 +2745,11 @@ export async function resumeRemoval(
1850
2745
  }
1851
2746
  if (!record.published) {
1852
2747
  const observed = await api.read(c.scopeId, c.configId);
1853
- if (observed.cid !== (await valueCid(record.nextConfig)))
2748
+ if (observed.cid !== (await valueCid(configValue(record.nextConfig))))
1854
2749
  await api.write(
1855
2750
  c.scopeId,
1856
2751
  c.configId,
1857
- record.nextConfig,
2752
+ configValue(record.nextConfig),
1858
2753
  record.configCid,
1859
2754
  `${record.operation}.config`,
1860
2755
  );
@@ -1883,6 +2778,34 @@ export async function resumeRemoval(
1883
2778
  if (!(cause instanceof ScopeApiError) || cause.status !== 410)
1884
2779
  throw cause;
1885
2780
  }
2781
+ for (const member of record.oldConfig.members) {
2782
+ if (
2783
+ member.memberId &&
2784
+ !record.nextConfig.members.some(
2785
+ (next) => next.memberId === member.memberId,
2786
+ )
2787
+ ) {
2788
+ for (const action of ["freeze", "delete"] as const) {
2789
+ try {
2790
+ if (action === "freeze")
2791
+ await api.freeze(
2792
+ c.scopeId,
2793
+ member.memberId,
2794
+ `${record.operation}.${member.publicKey}.freeze`,
2795
+ );
2796
+ else
2797
+ await api.delete(
2798
+ c.scopeId,
2799
+ member.memberId,
2800
+ `${record.operation}.${member.publicKey}.delete`,
2801
+ );
2802
+ } catch (cause) {
2803
+ if (!(cause instanceof ScopeApiError) || cause.status !== 410)
2804
+ throw cause;
2805
+ }
2806
+ }
2807
+ }
2808
+ }
1886
2809
  record.completed = true;
1887
2810
  await save();
1888
2811
  withState(context, (state) => {
@@ -2005,33 +2928,213 @@ export async function resolveReference(
2005
2928
  throw new HostError(
2006
2929
  `Formal Name "${shared.name}" was not found after refreshing HEAD.`,
2007
2930
  );
2008
- if (warm && header === warm.header)
2931
+ if (warm && header === warm.header && !header.localSourceReady)
2009
2932
  await lazyPrivateSource(context, selected, warm.account, header.config);
2010
2933
  targetCid = link.toString();
2011
2934
  } else {
2012
2935
  if (swarm) await readyMembership(context, swarm);
2013
2936
  targetCid = local(reference);
2014
2937
  }
2938
+ const cid = raw ? targetCid : await artifactValue(context.store, targetCid);
2939
+ return { targetCid, cid };
2940
+ }
2941
+ async function artifactValue(
2942
+ store: IpfsStore,
2943
+ targetCid: string,
2944
+ protect?: (cid: string) => Promise<void>,
2945
+ ): Promise<string> {
2015
2946
  let cid = targetCid;
2016
2947
  const visited = new Set<string>();
2017
- for (let depth = 0; !raw; depth++) {
2948
+ for (let depth = 0; ; depth++) {
2018
2949
  if (depth >= 64 || visited.has(cid))
2019
2950
  throw new HostError(
2020
2951
  "Artifact resolution exceeds limits or contains a cycle.",
2021
2952
  );
2022
2953
  visited.add(cid);
2954
+ await protect?.(cid);
2023
2955
  const bundle = await openBundle(CID.parse(cid), {
2024
- resolveCid: (cid) => context.store.block.get(cid.toString()),
2956
+ resolveCid: (cid) => store.block.get(cid.toString()),
2025
2957
  });
2026
2958
  if (bundle.schemaKey !== (await encodeSchema(artifactType)).cid.toString())
2027
2959
  break;
2028
2960
  cid = CID.parse(
2029
- parseArtifact(await typedJson(context.store, cid, artifactType)).value,
2961
+ parseArtifact(await typedJson(store, cid, artifactType)).value,
2030
2962
  )
2031
2963
  .toV1()
2032
2964
  .toString();
2033
2965
  }
2034
- return { targetCid, cid };
2966
+ return cid;
2967
+ }
2968
+ export function pinReference(
2969
+ state: State,
2970
+ reference: string,
2971
+ selected?: string,
2972
+ ): { reference: string; swarm?: string; name?: string } {
2973
+ const shared = parseNameReference(reference);
2974
+ if (!shared) return { reference: exactCid(reference) };
2975
+ const swarm = shared.swarm ? state.resolveSwarm(shared.swarm) : selected;
2976
+ if (!swarm)
2977
+ throw new HostError(
2978
+ "Pinning a shared Name requires --swarm or swarm use, or a Swarm authority in the IPAB URI.",
2979
+ );
2980
+ return {
2981
+ reference: formatNameReference(swarm, shared.name),
2982
+ swarm,
2983
+ name: shared.name,
2984
+ };
2985
+ }
2986
+ export async function pinNameSubscription(
2987
+ context: SwarmContext,
2988
+ reference: string,
2989
+ selected?: string,
2990
+ ) {
2991
+ const canonical = withState(context, (state) =>
2992
+ pinReference(state, reference, selected),
2993
+ );
2994
+ if (!canonical.swarm || !canonical.name) {
2995
+ let roots: string[];
2996
+ try {
2997
+ roots = [
2998
+ ...(await currentDependencies(context.store, canonical.reference)),
2999
+ ];
3000
+ } catch (cause) {
3001
+ if (!selected || !missingContent(cause)) throw cause;
3002
+ const swarm = withState(context, (state) => state.resolveSwarm(selected));
3003
+ await readyMembership(context, swarm);
3004
+ roots = [
3005
+ ...(await currentDependencies(context.store, canonical.reference)),
3006
+ ];
3007
+ }
3008
+ return withStateAsync(context, (state) =>
3009
+ pinCid(state, canonical.reference, context.store, roots),
3010
+ );
3011
+ }
3012
+ const resolved = await resolveReference(
3013
+ context,
3014
+ canonical.reference,
3015
+ canonical.swarm,
3016
+ exactCid,
3017
+ false,
3018
+ "local-first",
3019
+ );
3020
+ const roots = await currentDependencies(context.store, resolved.targetCid);
3021
+ const pin = withState(context, (state) =>
3022
+ reservePin(state, canonical.reference, context.store.configuration, {
3023
+ swarm: canonical.swarm!,
3024
+ name: canonical.name!,
3025
+ }),
3026
+ );
3027
+ return withStateAsync(context, (state) =>
3028
+ retainPin(state, pin, context.store, { ...resolved, roots: [...roots] }),
3029
+ );
3030
+ }
3031
+ async function withStateAsync<T>(
3032
+ context: SwarmContext,
3033
+ operation: (state: State) => Promise<T>,
3034
+ ): Promise<T> {
3035
+ if (context.state) return operation(context.state);
3036
+ const state = new State(context.stateDir);
3037
+ try {
3038
+ return await operation(state);
3039
+ } finally {
3040
+ state.close();
3041
+ }
3042
+ }
3043
+ export async function refreshNamePins(
3044
+ context: SwarmContext,
3045
+ url: string,
3046
+ header: Pick<SwarmHeader, "snapshot">,
3047
+ ): Promise<void> {
3048
+ const pins = withState(context, (state) =>
3049
+ state
3050
+ .contentPins()
3051
+ .filter((pin) => pin.swarm === url && pin.status !== "deleting"),
3052
+ );
3053
+ const failures: string[] = [];
3054
+ for (const saved of pins) {
3055
+ const target = Object.hasOwn(header.snapshot.names, saved.name!)
3056
+ ? header.snapshot.names[saved.name!]!.toString()
3057
+ : undefined;
3058
+ if (!target) {
3059
+ withState(context, (state) => {
3060
+ failedPin(
3061
+ state,
3062
+ saved.reference,
3063
+ new Error(
3064
+ "Shared Name is missing; keeping its last verified version.",
3065
+ ),
3066
+ true,
3067
+ );
3068
+ });
3069
+ context.diagnostic?.(
3070
+ `Pin ${saved.reference} is missing; its last verified version remains retained.`,
3071
+ );
3072
+ continue;
3073
+ }
3074
+ let claimed = false;
3075
+ try {
3076
+ // A cached HEAD can differ from the saved subscription after publication or a failed refresh.
3077
+ if (
3078
+ saved.targetCid === target &&
3079
+ saved.status === "ready" &&
3080
+ saved.freshness === "current"
3081
+ )
3082
+ continue;
3083
+ const pin = withState(context, (state) => refreshPinClaim(state, saved));
3084
+ if (!pin) continue;
3085
+ claimed = true;
3086
+ const cid = await artifactValue(context.store, target);
3087
+ const roots = [...(await currentDependencies(context.store, target))];
3088
+ await withStateAsync(context, (state) =>
3089
+ retainPin(state, pin, context.store, { cid, targetCid: target, roots }),
3090
+ );
3091
+ } catch (cause) {
3092
+ if (claimed)
3093
+ withState(context, (state) => {
3094
+ failedPin(state, saved.reference, cause);
3095
+ });
3096
+ failures.push(`${saved.reference}: ${message(cause)}`);
3097
+ }
3098
+ }
3099
+ if (failures.length)
3100
+ throw new HostError(
3101
+ `Name subscription refresh failed; prior verified versions remain retained:\n${failures.join("\n")}`,
3102
+ 1,
3103
+ "PIN_STALE",
3104
+ );
3105
+ }
3106
+ async function currentDependencies(
3107
+ store: IpfsStore,
3108
+ root: string,
3109
+ found = new Set<string>(),
3110
+ ): Promise<Set<string>> {
3111
+ if (found.has(root)) return found;
3112
+ if (found.size >= 64)
3113
+ throw new HostError("Current pin dependency limit exceeded.");
3114
+ found.add(root);
3115
+ const bundle = await openBundle(CID.parse(root), {
3116
+ resolveCid: (cid) => store.block.get(cid.toString()),
3117
+ });
3118
+ if (bundle.schemaKey === (await encodeSchema(artifactType)).cid.toString()) {
3119
+ await currentDependencies(
3120
+ store,
3121
+ parseArtifact(await typedJson(store, root, artifactType)).value,
3122
+ found,
3123
+ );
3124
+ } else if (bundle.schemaKey === appSchemaCid.toString()) {
3125
+ const app = object((await bundleJson(store, root)).value, "App");
3126
+ if (app.source) {
3127
+ const source = object(app.source, "source");
3128
+ if (typeof source.cid !== "string")
3129
+ throw new HostError("Invalid App source association.");
3130
+ await currentDependencies(store, source.cid, found);
3131
+ }
3132
+ } else if (isSwarmStateSchema(bundle.schemaKey)) {
3133
+ const snapshot = await readState(store, CID.parse(root));
3134
+ for (const target of Object.values(snapshot.names))
3135
+ await currentDependencies(store, target.toString(), found);
3136
+ }
3137
+ return found;
2035
3138
  }
2036
3139
  export async function searchNames(
2037
3140
  context: SwarmContext,
@@ -2065,7 +3168,12 @@ export async function searchNames(
2065
3168
  for (const swarm of swarms) {
2066
3169
  const header =
2067
3170
  (await localHeader(context, swarm.cid))?.header ??
2068
- (await swarmHeader(context, swarm.cid));
3171
+ (await swarmHeader(
3172
+ context,
3173
+ swarm.cid,
3174
+ context.forceRefresh,
3175
+ "local-first",
3176
+ ));
2069
3177
  searched.push({
2070
3178
  configUrl: swarm.cid,
2071
3179
  source: header.source,
@@ -2073,18 +3181,568 @@ export async function searchNames(
2073
3181
  valueCid: header.head.cid,
2074
3182
  verifiedAt: header.verifiedAt,
2075
3183
  });
2076
- for (const name of Object.keys(header.snapshot.names).sort())
2077
- if (name.toLowerCase().includes(query.toLowerCase()))
2078
- matches.push({
2079
- swarm: swarm.cid,
2080
- alias: swarm.alias,
2081
- name,
2082
- reference: formatNameReference(swarm.cid, name),
2083
- targetCid: header.snapshot.names[name]!.toString(),
2084
- });
3184
+ for (const { name, targetCid } of withState(context, (state) =>
3185
+ state.searchSwarmNames(headerProjection(header), query),
3186
+ ))
3187
+ matches.push({
3188
+ swarm: swarm.cid,
3189
+ alias: swarm.alias,
3190
+ name,
3191
+ reference: formatNameReference(swarm.cid, name),
3192
+ targetCid,
3193
+ });
2085
3194
  }
2086
3195
  return { matches, swarms: searched };
2087
3196
  }
3197
+ function assertNamesRegistry(snapshot: Snapshot): void {
3198
+ if (Object.keys(snapshot.registrations ?? {}).length)
3199
+ throw new HostError(
3200
+ "Legacy shared registrations are inactive; per-association argv is unsupported and has not been dropped or migrated. Create a new seeded Swarm and explicitly register intended Apps there. Old Swarm content and history remain readable.",
3201
+ );
3202
+ }
3203
+ export async function swarmMeta(
3204
+ context: SwarmContext,
3205
+ header: Pick<SwarmHeader, "snapshot">,
3206
+ ) {
3207
+ if (header.snapshot.stateBundle) return header.snapshot.stateBundle.meta;
3208
+ const cid = header.snapshot.names.ipab;
3209
+ if (!cid)
3210
+ throw new HostError(
3211
+ 'Swarm Meta Name "ipab" is missing. Create a new seeded Swarm or explicitly publish a typed Swarm Meta Bundle; existing Swarms are never automatically upgraded.',
3212
+ );
3213
+ try {
3214
+ const bundle = await openBundle(cid, {
3215
+ resolveCid: (key) => context.store.block.get(key.toString()),
3216
+ });
3217
+ const type =
3218
+ bundle.schemaKey === legacySwarmMetaSchema.cid.toString()
3219
+ ? legacySwarmMetaType
3220
+ : swarmMetaType;
3221
+ return parseSwarmMeta(await typedJson(context.store, cid.toString(), type));
3222
+ } catch (cause) {
3223
+ throw new HostError(
3224
+ `Invalid Swarm Meta at Name "ipab": ${message(cause)}. Publish a valid typed Meta Bundle explicitly; no builtin or legacy fallback is used.`,
3225
+ );
3226
+ }
3227
+ }
3228
+ function metaCid(snapshot: Snapshot): string {
3229
+ return snapshot.stateBundle?.cid ?? snapshot.names.ipab!.toString();
3230
+ }
3231
+ function hasMeta(snapshot: Snapshot): boolean {
3232
+ return (
3233
+ snapshot.stateBundle !== undefined || Object.hasOwn(snapshot.names, "ipab")
3234
+ );
3235
+ }
3236
+ export interface SharedSkill {
3237
+ name: string;
3238
+ cid: string;
3239
+ identity: string;
3240
+ }
3241
+ export async function swarmSkills(
3242
+ context: SwarmContext,
3243
+ configUrl: string,
3244
+ requested: readonly string[],
3245
+ owner: string,
3246
+ ): Promise<SharedSkill[]> {
3247
+ const warm = await localHeader(context, configUrl);
3248
+ if (warm && !warm.header.localSourceReady)
3249
+ await lazyPrivateSource(
3250
+ context,
3251
+ configUrl,
3252
+ warm.account,
3253
+ warm.header.config,
3254
+ );
3255
+ let header = warm?.header ?? (await swarmHeader(context, configUrl));
3256
+ const roots = new Set<string>();
3257
+ const protect = async (cid: string) => {
3258
+ roots.add(cid);
3259
+ const values = [...roots];
3260
+ context.store.registerOwner(owner, values);
3261
+ await context.store.retain(owner, values);
3262
+ await context.store.confirmRetained(owner, values);
3263
+ };
3264
+ for (let attempt = 0; ; attempt++) {
3265
+ if (!hasMeta(header.snapshot) && header.source === "cache" && !attempt) {
3266
+ header = await swarmHeader(context, configUrl, true);
3267
+ continue;
3268
+ }
3269
+ if (hasMeta(header.snapshot)) await protect(metaCid(header.snapshot));
3270
+ const meta = await swarmMeta(context, header);
3271
+ if (!meta.skillPath)
3272
+ throw new HostError(
3273
+ header.snapshot.stateBundle
3274
+ ? "This Swarm uses the earlier exact State Bundle type without skillPath. There is no in-place root-configuration migration command. Create a new seeded Swarm and explicitly republish reviewed Names. Publishing a user Name ipab never overrides root configuration; upgrades never rewrite it."
3275
+ : `This Swarm uses the legacy exact Meta type without skillPath. Explicitly build and publish a new typed Meta Bundle with templatePath and registryPath preserved and skillPath chosen, then run ipab publish ipab META_SOURCE --expect ${metaCid(header.snapshot)}. Upgrades never overwrite Meta.`,
3276
+ );
3277
+ const prefix = `${meta.skillPath}/`;
3278
+ const entries = Object.entries(header.snapshot.names).filter(([name]) =>
3279
+ name.startsWith(prefix),
3280
+ );
3281
+ for (const [, target] of entries) roots.add(target.toString());
3282
+ context.store.registerOwner(owner, [...roots]);
3283
+ const result: SharedSkill[] = [];
3284
+ const identities = new Set<string>();
3285
+ for (const [name, target] of entries.sort(([a], [b]) =>
3286
+ a.localeCompare(b),
3287
+ )) {
3288
+ if (name.slice(prefix.length).includes("/"))
3289
+ throw new HostError(
3290
+ `Skill Name "${name}" must be flat under ${meta.skillPath}.`,
3291
+ );
3292
+ const cid = await artifactValue(
3293
+ context.store,
3294
+ target.toString(),
3295
+ protect,
3296
+ );
3297
+ const bundle = await openBundle(CID.parse(cid), {
3298
+ resolveCid: (key) => context.store.block.get(key.toString()),
3299
+ });
3300
+ if (bundle.schemaKey !== skillSchema.cid.toString())
3301
+ throw new HostError(
3302
+ `Name "${name}" is not an exact Skill type Bundle.`,
3303
+ );
3304
+ const identity = await skillIdentity(bundle);
3305
+ if (identities.has(identity))
3306
+ throw new HostError(
3307
+ `Duplicate Skill installation name "${identity}" in this Swarm.`,
3308
+ );
3309
+ identities.add(identity);
3310
+ result.push({ name, cid, identity });
3311
+ }
3312
+ const missing = requested.filter(
3313
+ (reference) =>
3314
+ !result.some(
3315
+ (skill) => skill.name === reference || skill.identity === reference,
3316
+ ),
3317
+ );
3318
+ if (missing.length && !attempt && header.source === "cache") {
3319
+ header = await swarmHeader(context, configUrl, true);
3320
+ continue;
3321
+ }
3322
+ if (missing.length)
3323
+ throw new HostError(
3324
+ `Skill identities or shared Names not found under ${meta.skillPath}: ${missing.join(", ")}.`,
3325
+ );
3326
+ return result;
3327
+ }
3328
+ }
3329
+ export async function resolveTemplateSelector(
3330
+ context: SwarmContext,
3331
+ selector: string,
3332
+ configUrl: string,
3333
+ ): Promise<string> {
3334
+ formalName(selector);
3335
+ const warm = await localHeader(context, configUrl);
3336
+ if (warm && !warm.header.localSourceReady)
3337
+ await lazyPrivateSource(
3338
+ context,
3339
+ configUrl,
3340
+ warm.account,
3341
+ warm.header.config,
3342
+ );
3343
+ let header = warm?.header ?? (await swarmHeader(context, configUrl));
3344
+ if (!hasMeta(header.snapshot) && header.source === "cache")
3345
+ header = await swarmHeader(context, configUrl, true);
3346
+ for (let attempt = 0; ; attempt++) {
3347
+ const meta = await swarmMeta(context, header);
3348
+ const name = formalName(`${meta.templatePath}/${selector}`);
3349
+ const target = header.snapshot.names[name];
3350
+ if (target) return artifactValue(context.store, target.toString());
3351
+ if (attempt || header.source !== "cache")
3352
+ throw new HostError(
3353
+ `Template Name "${name}" was not found after refreshing HEAD.`,
3354
+ );
3355
+ header = await swarmHeader(context, configUrl, true);
3356
+ }
3357
+ }
3358
+ export function templateName(name: string): string {
3359
+ if (name.includes(":"))
3360
+ throw new HostError(
3361
+ "Template NAME must be a safe relative Name, not a URI.",
3362
+ );
3363
+ return formalName(name);
3364
+ }
3365
+ async function templateEntry(
3366
+ context: SwarmContext,
3367
+ configUrl: string,
3368
+ header: Pick<SwarmHeader, "snapshot">,
3369
+ selector: string,
3370
+ ) {
3371
+ const meta = await swarmMeta(context, header);
3372
+ const name = formalName(`${meta.templatePath}/${templateName(selector)}`);
3373
+ const target = header.snapshot.names[name];
3374
+ if (!target)
3375
+ throw new HostError(
3376
+ `Template Name "${name}" was not found after refreshing HEAD.`,
3377
+ );
3378
+ const targetCid = target.toString();
3379
+ return {
3380
+ swarm: configUrl,
3381
+ templatePath: meta.templatePath,
3382
+ metaCid: metaCid(header.snapshot),
3383
+ name,
3384
+ selector,
3385
+ reference: formatNameReference(configUrl, name),
3386
+ targetCid,
3387
+ ...(await inspectTemplate(
3388
+ context.store,
3389
+ await artifactValue(context.store, targetCid),
3390
+ )),
3391
+ };
3392
+ }
3393
+ export async function swarmTemplates(
3394
+ context: SwarmContext,
3395
+ configUrl: string,
3396
+ selector?: string,
3397
+ ) {
3398
+ if (selector !== undefined) templateName(selector);
3399
+ const warm = await localHeader(context, configUrl);
3400
+ if (warm && !warm.header.localSourceReady)
3401
+ await lazyPrivateSource(
3402
+ context,
3403
+ configUrl,
3404
+ warm.account,
3405
+ warm.header.config,
3406
+ );
3407
+ let header =
3408
+ warm?.header ??
3409
+ (await swarmHeader(context, configUrl, undefined, "local-first"));
3410
+ for (let attempt = 0; ; attempt++) {
3411
+ if (!hasMeta(header.snapshot) && header.source === "cache" && !attempt) {
3412
+ header = await swarmHeader(context, configUrl, true, "local-first");
3413
+ continue;
3414
+ }
3415
+ const meta = await swarmMeta(context, header);
3416
+ const name =
3417
+ selector === undefined
3418
+ ? undefined
3419
+ : formalName(`${meta.templatePath}/${selector}`);
3420
+ if (
3421
+ name &&
3422
+ !header.snapshot.names[name] &&
3423
+ header.source === "cache" &&
3424
+ !attempt
3425
+ ) {
3426
+ header = await swarmHeader(context, configUrl, true, "local-first");
3427
+ continue;
3428
+ }
3429
+ const selectors =
3430
+ selector === undefined
3431
+ ? Object.keys(header.snapshot.names)
3432
+ .filter((key) => key.startsWith(`${meta.templatePath}/`))
3433
+ .map((key) => key.slice(meta.templatePath.length + 1))
3434
+ .sort((a, b) => a.localeCompare(b))
3435
+ : [selector];
3436
+ const items = [];
3437
+ for (const item of selectors)
3438
+ items.push(await templateEntry(context, configUrl, header, item));
3439
+ return items;
3440
+ }
3441
+ }
3442
+ export async function setSwarmTemplate(
3443
+ context: SwarmContext,
3444
+ configUrl: string,
3445
+ selector: string,
3446
+ source: string,
3447
+ expect?: string,
3448
+ ) {
3449
+ templateName(selector);
3450
+ await pointer(context, configUrl);
3451
+ const content = await templatePublicationSource(source, context.store);
3452
+ const details = await inspectTemplate(context.store, content);
3453
+ let location:
3454
+ { name: string; templatePath: string; metaCid: string } | undefined;
3455
+ const targetCid = await publishContent(
3456
+ context,
3457
+ content,
3458
+ {
3459
+ swarm: configUrl,
3460
+ name: selector,
3461
+ ...(expect === undefined ? {} : { expect }),
3462
+ },
3463
+ async (current) => {
3464
+ const meta = await swarmMeta(context, { snapshot: current });
3465
+ const name = formalName(`${meta.templatePath}/${selector}`);
3466
+ location = {
3467
+ name,
3468
+ templatePath: meta.templatePath,
3469
+ metaCid: metaCid(current),
3470
+ };
3471
+ return name;
3472
+ },
3473
+ );
3474
+ return {
3475
+ swarm: configUrl,
3476
+ ...location!,
3477
+ selector,
3478
+ reference: formatNameReference(configUrl, location!.name),
3479
+ targetCid,
3480
+ ...details,
3481
+ };
3482
+ }
3483
+ export async function removeSwarmTemplate(
3484
+ context: SwarmContext,
3485
+ configUrl: string,
3486
+ selector: string,
3487
+ expect: string,
3488
+ ) {
3489
+ templateName(selector);
3490
+ const expected = exactCid(expect);
3491
+ const head = await pointer(context, configUrl);
3492
+ let basis: string | undefined;
3493
+ for (let attempt = 0; attempt < 8; attempt++) {
3494
+ const currentHead = await head.read();
3495
+ const current = await readSnapshot(context.store, currentHead.root);
3496
+ const meta = await swarmMeta(context, { snapshot: current });
3497
+ const name = formalName(`${meta.templatePath}/${selector}`);
3498
+ if (basis !== undefined && basis !== name)
3499
+ throw new HostError(
3500
+ "Template Meta path changed during removal; inspect and retry.",
3501
+ 3,
3502
+ "EDIT_CONFLICT",
3503
+ "publication",
3504
+ );
3505
+ basis = name;
3506
+ const old = current.names[name]?.toString();
3507
+ if (!old)
3508
+ throw new HostError(
3509
+ `Template Name "${name}" is missing; nothing was removed.`,
3510
+ );
3511
+ if (old !== expected)
3512
+ throw new HostError(
3513
+ `Edit conflict for ${name}; --expect must match the exact old Name target CID.`,
3514
+ 3,
3515
+ "EDIT_CONFLICT",
3516
+ "publication",
3517
+ );
3518
+ const names = { ...current.names };
3519
+ delete names[name];
3520
+ const next = await prepareNamesPublication(
3521
+ context,
3522
+ configUrl,
3523
+ currentHead.root,
3524
+ current,
3525
+ names,
3526
+ [],
3527
+ );
3528
+ try {
3529
+ await head.write(next, currentHead.cid, uniqueId());
3530
+ } catch (cause) {
3531
+ if (cause instanceof ScopeApiError && cause.status === 412) continue;
3532
+ throw new HostError(
3533
+ `Template removal unconfirmed: ${message(cause)}. Inspect HEAD before retry.`,
3534
+ 1,
3535
+ "HEAD_UNCONFIRMED",
3536
+ "publication",
3537
+ );
3538
+ }
3539
+ try {
3540
+ await swarmHeader(context, configUrl, true);
3541
+ } catch (cause) {
3542
+ throw new HostError(
3543
+ `Template removal committed, but HEAD/subscription refresh failed: ${message(cause)}. No content was deleted.`,
3544
+ 1,
3545
+ "PIN_STALE",
3546
+ "publication",
3547
+ );
3548
+ }
3549
+ return {
3550
+ swarm: configUrl,
3551
+ templatePath: meta.templatePath,
3552
+ metaCid: metaCid(current),
3553
+ selector,
3554
+ name,
3555
+ reference: formatNameReference(configUrl, name),
3556
+ targetCid: old,
3557
+ };
3558
+ }
3559
+ throw new HostError("HEAD is busy; retry the template removal.");
3560
+ }
3561
+ async function registryAssociations(
3562
+ context: SwarmContext,
3563
+ header: SwarmHeader,
3564
+ ): Promise<Association[]> {
3565
+ assertNamesRegistry(header.snapshot);
3566
+ const meta = await swarmMeta(context, header);
3567
+ const prefix = `${meta.registryPath}/`;
3568
+ const result: Association[] = [];
3569
+ for (const [name, cid] of Object.entries(header.snapshot.names)) {
3570
+ if (!name.startsWith(prefix)) continue;
3571
+ const schemaCid = name.slice(prefix.length);
3572
+ if (exactCid(schemaCid, true) !== schemaCid)
3573
+ throw new HostError(
3574
+ `Registry Name "${name}" must end in an exact canonical type CID.`,
3575
+ );
3576
+ result.push(createAssociation(schemaCid, cid.toString(), ["%"]));
3577
+ }
3578
+ return result.sort((left, right) =>
3579
+ left.schemaCid.localeCompare(right.schemaCid),
3580
+ );
3581
+ }
3582
+ export async function swarmRegistrations(
3583
+ context: SwarmContext,
3584
+ configUrl: string,
3585
+ ): Promise<Association[]> {
3586
+ let header = await swarmHeader(context, configUrl);
3587
+ if (!hasMeta(header.snapshot) && header.source === "cache")
3588
+ header = await swarmHeader(context, configUrl, true);
3589
+ return registryAssociations(context, header);
3590
+ }
3591
+ export async function swarmAssociation(
3592
+ context: SwarmContext,
3593
+ configUrl: string,
3594
+ schemaCid: string,
3595
+ mode: "active" | "local-first" = "active",
3596
+ ): Promise<Association | undefined> {
3597
+ const warm =
3598
+ mode === "local-first" ? await localHeader(context, configUrl) : undefined;
3599
+ if (warm && !warm.header.localSourceReady)
3600
+ await lazyPrivateSource(
3601
+ context,
3602
+ configUrl,
3603
+ warm.account,
3604
+ warm.header.config,
3605
+ );
3606
+ let header = warm?.header ?? (await swarmHeader(context, configUrl));
3607
+ if (!hasMeta(header.snapshot) && header.source === "cache")
3608
+ header = await swarmHeader(context, configUrl, true);
3609
+ let association = (await registryAssociations(context, header)).find(
3610
+ (item) => item.schemaCid === schemaCid,
3611
+ );
3612
+ if (!association && header.source === "cache") {
3613
+ header = await swarmHeader(context, configUrl, true);
3614
+ association = (await registryAssociations(context, header)).find(
3615
+ (item) => item.schemaCid === schemaCid,
3616
+ );
3617
+ }
3618
+ return association;
3619
+ }
3620
+ async function prepareNamesPublication(
3621
+ context: SwarmContext,
3622
+ configUrl: string,
3623
+ previousRoot: string,
3624
+ current: Snapshot,
3625
+ names: Record<string, CID>,
3626
+ roots: Iterable<string>,
3627
+ retainedRoots?: Iterable<string>,
3628
+ ) {
3629
+ const next = await publication(
3630
+ context.store,
3631
+ await writeSnapshot(context.store, { ...current, names }),
3632
+ previousRoot,
3633
+ );
3634
+ const closure = await publicationClosure(context.store, next, false);
3635
+ await provideContent(
3636
+ context.store,
3637
+ [...new Set([...closure.provided, ...roots])],
3638
+ context.node!.api,
3639
+ context.fetch,
3640
+ context.node!.auth,
3641
+ [...new Set([next, ...closure.nameTargets, ...(retainedRoots ?? roots)])],
3642
+ );
3643
+ withState(context, (state) => {
3644
+ state.invalidateSwarmHeader(configUrl);
3645
+ });
3646
+ return next;
3647
+ }
3648
+ async function editSwarmAssociation(
3649
+ context: SwarmContext,
3650
+ configUrl: string,
3651
+ schemaCid: string,
3652
+ association: Association | undefined,
3653
+ replace: boolean,
3654
+ ): Promise<void> {
3655
+ const head = await pointer(context, configUrl);
3656
+ if (association) {
3657
+ const app = await openBundle(CID.parse(association.appCid), {
3658
+ resolveCid: (cid) => context.store.block.get(cid.toString()),
3659
+ });
3660
+ if (app.schemaKey !== appSchemaCid.toString())
3661
+ throw new HostError(
3662
+ "Registry Names must directly reference an App Bundle CID, not an Artifact or another content type.",
3663
+ );
3664
+ }
3665
+ const roots = association
3666
+ ? await dependencies(context.store, association.appCid)
3667
+ : new Set<string>();
3668
+ for (let attempt = 0; attempt < 8; attempt++) {
3669
+ const currentHead = await head.read();
3670
+ const current = await readSnapshot(context.store, currentHead.root);
3671
+ assertNamesRegistry(current);
3672
+ const meta = await swarmMeta(context, { snapshot: current });
3673
+ const name = formalName(`${meta.registryPath}/${schemaCid}`);
3674
+ const oldCid = current.names[name]?.toString();
3675
+ if (association) {
3676
+ if (oldCid === association.appCid) return;
3677
+ if (oldCid && !replace)
3678
+ throw new HostError("Schema has another association; use --replace.");
3679
+ } else if (!oldCid) {
3680
+ throw new HostError(
3681
+ "No association exists for this Schema. Run ipab register list --swarm URL_OR_ALIAS.",
3682
+ );
3683
+ }
3684
+ const names = { ...current.names };
3685
+ if (association) names[name] = CID.parse(association.appCid);
3686
+ else delete names[name];
3687
+ const next = await prepareNamesPublication(
3688
+ context,
3689
+ configUrl,
3690
+ currentHead.root,
3691
+ current,
3692
+ names,
3693
+ roots,
3694
+ );
3695
+ try {
3696
+ await head.write(next, currentHead.cid, uniqueId());
3697
+ return;
3698
+ } catch (cause) {
3699
+ if (!(cause instanceof ScopeApiError) || cause.status !== 412)
3700
+ throw new HostError(
3701
+ `Registry publication unconfirmed for ${configUrl}: ${message(cause)}. Inspect the Swarm registry before retry.`,
3702
+ 1,
3703
+ "HEAD_UNCONFIRMED",
3704
+ "publication",
3705
+ );
3706
+ continue;
3707
+ }
3708
+ }
3709
+ throw new HostError(
3710
+ `HEAD is busy for ${configUrl}; retry the registry edit.`,
3711
+ );
3712
+ }
3713
+ export async function setSwarmAssociation(
3714
+ context: SwarmContext,
3715
+ configUrl: string,
3716
+ value: Association,
3717
+ replace = false,
3718
+ ): Promise<Association> {
3719
+ if (value.argv.length !== 1 || value.argv[0] !== "%")
3720
+ throw new HostError(
3721
+ 'Custom per-association argv is unsupported. Apps opened through the registry receive only the content CID (whole "%" argument); adapt the App or use ipab exec APP_CID ARGS.',
3722
+ );
3723
+ const association = createAssociation(
3724
+ value.schemaCid,
3725
+ value.appCid,
3726
+ value.argv,
3727
+ );
3728
+ await editSwarmAssociation(
3729
+ context,
3730
+ configUrl,
3731
+ association.schemaCid,
3732
+ association,
3733
+ replace,
3734
+ );
3735
+ return association;
3736
+ }
3737
+ export async function removeSwarmAssociation(
3738
+ context: SwarmContext,
3739
+ configUrl: string,
3740
+ schemaCid: string,
3741
+ ): Promise<string> {
3742
+ const schema = exactCid(schemaCid, true);
3743
+ await editSwarmAssociation(context, configUrl, schema, undefined, false);
3744
+ return schema;
3745
+ }
2088
3746
  async function dependencies(
2089
3747
  store: IpfsStore,
2090
3748
  root: string,
@@ -2116,6 +3774,10 @@ async function dependencies(
2116
3774
  throw new HostError("Invalid App source association.");
2117
3775
  await dependencies(store, source.cid, found);
2118
3776
  }
3777
+ } else if (isSwarmStateSchema(bundle.schemaKey)) {
3778
+ const snapshot = await readState(store, CID.parse(root));
3779
+ for (const target of Object.values(snapshot.names))
3780
+ await dependencies(store, target.toString(), found);
2119
3781
  }
2120
3782
  return found;
2121
3783
  }
@@ -2123,8 +3785,16 @@ export async function frozenPublicationClosure(
2123
3785
  store: IpfsStore,
2124
3786
  root: string,
2125
3787
  ): Promise<string[]> {
3788
+ return (await publicationClosure(store, root)).provided;
3789
+ }
3790
+ async function publicationClosure(
3791
+ store: IpfsStore,
3792
+ root: string,
3793
+ includeDependencies = true,
3794
+ ) {
2126
3795
  const publications = new Set<string>(),
2127
- content = new Set<string>();
3796
+ content = new Set<string>(),
3797
+ nameTargets = new Set<string>();
2128
3798
  let current: string | undefined = root;
2129
3799
  while (current !== undefined) {
2130
3800
  if (publications.has(current) || publications.size >= 256)
@@ -2133,29 +3803,50 @@ export async function frozenPublicationClosure(
2133
3803
  );
2134
3804
  publications.add(current);
2135
3805
  const publication = await readPublication(store, current);
2136
- const snapshot = decodeSnapshot(
2137
- await store.block.get(publication.state.toString()),
2138
- );
2139
- for (const target of Object.values(snapshot.names))
2140
- await dependencies(store, target.toString(), content);
3806
+ const snapshot = await readState(store, publication.state);
3807
+ for (const target of Object.values(snapshot.names)) {
3808
+ nameTargets.add(target.toString());
3809
+ if (includeDependencies)
3810
+ await dependencies(store, target.toString(), content);
3811
+ else content.add(target.toString());
3812
+ }
3813
+ if (includeDependencies)
3814
+ for (const association of Object.values(snapshot.registrations ?? {}))
3815
+ await dependencies(store, association.appCid.toString(), content);
2141
3816
  current = publication.previous?.toString();
2142
3817
  }
2143
- return [
2144
- root,
2145
- ...[...new Set([...publications, ...content])]
2146
- .filter((cid) => cid !== root)
2147
- .sort(),
2148
- ];
3818
+ return {
3819
+ nameTargets,
3820
+ provided: [
3821
+ root,
3822
+ ...[...new Set([...publications, ...content])]
3823
+ .filter((cid) => cid !== root)
3824
+ .sort(),
3825
+ ],
3826
+ };
2149
3827
  }
2150
3828
  export async function publish(
2151
3829
  context: SwarmContext,
2152
3830
  content: string,
2153
3831
  options: {
2154
3832
  swarm?: string;
2155
- name?: string;
3833
+ name: string;
3834
+ expect?: string;
3835
+ snapshot?: boolean;
3836
+ },
3837
+ ): Promise<string> {
3838
+ return publishContent(context, content, options);
3839
+ }
3840
+ async function publishContent(
3841
+ context: SwarmContext,
3842
+ content: string,
3843
+ options: {
3844
+ swarm?: string;
3845
+ name: string;
2156
3846
  expect?: string;
2157
3847
  snapshot?: boolean;
2158
3848
  },
3849
+ nameForSnapshot?: (current: Snapshot) => Promise<string>,
2159
3850
  ): Promise<string> {
2160
3851
  if (!options.swarm)
2161
3852
  throw new HostError(
@@ -2163,34 +3854,32 @@ export async function publish(
2163
3854
  );
2164
3855
  const head = await pointer(context, options.swarm);
2165
3856
  const roots = await dependencies(context.store, content);
2166
- if (!options.name) {
2167
- if (options.expect || options.snapshot)
2168
- throw new HostError("--expect/--snapshot require --name.");
2169
- await head.read();
2170
- await provideContent(
2171
- context.store,
2172
- [...roots],
2173
- context.node!.api,
2174
- context.fetch,
2175
- context.node!.auth,
2176
- );
2177
- return content;
2178
- }
2179
- const name = formalName(options.name);
3857
+ const currentRoots = [...(await currentDependencies(context.store, content))];
3858
+ await withStateAsync(context, (state) =>
3859
+ pinCid(state, content, context.store, currentRoots),
3860
+ );
3861
+ let name = formalName(options.name);
3862
+ let resolvedName: string | undefined;
2180
3863
  if (options.snapshot && options.expect)
2181
3864
  throw new HostError("Snapshots cannot replace an occupied Name.");
2182
3865
  const expected = options.expect
2183
3866
  ? CID.parse(options.expect).toV1().toString()
2184
3867
  : undefined;
2185
- if (expected)
2186
- parseArtifact(await typedJson(context.store, expected, artifactType));
2187
- const candidate = options.snapshot
2188
- ? content
2189
- : await jsonBundle(context.store, artifactType, {
2190
- value: content,
2191
- ...(expected ? { previous: expected } : {}),
2192
- timestamp: new Date().toISOString(),
2193
- });
3868
+ const contentBundle = await openBundle(CID.parse(content), {
3869
+ resolveCid: (cid) => context.store.block.get(cid.toString()),
3870
+ });
3871
+ const direct =
3872
+ contentBundle.schemaKey === appSchemaCid.toString() ||
3873
+ contentBundle.schemaKey === swarmMetaSchema.cid.toString() ||
3874
+ contentBundle.schemaKey === legacySwarmMetaSchema.cid.toString();
3875
+ const candidate =
3876
+ options.snapshot || direct
3877
+ ? content
3878
+ : await jsonBundle(context.store, artifactType, {
3879
+ value: content,
3880
+ ...(expected ? { previous: expected } : {}),
3881
+ timestamp: new Date().toISOString(),
3882
+ });
2194
3883
  roots.add(candidate);
2195
3884
  if (expected)
2196
3885
  for (const root of await dependencies(context.store, expected))
@@ -2198,38 +3887,39 @@ export async function publish(
2198
3887
  for (let attempt = 0; attempt < 8; attempt++) {
2199
3888
  const currentHead = await head.read(),
2200
3889
  current = await readSnapshot(context.store, currentHead.root);
3890
+ if (nameForSnapshot) {
3891
+ name = await nameForSnapshot(current);
3892
+ if (resolvedName !== undefined && resolvedName !== name)
3893
+ throw new HostError(
3894
+ "Template Meta path changed during publication; inspect and retry. Content remains pinned.",
3895
+ 3,
3896
+ "EDIT_CONFLICT",
3897
+ "publication",
3898
+ );
3899
+ resolvedName = name;
3900
+ }
2201
3901
  if (
2202
3902
  (Object.hasOwn(current.names, name)
2203
3903
  ? current.names[name]?.toString()
2204
3904
  : undefined) !== expected
2205
3905
  )
2206
3906
  throw new HostError(
2207
- `Edit conflict for ${name}; candidate ${candidate} remains retained. Choose an explicit baseline.`,
3907
+ `Edit conflict for ${name}; content ${content} remains pinned. Occupied Names require --expect EXACT_OLD_CID (the old Artifact CID when applicable); inspect the current Name before retrying.`,
2208
3908
  3,
2209
3909
  "EDIT_CONFLICT",
2210
3910
  "publication",
2211
3911
  );
2212
- const next = await publication(
2213
- context.store,
2214
- await writeSnapshot(context.store, {
2215
- ...current,
2216
- names: { ...current.names, [name]: CID.parse(candidate) },
2217
- }),
3912
+ const next = await prepareNamesPublication(
3913
+ context,
3914
+ options.swarm,
2218
3915
  currentHead.root,
3916
+ current,
3917
+ { ...current.names, [name]: CID.parse(candidate) },
3918
+ roots,
3919
+ expected ? await dependencies(context.store, expected) : [],
2219
3920
  );
2220
- await provideContent(
2221
- context.store,
2222
- [next, ...roots],
2223
- context.node!.api,
2224
- context.fetch,
2225
- context.node!.auth,
2226
- );
2227
- withState(context, (state) => {
2228
- state.invalidateSwarmHeader(options.swarm!);
2229
- });
2230
3921
  try {
2231
3922
  await head.write(next, currentHead.cid, uniqueId());
2232
- return candidate;
2233
3923
  } catch (cause) {
2234
3924
  if (!(cause instanceof ScopeApiError) || cause.status !== 412)
2235
3925
  throw new HostError(
@@ -2238,7 +3928,19 @@ export async function publish(
2238
3928
  "HEAD_UNCONFIRMED",
2239
3929
  "publication",
2240
3930
  );
3931
+ continue;
3932
+ }
3933
+ try {
3934
+ await swarmHeader(context, options.swarm, true);
3935
+ } catch (cause) {
3936
+ throw new HostError(
3937
+ `Publication committed as ${candidate}, but its HEAD/subscription refresh failed: ${message(cause)}. Published content remains pinned; inspect HEAD and retry the affected Name pin.`,
3938
+ 1,
3939
+ "PIN_STALE",
3940
+ "publication",
3941
+ );
2241
3942
  }
3943
+ return candidate;
2242
3944
  }
2243
3945
  throw new HostError(`HEAD is busy; candidate ${candidate} remains retained.`);
2244
3946
  }