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

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 (107) hide show
  1. package/README.md +40 -13
  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 +367 -124
  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 +29 -16
  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/identity.d.ts +5 -0
  40. package/dist/identity.d.ts.map +1 -1
  41. package/dist/identity.js +5 -0
  42. package/dist/identity.js.map +1 -1
  43. package/dist/kubo.d.ts +40 -0
  44. package/dist/kubo.d.ts.map +1 -0
  45. package/dist/kubo.js +555 -0
  46. package/dist/kubo.js.map +1 -0
  47. package/dist/pins.d.ts +3 -3
  48. package/dist/pins.js +1 -1
  49. package/dist/pins.js.map +1 -1
  50. package/dist/setup.d.ts +7 -0
  51. package/dist/setup.d.ts.map +1 -0
  52. package/dist/setup.js +22 -0
  53. package/dist/setup.js.map +1 -0
  54. package/dist/source-bundle.d.ts +3 -8
  55. package/dist/source-bundle.d.ts.map +1 -1
  56. package/dist/source-bundle.js +16 -11
  57. package/dist/source-bundle.js.map +1 -1
  58. package/dist/space.d.ts.map +1 -1
  59. package/dist/space.js +2 -2
  60. package/dist/space.js.map +1 -1
  61. package/dist/state.d.ts +7 -5
  62. package/dist/state.d.ts.map +1 -1
  63. package/dist/state.js +17 -14
  64. package/dist/state.js.map +1 -1
  65. package/dist/swarm-envelope.d.ts +36 -0
  66. package/dist/swarm-envelope.d.ts.map +1 -0
  67. package/dist/swarm-envelope.js +145 -0
  68. package/dist/swarm-envelope.js.map +1 -0
  69. package/dist/swarm-files.d.ts +6 -0
  70. package/dist/swarm-files.d.ts.map +1 -0
  71. package/dist/swarm-files.js +107 -0
  72. package/dist/swarm-files.js.map +1 -0
  73. package/dist/swarm.d.ts +120 -58
  74. package/dist/swarm.d.ts.map +1 -1
  75. package/dist/swarm.js +1065 -548
  76. package/dist/swarm.js.map +1 -1
  77. package/dist/template-definition.d.ts +47 -52
  78. package/dist/template-definition.d.ts.map +1 -1
  79. package/dist/template-definition.js +36 -41
  80. package/dist/template-definition.js.map +1 -1
  81. package/dist/template-source.d.ts +2 -0
  82. package/dist/template-source.d.ts.map +1 -1
  83. package/dist/template-source.js +4 -3
  84. package/dist/template-source.js.map +1 -1
  85. package/package.json +3 -3
  86. package/src/app-authoring.ts +22 -5
  87. package/src/app-definition.ts +33 -39
  88. package/src/app-templates.ts +9 -1
  89. package/src/assembly.ts +7 -4
  90. package/src/authoring.ts +31 -14
  91. package/src/builtins.ts +23 -2
  92. package/src/cli.ts +427 -147
  93. package/src/config.ts +32 -19
  94. package/src/content-provider.ts +5 -4
  95. package/src/get.ts +37 -15
  96. package/src/identity.ts +13 -0
  97. package/src/kubo.ts +732 -0
  98. package/src/pins.ts +1 -1
  99. package/src/setup.ts +21 -0
  100. package/src/source-bundle.ts +25 -12
  101. package/src/space.ts +2 -5
  102. package/src/state.ts +24 -15
  103. package/src/swarm-envelope.ts +255 -0
  104. package/src/swarm-files.ts +116 -0
  105. package/src/swarm.ts +1728 -836
  106. package/src/template-definition.ts +36 -41
  107. package/src/template-source.ts +10 -3
package/dist/swarm.js CHANGED
@@ -1,6 +1,5 @@
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";
@@ -8,58 +7,37 @@ import { CID } from "multiformats/cid";
8
7
  import { sha256 } from "multiformats/hashes/sha2";
9
8
  import { encodeSchema, openBundle } from "@ipab/bundle";
10
9
  import { encodeBundleCar, memoryTree, streamChunks, } from "@ipab/bundle-builder";
11
- import { PointerClient, PointerApiError, } from "@ipab/bundle/pointer/client";
12
- import { canonicalService, POINTER_ID_PATTERN, } from "@ipab/bundle/pointer/protocol";
13
- import { encodeCertificate, issueCertificate, verifyMemberCertificate, } from "@ipab/bundle/pointer/certificates";
14
- import { importPrivateKeyPkcs8, importPublicKeyRaw, signEd25519, verifyEd25519, randomBytes, toBase64Url, } from "@ipab/bundle/pointer/crypto";
10
+ import { ContentError } from "@ipab/ipfs-store";
11
+ import { ScopeClient, ScopeApiError, RESOURCE_ID_PATTERN, issueScopeCertificate, uniqueId, verifyScopeCertificate, valueCid, } from "@ipab/bundle/pointer/scope";
12
+ import { canonicalService, isCanonicalPublicKey, POINTER_ID_PATTERN, } from "@ipab/bundle/pointer/protocol";
13
+ import { importPrivateKeyPkcs8, importPublicKeyRaw, keyId, signEd25519, verifyEd25519, } from "@ipab/bundle/pointer/crypto";
15
14
  import { HostError, object, message } from "./errors.js";
16
- import { accountIdentity, protectedPath, secureNew, } from "./identity.js";
17
- import { nodeError } from "./authoring.js";
15
+ import { accountIdentity } from "./identity.js";
18
16
  import { bundleJson, provideContent } from "./content-provider.js";
19
17
  import { bytes, relativePath } from "./space.js";
20
- import { publicUrl } from "./config.js";
21
18
  import { appSchemaCid } from "./app-definition.js";
22
19
  import { State } from "./state.js";
20
+ import { privateDirectory, readPrivate, withPrivateLock, writePrivate, } from "./swarm-files.js";
21
+ import { encryptionIdentity, openApproval, sealApproval, parseEnvelope, } from "./swarm-envelope.js";
22
+ import { kuboSource, peerId, peerProof, prepareNode, startNode, validateAddress, } from "./kubo.js";
23
+ async function contextIdentity(context, initialize = false) {
24
+ context.identity ??= await accountIdentity(context.env, initialize);
25
+ return context.identity;
26
+ }
23
27
  const cidField = { type: "string", minLength: 1, maxLength: 128 };
24
- function definition(name, properties, required = Object.keys(properties)) {
25
- return {
26
- name,
27
- description: "",
28
- entry: {
29
- path: "entry.json",
30
- contentType: "application/json",
31
- schema: {
32
- type: "object",
33
- additionalProperties: false,
34
- required,
35
- properties,
36
- },
28
+ export const artifactType = {
29
+ contentType: "application/json",
30
+ schema: {
31
+ type: "object",
32
+ additionalProperties: false,
33
+ required: ["value", "timestamp"],
34
+ properties: {
35
+ value: cidField,
36
+ previous: cidField,
37
+ timestamp: { type: "string", format: "date-time" },
37
38
  },
38
- };
39
- }
40
- export const swarmType = definition("IPAB Swarm", {
41
- service: { type: "string" },
42
- variable: { type: "string" },
43
- owner: { type: "string" },
44
- });
45
- export const artifactType = definition("IPAB Artifact", {
46
- value: cidField,
47
- previous: cidField,
48
- timestamp: { type: "string", format: "date-time" },
49
- }, ["value", "timestamp"]);
50
- export const requestType = definition("IPAB Membership Request", {
51
- swarm: cidField,
52
- member: { type: "string" },
53
- requestId: { type: "string" },
54
- iat: { type: "integer" },
55
- exp: { type: "integer" },
56
- signature: { type: "string" },
57
- });
58
- export const responseType = definition("IPAB Membership Response", {
59
- swarm: cidField,
60
- request: cidField,
61
- certificate: { type: "object" },
62
- });
39
+ },
40
+ };
63
41
  function withState(context, operation) {
64
42
  if (context.state)
65
43
  return operation(context.state);
@@ -71,52 +49,367 @@ function withState(context, operation) {
71
49
  state.close();
72
50
  }
73
51
  }
74
- async function requestPointer(operation) {
75
- for (let attempt = 0;; attempt++) {
52
+ export function canonicalSwarmUrl(value) {
53
+ if (!/^https?:\/\//.test(value))
54
+ throw new HostError("Swarm requires a configuration URL; old Swarm CID protocol is unsupported.");
55
+ const url = new URL(value);
56
+ canonicalService(url.origin);
57
+ if (url.search ||
58
+ url.hash ||
59
+ url.username ||
60
+ url.password ||
61
+ url.toString() !== value ||
62
+ !/^\/v1\/[a-f0-9]{16}\/[a-f0-9]{16}$/.test(url.pathname))
63
+ throw new HostError("Swarm must be an exact Scope configuration URL; old Swarm CID protocol is unsupported.");
64
+ return value;
65
+ }
66
+ function coordinates(configUrl) {
67
+ const url = new URL(canonicalSwarmUrl(configUrl));
68
+ const [, , scopeId, configId] = url.pathname.split("/");
69
+ return { service: url.origin, scopeId: scopeId, configId: configId };
70
+ }
71
+ const localName = (url) => `${createHash("sha256").update(url).digest("hex")}.json`;
72
+ const nodeScope = (service, scopeId) => createHash("sha256").update(`${service}/v1/${scopeId}`).digest("hex");
73
+ async function directory(context) {
74
+ return privateDirectory(context.stateDir, "swarm-credentials");
75
+ }
76
+ async function local(context, configUrl) {
77
+ const value = await readPrivate(await directory(context), localName(configUrl));
78
+ const identity = await contextIdentity(context);
79
+ if (!value ||
80
+ value.configUrl !== configUrl ||
81
+ value.account !== identity.publicKey)
82
+ throw new HostError("No local Request for this configuration and HOME identity. Run swarm request with a trusted Owner fingerprint.");
83
+ return value;
84
+ }
85
+ async function saveLocal(context, membership) {
86
+ await writePrivate(await directory(context), localName(membership.configUrl), membership);
87
+ }
88
+ function client(context, service, identity, secret) {
89
+ return new ScopeClient({
90
+ service,
91
+ ...(identity
92
+ ? {
93
+ signer: {
94
+ ...identity,
95
+ ...(secret ? { certificate: secret.certificate } : {}),
96
+ },
97
+ }
98
+ : {}),
99
+ ...(context.fetch ? { fetch: context.fetch } : {}),
100
+ ...(context.pointerApiKey ? { apiKey: context.pointerApiKey } : {}),
101
+ });
102
+ }
103
+ function parseOrganization(value, configUrl) {
104
+ const data = object(value, "organization configuration");
105
+ const { scopeId } = coordinates(configUrl);
106
+ if (Object.keys(data).sort().join() !==
107
+ "bootstrap,description,epoch,headId,members,name,owner,scopeId,v" ||
108
+ data.v !== 1 ||
109
+ data.scopeId !== scopeId ||
110
+ !isCanonicalPublicKey(data.owner) ||
111
+ typeof data.name !== "string" ||
112
+ data.name.length > 256 ||
113
+ typeof data.description !== "string" ||
114
+ data.description.length > 2048 ||
115
+ typeof data.headId !== "string" ||
116
+ !RESOURCE_ID_PATTERN.test(data.headId) ||
117
+ typeof data.epoch !== "number" ||
118
+ !Number.isSafeInteger(data.epoch) ||
119
+ data.epoch < 1 ||
120
+ !Array.isArray(data.bootstrap) ||
121
+ data.bootstrap.length > 64 ||
122
+ !Array.isArray(data.members) ||
123
+ data.members.length < 1 ||
124
+ data.members.length > 16)
125
+ throw new HostError("Invalid Scope organization configuration.");
126
+ const identities = new Set(), peers = new Set(), profiles = new Set();
127
+ const members = [];
128
+ for (const raw of data.members) {
129
+ const member = object(raw, "member");
130
+ if (Object.keys(member).sort().join() !==
131
+ "approval,encryptionKey,peerId,profileId,publicKey,requestId" ||
132
+ !isCanonicalPublicKey(member.publicKey) ||
133
+ typeof member.encryptionKey !== "string" ||
134
+ member.encryptionKey.length > 256 ||
135
+ typeof member.peerId !== "string" ||
136
+ typeof member.profileId !== "string" ||
137
+ !RESOURCE_ID_PATTERN.test(member.profileId) ||
138
+ typeof member.requestId !== "string" ||
139
+ !POINTER_ID_PATTERN.test(member.requestId) ||
140
+ identities.has(member.publicKey) ||
141
+ peers.has(member.peerId) ||
142
+ profiles.has(member.profileId))
143
+ throw new HostError("Invalid or duplicate member/PeerID/profile binding.");
144
+ identities.add(member.publicKey);
145
+ peers.add(member.peerId);
146
+ profiles.add(member.profileId);
147
+ members.push({
148
+ publicKey: member.publicKey,
149
+ encryptionKey: member.encryptionKey,
150
+ peerId: member.peerId,
151
+ profileId: member.profileId,
152
+ requestId: member.requestId,
153
+ approval: member.approval === null ? null : parseEnvelope(member.approval),
154
+ });
155
+ }
156
+ if (!identities.has(data.owner))
157
+ throw new HostError("Owner must remain an organization member.");
158
+ const bootstrap = [];
159
+ for (const address of data.bootstrap) {
160
+ if (typeof address !== "string")
161
+ throw new HostError("Invalid bootstrap address.");
162
+ validateAddress(address);
163
+ if (![...peers].some((peer) => address.endsWith(`/p2p/${peer}`)))
164
+ throw new HostError("Bootstrap address is not a member PeerID.");
165
+ bootstrap.push(address);
166
+ }
167
+ return {
168
+ v: 1,
169
+ scopeId,
170
+ owner: data.owner,
171
+ name: data.name,
172
+ description: data.description,
173
+ headId: data.headId,
174
+ epoch: data.epoch,
175
+ bootstrap,
176
+ members,
177
+ };
178
+ }
179
+ function parseProfile(value, expectedPeer) {
180
+ const data = object(value, "member profile");
181
+ if (Object.keys(data).sort().join() !== "addresses,name,updatedAt" ||
182
+ typeof data.name !== "string" ||
183
+ data.name.length > 256 ||
184
+ typeof data.updatedAt !== "string" ||
185
+ !Number.isFinite(Date.parse(data.updatedAt)) ||
186
+ !Array.isArray(data.addresses) ||
187
+ data.addresses.length > 16)
188
+ throw new HostError("Invalid public member profile.");
189
+ const addresses = [];
190
+ for (const address of data.addresses) {
191
+ if (typeof address !== "string")
192
+ throw new HostError("Invalid member address.");
193
+ validateAddress(address, expectedPeer);
194
+ addresses.push(address);
195
+ }
196
+ return { name: data.name, addresses, updatedAt: data.updatedAt };
197
+ }
198
+ async function fetchConfig(context, configUrl) {
199
+ const c = coordinates(configUrl), api = client(context, c.service);
200
+ const [variable, scope] = await Promise.all([
201
+ api.read(c.scopeId, c.configId),
202
+ api.send("GET", c.scopeId),
203
+ ]);
204
+ const config = parseOrganization(variable.value, configUrl);
205
+ if (scope.owner !== config.owner)
206
+ throw new HostError("Organization Owner does not match the immutable Scope trust root.");
207
+ return { config, variable };
208
+ }
209
+ function binding(configUrl, config, member) {
210
+ return {
211
+ configUrl,
212
+ scopeId: config.scopeId,
213
+ owner: config.owner,
214
+ member: member.publicKey,
215
+ requestId: member.requestId,
216
+ peerId: member.peerId,
217
+ profileId: member.profileId,
218
+ headId: config.headId,
219
+ epoch: config.epoch,
220
+ encryptionKey: member.encryptionKey,
221
+ };
222
+ }
223
+ async function validateMembershipSecret(record, config, member) {
224
+ const secret = record.secret;
225
+ if (!secret ||
226
+ typeof secret.swarmKey !== "string" ||
227
+ !/^[a-f0-9]{64}$/.test(secret.swarmKey))
228
+ throw new HostError("Invalid approved Swarm key; preserve the original Request.");
229
+ if (record.account !== config.owner) {
230
+ const c = coordinates(record.configUrl);
231
+ await verifyScopeCertificate(secret.certificate, config.owner, c.service, c.scopeId, config.headId, record.account);
232
+ await verifyScopeCertificate(secret.certificate, config.owner, c.service, c.scopeId, member.profileId, record.account);
233
+ if (secret.certificate.body.write.length !== 2)
234
+ throw new HostError("Membership package must grant exactly HEAD and this member's profile.");
235
+ }
236
+ }
237
+ async function activate(context, record) {
238
+ const config = record.config, secret = record.secret;
239
+ const identity = await contextIdentity(context);
240
+ const self = config.members.find((member) => member.publicKey === identity.publicKey);
241
+ if (!self)
242
+ throw new HostError("This identity was removed. Make a new Request only after Owner confirmation.");
243
+ const c = coordinates(record.configUrl);
244
+ if (identity.publicKey !== config.owner) {
245
+ await verifyScopeCertificate(secret.certificate, config.owner, c.service, c.scopeId, config.headId, identity.publicKey);
246
+ await verifyScopeCertificate(secret.certificate, config.owner, c.service, c.scopeId, self.profileId, identity.publicKey);
247
+ }
248
+ const addresses = [...config.bootstrap];
249
+ const api = client(context, c.service);
250
+ let selfProfile;
251
+ const profiles = await Promise.allSettled(config.members.map((member) => api.read(c.scopeId, member.profileId)));
252
+ for (const [index, member] of config.members.entries()) {
253
+ const result = profiles[index];
254
+ if (result.status === "rejected")
255
+ throw result.reason;
256
+ const profile = result.value;
257
+ const value = parseProfile(profile.value, member.peerId);
258
+ if (member.publicKey === identity.publicKey)
259
+ selfProfile = { profile: value, cid: profile.cid };
260
+ addresses.push(...value.addresses);
261
+ }
262
+ const node = await startNode(context.stateDir, nodeScope(c.service, config.scopeId), secret.swarmKey, config.epoch, [...new Set(addresses)], context.diagnostic, context.listen);
263
+ if (node.peerId !== self.peerId)
264
+ throw new HostError("Approved PeerID differs from this local Request's Kubo identity.");
265
+ if (context.node?.api !== node.api) {
266
+ const store = context.store.withLocalSource(kuboSource(node));
267
+ await context.store.close();
268
+ context.store = store;
269
+ }
270
+ context.node = node;
271
+ if (selfProfile && selfProfile.profile.addresses.length === 0) {
272
+ const writer = client(context, c.service, identity, identity.publicKey === config.owner ? undefined : secret);
273
+ const profile = {
274
+ ...selfProfile.profile,
275
+ addresses: node.addresses,
276
+ updatedAt: new Date().toISOString(),
277
+ };
278
+ await writer.write(c.scopeId, self.profileId, profile, selfProfile.cid, uniqueId());
279
+ }
280
+ }
281
+ async function refresh(context, configUrl) {
282
+ const record = await local(context, configUrl);
283
+ if (record.account === record.owner) {
284
+ const transition = await readPrivate(await directory(context), `transition-${localName(configUrl)}`);
285
+ if (transition && !transition.completed)
286
+ throw new HostError("Organization switch incomplete; only Owner can continue with swarm resume.");
287
+ }
288
+ const { config } = await fetchConfig(context, configUrl);
289
+ if (config.owner !== record.owner)
290
+ throw new HostError("Pinned Owner changed; refusing configuration.");
291
+ if (record.config && config.epoch < record.config.epoch)
292
+ throw new HostError("Organization epoch rollback.");
293
+ const member = config.members.find((member) => member.publicKey === record.account);
294
+ if (!member)
295
+ throw new HostError("No approved package yet, or membership removed; ask the Owner.");
296
+ if (record.account !== config.owner) {
297
+ if (!record.request ||
298
+ member.requestId !== record.request.id ||
299
+ member.peerId !== record.request.peerId ||
300
+ !member.approval)
301
+ throw new HostError("Published package does not match the locally saved Request.");
302
+ record.secret = await openApproval(member.approval, binding(configUrl, config, member), record.encryption);
303
+ }
304
+ if (!record.secret)
305
+ throw new HostError("Owner key/Swarm key lost: no system recovery is available.");
306
+ record.config = config;
307
+ await validateMembershipSecret(record, config, member);
308
+ await saveLocal(context, record);
309
+ await activate(context, record);
310
+ return record;
311
+ }
312
+ async function readyMembership(context, configUrl) {
313
+ const record = await local(context, configUrl);
314
+ if (record.account === record.owner) {
315
+ const transition = await readPrivate(await directory(context), `transition-${localName(configUrl)}`);
316
+ if (transition && !transition.completed)
317
+ throw new HostError("Organization switch incomplete; run swarm resume before normal Owner operations.");
318
+ }
319
+ if (!record.config || !record.secret)
320
+ return refresh(context, configUrl);
321
+ if (!context.node ||
322
+ context.node.peerId !==
323
+ record.config.members.find((m) => m.publicKey === record.account)?.peerId) {
76
324
  try {
77
- return await operation();
325
+ await activate(context, record);
78
326
  }
79
327
  catch (cause) {
80
- if (attempt >= 2 ||
81
- !(cause instanceof Error) ||
82
- !["TypeError", "AbortError", "TimeoutError"].includes(cause.name))
83
- throw cause;
328
+ if (cause instanceof ScopeApiError &&
329
+ [403, 404, 410].includes(cause.status))
330
+ return refresh(context, configUrl);
331
+ throw cause;
84
332
  }
85
333
  }
334
+ return record;
86
335
  }
87
- const serviceFetch = (input, options) => fetch(input, {
88
- ...options,
89
- redirect: "error",
90
- cache: "no-store",
91
- signal: AbortSignal.timeout(30_000),
92
- });
93
- function bindPointer(context, data, identity, certificate) {
94
- const client = new PointerClient({
95
- service: data.service,
96
- signer: {
97
- privateKey: identity.privateKey,
98
- publicKey: identity.publicKey,
99
- ...(certificate ? { certificate } : {}),
100
- },
101
- fetch: context.fetch ?? serviceFetch,
102
- });
336
+ function headValue(head) {
337
+ const value = object(head.value, "HEAD");
338
+ if (Object.keys(value).join() !== "root" || typeof value.root !== "string")
339
+ throw new HostError("Invalid HEAD value.");
103
340
  return {
104
- read: () => requestPointer(() => client.read(data.variable)),
105
- write: (root, revision, idempotencyKey) => requestPointer(() => client.write(data.variable, root, {
106
- ifRevision: revision,
107
- idempotencyKey,
108
- })),
341
+ ...head,
342
+ root: value.root,
343
+ etag: `"${head.cid}"`,
344
+ };
345
+ }
346
+ export async function pointer(context, configUrl) {
347
+ return boundPointer(context, configUrl, await readyMembership(context, configUrl));
348
+ }
349
+ async function boundPointer(context, configUrl, record) {
350
+ const identity = await contextIdentity(context), c = coordinates(configUrl);
351
+ const operation = async (write, root, cid, key) => {
352
+ for (let attempt = 0;; attempt++) {
353
+ const config = record.config, api = client(context, c.service, identity, identity.publicKey === config.owner ? undefined : record.secret);
354
+ try {
355
+ return write
356
+ ? await api.write(c.scopeId, config.headId, { root: root }, cid, key)
357
+ : await api.read(c.scopeId, config.headId);
358
+ }
359
+ catch (cause) {
360
+ if (attempt === 0 &&
361
+ (!write ||
362
+ (cause instanceof ScopeApiError &&
363
+ [401, 403, 404, 410, 423].includes(cause.status)))) {
364
+ const oldHead = record.config.headId;
365
+ record = await refresh(context, configUrl);
366
+ if (write && record.config.headId !== oldHead)
367
+ throw new ScopeApiError(412, "cas_conflict", "HEAD switched; recompute against the new final snapshot", cause);
368
+ continue;
369
+ }
370
+ throw cause;
371
+ }
372
+ }
373
+ };
374
+ return {
375
+ read: async () => headValue(await operation(false)),
376
+ write: (root, cid, key) => operation(true, root, cid, key),
109
377
  };
110
378
  }
111
379
  export async function typedJson(store, cid, type) {
112
380
  const { bundle, value } = await bundleJson(store, cid);
113
381
  if (bundle.schemaKey !== (await encodeSchema(type)).cid.toString())
114
- throw new HostError(`Expected exact ${type.name} Bundle type.`);
382
+ throw new HostError("Expected exact Bundle type CID.");
115
383
  return value;
116
384
  }
385
+ function parseArtifact(value) {
386
+ const data = object(value, "Artifact");
387
+ if (Object.keys(data).some((key) => !["value", "previous", "timestamp"].includes(key)) ||
388
+ typeof data.value !== "string" ||
389
+ typeof data.timestamp !== "string" ||
390
+ !Number.isFinite(Date.parse(data.timestamp)) ||
391
+ (data.previous !== undefined && typeof data.previous !== "string"))
392
+ throw new HostError("Invalid Artifact.");
393
+ CID.parse(data.value);
394
+ if (data.previous !== undefined)
395
+ CID.parse(data.previous);
396
+ return {
397
+ value: data.value,
398
+ timestamp: data.timestamp,
399
+ ...(data.previous !== undefined ? { previous: data.previous } : {}),
400
+ };
401
+ }
117
402
  export async function jsonBundle(store, type, value) {
118
403
  const encoded = await encodeBundleCar(memoryTree(new Map([
119
- [".bundle.yaml", new TextEncoder().encode(stringify(type))],
404
+ [
405
+ ".bundle.yaml",
406
+ new TextEncoder().encode(stringify({
407
+ title: "IPAB Data",
408
+ entry: "entry.json",
409
+ type: ".bundle-type.yaml",
410
+ })),
411
+ ],
412
+ [".bundle-type.yaml", new TextEncoder().encode(stringify(type))],
120
413
  ["entry.json", new TextEncoder().encode(`${JSON.stringify(value)}\n`)],
121
414
  ])));
122
415
  try {
@@ -129,476 +422,650 @@ export async function jsonBundle(store, type, value) {
129
422
  await encoded.close();
130
423
  }
131
424
  }
132
- export async function descriptor(store, cid) {
133
- const data = await typedJson(store, cid, swarmType);
134
- return validateDescriptor(data);
135
- }
136
- async function validateDescriptor(data) {
137
- data.service = publicUrl(data.service).replace(/\/$/, "");
138
- const url = new URL(data.service);
139
- if (url.pathname !== "/" ||
140
- (url.protocol !== "https:" &&
141
- !["localhost", "127.0.0.1", "[::1]"].includes(url.hostname)))
142
- throw new HostError("Swarm service must be an HTTPS origin or isolated loopback HTTP origin.");
143
- if (!POINTER_ID_PATTERN.test(data.variable))
144
- throw new HostError("Invalid service pointer ID.");
145
- await importPublicKeyRaw(data.owner);
146
- return data;
147
- }
148
- const target = (data) => `${data.service}/v1/pointers/${data.variable}`;
149
- const now = () => Math.floor(Date.now() / 1000);
150
- function requestMessage(data, request) {
151
- 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 })}`;
152
- }
153
- async function verifiedRequest(store, cid) {
154
- const request = await typedJson(store, cid, requestType);
155
- const data = await descriptor(store, request.swarm);
156
- if (request.iat > now() + 60 ||
157
- request.exp <= now() ||
158
- request.exp <= request.iat ||
159
- request.exp - request.iat > 7 * 86400 ||
160
- !/^[A-Za-z0-9_-]{16,128}$/.test(request.requestId))
161
- throw new HostError("Membership request is expired or invalid.");
162
- if (!(await verifyEd25519(await importPublicKeyRaw(request.member), request.signature, requestMessage(data, request))))
163
- throw new HostError("Membership request possession proof is invalid.");
164
- return { request, data };
165
- }
166
- async function credentialDirectory(context) {
167
- const path = join(context.stateDir, "swarm-credentials");
168
- try {
169
- await lstat(path);
170
- }
171
- catch (cause) {
172
- if (!nodeError(cause, "ENOENT"))
173
- throw cause;
174
- await mkdir(path, { mode: 0o700 });
175
- await secureNew(path, true);
176
- }
177
- await protectedPath(path, true);
178
- return path;
179
- }
180
- async function save(context, name, value) {
181
- const path = join(await credentialDirectory(context), name);
182
- const handle = await open(path, "wx", 0o600);
183
- try {
184
- await handle.writeFile(JSON.stringify(value));
185
- await handle.sync();
186
- }
187
- finally {
188
- await handle.close();
189
- }
190
- await secureNew(path);
191
- }
192
- async function saved(context, name) {
193
- const path = join(await credentialDirectory(context), name);
194
- await protectedPath(path);
195
- return JSON.parse(await readFile(path, "utf8"));
196
- }
197
- export async function pointer(context, swarm, certificate) {
198
- const data = await descriptor(context.store, swarm);
199
- const identity = await accountIdentity(context.env);
200
- return authenticatedPointer(context, swarm, data, identity, certificate);
201
- }
202
- async function authenticatedPointer(context, swarm, data, identity, certificate) {
203
- if (identity.publicKey === data.owner && certificate === undefined)
204
- return bindPointer(context, data, identity);
205
- const cert = certificate ??
206
- (await saved(context, `${swarm}.json`))
207
- .certificate;
208
- const verified = await verifyMemberCertificate(encodeCertificate(cert), await importPublicKeyRaw(data.owner), data.owner, data.service, data.variable, now());
209
- if (verified.member !== identity.publicKey)
210
- throw new HostError("Membership certificate does not match this account, swarm, owner or validity window.");
211
- if (identity.publicKey === data.owner)
212
- return bindPointer(context, data, identity);
213
- return bindPointer(context, data, identity, cert);
214
- }
215
425
  export async function writeSnapshot(store, snapshot) {
216
- const encoded = dagCbor.encode(snapshot);
217
- const cid = CID.createV1(dagCbor.code, await sha256.digest(encoded));
426
+ const encoded = dagCbor.encode(snapshot), cid = CID.createV1(dagCbor.code, await sha256.digest(encoded));
218
427
  await store.put(cid, encoded);
219
428
  return cid.toString();
220
429
  }
221
- export async function readSnapshot(store, root) {
222
- const cid = CID.parse(root);
223
- if (cid.code !== dagCbor.code)
224
- throw new HostError("HEAD must reference a DAG-CBOR snapshot.");
225
- const publication = object(dagCbor.decode(await store.block.get(root)), "publication record");
226
- const stateCid = CID.asCID(publication.state);
227
- if (publication.v !== 1 ||
228
- !stateCid ||
229
- Object.keys(publication).some((key) => !["v", "state", "previous"].includes(key)) ||
230
- (publication.previous !== undefined && !CID.asCID(publication.previous)))
231
- throw new HostError("HEAD must reference a verified publication linking State and optional previous publication.");
232
- return decodeSnapshot(await store.block.get(stateCid.toString()));
233
- }
234
- function decodeSnapshot(bytes) {
235
- const value = object(dagCbor.decode(bytes), "swarm snapshot");
236
- const properties = object(value.properties, "swarm properties");
237
- const names = object(value.names, "swarm Names");
238
- if (value.v !== 1 ||
239
- typeof properties.name !== "string" ||
240
- typeof properties.description !== "string" ||
241
- Object.keys(value).some((key) => !["v", "names", "properties"].includes(key)))
242
- throw new HostError("Invalid swarm snapshot.");
430
+ function decodeSnapshot(data) {
431
+ const value = object(dagCbor.decode(data), "State"), names = object(value.names, "Names");
432
+ if (value.v !== 2 || Object.keys(value).sort().join() !== "names,v")
433
+ throw new HostError("Unsupported old State; rebuild the Swarm.");
434
+ const links = [];
243
435
  for (const [name, link] of Object.entries(names)) {
244
436
  formalName(name);
245
- if (!CID.asCID(link))
246
- throw new HostError("Snapshot Name targets must be CID links.");
437
+ const cid = CID.asCID(link);
438
+ if (!cid)
439
+ throw new HostError("Names must link CIDs.");
440
+ links.push([name, cid]);
247
441
  }
248
- return value;
442
+ return { v: 2, names: Object.fromEntries(links) };
443
+ }
444
+ export async function readSnapshot(store, root) {
445
+ const publication = await readPublication(store, root);
446
+ return decodeSnapshot(await store.block.get(publication.state.toString()));
447
+ }
448
+ async function readPublication(store, root) {
449
+ if (CID.parse(root).code !== dagCbor.code)
450
+ throw new HostError("Publication must be DAG-CBOR.");
451
+ const publication = object(dagCbor.decode(await store.block.get(root)), "publication");
452
+ const state = CID.asCID(publication.state);
453
+ const previous = publication.previous === undefined
454
+ ? undefined
455
+ : CID.asCID(publication.previous);
456
+ if (publication.v !== 1 ||
457
+ !state ||
458
+ Object.keys(publication).some((k) => !["v", "state", "previous"].includes(k)) ||
459
+ (publication.previous !== undefined && !previous))
460
+ throw new HostError("Invalid publication record.");
461
+ return { state, ...(previous ? { previous } : {}) };
462
+ }
463
+ async function publication(store, state, previous) {
464
+ const data = dagCbor.encode({
465
+ v: 1,
466
+ state: CID.parse(state),
467
+ ...(previous ? { previous: CID.parse(previous) } : {}),
468
+ });
469
+ const cid = CID.createV1(dagCbor.code, await sha256.digest(data));
470
+ await store.put(cid, data);
471
+ return cid.toString();
472
+ }
473
+ export async function sharedSwarmStatus(context, configUrl) {
474
+ const { config } = await fetchConfig(context, configUrl);
475
+ const c = coordinates(configUrl);
476
+ const head = headValue(await client(context, c.service).read(c.scopeId, config.headId));
477
+ let snapshot;
478
+ try {
479
+ snapshot = await readSnapshot(context.store, head.root);
480
+ }
481
+ catch (cause) {
482
+ if (!(cause instanceof ContentError) || cause.code !== "missing_block")
483
+ throw cause;
484
+ const registered = withState(context, (state) => state.swarms().some((entry) => entry.cid === configUrl));
485
+ if (!registered)
486
+ throw cause;
487
+ context.diagnostic?.("Shared State is missing locally; connecting the registered Swarm content source.");
488
+ return swarmHeader(context, configUrl, true);
489
+ }
490
+ return {
491
+ head,
492
+ snapshot,
493
+ config,
494
+ source: "network",
495
+ verifiedAt: new Date().toISOString(),
496
+ };
249
497
  }
250
- export async function swarmHeader(context, swarm, force = context.forceRefresh ?? false) {
251
- swarm = CID.parse(swarm).toV1().toString();
252
- const identity = await accountIdentity(context.env);
498
+ export async function swarmHeader(context, configUrl, force = context.forceRefresh ?? false) {
499
+ canonicalSwarmUrl(configUrl);
500
+ let record = force
501
+ ? await refresh(context, configUrl)
502
+ : await readyMembership(context, configUrl);
253
503
  const ttl = context.cacheTtl ?? 300;
254
- if (!Number.isSafeInteger(ttl) || ttl < 0 || ttl > 86400)
255
- throw new HostError("swarm.cacheTtl requires an integer number of seconds from 0 to 86400.");
256
504
  const cached = force
257
505
  ? undefined
258
- : withState(context, (state) => state.swarmHeader(identity.publicKey, swarm));
259
- if (cached !== undefined) {
260
- const value = object(cached, "swarm header cache");
261
- if (typeof value.root !== "string" ||
262
- CID.parse(value.root).code !== dagCbor.code ||
263
- typeof value.revision !== "string" ||
264
- !value.revision ||
265
- typeof value.etag !== "string" ||
266
- typeof value.verifiedAt !== "number" ||
267
- !Number.isSafeInteger(value.verifiedAt) ||
268
- value.verifiedAt < 0 ||
269
- typeof value.snapshot !== "string" ||
270
- Buffer.from(value.snapshot, "base64").toString("base64") !==
271
- value.snapshot)
272
- throw new HostError("Invalid persisted swarm header cache; retry with --force to replace it.");
273
- const snapshot = decodeSnapshot(Buffer.from(value.snapshot, "base64"));
274
- const cachedDescriptor = object(value.descriptor, "cached swarm descriptor");
275
- if (typeof cachedDescriptor.service !== "string" ||
276
- typeof cachedDescriptor.variable !== "string" ||
277
- typeof cachedDescriptor.owner !== "string")
278
- throw new HostError("Invalid cached swarm descriptor; retry with --force to replace it.");
279
- const data = await validateDescriptor({
280
- service: cachedDescriptor.service,
281
- variable: cachedDescriptor.variable,
282
- owner: cachedDescriptor.owner,
283
- });
284
- const age = Date.now() - value.verifiedAt;
285
- if (age >= 0 && age < ttl * 1000) {
286
- await authenticatedPointer(context, swarm, data, identity);
287
- return {
288
- head: { root: value.root, revision: value.revision, etag: value.etag },
289
- snapshot,
290
- source: "cache",
291
- verifiedAt: new Date(value.verifiedAt).toISOString(),
292
- };
293
- }
506
+ : withState(context, (state) => state.swarmHeader(record.account, configUrl));
507
+ if (cached &&
508
+ cached.headId === record.config.headId &&
509
+ Date.now() >= cached.verifiedAt &&
510
+ Date.now() - cached.verifiedAt < ttl * 1000)
511
+ return {
512
+ head: headValue(cached.head),
513
+ snapshot: decodeSnapshot(Buffer.from(cached.snapshot, "base64")),
514
+ config: record.config,
515
+ source: "cache",
516
+ verifiedAt: new Date(cached.verifiedAt).toISOString(),
517
+ };
518
+ let head = await (await boundPointer(context, configUrl, record)).read();
519
+ let snapshot;
520
+ try {
521
+ snapshot = await readSnapshot(context.store, head.root);
294
522
  }
295
- const data = await descriptor(context.store, swarm);
296
- const client = await authenticatedPointer(context, swarm, data, identity);
297
- context.diagnostic?.(`Refreshing swarm HEAD ${swarm}...`);
298
- const head = await client.read();
299
- const snapshot = await readSnapshot(context.store, head.root);
300
- const verifiedAt = Date.now();
523
+ catch {
524
+ record = await refresh(context, configUrl);
525
+ head = await (await boundPointer(context, configUrl, record)).read();
526
+ snapshot = await readSnapshot(context.store, head.root);
527
+ }
528
+ const current = await local(context, configUrl), verifiedAt = Date.now();
301
529
  withState(context, (state) => {
302
- state.saveSwarmHeader(identity.publicKey, swarm, {
303
- ...head,
304
- descriptor: data,
530
+ state.saveSwarmHeader(record.account, configUrl, {
531
+ head,
305
532
  snapshot: Buffer.from(dagCbor.encode(snapshot)).toString("base64"),
306
533
  verifiedAt,
534
+ headId: current.config.headId,
307
535
  });
308
536
  });
309
537
  return {
310
538
  head,
311
539
  snapshot,
540
+ config: current.config,
312
541
  source: "network",
313
542
  verifiedAt: new Date(verifiedAt).toISOString(),
314
543
  };
315
544
  }
316
- export async function addSwarm(context, swarm, alias) {
317
- swarm = CID.parse(swarm).toV1().toString();
318
- if (alias !== undefined)
319
- withState(context, (state) => {
320
- state.checkSwarmAlias(alias, swarm);
321
- });
322
- await swarmHeader(context, swarm, true);
323
- withState(context, (state) => state.registerSwarm(swarm, alias));
545
+ export async function addSwarm(context, url, alias) {
546
+ canonicalSwarmUrl(url);
547
+ await readyMembership(context, url);
548
+ withState(context, (state) => state.registerSwarm(url, alias));
324
549
  }
325
- export async function updateSwarm(context, swarm, changes) {
326
- if (changes.name === undefined && changes.description === undefined)
327
- throw new HostError("swarm update requires --name or --description.", 2);
328
- swarm = CID.parse(swarm).toV1().toString();
329
- const client = await pointer(context, swarm);
330
- for (let attempt = 0; attempt < 8; attempt++) {
331
- const head = await client.read();
332
- const current = await readSnapshot(context.store, head.root);
333
- const properties = {
334
- ...current.properties,
335
- ...(changes.name !== undefined ? { name: changes.name } : {}),
336
- ...(changes.description !== undefined
337
- ? { description: changes.description }
338
- : {}),
339
- };
340
- const state = await writeSnapshot(context.store, {
341
- ...current,
342
- properties,
343
- });
344
- const next = await publication(context.store, state, head.root);
345
- await provideContent(context.store, [next], context.provider, context.fetch);
346
- withState(context, (state) => {
347
- state.invalidateSwarmHeader(swarm);
348
- });
349
- try {
350
- const written = await client.write(next, head.revision, toBase64Url(randomBytes(18)));
351
- return {
352
- cid: swarm,
353
- root: written.root,
354
- revision: written.revision,
355
- properties,
356
- };
550
+ export async function createSwarm(context, options = {}) {
551
+ if ((options.properties?.name.length ?? 0) > 256 ||
552
+ (options.properties?.description.length ?? 0) > 2048 ||
553
+ (options.addresses?.length ?? 0) > 16)
554
+ throw new HostError("Organization name/description or address limit exceeded.");
555
+ const service = canonicalService(context.pointerService ?? "");
556
+ if (!context.pointerApiKey ||
557
+ (options.service && options.service !== service))
558
+ throw new HostError("Configure origin-bound pointers.service/apiKey before creating a Scope.");
559
+ const identity = await contextIdentity(context, true), op = options.resume ?? uniqueId(), dir = await directory(context);
560
+ if (!POINTER_ID_PATTERN.test(op))
561
+ throw new HostError("Invalid creation resume ID.");
562
+ return withPrivateLock(dir, async () => {
563
+ let record = await readPrivate(dir, `creation-${op}.json`);
564
+ if (options.alias !== undefined) {
565
+ const existingUrl = record?.scopeId && record.configId
566
+ ? `${service}/v1/${record.scopeId}/${record.configId}`
567
+ : undefined;
568
+ withState(context, (state) => {
569
+ state.checkSwarmAlias(options.alias, existingUrl);
570
+ });
357
571
  }
358
- catch (cause) {
359
- if (!(cause instanceof PointerApiError) || cause.status !== 412)
360
- throw new HostError(`Swarm information update failed or its result is unknown: ${message(cause)}. Publication ${next} remains retained; authenticate swarm status before retrying.`, 1, "HEAD_UNCONFIRMED", "publication");
361
- context.diagnostic?.("Swarm HEAD changed; retrying information update with the latest Names and properties.");
572
+ if (!record) {
573
+ if (options.resume)
574
+ throw new HostError("Unknown creation operation.");
575
+ record = {
576
+ owner: identity.publicKey,
577
+ service,
578
+ encryption: encryptionIdentity(),
579
+ key: randomBytes(32).toString("hex"),
580
+ name: options.properties?.name ?? "",
581
+ description: options.properties?.description ?? "",
582
+ createdAt: new Date().toISOString(),
583
+ };
584
+ await writePrivate(dir, `creation-${op}.json`, record);
362
585
  }
363
- }
364
- throw new HostError("Swarm HEAD is busy; information update could not complete. Retry later.", 1, "HEAD_BUSY", "publication");
365
- }
366
- export async function searchNames(context, query, swarms) {
367
- if (!query ||
368
- query.length > 256 ||
369
- [...query].some((character) => {
370
- const code = character.charCodeAt(0);
371
- return code < 32 || code === 127;
372
- }))
373
- throw new HostError("Search query must be 1..256 characters without control characters.", 2);
374
- const matches = [];
375
- const searched = [];
376
- for (const swarm of [...swarms].sort((a, b) => a.cid < b.cid ? -1 : a.cid > b.cid ? 1 : 0)) {
377
- let header;
586
+ if (record.owner !== identity.publicKey || record.service !== service)
587
+ throw new HostError("Creation belongs to another Owner or service.");
588
+ const save = () => writePrivate(dir, `creation-${op}.json`, record);
589
+ const api = client(context, service, identity);
378
590
  try {
379
- header = await swarmHeader(context, swarm.cid);
591
+ if (!record.scopeId) {
592
+ record.scopeId = (await api.createScope(`${op}.scope`)).id;
593
+ await save();
594
+ }
595
+ const node = await prepareNode(context.stateDir, nodeScope(service, record.scopeId), context.listen);
596
+ if (!record.headId) {
597
+ const root = await publication(context.store, await writeSnapshot(context.store, { v: 2, names: {} }));
598
+ record.headId = (await api.create(record.scopeId, { root }, `${op}.head`)).id;
599
+ await save();
600
+ }
601
+ if (!record.profileId) {
602
+ const addresses = options.addresses ?? node.addresses;
603
+ for (const address of addresses)
604
+ validateAddress(address, node.peerId);
605
+ record.profileId = (await api.create(record.scopeId, { name: record.name, addresses, updatedAt: record.createdAt }, `${op}.profile`)).id;
606
+ await save();
607
+ }
608
+ if (!record.config) {
609
+ record.config = {
610
+ v: 1,
611
+ scopeId: record.scopeId,
612
+ owner: identity.publicKey,
613
+ name: record.name,
614
+ description: record.description,
615
+ headId: record.headId,
616
+ epoch: 1,
617
+ bootstrap: options.addresses ?? node.addresses,
618
+ members: [
619
+ {
620
+ publicKey: identity.publicKey,
621
+ encryptionKey: record.encryption.publicKey,
622
+ peerId: node.peerId,
623
+ profileId: record.profileId,
624
+ requestId: op,
625
+ approval: null,
626
+ },
627
+ ],
628
+ };
629
+ await save();
630
+ }
631
+ if (!record.configId) {
632
+ record.configId = (await api.create(record.scopeId, record.config, `${op}.config`)).id;
633
+ await save();
634
+ }
635
+ const configUrl = `${service}/v1/${record.scopeId}/${record.configId}`;
636
+ const cert = await issueScopeCertificate({
637
+ v: 1,
638
+ service,
639
+ scopeId: record.scopeId,
640
+ subject: identity.publicKey,
641
+ write: [record.headId, record.profileId],
642
+ }, await importPrivateKeyPkcs8(identity.privateKey));
643
+ const membership = {
644
+ configUrl,
645
+ owner: identity.publicKey,
646
+ account: identity.publicKey,
647
+ encryption: record.encryption,
648
+ config: record.config,
649
+ secret: { certificate: cert, swarmKey: record.key },
650
+ };
651
+ await saveLocal(context, membership);
652
+ await activate(context, membership);
653
+ const head = await api.read(record.scopeId, record.headId);
654
+ await provideContent(context.store, [headValue(head).root], context.node.api, context.fetch, context.node.auth);
655
+ withState(context, (state) => state.registerSwarm(configUrl, options.alias));
656
+ return configUrl;
380
657
  }
381
658
  catch (cause) {
382
- throw new HostError(`Could not search swarm "${swarm.alias ?? swarm.cid}": ${message(cause)}. Search was not completed.`);
659
+ throw new HostError(`Swarm creation incomplete: ${message(cause)}. Resume only with swarm create --resume ${op}.`);
383
660
  }
384
- searched.push({
385
- cid: swarm.cid,
386
- source: header.source,
387
- root: header.head.root,
388
- revision: header.head.revision,
389
- verifiedAt: header.verifiedAt,
390
- });
391
- for (const name of Object.keys(header.snapshot.names).sort())
392
- if (name.toLowerCase().includes(query.toLowerCase()))
393
- matches.push({
394
- swarm: swarm.cid,
395
- alias: swarm.alias,
396
- name,
397
- reference: `ipab://${CID.parse(swarm.cid).toV1().toString()}/${name
398
- .split("/")
399
- .map((segment) => encodeURIComponent(segment).replace(/[!'()*]/g, (character) => `%${character.charCodeAt(0).toString(16).toUpperCase()}`))
400
- .join("/")}`,
401
- targetCid: header.snapshot.names[name].toString(),
402
- });
403
- }
404
- return { matches, swarms: searched };
405
- }
406
- async function publication(store, state, previous) {
407
- const bytes = dagCbor.encode({
408
- v: 1,
409
- state: CID.parse(state),
410
- ...(previous ? { previous: CID.parse(previous) } : {}),
411
661
  });
412
- const cid = CID.createV1(dagCbor.code, await sha256.digest(bytes));
413
- await store.put(cid, bytes);
414
- return cid.toString();
415
662
  }
416
- async function saveCreation(context, operation, record) {
417
- const directory = await credentialDirectory(context);
418
- const target = join(directory, `creation-${operation}.json`);
419
- const temporary = join(directory, `.creation-${randomUUID()}.tmp`);
420
- const handle = await open(temporary, "wx", 0o600);
663
+ const requestMessage = (request) => JSON.stringify(["IPAB-REQUEST/1", request]);
664
+ export async function exportRequest(context, url, output) {
665
+ const record = await local(context, canonicalSwarmUrl(url));
666
+ if (!record.request)
667
+ throw new HostError("Owner membership has no Request.");
668
+ const handle = await open(output, "wx", 0o600);
421
669
  try {
422
- await secureNew(temporary);
423
- await handle.writeFile(JSON.stringify(record));
670
+ await handle.writeFile(`${JSON.stringify(record.request, null, 2)}\n`);
424
671
  await handle.sync();
425
- await handle.close();
426
- await rename(temporary, target);
427
672
  }
428
673
  finally {
429
674
  await handle.close();
430
- await unlink(temporary).catch((cause) => {
431
- if (!nodeError(cause, "ENOENT"))
432
- return Promise.reject(cause instanceof Error
433
- ? cause
434
- : new HostError("Owned creation temporary-file cleanup failed."));
435
- return undefined;
436
- });
437
675
  }
676
+ return record.request.id;
438
677
  }
439
- export async function createSwarm(context, options = {}) {
440
- if (options.alias !== undefined && options.resume === undefined)
441
- withState(context, (state) => {
442
- state.checkSwarmAlias(options.alias);
443
- });
444
- const cfg = {
445
- service: context.pointerService,
446
- apiKey: context.pointerApiKey,
447
- };
448
- if (!cfg.service || !cfg.apiKey)
449
- throw new HostError("Configure protected pointers.service and pointers.apiKey via safe stdin before creating a swarm.");
450
- if (options.service && canonicalService(options.service) !== cfg.service)
451
- throw new HostError("Creation API key cannot be sent outside its explicitly configured origin.");
452
- const identity = await accountIdentity(context.env, true);
453
- const operation = options.resume ?? toBase64Url(randomBytes(18));
454
- if (!/^[A-Za-z0-9_-]{16,128}$/.test(operation))
455
- throw new HostError("Invalid saved creation operation.");
456
- let record;
457
- if (options.resume) {
458
- const value = object(await saved(context, `creation-${operation}.json`), "saved creation");
459
- if (value.origin !== cfg.service ||
460
- value.owner !== identity.publicKey ||
461
- typeof value.root !== "string" ||
462
- !Number.isSafeInteger(value.createdAt) ||
463
- (value.id !== undefined && typeof value.id !== "string") ||
464
- (value.cid !== undefined && typeof value.cid !== "string"))
465
- throw new HostError("Saved creation does not match this account and configured service.");
466
- record = value;
678
+ export async function requestMembership(context, url, options) {
679
+ if ((options.name?.length ?? 0) > 256)
680
+ throw new HostError("Request name exceeds 256 characters.");
681
+ canonicalSwarmUrl(url);
682
+ const identity = await contextIdentity(context, true);
683
+ const { config } = await fetchConfig(context, url);
684
+ if (options.ownerFingerprint !== (await keyId(config.owner)))
685
+ throw new HostError(`Trusted Owner fingerprint required; observed ${await keyId(config.owner)}. Verify through an independent trusted channel.`);
686
+ const dir = await directory(context);
687
+ await withPrivateLock(dir, async () => {
467
688
  if (options.alias !== undefined)
468
689
  withState(context, (state) => {
469
- state.checkSwarmAlias(options.alias, record.cid);
690
+ state.checkSwarmAlias(options.alias, url);
470
691
  });
471
- if (!record.id && Date.now() - record.createdAt >= 10 * 60 * 1000)
472
- throw new HostError("Unconfirmed creation is beyond the service's minimum idempotency window. Ask the operator to recover it; do not allocate another pointer.");
473
- }
474
- else {
475
- const state = await writeSnapshot(context.store, {
692
+ const existing = await readPrivate(dir, localName(url));
693
+ if (existing) {
694
+ if (existing.account !== identity.publicKey ||
695
+ existing.owner !== config.owner)
696
+ throw new HostError("Existing Request belongs to a different identity or pinned Owner.");
697
+ if (!existing.request)
698
+ throw new HostError("This identity is already the Owner.");
699
+ withState(context, (state) => state.registerSwarm(url, options.alias));
700
+ return;
701
+ }
702
+ const node = await prepareNode(context.stateDir, nodeScope(coordinates(url).service, config.scopeId), context.listen), encryption = encryptionIdentity();
703
+ const body = {
476
704
  v: 1,
477
- properties: options.properties ?? { name: "", description: "" },
478
- names: {},
479
- });
480
- record = {
481
- origin: cfg.service,
482
- owner: identity.publicKey,
483
- root: await publication(context.store, state),
484
- createdAt: Date.now(),
705
+ id: uniqueId(),
706
+ requestedAt: new Date().toISOString(),
707
+ configUrl: url,
708
+ scopeId: config.scopeId,
709
+ owner: config.owner,
710
+ name: options.name ?? "",
711
+ member: identity.publicKey,
712
+ encryptionKey: encryption.publicKey,
713
+ peerId: node.peerId,
714
+ peerPublicKey: "",
485
715
  };
486
- await saveCreation(context, operation, record);
487
- }
488
- try {
489
- await provideContent(context.store, [record.root], context.provider, context.fetch);
490
- if (!record.id) {
491
- const client = new PointerClient({
492
- service: cfg.service,
493
- apiKey: cfg.apiKey,
494
- signer: {
495
- privateKey: identity.privateKey,
496
- publicKey: identity.publicKey,
497
- },
498
- fetch: context.fetch ?? serviceFetch,
499
- });
500
- record.id = (await requestPointer(() => client.create(record.root, { idempotencyKey: operation }))).id;
501
- await saveCreation(context, operation, record);
502
- }
503
- const data = {
504
- service: cfg.service,
505
- variable: record.id,
506
- owner: identity.publicKey,
716
+ body.peerPublicKey = (await peerProof(node, "identity")).publicKey;
717
+ const proof = await peerProof(node, requestMessage(body));
718
+ const peerSignature = proof.signature;
719
+ const request = {
720
+ ...body,
721
+ peerSignature,
722
+ signature: await signEd25519(await importPrivateKeyPkcs8(identity.privateKey), JSON.stringify(["IPAB-REQUEST-MEMBER/1", body, peerSignature])),
507
723
  };
508
- const cid = await jsonBundle(context.store, swarmType, data);
509
- await provideContent(context.store, [cid, record.root], context.provider, context.fetch);
510
- record.cid = cid;
511
- await saveCreation(context, operation, record);
512
- await addSwarm(context, cid, options.alias);
513
- return cid;
514
- }
515
- catch (cause) {
516
- throw new HostError(`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.`, 1, "CREATE_UNCONFIRMED", "authorization");
517
- }
724
+ await saveLocal(context, {
725
+ configUrl: url,
726
+ owner: config.owner,
727
+ account: identity.publicKey,
728
+ encryption,
729
+ request,
730
+ });
731
+ withState(context, (state) => state.registerSwarm(url, options.alias));
732
+ });
733
+ if (options.output)
734
+ await exportRequest(context, url, options.output);
735
+ return (await local(context, url)).request.id;
736
+ }
737
+ export async function verifiedRequest(path) {
738
+ if ((await lstat(path)).size > 16 * 1024)
739
+ throw new HostError("Request file exceeds 16 KiB.");
740
+ return verifyRequest(JSON.parse(await readFile(path, "utf8")));
518
741
  }
519
- export async function requestMembership(context, swarm) {
520
- const identity = await accountIdentity(context.env, true);
521
- const data = await descriptor(context.store, swarm);
742
+ async function verifyRequest(input) {
743
+ const fields = object(input, "Request");
744
+ if (Object.keys(fields).sort().join() !==
745
+ "configUrl,encryptionKey,id,member,name,owner,peerId,peerPublicKey,peerSignature,requestedAt,scopeId,signature,v" ||
746
+ fields.v !== 1)
747
+ throw new HostError("Invalid self-contained Request format.");
748
+ const { id, member, owner, name, encryptionKey, requestedAt, configUrl, scopeId, peerId: requestPeer, peerPublicKey, peerSignature, signature, } = fields;
749
+ if (typeof id !== "string" ||
750
+ !POINTER_ID_PATTERN.test(id) ||
751
+ !isCanonicalPublicKey(member) ||
752
+ !isCanonicalPublicKey(owner) ||
753
+ typeof name !== "string" ||
754
+ name.length > 256 ||
755
+ typeof encryptionKey !== "string" ||
756
+ encryptionKey.length > 256 ||
757
+ typeof requestedAt !== "string" ||
758
+ !Number.isFinite(Date.parse(requestedAt)) ||
759
+ typeof configUrl !== "string" ||
760
+ typeof scopeId !== "string" ||
761
+ coordinates(configUrl).scopeId !== scopeId ||
762
+ !isCanonicalPublicKey(peerPublicKey) ||
763
+ typeof requestPeer !== "string" ||
764
+ peerId(peerPublicKey) !== requestPeer ||
765
+ typeof peerSignature !== "string" ||
766
+ typeof signature !== "string")
767
+ throw new HostError("Invalid self-contained Request.");
522
768
  const body = {
523
- swarm: CID.parse(swarm).toV1().toString(),
524
- member: identity.publicKey,
525
- requestId: toBase64Url(randomBytes(18)),
526
- iat: now(),
527
- exp: now() + 7 * 86400,
769
+ v: 1,
770
+ id,
771
+ requestedAt,
772
+ configUrl,
773
+ scopeId,
774
+ owner,
775
+ name,
776
+ member,
777
+ encryptionKey,
778
+ peerId: requestPeer,
779
+ peerPublicKey,
780
+ };
781
+ if (!(await verifyEd25519(await importPublicKeyRaw(peerPublicKey), peerSignature, requestMessage(body))) ||
782
+ !(await verifyEd25519(await importPublicKeyRaw(member), signature, JSON.stringify(["IPAB-REQUEST-MEMBER/1", body, peerSignature]))))
783
+ throw new HostError("Request member or PeerID possession proof is invalid.");
784
+ return { ...body, peerSignature, signature };
785
+ }
786
+ export async function membershipRequestSummary(request) {
787
+ return [
788
+ `Request: ${request.id}`,
789
+ `Target: ${request.configUrl}`,
790
+ `Name: ${JSON.stringify(request.name)}`,
791
+ `Member public key: ${request.member}`,
792
+ `Member fingerprint: ${await keyId(request.member)}`,
793
+ `PeerID: ${request.peerId}`,
794
+ `Requested at: ${JSON.stringify(request.requestedAt)}`,
795
+ "Verify the applicant through an independent trusted channel before approving.",
796
+ ].join("\n");
797
+ }
798
+ async function ownerCheck(context, url) {
799
+ const identity = await contextIdentity(context), record = await readyMembership(context, url);
800
+ if (identity.publicKey !== record.owner)
801
+ throw new HostError("Only the pinned Owner can manage membership or organization configuration.");
802
+ const transition = await readPrivate(await directory(context), `transition-${localName(url)}`);
803
+ if (transition && !transition.completed)
804
+ throw new HostError("Organization switch incomplete: run swarm resume for this URL before other Owner changes.");
805
+ return { identity, record };
806
+ }
807
+ export async function approveMembership(context, input, options = {}) {
808
+ const request = typeof input === "string"
809
+ ? await verifiedRequest(input)
810
+ : await verifyRequest(input), url = request.configUrl;
811
+ const dir = await directory(context);
812
+ return withPrivateLock(dir, async () => {
813
+ const { identity, record } = await ownerCheck(context, url);
814
+ if (request.owner !== identity.publicKey)
815
+ throw new HostError("Request targets a different Owner.");
816
+ let operation = await readPrivate(dir, `approval-${request.id}.json`);
817
+ if (operation && !operation.completed && options.again)
818
+ throw new HostError("The prior approval is unconfirmed; resume the same Request without --again before starting a new explicit approval.");
819
+ if (operation?.completed && !options.again) {
820
+ if (operation.owner !== identity.publicKey ||
821
+ JSON.stringify(operation.request) !== JSON.stringify(request))
822
+ throw new HostError("This Request ID differs from advisory history; manually verify it and use --again for a new explicit approval.");
823
+ context.diagnostic?.(`Previously approved Request ${request.id} from ${request.requestedAt}. History is advisory, not a revocation boundary.`);
824
+ context.diagnostic?.("Reusing the completed approval result without granting new authority. Use --again only after fresh manual confirmation.");
825
+ return url;
826
+ }
827
+ if (!operation || options.again) {
828
+ operation = {
829
+ owner: identity.publicKey,
830
+ request,
831
+ operation: uniqueId(),
832
+ createdAt: new Date().toISOString(),
833
+ };
834
+ await writePrivate(dir, `approval-${request.id}.json`, operation);
835
+ }
836
+ if (operation.owner !== identity.publicKey ||
837
+ JSON.stringify(operation.request) !== JSON.stringify(request))
838
+ throw new HostError("Saved approval does not match this exact Request.");
839
+ const save = () => writePrivate(dir, `approval-${request.id}.json`, operation);
840
+ const c = coordinates(url), api = client(context, c.service, identity);
841
+ const fetched = await fetchConfig(context, url);
842
+ if (fetched.config.epoch !== record.config.epoch ||
843
+ fetched.config.headId !== record.config.headId)
844
+ throw new HostError("Owner local keys are not synchronized with this organization epoch.");
845
+ if (!operation.profileId) {
846
+ const previousMember = fetched.config.members.find((m) => m.publicKey === request.member);
847
+ if (previousMember && previousMember.peerId !== request.peerId)
848
+ throw new HostError("PeerID rebinding requires removing the old membership first, then explicitly approving this Request.");
849
+ const existingProfile = fetched.config.members.find((m) => m.publicKey === request.member)?.profileId;
850
+ if (existingProfile)
851
+ operation.profileId = existingProfile;
852
+ if (!operation.profileId)
853
+ operation.profileId = (await api.create(c.scopeId, {
854
+ name: request.name,
855
+ addresses: [],
856
+ updatedAt: operation.createdAt,
857
+ }, `${operation.operation}.profile`)).id;
858
+ await save();
859
+ }
860
+ if (!operation.value) {
861
+ const member = {
862
+ publicKey: request.member,
863
+ encryptionKey: request.encryptionKey,
864
+ peerId: request.peerId,
865
+ profileId: operation.profileId,
866
+ requestId: request.id,
867
+ approval: null,
868
+ };
869
+ const config = {
870
+ ...fetched.config,
871
+ members: fetched.config.members.filter((m) => m.publicKey !== request.member),
872
+ };
873
+ if (config.members.some((m) => m.peerId === request.peerId))
874
+ throw new HostError("PeerID is already assigned to another member.");
875
+ if (request.member === identity.publicKey)
876
+ throw new HostError("Owner cannot request member approval.");
877
+ if (config.members.length >= 16)
878
+ throw new HostError("Organization member limit is 16.");
879
+ const certificate = await issueScopeCertificate({
880
+ v: 1,
881
+ service: c.service,
882
+ scopeId: c.scopeId,
883
+ subject: request.member,
884
+ write: [config.headId, member.profileId],
885
+ }, await importPrivateKeyPkcs8(identity.privateKey));
886
+ member.approval = await sealApproval(binding(url, config, member), { certificate, swarmKey: record.secret.swarmKey }, identity);
887
+ config.members.push(member);
888
+ operation.value = config;
889
+ operation.baseline = fetched.variable.cid;
890
+ await save();
891
+ }
892
+ const observed = await api.read(c.scopeId, c.configId);
893
+ if (observed.cid !== (await valueCid(operation.value)))
894
+ await api.write(c.scopeId, c.configId, operation.value, operation.baseline, `${operation.operation}.publish`);
895
+ operation.completed = true;
896
+ await save();
897
+ record.config = operation.value;
898
+ await saveLocal(context, record);
899
+ return url;
900
+ });
901
+ }
902
+ export async function updateSwarm(context, url, changes) {
903
+ if ((changes.name?.length ?? 0) > 256 ||
904
+ (changes.description?.length ?? 0) > 2048)
905
+ throw new HostError("Organization name/description limit exceeded.");
906
+ const { identity, record } = await ownerCheck(context, url), c = coordinates(url);
907
+ if (changes.name === undefined && changes.description === undefined)
908
+ throw new HostError("swarm update requires name or description.");
909
+ const fetched = await fetchConfig(context, url), config = { ...fetched.config, ...changes };
910
+ const result = await client(context, c.service, identity).write(c.scopeId, c.configId, config, fetched.variable.cid, uniqueId());
911
+ record.config = config;
912
+ await saveLocal(context, record);
913
+ return {
914
+ configUrl: url,
915
+ headId: config.headId,
916
+ valueCid: result.cid,
917
+ properties: { name: config.name, description: config.description },
528
918
  };
529
- const request = {
530
- ...body,
531
- signature: await signEd25519(await importPrivateKeyPkcs8(identity.privateKey), requestMessage(data, body)),
919
+ }
920
+ export async function updateProfile(context, url, changes) {
921
+ if (changes.name !== undefined && changes.name.length > 256)
922
+ throw new HostError("Profile name exceeds 256 characters.");
923
+ if ((changes.addresses?.length ?? 0) > 16)
924
+ throw new HostError("Profile address limit is 16.");
925
+ const record = await readyMembership(context, url), identity = await contextIdentity(context), c = coordinates(url);
926
+ const member = record.config.members.find((m) => m.publicKey === identity.publicKey);
927
+ for (const address of changes.addresses ?? [])
928
+ validateAddress(address, member.peerId);
929
+ const api = client(context, c.service, identity, identity.publicKey === record.owner ? undefined : record.secret);
930
+ const existing = await api.read(c.scopeId, member.profileId);
931
+ const profile = {
932
+ ...parseProfile(existing.value, member.peerId),
933
+ ...changes,
934
+ updatedAt: new Date().toISOString(),
532
935
  };
533
- const cid = await jsonBundle(context.store, requestType, request);
534
- await provideContent(context.store, [cid, swarm], context.provider, context.fetch);
535
- await save(context, `${cid}.pending.json`, {
536
- swarm,
537
- member: identity.publicKey,
936
+ await api.write(c.scopeId, member.profileId, profile, existing.cid, uniqueId());
937
+ return profile;
938
+ }
939
+ export async function removeMember(context, url, member) {
940
+ const dir = await directory(context);
941
+ await withPrivateLock(dir, async () => {
942
+ const { identity, record: membership } = await ownerCheck(context, url);
943
+ if (member === identity.publicKey)
944
+ throw new HostError("Owner removal/recovery is unsupported.");
945
+ const fetched = await fetchConfig(context, url);
946
+ if (!fetched.config.members.some((m) => m.publicKey === member))
947
+ throw new HostError("Unknown member public key.");
948
+ const record = {
949
+ owner: identity.publicKey,
950
+ url,
951
+ operation: uniqueId(),
952
+ member,
953
+ oldConfig: fetched.config,
954
+ configCid: fetched.variable.cid,
955
+ oldKey: membership.secret.swarmKey,
956
+ newKey: randomBytes(32).toString("hex"),
957
+ };
958
+ await writePrivate(dir, `transition-${localName(url)}`, record);
538
959
  });
539
- return cid;
540
- }
541
- export async function approveMembership(context, requestCid, seconds = 7 * 86400) {
542
- if (!Number.isSafeInteger(seconds) || seconds < 60 || seconds > 30 * 86400)
543
- throw new HostError("Certificate duration must be 60 seconds to 30 days.");
544
- const { request, data } = await verifiedRequest(context.store, requestCid);
545
- const identity = await accountIdentity(context.env);
546
- if (identity.publicKey !== data.owner)
547
- throw new HostError("Only this swarm's owner can approve members.");
548
- const certificate = await issueCertificate({
549
- v: 2,
550
- service: data.service,
551
- pointerId: data.variable,
552
- owner: data.owner,
553
- member: request.member,
554
- cid: toBase64Url(randomBytes(16)),
555
- iat: now(),
556
- exp: now() + seconds,
557
- }, await importPrivateKeyPkcs8(identity.privateKey));
558
- const cid = await jsonBundle(context.store, responseType, {
559
- swarm: request.swarm,
560
- request: CID.parse(requestCid).toV1().toString(),
561
- certificate,
960
+ await resumeRemoval(context, url);
961
+ }
962
+ export async function resumeRemoval(context, url) {
963
+ const dir = await directory(context);
964
+ return withPrivateLock(dir, async () => {
965
+ const identity = await contextIdentity(context);
966
+ const record = await readPrivate(dir, `transition-${localName(url)}`);
967
+ if (!record || record.owner !== identity.publicKey || record.url !== url)
968
+ throw new HostError("No resumable switch owned by this identity.");
969
+ if (record.completed)
970
+ return;
971
+ const c = coordinates(url), api = client(context, c.service, identity);
972
+ const save = () => writePrivate(dir, `transition-${localName(url)}`, record);
973
+ try {
974
+ if (!record.finalHead) {
975
+ record.finalHead = await api.freeze(c.scopeId, record.oldConfig.headId, `${record.operation}.freeze`);
976
+ await save();
977
+ }
978
+ // Fetch the frozen final DAG while the old private network is still connected.
979
+ // A publication acknowledged immediately before freeze may not be cached on Owner.
980
+ const membershipBeforeSwitch = await local(context, url);
981
+ if (!record.finalCaptured) {
982
+ membershipBeforeSwitch.config = record.oldConfig;
983
+ membershipBeforeSwitch.secret.swarmKey = record.oldKey;
984
+ await activate(context, membershipBeforeSwitch);
985
+ if (!record.finalClosureRoots) {
986
+ record.finalClosureRoots = await frozenPublicationClosure(context.store, headValue(record.finalHead).root);
987
+ await save();
988
+ }
989
+ await provideContent(context.store, record.finalClosureRoots, context.node.api, context.fetch, context.node.auth);
990
+ record.finalCaptured = true;
991
+ await save();
992
+ }
993
+ if (!record.finalClosureRoots ||
994
+ record.finalClosureRoots[0] !== headValue(record.finalHead).root)
995
+ throw new HostError("Frozen publication closure is missing; refusing to retire the old network or HEAD.");
996
+ if (!record.newHeadId) {
997
+ record.newHeadId = (await api.create(c.scopeId, record.finalHead.value, `${record.operation}.newhead`)).id;
998
+ await save();
999
+ }
1000
+ if (!record.nextConfig) {
1001
+ const config = {
1002
+ ...record.oldConfig,
1003
+ headId: record.newHeadId,
1004
+ epoch: record.oldConfig.epoch + 1,
1005
+ members: structuredClone(record.oldConfig.members.filter((m) => m.publicKey !== record.member)),
1006
+ bootstrap: record.oldConfig.bootstrap.filter((address) => !address.endsWith(`/p2p/${record.oldConfig.members.find((m) => m.publicKey === record.member).peerId}`)),
1007
+ };
1008
+ for (const member of config.members) {
1009
+ if (member.publicKey === identity.publicKey)
1010
+ continue;
1011
+ const certificate = await issueScopeCertificate({
1012
+ v: 1,
1013
+ service: c.service,
1014
+ scopeId: c.scopeId,
1015
+ subject: member.publicKey,
1016
+ write: [config.headId, member.profileId],
1017
+ }, await importPrivateKeyPkcs8(identity.privateKey));
1018
+ member.approval = await sealApproval(binding(url, config, member), { certificate, swarmKey: record.newKey }, identity);
1019
+ }
1020
+ record.nextConfig = config;
1021
+ await save();
1022
+ }
1023
+ const leaving = record.oldConfig.members.find((m) => m.publicKey === record.member);
1024
+ // Delete the profile before exposing the new configuration. Old HEAD stays readable until final cleanup.
1025
+ try {
1026
+ await api.freeze(c.scopeId, leaving.profileId, `${record.operation}.profilefreeze`);
1027
+ }
1028
+ catch (cause) {
1029
+ if (!(cause instanceof ScopeApiError) || cause.status !== 410)
1030
+ throw cause;
1031
+ }
1032
+ try {
1033
+ await api.delete(c.scopeId, leaving.profileId, `${record.operation}.profiledelete`);
1034
+ }
1035
+ catch (cause) {
1036
+ if (!(cause instanceof ScopeApiError) || cause.status !== 410)
1037
+ throw cause;
1038
+ }
1039
+ if (!record.published) {
1040
+ const observed = await api.read(c.scopeId, c.configId);
1041
+ if (observed.cid !== (await valueCid(record.nextConfig)))
1042
+ await api.write(c.scopeId, c.configId, record.nextConfig, record.configCid, `${record.operation}.config`);
1043
+ record.published = true;
1044
+ await save();
1045
+ }
1046
+ const membership = await local(context, url);
1047
+ membership.config = record.nextConfig;
1048
+ membership.secret.swarmKey = record.newKey;
1049
+ await saveLocal(context, membership);
1050
+ await activate(context, membership);
1051
+ await provideContent(context.store, record.finalClosureRoots, context.node.api, context.fetch, context.node.auth);
1052
+ try {
1053
+ await api.delete(c.scopeId, record.oldConfig.headId, `${record.operation}.delete`);
1054
+ }
1055
+ catch (cause) {
1056
+ if (!(cause instanceof ScopeApiError) || cause.status !== 410)
1057
+ throw cause;
1058
+ }
1059
+ record.completed = true;
1060
+ await save();
1061
+ withState(context, (state) => {
1062
+ state.invalidateSwarmHeader(url);
1063
+ });
1064
+ }
1065
+ catch (cause) {
1066
+ throw new HostError(`Organization switch incomplete (old HEAD is never unfrozen): ${message(cause)}. Owner must run swarm resume ${url}.`);
1067
+ }
562
1068
  });
563
- await provideContent(context.store, [cid, requestCid, request.swarm], context.provider, context.fetch);
564
- return cid;
565
- }
566
- export async function joinSwarm(context, responseCid, alias) {
567
- const response = await typedJson(context.store, responseCid, responseType);
568
- const { request } = await verifiedRequest(context.store, response.request);
569
- const identity = await accountIdentity(context.env);
570
- const pending = object(await saved(context, `${response.request}.pending.json`), "pending request");
571
- if (request.swarm !== response.swarm ||
572
- request.member !== identity.publicKey ||
573
- pending.swarm !== response.swarm ||
574
- pending.member !== identity.publicKey)
575
- throw new HostError("Response does not match this account's exact pending request and target swarm.");
576
- const client = await pointer(context, response.swarm, response.certificate);
577
- if (alias !== undefined)
578
- withState(context, (state) => {
579
- state.checkSwarmAlias(alias, response.swarm);
580
- });
581
- await client.read();
582
- try {
583
- await save(context, `${response.swarm}.json`, {
584
- certificate: response.certificate,
585
- request: response.request,
586
- });
587
- }
588
- catch (cause) {
589
- if (!nodeError(cause, "EEXIST"))
590
- throw cause;
591
- const previous = object(await saved(context, `${response.swarm}.json`), "membership");
592
- if (previous.request !== response.request)
593
- throw new HostError("An existing membership differs; explicit renewal is outside this MVP.");
594
- }
595
- try {
596
- await addSwarm(context, response.swarm, alias);
597
- }
598
- catch (cause) {
599
- throw new HostError(`Membership certificate was saved, but swarm registration failed: ${message(cause)}. Retry the same response or run ipab swarm add ${response.swarm}.`);
600
- }
601
- return response.swarm;
602
1069
  }
603
1070
  export function formalName(name) {
604
1071
  relativePath(name);
@@ -608,55 +1075,58 @@ export function formalName(name) {
608
1075
  }
609
1076
  export function parseNameReference(reference) {
610
1077
  if (/^name:/i.test(reference))
611
- throw new HostError("name: references are no longer supported. Use ipab://SWARM_CID_OR_ALIAS/PATH or ipab:///PATH.", 2);
1078
+ throw new HostError("name: is unsupported; use ipab://ALIAS/PATH.");
612
1079
  if (!/^ipab:/i.test(reference))
613
1080
  return undefined;
614
1081
  const match = /^ipab:\/\/([^/]*)\/([^?#\s]*)$/i.exec(reference);
615
- if (!match || (match[1] && !/^[A-Za-z0-9][A-Za-z0-9._-]*$/.test(match[1])))
616
- throw new HostError("Invalid IPAB URI. Use ipab://SWARM_CID_OR_ALIAS/PATH or ipab:///PATH without credentials, port, query or fragment; percent-encode path segments.", 2);
1082
+ if (!match)
1083
+ throw new HostError("Invalid IPAB URI; percent-encode the configuration URL authority and each path segment.");
1084
+ const authority = decodeURIComponent(match[1]);
1085
+ if (authority && !/^[A-Za-z0-9][A-Za-z0-9._-]*$/.test(authority))
1086
+ canonicalSwarmUrl(authority);
617
1087
  const segments = match[2].split("/").map((segment) => {
618
- let decoded;
619
- try {
620
- decoded = decodeURIComponent(segment);
621
- }
622
- catch {
623
- throw new HostError("Invalid percent encoding in IPAB URI path.", 2);
624
- }
1088
+ const decoded = decodeURIComponent(segment);
625
1089
  if (decoded.includes("/"))
626
- throw new HostError("Encoded path separators are not allowed in IPAB URIs.", 2);
1090
+ throw new HostError("Encoded path separators are unsupported.");
627
1091
  return decoded;
628
1092
  });
629
1093
  return {
630
- ...(match[1] ? { swarm: match[1] } : {}),
1094
+ ...(authority ? { swarm: authority } : {}),
631
1095
  name: formalName(segments.join("/")),
632
1096
  };
633
1097
  }
1098
+ function referenceFor(url, name) {
1099
+ const segment = (value) => encodeURIComponent(value).replace(/[!'()*]/g, (char) => `%${char.charCodeAt(0).toString(16).toUpperCase()}`);
1100
+ return `ipab://${segment(url)}/${name.split("/").map(segment).join("/")}`;
1101
+ }
634
1102
  export async function resolveReference(context, reference, swarm, local, raw = false) {
635
- let targetCid;
636
1103
  const shared = parseNameReference(reference);
1104
+ let targetCid;
637
1105
  if (shared) {
638
- const authority = shared.swarm;
639
- const selectedSwarm = authority
640
- ? withState(context, (state) => state.resolveSwarm(authority))
1106
+ const selected = shared.swarm
1107
+ ? withState(context, (state) => state.resolveSwarm(shared.swarm))
641
1108
  : swarm;
642
- if (!selectedSwarm)
643
- throw new HostError("Shared Names require a swarm in the URI, --swarm CID_OR_ALIAS or swarm.default. Run ipab swarm use CID_OR_ALIAS.");
644
- const name = shared.name;
645
- let header = await swarmHeader(context, selectedSwarm);
646
- const lookup = () => Object.hasOwn(header.snapshot.names, name)
647
- ? header.snapshot.names[name]
1109
+ if (!selected)
1110
+ throw new HostError("Select a configuration URL/alias using --swarm or swarm use.");
1111
+ let header = await swarmHeader(context, selected);
1112
+ let link = Object.hasOwn(header.snapshot.names, shared.name)
1113
+ ? header.snapshot.names[shared.name]
648
1114
  : undefined;
649
- let link = lookup();
650
1115
  if (!link && header.source === "cache") {
651
- header = await swarmHeader(context, selectedSwarm, true);
652
- link = lookup();
1116
+ header = await swarmHeader(context, selected, true);
1117
+ link = Object.hasOwn(header.snapshot.names, shared.name)
1118
+ ? header.snapshot.names[shared.name]
1119
+ : undefined;
653
1120
  }
654
1121
  if (!link)
655
- throw new HostError(`Formal Name "${name}" is not present in this swarm after refreshing HEAD.`);
1122
+ throw new HostError(`Formal Name "${shared.name}" was not found after refreshing HEAD.`);
656
1123
  targetCid = link.toString();
657
1124
  }
658
- else
1125
+ else {
1126
+ if (swarm)
1127
+ await readyMembership(context, swarm);
659
1128
  targetCid = local(reference);
1129
+ }
660
1130
  let cid = targetCid;
661
1131
  const visited = new Set();
662
1132
  for (let depth = 0; !raw; depth++) {
@@ -668,11 +1138,40 @@ export async function resolveReference(context, reference, swarm, local, raw = f
668
1138
  });
669
1139
  if (bundle.schemaKey !== (await encodeSchema(artifactType)).cid.toString())
670
1140
  break;
671
- const artifact = await typedJson(context.store, cid, artifactType);
672
- cid = CID.parse(artifact.value).toV1().toString();
1141
+ cid = CID.parse(parseArtifact(await typedJson(context.store, cid, artifactType)).value)
1142
+ .toV1()
1143
+ .toString();
673
1144
  }
674
1145
  return { targetCid, cid };
675
1146
  }
1147
+ export async function searchNames(context, query, swarms) {
1148
+ if (!query ||
1149
+ query.length > 256 ||
1150
+ [...query].some((char) => char.charCodeAt(0) < 32 || char.charCodeAt(0) === 127))
1151
+ throw new HostError("Search query must be 1..256 characters without controls.");
1152
+ const matches = [];
1153
+ const searched = [];
1154
+ for (const swarm of swarms) {
1155
+ const header = await swarmHeader(context, swarm.cid);
1156
+ searched.push({
1157
+ configUrl: swarm.cid,
1158
+ source: header.source,
1159
+ root: header.head.root,
1160
+ valueCid: header.head.cid,
1161
+ verifiedAt: header.verifiedAt,
1162
+ });
1163
+ for (const name of Object.keys(header.snapshot.names).sort())
1164
+ if (name.toLowerCase().includes(query.toLowerCase()))
1165
+ matches.push({
1166
+ swarm: swarm.cid,
1167
+ alias: swarm.alias,
1168
+ name,
1169
+ reference: referenceFor(swarm.cid, name),
1170
+ targetCid: header.snapshot.names[name].toString(),
1171
+ });
1172
+ }
1173
+ return { matches, swarms: searched };
1174
+ }
676
1175
  async function dependencies(store, root, found = new Set()) {
677
1176
  if (found.has(root))
678
1177
  return found;
@@ -683,15 +1182,15 @@ async function dependencies(store, root, found = new Set()) {
683
1182
  resolveCid: (cid) => store.block.get(cid.toString()),
684
1183
  });
685
1184
  if (bundle.schemaKey === (await encodeSchema(artifactType)).cid.toString()) {
686
- const node = await typedJson(store, root, artifactType);
1185
+ const node = parseArtifact(await typedJson(store, root, artifactType));
687
1186
  await dependencies(store, node.value, found);
688
1187
  if (node.previous)
689
1188
  await dependencies(store, node.previous, found);
690
1189
  }
691
1190
  else if (bundle.schemaKey === appSchemaCid.toString()) {
692
- const app = object(JSON.parse(new TextDecoder().decode(await bytes(await bundle.readFile(bundle.manifest.entry.path), 64 * 1024))), "App");
1191
+ const app = object(JSON.parse(new TextDecoder().decode(await bytes(await bundle.readFile(bundle.manifest.entry), 64 * 1024))), "App");
693
1192
  if (app.source) {
694
- const source = object(app.source, "App source");
1193
+ const source = object(app.source, "source");
695
1194
  if (typeof source.cid !== "string")
696
1195
  throw new HostError("Invalid App source association.");
697
1196
  await dependencies(store, source.cid, found);
@@ -699,24 +1198,46 @@ async function dependencies(store, root, found = new Set()) {
699
1198
  }
700
1199
  return found;
701
1200
  }
1201
+ export async function frozenPublicationClosure(store, root) {
1202
+ const publications = new Set(), content = new Set();
1203
+ let current = root;
1204
+ while (current !== undefined) {
1205
+ if (publications.has(current) || publications.size >= 256)
1206
+ throw new HostError("Frozen publication history exceeds limits or contains a cycle.");
1207
+ publications.add(current);
1208
+ const publication = await readPublication(store, current);
1209
+ const snapshot = decodeSnapshot(await store.block.get(publication.state.toString()));
1210
+ for (const target of Object.values(snapshot.names))
1211
+ await dependencies(store, target.toString(), content);
1212
+ current = publication.previous?.toString();
1213
+ }
1214
+ return [
1215
+ root,
1216
+ ...[...new Set([...publications, ...content])]
1217
+ .filter((cid) => cid !== root)
1218
+ .sort(),
1219
+ ];
1220
+ }
702
1221
  export async function publish(context, content, options) {
1222
+ if (!options.swarm)
1223
+ throw new HostError("Publication requires a selected Swarm configuration URL or alias.");
1224
+ const head = await pointer(context, options.swarm);
703
1225
  const roots = await dependencies(context.store, content);
704
1226
  if (!options.name) {
705
1227
  if (options.expect || options.snapshot)
706
1228
  throw new HostError("--expect/--snapshot require --name.");
707
- await provideContent(context.store, [...roots], context.provider, context.fetch);
1229
+ await head.read();
1230
+ await provideContent(context.store, [...roots], context.node.api, context.fetch, context.node.auth);
708
1231
  return content;
709
1232
  }
710
1233
  const name = formalName(options.name);
711
- if (!options.swarm)
712
- throw new HostError("Named publication requires --swarm CID or swarm.default.");
713
1234
  if (options.snapshot && options.expect)
714
- throw new HostError("Ordinary named snapshots cannot replace an occupied Name.");
1235
+ throw new HostError("Snapshots cannot replace an occupied Name.");
715
1236
  const expected = options.expect
716
1237
  ? CID.parse(options.expect).toV1().toString()
717
1238
  : undefined;
718
1239
  if (expected)
719
- await typedJson(context.store, expected, artifactType);
1240
+ parseArtifact(await typedJson(context.store, expected, artifactType));
720
1241
  const candidate = options.snapshot
721
1242
  ? content
722
1243
  : await jsonBundle(context.store, artifactType, {
@@ -728,33 +1249,29 @@ export async function publish(context, content, options) {
728
1249
  if (expected)
729
1250
  for (const root of await dependencies(context.store, expected))
730
1251
  roots.add(root);
731
- await provideContent(context.store, [...roots], context.provider, context.fetch);
732
- const client = await pointer(context, options.swarm);
733
1252
  for (let attempt = 0; attempt < 8; attempt++) {
734
- const head = await client.read();
735
- const current = await readSnapshot(context.store, head.root);
1253
+ const currentHead = await head.read(), current = await readSnapshot(context.store, currentHead.root);
736
1254
  if ((Object.hasOwn(current.names, name)
737
1255
  ? current.names[name]?.toString()
738
1256
  : undefined) !== expected)
739
- throw new HostError(`Edit conflict for ${name}; candidate ${candidate} and content ${content} remain retained. Refresh the Name and explicitly choose a baseline.`, 3, "EDIT_CONFLICT", "publication");
740
- const state = await writeSnapshot(context.store, {
1257
+ throw new HostError(`Edit conflict for ${name}; candidate ${candidate} remains retained. Choose an explicit baseline.`, 3, "EDIT_CONFLICT", "publication");
1258
+ const next = await publication(context.store, await writeSnapshot(context.store, {
741
1259
  ...current,
742
1260
  names: { ...current.names, [name]: CID.parse(candidate) },
1261
+ }), currentHead.root);
1262
+ await provideContent(context.store, [next, ...roots], context.node.api, context.fetch, context.node.auth);
1263
+ withState(context, (state) => {
1264
+ state.invalidateSwarmHeader(options.swarm);
743
1265
  });
744
- const next = await publication(context.store, state, head.root);
745
- await provideContent(context.store, [next, ...roots], context.provider, context.fetch);
746
1266
  try {
747
- withState(context, (state) => {
748
- state.invalidateSwarmHeader(options.swarm);
749
- });
750
- await client.write(next, head.revision, toBase64Url(randomBytes(18)));
1267
+ await head.write(next, currentHead.cid, uniqueId());
751
1268
  return candidate;
752
1269
  }
753
1270
  catch (cause) {
754
- if (!(cause instanceof PointerApiError) || cause.status !== 412)
755
- throw new HostError(`HEAD update failed or its result is unknown: ${message(cause)}. Candidate ${candidate} remains retained; authenticate swarm status before retrying.`, 1, "HEAD_UNCONFIRMED", "publication");
1271
+ if (!(cause instanceof ScopeApiError) || cause.status !== 412)
1272
+ throw new HostError(`HEAD publication unconfirmed: ${message(cause)}. Candidate ${candidate} remains retained; inspect HEAD before retry.`, 1, "HEAD_UNCONFIRMED", "publication");
756
1273
  }
757
1274
  }
758
- throw new HostError(`HEAD is busy; candidate ${candidate} remains retained. Retry the same explicit Name baseline.`);
1275
+ throw new HostError(`HEAD is busy; candidate ${candidate} remains retained.`);
759
1276
  }
760
1277
  //# sourceMappingURL=swarm.js.map