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

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 (116) hide show
  1. package/README.md +43 -6
  2. package/dist/app-authoring.d.ts +10 -0
  3. package/dist/app-authoring.d.ts.map +1 -1
  4. package/dist/app-authoring.js +138 -13
  5. package/dist/app-authoring.js.map +1 -1
  6. package/dist/app-definition.d.ts +52 -57
  7. package/dist/app-definition.d.ts.map +1 -1
  8. package/dist/app-definition.js +33 -38
  9. package/dist/app-definition.js.map +1 -1
  10. package/dist/app-templates.d.ts.map +1 -1
  11. package/dist/app-templates.js +2 -1
  12. package/dist/app-templates.js.map +1 -1
  13. package/dist/assembly.d.ts +7 -0
  14. package/dist/assembly.d.ts.map +1 -0
  15. package/dist/assembly.js +130 -0
  16. package/dist/assembly.js.map +1 -0
  17. package/dist/authoring.d.ts +4 -8
  18. package/dist/authoring.d.ts.map +1 -1
  19. package/dist/authoring.js +25 -15
  20. package/dist/authoring.js.map +1 -1
  21. package/dist/builtins/skill.ipab.car +0 -0
  22. package/dist/builtins/template.node.car +0 -0
  23. package/dist/builtins/template.web-app.car +0 -0
  24. package/dist/builtins.d.ts.map +1 -1
  25. package/dist/builtins.js +18 -2
  26. package/dist/builtins.js.map +1 -1
  27. package/dist/cli.d.ts +1 -0
  28. package/dist/cli.d.ts.map +1 -1
  29. package/dist/cli.js +720 -76
  30. package/dist/cli.js.map +1 -1
  31. package/dist/config-secret.d.ts +3 -0
  32. package/dist/config-secret.d.ts.map +1 -0
  33. package/dist/config-secret.js +83 -0
  34. package/dist/config-secret.js.map +1 -0
  35. package/dist/config.d.ts +6 -2
  36. package/dist/config.d.ts.map +1 -1
  37. package/dist/config.js +109 -7
  38. package/dist/config.js.map +1 -1
  39. package/dist/content-provider.d.ts +9 -0
  40. package/dist/content-provider.d.ts.map +1 -0
  41. package/dist/content-provider.js +93 -0
  42. package/dist/content-provider.js.map +1 -0
  43. package/dist/get.d.ts +3 -0
  44. package/dist/get.d.ts.map +1 -0
  45. package/dist/get.js +80 -0
  46. package/dist/get.js.map +1 -0
  47. package/dist/identity.d.ts +9 -0
  48. package/dist/identity.d.ts.map +1 -0
  49. package/dist/identity.js +89 -0
  50. package/dist/identity.js.map +1 -0
  51. package/dist/kubo.d.ts +38 -0
  52. package/dist/kubo.d.ts.map +1 -0
  53. package/dist/kubo.js +528 -0
  54. package/dist/kubo.js.map +1 -0
  55. package/dist/pins.d.ts +3 -3
  56. package/dist/pins.js +1 -1
  57. package/dist/pins.js.map +1 -1
  58. package/dist/setup.d.ts +7 -0
  59. package/dist/setup.d.ts.map +1 -0
  60. package/dist/setup.js +22 -0
  61. package/dist/setup.js.map +1 -0
  62. package/dist/source-bundle.d.ts +3 -8
  63. package/dist/source-bundle.d.ts.map +1 -1
  64. package/dist/source-bundle.js +17 -12
  65. package/dist/source-bundle.js.map +1 -1
  66. package/dist/space.d.ts.map +1 -1
  67. package/dist/space.js +2 -2
  68. package/dist/space.js.map +1 -1
  69. package/dist/state.d.ts +19 -4
  70. package/dist/state.d.ts.map +1 -1
  71. package/dist/state.js +105 -7
  72. package/dist/state.js.map +1 -1
  73. package/dist/swarm-envelope.d.ts +36 -0
  74. package/dist/swarm-envelope.d.ts.map +1 -0
  75. package/dist/swarm-envelope.js +145 -0
  76. package/dist/swarm-envelope.js.map +1 -0
  77. package/dist/swarm-files.d.ts +5 -0
  78. package/dist/swarm-files.d.ts.map +1 -0
  79. package/dist/swarm-files.js +94 -0
  80. package/dist/swarm-files.js.map +1 -0
  81. package/dist/swarm.d.ts +173 -0
  82. package/dist/swarm.d.ts.map +1 -0
  83. package/dist/swarm.js +1245 -0
  84. package/dist/swarm.js.map +1 -0
  85. package/dist/template-definition.d.ts +47 -52
  86. package/dist/template-definition.d.ts.map +1 -1
  87. package/dist/template-definition.js +36 -41
  88. package/dist/template-definition.js.map +1 -1
  89. package/dist/template-source.d.ts +2 -0
  90. package/dist/template-source.d.ts.map +1 -1
  91. package/dist/template-source.js +4 -3
  92. package/dist/template-source.js.map +1 -1
  93. package/package.json +10 -5
  94. package/src/app-authoring.ts +210 -21
  95. package/src/app-definition.ts +33 -39
  96. package/src/app-templates.ts +9 -1
  97. package/src/assembly.ts +185 -0
  98. package/src/authoring.ts +41 -17
  99. package/src/builtins.ts +23 -2
  100. package/src/cli.ts +875 -79
  101. package/src/config-secret.ts +96 -0
  102. package/src/config.ts +146 -7
  103. package/src/content-provider.ts +124 -0
  104. package/src/get.ts +90 -0
  105. package/src/identity.ts +133 -0
  106. package/src/kubo.ts +691 -0
  107. package/src/pins.ts +1 -1
  108. package/src/setup.ts +21 -0
  109. package/src/source-bundle.ts +26 -13
  110. package/src/space.ts +2 -5
  111. package/src/state.ts +121 -9
  112. package/src/swarm-envelope.ts +255 -0
  113. package/src/swarm-files.ts +100 -0
  114. package/src/swarm.ts +2025 -0
  115. package/src/template-definition.ts +36 -41
  116. package/src/template-source.ts +10 -3
package/src/swarm.ts ADDED
@@ -0,0 +1,2025 @@
1
+ import { lstat, open, readFile } from "node:fs/promises";
2
+ import { createHash, randomBytes } from "node:crypto";
3
+ import { stringify } from "yaml";
4
+ import { CarBlockIterator } from "@ipld/car/iterator";
5
+ import * as dagCbor from "@ipld/dag-cbor";
6
+ import { CID } from "multiformats/cid";
7
+ import { sha256 } from "multiformats/hashes/sha2";
8
+ import { encodeSchema, openBundle, type BundleType } from "@ipab/bundle";
9
+ import {
10
+ encodeBundleCar,
11
+ memoryTree,
12
+ streamChunks,
13
+ } from "@ipab/bundle-builder";
14
+ import type { IpfsStore } from "@ipab/ipfs-store";
15
+ import {
16
+ ScopeClient,
17
+ ScopeApiError,
18
+ issueScopeCertificate,
19
+ uniqueId,
20
+ verifyScopeCertificate,
21
+ valueCid,
22
+ type Variable,
23
+ } from "@ipab/bundle/pointer/scope";
24
+ import {
25
+ canonicalService,
26
+ isCanonicalPublicKey,
27
+ POINTER_ID_PATTERN,
28
+ } from "@ipab/bundle/pointer/protocol";
29
+ import {
30
+ importPrivateKeyPkcs8,
31
+ importPublicKeyRaw,
32
+ keyId,
33
+ signEd25519,
34
+ verifyEd25519,
35
+ } from "@ipab/bundle/pointer/crypto";
36
+ import { HostError, object, message } from "./errors.js";
37
+ import { accountIdentity, type Identity } from "./identity.js";
38
+ import { bundleJson, provideContent } from "./content-provider.js";
39
+ import { bytes, relativePath } from "./space.js";
40
+ import { appSchemaCid } from "./app-definition.js";
41
+ import { State } from "./state.js";
42
+ import {
43
+ privateDirectory,
44
+ readPrivate,
45
+ withPrivateLock,
46
+ writePrivate,
47
+ } from "./swarm-files.js";
48
+ import {
49
+ encryptionIdentity,
50
+ openApproval,
51
+ sealApproval,
52
+ type EncryptionIdentity,
53
+ type Envelope,
54
+ type EnvelopeBinding,
55
+ type MembershipSecret,
56
+ parseEnvelope,
57
+ } from "./swarm-envelope.js";
58
+ import {
59
+ kuboSource,
60
+ peerId,
61
+ peerProof,
62
+ prepareNode,
63
+ startNode,
64
+ validateAddress,
65
+ type KuboNode,
66
+ } from "./kubo.js";
67
+
68
+ export interface Member {
69
+ publicKey: string;
70
+ encryptionKey: string;
71
+ peerId: string;
72
+ profileId: string;
73
+ requestId: string;
74
+ approval: Envelope | null;
75
+ }
76
+ export interface Organization {
77
+ v: 1;
78
+ scopeId: string;
79
+ owner: string;
80
+ name: string;
81
+ description: string;
82
+ headId: string;
83
+ epoch: number;
84
+ bootstrap: string[];
85
+ members: Member[];
86
+ }
87
+ export interface Profile {
88
+ name: string;
89
+ addresses: string[];
90
+ updatedAt: string;
91
+ }
92
+ export interface Snapshot {
93
+ v: 2;
94
+ names: Record<string, CID>;
95
+ }
96
+ export interface MembershipRequest {
97
+ v: 1;
98
+ id: string;
99
+ requestedAt: string;
100
+ configUrl: string;
101
+ scopeId: string;
102
+ owner: string;
103
+ name: string;
104
+ member: string;
105
+ encryptionKey: string;
106
+ peerId: string;
107
+ peerPublicKey: string;
108
+ peerSignature: string;
109
+ signature: string;
110
+ }
111
+ export interface SwarmContext {
112
+ store: IpfsStore;
113
+ env: NodeJS.ProcessEnv;
114
+ stateDir: string;
115
+ fetch?: typeof fetch;
116
+ pointerService?: string;
117
+ pointerApiKey?: string;
118
+ state?: State;
119
+ cacheTtl?: number;
120
+ forceRefresh?: boolean;
121
+ diagnostic?: (text: string) => void;
122
+ node?: KuboNode;
123
+ identity?: Identity;
124
+ }
125
+ async function contextIdentity(
126
+ context: SwarmContext,
127
+ initialize = false,
128
+ ): Promise<Identity> {
129
+ context.identity ??= await accountIdentity(context.env, initialize);
130
+ return context.identity;
131
+ }
132
+ interface LocalMembership {
133
+ configUrl: string;
134
+ owner: string;
135
+ account: string;
136
+ encryption: EncryptionIdentity;
137
+ request?: MembershipRequest;
138
+ config?: Organization;
139
+ secret?: MembershipSecret;
140
+ }
141
+ const cidField = { type: "string", minLength: 1, maxLength: 128 } as const;
142
+ export const artifactType: BundleType = {
143
+ contentType: "application/json",
144
+ schema: {
145
+ type: "object",
146
+ additionalProperties: false,
147
+ required: ["value", "timestamp"],
148
+ properties: {
149
+ value: cidField,
150
+ previous: cidField,
151
+ timestamp: { type: "string", format: "date-time" },
152
+ },
153
+ },
154
+ };
155
+ export interface Artifact {
156
+ value: string;
157
+ previous?: string;
158
+ timestamp: string;
159
+ }
160
+ function withState<T>(
161
+ context: SwarmContext,
162
+ operation: (state: State) => T,
163
+ ): T {
164
+ if (context.state) return operation(context.state);
165
+ const state = new State(context.stateDir);
166
+ try {
167
+ return operation(state);
168
+ } finally {
169
+ state.close();
170
+ }
171
+ }
172
+ export function canonicalSwarmUrl(value: string): string {
173
+ if (!/^https?:\/\//.test(value))
174
+ throw new HostError(
175
+ "Swarm requires a configuration URL; old Swarm CID protocol is unsupported.",
176
+ );
177
+ const url = new URL(value);
178
+ canonicalService(url.origin);
179
+ if (
180
+ url.search ||
181
+ url.hash ||
182
+ url.username ||
183
+ url.password ||
184
+ url.toString() !== value ||
185
+ !/^\/v1\/[A-Za-z0-9_-]{43}\/[A-Za-z0-9_-]{43}$/.test(url.pathname)
186
+ )
187
+ throw new HostError(
188
+ "Swarm must be an exact Scope configuration URL; old Swarm CID protocol is unsupported.",
189
+ );
190
+ return value;
191
+ }
192
+ function coordinates(configUrl: string): {
193
+ service: string;
194
+ scopeId: string;
195
+ configId: string;
196
+ } {
197
+ const url = new URL(canonicalSwarmUrl(configUrl));
198
+ const [, , scopeId, configId] = url.pathname.split("/");
199
+ return { service: url.origin, scopeId: scopeId!, configId: configId! };
200
+ }
201
+ const localName = (url: string) =>
202
+ `${createHash("sha256").update(url).digest("hex")}.json`;
203
+ const nodeScope = (service: string, scopeId: string) =>
204
+ createHash("sha256").update(`${service}/v1/${scopeId}`).digest("hex");
205
+ async function directory(context: SwarmContext): Promise<string> {
206
+ return privateDirectory(context.stateDir, "swarm-credentials");
207
+ }
208
+ async function local(
209
+ context: SwarmContext,
210
+ configUrl: string,
211
+ ): Promise<LocalMembership> {
212
+ const value = await readPrivate<LocalMembership>(
213
+ await directory(context),
214
+ localName(configUrl),
215
+ );
216
+ const identity = await contextIdentity(context);
217
+ if (
218
+ !value ||
219
+ value.configUrl !== configUrl ||
220
+ value.account !== identity.publicKey
221
+ )
222
+ throw new HostError(
223
+ "No local Request for this configuration and HOME identity. Run swarm request with a trusted Owner fingerprint.",
224
+ );
225
+ return value;
226
+ }
227
+ async function saveLocal(
228
+ context: SwarmContext,
229
+ membership: LocalMembership,
230
+ ): Promise<void> {
231
+ await writePrivate(
232
+ await directory(context),
233
+ localName(membership.configUrl),
234
+ membership,
235
+ );
236
+ }
237
+ function client(
238
+ context: SwarmContext,
239
+ service: string,
240
+ identity?: Identity,
241
+ secret?: MembershipSecret,
242
+ ): ScopeClient {
243
+ return new ScopeClient({
244
+ service,
245
+ ...(identity
246
+ ? {
247
+ signer: {
248
+ ...identity,
249
+ ...(secret ? { certificate: secret.certificate } : {}),
250
+ },
251
+ }
252
+ : {}),
253
+ ...(context.fetch ? { fetch: context.fetch } : {}),
254
+ ...(context.pointerApiKey ? { apiKey: context.pointerApiKey } : {}),
255
+ });
256
+ }
257
+ function parseOrganization(value: unknown, configUrl: string): Organization {
258
+ const data = object(value, "organization configuration");
259
+ const { scopeId } = coordinates(configUrl);
260
+ if (
261
+ Object.keys(data).sort().join() !==
262
+ "bootstrap,description,epoch,headId,members,name,owner,scopeId,v" ||
263
+ data.v !== 1 ||
264
+ data.scopeId !== scopeId ||
265
+ !isCanonicalPublicKey(data.owner) ||
266
+ typeof data.name !== "string" ||
267
+ data.name.length > 256 ||
268
+ typeof data.description !== "string" ||
269
+ data.description.length > 2048 ||
270
+ typeof data.headId !== "string" ||
271
+ !POINTER_ID_PATTERN.test(data.headId) ||
272
+ typeof data.epoch !== "number" ||
273
+ !Number.isSafeInteger(data.epoch) ||
274
+ data.epoch < 1 ||
275
+ !Array.isArray(data.bootstrap) ||
276
+ data.bootstrap.length > 64 ||
277
+ !Array.isArray(data.members) ||
278
+ data.members.length < 1 ||
279
+ data.members.length > 16
280
+ )
281
+ throw new HostError("Invalid Scope organization configuration.");
282
+ const identities = new Set<string>(),
283
+ peers = new Set<string>(),
284
+ profiles = new Set<string>();
285
+ const members: Member[] = [];
286
+ for (const raw of data.members) {
287
+ const member = object(raw, "member");
288
+ if (
289
+ Object.keys(member).sort().join() !==
290
+ "approval,encryptionKey,peerId,profileId,publicKey,requestId" ||
291
+ !isCanonicalPublicKey(member.publicKey) ||
292
+ typeof member.encryptionKey !== "string" ||
293
+ member.encryptionKey.length > 256 ||
294
+ typeof member.peerId !== "string" ||
295
+ typeof member.profileId !== "string" ||
296
+ !POINTER_ID_PATTERN.test(member.profileId) ||
297
+ typeof member.requestId !== "string" ||
298
+ !POINTER_ID_PATTERN.test(member.requestId) ||
299
+ identities.has(member.publicKey) ||
300
+ peers.has(member.peerId) ||
301
+ profiles.has(member.profileId)
302
+ )
303
+ throw new HostError(
304
+ "Invalid or duplicate member/PeerID/profile binding.",
305
+ );
306
+ identities.add(member.publicKey);
307
+ peers.add(member.peerId);
308
+ profiles.add(member.profileId);
309
+ members.push({
310
+ publicKey: member.publicKey,
311
+ encryptionKey: member.encryptionKey,
312
+ peerId: member.peerId,
313
+ profileId: member.profileId,
314
+ requestId: member.requestId,
315
+ approval:
316
+ member.approval === null ? null : parseEnvelope(member.approval),
317
+ });
318
+ }
319
+ if (!identities.has(data.owner))
320
+ throw new HostError("Owner must remain an organization member.");
321
+ const bootstrap: string[] = [];
322
+ for (const address of data.bootstrap) {
323
+ if (typeof address !== "string")
324
+ throw new HostError("Invalid bootstrap address.");
325
+ validateAddress(address);
326
+ if (![...peers].some((peer) => address.endsWith(`/p2p/${peer}`)))
327
+ throw new HostError("Bootstrap address is not a member PeerID.");
328
+ bootstrap.push(address);
329
+ }
330
+ return {
331
+ v: 1,
332
+ scopeId,
333
+ owner: data.owner,
334
+ name: data.name,
335
+ description: data.description,
336
+ headId: data.headId,
337
+ epoch: data.epoch,
338
+ bootstrap,
339
+ members,
340
+ };
341
+ }
342
+ function parseProfile(value: unknown, expectedPeer: string): Profile {
343
+ const data = object(value, "member profile");
344
+ if (
345
+ Object.keys(data).sort().join() !== "addresses,name,updatedAt" ||
346
+ typeof data.name !== "string" ||
347
+ data.name.length > 256 ||
348
+ typeof data.updatedAt !== "string" ||
349
+ !Number.isFinite(Date.parse(data.updatedAt)) ||
350
+ !Array.isArray(data.addresses) ||
351
+ data.addresses.length > 16
352
+ )
353
+ throw new HostError("Invalid public member profile.");
354
+ const addresses: string[] = [];
355
+ for (const address of data.addresses) {
356
+ if (typeof address !== "string")
357
+ throw new HostError("Invalid member address.");
358
+ validateAddress(address, expectedPeer);
359
+ addresses.push(address);
360
+ }
361
+ return { name: data.name, addresses, updatedAt: data.updatedAt };
362
+ }
363
+ async function fetchConfig(
364
+ context: SwarmContext,
365
+ configUrl: string,
366
+ ): Promise<{ config: Organization; variable: Variable }> {
367
+ const c = coordinates(configUrl),
368
+ api = client(context, c.service);
369
+ const [variable, scope] = await Promise.all([
370
+ api.read(c.scopeId, c.configId),
371
+ api.send<{ owner: string }>("GET", c.scopeId),
372
+ ]);
373
+ const config = parseOrganization(variable.value, configUrl);
374
+ if (scope.owner !== config.owner)
375
+ throw new HostError(
376
+ "Organization Owner does not match the immutable Scope trust root.",
377
+ );
378
+ return { config, variable };
379
+ }
380
+ function binding(
381
+ configUrl: string,
382
+ config: Organization,
383
+ member: Member,
384
+ ): EnvelopeBinding {
385
+ return {
386
+ configUrl,
387
+ scopeId: config.scopeId,
388
+ owner: config.owner,
389
+ member: member.publicKey,
390
+ requestId: member.requestId,
391
+ peerId: member.peerId,
392
+ profileId: member.profileId,
393
+ headId: config.headId,
394
+ epoch: config.epoch,
395
+ encryptionKey: member.encryptionKey,
396
+ };
397
+ }
398
+ async function validateMembershipSecret(
399
+ record: LocalMembership,
400
+ config: Organization,
401
+ member: Member,
402
+ ): Promise<void> {
403
+ const secret = record.secret;
404
+ if (
405
+ !secret ||
406
+ typeof secret.swarmKey !== "string" ||
407
+ !/^[a-f0-9]{64}$/.test(secret.swarmKey)
408
+ )
409
+ throw new HostError(
410
+ "Invalid approved Swarm key; preserve the original Request.",
411
+ );
412
+ if (record.account !== config.owner) {
413
+ const c = coordinates(record.configUrl);
414
+ await verifyScopeCertificate(
415
+ secret.certificate,
416
+ config.owner,
417
+ c.service,
418
+ c.scopeId,
419
+ config.headId,
420
+ record.account,
421
+ );
422
+ await verifyScopeCertificate(
423
+ secret.certificate,
424
+ config.owner,
425
+ c.service,
426
+ c.scopeId,
427
+ member.profileId,
428
+ record.account,
429
+ );
430
+ if (secret.certificate.body.write.length !== 2)
431
+ throw new HostError(
432
+ "Membership package must grant exactly HEAD and this member's profile.",
433
+ );
434
+ }
435
+ }
436
+ async function activate(
437
+ context: SwarmContext,
438
+ record: LocalMembership,
439
+ ): Promise<void> {
440
+ const config = record.config!,
441
+ secret = record.secret!;
442
+ const identity = await contextIdentity(context);
443
+ const self = config.members.find(
444
+ (member) => member.publicKey === identity.publicKey,
445
+ );
446
+ if (!self)
447
+ throw new HostError(
448
+ "This identity was removed. Make a new Request only after Owner confirmation.",
449
+ );
450
+ const c = coordinates(record.configUrl);
451
+ if (identity.publicKey !== config.owner) {
452
+ await verifyScopeCertificate(
453
+ secret.certificate,
454
+ config.owner,
455
+ c.service,
456
+ c.scopeId,
457
+ config.headId,
458
+ identity.publicKey,
459
+ );
460
+ await verifyScopeCertificate(
461
+ secret.certificate,
462
+ config.owner,
463
+ c.service,
464
+ c.scopeId,
465
+ self.profileId,
466
+ identity.publicKey,
467
+ );
468
+ }
469
+ const addresses = [...config.bootstrap];
470
+ const api = client(context, c.service);
471
+ let selfProfile: { profile: Profile; cid: string } | undefined;
472
+ for (const member of config.members) {
473
+ const profile = await api.read(c.scopeId, member.profileId);
474
+ const value = parseProfile(profile.value, member.peerId);
475
+ if (member.publicKey === identity.publicKey)
476
+ selfProfile = { profile: value, cid: profile.cid };
477
+ addresses.push(...value.addresses);
478
+ }
479
+ const node = await startNode(
480
+ context.stateDir,
481
+ nodeScope(c.service, config.scopeId),
482
+ secret.swarmKey,
483
+ config.epoch,
484
+ [...new Set(addresses)],
485
+ context.diagnostic,
486
+ );
487
+ if (node.peerId !== self.peerId)
488
+ throw new HostError(
489
+ "Approved PeerID differs from this local Request's Kubo identity.",
490
+ );
491
+ if (context.node?.api !== node.api) {
492
+ const store = context.store.withLocalSource(kuboSource(node));
493
+ await context.store.close();
494
+ context.store = store;
495
+ }
496
+ context.node = node;
497
+ if (selfProfile && selfProfile.profile.addresses.length === 0) {
498
+ const writer = client(
499
+ context,
500
+ c.service,
501
+ identity,
502
+ identity.publicKey === config.owner ? undefined : secret,
503
+ );
504
+ const profile = {
505
+ ...selfProfile.profile,
506
+ addresses: node.addresses,
507
+ updatedAt: new Date().toISOString(),
508
+ };
509
+ await writer.write(
510
+ c.scopeId,
511
+ self.profileId,
512
+ profile,
513
+ selfProfile.cid,
514
+ uniqueId(),
515
+ );
516
+ }
517
+ }
518
+ async function refresh(
519
+ context: SwarmContext,
520
+ configUrl: string,
521
+ ): Promise<LocalMembership> {
522
+ const record = await local(context, configUrl);
523
+ if (record.account === record.owner) {
524
+ const transition = await readPrivate<Removal>(
525
+ await directory(context),
526
+ `transition-${localName(configUrl)}`,
527
+ );
528
+ if (transition && !transition.completed)
529
+ throw new HostError(
530
+ "Organization switch incomplete; only Owner can continue with swarm resume.",
531
+ );
532
+ }
533
+ const { config } = await fetchConfig(context, configUrl);
534
+ if (config.owner !== record.owner)
535
+ throw new HostError("Pinned Owner changed; refusing configuration.");
536
+ if (record.config && config.epoch < record.config.epoch)
537
+ throw new HostError("Organization epoch rollback.");
538
+ const member = config.members.find(
539
+ (member) => member.publicKey === record.account,
540
+ );
541
+ if (!member)
542
+ throw new HostError(
543
+ "No approved package yet, or membership removed; ask the Owner.",
544
+ );
545
+ if (record.account !== config.owner) {
546
+ if (
547
+ !record.request ||
548
+ member.requestId !== record.request.id ||
549
+ member.peerId !== record.request.peerId ||
550
+ !member.approval
551
+ )
552
+ throw new HostError(
553
+ "Published package does not match the locally saved Request.",
554
+ );
555
+ record.secret = await openApproval(
556
+ member.approval,
557
+ binding(configUrl, config, member),
558
+ record.encryption,
559
+ );
560
+ }
561
+ if (!record.secret)
562
+ throw new HostError(
563
+ "Owner key/Swarm key lost: no system recovery is available.",
564
+ );
565
+ record.config = config;
566
+ await validateMembershipSecret(record, config, member);
567
+ await saveLocal(context, record);
568
+ await activate(context, record);
569
+ return record;
570
+ }
571
+ async function readyMembership(
572
+ context: SwarmContext,
573
+ configUrl: string,
574
+ ): Promise<LocalMembership> {
575
+ const record = await local(context, configUrl);
576
+ if (record.account === record.owner) {
577
+ const transition = await readPrivate<Removal>(
578
+ await directory(context),
579
+ `transition-${localName(configUrl)}`,
580
+ );
581
+ if (transition && !transition.completed)
582
+ throw new HostError(
583
+ "Organization switch incomplete; run swarm resume before normal Owner operations.",
584
+ );
585
+ }
586
+ if (!record.config || !record.secret) return refresh(context, configUrl);
587
+ if (
588
+ !context.node ||
589
+ context.node.peerId !==
590
+ record.config.members.find((m) => m.publicKey === record.account)?.peerId
591
+ ) {
592
+ try {
593
+ await activate(context, record);
594
+ } catch (cause) {
595
+ if (
596
+ cause instanceof ScopeApiError &&
597
+ [403, 404, 410].includes(cause.status)
598
+ )
599
+ return refresh(context, configUrl);
600
+ throw cause;
601
+ }
602
+ }
603
+ return record;
604
+ }
605
+ interface BoundHead {
606
+ read(): Promise<Variable & { root: string; etag: string }>;
607
+ write(root: string, cid: string, key: string): Promise<Variable>;
608
+ }
609
+ function headValue(head: Variable): Variable & { root: string; etag: string } {
610
+ const value = object(head.value, "HEAD");
611
+ if (Object.keys(value).join() !== "root" || typeof value.root !== "string")
612
+ throw new HostError("Invalid HEAD value.");
613
+ return {
614
+ ...head,
615
+ root: value.root,
616
+ etag: `"${head.cid}"`,
617
+ };
618
+ }
619
+ export async function pointer(
620
+ context: SwarmContext,
621
+ configUrl: string,
622
+ ): Promise<BoundHead> {
623
+ let record = await readyMembership(context, configUrl);
624
+ const identity = await contextIdentity(context),
625
+ c = coordinates(configUrl);
626
+ const operation = async (
627
+ write: boolean,
628
+ root?: string,
629
+ cid?: string,
630
+ key?: string,
631
+ ) => {
632
+ for (let attempt = 0; ; attempt++) {
633
+ const config = record.config!,
634
+ api = client(
635
+ context,
636
+ c.service,
637
+ identity,
638
+ identity.publicKey === config.owner ? undefined : record.secret,
639
+ );
640
+ try {
641
+ return write
642
+ ? await api.write(
643
+ c.scopeId,
644
+ config.headId,
645
+ { root: root! },
646
+ cid!,
647
+ key!,
648
+ )
649
+ : await api.read(c.scopeId, config.headId);
650
+ } catch (cause) {
651
+ if (
652
+ attempt === 0 &&
653
+ (!write ||
654
+ (cause instanceof ScopeApiError &&
655
+ [401, 403, 404, 410, 423].includes(cause.status)))
656
+ ) {
657
+ const oldHead = record.config!.headId;
658
+ record = await refresh(context, configUrl);
659
+ if (write && record.config!.headId !== oldHead)
660
+ throw new ScopeApiError(
661
+ 412,
662
+ "cas_conflict",
663
+ "HEAD switched; recompute against the new final snapshot",
664
+ cause,
665
+ );
666
+ continue;
667
+ }
668
+ throw cause;
669
+ }
670
+ }
671
+ };
672
+ return {
673
+ read: async () => headValue(await operation(false)),
674
+ write: (root, cid, key) => operation(true, root, cid, key),
675
+ };
676
+ }
677
+ export async function typedJson(
678
+ store: IpfsStore,
679
+ cid: string,
680
+ type: BundleType,
681
+ ): Promise<unknown> {
682
+ const { bundle, value } = await bundleJson(store, cid);
683
+ if (bundle.schemaKey !== (await encodeSchema(type)).cid.toString())
684
+ throw new HostError("Expected exact Bundle type CID.");
685
+ return value;
686
+ }
687
+ function parseArtifact(value: unknown): Artifact {
688
+ const data = object(value, "Artifact");
689
+ if (
690
+ Object.keys(data).some(
691
+ (key) => !["value", "previous", "timestamp"].includes(key),
692
+ ) ||
693
+ typeof data.value !== "string" ||
694
+ typeof data.timestamp !== "string" ||
695
+ !Number.isFinite(Date.parse(data.timestamp)) ||
696
+ (data.previous !== undefined && typeof data.previous !== "string")
697
+ )
698
+ throw new HostError("Invalid Artifact.");
699
+ CID.parse(data.value);
700
+ if (data.previous !== undefined) CID.parse(data.previous);
701
+ return {
702
+ value: data.value,
703
+ timestamp: data.timestamp,
704
+ ...(data.previous !== undefined ? { previous: data.previous } : {}),
705
+ };
706
+ }
707
+ export async function jsonBundle(
708
+ store: IpfsStore,
709
+ type: BundleType,
710
+ value: unknown,
711
+ ): Promise<string> {
712
+ const encoded = await encodeBundleCar(
713
+ memoryTree(
714
+ new Map([
715
+ [
716
+ ".bundle.yaml",
717
+ new TextEncoder().encode(
718
+ stringify({
719
+ title: "IPAB Data",
720
+ entry: "entry.json",
721
+ type: ".bundle-type.yaml",
722
+ }),
723
+ ),
724
+ ],
725
+ [".bundle-type.yaml", new TextEncoder().encode(stringify(type))],
726
+ ["entry.json", new TextEncoder().encode(`${JSON.stringify(value)}\n`)],
727
+ ]),
728
+ ),
729
+ );
730
+ try {
731
+ const iterator = await CarBlockIterator.fromIterable(
732
+ streamChunks(encoded.stream),
733
+ );
734
+ for await (const block of iterator) await store.put(block.cid, block.bytes);
735
+ return encoded.cid.toString();
736
+ } finally {
737
+ await encoded.close();
738
+ }
739
+ }
740
+ export async function writeSnapshot(
741
+ store: IpfsStore,
742
+ snapshot: Snapshot,
743
+ ): Promise<string> {
744
+ const encoded = dagCbor.encode(snapshot),
745
+ cid = CID.createV1(dagCbor.code, await sha256.digest(encoded));
746
+ await store.put(cid, encoded);
747
+ return cid.toString();
748
+ }
749
+ function decodeSnapshot(data: Uint8Array): Snapshot {
750
+ const value = object(dagCbor.decode(data), "State"),
751
+ names = object(value.names, "Names");
752
+ if (value.v !== 2 || Object.keys(value).sort().join() !== "names,v")
753
+ throw new HostError("Unsupported old State; rebuild the Swarm.");
754
+ const links: [string, CID][] = [];
755
+ for (const [name, link] of Object.entries(names)) {
756
+ formalName(name);
757
+ const cid = CID.asCID(link);
758
+ if (!cid) throw new HostError("Names must link CIDs.");
759
+ links.push([name, cid]);
760
+ }
761
+ return { v: 2, names: Object.fromEntries(links) };
762
+ }
763
+ export async function readSnapshot(
764
+ store: IpfsStore,
765
+ root: string,
766
+ ): Promise<Snapshot> {
767
+ const publication = await readPublication(store, root);
768
+ return decodeSnapshot(await store.block.get(publication.state.toString()));
769
+ }
770
+ async function readPublication(
771
+ store: IpfsStore,
772
+ root: string,
773
+ ): Promise<{ state: CID; previous?: CID }> {
774
+ if (CID.parse(root).code !== dagCbor.code)
775
+ throw new HostError("Publication must be DAG-CBOR.");
776
+ const publication = object(
777
+ dagCbor.decode(await store.block.get(root)),
778
+ "publication",
779
+ );
780
+ const state = CID.asCID(publication.state);
781
+ const previous =
782
+ publication.previous === undefined
783
+ ? undefined
784
+ : CID.asCID(publication.previous);
785
+ if (
786
+ publication.v !== 1 ||
787
+ !state ||
788
+ Object.keys(publication).some(
789
+ (k) => !["v", "state", "previous"].includes(k),
790
+ ) ||
791
+ (publication.previous !== undefined && !previous)
792
+ )
793
+ throw new HostError("Invalid publication record.");
794
+ return { state, ...(previous ? { previous } : {}) };
795
+ }
796
+ async function publication(
797
+ store: IpfsStore,
798
+ state: string,
799
+ previous?: string,
800
+ ): Promise<string> {
801
+ const data = dagCbor.encode({
802
+ v: 1,
803
+ state: CID.parse(state),
804
+ ...(previous ? { previous: CID.parse(previous) } : {}),
805
+ });
806
+ const cid = CID.createV1(dagCbor.code, await sha256.digest(data));
807
+ await store.put(cid, data);
808
+ return cid.toString();
809
+ }
810
+ export interface SwarmHeader {
811
+ head: Variable & { root: string; etag: string };
812
+ snapshot: Snapshot;
813
+ config: Organization;
814
+ source: "cache" | "network";
815
+ verifiedAt: string;
816
+ }
817
+ export async function swarmHeader(
818
+ context: SwarmContext,
819
+ configUrl: string,
820
+ force = context.forceRefresh ?? false,
821
+ ): Promise<SwarmHeader> {
822
+ canonicalSwarmUrl(configUrl);
823
+ let record = force
824
+ ? await refresh(context, configUrl)
825
+ : await readyMembership(context, configUrl);
826
+ const ttl = context.cacheTtl ?? 300;
827
+ const cached = force
828
+ ? undefined
829
+ : (withState(context, (state) =>
830
+ state.swarmHeader(record.account, configUrl),
831
+ ) as
832
+ | {
833
+ head: Variable;
834
+ snapshot: string;
835
+ verifiedAt: number;
836
+ headId: string;
837
+ }
838
+ | undefined);
839
+ if (
840
+ cached &&
841
+ cached.headId === record.config!.headId &&
842
+ Date.now() >= cached.verifiedAt &&
843
+ Date.now() - cached.verifiedAt < ttl * 1000
844
+ )
845
+ return {
846
+ head: headValue(cached.head),
847
+ snapshot: decodeSnapshot(Buffer.from(cached.snapshot, "base64")),
848
+ config: record.config!,
849
+ source: "cache",
850
+ verifiedAt: new Date(cached.verifiedAt).toISOString(),
851
+ };
852
+ let head = await (await pointer(context, configUrl)).read();
853
+ let snapshot: Snapshot;
854
+ try {
855
+ snapshot = await readSnapshot(context.store, head.root);
856
+ } catch {
857
+ record = await refresh(context, configUrl);
858
+ head = await (await pointer(context, configUrl)).read();
859
+ snapshot = await readSnapshot(context.store, head.root);
860
+ }
861
+ const current = await local(context, configUrl),
862
+ verifiedAt = Date.now();
863
+ withState(context, (state) => {
864
+ state.saveSwarmHeader(record.account, configUrl, {
865
+ head,
866
+ snapshot: Buffer.from(dagCbor.encode(snapshot)).toString("base64"),
867
+ verifiedAt,
868
+ headId: current.config!.headId,
869
+ });
870
+ });
871
+ return {
872
+ head,
873
+ snapshot,
874
+ config: current.config!,
875
+ source: "network",
876
+ verifiedAt: new Date(verifiedAt).toISOString(),
877
+ };
878
+ }
879
+ export async function addSwarm(
880
+ context: SwarmContext,
881
+ url: string,
882
+ alias?: string,
883
+ ): Promise<void> {
884
+ canonicalSwarmUrl(url);
885
+ await readyMembership(context, url);
886
+ withState(context, (state) => state.registerSwarm(url, alias));
887
+ }
888
+ interface Creation {
889
+ owner: string;
890
+ service: string;
891
+ encryption: EncryptionIdentity;
892
+ key: string;
893
+ name: string;
894
+ description: string;
895
+ createdAt: string;
896
+ scopeId?: string;
897
+ headId?: string;
898
+ profileId?: string;
899
+ configId?: string;
900
+ config?: Organization;
901
+ }
902
+ export async function createSwarm(
903
+ context: SwarmContext,
904
+ options: {
905
+ service?: string;
906
+ resume?: string;
907
+ properties?: { name: string; description: string };
908
+ alias?: string;
909
+ addresses?: string[];
910
+ } = {},
911
+ ): Promise<string> {
912
+ if (
913
+ (options.properties?.name.length ?? 0) > 256 ||
914
+ (options.properties?.description.length ?? 0) > 2048 ||
915
+ (options.addresses?.length ?? 0) > 16
916
+ )
917
+ throw new HostError(
918
+ "Organization name/description or address limit exceeded.",
919
+ );
920
+ const service = canonicalService(context.pointerService ?? "");
921
+ if (
922
+ !context.pointerApiKey ||
923
+ (options.service && options.service !== service)
924
+ )
925
+ throw new HostError(
926
+ "Configure origin-bound pointers.service/apiKey before creating a Scope.",
927
+ );
928
+ const identity = await contextIdentity(context, true),
929
+ op = options.resume ?? uniqueId(),
930
+ dir = await directory(context);
931
+ if (!POINTER_ID_PATTERN.test(op))
932
+ throw new HostError("Invalid creation resume ID.");
933
+ return withPrivateLock(dir, async () => {
934
+ let record = await readPrivate<Creation>(dir, `creation-${op}.json`);
935
+ if (options.alias !== undefined) {
936
+ const existingUrl =
937
+ record?.scopeId && record.configId
938
+ ? `${service}/v1/${record.scopeId}/${record.configId}`
939
+ : undefined;
940
+ withState(context, (state) => {
941
+ state.checkSwarmAlias(options.alias!, existingUrl);
942
+ });
943
+ }
944
+ if (!record) {
945
+ if (options.resume) throw new HostError("Unknown creation operation.");
946
+ record = {
947
+ owner: identity.publicKey,
948
+ service,
949
+ encryption: encryptionIdentity(),
950
+ key: randomBytes(32).toString("hex"),
951
+ name: options.properties?.name ?? "",
952
+ description: options.properties?.description ?? "",
953
+ createdAt: new Date().toISOString(),
954
+ };
955
+ await writePrivate(dir, `creation-${op}.json`, record);
956
+ }
957
+ if (record.owner !== identity.publicKey || record.service !== service)
958
+ throw new HostError("Creation belongs to another Owner or service.");
959
+ const save = () => writePrivate(dir, `creation-${op}.json`, record);
960
+ const api = client(context, service, identity);
961
+ try {
962
+ if (!record.scopeId) {
963
+ record.scopeId = (await api.createScope(`${op}.scope`)).id;
964
+ await save();
965
+ }
966
+ const node = await prepareNode(
967
+ context.stateDir,
968
+ nodeScope(service, record.scopeId),
969
+ );
970
+ if (!record.headId) {
971
+ const root = await publication(
972
+ context.store,
973
+ await writeSnapshot(context.store, { v: 2, names: {} }),
974
+ );
975
+ record.headId = (
976
+ await api.create(record.scopeId, { root }, `${op}.head`)
977
+ ).id;
978
+ await save();
979
+ }
980
+ if (!record.profileId) {
981
+ const addresses = options.addresses ?? node.addresses;
982
+ for (const address of addresses) validateAddress(address, node.peerId);
983
+ record.profileId = (
984
+ await api.create(
985
+ record.scopeId,
986
+ { name: record.name, addresses, updatedAt: record.createdAt },
987
+ `${op}.profile`,
988
+ )
989
+ ).id;
990
+ await save();
991
+ }
992
+ if (!record.config) {
993
+ record.config = {
994
+ v: 1,
995
+ scopeId: record.scopeId,
996
+ owner: identity.publicKey,
997
+ name: record.name,
998
+ description: record.description,
999
+ headId: record.headId,
1000
+ epoch: 1,
1001
+ bootstrap: options.addresses ?? node.addresses,
1002
+ members: [
1003
+ {
1004
+ publicKey: identity.publicKey,
1005
+ encryptionKey: record.encryption.publicKey,
1006
+ peerId: node.peerId,
1007
+ profileId: record.profileId,
1008
+ requestId: op,
1009
+ approval: null,
1010
+ },
1011
+ ],
1012
+ };
1013
+ await save();
1014
+ }
1015
+ if (!record.configId) {
1016
+ record.configId = (
1017
+ await api.create(record.scopeId, record.config, `${op}.config`)
1018
+ ).id;
1019
+ await save();
1020
+ }
1021
+ const configUrl = `${service}/v1/${record.scopeId}/${record.configId}`;
1022
+ const cert = await issueScopeCertificate(
1023
+ {
1024
+ v: 1,
1025
+ service,
1026
+ scopeId: record.scopeId,
1027
+ subject: identity.publicKey,
1028
+ write: [record.headId, record.profileId],
1029
+ },
1030
+ await importPrivateKeyPkcs8(identity.privateKey),
1031
+ );
1032
+ const membership: LocalMembership = {
1033
+ configUrl,
1034
+ owner: identity.publicKey,
1035
+ account: identity.publicKey,
1036
+ encryption: record.encryption,
1037
+ config: record.config,
1038
+ secret: { certificate: cert, swarmKey: record.key },
1039
+ };
1040
+ await saveLocal(context, membership);
1041
+ await activate(context, membership);
1042
+ const head = await api.read(record.scopeId, record.headId);
1043
+ await provideContent(
1044
+ context.store,
1045
+ [headValue(head).root],
1046
+ context.node!.api,
1047
+ context.fetch,
1048
+ context.node!.auth,
1049
+ );
1050
+ withState(context, (state) =>
1051
+ state.registerSwarm(configUrl, options.alias),
1052
+ );
1053
+ return configUrl;
1054
+ } catch (cause) {
1055
+ throw new HostError(
1056
+ `Swarm creation incomplete: ${message(cause)}. Resume only with swarm create --resume ${op}.`,
1057
+ );
1058
+ }
1059
+ });
1060
+ }
1061
+ const requestMessage = (
1062
+ request: Omit<MembershipRequest, "signature" | "peerSignature">,
1063
+ ) => JSON.stringify(["IPAB-REQUEST/1", request]);
1064
+ export async function exportRequest(
1065
+ context: SwarmContext,
1066
+ url: string,
1067
+ output: string,
1068
+ ): Promise<string> {
1069
+ const record = await local(context, canonicalSwarmUrl(url));
1070
+ if (!record.request) throw new HostError("Owner membership has no Request.");
1071
+ const handle = await open(output, "wx", 0o600);
1072
+ try {
1073
+ await handle.writeFile(`${JSON.stringify(record.request, null, 2)}\n`);
1074
+ await handle.sync();
1075
+ } finally {
1076
+ await handle.close();
1077
+ }
1078
+ return record.request.id;
1079
+ }
1080
+ export async function requestMembership(
1081
+ context: SwarmContext,
1082
+ url: string,
1083
+ options: {
1084
+ ownerFingerprint: string;
1085
+ name?: string;
1086
+ alias?: string;
1087
+ output?: string;
1088
+ },
1089
+ ): Promise<string> {
1090
+ if ((options.name?.length ?? 0) > 256)
1091
+ throw new HostError("Request name exceeds 256 characters.");
1092
+ canonicalSwarmUrl(url);
1093
+ const identity = await contextIdentity(context, true);
1094
+ const { config } = await fetchConfig(context, url);
1095
+ if (options.ownerFingerprint !== (await keyId(config.owner)))
1096
+ throw new HostError(
1097
+ `Trusted Owner fingerprint required; observed ${await keyId(config.owner)}. Verify through an independent trusted channel.`,
1098
+ );
1099
+ const dir = await directory(context);
1100
+ await withPrivateLock(dir, async () => {
1101
+ if (options.alias !== undefined)
1102
+ withState(context, (state) => {
1103
+ state.checkSwarmAlias(options.alias!, url);
1104
+ });
1105
+ const existing = await readPrivate<LocalMembership>(dir, localName(url));
1106
+ if (existing) {
1107
+ if (
1108
+ existing.account !== identity.publicKey ||
1109
+ existing.owner !== config.owner
1110
+ )
1111
+ throw new HostError(
1112
+ "Existing Request belongs to a different identity or pinned Owner.",
1113
+ );
1114
+ if (!existing.request)
1115
+ throw new HostError("This identity is already the Owner.");
1116
+ withState(context, (state) => state.registerSwarm(url, options.alias));
1117
+ return;
1118
+ }
1119
+ const node = await prepareNode(
1120
+ context.stateDir,
1121
+ nodeScope(coordinates(url).service, config.scopeId),
1122
+ ),
1123
+ encryption = encryptionIdentity();
1124
+ const body = {
1125
+ v: 1 as const,
1126
+ id: uniqueId(),
1127
+ requestedAt: new Date().toISOString(),
1128
+ configUrl: url,
1129
+ scopeId: config.scopeId,
1130
+ owner: config.owner,
1131
+ name: options.name ?? "",
1132
+ member: identity.publicKey,
1133
+ encryptionKey: encryption.publicKey,
1134
+ peerId: node.peerId,
1135
+ peerPublicKey: "",
1136
+ };
1137
+ body.peerPublicKey = (await peerProof(node, "identity")).publicKey;
1138
+ const proof = await peerProof(node, requestMessage(body));
1139
+ const peerSignature = proof.signature;
1140
+ const request = {
1141
+ ...body,
1142
+ peerSignature,
1143
+ signature: await signEd25519(
1144
+ await importPrivateKeyPkcs8(identity.privateKey),
1145
+ JSON.stringify(["IPAB-REQUEST-MEMBER/1", body, peerSignature]),
1146
+ ),
1147
+ };
1148
+ await saveLocal(context, {
1149
+ configUrl: url,
1150
+ owner: config.owner,
1151
+ account: identity.publicKey,
1152
+ encryption,
1153
+ request,
1154
+ });
1155
+ withState(context, (state) => state.registerSwarm(url, options.alias));
1156
+ });
1157
+ if (options.output) await exportRequest(context, url, options.output);
1158
+ return (await local(context, url)).request!.id;
1159
+ }
1160
+ export async function verifiedRequest(
1161
+ path: string,
1162
+ ): Promise<MembershipRequest> {
1163
+ if ((await lstat(path)).size > 16 * 1024)
1164
+ throw new HostError("Request file exceeds 16 KiB.");
1165
+ return verifyRequest(JSON.parse(await readFile(path, "utf8")) as unknown);
1166
+ }
1167
+ async function verifyRequest(input: unknown): Promise<MembershipRequest> {
1168
+ const fields = object(input, "Request");
1169
+ if (
1170
+ Object.keys(fields).sort().join() !==
1171
+ "configUrl,encryptionKey,id,member,name,owner,peerId,peerPublicKey,peerSignature,requestedAt,scopeId,signature,v" ||
1172
+ fields.v !== 1
1173
+ )
1174
+ throw new HostError("Invalid self-contained Request format.");
1175
+ const {
1176
+ id,
1177
+ member,
1178
+ owner,
1179
+ name,
1180
+ encryptionKey,
1181
+ requestedAt,
1182
+ configUrl,
1183
+ scopeId,
1184
+ peerId: requestPeer,
1185
+ peerPublicKey,
1186
+ peerSignature,
1187
+ signature,
1188
+ } = fields;
1189
+ if (
1190
+ typeof id !== "string" ||
1191
+ !POINTER_ID_PATTERN.test(id) ||
1192
+ !isCanonicalPublicKey(member) ||
1193
+ !isCanonicalPublicKey(owner) ||
1194
+ typeof name !== "string" ||
1195
+ name.length > 256 ||
1196
+ typeof encryptionKey !== "string" ||
1197
+ encryptionKey.length > 256 ||
1198
+ typeof requestedAt !== "string" ||
1199
+ !Number.isFinite(Date.parse(requestedAt)) ||
1200
+ typeof configUrl !== "string" ||
1201
+ typeof scopeId !== "string" ||
1202
+ coordinates(configUrl).scopeId !== scopeId ||
1203
+ !isCanonicalPublicKey(peerPublicKey) ||
1204
+ typeof requestPeer !== "string" ||
1205
+ peerId(peerPublicKey) !== requestPeer ||
1206
+ typeof peerSignature !== "string" ||
1207
+ typeof signature !== "string"
1208
+ )
1209
+ throw new HostError("Invalid self-contained Request.");
1210
+ const body: Omit<MembershipRequest, "signature" | "peerSignature"> = {
1211
+ v: 1,
1212
+ id,
1213
+ requestedAt,
1214
+ configUrl,
1215
+ scopeId,
1216
+ owner,
1217
+ name,
1218
+ member,
1219
+ encryptionKey,
1220
+ peerId: requestPeer,
1221
+ peerPublicKey,
1222
+ };
1223
+ if (
1224
+ !(await verifyEd25519(
1225
+ await importPublicKeyRaw(peerPublicKey),
1226
+ peerSignature,
1227
+ requestMessage(body),
1228
+ )) ||
1229
+ !(await verifyEd25519(
1230
+ await importPublicKeyRaw(member),
1231
+ signature,
1232
+ JSON.stringify(["IPAB-REQUEST-MEMBER/1", body, peerSignature]),
1233
+ ))
1234
+ )
1235
+ throw new HostError(
1236
+ "Request member or PeerID possession proof is invalid.",
1237
+ );
1238
+ return { ...body, peerSignature, signature };
1239
+ }
1240
+ export async function membershipRequestSummary(
1241
+ request: MembershipRequest,
1242
+ ): Promise<string> {
1243
+ return [
1244
+ `Request: ${request.id}`,
1245
+ `Target: ${request.configUrl}`,
1246
+ `Name: ${JSON.stringify(request.name)}`,
1247
+ `Member public key: ${request.member}`,
1248
+ `Member fingerprint: ${await keyId(request.member)}`,
1249
+ `PeerID: ${request.peerId}`,
1250
+ `Requested at: ${JSON.stringify(request.requestedAt)}`,
1251
+ "Verify the applicant through an independent trusted channel before approving.",
1252
+ ].join("\n");
1253
+ }
1254
+ interface ApprovalOperation {
1255
+ owner: string;
1256
+ request: MembershipRequest;
1257
+ operation: string;
1258
+ createdAt: string;
1259
+ profileId?: string;
1260
+ completed?: boolean;
1261
+ value?: Organization;
1262
+ baseline?: string;
1263
+ }
1264
+ async function ownerCheck(
1265
+ context: SwarmContext,
1266
+ url: string,
1267
+ ): Promise<{ identity: Identity; record: LocalMembership }> {
1268
+ const identity = await contextIdentity(context),
1269
+ record = await readyMembership(context, url);
1270
+ if (identity.publicKey !== record.owner)
1271
+ throw new HostError(
1272
+ "Only the pinned Owner can manage membership or organization configuration.",
1273
+ );
1274
+ const transition = await readPrivate<Removal>(
1275
+ await directory(context),
1276
+ `transition-${localName(url)}`,
1277
+ );
1278
+ if (transition && !transition.completed)
1279
+ throw new HostError(
1280
+ "Organization switch incomplete: run swarm resume for this URL before other Owner changes.",
1281
+ );
1282
+ return { identity, record };
1283
+ }
1284
+ export async function approveMembership(
1285
+ context: SwarmContext,
1286
+ input: string | MembershipRequest,
1287
+ options: { again?: boolean } = {},
1288
+ ): Promise<string> {
1289
+ const request =
1290
+ typeof input === "string"
1291
+ ? await verifiedRequest(input)
1292
+ : await verifyRequest(input),
1293
+ url = request.configUrl;
1294
+ const dir = await directory(context);
1295
+ return withPrivateLock(dir, async () => {
1296
+ const { identity, record } = await ownerCheck(context, url);
1297
+ if (request.owner !== identity.publicKey)
1298
+ throw new HostError("Request targets a different Owner.");
1299
+ let operation = await readPrivate<ApprovalOperation>(
1300
+ dir,
1301
+ `approval-${request.id}.json`,
1302
+ );
1303
+ if (operation && !operation.completed && options.again)
1304
+ throw new HostError(
1305
+ "The prior approval is unconfirmed; resume the same Request without --again before starting a new explicit approval.",
1306
+ );
1307
+ if (operation?.completed && !options.again) {
1308
+ if (
1309
+ operation.owner !== identity.publicKey ||
1310
+ JSON.stringify(operation.request) !== JSON.stringify(request)
1311
+ )
1312
+ throw new HostError(
1313
+ "This Request ID differs from advisory history; manually verify it and use --again for a new explicit approval.",
1314
+ );
1315
+ context.diagnostic?.(
1316
+ `Previously approved Request ${request.id} from ${request.requestedAt}. History is advisory, not a revocation boundary.`,
1317
+ );
1318
+ context.diagnostic?.(
1319
+ "Reusing the completed approval result without granting new authority. Use --again only after fresh manual confirmation.",
1320
+ );
1321
+ return url;
1322
+ }
1323
+ if (!operation || options.again) {
1324
+ operation = {
1325
+ owner: identity.publicKey,
1326
+ request,
1327
+ operation: uniqueId(),
1328
+ createdAt: new Date().toISOString(),
1329
+ };
1330
+ await writePrivate(dir, `approval-${request.id}.json`, operation);
1331
+ }
1332
+ if (
1333
+ operation.owner !== identity.publicKey ||
1334
+ JSON.stringify(operation.request) !== JSON.stringify(request)
1335
+ )
1336
+ throw new HostError("Saved approval does not match this exact Request.");
1337
+ const save = () =>
1338
+ writePrivate(dir, `approval-${request.id}.json`, operation);
1339
+ const c = coordinates(url),
1340
+ api = client(context, c.service, identity);
1341
+ const fetched = await fetchConfig(context, url);
1342
+ if (
1343
+ fetched.config.epoch !== record.config!.epoch ||
1344
+ fetched.config.headId !== record.config!.headId
1345
+ )
1346
+ throw new HostError(
1347
+ "Owner local keys are not synchronized with this organization epoch.",
1348
+ );
1349
+ if (!operation.profileId) {
1350
+ const previousMember = fetched.config.members.find(
1351
+ (m) => m.publicKey === request.member,
1352
+ );
1353
+ if (previousMember && previousMember.peerId !== request.peerId)
1354
+ throw new HostError(
1355
+ "PeerID rebinding requires removing the old membership first, then explicitly approving this Request.",
1356
+ );
1357
+ const existingProfile = fetched.config.members.find(
1358
+ (m) => m.publicKey === request.member,
1359
+ )?.profileId;
1360
+ if (existingProfile) operation.profileId = existingProfile;
1361
+ if (!operation.profileId)
1362
+ operation.profileId = (
1363
+ await api.create(
1364
+ c.scopeId,
1365
+ {
1366
+ name: request.name,
1367
+ addresses: [],
1368
+ updatedAt: operation.createdAt,
1369
+ },
1370
+ `${operation.operation}.profile`,
1371
+ )
1372
+ ).id;
1373
+ await save();
1374
+ }
1375
+ if (!operation.value) {
1376
+ const member: Member = {
1377
+ publicKey: request.member,
1378
+ encryptionKey: request.encryptionKey,
1379
+ peerId: request.peerId,
1380
+ profileId: operation.profileId,
1381
+ requestId: request.id,
1382
+ approval: null,
1383
+ };
1384
+ const config = {
1385
+ ...fetched.config,
1386
+ members: fetched.config.members.filter(
1387
+ (m) => m.publicKey !== request.member,
1388
+ ),
1389
+ };
1390
+ if (config.members.some((m) => m.peerId === request.peerId))
1391
+ throw new HostError("PeerID is already assigned to another member.");
1392
+ if (request.member === identity.publicKey)
1393
+ throw new HostError("Owner cannot request member approval.");
1394
+ if (config.members.length >= 16)
1395
+ throw new HostError("Organization member limit is 16.");
1396
+ const certificate = await issueScopeCertificate(
1397
+ {
1398
+ v: 1,
1399
+ service: c.service,
1400
+ scopeId: c.scopeId,
1401
+ subject: request.member,
1402
+ write: [config.headId, member.profileId],
1403
+ },
1404
+ await importPrivateKeyPkcs8(identity.privateKey),
1405
+ );
1406
+ member.approval = await sealApproval(
1407
+ binding(url, config, member),
1408
+ { certificate, swarmKey: record.secret!.swarmKey },
1409
+ identity,
1410
+ );
1411
+ config.members.push(member);
1412
+ operation.value = config;
1413
+ operation.baseline = fetched.variable.cid;
1414
+ await save();
1415
+ }
1416
+ const observed = await api.read(c.scopeId, c.configId);
1417
+ if (observed.cid !== (await valueCid(operation.value)))
1418
+ await api.write(
1419
+ c.scopeId,
1420
+ c.configId,
1421
+ operation.value,
1422
+ operation.baseline!,
1423
+ `${operation.operation}.publish`,
1424
+ );
1425
+ operation.completed = true;
1426
+ await save();
1427
+ record.config = operation.value;
1428
+ await saveLocal(context, record);
1429
+ return url;
1430
+ });
1431
+ }
1432
+ export async function updateSwarm(
1433
+ context: SwarmContext,
1434
+ url: string,
1435
+ changes: { name?: string; description?: string },
1436
+ ) {
1437
+ if (
1438
+ (changes.name?.length ?? 0) > 256 ||
1439
+ (changes.description?.length ?? 0) > 2048
1440
+ )
1441
+ throw new HostError("Organization name/description limit exceeded.");
1442
+ const { identity, record } = await ownerCheck(context, url),
1443
+ c = coordinates(url);
1444
+ if (changes.name === undefined && changes.description === undefined)
1445
+ throw new HostError("swarm update requires name or description.");
1446
+ const fetched = await fetchConfig(context, url),
1447
+ config = { ...fetched.config, ...changes };
1448
+ const result = await client(context, c.service, identity).write(
1449
+ c.scopeId,
1450
+ c.configId,
1451
+ config,
1452
+ fetched.variable.cid,
1453
+ uniqueId(),
1454
+ );
1455
+ record.config = config;
1456
+ await saveLocal(context, record);
1457
+ return {
1458
+ configUrl: url,
1459
+ headId: config.headId,
1460
+ valueCid: result.cid,
1461
+ properties: { name: config.name, description: config.description },
1462
+ };
1463
+ }
1464
+ export async function updateProfile(
1465
+ context: SwarmContext,
1466
+ url: string,
1467
+ changes: { name?: string; addresses?: string[] },
1468
+ ): Promise<Profile> {
1469
+ if (changes.name !== undefined && changes.name.length > 256)
1470
+ throw new HostError("Profile name exceeds 256 characters.");
1471
+ if ((changes.addresses?.length ?? 0) > 16)
1472
+ throw new HostError("Profile address limit is 16.");
1473
+ const record = await readyMembership(context, url),
1474
+ identity = await contextIdentity(context),
1475
+ c = coordinates(url);
1476
+ const member = record.config!.members.find(
1477
+ (m) => m.publicKey === identity.publicKey,
1478
+ )!;
1479
+ for (const address of changes.addresses ?? [])
1480
+ validateAddress(address, member.peerId);
1481
+ const api = client(
1482
+ context,
1483
+ c.service,
1484
+ identity,
1485
+ identity.publicKey === record.owner ? undefined : record.secret,
1486
+ );
1487
+ const existing = await api.read(c.scopeId, member.profileId);
1488
+ const profile = {
1489
+ ...parseProfile(existing.value, member.peerId),
1490
+ ...changes,
1491
+ updatedAt: new Date().toISOString(),
1492
+ };
1493
+ await api.write(
1494
+ c.scopeId,
1495
+ member.profileId,
1496
+ profile,
1497
+ existing.cid,
1498
+ uniqueId(),
1499
+ );
1500
+ return profile;
1501
+ }
1502
+ interface Removal {
1503
+ owner: string;
1504
+ url: string;
1505
+ operation: string;
1506
+ member: string;
1507
+ oldConfig: Organization;
1508
+ configCid: string;
1509
+ newKey: string;
1510
+ oldKey: string;
1511
+ finalHead?: Variable;
1512
+ finalCaptured?: boolean;
1513
+ finalClosureRoots?: string[];
1514
+ newHeadId?: string;
1515
+ nextConfig?: Organization;
1516
+ published?: boolean;
1517
+ completed?: boolean;
1518
+ }
1519
+ export async function removeMember(
1520
+ context: SwarmContext,
1521
+ url: string,
1522
+ member: string,
1523
+ ): Promise<void> {
1524
+ const dir = await directory(context);
1525
+ await withPrivateLock(dir, async () => {
1526
+ const { identity, record: membership } = await ownerCheck(context, url);
1527
+ if (member === identity.publicKey)
1528
+ throw new HostError("Owner removal/recovery is unsupported.");
1529
+ const fetched = await fetchConfig(context, url);
1530
+ if (!fetched.config.members.some((m) => m.publicKey === member))
1531
+ throw new HostError("Unknown member public key.");
1532
+ const record: Removal = {
1533
+ owner: identity.publicKey,
1534
+ url,
1535
+ operation: uniqueId(),
1536
+ member,
1537
+ oldConfig: fetched.config,
1538
+ configCid: fetched.variable.cid,
1539
+ oldKey: membership.secret!.swarmKey,
1540
+ newKey: randomBytes(32).toString("hex"),
1541
+ };
1542
+ await writePrivate(dir, `transition-${localName(url)}`, record);
1543
+ });
1544
+ await resumeRemoval(context, url);
1545
+ }
1546
+ export async function resumeRemoval(
1547
+ context: SwarmContext,
1548
+ url: string,
1549
+ ): Promise<void> {
1550
+ const dir = await directory(context);
1551
+ return withPrivateLock(dir, async () => {
1552
+ const identity = await contextIdentity(context);
1553
+ const record = await readPrivate<Removal>(
1554
+ dir,
1555
+ `transition-${localName(url)}`,
1556
+ );
1557
+ if (!record || record.owner !== identity.publicKey || record.url !== url)
1558
+ throw new HostError("No resumable switch owned by this identity.");
1559
+ if (record.completed) return;
1560
+ const c = coordinates(url),
1561
+ api = client(context, c.service, identity);
1562
+ const save = () =>
1563
+ writePrivate(dir, `transition-${localName(url)}`, record);
1564
+ try {
1565
+ if (!record.finalHead) {
1566
+ record.finalHead = await api.freeze(
1567
+ c.scopeId,
1568
+ record.oldConfig.headId,
1569
+ `${record.operation}.freeze`,
1570
+ );
1571
+ await save();
1572
+ }
1573
+ // Fetch the frozen final DAG while the old private network is still connected.
1574
+ // A publication acknowledged immediately before freeze may not be cached on Owner.
1575
+ const membershipBeforeSwitch = await local(context, url);
1576
+ if (!record.finalCaptured) {
1577
+ membershipBeforeSwitch.config = record.oldConfig;
1578
+ membershipBeforeSwitch.secret!.swarmKey = record.oldKey;
1579
+ await activate(context, membershipBeforeSwitch);
1580
+ if (!record.finalClosureRoots) {
1581
+ record.finalClosureRoots = await frozenPublicationClosure(
1582
+ context.store,
1583
+ headValue(record.finalHead).root,
1584
+ );
1585
+ await save();
1586
+ }
1587
+ await provideContent(
1588
+ context.store,
1589
+ record.finalClosureRoots,
1590
+ context.node!.api,
1591
+ context.fetch,
1592
+ context.node!.auth,
1593
+ );
1594
+ record.finalCaptured = true;
1595
+ await save();
1596
+ }
1597
+ if (
1598
+ !record.finalClosureRoots ||
1599
+ record.finalClosureRoots[0] !== headValue(record.finalHead).root
1600
+ )
1601
+ throw new HostError(
1602
+ "Frozen publication closure is missing; refusing to retire the old network or HEAD.",
1603
+ );
1604
+ if (!record.newHeadId) {
1605
+ record.newHeadId = (
1606
+ await api.create(
1607
+ c.scopeId,
1608
+ record.finalHead.value,
1609
+ `${record.operation}.newhead`,
1610
+ )
1611
+ ).id;
1612
+ await save();
1613
+ }
1614
+ if (!record.nextConfig) {
1615
+ const config = {
1616
+ ...record.oldConfig,
1617
+ headId: record.newHeadId,
1618
+ epoch: record.oldConfig.epoch + 1,
1619
+ members: structuredClone(
1620
+ record.oldConfig.members.filter(
1621
+ (m) => m.publicKey !== record.member,
1622
+ ),
1623
+ ),
1624
+ bootstrap: record.oldConfig.bootstrap.filter(
1625
+ (address) =>
1626
+ !address.endsWith(
1627
+ `/p2p/${record.oldConfig.members.find((m) => m.publicKey === record.member)!.peerId}`,
1628
+ ),
1629
+ ),
1630
+ };
1631
+ for (const member of config.members) {
1632
+ if (member.publicKey === identity.publicKey) continue;
1633
+ const certificate = await issueScopeCertificate(
1634
+ {
1635
+ v: 1,
1636
+ service: c.service,
1637
+ scopeId: c.scopeId,
1638
+ subject: member.publicKey,
1639
+ write: [config.headId, member.profileId],
1640
+ },
1641
+ await importPrivateKeyPkcs8(identity.privateKey),
1642
+ );
1643
+ member.approval = await sealApproval(
1644
+ binding(url, config, member),
1645
+ { certificate, swarmKey: record.newKey },
1646
+ identity,
1647
+ );
1648
+ }
1649
+ record.nextConfig = config;
1650
+ await save();
1651
+ }
1652
+ const leaving = record.oldConfig.members.find(
1653
+ (m) => m.publicKey === record.member,
1654
+ )!;
1655
+ // Delete the profile before exposing the new configuration. Old HEAD stays readable until final cleanup.
1656
+ try {
1657
+ await api.freeze(
1658
+ c.scopeId,
1659
+ leaving.profileId,
1660
+ `${record.operation}.profilefreeze`,
1661
+ );
1662
+ } catch (cause) {
1663
+ if (!(cause instanceof ScopeApiError) || cause.status !== 410)
1664
+ throw cause;
1665
+ }
1666
+ try {
1667
+ await api.delete(
1668
+ c.scopeId,
1669
+ leaving.profileId,
1670
+ `${record.operation}.profiledelete`,
1671
+ );
1672
+ } catch (cause) {
1673
+ if (!(cause instanceof ScopeApiError) || cause.status !== 410)
1674
+ throw cause;
1675
+ }
1676
+ if (!record.published) {
1677
+ const observed = await api.read(c.scopeId, c.configId);
1678
+ if (observed.cid !== (await valueCid(record.nextConfig)))
1679
+ await api.write(
1680
+ c.scopeId,
1681
+ c.configId,
1682
+ record.nextConfig,
1683
+ record.configCid,
1684
+ `${record.operation}.config`,
1685
+ );
1686
+ record.published = true;
1687
+ await save();
1688
+ }
1689
+ const membership = await local(context, url);
1690
+ membership.config = record.nextConfig;
1691
+ membership.secret!.swarmKey = record.newKey;
1692
+ await saveLocal(context, membership);
1693
+ await activate(context, membership);
1694
+ await provideContent(
1695
+ context.store,
1696
+ record.finalClosureRoots,
1697
+ context.node!.api,
1698
+ context.fetch,
1699
+ context.node!.auth,
1700
+ );
1701
+ try {
1702
+ await api.delete(
1703
+ c.scopeId,
1704
+ record.oldConfig.headId,
1705
+ `${record.operation}.delete`,
1706
+ );
1707
+ } catch (cause) {
1708
+ if (!(cause instanceof ScopeApiError) || cause.status !== 410)
1709
+ throw cause;
1710
+ }
1711
+ record.completed = true;
1712
+ await save();
1713
+ withState(context, (state) => {
1714
+ state.invalidateSwarmHeader(url);
1715
+ });
1716
+ } catch (cause) {
1717
+ throw new HostError(
1718
+ `Organization switch incomplete (old HEAD is never unfrozen): ${message(cause)}. Owner must run swarm resume ${url}.`,
1719
+ );
1720
+ }
1721
+ });
1722
+ }
1723
+ export function formalName(name: string): string {
1724
+ relativePath(name);
1725
+ if (name.length > 256 || name.startsWith("builtin:"))
1726
+ throw new HostError("Invalid formal Name.");
1727
+ return name;
1728
+ }
1729
+ export function parseNameReference(
1730
+ reference: string,
1731
+ ): { swarm?: string; name: string } | undefined {
1732
+ if (/^name:/i.test(reference))
1733
+ throw new HostError("name: is unsupported; use ipab://ALIAS/PATH.");
1734
+ if (!/^ipab:/i.test(reference)) return undefined;
1735
+ const match = /^ipab:\/\/([^/]*)\/([^?#\s]*)$/i.exec(reference);
1736
+ if (!match)
1737
+ throw new HostError(
1738
+ "Invalid IPAB URI; percent-encode the configuration URL authority and each path segment.",
1739
+ );
1740
+ const authority = decodeURIComponent(match[1]!);
1741
+ if (authority && !/^[A-Za-z0-9][A-Za-z0-9._-]*$/.test(authority))
1742
+ canonicalSwarmUrl(authority);
1743
+ const segments = match[2]!.split("/").map((segment) => {
1744
+ const decoded = decodeURIComponent(segment);
1745
+ if (decoded.includes("/"))
1746
+ throw new HostError("Encoded path separators are unsupported.");
1747
+ return decoded;
1748
+ });
1749
+ return {
1750
+ ...(authority ? { swarm: authority } : {}),
1751
+ name: formalName(segments.join("/")),
1752
+ };
1753
+ }
1754
+ function referenceFor(url: string, name: string): string {
1755
+ const segment = (value: string) =>
1756
+ encodeURIComponent(value).replace(
1757
+ /[!'()*]/g,
1758
+ (char) => `%${char.charCodeAt(0).toString(16).toUpperCase()}`,
1759
+ );
1760
+ return `ipab://${segment(url)}/${name.split("/").map(segment).join("/")}`;
1761
+ }
1762
+ export async function resolveReference(
1763
+ context: SwarmContext,
1764
+ reference: string,
1765
+ swarm: string | undefined,
1766
+ local: (reference: string) => string,
1767
+ raw = false,
1768
+ ): Promise<{ targetCid: string; cid: string }> {
1769
+ const shared = parseNameReference(reference);
1770
+ let targetCid: string;
1771
+ if (shared) {
1772
+ const selected = shared.swarm
1773
+ ? withState(context, (state) => state.resolveSwarm(shared.swarm!))
1774
+ : swarm;
1775
+ if (!selected)
1776
+ throw new HostError(
1777
+ "Select a configuration URL/alias using --swarm or swarm use.",
1778
+ );
1779
+ let header = await swarmHeader(context, selected);
1780
+ let link = Object.hasOwn(header.snapshot.names, shared.name)
1781
+ ? header.snapshot.names[shared.name]
1782
+ : undefined;
1783
+ if (!link && header.source === "cache") {
1784
+ header = await swarmHeader(context, selected, true);
1785
+ link = Object.hasOwn(header.snapshot.names, shared.name)
1786
+ ? header.snapshot.names[shared.name]
1787
+ : undefined;
1788
+ }
1789
+ if (!link)
1790
+ throw new HostError(
1791
+ `Formal Name "${shared.name}" was not found after refreshing HEAD.`,
1792
+ );
1793
+ targetCid = link.toString();
1794
+ } else {
1795
+ if (swarm) await readyMembership(context, swarm);
1796
+ targetCid = local(reference);
1797
+ }
1798
+ let cid = targetCid;
1799
+ const visited = new Set<string>();
1800
+ for (let depth = 0; !raw; depth++) {
1801
+ if (depth >= 64 || visited.has(cid))
1802
+ throw new HostError(
1803
+ "Artifact resolution exceeds limits or contains a cycle.",
1804
+ );
1805
+ visited.add(cid);
1806
+ const bundle = await openBundle(CID.parse(cid), {
1807
+ resolveCid: (cid) => context.store.block.get(cid.toString()),
1808
+ });
1809
+ if (bundle.schemaKey !== (await encodeSchema(artifactType)).cid.toString())
1810
+ break;
1811
+ cid = CID.parse(
1812
+ parseArtifact(await typedJson(context.store, cid, artifactType)).value,
1813
+ )
1814
+ .toV1()
1815
+ .toString();
1816
+ }
1817
+ return { targetCid, cid };
1818
+ }
1819
+ export async function searchNames(
1820
+ context: SwarmContext,
1821
+ query: string,
1822
+ swarms: readonly { cid: string; alias: string | null }[],
1823
+ ) {
1824
+ if (
1825
+ !query ||
1826
+ query.length > 256 ||
1827
+ [...query].some(
1828
+ (char) => char.charCodeAt(0) < 32 || char.charCodeAt(0) === 127,
1829
+ )
1830
+ )
1831
+ throw new HostError(
1832
+ "Search query must be 1..256 characters without controls.",
1833
+ );
1834
+ const matches: {
1835
+ swarm: string;
1836
+ alias: string | null;
1837
+ name: string;
1838
+ reference: string;
1839
+ targetCid: string;
1840
+ }[] = [];
1841
+ const searched: {
1842
+ configUrl: string;
1843
+ source: "cache" | "network";
1844
+ root: string;
1845
+ valueCid: string;
1846
+ verifiedAt: string;
1847
+ }[] = [];
1848
+ for (const swarm of swarms) {
1849
+ const header = await swarmHeader(context, swarm.cid);
1850
+ searched.push({
1851
+ configUrl: swarm.cid,
1852
+ source: header.source,
1853
+ root: header.head.root,
1854
+ valueCid: header.head.cid,
1855
+ verifiedAt: header.verifiedAt,
1856
+ });
1857
+ for (const name of Object.keys(header.snapshot.names).sort())
1858
+ if (name.toLowerCase().includes(query.toLowerCase()))
1859
+ matches.push({
1860
+ swarm: swarm.cid,
1861
+ alias: swarm.alias,
1862
+ name,
1863
+ reference: referenceFor(swarm.cid, name),
1864
+ targetCid: header.snapshot.names[name]!.toString(),
1865
+ });
1866
+ }
1867
+ return { matches, swarms: searched };
1868
+ }
1869
+ async function dependencies(
1870
+ store: IpfsStore,
1871
+ root: string,
1872
+ found = new Set<string>(),
1873
+ ): Promise<Set<string>> {
1874
+ if (found.has(root)) return found;
1875
+ if (found.size >= 256)
1876
+ throw new HostError("Publication dependency/history limit exceeded.");
1877
+ found.add(root);
1878
+ const bundle = await openBundle(CID.parse(root), {
1879
+ resolveCid: (cid) => store.block.get(cid.toString()),
1880
+ });
1881
+ if (bundle.schemaKey === (await encodeSchema(artifactType)).cid.toString()) {
1882
+ const node = parseArtifact(await typedJson(store, root, artifactType));
1883
+ await dependencies(store, node.value, found);
1884
+ if (node.previous) await dependencies(store, node.previous, found);
1885
+ } else if (bundle.schemaKey === appSchemaCid.toString()) {
1886
+ const app = object(
1887
+ JSON.parse(
1888
+ new TextDecoder().decode(
1889
+ await bytes(await bundle.readFile(bundle.manifest.entry), 64 * 1024),
1890
+ ),
1891
+ ) as unknown,
1892
+ "App",
1893
+ );
1894
+ if (app.source) {
1895
+ const source = object(app.source, "source");
1896
+ if (typeof source.cid !== "string")
1897
+ throw new HostError("Invalid App source association.");
1898
+ await dependencies(store, source.cid, found);
1899
+ }
1900
+ }
1901
+ return found;
1902
+ }
1903
+ export async function frozenPublicationClosure(
1904
+ store: IpfsStore,
1905
+ root: string,
1906
+ ): Promise<string[]> {
1907
+ const publications = new Set<string>(),
1908
+ content = new Set<string>();
1909
+ let current: string | undefined = root;
1910
+ while (current !== undefined) {
1911
+ if (publications.has(current) || publications.size >= 256)
1912
+ throw new HostError(
1913
+ "Frozen publication history exceeds limits or contains a cycle.",
1914
+ );
1915
+ publications.add(current);
1916
+ const publication = await readPublication(store, current);
1917
+ const snapshot = decodeSnapshot(
1918
+ await store.block.get(publication.state.toString()),
1919
+ );
1920
+ for (const target of Object.values(snapshot.names))
1921
+ await dependencies(store, target.toString(), content);
1922
+ current = publication.previous?.toString();
1923
+ }
1924
+ return [
1925
+ root,
1926
+ ...[...new Set([...publications, ...content])]
1927
+ .filter((cid) => cid !== root)
1928
+ .sort(),
1929
+ ];
1930
+ }
1931
+ export async function publish(
1932
+ context: SwarmContext,
1933
+ content: string,
1934
+ options: {
1935
+ swarm?: string;
1936
+ name?: string;
1937
+ expect?: string;
1938
+ snapshot?: boolean;
1939
+ },
1940
+ ): Promise<string> {
1941
+ if (!options.swarm)
1942
+ throw new HostError(
1943
+ "Publication requires a selected Swarm configuration URL or alias.",
1944
+ );
1945
+ const head = await pointer(context, options.swarm);
1946
+ const roots = await dependencies(context.store, content);
1947
+ if (!options.name) {
1948
+ if (options.expect || options.snapshot)
1949
+ throw new HostError("--expect/--snapshot require --name.");
1950
+ await head.read();
1951
+ await provideContent(
1952
+ context.store,
1953
+ [...roots],
1954
+ context.node!.api,
1955
+ context.fetch,
1956
+ context.node!.auth,
1957
+ );
1958
+ return content;
1959
+ }
1960
+ const name = formalName(options.name);
1961
+ if (options.snapshot && options.expect)
1962
+ throw new HostError("Snapshots cannot replace an occupied Name.");
1963
+ const expected = options.expect
1964
+ ? CID.parse(options.expect).toV1().toString()
1965
+ : undefined;
1966
+ if (expected)
1967
+ parseArtifact(await typedJson(context.store, expected, artifactType));
1968
+ const candidate = options.snapshot
1969
+ ? content
1970
+ : await jsonBundle(context.store, artifactType, {
1971
+ value: content,
1972
+ ...(expected ? { previous: expected } : {}),
1973
+ timestamp: new Date().toISOString(),
1974
+ });
1975
+ roots.add(candidate);
1976
+ if (expected)
1977
+ for (const root of await dependencies(context.store, expected))
1978
+ roots.add(root);
1979
+ for (let attempt = 0; attempt < 8; attempt++) {
1980
+ const currentHead = await head.read(),
1981
+ current = await readSnapshot(context.store, currentHead.root);
1982
+ if (
1983
+ (Object.hasOwn(current.names, name)
1984
+ ? current.names[name]?.toString()
1985
+ : undefined) !== expected
1986
+ )
1987
+ throw new HostError(
1988
+ `Edit conflict for ${name}; candidate ${candidate} remains retained. Choose an explicit baseline.`,
1989
+ 3,
1990
+ "EDIT_CONFLICT",
1991
+ "publication",
1992
+ );
1993
+ const next = await publication(
1994
+ context.store,
1995
+ await writeSnapshot(context.store, {
1996
+ ...current,
1997
+ names: { ...current.names, [name]: CID.parse(candidate) },
1998
+ }),
1999
+ currentHead.root,
2000
+ );
2001
+ await provideContent(
2002
+ context.store,
2003
+ [next, ...roots],
2004
+ context.node!.api,
2005
+ context.fetch,
2006
+ context.node!.auth,
2007
+ );
2008
+ withState(context, (state) => {
2009
+ state.invalidateSwarmHeader(options.swarm!);
2010
+ });
2011
+ try {
2012
+ await head.write(next, currentHead.cid, uniqueId());
2013
+ return candidate;
2014
+ } catch (cause) {
2015
+ if (!(cause instanceof ScopeApiError) || cause.status !== 412)
2016
+ throw new HostError(
2017
+ `HEAD publication unconfirmed: ${message(cause)}. Candidate ${candidate} remains retained; inspect HEAD before retry.`,
2018
+ 1,
2019
+ "HEAD_UNCONFIRMED",
2020
+ "publication",
2021
+ );
2022
+ }
2023
+ }
2024
+ throw new HostError(`HEAD is busy; candidate ${candidate} remains retained.`);
2025
+ }