@ipab/cli 0.1.0-rc.2 → 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 (102) hide show
  1. package/README.md +35 -14
  2. package/dist/app-authoring.d.ts.map +1 -1
  3. package/dist/app-authoring.js +11 -2
  4. package/dist/app-authoring.js.map +1 -1
  5. package/dist/app-definition.d.ts +52 -57
  6. package/dist/app-definition.d.ts.map +1 -1
  7. package/dist/app-definition.js +33 -38
  8. package/dist/app-definition.js.map +1 -1
  9. package/dist/app-templates.d.ts.map +1 -1
  10. package/dist/app-templates.js +2 -1
  11. package/dist/app-templates.js.map +1 -1
  12. package/dist/assembly.d.ts.map +1 -1
  13. package/dist/assembly.js +3 -4
  14. package/dist/assembly.js.map +1 -1
  15. package/dist/authoring.d.ts +3 -7
  16. package/dist/authoring.d.ts.map +1 -1
  17. package/dist/authoring.js +22 -12
  18. package/dist/authoring.js.map +1 -1
  19. package/dist/builtins/skill.ipab.car +0 -0
  20. package/dist/builtins/template.node.car +0 -0
  21. package/dist/builtins/template.web-app.car +0 -0
  22. package/dist/builtins.d.ts.map +1 -1
  23. package/dist/builtins.js +18 -2
  24. package/dist/builtins.js.map +1 -1
  25. package/dist/cli.d.ts.map +1 -1
  26. package/dist/cli.js +306 -116
  27. package/dist/cli.js.map +1 -1
  28. package/dist/config.d.ts +2 -1
  29. package/dist/config.d.ts.map +1 -1
  30. package/dist/config.js +19 -15
  31. package/dist/config.js.map +1 -1
  32. package/dist/content-provider.d.ts +1 -1
  33. package/dist/content-provider.d.ts.map +1 -1
  34. package/dist/content-provider.js +5 -2
  35. package/dist/content-provider.js.map +1 -1
  36. package/dist/get.d.ts.map +1 -1
  37. package/dist/get.js +34 -15
  38. package/dist/get.js.map +1 -1
  39. package/dist/kubo.d.ts +38 -0
  40. package/dist/kubo.d.ts.map +1 -0
  41. package/dist/kubo.js +528 -0
  42. package/dist/kubo.js.map +1 -0
  43. package/dist/pins.d.ts +3 -3
  44. package/dist/pins.js +1 -1
  45. package/dist/pins.js.map +1 -1
  46. package/dist/setup.d.ts +7 -0
  47. package/dist/setup.d.ts.map +1 -0
  48. package/dist/setup.js +22 -0
  49. package/dist/setup.js.map +1 -0
  50. package/dist/source-bundle.d.ts +3 -8
  51. package/dist/source-bundle.d.ts.map +1 -1
  52. package/dist/source-bundle.js +16 -11
  53. package/dist/source-bundle.js.map +1 -1
  54. package/dist/space.d.ts.map +1 -1
  55. package/dist/space.js +2 -2
  56. package/dist/space.js.map +1 -1
  57. package/dist/state.d.ts +4 -4
  58. package/dist/state.d.ts.map +1 -1
  59. package/dist/state.js +11 -12
  60. package/dist/state.js.map +1 -1
  61. package/dist/swarm-envelope.d.ts +36 -0
  62. package/dist/swarm-envelope.d.ts.map +1 -0
  63. package/dist/swarm-envelope.js +145 -0
  64. package/dist/swarm-envelope.js.map +1 -0
  65. package/dist/swarm-files.d.ts +5 -0
  66. package/dist/swarm-files.d.ts.map +1 -0
  67. package/dist/swarm-files.js +94 -0
  68. package/dist/swarm-files.js.map +1 -0
  69. package/dist/swarm.d.ts +117 -57
  70. package/dist/swarm.d.ts.map +1 -1
  71. package/dist/swarm.js +1033 -548
  72. package/dist/swarm.js.map +1 -1
  73. package/dist/template-definition.d.ts +47 -52
  74. package/dist/template-definition.d.ts.map +1 -1
  75. package/dist/template-definition.js +36 -41
  76. package/dist/template-definition.js.map +1 -1
  77. package/dist/template-source.d.ts +2 -0
  78. package/dist/template-source.d.ts.map +1 -1
  79. package/dist/template-source.js +4 -3
  80. package/dist/template-source.js.map +1 -1
  81. package/package.json +3 -3
  82. package/src/app-authoring.ts +22 -5
  83. package/src/app-definition.ts +33 -39
  84. package/src/app-templates.ts +9 -1
  85. package/src/assembly.ts +7 -4
  86. package/src/authoring.ts +31 -14
  87. package/src/builtins.ts +23 -2
  88. package/src/cli.ts +362 -139
  89. package/src/config.ts +22 -18
  90. package/src/content-provider.ts +5 -4
  91. package/src/get.ts +37 -15
  92. package/src/kubo.ts +691 -0
  93. package/src/pins.ts +1 -1
  94. package/src/setup.ts +21 -0
  95. package/src/source-bundle.ts +25 -12
  96. package/src/space.ts +2 -5
  97. package/src/state.ts +14 -13
  98. package/src/swarm-envelope.ts +255 -0
  99. package/src/swarm-files.ts +100 -0
  100. package/src/swarm.ts +1676 -837
  101. package/src/template-definition.ts +36 -41
  102. package/src/template-source.ts +10 -3
package/src/swarm.ts CHANGED
@@ -1,12 +1,11 @@
1
- import { mkdir, lstat, open, readFile, rename, unlink } from "node:fs/promises";
2
- import { join } from "node:path";
3
- import { randomUUID } from "node:crypto";
1
+ import { lstat, open, readFile } from "node:fs/promises";
2
+ import { createHash, randomBytes } from "node:crypto";
4
3
  import { stringify } from "yaml";
5
4
  import { CarBlockIterator } from "@ipld/car/iterator";
6
5
  import * as dagCbor from "@ipld/dag-cbor";
7
6
  import { CID } from "multiformats/cid";
8
7
  import { sha256 } from "multiformats/hashes/sha2";
9
- import { encodeSchema, openBundle, type BundleManifest } from "@ipab/bundle";
8
+ import { encodeSchema, openBundle, type BundleType } from "@ipab/bundle";
10
9
  import {
11
10
  encodeBundleCar,
12
11
  memoryTree,
@@ -14,118 +13,105 @@ import {
14
13
  } from "@ipab/bundle-builder";
15
14
  import type { IpfsStore } from "@ipab/ipfs-store";
16
15
  import {
17
- PointerClient,
18
- PointerApiError,
19
- type ReadResult,
20
- } from "@ipab/bundle/pointer/client";
16
+ ScopeClient,
17
+ ScopeApiError,
18
+ issueScopeCertificate,
19
+ uniqueId,
20
+ verifyScopeCertificate,
21
+ valueCid,
22
+ type Variable,
23
+ } from "@ipab/bundle/pointer/scope";
21
24
  import {
22
25
  canonicalService,
26
+ isCanonicalPublicKey,
23
27
  POINTER_ID_PATTERN,
24
28
  } from "@ipab/bundle/pointer/protocol";
25
- import {
26
- encodeCertificate,
27
- issueCertificate,
28
- verifyMemberCertificate,
29
- } from "@ipab/bundle/pointer/certificates";
30
29
  import {
31
30
  importPrivateKeyPkcs8,
32
31
  importPublicKeyRaw,
32
+ keyId,
33
33
  signEd25519,
34
34
  verifyEd25519,
35
- randomBytes,
36
- toBase64Url,
37
35
  } from "@ipab/bundle/pointer/crypto";
38
- import type { Certificate } from "@ipab/bundle/pointer/protocol";
39
36
  import { HostError, object, message } from "./errors.js";
40
- import {
41
- accountIdentity,
42
- protectedPath,
43
- secureNew,
44
- type Identity,
45
- } from "./identity.js";
46
- import { nodeError } from "./authoring.js";
37
+ import { accountIdentity, type Identity } from "./identity.js";
47
38
  import { bundleJson, provideContent } from "./content-provider.js";
48
39
  import { bytes, relativePath } from "./space.js";
49
- import { publicUrl } from "./config.js";
50
40
  import { appSchemaCid } from "./app-definition.js";
51
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";
52
67
 
53
- const cidField = { type: "string", minLength: 1, maxLength: 128 } as const;
54
- function definition(
55
- name: string,
56
- properties: Record<string, unknown>,
57
- required = Object.keys(properties),
58
- ): BundleManifest {
59
- return {
60
- name,
61
- description: "",
62
- entry: {
63
- path: "entry.json",
64
- contentType: "application/json",
65
- schema: {
66
- type: "object",
67
- additionalProperties: false,
68
- required,
69
- properties,
70
- },
71
- },
72
- };
68
+ export interface Member {
69
+ publicKey: string;
70
+ encryptionKey: string;
71
+ peerId: string;
72
+ profileId: string;
73
+ requestId: string;
74
+ approval: Envelope | null;
73
75
  }
74
- export const swarmType = definition("IPAB Swarm", {
75
- service: { type: "string" },
76
- variable: { type: "string" },
77
- owner: { type: "string" },
78
- });
79
- export const artifactType = definition(
80
- "IPAB Artifact",
81
- {
82
- value: cidField,
83
- previous: cidField,
84
- timestamp: { type: "string", format: "date-time" },
85
- },
86
- ["value", "timestamp"],
87
- );
88
- export const requestType = definition("IPAB Membership Request", {
89
- swarm: cidField,
90
- member: { type: "string" },
91
- requestId: { type: "string" },
92
- iat: { type: "integer" },
93
- exp: { type: "integer" },
94
- signature: { type: "string" },
95
- });
96
- export const responseType = definition("IPAB Membership Response", {
97
- swarm: cidField,
98
- request: cidField,
99
- certificate: { type: "object" },
100
- });
101
- export interface Descriptor {
102
- service: string;
103
- variable: string;
76
+ export interface Organization {
77
+ v: 1;
78
+ scopeId: string;
104
79
  owner: string;
80
+ name: string;
81
+ description: string;
82
+ headId: string;
83
+ epoch: number;
84
+ bootstrap: string[];
85
+ members: Member[];
105
86
  }
106
- interface MembershipRequest {
107
- swarm: string;
108
- member: string;
109
- requestId: string;
110
- iat: number;
111
- exp: number;
112
- signature: string;
113
- }
114
- export interface Artifact {
115
- value: string;
116
- previous?: string;
117
- timestamp: string;
87
+ export interface Profile {
88
+ name: string;
89
+ addresses: string[];
90
+ updatedAt: string;
118
91
  }
119
92
  export interface Snapshot {
120
- v: 1;
121
- properties: { name: string; description: string };
93
+ v: 2;
122
94
  names: Record<string, CID>;
123
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
+ }
124
111
  export interface SwarmContext {
125
112
  store: IpfsStore;
126
113
  env: NodeJS.ProcessEnv;
127
114
  stateDir: string;
128
- provider: string;
129
115
  fetch?: typeof fetch;
130
116
  pointerService?: string;
131
117
  pointerApiKey?: string;
@@ -133,6 +119,43 @@ export interface SwarmContext {
133
119
  cacheTtl?: number;
134
120
  forceRefresh?: boolean;
135
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;
136
159
  }
137
160
  function withState<T>(
138
161
  context: SwarmContext,
@@ -146,80 +169,560 @@ function withState<T>(
146
169
  state.close();
147
170
  }
148
171
  }
149
- async function requestPointer<T>(operation: () => Promise<T>): Promise<T> {
150
- for (let attempt = 0; ; attempt++) {
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
+ ) {
151
592
  try {
152
- return await operation();
593
+ await activate(context, record);
153
594
  } catch (cause) {
154
595
  if (
155
- attempt >= 2 ||
156
- !(cause instanceof Error) ||
157
- !["TypeError", "AbortError", "TimeoutError"].includes(cause.name)
596
+ cause instanceof ScopeApiError &&
597
+ [403, 404, 410].includes(cause.status)
158
598
  )
159
- throw cause;
599
+ return refresh(context, configUrl);
600
+ throw cause;
160
601
  }
161
602
  }
603
+ return record;
162
604
  }
163
- const serviceFetch: typeof fetch = (input, options) =>
164
- fetch(input, {
165
- ...options,
166
- redirect: "error",
167
- cache: "no-store",
168
- signal: AbortSignal.timeout(30_000),
169
- });
170
- interface BoundPointer {
171
- read(): Promise<ReadResult>;
172
- write(
173
- root: string,
174
- revision: string,
175
- idempotencyKey: string,
176
- ): Promise<ReadResult>;
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
+ };
177
618
  }
178
- function bindPointer(
619
+ export async function pointer(
179
620
  context: SwarmContext,
180
- data: Descriptor,
181
- identity: Identity,
182
- certificate?: Certificate,
183
- ): BoundPointer {
184
- const client = new PointerClient({
185
- service: data.service,
186
- signer: {
187
- privateKey: identity.privateKey,
188
- publicKey: identity.publicKey,
189
- ...(certificate ? { certificate } : {}),
190
- },
191
- fetch: context.fetch ?? serviceFetch,
192
- });
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
+ };
193
672
  return {
194
- read: () => requestPointer(() => client.read(data.variable)),
195
- write: (root, revision, idempotencyKey) =>
196
- requestPointer(() =>
197
- client.write(data.variable, root, {
198
- ifRevision: revision,
199
- idempotencyKey,
200
- }),
201
- ),
673
+ read: async () => headValue(await operation(false)),
674
+ write: (root, cid, key) => operation(true, root, cid, key),
202
675
  };
203
676
  }
204
- export async function typedJson<T>(
677
+ export async function typedJson(
205
678
  store: IpfsStore,
206
679
  cid: string,
207
- type: BundleManifest,
208
- ): Promise<T> {
680
+ type: BundleType,
681
+ ): Promise<unknown> {
209
682
  const { bundle, value } = await bundleJson(store, cid);
210
683
  if (bundle.schemaKey !== (await encodeSchema(type)).cid.toString())
211
- throw new HostError(`Expected exact ${type.name} Bundle type.`);
212
- return value as T;
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
+ };
213
706
  }
214
707
  export async function jsonBundle(
215
708
  store: IpfsStore,
216
- type: BundleManifest,
709
+ type: BundleType,
217
710
  value: unknown,
218
711
  ): Promise<string> {
219
712
  const encoded = await encodeBundleCar(
220
713
  memoryTree(
221
714
  new Map([
222
- [".bundle.yaml", new TextEncoder().encode(stringify(type))],
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))],
223
726
  ["entry.json", new TextEncoder().encode(`${JSON.stringify(value)}\n`)],
224
727
  ]),
225
728
  ),
@@ -234,722 +737,988 @@ export async function jsonBundle(
234
737
  await encoded.close();
235
738
  }
236
739
  }
237
- export async function descriptor(
238
- store: IpfsStore,
239
- cid: string,
240
- ): Promise<Descriptor> {
241
- const data = await typedJson<Descriptor>(store, cid, swarmType);
242
- return validateDescriptor(data);
243
- }
244
- async function validateDescriptor(data: Descriptor): Promise<Descriptor> {
245
- data.service = publicUrl(data.service).replace(/\/$/, "");
246
- const url = new URL(data.service);
247
- if (
248
- url.pathname !== "/" ||
249
- (url.protocol !== "https:" &&
250
- !["localhost", "127.0.0.1", "[::1]"].includes(url.hostname))
251
- )
252
- throw new HostError(
253
- "Swarm service must be an HTTPS origin or isolated loopback HTTP origin.",
254
- );
255
- if (!POINTER_ID_PATTERN.test(data.variable))
256
- throw new HostError("Invalid service pointer ID.");
257
- await importPublicKeyRaw(data.owner);
258
- return data;
259
- }
260
- const target = (data: Descriptor) =>
261
- `${data.service}/v1/pointers/${data.variable}`;
262
- const now = () => Math.floor(Date.now() / 1000);
263
- function requestMessage(
264
- data: Descriptor,
265
- request: Omit<MembershipRequest, "signature">,
266
- ): string {
267
- return `IPAB-MEMBERSHIP/1\n${target(data)}\n${JSON.stringify({ swarm: request.swarm, member: request.member, requestId: request.requestId, iat: request.iat, exp: request.exp })}`;
268
- }
269
- async function verifiedRequest(
270
- store: IpfsStore,
271
- cid: string,
272
- ): Promise<{ request: MembershipRequest; data: Descriptor }> {
273
- const request = await typedJson<MembershipRequest>(store, cid, requestType);
274
- const data = await descriptor(store, request.swarm);
275
- if (
276
- request.iat > now() + 60 ||
277
- request.exp <= now() ||
278
- request.exp <= request.iat ||
279
- request.exp - request.iat > 7 * 86400 ||
280
- !/^[A-Za-z0-9_-]{16,128}$/.test(request.requestId)
281
- )
282
- throw new HostError("Membership request is expired or invalid.");
283
- if (
284
- !(await verifyEd25519(
285
- await importPublicKeyRaw(request.member),
286
- request.signature,
287
- requestMessage(data, request),
288
- ))
289
- )
290
- throw new HostError("Membership request possession proof is invalid.");
291
- return { request, data };
292
- }
293
- async function credentialDirectory(context: SwarmContext): Promise<string> {
294
- const path = join(context.stateDir, "swarm-credentials");
295
- try {
296
- await lstat(path);
297
- } catch (cause) {
298
- if (!nodeError(cause, "ENOENT")) throw cause;
299
- await mkdir(path, { mode: 0o700 });
300
- await secureNew(path, true);
301
- }
302
- await protectedPath(path, true);
303
- return path;
304
- }
305
- async function save(
306
- context: SwarmContext,
307
- name: string,
308
- value: unknown,
309
- ): Promise<void> {
310
- const path = join(await credentialDirectory(context), name);
311
- const handle = await open(path, "wx", 0o600);
312
- try {
313
- await handle.writeFile(JSON.stringify(value));
314
- await handle.sync();
315
- } finally {
316
- await handle.close();
317
- }
318
- await secureNew(path);
319
- }
320
- async function saved(context: SwarmContext, name: string): Promise<unknown> {
321
- const path = join(await credentialDirectory(context), name);
322
- await protectedPath(path);
323
- return JSON.parse(await readFile(path, "utf8")) as unknown;
324
- }
325
- export async function pointer(
326
- context: SwarmContext,
327
- swarm: string,
328
- certificate?: Certificate,
329
- ): Promise<BoundPointer> {
330
- const data = await descriptor(context.store, swarm);
331
- const identity = await accountIdentity(context.env);
332
- return authenticatedPointer(context, swarm, data, identity, certificate);
333
- }
334
- async function authenticatedPointer(
335
- context: SwarmContext,
336
- swarm: string,
337
- data: Descriptor,
338
- identity: Identity,
339
- certificate?: Certificate,
340
- ): Promise<BoundPointer> {
341
- if (identity.publicKey === data.owner && certificate === undefined)
342
- return bindPointer(context, data, identity);
343
- const cert =
344
- certificate ??
345
- ((await saved(context, `${swarm}.json`)) as { certificate: Certificate })
346
- .certificate;
347
- const verified = await verifyMemberCertificate(
348
- encodeCertificate(cert),
349
- await importPublicKeyRaw(data.owner),
350
- data.owner,
351
- data.service,
352
- data.variable,
353
- now(),
354
- );
355
- if (verified.member !== identity.publicKey)
356
- throw new HostError(
357
- "Membership certificate does not match this account, swarm, owner or validity window.",
358
- );
359
- if (identity.publicKey === data.owner)
360
- return bindPointer(context, data, identity);
361
- return bindPointer(context, data, identity, cert);
362
- }
363
740
  export async function writeSnapshot(
364
741
  store: IpfsStore,
365
742
  snapshot: Snapshot,
366
743
  ): Promise<string> {
367
- const encoded = dagCbor.encode(snapshot);
368
- const cid = CID.createV1(dagCbor.code, await sha256.digest(encoded));
744
+ const encoded = dagCbor.encode(snapshot),
745
+ cid = CID.createV1(dagCbor.code, await sha256.digest(encoded));
369
746
  await store.put(cid, encoded);
370
747
  return cid.toString();
371
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
+ }
372
763
  export async function readSnapshot(
373
764
  store: IpfsStore,
374
765
  root: string,
375
766
  ): Promise<Snapshot> {
376
- const cid = CID.parse(root);
377
- if (cid.code !== dagCbor.code)
378
- throw new HostError("HEAD must reference a DAG-CBOR 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.");
379
776
  const publication = object(
380
777
  dagCbor.decode(await store.block.get(root)),
381
- "publication record",
778
+ "publication",
382
779
  );
383
- const stateCid = CID.asCID(publication.state);
780
+ const state = CID.asCID(publication.state);
781
+ const previous =
782
+ publication.previous === undefined
783
+ ? undefined
784
+ : CID.asCID(publication.previous);
384
785
  if (
385
786
  publication.v !== 1 ||
386
- !stateCid ||
787
+ !state ||
387
788
  Object.keys(publication).some(
388
- (key) => !["v", "state", "previous"].includes(key),
789
+ (k) => !["v", "state", "previous"].includes(k),
389
790
  ) ||
390
- (publication.previous !== undefined && !CID.asCID(publication.previous))
791
+ (publication.previous !== undefined && !previous)
391
792
  )
392
- throw new HostError(
393
- "HEAD must reference a verified publication linking State and optional previous publication.",
394
- );
395
- return decodeSnapshot(await store.block.get(stateCid.toString()));
793
+ throw new HostError("Invalid publication record.");
794
+ return { state, ...(previous ? { previous } : {}) };
396
795
  }
397
- function decodeSnapshot(bytes: Uint8Array): Snapshot {
398
- const value = object(dagCbor.decode(bytes), "swarm snapshot");
399
- const properties = object(value.properties, "swarm properties");
400
- const names = object(value.names, "swarm Names");
401
- if (
402
- value.v !== 1 ||
403
- typeof properties.name !== "string" ||
404
- typeof properties.description !== "string" ||
405
- Object.keys(value).some(
406
- (key) => !["v", "names", "properties"].includes(key),
407
- )
408
- )
409
- throw new HostError("Invalid swarm snapshot.");
410
- for (const [name, link] of Object.entries(names)) {
411
- formalName(name);
412
- if (!CID.asCID(link))
413
- throw new HostError("Snapshot Name targets must be CID links.");
414
- }
415
- return value as unknown as Snapshot;
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();
416
809
  }
417
810
  export interface SwarmHeader {
418
- head: ReadResult;
811
+ head: Variable & { root: string; etag: string };
419
812
  snapshot: Snapshot;
813
+ config: Organization;
420
814
  source: "cache" | "network";
421
815
  verifiedAt: string;
422
816
  }
423
817
  export async function swarmHeader(
424
818
  context: SwarmContext,
425
- swarm: string,
819
+ configUrl: string,
426
820
  force = context.forceRefresh ?? false,
427
821
  ): Promise<SwarmHeader> {
428
- swarm = CID.parse(swarm).toV1().toString();
429
- const identity = await accountIdentity(context.env);
822
+ canonicalSwarmUrl(configUrl);
823
+ let record = force
824
+ ? await refresh(context, configUrl)
825
+ : await readyMembership(context, configUrl);
430
826
  const ttl = context.cacheTtl ?? 300;
431
- if (!Number.isSafeInteger(ttl) || ttl < 0 || ttl > 86400)
432
- throw new HostError(
433
- "swarm.cacheTtl requires an integer number of seconds from 0 to 86400.",
434
- );
435
827
  const cached = force
436
828
  ? undefined
437
- : withState(context, (state) =>
438
- state.swarmHeader(identity.publicKey, swarm),
439
- );
440
- if (cached !== undefined) {
441
- const value = object(cached, "swarm header cache");
442
- if (
443
- typeof value.root !== "string" ||
444
- CID.parse(value.root).code !== dagCbor.code ||
445
- typeof value.revision !== "string" ||
446
- !value.revision ||
447
- typeof value.etag !== "string" ||
448
- typeof value.verifiedAt !== "number" ||
449
- !Number.isSafeInteger(value.verifiedAt) ||
450
- value.verifiedAt < 0 ||
451
- typeof value.snapshot !== "string" ||
452
- Buffer.from(value.snapshot, "base64").toString("base64") !==
453
- value.snapshot
454
- )
455
- throw new HostError(
456
- "Invalid persisted swarm header cache; retry with --force to replace it.",
457
- );
458
- const snapshot = decodeSnapshot(Buffer.from(value.snapshot, "base64"));
459
- const cachedDescriptor = object(
460
- value.descriptor,
461
- "cached swarm descriptor",
462
- );
463
- if (
464
- typeof cachedDescriptor.service !== "string" ||
465
- typeof cachedDescriptor.variable !== "string" ||
466
- typeof cachedDescriptor.owner !== "string"
467
- )
468
- throw new HostError(
469
- "Invalid cached swarm descriptor; retry with --force to replace it.",
470
- );
471
- const data = await validateDescriptor({
472
- service: cachedDescriptor.service,
473
- variable: cachedDescriptor.variable,
474
- owner: cachedDescriptor.owner,
475
- });
476
- const age = Date.now() - value.verifiedAt;
477
- if (age >= 0 && age < ttl * 1000) {
478
- await authenticatedPointer(context, swarm, data, identity);
479
- return {
480
- head: { root: value.root, revision: value.revision, etag: value.etag },
481
- snapshot,
482
- source: "cache",
483
- verifiedAt: new Date(value.verifiedAt).toISOString(),
484
- };
485
- }
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);
486
860
  }
487
- const data = await descriptor(context.store, swarm);
488
- const client = await authenticatedPointer(context, swarm, data, identity);
489
- context.diagnostic?.(`Refreshing swarm HEAD ${swarm}...`);
490
- const head = await client.read();
491
- const snapshot = await readSnapshot(context.store, head.root);
492
- const verifiedAt = Date.now();
861
+ const current = await local(context, configUrl),
862
+ verifiedAt = Date.now();
493
863
  withState(context, (state) => {
494
- state.saveSwarmHeader(identity.publicKey, swarm, {
495
- ...head,
496
- descriptor: data,
864
+ state.saveSwarmHeader(record.account, configUrl, {
865
+ head,
497
866
  snapshot: Buffer.from(dagCbor.encode(snapshot)).toString("base64"),
498
867
  verifiedAt,
868
+ headId: current.config!.headId,
499
869
  });
500
870
  });
501
871
  return {
502
872
  head,
503
873
  snapshot,
874
+ config: current.config!,
504
875
  source: "network",
505
876
  verifiedAt: new Date(verifiedAt).toISOString(),
506
877
  };
507
878
  }
508
879
  export async function addSwarm(
509
880
  context: SwarmContext,
510
- swarm: string,
881
+ url: string,
511
882
  alias?: string,
512
883
  ): Promise<void> {
513
- swarm = CID.parse(swarm).toV1().toString();
514
- if (alias !== undefined)
515
- withState(context, (state) => {
516
- state.checkSwarmAlias(alias, swarm);
517
- });
518
- await swarmHeader(context, swarm, true);
519
- withState(context, (state) => state.registerSwarm(swarm, alias));
884
+ canonicalSwarmUrl(url);
885
+ await readyMembership(context, url);
886
+ withState(context, (state) => state.registerSwarm(url, alias));
520
887
  }
521
- export async function updateSwarm(
522
- context: SwarmContext,
523
- swarm: string,
524
- changes: Partial<Snapshot["properties"]>,
525
- ): Promise<{
526
- cid: string;
527
- root: string;
528
- revision: string;
529
- properties: Snapshot["properties"];
530
- }> {
531
- if (changes.name === undefined && changes.description === undefined)
532
- throw new HostError("swarm update requires --name or --description.", 2);
533
- swarm = CID.parse(swarm).toV1().toString();
534
- const client = await pointer(context, swarm);
535
- for (let attempt = 0; attempt < 8; attempt++) {
536
- const head = await client.read();
537
- const current = await readSnapshot(context.store, head.root);
538
- const properties = {
539
- ...current.properties,
540
- ...(changes.name !== undefined ? { name: changes.name } : {}),
541
- ...(changes.description !== undefined
542
- ? { description: changes.description }
543
- : {}),
544
- };
545
- const state = await writeSnapshot(context.store, {
546
- ...current,
547
- properties,
548
- });
549
- const next = await publication(context.store, state, head.root);
550
- await provideContent(
551
- context.store,
552
- [next],
553
- context.provider,
554
- context.fetch,
555
- );
556
- withState(context, (state) => {
557
- state.invalidateSwarmHeader(swarm);
558
- });
559
- try {
560
- const written = await client.write(
561
- next,
562
- head.revision,
563
- toBase64Url(randomBytes(18)),
564
- );
565
- return {
566
- cid: swarm,
567
- root: written.root,
568
- revision: written.revision,
569
- properties,
570
- };
571
- } catch (cause) {
572
- if (!(cause instanceof PointerApiError) || cause.status !== 412)
573
- throw new HostError(
574
- `Swarm information update failed or its result is unknown: ${message(cause)}. Publication ${next} remains retained; authenticate swarm status before retrying.`,
575
- 1,
576
- "HEAD_UNCONFIRMED",
577
- "publication",
578
- );
579
- context.diagnostic?.(
580
- "Swarm HEAD changed; retrying information update with the latest Names and properties.",
581
- );
582
- }
583
- }
584
- throw new HostError(
585
- "Swarm HEAD is busy; information update could not complete. Retry later.",
586
- 1,
587
- "HEAD_BUSY",
588
- "publication",
589
- );
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;
590
901
  }
591
- export async function searchNames(
902
+ export async function createSwarm(
592
903
  context: SwarmContext,
593
- query: string,
594
- swarms: readonly { cid: string; alias: string | null }[],
595
- ) {
904
+ options: {
905
+ service?: string;
906
+ resume?: string;
907
+ properties?: { name: string; description: string };
908
+ alias?: string;
909
+ addresses?: string[];
910
+ } = {},
911
+ ): Promise<string> {
596
912
  if (
597
- !query ||
598
- query.length > 256 ||
599
- [...query].some((character) => {
600
- const code = character.charCodeAt(0);
601
- return code < 32 || code === 127;
602
- })
913
+ (options.properties?.name.length ?? 0) > 256 ||
914
+ (options.properties?.description.length ?? 0) > 2048 ||
915
+ (options.addresses?.length ?? 0) > 16
603
916
  )
604
917
  throw new HostError(
605
- "Search query must be 1..256 characters without control characters.",
606
- 2,
918
+ "Organization name/description or address limit exceeded.",
607
919
  );
608
- const matches: {
609
- swarm: string;
610
- alias: string | null;
611
- name: string;
612
- reference: string;
613
- targetCid: string;
614
- }[] = [];
615
- const searched: {
616
- cid: string;
617
- source: "cache" | "network";
618
- root: string;
619
- revision: string;
620
- verifiedAt: string;
621
- }[] = [];
622
- for (const swarm of [...swarms].sort((a, b) =>
623
- a.cid < b.cid ? -1 : a.cid > b.cid ? 1 : 0,
624
- )) {
625
- let header: SwarmHeader;
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);
626
961
  try {
627
- header = await swarmHeader(context, swarm.cid);
628
- } catch (cause) {
629
- throw new HostError(
630
- `Could not search swarm "${swarm.alias ?? swarm.cid}": ${message(cause)}. Search was not completed.`,
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),
631
969
  );
632
- }
633
- searched.push({
634
- cid: swarm.cid,
635
- source: header.source,
636
- root: header.head.root,
637
- revision: header.head.revision,
638
- verifiedAt: header.verifiedAt,
639
- });
640
- for (const name of Object.keys(header.snapshot.names).sort())
641
- if (name.toLowerCase().includes(query.toLowerCase()))
642
- matches.push({
643
- swarm: swarm.cid,
644
- alias: swarm.alias,
645
- name,
646
- reference: `ipab://${CID.parse(swarm.cid).toV1().toString()}/${name
647
- .split("/")
648
- .map((segment) =>
649
- encodeURIComponent(segment).replace(
650
- /[!'()*]/g,
651
- (character) =>
652
- `%${character.charCodeAt(0).toString(16).toUpperCase()}`,
653
- ),
654
- )
655
- .join("/")}`,
656
- targetCid: header.snapshot.names[name]!.toString(),
657
- });
658
- }
659
- return { matches, swarms: searched };
660
- }
661
- async function publication(
662
- store: IpfsStore,
663
- state: string,
664
- previous?: string,
665
- ): Promise<string> {
666
- const bytes = dagCbor.encode({
667
- v: 1,
668
- state: CID.parse(state),
669
- ...(previous ? { previous: CID.parse(previous) } : {}),
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
+ }
670
1059
  });
671
- const cid = CID.createV1(dagCbor.code, await sha256.digest(bytes));
672
- await store.put(cid, bytes);
673
- return cid.toString();
674
1060
  }
675
- async function saveCreation(
1061
+ const requestMessage = (
1062
+ request: Omit<MembershipRequest, "signature" | "peerSignature">,
1063
+ ) => JSON.stringify(["IPAB-REQUEST/1", request]);
1064
+ export async function exportRequest(
676
1065
  context: SwarmContext,
677
- operation: string,
678
- record: unknown,
679
- ): Promise<void> {
680
- const directory = await credentialDirectory(context);
681
- const target = join(directory, `creation-${operation}.json`);
682
- const temporary = join(directory, `.creation-${randomUUID()}.tmp`);
683
- const handle = await open(temporary, "wx", 0o600);
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);
684
1072
  try {
685
- await secureNew(temporary);
686
- await handle.writeFile(JSON.stringify(record));
1073
+ await handle.writeFile(`${JSON.stringify(record.request, null, 2)}\n`);
687
1074
  await handle.sync();
688
- await handle.close();
689
- await rename(temporary, target);
690
1075
  } finally {
691
1076
  await handle.close();
692
- await unlink(temporary).catch((cause: unknown) => {
693
- if (!nodeError(cause, "ENOENT"))
694
- return Promise.reject(
695
- cause instanceof Error
696
- ? cause
697
- : new HostError("Owned creation temporary-file cleanup failed."),
698
- );
699
- return undefined;
700
- });
701
1077
  }
1078
+ return record.request.id;
702
1079
  }
703
- export async function createSwarm(
1080
+ export async function requestMembership(
704
1081
  context: SwarmContext,
1082
+ url: string,
705
1083
  options: {
706
- service?: string;
707
- resume?: string;
708
- properties?: { name: string; description: string };
1084
+ ownerFingerprint: string;
1085
+ name?: string;
709
1086
  alias?: string;
710
- } = {},
1087
+ output?: string;
1088
+ },
711
1089
  ): Promise<string> {
712
- if (options.alias !== undefined && options.resume === undefined)
713
- withState(context, (state) => {
714
- state.checkSwarmAlias(options.alias!);
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,
715
1154
  });
716
- const cfg = {
717
- service: context.pointerService,
718
- apiKey: context.pointerApiKey,
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,
719
1222
  };
720
- if (!cfg.service || !cfg.apiKey)
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
+ )
721
1235
  throw new HostError(
722
- "Configure protected pointers.service and pointers.apiKey via safe stdin before creating a swarm.",
1236
+ "Request member or PeerID possession proof is invalid.",
723
1237
  );
724
- if (options.service && canonicalService(options.service) !== cfg.service)
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)
725
1271
  throw new HostError(
726
- "Creation API key cannot be sent outside its explicitly configured origin.",
1272
+ "Only the pinned Owner can manage membership or organization configuration.",
727
1273
  );
728
- const identity = await accountIdentity(context.env, true);
729
- const operation = options.resume ?? toBase64Url(randomBytes(18));
730
- if (!/^[A-Za-z0-9_-]{16,128}$/.test(operation))
731
- throw new HostError("Invalid saved creation operation.");
732
- let record: {
733
- origin: string;
734
- owner: string;
735
- root: string;
736
- createdAt: number;
737
- id?: string;
738
- cid?: string;
739
- };
740
- if (options.resume) {
741
- const value = object(
742
- await saved(context, `creation-${operation}.json`),
743
- "saved creation",
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`,
744
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
+ }
745
1332
  if (
746
- value.origin !== cfg.service ||
747
- value.owner !== identity.publicKey ||
748
- typeof value.root !== "string" ||
749
- !Number.isSafeInteger(value.createdAt) ||
750
- (value.id !== undefined && typeof value.id !== "string") ||
751
- (value.cid !== undefined && typeof value.cid !== "string")
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
752
1345
  )
753
1346
  throw new HostError(
754
- "Saved creation does not match this account and configured service.",
1347
+ "Owner local keys are not synchronized with this organization epoch.",
755
1348
  );
756
- record = value as typeof record;
757
- if (options.alias !== undefined)
758
- withState(context, (state) => {
759
- state.checkSwarmAlias(options.alias!, record.cid);
760
- });
761
- if (!record.id && Date.now() - record.createdAt >= 10 * 60 * 1000)
762
- throw new HostError(
763
- "Unconfirmed creation is beyond the service's minimum idempotency window. Ask the operator to recover it; do not allocate another pointer.",
1349
+ if (!operation.profileId) {
1350
+ const previousMember = fetched.config.members.find(
1351
+ (m) => m.publicKey === request.member,
764
1352
  );
765
- } else {
766
- const state = await writeSnapshot(context.store, {
767
- v: 1,
768
- properties: options.properties ?? { name: "", description: "" },
769
- names: {},
770
- });
771
- record = {
772
- origin: cfg.service,
773
- owner: identity.publicKey,
774
- root: await publication(context.store, state),
775
- createdAt: Date.now(),
776
- };
777
- await saveCreation(context, operation, record);
778
- }
779
- try {
780
- await provideContent(
781
- context.store,
782
- [record.root],
783
- context.provider,
784
- context.fetch,
785
- );
786
- if (!record.id) {
787
- const client = new PointerClient({
788
- service: cfg.service,
789
- apiKey: cfg.apiKey,
790
- signer: {
791
- privateKey: identity.privateKey,
792
- publicKey: identity.publicKey,
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],
793
1403
  },
794
- fetch: context.fetch ?? serviceFetch,
795
- });
796
- record.id = (
797
- await requestPointer(() =>
798
- client.create(record.root, { idempotencyKey: operation }),
799
- )
800
- ).id;
801
- await saveCreation(context, operation, record);
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();
802
1415
  }
803
- const data: Descriptor = {
804
- service: cfg.service,
805
- variable: record.id,
806
- owner: identity.publicKey,
807
- };
808
- const cid = await jsonBundle(context.store, swarmType, data);
809
- await provideContent(
810
- context.store,
811
- [cid, record.root],
812
- context.provider,
813
- context.fetch,
814
- );
815
- record.cid = cid;
816
- await saveCreation(context, operation, record);
817
- await addSwarm(context, cid, options.alias);
818
- return cid;
819
- } catch (cause) {
820
- throw new HostError(
821
- `Swarm creation was not confirmed: ${message(cause)}. ${record.id ? `Pointer ${record.id} is saved.` : "The same creation idempotency key is saved."} Recover with ipab swarm create --resume ${operation}; do not allocate a replacement pointer.`,
822
- 1,
823
- "CREATE_UNCONFIRMED",
824
- "authorization",
825
- );
826
- }
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
+ });
827
1431
  }
828
- export async function requestMembership(
1432
+ export async function updateSwarm(
829
1433
  context: SwarmContext,
830
- swarm: string,
831
- ): Promise<string> {
832
- const identity = await accountIdentity(context.env, true);
833
- const data = await descriptor(context.store, swarm);
834
- const body = {
835
- swarm: CID.parse(swarm).toV1().toString(),
836
- member: identity.publicKey,
837
- requestId: toBase64Url(randomBytes(18)),
838
- iat: now(),
839
- exp: now() + 7 * 86400,
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 },
840
1462
  };
841
- const request: MembershipRequest = {
842
- ...body,
843
- signature: await signEd25519(
844
- await importPrivateKeyPkcs8(identity.privateKey),
845
- requestMessage(data, body),
846
- ),
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(),
847
1492
  };
848
- const cid = await jsonBundle(context.store, requestType, request);
849
- await provideContent(
850
- context.store,
851
- [cid, swarm],
852
- context.provider,
853
- context.fetch,
1493
+ await api.write(
1494
+ c.scopeId,
1495
+ member.profileId,
1496
+ profile,
1497
+ existing.cid,
1498
+ uniqueId(),
854
1499
  );
855
- await save(context, `${cid}.pending.json`, {
856
- swarm,
857
- member: identity.publicKey,
858
- });
859
- return cid;
1500
+ return profile;
860
1501
  }
861
- export async function approveMembership(
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(
862
1520
  context: SwarmContext,
863
- requestCid: string,
864
- seconds = 7 * 86400,
865
- ): Promise<string> {
866
- if (!Number.isSafeInteger(seconds) || seconds < 60 || seconds > 30 * 86400)
867
- throw new HostError("Certificate duration must be 60 seconds to 30 days.");
868
- const { request, data } = await verifiedRequest(context.store, requestCid);
869
- const identity = await accountIdentity(context.env);
870
- if (identity.publicKey !== data.owner)
871
- throw new HostError("Only this swarm's owner can approve members.");
872
- const certificate = await issueCertificate(
873
- {
874
- v: 2,
875
- service: data.service,
876
- pointerId: data.variable,
877
- owner: data.owner,
878
- member: request.member,
879
- cid: toBase64Url(randomBytes(16)),
880
- iat: now(),
881
- exp: now() + seconds,
882
- },
883
- await importPrivateKeyPkcs8(identity.privateKey),
884
- );
885
- const cid = await jsonBundle(context.store, responseType, {
886
- swarm: request.swarm,
887
- request: CID.parse(requestCid).toV1().toString(),
888
- certificate,
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);
889
1543
  });
890
- await provideContent(
891
- context.store,
892
- [cid, requestCid, request.swarm],
893
- context.provider,
894
- context.fetch,
895
- );
896
- return cid;
1544
+ await resumeRemoval(context, url);
897
1545
  }
898
- export async function joinSwarm(
1546
+ export async function resumeRemoval(
899
1547
  context: SwarmContext,
900
- responseCid: string,
901
- alias?: string,
902
- ): Promise<string> {
903
- const response = await typedJson<{
904
- swarm: string;
905
- request: string;
906
- certificate: Certificate;
907
- }>(context.store, responseCid, responseType);
908
- const { request } = await verifiedRequest(context.store, response.request);
909
- const identity = await accountIdentity(context.env);
910
- const pending = object(
911
- await saved(context, `${response.request}.pending.json`),
912
- "pending request",
913
- );
914
- if (
915
- request.swarm !== response.swarm ||
916
- request.member !== identity.publicKey ||
917
- pending.swarm !== response.swarm ||
918
- pending.member !== identity.publicKey
919
- )
920
- throw new HostError(
921
- "Response does not match this account's exact pending request and target swarm.",
922
- );
923
- const client = await pointer(context, response.swarm, response.certificate);
924
- if (alias !== undefined)
925
- withState(context, (state) => {
926
- state.checkSwarmAlias(alias, response.swarm);
927
- });
928
- await client.read();
929
- try {
930
- await save(context, `${response.swarm}.json`, {
931
- certificate: response.certificate,
932
- request: response.request,
933
- });
934
- } catch (cause) {
935
- if (!nodeError(cause, "EEXIST")) throw cause;
936
- const previous = object(
937
- await saved(context, `${response.swarm}.json`),
938
- "membership",
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)}`,
939
1556
  );
940
- if (previous.request !== response.request)
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) {
941
1717
  throw new HostError(
942
- "An existing membership differs; explicit renewal is outside this MVP.",
1718
+ `Organization switch incomplete (old HEAD is never unfrozen): ${message(cause)}. Owner must run swarm resume ${url}.`,
943
1719
  );
944
- }
945
- try {
946
- await addSwarm(context, response.swarm, alias);
947
- } catch (cause) {
948
- throw new HostError(
949
- `Membership certificate was saved, but swarm registration failed: ${message(cause)}. Retry the same response or run ipab swarm add ${response.swarm}.`,
950
- );
951
- }
952
- return response.swarm;
1720
+ }
1721
+ });
953
1722
  }
954
1723
  export function formalName(name: string): string {
955
1724
  relativePath(name);
@@ -961,36 +1730,35 @@ export function parseNameReference(
961
1730
  reference: string,
962
1731
  ): { swarm?: string; name: string } | undefined {
963
1732
  if (/^name:/i.test(reference))
964
- throw new HostError(
965
- "name: references are no longer supported. Use ipab://SWARM_CID_OR_ALIAS/PATH or ipab:///PATH.",
966
- 2,
967
- );
1733
+ throw new HostError("name: is unsupported; use ipab://ALIAS/PATH.");
968
1734
  if (!/^ipab:/i.test(reference)) return undefined;
969
1735
  const match = /^ipab:\/\/([^/]*)\/([^?#\s]*)$/i.exec(reference);
970
- if (!match || (match[1] && !/^[A-Za-z0-9][A-Za-z0-9._-]*$/.test(match[1])))
1736
+ if (!match)
971
1737
  throw new HostError(
972
- "Invalid IPAB URI. Use ipab://SWARM_CID_OR_ALIAS/PATH or ipab:///PATH without credentials, port, query or fragment; percent-encode path segments.",
973
- 2,
1738
+ "Invalid IPAB URI; percent-encode the configuration URL authority and each path segment.",
974
1739
  );
1740
+ const authority = decodeURIComponent(match[1]!);
1741
+ if (authority && !/^[A-Za-z0-9][A-Za-z0-9._-]*$/.test(authority))
1742
+ canonicalSwarmUrl(authority);
975
1743
  const segments = match[2]!.split("/").map((segment) => {
976
- let decoded: string;
977
- try {
978
- decoded = decodeURIComponent(segment);
979
- } catch {
980
- throw new HostError("Invalid percent encoding in IPAB URI path.", 2);
981
- }
1744
+ const decoded = decodeURIComponent(segment);
982
1745
  if (decoded.includes("/"))
983
- throw new HostError(
984
- "Encoded path separators are not allowed in IPAB URIs.",
985
- 2,
986
- );
1746
+ throw new HostError("Encoded path separators are unsupported.");
987
1747
  return decoded;
988
1748
  });
989
1749
  return {
990
- ...(match[1] ? { swarm: match[1] } : {}),
1750
+ ...(authority ? { swarm: authority } : {}),
991
1751
  name: formalName(segments.join("/")),
992
1752
  };
993
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
+ }
994
1762
  export async function resolveReference(
995
1763
  context: SwarmContext,
996
1764
  reference: string,
@@ -998,34 +1766,35 @@ export async function resolveReference(
998
1766
  local: (reference: string) => string,
999
1767
  raw = false,
1000
1768
  ): Promise<{ targetCid: string; cid: string }> {
1001
- let targetCid: string;
1002
1769
  const shared = parseNameReference(reference);
1770
+ let targetCid: string;
1003
1771
  if (shared) {
1004
- const authority = shared.swarm;
1005
- const selectedSwarm = authority
1006
- ? withState(context, (state) => state.resolveSwarm(authority))
1772
+ const selected = shared.swarm
1773
+ ? withState(context, (state) => state.resolveSwarm(shared.swarm!))
1007
1774
  : swarm;
1008
- if (!selectedSwarm)
1775
+ if (!selected)
1009
1776
  throw new HostError(
1010
- "Shared Names require a swarm in the URI, --swarm CID_OR_ALIAS or swarm.default. Run ipab swarm use CID_OR_ALIAS.",
1777
+ "Select a configuration URL/alias using --swarm or swarm use.",
1011
1778
  );
1012
- const name = shared.name;
1013
- let header = await swarmHeader(context, selectedSwarm);
1014
- const lookup = () =>
1015
- Object.hasOwn(header.snapshot.names, name)
1016
- ? header.snapshot.names[name]
1017
- : undefined;
1018
- let link = lookup();
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;
1019
1783
  if (!link && header.source === "cache") {
1020
- header = await swarmHeader(context, selectedSwarm, true);
1021
- link = lookup();
1784
+ header = await swarmHeader(context, selected, true);
1785
+ link = Object.hasOwn(header.snapshot.names, shared.name)
1786
+ ? header.snapshot.names[shared.name]
1787
+ : undefined;
1022
1788
  }
1023
1789
  if (!link)
1024
1790
  throw new HostError(
1025
- `Formal Name "${name}" is not present in this swarm after refreshing HEAD.`,
1791
+ `Formal Name "${shared.name}" was not found after refreshing HEAD.`,
1026
1792
  );
1027
1793
  targetCid = link.toString();
1028
- } else targetCid = local(reference);
1794
+ } else {
1795
+ if (swarm) await readyMembership(context, swarm);
1796
+ targetCid = local(reference);
1797
+ }
1029
1798
  let cid = targetCid;
1030
1799
  const visited = new Set<string>();
1031
1800
  for (let depth = 0; !raw; depth++) {
@@ -1039,15 +1808,64 @@ export async function resolveReference(
1039
1808
  });
1040
1809
  if (bundle.schemaKey !== (await encodeSchema(artifactType)).cid.toString())
1041
1810
  break;
1042
- const artifact = await typedJson<Artifact>(
1043
- context.store,
1044
- cid,
1045
- artifactType,
1046
- );
1047
- cid = CID.parse(artifact.value).toV1().toString();
1811
+ cid = CID.parse(
1812
+ parseArtifact(await typedJson(context.store, cid, artifactType)).value,
1813
+ )
1814
+ .toV1()
1815
+ .toString();
1048
1816
  }
1049
1817
  return { targetCid, cid };
1050
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
+ }
1051
1869
  async function dependencies(
1052
1870
  store: IpfsStore,
1053
1871
  root: string,
@@ -1061,23 +1879,20 @@ async function dependencies(
1061
1879
  resolveCid: (cid) => store.block.get(cid.toString()),
1062
1880
  });
1063
1881
  if (bundle.schemaKey === (await encodeSchema(artifactType)).cid.toString()) {
1064
- const node = await typedJson<Artifact>(store, root, artifactType);
1882
+ const node = parseArtifact(await typedJson(store, root, artifactType));
1065
1883
  await dependencies(store, node.value, found);
1066
1884
  if (node.previous) await dependencies(store, node.previous, found);
1067
1885
  } else if (bundle.schemaKey === appSchemaCid.toString()) {
1068
1886
  const app = object(
1069
1887
  JSON.parse(
1070
1888
  new TextDecoder().decode(
1071
- await bytes(
1072
- await bundle.readFile(bundle.manifest.entry.path),
1073
- 64 * 1024,
1074
- ),
1889
+ await bytes(await bundle.readFile(bundle.manifest.entry), 64 * 1024),
1075
1890
  ),
1076
1891
  ) as unknown,
1077
1892
  "App",
1078
1893
  );
1079
1894
  if (app.source) {
1080
- const source = object(app.source, "App source");
1895
+ const source = object(app.source, "source");
1081
1896
  if (typeof source.cid !== "string")
1082
1897
  throw new HostError("Invalid App source association.");
1083
1898
  await dependencies(store, source.cid, found);
@@ -1085,6 +1900,34 @@ async function dependencies(
1085
1900
  }
1086
1901
  return found;
1087
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
+ }
1088
1931
  export async function publish(
1089
1932
  context: SwarmContext,
1090
1933
  content: string,
@@ -1095,32 +1938,33 @@ export async function publish(
1095
1938
  snapshot?: boolean;
1096
1939
  },
1097
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);
1098
1946
  const roots = await dependencies(context.store, content);
1099
1947
  if (!options.name) {
1100
1948
  if (options.expect || options.snapshot)
1101
1949
  throw new HostError("--expect/--snapshot require --name.");
1950
+ await head.read();
1102
1951
  await provideContent(
1103
1952
  context.store,
1104
1953
  [...roots],
1105
- context.provider,
1954
+ context.node!.api,
1106
1955
  context.fetch,
1956
+ context.node!.auth,
1107
1957
  );
1108
1958
  return content;
1109
1959
  }
1110
1960
  const name = formalName(options.name);
1111
- if (!options.swarm)
1112
- throw new HostError(
1113
- "Named publication requires --swarm CID or swarm.default.",
1114
- );
1115
1961
  if (options.snapshot && options.expect)
1116
- throw new HostError(
1117
- "Ordinary named snapshots cannot replace an occupied Name.",
1118
- );
1962
+ throw new HostError("Snapshots cannot replace an occupied Name.");
1119
1963
  const expected = options.expect
1120
1964
  ? CID.parse(options.expect).toV1().toString()
1121
1965
  : undefined;
1122
1966
  if (expected)
1123
- await typedJson<Artifact>(context.store, expected, artifactType);
1967
+ parseArtifact(await typedJson(context.store, expected, artifactType));
1124
1968
  const candidate = options.snapshot
1125
1969
  ? content
1126
1970
  : await jsonBundle(context.store, artifactType, {
@@ -1132,55 +1976,50 @@ export async function publish(
1132
1976
  if (expected)
1133
1977
  for (const root of await dependencies(context.store, expected))
1134
1978
  roots.add(root);
1135
- await provideContent(
1136
- context.store,
1137
- [...roots],
1138
- context.provider,
1139
- context.fetch,
1140
- );
1141
- const client = await pointer(context, options.swarm);
1142
1979
  for (let attempt = 0; attempt < 8; attempt++) {
1143
- const head = await client.read();
1144
- const current = await readSnapshot(context.store, head.root);
1980
+ const currentHead = await head.read(),
1981
+ current = await readSnapshot(context.store, currentHead.root);
1145
1982
  if (
1146
1983
  (Object.hasOwn(current.names, name)
1147
1984
  ? current.names[name]?.toString()
1148
1985
  : undefined) !== expected
1149
1986
  )
1150
1987
  throw new HostError(
1151
- `Edit conflict for ${name}; candidate ${candidate} and content ${content} remain retained. Refresh the Name and explicitly choose a baseline.`,
1988
+ `Edit conflict for ${name}; candidate ${candidate} remains retained. Choose an explicit baseline.`,
1152
1989
  3,
1153
1990
  "EDIT_CONFLICT",
1154
1991
  "publication",
1155
1992
  );
1156
- const state = await writeSnapshot(context.store, {
1157
- ...current,
1158
- names: { ...current.names, [name]: CID.parse(candidate) },
1159
- });
1160
- const next = await publication(context.store, state, head.root);
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
+ );
1161
2001
  await provideContent(
1162
2002
  context.store,
1163
2003
  [next, ...roots],
1164
- context.provider,
2004
+ context.node!.api,
1165
2005
  context.fetch,
2006
+ context.node!.auth,
1166
2007
  );
2008
+ withState(context, (state) => {
2009
+ state.invalidateSwarmHeader(options.swarm!);
2010
+ });
1167
2011
  try {
1168
- withState(context, (state) => {
1169
- state.invalidateSwarmHeader(options.swarm!);
1170
- });
1171
- await client.write(next, head.revision, toBase64Url(randomBytes(18)));
2012
+ await head.write(next, currentHead.cid, uniqueId());
1172
2013
  return candidate;
1173
2014
  } catch (cause) {
1174
- if (!(cause instanceof PointerApiError) || cause.status !== 412)
2015
+ if (!(cause instanceof ScopeApiError) || cause.status !== 412)
1175
2016
  throw new HostError(
1176
- `HEAD update failed or its result is unknown: ${message(cause)}. Candidate ${candidate} remains retained; authenticate swarm status before retrying.`,
2017
+ `HEAD publication unconfirmed: ${message(cause)}. Candidate ${candidate} remains retained; inspect HEAD before retry.`,
1177
2018
  1,
1178
2019
  "HEAD_UNCONFIRMED",
1179
2020
  "publication",
1180
2021
  );
1181
2022
  }
1182
2023
  }
1183
- throw new HostError(
1184
- `HEAD is busy; candidate ${candidate} remains retained. Retry the same explicit Name baseline.`,
1185
- );
2024
+ throw new HostError(`HEAD is busy; candidate ${candidate} remains retained.`);
1186
2025
  }