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

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 (101) hide show
  1. package/README.md +26 -4
  2. package/dist/app-authoring.d.ts +11 -2
  3. package/dist/app-authoring.d.ts.map +1 -1
  4. package/dist/app-authoring.js +135 -20
  5. package/dist/app-authoring.js.map +1 -1
  6. package/dist/app-definition.d.ts +0 -6
  7. package/dist/app-definition.d.ts.map +1 -1
  8. package/dist/app-definition.js +1 -7
  9. package/dist/app-definition.js.map +1 -1
  10. package/dist/app-templates.d.ts.map +1 -1
  11. package/dist/app-templates.js +8 -0
  12. package/dist/app-templates.js.map +1 -1
  13. package/dist/assembly.d.ts +7 -0
  14. package/dist/assembly.d.ts.map +1 -0
  15. package/dist/assembly.js +131 -0
  16. package/dist/assembly.js.map +1 -0
  17. package/dist/authoring.d.ts +6 -15
  18. package/dist/authoring.d.ts.map +1 -1
  19. package/dist/authoring.js +13 -42
  20. package/dist/authoring.js.map +1 -1
  21. package/dist/builtins/template.node.car +0 -0
  22. package/dist/builtins/template.web-app.car +0 -0
  23. package/dist/builtins.d.ts.map +1 -1
  24. package/dist/builtins.js +5 -10
  25. package/dist/builtins.js.map +1 -1
  26. package/dist/cli.d.ts +1 -0
  27. package/dist/cli.d.ts.map +1 -1
  28. package/dist/cli.js +639 -147
  29. package/dist/cli.js.map +1 -1
  30. package/dist/config-secret.d.ts +3 -0
  31. package/dist/config-secret.d.ts.map +1 -0
  32. package/dist/config-secret.js +83 -0
  33. package/dist/config-secret.js.map +1 -0
  34. package/dist/config.d.ts +7 -4
  35. package/dist/config.d.ts.map +1 -1
  36. package/dist/config.js +118 -22
  37. package/dist/config.js.map +1 -1
  38. package/dist/content-provider.d.ts +9 -0
  39. package/dist/content-provider.d.ts.map +1 -0
  40. package/dist/content-provider.js +90 -0
  41. package/dist/content-provider.js.map +1 -0
  42. package/dist/context.d.ts +1 -0
  43. package/dist/context.d.ts.map +1 -1
  44. package/dist/context.js +10 -0
  45. package/dist/context.js.map +1 -1
  46. package/dist/get.d.ts +3 -0
  47. package/dist/get.d.ts.map +1 -0
  48. package/dist/get.js +61 -0
  49. package/dist/get.js.map +1 -0
  50. package/dist/identity.d.ts +9 -0
  51. package/dist/identity.d.ts.map +1 -0
  52. package/dist/identity.js +89 -0
  53. package/dist/identity.js.map +1 -0
  54. package/dist/ipc.d.ts +2 -1
  55. package/dist/ipc.d.ts.map +1 -1
  56. package/dist/ipc.js +10 -1
  57. package/dist/ipc.js.map +1 -1
  58. package/dist/pins.d.ts +9 -9
  59. package/dist/pins.d.ts.map +1 -1
  60. package/dist/pins.js +10 -28
  61. package/dist/pins.js.map +1 -1
  62. package/dist/runtime.d.ts.map +1 -1
  63. package/dist/runtime.js +1 -1
  64. package/dist/runtime.js.map +1 -1
  65. package/dist/source-bundle.d.ts +0 -1
  66. package/dist/source-bundle.d.ts.map +1 -1
  67. package/dist/source-bundle.js +1 -2
  68. package/dist/source-bundle.js.map +1 -1
  69. package/dist/state.d.ts +35 -10
  70. package/dist/state.d.ts.map +1 -1
  71. package/dist/state.js +124 -14
  72. package/dist/state.js.map +1 -1
  73. package/dist/swarm.d.ts +113 -0
  74. package/dist/swarm.d.ts.map +1 -0
  75. package/dist/swarm.js +760 -0
  76. package/dist/swarm.js.map +1 -0
  77. package/dist/template-definition.d.ts +0 -17
  78. package/dist/template-definition.d.ts.map +1 -1
  79. package/dist/template-definition.js +1 -10
  80. package/dist/template-definition.js.map +1 -1
  81. package/package.json +15 -10
  82. package/src/app-authoring.ts +203 -29
  83. package/src/app-definition.ts +1 -7
  84. package/src/app-templates.ts +13 -0
  85. package/src/assembly.ts +182 -0
  86. package/src/authoring.ts +32 -58
  87. package/src/builtins.ts +5 -11
  88. package/src/cli.ts +785 -167
  89. package/src/config-secret.ts +96 -0
  90. package/src/config.ts +161 -25
  91. package/src/content-provider.ts +123 -0
  92. package/src/context.ts +10 -0
  93. package/src/get.ts +68 -0
  94. package/src/identity.ts +133 -0
  95. package/src/ipc.ts +8 -0
  96. package/src/pins.ts +14 -28
  97. package/src/runtime.ts +1 -0
  98. package/src/source-bundle.ts +1 -2
  99. package/src/state.ts +149 -24
  100. package/src/swarm.ts +1186 -0
  101. package/src/template-definition.ts +1 -10
package/dist/swarm.js ADDED
@@ -0,0 +1,760 @@
1
+ import { mkdir, lstat, open, readFile, rename, unlink } from "node:fs/promises";
2
+ import { join } from "node:path";
3
+ import { randomUUID } from "node:crypto";
4
+ import { stringify } from "yaml";
5
+ import { CarBlockIterator } from "@ipld/car/iterator";
6
+ import * as dagCbor from "@ipld/dag-cbor";
7
+ import { CID } from "multiformats/cid";
8
+ import { sha256 } from "multiformats/hashes/sha2";
9
+ import { encodeSchema, openBundle } from "@ipab/bundle";
10
+ 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";
15
+ import { HostError, object, message } from "./errors.js";
16
+ import { accountIdentity, protectedPath, secureNew, } from "./identity.js";
17
+ import { nodeError } from "./authoring.js";
18
+ import { bundleJson, provideContent } from "./content-provider.js";
19
+ import { bytes, relativePath } from "./space.js";
20
+ import { publicUrl } from "./config.js";
21
+ import { appSchemaCid } from "./app-definition.js";
22
+ import { State } from "./state.js";
23
+ 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
+ },
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
+ });
63
+ function withState(context, operation) {
64
+ if (context.state)
65
+ return operation(context.state);
66
+ const state = new State(context.stateDir);
67
+ try {
68
+ return operation(state);
69
+ }
70
+ finally {
71
+ state.close();
72
+ }
73
+ }
74
+ async function requestPointer(operation) {
75
+ for (let attempt = 0;; attempt++) {
76
+ try {
77
+ return await operation();
78
+ }
79
+ catch (cause) {
80
+ if (attempt >= 2 ||
81
+ !(cause instanceof Error) ||
82
+ !["TypeError", "AbortError", "TimeoutError"].includes(cause.name))
83
+ throw cause;
84
+ }
85
+ }
86
+ }
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
+ });
103
+ 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
+ })),
109
+ };
110
+ }
111
+ export async function typedJson(store, cid, type) {
112
+ const { bundle, value } = await bundleJson(store, cid);
113
+ if (bundle.schemaKey !== (await encodeSchema(type)).cid.toString())
114
+ throw new HostError(`Expected exact ${type.name} Bundle type.`);
115
+ return value;
116
+ }
117
+ export async function jsonBundle(store, type, value) {
118
+ const encoded = await encodeBundleCar(memoryTree(new Map([
119
+ [".bundle.yaml", new TextEncoder().encode(stringify(type))],
120
+ ["entry.json", new TextEncoder().encode(`${JSON.stringify(value)}\n`)],
121
+ ])));
122
+ try {
123
+ const iterator = await CarBlockIterator.fromIterable(streamChunks(encoded.stream));
124
+ for await (const block of iterator)
125
+ await store.put(block.cid, block.bytes);
126
+ return encoded.cid.toString();
127
+ }
128
+ finally {
129
+ await encoded.close();
130
+ }
131
+ }
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
+ export async function writeSnapshot(store, snapshot) {
216
+ const encoded = dagCbor.encode(snapshot);
217
+ const cid = CID.createV1(dagCbor.code, await sha256.digest(encoded));
218
+ await store.put(cid, encoded);
219
+ return cid.toString();
220
+ }
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.");
243
+ for (const [name, link] of Object.entries(names)) {
244
+ formalName(name);
245
+ if (!CID.asCID(link))
246
+ throw new HostError("Snapshot Name targets must be CID links.");
247
+ }
248
+ return value;
249
+ }
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);
253
+ 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
+ const cached = force
257
+ ? 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
+ }
294
+ }
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();
301
+ withState(context, (state) => {
302
+ state.saveSwarmHeader(identity.publicKey, swarm, {
303
+ ...head,
304
+ descriptor: data,
305
+ snapshot: Buffer.from(dagCbor.encode(snapshot)).toString("base64"),
306
+ verifiedAt,
307
+ });
308
+ });
309
+ return {
310
+ head,
311
+ snapshot,
312
+ source: "network",
313
+ verifiedAt: new Date(verifiedAt).toISOString(),
314
+ };
315
+ }
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));
324
+ }
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
+ };
357
+ }
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.");
362
+ }
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;
378
+ try {
379
+ header = await swarmHeader(context, swarm.cid);
380
+ }
381
+ catch (cause) {
382
+ throw new HostError(`Could not search swarm "${swarm.alias ?? swarm.cid}": ${message(cause)}. Search was not completed.`);
383
+ }
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
+ });
412
+ const cid = CID.createV1(dagCbor.code, await sha256.digest(bytes));
413
+ await store.put(cid, bytes);
414
+ return cid.toString();
415
+ }
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);
421
+ try {
422
+ await secureNew(temporary);
423
+ await handle.writeFile(JSON.stringify(record));
424
+ await handle.sync();
425
+ await handle.close();
426
+ await rename(temporary, target);
427
+ }
428
+ finally {
429
+ 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
+ }
438
+ }
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;
467
+ if (options.alias !== undefined)
468
+ withState(context, (state) => {
469
+ state.checkSwarmAlias(options.alias, record.cid);
470
+ });
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, {
476
+ 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(),
485
+ };
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,
507
+ };
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
+ }
518
+ }
519
+ export async function requestMembership(context, swarm) {
520
+ const identity = await accountIdentity(context.env, true);
521
+ const data = await descriptor(context.store, swarm);
522
+ 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,
528
+ };
529
+ const request = {
530
+ ...body,
531
+ signature: await signEd25519(await importPrivateKeyPkcs8(identity.privateKey), requestMessage(data, body)),
532
+ };
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,
538
+ });
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,
562
+ });
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
+ }
603
+ export function formalName(name) {
604
+ relativePath(name);
605
+ if (name.length > 256 || name.startsWith("builtin:"))
606
+ throw new HostError("Invalid formal Name.");
607
+ return name;
608
+ }
609
+ export function parseNameReference(reference) {
610
+ 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);
612
+ if (!/^ipab:/i.test(reference))
613
+ return undefined;
614
+ 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);
617
+ 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
+ }
625
+ if (decoded.includes("/"))
626
+ throw new HostError("Encoded path separators are not allowed in IPAB URIs.", 2);
627
+ return decoded;
628
+ });
629
+ return {
630
+ ...(match[1] ? { swarm: match[1] } : {}),
631
+ name: formalName(segments.join("/")),
632
+ };
633
+ }
634
+ export async function resolveReference(context, reference, swarm, local, raw = false) {
635
+ let targetCid;
636
+ const shared = parseNameReference(reference);
637
+ if (shared) {
638
+ const authority = shared.swarm;
639
+ const selectedSwarm = authority
640
+ ? withState(context, (state) => state.resolveSwarm(authority))
641
+ : 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]
648
+ : undefined;
649
+ let link = lookup();
650
+ if (!link && header.source === "cache") {
651
+ header = await swarmHeader(context, selectedSwarm, true);
652
+ link = lookup();
653
+ }
654
+ if (!link)
655
+ throw new HostError(`Formal Name "${name}" is not present in this swarm after refreshing HEAD.`);
656
+ targetCid = link.toString();
657
+ }
658
+ else
659
+ targetCid = local(reference);
660
+ let cid = targetCid;
661
+ const visited = new Set();
662
+ for (let depth = 0; !raw; depth++) {
663
+ if (depth >= 64 || visited.has(cid))
664
+ throw new HostError("Artifact resolution exceeds limits or contains a cycle.");
665
+ visited.add(cid);
666
+ const bundle = await openBundle(CID.parse(cid), {
667
+ resolveCid: (cid) => context.store.block.get(cid.toString()),
668
+ });
669
+ if (bundle.schemaKey !== (await encodeSchema(artifactType)).cid.toString())
670
+ break;
671
+ const artifact = await typedJson(context.store, cid, artifactType);
672
+ cid = CID.parse(artifact.value).toV1().toString();
673
+ }
674
+ return { targetCid, cid };
675
+ }
676
+ async function dependencies(store, root, found = new Set()) {
677
+ if (found.has(root))
678
+ return found;
679
+ if (found.size >= 256)
680
+ throw new HostError("Publication dependency/history limit exceeded.");
681
+ found.add(root);
682
+ const bundle = await openBundle(CID.parse(root), {
683
+ resolveCid: (cid) => store.block.get(cid.toString()),
684
+ });
685
+ if (bundle.schemaKey === (await encodeSchema(artifactType)).cid.toString()) {
686
+ const node = await typedJson(store, root, artifactType);
687
+ await dependencies(store, node.value, found);
688
+ if (node.previous)
689
+ await dependencies(store, node.previous, found);
690
+ }
691
+ 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");
693
+ if (app.source) {
694
+ const source = object(app.source, "App source");
695
+ if (typeof source.cid !== "string")
696
+ throw new HostError("Invalid App source association.");
697
+ await dependencies(store, source.cid, found);
698
+ }
699
+ }
700
+ return found;
701
+ }
702
+ export async function publish(context, content, options) {
703
+ const roots = await dependencies(context.store, content);
704
+ if (!options.name) {
705
+ if (options.expect || options.snapshot)
706
+ throw new HostError("--expect/--snapshot require --name.");
707
+ await provideContent(context.store, [...roots], context.provider, context.fetch);
708
+ return content;
709
+ }
710
+ const name = formalName(options.name);
711
+ if (!options.swarm)
712
+ throw new HostError("Named publication requires --swarm CID or swarm.default.");
713
+ if (options.snapshot && options.expect)
714
+ throw new HostError("Ordinary named snapshots cannot replace an occupied Name.");
715
+ const expected = options.expect
716
+ ? CID.parse(options.expect).toV1().toString()
717
+ : undefined;
718
+ if (expected)
719
+ await typedJson(context.store, expected, artifactType);
720
+ const candidate = options.snapshot
721
+ ? content
722
+ : await jsonBundle(context.store, artifactType, {
723
+ value: content,
724
+ ...(expected ? { previous: expected } : {}),
725
+ timestamp: new Date().toISOString(),
726
+ });
727
+ roots.add(candidate);
728
+ if (expected)
729
+ for (const root of await dependencies(context.store, expected))
730
+ roots.add(root);
731
+ await provideContent(context.store, [...roots], context.provider, context.fetch);
732
+ const client = await pointer(context, options.swarm);
733
+ for (let attempt = 0; attempt < 8; attempt++) {
734
+ const head = await client.read();
735
+ const current = await readSnapshot(context.store, head.root);
736
+ if ((Object.hasOwn(current.names, name)
737
+ ? current.names[name]?.toString()
738
+ : 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, {
741
+ ...current,
742
+ names: { ...current.names, [name]: CID.parse(candidate) },
743
+ });
744
+ const next = await publication(context.store, state, head.root);
745
+ await provideContent(context.store, [next, ...roots], context.provider, context.fetch);
746
+ try {
747
+ withState(context, (state) => {
748
+ state.invalidateSwarmHeader(options.swarm);
749
+ });
750
+ await client.write(next, head.revision, toBase64Url(randomBytes(18)));
751
+ return candidate;
752
+ }
753
+ 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");
756
+ }
757
+ }
758
+ throw new HostError(`HEAD is busy; candidate ${candidate} remains retained. Retry the same explicit Name baseline.`);
759
+ }
760
+ //# sourceMappingURL=swarm.js.map