@ipab/cli 0.1.0-rc.5 → 0.1.0-rc.6
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 +82 -15
- package/dist/app-templates.js +1 -1
- package/dist/app-templates.js.map +1 -1
- package/dist/builtins/skill.ipab.car +0 -0
- package/dist/builtins/template.node.car +0 -0
- package/dist/builtins/template.web-app.car +0 -0
- package/dist/cli.d.ts +3 -1
- package/dist/cli.d.ts.map +1 -1
- package/dist/cli.js +561 -272
- package/dist/cli.js.map +1 -1
- package/dist/content-provider.d.ts +1 -1
- package/dist/content-provider.d.ts.map +1 -1
- package/dist/content-provider.js +4 -3
- package/dist/content-provider.js.map +1 -1
- package/dist/context.d.ts +0 -1
- package/dist/context.d.ts.map +1 -1
- package/dist/context.js +0 -10
- package/dist/context.js.map +1 -1
- package/dist/doctor.d.ts +29 -0
- package/dist/doctor.d.ts.map +1 -0
- package/dist/doctor.js +576 -0
- package/dist/doctor.js.map +1 -0
- package/dist/identity.d.ts +1 -1
- package/dist/identity.d.ts.map +1 -1
- package/dist/identity.js +9 -9
- package/dist/identity.js.map +1 -1
- package/dist/ipc.d.ts +1 -2
- package/dist/ipc.d.ts.map +1 -1
- package/dist/ipc.js +1 -10
- package/dist/ipc.js.map +1 -1
- package/dist/kubo-install.d.ts +18 -1
- package/dist/kubo-install.d.ts.map +1 -1
- package/dist/kubo-install.js +424 -61
- package/dist/kubo-install.js.map +1 -1
- package/dist/kubo-release.d.ts +19 -0
- package/dist/kubo-release.d.ts.map +1 -1
- package/dist/kubo-release.js +164 -0
- package/dist/kubo-release.js.map +1 -1
- package/dist/kubo.d.ts +1 -0
- package/dist/kubo.d.ts.map +1 -1
- package/dist/kubo.js +102 -96
- package/dist/kubo.js.map +1 -1
- package/dist/pins.d.ts +15 -17
- package/dist/pins.d.ts.map +1 -1
- package/dist/pins.js +144 -106
- package/dist/pins.js.map +1 -1
- package/dist/publish-source.d.ts +3 -0
- package/dist/publish-source.d.ts.map +1 -0
- package/dist/publish-source.js +85 -0
- package/dist/publish-source.js.map +1 -0
- package/dist/runtime.d.ts.map +1 -1
- package/dist/runtime.js +1 -3
- package/dist/runtime.js.map +1 -1
- package/dist/state-storage-windows.js +1 -1
- package/dist/state-storage.d.ts +3 -1
- package/dist/state-storage.d.ts.map +1 -1
- package/dist/state-storage.js +38 -7
- package/dist/state-storage.js.map +1 -1
- package/dist/state.d.ts +40 -6
- package/dist/state.d.ts.map +1 -1
- package/dist/state.js +208 -82
- package/dist/state.js.map +1 -1
- package/dist/swarm-envelope.d.ts +1 -0
- package/dist/swarm-envelope.d.ts.map +1 -1
- package/dist/swarm-envelope.js +12 -0
- package/dist/swarm-envelope.js.map +1 -1
- package/dist/swarm.d.ts +64 -8
- package/dist/swarm.d.ts.map +1 -1
- package/dist/swarm.js +858 -106
- package/dist/swarm.js.map +1 -1
- package/package.json +4 -4
- package/src/app-templates.ts +1 -1
- package/src/cli.ts +702 -338
- package/src/content-provider.ts +4 -2
- package/src/context.ts +0 -10
- package/src/doctor.ts +902 -0
- package/src/identity.ts +10 -10
- package/src/ipc.ts +0 -8
- package/src/kubo-install.ts +562 -78
- package/src/kubo-release.ts +213 -0
- package/src/kubo.ts +134 -106
- package/src/pins.ts +188 -126
- package/src/publish-source.ts +103 -0
- package/src/runtime.ts +0 -3
- package/src/state-storage-windows.ts +1 -1
- package/src/state-storage.ts +53 -7
- package/src/state.ts +357 -98
- package/src/swarm-envelope.ts +14 -0
- package/src/swarm.ts +1234 -125
- package/dist/setup.d.ts +0 -8
- package/dist/setup.d.ts.map +0 -1
- package/dist/setup.js +0 -27
- package/dist/setup.js.map +0 -1
- package/src/setup.ts +0 -34
package/dist/swarm.js
CHANGED
|
@@ -1,31 +1,82 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { createReadStream } from "node:fs";
|
|
2
|
+
import { lstat, mkdir, open } from "node:fs/promises";
|
|
3
|
+
import { homedir } from "node:os";
|
|
4
|
+
import { join, resolve } from "node:path";
|
|
2
5
|
import { createHash, randomBytes } from "node:crypto";
|
|
3
6
|
import { stringify } from "yaml";
|
|
4
7
|
import { CarBlockIterator } from "@ipld/car/iterator";
|
|
5
8
|
import * as dagCbor from "@ipld/dag-cbor";
|
|
6
9
|
import { CID } from "multiformats/cid";
|
|
7
10
|
import { sha256 } from "multiformats/hashes/sha2";
|
|
8
|
-
import { encodeSchema, openBundle } from "@ipab/bundle";
|
|
11
|
+
import { ContentBundleError, encodeSchema, openBundle, } from "@ipab/bundle";
|
|
9
12
|
import { encodeBundleCar, memoryTree, streamChunks, } from "@ipab/bundle-builder";
|
|
10
13
|
import { ContentError } from "@ipab/ipfs-store";
|
|
11
14
|
import { ScopeClient, ScopeApiError, RESOURCE_ID_PATTERN, issueScopeCertificate, uniqueId, verifyScopeCertificate, valueCid, } from "@ipab/bundle/pointer/scope";
|
|
12
15
|
import { canonicalService, isCanonicalPublicKey, POINTER_ID_PATTERN, } from "@ipab/bundle/pointer/protocol";
|
|
13
16
|
import { importPrivateKeyPkcs8, importPublicKeyRaw, keyId, signEd25519, verifyEd25519, } from "@ipab/bundle/pointer/crypto";
|
|
14
17
|
import { HostError, object, message } from "./errors.js";
|
|
15
|
-
import { accountIdentity } from "./identity.js";
|
|
18
|
+
import { accountIdentity, protectedPath, secureNew, } from "./identity.js";
|
|
19
|
+
import { nodeError } from "./authoring.js";
|
|
16
20
|
import { swarmUrl as canonicalSwarmUrl } from "./config.js";
|
|
17
21
|
import { bundleJson, provideContent } from "./content-provider.js";
|
|
22
|
+
import { failedPin, pinCid, refreshPinClaim, reservePin, retainPin, } from "./pins.js";
|
|
18
23
|
import { bytes, relativePath } from "./space.js";
|
|
19
24
|
import { appSchemaCid } from "./app-definition.js";
|
|
20
|
-
import { State } from "./state.js";
|
|
25
|
+
import { State, createAssociation, exactCid, } from "./state.js";
|
|
21
26
|
import { privateDirectory, readPrivate, withPrivateLock, writePrivate, } from "./swarm-files.js";
|
|
22
|
-
import { encryptionIdentity, openApproval, sealApproval, parseEnvelope, } from "./swarm-envelope.js";
|
|
27
|
+
import { encryptionIdentity, openApproval, sealApproval, parseEnvelope, validateEncryptionIdentity, } from "./swarm-envelope.js";
|
|
23
28
|
import { checkCachedNode, kuboSource, peerId, peerProof, prepareNode, startNode, validateAddress, } from "./kubo.js";
|
|
24
29
|
import { memberPeers } from "./kubo-peering.js";
|
|
25
30
|
async function contextIdentity(context, initialize = false) {
|
|
26
31
|
context.identity ??= await accountIdentity(context.env, initialize);
|
|
27
32
|
return context.identity;
|
|
28
33
|
}
|
|
34
|
+
export async function inspectLocalMembership(input, account) {
|
|
35
|
+
const value = object(input, "local membership");
|
|
36
|
+
if (typeof value.configUrl !== "string" ||
|
|
37
|
+
!isCanonicalPublicKey(value.owner) ||
|
|
38
|
+
!isCanonicalPublicKey(value.account) ||
|
|
39
|
+
value.account !== account)
|
|
40
|
+
throw new HostError("Stored membership is inconsistent with HOME identity.");
|
|
41
|
+
const configUrl = canonicalSwarmUrl(value.configUrl);
|
|
42
|
+
if (configUrl !== value.configUrl)
|
|
43
|
+
throw new HostError("Noncanonical membership URL.");
|
|
44
|
+
const encryption = object(value.encryption, "encryption identity");
|
|
45
|
+
if (typeof encryption.privateKey !== "string" ||
|
|
46
|
+
typeof encryption.publicKey !== "string")
|
|
47
|
+
throw new HostError("Invalid encryption identity.");
|
|
48
|
+
validateEncryptionIdentity({
|
|
49
|
+
privateKey: encryption.privateKey,
|
|
50
|
+
publicKey: encryption.publicKey,
|
|
51
|
+
});
|
|
52
|
+
const request = value.request === undefined
|
|
53
|
+
? undefined
|
|
54
|
+
: await verifyRequest(value.request);
|
|
55
|
+
if (request &&
|
|
56
|
+
(request.configUrl !== configUrl ||
|
|
57
|
+
request.member !== account ||
|
|
58
|
+
request.owner !== value.owner ||
|
|
59
|
+
request.encryptionKey !== encryption.publicKey))
|
|
60
|
+
throw new HostError("Stored Request binding mismatch.");
|
|
61
|
+
const config = value.config === undefined
|
|
62
|
+
? undefined
|
|
63
|
+
: parseOrganization(value.config, configUrl);
|
|
64
|
+
if (config && config.owner !== value.owner)
|
|
65
|
+
throw new HostError("Stored Owner binding mismatch.");
|
|
66
|
+
let peer = request?.peerId;
|
|
67
|
+
if (value.secret !== undefined) {
|
|
68
|
+
if (!config)
|
|
69
|
+
throw new HostError("Stored secret has no configuration binding.");
|
|
70
|
+
const member = config.members.find((member) => member.publicKey === account);
|
|
71
|
+
if (!member)
|
|
72
|
+
throw new HostError("Stored membership lacks its member binding.");
|
|
73
|
+
const record = value;
|
|
74
|
+
await validateMembershipSecret(record, config, member);
|
|
75
|
+
peer = member.peerId;
|
|
76
|
+
}
|
|
77
|
+
const c = coordinates(configUrl);
|
|
78
|
+
return { configUrl, scope: nodeScope(c.service, c.scopeId), peer };
|
|
79
|
+
}
|
|
29
80
|
const cidField = { type: "string", minLength: 1, maxLength: 128 };
|
|
30
81
|
export const artifactType = {
|
|
31
82
|
contentType: "application/json",
|
|
@@ -94,7 +145,7 @@ function parseOrganization(value, configUrl) {
|
|
|
94
145
|
const { scopeId } = coordinates(configUrl);
|
|
95
146
|
if (Object.keys(data).sort().join() !==
|
|
96
147
|
"bootstrap,description,epoch,headId,members,name,owner,scopeId,v" ||
|
|
97
|
-
data.v !== 1 ||
|
|
148
|
+
(data.v !== 1 && data.v !== 2) ||
|
|
98
149
|
data.scopeId !== scopeId ||
|
|
99
150
|
!isCanonicalPublicKey(data.owner) ||
|
|
100
151
|
typeof data.name !== "string" ||
|
|
@@ -110,14 +161,20 @@ function parseOrganization(value, configUrl) {
|
|
|
110
161
|
data.bootstrap.length > 64 ||
|
|
111
162
|
!Array.isArray(data.members) ||
|
|
112
163
|
data.members.length < 1 ||
|
|
113
|
-
data.members.length >
|
|
164
|
+
data.members.length > 256)
|
|
114
165
|
throw new HostError("Invalid Scope organization configuration.");
|
|
115
166
|
const identities = new Set(), peers = new Set(), profiles = new Set();
|
|
116
167
|
const members = [];
|
|
117
168
|
for (const raw of data.members) {
|
|
118
169
|
const member = object(raw, "member");
|
|
119
|
-
if (Object.keys(member)
|
|
170
|
+
if (Object.keys(member)
|
|
171
|
+
.filter((key) => key !== "memberId")
|
|
172
|
+
.sort()
|
|
173
|
+
.join() !==
|
|
120
174
|
"approval,encryptionKey,peerId,profileId,publicKey,requestId" ||
|
|
175
|
+
(member.memberId !== undefined &&
|
|
176
|
+
(typeof member.memberId !== "string" ||
|
|
177
|
+
!RESOURCE_ID_PATTERN.test(member.memberId))) ||
|
|
121
178
|
!isCanonicalPublicKey(member.publicKey) ||
|
|
122
179
|
typeof member.encryptionKey !== "string" ||
|
|
123
180
|
member.encryptionKey.length > 256 ||
|
|
@@ -134,6 +191,9 @@ function parseOrganization(value, configUrl) {
|
|
|
134
191
|
peers.add(member.peerId);
|
|
135
192
|
profiles.add(member.profileId);
|
|
136
193
|
members.push({
|
|
194
|
+
...(typeof member.memberId === "string"
|
|
195
|
+
? { memberId: member.memberId }
|
|
196
|
+
: {}),
|
|
137
197
|
publicKey: member.publicKey,
|
|
138
198
|
encryptionKey: member.encryptionKey,
|
|
139
199
|
peerId: member.peerId,
|
|
@@ -154,7 +214,7 @@ function parseOrganization(value, configUrl) {
|
|
|
154
214
|
bootstrap.push(address);
|
|
155
215
|
}
|
|
156
216
|
return {
|
|
157
|
-
v:
|
|
217
|
+
v: data.v,
|
|
158
218
|
scopeId,
|
|
159
219
|
owner: data.owner,
|
|
160
220
|
name: data.name,
|
|
@@ -167,9 +227,15 @@ function parseOrganization(value, configUrl) {
|
|
|
167
227
|
}
|
|
168
228
|
function parseProfile(value, expectedPeer) {
|
|
169
229
|
const data = object(value, "member profile");
|
|
170
|
-
if (
|
|
230
|
+
if (![
|
|
231
|
+
"addresses,name,updatedAt",
|
|
232
|
+
"addresses,description,name,updatedAt",
|
|
233
|
+
].includes(Object.keys(data).sort().join()) ||
|
|
171
234
|
typeof data.name !== "string" ||
|
|
172
235
|
data.name.length > 256 ||
|
|
236
|
+
(data.description !== undefined &&
|
|
237
|
+
(typeof data.description !== "string" ||
|
|
238
|
+
data.description.length > 2048)) ||
|
|
173
239
|
typeof data.updatedAt !== "string" ||
|
|
174
240
|
!Number.isFinite(Date.parse(data.updatedAt)) ||
|
|
175
241
|
!Array.isArray(data.addresses) ||
|
|
@@ -182,7 +248,191 @@ function parseProfile(value, expectedPeer) {
|
|
|
182
248
|
validateAddress(address, expectedPeer);
|
|
183
249
|
addresses.push(address);
|
|
184
250
|
}
|
|
185
|
-
return {
|
|
251
|
+
return {
|
|
252
|
+
name: data.name,
|
|
253
|
+
...(typeof data.description === "string"
|
|
254
|
+
? { description: data.description }
|
|
255
|
+
: {}),
|
|
256
|
+
addresses,
|
|
257
|
+
updatedAt: data.updatedAt,
|
|
258
|
+
};
|
|
259
|
+
}
|
|
260
|
+
export async function swarmMembers(context, url) {
|
|
261
|
+
const { config } = await fetchConfig(context, canonicalSwarmUrl(url));
|
|
262
|
+
const c = coordinates(url), api = client(context, c.service);
|
|
263
|
+
const members = await boundedMap(config.members, async (member) => {
|
|
264
|
+
const profile = parseProfile((await api.read(c.scopeId, member.profileId)).value, member.peerId);
|
|
265
|
+
return {
|
|
266
|
+
publicKey: member.publicKey,
|
|
267
|
+
role: member.publicKey === config.owner ? "owner" : "member",
|
|
268
|
+
name: profile.name,
|
|
269
|
+
description: profile.description ?? "",
|
|
270
|
+
};
|
|
271
|
+
});
|
|
272
|
+
return { configUrl: url, members };
|
|
273
|
+
}
|
|
274
|
+
function accountProfileLocation(context, publicKey) {
|
|
275
|
+
return {
|
|
276
|
+
parent: join(resolve(context.env.HOME ?? context.env.USERPROFILE ?? homedir()), ".ipab"),
|
|
277
|
+
name: `${createHash("sha256").update(publicKey).digest("hex")}.json`,
|
|
278
|
+
};
|
|
279
|
+
}
|
|
280
|
+
async function storedAccountProfile(context) {
|
|
281
|
+
const identity = await contextIdentity(context);
|
|
282
|
+
const { parent, name } = accountProfileLocation(context, identity.publicKey);
|
|
283
|
+
try {
|
|
284
|
+
await lstat(join(parent, "profiles"));
|
|
285
|
+
}
|
|
286
|
+
catch (cause) {
|
|
287
|
+
if (nodeError(cause, "ENOENT"))
|
|
288
|
+
return undefined;
|
|
289
|
+
throw cause;
|
|
290
|
+
}
|
|
291
|
+
await protectedPath(parent, true);
|
|
292
|
+
await protectedPath(join(parent, "profiles"), true);
|
|
293
|
+
const value = await readPrivate(join(parent, "profiles"), name);
|
|
294
|
+
if (value === undefined)
|
|
295
|
+
return undefined;
|
|
296
|
+
const data = object(value, "account profile");
|
|
297
|
+
if (Object.keys(data).sort().join() !==
|
|
298
|
+
"description,name,publicKey,updatedAt" ||
|
|
299
|
+
data.publicKey !== identity.publicKey ||
|
|
300
|
+
typeof data.name !== "string" ||
|
|
301
|
+
data.name.length > 256 ||
|
|
302
|
+
typeof data.description !== "string" ||
|
|
303
|
+
data.description.length > 2048 ||
|
|
304
|
+
typeof data.updatedAt !== "string" ||
|
|
305
|
+
!Number.isFinite(Date.parse(data.updatedAt)))
|
|
306
|
+
throw new HostError("Invalid protected account profile; restore the existing profile file.");
|
|
307
|
+
return {
|
|
308
|
+
publicKey: identity.publicKey,
|
|
309
|
+
name: data.name,
|
|
310
|
+
description: data.description,
|
|
311
|
+
updatedAt: data.updatedAt,
|
|
312
|
+
};
|
|
313
|
+
}
|
|
314
|
+
async function accountProfileDirectory(context, publicKey) {
|
|
315
|
+
const { parent } = accountProfileLocation(context, publicKey);
|
|
316
|
+
try {
|
|
317
|
+
await lstat(parent);
|
|
318
|
+
}
|
|
319
|
+
catch (cause) {
|
|
320
|
+
if (!nodeError(cause, "ENOENT"))
|
|
321
|
+
throw cause;
|
|
322
|
+
await mkdir(parent, { mode: 0o700 });
|
|
323
|
+
await secureNew(parent, true);
|
|
324
|
+
}
|
|
325
|
+
await protectedPath(parent, true);
|
|
326
|
+
return privateDirectory(parent, "profiles");
|
|
327
|
+
}
|
|
328
|
+
async function initialAccountProfile(context, changes = {}) {
|
|
329
|
+
const identity = await contextIdentity(context);
|
|
330
|
+
if (changes.name !== undefined && changes.description !== undefined)
|
|
331
|
+
return {
|
|
332
|
+
publicKey: identity.publicKey,
|
|
333
|
+
name: changes.name,
|
|
334
|
+
description: changes.description,
|
|
335
|
+
updatedAt: null,
|
|
336
|
+
};
|
|
337
|
+
const legacy = [];
|
|
338
|
+
for (const entry of withState(context, (state) => state.swarms())) {
|
|
339
|
+
const { config } = await fetchConfig(context, entry.cid);
|
|
340
|
+
const self = config.members.find((member) => member.publicKey === identity.publicKey);
|
|
341
|
+
if (!self)
|
|
342
|
+
continue; // Pending requests have no public profile yet.
|
|
343
|
+
const c = coordinates(entry.cid);
|
|
344
|
+
legacy.push(parseProfile((await client(context, c.service).read(c.scopeId, self.profileId))
|
|
345
|
+
.value, self.peerId));
|
|
346
|
+
}
|
|
347
|
+
const field = (key) => {
|
|
348
|
+
if (changes[key] !== undefined)
|
|
349
|
+
return changes[key];
|
|
350
|
+
const values = new Set(legacy.map((profile) => profile[key] ?? ""));
|
|
351
|
+
if (values.size > 1)
|
|
352
|
+
throw new HostError(`Legacy Swarm profiles disagree on ${key}. Run ipab profile --${key} TEXT to choose your account-wide value; no profile has been saved.`);
|
|
353
|
+
return values.values().next().value ?? "";
|
|
354
|
+
};
|
|
355
|
+
return {
|
|
356
|
+
publicKey: identity.publicKey,
|
|
357
|
+
name: field("name"),
|
|
358
|
+
description: field("description"),
|
|
359
|
+
updatedAt: null,
|
|
360
|
+
};
|
|
361
|
+
}
|
|
362
|
+
export async function accountProfile(context) {
|
|
363
|
+
return ((await storedAccountProfile(context)) ??
|
|
364
|
+
(await initialAccountProfile(context)));
|
|
365
|
+
}
|
|
366
|
+
async function ensureAccountProfile(context, changes = {}) {
|
|
367
|
+
const identity = await contextIdentity(context);
|
|
368
|
+
const dir = await accountProfileDirectory(context, identity.publicKey);
|
|
369
|
+
return withPrivateLock(dir, async () => {
|
|
370
|
+
const existing = await storedAccountProfile(context);
|
|
371
|
+
if (existing &&
|
|
372
|
+
changes.name === undefined &&
|
|
373
|
+
changes.description === undefined)
|
|
374
|
+
return existing;
|
|
375
|
+
const profile = {
|
|
376
|
+
...(existing ?? (await initialAccountProfile(context, changes))),
|
|
377
|
+
...changes,
|
|
378
|
+
updatedAt: new Date().toISOString(),
|
|
379
|
+
};
|
|
380
|
+
await writePrivate(dir, accountProfileLocation(context, identity.publicKey).name, profile);
|
|
381
|
+
return profile;
|
|
382
|
+
});
|
|
383
|
+
}
|
|
384
|
+
async function syncAccountProfile(context, record, personal, fetched) {
|
|
385
|
+
const identity = await contextIdentity(context), c = coordinates(record.configUrl);
|
|
386
|
+
const self = record.config.members.find((member) => member.publicKey === identity.publicKey);
|
|
387
|
+
const api = client(context, c.service, identity, identity.publicKey === record.owner ? undefined : record.secret);
|
|
388
|
+
let existing = fetched;
|
|
389
|
+
if (!existing) {
|
|
390
|
+
const variable = await api.read(c.scopeId, self.profileId);
|
|
391
|
+
existing = {
|
|
392
|
+
profile: parseProfile(variable.value, self.peerId),
|
|
393
|
+
cid: variable.cid,
|
|
394
|
+
};
|
|
395
|
+
}
|
|
396
|
+
const old = existing.profile;
|
|
397
|
+
if (old.name === personal.name && old.description === personal.description)
|
|
398
|
+
return old;
|
|
399
|
+
const profile = {
|
|
400
|
+
...old,
|
|
401
|
+
name: personal.name,
|
|
402
|
+
description: personal.description,
|
|
403
|
+
updatedAt: new Date().toISOString(),
|
|
404
|
+
};
|
|
405
|
+
await api.write(c.scopeId, self.profileId, profile, existing.cid, uniqueId());
|
|
406
|
+
return profile;
|
|
407
|
+
}
|
|
408
|
+
export async function updateAccountProfile(context, changes) {
|
|
409
|
+
if ((changes.name?.length ?? 0) > 256 ||
|
|
410
|
+
(changes.description?.length ?? 0) > 2048)
|
|
411
|
+
throw new HostError("Profile name/description limit exceeded.");
|
|
412
|
+
await contextIdentity(context, true);
|
|
413
|
+
let profile;
|
|
414
|
+
try {
|
|
415
|
+
profile = await ensureAccountProfile(context, changes);
|
|
416
|
+
}
|
|
417
|
+
catch (cause) {
|
|
418
|
+
throw new HostError(`Personal profile local persistence failed: ${message(cause)}. No Swarm synchronization was attempted.`);
|
|
419
|
+
}
|
|
420
|
+
const swarms = [];
|
|
421
|
+
for (const entry of withState(context, (state) => state.swarms())) {
|
|
422
|
+
try {
|
|
423
|
+
const record = await approvedMembership(context, entry.cid);
|
|
424
|
+
await syncAccountProfile(context, record, profile);
|
|
425
|
+
swarms.push({ configUrl: entry.cid, synchronized: true });
|
|
426
|
+
}
|
|
427
|
+
catch (cause) {
|
|
428
|
+
swarms.push({
|
|
429
|
+
configUrl: entry.cid,
|
|
430
|
+
synchronized: false,
|
|
431
|
+
error: message(cause),
|
|
432
|
+
});
|
|
433
|
+
}
|
|
434
|
+
}
|
|
435
|
+
return { profile, localPersisted: true, swarms };
|
|
186
436
|
}
|
|
187
437
|
async function fetchConfig(context, configUrl, signal) {
|
|
188
438
|
const c = coordinates(configUrl), api = client(context, c.service);
|
|
@@ -191,10 +441,76 @@ async function fetchConfig(context, configUrl, signal) {
|
|
|
191
441
|
api.read(c.scopeId, c.configId, options),
|
|
192
442
|
api.send("GET", c.scopeId, "", undefined, options),
|
|
193
443
|
]);
|
|
194
|
-
const
|
|
195
|
-
if (scope.owner !==
|
|
444
|
+
const raw = object(variable.value, "organization configuration");
|
|
445
|
+
if (scope.owner !== raw.owner)
|
|
196
446
|
throw new HostError("Organization Owner does not match the immutable Scope trust root.");
|
|
197
|
-
|
|
447
|
+
if (raw.v === 2) {
|
|
448
|
+
if (!Array.isArray(raw.members) ||
|
|
449
|
+
raw.members.length < 1 ||
|
|
450
|
+
raw.members.length > 256)
|
|
451
|
+
throw new HostError("Invalid organization member directory.");
|
|
452
|
+
const ids = new Set(), identities = new Set();
|
|
453
|
+
const directory = raw.members.map((item) => {
|
|
454
|
+
const member = object(item, "member directory entry");
|
|
455
|
+
if (Object.keys(member).sort().join() !== "memberId,publicKey" ||
|
|
456
|
+
!isCanonicalPublicKey(member.publicKey) ||
|
|
457
|
+
typeof member.memberId !== "string" ||
|
|
458
|
+
!RESOURCE_ID_PATTERN.test(member.memberId) ||
|
|
459
|
+
ids.has(member.memberId) ||
|
|
460
|
+
identities.has(member.publicKey))
|
|
461
|
+
throw new HostError("Invalid or duplicate member directory entry.");
|
|
462
|
+
ids.add(member.memberId);
|
|
463
|
+
identities.add(member.publicKey);
|
|
464
|
+
return { publicKey: member.publicKey, memberId: member.memberId };
|
|
465
|
+
});
|
|
466
|
+
const members = await boundedMap(directory, async (entry) => {
|
|
467
|
+
const member = object((await api.read(c.scopeId, entry.memberId, options)).value, "member record");
|
|
468
|
+
if (member.publicKey !== entry.publicKey)
|
|
469
|
+
throw new HostError("Member record does not match its directory identity.");
|
|
470
|
+
return { ...member, memberId: entry.memberId };
|
|
471
|
+
});
|
|
472
|
+
return {
|
|
473
|
+
config: parseOrganization({ ...raw, members }, configUrl),
|
|
474
|
+
variable,
|
|
475
|
+
};
|
|
476
|
+
}
|
|
477
|
+
return { config: parseOrganization(raw, configUrl), variable };
|
|
478
|
+
}
|
|
479
|
+
async function boundedMap(items, operation) {
|
|
480
|
+
const results = [];
|
|
481
|
+
for (let offset = 0; offset < items.length; offset += 16) {
|
|
482
|
+
const batch = await Promise.allSettled(items.slice(offset, offset + 16).map(operation));
|
|
483
|
+
for (const result of batch) {
|
|
484
|
+
if (result.status === "rejected")
|
|
485
|
+
throw result.reason;
|
|
486
|
+
results.push(result.value);
|
|
487
|
+
}
|
|
488
|
+
}
|
|
489
|
+
return results;
|
|
490
|
+
}
|
|
491
|
+
function configValue(config) {
|
|
492
|
+
if (config.v === 1)
|
|
493
|
+
return config;
|
|
494
|
+
return {
|
|
495
|
+
...config,
|
|
496
|
+
members: config.members.map((member) => {
|
|
497
|
+
if (!member.memberId)
|
|
498
|
+
throw new HostError("Member directory is missing its record ID.");
|
|
499
|
+
return { publicKey: member.publicKey, memberId: member.memberId };
|
|
500
|
+
}),
|
|
501
|
+
};
|
|
502
|
+
}
|
|
503
|
+
async function createMemberRecord(api, scopeId, member, key) {
|
|
504
|
+
const value = {
|
|
505
|
+
publicKey: member.publicKey,
|
|
506
|
+
encryptionKey: member.encryptionKey,
|
|
507
|
+
peerId: member.peerId,
|
|
508
|
+
profileId: member.profileId,
|
|
509
|
+
requestId: member.requestId,
|
|
510
|
+
approval: member.approval,
|
|
511
|
+
};
|
|
512
|
+
const created = await api.create(scopeId, value, key);
|
|
513
|
+
return { ...value, memberId: created.id };
|
|
198
514
|
}
|
|
199
515
|
function binding(configUrl, config, member) {
|
|
200
516
|
return {
|
|
@@ -235,20 +551,22 @@ async function privateSource(context, record, signal) {
|
|
|
235
551
|
await verifyScopeCertificate(secret.certificate, config.owner, c.service, c.scopeId, config.headId, identity.publicKey);
|
|
236
552
|
await verifyScopeCertificate(secret.certificate, config.owner, c.service, c.scopeId, self.profileId, identity.publicKey);
|
|
237
553
|
}
|
|
554
|
+
const personal = await storedAccountProfile(context);
|
|
238
555
|
const addresses = new Map();
|
|
239
556
|
const api = client(context, c.service);
|
|
240
557
|
let selfProfile;
|
|
241
|
-
const profiles = await
|
|
558
|
+
const profiles = await boundedMap(config.members, (member) => api.read(c.scopeId, member.profileId, signal ? { signal } : {}));
|
|
242
559
|
for (const [index, member] of config.members.entries()) {
|
|
243
|
-
const
|
|
244
|
-
if (result.status === "rejected")
|
|
245
|
-
throw result.reason;
|
|
246
|
-
const profile = result.value;
|
|
560
|
+
const profile = profiles[index];
|
|
247
561
|
const value = parseProfile(profile.value, member.peerId);
|
|
248
562
|
if (member.publicKey === identity.publicKey)
|
|
249
563
|
selfProfile = { profile: value, cid: profile.cid };
|
|
250
564
|
addresses.set(member.peerId, value.addresses);
|
|
251
565
|
}
|
|
566
|
+
if (personal && selfProfile) {
|
|
567
|
+
selfProfile.profile = await syncAccountProfile(context, record, personal, selfProfile);
|
|
568
|
+
selfProfile.cid = await valueCid(selfProfile.profile);
|
|
569
|
+
}
|
|
252
570
|
const desired = memberPeers(self.peerId, addresses, config.bootstrap);
|
|
253
571
|
signal?.throwIfAborted();
|
|
254
572
|
const node = await startNode(context.stateDir, nodeScope(c.service, config.scopeId), secret.swarmKey, config.epoch, context.listen, { self: self.peerId, peers: desired, ...(signal ? { signal } : {}) });
|
|
@@ -343,6 +661,11 @@ async function readyMembership(context, configUrl) {
|
|
|
343
661
|
throw cause;
|
|
344
662
|
}
|
|
345
663
|
}
|
|
664
|
+
else {
|
|
665
|
+
const personal = await storedAccountProfile(context);
|
|
666
|
+
if (personal)
|
|
667
|
+
await syncAccountProfile(context, record, personal);
|
|
668
|
+
}
|
|
346
669
|
return record;
|
|
347
670
|
}
|
|
348
671
|
function headValue(head) {
|
|
@@ -435,13 +758,40 @@ export async function jsonBundle(store, type, value) {
|
|
|
435
758
|
}
|
|
436
759
|
}
|
|
437
760
|
export async function writeSnapshot(store, snapshot) {
|
|
438
|
-
const
|
|
439
|
-
|
|
440
|
-
|
|
761
|
+
const put = async (value) => {
|
|
762
|
+
const encoded = dagCbor.encode(value);
|
|
763
|
+
const cid = CID.createV1(dagCbor.code, await sha256.digest(encoded));
|
|
764
|
+
await store.put(cid, encoded);
|
|
765
|
+
return cid;
|
|
766
|
+
};
|
|
767
|
+
const names = await put(snapshot.names);
|
|
768
|
+
const registrations = await put(snapshot.registrations ?? {});
|
|
769
|
+
return (await put({ v: 3, names, registrations })).toString();
|
|
770
|
+
}
|
|
771
|
+
async function readState(store, cid) {
|
|
772
|
+
const data = await store.block.get(cid.toString());
|
|
773
|
+
const root = object(dagCbor.decode(data), "State");
|
|
774
|
+
if (root.v !== 3)
|
|
775
|
+
return decodeSnapshot(data);
|
|
776
|
+
const names = CID.asCID(root.names), registrations = CID.asCID(root.registrations);
|
|
777
|
+
if (!names ||
|
|
778
|
+
!registrations ||
|
|
779
|
+
Object.keys(root).sort().join() !== "names,registrations,v")
|
|
780
|
+
throw new HostError("Invalid State index roots.");
|
|
781
|
+
const [namesBlock, registrationsBlock] = await Promise.all([
|
|
782
|
+
store.block.get(names.toString()),
|
|
783
|
+
store.block.get(registrations.toString()),
|
|
784
|
+
]);
|
|
785
|
+
return decodeSnapshot(dagCbor.encode({
|
|
786
|
+
v: 2,
|
|
787
|
+
names: dagCbor.decode(namesBlock),
|
|
788
|
+
registrations: dagCbor.decode(registrationsBlock),
|
|
789
|
+
}));
|
|
441
790
|
}
|
|
442
791
|
function decodeSnapshot(data) {
|
|
443
792
|
const value = object(dagCbor.decode(data), "State"), names = object(value.names, "Names");
|
|
444
|
-
if (value.v !== 2 ||
|
|
793
|
+
if (value.v !== 2 ||
|
|
794
|
+
Object.keys(value).some((key) => !["v", "names", "registrations"].includes(key)))
|
|
445
795
|
throw new HostError("Unsupported old State; rebuild the Swarm.");
|
|
446
796
|
const links = [];
|
|
447
797
|
for (const [name, link] of Object.entries(names)) {
|
|
@@ -451,11 +801,38 @@ function decodeSnapshot(data) {
|
|
|
451
801
|
throw new HostError("Names must link CIDs.");
|
|
452
802
|
links.push([name, cid]);
|
|
453
803
|
}
|
|
454
|
-
|
|
804
|
+
const registrations = {};
|
|
805
|
+
if (value.registrations !== undefined) {
|
|
806
|
+
for (const [schema, raw] of Object.entries(object(value.registrations, "Registrations"))) {
|
|
807
|
+
const item = object(raw, "Association");
|
|
808
|
+
const appCid = CID.asCID(item.appCid);
|
|
809
|
+
if (Object.keys(item).sort().join() !== "appCid,argv" ||
|
|
810
|
+
!appCid ||
|
|
811
|
+
!Array.isArray(item.argv) ||
|
|
812
|
+
!item.argv.every((argument) => typeof argument === "string"))
|
|
813
|
+
throw new HostError("Invalid shared Association.");
|
|
814
|
+
const association = createAssociation(schema, appCid.toString(), item.argv);
|
|
815
|
+
if (association.schemaCid !== schema)
|
|
816
|
+
throw new HostError("Shared Association requires a canonical type CID.");
|
|
817
|
+
registrations[schema] = { appCid, argv: association.argv };
|
|
818
|
+
}
|
|
819
|
+
}
|
|
820
|
+
return {
|
|
821
|
+
v: 2,
|
|
822
|
+
names: Object.fromEntries(links),
|
|
823
|
+
...(value.registrations !== undefined ? { registrations } : {}),
|
|
824
|
+
};
|
|
455
825
|
}
|
|
456
826
|
export async function readSnapshot(store, root) {
|
|
457
827
|
const publication = await readPublication(store, root);
|
|
458
|
-
return
|
|
828
|
+
return readState(store, publication.state);
|
|
829
|
+
}
|
|
830
|
+
async function readHeaderSnapshot(store, root) {
|
|
831
|
+
const publication = await readPublication(store, root);
|
|
832
|
+
return {
|
|
833
|
+
snapshot: await readState(store, publication.state),
|
|
834
|
+
stateCid: publication.state.toString(),
|
|
835
|
+
};
|
|
459
836
|
}
|
|
460
837
|
async function readPublication(store, root) {
|
|
461
838
|
if (CID.parse(root).code !== dagCbor.code)
|
|
@@ -486,9 +863,9 @@ export async function sharedSwarmStatus(context, configUrl) {
|
|
|
486
863
|
const { config } = await fetchConfig(context, configUrl);
|
|
487
864
|
const c = coordinates(configUrl);
|
|
488
865
|
const head = headValue(await client(context, c.service).read(c.scopeId, config.headId));
|
|
489
|
-
let
|
|
866
|
+
let content;
|
|
490
867
|
try {
|
|
491
|
-
|
|
868
|
+
content = await readHeaderSnapshot(context.store, head.root);
|
|
492
869
|
}
|
|
493
870
|
catch (cause) {
|
|
494
871
|
if (!(cause instanceof ContentError) || cause.code !== "missing_block")
|
|
@@ -499,51 +876,94 @@ export async function sharedSwarmStatus(context, configUrl) {
|
|
|
499
876
|
context.diagnostic?.("Shared State is missing locally; connecting the registered Swarm content source.");
|
|
500
877
|
return swarmHeader(context, configUrl, true);
|
|
501
878
|
}
|
|
502
|
-
|
|
879
|
+
const header = {
|
|
503
880
|
head,
|
|
504
|
-
|
|
881
|
+
...content,
|
|
505
882
|
config,
|
|
506
883
|
source: "network",
|
|
507
884
|
verifiedAt: new Date().toISOString(),
|
|
508
885
|
};
|
|
886
|
+
if (withState(context, (state) => state
|
|
887
|
+
.contentPins()
|
|
888
|
+
.some((pin) => pin.swarm === configUrl && pin.status !== "deleting"))) {
|
|
889
|
+
const record = await localForRead(context, configUrl);
|
|
890
|
+
await lazyPrivateSource(context, configUrl, record.account, config);
|
|
891
|
+
await refreshNamePins(context, configUrl, header);
|
|
892
|
+
}
|
|
893
|
+
return header;
|
|
509
894
|
}
|
|
510
|
-
export async function swarmHeader(context, configUrl, force = context.forceRefresh ?? false) {
|
|
895
|
+
export async function swarmHeader(context, configUrl, force = context.forceRefresh ?? false, mode = "active") {
|
|
896
|
+
try {
|
|
897
|
+
return await readSwarmHeader(context, configUrl, force, mode);
|
|
898
|
+
}
|
|
899
|
+
catch (cause) {
|
|
900
|
+
withState(context, (state) => {
|
|
901
|
+
for (const pin of state.contentPins())
|
|
902
|
+
if (pin.swarm === configUrl && pin.status !== "deleting")
|
|
903
|
+
state.saveContentPin({
|
|
904
|
+
...pin,
|
|
905
|
+
freshness: "stale",
|
|
906
|
+
error: message(cause),
|
|
907
|
+
});
|
|
908
|
+
});
|
|
909
|
+
throw cause;
|
|
910
|
+
}
|
|
911
|
+
}
|
|
912
|
+
async function readSwarmHeader(context, configUrl, force = context.forceRefresh ?? false, mode = "active") {
|
|
511
913
|
canonicalSwarmUrl(configUrl);
|
|
512
|
-
let record =
|
|
513
|
-
? await
|
|
514
|
-
:
|
|
515
|
-
|
|
516
|
-
|
|
914
|
+
let record = mode === "local-first"
|
|
915
|
+
? await approvedMembership(context, configUrl)
|
|
916
|
+
: force
|
|
917
|
+
? await refresh(context, configUrl)
|
|
918
|
+
: await readyMembership(context, configUrl);
|
|
919
|
+
const cached = !force && (await cachedHeader(context, record));
|
|
920
|
+
if (cached) {
|
|
921
|
+
projectHeader(context, record, cached);
|
|
922
|
+
await refreshNamePins(context, configUrl, cached);
|
|
517
923
|
return cached;
|
|
518
|
-
|
|
519
|
-
|
|
924
|
+
}
|
|
925
|
+
if (mode === "local-first") {
|
|
926
|
+
await saveLocal(context, record);
|
|
927
|
+
await lazyPrivateSource(context, configUrl, record.account, record.config);
|
|
928
|
+
}
|
|
929
|
+
const c = coordinates(configUrl);
|
|
930
|
+
let head = mode === "local-first"
|
|
931
|
+
? headValue(await client(context, c.service).read(c.scopeId, record.config.headId))
|
|
932
|
+
: await (await boundPointer(context, configUrl, record)).read();
|
|
933
|
+
let content;
|
|
520
934
|
try {
|
|
521
|
-
|
|
935
|
+
content = await readHeaderSnapshot(context.store, head.root);
|
|
522
936
|
}
|
|
523
|
-
catch {
|
|
937
|
+
catch (cause) {
|
|
938
|
+
if (mode === "local-first")
|
|
939
|
+
throw cause;
|
|
524
940
|
record = await refresh(context, configUrl);
|
|
525
941
|
head = await (await boundPointer(context, configUrl, record)).read();
|
|
526
|
-
|
|
942
|
+
content = await readHeaderSnapshot(context.store, head.root);
|
|
527
943
|
}
|
|
528
944
|
const current = await local(context, configUrl), verifiedAt = Date.now();
|
|
529
945
|
withState(context, (state) => {
|
|
530
946
|
state.saveSwarmHeader(record.account, configUrl, {
|
|
531
947
|
head,
|
|
532
|
-
snapshot: Buffer.from(dagCbor.encode(snapshot)).toString("base64"),
|
|
948
|
+
snapshot: Buffer.from(dagCbor.encode(content.snapshot)).toString("base64"),
|
|
949
|
+
stateCid: content.stateCid,
|
|
533
950
|
verifiedAt,
|
|
534
951
|
headId: current.config.headId,
|
|
535
952
|
epoch: current.config.epoch,
|
|
536
953
|
});
|
|
537
954
|
});
|
|
538
|
-
|
|
955
|
+
const header = {
|
|
539
956
|
head,
|
|
540
|
-
|
|
957
|
+
...content,
|
|
541
958
|
config: current.config,
|
|
542
959
|
source: "network",
|
|
543
960
|
verifiedAt: new Date(verifiedAt).toISOString(),
|
|
544
961
|
};
|
|
962
|
+
projectHeader(context, current, header);
|
|
963
|
+
await refreshNamePins(context, configUrl, header);
|
|
964
|
+
return header;
|
|
545
965
|
}
|
|
546
|
-
function cachedHeader(context, record) {
|
|
966
|
+
async function cachedHeader(context, record) {
|
|
547
967
|
const config = record.config;
|
|
548
968
|
if (!config || !record.secret)
|
|
549
969
|
return;
|
|
@@ -554,20 +974,58 @@ function cachedHeader(context, record) {
|
|
|
554
974
|
(cached.epoch !== undefined && cached.epoch !== config.epoch) ||
|
|
555
975
|
!(age >= 0 && age < (context.cacheTtl ?? 300) * 1000))
|
|
556
976
|
return;
|
|
977
|
+
const snapshot = decodeSnapshot(Buffer.from(cached.snapshot, "base64"));
|
|
978
|
+
let stateCid = cached.stateCid;
|
|
979
|
+
if (!stateCid) {
|
|
980
|
+
try {
|
|
981
|
+
stateCid = (await readPublication(context.store, headValue(cached.head).root)).state.toString();
|
|
982
|
+
}
|
|
983
|
+
catch (cause) {
|
|
984
|
+
if (cause instanceof ContentError && cause.code === "missing_block")
|
|
985
|
+
return;
|
|
986
|
+
throw cause;
|
|
987
|
+
}
|
|
988
|
+
}
|
|
557
989
|
return {
|
|
558
990
|
head: headValue(cached.head),
|
|
559
|
-
snapshot
|
|
991
|
+
snapshot,
|
|
992
|
+
stateCid,
|
|
560
993
|
config,
|
|
561
994
|
source: "cache",
|
|
562
995
|
verifiedAt: new Date(cached.verifiedAt).toISOString(),
|
|
563
996
|
};
|
|
564
997
|
}
|
|
998
|
+
function projectHeader(context, record, header) {
|
|
999
|
+
const member = header.config.members.find((item) => item.publicKey === record.account);
|
|
1000
|
+
if (!member || record.owner !== header.config.owner)
|
|
1001
|
+
throw new HostError("Projection membership does not match the verified account.");
|
|
1002
|
+
const binding = {
|
|
1003
|
+
account: record.account,
|
|
1004
|
+
swarm: record.configUrl,
|
|
1005
|
+
stateCid: header.stateCid,
|
|
1006
|
+
root: header.head.root,
|
|
1007
|
+
valueCid: header.head.cid,
|
|
1008
|
+
verifiedAt: Date.parse(header.verifiedAt),
|
|
1009
|
+
headId: header.config.headId,
|
|
1010
|
+
epoch: header.config.epoch,
|
|
1011
|
+
membership: JSON.stringify({ owner: record.owner, member }),
|
|
1012
|
+
};
|
|
1013
|
+
withState(context, (state) => {
|
|
1014
|
+
state.projectSwarm(binding, header.snapshot.names, () => snapshotAssociations(header.snapshot));
|
|
1015
|
+
});
|
|
1016
|
+
header.projection = binding;
|
|
1017
|
+
}
|
|
1018
|
+
function headerProjection(header) {
|
|
1019
|
+
if (!header.projection)
|
|
1020
|
+
throw new HostError("A verified account projection is required.");
|
|
1021
|
+
return header.projection;
|
|
1022
|
+
}
|
|
565
1023
|
async function localHeader(context, url) {
|
|
566
1024
|
if (context.forceRefresh)
|
|
567
1025
|
return;
|
|
568
1026
|
canonicalSwarmUrl(url);
|
|
569
1027
|
const record = await localForRead(context, url);
|
|
570
|
-
const header = cachedHeader(context, record);
|
|
1028
|
+
const header = await cachedHeader(context, record);
|
|
571
1029
|
if (!header)
|
|
572
1030
|
return;
|
|
573
1031
|
const config = parseOrganization(header.config, url);
|
|
@@ -583,11 +1041,22 @@ async function localHeader(context, url) {
|
|
|
583
1041
|
await validateMembershipSecret(record, config, member);
|
|
584
1042
|
const c = coordinates(url);
|
|
585
1043
|
await checkCachedNode(context.stateDir, nodeScope(c.service, c.scopeId), config.epoch, member.peerId);
|
|
1044
|
+
projectHeader(context, record, header);
|
|
1045
|
+
if (withState(context, (state) => state
|
|
1046
|
+
.contentPins()
|
|
1047
|
+
.some((pin) => pin.swarm === url && pin.status !== "deleting"))) {
|
|
1048
|
+
await lazyPrivateSource(context, url, record.account, header.config);
|
|
1049
|
+
header.localSourceReady = true;
|
|
1050
|
+
await refreshNamePins(context, url, header);
|
|
1051
|
+
}
|
|
586
1052
|
return { header, account: record.account };
|
|
587
1053
|
}
|
|
588
1054
|
// SharedContent invokes this source only after a genuine local ENOENT. Its
|
|
589
1055
|
// store is not replaced from inside its own pending read (which would deadlock).
|
|
590
1056
|
async function lazyPrivateSource(context, url, account, basis) {
|
|
1057
|
+
const finishPrevious = context.finishRead;
|
|
1058
|
+
delete context.finishRead;
|
|
1059
|
+
await finishPrevious?.();
|
|
591
1060
|
const lifetime = new AbortController();
|
|
592
1061
|
let pending;
|
|
593
1062
|
const load = async (signal) => {
|
|
@@ -645,6 +1114,7 @@ export async function createSwarm(context, options = {}) {
|
|
|
645
1114
|
(options.service && options.service !== service))
|
|
646
1115
|
throw new HostError("Configure origin-bound pointers.service/apiKey before creating a Scope.");
|
|
647
1116
|
const identity = await contextIdentity(context, true), op = options.resume ?? uniqueId(), dir = await directory(context);
|
|
1117
|
+
const personal = await ensureAccountProfile(context);
|
|
648
1118
|
if (!POINTER_ID_PATTERN.test(op))
|
|
649
1119
|
throw new HostError("Invalid creation resume ID.");
|
|
650
1120
|
return withPrivateLock(dir, async () => {
|
|
@@ -668,6 +1138,7 @@ export async function createSwarm(context, options = {}) {
|
|
|
668
1138
|
name: options.properties?.name ?? "",
|
|
669
1139
|
description: options.properties?.description ?? "",
|
|
670
1140
|
createdAt: new Date().toISOString(),
|
|
1141
|
+
personal: { name: personal.name, description: personal.description },
|
|
671
1142
|
};
|
|
672
1143
|
await writePrivate(dir, `creation-${op}.json`, record);
|
|
673
1144
|
}
|
|
@@ -687,15 +1158,31 @@ export async function createSwarm(context, options = {}) {
|
|
|
687
1158
|
await save();
|
|
688
1159
|
}
|
|
689
1160
|
if (!record.profileId) {
|
|
690
|
-
|
|
691
|
-
|
|
692
|
-
|
|
693
|
-
|
|
1161
|
+
if (!record.profile) {
|
|
1162
|
+
const addresses = options.addresses ?? node.addresses;
|
|
1163
|
+
for (const address of addresses)
|
|
1164
|
+
validateAddress(address, node.peerId);
|
|
1165
|
+
record.profile = {
|
|
1166
|
+
...(record.personal ?? { name: record.name }),
|
|
1167
|
+
addresses,
|
|
1168
|
+
updatedAt: record.createdAt,
|
|
1169
|
+
};
|
|
1170
|
+
await save();
|
|
1171
|
+
}
|
|
1172
|
+
record.profileId = (await api.create(record.scopeId, record.profile, `${op}.profile`)).id;
|
|
694
1173
|
await save();
|
|
695
1174
|
}
|
|
696
1175
|
if (!record.config) {
|
|
1176
|
+
const member = await createMemberRecord(api, record.scopeId, {
|
|
1177
|
+
publicKey: identity.publicKey,
|
|
1178
|
+
encryptionKey: record.encryption.publicKey,
|
|
1179
|
+
peerId: node.peerId,
|
|
1180
|
+
profileId: record.profileId,
|
|
1181
|
+
requestId: op,
|
|
1182
|
+
approval: null,
|
|
1183
|
+
}, `${op}.member`);
|
|
697
1184
|
record.config = {
|
|
698
|
-
v:
|
|
1185
|
+
v: 2,
|
|
699
1186
|
scopeId: record.scopeId,
|
|
700
1187
|
owner: identity.publicKey,
|
|
701
1188
|
name: record.name,
|
|
@@ -703,21 +1190,12 @@ export async function createSwarm(context, options = {}) {
|
|
|
703
1190
|
headId: record.headId,
|
|
704
1191
|
epoch: 1,
|
|
705
1192
|
bootstrap: options.addresses ?? node.addresses,
|
|
706
|
-
members: [
|
|
707
|
-
{
|
|
708
|
-
publicKey: identity.publicKey,
|
|
709
|
-
encryptionKey: record.encryption.publicKey,
|
|
710
|
-
peerId: node.peerId,
|
|
711
|
-
profileId: record.profileId,
|
|
712
|
-
requestId: op,
|
|
713
|
-
approval: null,
|
|
714
|
-
},
|
|
715
|
-
],
|
|
1193
|
+
members: [member],
|
|
716
1194
|
};
|
|
717
1195
|
await save();
|
|
718
1196
|
}
|
|
719
1197
|
if (!record.configId) {
|
|
720
|
-
record.configId = (await api.create(record.scopeId, record.config, `${op}.config`)).id;
|
|
1198
|
+
record.configId = (await api.create(record.scopeId, configValue(record.config), `${op}.config`)).id;
|
|
721
1199
|
await save();
|
|
722
1200
|
}
|
|
723
1201
|
const configUrl = `${service}/v1/${record.scopeId}/${record.configId}`;
|
|
@@ -764,13 +1242,12 @@ export async function exportRequest(context, url, output) {
|
|
|
764
1242
|
return record.request.id;
|
|
765
1243
|
}
|
|
766
1244
|
export async function requestMembership(context, url, options) {
|
|
767
|
-
if (
|
|
768
|
-
throw new HostError("
|
|
1245
|
+
if ("name" in options)
|
|
1246
|
+
throw new HostError("Set your account-wide name with ipab profile --name NAME before requesting membership.");
|
|
769
1247
|
canonicalSwarmUrl(url);
|
|
770
1248
|
const identity = await contextIdentity(context, true);
|
|
771
1249
|
const { config } = await fetchConfig(context, url);
|
|
772
|
-
|
|
773
|
-
throw new HostError(`Trusted Owner fingerprint required; observed ${await keyId(config.owner)}. Verify through an independent trusted channel.`);
|
|
1250
|
+
const personal = await ensureAccountProfile(context);
|
|
774
1251
|
const dir = await directory(context);
|
|
775
1252
|
await withPrivateLock(dir, async () => {
|
|
776
1253
|
if (options.alias !== undefined)
|
|
@@ -795,7 +1272,7 @@ export async function requestMembership(context, url, options) {
|
|
|
795
1272
|
configUrl: url,
|
|
796
1273
|
scopeId: config.scopeId,
|
|
797
1274
|
owner: config.owner,
|
|
798
|
-
name:
|
|
1275
|
+
name: personal.name,
|
|
799
1276
|
member: identity.publicKey,
|
|
800
1277
|
encryptionKey: encryption.publicKey,
|
|
801
1278
|
peerId: node.peerId,
|
|
@@ -818,14 +1295,42 @@ export async function requestMembership(context, url, options) {
|
|
|
818
1295
|
});
|
|
819
1296
|
withState(context, (state) => state.registerSwarm(url, options.alias));
|
|
820
1297
|
});
|
|
821
|
-
|
|
822
|
-
|
|
823
|
-
|
|
1298
|
+
const file = options.output === undefined ? undefined : resolve(options.output);
|
|
1299
|
+
if (file !== undefined)
|
|
1300
|
+
await exportRequest(context, url, file);
|
|
1301
|
+
const record = await local(context, url);
|
|
1302
|
+
return {
|
|
1303
|
+
requestId: record.request.id,
|
|
1304
|
+
ownerFingerprint: await keyId(record.owner),
|
|
1305
|
+
request: record.request,
|
|
1306
|
+
...(file === undefined ? {} : { file }),
|
|
1307
|
+
};
|
|
824
1308
|
}
|
|
825
1309
|
export async function verifiedRequest(path) {
|
|
826
1310
|
if ((await lstat(path)).size > 16 * 1024)
|
|
827
1311
|
throw new HostError("Request file exceeds 16 KiB.");
|
|
828
|
-
return
|
|
1312
|
+
return verifiedRequestStream(createReadStream(path));
|
|
1313
|
+
}
|
|
1314
|
+
export async function verifiedRequestStream(input) {
|
|
1315
|
+
const chunks = [];
|
|
1316
|
+
let size = 0;
|
|
1317
|
+
for await (const chunk of input) {
|
|
1318
|
+
const bytes = typeof chunk === "string" ? Buffer.from(chunk) : chunk;
|
|
1319
|
+
size += bytes.byteLength;
|
|
1320
|
+
if (size > 16 * 1024)
|
|
1321
|
+
throw new HostError("Request input exceeds 16 KiB.");
|
|
1322
|
+
chunks.push(bytes);
|
|
1323
|
+
}
|
|
1324
|
+
let value;
|
|
1325
|
+
try {
|
|
1326
|
+
value = JSON.parse(Buffer.concat(chunks)
|
|
1327
|
+
.toString("utf8")
|
|
1328
|
+
.replace(/^\uFEFF/, ""));
|
|
1329
|
+
}
|
|
1330
|
+
catch (cause) {
|
|
1331
|
+
throw new HostError(`Invalid Request JSON: ${message(cause)}.`);
|
|
1332
|
+
}
|
|
1333
|
+
return verifyRequest(value);
|
|
829
1334
|
}
|
|
830
1335
|
async function verifyRequest(input) {
|
|
831
1336
|
const fields = object(input, "Request");
|
|
@@ -940,6 +1445,7 @@ export async function approveMembership(context, input, options = {}) {
|
|
|
940
1445
|
if (!operation.profileId)
|
|
941
1446
|
operation.profileId = (await api.create(c.scopeId, {
|
|
942
1447
|
name: request.name,
|
|
1448
|
+
description: "",
|
|
943
1449
|
addresses: [],
|
|
944
1450
|
updatedAt: operation.createdAt,
|
|
945
1451
|
}, `${operation.operation}.profile`)).id;
|
|
@@ -956,14 +1462,15 @@ export async function approveMembership(context, input, options = {}) {
|
|
|
956
1462
|
};
|
|
957
1463
|
const config = {
|
|
958
1464
|
...fetched.config,
|
|
1465
|
+
v: 2,
|
|
959
1466
|
members: fetched.config.members.filter((m) => m.publicKey !== request.member),
|
|
960
1467
|
};
|
|
961
1468
|
if (config.members.some((m) => m.peerId === request.peerId))
|
|
962
1469
|
throw new HostError("PeerID is already assigned to another member.");
|
|
963
1470
|
if (request.member === identity.publicKey)
|
|
964
1471
|
throw new HostError("Owner cannot request member approval.");
|
|
965
|
-
if (config.members.length >=
|
|
966
|
-
throw new HostError("Organization member limit is
|
|
1472
|
+
if (config.members.length >= 256)
|
|
1473
|
+
throw new HostError("Organization member limit is 256.");
|
|
967
1474
|
const certificate = await issueScopeCertificate({
|
|
968
1475
|
v: 1,
|
|
969
1476
|
service: c.service,
|
|
@@ -977,9 +1484,17 @@ export async function approveMembership(context, input, options = {}) {
|
|
|
977
1484
|
operation.baseline = fetched.variable.cid;
|
|
978
1485
|
await save();
|
|
979
1486
|
}
|
|
1487
|
+
if (operation.value.v === 2) {
|
|
1488
|
+
for (const member of operation.value.members) {
|
|
1489
|
+
if (!member.memberId) {
|
|
1490
|
+
Object.assign(member, await createMemberRecord(api, c.scopeId, member, `${operation.operation}.${member.publicKey}.member`));
|
|
1491
|
+
await save();
|
|
1492
|
+
}
|
|
1493
|
+
}
|
|
1494
|
+
}
|
|
980
1495
|
const observed = await api.read(c.scopeId, c.configId);
|
|
981
|
-
if (observed.cid !== (await valueCid(operation.value)))
|
|
982
|
-
await api.write(c.scopeId, c.configId, operation.value, operation.baseline, `${operation.operation}.publish`);
|
|
1496
|
+
if (observed.cid !== (await valueCid(configValue(operation.value))))
|
|
1497
|
+
await api.write(c.scopeId, c.configId, configValue(operation.value), operation.baseline, `${operation.operation}.publish`);
|
|
983
1498
|
operation.completed = true;
|
|
984
1499
|
await save();
|
|
985
1500
|
record.config = operation.value;
|
|
@@ -995,7 +1510,7 @@ export async function updateSwarm(context, url, changes) {
|
|
|
995
1510
|
if (changes.name === undefined && changes.description === undefined)
|
|
996
1511
|
throw new HostError("swarm update requires name or description.");
|
|
997
1512
|
const fetched = await fetchConfig(context, url), config = { ...fetched.config, ...changes };
|
|
998
|
-
const result = await client(context, c.service, identity).write(c.scopeId, c.configId, config, fetched.variable.cid, uniqueId());
|
|
1513
|
+
const result = await client(context, c.service, identity).write(c.scopeId, c.configId, configValue(config), fetched.variable.cid, uniqueId());
|
|
999
1514
|
record.config = config;
|
|
1000
1515
|
await saveLocal(context, record);
|
|
1001
1516
|
return {
|
|
@@ -1006,10 +1521,12 @@ export async function updateSwarm(context, url, changes) {
|
|
|
1006
1521
|
};
|
|
1007
1522
|
}
|
|
1008
1523
|
export async function updateProfile(context, url, changes) {
|
|
1009
|
-
if (
|
|
1010
|
-
throw new HostError("
|
|
1524
|
+
if ("name" in changes || "description" in changes)
|
|
1525
|
+
throw new HostError("Use ipab profile --name NAME --description TEXT for personal data; swarm profile configures network addresses only.");
|
|
1011
1526
|
if ((changes.addresses?.length ?? 0) > 16)
|
|
1012
1527
|
throw new HostError("Profile address limit is 16.");
|
|
1528
|
+
if (changes.addresses === undefined)
|
|
1529
|
+
throw new HostError("swarm profile requires --address MULTIADDR; use ipab profile to read personal data.");
|
|
1013
1530
|
const record = await readyMembership(context, url), identity = await contextIdentity(context), c = coordinates(url);
|
|
1014
1531
|
const member = record.config.members.find((m) => m.publicKey === identity.publicKey);
|
|
1015
1532
|
for (const address of changes.addresses ?? [])
|
|
@@ -1088,6 +1605,7 @@ export async function resumeRemoval(context, url) {
|
|
|
1088
1605
|
if (!record.nextConfig) {
|
|
1089
1606
|
const config = {
|
|
1090
1607
|
...record.oldConfig,
|
|
1608
|
+
v: 2,
|
|
1091
1609
|
headId: record.newHeadId,
|
|
1092
1610
|
epoch: record.oldConfig.epoch + 1,
|
|
1093
1611
|
members: structuredClone(record.oldConfig.members.filter((m) => m.publicKey !== record.member)),
|
|
@@ -1104,10 +1622,19 @@ export async function resumeRemoval(context, url) {
|
|
|
1104
1622
|
write: [config.headId, member.profileId],
|
|
1105
1623
|
}, await importPrivateKeyPkcs8(identity.privateKey));
|
|
1106
1624
|
member.approval = await sealApproval(binding(url, config, member), { certificate, swarmKey: record.newKey }, identity);
|
|
1625
|
+
delete member.memberId;
|
|
1107
1626
|
}
|
|
1108
1627
|
record.nextConfig = config;
|
|
1109
1628
|
await save();
|
|
1110
1629
|
}
|
|
1630
|
+
if (record.nextConfig.v === 2) {
|
|
1631
|
+
for (const member of record.nextConfig.members) {
|
|
1632
|
+
if (!member.memberId) {
|
|
1633
|
+
Object.assign(member, await createMemberRecord(api, c.scopeId, member, `${record.operation}.${member.publicKey}.member`));
|
|
1634
|
+
await save();
|
|
1635
|
+
}
|
|
1636
|
+
}
|
|
1637
|
+
}
|
|
1111
1638
|
const leaving = record.oldConfig.members.find((m) => m.publicKey === record.member);
|
|
1112
1639
|
// Delete the profile before exposing the new configuration. Old HEAD stays readable until final cleanup.
|
|
1113
1640
|
try {
|
|
@@ -1126,8 +1653,8 @@ export async function resumeRemoval(context, url) {
|
|
|
1126
1653
|
}
|
|
1127
1654
|
if (!record.published) {
|
|
1128
1655
|
const observed = await api.read(c.scopeId, c.configId);
|
|
1129
|
-
if (observed.cid !== (await valueCid(record.nextConfig)))
|
|
1130
|
-
await api.write(c.scopeId, c.configId, record.nextConfig, record.configCid, `${record.operation}.config`);
|
|
1656
|
+
if (observed.cid !== (await valueCid(configValue(record.nextConfig))))
|
|
1657
|
+
await api.write(c.scopeId, c.configId, configValue(record.nextConfig), record.configCid, `${record.operation}.config`);
|
|
1131
1658
|
record.published = true;
|
|
1132
1659
|
await save();
|
|
1133
1660
|
}
|
|
@@ -1144,6 +1671,23 @@ export async function resumeRemoval(context, url) {
|
|
|
1144
1671
|
if (!(cause instanceof ScopeApiError) || cause.status !== 410)
|
|
1145
1672
|
throw cause;
|
|
1146
1673
|
}
|
|
1674
|
+
for (const member of record.oldConfig.members) {
|
|
1675
|
+
if (member.memberId &&
|
|
1676
|
+
!record.nextConfig.members.some((next) => next.memberId === member.memberId)) {
|
|
1677
|
+
for (const action of ["freeze", "delete"]) {
|
|
1678
|
+
try {
|
|
1679
|
+
if (action === "freeze")
|
|
1680
|
+
await api.freeze(c.scopeId, member.memberId, `${record.operation}.${member.publicKey}.freeze`);
|
|
1681
|
+
else
|
|
1682
|
+
await api.delete(c.scopeId, member.memberId, `${record.operation}.${member.publicKey}.delete`);
|
|
1683
|
+
}
|
|
1684
|
+
catch (cause) {
|
|
1685
|
+
if (!(cause instanceof ScopeApiError) || cause.status !== 410)
|
|
1686
|
+
throw cause;
|
|
1687
|
+
}
|
|
1688
|
+
}
|
|
1689
|
+
}
|
|
1690
|
+
}
|
|
1147
1691
|
record.completed = true;
|
|
1148
1692
|
await save();
|
|
1149
1693
|
withState(context, (state) => {
|
|
@@ -1231,7 +1775,7 @@ export async function resolveReference(context, reference, swarm, local, raw = f
|
|
|
1231
1775
|
}
|
|
1232
1776
|
if (!link)
|
|
1233
1777
|
throw new HostError(`Formal Name "${shared.name}" was not found after refreshing HEAD.`);
|
|
1234
|
-
if (warm && header === warm.header)
|
|
1778
|
+
if (warm && header === warm.header && !header.localSourceReady)
|
|
1235
1779
|
await lazyPrivateSource(context, selected, warm.account, header.config);
|
|
1236
1780
|
targetCid = link.toString();
|
|
1237
1781
|
}
|
|
@@ -1240,22 +1784,148 @@ export async function resolveReference(context, reference, swarm, local, raw = f
|
|
|
1240
1784
|
await readyMembership(context, swarm);
|
|
1241
1785
|
targetCid = local(reference);
|
|
1242
1786
|
}
|
|
1787
|
+
const cid = raw ? targetCid : await artifactValue(context.store, targetCid);
|
|
1788
|
+
return { targetCid, cid };
|
|
1789
|
+
}
|
|
1790
|
+
async function artifactValue(store, targetCid) {
|
|
1243
1791
|
let cid = targetCid;
|
|
1244
1792
|
const visited = new Set();
|
|
1245
|
-
for (let depth = 0
|
|
1793
|
+
for (let depth = 0;; depth++) {
|
|
1246
1794
|
if (depth >= 64 || visited.has(cid))
|
|
1247
1795
|
throw new HostError("Artifact resolution exceeds limits or contains a cycle.");
|
|
1248
1796
|
visited.add(cid);
|
|
1249
1797
|
const bundle = await openBundle(CID.parse(cid), {
|
|
1250
|
-
resolveCid: (cid) =>
|
|
1798
|
+
resolveCid: (cid) => store.block.get(cid.toString()),
|
|
1251
1799
|
});
|
|
1252
1800
|
if (bundle.schemaKey !== (await encodeSchema(artifactType)).cid.toString())
|
|
1253
1801
|
break;
|
|
1254
|
-
cid = CID.parse(parseArtifact(await typedJson(
|
|
1802
|
+
cid = CID.parse(parseArtifact(await typedJson(store, cid, artifactType)).value)
|
|
1255
1803
|
.toV1()
|
|
1256
1804
|
.toString();
|
|
1257
1805
|
}
|
|
1258
|
-
return
|
|
1806
|
+
return cid;
|
|
1807
|
+
}
|
|
1808
|
+
export function pinReference(state, reference, selected) {
|
|
1809
|
+
const shared = parseNameReference(reference);
|
|
1810
|
+
if (!shared)
|
|
1811
|
+
return { reference: exactCid(reference) };
|
|
1812
|
+
const swarm = shared.swarm ? state.resolveSwarm(shared.swarm) : selected;
|
|
1813
|
+
if (!swarm)
|
|
1814
|
+
throw new HostError("Pinning a shared Name requires --swarm or swarm use, or a Swarm authority in the IPAB URI.");
|
|
1815
|
+
return {
|
|
1816
|
+
reference: formatNameReference(swarm, shared.name),
|
|
1817
|
+
swarm,
|
|
1818
|
+
name: shared.name,
|
|
1819
|
+
};
|
|
1820
|
+
}
|
|
1821
|
+
export async function pinNameSubscription(context, reference, selected) {
|
|
1822
|
+
const canonical = withState(context, (state) => pinReference(state, reference, selected));
|
|
1823
|
+
if (!canonical.swarm || !canonical.name) {
|
|
1824
|
+
let roots;
|
|
1825
|
+
try {
|
|
1826
|
+
roots = [
|
|
1827
|
+
...(await currentDependencies(context.store, canonical.reference)),
|
|
1828
|
+
];
|
|
1829
|
+
}
|
|
1830
|
+
catch (cause) {
|
|
1831
|
+
let failure = cause;
|
|
1832
|
+
for (let depth = 0; depth < 8 && failure instanceof ContentBundleError; depth++)
|
|
1833
|
+
failure = failure.cause;
|
|
1834
|
+
if (!selected ||
|
|
1835
|
+
!(failure instanceof ContentError) ||
|
|
1836
|
+
failure.code !== "missing_block")
|
|
1837
|
+
throw cause;
|
|
1838
|
+
const swarm = withState(context, (state) => state.resolveSwarm(selected));
|
|
1839
|
+
await readyMembership(context, swarm);
|
|
1840
|
+
roots = [
|
|
1841
|
+
...(await currentDependencies(context.store, canonical.reference)),
|
|
1842
|
+
];
|
|
1843
|
+
}
|
|
1844
|
+
return withStateAsync(context, (state) => pinCid(state, canonical.reference, context.store, roots));
|
|
1845
|
+
}
|
|
1846
|
+
const resolved = await resolveReference(context, canonical.reference, canonical.swarm, exactCid, false, "local-first");
|
|
1847
|
+
const roots = await currentDependencies(context.store, resolved.targetCid);
|
|
1848
|
+
const pin = withState(context, (state) => reservePin(state, canonical.reference, context.store.configuration, {
|
|
1849
|
+
swarm: canonical.swarm,
|
|
1850
|
+
name: canonical.name,
|
|
1851
|
+
}));
|
|
1852
|
+
return withStateAsync(context, (state) => retainPin(state, pin, context.store, { ...resolved, roots: [...roots] }));
|
|
1853
|
+
}
|
|
1854
|
+
async function withStateAsync(context, operation) {
|
|
1855
|
+
if (context.state)
|
|
1856
|
+
return operation(context.state);
|
|
1857
|
+
const state = new State(context.stateDir);
|
|
1858
|
+
try {
|
|
1859
|
+
return await operation(state);
|
|
1860
|
+
}
|
|
1861
|
+
finally {
|
|
1862
|
+
state.close();
|
|
1863
|
+
}
|
|
1864
|
+
}
|
|
1865
|
+
export async function refreshNamePins(context, url, header) {
|
|
1866
|
+
const pins = withState(context, (state) => state
|
|
1867
|
+
.contentPins()
|
|
1868
|
+
.filter((pin) => pin.swarm === url && pin.status !== "deleting"));
|
|
1869
|
+
const failures = [];
|
|
1870
|
+
for (const saved of pins) {
|
|
1871
|
+
const target = Object.hasOwn(header.snapshot.names, saved.name)
|
|
1872
|
+
? header.snapshot.names[saved.name].toString()
|
|
1873
|
+
: undefined;
|
|
1874
|
+
if (!target) {
|
|
1875
|
+
withState(context, (state) => {
|
|
1876
|
+
failedPin(state, saved.reference, new Error("Shared Name is missing; keeping its last verified version."), true);
|
|
1877
|
+
});
|
|
1878
|
+
context.diagnostic?.(`Pin ${saved.reference} is missing; its last verified version remains retained.`);
|
|
1879
|
+
continue;
|
|
1880
|
+
}
|
|
1881
|
+
let claimed = false;
|
|
1882
|
+
try {
|
|
1883
|
+
// A cached HEAD can differ from the saved subscription after publication or a failed refresh.
|
|
1884
|
+
if (saved.targetCid === target &&
|
|
1885
|
+
saved.status === "ready" &&
|
|
1886
|
+
saved.freshness === "current")
|
|
1887
|
+
continue;
|
|
1888
|
+
const pin = withState(context, (state) => refreshPinClaim(state, saved));
|
|
1889
|
+
if (!pin)
|
|
1890
|
+
continue;
|
|
1891
|
+
claimed = true;
|
|
1892
|
+
const cid = await artifactValue(context.store, target);
|
|
1893
|
+
const roots = [...(await currentDependencies(context.store, target))];
|
|
1894
|
+
await withStateAsync(context, (state) => retainPin(state, pin, context.store, { cid, targetCid: target, roots }));
|
|
1895
|
+
}
|
|
1896
|
+
catch (cause) {
|
|
1897
|
+
if (claimed)
|
|
1898
|
+
withState(context, (state) => {
|
|
1899
|
+
failedPin(state, saved.reference, cause);
|
|
1900
|
+
});
|
|
1901
|
+
failures.push(`${saved.reference}: ${message(cause)}`);
|
|
1902
|
+
}
|
|
1903
|
+
}
|
|
1904
|
+
if (failures.length)
|
|
1905
|
+
throw new HostError(`Name subscription refresh failed; prior verified versions remain retained:\n${failures.join("\n")}`, 1, "PIN_STALE");
|
|
1906
|
+
}
|
|
1907
|
+
async function currentDependencies(store, root, found = new Set()) {
|
|
1908
|
+
if (found.has(root))
|
|
1909
|
+
return found;
|
|
1910
|
+
if (found.size >= 64)
|
|
1911
|
+
throw new HostError("Current pin dependency limit exceeded.");
|
|
1912
|
+
found.add(root);
|
|
1913
|
+
const bundle = await openBundle(CID.parse(root), {
|
|
1914
|
+
resolveCid: (cid) => store.block.get(cid.toString()),
|
|
1915
|
+
});
|
|
1916
|
+
if (bundle.schemaKey === (await encodeSchema(artifactType)).cid.toString()) {
|
|
1917
|
+
await currentDependencies(store, parseArtifact(await typedJson(store, root, artifactType)).value, found);
|
|
1918
|
+
}
|
|
1919
|
+
else if (bundle.schemaKey === appSchemaCid.toString()) {
|
|
1920
|
+
const app = object((await bundleJson(store, root)).value, "App");
|
|
1921
|
+
if (app.source) {
|
|
1922
|
+
const source = object(app.source, "source");
|
|
1923
|
+
if (typeof source.cid !== "string")
|
|
1924
|
+
throw new HostError("Invalid App source association.");
|
|
1925
|
+
await currentDependencies(store, source.cid, found);
|
|
1926
|
+
}
|
|
1927
|
+
}
|
|
1928
|
+
return found;
|
|
1259
1929
|
}
|
|
1260
1930
|
export async function searchNames(context, query, swarms) {
|
|
1261
1931
|
if (!query ||
|
|
@@ -1266,7 +1936,7 @@ export async function searchNames(context, query, swarms) {
|
|
|
1266
1936
|
const searched = [];
|
|
1267
1937
|
for (const swarm of swarms) {
|
|
1268
1938
|
const header = (await localHeader(context, swarm.cid))?.header ??
|
|
1269
|
-
(await swarmHeader(context, swarm.cid));
|
|
1939
|
+
(await swarmHeader(context, swarm.cid, context.forceRefresh, "local-first"));
|
|
1270
1940
|
searched.push({
|
|
1271
1941
|
configUrl: swarm.cid,
|
|
1272
1942
|
source: header.source,
|
|
@@ -1274,18 +1944,96 @@ export async function searchNames(context, query, swarms) {
|
|
|
1274
1944
|
valueCid: header.head.cid,
|
|
1275
1945
|
verifiedAt: header.verifiedAt,
|
|
1276
1946
|
});
|
|
1277
|
-
for (const name of
|
|
1278
|
-
|
|
1279
|
-
|
|
1280
|
-
|
|
1281
|
-
|
|
1282
|
-
|
|
1283
|
-
|
|
1284
|
-
|
|
1285
|
-
});
|
|
1947
|
+
for (const { name, targetCid } of withState(context, (state) => state.searchSwarmNames(headerProjection(header), query)))
|
|
1948
|
+
matches.push({
|
|
1949
|
+
swarm: swarm.cid,
|
|
1950
|
+
alias: swarm.alias,
|
|
1951
|
+
name,
|
|
1952
|
+
reference: formatNameReference(swarm.cid, name),
|
|
1953
|
+
targetCid,
|
|
1954
|
+
});
|
|
1286
1955
|
}
|
|
1287
1956
|
return { matches, swarms: searched };
|
|
1288
1957
|
}
|
|
1958
|
+
function snapshotAssociations(snapshot) {
|
|
1959
|
+
return Object.entries(snapshot.registrations ?? {})
|
|
1960
|
+
.sort(([left], [right]) => left.localeCompare(right))
|
|
1961
|
+
.map(([schemaCid, item]) => ({
|
|
1962
|
+
schemaCid,
|
|
1963
|
+
appCid: item.appCid.toString(),
|
|
1964
|
+
argv: [...item.argv],
|
|
1965
|
+
}));
|
|
1966
|
+
}
|
|
1967
|
+
export async function swarmRegistrations(context, configUrl) {
|
|
1968
|
+
const header = await swarmHeader(context, configUrl);
|
|
1969
|
+
return withState(context, (state) => state.projectedSwarmRegistrations(headerProjection(header)));
|
|
1970
|
+
}
|
|
1971
|
+
export async function swarmAssociation(context, configUrl, schemaCid, mode = "active") {
|
|
1972
|
+
let header = (mode === "local-first"
|
|
1973
|
+
? (await localHeader(context, configUrl))?.header
|
|
1974
|
+
: undefined) ?? (await swarmHeader(context, configUrl));
|
|
1975
|
+
let association = withState(context, (state) => state.projectedSwarmRegistrations(headerProjection(header), schemaCid)[0]);
|
|
1976
|
+
if (!association && header.source === "cache") {
|
|
1977
|
+
header = await swarmHeader(context, configUrl, true);
|
|
1978
|
+
association = withState(context, (state) => state.projectedSwarmRegistrations(headerProjection(header), schemaCid)[0]);
|
|
1979
|
+
}
|
|
1980
|
+
return association;
|
|
1981
|
+
}
|
|
1982
|
+
async function editSwarmAssociation(context, configUrl, schemaCid, association, replace) {
|
|
1983
|
+
const head = await pointer(context, configUrl);
|
|
1984
|
+
const roots = association
|
|
1985
|
+
? await dependencies(context.store, association.appCid)
|
|
1986
|
+
: new Set();
|
|
1987
|
+
for (let attempt = 0; attempt < 8; attempt++) {
|
|
1988
|
+
const currentHead = await head.read();
|
|
1989
|
+
const current = await readSnapshot(context.store, currentHead.root);
|
|
1990
|
+
const old = snapshotAssociations(current).find((item) => item.schemaCid === schemaCid);
|
|
1991
|
+
if (association) {
|
|
1992
|
+
if (old &&
|
|
1993
|
+
old.appCid === association.appCid &&
|
|
1994
|
+
JSON.stringify(old.argv) === JSON.stringify(association.argv))
|
|
1995
|
+
return;
|
|
1996
|
+
if (old && !replace)
|
|
1997
|
+
throw new HostError("Schema has another association; use --replace before --.");
|
|
1998
|
+
}
|
|
1999
|
+
else if (!old) {
|
|
2000
|
+
throw new HostError("No association exists for this Schema. Run ipab register list --swarm URL_OR_ALIAS.");
|
|
2001
|
+
}
|
|
2002
|
+
const registrations = { ...current.registrations };
|
|
2003
|
+
if (association)
|
|
2004
|
+
registrations[schemaCid] = {
|
|
2005
|
+
appCid: CID.parse(association.appCid),
|
|
2006
|
+
argv: association.argv,
|
|
2007
|
+
};
|
|
2008
|
+
else
|
|
2009
|
+
delete registrations[schemaCid];
|
|
2010
|
+
const next = await publication(context.store, await writeSnapshot(context.store, { ...current, registrations }), currentHead.root);
|
|
2011
|
+
await provideContent(context.store, [next, ...roots], context.node.api, context.fetch, context.node.auth);
|
|
2012
|
+
withState(context, (state) => {
|
|
2013
|
+
state.invalidateSwarmHeader(configUrl);
|
|
2014
|
+
});
|
|
2015
|
+
try {
|
|
2016
|
+
await head.write(next, currentHead.cid, uniqueId());
|
|
2017
|
+
return;
|
|
2018
|
+
}
|
|
2019
|
+
catch (cause) {
|
|
2020
|
+
if (!(cause instanceof ScopeApiError) || cause.status !== 412)
|
|
2021
|
+
throw new HostError(`Registry publication unconfirmed for ${configUrl}: ${message(cause)}. Inspect the Swarm registry before retry.`, 1, "HEAD_UNCONFIRMED", "publication");
|
|
2022
|
+
continue;
|
|
2023
|
+
}
|
|
2024
|
+
}
|
|
2025
|
+
throw new HostError(`HEAD is busy for ${configUrl}; retry the registry edit.`);
|
|
2026
|
+
}
|
|
2027
|
+
export async function setSwarmAssociation(context, configUrl, value, replace = false) {
|
|
2028
|
+
const association = createAssociation(value.schemaCid, value.appCid, value.argv);
|
|
2029
|
+
await editSwarmAssociation(context, configUrl, association.schemaCid, association, replace);
|
|
2030
|
+
return association;
|
|
2031
|
+
}
|
|
2032
|
+
export async function removeSwarmAssociation(context, configUrl, schemaCid) {
|
|
2033
|
+
const schema = exactCid(schemaCid, true);
|
|
2034
|
+
await editSwarmAssociation(context, configUrl, schema, undefined, false);
|
|
2035
|
+
return schema;
|
|
2036
|
+
}
|
|
1289
2037
|
async function dependencies(store, root, found = new Set()) {
|
|
1290
2038
|
if (found.has(root))
|
|
1291
2039
|
return found;
|
|
@@ -1320,9 +2068,11 @@ export async function frozenPublicationClosure(store, root) {
|
|
|
1320
2068
|
throw new HostError("Frozen publication history exceeds limits or contains a cycle.");
|
|
1321
2069
|
publications.add(current);
|
|
1322
2070
|
const publication = await readPublication(store, current);
|
|
1323
|
-
const snapshot =
|
|
2071
|
+
const snapshot = await readState(store, publication.state);
|
|
1324
2072
|
for (const target of Object.values(snapshot.names))
|
|
1325
2073
|
await dependencies(store, target.toString(), content);
|
|
2074
|
+
for (const association of Object.values(snapshot.registrations ?? {}))
|
|
2075
|
+
await dependencies(store, association.appCid.toString(), content);
|
|
1326
2076
|
current = publication.previous?.toString();
|
|
1327
2077
|
}
|
|
1328
2078
|
return [
|
|
@@ -1337,13 +2087,8 @@ export async function publish(context, content, options) {
|
|
|
1337
2087
|
throw new HostError("Publication requires a selected Swarm configuration URL or alias.");
|
|
1338
2088
|
const head = await pointer(context, options.swarm);
|
|
1339
2089
|
const roots = await dependencies(context.store, content);
|
|
1340
|
-
|
|
1341
|
-
|
|
1342
|
-
throw new HostError("--expect/--snapshot require --name.");
|
|
1343
|
-
await head.read();
|
|
1344
|
-
await provideContent(context.store, [...roots], context.node.api, context.fetch, context.node.auth);
|
|
1345
|
-
return content;
|
|
1346
|
-
}
|
|
2090
|
+
const currentRoots = [...(await currentDependencies(context.store, content))];
|
|
2091
|
+
await withStateAsync(context, (state) => pinCid(state, content, context.store, currentRoots));
|
|
1347
2092
|
const name = formalName(options.name);
|
|
1348
2093
|
if (options.snapshot && options.expect)
|
|
1349
2094
|
throw new HostError("Snapshots cannot replace an occupied Name.");
|
|
@@ -1368,23 +2113,30 @@ export async function publish(context, content, options) {
|
|
|
1368
2113
|
if ((Object.hasOwn(current.names, name)
|
|
1369
2114
|
? current.names[name]?.toString()
|
|
1370
2115
|
: undefined) !== expected)
|
|
1371
|
-
throw new HostError(`Edit conflict for ${name};
|
|
2116
|
+
throw new HostError(`Edit conflict for ${name}; content ${content} remains pinned. Occupied Names require --expect EXACT_OLD_ARTIFACT_CID; inspect the current Name before retrying.`, 3, "EDIT_CONFLICT", "publication");
|
|
1372
2117
|
const next = await publication(context.store, await writeSnapshot(context.store, {
|
|
1373
2118
|
...current,
|
|
1374
2119
|
names: { ...current.names, [name]: CID.parse(candidate) },
|
|
1375
2120
|
}), currentHead.root);
|
|
1376
|
-
await provideContent(context.store, [next, ...roots], context.node.api, context.fetch, context.node.auth);
|
|
2121
|
+
await provideContent(context.store, [next, ...roots], context.node.api, context.fetch, context.node.auth, [next, ...(expected ? await dependencies(context.store, expected) : [])]);
|
|
1377
2122
|
withState(context, (state) => {
|
|
1378
2123
|
state.invalidateSwarmHeader(options.swarm);
|
|
1379
2124
|
});
|
|
1380
2125
|
try {
|
|
1381
2126
|
await head.write(next, currentHead.cid, uniqueId());
|
|
1382
|
-
return candidate;
|
|
1383
2127
|
}
|
|
1384
2128
|
catch (cause) {
|
|
1385
2129
|
if (!(cause instanceof ScopeApiError) || cause.status !== 412)
|
|
1386
2130
|
throw new HostError(`HEAD publication unconfirmed: ${message(cause)}. Candidate ${candidate} remains retained; inspect HEAD before retry.`, 1, "HEAD_UNCONFIRMED", "publication");
|
|
2131
|
+
continue;
|
|
2132
|
+
}
|
|
2133
|
+
try {
|
|
2134
|
+
await swarmHeader(context, options.swarm, true);
|
|
2135
|
+
}
|
|
2136
|
+
catch (cause) {
|
|
2137
|
+
throw new HostError(`Publication committed as ${candidate}, but its HEAD/subscription refresh failed: ${message(cause)}. Published content remains pinned; inspect HEAD and retry the affected Name pin.`, 1, "PIN_STALE", "publication");
|
|
1387
2138
|
}
|
|
2139
|
+
return candidate;
|
|
1388
2140
|
}
|
|
1389
2141
|
throw new HostError(`HEAD is busy; candidate ${candidate} remains retained.`);
|
|
1390
2142
|
}
|