@ipab/cli 0.1.0-rc.4 → 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 +88 -16
- 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 +6 -2
- package/dist/cli.d.ts.map +1 -1
- package/dist/cli.js +656 -278
- package/dist/cli.js.map +1 -1
- package/dist/config-secret.d.ts +1 -1
- package/dist/config-secret.d.ts.map +1 -1
- package/dist/config-secret.js +2 -73
- package/dist/config-secret.js.map +1 -1
- package/dist/config.d.ts +1 -0
- package/dist/config.d.ts.map +1 -1
- package/dist/config.js +12 -1
- package/dist/config.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-types.d.ts +12 -0
- package/dist/context-types.d.ts.map +1 -0
- package/dist/context-types.js +2 -0
- package/dist/context-types.js.map +1 -0
- package/dist/context.d.ts +6 -1
- package/dist/context.d.ts.map +1 -1
- package/dist/context.js +24 -9
- 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 +3 -2
- package/dist/ipc.d.ts.map +1 -1
- package/dist/ipc.js +33 -9
- package/dist/ipc.js.map +1 -1
- package/dist/kubo-install.d.ts +26 -0
- package/dist/kubo-install.d.ts.map +1 -0
- package/dist/kubo-install.js +724 -0
- package/dist/kubo-install.js.map +1 -0
- package/dist/kubo-peering.d.ts +11 -0
- package/dist/kubo-peering.d.ts.map +1 -0
- package/dist/kubo-peering.js +93 -0
- package/dist/kubo-peering.js.map +1 -0
- package/dist/kubo-peers.d.ts +12 -0
- package/dist/kubo-peers.d.ts.map +1 -0
- package/dist/kubo-peers.js +118 -0
- package/dist/kubo-peers.js.map +1 -0
- package/dist/kubo-release.d.ts +22 -0
- package/dist/kubo-release.d.ts.map +1 -0
- package/dist/kubo-release.js +176 -0
- package/dist/kubo-release.js.map +1 -0
- package/dist/kubo.d.ts +12 -4
- package/dist/kubo.d.ts.map +1 -1
- package/dist/kubo.js +218 -259
- 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 +2 -0
- package/dist/runtime.d.ts.map +1 -1
- package/dist/runtime.js +4 -2
- package/dist/runtime.js.map +1 -1
- package/dist/state-storage-windows.d.ts +2 -0
- package/dist/state-storage-windows.d.ts.map +1 -0
- package/dist/state-storage-windows.js +114 -0
- package/dist/state-storage-windows.js.map +1 -0
- package/dist/state-storage.d.ts +5 -0
- package/dist/state-storage.d.ts.map +1 -0
- package/dist/state-storage.js +330 -0
- package/dist/state-storage.js.map +1 -0
- package/dist/state.d.ts +42 -8
- package/dist/state.d.ts.map +1 -1
- package/dist/state.js +254 -98
- 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-files.d.ts +1 -1
- package/dist/swarm-files.d.ts.map +1 -1
- package/dist/swarm-files.js +4 -1
- package/dist/swarm-files.js.map +1 -1
- package/dist/swarm.d.ts +70 -11
- package/dist/swarm.d.ts.map +1 -1
- package/dist/swarm.js +1033 -167
- package/dist/swarm.js.map +1 -1
- package/package.json +4 -4
- package/src/app-templates.ts +1 -1
- package/src/cli.ts +827 -356
- package/src/config-secret.ts +2 -84
- package/src/config.ts +14 -1
- package/src/content-provider.ts +4 -2
- package/src/context-types.ts +11 -0
- package/src/context.ts +39 -9
- package/src/doctor.ts +902 -0
- package/src/identity.ts +10 -10
- package/src/ipc.ts +49 -8
- package/src/kubo-install.ts +936 -0
- package/src/kubo-peering.ts +126 -0
- package/src/kubo-peers.ts +145 -0
- package/src/kubo-release.ts +230 -0
- package/src/kubo.ts +302 -336
- package/src/pins.ts +188 -126
- package/src/publish-source.ts +103 -0
- package/src/runtime.ts +10 -2
- package/src/state-storage-windows.ts +134 -0
- package/src/state-storage.ts +375 -0
- package/src/state.ts +410 -118
- package/src/swarm-envelope.ts +14 -0
- package/src/swarm-files.ts +4 -0
- package/src/swarm.ts +1482 -207
- package/dist/setup.d.ts +0 -7
- package/dist/setup.d.ts.map +0 -1
- package/dist/setup.js +0 -22
- package/dist/setup.js.map +0 -1
- package/src/setup.ts +0 -21
package/dist/swarm.js
CHANGED
|
@@ -1,29 +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";
|
|
20
|
+
import { swarmUrl as canonicalSwarmUrl } from "./config.js";
|
|
16
21
|
import { bundleJson, provideContent } from "./content-provider.js";
|
|
22
|
+
import { failedPin, pinCid, refreshPinClaim, reservePin, retainPin, } from "./pins.js";
|
|
17
23
|
import { bytes, relativePath } from "./space.js";
|
|
18
24
|
import { appSchemaCid } from "./app-definition.js";
|
|
19
|
-
import { State } from "./state.js";
|
|
25
|
+
import { State, createAssociation, exactCid, } from "./state.js";
|
|
20
26
|
import { privateDirectory, readPrivate, withPrivateLock, writePrivate, } from "./swarm-files.js";
|
|
21
|
-
import { encryptionIdentity, openApproval, sealApproval, parseEnvelope, } from "./swarm-envelope.js";
|
|
22
|
-
import { kuboSource, peerId, peerProof, prepareNode, startNode, validateAddress, } from "./kubo.js";
|
|
27
|
+
import { encryptionIdentity, openApproval, sealApproval, parseEnvelope, validateEncryptionIdentity, } from "./swarm-envelope.js";
|
|
28
|
+
import { checkCachedNode, kuboSource, peerId, peerProof, prepareNode, startNode, validateAddress, } from "./kubo.js";
|
|
29
|
+
import { memberPeers } from "./kubo-peering.js";
|
|
23
30
|
async function contextIdentity(context, initialize = false) {
|
|
24
31
|
context.identity ??= await accountIdentity(context.env, initialize);
|
|
25
32
|
return context.identity;
|
|
26
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
|
+
}
|
|
27
80
|
const cidField = { type: "string", minLength: 1, maxLength: 128 };
|
|
28
81
|
export const artifactType = {
|
|
29
82
|
contentType: "application/json",
|
|
@@ -49,20 +102,7 @@ function withState(context, operation) {
|
|
|
49
102
|
state.close();
|
|
50
103
|
}
|
|
51
104
|
}
|
|
52
|
-
export
|
|
53
|
-
if (!/^https?:\/\//.test(value))
|
|
54
|
-
throw new HostError("Swarm requires a configuration URL; old Swarm CID protocol is unsupported.");
|
|
55
|
-
const url = new URL(value);
|
|
56
|
-
canonicalService(url.origin);
|
|
57
|
-
if (url.search ||
|
|
58
|
-
url.hash ||
|
|
59
|
-
url.username ||
|
|
60
|
-
url.password ||
|
|
61
|
-
url.toString() !== value ||
|
|
62
|
-
!/^\/v1\/[a-f0-9]{16}\/[a-f0-9]{16}$/.test(url.pathname))
|
|
63
|
-
throw new HostError("Swarm must be an exact Scope configuration URL; old Swarm CID protocol is unsupported.");
|
|
64
|
-
return value;
|
|
65
|
-
}
|
|
105
|
+
export { canonicalSwarmUrl };
|
|
66
106
|
function coordinates(configUrl) {
|
|
67
107
|
const url = new URL(canonicalSwarmUrl(configUrl));
|
|
68
108
|
const [, , scopeId, configId] = url.pathname.split("/");
|
|
@@ -105,7 +145,7 @@ function parseOrganization(value, configUrl) {
|
|
|
105
145
|
const { scopeId } = coordinates(configUrl);
|
|
106
146
|
if (Object.keys(data).sort().join() !==
|
|
107
147
|
"bootstrap,description,epoch,headId,members,name,owner,scopeId,v" ||
|
|
108
|
-
data.v !== 1 ||
|
|
148
|
+
(data.v !== 1 && data.v !== 2) ||
|
|
109
149
|
data.scopeId !== scopeId ||
|
|
110
150
|
!isCanonicalPublicKey(data.owner) ||
|
|
111
151
|
typeof data.name !== "string" ||
|
|
@@ -121,14 +161,20 @@ function parseOrganization(value, configUrl) {
|
|
|
121
161
|
data.bootstrap.length > 64 ||
|
|
122
162
|
!Array.isArray(data.members) ||
|
|
123
163
|
data.members.length < 1 ||
|
|
124
|
-
data.members.length >
|
|
164
|
+
data.members.length > 256)
|
|
125
165
|
throw new HostError("Invalid Scope organization configuration.");
|
|
126
166
|
const identities = new Set(), peers = new Set(), profiles = new Set();
|
|
127
167
|
const members = [];
|
|
128
168
|
for (const raw of data.members) {
|
|
129
169
|
const member = object(raw, "member");
|
|
130
|
-
if (Object.keys(member)
|
|
170
|
+
if (Object.keys(member)
|
|
171
|
+
.filter((key) => key !== "memberId")
|
|
172
|
+
.sort()
|
|
173
|
+
.join() !==
|
|
131
174
|
"approval,encryptionKey,peerId,profileId,publicKey,requestId" ||
|
|
175
|
+
(member.memberId !== undefined &&
|
|
176
|
+
(typeof member.memberId !== "string" ||
|
|
177
|
+
!RESOURCE_ID_PATTERN.test(member.memberId))) ||
|
|
132
178
|
!isCanonicalPublicKey(member.publicKey) ||
|
|
133
179
|
typeof member.encryptionKey !== "string" ||
|
|
134
180
|
member.encryptionKey.length > 256 ||
|
|
@@ -145,6 +191,9 @@ function parseOrganization(value, configUrl) {
|
|
|
145
191
|
peers.add(member.peerId);
|
|
146
192
|
profiles.add(member.profileId);
|
|
147
193
|
members.push({
|
|
194
|
+
...(typeof member.memberId === "string"
|
|
195
|
+
? { memberId: member.memberId }
|
|
196
|
+
: {}),
|
|
148
197
|
publicKey: member.publicKey,
|
|
149
198
|
encryptionKey: member.encryptionKey,
|
|
150
199
|
peerId: member.peerId,
|
|
@@ -165,7 +214,7 @@ function parseOrganization(value, configUrl) {
|
|
|
165
214
|
bootstrap.push(address);
|
|
166
215
|
}
|
|
167
216
|
return {
|
|
168
|
-
v:
|
|
217
|
+
v: data.v,
|
|
169
218
|
scopeId,
|
|
170
219
|
owner: data.owner,
|
|
171
220
|
name: data.name,
|
|
@@ -178,9 +227,15 @@ function parseOrganization(value, configUrl) {
|
|
|
178
227
|
}
|
|
179
228
|
function parseProfile(value, expectedPeer) {
|
|
180
229
|
const data = object(value, "member profile");
|
|
181
|
-
if (
|
|
230
|
+
if (![
|
|
231
|
+
"addresses,name,updatedAt",
|
|
232
|
+
"addresses,description,name,updatedAt",
|
|
233
|
+
].includes(Object.keys(data).sort().join()) ||
|
|
182
234
|
typeof data.name !== "string" ||
|
|
183
235
|
data.name.length > 256 ||
|
|
236
|
+
(data.description !== undefined &&
|
|
237
|
+
(typeof data.description !== "string" ||
|
|
238
|
+
data.description.length > 2048)) ||
|
|
184
239
|
typeof data.updatedAt !== "string" ||
|
|
185
240
|
!Number.isFinite(Date.parse(data.updatedAt)) ||
|
|
186
241
|
!Array.isArray(data.addresses) ||
|
|
@@ -193,18 +248,269 @@ function parseProfile(value, expectedPeer) {
|
|
|
193
248
|
validateAddress(address, expectedPeer);
|
|
194
249
|
addresses.push(address);
|
|
195
250
|
}
|
|
196
|
-
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 };
|
|
197
436
|
}
|
|
198
|
-
async function fetchConfig(context, configUrl) {
|
|
437
|
+
async function fetchConfig(context, configUrl, signal) {
|
|
199
438
|
const c = coordinates(configUrl), api = client(context, c.service);
|
|
439
|
+
const options = signal ? { signal } : {};
|
|
200
440
|
const [variable, scope] = await Promise.all([
|
|
201
|
-
api.read(c.scopeId, c.configId),
|
|
202
|
-
api.send("GET", c.scopeId),
|
|
441
|
+
api.read(c.scopeId, c.configId, options),
|
|
442
|
+
api.send("GET", c.scopeId, "", undefined, options),
|
|
203
443
|
]);
|
|
204
|
-
const
|
|
205
|
-
if (scope.owner !==
|
|
444
|
+
const raw = object(variable.value, "organization configuration");
|
|
445
|
+
if (scope.owner !== raw.owner)
|
|
206
446
|
throw new HostError("Organization Owner does not match the immutable Scope trust root.");
|
|
207
|
-
|
|
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 };
|
|
208
514
|
}
|
|
209
515
|
function binding(configUrl, config, member) {
|
|
210
516
|
return {
|
|
@@ -234,7 +540,7 @@ async function validateMembershipSecret(record, config, member) {
|
|
|
234
540
|
throw new HostError("Membership package must grant exactly HEAD and this member's profile.");
|
|
235
541
|
}
|
|
236
542
|
}
|
|
237
|
-
async function
|
|
543
|
+
async function privateSource(context, record, signal) {
|
|
238
544
|
const config = record.config, secret = record.secret;
|
|
239
545
|
const identity = await contextIdentity(context);
|
|
240
546
|
const self = config.members.find((member) => member.publicKey === identity.publicKey);
|
|
@@ -245,47 +551,72 @@ async function activate(context, record) {
|
|
|
245
551
|
await verifyScopeCertificate(secret.certificate, config.owner, c.service, c.scopeId, config.headId, identity.publicKey);
|
|
246
552
|
await verifyScopeCertificate(secret.certificate, config.owner, c.service, c.scopeId, self.profileId, identity.publicKey);
|
|
247
553
|
}
|
|
248
|
-
const
|
|
554
|
+
const personal = await storedAccountProfile(context);
|
|
555
|
+
const addresses = new Map();
|
|
249
556
|
const api = client(context, c.service);
|
|
250
557
|
let selfProfile;
|
|
251
|
-
const profiles = await
|
|
558
|
+
const profiles = await boundedMap(config.members, (member) => api.read(c.scopeId, member.profileId, signal ? { signal } : {}));
|
|
252
559
|
for (const [index, member] of config.members.entries()) {
|
|
253
|
-
const
|
|
254
|
-
if (result.status === "rejected")
|
|
255
|
-
throw result.reason;
|
|
256
|
-
const profile = result.value;
|
|
560
|
+
const profile = profiles[index];
|
|
257
561
|
const value = parseProfile(profile.value, member.peerId);
|
|
258
562
|
if (member.publicKey === identity.publicKey)
|
|
259
563
|
selfProfile = { profile: value, cid: profile.cid };
|
|
260
|
-
addresses.
|
|
564
|
+
addresses.set(member.peerId, value.addresses);
|
|
261
565
|
}
|
|
262
|
-
|
|
566
|
+
if (personal && selfProfile) {
|
|
567
|
+
selfProfile.profile = await syncAccountProfile(context, record, personal, selfProfile);
|
|
568
|
+
selfProfile.cid = await valueCid(selfProfile.profile);
|
|
569
|
+
}
|
|
570
|
+
const desired = memberPeers(self.peerId, addresses, config.bootstrap);
|
|
571
|
+
signal?.throwIfAborted();
|
|
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 } : {}) });
|
|
263
573
|
if (node.peerId !== self.peerId)
|
|
264
574
|
throw new HostError("Approved PeerID differs from this local Request's Kubo identity.");
|
|
265
|
-
|
|
266
|
-
|
|
267
|
-
|
|
268
|
-
context.
|
|
269
|
-
|
|
270
|
-
|
|
271
|
-
|
|
575
|
+
const peers = desired.flatMap(({ ID, Addrs }) => Addrs.map((addr) => `${addr}/p2p/${ID}`));
|
|
576
|
+
signal?.throwIfAborted();
|
|
577
|
+
if (!node.addresses.length && !selfProfile?.profile.addresses.length)
|
|
578
|
+
context.diagnostic?.("No private LAN/VPN IPv4 address to advertise. Connect a routed interface or set your own address with swarm profile --address.");
|
|
579
|
+
if (node.addresses.length &&
|
|
580
|
+
selfProfile &&
|
|
581
|
+
selfProfile.profile.addresses.length === 0) {
|
|
272
582
|
const writer = client(context, c.service, identity, identity.publicKey === config.owner ? undefined : secret);
|
|
273
583
|
const profile = {
|
|
274
584
|
...selfProfile.profile,
|
|
275
585
|
addresses: node.addresses,
|
|
276
586
|
updatedAt: new Date().toISOString(),
|
|
277
587
|
};
|
|
278
|
-
await writer.write(c.scopeId, self.profileId, profile, selfProfile.cid, uniqueId());
|
|
588
|
+
await writer.write(c.scopeId, self.profileId, profile, selfProfile.cid, uniqueId(), signal ? { signal } : {});
|
|
279
589
|
}
|
|
590
|
+
return {
|
|
591
|
+
node,
|
|
592
|
+
peers,
|
|
593
|
+
source: kuboSource(node, peers, context.diagnostic, context.env.IPAB_SWARM_DIAL_DEBUG === "1"),
|
|
594
|
+
};
|
|
280
595
|
}
|
|
281
|
-
async function
|
|
596
|
+
async function activate(context, record) {
|
|
597
|
+
const { node, peers, source } = await privateSource(context, record);
|
|
598
|
+
if (context.node?.api !== node.api ||
|
|
599
|
+
context.sourcePeers?.length !== peers.length ||
|
|
600
|
+
peers.some((peer, i) => context.sourcePeers?.[i] !== peer)) {
|
|
601
|
+
const store = context.store.withLocalSource(source);
|
|
602
|
+
await context.store.close();
|
|
603
|
+
context.store = store;
|
|
604
|
+
context.sourcePeers = peers;
|
|
605
|
+
}
|
|
606
|
+
context.node = node;
|
|
607
|
+
}
|
|
608
|
+
async function localForRead(context, configUrl) {
|
|
282
609
|
const record = await local(context, configUrl);
|
|
283
610
|
if (record.account === record.owner) {
|
|
284
611
|
const transition = await readPrivate(await directory(context), `transition-${localName(configUrl)}`);
|
|
285
612
|
if (transition && !transition.completed)
|
|
286
613
|
throw new HostError("Organization switch incomplete; only Owner can continue with swarm resume.");
|
|
287
614
|
}
|
|
288
|
-
|
|
615
|
+
return record;
|
|
616
|
+
}
|
|
617
|
+
async function approvedMembership(context, configUrl, signal) {
|
|
618
|
+
const record = await localForRead(context, configUrl);
|
|
619
|
+
const { config } = await fetchConfig(context, configUrl, signal);
|
|
289
620
|
if (config.owner !== record.owner)
|
|
290
621
|
throw new HostError("Pinned Owner changed; refusing configuration.");
|
|
291
622
|
if (record.config && config.epoch < record.config.epoch)
|
|
@@ -305,17 +636,16 @@ async function refresh(context, configUrl) {
|
|
|
305
636
|
throw new HostError("Owner key/Swarm key lost: no system recovery is available.");
|
|
306
637
|
record.config = config;
|
|
307
638
|
await validateMembershipSecret(record, config, member);
|
|
639
|
+
return record;
|
|
640
|
+
}
|
|
641
|
+
async function refresh(context, configUrl) {
|
|
642
|
+
const record = await approvedMembership(context, configUrl);
|
|
308
643
|
await saveLocal(context, record);
|
|
309
644
|
await activate(context, record);
|
|
310
645
|
return record;
|
|
311
646
|
}
|
|
312
647
|
async function readyMembership(context, configUrl) {
|
|
313
|
-
const record = await
|
|
314
|
-
if (record.account === record.owner) {
|
|
315
|
-
const transition = await readPrivate(await directory(context), `transition-${localName(configUrl)}`);
|
|
316
|
-
if (transition && !transition.completed)
|
|
317
|
-
throw new HostError("Organization switch incomplete; run swarm resume before normal Owner operations.");
|
|
318
|
-
}
|
|
648
|
+
const record = await localForRead(context, configUrl);
|
|
319
649
|
if (!record.config || !record.secret)
|
|
320
650
|
return refresh(context, configUrl);
|
|
321
651
|
if (!context.node ||
|
|
@@ -331,6 +661,11 @@ async function readyMembership(context, configUrl) {
|
|
|
331
661
|
throw cause;
|
|
332
662
|
}
|
|
333
663
|
}
|
|
664
|
+
else {
|
|
665
|
+
const personal = await storedAccountProfile(context);
|
|
666
|
+
if (personal)
|
|
667
|
+
await syncAccountProfile(context, record, personal);
|
|
668
|
+
}
|
|
334
669
|
return record;
|
|
335
670
|
}
|
|
336
671
|
function headValue(head) {
|
|
@@ -423,13 +758,40 @@ export async function jsonBundle(store, type, value) {
|
|
|
423
758
|
}
|
|
424
759
|
}
|
|
425
760
|
export async function writeSnapshot(store, snapshot) {
|
|
426
|
-
const
|
|
427
|
-
|
|
428
|
-
|
|
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
|
+
}));
|
|
429
790
|
}
|
|
430
791
|
function decodeSnapshot(data) {
|
|
431
792
|
const value = object(dagCbor.decode(data), "State"), names = object(value.names, "Names");
|
|
432
|
-
if (value.v !== 2 ||
|
|
793
|
+
if (value.v !== 2 ||
|
|
794
|
+
Object.keys(value).some((key) => !["v", "names", "registrations"].includes(key)))
|
|
433
795
|
throw new HostError("Unsupported old State; rebuild the Swarm.");
|
|
434
796
|
const links = [];
|
|
435
797
|
for (const [name, link] of Object.entries(names)) {
|
|
@@ -439,11 +801,38 @@ function decodeSnapshot(data) {
|
|
|
439
801
|
throw new HostError("Names must link CIDs.");
|
|
440
802
|
links.push([name, cid]);
|
|
441
803
|
}
|
|
442
|
-
|
|
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
|
+
};
|
|
443
825
|
}
|
|
444
826
|
export async function readSnapshot(store, root) {
|
|
445
827
|
const publication = await readPublication(store, root);
|
|
446
|
-
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
|
+
};
|
|
447
836
|
}
|
|
448
837
|
async function readPublication(store, root) {
|
|
449
838
|
if (CID.parse(root).code !== dagCbor.code)
|
|
@@ -474,9 +863,9 @@ export async function sharedSwarmStatus(context, configUrl) {
|
|
|
474
863
|
const { config } = await fetchConfig(context, configUrl);
|
|
475
864
|
const c = coordinates(configUrl);
|
|
476
865
|
const head = headValue(await client(context, c.service).read(c.scopeId, config.headId));
|
|
477
|
-
let
|
|
866
|
+
let content;
|
|
478
867
|
try {
|
|
479
|
-
|
|
868
|
+
content = await readHeaderSnapshot(context.store, head.root);
|
|
480
869
|
}
|
|
481
870
|
catch (cause) {
|
|
482
871
|
if (!(cause instanceof ContentError) || cause.code !== "missing_block")
|
|
@@ -487,60 +876,228 @@ export async function sharedSwarmStatus(context, configUrl) {
|
|
|
487
876
|
context.diagnostic?.("Shared State is missing locally; connecting the registered Swarm content source.");
|
|
488
877
|
return swarmHeader(context, configUrl, true);
|
|
489
878
|
}
|
|
490
|
-
|
|
879
|
+
const header = {
|
|
491
880
|
head,
|
|
492
|
-
|
|
881
|
+
...content,
|
|
493
882
|
config,
|
|
494
883
|
source: "network",
|
|
495
884
|
verifiedAt: new Date().toISOString(),
|
|
496
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;
|
|
497
894
|
}
|
|
498
|
-
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") {
|
|
499
913
|
canonicalSwarmUrl(configUrl);
|
|
500
|
-
let record =
|
|
501
|
-
? await
|
|
502
|
-
:
|
|
503
|
-
|
|
504
|
-
|
|
505
|
-
|
|
506
|
-
|
|
507
|
-
|
|
508
|
-
|
|
509
|
-
|
|
510
|
-
|
|
511
|
-
|
|
512
|
-
|
|
513
|
-
|
|
514
|
-
|
|
515
|
-
|
|
516
|
-
|
|
517
|
-
|
|
518
|
-
|
|
519
|
-
let
|
|
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);
|
|
923
|
+
return cached;
|
|
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,
|
|
952
|
+
epoch: current.config.epoch,
|
|
535
953
|
});
|
|
536
954
|
});
|
|
537
|
-
|
|
955
|
+
const header = {
|
|
538
956
|
head,
|
|
539
|
-
|
|
957
|
+
...content,
|
|
540
958
|
config: current.config,
|
|
541
959
|
source: "network",
|
|
542
960
|
verifiedAt: new Date(verifiedAt).toISOString(),
|
|
543
961
|
};
|
|
962
|
+
projectHeader(context, current, header);
|
|
963
|
+
await refreshNamePins(context, configUrl, header);
|
|
964
|
+
return header;
|
|
965
|
+
}
|
|
966
|
+
async function cachedHeader(context, record) {
|
|
967
|
+
const config = record.config;
|
|
968
|
+
if (!config || !record.secret)
|
|
969
|
+
return;
|
|
970
|
+
const cached = withState(context, (state) => state.swarmHeader(record.account, record.configUrl));
|
|
971
|
+
const age = cached ? Date.now() - cached.verifiedAt : NaN;
|
|
972
|
+
if (!cached ||
|
|
973
|
+
cached.headId !== config.headId ||
|
|
974
|
+
(cached.epoch !== undefined && cached.epoch !== config.epoch) ||
|
|
975
|
+
!(age >= 0 && age < (context.cacheTtl ?? 300) * 1000))
|
|
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
|
+
}
|
|
989
|
+
return {
|
|
990
|
+
head: headValue(cached.head),
|
|
991
|
+
snapshot,
|
|
992
|
+
stateCid,
|
|
993
|
+
config,
|
|
994
|
+
source: "cache",
|
|
995
|
+
verifiedAt: new Date(cached.verifiedAt).toISOString(),
|
|
996
|
+
};
|
|
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
|
+
}
|
|
1023
|
+
async function localHeader(context, url) {
|
|
1024
|
+
if (context.forceRefresh)
|
|
1025
|
+
return;
|
|
1026
|
+
canonicalSwarmUrl(url);
|
|
1027
|
+
const record = await localForRead(context, url);
|
|
1028
|
+
const header = await cachedHeader(context, record);
|
|
1029
|
+
if (!header)
|
|
1030
|
+
return;
|
|
1031
|
+
const config = parseOrganization(header.config, url);
|
|
1032
|
+
const member = config.members.find((item) => item.publicKey === record.account);
|
|
1033
|
+
if (!member || config.owner !== record.owner)
|
|
1034
|
+
throw new HostError("Cached membership no longer matches the account or Owner.");
|
|
1035
|
+
if (record.account !== config.owner &&
|
|
1036
|
+
(!record.request ||
|
|
1037
|
+
record.request.id !== member.requestId ||
|
|
1038
|
+
record.request.peerId !== member.peerId ||
|
|
1039
|
+
!member.approval))
|
|
1040
|
+
throw new HostError("Cached membership does not match the saved Request.");
|
|
1041
|
+
await validateMembershipSecret(record, config, member);
|
|
1042
|
+
const c = coordinates(url);
|
|
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
|
+
}
|
|
1052
|
+
return { header, account: record.account };
|
|
1053
|
+
}
|
|
1054
|
+
// SharedContent invokes this source only after a genuine local ENOENT. Its
|
|
1055
|
+
// store is not replaced from inside its own pending read (which would deadlock).
|
|
1056
|
+
async function lazyPrivateSource(context, url, account, basis) {
|
|
1057
|
+
const finishPrevious = context.finishRead;
|
|
1058
|
+
delete context.finishRead;
|
|
1059
|
+
await finishPrevious?.();
|
|
1060
|
+
const lifetime = new AbortController();
|
|
1061
|
+
let pending;
|
|
1062
|
+
const load = async (signal) => {
|
|
1063
|
+
const scoped = { ...context };
|
|
1064
|
+
// Re-read the protected HOME binding and live approval on the first miss;
|
|
1065
|
+
// do not serve an old resolved Name through a different epoch or identity.
|
|
1066
|
+
delete scoped.identity;
|
|
1067
|
+
const authorize = async () => {
|
|
1068
|
+
const record = await approvedMembership(scoped, url, signal);
|
|
1069
|
+
signal.throwIfAborted();
|
|
1070
|
+
if (record.account !== account ||
|
|
1071
|
+
record.config.owner !== basis.owner ||
|
|
1072
|
+
record.config.epoch !== basis.epoch ||
|
|
1073
|
+
record.config.headId !== basis.headId)
|
|
1074
|
+
throw new HostError("Swarm membership changed since this cached HEAD; retry with --force.");
|
|
1075
|
+
return (await privateSource(scoped, record, signal)).source;
|
|
1076
|
+
};
|
|
1077
|
+
// Same lock order as Owner rotation: credentials first, then the node.
|
|
1078
|
+
return withPrivateLock(await directory(scoped), authorize, signal);
|
|
1079
|
+
};
|
|
1080
|
+
const store = context.store.withLocalSource({
|
|
1081
|
+
block: {
|
|
1082
|
+
async get(cid, options = {}) {
|
|
1083
|
+
const signal = options.signal
|
|
1084
|
+
? AbortSignal.any([lifetime.signal, options.signal])
|
|
1085
|
+
: lifetime.signal;
|
|
1086
|
+
signal.throwIfAborted();
|
|
1087
|
+
const source = await (pending ??= load(signal));
|
|
1088
|
+
signal.throwIfAborted();
|
|
1089
|
+
return source.block.get(cid, { signal });
|
|
1090
|
+
},
|
|
1091
|
+
},
|
|
1092
|
+
});
|
|
1093
|
+
await context.store.close();
|
|
1094
|
+
context.store = store;
|
|
1095
|
+
delete context.node;
|
|
1096
|
+
delete context.sourcePeers;
|
|
1097
|
+
context.finishRead = async () => {
|
|
1098
|
+
lifetime.abort();
|
|
1099
|
+
await pending?.catch(() => { });
|
|
1100
|
+
};
|
|
544
1101
|
}
|
|
545
1102
|
export async function addSwarm(context, url, alias) {
|
|
546
1103
|
canonicalSwarmUrl(url);
|
|
@@ -557,6 +1114,7 @@ export async function createSwarm(context, options = {}) {
|
|
|
557
1114
|
(options.service && options.service !== service))
|
|
558
1115
|
throw new HostError("Configure origin-bound pointers.service/apiKey before creating a Scope.");
|
|
559
1116
|
const identity = await contextIdentity(context, true), op = options.resume ?? uniqueId(), dir = await directory(context);
|
|
1117
|
+
const personal = await ensureAccountProfile(context);
|
|
560
1118
|
if (!POINTER_ID_PATTERN.test(op))
|
|
561
1119
|
throw new HostError("Invalid creation resume ID.");
|
|
562
1120
|
return withPrivateLock(dir, async () => {
|
|
@@ -580,6 +1138,7 @@ export async function createSwarm(context, options = {}) {
|
|
|
580
1138
|
name: options.properties?.name ?? "",
|
|
581
1139
|
description: options.properties?.description ?? "",
|
|
582
1140
|
createdAt: new Date().toISOString(),
|
|
1141
|
+
personal: { name: personal.name, description: personal.description },
|
|
583
1142
|
};
|
|
584
1143
|
await writePrivate(dir, `creation-${op}.json`, record);
|
|
585
1144
|
}
|
|
@@ -599,15 +1158,31 @@ export async function createSwarm(context, options = {}) {
|
|
|
599
1158
|
await save();
|
|
600
1159
|
}
|
|
601
1160
|
if (!record.profileId) {
|
|
602
|
-
|
|
603
|
-
|
|
604
|
-
|
|
605
|
-
|
|
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;
|
|
606
1173
|
await save();
|
|
607
1174
|
}
|
|
608
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`);
|
|
609
1184
|
record.config = {
|
|
610
|
-
v:
|
|
1185
|
+
v: 2,
|
|
611
1186
|
scopeId: record.scopeId,
|
|
612
1187
|
owner: identity.publicKey,
|
|
613
1188
|
name: record.name,
|
|
@@ -615,21 +1190,12 @@ export async function createSwarm(context, options = {}) {
|
|
|
615
1190
|
headId: record.headId,
|
|
616
1191
|
epoch: 1,
|
|
617
1192
|
bootstrap: options.addresses ?? node.addresses,
|
|
618
|
-
members: [
|
|
619
|
-
{
|
|
620
|
-
publicKey: identity.publicKey,
|
|
621
|
-
encryptionKey: record.encryption.publicKey,
|
|
622
|
-
peerId: node.peerId,
|
|
623
|
-
profileId: record.profileId,
|
|
624
|
-
requestId: op,
|
|
625
|
-
approval: null,
|
|
626
|
-
},
|
|
627
|
-
],
|
|
1193
|
+
members: [member],
|
|
628
1194
|
};
|
|
629
1195
|
await save();
|
|
630
1196
|
}
|
|
631
1197
|
if (!record.configId) {
|
|
632
|
-
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;
|
|
633
1199
|
await save();
|
|
634
1200
|
}
|
|
635
1201
|
const configUrl = `${service}/v1/${record.scopeId}/${record.configId}`;
|
|
@@ -676,13 +1242,12 @@ export async function exportRequest(context, url, output) {
|
|
|
676
1242
|
return record.request.id;
|
|
677
1243
|
}
|
|
678
1244
|
export async function requestMembership(context, url, options) {
|
|
679
|
-
if (
|
|
680
|
-
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.");
|
|
681
1247
|
canonicalSwarmUrl(url);
|
|
682
1248
|
const identity = await contextIdentity(context, true);
|
|
683
1249
|
const { config } = await fetchConfig(context, url);
|
|
684
|
-
|
|
685
|
-
throw new HostError(`Trusted Owner fingerprint required; observed ${await keyId(config.owner)}. Verify through an independent trusted channel.`);
|
|
1250
|
+
const personal = await ensureAccountProfile(context);
|
|
686
1251
|
const dir = await directory(context);
|
|
687
1252
|
await withPrivateLock(dir, async () => {
|
|
688
1253
|
if (options.alias !== undefined)
|
|
@@ -707,7 +1272,7 @@ export async function requestMembership(context, url, options) {
|
|
|
707
1272
|
configUrl: url,
|
|
708
1273
|
scopeId: config.scopeId,
|
|
709
1274
|
owner: config.owner,
|
|
710
|
-
name:
|
|
1275
|
+
name: personal.name,
|
|
711
1276
|
member: identity.publicKey,
|
|
712
1277
|
encryptionKey: encryption.publicKey,
|
|
713
1278
|
peerId: node.peerId,
|
|
@@ -730,14 +1295,42 @@ export async function requestMembership(context, url, options) {
|
|
|
730
1295
|
});
|
|
731
1296
|
withState(context, (state) => state.registerSwarm(url, options.alias));
|
|
732
1297
|
});
|
|
733
|
-
|
|
734
|
-
|
|
735
|
-
|
|
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
|
+
};
|
|
736
1308
|
}
|
|
737
1309
|
export async function verifiedRequest(path) {
|
|
738
1310
|
if ((await lstat(path)).size > 16 * 1024)
|
|
739
1311
|
throw new HostError("Request file exceeds 16 KiB.");
|
|
740
|
-
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);
|
|
741
1334
|
}
|
|
742
1335
|
async function verifyRequest(input) {
|
|
743
1336
|
const fields = object(input, "Request");
|
|
@@ -852,6 +1445,7 @@ export async function approveMembership(context, input, options = {}) {
|
|
|
852
1445
|
if (!operation.profileId)
|
|
853
1446
|
operation.profileId = (await api.create(c.scopeId, {
|
|
854
1447
|
name: request.name,
|
|
1448
|
+
description: "",
|
|
855
1449
|
addresses: [],
|
|
856
1450
|
updatedAt: operation.createdAt,
|
|
857
1451
|
}, `${operation.operation}.profile`)).id;
|
|
@@ -868,14 +1462,15 @@ export async function approveMembership(context, input, options = {}) {
|
|
|
868
1462
|
};
|
|
869
1463
|
const config = {
|
|
870
1464
|
...fetched.config,
|
|
1465
|
+
v: 2,
|
|
871
1466
|
members: fetched.config.members.filter((m) => m.publicKey !== request.member),
|
|
872
1467
|
};
|
|
873
1468
|
if (config.members.some((m) => m.peerId === request.peerId))
|
|
874
1469
|
throw new HostError("PeerID is already assigned to another member.");
|
|
875
1470
|
if (request.member === identity.publicKey)
|
|
876
1471
|
throw new HostError("Owner cannot request member approval.");
|
|
877
|
-
if (config.members.length >=
|
|
878
|
-
throw new HostError("Organization member limit is
|
|
1472
|
+
if (config.members.length >= 256)
|
|
1473
|
+
throw new HostError("Organization member limit is 256.");
|
|
879
1474
|
const certificate = await issueScopeCertificate({
|
|
880
1475
|
v: 1,
|
|
881
1476
|
service: c.service,
|
|
@@ -889,9 +1484,17 @@ export async function approveMembership(context, input, options = {}) {
|
|
|
889
1484
|
operation.baseline = fetched.variable.cid;
|
|
890
1485
|
await save();
|
|
891
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
|
+
}
|
|
892
1495
|
const observed = await api.read(c.scopeId, c.configId);
|
|
893
|
-
if (observed.cid !== (await valueCid(operation.value)))
|
|
894
|
-
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`);
|
|
895
1498
|
operation.completed = true;
|
|
896
1499
|
await save();
|
|
897
1500
|
record.config = operation.value;
|
|
@@ -907,7 +1510,7 @@ export async function updateSwarm(context, url, changes) {
|
|
|
907
1510
|
if (changes.name === undefined && changes.description === undefined)
|
|
908
1511
|
throw new HostError("swarm update requires name or description.");
|
|
909
1512
|
const fetched = await fetchConfig(context, url), config = { ...fetched.config, ...changes };
|
|
910
|
-
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());
|
|
911
1514
|
record.config = config;
|
|
912
1515
|
await saveLocal(context, record);
|
|
913
1516
|
return {
|
|
@@ -918,10 +1521,12 @@ export async function updateSwarm(context, url, changes) {
|
|
|
918
1521
|
};
|
|
919
1522
|
}
|
|
920
1523
|
export async function updateProfile(context, url, changes) {
|
|
921
|
-
if (
|
|
922
|
-
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.");
|
|
923
1526
|
if ((changes.addresses?.length ?? 0) > 16)
|
|
924
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.");
|
|
925
1530
|
const record = await readyMembership(context, url), identity = await contextIdentity(context), c = coordinates(url);
|
|
926
1531
|
const member = record.config.members.find((m) => m.publicKey === identity.publicKey);
|
|
927
1532
|
for (const address of changes.addresses ?? [])
|
|
@@ -1000,6 +1605,7 @@ export async function resumeRemoval(context, url) {
|
|
|
1000
1605
|
if (!record.nextConfig) {
|
|
1001
1606
|
const config = {
|
|
1002
1607
|
...record.oldConfig,
|
|
1608
|
+
v: 2,
|
|
1003
1609
|
headId: record.newHeadId,
|
|
1004
1610
|
epoch: record.oldConfig.epoch + 1,
|
|
1005
1611
|
members: structuredClone(record.oldConfig.members.filter((m) => m.publicKey !== record.member)),
|
|
@@ -1016,10 +1622,19 @@ export async function resumeRemoval(context, url) {
|
|
|
1016
1622
|
write: [config.headId, member.profileId],
|
|
1017
1623
|
}, await importPrivateKeyPkcs8(identity.privateKey));
|
|
1018
1624
|
member.approval = await sealApproval(binding(url, config, member), { certificate, swarmKey: record.newKey }, identity);
|
|
1625
|
+
delete member.memberId;
|
|
1019
1626
|
}
|
|
1020
1627
|
record.nextConfig = config;
|
|
1021
1628
|
await save();
|
|
1022
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
|
+
}
|
|
1023
1638
|
const leaving = record.oldConfig.members.find((m) => m.publicKey === record.member);
|
|
1024
1639
|
// Delete the profile before exposing the new configuration. Old HEAD stays readable until final cleanup.
|
|
1025
1640
|
try {
|
|
@@ -1038,8 +1653,8 @@ export async function resumeRemoval(context, url) {
|
|
|
1038
1653
|
}
|
|
1039
1654
|
if (!record.published) {
|
|
1040
1655
|
const observed = await api.read(c.scopeId, c.configId);
|
|
1041
|
-
if (observed.cid !== (await valueCid(record.nextConfig)))
|
|
1042
|
-
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`);
|
|
1043
1658
|
record.published = true;
|
|
1044
1659
|
await save();
|
|
1045
1660
|
}
|
|
@@ -1056,6 +1671,23 @@ export async function resumeRemoval(context, url) {
|
|
|
1056
1671
|
if (!(cause instanceof ScopeApiError) || cause.status !== 410)
|
|
1057
1672
|
throw cause;
|
|
1058
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
|
+
}
|
|
1059
1691
|
record.completed = true;
|
|
1060
1692
|
await save();
|
|
1061
1693
|
withState(context, (state) => {
|
|
@@ -1073,33 +1705,55 @@ export function formalName(name) {
|
|
|
1073
1705
|
throw new HostError("Invalid formal Name.");
|
|
1074
1706
|
return name;
|
|
1075
1707
|
}
|
|
1708
|
+
function decodeNameComponent(value, part) {
|
|
1709
|
+
try {
|
|
1710
|
+
return decodeURIComponent(value);
|
|
1711
|
+
}
|
|
1712
|
+
catch {
|
|
1713
|
+
throw new HostError(`Malformed percent-encoding in IPAB URI ${part}; use valid UTF-8 escapes or copy the reference from ipab search.`);
|
|
1714
|
+
}
|
|
1715
|
+
}
|
|
1076
1716
|
export function parseNameReference(reference) {
|
|
1077
1717
|
if (/^name:/i.test(reference))
|
|
1078
1718
|
throw new HostError("name: is unsupported; use ipab://ALIAS/PATH.");
|
|
1079
1719
|
if (!/^ipab:/i.test(reference))
|
|
1080
1720
|
return undefined;
|
|
1081
|
-
|
|
1721
|
+
if (/^ipab:\/\/https?:\/\//i.test(reference))
|
|
1722
|
+
throw new HostError("Unencoded configuration URL in IPAB URI. Percent-encode the entire configuration URL and each Name path segment separately, or copy the reference from ipab search.");
|
|
1723
|
+
const match = /^ipab:\/\/([^/]*)\/(.*)$/is.exec(reference);
|
|
1082
1724
|
if (!match)
|
|
1083
1725
|
throw new HostError("Invalid IPAB URI; percent-encode the configuration URL authority and each path segment.");
|
|
1084
|
-
const authority =
|
|
1085
|
-
if (authority && !/^[A-Za-z0-9][A-Za-z0-9._-]*$/.test(authority))
|
|
1726
|
+
const authority = decodeNameComponent(match[1], "authority");
|
|
1727
|
+
if (authority && !/^[A-Za-z0-9][A-Za-z0-9._-]*$/.test(authority)) {
|
|
1728
|
+
if (!/^https?:\/\//i.test(authority))
|
|
1729
|
+
throw new HostError("Invalid IPAB URI authority; use a registered alias or the percent-encoded configuration URL.");
|
|
1086
1730
|
canonicalSwarmUrl(authority);
|
|
1731
|
+
}
|
|
1732
|
+
if (/[?#\s]/.test(match[2]))
|
|
1733
|
+
throw new HostError("Invalid IPAB URI path; percent-encode each Name path segment. Queries and fragments are not supported.");
|
|
1087
1734
|
const segments = match[2].split("/").map((segment) => {
|
|
1088
|
-
const decoded =
|
|
1089
|
-
if (decoded
|
|
1090
|
-
throw new HostError("
|
|
1735
|
+
const decoded = decodeNameComponent(segment, "path");
|
|
1736
|
+
if (/[/\\]/.test(decoded))
|
|
1737
|
+
throw new HostError("Invalid IPAB URI path separator; use literal / between Name segments, never an encoded slash or backslash.");
|
|
1091
1738
|
return decoded;
|
|
1092
1739
|
});
|
|
1093
|
-
|
|
1094
|
-
|
|
1095
|
-
|
|
1096
|
-
|
|
1740
|
+
try {
|
|
1741
|
+
return {
|
|
1742
|
+
...(authority ? { swarm: authority } : {}),
|
|
1743
|
+
name: formalName(segments.join("/")),
|
|
1744
|
+
};
|
|
1745
|
+
}
|
|
1746
|
+
catch (error) {
|
|
1747
|
+
if (!(error instanceof HostError))
|
|
1748
|
+
throw error;
|
|
1749
|
+
throw new HostError("Invalid IPAB URI path; use a safe relative Name of at most 256 characters without empty, . or .. segments.", error.exitCode, error.code, error.phase);
|
|
1750
|
+
}
|
|
1097
1751
|
}
|
|
1098
|
-
function
|
|
1752
|
+
export function formatNameReference(swarm, name) {
|
|
1099
1753
|
const segment = (value) => encodeURIComponent(value).replace(/[!'()*]/g, (char) => `%${char.charCodeAt(0).toString(16).toUpperCase()}`);
|
|
1100
|
-
return `ipab://${segment(
|
|
1754
|
+
return `ipab://${segment(swarm)}/${name.split("/").map(segment).join("/")}`;
|
|
1101
1755
|
}
|
|
1102
|
-
export async function resolveReference(context, reference, swarm, local, raw = false) {
|
|
1756
|
+
export async function resolveReference(context, reference, swarm, local, raw = false, mode = "active") {
|
|
1103
1757
|
const shared = parseNameReference(reference);
|
|
1104
1758
|
let targetCid;
|
|
1105
1759
|
if (shared) {
|
|
@@ -1108,7 +1762,8 @@ export async function resolveReference(context, reference, swarm, local, raw = f
|
|
|
1108
1762
|
: swarm;
|
|
1109
1763
|
if (!selected)
|
|
1110
1764
|
throw new HostError("Select a configuration URL/alias using --swarm or swarm use.");
|
|
1111
|
-
|
|
1765
|
+
const warm = mode === "local-first" ? await localHeader(context, selected) : undefined;
|
|
1766
|
+
let header = warm?.header ?? (await swarmHeader(context, selected));
|
|
1112
1767
|
let link = Object.hasOwn(header.snapshot.names, shared.name)
|
|
1113
1768
|
? header.snapshot.names[shared.name]
|
|
1114
1769
|
: undefined;
|
|
@@ -1120,6 +1775,8 @@ export async function resolveReference(context, reference, swarm, local, raw = f
|
|
|
1120
1775
|
}
|
|
1121
1776
|
if (!link)
|
|
1122
1777
|
throw new HostError(`Formal Name "${shared.name}" was not found after refreshing HEAD.`);
|
|
1778
|
+
if (warm && header === warm.header && !header.localSourceReady)
|
|
1779
|
+
await lazyPrivateSource(context, selected, warm.account, header.config);
|
|
1123
1780
|
targetCid = link.toString();
|
|
1124
1781
|
}
|
|
1125
1782
|
else {
|
|
@@ -1127,22 +1784,148 @@ export async function resolveReference(context, reference, swarm, local, raw = f
|
|
|
1127
1784
|
await readyMembership(context, swarm);
|
|
1128
1785
|
targetCid = local(reference);
|
|
1129
1786
|
}
|
|
1787
|
+
const cid = raw ? targetCid : await artifactValue(context.store, targetCid);
|
|
1788
|
+
return { targetCid, cid };
|
|
1789
|
+
}
|
|
1790
|
+
async function artifactValue(store, targetCid) {
|
|
1130
1791
|
let cid = targetCid;
|
|
1131
1792
|
const visited = new Set();
|
|
1132
|
-
for (let depth = 0
|
|
1793
|
+
for (let depth = 0;; depth++) {
|
|
1133
1794
|
if (depth >= 64 || visited.has(cid))
|
|
1134
1795
|
throw new HostError("Artifact resolution exceeds limits or contains a cycle.");
|
|
1135
1796
|
visited.add(cid);
|
|
1136
1797
|
const bundle = await openBundle(CID.parse(cid), {
|
|
1137
|
-
resolveCid: (cid) =>
|
|
1798
|
+
resolveCid: (cid) => store.block.get(cid.toString()),
|
|
1138
1799
|
});
|
|
1139
1800
|
if (bundle.schemaKey !== (await encodeSchema(artifactType)).cid.toString())
|
|
1140
1801
|
break;
|
|
1141
|
-
cid = CID.parse(parseArtifact(await typedJson(
|
|
1802
|
+
cid = CID.parse(parseArtifact(await typedJson(store, cid, artifactType)).value)
|
|
1142
1803
|
.toV1()
|
|
1143
1804
|
.toString();
|
|
1144
1805
|
}
|
|
1145
|
-
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;
|
|
1146
1929
|
}
|
|
1147
1930
|
export async function searchNames(context, query, swarms) {
|
|
1148
1931
|
if (!query ||
|
|
@@ -1152,7 +1935,8 @@ export async function searchNames(context, query, swarms) {
|
|
|
1152
1935
|
const matches = [];
|
|
1153
1936
|
const searched = [];
|
|
1154
1937
|
for (const swarm of swarms) {
|
|
1155
|
-
const header = await
|
|
1938
|
+
const header = (await localHeader(context, swarm.cid))?.header ??
|
|
1939
|
+
(await swarmHeader(context, swarm.cid, context.forceRefresh, "local-first"));
|
|
1156
1940
|
searched.push({
|
|
1157
1941
|
configUrl: swarm.cid,
|
|
1158
1942
|
source: header.source,
|
|
@@ -1160,18 +1944,96 @@ export async function searchNames(context, query, swarms) {
|
|
|
1160
1944
|
valueCid: header.head.cid,
|
|
1161
1945
|
verifiedAt: header.verifiedAt,
|
|
1162
1946
|
});
|
|
1163
|
-
for (const name of
|
|
1164
|
-
|
|
1165
|
-
|
|
1166
|
-
|
|
1167
|
-
|
|
1168
|
-
|
|
1169
|
-
|
|
1170
|
-
|
|
1171
|
-
});
|
|
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
|
+
});
|
|
1172
1955
|
}
|
|
1173
1956
|
return { matches, swarms: searched };
|
|
1174
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
|
+
}
|
|
1175
2037
|
async function dependencies(store, root, found = new Set()) {
|
|
1176
2038
|
if (found.has(root))
|
|
1177
2039
|
return found;
|
|
@@ -1206,9 +2068,11 @@ export async function frozenPublicationClosure(store, root) {
|
|
|
1206
2068
|
throw new HostError("Frozen publication history exceeds limits or contains a cycle.");
|
|
1207
2069
|
publications.add(current);
|
|
1208
2070
|
const publication = await readPublication(store, current);
|
|
1209
|
-
const snapshot =
|
|
2071
|
+
const snapshot = await readState(store, publication.state);
|
|
1210
2072
|
for (const target of Object.values(snapshot.names))
|
|
1211
2073
|
await dependencies(store, target.toString(), content);
|
|
2074
|
+
for (const association of Object.values(snapshot.registrations ?? {}))
|
|
2075
|
+
await dependencies(store, association.appCid.toString(), content);
|
|
1212
2076
|
current = publication.previous?.toString();
|
|
1213
2077
|
}
|
|
1214
2078
|
return [
|
|
@@ -1223,13 +2087,8 @@ export async function publish(context, content, options) {
|
|
|
1223
2087
|
throw new HostError("Publication requires a selected Swarm configuration URL or alias.");
|
|
1224
2088
|
const head = await pointer(context, options.swarm);
|
|
1225
2089
|
const roots = await dependencies(context.store, content);
|
|
1226
|
-
|
|
1227
|
-
|
|
1228
|
-
throw new HostError("--expect/--snapshot require --name.");
|
|
1229
|
-
await head.read();
|
|
1230
|
-
await provideContent(context.store, [...roots], context.node.api, context.fetch, context.node.auth);
|
|
1231
|
-
return content;
|
|
1232
|
-
}
|
|
2090
|
+
const currentRoots = [...(await currentDependencies(context.store, content))];
|
|
2091
|
+
await withStateAsync(context, (state) => pinCid(state, content, context.store, currentRoots));
|
|
1233
2092
|
const name = formalName(options.name);
|
|
1234
2093
|
if (options.snapshot && options.expect)
|
|
1235
2094
|
throw new HostError("Snapshots cannot replace an occupied Name.");
|
|
@@ -1254,23 +2113,30 @@ export async function publish(context, content, options) {
|
|
|
1254
2113
|
if ((Object.hasOwn(current.names, name)
|
|
1255
2114
|
? current.names[name]?.toString()
|
|
1256
2115
|
: undefined) !== expected)
|
|
1257
|
-
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");
|
|
1258
2117
|
const next = await publication(context.store, await writeSnapshot(context.store, {
|
|
1259
2118
|
...current,
|
|
1260
2119
|
names: { ...current.names, [name]: CID.parse(candidate) },
|
|
1261
2120
|
}), currentHead.root);
|
|
1262
|
-
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) : [])]);
|
|
1263
2122
|
withState(context, (state) => {
|
|
1264
2123
|
state.invalidateSwarmHeader(options.swarm);
|
|
1265
2124
|
});
|
|
1266
2125
|
try {
|
|
1267
2126
|
await head.write(next, currentHead.cid, uniqueId());
|
|
1268
|
-
return candidate;
|
|
1269
2127
|
}
|
|
1270
2128
|
catch (cause) {
|
|
1271
2129
|
if (!(cause instanceof ScopeApiError) || cause.status !== 412)
|
|
1272
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");
|
|
1273
2138
|
}
|
|
2139
|
+
return candidate;
|
|
1274
2140
|
}
|
|
1275
2141
|
throw new HostError(`HEAD is busy; candidate ${candidate} remains retained.`);
|
|
1276
2142
|
}
|