@ipab/cli 0.1.0-rc.7 → 0.1.0-rc.9
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 +70 -30
- package/dist/app-authoring.d.ts.map +1 -1
- package/dist/app-authoring.js +2 -44
- 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/builtins/skill.ipab.car +0 -0
- package/dist/bundled-skills.d.ts +14 -0
- package/dist/bundled-skills.d.ts.map +1 -0
- package/dist/bundled-skills.js +34 -0
- package/dist/bundled-skills.js.map +1 -0
- package/dist/cli.d.ts.map +1 -1
- package/dist/cli.js +309 -157
- 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 +4 -0
- package/dist/context.d.ts.map +1 -1
- package/dist/context.js +11 -2
- package/dist/context.js.map +1 -1
- package/dist/daemon.d.ts +4 -0
- package/dist/daemon.d.ts.map +1 -0
- package/dist/daemon.js +200 -0
- package/dist/daemon.js.map +1 -0
- package/dist/doctor.d.ts +2 -0
- package/dist/doctor.d.ts.map +1 -1
- package/dist/doctor.js +18 -4
- package/dist/doctor.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.map +1 -1
- package/dist/ipc.js +17 -0
- 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/skill-source.d.ts +4 -0
- package/dist/skill-source.d.ts.map +1 -1
- package/dist/skill-source.js +14 -2
- package/dist/skill-source.js.map +1 -1
- package/dist/skills.d.ts +18 -1
- package/dist/skills.d.ts.map +1 -1
- package/dist/skills.js +137 -39
- package/dist/skills.js.map +1 -1
- 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 +1 -2
- package/dist/space.d.ts.map +1 -1
- package/dist/space.js +2 -15
- 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 +31 -12
- package/dist/state.js.map +1 -1
- package/dist/swarm-files.d.ts +1 -1
- package/dist/swarm-files.d.ts.map +1 -1
- package/dist/swarm-files.js +10 -4
- package/dist/swarm-files.js.map +1 -1
- package/dist/swarm-meta.d.ts +1 -4
- package/dist/swarm-meta.d.ts.map +1 -1
- package/dist/swarm-meta.js +3 -34
- package/dist/swarm-meta.js.map +1 -1
- 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 +121 -6
- package/dist/swarm.d.ts.map +1 -1
- package/dist/swarm.js +672 -81
- package/dist/swarm.js.map +1 -1
- package/package.json +4 -4
- package/src/app-authoring.ts +12 -53
- package/src/app-prebuild.ts +61 -0
- package/src/bundled-skills.ts +60 -0
- package/src/cli.ts +398 -195
- package/src/config.ts +12 -4
- package/src/context.ts +15 -2
- package/src/daemon.ts +237 -0
- package/src/doctor.ts +42 -5
- package/src/errors.ts +1 -25
- package/src/host-error.ts +26 -0
- package/src/ipc.ts +19 -0
- 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/skill-source.ts +16 -2
- package/src/skills.ts +195 -53
- package/src/space-path.ts +30 -0
- package/src/space.ts +2 -28
- package/src/state-storage.ts +1 -1
- package/src/state.ts +37 -12
- package/src/swarm-files.ts +8 -3
- package/src/swarm-meta.ts +15 -34
- package/src/swarm-observations.ts +374 -0
- package/src/swarm.ts +953 -92
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";
|
|
@@ -25,13 +26,15 @@ 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";
|
|
30
33
|
import { seedTemplateNames, seedTemplateSource } from "./template-source.js";
|
|
31
34
|
import { inspectTemplate, templatePublicationSource } from "./templates.js";
|
|
32
35
|
import { seedSkillSource } from "./skill-source.js";
|
|
33
36
|
import { skillIdentity, skillSchema } from "./skill-definition.js";
|
|
34
|
-
import { parseSwarmMeta, swarmMetaType, swarmMetaSchema, swarmStateType, legacySwarmStateType, legacySwarmStateSchema, isSwarmStateSchema, legacySwarmMetaType, legacySwarmMetaSchema, } from "./swarm-meta.js";
|
|
37
|
+
import { parseSwarmMeta, swarmMetaType, swarmMetaSchema, swarmStateType, previousSwarmStateType, previousSwarmStateSchema, parseSwarmState, legacySwarmStateType, legacySwarmStateSchema, isSwarmStateSchema, legacySwarmMetaType, legacySwarmMetaSchema, } from "./swarm-meta.js";
|
|
35
38
|
async function contextIdentity(context, initialize = false) {
|
|
36
39
|
context.identity ??= await accountIdentity(context.env, initialize);
|
|
37
40
|
return context.identity;
|
|
@@ -147,6 +150,8 @@ function client(context, service, identity, secret) {
|
|
|
147
150
|
}
|
|
148
151
|
function parseOrganization(value, configUrl) {
|
|
149
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.");
|
|
150
155
|
const { scopeId } = coordinates(configUrl);
|
|
151
156
|
if (Object.keys(data).sort().join() !==
|
|
152
157
|
"bootstrap,description,epoch,headId,members,name,owner,scopeId,v" ||
|
|
@@ -232,10 +237,8 @@ function parseOrganization(value, configUrl) {
|
|
|
232
237
|
}
|
|
233
238
|
function parseProfile(value, expectedPeer) {
|
|
234
239
|
const data = object(value, "member profile");
|
|
235
|
-
if (![
|
|
236
|
-
"
|
|
237
|
-
"addresses,description,name,updatedAt",
|
|
238
|
-
].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") ||
|
|
239
242
|
typeof data.name !== "string" ||
|
|
240
243
|
data.name.length > 256 ||
|
|
241
244
|
(data.description !== undefined &&
|
|
@@ -259,22 +262,269 @@ function parseProfile(value, expectedPeer) {
|
|
|
259
262
|
? { description: data.description }
|
|
260
263
|
: {}),
|
|
261
264
|
addresses,
|
|
265
|
+
...(typeof data.pivot === "boolean" ? { pivot: data.pivot } : {}),
|
|
262
266
|
updatedAt: data.updatedAt,
|
|
263
267
|
};
|
|
264
268
|
}
|
|
265
|
-
|
|
266
|
-
const { config } = await fetchConfig(context, canonicalSwarmUrl(url));
|
|
269
|
+
async function memberDirectory(context, url, config) {
|
|
267
270
|
const c = coordinates(url), api = client(context, c.service);
|
|
268
271
|
const members = await boundedMap(config.members, async (member) => {
|
|
269
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);
|
|
270
286
|
return {
|
|
271
|
-
|
|
272
|
-
|
|
273
|
-
|
|
274
|
-
|
|
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
|
+
},
|
|
275
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) };
|
|
276
337
|
});
|
|
277
|
-
|
|
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
|
+
};
|
|
278
528
|
}
|
|
279
529
|
function accountProfileLocation(context, publicKey) {
|
|
280
530
|
return {
|
|
@@ -545,7 +795,7 @@ async function validateMembershipSecret(record, config, member) {
|
|
|
545
795
|
throw new HostError("Membership package must grant exactly HEAD and this member's profile.");
|
|
546
796
|
}
|
|
547
797
|
}
|
|
548
|
-
async function privateSource(context, record, signal) {
|
|
798
|
+
async function privateSource(context, record, signal, candidates) {
|
|
549
799
|
const config = record.config, secret = record.secret;
|
|
550
800
|
const identity = await contextIdentity(context);
|
|
551
801
|
const self = config.members.find((member) => member.publicKey === identity.publicKey);
|
|
@@ -558,36 +808,102 @@ async function privateSource(context, record, signal) {
|
|
|
558
808
|
}
|
|
559
809
|
const personal = await storedAccountProfile(context);
|
|
560
810
|
const addresses = new Map();
|
|
811
|
+
const observationErrors = [];
|
|
561
812
|
const api = client(context, c.service);
|
|
562
813
|
let selfProfile;
|
|
563
|
-
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
|
+
});
|
|
564
827
|
for (const [index, member] of config.members.entries()) {
|
|
565
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
|
+
}
|
|
566
835
|
const value = parseProfile(profile.value, member.peerId);
|
|
567
836
|
if (member.publicKey === identity.publicKey)
|
|
568
837
|
selfProfile = { profile: value, cid: profile.cid };
|
|
569
|
-
|
|
838
|
+
if (value.pivot === true && member.peerId !== self.peerId)
|
|
839
|
+
addresses.set(member.peerId, value.addresses);
|
|
570
840
|
}
|
|
571
841
|
if (personal && selfProfile) {
|
|
572
842
|
selfProfile.profile = await syncAccountProfile(context, record, personal, selfProfile);
|
|
573
843
|
selfProfile.cid = await valueCid(selfProfile.profile);
|
|
574
844
|
}
|
|
575
|
-
|
|
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, []);
|
|
576
861
|
signal?.throwIfAborted();
|
|
577
|
-
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
|
+
});
|
|
578
868
|
if (node.peerId !== self.peerId)
|
|
579
869
|
throw new HostError("Approved PeerID differs from this local Request's Kubo identity.");
|
|
580
870
|
const peers = desired.flatMap(({ ID, Addrs }) => Addrs.map((addr) => `${addr}/p2p/${ID}`));
|
|
581
871
|
signal?.throwIfAborted();
|
|
582
|
-
if (
|
|
583
|
-
|
|
584
|
-
|
|
585
|
-
|
|
586
|
-
|
|
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
|
+
};
|
|
587
902
|
const writer = client(context, c.service, identity, identity.publicKey === config.owner ? undefined : secret);
|
|
588
903
|
const profile = {
|
|
589
904
|
...selfProfile.profile,
|
|
590
|
-
|
|
905
|
+
pivot,
|
|
906
|
+
addresses: published,
|
|
591
907
|
updatedAt: new Date().toISOString(),
|
|
592
908
|
};
|
|
593
909
|
await writer.write(c.scopeId, self.profileId, profile, selfProfile.cid, uniqueId(), signal ? { signal } : {});
|
|
@@ -595,9 +911,207 @@ async function privateSource(context, record, signal) {
|
|
|
595
911
|
return {
|
|
596
912
|
node,
|
|
597
913
|
peers,
|
|
914
|
+
observationError: observationErrors.length
|
|
915
|
+
? observationErrors.join("; ")
|
|
916
|
+
: null,
|
|
598
917
|
source: kuboSource(node, peers, context.diagnostic, context.env.IPAB_SWARM_DIAL_DEBUG === "1"),
|
|
599
918
|
};
|
|
600
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 closeReadiness = await context.daemonReady?.();
|
|
924
|
+
const sessions = new Map();
|
|
925
|
+
context.diagnostic?.("IPAB daemon running in foreground; Ctrl-C stops management and leaves Kubo running.");
|
|
926
|
+
const persist = async (url, session, running) => {
|
|
927
|
+
const record = session.record;
|
|
928
|
+
if (!record?.config)
|
|
929
|
+
return;
|
|
930
|
+
const redact = (error) => {
|
|
931
|
+
if (error === null)
|
|
932
|
+
return null;
|
|
933
|
+
for (const secret of [
|
|
934
|
+
record.secret?.swarmKey,
|
|
935
|
+
session.node?.auth,
|
|
936
|
+
session.context.identity?.privateKey,
|
|
937
|
+
])
|
|
938
|
+
if (secret)
|
|
939
|
+
error = error.split(secret).join("[redacted]");
|
|
940
|
+
return error.slice(0, 2048);
|
|
941
|
+
};
|
|
942
|
+
const snapshot = {
|
|
943
|
+
v: 1,
|
|
944
|
+
binding: networkingBinding(url, record.account, record.config),
|
|
945
|
+
pid: process.pid,
|
|
946
|
+
running,
|
|
947
|
+
updatedAt: Date.now(),
|
|
948
|
+
verifiedAt: session.verifiedAt,
|
|
949
|
+
error: redact(session.error),
|
|
950
|
+
topology: session.node?.topology ?? null,
|
|
951
|
+
pivots: [...session.candidates.observations()].map(([peerId, value]) => ({
|
|
952
|
+
...value,
|
|
953
|
+
peerId,
|
|
954
|
+
selected: session.selected.has(peerId),
|
|
955
|
+
error: redact(value.error),
|
|
956
|
+
})),
|
|
957
|
+
account: record.account,
|
|
958
|
+
connections: session.connections
|
|
959
|
+
? {
|
|
960
|
+
...session.connections,
|
|
961
|
+
error: redact(session.connections.error),
|
|
962
|
+
}
|
|
963
|
+
: {
|
|
964
|
+
observedAt: null,
|
|
965
|
+
error: "No connection snapshot collected.",
|
|
966
|
+
peers: [],
|
|
967
|
+
},
|
|
968
|
+
};
|
|
969
|
+
await writeNetworkingSnapshot(context.stateDir, url, snapshot);
|
|
970
|
+
};
|
|
971
|
+
try {
|
|
972
|
+
while (!signal.aborted) {
|
|
973
|
+
const registrations = withState(context, (state) => state.swarms()).filter((entry) => selected === undefined || entry.cid === selected);
|
|
974
|
+
if (selected && !registrations.length)
|
|
975
|
+
throw new HostError("Selected Swarm is not registered; run ipab swarm add first.");
|
|
976
|
+
const urls = new Set(registrations.map((entry) => entry.cid));
|
|
977
|
+
for (const url of sessions.keys())
|
|
978
|
+
if (!urls.has(url)) {
|
|
979
|
+
await persist(url, sessions.get(url), false);
|
|
980
|
+
sessions.delete(url);
|
|
981
|
+
}
|
|
982
|
+
await boundedMap(registrations, async ({ cid: url }) => {
|
|
983
|
+
let session = sessions.get(url);
|
|
984
|
+
if (!session) {
|
|
985
|
+
session = {
|
|
986
|
+
context: { ...context },
|
|
987
|
+
candidates: new PivotCandidates(),
|
|
988
|
+
nextDiscovery: 0,
|
|
989
|
+
healthy: 0,
|
|
990
|
+
selected: new Set(),
|
|
991
|
+
verifiedAt: null,
|
|
992
|
+
error: null,
|
|
993
|
+
};
|
|
994
|
+
sessions.set(url, session);
|
|
995
|
+
}
|
|
996
|
+
try {
|
|
997
|
+
if (Date.now() >= session.nextDiscovery || session.healthy < 1) {
|
|
998
|
+
const record = await approvedMembership(session.context, url, signal);
|
|
999
|
+
const c = coordinates(url);
|
|
1000
|
+
const scope = nodeScope(c.service, record.config.scopeId);
|
|
1001
|
+
const existing = await readPrivate(join(context.stateDir, "swarm-nodes", scope), "node.json");
|
|
1002
|
+
if (!existing)
|
|
1003
|
+
throw new HostError("No existing managed node; activate this membership before running daemon.");
|
|
1004
|
+
await saveLocal(session.context, record);
|
|
1005
|
+
if (!session.record?.config ||
|
|
1006
|
+
networkingBinding(url, record.account, record.config) !==
|
|
1007
|
+
networkingBinding(url, session.record.account, session.record.config)) {
|
|
1008
|
+
session.candidates.reconcile(new Map());
|
|
1009
|
+
session.selected.clear();
|
|
1010
|
+
session.verifiedAt = null;
|
|
1011
|
+
delete session.connections;
|
|
1012
|
+
delete session.node;
|
|
1013
|
+
}
|
|
1014
|
+
session.record = record;
|
|
1015
|
+
const result = await privateSource(session.context, record, signal, session.candidates);
|
|
1016
|
+
session.node = result.node;
|
|
1017
|
+
session.selected = new Set(result.peers.map((address) => address.split("/").at(-1)));
|
|
1018
|
+
session.error = result.observationError;
|
|
1019
|
+
if (!session.error)
|
|
1020
|
+
session.verifiedAt = Date.now();
|
|
1021
|
+
session.context.node = result.node;
|
|
1022
|
+
session.nextDiscovery = Date.now() + 120_000;
|
|
1023
|
+
await persist(url, session, true);
|
|
1024
|
+
}
|
|
1025
|
+
if (!session.node)
|
|
1026
|
+
return;
|
|
1027
|
+
let healthy = 0;
|
|
1028
|
+
await boundedMap([...session.candidates.active()], async ([id, addresses]) => {
|
|
1029
|
+
let success = false;
|
|
1030
|
+
let error = null;
|
|
1031
|
+
try {
|
|
1032
|
+
success = await probePeer(session.node, id, addresses, signal);
|
|
1033
|
+
}
|
|
1034
|
+
catch (cause) {
|
|
1035
|
+
signal.throwIfAborted();
|
|
1036
|
+
error = message(cause);
|
|
1037
|
+
context.diagnostic?.(`[${url}] Pivot probe ${id}: ${message(cause)}`);
|
|
1038
|
+
}
|
|
1039
|
+
session.candidates.result(id, success, Date.now(), Math.random(), success ? null : (error ?? "Pivot dial failed."));
|
|
1040
|
+
if (success)
|
|
1041
|
+
healthy++;
|
|
1042
|
+
else {
|
|
1043
|
+
session.nextDiscovery = 0;
|
|
1044
|
+
context.diagnostic?.(`[${url}] Pivot ${id} dial failed; refreshing profile, with cooldown after repeated failure.`);
|
|
1045
|
+
}
|
|
1046
|
+
});
|
|
1047
|
+
session.healthy = healthy;
|
|
1048
|
+
// Startup-captured relay/bootstrap options must be removed immediately
|
|
1049
|
+
// when a candidate enters cooldown, not merely changed through config RPC.
|
|
1050
|
+
const record = session.record;
|
|
1051
|
+
const self = record.config.members.find((member) => member.publicKey === record.account);
|
|
1052
|
+
const desired = memberPeers(self.peerId, session.candidates.active(), []);
|
|
1053
|
+
session.node = await startNode(context.stateDir, nodeScope(coordinates(url).service, record.config.scopeId), record.secret.swarmKey, record.config.epoch, context.listen, {
|
|
1054
|
+
self: self.peerId,
|
|
1055
|
+
pivot: context.pivot ?? false,
|
|
1056
|
+
peers: desired,
|
|
1057
|
+
signal,
|
|
1058
|
+
});
|
|
1059
|
+
session.selected = new Set(desired.map(({ ID }) => ID));
|
|
1060
|
+
try {
|
|
1061
|
+
const peers = await nodeConnections(session.node, signal);
|
|
1062
|
+
session.connections = {
|
|
1063
|
+
observedAt: Date.now(),
|
|
1064
|
+
error: null,
|
|
1065
|
+
peers,
|
|
1066
|
+
};
|
|
1067
|
+
}
|
|
1068
|
+
catch (cause) {
|
|
1069
|
+
signal.throwIfAborted();
|
|
1070
|
+
session.connections = {
|
|
1071
|
+
observedAt: session.connections?.observedAt ?? null,
|
|
1072
|
+
error: message(cause).slice(0, 2048),
|
|
1073
|
+
peers: session.connections?.peers ?? [],
|
|
1074
|
+
};
|
|
1075
|
+
}
|
|
1076
|
+
}
|
|
1077
|
+
catch (cause) {
|
|
1078
|
+
if (signal.aborted)
|
|
1079
|
+
return;
|
|
1080
|
+
session.error = message(cause);
|
|
1081
|
+
session.nextDiscovery = 0;
|
|
1082
|
+
context.diagnostic?.(`[${url}] Daemon refresh failed (last-known local candidates retained): ${message(cause)}`);
|
|
1083
|
+
if (cause instanceof HostError &&
|
|
1084
|
+
/membership removed|identity was removed|epoch rollback|Pinned Owner changed/.test(cause.message)) {
|
|
1085
|
+
if (session.node)
|
|
1086
|
+
await stopNode(session.node);
|
|
1087
|
+
session.candidates.reconcile(new Map());
|
|
1088
|
+
delete session.node;
|
|
1089
|
+
session.selected.clear();
|
|
1090
|
+
await persist(url, session, false);
|
|
1091
|
+
delete session.record;
|
|
1092
|
+
}
|
|
1093
|
+
}
|
|
1094
|
+
await persist(url, session, true);
|
|
1095
|
+
});
|
|
1096
|
+
try {
|
|
1097
|
+
await delay(30_000 + Math.random() * 15_000, undefined, { signal });
|
|
1098
|
+
}
|
|
1099
|
+
catch {
|
|
1100
|
+
signal.throwIfAborted();
|
|
1101
|
+
}
|
|
1102
|
+
}
|
|
1103
|
+
}
|
|
1104
|
+
finally {
|
|
1105
|
+
try {
|
|
1106
|
+
for (const [url, session] of sessions)
|
|
1107
|
+
await persist(url, session, false);
|
|
1108
|
+
}
|
|
1109
|
+
finally {
|
|
1110
|
+
await closeReadiness?.();
|
|
1111
|
+
}
|
|
1112
|
+
}
|
|
1113
|
+
}, signal, 1);
|
|
1114
|
+
}
|
|
601
1115
|
async function activate(context, record) {
|
|
602
1116
|
const { node, peers, source } = await privateSource(context, record);
|
|
603
1117
|
if (context.node?.api !== node.api ||
|
|
@@ -609,6 +1123,7 @@ async function activate(context, record) {
|
|
|
609
1123
|
context.sourcePeers = peers;
|
|
610
1124
|
}
|
|
611
1125
|
context.node = node;
|
|
1126
|
+
await context.ensureDaemon?.();
|
|
612
1127
|
}
|
|
613
1128
|
async function localForRead(context, configUrl) {
|
|
614
1129
|
const record = await local(context, configUrl);
|
|
@@ -762,19 +1277,30 @@ export async function jsonBundle(store, type, value) {
|
|
|
762
1277
|
await encoded.close();
|
|
763
1278
|
}
|
|
764
1279
|
}
|
|
765
|
-
async function writeStateBundle(store, configuration, targets) {
|
|
1280
|
+
async function writeStateBundle(store, configuration, targets, configUrl) {
|
|
766
1281
|
const meta = parseSwarmMeta(configuration);
|
|
767
1282
|
const names = Object.fromEntries(Object.entries(targets).map(([name, cid]) => [
|
|
768
1283
|
formalName(name),
|
|
769
1284
|
cid.toString(),
|
|
770
1285
|
]));
|
|
771
|
-
|
|
1286
|
+
const value = parseSwarmState({
|
|
1287
|
+
v: configUrl === undefined ? 5 : 6,
|
|
1288
|
+
...(configUrl === undefined ? {} : { configUrl }),
|
|
1289
|
+
...meta,
|
|
1290
|
+
names,
|
|
1291
|
+
});
|
|
1292
|
+
return jsonBundle(store, configUrl !== undefined
|
|
1293
|
+
? swarmStateType
|
|
1294
|
+
: meta.skillPath === undefined
|
|
1295
|
+
? legacySwarmStateType
|
|
1296
|
+
: previousSwarmStateType, value);
|
|
772
1297
|
}
|
|
773
|
-
export async function writeSnapshot(store, snapshot) {
|
|
1298
|
+
export async function writeSnapshot(store, snapshot, configUrl) {
|
|
774
1299
|
if (snapshot.stateBundle) {
|
|
775
1300
|
if (Object.keys(snapshot.registrations ?? {}).length)
|
|
776
1301
|
throw new HostError("State Bundles cannot contain legacy registrations.");
|
|
777
|
-
|
|
1302
|
+
checkStateOrigin(snapshot, configUrl);
|
|
1303
|
+
return writeStateBundle(store, snapshot.stateBundle.meta, snapshot.names, snapshot.stateBundle.configUrl);
|
|
778
1304
|
}
|
|
779
1305
|
const put = async (value) => {
|
|
780
1306
|
const encoded = dagCbor.encode(value);
|
|
@@ -796,18 +1322,14 @@ async function readState(store, cid) {
|
|
|
796
1322
|
});
|
|
797
1323
|
const type = bundle.schemaKey === legacySwarmStateSchema.cid.toString()
|
|
798
1324
|
? legacySwarmStateType
|
|
799
|
-
:
|
|
800
|
-
|
|
801
|
-
|
|
802
|
-
|
|
803
|
-
(type === legacySwarmStateType
|
|
804
|
-
? "names,registryPath,templatePath,v"
|
|
805
|
-
: "names,registryPath,skillPath,templatePath,v"))
|
|
806
|
-
throw new HostError("Invalid State Bundle entry.");
|
|
1325
|
+
: bundle.schemaKey === previousSwarmStateSchema.cid.toString()
|
|
1326
|
+
? previousSwarmStateType
|
|
1327
|
+
: swarmStateType;
|
|
1328
|
+
const value = parseSwarmState(await typedJson(store, cid.toString(), type));
|
|
807
1329
|
const meta = parseSwarmMeta({
|
|
808
1330
|
templatePath: value.templatePath,
|
|
809
1331
|
registryPath: value.registryPath,
|
|
810
|
-
...(
|
|
1332
|
+
...(value.skillPath === undefined ? {} : { skillPath: value.skillPath }),
|
|
811
1333
|
});
|
|
812
1334
|
const names = Object.fromEntries(Object.entries(object(value.names, "Names")).map(([name, target]) => {
|
|
813
1335
|
formalName(name);
|
|
@@ -815,7 +1337,17 @@ async function readState(store, cid) {
|
|
|
815
1337
|
throw new HostError("State Names require exact canonical CIDs.");
|
|
816
1338
|
return [name, CID.parse(target)];
|
|
817
1339
|
}));
|
|
818
|
-
return {
|
|
1340
|
+
return {
|
|
1341
|
+
v: 2,
|
|
1342
|
+
names,
|
|
1343
|
+
stateBundle: {
|
|
1344
|
+
meta,
|
|
1345
|
+
cid: cid.toString(),
|
|
1346
|
+
...(value.configUrl === undefined
|
|
1347
|
+
? {}
|
|
1348
|
+
: { configUrl: value.configUrl }),
|
|
1349
|
+
},
|
|
1350
|
+
};
|
|
819
1351
|
}
|
|
820
1352
|
const data = await store.block.get(cid.toString());
|
|
821
1353
|
const root = object(dagCbor.decode(data), "State");
|
|
@@ -880,14 +1412,24 @@ function decodeSnapshot(data) {
|
|
|
880
1412
|
...(value.registrations !== undefined ? { registrations } : {}),
|
|
881
1413
|
};
|
|
882
1414
|
}
|
|
883
|
-
export async function readSnapshot(store, root) {
|
|
1415
|
+
export async function readSnapshot(store, root, configUrl) {
|
|
884
1416
|
const publication = await readPublication(store, root);
|
|
885
|
-
|
|
1417
|
+
const snapshot = await readState(store, publication.state);
|
|
1418
|
+
checkStateOrigin(snapshot, configUrl);
|
|
1419
|
+
return snapshot;
|
|
886
1420
|
}
|
|
887
|
-
|
|
1421
|
+
function checkStateOrigin(snapshot, configUrl) {
|
|
1422
|
+
if (configUrl !== undefined &&
|
|
1423
|
+
snapshot.stateBundle?.configUrl !== undefined &&
|
|
1424
|
+
snapshot.stateBundle.configUrl !== configUrl)
|
|
1425
|
+
throw new HostError("State Bundle Config URL does not match the selected Swarm.");
|
|
1426
|
+
}
|
|
1427
|
+
async function readHeaderSnapshot(store, root, configUrl) {
|
|
888
1428
|
const publication = await readPublication(store, root);
|
|
1429
|
+
const snapshot = await readState(store, publication.state);
|
|
1430
|
+
checkStateOrigin(snapshot, configUrl);
|
|
889
1431
|
return {
|
|
890
|
-
snapshot
|
|
1432
|
+
snapshot,
|
|
891
1433
|
stateCid: publication.state.toString(),
|
|
892
1434
|
};
|
|
893
1435
|
}
|
|
@@ -928,7 +1470,7 @@ export async function sharedSwarmStatus(context, configUrl) {
|
|
|
928
1470
|
const head = headValue(await client(context, c.service).read(c.scopeId, config.headId));
|
|
929
1471
|
let content;
|
|
930
1472
|
try {
|
|
931
|
-
content = await readHeaderSnapshot(context.store, head.root);
|
|
1473
|
+
content = await readHeaderSnapshot(context.store, head.root, configUrl);
|
|
932
1474
|
}
|
|
933
1475
|
catch (cause) {
|
|
934
1476
|
if (!missingContent(cause))
|
|
@@ -995,14 +1537,14 @@ async function readSwarmHeader(context, configUrl, force = context.forceRefresh
|
|
|
995
1537
|
: await (await boundPointer(context, configUrl, record)).read();
|
|
996
1538
|
let content;
|
|
997
1539
|
try {
|
|
998
|
-
content = await readHeaderSnapshot(context.store, head.root);
|
|
1540
|
+
content = await readHeaderSnapshot(context.store, head.root, configUrl);
|
|
999
1541
|
}
|
|
1000
1542
|
catch (cause) {
|
|
1001
1543
|
if (mode === "local-first")
|
|
1002
1544
|
throw cause;
|
|
1003
1545
|
record = await refresh(context, configUrl);
|
|
1004
1546
|
head = await (await boundPointer(context, configUrl, record)).read();
|
|
1005
|
-
content = await readHeaderSnapshot(context.store, head.root);
|
|
1547
|
+
content = await readHeaderSnapshot(context.store, head.root, configUrl);
|
|
1006
1548
|
}
|
|
1007
1549
|
const current = await local(context, configUrl), verifiedAt = Date.now();
|
|
1008
1550
|
withState(context, (state) => {
|
|
@@ -1042,12 +1584,26 @@ async function cachedHeader(context, record) {
|
|
|
1042
1584
|
const snapshot = decodeSnapshot(dagCbor.encode(legacySnapshot));
|
|
1043
1585
|
if (stateBundle !== undefined) {
|
|
1044
1586
|
const data = object(stateBundle, "cached State Bundle");
|
|
1045
|
-
if (Object.keys(data).sort().join()
|
|
1587
|
+
if (!["cid,meta", "cid,configUrl,meta"].includes(Object.keys(data).sort().join()) ||
|
|
1046
1588
|
typeof data.cid !== "string" ||
|
|
1047
1589
|
exactCid(data.cid) !== data.cid ||
|
|
1048
1590
|
(cached.stateCid !== undefined && data.cid !== cached.stateCid))
|
|
1049
1591
|
throw new HostError("Invalid cached State Bundle.");
|
|
1050
|
-
|
|
1592
|
+
const meta = parseSwarmMeta(data.meta);
|
|
1593
|
+
const parsed = parseSwarmState({
|
|
1594
|
+
v: data.configUrl === undefined ? 5 : 6,
|
|
1595
|
+
...meta,
|
|
1596
|
+
...(data.configUrl === undefined ? {} : { configUrl: data.configUrl }),
|
|
1597
|
+
names: {},
|
|
1598
|
+
});
|
|
1599
|
+
snapshot.stateBundle = {
|
|
1600
|
+
meta,
|
|
1601
|
+
cid: data.cid,
|
|
1602
|
+
...(parsed.configUrl === undefined
|
|
1603
|
+
? {}
|
|
1604
|
+
: { configUrl: parsed.configUrl }),
|
|
1605
|
+
};
|
|
1606
|
+
checkStateOrigin(snapshot, record.configUrl);
|
|
1051
1607
|
}
|
|
1052
1608
|
let stateCid = cached.stateCid;
|
|
1053
1609
|
if (!stateCid) {
|
|
@@ -1145,8 +1701,10 @@ async function lazyPrivateSource(context, url, account, basis) {
|
|
|
1145
1701
|
record.config.owner !== basis.owner ||
|
|
1146
1702
|
record.config.epoch !== basis.epoch ||
|
|
1147
1703
|
record.config.headId !== basis.headId)
|
|
1148
|
-
throw new HostError("Swarm membership changed since this cached HEAD; retry with --
|
|
1149
|
-
|
|
1704
|
+
throw new HostError("Swarm membership changed since this cached HEAD; retry with --refresh.");
|
|
1705
|
+
const { source } = await privateSource(scoped, record, signal);
|
|
1706
|
+
await context.ensureDaemon?.();
|
|
1707
|
+
return source;
|
|
1150
1708
|
};
|
|
1151
1709
|
// Same lock order as Owner rotation: credentials first, then the node.
|
|
1152
1710
|
return withPrivateLock(await directory(scoped), authorize, signal);
|
|
@@ -1173,11 +1731,6 @@ async function lazyPrivateSource(context, url, account, basis) {
|
|
|
1173
1731
|
await pending?.catch(() => { });
|
|
1174
1732
|
};
|
|
1175
1733
|
}
|
|
1176
|
-
export async function addSwarm(context, url, alias) {
|
|
1177
|
-
canonicalSwarmUrl(url);
|
|
1178
|
-
await readyMembership(context, url);
|
|
1179
|
-
withState(context, (state) => state.registerSwarm(url, alias));
|
|
1180
|
-
}
|
|
1181
1734
|
export async function createSwarm(context, options = {}) {
|
|
1182
1735
|
if ((options.properties?.name.length ?? 0) > 256 ||
|
|
1183
1736
|
(options.properties?.description.length ?? 0) > 2048 ||
|
|
@@ -1205,6 +1758,7 @@ export async function createSwarm(context, options = {}) {
|
|
|
1205
1758
|
if (options.resume)
|
|
1206
1759
|
throw new HostError("Unknown creation operation.");
|
|
1207
1760
|
record = {
|
|
1761
|
+
stateVersion: 6,
|
|
1208
1762
|
owner: identity.publicKey,
|
|
1209
1763
|
service,
|
|
1210
1764
|
encryption: encryptionIdentity(),
|
|
@@ -1221,6 +1775,24 @@ export async function createSwarm(context, options = {}) {
|
|
|
1221
1775
|
const save = () => writePrivate(dir, `creation-${op}.json`, record);
|
|
1222
1776
|
const api = client(context, service, identity);
|
|
1223
1777
|
try {
|
|
1778
|
+
if (record.stateVersion === 6) {
|
|
1779
|
+
if (!record.scopeId) {
|
|
1780
|
+
record.scopeId = (await api.createScope(`${op}.scope`)).id;
|
|
1781
|
+
await save();
|
|
1782
|
+
}
|
|
1783
|
+
if (!record.configId) {
|
|
1784
|
+
// Reserve the Config address, not a Config or a temporary HEAD.
|
|
1785
|
+
const reservation = await api.create(record.scopeId, {
|
|
1786
|
+
v: 1,
|
|
1787
|
+
kind: "ipab-config-reservation",
|
|
1788
|
+
owner: record.owner,
|
|
1789
|
+
operation: op,
|
|
1790
|
+
}, `${op}.config-reserve`);
|
|
1791
|
+
record.configId = reservation.id;
|
|
1792
|
+
record.configReservationCid = reservation.cid;
|
|
1793
|
+
await save();
|
|
1794
|
+
}
|
|
1795
|
+
}
|
|
1224
1796
|
if (!record.seed) {
|
|
1225
1797
|
if (record.headId)
|
|
1226
1798
|
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.");
|
|
@@ -1229,17 +1801,19 @@ export async function createSwarm(context, options = {}) {
|
|
|
1229
1801
|
const template = await seedTemplateSource(selector);
|
|
1230
1802
|
for (const [cid, data] of template.blocks)
|
|
1231
1803
|
await context.store.put(CID.parse(cid), data);
|
|
1232
|
-
names[`ipab/
|
|
1804
|
+
names[`ipab/templates/${selector}`] = CID.parse(template.cid);
|
|
1233
1805
|
}
|
|
1234
1806
|
const skill = await seedSkillSource();
|
|
1235
1807
|
for (const [cid, data] of skill.blocks)
|
|
1236
1808
|
await context.store.put(CID.parse(cid), data);
|
|
1237
1809
|
names["ipab/skills/ipab"] = CID.parse(skill.cid);
|
|
1238
1810
|
const root = await publication(context.store, await writeStateBundle(context.store, {
|
|
1239
|
-
templatePath: "ipab/
|
|
1811
|
+
templatePath: "ipab/templates",
|
|
1240
1812
|
registryPath: "ipab/registry",
|
|
1241
1813
|
skillPath: "ipab/skills",
|
|
1242
|
-
}, names
|
|
1814
|
+
}, names, record.stateVersion === 6
|
|
1815
|
+
? `${service}/v1/${record.scopeId}/${record.configId}`
|
|
1816
|
+
: undefined));
|
|
1243
1817
|
const roots = await frozenPublicationClosure(context.store, root);
|
|
1244
1818
|
record.seed = {
|
|
1245
1819
|
root,
|
|
@@ -1263,12 +1837,13 @@ export async function createSwarm(context, options = {}) {
|
|
|
1263
1837
|
}
|
|
1264
1838
|
if (!record.profileId) {
|
|
1265
1839
|
if (!record.profile) {
|
|
1266
|
-
const addresses = options.addresses ??
|
|
1840
|
+
const addresses = options.addresses ?? [];
|
|
1267
1841
|
for (const address of addresses)
|
|
1268
1842
|
validateAddress(address, node.peerId);
|
|
1269
1843
|
record.profile = {
|
|
1270
1844
|
...(record.personal ?? { name: record.name }),
|
|
1271
1845
|
addresses,
|
|
1846
|
+
pivot: context.pivot ?? false,
|
|
1272
1847
|
updatedAt: record.createdAt,
|
|
1273
1848
|
};
|
|
1274
1849
|
await save();
|
|
@@ -1293,7 +1868,7 @@ export async function createSwarm(context, options = {}) {
|
|
|
1293
1868
|
description: record.description,
|
|
1294
1869
|
headId: record.headId,
|
|
1295
1870
|
epoch: 1,
|
|
1296
|
-
bootstrap:
|
|
1871
|
+
bootstrap: [],
|
|
1297
1872
|
members: [member],
|
|
1298
1873
|
};
|
|
1299
1874
|
await save();
|
|
@@ -1302,6 +1877,19 @@ export async function createSwarm(context, options = {}) {
|
|
|
1302
1877
|
record.configId = (await api.create(record.scopeId, configValue(record.config), `${op}.config`)).id;
|
|
1303
1878
|
await save();
|
|
1304
1879
|
}
|
|
1880
|
+
if (record.stateVersion === 6 && !record.configPublished) {
|
|
1881
|
+
if (!record.configReservationCid)
|
|
1882
|
+
throw new HostError("Creation Config reservation checkpoint is missing.");
|
|
1883
|
+
const value = configValue(record.config);
|
|
1884
|
+
const current = await api.read(record.scopeId, record.configId);
|
|
1885
|
+
if (current.cid !== (await valueCid(value))) {
|
|
1886
|
+
if (current.cid !== record.configReservationCid)
|
|
1887
|
+
throw new HostError("Creation Config reservation was changed; refusing to overwrite it.");
|
|
1888
|
+
await api.write(record.scopeId, record.configId, value, record.configReservationCid, `${op}.config`);
|
|
1889
|
+
}
|
|
1890
|
+
record.configPublished = true;
|
|
1891
|
+
await save();
|
|
1892
|
+
}
|
|
1305
1893
|
const configUrl = `${service}/v1/${record.scopeId}/${record.configId}`;
|
|
1306
1894
|
const cert = await issueScopeCertificate({
|
|
1307
1895
|
v: 1,
|
|
@@ -1354,10 +1942,6 @@ export async function requestMembership(context, url, options) {
|
|
|
1354
1942
|
const personal = await ensureAccountProfile(context);
|
|
1355
1943
|
const dir = await directory(context);
|
|
1356
1944
|
await withPrivateLock(dir, async () => {
|
|
1357
|
-
if (options.alias !== undefined)
|
|
1358
|
-
withState(context, (state) => {
|
|
1359
|
-
state.checkSwarmAlias(options.alias, url);
|
|
1360
|
-
});
|
|
1361
1945
|
const existing = await readPrivate(dir, localName(url));
|
|
1362
1946
|
if (existing) {
|
|
1363
1947
|
if (existing.account !== identity.publicKey ||
|
|
@@ -1365,7 +1949,6 @@ export async function requestMembership(context, url, options) {
|
|
|
1365
1949
|
throw new HostError("Existing Request belongs to a different identity or pinned Owner.");
|
|
1366
1950
|
if (!existing.request)
|
|
1367
1951
|
throw new HostError("This identity is already the Owner.");
|
|
1368
|
-
withState(context, (state) => state.registerSwarm(url, options.alias));
|
|
1369
1952
|
return;
|
|
1370
1953
|
}
|
|
1371
1954
|
const node = await prepareNode(context.stateDir, nodeScope(coordinates(url).service, config.scopeId), context.listen), encryption = encryptionIdentity();
|
|
@@ -1397,7 +1980,6 @@ export async function requestMembership(context, url, options) {
|
|
|
1397
1980
|
encryption,
|
|
1398
1981
|
request,
|
|
1399
1982
|
});
|
|
1400
|
-
withState(context, (state) => state.registerSwarm(url, options.alias));
|
|
1401
1983
|
});
|
|
1402
1984
|
const file = options.output === undefined ? undefined : resolve(options.output);
|
|
1403
1985
|
if (file !== undefined)
|
|
@@ -1643,6 +2225,11 @@ export async function updateProfile(context, url, changes) {
|
|
|
1643
2225
|
updatedAt: new Date().toISOString(),
|
|
1644
2226
|
};
|
|
1645
2227
|
await api.write(c.scopeId, member.profileId, profile, existing.cid, uniqueId());
|
|
2228
|
+
await writePrivate(await directory(context), `pivot-${localName(url)}`, {
|
|
2229
|
+
manual: changes.addresses,
|
|
2230
|
+
});
|
|
2231
|
+
if (!context.pivot)
|
|
2232
|
+
context.diagnostic?.("Manual addresses saved; they are discovery candidates only when swarm.pivot=true. Ordinary nodes do not provide relay service.");
|
|
1646
2233
|
return profile;
|
|
1647
2234
|
}
|
|
1648
2235
|
export async function removeMember(context, url, member) {
|
|
@@ -1691,6 +2278,7 @@ export async function resumeRemoval(context, url) {
|
|
|
1691
2278
|
membershipBeforeSwitch.config = record.oldConfig;
|
|
1692
2279
|
membershipBeforeSwitch.secret.swarmKey = record.oldKey;
|
|
1693
2280
|
await activate(context, membershipBeforeSwitch);
|
|
2281
|
+
await readSnapshot(context.store, headValue(record.finalHead).root, url);
|
|
1694
2282
|
if (!record.finalClosureRoots) {
|
|
1695
2283
|
record.finalClosureRoots = await frozenPublicationClosure(context.store, headValue(record.finalHead).root);
|
|
1696
2284
|
await save();
|
|
@@ -1844,7 +2432,7 @@ export function parseNameReference(reference) {
|
|
|
1844
2432
|
try {
|
|
1845
2433
|
return {
|
|
1846
2434
|
...(authority ? { swarm: authority } : {}),
|
|
1847
|
-
name: formalName(segments.join("/")),
|
|
2435
|
+
name: match[2] === "" ? "" : formalName(segments.join("/")),
|
|
1848
2436
|
};
|
|
1849
2437
|
}
|
|
1850
2438
|
catch (error) {
|
|
@@ -1868,20 +2456,21 @@ export async function resolveReference(context, reference, swarm, local, raw = f
|
|
|
1868
2456
|
throw new HostError("Select a configuration URL/alias using --swarm or swarm use.");
|
|
1869
2457
|
const warm = mode === "local-first" ? await localHeader(context, selected) : undefined;
|
|
1870
2458
|
let header = warm?.header ?? (await swarmHeader(context, selected));
|
|
1871
|
-
|
|
1872
|
-
? header.
|
|
1873
|
-
:
|
|
2459
|
+
const target = () => shared.name === ""
|
|
2460
|
+
? header.stateCid
|
|
2461
|
+
: Object.hasOwn(header.snapshot.names, shared.name)
|
|
2462
|
+
? header.snapshot.names[shared.name]?.toString()
|
|
2463
|
+
: undefined;
|
|
2464
|
+
let link = target();
|
|
1874
2465
|
if (!link && header.source === "cache") {
|
|
1875
2466
|
header = await swarmHeader(context, selected, true);
|
|
1876
|
-
link =
|
|
1877
|
-
? header.snapshot.names[shared.name]
|
|
1878
|
-
: undefined;
|
|
2467
|
+
link = target();
|
|
1879
2468
|
}
|
|
1880
2469
|
if (!link)
|
|
1881
2470
|
throw new HostError(`Formal Name "${shared.name}" was not found after refreshing HEAD.`);
|
|
1882
2471
|
if (warm && header === warm.header && !header.localSourceReady)
|
|
1883
2472
|
await lazyPrivateSource(context, selected, warm.account, header.config);
|
|
1884
|
-
targetCid = link
|
|
2473
|
+
targetCid = link;
|
|
1885
2474
|
}
|
|
1886
2475
|
else {
|
|
1887
2476
|
if (swarm)
|
|
@@ -1925,7 +2514,7 @@ export function pinReference(state, reference, selected) {
|
|
|
1925
2514
|
}
|
|
1926
2515
|
export async function pinNameSubscription(context, reference, selected) {
|
|
1927
2516
|
const canonical = withState(context, (state) => pinReference(state, reference, selected));
|
|
1928
|
-
if (!canonical.swarm ||
|
|
2517
|
+
if (!canonical.swarm || canonical.name === undefined) {
|
|
1929
2518
|
let roots;
|
|
1930
2519
|
try {
|
|
1931
2520
|
roots = [
|
|
@@ -1968,9 +2557,11 @@ export async function refreshNamePins(context, url, header) {
|
|
|
1968
2557
|
.filter((pin) => pin.swarm === url && pin.status !== "deleting"));
|
|
1969
2558
|
const failures = [];
|
|
1970
2559
|
for (const saved of pins) {
|
|
1971
|
-
const target =
|
|
1972
|
-
? header.
|
|
1973
|
-
:
|
|
2560
|
+
const target = saved.name === ""
|
|
2561
|
+
? header.stateCid
|
|
2562
|
+
: Object.hasOwn(header.snapshot.names, saved.name)
|
|
2563
|
+
? header.snapshot.names[saved.name].toString()
|
|
2564
|
+
: undefined;
|
|
1974
2565
|
if (!target) {
|
|
1975
2566
|
withState(context, (state) => {
|
|
1976
2567
|
failedPin(state, saved.reference, new Error("Shared Name is missing; keeping its last verified version."), true);
|
|
@@ -2260,7 +2851,7 @@ export async function removeSwarmTemplate(context, configUrl, selector, expect)
|
|
|
2260
2851
|
let basis;
|
|
2261
2852
|
for (let attempt = 0; attempt < 8; attempt++) {
|
|
2262
2853
|
const currentHead = await head.read();
|
|
2263
|
-
const current = await readSnapshot(context.store, currentHead.root);
|
|
2854
|
+
const current = await readSnapshot(context.store, currentHead.root, configUrl);
|
|
2264
2855
|
const meta = await swarmMeta(context, { snapshot: current });
|
|
2265
2856
|
const name = formalName(`${meta.templatePath}/${selector}`);
|
|
2266
2857
|
if (basis !== undefined && basis !== name)
|
|
@@ -2336,7 +2927,7 @@ export async function swarmAssociation(context, configUrl, schemaCid, mode = "ac
|
|
|
2336
2927
|
return association;
|
|
2337
2928
|
}
|
|
2338
2929
|
async function prepareNamesPublication(context, configUrl, previousRoot, current, names, roots, retainedRoots) {
|
|
2339
|
-
const next = await publication(context.store, await writeSnapshot(context.store, { ...current, names }), previousRoot);
|
|
2930
|
+
const next = await publication(context.store, await writeSnapshot(context.store, { ...current, names }, configUrl), previousRoot);
|
|
2340
2931
|
const closure = await publicationClosure(context.store, next, false);
|
|
2341
2932
|
await provideContent(context.store, [...new Set([...closure.provided, ...roots])], context.node.api, context.fetch, context.node.auth, [...new Set([next, ...closure.nameTargets, ...(retainedRoots ?? roots)])]);
|
|
2342
2933
|
withState(context, (state) => {
|
|
@@ -2358,7 +2949,7 @@ async function editSwarmAssociation(context, configUrl, schemaCid, association,
|
|
|
2358
2949
|
: new Set();
|
|
2359
2950
|
for (let attempt = 0; attempt < 8; attempt++) {
|
|
2360
2951
|
const currentHead = await head.read();
|
|
2361
|
-
const current = await readSnapshot(context.store, currentHead.root);
|
|
2952
|
+
const current = await readSnapshot(context.store, currentHead.root, configUrl);
|
|
2362
2953
|
assertNamesRegistry(current);
|
|
2363
2954
|
const meta = await swarmMeta(context, { snapshot: current });
|
|
2364
2955
|
const name = formalName(`${meta.registryPath}/${schemaCid}`);
|
|
@@ -2502,7 +3093,7 @@ async function publishContent(context, content, options, nameForSnapshot) {
|
|
|
2502
3093
|
for (const root of await dependencies(context.store, expected))
|
|
2503
3094
|
roots.add(root);
|
|
2504
3095
|
for (let attempt = 0; attempt < 8; attempt++) {
|
|
2505
|
-
const currentHead = await head.read(), current = await readSnapshot(context.store, currentHead.root);
|
|
3096
|
+
const currentHead = await head.read(), current = await readSnapshot(context.store, currentHead.root, options.swarm);
|
|
2506
3097
|
if (nameForSnapshot) {
|
|
2507
3098
|
name = await nameForSnapshot(current);
|
|
2508
3099
|
if (resolvedName !== undefined && resolvedName !== name)
|