@ipab/cli 0.1.0-rc.7 → 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 +24 -1
- 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/cli.d.ts.map +1 -1
- package/dist/cli.js +290 -152
- 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/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/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 +2 -2
- 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 +119 -6
- package/dist/swarm.d.ts.map +1 -1
- package/dist/swarm.js +662 -80
- 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/cli.ts +370 -190
- package/src/config.ts +12 -4
- package/src/context.ts +15 -2
- 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/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 +2 -1
- package/src/swarm-meta.ts +15 -34
- package/src/swarm-observations.ts +374 -0
- package/src/swarm.ts +942 -91
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,201 @@ 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 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
|
+
}
|
|
601
1109
|
async function activate(context, record) {
|
|
602
1110
|
const { node, peers, source } = await privateSource(context, record);
|
|
603
1111
|
if (context.node?.api !== node.api ||
|
|
@@ -762,19 +1270,30 @@ export async function jsonBundle(store, type, value) {
|
|
|
762
1270
|
await encoded.close();
|
|
763
1271
|
}
|
|
764
1272
|
}
|
|
765
|
-
async function writeStateBundle(store, configuration, targets) {
|
|
1273
|
+
async function writeStateBundle(store, configuration, targets, configUrl) {
|
|
766
1274
|
const meta = parseSwarmMeta(configuration);
|
|
767
1275
|
const names = Object.fromEntries(Object.entries(targets).map(([name, cid]) => [
|
|
768
1276
|
formalName(name),
|
|
769
1277
|
cid.toString(),
|
|
770
1278
|
]));
|
|
771
|
-
|
|
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);
|
|
772
1290
|
}
|
|
773
|
-
export async function writeSnapshot(store, snapshot) {
|
|
1291
|
+
export async function writeSnapshot(store, snapshot, configUrl) {
|
|
774
1292
|
if (snapshot.stateBundle) {
|
|
775
1293
|
if (Object.keys(snapshot.registrations ?? {}).length)
|
|
776
1294
|
throw new HostError("State Bundles cannot contain legacy registrations.");
|
|
777
|
-
|
|
1295
|
+
checkStateOrigin(snapshot, configUrl);
|
|
1296
|
+
return writeStateBundle(store, snapshot.stateBundle.meta, snapshot.names, snapshot.stateBundle.configUrl);
|
|
778
1297
|
}
|
|
779
1298
|
const put = async (value) => {
|
|
780
1299
|
const encoded = dagCbor.encode(value);
|
|
@@ -796,18 +1315,14 @@ async function readState(store, cid) {
|
|
|
796
1315
|
});
|
|
797
1316
|
const type = bundle.schemaKey === legacySwarmStateSchema.cid.toString()
|
|
798
1317
|
? 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.");
|
|
1318
|
+
: bundle.schemaKey === previousSwarmStateSchema.cid.toString()
|
|
1319
|
+
? previousSwarmStateType
|
|
1320
|
+
: swarmStateType;
|
|
1321
|
+
const value = parseSwarmState(await typedJson(store, cid.toString(), type));
|
|
807
1322
|
const meta = parseSwarmMeta({
|
|
808
1323
|
templatePath: value.templatePath,
|
|
809
1324
|
registryPath: value.registryPath,
|
|
810
|
-
...(
|
|
1325
|
+
...(value.skillPath === undefined ? {} : { skillPath: value.skillPath }),
|
|
811
1326
|
});
|
|
812
1327
|
const names = Object.fromEntries(Object.entries(object(value.names, "Names")).map(([name, target]) => {
|
|
813
1328
|
formalName(name);
|
|
@@ -815,7 +1330,17 @@ async function readState(store, cid) {
|
|
|
815
1330
|
throw new HostError("State Names require exact canonical CIDs.");
|
|
816
1331
|
return [name, CID.parse(target)];
|
|
817
1332
|
}));
|
|
818
|
-
return {
|
|
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
|
+
};
|
|
819
1344
|
}
|
|
820
1345
|
const data = await store.block.get(cid.toString());
|
|
821
1346
|
const root = object(dagCbor.decode(data), "State");
|
|
@@ -880,14 +1405,24 @@ function decodeSnapshot(data) {
|
|
|
880
1405
|
...(value.registrations !== undefined ? { registrations } : {}),
|
|
881
1406
|
};
|
|
882
1407
|
}
|
|
883
|
-
export async function readSnapshot(store, root) {
|
|
1408
|
+
export async function readSnapshot(store, root, configUrl) {
|
|
884
1409
|
const publication = await readPublication(store, root);
|
|
885
|
-
|
|
1410
|
+
const snapshot = await readState(store, publication.state);
|
|
1411
|
+
checkStateOrigin(snapshot, configUrl);
|
|
1412
|
+
return snapshot;
|
|
886
1413
|
}
|
|
887
|
-
|
|
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.");
|
|
1419
|
+
}
|
|
1420
|
+
async function readHeaderSnapshot(store, root, configUrl) {
|
|
888
1421
|
const publication = await readPublication(store, root);
|
|
1422
|
+
const snapshot = await readState(store, publication.state);
|
|
1423
|
+
checkStateOrigin(snapshot, configUrl);
|
|
889
1424
|
return {
|
|
890
|
-
snapshot
|
|
1425
|
+
snapshot,
|
|
891
1426
|
stateCid: publication.state.toString(),
|
|
892
1427
|
};
|
|
893
1428
|
}
|
|
@@ -928,7 +1463,7 @@ export async function sharedSwarmStatus(context, configUrl) {
|
|
|
928
1463
|
const head = headValue(await client(context, c.service).read(c.scopeId, config.headId));
|
|
929
1464
|
let content;
|
|
930
1465
|
try {
|
|
931
|
-
content = await readHeaderSnapshot(context.store, head.root);
|
|
1466
|
+
content = await readHeaderSnapshot(context.store, head.root, configUrl);
|
|
932
1467
|
}
|
|
933
1468
|
catch (cause) {
|
|
934
1469
|
if (!missingContent(cause))
|
|
@@ -995,14 +1530,14 @@ async function readSwarmHeader(context, configUrl, force = context.forceRefresh
|
|
|
995
1530
|
: await (await boundPointer(context, configUrl, record)).read();
|
|
996
1531
|
let content;
|
|
997
1532
|
try {
|
|
998
|
-
content = await readHeaderSnapshot(context.store, head.root);
|
|
1533
|
+
content = await readHeaderSnapshot(context.store, head.root, configUrl);
|
|
999
1534
|
}
|
|
1000
1535
|
catch (cause) {
|
|
1001
1536
|
if (mode === "local-first")
|
|
1002
1537
|
throw cause;
|
|
1003
1538
|
record = await refresh(context, configUrl);
|
|
1004
1539
|
head = await (await boundPointer(context, configUrl, record)).read();
|
|
1005
|
-
content = await readHeaderSnapshot(context.store, head.root);
|
|
1540
|
+
content = await readHeaderSnapshot(context.store, head.root, configUrl);
|
|
1006
1541
|
}
|
|
1007
1542
|
const current = await local(context, configUrl), verifiedAt = Date.now();
|
|
1008
1543
|
withState(context, (state) => {
|
|
@@ -1042,12 +1577,26 @@ async function cachedHeader(context, record) {
|
|
|
1042
1577
|
const snapshot = decodeSnapshot(dagCbor.encode(legacySnapshot));
|
|
1043
1578
|
if (stateBundle !== undefined) {
|
|
1044
1579
|
const data = object(stateBundle, "cached State Bundle");
|
|
1045
|
-
if (Object.keys(data).sort().join()
|
|
1580
|
+
if (!["cid,meta", "cid,configUrl,meta"].includes(Object.keys(data).sort().join()) ||
|
|
1046
1581
|
typeof data.cid !== "string" ||
|
|
1047
1582
|
exactCid(data.cid) !== data.cid ||
|
|
1048
1583
|
(cached.stateCid !== undefined && data.cid !== cached.stateCid))
|
|
1049
1584
|
throw new HostError("Invalid cached State Bundle.");
|
|
1050
|
-
|
|
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);
|
|
1051
1600
|
}
|
|
1052
1601
|
let stateCid = cached.stateCid;
|
|
1053
1602
|
if (!stateCid) {
|
|
@@ -1145,7 +1694,7 @@ async function lazyPrivateSource(context, url, account, basis) {
|
|
|
1145
1694
|
record.config.owner !== basis.owner ||
|
|
1146
1695
|
record.config.epoch !== basis.epoch ||
|
|
1147
1696
|
record.config.headId !== basis.headId)
|
|
1148
|
-
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.");
|
|
1149
1698
|
return (await privateSource(scoped, record, signal)).source;
|
|
1150
1699
|
};
|
|
1151
1700
|
// Same lock order as Owner rotation: credentials first, then the node.
|
|
@@ -1173,11 +1722,6 @@ async function lazyPrivateSource(context, url, account, basis) {
|
|
|
1173
1722
|
await pending?.catch(() => { });
|
|
1174
1723
|
};
|
|
1175
1724
|
}
|
|
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
1725
|
export async function createSwarm(context, options = {}) {
|
|
1182
1726
|
if ((options.properties?.name.length ?? 0) > 256 ||
|
|
1183
1727
|
(options.properties?.description.length ?? 0) > 2048 ||
|
|
@@ -1205,6 +1749,7 @@ export async function createSwarm(context, options = {}) {
|
|
|
1205
1749
|
if (options.resume)
|
|
1206
1750
|
throw new HostError("Unknown creation operation.");
|
|
1207
1751
|
record = {
|
|
1752
|
+
stateVersion: 6,
|
|
1208
1753
|
owner: identity.publicKey,
|
|
1209
1754
|
service,
|
|
1210
1755
|
encryption: encryptionIdentity(),
|
|
@@ -1221,6 +1766,24 @@ export async function createSwarm(context, options = {}) {
|
|
|
1221
1766
|
const save = () => writePrivate(dir, `creation-${op}.json`, record);
|
|
1222
1767
|
const api = client(context, service, identity);
|
|
1223
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
|
+
}
|
|
1224
1787
|
if (!record.seed) {
|
|
1225
1788
|
if (record.headId)
|
|
1226
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.");
|
|
@@ -1229,17 +1792,19 @@ export async function createSwarm(context, options = {}) {
|
|
|
1229
1792
|
const template = await seedTemplateSource(selector);
|
|
1230
1793
|
for (const [cid, data] of template.blocks)
|
|
1231
1794
|
await context.store.put(CID.parse(cid), data);
|
|
1232
|
-
names[`ipab/
|
|
1795
|
+
names[`ipab/templates/${selector}`] = CID.parse(template.cid);
|
|
1233
1796
|
}
|
|
1234
1797
|
const skill = await seedSkillSource();
|
|
1235
1798
|
for (const [cid, data] of skill.blocks)
|
|
1236
1799
|
await context.store.put(CID.parse(cid), data);
|
|
1237
1800
|
names["ipab/skills/ipab"] = CID.parse(skill.cid);
|
|
1238
1801
|
const root = await publication(context.store, await writeStateBundle(context.store, {
|
|
1239
|
-
templatePath: "ipab/
|
|
1802
|
+
templatePath: "ipab/templates",
|
|
1240
1803
|
registryPath: "ipab/registry",
|
|
1241
1804
|
skillPath: "ipab/skills",
|
|
1242
|
-
}, names
|
|
1805
|
+
}, names, record.stateVersion === 6
|
|
1806
|
+
? `${service}/v1/${record.scopeId}/${record.configId}`
|
|
1807
|
+
: undefined));
|
|
1243
1808
|
const roots = await frozenPublicationClosure(context.store, root);
|
|
1244
1809
|
record.seed = {
|
|
1245
1810
|
root,
|
|
@@ -1263,12 +1828,13 @@ export async function createSwarm(context, options = {}) {
|
|
|
1263
1828
|
}
|
|
1264
1829
|
if (!record.profileId) {
|
|
1265
1830
|
if (!record.profile) {
|
|
1266
|
-
const addresses = options.addresses ??
|
|
1831
|
+
const addresses = options.addresses ?? [];
|
|
1267
1832
|
for (const address of addresses)
|
|
1268
1833
|
validateAddress(address, node.peerId);
|
|
1269
1834
|
record.profile = {
|
|
1270
1835
|
...(record.personal ?? { name: record.name }),
|
|
1271
1836
|
addresses,
|
|
1837
|
+
pivot: context.pivot ?? false,
|
|
1272
1838
|
updatedAt: record.createdAt,
|
|
1273
1839
|
};
|
|
1274
1840
|
await save();
|
|
@@ -1293,7 +1859,7 @@ export async function createSwarm(context, options = {}) {
|
|
|
1293
1859
|
description: record.description,
|
|
1294
1860
|
headId: record.headId,
|
|
1295
1861
|
epoch: 1,
|
|
1296
|
-
bootstrap:
|
|
1862
|
+
bootstrap: [],
|
|
1297
1863
|
members: [member],
|
|
1298
1864
|
};
|
|
1299
1865
|
await save();
|
|
@@ -1302,6 +1868,19 @@ export async function createSwarm(context, options = {}) {
|
|
|
1302
1868
|
record.configId = (await api.create(record.scopeId, configValue(record.config), `${op}.config`)).id;
|
|
1303
1869
|
await save();
|
|
1304
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
|
+
}
|
|
1305
1884
|
const configUrl = `${service}/v1/${record.scopeId}/${record.configId}`;
|
|
1306
1885
|
const cert = await issueScopeCertificate({
|
|
1307
1886
|
v: 1,
|
|
@@ -1354,10 +1933,6 @@ export async function requestMembership(context, url, options) {
|
|
|
1354
1933
|
const personal = await ensureAccountProfile(context);
|
|
1355
1934
|
const dir = await directory(context);
|
|
1356
1935
|
await withPrivateLock(dir, async () => {
|
|
1357
|
-
if (options.alias !== undefined)
|
|
1358
|
-
withState(context, (state) => {
|
|
1359
|
-
state.checkSwarmAlias(options.alias, url);
|
|
1360
|
-
});
|
|
1361
1936
|
const existing = await readPrivate(dir, localName(url));
|
|
1362
1937
|
if (existing) {
|
|
1363
1938
|
if (existing.account !== identity.publicKey ||
|
|
@@ -1365,7 +1940,6 @@ export async function requestMembership(context, url, options) {
|
|
|
1365
1940
|
throw new HostError("Existing Request belongs to a different identity or pinned Owner.");
|
|
1366
1941
|
if (!existing.request)
|
|
1367
1942
|
throw new HostError("This identity is already the Owner.");
|
|
1368
|
-
withState(context, (state) => state.registerSwarm(url, options.alias));
|
|
1369
1943
|
return;
|
|
1370
1944
|
}
|
|
1371
1945
|
const node = await prepareNode(context.stateDir, nodeScope(coordinates(url).service, config.scopeId), context.listen), encryption = encryptionIdentity();
|
|
@@ -1397,7 +1971,6 @@ export async function requestMembership(context, url, options) {
|
|
|
1397
1971
|
encryption,
|
|
1398
1972
|
request,
|
|
1399
1973
|
});
|
|
1400
|
-
withState(context, (state) => state.registerSwarm(url, options.alias));
|
|
1401
1974
|
});
|
|
1402
1975
|
const file = options.output === undefined ? undefined : resolve(options.output);
|
|
1403
1976
|
if (file !== undefined)
|
|
@@ -1643,6 +2216,11 @@ export async function updateProfile(context, url, changes) {
|
|
|
1643
2216
|
updatedAt: new Date().toISOString(),
|
|
1644
2217
|
};
|
|
1645
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.");
|
|
1646
2224
|
return profile;
|
|
1647
2225
|
}
|
|
1648
2226
|
export async function removeMember(context, url, member) {
|
|
@@ -1691,6 +2269,7 @@ export async function resumeRemoval(context, url) {
|
|
|
1691
2269
|
membershipBeforeSwitch.config = record.oldConfig;
|
|
1692
2270
|
membershipBeforeSwitch.secret.swarmKey = record.oldKey;
|
|
1693
2271
|
await activate(context, membershipBeforeSwitch);
|
|
2272
|
+
await readSnapshot(context.store, headValue(record.finalHead).root, url);
|
|
1694
2273
|
if (!record.finalClosureRoots) {
|
|
1695
2274
|
record.finalClosureRoots = await frozenPublicationClosure(context.store, headValue(record.finalHead).root);
|
|
1696
2275
|
await save();
|
|
@@ -1844,7 +2423,7 @@ export function parseNameReference(reference) {
|
|
|
1844
2423
|
try {
|
|
1845
2424
|
return {
|
|
1846
2425
|
...(authority ? { swarm: authority } : {}),
|
|
1847
|
-
name: formalName(segments.join("/")),
|
|
2426
|
+
name: match[2] === "" ? "" : formalName(segments.join("/")),
|
|
1848
2427
|
};
|
|
1849
2428
|
}
|
|
1850
2429
|
catch (error) {
|
|
@@ -1868,20 +2447,21 @@ export async function resolveReference(context, reference, swarm, local, raw = f
|
|
|
1868
2447
|
throw new HostError("Select a configuration URL/alias using --swarm or swarm use.");
|
|
1869
2448
|
const warm = mode === "local-first" ? await localHeader(context, selected) : undefined;
|
|
1870
2449
|
let header = warm?.header ?? (await swarmHeader(context, selected));
|
|
1871
|
-
|
|
1872
|
-
? header.
|
|
1873
|
-
:
|
|
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();
|
|
1874
2456
|
if (!link && header.source === "cache") {
|
|
1875
2457
|
header = await swarmHeader(context, selected, true);
|
|
1876
|
-
link =
|
|
1877
|
-
? header.snapshot.names[shared.name]
|
|
1878
|
-
: undefined;
|
|
2458
|
+
link = target();
|
|
1879
2459
|
}
|
|
1880
2460
|
if (!link)
|
|
1881
2461
|
throw new HostError(`Formal Name "${shared.name}" was not found after refreshing HEAD.`);
|
|
1882
2462
|
if (warm && header === warm.header && !header.localSourceReady)
|
|
1883
2463
|
await lazyPrivateSource(context, selected, warm.account, header.config);
|
|
1884
|
-
targetCid = link
|
|
2464
|
+
targetCid = link;
|
|
1885
2465
|
}
|
|
1886
2466
|
else {
|
|
1887
2467
|
if (swarm)
|
|
@@ -1925,7 +2505,7 @@ export function pinReference(state, reference, selected) {
|
|
|
1925
2505
|
}
|
|
1926
2506
|
export async function pinNameSubscription(context, reference, selected) {
|
|
1927
2507
|
const canonical = withState(context, (state) => pinReference(state, reference, selected));
|
|
1928
|
-
if (!canonical.swarm ||
|
|
2508
|
+
if (!canonical.swarm || canonical.name === undefined) {
|
|
1929
2509
|
let roots;
|
|
1930
2510
|
try {
|
|
1931
2511
|
roots = [
|
|
@@ -1968,9 +2548,11 @@ export async function refreshNamePins(context, url, header) {
|
|
|
1968
2548
|
.filter((pin) => pin.swarm === url && pin.status !== "deleting"));
|
|
1969
2549
|
const failures = [];
|
|
1970
2550
|
for (const saved of pins) {
|
|
1971
|
-
const target =
|
|
1972
|
-
? header.
|
|
1973
|
-
:
|
|
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;
|
|
1974
2556
|
if (!target) {
|
|
1975
2557
|
withState(context, (state) => {
|
|
1976
2558
|
failedPin(state, saved.reference, new Error("Shared Name is missing; keeping its last verified version."), true);
|
|
@@ -2260,7 +2842,7 @@ export async function removeSwarmTemplate(context, configUrl, selector, expect)
|
|
|
2260
2842
|
let basis;
|
|
2261
2843
|
for (let attempt = 0; attempt < 8; attempt++) {
|
|
2262
2844
|
const currentHead = await head.read();
|
|
2263
|
-
const current = await readSnapshot(context.store, currentHead.root);
|
|
2845
|
+
const current = await readSnapshot(context.store, currentHead.root, configUrl);
|
|
2264
2846
|
const meta = await swarmMeta(context, { snapshot: current });
|
|
2265
2847
|
const name = formalName(`${meta.templatePath}/${selector}`);
|
|
2266
2848
|
if (basis !== undefined && basis !== name)
|
|
@@ -2336,7 +2918,7 @@ export async function swarmAssociation(context, configUrl, schemaCid, mode = "ac
|
|
|
2336
2918
|
return association;
|
|
2337
2919
|
}
|
|
2338
2920
|
async function prepareNamesPublication(context, configUrl, previousRoot, current, names, roots, retainedRoots) {
|
|
2339
|
-
const next = await publication(context.store, await writeSnapshot(context.store, { ...current, names }), previousRoot);
|
|
2921
|
+
const next = await publication(context.store, await writeSnapshot(context.store, { ...current, names }, configUrl), previousRoot);
|
|
2340
2922
|
const closure = await publicationClosure(context.store, next, false);
|
|
2341
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)])]);
|
|
2342
2924
|
withState(context, (state) => {
|
|
@@ -2358,7 +2940,7 @@ async function editSwarmAssociation(context, configUrl, schemaCid, association,
|
|
|
2358
2940
|
: new Set();
|
|
2359
2941
|
for (let attempt = 0; attempt < 8; attempt++) {
|
|
2360
2942
|
const currentHead = await head.read();
|
|
2361
|
-
const current = await readSnapshot(context.store, currentHead.root);
|
|
2943
|
+
const current = await readSnapshot(context.store, currentHead.root, configUrl);
|
|
2362
2944
|
assertNamesRegistry(current);
|
|
2363
2945
|
const meta = await swarmMeta(context, { snapshot: current });
|
|
2364
2946
|
const name = formalName(`${meta.registryPath}/${schemaCid}`);
|
|
@@ -2502,7 +3084,7 @@ async function publishContent(context, content, options, nameForSnapshot) {
|
|
|
2502
3084
|
for (const root of await dependencies(context.store, expected))
|
|
2503
3085
|
roots.add(root);
|
|
2504
3086
|
for (let attempt = 0; attempt < 8; attempt++) {
|
|
2505
|
-
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);
|
|
2506
3088
|
if (nameForSnapshot) {
|
|
2507
3089
|
name = await nameForSnapshot(current);
|
|
2508
3090
|
if (resolvedName !== undefined && resolvedName !== name)
|