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