@ipab/cli 0.1.0-rc.6 → 0.1.0-rc.8
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.
- package/README.md +96 -34
- package/dist/app-authoring.d.ts +5 -0
- package/dist/app-authoring.d.ts.map +1 -1
- package/dist/app-authoring.js +6 -45
- package/dist/app-authoring.js.map +1 -1
- package/dist/app-prebuild.d.ts +18 -0
- package/dist/app-prebuild.d.ts.map +1 -1
- package/dist/app-prebuild.js +46 -0
- package/dist/app-prebuild.js.map +1 -1
- package/dist/app-templates.d.ts +0 -1
- package/dist/app-templates.d.ts.map +1 -1
- package/dist/app-templates.js +6 -45
- package/dist/app-templates.js.map +1 -1
- package/dist/builtins/skill.ipab.car +0 -0
- package/dist/builtins/template.bundle-viewer.car +0 -0
- package/dist/builtins/template.check.car +0 -0
- package/dist/builtins/template.node.car +0 -0
- package/dist/builtins/template.web-app.car +0 -0
- package/dist/builtins.d.ts.map +1 -1
- package/dist/builtins.js +1 -39
- package/dist/builtins.js.map +1 -1
- package/dist/cli.d.ts +1 -0
- package/dist/cli.d.ts.map +1 -1
- package/dist/cli.js +668 -221
- package/dist/cli.js.map +1 -1
- package/dist/config.d.ts +1 -1
- package/dist/config.d.ts.map +1 -1
- package/dist/config.js +9 -4
- package/dist/config.js.map +1 -1
- package/dist/context.d.ts +20 -0
- package/dist/context.d.ts.map +1 -1
- package/dist/context.js +31 -2
- package/dist/context.js.map +1 -1
- package/dist/errors.d.ts +1 -8
- package/dist/errors.d.ts.map +1 -1
- package/dist/errors.js +1 -20
- package/dist/errors.js.map +1 -1
- package/dist/host-error.d.ts +9 -0
- package/dist/host-error.d.ts.map +1 -0
- package/dist/host-error.js +21 -0
- package/dist/host-error.js.map +1 -0
- package/dist/ipc.d.ts +2 -1
- package/dist/ipc.d.ts.map +1 -1
- package/dist/ipc.js +61 -3
- package/dist/ipc.js.map +1 -1
- package/dist/kubo-install.js +1 -1
- package/dist/kubo-install.js.map +1 -1
- package/dist/kubo-peers.d.ts.map +1 -1
- package/dist/kubo-peers.js +2 -1
- package/dist/kubo-peers.js.map +1 -1
- package/dist/kubo-topology.d.ts +19 -0
- package/dist/kubo-topology.d.ts.map +1 -0
- package/dist/kubo-topology.js +105 -0
- package/dist/kubo-topology.js.map +1 -0
- package/dist/kubo.d.ts +10 -0
- package/dist/kubo.d.ts.map +1 -1
- package/dist/kubo.js +96 -15
- package/dist/kubo.js.map +1 -1
- package/dist/runtime.d.ts.map +1 -1
- package/dist/runtime.js +6 -3
- package/dist/runtime.js.map +1 -1
- package/dist/skill-definition.d.ts +6 -0
- package/dist/skill-definition.d.ts.map +1 -0
- package/dist/skill-definition.js +38 -0
- package/dist/skill-definition.js.map +1 -0
- package/dist/skill-source.d.ts +5 -0
- package/dist/skill-source.d.ts.map +1 -0
- package/dist/skill-source.js +12 -0
- package/dist/skill-source.js.map +1 -0
- package/dist/skills.d.ts +84 -0
- package/dist/skills.d.ts.map +1 -0
- package/dist/skills.js +736 -0
- package/dist/skills.js.map +1 -0
- package/dist/space-path.d.ts +3 -0
- package/dist/space-path.d.ts.map +1 -0
- package/dist/space-path.js +17 -0
- package/dist/space-path.js.map +1 -0
- package/dist/space.d.ts +16 -4
- package/dist/space.d.ts.map +1 -1
- package/dist/space.js +155 -18
- package/dist/space.js.map +1 -1
- package/dist/state-storage.js +1 -1
- package/dist/state-storage.js.map +1 -1
- package/dist/state.d.ts +2 -0
- package/dist/state.d.ts.map +1 -1
- package/dist/state.js +32 -13
- package/dist/state.js.map +1 -1
- package/dist/swarm-files.d.ts +2 -2
- package/dist/swarm-files.d.ts.map +1 -1
- package/dist/swarm-files.js +4 -4
- package/dist/swarm-files.js.map +1 -1
- package/dist/swarm-meta.d.ts +14 -0
- package/dist/swarm-meta.d.ts.map +1 -0
- package/dist/swarm-meta.js +65 -0
- package/dist/swarm-meta.js.map +1 -0
- package/dist/swarm-observations.d.ts +40 -0
- package/dist/swarm-observations.d.ts.map +1 -0
- package/dist/swarm-observations.js +262 -0
- package/dist/swarm-observations.js.map +1 -0
- package/dist/swarm.d.ts +172 -6
- package/dist/swarm.d.ts.map +1 -1
- package/dist/swarm.js +1106 -132
- package/dist/swarm.js.map +1 -1
- package/dist/template-paths.d.ts +7 -0
- package/dist/template-paths.d.ts.map +1 -0
- package/dist/template-paths.js +23 -0
- package/dist/template-paths.js.map +1 -0
- package/dist/template-presentation.d.ts +20 -0
- package/dist/template-presentation.d.ts.map +1 -0
- package/dist/template-presentation.js +133 -0
- package/dist/template-presentation.js.map +1 -0
- package/dist/template-source.d.ts +2 -1
- package/dist/template-source.d.ts.map +1 -1
- package/dist/template-source.js +7 -1
- package/dist/template-source.js.map +1 -1
- package/dist/templates.d.ts +11 -0
- package/dist/templates.d.ts.map +1 -0
- package/dist/templates.js +53 -0
- package/dist/templates.js.map +1 -0
- package/package.json +7 -6
- package/src/app-authoring.ts +30 -55
- package/src/app-prebuild.ts +61 -0
- package/src/app-templates.ts +8 -72
- package/src/builtins.ts +2 -48
- package/src/cli.ts +830 -247
- package/src/config.ts +12 -4
- package/src/context.ts +60 -2
- package/src/errors.ts +1 -25
- package/src/host-error.ts +26 -0
- package/src/ipc.ts +82 -2
- package/src/kubo-install.ts +1 -1
- package/src/kubo-peers.ts +2 -3
- package/src/kubo-topology.ts +135 -0
- package/src/kubo.ts +134 -25
- package/src/runtime.ts +6 -2
- package/src/skill-definition.ts +53 -0
- package/src/skill-source.ts +15 -0
- package/src/skills.ts +1005 -0
- package/src/space-path.ts +30 -0
- package/src/space.ts +216 -33
- package/src/state-storage.ts +1 -1
- package/src/state.ts +38 -13
- package/src/swarm-files.ts +4 -2
- package/src/swarm-meta.ts +90 -0
- package/src/swarm-observations.ts +374 -0
- package/src/swarm.ts +1637 -193
- package/src/template-paths.ts +43 -0
- package/src/template-presentation.ts +151 -0
- package/src/template-source.ts +9 -2
- package/src/templates.ts +77 -0
package/dist/swarm.js
CHANGED
|
@@ -2,6 +2,7 @@ import { createReadStream } from "node:fs";
|
|
|
2
2
|
import { lstat, mkdir, open } from "node:fs/promises";
|
|
3
3
|
import { homedir } from "node:os";
|
|
4
4
|
import { join, resolve } from "node:path";
|
|
5
|
+
import { setTimeout as delay } from "node:timers/promises";
|
|
5
6
|
import { createHash, randomBytes } from "node:crypto";
|
|
6
7
|
import { stringify } from "yaml";
|
|
7
8
|
import { CarBlockIterator } from "@ipld/car/iterator";
|
|
@@ -18,15 +19,22 @@ import { HostError, object, message } from "./errors.js";
|
|
|
18
19
|
import { accountIdentity, protectedPath, secureNew, } from "./identity.js";
|
|
19
20
|
import { nodeError } from "./authoring.js";
|
|
20
21
|
import { swarmUrl as canonicalSwarmUrl } from "./config.js";
|
|
21
|
-
import { bundleJson, provideContent } from "./content-provider.js";
|
|
22
|
+
import { bundleJson, contentCar, provideContent } from "./content-provider.js";
|
|
22
23
|
import { failedPin, pinCid, refreshPinClaim, reservePin, retainPin, } from "./pins.js";
|
|
23
24
|
import { bytes, relativePath } from "./space.js";
|
|
24
25
|
import { appSchemaCid } from "./app-definition.js";
|
|
25
26
|
import { State, createAssociation, exactCid, } from "./state.js";
|
|
26
27
|
import { privateDirectory, readPrivate, withPrivateLock, writePrivate, } from "./swarm-files.js";
|
|
27
28
|
import { encryptionIdentity, openApproval, sealApproval, parseEnvelope, validateEncryptionIdentity, } from "./swarm-envelope.js";
|
|
28
|
-
import { checkCachedNode, kuboSource, peerId, peerProof, prepareNode, startNode, validateAddress, } from "./kubo.js";
|
|
29
|
+
import { checkCachedNode, kuboSource, peerId, peerProof, prepareNode, startNode, stopNode, probePeer, nodeConnections, validateAddress, } from "./kubo.js";
|
|
29
30
|
import { memberPeers } from "./kubo-peering.js";
|
|
31
|
+
import { PivotCandidates } from "./kubo-topology.js";
|
|
32
|
+
import { networkingBinding, pivotLocalStatus, readNetworkingSnapshot, writeNetworkingSnapshot, networkingAccount, } from "./swarm-observations.js";
|
|
33
|
+
import { seedTemplateNames, seedTemplateSource } from "./template-source.js";
|
|
34
|
+
import { inspectTemplate, templatePublicationSource } from "./templates.js";
|
|
35
|
+
import { seedSkillSource } from "./skill-source.js";
|
|
36
|
+
import { skillIdentity, skillSchema } from "./skill-definition.js";
|
|
37
|
+
import { parseSwarmMeta, swarmMetaType, swarmMetaSchema, swarmStateType, previousSwarmStateType, previousSwarmStateSchema, parseSwarmState, legacySwarmStateType, legacySwarmStateSchema, isSwarmStateSchema, legacySwarmMetaType, legacySwarmMetaSchema, } from "./swarm-meta.js";
|
|
30
38
|
async function contextIdentity(context, initialize = false) {
|
|
31
39
|
context.identity ??= await accountIdentity(context.env, initialize);
|
|
32
40
|
return context.identity;
|
|
@@ -142,6 +150,8 @@ function client(context, service, identity, secret) {
|
|
|
142
150
|
}
|
|
143
151
|
function parseOrganization(value, configUrl) {
|
|
144
152
|
const data = object(value, "organization configuration");
|
|
153
|
+
if (data.kind === "ipab-config-reservation")
|
|
154
|
+
throw new HostError("Swarm creation is initializing; the Owner must resume the saved creation operation.");
|
|
145
155
|
const { scopeId } = coordinates(configUrl);
|
|
146
156
|
if (Object.keys(data).sort().join() !==
|
|
147
157
|
"bootstrap,description,epoch,headId,members,name,owner,scopeId,v" ||
|
|
@@ -227,10 +237,8 @@ function parseOrganization(value, configUrl) {
|
|
|
227
237
|
}
|
|
228
238
|
function parseProfile(value, expectedPeer) {
|
|
229
239
|
const data = object(value, "member profile");
|
|
230
|
-
if (![
|
|
231
|
-
"
|
|
232
|
-
"addresses,description,name,updatedAt",
|
|
233
|
-
].includes(Object.keys(data).sort().join()) ||
|
|
240
|
+
if (Object.keys(data).some((key) => !["addresses", "name", "description", "updatedAt", "pivot"].includes(key)) ||
|
|
241
|
+
(data.pivot !== undefined && typeof data.pivot !== "boolean") ||
|
|
234
242
|
typeof data.name !== "string" ||
|
|
235
243
|
data.name.length > 256 ||
|
|
236
244
|
(data.description !== undefined &&
|
|
@@ -254,22 +262,269 @@ function parseProfile(value, expectedPeer) {
|
|
|
254
262
|
? { description: data.description }
|
|
255
263
|
: {}),
|
|
256
264
|
addresses,
|
|
265
|
+
...(typeof data.pivot === "boolean" ? { pivot: data.pivot } : {}),
|
|
257
266
|
updatedAt: data.updatedAt,
|
|
258
267
|
};
|
|
259
268
|
}
|
|
260
|
-
|
|
261
|
-
const { config } = await fetchConfig(context, canonicalSwarmUrl(url));
|
|
269
|
+
async function memberDirectory(context, url, config) {
|
|
262
270
|
const c = coordinates(url), api = client(context, c.service);
|
|
263
271
|
const members = await boundedMap(config.members, async (member) => {
|
|
264
272
|
const profile = parseProfile((await api.read(c.scopeId, member.profileId)).value, member.peerId);
|
|
273
|
+
return { member, profile };
|
|
274
|
+
});
|
|
275
|
+
return members;
|
|
276
|
+
}
|
|
277
|
+
async function localObservations(context, url, config) {
|
|
278
|
+
try {
|
|
279
|
+
const account = context.identity?.publicKey ??
|
|
280
|
+
(await networkingAccount(context.stateDir, url));
|
|
281
|
+
const self = config.members.find((member) => member.publicKey === account);
|
|
282
|
+
if (!self || !account)
|
|
283
|
+
throw new HostError("No bound local daemon observations; run ipab daemon after normal membership activation.");
|
|
284
|
+
const c = coordinates(url);
|
|
285
|
+
const local = await readNetworkingSnapshot(context.stateDir, url, networkingBinding(url, account, config), nodeScope(c.service, config.scopeId), config.epoch, self.peerId);
|
|
265
286
|
return {
|
|
266
|
-
|
|
267
|
-
|
|
268
|
-
|
|
269
|
-
|
|
287
|
+
account: context.identity?.publicKey ?? (local.snapshot ? account : undefined),
|
|
288
|
+
local,
|
|
289
|
+
};
|
|
290
|
+
}
|
|
291
|
+
catch (cause) {
|
|
292
|
+
return {
|
|
293
|
+
account: context.identity?.publicKey,
|
|
294
|
+
local: {
|
|
295
|
+
status: "unavailable",
|
|
296
|
+
updatedAt: null,
|
|
297
|
+
verifiedAt: null,
|
|
298
|
+
error: message(cause),
|
|
299
|
+
snapshot: null,
|
|
300
|
+
},
|
|
270
301
|
};
|
|
302
|
+
}
|
|
303
|
+
}
|
|
304
|
+
function observationSummary(local) {
|
|
305
|
+
return {
|
|
306
|
+
status: local.status,
|
|
307
|
+
updatedAt: local.updatedAt,
|
|
308
|
+
verifiedAt: local.verifiedAt,
|
|
309
|
+
error: local.error,
|
|
310
|
+
};
|
|
311
|
+
}
|
|
312
|
+
function parseInspection(input, url) {
|
|
313
|
+
const data = object(input, "Swarm inspection cache");
|
|
314
|
+
if (Object.keys(data).sort().join() !==
|
|
315
|
+
"config,configUrl,directory,head,updatedAt,v" ||
|
|
316
|
+
data.v !== 1 ||
|
|
317
|
+
data.configUrl !== url ||
|
|
318
|
+
typeof data.updatedAt !== "number" ||
|
|
319
|
+
!Number.isSafeInteger(data.updatedAt) ||
|
|
320
|
+
data.updatedAt < 0 ||
|
|
321
|
+
data.updatedAt > 8_640_000_000_000_000 ||
|
|
322
|
+
!Array.isArray(data.directory) ||
|
|
323
|
+
data.directory.length > 256)
|
|
324
|
+
throw new HostError("Invalid Swarm inspection cache; retry with --refresh.");
|
|
325
|
+
const config = parseOrganization(data.config, url);
|
|
326
|
+
if (config.members.some((member) => !/^[A-Za-z0-9]{32,128}$/.test(member.peerId)))
|
|
327
|
+
throw new HostError("Invalid cached member PeerID; use --refresh.");
|
|
328
|
+
if (data.directory.length !== config.members.length)
|
|
329
|
+
throw new HostError("Incomplete Swarm inspection directory; use --refresh.");
|
|
330
|
+
const directory = data.directory.map((input, index) => {
|
|
331
|
+
const entry = object(input, "cached directory entry");
|
|
332
|
+
const member = config.members[index];
|
|
333
|
+
if (Object.keys(entry).sort().join() !== "member,profile" ||
|
|
334
|
+
JSON.stringify(entry.member) !== JSON.stringify(member))
|
|
335
|
+
throw new HostError("Cached member binding mismatch; use --refresh.");
|
|
336
|
+
return { member, profile: parseProfile(entry.profile, member.peerId) };
|
|
271
337
|
});
|
|
272
|
-
|
|
338
|
+
const head = object(data.head, "cached HEAD");
|
|
339
|
+
if (Object.keys(head).sort().join() !== "cid,root" ||
|
|
340
|
+
typeof head.root !== "string" ||
|
|
341
|
+
typeof head.cid !== "string" ||
|
|
342
|
+
exactCid(head.root) !== head.root ||
|
|
343
|
+
exactCid(head.cid) !== head.cid)
|
|
344
|
+
throw new HostError("Invalid cached HEAD; use --refresh.");
|
|
345
|
+
return {
|
|
346
|
+
v: 1,
|
|
347
|
+
configUrl: url,
|
|
348
|
+
updatedAt: data.updatedAt,
|
|
349
|
+
config,
|
|
350
|
+
directory,
|
|
351
|
+
head: { root: head.root, cid: head.cid },
|
|
352
|
+
};
|
|
353
|
+
}
|
|
354
|
+
async function inspection(context, url, refresh = false) {
|
|
355
|
+
canonicalSwarmUrl(url);
|
|
356
|
+
const parent = join(context.stateDir, "swarm-inspections");
|
|
357
|
+
const name = `${createHash("sha256").update(url).digest("hex")}.json`;
|
|
358
|
+
const saved = refresh
|
|
359
|
+
? undefined
|
|
360
|
+
: await readPrivate(parent, name, [
|
|
361
|
+
{ path: parent, directory: true },
|
|
362
|
+
]);
|
|
363
|
+
let snapshot;
|
|
364
|
+
if (saved === undefined) {
|
|
365
|
+
snapshot = await withPrivateLock(await privateDirectory(context.stateDir, "swarm-inspections"), async () => {
|
|
366
|
+
const { config, variable } = await fetchConfig(context, url);
|
|
367
|
+
const directory = await memberDirectory(context, url, config);
|
|
368
|
+
const c = coordinates(url);
|
|
369
|
+
const head = headValue(await client(context, c.service).read(c.scopeId, config.headId));
|
|
370
|
+
const confirmed = await fetchConfig(context, url);
|
|
371
|
+
if (variable.cid !== confirmed.variable.cid ||
|
|
372
|
+
JSON.stringify(config) !== JSON.stringify(confirmed.config))
|
|
373
|
+
throw new HostError("Swarm configuration changed during inspection; retry --refresh.");
|
|
374
|
+
// Inspection persists only public declarations, never approval envelopes.
|
|
375
|
+
const publicConfig = {
|
|
376
|
+
...config,
|
|
377
|
+
members: config.members.map((member) => ({
|
|
378
|
+
...member,
|
|
379
|
+
approval: null,
|
|
380
|
+
})),
|
|
381
|
+
};
|
|
382
|
+
const fresh = parseInspection({
|
|
383
|
+
v: 1,
|
|
384
|
+
configUrl: url,
|
|
385
|
+
updatedAt: Date.now(),
|
|
386
|
+
config: publicConfig,
|
|
387
|
+
directory: directory.map(({ profile }, index) => ({
|
|
388
|
+
member: publicConfig.members[index],
|
|
389
|
+
profile,
|
|
390
|
+
})),
|
|
391
|
+
head: { root: head.root, cid: head.cid },
|
|
392
|
+
}, url);
|
|
393
|
+
if (Buffer.byteLength(JSON.stringify(fresh)) > 2 * 1024 * 1024)
|
|
394
|
+
throw new HostError("Swarm inspection snapshot is oversized.");
|
|
395
|
+
await writePrivate(parent, name, fresh);
|
|
396
|
+
return fresh;
|
|
397
|
+
});
|
|
398
|
+
}
|
|
399
|
+
else {
|
|
400
|
+
snapshot = parseInspection(saved, url);
|
|
401
|
+
}
|
|
402
|
+
const age = Date.now() - snapshot.updatedAt;
|
|
403
|
+
return {
|
|
404
|
+
...snapshot,
|
|
405
|
+
cache: {
|
|
406
|
+
source: saved === undefined ? "network" : "cache",
|
|
407
|
+
updatedAt: new Date(snapshot.updatedAt).toISOString(),
|
|
408
|
+
freshness: age >= 0 && age < (context.cacheTtl ?? 300) * 1000
|
|
409
|
+
? "current"
|
|
410
|
+
: "stale",
|
|
411
|
+
},
|
|
412
|
+
};
|
|
413
|
+
}
|
|
414
|
+
export async function swarmMembers(context, url, refresh = false) {
|
|
415
|
+
const { config, directory, cache } = await inspection(context, url, refresh);
|
|
416
|
+
const observations = await localObservations(context, url, config);
|
|
417
|
+
const members = directory.map(({ member, profile }) => ({
|
|
418
|
+
publicKey: member.publicKey,
|
|
419
|
+
role: member.publicKey === config.owner ? "owner" : "member",
|
|
420
|
+
name: profile.name,
|
|
421
|
+
description: profile.description ?? "",
|
|
422
|
+
pivot: profile.pivot === true,
|
|
423
|
+
localStatus: pivotLocalStatus(profile.pivot === true, member.publicKey === observations.account, profile.addresses, member.peerId, observations.local),
|
|
424
|
+
peerId: member.peerId,
|
|
425
|
+
updatedAt: profile.updatedAt,
|
|
426
|
+
}));
|
|
427
|
+
return {
|
|
428
|
+
configUrl: url,
|
|
429
|
+
members,
|
|
430
|
+
cache,
|
|
431
|
+
local: observationSummary(observations.local),
|
|
432
|
+
};
|
|
433
|
+
}
|
|
434
|
+
export async function swarmNetworking(context, url, config, directory) {
|
|
435
|
+
directory ??= (await inspection(context, url)).directory;
|
|
436
|
+
const { account, local } = await localObservations(context, url, config);
|
|
437
|
+
const saved = local.snapshot?.connections;
|
|
438
|
+
const observedAt = saved?.observedAt == null ? null : new Date(saved.observedAt).toISOString();
|
|
439
|
+
const connectionError = local.status !== "current"
|
|
440
|
+
? (local.error ?? "Daemon observations are not current.")
|
|
441
|
+
: saved === undefined || saved.observedAt === null
|
|
442
|
+
? "No daemon connection snapshot; run ipab daemon."
|
|
443
|
+
: saved.error;
|
|
444
|
+
const connections = saved?.peers ?? [];
|
|
445
|
+
const freshness = connectionError || !saved?.observedAt
|
|
446
|
+
? observedAt
|
|
447
|
+
? "stale"
|
|
448
|
+
: "unavailable"
|
|
449
|
+
: Date.now() - saved.observedAt > 90_000
|
|
450
|
+
? "stale"
|
|
451
|
+
: "current";
|
|
452
|
+
const currentConnections = freshness === "current";
|
|
453
|
+
return {
|
|
454
|
+
daemon: observationSummary(local),
|
|
455
|
+
connections: {
|
|
456
|
+
observedAt,
|
|
457
|
+
error: connectionError,
|
|
458
|
+
peers: connections,
|
|
459
|
+
freshness,
|
|
460
|
+
},
|
|
461
|
+
pivots: directory
|
|
462
|
+
.filter(({ profile }) => profile.pivot === true)
|
|
463
|
+
.map(({ member, profile }) => {
|
|
464
|
+
const localStatus = pivotLocalStatus(true, member.publicKey === account, profile.addresses, member.peerId, local);
|
|
465
|
+
const observation = local.snapshot?.pivots.find((entry) => entry.peerId === member.peerId);
|
|
466
|
+
const matching = observation &&
|
|
467
|
+
JSON.stringify(observation.addresses) ===
|
|
468
|
+
JSON.stringify([...new Set(profile.addresses)].sort());
|
|
469
|
+
const current = local.status === "current" && matching;
|
|
470
|
+
const actual = connections.filter((entry) => entry.peerId === member.peerId);
|
|
471
|
+
const probeFreshness = matching && observation.probedAt !== null
|
|
472
|
+
? current && Date.now() - observation.probedAt <= 90_000
|
|
473
|
+
? "current"
|
|
474
|
+
: "stale"
|
|
475
|
+
: "unavailable";
|
|
476
|
+
const connectionStatus = member.publicKey === account
|
|
477
|
+
? "self"
|
|
478
|
+
: !currentConnections
|
|
479
|
+
? "unknown"
|
|
480
|
+
: actual.some((entry) => entry.transport === "direct")
|
|
481
|
+
? "direct"
|
|
482
|
+
: actual.length
|
|
483
|
+
? "relay"
|
|
484
|
+
: "disconnected";
|
|
485
|
+
return {
|
|
486
|
+
publicKey: member.publicKey,
|
|
487
|
+
name: profile.name,
|
|
488
|
+
peerId: member.peerId,
|
|
489
|
+
pivot: true,
|
|
490
|
+
addresses: profile.addresses,
|
|
491
|
+
localStatus,
|
|
492
|
+
selected: localStatus === "unknown" ? null : localStatus === "selected",
|
|
493
|
+
failures: matching ? observation.failures : null,
|
|
494
|
+
retryAt: matching && observation.retryAt > 0
|
|
495
|
+
? new Date(observation.retryAt).toISOString()
|
|
496
|
+
: null,
|
|
497
|
+
probe: {
|
|
498
|
+
result: matching ? observation.probe : "unknown",
|
|
499
|
+
at: matching && observation.probedAt !== null
|
|
500
|
+
? new Date(observation.probedAt).toISOString()
|
|
501
|
+
: null,
|
|
502
|
+
error: matching ? observation.error : null,
|
|
503
|
+
freshness: probeFreshness,
|
|
504
|
+
},
|
|
505
|
+
connection: {
|
|
506
|
+
status: connectionStatus,
|
|
507
|
+
observedAt,
|
|
508
|
+
error: connectionError,
|
|
509
|
+
freshness,
|
|
510
|
+
addresses: actual.map((entry) => entry.address),
|
|
511
|
+
},
|
|
512
|
+
};
|
|
513
|
+
}),
|
|
514
|
+
};
|
|
515
|
+
}
|
|
516
|
+
export async function inspectSwarmStatus(context, url, refresh = false) {
|
|
517
|
+
const { config, directory, head, cache } = await inspection(context, url, refresh);
|
|
518
|
+
return {
|
|
519
|
+
config,
|
|
520
|
+
head,
|
|
521
|
+
cache,
|
|
522
|
+
state: {
|
|
523
|
+
status: "unavailable",
|
|
524
|
+
error: "State content is not fetched or verified by inspection; use get ipab:/// to obtain the State Bundle.",
|
|
525
|
+
},
|
|
526
|
+
networking: await swarmNetworking(context, url, config, directory),
|
|
527
|
+
};
|
|
273
528
|
}
|
|
274
529
|
function accountProfileLocation(context, publicKey) {
|
|
275
530
|
return {
|
|
@@ -540,7 +795,7 @@ async function validateMembershipSecret(record, config, member) {
|
|
|
540
795
|
throw new HostError("Membership package must grant exactly HEAD and this member's profile.");
|
|
541
796
|
}
|
|
542
797
|
}
|
|
543
|
-
async function privateSource(context, record, signal) {
|
|
798
|
+
async function privateSource(context, record, signal, candidates) {
|
|
544
799
|
const config = record.config, secret = record.secret;
|
|
545
800
|
const identity = await contextIdentity(context);
|
|
546
801
|
const self = config.members.find((member) => member.publicKey === identity.publicKey);
|
|
@@ -553,36 +808,102 @@ async function privateSource(context, record, signal) {
|
|
|
553
808
|
}
|
|
554
809
|
const personal = await storedAccountProfile(context);
|
|
555
810
|
const addresses = new Map();
|
|
811
|
+
const observationErrors = [];
|
|
556
812
|
const api = client(context, c.service);
|
|
557
813
|
let selfProfile;
|
|
558
|
-
const profiles = await boundedMap(config.members, (member) =>
|
|
814
|
+
const profiles = await boundedMap(config.members, async (member) => {
|
|
815
|
+
try {
|
|
816
|
+
return await api.read(c.scopeId, member.profileId, signal ? { signal } : {});
|
|
817
|
+
}
|
|
818
|
+
catch (cause) {
|
|
819
|
+
signal?.throwIfAborted();
|
|
820
|
+
if (!candidates)
|
|
821
|
+
throw cause;
|
|
822
|
+
observationErrors.push(`Profile ${member.peerId}: ${message(cause)}`);
|
|
823
|
+
context.diagnostic?.(`Pivot profile refresh ${member.peerId} failed; retaining last-known approved candidate: ${message(cause)}`);
|
|
824
|
+
return undefined;
|
|
825
|
+
}
|
|
826
|
+
});
|
|
559
827
|
for (const [index, member] of config.members.entries()) {
|
|
560
828
|
const profile = profiles[index];
|
|
829
|
+
if (!profile) {
|
|
830
|
+
const known = candidates?.known(member.peerId);
|
|
831
|
+
if (known)
|
|
832
|
+
addresses.set(member.peerId, known);
|
|
833
|
+
continue;
|
|
834
|
+
}
|
|
561
835
|
const value = parseProfile(profile.value, member.peerId);
|
|
562
836
|
if (member.publicKey === identity.publicKey)
|
|
563
837
|
selfProfile = { profile: value, cid: profile.cid };
|
|
564
|
-
|
|
838
|
+
if (value.pivot === true && member.peerId !== self.peerId)
|
|
839
|
+
addresses.set(member.peerId, value.addresses);
|
|
565
840
|
}
|
|
566
841
|
if (personal && selfProfile) {
|
|
567
842
|
selfProfile.profile = await syncAccountProfile(context, record, personal, selfProfile);
|
|
568
843
|
selfProfile.cid = await valueCid(selfProfile.profile);
|
|
569
844
|
}
|
|
570
|
-
|
|
845
|
+
candidates?.reconcile(addresses);
|
|
846
|
+
const active = candidates?.active() ?? addresses;
|
|
847
|
+
if (!candidates) {
|
|
848
|
+
try {
|
|
849
|
+
const observed = await readNetworkingSnapshot(context.stateDir, record.configUrl, networkingBinding(record.configUrl, identity.publicKey, config), nodeScope(c.service, config.scopeId), config.epoch, self.peerId);
|
|
850
|
+
if (observed.status === "current")
|
|
851
|
+
for (const pivot of observed.snapshot.pivots)
|
|
852
|
+
if (pivot.retryAt > Date.now() &&
|
|
853
|
+
JSON.stringify([...new Set(active.get(pivot.peerId) ?? [])].sort()) === JSON.stringify(pivot.addresses))
|
|
854
|
+
active.delete(pivot.peerId);
|
|
855
|
+
}
|
|
856
|
+
catch (cause) {
|
|
857
|
+
context.diagnostic?.(`Local daemon observations could not be read: ${message(cause)}`);
|
|
858
|
+
}
|
|
859
|
+
}
|
|
860
|
+
const desired = memberPeers(self.peerId, active, []);
|
|
571
861
|
signal?.throwIfAborted();
|
|
572
|
-
const node = await startNode(context.stateDir, nodeScope(c.service, config.scopeId), secret.swarmKey, config.epoch, context.listen, {
|
|
862
|
+
const node = await startNode(context.stateDir, nodeScope(c.service, config.scopeId), secret.swarmKey, config.epoch, context.listen, {
|
|
863
|
+
self: self.peerId,
|
|
864
|
+
peers: desired,
|
|
865
|
+
pivot: context.pivot ?? false,
|
|
866
|
+
...(signal ? { signal } : {}),
|
|
867
|
+
});
|
|
573
868
|
if (node.peerId !== self.peerId)
|
|
574
869
|
throw new HostError("Approved PeerID differs from this local Request's Kubo identity.");
|
|
575
870
|
const peers = desired.flatMap(({ ID, Addrs }) => Addrs.map((addr) => `${addr}/p2p/${ID}`));
|
|
576
871
|
signal?.throwIfAborted();
|
|
577
|
-
if (
|
|
578
|
-
|
|
579
|
-
|
|
580
|
-
|
|
581
|
-
|
|
872
|
+
if (context.pivot &&
|
|
873
|
+
!node.addresses.length &&
|
|
874
|
+
!selfProfile?.profile.addresses.length)
|
|
875
|
+
context.diagnostic?.("Pivot has no IPv4 candidates. Connect an interface or set manual candidates with swarm profile --address.");
|
|
876
|
+
if (selfProfile) {
|
|
877
|
+
const dir = await directory(context);
|
|
878
|
+
const preference = `pivot-${localName(record.configUrl)}`;
|
|
879
|
+
const saved = await readPrivate(dir, preference);
|
|
880
|
+
const manual = saved?.manual ?? selfProfile.profile.addresses;
|
|
881
|
+
for (const address of manual)
|
|
882
|
+
validateAddress(address, self.peerId);
|
|
883
|
+
if (!saved && context.pivot)
|
|
884
|
+
await writePrivate(dir, preference, { manual });
|
|
885
|
+
const published = context.pivot
|
|
886
|
+
? [...new Set([...manual, ...node.addresses])].slice(0, 16).sort()
|
|
887
|
+
: manual;
|
|
888
|
+
if (context.pivot && new Set([...manual, ...node.addresses]).size > 16)
|
|
889
|
+
context.diagnostic?.("Pivot profile is capped at 16 candidates; manual hints take priority over interface snapshots.");
|
|
890
|
+
const pivot = context.pivot ?? false;
|
|
891
|
+
if (selfProfile.profile.pivot === pivot &&
|
|
892
|
+
JSON.stringify([...selfProfile.profile.addresses].sort()) ===
|
|
893
|
+
JSON.stringify(published))
|
|
894
|
+
return {
|
|
895
|
+
node,
|
|
896
|
+
peers,
|
|
897
|
+
observationError: observationErrors.length
|
|
898
|
+
? observationErrors.join("; ")
|
|
899
|
+
: null,
|
|
900
|
+
source: kuboSource(node, peers, context.diagnostic, context.env.IPAB_SWARM_DIAL_DEBUG === "1"),
|
|
901
|
+
};
|
|
582
902
|
const writer = client(context, c.service, identity, identity.publicKey === config.owner ? undefined : secret);
|
|
583
903
|
const profile = {
|
|
584
904
|
...selfProfile.profile,
|
|
585
|
-
|
|
905
|
+
pivot,
|
|
906
|
+
addresses: published,
|
|
586
907
|
updatedAt: new Date().toISOString(),
|
|
587
908
|
};
|
|
588
909
|
await writer.write(c.scopeId, self.profileId, profile, selfProfile.cid, uniqueId(), signal ? { signal } : {});
|
|
@@ -590,9 +911,201 @@ async function privateSource(context, record, signal) {
|
|
|
590
911
|
return {
|
|
591
912
|
node,
|
|
592
913
|
peers,
|
|
914
|
+
observationError: observationErrors.length
|
|
915
|
+
? observationErrors.join("; ")
|
|
916
|
+
: null,
|
|
593
917
|
source: kuboSource(node, peers, context.diagnostic, context.env.IPAB_SWARM_DIAL_DEBUG === "1"),
|
|
594
918
|
};
|
|
595
919
|
}
|
|
920
|
+
export async function swarmDaemon(context, selected, signal) {
|
|
921
|
+
const lock = await privateDirectory(context.stateDir, "swarm-daemon");
|
|
922
|
+
await withPrivateLock(lock, async () => {
|
|
923
|
+
const sessions = new Map();
|
|
924
|
+
context.diagnostic?.("IPAB daemon running in foreground; Ctrl-C stops management and leaves Kubo running.");
|
|
925
|
+
const persist = async (url, session, running) => {
|
|
926
|
+
const record = session.record;
|
|
927
|
+
if (!record?.config)
|
|
928
|
+
return;
|
|
929
|
+
const redact = (error) => {
|
|
930
|
+
if (error === null)
|
|
931
|
+
return null;
|
|
932
|
+
for (const secret of [
|
|
933
|
+
record.secret?.swarmKey,
|
|
934
|
+
session.node?.auth,
|
|
935
|
+
session.context.identity?.privateKey,
|
|
936
|
+
])
|
|
937
|
+
if (secret)
|
|
938
|
+
error = error.split(secret).join("[redacted]");
|
|
939
|
+
return error.slice(0, 2048);
|
|
940
|
+
};
|
|
941
|
+
const snapshot = {
|
|
942
|
+
v: 1,
|
|
943
|
+
binding: networkingBinding(url, record.account, record.config),
|
|
944
|
+
pid: process.pid,
|
|
945
|
+
running,
|
|
946
|
+
updatedAt: Date.now(),
|
|
947
|
+
verifiedAt: session.verifiedAt,
|
|
948
|
+
error: redact(session.error),
|
|
949
|
+
topology: session.node?.topology ?? null,
|
|
950
|
+
pivots: [...session.candidates.observations()].map(([peerId, value]) => ({
|
|
951
|
+
...value,
|
|
952
|
+
peerId,
|
|
953
|
+
selected: session.selected.has(peerId),
|
|
954
|
+
error: redact(value.error),
|
|
955
|
+
})),
|
|
956
|
+
account: record.account,
|
|
957
|
+
connections: session.connections
|
|
958
|
+
? {
|
|
959
|
+
...session.connections,
|
|
960
|
+
error: redact(session.connections.error),
|
|
961
|
+
}
|
|
962
|
+
: {
|
|
963
|
+
observedAt: null,
|
|
964
|
+
error: "No connection snapshot collected.",
|
|
965
|
+
peers: [],
|
|
966
|
+
},
|
|
967
|
+
};
|
|
968
|
+
await writeNetworkingSnapshot(context.stateDir, url, snapshot);
|
|
969
|
+
};
|
|
970
|
+
try {
|
|
971
|
+
while (!signal.aborted) {
|
|
972
|
+
const registrations = withState(context, (state) => state.swarms()).filter((entry) => selected === undefined || entry.cid === selected);
|
|
973
|
+
if (selected && !registrations.length)
|
|
974
|
+
throw new HostError("Selected Swarm is not registered; run ipab swarm add first.");
|
|
975
|
+
const urls = new Set(registrations.map((entry) => entry.cid));
|
|
976
|
+
for (const url of sessions.keys())
|
|
977
|
+
if (!urls.has(url)) {
|
|
978
|
+
await persist(url, sessions.get(url), false);
|
|
979
|
+
sessions.delete(url);
|
|
980
|
+
}
|
|
981
|
+
await boundedMap(registrations, async ({ cid: url }) => {
|
|
982
|
+
let session = sessions.get(url);
|
|
983
|
+
if (!session) {
|
|
984
|
+
session = {
|
|
985
|
+
context: { ...context },
|
|
986
|
+
candidates: new PivotCandidates(),
|
|
987
|
+
nextDiscovery: 0,
|
|
988
|
+
healthy: 0,
|
|
989
|
+
selected: new Set(),
|
|
990
|
+
verifiedAt: null,
|
|
991
|
+
error: null,
|
|
992
|
+
};
|
|
993
|
+
sessions.set(url, session);
|
|
994
|
+
}
|
|
995
|
+
try {
|
|
996
|
+
if (Date.now() >= session.nextDiscovery || session.healthy < 1) {
|
|
997
|
+
const record = await approvedMembership(session.context, url, signal);
|
|
998
|
+
const c = coordinates(url);
|
|
999
|
+
const scope = nodeScope(c.service, record.config.scopeId);
|
|
1000
|
+
const existing = await readPrivate(join(context.stateDir, "swarm-nodes", scope), "node.json");
|
|
1001
|
+
if (!existing)
|
|
1002
|
+
throw new HostError("No existing managed node; activate this membership before running daemon.");
|
|
1003
|
+
await saveLocal(session.context, record);
|
|
1004
|
+
if (!session.record?.config ||
|
|
1005
|
+
networkingBinding(url, record.account, record.config) !==
|
|
1006
|
+
networkingBinding(url, session.record.account, session.record.config)) {
|
|
1007
|
+
session.candidates.reconcile(new Map());
|
|
1008
|
+
session.selected.clear();
|
|
1009
|
+
session.verifiedAt = null;
|
|
1010
|
+
delete session.connections;
|
|
1011
|
+
delete session.node;
|
|
1012
|
+
}
|
|
1013
|
+
session.record = record;
|
|
1014
|
+
const result = await privateSource(session.context, record, signal, session.candidates);
|
|
1015
|
+
session.node = result.node;
|
|
1016
|
+
session.selected = new Set(result.peers.map((address) => address.split("/").at(-1)));
|
|
1017
|
+
session.error = result.observationError;
|
|
1018
|
+
if (!session.error)
|
|
1019
|
+
session.verifiedAt = Date.now();
|
|
1020
|
+
session.context.node = result.node;
|
|
1021
|
+
session.nextDiscovery = Date.now() + 120_000;
|
|
1022
|
+
await persist(url, session, true);
|
|
1023
|
+
}
|
|
1024
|
+
if (!session.node)
|
|
1025
|
+
return;
|
|
1026
|
+
let healthy = 0;
|
|
1027
|
+
await boundedMap([...session.candidates.active()], async ([id, addresses]) => {
|
|
1028
|
+
let success = false;
|
|
1029
|
+
let error = null;
|
|
1030
|
+
try {
|
|
1031
|
+
success = await probePeer(session.node, id, addresses, signal);
|
|
1032
|
+
}
|
|
1033
|
+
catch (cause) {
|
|
1034
|
+
signal.throwIfAborted();
|
|
1035
|
+
error = message(cause);
|
|
1036
|
+
context.diagnostic?.(`[${url}] Pivot probe ${id}: ${message(cause)}`);
|
|
1037
|
+
}
|
|
1038
|
+
session.candidates.result(id, success, Date.now(), Math.random(), success ? null : (error ?? "Pivot dial failed."));
|
|
1039
|
+
if (success)
|
|
1040
|
+
healthy++;
|
|
1041
|
+
else {
|
|
1042
|
+
session.nextDiscovery = 0;
|
|
1043
|
+
context.diagnostic?.(`[${url}] Pivot ${id} dial failed; refreshing profile, with cooldown after repeated failure.`);
|
|
1044
|
+
}
|
|
1045
|
+
});
|
|
1046
|
+
session.healthy = healthy;
|
|
1047
|
+
// Startup-captured relay/bootstrap options must be removed immediately
|
|
1048
|
+
// when a candidate enters cooldown, not merely changed through config RPC.
|
|
1049
|
+
const record = session.record;
|
|
1050
|
+
const self = record.config.members.find((member) => member.publicKey === record.account);
|
|
1051
|
+
const desired = memberPeers(self.peerId, session.candidates.active(), []);
|
|
1052
|
+
session.node = await startNode(context.stateDir, nodeScope(coordinates(url).service, record.config.scopeId), record.secret.swarmKey, record.config.epoch, context.listen, {
|
|
1053
|
+
self: self.peerId,
|
|
1054
|
+
pivot: context.pivot ?? false,
|
|
1055
|
+
peers: desired,
|
|
1056
|
+
signal,
|
|
1057
|
+
});
|
|
1058
|
+
session.selected = new Set(desired.map(({ ID }) => ID));
|
|
1059
|
+
try {
|
|
1060
|
+
const peers = await nodeConnections(session.node, signal);
|
|
1061
|
+
session.connections = {
|
|
1062
|
+
observedAt: Date.now(),
|
|
1063
|
+
error: null,
|
|
1064
|
+
peers,
|
|
1065
|
+
};
|
|
1066
|
+
}
|
|
1067
|
+
catch (cause) {
|
|
1068
|
+
signal.throwIfAborted();
|
|
1069
|
+
session.connections = {
|
|
1070
|
+
observedAt: session.connections?.observedAt ?? null,
|
|
1071
|
+
error: message(cause).slice(0, 2048),
|
|
1072
|
+
peers: session.connections?.peers ?? [],
|
|
1073
|
+
};
|
|
1074
|
+
}
|
|
1075
|
+
}
|
|
1076
|
+
catch (cause) {
|
|
1077
|
+
if (signal.aborted)
|
|
1078
|
+
return;
|
|
1079
|
+
session.error = message(cause);
|
|
1080
|
+
session.nextDiscovery = 0;
|
|
1081
|
+
context.diagnostic?.(`[${url}] Daemon refresh failed (last-known local candidates retained): ${message(cause)}`);
|
|
1082
|
+
if (cause instanceof HostError &&
|
|
1083
|
+
/membership removed|identity was removed|epoch rollback|Pinned Owner changed/.test(cause.message)) {
|
|
1084
|
+
if (session.node)
|
|
1085
|
+
await stopNode(session.node);
|
|
1086
|
+
session.candidates.reconcile(new Map());
|
|
1087
|
+
delete session.node;
|
|
1088
|
+
session.selected.clear();
|
|
1089
|
+
await persist(url, session, false);
|
|
1090
|
+
delete session.record;
|
|
1091
|
+
}
|
|
1092
|
+
}
|
|
1093
|
+
await persist(url, session, true);
|
|
1094
|
+
});
|
|
1095
|
+
try {
|
|
1096
|
+
await delay(30_000 + Math.random() * 15_000, undefined, { signal });
|
|
1097
|
+
}
|
|
1098
|
+
catch {
|
|
1099
|
+
signal.throwIfAborted();
|
|
1100
|
+
}
|
|
1101
|
+
}
|
|
1102
|
+
}
|
|
1103
|
+
finally {
|
|
1104
|
+
for (const [url, session] of sessions)
|
|
1105
|
+
await persist(url, session, false);
|
|
1106
|
+
}
|
|
1107
|
+
}, signal, 1);
|
|
1108
|
+
}
|
|
596
1109
|
async function activate(context, record) {
|
|
597
1110
|
const { node, peers, source } = await privateSource(context, record);
|
|
598
1111
|
if (context.node?.api !== node.api ||
|
|
@@ -757,7 +1270,31 @@ export async function jsonBundle(store, type, value) {
|
|
|
757
1270
|
await encoded.close();
|
|
758
1271
|
}
|
|
759
1272
|
}
|
|
760
|
-
|
|
1273
|
+
async function writeStateBundle(store, configuration, targets, configUrl) {
|
|
1274
|
+
const meta = parseSwarmMeta(configuration);
|
|
1275
|
+
const names = Object.fromEntries(Object.entries(targets).map(([name, cid]) => [
|
|
1276
|
+
formalName(name),
|
|
1277
|
+
cid.toString(),
|
|
1278
|
+
]));
|
|
1279
|
+
const value = parseSwarmState({
|
|
1280
|
+
v: configUrl === undefined ? 5 : 6,
|
|
1281
|
+
...(configUrl === undefined ? {} : { configUrl }),
|
|
1282
|
+
...meta,
|
|
1283
|
+
names,
|
|
1284
|
+
});
|
|
1285
|
+
return jsonBundle(store, configUrl !== undefined
|
|
1286
|
+
? swarmStateType
|
|
1287
|
+
: meta.skillPath === undefined
|
|
1288
|
+
? legacySwarmStateType
|
|
1289
|
+
: previousSwarmStateType, value);
|
|
1290
|
+
}
|
|
1291
|
+
export async function writeSnapshot(store, snapshot, configUrl) {
|
|
1292
|
+
if (snapshot.stateBundle) {
|
|
1293
|
+
if (Object.keys(snapshot.registrations ?? {}).length)
|
|
1294
|
+
throw new HostError("State Bundles cannot contain legacy registrations.");
|
|
1295
|
+
checkStateOrigin(snapshot, configUrl);
|
|
1296
|
+
return writeStateBundle(store, snapshot.stateBundle.meta, snapshot.names, snapshot.stateBundle.configUrl);
|
|
1297
|
+
}
|
|
761
1298
|
const put = async (value) => {
|
|
762
1299
|
const encoded = dagCbor.encode(value);
|
|
763
1300
|
const cid = CID.createV1(dagCbor.code, await sha256.digest(encoded));
|
|
@@ -765,12 +1302,57 @@ export async function writeSnapshot(store, snapshot) {
|
|
|
765
1302
|
return cid;
|
|
766
1303
|
};
|
|
767
1304
|
const names = await put(snapshot.names);
|
|
768
|
-
|
|
769
|
-
|
|
1305
|
+
if (Object.keys(snapshot.registrations ?? {}).length) {
|
|
1306
|
+
const registrations = await put(snapshot.registrations);
|
|
1307
|
+
return (await put({ v: 3, names, registrations })).toString();
|
|
1308
|
+
}
|
|
1309
|
+
return (await put({ v: 4, names })).toString();
|
|
770
1310
|
}
|
|
771
1311
|
async function readState(store, cid) {
|
|
1312
|
+
if (cid.code !== dagCbor.code) {
|
|
1313
|
+
const bundle = await openBundle(cid, {
|
|
1314
|
+
resolveCid: (key) => store.block.get(key.toString()),
|
|
1315
|
+
});
|
|
1316
|
+
const type = bundle.schemaKey === legacySwarmStateSchema.cid.toString()
|
|
1317
|
+
? legacySwarmStateType
|
|
1318
|
+
: bundle.schemaKey === previousSwarmStateSchema.cid.toString()
|
|
1319
|
+
? previousSwarmStateType
|
|
1320
|
+
: swarmStateType;
|
|
1321
|
+
const value = parseSwarmState(await typedJson(store, cid.toString(), type));
|
|
1322
|
+
const meta = parseSwarmMeta({
|
|
1323
|
+
templatePath: value.templatePath,
|
|
1324
|
+
registryPath: value.registryPath,
|
|
1325
|
+
...(value.skillPath === undefined ? {} : { skillPath: value.skillPath }),
|
|
1326
|
+
});
|
|
1327
|
+
const names = Object.fromEntries(Object.entries(object(value.names, "Names")).map(([name, target]) => {
|
|
1328
|
+
formalName(name);
|
|
1329
|
+
if (typeof target !== "string" || exactCid(target) !== target)
|
|
1330
|
+
throw new HostError("State Names require exact canonical CIDs.");
|
|
1331
|
+
return [name, CID.parse(target)];
|
|
1332
|
+
}));
|
|
1333
|
+
return {
|
|
1334
|
+
v: 2,
|
|
1335
|
+
names,
|
|
1336
|
+
stateBundle: {
|
|
1337
|
+
meta,
|
|
1338
|
+
cid: cid.toString(),
|
|
1339
|
+
...(value.configUrl === undefined
|
|
1340
|
+
? {}
|
|
1341
|
+
: { configUrl: value.configUrl }),
|
|
1342
|
+
},
|
|
1343
|
+
};
|
|
1344
|
+
}
|
|
772
1345
|
const data = await store.block.get(cid.toString());
|
|
773
1346
|
const root = object(dagCbor.decode(data), "State");
|
|
1347
|
+
if (root.v === 4) {
|
|
1348
|
+
const names = CID.asCID(root.names);
|
|
1349
|
+
if (!names || Object.keys(root).sort().join() !== "names,v")
|
|
1350
|
+
throw new HostError("Invalid State Names root.");
|
|
1351
|
+
return decodeSnapshot(dagCbor.encode({
|
|
1352
|
+
v: 2,
|
|
1353
|
+
names: dagCbor.decode(await store.block.get(names.toString())),
|
|
1354
|
+
}));
|
|
1355
|
+
}
|
|
774
1356
|
if (root.v !== 3)
|
|
775
1357
|
return decodeSnapshot(data);
|
|
776
1358
|
const names = CID.asCID(root.names), registrations = CID.asCID(root.registrations);
|
|
@@ -823,14 +1405,24 @@ function decodeSnapshot(data) {
|
|
|
823
1405
|
...(value.registrations !== undefined ? { registrations } : {}),
|
|
824
1406
|
};
|
|
825
1407
|
}
|
|
826
|
-
export async function readSnapshot(store, root) {
|
|
1408
|
+
export async function readSnapshot(store, root, configUrl) {
|
|
827
1409
|
const publication = await readPublication(store, root);
|
|
828
|
-
|
|
1410
|
+
const snapshot = await readState(store, publication.state);
|
|
1411
|
+
checkStateOrigin(snapshot, configUrl);
|
|
1412
|
+
return snapshot;
|
|
1413
|
+
}
|
|
1414
|
+
function checkStateOrigin(snapshot, configUrl) {
|
|
1415
|
+
if (configUrl !== undefined &&
|
|
1416
|
+
snapshot.stateBundle?.configUrl !== undefined &&
|
|
1417
|
+
snapshot.stateBundle.configUrl !== configUrl)
|
|
1418
|
+
throw new HostError("State Bundle Config URL does not match the selected Swarm.");
|
|
829
1419
|
}
|
|
830
|
-
async function readHeaderSnapshot(store, root) {
|
|
1420
|
+
async function readHeaderSnapshot(store, root, configUrl) {
|
|
831
1421
|
const publication = await readPublication(store, root);
|
|
1422
|
+
const snapshot = await readState(store, publication.state);
|
|
1423
|
+
checkStateOrigin(snapshot, configUrl);
|
|
832
1424
|
return {
|
|
833
|
-
snapshot
|
|
1425
|
+
snapshot,
|
|
834
1426
|
stateCid: publication.state.toString(),
|
|
835
1427
|
};
|
|
836
1428
|
}
|
|
@@ -859,16 +1451,22 @@ async function publication(store, state, previous) {
|
|
|
859
1451
|
await store.put(cid, data);
|
|
860
1452
|
return cid.toString();
|
|
861
1453
|
}
|
|
1454
|
+
function missingContent(cause) {
|
|
1455
|
+
let failure = cause;
|
|
1456
|
+
for (let depth = 0; depth < 8 && failure instanceof ContentBundleError; depth++)
|
|
1457
|
+
failure = failure.cause;
|
|
1458
|
+
return failure instanceof ContentError && failure.code === "missing_block";
|
|
1459
|
+
}
|
|
862
1460
|
export async function sharedSwarmStatus(context, configUrl) {
|
|
863
1461
|
const { config } = await fetchConfig(context, configUrl);
|
|
864
1462
|
const c = coordinates(configUrl);
|
|
865
1463
|
const head = headValue(await client(context, c.service).read(c.scopeId, config.headId));
|
|
866
1464
|
let content;
|
|
867
1465
|
try {
|
|
868
|
-
content = await readHeaderSnapshot(context.store, head.root);
|
|
1466
|
+
content = await readHeaderSnapshot(context.store, head.root, configUrl);
|
|
869
1467
|
}
|
|
870
1468
|
catch (cause) {
|
|
871
|
-
if (!(cause
|
|
1469
|
+
if (!missingContent(cause))
|
|
872
1470
|
throw cause;
|
|
873
1471
|
const registered = withState(context, (state) => state.swarms().some((entry) => entry.cid === configUrl));
|
|
874
1472
|
if (!registered)
|
|
@@ -932,14 +1530,14 @@ async function readSwarmHeader(context, configUrl, force = context.forceRefresh
|
|
|
932
1530
|
: await (await boundPointer(context, configUrl, record)).read();
|
|
933
1531
|
let content;
|
|
934
1532
|
try {
|
|
935
|
-
content = await readHeaderSnapshot(context.store, head.root);
|
|
1533
|
+
content = await readHeaderSnapshot(context.store, head.root, configUrl);
|
|
936
1534
|
}
|
|
937
1535
|
catch (cause) {
|
|
938
1536
|
if (mode === "local-first")
|
|
939
1537
|
throw cause;
|
|
940
1538
|
record = await refresh(context, configUrl);
|
|
941
1539
|
head = await (await boundPointer(context, configUrl, record)).read();
|
|
942
|
-
content = await readHeaderSnapshot(context.store, head.root);
|
|
1540
|
+
content = await readHeaderSnapshot(context.store, head.root, configUrl);
|
|
943
1541
|
}
|
|
944
1542
|
const current = await local(context, configUrl), verifiedAt = Date.now();
|
|
945
1543
|
withState(context, (state) => {
|
|
@@ -974,7 +1572,32 @@ async function cachedHeader(context, record) {
|
|
|
974
1572
|
(cached.epoch !== undefined && cached.epoch !== config.epoch) ||
|
|
975
1573
|
!(age >= 0 && age < (context.cacheTtl ?? 300) * 1000))
|
|
976
1574
|
return;
|
|
977
|
-
const
|
|
1575
|
+
const cachedSnapshot = object(dagCbor.decode(Buffer.from(cached.snapshot, "base64")), "cached State");
|
|
1576
|
+
const { stateBundle, ...legacySnapshot } = cachedSnapshot;
|
|
1577
|
+
const snapshot = decodeSnapshot(dagCbor.encode(legacySnapshot));
|
|
1578
|
+
if (stateBundle !== undefined) {
|
|
1579
|
+
const data = object(stateBundle, "cached State Bundle");
|
|
1580
|
+
if (!["cid,meta", "cid,configUrl,meta"].includes(Object.keys(data).sort().join()) ||
|
|
1581
|
+
typeof data.cid !== "string" ||
|
|
1582
|
+
exactCid(data.cid) !== data.cid ||
|
|
1583
|
+
(cached.stateCid !== undefined && data.cid !== cached.stateCid))
|
|
1584
|
+
throw new HostError("Invalid cached State Bundle.");
|
|
1585
|
+
const meta = parseSwarmMeta(data.meta);
|
|
1586
|
+
const parsed = parseSwarmState({
|
|
1587
|
+
v: data.configUrl === undefined ? 5 : 6,
|
|
1588
|
+
...meta,
|
|
1589
|
+
...(data.configUrl === undefined ? {} : { configUrl: data.configUrl }),
|
|
1590
|
+
names: {},
|
|
1591
|
+
});
|
|
1592
|
+
snapshot.stateBundle = {
|
|
1593
|
+
meta,
|
|
1594
|
+
cid: data.cid,
|
|
1595
|
+
...(parsed.configUrl === undefined
|
|
1596
|
+
? {}
|
|
1597
|
+
: { configUrl: parsed.configUrl }),
|
|
1598
|
+
};
|
|
1599
|
+
checkStateOrigin(snapshot, record.configUrl);
|
|
1600
|
+
}
|
|
978
1601
|
let stateCid = cached.stateCid;
|
|
979
1602
|
if (!stateCid) {
|
|
980
1603
|
try {
|
|
@@ -1011,7 +1634,7 @@ function projectHeader(context, record, header) {
|
|
|
1011
1634
|
membership: JSON.stringify({ owner: record.owner, member }),
|
|
1012
1635
|
};
|
|
1013
1636
|
withState(context, (state) => {
|
|
1014
|
-
state.projectSwarm(binding, header.snapshot.names, () =>
|
|
1637
|
+
state.projectSwarm(binding, header.snapshot.names, () => []);
|
|
1015
1638
|
});
|
|
1016
1639
|
header.projection = binding;
|
|
1017
1640
|
}
|
|
@@ -1071,7 +1694,7 @@ async function lazyPrivateSource(context, url, account, basis) {
|
|
|
1071
1694
|
record.config.owner !== basis.owner ||
|
|
1072
1695
|
record.config.epoch !== basis.epoch ||
|
|
1073
1696
|
record.config.headId !== basis.headId)
|
|
1074
|
-
throw new HostError("Swarm membership changed since this cached HEAD; retry with --
|
|
1697
|
+
throw new HostError("Swarm membership changed since this cached HEAD; retry with --refresh.");
|
|
1075
1698
|
return (await privateSource(scoped, record, signal)).source;
|
|
1076
1699
|
};
|
|
1077
1700
|
// Same lock order as Owner rotation: credentials first, then the node.
|
|
@@ -1099,11 +1722,6 @@ async function lazyPrivateSource(context, url, account, basis) {
|
|
|
1099
1722
|
await pending?.catch(() => { });
|
|
1100
1723
|
};
|
|
1101
1724
|
}
|
|
1102
|
-
export async function addSwarm(context, url, alias) {
|
|
1103
|
-
canonicalSwarmUrl(url);
|
|
1104
|
-
await readyMembership(context, url);
|
|
1105
|
-
withState(context, (state) => state.registerSwarm(url, alias));
|
|
1106
|
-
}
|
|
1107
1725
|
export async function createSwarm(context, options = {}) {
|
|
1108
1726
|
if ((options.properties?.name.length ?? 0) > 256 ||
|
|
1109
1727
|
(options.properties?.description.length ?? 0) > 2048 ||
|
|
@@ -1131,6 +1749,7 @@ export async function createSwarm(context, options = {}) {
|
|
|
1131
1749
|
if (options.resume)
|
|
1132
1750
|
throw new HostError("Unknown creation operation.");
|
|
1133
1751
|
record = {
|
|
1752
|
+
stateVersion: 6,
|
|
1134
1753
|
owner: identity.publicKey,
|
|
1135
1754
|
service,
|
|
1136
1755
|
encryption: encryptionIdentity(),
|
|
@@ -1147,24 +1766,75 @@ export async function createSwarm(context, options = {}) {
|
|
|
1147
1766
|
const save = () => writePrivate(dir, `creation-${op}.json`, record);
|
|
1148
1767
|
const api = client(context, service, identity);
|
|
1149
1768
|
try {
|
|
1769
|
+
if (record.stateVersion === 6) {
|
|
1770
|
+
if (!record.scopeId) {
|
|
1771
|
+
record.scopeId = (await api.createScope(`${op}.scope`)).id;
|
|
1772
|
+
await save();
|
|
1773
|
+
}
|
|
1774
|
+
if (!record.configId) {
|
|
1775
|
+
// Reserve the Config address, not a Config or a temporary HEAD.
|
|
1776
|
+
const reservation = await api.create(record.scopeId, {
|
|
1777
|
+
v: 1,
|
|
1778
|
+
kind: "ipab-config-reservation",
|
|
1779
|
+
owner: record.owner,
|
|
1780
|
+
operation: op,
|
|
1781
|
+
}, `${op}.config-reserve`);
|
|
1782
|
+
record.configId = reservation.id;
|
|
1783
|
+
record.configReservationCid = reservation.cid;
|
|
1784
|
+
await save();
|
|
1785
|
+
}
|
|
1786
|
+
}
|
|
1787
|
+
if (!record.seed) {
|
|
1788
|
+
if (record.headId)
|
|
1789
|
+
throw new HostError("Legacy creation has an unseeded HEAD. Preserve this recovery record and explicitly migrate the Swarm; it cannot complete as a newly seeded Swarm.");
|
|
1790
|
+
const names = {};
|
|
1791
|
+
for (const selector of seedTemplateNames) {
|
|
1792
|
+
const template = await seedTemplateSource(selector);
|
|
1793
|
+
for (const [cid, data] of template.blocks)
|
|
1794
|
+
await context.store.put(CID.parse(cid), data);
|
|
1795
|
+
names[`ipab/templates/${selector}`] = CID.parse(template.cid);
|
|
1796
|
+
}
|
|
1797
|
+
const skill = await seedSkillSource();
|
|
1798
|
+
for (const [cid, data] of skill.blocks)
|
|
1799
|
+
await context.store.put(CID.parse(cid), data);
|
|
1800
|
+
names["ipab/skills/ipab"] = CID.parse(skill.cid);
|
|
1801
|
+
const root = await publication(context.store, await writeStateBundle(context.store, {
|
|
1802
|
+
templatePath: "ipab/templates",
|
|
1803
|
+
registryPath: "ipab/registry",
|
|
1804
|
+
skillPath: "ipab/skills",
|
|
1805
|
+
}, names, record.stateVersion === 6
|
|
1806
|
+
? `${service}/v1/${record.scopeId}/${record.configId}`
|
|
1807
|
+
: undefined));
|
|
1808
|
+
const roots = await frozenPublicationClosure(context.store, root);
|
|
1809
|
+
record.seed = {
|
|
1810
|
+
root,
|
|
1811
|
+
roots,
|
|
1812
|
+
car: Buffer.from(await contentCar(context.store, roots)).toString("base64"),
|
|
1813
|
+
};
|
|
1814
|
+
await save();
|
|
1815
|
+
}
|
|
1816
|
+
const seedBytes = Buffer.from(record.seed.car, "base64");
|
|
1817
|
+
const seed = await CarBlockIterator.fromIterable(streamChunks(new Blob([seedBytes]).stream()));
|
|
1818
|
+
for await (const block of seed)
|
|
1819
|
+
await context.store.put(block.cid, block.bytes);
|
|
1150
1820
|
if (!record.scopeId) {
|
|
1151
1821
|
record.scopeId = (await api.createScope(`${op}.scope`)).id;
|
|
1152
1822
|
await save();
|
|
1153
1823
|
}
|
|
1154
1824
|
const node = await prepareNode(context.stateDir, nodeScope(service, record.scopeId), context.listen);
|
|
1155
1825
|
if (!record.headId) {
|
|
1156
|
-
|
|
1157
|
-
record.headId = (await api.create(record.scopeId, { root }, `${op}.head`)).id;
|
|
1826
|
+
record.headId = (await api.create(record.scopeId, { root: record.seed.root }, `${op}.head`)).id;
|
|
1158
1827
|
await save();
|
|
1159
1828
|
}
|
|
1160
1829
|
if (!record.profileId) {
|
|
1161
1830
|
if (!record.profile) {
|
|
1162
|
-
const addresses = options.addresses ??
|
|
1831
|
+
const addresses = options.addresses ?? [];
|
|
1163
1832
|
for (const address of addresses)
|
|
1164
1833
|
validateAddress(address, node.peerId);
|
|
1165
1834
|
record.profile = {
|
|
1166
1835
|
...(record.personal ?? { name: record.name }),
|
|
1167
1836
|
addresses,
|
|
1837
|
+
pivot: context.pivot ?? false,
|
|
1168
1838
|
updatedAt: record.createdAt,
|
|
1169
1839
|
};
|
|
1170
1840
|
await save();
|
|
@@ -1189,7 +1859,7 @@ export async function createSwarm(context, options = {}) {
|
|
|
1189
1859
|
description: record.description,
|
|
1190
1860
|
headId: record.headId,
|
|
1191
1861
|
epoch: 1,
|
|
1192
|
-
bootstrap:
|
|
1862
|
+
bootstrap: [],
|
|
1193
1863
|
members: [member],
|
|
1194
1864
|
};
|
|
1195
1865
|
await save();
|
|
@@ -1198,6 +1868,19 @@ export async function createSwarm(context, options = {}) {
|
|
|
1198
1868
|
record.configId = (await api.create(record.scopeId, configValue(record.config), `${op}.config`)).id;
|
|
1199
1869
|
await save();
|
|
1200
1870
|
}
|
|
1871
|
+
if (record.stateVersion === 6 && !record.configPublished) {
|
|
1872
|
+
if (!record.configReservationCid)
|
|
1873
|
+
throw new HostError("Creation Config reservation checkpoint is missing.");
|
|
1874
|
+
const value = configValue(record.config);
|
|
1875
|
+
const current = await api.read(record.scopeId, record.configId);
|
|
1876
|
+
if (current.cid !== (await valueCid(value))) {
|
|
1877
|
+
if (current.cid !== record.configReservationCid)
|
|
1878
|
+
throw new HostError("Creation Config reservation was changed; refusing to overwrite it.");
|
|
1879
|
+
await api.write(record.scopeId, record.configId, value, record.configReservationCid, `${op}.config`);
|
|
1880
|
+
}
|
|
1881
|
+
record.configPublished = true;
|
|
1882
|
+
await save();
|
|
1883
|
+
}
|
|
1201
1884
|
const configUrl = `${service}/v1/${record.scopeId}/${record.configId}`;
|
|
1202
1885
|
const cert = await issueScopeCertificate({
|
|
1203
1886
|
v: 1,
|
|
@@ -1217,7 +1900,7 @@ export async function createSwarm(context, options = {}) {
|
|
|
1217
1900
|
await saveLocal(context, membership);
|
|
1218
1901
|
await activate(context, membership);
|
|
1219
1902
|
const head = await api.read(record.scopeId, record.headId);
|
|
1220
|
-
await provideContent(context.store, [headValue(head).root], context.node.api, context.fetch, context.node.auth);
|
|
1903
|
+
await provideContent(context.store, [...new Set([headValue(head).root, ...record.seed.roots])], context.node.api, context.fetch, context.node.auth);
|
|
1221
1904
|
withState(context, (state) => state.registerSwarm(configUrl, options.alias));
|
|
1222
1905
|
return configUrl;
|
|
1223
1906
|
}
|
|
@@ -1250,10 +1933,6 @@ export async function requestMembership(context, url, options) {
|
|
|
1250
1933
|
const personal = await ensureAccountProfile(context);
|
|
1251
1934
|
const dir = await directory(context);
|
|
1252
1935
|
await withPrivateLock(dir, async () => {
|
|
1253
|
-
if (options.alias !== undefined)
|
|
1254
|
-
withState(context, (state) => {
|
|
1255
|
-
state.checkSwarmAlias(options.alias, url);
|
|
1256
|
-
});
|
|
1257
1936
|
const existing = await readPrivate(dir, localName(url));
|
|
1258
1937
|
if (existing) {
|
|
1259
1938
|
if (existing.account !== identity.publicKey ||
|
|
@@ -1261,7 +1940,6 @@ export async function requestMembership(context, url, options) {
|
|
|
1261
1940
|
throw new HostError("Existing Request belongs to a different identity or pinned Owner.");
|
|
1262
1941
|
if (!existing.request)
|
|
1263
1942
|
throw new HostError("This identity is already the Owner.");
|
|
1264
|
-
withState(context, (state) => state.registerSwarm(url, options.alias));
|
|
1265
1943
|
return;
|
|
1266
1944
|
}
|
|
1267
1945
|
const node = await prepareNode(context.stateDir, nodeScope(coordinates(url).service, config.scopeId), context.listen), encryption = encryptionIdentity();
|
|
@@ -1293,7 +1971,6 @@ export async function requestMembership(context, url, options) {
|
|
|
1293
1971
|
encryption,
|
|
1294
1972
|
request,
|
|
1295
1973
|
});
|
|
1296
|
-
withState(context, (state) => state.registerSwarm(url, options.alias));
|
|
1297
1974
|
});
|
|
1298
1975
|
const file = options.output === undefined ? undefined : resolve(options.output);
|
|
1299
1976
|
if (file !== undefined)
|
|
@@ -1539,6 +2216,11 @@ export async function updateProfile(context, url, changes) {
|
|
|
1539
2216
|
updatedAt: new Date().toISOString(),
|
|
1540
2217
|
};
|
|
1541
2218
|
await api.write(c.scopeId, member.profileId, profile, existing.cid, uniqueId());
|
|
2219
|
+
await writePrivate(await directory(context), `pivot-${localName(url)}`, {
|
|
2220
|
+
manual: changes.addresses,
|
|
2221
|
+
});
|
|
2222
|
+
if (!context.pivot)
|
|
2223
|
+
context.diagnostic?.("Manual addresses saved; they are discovery candidates only when swarm.pivot=true. Ordinary nodes do not provide relay service.");
|
|
1542
2224
|
return profile;
|
|
1543
2225
|
}
|
|
1544
2226
|
export async function removeMember(context, url, member) {
|
|
@@ -1587,6 +2269,7 @@ export async function resumeRemoval(context, url) {
|
|
|
1587
2269
|
membershipBeforeSwitch.config = record.oldConfig;
|
|
1588
2270
|
membershipBeforeSwitch.secret.swarmKey = record.oldKey;
|
|
1589
2271
|
await activate(context, membershipBeforeSwitch);
|
|
2272
|
+
await readSnapshot(context.store, headValue(record.finalHead).root, url);
|
|
1590
2273
|
if (!record.finalClosureRoots) {
|
|
1591
2274
|
record.finalClosureRoots = await frozenPublicationClosure(context.store, headValue(record.finalHead).root);
|
|
1592
2275
|
await save();
|
|
@@ -1740,7 +2423,7 @@ export function parseNameReference(reference) {
|
|
|
1740
2423
|
try {
|
|
1741
2424
|
return {
|
|
1742
2425
|
...(authority ? { swarm: authority } : {}),
|
|
1743
|
-
name: formalName(segments.join("/")),
|
|
2426
|
+
name: match[2] === "" ? "" : formalName(segments.join("/")),
|
|
1744
2427
|
};
|
|
1745
2428
|
}
|
|
1746
2429
|
catch (error) {
|
|
@@ -1764,20 +2447,21 @@ export async function resolveReference(context, reference, swarm, local, raw = f
|
|
|
1764
2447
|
throw new HostError("Select a configuration URL/alias using --swarm or swarm use.");
|
|
1765
2448
|
const warm = mode === "local-first" ? await localHeader(context, selected) : undefined;
|
|
1766
2449
|
let header = warm?.header ?? (await swarmHeader(context, selected));
|
|
1767
|
-
|
|
1768
|
-
? header.
|
|
1769
|
-
:
|
|
2450
|
+
const target = () => shared.name === ""
|
|
2451
|
+
? header.stateCid
|
|
2452
|
+
: Object.hasOwn(header.snapshot.names, shared.name)
|
|
2453
|
+
? header.snapshot.names[shared.name]?.toString()
|
|
2454
|
+
: undefined;
|
|
2455
|
+
let link = target();
|
|
1770
2456
|
if (!link && header.source === "cache") {
|
|
1771
2457
|
header = await swarmHeader(context, selected, true);
|
|
1772
|
-
link =
|
|
1773
|
-
? header.snapshot.names[shared.name]
|
|
1774
|
-
: undefined;
|
|
2458
|
+
link = target();
|
|
1775
2459
|
}
|
|
1776
2460
|
if (!link)
|
|
1777
2461
|
throw new HostError(`Formal Name "${shared.name}" was not found after refreshing HEAD.`);
|
|
1778
2462
|
if (warm && header === warm.header && !header.localSourceReady)
|
|
1779
2463
|
await lazyPrivateSource(context, selected, warm.account, header.config);
|
|
1780
|
-
targetCid = link
|
|
2464
|
+
targetCid = link;
|
|
1781
2465
|
}
|
|
1782
2466
|
else {
|
|
1783
2467
|
if (swarm)
|
|
@@ -1787,13 +2471,14 @@ export async function resolveReference(context, reference, swarm, local, raw = f
|
|
|
1787
2471
|
const cid = raw ? targetCid : await artifactValue(context.store, targetCid);
|
|
1788
2472
|
return { targetCid, cid };
|
|
1789
2473
|
}
|
|
1790
|
-
async function artifactValue(store, targetCid) {
|
|
2474
|
+
async function artifactValue(store, targetCid, protect) {
|
|
1791
2475
|
let cid = targetCid;
|
|
1792
2476
|
const visited = new Set();
|
|
1793
2477
|
for (let depth = 0;; depth++) {
|
|
1794
2478
|
if (depth >= 64 || visited.has(cid))
|
|
1795
2479
|
throw new HostError("Artifact resolution exceeds limits or contains a cycle.");
|
|
1796
2480
|
visited.add(cid);
|
|
2481
|
+
await protect?.(cid);
|
|
1797
2482
|
const bundle = await openBundle(CID.parse(cid), {
|
|
1798
2483
|
resolveCid: (cid) => store.block.get(cid.toString()),
|
|
1799
2484
|
});
|
|
@@ -1820,7 +2505,7 @@ export function pinReference(state, reference, selected) {
|
|
|
1820
2505
|
}
|
|
1821
2506
|
export async function pinNameSubscription(context, reference, selected) {
|
|
1822
2507
|
const canonical = withState(context, (state) => pinReference(state, reference, selected));
|
|
1823
|
-
if (!canonical.swarm ||
|
|
2508
|
+
if (!canonical.swarm || canonical.name === undefined) {
|
|
1824
2509
|
let roots;
|
|
1825
2510
|
try {
|
|
1826
2511
|
roots = [
|
|
@@ -1828,12 +2513,7 @@ export async function pinNameSubscription(context, reference, selected) {
|
|
|
1828
2513
|
];
|
|
1829
2514
|
}
|
|
1830
2515
|
catch (cause) {
|
|
1831
|
-
|
|
1832
|
-
for (let depth = 0; depth < 8 && failure instanceof ContentBundleError; depth++)
|
|
1833
|
-
failure = failure.cause;
|
|
1834
|
-
if (!selected ||
|
|
1835
|
-
!(failure instanceof ContentError) ||
|
|
1836
|
-
failure.code !== "missing_block")
|
|
2516
|
+
if (!selected || !missingContent(cause))
|
|
1837
2517
|
throw cause;
|
|
1838
2518
|
const swarm = withState(context, (state) => state.resolveSwarm(selected));
|
|
1839
2519
|
await readyMembership(context, swarm);
|
|
@@ -1868,9 +2548,11 @@ export async function refreshNamePins(context, url, header) {
|
|
|
1868
2548
|
.filter((pin) => pin.swarm === url && pin.status !== "deleting"));
|
|
1869
2549
|
const failures = [];
|
|
1870
2550
|
for (const saved of pins) {
|
|
1871
|
-
const target =
|
|
1872
|
-
? header.
|
|
1873
|
-
:
|
|
2551
|
+
const target = saved.name === ""
|
|
2552
|
+
? header.stateCid
|
|
2553
|
+
: Object.hasOwn(header.snapshot.names, saved.name)
|
|
2554
|
+
? header.snapshot.names[saved.name].toString()
|
|
2555
|
+
: undefined;
|
|
1874
2556
|
if (!target) {
|
|
1875
2557
|
withState(context, (state) => {
|
|
1876
2558
|
failedPin(state, saved.reference, new Error("Shared Name is missing; keeping its last verified version."), true);
|
|
@@ -1925,6 +2607,11 @@ async function currentDependencies(store, root, found = new Set()) {
|
|
|
1925
2607
|
await currentDependencies(store, source.cid, found);
|
|
1926
2608
|
}
|
|
1927
2609
|
}
|
|
2610
|
+
else if (isSwarmStateSchema(bundle.schemaKey)) {
|
|
2611
|
+
const snapshot = await readState(store, CID.parse(root));
|
|
2612
|
+
for (const target of Object.values(snapshot.names))
|
|
2613
|
+
await currentDependencies(store, target.toString(), found);
|
|
2614
|
+
}
|
|
1928
2615
|
return found;
|
|
1929
2616
|
}
|
|
1930
2617
|
export async function searchNames(context, query, swarms) {
|
|
@@ -1955,63 +2642,324 @@ export async function searchNames(context, query, swarms) {
|
|
|
1955
2642
|
}
|
|
1956
2643
|
return { matches, swarms: searched };
|
|
1957
2644
|
}
|
|
1958
|
-
function
|
|
1959
|
-
|
|
1960
|
-
|
|
1961
|
-
|
|
1962
|
-
|
|
1963
|
-
|
|
1964
|
-
|
|
1965
|
-
|
|
2645
|
+
function assertNamesRegistry(snapshot) {
|
|
2646
|
+
if (Object.keys(snapshot.registrations ?? {}).length)
|
|
2647
|
+
throw new HostError("Legacy shared registrations are inactive; per-association argv is unsupported and has not been dropped or migrated. Create a new seeded Swarm and explicitly register intended Apps there. Old Swarm content and history remain readable.");
|
|
2648
|
+
}
|
|
2649
|
+
export async function swarmMeta(context, header) {
|
|
2650
|
+
if (header.snapshot.stateBundle)
|
|
2651
|
+
return header.snapshot.stateBundle.meta;
|
|
2652
|
+
const cid = header.snapshot.names.ipab;
|
|
2653
|
+
if (!cid)
|
|
2654
|
+
throw new HostError('Swarm Meta Name "ipab" is missing. Create a new seeded Swarm or explicitly publish a typed Swarm Meta Bundle; existing Swarms are never automatically upgraded.');
|
|
2655
|
+
try {
|
|
2656
|
+
const bundle = await openBundle(cid, {
|
|
2657
|
+
resolveCid: (key) => context.store.block.get(key.toString()),
|
|
2658
|
+
});
|
|
2659
|
+
const type = bundle.schemaKey === legacySwarmMetaSchema.cid.toString()
|
|
2660
|
+
? legacySwarmMetaType
|
|
2661
|
+
: swarmMetaType;
|
|
2662
|
+
return parseSwarmMeta(await typedJson(context.store, cid.toString(), type));
|
|
2663
|
+
}
|
|
2664
|
+
catch (cause) {
|
|
2665
|
+
throw new HostError(`Invalid Swarm Meta at Name "ipab": ${message(cause)}. Publish a valid typed Meta Bundle explicitly; no builtin or legacy fallback is used.`);
|
|
2666
|
+
}
|
|
2667
|
+
}
|
|
2668
|
+
function metaCid(snapshot) {
|
|
2669
|
+
return snapshot.stateBundle?.cid ?? snapshot.names.ipab.toString();
|
|
2670
|
+
}
|
|
2671
|
+
function hasMeta(snapshot) {
|
|
2672
|
+
return (snapshot.stateBundle !== undefined || Object.hasOwn(snapshot.names, "ipab"));
|
|
2673
|
+
}
|
|
2674
|
+
export async function swarmSkills(context, configUrl, requested, owner) {
|
|
2675
|
+
const warm = await localHeader(context, configUrl);
|
|
2676
|
+
if (warm && !warm.header.localSourceReady)
|
|
2677
|
+
await lazyPrivateSource(context, configUrl, warm.account, warm.header.config);
|
|
2678
|
+
let header = warm?.header ?? (await swarmHeader(context, configUrl));
|
|
2679
|
+
const roots = new Set();
|
|
2680
|
+
const protect = async (cid) => {
|
|
2681
|
+
roots.add(cid);
|
|
2682
|
+
const values = [...roots];
|
|
2683
|
+
context.store.registerOwner(owner, values);
|
|
2684
|
+
await context.store.retain(owner, values);
|
|
2685
|
+
await context.store.confirmRetained(owner, values);
|
|
2686
|
+
};
|
|
2687
|
+
for (let attempt = 0;; attempt++) {
|
|
2688
|
+
if (!hasMeta(header.snapshot) && header.source === "cache" && !attempt) {
|
|
2689
|
+
header = await swarmHeader(context, configUrl, true);
|
|
2690
|
+
continue;
|
|
2691
|
+
}
|
|
2692
|
+
if (hasMeta(header.snapshot))
|
|
2693
|
+
await protect(metaCid(header.snapshot));
|
|
2694
|
+
const meta = await swarmMeta(context, header);
|
|
2695
|
+
if (!meta.skillPath)
|
|
2696
|
+
throw new HostError(header.snapshot.stateBundle
|
|
2697
|
+
? "This Swarm uses the earlier exact State Bundle type without skillPath. There is no in-place root-configuration migration command. Create a new seeded Swarm and explicitly republish reviewed Names. Publishing a user Name ipab never overrides root configuration; upgrades never rewrite it."
|
|
2698
|
+
: `This Swarm uses the legacy exact Meta type without skillPath. Explicitly build and publish a new typed Meta Bundle with templatePath and registryPath preserved and skillPath chosen, then run ipab publish ipab META_SOURCE --expect ${metaCid(header.snapshot)}. Upgrades never overwrite Meta.`);
|
|
2699
|
+
const prefix = `${meta.skillPath}/`;
|
|
2700
|
+
const entries = Object.entries(header.snapshot.names).filter(([name]) => name.startsWith(prefix));
|
|
2701
|
+
for (const [, target] of entries)
|
|
2702
|
+
roots.add(target.toString());
|
|
2703
|
+
context.store.registerOwner(owner, [...roots]);
|
|
2704
|
+
const result = [];
|
|
2705
|
+
const identities = new Set();
|
|
2706
|
+
for (const [name, target] of entries.sort(([a], [b]) => a.localeCompare(b))) {
|
|
2707
|
+
if (name.slice(prefix.length).includes("/"))
|
|
2708
|
+
throw new HostError(`Skill Name "${name}" must be flat under ${meta.skillPath}.`);
|
|
2709
|
+
const cid = await artifactValue(context.store, target.toString(), protect);
|
|
2710
|
+
const bundle = await openBundle(CID.parse(cid), {
|
|
2711
|
+
resolveCid: (key) => context.store.block.get(key.toString()),
|
|
2712
|
+
});
|
|
2713
|
+
if (bundle.schemaKey !== skillSchema.cid.toString())
|
|
2714
|
+
throw new HostError(`Name "${name}" is not an exact Skill type Bundle.`);
|
|
2715
|
+
const identity = await skillIdentity(bundle);
|
|
2716
|
+
if (identities.has(identity))
|
|
2717
|
+
throw new HostError(`Duplicate Skill installation name "${identity}" in this Swarm.`);
|
|
2718
|
+
identities.add(identity);
|
|
2719
|
+
result.push({ name, cid, identity });
|
|
2720
|
+
}
|
|
2721
|
+
const missing = requested.filter((reference) => !result.some((skill) => skill.name === reference || skill.identity === reference));
|
|
2722
|
+
if (missing.length && !attempt && header.source === "cache") {
|
|
2723
|
+
header = await swarmHeader(context, configUrl, true);
|
|
2724
|
+
continue;
|
|
2725
|
+
}
|
|
2726
|
+
if (missing.length)
|
|
2727
|
+
throw new HostError(`Skill identities or shared Names not found under ${meta.skillPath}: ${missing.join(", ")}.`);
|
|
2728
|
+
return result;
|
|
2729
|
+
}
|
|
2730
|
+
}
|
|
2731
|
+
export async function resolveTemplateSelector(context, selector, configUrl) {
|
|
2732
|
+
formalName(selector);
|
|
2733
|
+
const warm = await localHeader(context, configUrl);
|
|
2734
|
+
if (warm && !warm.header.localSourceReady)
|
|
2735
|
+
await lazyPrivateSource(context, configUrl, warm.account, warm.header.config);
|
|
2736
|
+
let header = warm?.header ?? (await swarmHeader(context, configUrl));
|
|
2737
|
+
if (!hasMeta(header.snapshot) && header.source === "cache")
|
|
2738
|
+
header = await swarmHeader(context, configUrl, true);
|
|
2739
|
+
for (let attempt = 0;; attempt++) {
|
|
2740
|
+
const meta = await swarmMeta(context, header);
|
|
2741
|
+
const name = formalName(`${meta.templatePath}/${selector}`);
|
|
2742
|
+
const target = header.snapshot.names[name];
|
|
2743
|
+
if (target)
|
|
2744
|
+
return artifactValue(context.store, target.toString());
|
|
2745
|
+
if (attempt || header.source !== "cache")
|
|
2746
|
+
throw new HostError(`Template Name "${name}" was not found after refreshing HEAD.`);
|
|
2747
|
+
header = await swarmHeader(context, configUrl, true);
|
|
2748
|
+
}
|
|
2749
|
+
}
|
|
2750
|
+
export function templateName(name) {
|
|
2751
|
+
if (name.includes(":"))
|
|
2752
|
+
throw new HostError("Template NAME must be a safe relative Name, not a URI.");
|
|
2753
|
+
return formalName(name);
|
|
2754
|
+
}
|
|
2755
|
+
async function templateEntry(context, configUrl, header, selector) {
|
|
2756
|
+
const meta = await swarmMeta(context, header);
|
|
2757
|
+
const name = formalName(`${meta.templatePath}/${templateName(selector)}`);
|
|
2758
|
+
const target = header.snapshot.names[name];
|
|
2759
|
+
if (!target)
|
|
2760
|
+
throw new HostError(`Template Name "${name}" was not found after refreshing HEAD.`);
|
|
2761
|
+
const targetCid = target.toString();
|
|
2762
|
+
return {
|
|
2763
|
+
swarm: configUrl,
|
|
2764
|
+
templatePath: meta.templatePath,
|
|
2765
|
+
metaCid: metaCid(header.snapshot),
|
|
2766
|
+
name,
|
|
2767
|
+
selector,
|
|
2768
|
+
reference: formatNameReference(configUrl, name),
|
|
2769
|
+
targetCid,
|
|
2770
|
+
...(await inspectTemplate(context.store, await artifactValue(context.store, targetCid))),
|
|
2771
|
+
};
|
|
2772
|
+
}
|
|
2773
|
+
export async function swarmTemplates(context, configUrl, selector) {
|
|
2774
|
+
if (selector !== undefined)
|
|
2775
|
+
templateName(selector);
|
|
2776
|
+
const warm = await localHeader(context, configUrl);
|
|
2777
|
+
if (warm && !warm.header.localSourceReady)
|
|
2778
|
+
await lazyPrivateSource(context, configUrl, warm.account, warm.header.config);
|
|
2779
|
+
let header = warm?.header ??
|
|
2780
|
+
(await swarmHeader(context, configUrl, undefined, "local-first"));
|
|
2781
|
+
for (let attempt = 0;; attempt++) {
|
|
2782
|
+
if (!hasMeta(header.snapshot) && header.source === "cache" && !attempt) {
|
|
2783
|
+
header = await swarmHeader(context, configUrl, true, "local-first");
|
|
2784
|
+
continue;
|
|
2785
|
+
}
|
|
2786
|
+
const meta = await swarmMeta(context, header);
|
|
2787
|
+
const name = selector === undefined
|
|
2788
|
+
? undefined
|
|
2789
|
+
: formalName(`${meta.templatePath}/${selector}`);
|
|
2790
|
+
if (name &&
|
|
2791
|
+
!header.snapshot.names[name] &&
|
|
2792
|
+
header.source === "cache" &&
|
|
2793
|
+
!attempt) {
|
|
2794
|
+
header = await swarmHeader(context, configUrl, true, "local-first");
|
|
2795
|
+
continue;
|
|
2796
|
+
}
|
|
2797
|
+
const selectors = selector === undefined
|
|
2798
|
+
? Object.keys(header.snapshot.names)
|
|
2799
|
+
.filter((key) => key.startsWith(`${meta.templatePath}/`))
|
|
2800
|
+
.map((key) => key.slice(meta.templatePath.length + 1))
|
|
2801
|
+
.sort((a, b) => a.localeCompare(b))
|
|
2802
|
+
: [selector];
|
|
2803
|
+
const items = [];
|
|
2804
|
+
for (const item of selectors)
|
|
2805
|
+
items.push(await templateEntry(context, configUrl, header, item));
|
|
2806
|
+
return items;
|
|
2807
|
+
}
|
|
2808
|
+
}
|
|
2809
|
+
export async function setSwarmTemplate(context, configUrl, selector, source, expect) {
|
|
2810
|
+
templateName(selector);
|
|
2811
|
+
await pointer(context, configUrl);
|
|
2812
|
+
const content = await templatePublicationSource(source, context.store);
|
|
2813
|
+
const details = await inspectTemplate(context.store, content);
|
|
2814
|
+
let location;
|
|
2815
|
+
const targetCid = await publishContent(context, content, {
|
|
2816
|
+
swarm: configUrl,
|
|
2817
|
+
name: selector,
|
|
2818
|
+
...(expect === undefined ? {} : { expect }),
|
|
2819
|
+
}, async (current) => {
|
|
2820
|
+
const meta = await swarmMeta(context, { snapshot: current });
|
|
2821
|
+
const name = formalName(`${meta.templatePath}/${selector}`);
|
|
2822
|
+
location = {
|
|
2823
|
+
name,
|
|
2824
|
+
templatePath: meta.templatePath,
|
|
2825
|
+
metaCid: metaCid(current),
|
|
2826
|
+
};
|
|
2827
|
+
return name;
|
|
2828
|
+
});
|
|
2829
|
+
return {
|
|
2830
|
+
swarm: configUrl,
|
|
2831
|
+
...location,
|
|
2832
|
+
selector,
|
|
2833
|
+
reference: formatNameReference(configUrl, location.name),
|
|
2834
|
+
targetCid,
|
|
2835
|
+
...details,
|
|
2836
|
+
};
|
|
2837
|
+
}
|
|
2838
|
+
export async function removeSwarmTemplate(context, configUrl, selector, expect) {
|
|
2839
|
+
templateName(selector);
|
|
2840
|
+
const expected = exactCid(expect);
|
|
2841
|
+
const head = await pointer(context, configUrl);
|
|
2842
|
+
let basis;
|
|
2843
|
+
for (let attempt = 0; attempt < 8; attempt++) {
|
|
2844
|
+
const currentHead = await head.read();
|
|
2845
|
+
const current = await readSnapshot(context.store, currentHead.root, configUrl);
|
|
2846
|
+
const meta = await swarmMeta(context, { snapshot: current });
|
|
2847
|
+
const name = formalName(`${meta.templatePath}/${selector}`);
|
|
2848
|
+
if (basis !== undefined && basis !== name)
|
|
2849
|
+
throw new HostError("Template Meta path changed during removal; inspect and retry.", 3, "EDIT_CONFLICT", "publication");
|
|
2850
|
+
basis = name;
|
|
2851
|
+
const old = current.names[name]?.toString();
|
|
2852
|
+
if (!old)
|
|
2853
|
+
throw new HostError(`Template Name "${name}" is missing; nothing was removed.`);
|
|
2854
|
+
if (old !== expected)
|
|
2855
|
+
throw new HostError(`Edit conflict for ${name}; --expect must match the exact old Name target CID.`, 3, "EDIT_CONFLICT", "publication");
|
|
2856
|
+
const names = { ...current.names };
|
|
2857
|
+
delete names[name];
|
|
2858
|
+
const next = await prepareNamesPublication(context, configUrl, currentHead.root, current, names, []);
|
|
2859
|
+
try {
|
|
2860
|
+
await head.write(next, currentHead.cid, uniqueId());
|
|
2861
|
+
}
|
|
2862
|
+
catch (cause) {
|
|
2863
|
+
if (cause instanceof ScopeApiError && cause.status === 412)
|
|
2864
|
+
continue;
|
|
2865
|
+
throw new HostError(`Template removal unconfirmed: ${message(cause)}. Inspect HEAD before retry.`, 1, "HEAD_UNCONFIRMED", "publication");
|
|
2866
|
+
}
|
|
2867
|
+
try {
|
|
2868
|
+
await swarmHeader(context, configUrl, true);
|
|
2869
|
+
}
|
|
2870
|
+
catch (cause) {
|
|
2871
|
+
throw new HostError(`Template removal committed, but HEAD/subscription refresh failed: ${message(cause)}. No content was deleted.`, 1, "PIN_STALE", "publication");
|
|
2872
|
+
}
|
|
2873
|
+
return {
|
|
2874
|
+
swarm: configUrl,
|
|
2875
|
+
templatePath: meta.templatePath,
|
|
2876
|
+
metaCid: metaCid(current),
|
|
2877
|
+
selector,
|
|
2878
|
+
name,
|
|
2879
|
+
reference: formatNameReference(configUrl, name),
|
|
2880
|
+
targetCid: old,
|
|
2881
|
+
};
|
|
2882
|
+
}
|
|
2883
|
+
throw new HostError("HEAD is busy; retry the template removal.");
|
|
2884
|
+
}
|
|
2885
|
+
async function registryAssociations(context, header) {
|
|
2886
|
+
assertNamesRegistry(header.snapshot);
|
|
2887
|
+
const meta = await swarmMeta(context, header);
|
|
2888
|
+
const prefix = `${meta.registryPath}/`;
|
|
2889
|
+
const result = [];
|
|
2890
|
+
for (const [name, cid] of Object.entries(header.snapshot.names)) {
|
|
2891
|
+
if (!name.startsWith(prefix))
|
|
2892
|
+
continue;
|
|
2893
|
+
const schemaCid = name.slice(prefix.length);
|
|
2894
|
+
if (exactCid(schemaCid, true) !== schemaCid)
|
|
2895
|
+
throw new HostError(`Registry Name "${name}" must end in an exact canonical type CID.`);
|
|
2896
|
+
result.push(createAssociation(schemaCid, cid.toString(), ["%"]));
|
|
2897
|
+
}
|
|
2898
|
+
return result.sort((left, right) => left.schemaCid.localeCompare(right.schemaCid));
|
|
1966
2899
|
}
|
|
1967
2900
|
export async function swarmRegistrations(context, configUrl) {
|
|
1968
|
-
|
|
1969
|
-
|
|
2901
|
+
let header = await swarmHeader(context, configUrl);
|
|
2902
|
+
if (!hasMeta(header.snapshot) && header.source === "cache")
|
|
2903
|
+
header = await swarmHeader(context, configUrl, true);
|
|
2904
|
+
return registryAssociations(context, header);
|
|
1970
2905
|
}
|
|
1971
2906
|
export async function swarmAssociation(context, configUrl, schemaCid, mode = "active") {
|
|
1972
|
-
|
|
1973
|
-
|
|
1974
|
-
|
|
1975
|
-
let
|
|
2907
|
+
const warm = mode === "local-first" ? await localHeader(context, configUrl) : undefined;
|
|
2908
|
+
if (warm && !warm.header.localSourceReady)
|
|
2909
|
+
await lazyPrivateSource(context, configUrl, warm.account, warm.header.config);
|
|
2910
|
+
let header = warm?.header ?? (await swarmHeader(context, configUrl));
|
|
2911
|
+
if (!hasMeta(header.snapshot) && header.source === "cache")
|
|
2912
|
+
header = await swarmHeader(context, configUrl, true);
|
|
2913
|
+
let association = (await registryAssociations(context, header)).find((item) => item.schemaCid === schemaCid);
|
|
1976
2914
|
if (!association && header.source === "cache") {
|
|
1977
2915
|
header = await swarmHeader(context, configUrl, true);
|
|
1978
|
-
association =
|
|
2916
|
+
association = (await registryAssociations(context, header)).find((item) => item.schemaCid === schemaCid);
|
|
1979
2917
|
}
|
|
1980
2918
|
return association;
|
|
1981
2919
|
}
|
|
2920
|
+
async function prepareNamesPublication(context, configUrl, previousRoot, current, names, roots, retainedRoots) {
|
|
2921
|
+
const next = await publication(context.store, await writeSnapshot(context.store, { ...current, names }, configUrl), previousRoot);
|
|
2922
|
+
const closure = await publicationClosure(context.store, next, false);
|
|
2923
|
+
await provideContent(context.store, [...new Set([...closure.provided, ...roots])], context.node.api, context.fetch, context.node.auth, [...new Set([next, ...closure.nameTargets, ...(retainedRoots ?? roots)])]);
|
|
2924
|
+
withState(context, (state) => {
|
|
2925
|
+
state.invalidateSwarmHeader(configUrl);
|
|
2926
|
+
});
|
|
2927
|
+
return next;
|
|
2928
|
+
}
|
|
1982
2929
|
async function editSwarmAssociation(context, configUrl, schemaCid, association, replace) {
|
|
1983
2930
|
const head = await pointer(context, configUrl);
|
|
2931
|
+
if (association) {
|
|
2932
|
+
const app = await openBundle(CID.parse(association.appCid), {
|
|
2933
|
+
resolveCid: (cid) => context.store.block.get(cid.toString()),
|
|
2934
|
+
});
|
|
2935
|
+
if (app.schemaKey !== appSchemaCid.toString())
|
|
2936
|
+
throw new HostError("Registry Names must directly reference an App Bundle CID, not an Artifact or another content type.");
|
|
2937
|
+
}
|
|
1984
2938
|
const roots = association
|
|
1985
2939
|
? await dependencies(context.store, association.appCid)
|
|
1986
2940
|
: new Set();
|
|
1987
2941
|
for (let attempt = 0; attempt < 8; attempt++) {
|
|
1988
2942
|
const currentHead = await head.read();
|
|
1989
|
-
const current = await readSnapshot(context.store, currentHead.root);
|
|
1990
|
-
|
|
2943
|
+
const current = await readSnapshot(context.store, currentHead.root, configUrl);
|
|
2944
|
+
assertNamesRegistry(current);
|
|
2945
|
+
const meta = await swarmMeta(context, { snapshot: current });
|
|
2946
|
+
const name = formalName(`${meta.registryPath}/${schemaCid}`);
|
|
2947
|
+
const oldCid = current.names[name]?.toString();
|
|
1991
2948
|
if (association) {
|
|
1992
|
-
if (
|
|
1993
|
-
old.appCid === association.appCid &&
|
|
1994
|
-
JSON.stringify(old.argv) === JSON.stringify(association.argv))
|
|
2949
|
+
if (oldCid === association.appCid)
|
|
1995
2950
|
return;
|
|
1996
|
-
if (
|
|
1997
|
-
throw new HostError("Schema has another association; use --replace
|
|
2951
|
+
if (oldCid && !replace)
|
|
2952
|
+
throw new HostError("Schema has another association; use --replace.");
|
|
1998
2953
|
}
|
|
1999
|
-
else if (!
|
|
2954
|
+
else if (!oldCid) {
|
|
2000
2955
|
throw new HostError("No association exists for this Schema. Run ipab register list --swarm URL_OR_ALIAS.");
|
|
2001
2956
|
}
|
|
2002
|
-
const
|
|
2957
|
+
const names = { ...current.names };
|
|
2003
2958
|
if (association)
|
|
2004
|
-
|
|
2005
|
-
appCid: CID.parse(association.appCid),
|
|
2006
|
-
argv: association.argv,
|
|
2007
|
-
};
|
|
2959
|
+
names[name] = CID.parse(association.appCid);
|
|
2008
2960
|
else
|
|
2009
|
-
delete
|
|
2010
|
-
const next = await
|
|
2011
|
-
await provideContent(context.store, [next, ...roots], context.node.api, context.fetch, context.node.auth);
|
|
2012
|
-
withState(context, (state) => {
|
|
2013
|
-
state.invalidateSwarmHeader(configUrl);
|
|
2014
|
-
});
|
|
2961
|
+
delete names[name];
|
|
2962
|
+
const next = await prepareNamesPublication(context, configUrl, currentHead.root, current, names, roots);
|
|
2015
2963
|
try {
|
|
2016
2964
|
await head.write(next, currentHead.cid, uniqueId());
|
|
2017
2965
|
return;
|
|
@@ -2025,6 +2973,8 @@ async function editSwarmAssociation(context, configUrl, schemaCid, association,
|
|
|
2025
2973
|
throw new HostError(`HEAD is busy for ${configUrl}; retry the registry edit.`);
|
|
2026
2974
|
}
|
|
2027
2975
|
export async function setSwarmAssociation(context, configUrl, value, replace = false) {
|
|
2976
|
+
if (value.argv.length !== 1 || value.argv[0] !== "%")
|
|
2977
|
+
throw new HostError('Custom per-association argv is unsupported. Apps opened through the registry receive only the content CID (whole "%" argument); adapt the App or use ipab exec APP_CID ARGS.');
|
|
2028
2978
|
const association = createAssociation(value.schemaCid, value.appCid, value.argv);
|
|
2029
2979
|
await editSwarmAssociation(context, configUrl, association.schemaCid, association, replace);
|
|
2030
2980
|
return association;
|
|
@@ -2058,10 +3008,18 @@ async function dependencies(store, root, found = new Set()) {
|
|
|
2058
3008
|
await dependencies(store, source.cid, found);
|
|
2059
3009
|
}
|
|
2060
3010
|
}
|
|
3011
|
+
else if (isSwarmStateSchema(bundle.schemaKey)) {
|
|
3012
|
+
const snapshot = await readState(store, CID.parse(root));
|
|
3013
|
+
for (const target of Object.values(snapshot.names))
|
|
3014
|
+
await dependencies(store, target.toString(), found);
|
|
3015
|
+
}
|
|
2061
3016
|
return found;
|
|
2062
3017
|
}
|
|
2063
3018
|
export async function frozenPublicationClosure(store, root) {
|
|
2064
|
-
|
|
3019
|
+
return (await publicationClosure(store, root)).provided;
|
|
3020
|
+
}
|
|
3021
|
+
async function publicationClosure(store, root, includeDependencies = true) {
|
|
3022
|
+
const publications = new Set(), content = new Set(), nameTargets = new Set();
|
|
2065
3023
|
let current = root;
|
|
2066
3024
|
while (current !== undefined) {
|
|
2067
3025
|
if (publications.has(current) || publications.size >= 256)
|
|
@@ -2069,35 +3027,52 @@ export async function frozenPublicationClosure(store, root) {
|
|
|
2069
3027
|
publications.add(current);
|
|
2070
3028
|
const publication = await readPublication(store, current);
|
|
2071
3029
|
const snapshot = await readState(store, publication.state);
|
|
2072
|
-
for (const target of Object.values(snapshot.names))
|
|
2073
|
-
|
|
2074
|
-
|
|
2075
|
-
|
|
3030
|
+
for (const target of Object.values(snapshot.names)) {
|
|
3031
|
+
nameTargets.add(target.toString());
|
|
3032
|
+
if (includeDependencies)
|
|
3033
|
+
await dependencies(store, target.toString(), content);
|
|
3034
|
+
else
|
|
3035
|
+
content.add(target.toString());
|
|
3036
|
+
}
|
|
3037
|
+
if (includeDependencies)
|
|
3038
|
+
for (const association of Object.values(snapshot.registrations ?? {}))
|
|
3039
|
+
await dependencies(store, association.appCid.toString(), content);
|
|
2076
3040
|
current = publication.previous?.toString();
|
|
2077
3041
|
}
|
|
2078
|
-
return
|
|
2079
|
-
|
|
2080
|
-
|
|
2081
|
-
|
|
2082
|
-
|
|
2083
|
-
|
|
3042
|
+
return {
|
|
3043
|
+
nameTargets,
|
|
3044
|
+
provided: [
|
|
3045
|
+
root,
|
|
3046
|
+
...[...new Set([...publications, ...content])]
|
|
3047
|
+
.filter((cid) => cid !== root)
|
|
3048
|
+
.sort(),
|
|
3049
|
+
],
|
|
3050
|
+
};
|
|
2084
3051
|
}
|
|
2085
3052
|
export async function publish(context, content, options) {
|
|
3053
|
+
return publishContent(context, content, options);
|
|
3054
|
+
}
|
|
3055
|
+
async function publishContent(context, content, options, nameForSnapshot) {
|
|
2086
3056
|
if (!options.swarm)
|
|
2087
3057
|
throw new HostError("Publication requires a selected Swarm configuration URL or alias.");
|
|
2088
3058
|
const head = await pointer(context, options.swarm);
|
|
2089
3059
|
const roots = await dependencies(context.store, content);
|
|
2090
3060
|
const currentRoots = [...(await currentDependencies(context.store, content))];
|
|
2091
3061
|
await withStateAsync(context, (state) => pinCid(state, content, context.store, currentRoots));
|
|
2092
|
-
|
|
3062
|
+
let name = formalName(options.name);
|
|
3063
|
+
let resolvedName;
|
|
2093
3064
|
if (options.snapshot && options.expect)
|
|
2094
3065
|
throw new HostError("Snapshots cannot replace an occupied Name.");
|
|
2095
3066
|
const expected = options.expect
|
|
2096
3067
|
? CID.parse(options.expect).toV1().toString()
|
|
2097
3068
|
: undefined;
|
|
2098
|
-
|
|
2099
|
-
|
|
2100
|
-
|
|
3069
|
+
const contentBundle = await openBundle(CID.parse(content), {
|
|
3070
|
+
resolveCid: (cid) => context.store.block.get(cid.toString()),
|
|
3071
|
+
});
|
|
3072
|
+
const direct = contentBundle.schemaKey === appSchemaCid.toString() ||
|
|
3073
|
+
contentBundle.schemaKey === swarmMetaSchema.cid.toString() ||
|
|
3074
|
+
contentBundle.schemaKey === legacySwarmMetaSchema.cid.toString();
|
|
3075
|
+
const candidate = options.snapshot || direct
|
|
2101
3076
|
? content
|
|
2102
3077
|
: await jsonBundle(context.store, artifactType, {
|
|
2103
3078
|
value: content,
|
|
@@ -2109,19 +3084,18 @@ export async function publish(context, content, options) {
|
|
|
2109
3084
|
for (const root of await dependencies(context.store, expected))
|
|
2110
3085
|
roots.add(root);
|
|
2111
3086
|
for (let attempt = 0; attempt < 8; attempt++) {
|
|
2112
|
-
const currentHead = await head.read(), current = await readSnapshot(context.store, currentHead.root);
|
|
3087
|
+
const currentHead = await head.read(), current = await readSnapshot(context.store, currentHead.root, options.swarm);
|
|
3088
|
+
if (nameForSnapshot) {
|
|
3089
|
+
name = await nameForSnapshot(current);
|
|
3090
|
+
if (resolvedName !== undefined && resolvedName !== name)
|
|
3091
|
+
throw new HostError("Template Meta path changed during publication; inspect and retry. Content remains pinned.", 3, "EDIT_CONFLICT", "publication");
|
|
3092
|
+
resolvedName = name;
|
|
3093
|
+
}
|
|
2113
3094
|
if ((Object.hasOwn(current.names, name)
|
|
2114
3095
|
? current.names[name]?.toString()
|
|
2115
3096
|
: undefined) !== expected)
|
|
2116
|
-
throw new HostError(`Edit conflict for ${name}; content ${content} remains pinned. Occupied Names require --expect
|
|
2117
|
-
const next = await
|
|
2118
|
-
...current,
|
|
2119
|
-
names: { ...current.names, [name]: CID.parse(candidate) },
|
|
2120
|
-
}), currentHead.root);
|
|
2121
|
-
await provideContent(context.store, [next, ...roots], context.node.api, context.fetch, context.node.auth, [next, ...(expected ? await dependencies(context.store, expected) : [])]);
|
|
2122
|
-
withState(context, (state) => {
|
|
2123
|
-
state.invalidateSwarmHeader(options.swarm);
|
|
2124
|
-
});
|
|
3097
|
+
throw new HostError(`Edit conflict for ${name}; content ${content} remains pinned. Occupied Names require --expect EXACT_OLD_CID (the old Artifact CID when applicable); inspect the current Name before retrying.`, 3, "EDIT_CONFLICT", "publication");
|
|
3098
|
+
const next = await prepareNamesPublication(context, options.swarm, currentHead.root, current, { ...current.names, [name]: CID.parse(candidate) }, roots, expected ? await dependencies(context.store, expected) : []);
|
|
2125
3099
|
try {
|
|
2126
3100
|
await head.write(next, currentHead.cid, uniqueId());
|
|
2127
3101
|
}
|