@ipab/cli 0.1.0-rc.1 → 0.1.0-rc.10

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.
Files changed (285) hide show
  1. package/README.md +226 -9
  2. package/dist/app-authoring.d.ts +15 -0
  3. package/dist/app-authoring.d.ts.map +1 -1
  4. package/dist/app-authoring.js +144 -58
  5. package/dist/app-authoring.js.map +1 -1
  6. package/dist/app-definition.d.ts +52 -57
  7. package/dist/app-definition.d.ts.map +1 -1
  8. package/dist/app-definition.js +33 -38
  9. package/dist/app-definition.js.map +1 -1
  10. package/dist/app-prebuild.d.ts +18 -0
  11. package/dist/app-prebuild.d.ts.map +1 -1
  12. package/dist/app-prebuild.js +46 -0
  13. package/dist/app-prebuild.js.map +1 -1
  14. package/dist/app-templates.d.ts +0 -1
  15. package/dist/app-templates.d.ts.map +1 -1
  16. package/dist/app-templates.js +8 -46
  17. package/dist/app-templates.js.map +1 -1
  18. package/dist/assembly.d.ts +7 -0
  19. package/dist/assembly.d.ts.map +1 -0
  20. package/dist/assembly.js +130 -0
  21. package/dist/assembly.js.map +1 -0
  22. package/dist/authoring.d.ts +4 -8
  23. package/dist/authoring.d.ts.map +1 -1
  24. package/dist/authoring.js +25 -15
  25. package/dist/authoring.js.map +1 -1
  26. package/dist/builtins/skill.ipab.car +0 -0
  27. package/dist/builtins/template.bundle-viewer.car +0 -0
  28. package/dist/builtins/template.check.car +0 -0
  29. package/dist/builtins/template.node.car +0 -0
  30. package/dist/builtins/template.web-app.car +0 -0
  31. package/dist/builtins.d.ts.map +1 -1
  32. package/dist/builtins.js +1 -23
  33. package/dist/builtins.js.map +1 -1
  34. package/dist/bundled-skills.d.ts +14 -0
  35. package/dist/bundled-skills.d.ts.map +1 -0
  36. package/dist/bundled-skills.js +34 -0
  37. package/dist/bundled-skills.js.map +1 -0
  38. package/dist/cli.d.ts +8 -2
  39. package/dist/cli.d.ts.map +1 -1
  40. package/dist/cli.js +1919 -256
  41. package/dist/cli.js.map +1 -1
  42. package/dist/config-secret.d.ts +3 -0
  43. package/dist/config-secret.d.ts.map +1 -0
  44. package/dist/config-secret.js +12 -0
  45. package/dist/config-secret.js.map +1 -0
  46. package/dist/config.d.ts +7 -2
  47. package/dist/config.d.ts.map +1 -1
  48. package/dist/config.js +151 -8
  49. package/dist/config.js.map +1 -1
  50. package/dist/content-provider.d.ts +32 -0
  51. package/dist/content-provider.d.ts.map +1 -0
  52. package/dist/content-provider.js +222 -0
  53. package/dist/content-provider.js.map +1 -0
  54. package/dist/context-types.d.ts +12 -0
  55. package/dist/context-types.d.ts.map +1 -0
  56. package/dist/context-types.js +2 -0
  57. package/dist/context-types.js.map +1 -0
  58. package/dist/context.d.ts +26 -1
  59. package/dist/context.d.ts.map +1 -1
  60. package/dist/context.js +54 -10
  61. package/dist/context.js.map +1 -1
  62. package/dist/daemon-ui.d.ts +93 -0
  63. package/dist/daemon-ui.d.ts.map +1 -0
  64. package/dist/daemon-ui.js +713 -0
  65. package/dist/daemon-ui.js.map +1 -0
  66. package/dist/daemon.d.ts +21 -0
  67. package/dist/daemon.d.ts.map +1 -0
  68. package/dist/daemon.js +317 -0
  69. package/dist/daemon.js.map +1 -0
  70. package/dist/doctor.d.ts +32 -0
  71. package/dist/doctor.d.ts.map +1 -0
  72. package/dist/doctor.js +684 -0
  73. package/dist/doctor.js.map +1 -0
  74. package/dist/errors.d.ts +1 -8
  75. package/dist/errors.d.ts.map +1 -1
  76. package/dist/errors.js +1 -20
  77. package/dist/errors.js.map +1 -1
  78. package/dist/get.d.ts +3 -0
  79. package/dist/get.d.ts.map +1 -0
  80. package/dist/get.js +80 -0
  81. package/dist/get.js.map +1 -0
  82. package/dist/history.d.ts.map +1 -1
  83. package/dist/history.js +6 -14
  84. package/dist/history.js.map +1 -1
  85. package/dist/host-error.d.ts +9 -0
  86. package/dist/host-error.d.ts.map +1 -0
  87. package/dist/host-error.js +21 -0
  88. package/dist/host-error.js.map +1 -0
  89. package/dist/identity.d.ts +16 -0
  90. package/dist/identity.d.ts.map +1 -0
  91. package/dist/identity.js +119 -0
  92. package/dist/identity.js.map +1 -0
  93. package/dist/ipc.d.ts +5 -2
  94. package/dist/ipc.d.ts.map +1 -1
  95. package/dist/ipc.js +124 -12
  96. package/dist/ipc.js.map +1 -1
  97. package/dist/kubo-install.d.ts +26 -0
  98. package/dist/kubo-install.d.ts.map +1 -0
  99. package/dist/kubo-install.js +724 -0
  100. package/dist/kubo-install.js.map +1 -0
  101. package/dist/kubo-peering.d.ts +11 -0
  102. package/dist/kubo-peering.d.ts.map +1 -0
  103. package/dist/kubo-peering.js +93 -0
  104. package/dist/kubo-peering.js.map +1 -0
  105. package/dist/kubo-peers.d.ts +12 -0
  106. package/dist/kubo-peers.d.ts.map +1 -0
  107. package/dist/kubo-peers.js +119 -0
  108. package/dist/kubo-peers.js.map +1 -0
  109. package/dist/kubo-release.d.ts +22 -0
  110. package/dist/kubo-release.d.ts.map +1 -0
  111. package/dist/kubo-release.js +176 -0
  112. package/dist/kubo-release.js.map +1 -0
  113. package/dist/kubo-topology.d.ts +19 -0
  114. package/dist/kubo-topology.d.ts.map +1 -0
  115. package/dist/kubo-topology.js +113 -0
  116. package/dist/kubo-topology.js.map +1 -0
  117. package/dist/kubo.d.ts +85 -0
  118. package/dist/kubo.d.ts.map +1 -0
  119. package/dist/kubo.js +755 -0
  120. package/dist/kubo.js.map +1 -0
  121. package/dist/pins.d.ts +16 -18
  122. package/dist/pins.d.ts.map +1 -1
  123. package/dist/pins.js +144 -106
  124. package/dist/pins.js.map +1 -1
  125. package/dist/pivot-rpc.d.ts +62 -0
  126. package/dist/pivot-rpc.d.ts.map +1 -0
  127. package/dist/pivot-rpc.js +407 -0
  128. package/dist/pivot-rpc.js.map +1 -0
  129. package/dist/pivot-service.d.ts +16 -0
  130. package/dist/pivot-service.d.ts.map +1 -0
  131. package/dist/pivot-service.js +50 -0
  132. package/dist/pivot-service.js.map +1 -0
  133. package/dist/publish-source.d.ts +3 -0
  134. package/dist/publish-source.d.ts.map +1 -0
  135. package/dist/publish-source.js +85 -0
  136. package/dist/publish-source.js.map +1 -0
  137. package/dist/runtime.d.ts +2 -0
  138. package/dist/runtime.d.ts.map +1 -1
  139. package/dist/runtime.js +9 -4
  140. package/dist/runtime.js.map +1 -1
  141. package/dist/search-index.d.ts +64 -0
  142. package/dist/search-index.d.ts.map +1 -0
  143. package/dist/search-index.js +409 -0
  144. package/dist/search-index.js.map +1 -0
  145. package/dist/search-service.d.ts +23 -0
  146. package/dist/search-service.d.ts.map +1 -0
  147. package/dist/search-service.js +116 -0
  148. package/dist/search-service.js.map +1 -0
  149. package/dist/skill-definition.d.ts +6 -0
  150. package/dist/skill-definition.d.ts.map +1 -0
  151. package/dist/skill-definition.js +38 -0
  152. package/dist/skill-definition.js.map +1 -0
  153. package/dist/skill-source.d.ts +9 -0
  154. package/dist/skill-source.d.ts.map +1 -0
  155. package/dist/skill-source.js +24 -0
  156. package/dist/skill-source.js.map +1 -0
  157. package/dist/skills.d.ts +104 -0
  158. package/dist/skills.d.ts.map +1 -0
  159. package/dist/skills.js +894 -0
  160. package/dist/skills.js.map +1 -0
  161. package/dist/source-bundle.d.ts +3 -8
  162. package/dist/source-bundle.d.ts.map +1 -1
  163. package/dist/source-bundle.js +17 -12
  164. package/dist/source-bundle.js.map +1 -1
  165. package/dist/space-path.d.ts +3 -0
  166. package/dist/space-path.d.ts.map +1 -0
  167. package/dist/space-path.js +17 -0
  168. package/dist/space-path.js.map +1 -0
  169. package/dist/space.d.ts +16 -4
  170. package/dist/space.d.ts.map +1 -1
  171. package/dist/space.js +170 -24
  172. package/dist/space.js.map +1 -1
  173. package/dist/state-storage-windows.d.ts +2 -0
  174. package/dist/state-storage-windows.d.ts.map +1 -0
  175. package/dist/state-storage-windows.js +114 -0
  176. package/dist/state-storage-windows.js.map +1 -0
  177. package/dist/state-storage.d.ts +5 -0
  178. package/dist/state-storage.d.ts.map +1 -0
  179. package/dist/state-storage.js +333 -0
  180. package/dist/state-storage.js.map +1 -0
  181. package/dist/state.d.ts +115 -13
  182. package/dist/state.d.ts.map +1 -1
  183. package/dist/state.js +492 -91
  184. package/dist/state.js.map +1 -1
  185. package/dist/swarm-envelope.d.ts +57 -0
  186. package/dist/swarm-envelope.d.ts.map +1 -0
  187. package/dist/swarm-envelope.js +299 -0
  188. package/dist/swarm-envelope.js.map +1 -0
  189. package/dist/swarm-files.d.ts +6 -0
  190. package/dist/swarm-files.d.ts.map +1 -0
  191. package/dist/swarm-files.js +116 -0
  192. package/dist/swarm-files.js.map +1 -0
  193. package/dist/swarm-meta.d.ts +15 -0
  194. package/dist/swarm-meta.d.ts.map +1 -0
  195. package/dist/swarm-meta.js +68 -0
  196. package/dist/swarm-meta.js.map +1 -0
  197. package/dist/swarm-observations.d.ts +40 -0
  198. package/dist/swarm-observations.d.ts.map +1 -0
  199. package/dist/swarm-observations.js +271 -0
  200. package/dist/swarm-observations.js.map +1 -0
  201. package/dist/swarm.d.ts +469 -0
  202. package/dist/swarm.d.ts.map +1 -0
  203. package/dist/swarm.js +4708 -0
  204. package/dist/swarm.js.map +1 -0
  205. package/dist/template-definition.d.ts +47 -52
  206. package/dist/template-definition.d.ts.map +1 -1
  207. package/dist/template-definition.js +36 -41
  208. package/dist/template-definition.js.map +1 -1
  209. package/dist/template-paths.d.ts +7 -0
  210. package/dist/template-paths.d.ts.map +1 -0
  211. package/dist/template-paths.js +23 -0
  212. package/dist/template-paths.js.map +1 -0
  213. package/dist/template-presentation.d.ts +20 -0
  214. package/dist/template-presentation.d.ts.map +1 -0
  215. package/dist/template-presentation.js +133 -0
  216. package/dist/template-presentation.js.map +1 -0
  217. package/dist/template-source.d.ts +4 -1
  218. package/dist/template-source.d.ts.map +1 -1
  219. package/dist/template-source.js +11 -4
  220. package/dist/template-source.js.map +1 -1
  221. package/dist/templates.d.ts +11 -0
  222. package/dist/templates.d.ts.map +1 -0
  223. package/dist/templates.js +53 -0
  224. package/dist/templates.js.map +1 -0
  225. package/dist/unixfs-tree.d.ts +67 -0
  226. package/dist/unixfs-tree.d.ts.map +1 -0
  227. package/dist/unixfs-tree.js +329 -0
  228. package/dist/unixfs-tree.js.map +1 -0
  229. package/package.json +14 -7
  230. package/src/app-authoring.ts +240 -76
  231. package/src/app-definition.ts +33 -39
  232. package/src/app-prebuild.ts +61 -0
  233. package/src/app-templates.ts +17 -73
  234. package/src/assembly.ts +185 -0
  235. package/src/authoring.ts +41 -17
  236. package/src/builtins.ts +2 -27
  237. package/src/bundled-skills.ts +60 -0
  238. package/src/cli.ts +2399 -320
  239. package/src/config-secret.ts +14 -0
  240. package/src/config.ts +196 -8
  241. package/src/content-provider.ts +299 -0
  242. package/src/context-types.ts +11 -0
  243. package/src/context.ts +98 -10
  244. package/src/daemon-ui.ts +812 -0
  245. package/src/daemon.ts +386 -0
  246. package/src/doctor.ts +1082 -0
  247. package/src/errors.ts +1 -25
  248. package/src/get.ts +90 -0
  249. package/src/history.ts +5 -15
  250. package/src/host-error.ts +26 -0
  251. package/src/identity.ts +175 -0
  252. package/src/ipc.ts +160 -11
  253. package/src/kubo-install.ts +936 -0
  254. package/src/kubo-peering.ts +126 -0
  255. package/src/kubo-peers.ts +144 -0
  256. package/src/kubo-release.ts +230 -0
  257. package/src/kubo-topology.ts +148 -0
  258. package/src/kubo.ts +1088 -0
  259. package/src/pins.ts +188 -126
  260. package/src/pivot-rpc.ts +601 -0
  261. package/src/pivot-service.ts +87 -0
  262. package/src/publish-source.ts +103 -0
  263. package/src/runtime.ts +16 -4
  264. package/src/search-index.ts +560 -0
  265. package/src/search-service.ts +152 -0
  266. package/src/skill-definition.ts +53 -0
  267. package/src/skill-source.ts +29 -0
  268. package/src/skills.ts +1236 -0
  269. package/src/source-bundle.ts +26 -13
  270. package/src/space-path.ts +30 -0
  271. package/src/space.ts +230 -42
  272. package/src/state-storage-windows.ts +134 -0
  273. package/src/state-storage.ts +378 -0
  274. package/src/state.ts +759 -107
  275. package/src/swarm-envelope.ts +461 -0
  276. package/src/swarm-files.ts +126 -0
  277. package/src/swarm-meta.ts +98 -0
  278. package/src/swarm-observations.ts +393 -0
  279. package/src/swarm.ts +7051 -0
  280. package/src/template-definition.ts +36 -41
  281. package/src/template-paths.ts +43 -0
  282. package/src/template-presentation.ts +151 -0
  283. package/src/template-source.ts +19 -5
  284. package/src/templates.ts +77 -0
  285. package/src/unixfs-tree.ts +401 -0
package/dist/swarm.js ADDED
@@ -0,0 +1,4708 @@
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";
5
+ import { setTimeout as delay } from "node:timers/promises";
6
+ import { createHash, randomBytes } from "node:crypto";
7
+ import { stringify } from "yaml";
8
+ import { CarBlockIterator } from "@ipld/car/iterator";
9
+ import * as dagCbor from "@ipld/dag-cbor";
10
+ import * as dagPb from "@ipld/dag-pb";
11
+ import { CID } from "multiformats/cid";
12
+ import { sha256 } from "multiformats/hashes/sha2";
13
+ import { ContentBundleError, encodeSchema, openBundle, } from "@ipab/bundle";
14
+ import { encodeBundleCar, memoryTree, streamChunks, } from "@ipab/bundle-builder";
15
+ import { ContentError, GatewayReadError, IpfsStore } from "@ipab/ipfs-store";
16
+ import { ScopeClient, ScopeApiError, RESOURCE_ID_PATTERN, issueScopeCertificate, signScopeWriteReceipt, uniqueId, verifyScopeCertificate, valueCid, parseVariableUpdate, } from "@ipab/bundle/pointer/scope";
17
+ import { canonicalService, isCanonicalPublicKey, POINTER_ID_PATTERN, } from "@ipab/bundle/pointer/protocol";
18
+ import { importPrivateKeyPkcs8, importPublicKeyRaw, keyId, signEd25519, verifyEd25519, } from "@ipab/bundle/pointer/crypto";
19
+ import { HostError, object, message } from "./errors.js";
20
+ import { accountIdentity, protectedPath, secureNew, } from "./identity.js";
21
+ import { nodeError } from "./authoring.js";
22
+ import { swarmUrl as canonicalSwarmUrl } from "./config.js";
23
+ import { bundleJson, contentCar, provideContent, provideShallowContent, } from "./content-provider.js";
24
+ import { deleteUnixfsPath, listUnixfsDirectory, resolveUnixfsPath, setUnixfsPath, walkUnixfsNames, } from "./unixfs-tree.js";
25
+ import { parsePublicationPins, pinPublication, } from "./pivot-service.js";
26
+ import { mountPivotServer, parsePivotReceiptRequest, requestPivotReceiptOverP2p, signPivotReceiptRequest, verifyPivotReceiptRequest, } from "./pivot-rpc.js";
27
+ import { failedPin, pinCid, refreshPinClaim, reservePin, retainPin, } from "./pins.js";
28
+ import { bytes, relativePath } from "./space.js";
29
+ import { appSchemaCid } from "./app-definition.js";
30
+ import { State, createAssociation, exactCid, } from "./state.js";
31
+ import { privateDirectory, readPrivate, withPrivateLock, writePrivate, } from "./swarm-files.js";
32
+ import { openApproval, openApprovalV2, sealApprovalV2, parseEnvelope, validateEncryptionIdentity, } from "./swarm-envelope.js";
33
+ import { checkCachedNode, kuboSource, peerId, pinAdd, pinRm, prepareNode, startNode, stopNode, probePeer, nodeConnections, validateAddress, } from "./kubo.js";
34
+ import { memberPeers } from "./kubo-peering.js";
35
+ import { PivotCandidates } from "./kubo-topology.js";
36
+ import { indexV7UnixfsSwarm, queryLocalSearchIndex, validateSearchParams, } from "./search-index.js";
37
+ import { queryRemotePivotSearch, rankPivotCandidates, } from "./search-service.js";
38
+ import { DaemonLogBuffer, emptySyncState, pivotReceiptProtocol, redactDaemonText, } from "./daemon-ui.js";
39
+ import { networkingBinding, pivotLocalStatus, readNetworkingSnapshot, writeNetworkingSnapshot, networkingAccount, } from "./swarm-observations.js";
40
+ import { seedTemplateNames, seedTemplateSource } from "./template-source.js";
41
+ import { inspectTemplate, templatePublicationSource } from "./templates.js";
42
+ import { seedSkillSource } from "./skill-source.js";
43
+ import { skillIdentity, skillSchema } from "./skill-definition.js";
44
+ import { parseSwarmMeta, swarmMetaType, swarmMetaSchema, swarmRootType, parseSwarmRootState, isSwarmRootSchema, swarmStateType, previousSwarmStateType, previousSwarmStateSchema, parseSwarmState, legacySwarmStateType, legacySwarmStateSchema, isSwarmStateSchema, legacySwarmMetaType, legacySwarmMetaSchema, } from "./swarm-meta.js";
45
+ function memberIsPivot(config, member, profile) {
46
+ return config.v === 3
47
+ ? member.role === "pivot" && profile.pivot !== false
48
+ : profile.pivot === true;
49
+ }
50
+ async function contextIdentity(context, initialize = false) {
51
+ context.identity ??= await accountIdentity(context.env, initialize);
52
+ return context.identity;
53
+ }
54
+ export async function inspectLocalMembership(input, account) {
55
+ const value = object(input, "local membership");
56
+ if (typeof value.configUrl !== "string" ||
57
+ !isCanonicalPublicKey(value.owner) ||
58
+ !isCanonicalPublicKey(value.account) ||
59
+ value.account !== account)
60
+ throw new HostError("Stored membership is inconsistent with HOME identity.");
61
+ const configUrl = canonicalSwarmUrl(value.configUrl);
62
+ if (configUrl !== value.configUrl)
63
+ throw new HostError("Noncanonical membership URL.");
64
+ let encryption;
65
+ if (value.encryption !== undefined) {
66
+ const rawEncryption = object(value.encryption, "encryption identity");
67
+ if (typeof rawEncryption.privateKey !== "string" ||
68
+ typeof rawEncryption.publicKey !== "string")
69
+ throw new HostError("Invalid encryption identity.");
70
+ encryption = {
71
+ privateKey: rawEncryption.privateKey,
72
+ publicKey: rawEncryption.publicKey,
73
+ };
74
+ validateEncryptionIdentity(encryption);
75
+ }
76
+ let peer;
77
+ if (value.request !== undefined) {
78
+ const rawRequest = object(value.request, "Request");
79
+ if (rawRequest.v === 1) {
80
+ if (!encryption)
81
+ throw new HostError("Legacy Request is missing encryption identity.");
82
+ const request = await verifyLegacyRequest(value.request);
83
+ if (request.configUrl !== configUrl ||
84
+ request.member !== account ||
85
+ request.owner !== value.owner ||
86
+ request.encryptionKey !== encryption.publicKey)
87
+ throw new HostError("Stored Request binding mismatch.");
88
+ peer = request.peerId;
89
+ }
90
+ else {
91
+ const request = await verifyRequest(value.request);
92
+ if (request.configUrl !== configUrl ||
93
+ request.member !== account ||
94
+ request.owner !== value.owner)
95
+ throw new HostError("Stored Request binding mismatch.");
96
+ peer = peerId(account);
97
+ }
98
+ }
99
+ const config = value.config === undefined
100
+ ? undefined
101
+ : parseOrganization(value.config, configUrl, false);
102
+ if (config && config.owner !== value.owner)
103
+ throw new HostError("Stored Owner binding mismatch.");
104
+ if (value.secret !== undefined) {
105
+ if (!config)
106
+ throw new HostError("Stored secret has no configuration binding.");
107
+ const member = config.members.find((member) => member.publicKey === account);
108
+ if (!member)
109
+ throw new HostError("Stored membership lacks its member binding.");
110
+ const record = value;
111
+ await validateMembershipSecret(record, config, member);
112
+ peer = member.peerId;
113
+ }
114
+ const c = coordinates(configUrl);
115
+ return { configUrl, scope: nodeScope(c.service, c.scopeId), peer };
116
+ }
117
+ const cidField = { type: "string", minLength: 1, maxLength: 128 };
118
+ export const artifactType = {
119
+ contentType: "application/json",
120
+ schema: {
121
+ type: "object",
122
+ additionalProperties: false,
123
+ required: ["value", "timestamp"],
124
+ properties: {
125
+ value: cidField,
126
+ previous: cidField,
127
+ timestamp: { type: "string", format: "date-time" },
128
+ },
129
+ },
130
+ };
131
+ function withState(context, operation) {
132
+ if (context.state)
133
+ return operation(context.state);
134
+ const state = new State(context.stateDir);
135
+ try {
136
+ return operation(state);
137
+ }
138
+ finally {
139
+ state.close();
140
+ }
141
+ }
142
+ export { canonicalSwarmUrl };
143
+ function coordinates(configUrl) {
144
+ const url = new URL(canonicalSwarmUrl(configUrl));
145
+ const [, , scopeId, configId] = url.pathname.split("/");
146
+ return { service: url.origin, scopeId: scopeId, configId: configId };
147
+ }
148
+ const localName = (url) => `${createHash("sha256").update(url).digest("hex")}.json`;
149
+ const nodeScope = (service, scopeId) => createHash("sha256").update(`${service}/v1/${scopeId}`).digest("hex");
150
+ async function directory(context) {
151
+ return privateDirectory(context.stateDir, "swarm-credentials");
152
+ }
153
+ async function local(context, configUrl) {
154
+ const value = await readPrivate(await directory(context), localName(configUrl));
155
+ const identity = await contextIdentity(context);
156
+ if (!value ||
157
+ value.configUrl !== configUrl ||
158
+ value.account !== identity.publicKey)
159
+ throw new HostError("No local Request for this configuration and HOME identity. Run swarm request with a trusted Owner fingerprint.");
160
+ return value;
161
+ }
162
+ async function saveLocal(context, membership) {
163
+ await writePrivate(await directory(context), localName(membership.configUrl), membership);
164
+ }
165
+ function client(context, service, identity, secret) {
166
+ return new ScopeClient({
167
+ service,
168
+ ...(identity
169
+ ? {
170
+ signer: {
171
+ ...identity,
172
+ ...(secret ? { certificate: secret.certificate } : {}),
173
+ },
174
+ }
175
+ : {}),
176
+ ...(context.fetch ? { fetch: context.fetch } : {}),
177
+ ...(context.pointerApiKey ? { apiKey: context.pointerApiKey } : {}),
178
+ });
179
+ }
180
+ function parseOrganization(value, configUrl, wire = true) {
181
+ const data = object(value, "organization configuration");
182
+ if (data.kind === "ipab-config-reservation")
183
+ throw new HostError("Swarm creation is initializing; the Owner must resume the saved creation operation.");
184
+ const { scopeId } = coordinates(configUrl);
185
+ if (Object.keys(data).sort().join() !==
186
+ "bootstrap,description,epoch,headId,members,name,owner,scopeId,v" ||
187
+ (data.v !== 1 && data.v !== 2 && data.v !== 3) ||
188
+ data.scopeId !== scopeId ||
189
+ !isCanonicalPublicKey(data.owner) ||
190
+ typeof data.name !== "string" ||
191
+ data.name.length > 256 ||
192
+ typeof data.description !== "string" ||
193
+ data.description.length > 2048 ||
194
+ typeof data.headId !== "string" ||
195
+ !RESOURCE_ID_PATTERN.test(data.headId) ||
196
+ typeof data.epoch !== "number" ||
197
+ !Number.isSafeInteger(data.epoch) ||
198
+ data.epoch < 1 ||
199
+ !Array.isArray(data.bootstrap) ||
200
+ data.bootstrap.length > 64 ||
201
+ !Array.isArray(data.members) ||
202
+ data.members.length < 1 ||
203
+ data.members.length > 256)
204
+ throw new HostError("Invalid Scope organization configuration.");
205
+ const identities = new Set(), peers = new Set(), profiles = new Set(), approvals = new Set();
206
+ const members = [];
207
+ for (const raw of data.members) {
208
+ const member = object(raw, "member");
209
+ if (data.v === 3) {
210
+ const isOwner = member.publicKey === data.owner;
211
+ const approvalId = member.approvalId === null
212
+ ? null
213
+ : typeof member.approvalId === "string"
214
+ ? member.approvalId
215
+ : undefined;
216
+ const role = member.role === "ordinary" || member.role === "pivot"
217
+ ? member.role
218
+ : undefined;
219
+ const keys = Object.keys(member).sort().join();
220
+ const validKeys = wire
221
+ ? keys === "approvalId,profileId,publicKey,role"
222
+ : keys === "approvalId,profileId,publicKey,role" ||
223
+ keys === "approvalId,peerId,profileId,publicKey,role";
224
+ if (!validKeys ||
225
+ !isCanonicalPublicKey(member.publicKey) ||
226
+ !role ||
227
+ typeof member.profileId !== "string" ||
228
+ !RESOURCE_ID_PATTERN.test(member.profileId) ||
229
+ approvalId === undefined ||
230
+ (isOwner
231
+ ? approvalId !== null
232
+ : approvalId === null ||
233
+ !RESOURCE_ID_PATTERN.test(approvalId) ||
234
+ approvals.has(approvalId)) ||
235
+ identities.has(member.publicKey) ||
236
+ profiles.has(member.profileId))
237
+ throw new HostError("Invalid or duplicate member/PeerID/profile binding.");
238
+ const derivedPeer = peerId(member.publicKey);
239
+ if (!wire && member.peerId !== undefined && member.peerId !== derivedPeer)
240
+ throw new HostError("Invalid or duplicate member/PeerID/profile binding.");
241
+ identities.add(member.publicKey);
242
+ peers.add(derivedPeer);
243
+ profiles.add(member.profileId);
244
+ if (approvalId !== null)
245
+ approvals.add(approvalId);
246
+ members.push({
247
+ publicKey: member.publicKey,
248
+ role,
249
+ peerId: derivedPeer,
250
+ profileId: member.profileId,
251
+ approvalId,
252
+ });
253
+ continue;
254
+ }
255
+ if (Object.keys(member)
256
+ .filter((key) => key !== "memberId" && key !== "pivotAuthority")
257
+ .sort()
258
+ .join() !==
259
+ "approval,encryptionKey,peerId,profileId,publicKey,requestId" ||
260
+ (member.memberId !== undefined &&
261
+ (typeof member.memberId !== "string" ||
262
+ !RESOURCE_ID_PATTERN.test(member.memberId))) ||
263
+ (member.pivotAuthority !== undefined &&
264
+ typeof member.pivotAuthority !== "boolean") ||
265
+ !isCanonicalPublicKey(member.publicKey) ||
266
+ typeof member.encryptionKey !== "string" ||
267
+ member.encryptionKey.length > 256 ||
268
+ typeof member.peerId !== "string" ||
269
+ typeof member.profileId !== "string" ||
270
+ !RESOURCE_ID_PATTERN.test(member.profileId) ||
271
+ typeof member.requestId !== "string" ||
272
+ !POINTER_ID_PATTERN.test(member.requestId) ||
273
+ identities.has(member.publicKey) ||
274
+ peers.has(member.peerId) ||
275
+ profiles.has(member.profileId))
276
+ throw new HostError("Invalid or duplicate member/PeerID/profile binding.");
277
+ identities.add(member.publicKey);
278
+ peers.add(member.peerId);
279
+ profiles.add(member.profileId);
280
+ members.push({
281
+ ...(typeof member.memberId === "string"
282
+ ? { memberId: member.memberId }
283
+ : {}),
284
+ ...(typeof member.pivotAuthority === "boolean"
285
+ ? { pivotAuthority: member.pivotAuthority }
286
+ : {}),
287
+ publicKey: member.publicKey,
288
+ encryptionKey: member.encryptionKey,
289
+ peerId: member.peerId,
290
+ profileId: member.profileId,
291
+ requestId: member.requestId,
292
+ approval: member.approval === null ? null : parseEnvelope(member.approval),
293
+ });
294
+ }
295
+ if (!identities.has(data.owner))
296
+ throw new HostError("Owner must remain an organization member.");
297
+ const bootstrap = [];
298
+ for (const address of data.bootstrap) {
299
+ if (typeof address !== "string")
300
+ throw new HostError("Invalid bootstrap address.");
301
+ validateAddress(address);
302
+ if (![...peers].some((peer) => address.endsWith(`/p2p/${peer}`)))
303
+ throw new HostError("Bootstrap address is not a member PeerID.");
304
+ bootstrap.push(address);
305
+ }
306
+ return {
307
+ v: data.v,
308
+ scopeId,
309
+ owner: data.owner,
310
+ name: data.name,
311
+ description: data.description,
312
+ headId: data.headId,
313
+ epoch: data.epoch,
314
+ bootstrap,
315
+ members,
316
+ };
317
+ }
318
+ function parseProfile(value, expectedPeer) {
319
+ const data = object(value, "member profile");
320
+ if (Object.keys(data).some((key) => ![
321
+ "addresses",
322
+ "name",
323
+ "description",
324
+ "updatedAt",
325
+ "pivot",
326
+ "publicationPin",
327
+ "publicationPins",
328
+ ].includes(key)) ||
329
+ (data.pivot !== undefined && typeof data.pivot !== "boolean") ||
330
+ typeof data.name !== "string" ||
331
+ data.name.length > 256 ||
332
+ (data.description !== undefined &&
333
+ (typeof data.description !== "string" ||
334
+ data.description.length > 2048)) ||
335
+ typeof data.updatedAt !== "string" ||
336
+ !Number.isFinite(Date.parse(data.updatedAt)) ||
337
+ !Array.isArray(data.addresses) ||
338
+ data.addresses.length > 16)
339
+ throw new HostError("Invalid public member profile.");
340
+ const addresses = [];
341
+ for (const address of data.addresses) {
342
+ if (typeof address !== "string")
343
+ throw new HostError("Invalid member address.");
344
+ validateAddress(address, expectedPeer);
345
+ addresses.push(address);
346
+ }
347
+ return {
348
+ name: data.name,
349
+ ...(typeof data.description === "string"
350
+ ? { description: data.description }
351
+ : {}),
352
+ addresses,
353
+ ...(typeof data.pivot === "boolean" ? { pivot: data.pivot } : {}),
354
+ ...parsePublicationPins(data),
355
+ updatedAt: data.updatedAt,
356
+ };
357
+ }
358
+ async function memberDirectory(context, url, config) {
359
+ const c = coordinates(url), api = client(context, c.service);
360
+ const members = await boundedMap(config.members, async (member) => {
361
+ const profile = parseProfile((await api.read(c.scopeId, member.profileId)).value, member.peerId);
362
+ return { member, profile };
363
+ });
364
+ return members;
365
+ }
366
+ async function localObservations(context, url, config) {
367
+ try {
368
+ const account = context.identity?.publicKey ??
369
+ (await networkingAccount(context.stateDir, url));
370
+ const self = config.members.find((member) => member.publicKey === account);
371
+ if (!self || !account)
372
+ throw new HostError("No bound local daemon observations; run ipab daemon after normal membership activation.");
373
+ const c = coordinates(url);
374
+ const local = await readNetworkingSnapshot(context.stateDir, url, networkingBinding(url, account, config), nodeScope(c.service, config.scopeId), config.epoch, self.peerId);
375
+ return {
376
+ account: context.identity?.publicKey ?? (local.snapshot ? account : undefined),
377
+ local,
378
+ };
379
+ }
380
+ catch (cause) {
381
+ return {
382
+ account: context.identity?.publicKey,
383
+ local: {
384
+ status: "unavailable",
385
+ updatedAt: null,
386
+ verifiedAt: null,
387
+ error: message(cause),
388
+ snapshot: null,
389
+ },
390
+ };
391
+ }
392
+ }
393
+ function observationSummary(local) {
394
+ return {
395
+ status: local.status,
396
+ updatedAt: local.updatedAt,
397
+ verifiedAt: local.verifiedAt,
398
+ error: local.error,
399
+ };
400
+ }
401
+ function parseInspection(input, url) {
402
+ const data = object(input, "Swarm inspection cache");
403
+ if (Object.keys(data).sort().join() !==
404
+ "config,configUrl,directory,head,updatedAt,v" ||
405
+ data.v !== 1 ||
406
+ data.configUrl !== url ||
407
+ typeof data.updatedAt !== "number" ||
408
+ !Number.isSafeInteger(data.updatedAt) ||
409
+ data.updatedAt < 0 ||
410
+ data.updatedAt > 8_640_000_000_000_000 ||
411
+ !Array.isArray(data.directory) ||
412
+ data.directory.length > 256)
413
+ throw new HostError("Invalid Swarm inspection cache; retry with --refresh.");
414
+ const config = parseOrganization(data.config, url, false);
415
+ if (config.members.some((member) => !/^[A-Za-z0-9]{32,128}$/.test(member.peerId)))
416
+ throw new HostError("Invalid cached member PeerID; use --refresh.");
417
+ if (data.directory.length !== config.members.length)
418
+ throw new HostError("Incomplete Swarm inspection directory; use --refresh.");
419
+ const directory = data.directory.map((input, index) => {
420
+ const entry = object(input, "cached directory entry");
421
+ const member = config.members[index];
422
+ if (Object.keys(entry).sort().join() !== "member,profile" ||
423
+ JSON.stringify(entry.member) !== JSON.stringify(member))
424
+ throw new HostError("Cached member binding mismatch; use --refresh.");
425
+ return { member, profile: parseProfile(entry.profile, member.peerId) };
426
+ });
427
+ const head = object(data.head, "cached HEAD");
428
+ if (!["cid,root", "cid,root,update"].includes(Object.keys(head).sort().join()) ||
429
+ typeof head.root !== "string" ||
430
+ typeof head.cid !== "string" ||
431
+ exactCid(head.root) !== head.root ||
432
+ exactCid(head.cid) !== head.cid)
433
+ throw new HostError("Invalid cached HEAD; use --refresh.");
434
+ return {
435
+ v: 1,
436
+ configUrl: url,
437
+ updatedAt: data.updatedAt,
438
+ config,
439
+ directory,
440
+ head: {
441
+ root: head.root,
442
+ cid: head.cid,
443
+ ...(head.update === undefined
444
+ ? {}
445
+ : {
446
+ update: parseVariableUpdate(head.update, {
447
+ scopeId: config.scopeId,
448
+ variableId: config.headId,
449
+ cid: head.cid,
450
+ }),
451
+ }),
452
+ },
453
+ };
454
+ }
455
+ async function inspection(context, url, refresh = false) {
456
+ canonicalSwarmUrl(url);
457
+ const parent = join(context.stateDir, "swarm-inspections");
458
+ const name = `${createHash("sha256").update(url).digest("hex")}.json`;
459
+ const saved = refresh
460
+ ? undefined
461
+ : await readPrivate(parent, name, [
462
+ { path: parent, directory: true },
463
+ ]);
464
+ let snapshot;
465
+ if (saved === undefined) {
466
+ snapshot = await withPrivateLock(await privateDirectory(context.stateDir, "swarm-inspections"), async () => {
467
+ const { config, variable } = await fetchConfig(context, url);
468
+ const directory = await memberDirectory(context, url, config);
469
+ const c = coordinates(url);
470
+ const head = headValue(await client(context, c.service).read(c.scopeId, config.headId));
471
+ const confirmed = await fetchConfig(context, url);
472
+ if (variable.cid !== confirmed.variable.cid ||
473
+ JSON.stringify(config) !== JSON.stringify(confirmed.config))
474
+ throw new HostError("Swarm configuration changed during inspection; retry --refresh.");
475
+ // Inspection persists only public declarations, never approval envelopes.
476
+ const publicConfig = config.v === 3
477
+ ? config
478
+ : {
479
+ ...config,
480
+ members: config.members.map((member) => ({
481
+ ...member,
482
+ approval: null,
483
+ })),
484
+ };
485
+ const fresh = parseInspection({
486
+ v: 1,
487
+ configUrl: url,
488
+ updatedAt: Date.now(),
489
+ config: publicConfig,
490
+ directory: directory.map(({ profile }, index) => ({
491
+ member: publicConfig.members[index],
492
+ profile,
493
+ })),
494
+ head: {
495
+ root: head.root,
496
+ cid: head.cid,
497
+ ...(head.update ? { update: head.update } : {}),
498
+ },
499
+ }, url);
500
+ if (Buffer.byteLength(JSON.stringify(fresh)) > 2 * 1024 * 1024)
501
+ throw new HostError("Swarm inspection snapshot is oversized.");
502
+ await writePrivate(parent, name, fresh);
503
+ return fresh;
504
+ });
505
+ }
506
+ else {
507
+ snapshot = parseInspection(saved, url);
508
+ }
509
+ const age = Date.now() - snapshot.updatedAt;
510
+ return {
511
+ ...snapshot,
512
+ cache: {
513
+ source: saved === undefined ? "network" : "cache",
514
+ updatedAt: new Date(snapshot.updatedAt).toISOString(),
515
+ freshness: age >= 0 && age < (context.cacheTtl ?? 300) * 1000
516
+ ? "current"
517
+ : "stale",
518
+ },
519
+ };
520
+ }
521
+ export async function swarmMembers(context, url, refresh = false) {
522
+ const { config, directory, cache } = await inspection(context, url, refresh);
523
+ const observations = await localObservations(context, url, config);
524
+ const members = directory.map(({ member, profile }) => {
525
+ const pivot = memberIsPivot(config, member, profile);
526
+ return {
527
+ publicKey: member.publicKey,
528
+ role: member.publicKey === config.owner ? "owner" : "member",
529
+ name: profile.name,
530
+ description: profile.description ?? "",
531
+ pivot,
532
+ localStatus: pivotLocalStatus(pivot, member.publicKey === observations.account, profile.addresses, member.peerId, observations.local),
533
+ peerId: member.peerId,
534
+ updatedAt: profile.updatedAt,
535
+ };
536
+ });
537
+ return {
538
+ configUrl: url,
539
+ members,
540
+ cache,
541
+ local: observationSummary(observations.local),
542
+ };
543
+ }
544
+ export async function swarmNetworking(context, url, config, directory) {
545
+ directory ??= (await inspection(context, url)).directory;
546
+ const { account, local } = await localObservations(context, url, config);
547
+ const saved = local.snapshot?.connections;
548
+ const observedAt = saved?.observedAt == null ? null : new Date(saved.observedAt).toISOString();
549
+ const connectionError = local.status !== "current"
550
+ ? (local.error ?? "Daemon observations are not current.")
551
+ : saved === undefined || saved.observedAt === null
552
+ ? "No daemon connection snapshot; run ipab daemon."
553
+ : saved.error;
554
+ const connections = saved?.peers ?? [];
555
+ const freshness = connectionError || !saved?.observedAt
556
+ ? observedAt
557
+ ? "stale"
558
+ : "unavailable"
559
+ : Date.now() - saved.observedAt > 90_000
560
+ ? "stale"
561
+ : "current";
562
+ const currentConnections = freshness === "current";
563
+ return {
564
+ daemon: observationSummary(local),
565
+ connections: {
566
+ observedAt,
567
+ error: connectionError,
568
+ peers: connections,
569
+ freshness,
570
+ },
571
+ pivots: directory
572
+ .filter(({ member, profile }) => memberIsPivot(config, member, profile))
573
+ .map(({ member, profile }) => {
574
+ const localStatus = pivotLocalStatus(true, member.publicKey === account, profile.addresses, member.peerId, local);
575
+ const observation = local.snapshot?.pivots.find((entry) => entry.peerId === member.peerId);
576
+ const matching = observation &&
577
+ JSON.stringify(observation.addresses) ===
578
+ JSON.stringify([...new Set(profile.addresses)].sort());
579
+ const current = local.status === "current" && matching;
580
+ const actual = connections.filter((entry) => entry.peerId === member.peerId);
581
+ const probeFreshness = matching && observation.probedAt !== null
582
+ ? current && Date.now() - observation.probedAt <= 90_000
583
+ ? "current"
584
+ : "stale"
585
+ : "unavailable";
586
+ const connectionStatus = member.publicKey === account
587
+ ? "self"
588
+ : !currentConnections
589
+ ? "unknown"
590
+ : actual.some((entry) => entry.transport === "direct")
591
+ ? "direct"
592
+ : actual.length
593
+ ? "relay"
594
+ : "disconnected";
595
+ return {
596
+ publicKey: member.publicKey,
597
+ name: profile.name,
598
+ peerId: member.peerId,
599
+ pivot: true,
600
+ addresses: profile.addresses,
601
+ localStatus,
602
+ selected: localStatus === "unknown" ? null : localStatus === "selected",
603
+ failures: matching ? observation.failures : null,
604
+ retryAt: matching && observation.retryAt > 0
605
+ ? new Date(observation.retryAt).toISOString()
606
+ : null,
607
+ probe: {
608
+ result: matching ? observation.probe : "unknown",
609
+ at: matching && observation.probedAt !== null
610
+ ? new Date(observation.probedAt).toISOString()
611
+ : null,
612
+ error: matching ? observation.error : null,
613
+ freshness: probeFreshness,
614
+ },
615
+ connection: {
616
+ status: connectionStatus,
617
+ observedAt,
618
+ error: connectionError,
619
+ freshness,
620
+ addresses: actual.map((entry) => entry.address),
621
+ },
622
+ };
623
+ }),
624
+ };
625
+ }
626
+ export async function inspectSwarmStatus(context, url, refresh = false) {
627
+ const { config, directory, head, cache } = await inspection(context, url, refresh);
628
+ const writer = directory.find(({ member }) => member.publicKey === head.update?.subject);
629
+ return {
630
+ config,
631
+ head,
632
+ lastWriter: head.update
633
+ ? {
634
+ ...head.update,
635
+ name: writer?.profile.name ?? null,
636
+ peerId: writer?.member.peerId ?? null,
637
+ }
638
+ : null,
639
+ cache,
640
+ state: {
641
+ status: "unavailable",
642
+ error: "State content is not fetched or verified by inspection; use get ipab:/// to obtain the State Bundle.",
643
+ },
644
+ networking: await swarmNetworking(context, url, config, directory),
645
+ };
646
+ }
647
+ function accountProfileLocation(context, publicKey) {
648
+ return {
649
+ parent: join(resolve(context.env.HOME ?? context.env.USERPROFILE ?? homedir()), ".ipab"),
650
+ name: `${createHash("sha256").update(publicKey).digest("hex")}.json`,
651
+ };
652
+ }
653
+ async function storedAccountProfile(context) {
654
+ const identity = await contextIdentity(context);
655
+ const { parent, name } = accountProfileLocation(context, identity.publicKey);
656
+ try {
657
+ await lstat(join(parent, "profiles"));
658
+ }
659
+ catch (cause) {
660
+ if (nodeError(cause, "ENOENT"))
661
+ return undefined;
662
+ throw cause;
663
+ }
664
+ await protectedPath(parent, true);
665
+ await protectedPath(join(parent, "profiles"), true);
666
+ const value = await readPrivate(join(parent, "profiles"), name);
667
+ if (value === undefined)
668
+ return undefined;
669
+ const data = object(value, "account profile");
670
+ if (Object.keys(data).sort().join() !==
671
+ "description,name,publicKey,updatedAt" ||
672
+ data.publicKey !== identity.publicKey ||
673
+ typeof data.name !== "string" ||
674
+ data.name.length > 256 ||
675
+ typeof data.description !== "string" ||
676
+ data.description.length > 2048 ||
677
+ typeof data.updatedAt !== "string" ||
678
+ !Number.isFinite(Date.parse(data.updatedAt)))
679
+ throw new HostError("Invalid protected account profile; restore the existing profile file.");
680
+ return {
681
+ publicKey: identity.publicKey,
682
+ name: data.name,
683
+ description: data.description,
684
+ updatedAt: data.updatedAt,
685
+ };
686
+ }
687
+ async function accountProfileDirectory(context, publicKey) {
688
+ const { parent } = accountProfileLocation(context, publicKey);
689
+ try {
690
+ await lstat(parent);
691
+ }
692
+ catch (cause) {
693
+ if (!nodeError(cause, "ENOENT"))
694
+ throw cause;
695
+ await mkdir(parent, { mode: 0o700 });
696
+ await secureNew(parent, true);
697
+ }
698
+ await protectedPath(parent, true);
699
+ return privateDirectory(parent, "profiles");
700
+ }
701
+ async function initialAccountProfile(context, changes = {}) {
702
+ const identity = await contextIdentity(context);
703
+ if (changes.name !== undefined && changes.description !== undefined)
704
+ return {
705
+ publicKey: identity.publicKey,
706
+ name: changes.name,
707
+ description: changes.description,
708
+ updatedAt: null,
709
+ };
710
+ const legacy = [];
711
+ for (const entry of withState(context, (state) => state.swarms())) {
712
+ const { config } = await fetchConfig(context, entry.cid);
713
+ const self = config.members.find((member) => member.publicKey === identity.publicKey);
714
+ if (!self)
715
+ continue; // Pending requests have no public profile yet.
716
+ const c = coordinates(entry.cid);
717
+ legacy.push(parseProfile((await client(context, c.service).read(c.scopeId, self.profileId))
718
+ .value, self.peerId));
719
+ }
720
+ const field = (key) => {
721
+ if (changes[key] !== undefined)
722
+ return changes[key];
723
+ const values = new Set(legacy.map((profile) => profile[key] ?? ""));
724
+ if (values.size > 1)
725
+ 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.`);
726
+ return values.values().next().value ?? "";
727
+ };
728
+ return {
729
+ publicKey: identity.publicKey,
730
+ name: field("name"),
731
+ description: field("description"),
732
+ updatedAt: null,
733
+ };
734
+ }
735
+ export async function accountProfile(context) {
736
+ return ((await storedAccountProfile(context)) ??
737
+ (await initialAccountProfile(context)));
738
+ }
739
+ async function ensureAccountProfile(context, changes = {}) {
740
+ const identity = await contextIdentity(context);
741
+ const dir = await accountProfileDirectory(context, identity.publicKey);
742
+ return withPrivateLock(dir, async () => {
743
+ const existing = await storedAccountProfile(context);
744
+ if (existing &&
745
+ changes.name === undefined &&
746
+ changes.description === undefined)
747
+ return existing;
748
+ const profile = {
749
+ ...(existing ?? (await initialAccountProfile(context, changes))),
750
+ ...changes,
751
+ updatedAt: new Date().toISOString(),
752
+ };
753
+ await writePrivate(dir, accountProfileLocation(context, identity.publicKey).name, profile);
754
+ return profile;
755
+ });
756
+ }
757
+ async function syncAccountProfile(context, record, personal, fetched) {
758
+ const identity = await contextIdentity(context), c = coordinates(record.configUrl);
759
+ const self = record.config.members.find((member) => member.publicKey === identity.publicKey);
760
+ const api = client(context, c.service, identity, identity.publicKey === record.owner ? undefined : record.secret);
761
+ let existing = fetched;
762
+ if (!existing) {
763
+ const variable = await api.read(c.scopeId, self.profileId);
764
+ existing = {
765
+ profile: parseProfile(variable.value, self.peerId),
766
+ cid: variable.cid,
767
+ };
768
+ }
769
+ const old = existing.profile;
770
+ if (old.name === personal.name && old.description === personal.description)
771
+ return old;
772
+ const profile = {
773
+ ...old,
774
+ name: personal.name,
775
+ description: personal.description,
776
+ updatedAt: new Date().toISOString(),
777
+ };
778
+ await api.write(c.scopeId, self.profileId, profile, existing.cid, uniqueId());
779
+ return profile;
780
+ }
781
+ export async function updateAccountProfile(context, changes) {
782
+ if ((changes.name?.length ?? 0) > 256 ||
783
+ (changes.description?.length ?? 0) > 2048)
784
+ throw new HostError("Profile name/description limit exceeded.");
785
+ await contextIdentity(context, true);
786
+ let profile;
787
+ try {
788
+ profile = await ensureAccountProfile(context, changes);
789
+ }
790
+ catch (cause) {
791
+ throw new HostError(`Personal profile local persistence failed: ${message(cause)}. No Swarm synchronization was attempted.`);
792
+ }
793
+ const swarms = [];
794
+ for (const entry of withState(context, (state) => state.swarms())) {
795
+ try {
796
+ const record = await approvedMembership(context, entry.cid);
797
+ await syncAccountProfile(context, record, profile);
798
+ swarms.push({ configUrl: entry.cid, synchronized: true });
799
+ }
800
+ catch (cause) {
801
+ swarms.push({
802
+ configUrl: entry.cid,
803
+ synchronized: false,
804
+ error: message(cause),
805
+ });
806
+ }
807
+ }
808
+ return { profile, localPersisted: true, swarms };
809
+ }
810
+ async function fetchConfig(context, configUrl, signal) {
811
+ const c = coordinates(configUrl), api = client(context, c.service);
812
+ const options = signal ? { signal } : {};
813
+ const [variable, scope] = await Promise.all([
814
+ api.read(c.scopeId, c.configId, options),
815
+ api.send("GET", c.scopeId, "", undefined, options),
816
+ ]);
817
+ const raw = object(variable.value, "organization configuration");
818
+ if (scope.owner !== raw.owner)
819
+ throw new HostError("Organization Owner does not match the immutable Scope trust root.");
820
+ if (raw.v === 2) {
821
+ if (!Array.isArray(raw.members) ||
822
+ raw.members.length < 1 ||
823
+ raw.members.length > 256)
824
+ throw new HostError("Invalid organization member directory.");
825
+ const ids = new Set(), identities = new Set();
826
+ const directory = raw.members.map((item) => {
827
+ const member = object(item, "member directory entry");
828
+ if (Object.keys(member).sort().join() !== "memberId,publicKey" ||
829
+ !isCanonicalPublicKey(member.publicKey) ||
830
+ typeof member.memberId !== "string" ||
831
+ !RESOURCE_ID_PATTERN.test(member.memberId) ||
832
+ ids.has(member.memberId) ||
833
+ identities.has(member.publicKey))
834
+ throw new HostError("Invalid or duplicate member directory entry.");
835
+ ids.add(member.memberId);
836
+ identities.add(member.publicKey);
837
+ return { publicKey: member.publicKey, memberId: member.memberId };
838
+ });
839
+ const members = await boundedMap(directory, async (entry) => {
840
+ const member = object((await api.read(c.scopeId, entry.memberId, options)).value, "member record");
841
+ if (member.publicKey !== entry.publicKey)
842
+ throw new HostError("Member record does not match its directory identity.");
843
+ return { ...member, memberId: entry.memberId };
844
+ });
845
+ return {
846
+ config: parseOrganization({ ...raw, members }, configUrl),
847
+ variable,
848
+ };
849
+ }
850
+ return { config: parseOrganization(raw, configUrl), variable };
851
+ }
852
+ async function boundedMap(items, operation) {
853
+ const results = [];
854
+ for (let offset = 0; offset < items.length; offset += 16) {
855
+ const batch = await Promise.allSettled(items.slice(offset, offset + 16).map(operation));
856
+ for (const result of batch) {
857
+ if (result.status === "rejected")
858
+ throw result.reason;
859
+ results.push(result.value);
860
+ }
861
+ }
862
+ return results;
863
+ }
864
+ function configValue(config) {
865
+ if (config.v === 1)
866
+ return config;
867
+ if (config.v === 3) {
868
+ return {
869
+ ...config,
870
+ members: config.members.map((member) => {
871
+ const isOwner = member.publicKey === config.owner;
872
+ const role = member.role ?? "ordinary";
873
+ if (isOwner) {
874
+ if (member.approvalId !== null)
875
+ throw new HostError("Owner must not have an approval variable.");
876
+ return {
877
+ publicKey: member.publicKey,
878
+ role,
879
+ profileId: member.profileId,
880
+ approvalId: null,
881
+ };
882
+ }
883
+ if (typeof member.approvalId !== "string")
884
+ throw new HostError("Member directory is missing its approval ID.");
885
+ return {
886
+ publicKey: member.publicKey,
887
+ role,
888
+ profileId: member.profileId,
889
+ approvalId: member.approvalId,
890
+ };
891
+ }),
892
+ };
893
+ }
894
+ return {
895
+ ...config,
896
+ members: config.members.map((member) => {
897
+ if (!member.memberId)
898
+ throw new HostError("Member directory is missing its record ID.");
899
+ return { publicKey: member.publicKey, memberId: member.memberId };
900
+ }),
901
+ };
902
+ }
903
+ async function createApprovalRecord(api, scopeId, approval, key) {
904
+ return (await api.create(scopeId, approval, key)).id;
905
+ }
906
+ async function retireVariable(api, scopeId, variableId, keyPrefix) {
907
+ for (const action of ["freeze", "delete"]) {
908
+ try {
909
+ if (action === "freeze")
910
+ await api.freeze(scopeId, variableId, `${keyPrefix}.freeze`);
911
+ else
912
+ await api.delete(scopeId, variableId, `${keyPrefix}.delete`);
913
+ }
914
+ catch (cause) {
915
+ if (!(cause instanceof ScopeApiError) || cause.status !== 410)
916
+ throw cause;
917
+ }
918
+ }
919
+ }
920
+ async function verifyMemberCertificate(certificate, owner, service, scopeId, headId, profileId, subject) {
921
+ await verifyScopeCertificate(certificate, owner, service, scopeId, profileId, subject);
922
+ if (!certificate.body.write.every((id) => id === profileId || id === headId))
923
+ throw new HostError("Membership package may grant only this member's profile and optionally HEAD.");
924
+ }
925
+ function binding(configUrl, config, member, requestId, encryptionKey) {
926
+ return {
927
+ configUrl,
928
+ scopeId: config.scopeId,
929
+ owner: config.owner,
930
+ member: member.publicKey,
931
+ requestId,
932
+ peerId: member.peerId,
933
+ profileId: member.profileId,
934
+ headId: config.headId,
935
+ epoch: config.epoch,
936
+ encryptionKey,
937
+ };
938
+ }
939
+ async function validateMembershipSecret(record, config, member) {
940
+ const secret = record.secret;
941
+ if (!secret ||
942
+ typeof secret.swarmKey !== "string" ||
943
+ !/^[a-f0-9]{64}$/.test(secret.swarmKey))
944
+ throw new HostError("Invalid approved Swarm key; preserve the original Request.");
945
+ if (record.account !== config.owner) {
946
+ const c = coordinates(record.configUrl);
947
+ await verifyMemberCertificate(secret.certificate, config.owner, c.service, c.scopeId, config.headId, member.profileId, record.account);
948
+ if (config.v === 3 && member.role === "ordinary") {
949
+ if (secret.certificate.body.write.length !== 1)
950
+ throw new HostError("Ordinary membership package must grant only this member's profile (not HEAD).");
951
+ }
952
+ else if (config.v === 3 && member.role === "pivot") {
953
+ if (!secret.certificate.body.write.includes(config.headId))
954
+ throw new HostError("Pivot membership package must grant HEAD and this member's profile.");
955
+ }
956
+ }
957
+ }
958
+ async function privateSource(context, record, signal, candidates) {
959
+ const config = record.config, secret = record.secret;
960
+ const identity = await contextIdentity(context);
961
+ const self = config.members.find((member) => member.publicKey === identity.publicKey);
962
+ if (!self)
963
+ throw new HostError("This identity was removed. Make a new Request only after Owner confirmation.");
964
+ const c = coordinates(record.configUrl);
965
+ if (identity.publicKey !== config.owner) {
966
+ await verifyMemberCertificate(secret.certificate, config.owner, c.service, c.scopeId, config.headId, self.profileId, identity.publicKey);
967
+ if (config.v === 3 &&
968
+ self.role === "pivot" &&
969
+ !secret.certificate.body.write.includes(config.headId))
970
+ throw new HostError("Pivot membership package must grant HEAD and this member's profile.");
971
+ }
972
+ const personal = await storedAccountProfile(context);
973
+ const addresses = new Map();
974
+ const observationErrors = [];
975
+ const api = client(context, c.service);
976
+ let selfProfile;
977
+ const profiles = await boundedMap(config.members, async (member) => {
978
+ try {
979
+ return await api.read(c.scopeId, member.profileId, signal ? { signal } : {});
980
+ }
981
+ catch (cause) {
982
+ signal?.throwIfAborted();
983
+ if (!candidates)
984
+ throw cause;
985
+ observationErrors.push(`Profile ${member.peerId}: ${message(cause)}`);
986
+ context.diagnostic?.(`Pivot profile refresh ${member.peerId} failed; retaining last-known approved candidate: ${message(cause)}`);
987
+ return undefined;
988
+ }
989
+ });
990
+ for (const [index, member] of config.members.entries()) {
991
+ const profile = profiles[index];
992
+ if (!profile) {
993
+ const known = candidates?.known(member.peerId);
994
+ if (known)
995
+ addresses.set(member.peerId, known);
996
+ continue;
997
+ }
998
+ const value = parseProfile(profile.value, member.peerId);
999
+ if (member.publicKey === identity.publicKey)
1000
+ selfProfile = { profile: value, cid: profile.cid };
1001
+ if (memberIsPivot(config, member, value) && member.peerId !== self.peerId)
1002
+ addresses.set(member.peerId, value.addresses);
1003
+ }
1004
+ if (personal && selfProfile) {
1005
+ selfProfile.profile = await syncAccountProfile(context, record, personal, selfProfile);
1006
+ selfProfile.cid = await valueCid(selfProfile.profile);
1007
+ }
1008
+ candidates?.reconcile(addresses);
1009
+ const active = candidates?.active() ?? addresses;
1010
+ if (!candidates) {
1011
+ try {
1012
+ const observed = await readNetworkingSnapshot(context.stateDir, record.configUrl, networkingBinding(record.configUrl, identity.publicKey, config), nodeScope(c.service, config.scopeId), config.epoch, self.peerId);
1013
+ if (observed.status === "current")
1014
+ for (const pivot of observed.snapshot.pivots)
1015
+ if (pivot.retryAt > Date.now() &&
1016
+ JSON.stringify([...new Set(active.get(pivot.peerId) ?? [])].sort()) === JSON.stringify(pivot.addresses))
1017
+ active.delete(pivot.peerId);
1018
+ }
1019
+ catch (cause) {
1020
+ context.diagnostic?.(`Local daemon observations could not be read: ${message(cause)}`);
1021
+ }
1022
+ }
1023
+ const desired = memberPeers(self.peerId, active, []);
1024
+ const pivot = context.pivot ?? selfProfile?.profile.pivot ?? false;
1025
+ signal?.throwIfAborted();
1026
+ const node = await startNode(context.stateDir, nodeScope(c.service, config.scopeId), secret.swarmKey, config.epoch, context.listen, {
1027
+ self: self.peerId,
1028
+ peers: desired,
1029
+ pivot,
1030
+ ...(signal ? { signal } : {}),
1031
+ ...(config.v === 3 ? { identity } : {}),
1032
+ });
1033
+ if (node.peerId !== self.peerId)
1034
+ throw new HostError("Approved PeerID differs from this local Request's Kubo identity.");
1035
+ const peers = desired.flatMap(({ ID, Addrs }) => Addrs.map((addr) => `${addr}/p2p/${ID}`));
1036
+ signal?.throwIfAborted();
1037
+ if (pivot && !node.addresses.length && !selfProfile?.profile.addresses.length)
1038
+ context.diagnostic?.("Pivot has no IPv4 candidates. Connect an interface or set manual candidates with swarm profile --address.");
1039
+ if (selfProfile) {
1040
+ const dir = await directory(context);
1041
+ const preference = `pivot-${localName(record.configUrl)}`;
1042
+ const saved = await readPrivate(dir, preference);
1043
+ const manual = saved?.manual ?? selfProfile.profile.addresses;
1044
+ for (const address of manual)
1045
+ validateAddress(address, self.peerId);
1046
+ if (!saved && pivot)
1047
+ await writePrivate(dir, preference, { manual });
1048
+ const published = pivot
1049
+ ? [...new Set([...manual, ...node.addresses])].slice(0, 16).sort()
1050
+ : manual;
1051
+ if (pivot && new Set([...manual, ...node.addresses]).size > 16)
1052
+ context.diagnostic?.("Pivot profile is capped at 16 candidates; manual hints take priority over interface snapshots.");
1053
+ if (selfProfile.profile.pivot === pivot &&
1054
+ JSON.stringify([...selfProfile.profile.addresses].sort()) ===
1055
+ JSON.stringify(published))
1056
+ return {
1057
+ node,
1058
+ peers,
1059
+ pivot,
1060
+ selectedPeers: desired.map(({ ID }) => ID),
1061
+ observationError: observationErrors.length
1062
+ ? observationErrors.join("; ")
1063
+ : null,
1064
+ source: kuboSource(node, peers, context.diagnostic, context.env.IPAB_SWARM_DIAL_DEBUG === "1"),
1065
+ };
1066
+ const writer = client(context, c.service, identity, identity.publicKey === config.owner ? undefined : secret);
1067
+ const profile = {
1068
+ ...selfProfile.profile,
1069
+ pivot,
1070
+ addresses: published,
1071
+ updatedAt: new Date().toISOString(),
1072
+ };
1073
+ await writer.write(c.scopeId, self.profileId, profile, selfProfile.cid, uniqueId(), signal ? { signal } : {});
1074
+ }
1075
+ return {
1076
+ node,
1077
+ peers,
1078
+ pivot,
1079
+ selectedPeers: desired.map(({ ID }) => ID),
1080
+ observationError: observationErrors.length
1081
+ ? observationErrors.join("; ")
1082
+ : null,
1083
+ source: kuboSource(node, peers, context.diagnostic, context.env.IPAB_SWARM_DIAL_DEBUG === "1"),
1084
+ };
1085
+ }
1086
+ export async function swarmDaemon(context, signal, synchronize) {
1087
+ const lock = await privateDirectory(context.stateDir, "swarm-daemon");
1088
+ await withPrivateLock(lock, async () => {
1089
+ const startedAt = new Date().toISOString();
1090
+ const logBuffer = new DaemonLogBuffer();
1091
+ let uiUrl = "";
1092
+ let knownAliases = new Map();
1093
+ const sessions = new Map();
1094
+ const collectSecrets = (session) => {
1095
+ const secrets = [
1096
+ context.identity?.privateKey,
1097
+ context.pointerApiKey,
1098
+ ];
1099
+ if (session) {
1100
+ secrets.push(session.record?.secret?.swarmKey, session.node?.auth, session.context.identity?.privateKey, session.context.pointerApiKey);
1101
+ }
1102
+ else {
1103
+ for (const entry of sessions.values())
1104
+ secrets.push(entry.record?.secret?.swarmKey, entry.node?.auth, entry.context.identity?.privateKey, entry.context.pointerApiKey);
1105
+ }
1106
+ return secrets;
1107
+ };
1108
+ const redact = (error, session) => error === null
1109
+ ? null
1110
+ : redactDaemonText(error, collectSecrets(session));
1111
+ const emitDiagnostic = (text) => {
1112
+ logBuffer.push(text, collectSecrets());
1113
+ context.diagnostic?.(text);
1114
+ };
1115
+ const buildStatusSnapshot = () => {
1116
+ const now = Date.now();
1117
+ const urls = [...new Set([...knownAliases.keys(), ...sessions.keys()])];
1118
+ const swarms = urls.map((url) => {
1119
+ const session = sessions.get(url);
1120
+ const record = session?.record;
1121
+ const config = record?.config;
1122
+ const self = config?.members.find((member) => member.publicKey === record?.account);
1123
+ const pivots = session
1124
+ ? [...session.candidates.observations()].map(([id, value]) => ({
1125
+ peerId: id,
1126
+ selected: session.selected.has(id),
1127
+ probe: value.probe,
1128
+ probedAt: value.probedAt === null
1129
+ ? null
1130
+ : new Date(value.probedAt).toISOString(),
1131
+ failures: value.failures,
1132
+ retryAt: value.retryAt > 0
1133
+ ? new Date(value.retryAt).toISOString()
1134
+ : null,
1135
+ cooldown: value.retryAt > now,
1136
+ addresses: [...value.addresses],
1137
+ error: redact(value.error, session),
1138
+ }))
1139
+ : [];
1140
+ const connections = session?.connections
1141
+ ? {
1142
+ observedAt: session.connections.observedAt === null
1143
+ ? null
1144
+ : new Date(session.connections.observedAt).toISOString(),
1145
+ error: redact(session.connections.error, session),
1146
+ peers: session.connections.peers.map((peer) => ({ ...peer })),
1147
+ }
1148
+ : {
1149
+ observedAt: null,
1150
+ error: null,
1151
+ peers: [],
1152
+ };
1153
+ const syncState = session?.sync ?? emptySyncState();
1154
+ return {
1155
+ url,
1156
+ alias: knownAliases.get(url) ?? null,
1157
+ name: config?.name ?? null,
1158
+ scopeId: config?.scopeId ?? null,
1159
+ epoch: config?.epoch ?? null,
1160
+ account: record?.account ?? null,
1161
+ peerId: self?.peerId ?? null,
1162
+ role: session?.pivot === true
1163
+ ? "pivot"
1164
+ : session?.pivot === false
1165
+ ? "member"
1166
+ : "unknown",
1167
+ running: Boolean(session?.running),
1168
+ receiptRpc: {
1169
+ active: Boolean(session?.pivotServer),
1170
+ protocol: pivotReceiptProtocol,
1171
+ epoch: session?.pivotServer?.epoch ?? null,
1172
+ headId: session?.pivotServer?.headId ?? null,
1173
+ },
1174
+ updatedAt: session?.updatedAt != null
1175
+ ? new Date(session.updatedAt).toISOString()
1176
+ : null,
1177
+ verifiedAt: session?.verifiedAt != null
1178
+ ? new Date(session.verifiedAt).toISOString()
1179
+ : null,
1180
+ error: session ? redact(session.error, session) : null,
1181
+ pivots,
1182
+ connections,
1183
+ sync: {
1184
+ ...syncState,
1185
+ error: redact(syncState.error, session),
1186
+ skills: {
1187
+ ...syncState.skills,
1188
+ error: redact(syncState.skills.error, session),
1189
+ },
1190
+ templates: {
1191
+ ...syncState.templates,
1192
+ error: redact(syncState.templates.error, session),
1193
+ },
1194
+ registry: {
1195
+ ...syncState.registry,
1196
+ error: redact(syncState.registry.error, session),
1197
+ },
1198
+ },
1199
+ };
1200
+ });
1201
+ return {
1202
+ v: 1,
1203
+ pid: process.pid,
1204
+ stateDir: resolve(context.stateDir),
1205
+ startedAt,
1206
+ updatedAt: new Date(now).toISOString(),
1207
+ uiUrl,
1208
+ listen: context.listen ?? "lan",
1209
+ syncInterval: context.syncInterval ?? 60,
1210
+ swarms,
1211
+ logs: logBuffer.entries(),
1212
+ };
1213
+ };
1214
+ const closeReadiness = await context.daemonReady?.(buildStatusSnapshot, ({ url }) => {
1215
+ uiUrl = url;
1216
+ });
1217
+ emitDiagnostic(`IPAB daemon running in foreground; Ctrl-C stops management and leaves Kubo running.${uiUrl ? ` Status UI: ${uiUrl}` : ""}`);
1218
+ const stopPivotServer = async (session) => {
1219
+ const current = session.pivotServer;
1220
+ if (!current)
1221
+ return;
1222
+ delete session.pivotServer;
1223
+ await current.server.close().catch(() => { });
1224
+ };
1225
+ const closeSession = async (session) => {
1226
+ try {
1227
+ await stopPivotServer(session);
1228
+ }
1229
+ finally {
1230
+ try {
1231
+ await session.context.finishRead?.();
1232
+ }
1233
+ finally {
1234
+ await session.context.store.close();
1235
+ }
1236
+ }
1237
+ };
1238
+ const persist = async (url, session, running) => {
1239
+ const now = Date.now();
1240
+ session.updatedAt = now;
1241
+ session.running = running;
1242
+ const record = session.record;
1243
+ if (!record?.config)
1244
+ return;
1245
+ const snapshot = {
1246
+ v: 1,
1247
+ binding: networkingBinding(url, record.account, record.config),
1248
+ pid: process.pid,
1249
+ running,
1250
+ updatedAt: now,
1251
+ verifiedAt: session.verifiedAt,
1252
+ error: redact(session.error, session),
1253
+ topology: session.node?.topology ?? null,
1254
+ pivots: [...session.candidates.observations()].map(([peerId, value]) => ({
1255
+ ...value,
1256
+ peerId,
1257
+ selected: session.selected.has(peerId),
1258
+ error: redact(value.error, session),
1259
+ })),
1260
+ account: record.account,
1261
+ connections: session.connections
1262
+ ? {
1263
+ ...session.connections,
1264
+ error: redact(session.connections.error, session),
1265
+ }
1266
+ : {
1267
+ observedAt: null,
1268
+ error: "No connection snapshot collected.",
1269
+ peers: [],
1270
+ },
1271
+ };
1272
+ await writeNetworkingSnapshot(context.stateDir, url, snapshot);
1273
+ };
1274
+ try {
1275
+ while (!signal.aborted) {
1276
+ const registrations = withState(context, (state) => state.swarms());
1277
+ knownAliases = new Map(registrations.map((entry) => [entry.cid, entry.alias]));
1278
+ const urls = new Set(registrations.map((entry) => entry.cid));
1279
+ for (const url of sessions.keys())
1280
+ if (!urls.has(url)) {
1281
+ const session = sessions.get(url);
1282
+ await persist(url, session, false);
1283
+ await closeSession(session);
1284
+ sessions.delete(url);
1285
+ }
1286
+ await boundedMap(registrations, async ({ cid: url }) => {
1287
+ let session = sessions.get(url);
1288
+ if (!session) {
1289
+ session = {
1290
+ context: {
1291
+ ...context,
1292
+ diagnostic: emitDiagnostic,
1293
+ store: new IpfsStore(context.store.configuration),
1294
+ forceRefresh: true,
1295
+ },
1296
+ candidates: new PivotCandidates(),
1297
+ nextDiscovery: 0,
1298
+ nextSync: 0,
1299
+ healthy: 0,
1300
+ selected: new Set(),
1301
+ verifiedAt: null,
1302
+ updatedAt: null,
1303
+ running: false,
1304
+ error: null,
1305
+ sync: emptySyncState(),
1306
+ };
1307
+ sessions.set(url, session);
1308
+ }
1309
+ try {
1310
+ if (session.record?.config && context.pivot === undefined) {
1311
+ const self = session.record.config.members.find((member) => member.publicKey === session.record.account);
1312
+ const c = coordinates(url);
1313
+ const profile = parseProfile((await client(session.context, c.service).read(c.scopeId, self.profileId, { signal })).value, self.peerId);
1314
+ if ((profile.pivot ?? false) !== session.pivot)
1315
+ session.nextDiscovery = 0;
1316
+ }
1317
+ if (Date.now() >= session.nextDiscovery || session.healthy < 1) {
1318
+ const record = await approvedMembership(session.context, url, signal);
1319
+ const c = coordinates(url);
1320
+ const scope = nodeScope(c.service, record.config.scopeId);
1321
+ const existing = await readPrivate(join(context.stateDir, "swarm-nodes", scope), "node.json");
1322
+ if (!existing)
1323
+ throw new HostError("No existing managed node; activate this membership before running daemon.");
1324
+ await saveLocal(session.context, record);
1325
+ if (!session.record?.config ||
1326
+ networkingBinding(url, record.account, record.config) !==
1327
+ networkingBinding(url, session.record.account, session.record.config)) {
1328
+ session.candidates.reconcile(new Map());
1329
+ session.selected.clear();
1330
+ session.verifiedAt = null;
1331
+ delete session.connections;
1332
+ delete session.node;
1333
+ }
1334
+ session.record = record;
1335
+ const result = await privateSource(session.context, record, signal, session.candidates);
1336
+ session.node = result.node;
1337
+ session.pivot = result.pivot;
1338
+ session.context.pivot = result.pivot;
1339
+ session.selected = new Set(result.selectedPeers);
1340
+ session.error = result.observationError;
1341
+ if (!session.error)
1342
+ session.verifiedAt = Date.now();
1343
+ session.context.node = result.node;
1344
+ session.nextDiscovery = Date.now() + 120_000;
1345
+ await persist(url, session, true);
1346
+ }
1347
+ if (!session.node)
1348
+ return;
1349
+ let healthy = 0;
1350
+ await boundedMap([...session.candidates.active()], async ([id, addresses]) => {
1351
+ let success = false;
1352
+ let error = null;
1353
+ try {
1354
+ success = await probePeer(session.node, id, addresses, signal);
1355
+ }
1356
+ catch (cause) {
1357
+ signal.throwIfAborted();
1358
+ error = message(cause);
1359
+ emitDiagnostic(`[${url}] Pivot probe ${id}: ${message(cause)}`);
1360
+ }
1361
+ session.candidates.result(id, success, Date.now(), Math.random(), success ? null : (error ?? "Pivot dial failed."));
1362
+ if (success)
1363
+ healthy++;
1364
+ else {
1365
+ session.nextDiscovery = 0;
1366
+ emitDiagnostic(`[${url}] Pivot ${id} dial failed; refreshing profile, with cooldown after repeated failure.`);
1367
+ }
1368
+ });
1369
+ session.healthy = healthy;
1370
+ // Startup-captured relay/bootstrap options must be removed immediately
1371
+ // when a candidate enters cooldown, not merely changed through config RPC.
1372
+ const record = session.record;
1373
+ const self = record.config.members.find((member) => member.publicKey === record.account);
1374
+ const desired = memberPeers(self.peerId, session.candidates.active(), []);
1375
+ session.node = await startNode(context.stateDir, nodeScope(coordinates(url).service, record.config.scopeId), record.secret.swarmKey, record.config.epoch, context.listen, {
1376
+ self: self.peerId,
1377
+ pivot: session.pivot ?? false,
1378
+ peers: desired,
1379
+ signal,
1380
+ });
1381
+ session.selected = new Set(desired.map(({ ID }) => ID));
1382
+ session.context.node = session.node;
1383
+ if (session.pivot) {
1384
+ if (!session.pivotServer ||
1385
+ session.pivotServer.nodeApi !== session.node.api ||
1386
+ session.pivotServer.epoch !== record.config.epoch ||
1387
+ session.pivotServer.headId !== record.config.headId) {
1388
+ await stopPivotServer(session);
1389
+ const pivotNode = session.node;
1390
+ const mounted = await mountPivotServer(pivotNode, {
1391
+ receipt: (receiptRequest, requestSignal) => handlePivotReceiptRequest({ ...session.context, node: pivotNode }, url, receiptRequest, requestSignal),
1392
+ search: (params) => withState(session.context, (state) => queryLocalSearchIndex(state, url, params)),
1393
+ ...(context.diagnostic
1394
+ ? { diagnostic: context.diagnostic }
1395
+ : {}),
1396
+ }, session.context.fetch);
1397
+ session.pivotServer = {
1398
+ server: mounted,
1399
+ nodeApi: session.node.api,
1400
+ epoch: record.config.epoch,
1401
+ headId: record.config.headId,
1402
+ };
1403
+ }
1404
+ await syncPivotPublications(session.context, url, signal);
1405
+ }
1406
+ else {
1407
+ await stopPivotServer(session);
1408
+ }
1409
+ try {
1410
+ const peers = await nodeConnections(session.node, signal);
1411
+ session.connections = {
1412
+ observedAt: Date.now(),
1413
+ error: null,
1414
+ peers,
1415
+ };
1416
+ }
1417
+ catch (cause) {
1418
+ signal.throwIfAborted();
1419
+ session.connections = {
1420
+ observedAt: session.connections?.observedAt ?? null,
1421
+ error: message(cause).slice(0, 2048),
1422
+ peers: session.connections?.peers ?? [],
1423
+ };
1424
+ }
1425
+ }
1426
+ catch (cause) {
1427
+ if (signal.aborted)
1428
+ return;
1429
+ session.error = message(cause);
1430
+ session.nextDiscovery = 0;
1431
+ emitDiagnostic(`[${url}] Daemon refresh failed (last-known local candidates retained): ${message(cause)}`);
1432
+ if (cause instanceof HostError &&
1433
+ /membership removed|identity was removed|epoch rollback|Pinned Owner changed/.test(cause.message)) {
1434
+ await stopPivotServer(session);
1435
+ if (session.node)
1436
+ await stopNode(session.node);
1437
+ session.candidates.reconcile(new Map());
1438
+ delete session.node;
1439
+ session.selected.clear();
1440
+ await persist(url, session, false);
1441
+ delete session.record;
1442
+ }
1443
+ }
1444
+ if (synchronize &&
1445
+ session.node &&
1446
+ !signal.aborted &&
1447
+ Date.now() >= session.nextSync) {
1448
+ let deferIsolatedPivot = false;
1449
+ if (session.pivot &&
1450
+ (session.connections?.peers.length ?? 0) === 0 &&
1451
+ session.candidates.active().size === 0 &&
1452
+ session.record?.config) {
1453
+ try {
1454
+ const c = coordinates(url);
1455
+ const head = headValue(await client(session.context, c.service).read(c.scopeId, session.record.config.headId, { signal }));
1456
+ deferIsolatedPivot = !(await hasLocalBlock(session.context.store, head.root));
1457
+ }
1458
+ catch (cause) {
1459
+ signal.throwIfAborted();
1460
+ emitDiagnostic(`[${url}] Isolated Pivot HEAD check failed: ${message(cause)}`);
1461
+ }
1462
+ }
1463
+ if (deferIsolatedPivot) {
1464
+ session.nextSync = Date.now() + 5_000;
1465
+ session.sync.nextSyncAt = new Date(session.nextSync).toISOString();
1466
+ }
1467
+ else {
1468
+ const attemptAt = new Date().toISOString();
1469
+ session.sync.lastAttemptAt = attemptAt;
1470
+ let reported;
1471
+ try {
1472
+ const summary = await raceAbort(synchronize(session.context, url, (partial) => {
1473
+ reported = partial;
1474
+ }), signal);
1475
+ const applied = summary ?? reported;
1476
+ if (applied) {
1477
+ session.sync = {
1478
+ ...session.sync,
1479
+ ...applied,
1480
+ lastAttemptAt: attemptAt,
1481
+ lastSuccessAt: new Date().toISOString(),
1482
+ status: "ok",
1483
+ error: null,
1484
+ };
1485
+ }
1486
+ else {
1487
+ session.sync = {
1488
+ ...session.sync,
1489
+ lastAttemptAt: attemptAt,
1490
+ lastSuccessAt: new Date().toISOString(),
1491
+ status: "ok",
1492
+ error: null,
1493
+ };
1494
+ }
1495
+ }
1496
+ catch (cause) {
1497
+ signal.throwIfAborted();
1498
+ const detail = message(cause);
1499
+ emitDiagnostic(`[${url}] Swarm sync failed; will retry next interval: ${detail}`);
1500
+ session.sync = {
1501
+ ...session.sync,
1502
+ ...(reported ?? {}),
1503
+ lastAttemptAt: attemptAt,
1504
+ status: "error",
1505
+ error: redact(detail, session),
1506
+ };
1507
+ }
1508
+ finally {
1509
+ session.nextSync =
1510
+ Date.now() + (context.syncInterval ?? 60) * 1000;
1511
+ session.sync.nextSyncAt = new Date(session.nextSync).toISOString();
1512
+ }
1513
+ }
1514
+ }
1515
+ await persist(url, session, true);
1516
+ });
1517
+ try {
1518
+ const nextSync = synchronize
1519
+ ? Math.min(...[...sessions.values()]
1520
+ .filter((session) => session.node)
1521
+ .map((session) => Math.max(0, session.nextSync - Date.now())))
1522
+ : Infinity;
1523
+ await delay(Math.min(30_000 + Math.random() * 15_000, nextSync), undefined, { signal });
1524
+ }
1525
+ catch {
1526
+ signal.throwIfAborted();
1527
+ }
1528
+ }
1529
+ }
1530
+ finally {
1531
+ try {
1532
+ for (const [url, session] of sessions) {
1533
+ try {
1534
+ await persist(url, session, false);
1535
+ }
1536
+ finally {
1537
+ await closeSession(session);
1538
+ }
1539
+ }
1540
+ }
1541
+ finally {
1542
+ await closeReadiness?.();
1543
+ }
1544
+ }
1545
+ }, signal, 1);
1546
+ }
1547
+ async function activate(context, record) {
1548
+ const { node, peers, source } = await privateSource(context, record);
1549
+ if (context.node?.api !== node.api ||
1550
+ context.sourcePeers?.length !== peers.length ||
1551
+ peers.some((peer, i) => context.sourcePeers?.[i] !== peer)) {
1552
+ const store = context.store.withLocalSource(source);
1553
+ await context.store.close();
1554
+ context.store = store;
1555
+ context.sourcePeers = peers;
1556
+ }
1557
+ context.node = node;
1558
+ await context.ensureDaemon?.();
1559
+ }
1560
+ async function localForRead(context, configUrl) {
1561
+ const record = await local(context, configUrl);
1562
+ if (record.account === record.owner) {
1563
+ const transition = await readPrivate(await directory(context), `transition-${localName(configUrl)}`);
1564
+ if (transition && !transition.completed)
1565
+ throw new HostError("Organization switch incomplete; only Owner can continue with swarm resume.");
1566
+ }
1567
+ return record;
1568
+ }
1569
+ async function approvedMembership(context, configUrl, signal) {
1570
+ const record = await localForRead(context, configUrl);
1571
+ const { config } = await fetchConfig(context, configUrl, signal);
1572
+ if (config.owner !== record.owner)
1573
+ throw new HostError("Pinned Owner changed; refusing configuration.");
1574
+ if (record.config && config.epoch < record.config.epoch)
1575
+ throw new HostError("Organization epoch rollback.");
1576
+ const member = config.members.find((member) => member.publicKey === record.account);
1577
+ if (!member)
1578
+ throw new HostError("No approved package yet, or membership removed; ask the Owner.");
1579
+ if (record.account !== config.owner) {
1580
+ if (config.v === 3) {
1581
+ if (typeof member.approvalId !== "string")
1582
+ throw new HostError("Published package does not match the approved member.");
1583
+ const previousSelf = record.config?.members.find((entry) => entry.publicKey === record.account);
1584
+ const needsUnseal = !record.secret ||
1585
+ !record.config ||
1586
+ record.config.v !== 3 ||
1587
+ record.config.epoch !== config.epoch ||
1588
+ record.config.headId !== config.headId ||
1589
+ !previousSelf ||
1590
+ previousSelf.role !== member.role ||
1591
+ previousSelf.profileId !== member.profileId ||
1592
+ previousSelf.approvalId !== member.approvalId;
1593
+ if (needsUnseal) {
1594
+ const identity = await contextIdentity(context);
1595
+ const c = coordinates(configUrl);
1596
+ const approvalVariable = await client(context, c.service).read(c.scopeId, member.approvalId, signal ? { signal } : {});
1597
+ record.secret = openApprovalV2(approvalVariable.value, {
1598
+ configUrl,
1599
+ owner: config.owner,
1600
+ member: member.publicKey,
1601
+ role: member.role ?? "ordinary",
1602
+ profileId: member.profileId,
1603
+ headId: config.headId,
1604
+ epoch: config.epoch,
1605
+ }, identity);
1606
+ }
1607
+ }
1608
+ else {
1609
+ if (!record.request ||
1610
+ record.request.v !== 1 ||
1611
+ !record.encryption ||
1612
+ member.requestId !== record.request.id ||
1613
+ member.peerId !== record.request.peerId ||
1614
+ !member.approval ||
1615
+ typeof member.encryptionKey !== "string")
1616
+ throw new HostError("Published package does not match the locally saved Request.");
1617
+ record.secret = await openApproval(member.approval, binding(configUrl, config, member, member.requestId, member.encryptionKey), record.encryption);
1618
+ }
1619
+ }
1620
+ if (!record.secret)
1621
+ throw new HostError("Owner key/Swarm key lost: no system recovery is available.");
1622
+ record.config = config;
1623
+ await validateMembershipSecret(record, config, member);
1624
+ return record;
1625
+ }
1626
+ async function refresh(context, configUrl) {
1627
+ const record = await approvedMembership(context, configUrl);
1628
+ await saveLocal(context, record);
1629
+ await activate(context, record);
1630
+ return record;
1631
+ }
1632
+ async function readyMembership(context, configUrl) {
1633
+ const record = await localForRead(context, configUrl);
1634
+ if (!record.config || !record.secret)
1635
+ return refresh(context, configUrl);
1636
+ if (!context.node ||
1637
+ context.node.peerId !==
1638
+ record.config.members.find((m) => m.publicKey === record.account)?.peerId) {
1639
+ try {
1640
+ await activate(context, record);
1641
+ }
1642
+ catch (cause) {
1643
+ if (cause instanceof ScopeApiError &&
1644
+ [403, 404, 410].includes(cause.status))
1645
+ return refresh(context, configUrl);
1646
+ throw cause;
1647
+ }
1648
+ }
1649
+ else {
1650
+ const personal = await storedAccountProfile(context);
1651
+ if (personal)
1652
+ await syncAccountProfile(context, record, personal);
1653
+ }
1654
+ return record;
1655
+ }
1656
+ function headValue(head) {
1657
+ const value = object(head.value, "HEAD");
1658
+ if (Object.keys(value).join() !== "root" || typeof value.root !== "string")
1659
+ throw new HostError("Invalid HEAD value.");
1660
+ return {
1661
+ ...head,
1662
+ root: value.root,
1663
+ etag: `"${head.cid}"`,
1664
+ };
1665
+ }
1666
+ export async function pointer(context, configUrl) {
1667
+ return boundPointer(context, configUrl, await readyMembership(context, configUrl));
1668
+ }
1669
+ async function boundPointer(context, configUrl, record) {
1670
+ const identity = await contextIdentity(context), c = coordinates(configUrl);
1671
+ const operation = async (write, root, cid, key) => {
1672
+ for (let attempt = 0;; attempt++) {
1673
+ const config = record.config, api = client(context, c.service, identity, identity.publicKey === config.owner ? undefined : record.secret);
1674
+ try {
1675
+ return write
1676
+ ? await api.write(c.scopeId, config.headId, { root: root }, cid, key)
1677
+ : await api.read(c.scopeId, config.headId);
1678
+ }
1679
+ catch (cause) {
1680
+ if (attempt === 0 &&
1681
+ (!write ||
1682
+ (cause instanceof ScopeApiError &&
1683
+ [401, 403, 404, 410, 423].includes(cause.status)))) {
1684
+ const oldHead = record.config.headId;
1685
+ record = await refresh(context, configUrl);
1686
+ if (write && record.config.headId !== oldHead)
1687
+ throw new ScopeApiError(412, "cas_conflict", "HEAD switched; recompute against the new final snapshot", cause);
1688
+ continue;
1689
+ }
1690
+ throw cause;
1691
+ }
1692
+ }
1693
+ };
1694
+ return {
1695
+ read: async () => headValue(await operation(false)),
1696
+ write: (root, cid, key) => operation(true, root, cid, key),
1697
+ writeWithReceipt: (receipt) => client(context, c.service).writeWithReceipt(c.scopeId, record.config.headId, receipt),
1698
+ };
1699
+ }
1700
+ async function writeNamesHead(context, url, head, root, cid) {
1701
+ const lock = await privateDirectory(await directory(context), `state-pin-${createHash("sha256").update(url).digest("hex")}`);
1702
+ await withPrivateLock(lock, async () => {
1703
+ if (context.confirmPublication) {
1704
+ try {
1705
+ await context.confirmPublication(url, root);
1706
+ }
1707
+ catch (cause) {
1708
+ throw new HostError(`Pivot replication failed; HEAD was not changed: ${message(cause)}`, 1, "PIVOT_PIN_FAILED", "publication");
1709
+ }
1710
+ await head.write(root, cid, uniqueId());
1711
+ return;
1712
+ }
1713
+ const idempotencyKey = uniqueId();
1714
+ let receipt;
1715
+ try {
1716
+ receipt = await requestPivotWriteReceipt(context, url, root, cid, idempotencyKey);
1717
+ }
1718
+ catch (cause) {
1719
+ throw new HostError(`Pivot replication failed; HEAD was not changed: ${message(cause)}`, 1, "PIVOT_PIN_FAILED", "publication");
1720
+ }
1721
+ await head.writeWithReceipt(receipt);
1722
+ });
1723
+ }
1724
+ async function requestPivotWriteReceipt(context, url, root, ifCid, idempotencyKey) {
1725
+ const record = await approvedMembership(context, url);
1726
+ const config = record.config;
1727
+ const identity = await contextIdentity(context);
1728
+ const members = await memberDirectory(context, url, config);
1729
+ const pivots = members.filter(({ member, profile }) => memberIsPivot(config, member, profile));
1730
+ if (!pivots.length)
1731
+ throw new HostError("No Pivot nodes are declared. Declare an independent member with swarm profile --pivot true before publishing; HEAD was not changed.");
1732
+ const remote = pivots.filter(({ member }) => member.publicKey !== record.account);
1733
+ if (!remote.length)
1734
+ throw new HostError("Publication requires an independent Pivot node. Declare another member with swarm profile --pivot true; HEAD was not changed.");
1735
+ const authorized = remote.filter(({ member }) => member.publicKey === config.owner ||
1736
+ (config.v === 3
1737
+ ? member.role === "pivot"
1738
+ : member.pivotAuthority === true));
1739
+ const candidates = authorized.length
1740
+ ? [
1741
+ ...authorized,
1742
+ ...remote.filter(({ member }) => member.publicKey !== config.owner &&
1743
+ config.v !== 3 &&
1744
+ member.pivotAuthority === undefined),
1745
+ ]
1746
+ : remote;
1747
+ if (!context.requestPivotReceipt && !context.node)
1748
+ throw new HostError("State pin requires an active publishing node.");
1749
+ const c = coordinates(url);
1750
+ const addresses = context.node ? context.node.addresses.slice(0, 16) : [];
1751
+ const request = await signPivotReceiptRequest({
1752
+ service: c.service,
1753
+ scopeId: c.scopeId,
1754
+ headId: config.headId,
1755
+ epoch: config.epoch,
1756
+ root,
1757
+ ifCid,
1758
+ idempotencyKey,
1759
+ member: identity.publicKey,
1760
+ addresses,
1761
+ }, identity.privateKey);
1762
+ context.diagnostic?.(`[${url}] Requesting Pivot-signed HEAD write receipt for publication ${root}...`);
1763
+ const signal = AbortSignal.timeout(90_000);
1764
+ const errors = [];
1765
+ for (const pivot of candidates) {
1766
+ try {
1767
+ const receipt = context.requestPivotReceipt
1768
+ ? await context.requestPivotReceipt(pivot, request, signal)
1769
+ : await requestPivotReceiptOverP2p(context.node, pivot.member.peerId, pivot.profile.addresses, request, signal, context.fetch);
1770
+ if (JSON.stringify(receipt.value) !== JSON.stringify({ root }) ||
1771
+ receipt.ifCid !== ifCid ||
1772
+ receipt.idempotencyKey !== idempotencyKey ||
1773
+ receipt.subject !== pivot.member.publicKey)
1774
+ throw new HostError(`Pivot ${pivot.member.publicKey} returned a receipt that does not match this publication.`);
1775
+ context.diagnostic?.(`[${url}] Received HEAD write receipt from Pivot ${pivot.profile.name} (${pivot.member.publicKey}).`);
1776
+ return receipt;
1777
+ }
1778
+ catch (cause) {
1779
+ const detail = message(cause);
1780
+ errors.push(`${pivot.member.publicKey}: ${detail}`);
1781
+ context.diagnostic?.(`[${url}] Pivot receipt request to ${pivot.member.publicKey} failed: ${detail}`);
1782
+ }
1783
+ }
1784
+ throw new HostError(`No authorized independent Pivot issued a HEAD write receipt for publication ${root} (${errors.join("; ")}); HEAD was not changed.`);
1785
+ }
1786
+ export async function handlePivotReceiptRequest(context, url, input, signal) {
1787
+ const request = parsePivotReceiptRequest(input);
1788
+ const record = await approvedMembership(context, url, signal);
1789
+ const config = record.config;
1790
+ const c = coordinates(url);
1791
+ const identity = await contextIdentity(context);
1792
+ const canSignHead = identity.publicKey === config.owner ||
1793
+ Boolean(record.secret?.certificate.body.write.includes(config.headId));
1794
+ if (!canSignHead)
1795
+ throw new HostError("This Pivot is not authorized by the Owner to sign HEAD write receipts. Run swarm pivot grant.", 1, "PIVOT_UNAUTHORIZED");
1796
+ if (request.service !== c.service ||
1797
+ request.scopeId !== c.scopeId ||
1798
+ request.headId !== config.headId ||
1799
+ request.epoch !== config.epoch)
1800
+ throw new HostError("Receipt request does not match current Swarm configuration or epoch.");
1801
+ const member = config.members.find((m) => m.publicKey === request.member);
1802
+ if (!member)
1803
+ throw new HostError("Receipt requester is not an approved Swarm member.");
1804
+ await verifyPivotReceiptRequest(request, member.peerId);
1805
+ const node = context.node;
1806
+ if (!node)
1807
+ throw new HostError("Pivot receipt signing requires an active Kubo node.");
1808
+ const peers = [...request.addresses];
1809
+ if (!peers.length) {
1810
+ const profile = parseProfile((await client(context, c.service).read(c.scopeId, member.profileId, {
1811
+ signal,
1812
+ })).value, member.peerId);
1813
+ peers.push(...profile.addresses);
1814
+ }
1815
+ const source = context.store.withLocalSource(kuboSource(node, peers, context.diagnostic, context.env.IPAB_SWARM_DIAL_DEBUG === "1"));
1816
+ try {
1817
+ if (CID.parse(request.root).code === dagPb.code) {
1818
+ if (peers.length > 0)
1819
+ await probePeer(node, member.peerId, peers, signal).catch(() => false);
1820
+ await readSnapshot(source, request.root, url);
1821
+ await pinPublication(source, [request.root], node, signal, context.fetch);
1822
+ }
1823
+ else {
1824
+ const pub = await readPublication(source, request.root);
1825
+ if (pub.writer !== request.member)
1826
+ throw new HostError("Publication writer does not match the authenticated requesting member.");
1827
+ await readSnapshot(source, request.root, url);
1828
+ await pinPublication(source, await frozenPublicationClosure(source, request.root), node, signal, context.fetch);
1829
+ }
1830
+ }
1831
+ finally {
1832
+ await source.close();
1833
+ }
1834
+ // Revalidate authorization after durable pin, before signing the HEAD receipt.
1835
+ const fresh = await approvedMembership(context, url, signal);
1836
+ const freshConfig = fresh.config;
1837
+ const stillAuthorized = identity.publicKey === freshConfig.owner ||
1838
+ Boolean(fresh.secret?.certificate.body.write.includes(freshConfig.headId));
1839
+ if (!stillAuthorized ||
1840
+ freshConfig.epoch !== config.epoch ||
1841
+ freshConfig.headId !== config.headId ||
1842
+ !freshConfig.members.some((m) => m.publicKey === request.member))
1843
+ throw new HostError("Swarm membership or epoch changed during Pivot pin; no receipt was signed.");
1844
+ return signScopeWriteReceipt({
1845
+ service: c.service,
1846
+ scopeId: c.scopeId,
1847
+ variableId: freshConfig.headId,
1848
+ value: { root: request.root },
1849
+ ifCid: request.ifCid,
1850
+ idempotencyKey: request.idempotencyKey,
1851
+ signer: {
1852
+ publicKey: identity.publicKey,
1853
+ privateKey: identity.privateKey,
1854
+ ...(identity.publicKey === freshConfig.owner
1855
+ ? {}
1856
+ : { certificate: fresh.secret.certificate }),
1857
+ },
1858
+ });
1859
+ }
1860
+ async function raceAbort(promise, signal) {
1861
+ if (signal.aborted) {
1862
+ void promise.catch(() => { });
1863
+ throw signal.reason instanceof Error
1864
+ ? signal.reason
1865
+ : new Error("Operation aborted.");
1866
+ }
1867
+ return new Promise((resolve, reject) => {
1868
+ const onAbort = () => {
1869
+ void promise.catch(() => { });
1870
+ reject(signal.reason instanceof Error
1871
+ ? signal.reason
1872
+ : new Error("Operation aborted."));
1873
+ };
1874
+ signal.addEventListener("abort", onAbort, { once: true });
1875
+ promise.then((value) => {
1876
+ signal.removeEventListener("abort", onAbort);
1877
+ resolve(value);
1878
+ }, (cause) => {
1879
+ signal.removeEventListener("abort", onAbort);
1880
+ reject(cause instanceof Error ? cause : new Error(String(cause)));
1881
+ });
1882
+ });
1883
+ }
1884
+ async function hasLocalBlock(store, cid) {
1885
+ if (!store.supportsRetention)
1886
+ return true;
1887
+ const localOnly = new IpfsStore(store.configuration);
1888
+ try {
1889
+ await localOnly.block.get(cid);
1890
+ return true;
1891
+ }
1892
+ catch (cause) {
1893
+ if (cause instanceof ContentError && cause.code === "missing_block")
1894
+ return false;
1895
+ throw cause;
1896
+ }
1897
+ finally {
1898
+ await localOnly.close();
1899
+ }
1900
+ }
1901
+ export async function syncPivotPublications(context, url, signal) {
1902
+ if (context.pivot === false)
1903
+ return;
1904
+ const record = await approvedMembership(context, url, signal);
1905
+ const config = record.config;
1906
+ const node = context.node;
1907
+ if (!node)
1908
+ throw new HostError("Pivot synchronization requires an active managed node.");
1909
+ const members = await memberDirectory(context, url, config);
1910
+ const self = members.find(({ member }) => member.publicKey === record.account);
1911
+ const selfAuthorizedPivot = config.v === 3
1912
+ ? self.member.role === "pivot" || record.account === config.owner
1913
+ : true;
1914
+ if (!selfAuthorizedPivot || !(context.pivot ?? self.profile.pivot))
1915
+ return;
1916
+ const c = coordinates(url);
1917
+ const head = headValue(await client(context, c.service).read(c.scopeId, config.headId, { signal }));
1918
+ const peers = members.flatMap(({ member, profile }) => profile.addresses.map((address) => {
1919
+ validateAddress(address, member.peerId);
1920
+ return address;
1921
+ }));
1922
+ const remotePeers = peers.filter((address) => !address.endsWith(`/p2p/${node.peerId}`));
1923
+ // Avoid starting a 0-peer online Bitswap block/get on an isolated Pivot
1924
+ // before any remote peer is known or connected; in Kubo v0.43.2 a peer
1925
+ // connecting while a 0-peer block/get is in flight can stall Bitswap.
1926
+ if (remotePeers.length === 0 &&
1927
+ !(await hasLocalBlock(context.store, head.root))) {
1928
+ const connected = await nodeConnections(node, signal).catch(() => []);
1929
+ if (connected.length === 0)
1930
+ return;
1931
+ }
1932
+ const source = context.store.withLocalSource(kuboSource(node, peers, context.diagnostic));
1933
+ try {
1934
+ await readSnapshot(source, head.root, url);
1935
+ const roots = CID.parse(head.root).code === dagPb.code
1936
+ ? [head.root]
1937
+ : await frozenPublicationClosure(source, head.root);
1938
+ await pinPublication(source, roots, node, signal, context.fetch);
1939
+ }
1940
+ finally {
1941
+ await source.close();
1942
+ }
1943
+ }
1944
+ export async function typedJson(store, cid, type) {
1945
+ const { bundle, value } = await bundleJson(store, cid);
1946
+ if (bundle.schemaKey !== (await encodeSchema(type)).cid.toString())
1947
+ throw new HostError("Expected exact Bundle type CID.");
1948
+ return value;
1949
+ }
1950
+ function parseArtifact(value) {
1951
+ const data = object(value, "Artifact");
1952
+ if (Object.keys(data).some((key) => !["value", "previous", "timestamp"].includes(key)) ||
1953
+ typeof data.value !== "string" ||
1954
+ typeof data.timestamp !== "string" ||
1955
+ !Number.isFinite(Date.parse(data.timestamp)) ||
1956
+ (data.previous !== undefined && typeof data.previous !== "string"))
1957
+ throw new HostError("Invalid Artifact.");
1958
+ CID.parse(data.value);
1959
+ if (data.previous !== undefined)
1960
+ CID.parse(data.previous);
1961
+ return {
1962
+ value: data.value,
1963
+ timestamp: data.timestamp,
1964
+ ...(data.previous !== undefined ? { previous: data.previous } : {}),
1965
+ };
1966
+ }
1967
+ export async function jsonBundle(store, type, value) {
1968
+ const encoded = await encodeBundleCar(memoryTree(new Map([
1969
+ [
1970
+ ".bundle.yaml",
1971
+ new TextEncoder().encode(stringify({
1972
+ title: "IPAB Data",
1973
+ entry: "entry.json",
1974
+ type: ".bundle-type.yaml",
1975
+ })),
1976
+ ],
1977
+ [".bundle-type.yaml", new TextEncoder().encode(stringify(type))],
1978
+ ["entry.json", new TextEncoder().encode(`${JSON.stringify(value)}\n`)],
1979
+ ])));
1980
+ try {
1981
+ const iterator = await CarBlockIterator.fromIterable(streamChunks(encoded.stream));
1982
+ for await (const block of iterator)
1983
+ await store.put(block.cid, block.bytes);
1984
+ return encoded.cid.toString();
1985
+ }
1986
+ finally {
1987
+ await encoded.close();
1988
+ }
1989
+ }
1990
+ async function writeStateBundle(store, configuration, targets, configUrl) {
1991
+ const meta = parseSwarmMeta(configuration);
1992
+ const names = Object.fromEntries(Object.entries(targets).map(([name, cid]) => [
1993
+ formalName(name),
1994
+ cid.toString(),
1995
+ ]));
1996
+ const value = parseSwarmState({
1997
+ v: configUrl === undefined ? 5 : 6,
1998
+ ...(configUrl === undefined ? {} : { configUrl }),
1999
+ ...meta,
2000
+ names,
2001
+ });
2002
+ return jsonBundle(store, configUrl !== undefined
2003
+ ? swarmStateType
2004
+ : meta.skillPath === undefined
2005
+ ? legacySwarmStateType
2006
+ : previousSwarmStateType, value);
2007
+ }
2008
+ async function writeV7RootBundle(store, configuration, configUrl) {
2009
+ const meta = parseSwarmMeta(configuration);
2010
+ if (!meta.skillPath)
2011
+ throw new HostError("Swarm v7 root requires skillPath.");
2012
+ const value = parseSwarmRootState({
2013
+ v: 7,
2014
+ configUrl,
2015
+ templatePath: meta.templatePath,
2016
+ registryPath: meta.registryPath,
2017
+ skillPath: meta.skillPath,
2018
+ });
2019
+ return jsonBundle(store, swarmRootType, value);
2020
+ }
2021
+ function isV7Snapshot(snapshot) {
2022
+ return snapshot.stateBundle?.unixfsRoot?.version === 7;
2023
+ }
2024
+ function v7RootSkipFiles(snapshot) {
2025
+ const root = snapshot.stateBundle?.unixfsRoot;
2026
+ if (!root)
2027
+ return new Set();
2028
+ return new Set([".bundle.yaml", root.typeFile, root.entryFile]);
2029
+ }
2030
+ async function resolveSnapshotName(store, snapshot, name) {
2031
+ if (isV7Snapshot(snapshot))
2032
+ return resolveUnixfsPath(store, CID.parse(snapshot.stateBundle.cid), name);
2033
+ return Object.hasOwn(snapshot.names, name) ? snapshot.names[name] : undefined;
2034
+ }
2035
+ async function listSubtreeNames(store, snapshot, prefix, flatOnly = false) {
2036
+ if (isV7Snapshot(snapshot)) {
2037
+ const dirCid = await resolveUnixfsPath(store, CID.parse(snapshot.stateBundle.cid), prefix);
2038
+ if (!dirCid)
2039
+ return [];
2040
+ if (flatOnly) {
2041
+ const entries = await listUnixfsDirectory(store, dirCid);
2042
+ return [...entries.entries()]
2043
+ .map(([child, cid]) => ({ name: `${prefix}/${child}`, cid }))
2044
+ .sort((a, b) => a.name.localeCompare(b.name));
2045
+ }
2046
+ const walked = await walkUnixfsNames(store, dirCid, {
2047
+ prefix,
2048
+ stopAtBundle: true,
2049
+ });
2050
+ return walked.entries.map((entry) => ({
2051
+ name: entry.name,
2052
+ cid: CID.parse(entry.targetCid),
2053
+ }));
2054
+ }
2055
+ const needle = `${prefix}/`;
2056
+ return Object.entries(snapshot.names)
2057
+ .filter(([name]) => name.startsWith(needle))
2058
+ .map(([name, cid]) => ({ name, cid }))
2059
+ .sort((a, b) => a.name.localeCompare(b.name));
2060
+ }
2061
+ async function readV7Root(store, cid) {
2062
+ const canonical = cid.toV1();
2063
+ const rootKey = canonical.toString();
2064
+ // Read the root block directly first so non-missing block errors propagate unwrapped.
2065
+ const rootBytes = await store.block.get(rootKey);
2066
+ const bundle = await openBundle(canonical, {
2067
+ shallow: true,
2068
+ resolveCid: (key) => {
2069
+ const k = key.toV1().toString();
2070
+ return k === rootKey
2071
+ ? Promise.resolve(rootBytes)
2072
+ : store.block.get(key.toString());
2073
+ },
2074
+ });
2075
+ if (!isSwarmRootSchema(bundle.schemaKey))
2076
+ throw new HostError("Swarm v7 UnixFS root does not match the exact v7 root schema.");
2077
+ const raw = JSON.parse(new TextDecoder("utf-8", { fatal: true }).decode(await bytes(await bundle.readFile(bundle.manifest.entry), 1024 * 1024)));
2078
+ const value = parseSwarmRootState(raw);
2079
+ const meta = parseSwarmMeta({
2080
+ templatePath: value.templatePath,
2081
+ registryPath: value.registryPath,
2082
+ skillPath: value.skillPath,
2083
+ });
2084
+ return {
2085
+ v: 2,
2086
+ names: {},
2087
+ stateBundle: {
2088
+ meta,
2089
+ cid: rootKey,
2090
+ configUrl: value.configUrl,
2091
+ unixfsRoot: {
2092
+ version: 7,
2093
+ entryFile: bundle.manifest.entry,
2094
+ typeFile: bundle.manifest.type,
2095
+ },
2096
+ },
2097
+ };
2098
+ }
2099
+ export async function writeSnapshot(store, snapshot, configUrl) {
2100
+ if (snapshot.stateBundle) {
2101
+ if (Object.keys(snapshot.registrations ?? {}).length)
2102
+ throw new HostError("State Bundles cannot contain legacy registrations.");
2103
+ checkStateOrigin(snapshot, configUrl);
2104
+ return writeStateBundle(store, snapshot.stateBundle.meta, snapshot.names, snapshot.stateBundle.configUrl);
2105
+ }
2106
+ const put = async (value) => {
2107
+ const encoded = dagCbor.encode(value);
2108
+ const cid = CID.createV1(dagCbor.code, await sha256.digest(encoded));
2109
+ await store.put(cid, encoded);
2110
+ return cid;
2111
+ };
2112
+ const names = await put(snapshot.names);
2113
+ if (Object.keys(snapshot.registrations ?? {}).length) {
2114
+ const registrations = await put(snapshot.registrations);
2115
+ return (await put({ v: 3, names, registrations })).toString();
2116
+ }
2117
+ return (await put({ v: 4, names })).toString();
2118
+ }
2119
+ async function readState(store, cid) {
2120
+ if (cid.code !== dagCbor.code) {
2121
+ const bundle = await openBundle(cid, {
2122
+ resolveCid: (key) => store.block.get(key.toString()),
2123
+ });
2124
+ const type = bundle.schemaKey === legacySwarmStateSchema.cid.toString()
2125
+ ? legacySwarmStateType
2126
+ : bundle.schemaKey === previousSwarmStateSchema.cid.toString()
2127
+ ? previousSwarmStateType
2128
+ : swarmStateType;
2129
+ const value = parseSwarmState(await typedJson(store, cid.toString(), type));
2130
+ const meta = parseSwarmMeta({
2131
+ templatePath: value.templatePath,
2132
+ registryPath: value.registryPath,
2133
+ ...(value.skillPath === undefined ? {} : { skillPath: value.skillPath }),
2134
+ });
2135
+ const names = Object.fromEntries(Object.entries(object(value.names, "Names")).map(([name, target]) => {
2136
+ formalName(name);
2137
+ if (typeof target !== "string" || exactCid(target) !== target)
2138
+ throw new HostError("State Names require exact canonical CIDs.");
2139
+ return [name, CID.parse(target)];
2140
+ }));
2141
+ return {
2142
+ v: 2,
2143
+ names,
2144
+ stateBundle: {
2145
+ meta,
2146
+ cid: cid.toString(),
2147
+ ...(value.configUrl === undefined
2148
+ ? {}
2149
+ : { configUrl: value.configUrl }),
2150
+ },
2151
+ };
2152
+ }
2153
+ const data = await store.block.get(cid.toString());
2154
+ const root = object(dagCbor.decode(data), "State");
2155
+ if (root.v === 4) {
2156
+ const names = CID.asCID(root.names);
2157
+ if (!names || Object.keys(root).sort().join() !== "names,v")
2158
+ throw new HostError("Invalid State Names root.");
2159
+ return decodeSnapshot(dagCbor.encode({
2160
+ v: 2,
2161
+ names: dagCbor.decode(await store.block.get(names.toString())),
2162
+ }));
2163
+ }
2164
+ if (root.v !== 3)
2165
+ return decodeSnapshot(data);
2166
+ const names = CID.asCID(root.names), registrations = CID.asCID(root.registrations);
2167
+ if (!names ||
2168
+ !registrations ||
2169
+ Object.keys(root).sort().join() !== "names,registrations,v")
2170
+ throw new HostError("Invalid State index roots.");
2171
+ const [namesBlock, registrationsBlock] = await Promise.all([
2172
+ store.block.get(names.toString()),
2173
+ store.block.get(registrations.toString()),
2174
+ ]);
2175
+ return decodeSnapshot(dagCbor.encode({
2176
+ v: 2,
2177
+ names: dagCbor.decode(namesBlock),
2178
+ registrations: dagCbor.decode(registrationsBlock),
2179
+ }));
2180
+ }
2181
+ function decodeSnapshot(data) {
2182
+ const value = object(dagCbor.decode(data), "State"), names = object(value.names, "Names");
2183
+ if (value.v !== 2 ||
2184
+ Object.keys(value).some((key) => !["v", "names", "registrations"].includes(key)))
2185
+ throw new HostError("Unsupported old State; rebuild the Swarm.");
2186
+ const links = [];
2187
+ for (const [name, link] of Object.entries(names)) {
2188
+ formalName(name);
2189
+ const cid = CID.asCID(link);
2190
+ if (!cid)
2191
+ throw new HostError("Names must link CIDs.");
2192
+ links.push([name, cid]);
2193
+ }
2194
+ const registrations = {};
2195
+ if (value.registrations !== undefined) {
2196
+ for (const [schema, raw] of Object.entries(object(value.registrations, "Registrations"))) {
2197
+ const item = object(raw, "Association");
2198
+ const appCid = CID.asCID(item.appCid);
2199
+ if (Object.keys(item).sort().join() !== "appCid,argv" ||
2200
+ !appCid ||
2201
+ !Array.isArray(item.argv) ||
2202
+ !item.argv.every((argument) => typeof argument === "string"))
2203
+ throw new HostError("Invalid shared Association.");
2204
+ const association = createAssociation(schema, appCid.toString(), item.argv);
2205
+ if (association.schemaCid !== schema)
2206
+ throw new HostError("Shared Association requires a canonical type CID.");
2207
+ registrations[schema] = { appCid, argv: association.argv };
2208
+ }
2209
+ }
2210
+ return {
2211
+ v: 2,
2212
+ names: Object.fromEntries(links),
2213
+ ...(value.registrations !== undefined ? { registrations } : {}),
2214
+ };
2215
+ }
2216
+ export async function readSnapshot(store, root, configUrl) {
2217
+ const parsed = CID.parse(root);
2218
+ if (parsed.code === dagPb.code) {
2219
+ const snapshot = await readV7Root(store, parsed);
2220
+ checkStateOrigin(snapshot, configUrl);
2221
+ return snapshot;
2222
+ }
2223
+ const publication = await readPublication(store, root);
2224
+ const snapshot = await readState(store, publication.state);
2225
+ checkStateOrigin(snapshot, configUrl);
2226
+ return snapshot;
2227
+ }
2228
+ function checkStateOrigin(snapshot, configUrl) {
2229
+ if (configUrl !== undefined &&
2230
+ snapshot.stateBundle?.configUrl !== undefined &&
2231
+ snapshot.stateBundle.configUrl !== configUrl)
2232
+ throw new HostError("State Bundle Config URL does not match the selected Swarm.");
2233
+ }
2234
+ async function readHeaderSnapshot(store, root, configUrl) {
2235
+ const parsed = CID.parse(root);
2236
+ if (parsed.code === dagPb.code) {
2237
+ const snapshot = await readV7Root(store, parsed);
2238
+ checkStateOrigin(snapshot, configUrl);
2239
+ return {
2240
+ snapshot,
2241
+ stateCid: parsed.toV1().toString(),
2242
+ };
2243
+ }
2244
+ const publication = await readPublication(store, root);
2245
+ const snapshot = await readState(store, publication.state);
2246
+ checkStateOrigin(snapshot, configUrl);
2247
+ return {
2248
+ snapshot,
2249
+ stateCid: publication.state.toString(),
2250
+ };
2251
+ }
2252
+ async function readPublication(store, root) {
2253
+ if (CID.parse(root).code !== dagCbor.code)
2254
+ throw new HostError("Publication must be DAG-CBOR.");
2255
+ const publication = object(dagCbor.decode(await store.block.get(root)), "publication");
2256
+ const state = CID.asCID(publication.state);
2257
+ const previous = publication.previous === undefined
2258
+ ? undefined
2259
+ : CID.asCID(publication.previous);
2260
+ const writer = publication.writer === undefined ? undefined : publication.writer;
2261
+ if (publication.v !== 1 ||
2262
+ !state ||
2263
+ Object.keys(publication).some((k) => !["v", "state", "previous", "writer"].includes(k)) ||
2264
+ (publication.previous !== undefined && !previous) ||
2265
+ (writer !== undefined && !isCanonicalPublicKey(writer)))
2266
+ throw new HostError("Invalid publication record.");
2267
+ return {
2268
+ state,
2269
+ ...(previous ? { previous } : {}),
2270
+ ...(typeof writer === "string" ? { writer } : {}),
2271
+ };
2272
+ }
2273
+ async function publication(store, state, previous, writer) {
2274
+ if (writer !== undefined && !isCanonicalPublicKey(writer))
2275
+ throw new HostError("Invalid publication writer public key.");
2276
+ const data = dagCbor.encode({
2277
+ v: 1,
2278
+ state: CID.parse(state),
2279
+ ...(previous ? { previous: CID.parse(previous) } : {}),
2280
+ ...(writer ? { writer } : {}),
2281
+ });
2282
+ const cid = CID.createV1(dagCbor.code, await sha256.digest(data));
2283
+ await store.put(cid, data);
2284
+ return cid.toString();
2285
+ }
2286
+ function missingContent(cause) {
2287
+ let failure = cause;
2288
+ for (let depth = 0; depth < 8 && failure instanceof ContentBundleError; depth++)
2289
+ failure = failure.cause;
2290
+ return failure instanceof ContentError && failure.code === "missing_block";
2291
+ }
2292
+ function unavailableContent(cause) {
2293
+ for (let depth = 0; depth < 8 && cause instanceof ContentBundleError; depth++)
2294
+ cause = cause.cause;
2295
+ return (missingContent(cause) ||
2296
+ (cause instanceof ContentError && cause.code === "acquisition_failed") ||
2297
+ cause instanceof GatewayReadError ||
2298
+ (cause instanceof Error && cause.name === "TimeoutError"));
2299
+ }
2300
+ async function headContentFailure(context, configUrl, config, head, cause) {
2301
+ if (!unavailableContent(cause))
2302
+ throw cause;
2303
+ let failure = cause;
2304
+ for (let depth = 0; depth < 8 && failure instanceof ContentBundleError; depth++)
2305
+ failure = failure.cause;
2306
+ let writer = "Last HEAD writer/time: unknown (legacy record or service without update metadata).";
2307
+ if (head.update) {
2308
+ const update = parseVariableUpdate(head.update, {
2309
+ ...coordinates(configUrl),
2310
+ variableId: config.headId,
2311
+ cid: head.cid,
2312
+ });
2313
+ const member = config.members.find((member) => member.publicKey === update.subject);
2314
+ let label = "public profile unavailable";
2315
+ if (member) {
2316
+ try {
2317
+ const c = coordinates(configUrl);
2318
+ const profile = parseProfile((await client(context, c.service).read(c.scopeId, member.profileId))
2319
+ .value, member.peerId);
2320
+ label = `${JSON.stringify(profile.name)} (profile label), PeerID ${member.peerId}`;
2321
+ }
2322
+ catch (profileError) {
2323
+ label = `profile lookup failed: ${message(profileError)}`;
2324
+ }
2325
+ }
2326
+ writer =
2327
+ `Last HEAD writer: ${update.subject}; service time ${update.updatedAt}; ${label}. ` +
2328
+ "Ask that device/key holder to come online, or locate another content copy. " +
2329
+ "The last writer is not necessarily the only copy or a confirmed holder; bringing it online may not recover the content.";
2330
+ }
2331
+ const error = new HostError(`${message(failure)} HEAD publication ${head.root}; HEAD value CID ${head.cid}. ${writer}`, 1, "CONTENT_UNAVAILABLE", "acquisition");
2332
+ error.cause = cause;
2333
+ throw error;
2334
+ }
2335
+ export async function sharedSwarmStatus(context, configUrl) {
2336
+ const { config } = await fetchConfig(context, configUrl);
2337
+ const c = coordinates(configUrl);
2338
+ const head = headValue(await client(context, c.service).read(c.scopeId, config.headId));
2339
+ let content;
2340
+ try {
2341
+ content = await readHeaderSnapshot(context.store, head.root, configUrl);
2342
+ }
2343
+ catch (cause) {
2344
+ if (!unavailableContent(cause))
2345
+ throw cause;
2346
+ const registered = withState(context, (state) => state.swarms().some((entry) => entry.cid === configUrl));
2347
+ if (!registered)
2348
+ return headContentFailure(context, configUrl, config, head, cause);
2349
+ context.diagnostic?.("Shared State is missing locally; connecting the registered Swarm content source.");
2350
+ return swarmHeader(context, configUrl, true);
2351
+ }
2352
+ const header = {
2353
+ head,
2354
+ ...content,
2355
+ config,
2356
+ source: "network",
2357
+ verifiedAt: new Date().toISOString(),
2358
+ };
2359
+ if (withState(context, (state) => state
2360
+ .contentPins()
2361
+ .some((pin) => pin.swarm === configUrl && pin.status !== "deleting"))) {
2362
+ const record = await localForRead(context, configUrl);
2363
+ await lazyPrivateSource(context, configUrl, record.account, config);
2364
+ await refreshNamePins(context, configUrl, header);
2365
+ }
2366
+ return header;
2367
+ }
2368
+ export async function swarmHeader(context, configUrl, force = context.forceRefresh ?? false, mode = "active") {
2369
+ try {
2370
+ return await readSwarmHeader(context, configUrl, force, mode);
2371
+ }
2372
+ catch (cause) {
2373
+ withState(context, (state) => {
2374
+ for (const pin of state.contentPins())
2375
+ if (pin.swarm === configUrl && pin.status !== "deleting")
2376
+ state.saveContentPin({
2377
+ ...pin,
2378
+ freshness: "stale",
2379
+ error: message(cause),
2380
+ });
2381
+ });
2382
+ throw cause;
2383
+ }
2384
+ }
2385
+ async function readSwarmHeader(context, configUrl, force = context.forceRefresh ?? false, mode = "active") {
2386
+ canonicalSwarmUrl(configUrl);
2387
+ let record = mode === "local-first"
2388
+ ? await approvedMembership(context, configUrl)
2389
+ : force
2390
+ ? await refresh(context, configUrl)
2391
+ : await readyMembership(context, configUrl);
2392
+ const cached = !force && (await cachedHeader(context, record));
2393
+ if (cached) {
2394
+ projectHeader(context, record, cached);
2395
+ await refreshNamePins(context, configUrl, cached);
2396
+ return cached;
2397
+ }
2398
+ if (mode === "local-first") {
2399
+ await saveLocal(context, record);
2400
+ await lazyPrivateSource(context, configUrl, record.account, record.config);
2401
+ }
2402
+ const c = coordinates(configUrl);
2403
+ let head = mode === "local-first"
2404
+ ? headValue(await client(context, c.service).read(c.scopeId, record.config.headId))
2405
+ : await (await boundPointer(context, configUrl, record)).read();
2406
+ let content;
2407
+ try {
2408
+ content = await readHeaderSnapshot(context.store, head.root, configUrl);
2409
+ }
2410
+ catch (cause) {
2411
+ if (mode === "local-first")
2412
+ return headContentFailure(context, configUrl, record.config, head, cause);
2413
+ record = await refresh(context, configUrl);
2414
+ head = await (await boundPointer(context, configUrl, record)).read();
2415
+ try {
2416
+ content = await readHeaderSnapshot(context.store, head.root, configUrl);
2417
+ }
2418
+ catch (cause) {
2419
+ return headContentFailure(context, configUrl, record.config, head, cause);
2420
+ }
2421
+ }
2422
+ const current = await local(context, configUrl), verifiedAt = Date.now();
2423
+ withState(context, (state) => {
2424
+ state.saveSwarmHeader(record.account, configUrl, {
2425
+ head,
2426
+ snapshot: Buffer.from(dagCbor.encode(content.snapshot)).toString("base64"),
2427
+ stateCid: content.stateCid,
2428
+ verifiedAt,
2429
+ headId: current.config.headId,
2430
+ epoch: current.config.epoch,
2431
+ });
2432
+ });
2433
+ const header = {
2434
+ head,
2435
+ ...content,
2436
+ config: current.config,
2437
+ source: "network",
2438
+ verifiedAt: new Date(verifiedAt).toISOString(),
2439
+ };
2440
+ projectHeader(context, current, header);
2441
+ await refreshNamePins(context, configUrl, header);
2442
+ return header;
2443
+ }
2444
+ async function cachedHeader(context, record) {
2445
+ const config = record.config;
2446
+ if (!config || !record.secret)
2447
+ return;
2448
+ const cached = withState(context, (state) => state.swarmHeader(record.account, record.configUrl));
2449
+ const age = cached ? Date.now() - cached.verifiedAt : NaN;
2450
+ if (!cached ||
2451
+ cached.headId !== config.headId ||
2452
+ (cached.epoch !== undefined && cached.epoch !== config.epoch) ||
2453
+ !(age >= 0 && age < (context.cacheTtl ?? 300) * 1000))
2454
+ return;
2455
+ const cachedSnapshot = object(dagCbor.decode(Buffer.from(cached.snapshot, "base64")), "cached State");
2456
+ const { stateBundle, ...legacySnapshot } = cachedSnapshot;
2457
+ const snapshot = decodeSnapshot(dagCbor.encode(legacySnapshot));
2458
+ if (stateBundle !== undefined) {
2459
+ const data = object(stateBundle, "cached State Bundle");
2460
+ const keys = Object.keys(data).sort().join();
2461
+ if (![
2462
+ "cid,meta",
2463
+ "cid,configUrl,meta",
2464
+ "cid,configUrl,meta,unixfsRoot",
2465
+ ].includes(keys) ||
2466
+ typeof data.cid !== "string" ||
2467
+ exactCid(data.cid) !== data.cid ||
2468
+ (cached.stateCid !== undefined && data.cid !== cached.stateCid))
2469
+ throw new HostError("Invalid cached State Bundle.");
2470
+ const meta = parseSwarmMeta(data.meta);
2471
+ if (data.unixfsRoot !== undefined) {
2472
+ const rootInfo = object(data.unixfsRoot, "cached UnixFS root");
2473
+ if (rootInfo.version !== 7 ||
2474
+ typeof rootInfo.entryFile !== "string" ||
2475
+ typeof rootInfo.typeFile !== "string")
2476
+ throw new HostError("Invalid cached v7 UnixFS root metadata.");
2477
+ const parsed = parseSwarmRootState({
2478
+ v: 7,
2479
+ configUrl: data.configUrl,
2480
+ ...meta,
2481
+ });
2482
+ snapshot.stateBundle = {
2483
+ meta,
2484
+ cid: data.cid,
2485
+ configUrl: parsed.configUrl,
2486
+ unixfsRoot: {
2487
+ version: 7,
2488
+ entryFile: rootInfo.entryFile,
2489
+ typeFile: rootInfo.typeFile,
2490
+ },
2491
+ };
2492
+ }
2493
+ else {
2494
+ const parsed = parseSwarmState({
2495
+ v: data.configUrl === undefined ? 5 : 6,
2496
+ ...meta,
2497
+ ...(data.configUrl === undefined ? {} : { configUrl: data.configUrl }),
2498
+ names: {},
2499
+ });
2500
+ snapshot.stateBundle = {
2501
+ meta,
2502
+ cid: data.cid,
2503
+ ...(parsed.configUrl === undefined
2504
+ ? {}
2505
+ : { configUrl: parsed.configUrl }),
2506
+ };
2507
+ }
2508
+ checkStateOrigin(snapshot, record.configUrl);
2509
+ }
2510
+ let stateCid = cached.stateCid;
2511
+ if (!stateCid) {
2512
+ const headRoot = headValue(cached.head).root;
2513
+ if (CID.parse(headRoot).code === dagPb.code) {
2514
+ stateCid = headRoot;
2515
+ }
2516
+ else {
2517
+ try {
2518
+ stateCid = (await readPublication(context.store, headRoot)).state.toString();
2519
+ }
2520
+ catch (cause) {
2521
+ if (cause instanceof ContentError && cause.code === "missing_block")
2522
+ return;
2523
+ throw cause;
2524
+ }
2525
+ }
2526
+ }
2527
+ return {
2528
+ head: headValue(cached.head),
2529
+ snapshot,
2530
+ stateCid,
2531
+ config,
2532
+ source: "cache",
2533
+ verifiedAt: new Date(cached.verifiedAt).toISOString(),
2534
+ };
2535
+ }
2536
+ function projectHeader(context, record, header) {
2537
+ const member = header.config.members.find((item) => item.publicKey === record.account);
2538
+ if (!member || record.owner !== header.config.owner)
2539
+ throw new HostError("Projection membership does not match the verified account.");
2540
+ const binding = {
2541
+ account: record.account,
2542
+ swarm: record.configUrl,
2543
+ stateCid: header.stateCid,
2544
+ root: header.head.root,
2545
+ valueCid: header.head.cid,
2546
+ verifiedAt: Date.parse(header.verifiedAt),
2547
+ headId: header.config.headId,
2548
+ epoch: header.config.epoch,
2549
+ membership: JSON.stringify({ owner: record.owner, member }),
2550
+ };
2551
+ withState(context, (state) => {
2552
+ state.projectSwarm(binding, header.snapshot.names, () => []);
2553
+ });
2554
+ header.projection = binding;
2555
+ }
2556
+ function headerProjection(header) {
2557
+ if (!header.projection)
2558
+ throw new HostError("A verified account projection is required.");
2559
+ return header.projection;
2560
+ }
2561
+ async function localHeader(context, url) {
2562
+ if (context.forceRefresh)
2563
+ return;
2564
+ canonicalSwarmUrl(url);
2565
+ const record = await localForRead(context, url);
2566
+ const header = await cachedHeader(context, record);
2567
+ if (!header)
2568
+ return;
2569
+ const config = parseOrganization(header.config, url, false);
2570
+ const member = config.members.find((item) => item.publicKey === record.account);
2571
+ if (!member || config.owner !== record.owner)
2572
+ throw new HostError("Cached membership no longer matches the account or Owner.");
2573
+ if (record.account !== config.owner &&
2574
+ (config.v === 3
2575
+ ? typeof member.approvalId !== "string"
2576
+ : !record.request ||
2577
+ record.request.v !== 1 ||
2578
+ record.request.id !== member.requestId ||
2579
+ record.request.peerId !== member.peerId ||
2580
+ !member.approval))
2581
+ throw new HostError("Cached membership does not match the saved Request.");
2582
+ await validateMembershipSecret(record, config, member);
2583
+ const c = coordinates(url);
2584
+ await checkCachedNode(context.stateDir, nodeScope(c.service, c.scopeId), config.epoch, member.peerId);
2585
+ projectHeader(context, record, header);
2586
+ if (withState(context, (state) => state
2587
+ .contentPins()
2588
+ .some((pin) => pin.swarm === url && pin.status !== "deleting"))) {
2589
+ await lazyPrivateSource(context, url, record.account, header.config);
2590
+ header.localSourceReady = true;
2591
+ await refreshNamePins(context, url, header);
2592
+ }
2593
+ return { header, account: record.account };
2594
+ }
2595
+ // SharedContent invokes this source only after a genuine local ENOENT. Its
2596
+ // store is not replaced from inside its own pending read (which would deadlock).
2597
+ async function lazyPrivateSource(context, url, account, basis) {
2598
+ const finishPrevious = context.finishRead;
2599
+ delete context.finishRead;
2600
+ await finishPrevious?.();
2601
+ const lifetime = new AbortController();
2602
+ let pending;
2603
+ const load = async (signal) => {
2604
+ const scoped = { ...context };
2605
+ // Re-read the protected HOME binding and live approval on the first miss;
2606
+ // do not serve an old resolved Name through a different epoch or identity.
2607
+ delete scoped.identity;
2608
+ const authorize = async () => {
2609
+ const record = await approvedMembership(scoped, url, signal);
2610
+ signal.throwIfAborted();
2611
+ if (record.account !== account ||
2612
+ record.config.owner !== basis.owner ||
2613
+ record.config.epoch !== basis.epoch ||
2614
+ record.config.headId !== basis.headId)
2615
+ throw new HostError("Swarm membership changed since this cached HEAD; retry with --refresh.");
2616
+ const { source } = await privateSource(scoped, record, signal);
2617
+ await context.ensureDaemon?.();
2618
+ return source;
2619
+ };
2620
+ // Same lock order as Owner rotation: credentials first, then the node.
2621
+ return withPrivateLock(await directory(scoped), authorize, signal);
2622
+ };
2623
+ const store = context.store.withLocalSource({
2624
+ block: {
2625
+ async get(cid, options = {}) {
2626
+ const signal = options.signal
2627
+ ? AbortSignal.any([lifetime.signal, options.signal])
2628
+ : lifetime.signal;
2629
+ signal.throwIfAborted();
2630
+ const source = await (pending ??= load(signal));
2631
+ signal.throwIfAborted();
2632
+ return source.block.get(cid, { signal });
2633
+ },
2634
+ },
2635
+ });
2636
+ await context.store.close();
2637
+ context.store = store;
2638
+ delete context.node;
2639
+ delete context.sourcePeers;
2640
+ context.finishRead = async () => {
2641
+ lifetime.abort();
2642
+ await pending?.catch(() => { });
2643
+ };
2644
+ }
2645
+ export async function createSwarm(context, options = {}) {
2646
+ if ((options.properties?.name.length ?? 0) > 256 ||
2647
+ (options.properties?.description.length ?? 0) > 2048 ||
2648
+ (options.addresses?.length ?? 0) > 16)
2649
+ throw new HostError("Organization name/description or address limit exceeded.");
2650
+ const service = canonicalService(context.pointerService ?? "");
2651
+ if (!context.pointerApiKey ||
2652
+ (options.service && options.service !== service))
2653
+ throw new HostError("Configure origin-bound pointers.service/apiKey before creating a Scope.");
2654
+ const identity = await contextIdentity(context, true), op = options.resume ?? uniqueId(), dir = await directory(context);
2655
+ const personal = await ensureAccountProfile(context);
2656
+ if (!POINTER_ID_PATTERN.test(op))
2657
+ throw new HostError("Invalid creation resume ID.");
2658
+ return withPrivateLock(dir, async () => {
2659
+ let record = await readPrivate(dir, `creation-${op}.json`);
2660
+ if (options.alias !== undefined) {
2661
+ const existingUrl = record?.scopeId && record.configId
2662
+ ? `${service}/v1/${record.scopeId}/${record.configId}`
2663
+ : undefined;
2664
+ withState(context, (state) => {
2665
+ state.checkSwarmAlias(options.alias, existingUrl);
2666
+ });
2667
+ }
2668
+ if (!record) {
2669
+ if (options.resume)
2670
+ throw new HostError("Unknown creation operation.");
2671
+ record = {
2672
+ stateVersion: 7,
2673
+ owner: identity.publicKey,
2674
+ service,
2675
+ key: randomBytes(32).toString("hex"),
2676
+ name: options.properties?.name ?? "",
2677
+ description: options.properties?.description ?? "",
2678
+ createdAt: new Date().toISOString(),
2679
+ personal: { name: personal.name, description: personal.description },
2680
+ };
2681
+ await writePrivate(dir, `creation-${op}.json`, record);
2682
+ }
2683
+ if (record.owner !== identity.publicKey || record.service !== service)
2684
+ throw new HostError("Creation belongs to another Owner or service.");
2685
+ const save = () => writePrivate(dir, `creation-${op}.json`, record);
2686
+ const api = client(context, service, identity);
2687
+ const reservesConfig = record.stateVersion === 6 || record.stateVersion === 7;
2688
+ try {
2689
+ if (reservesConfig) {
2690
+ if (!record.scopeId) {
2691
+ record.scopeId = (await api.createScope(`${op}.scope`)).id;
2692
+ await save();
2693
+ }
2694
+ if (!record.configId) {
2695
+ // Reserve the Config address, not a Config or a temporary HEAD.
2696
+ const reservation = await api.create(record.scopeId, {
2697
+ v: 1,
2698
+ kind: "ipab-config-reservation",
2699
+ owner: record.owner,
2700
+ operation: op,
2701
+ }, `${op}.config-reserve`);
2702
+ record.configId = reservation.id;
2703
+ record.configReservationCid = reservation.cid;
2704
+ await save();
2705
+ }
2706
+ }
2707
+ if (!record.seed) {
2708
+ if (record.headId)
2709
+ throw new HostError("Legacy creation has an unseeded HEAD. Preserve this recovery record and explicitly migrate the Swarm; it cannot complete as a newly seeded Swarm.");
2710
+ const names = {};
2711
+ for (const selector of seedTemplateNames) {
2712
+ const template = await seedTemplateSource(selector);
2713
+ for (const [cid, data] of template.blocks)
2714
+ await context.store.put(CID.parse(cid), data);
2715
+ names[`ipab/templates/${selector}`] = CID.parse(template.cid);
2716
+ }
2717
+ const skill = await seedSkillSource();
2718
+ for (const [cid, data] of skill.blocks)
2719
+ await context.store.put(CID.parse(cid), data);
2720
+ names["ipab/skills/ipab"] = CID.parse(skill.cid);
2721
+ let root;
2722
+ if (record.stateVersion === 7) {
2723
+ let currentRoot = CID.parse(await writeV7RootBundle(context.store, {
2724
+ templatePath: "ipab/templates",
2725
+ registryPath: "ipab/registry",
2726
+ skillPath: "ipab/skills",
2727
+ }, `${service}/v1/${record.scopeId}/${record.configId}`));
2728
+ for (const [path, targetCid] of Object.entries(names)) {
2729
+ currentRoot = (await setUnixfsPath(context.store, currentRoot, path, targetCid)).newRootCid;
2730
+ }
2731
+ root = currentRoot.toString();
2732
+ }
2733
+ else {
2734
+ root = await publication(context.store, await writeStateBundle(context.store, {
2735
+ templatePath: "ipab/templates",
2736
+ registryPath: "ipab/registry",
2737
+ skillPath: "ipab/skills",
2738
+ }, names, record.stateVersion === 6
2739
+ ? `${service}/v1/${record.scopeId}/${record.configId}`
2740
+ : undefined));
2741
+ }
2742
+ const roots = await frozenPublicationClosure(context.store, root);
2743
+ record.seed = {
2744
+ root,
2745
+ roots,
2746
+ car: Buffer.from(await contentCar(context.store, roots)).toString("base64"),
2747
+ };
2748
+ await save();
2749
+ }
2750
+ const seedBytes = Buffer.from(record.seed.car, "base64");
2751
+ const seed = await CarBlockIterator.fromIterable(streamChunks(new Blob([seedBytes]).stream()));
2752
+ for await (const block of seed)
2753
+ await context.store.put(block.cid, block.bytes);
2754
+ if (!record.scopeId) {
2755
+ record.scopeId = (await api.createScope(`${op}.scope`)).id;
2756
+ await save();
2757
+ }
2758
+ const node = await prepareNode(context.stateDir, nodeScope(service, record.scopeId), context.listen, identity);
2759
+ if (!record.headId) {
2760
+ record.headId = (await api.create(record.scopeId, { root: record.seed.root }, `${op}.head`)).id;
2761
+ await save();
2762
+ }
2763
+ if (!record.profileId) {
2764
+ if (!record.profile) {
2765
+ const addresses = options.addresses ?? [];
2766
+ for (const address of addresses)
2767
+ validateAddress(address, node.peerId);
2768
+ record.profile = {
2769
+ ...(record.personal ?? { name: record.name }),
2770
+ addresses,
2771
+ pivot: context.pivot ?? false,
2772
+ updatedAt: record.createdAt,
2773
+ };
2774
+ await save();
2775
+ }
2776
+ record.profileId = (await api.create(record.scopeId, record.profile, `${op}.profile`)).id;
2777
+ await save();
2778
+ }
2779
+ if (!record.config) {
2780
+ record.config = {
2781
+ v: 3,
2782
+ scopeId: record.scopeId,
2783
+ owner: identity.publicKey,
2784
+ name: record.name,
2785
+ description: record.description,
2786
+ headId: record.headId,
2787
+ epoch: 1,
2788
+ bootstrap: [],
2789
+ members: [
2790
+ {
2791
+ publicKey: identity.publicKey,
2792
+ role: context.pivot ? "pivot" : "ordinary",
2793
+ peerId: node.peerId,
2794
+ profileId: record.profileId,
2795
+ approvalId: null,
2796
+ },
2797
+ ],
2798
+ };
2799
+ await save();
2800
+ }
2801
+ if (!record.configId) {
2802
+ record.configId = (await api.create(record.scopeId, configValue(record.config), `${op}.config`)).id;
2803
+ await save();
2804
+ }
2805
+ if (reservesConfig && !record.configPublished) {
2806
+ if (!record.configReservationCid)
2807
+ throw new HostError("Creation Config reservation checkpoint is missing.");
2808
+ const value = configValue(record.config);
2809
+ const current = await api.read(record.scopeId, record.configId);
2810
+ if (current.cid !== (await valueCid(value))) {
2811
+ if (current.cid !== record.configReservationCid)
2812
+ throw new HostError("Creation Config reservation was changed; refusing to overwrite it.");
2813
+ await api.write(record.scopeId, record.configId, value, record.configReservationCid, `${op}.config`);
2814
+ }
2815
+ record.configPublished = true;
2816
+ await save();
2817
+ }
2818
+ const configUrl = `${service}/v1/${record.scopeId}/${record.configId}`;
2819
+ const cert = await issueScopeCertificate({
2820
+ v: 1,
2821
+ service,
2822
+ scopeId: record.scopeId,
2823
+ subject: identity.publicKey,
2824
+ write: [record.headId, record.profileId],
2825
+ }, await importPrivateKeyPkcs8(identity.privateKey));
2826
+ const membership = {
2827
+ configUrl,
2828
+ owner: identity.publicKey,
2829
+ account: identity.publicKey,
2830
+ config: record.config,
2831
+ secret: { certificate: cert, swarmKey: record.key },
2832
+ };
2833
+ await saveLocal(context, membership);
2834
+ await activate(context, membership);
2835
+ const head = await api.read(record.scopeId, record.headId);
2836
+ await provideContent(context.store, [...new Set([headValue(head).root, ...record.seed.roots])], context.node.api, context.fetch, context.node.auth);
2837
+ withState(context, (state) => state.registerSwarm(configUrl, options.alias));
2838
+ return configUrl;
2839
+ }
2840
+ catch (cause) {
2841
+ throw new HostError(`Swarm creation incomplete: ${message(cause)}. Resume only with swarm create --resume ${op}.`);
2842
+ }
2843
+ });
2844
+ }
2845
+ const requestMessageV2 = (request) => JSON.stringify(["IPAB-REQUEST/2", request]);
2846
+ const legacyRequestMessage = (request) => JSON.stringify(["IPAB-REQUEST/1", request]);
2847
+ const requestDigest = (request) => createHash("sha256").update(JSON.stringify(request)).digest("hex");
2848
+ export async function exportRequest(context, url, output) {
2849
+ const record = await local(context, canonicalSwarmUrl(url));
2850
+ if (!record.request)
2851
+ throw new HostError("Owner membership has no Request.");
2852
+ const handle = await open(output, "wx", 0o600);
2853
+ try {
2854
+ await handle.writeFile(`${JSON.stringify(record.request, null, 2)}\n`);
2855
+ await handle.sync();
2856
+ }
2857
+ finally {
2858
+ await handle.close();
2859
+ }
2860
+ return record.request.member;
2861
+ }
2862
+ export async function requestMembership(context, url, options) {
2863
+ if ("name" in options)
2864
+ throw new HostError("Set your account-wide name with ipab profile --name NAME; membership requests no longer embed display names.");
2865
+ const desiredRole = options.role ?? "ordinary";
2866
+ canonicalSwarmUrl(url);
2867
+ const identity = await contextIdentity(context, true);
2868
+ const { config } = await fetchConfig(context, url);
2869
+ const dir = await directory(context);
2870
+ await withPrivateLock(dir, async () => {
2871
+ const existing = await readPrivate(dir, localName(url));
2872
+ if (existing) {
2873
+ if (existing.account !== identity.publicKey ||
2874
+ existing.owner !== config.owner)
2875
+ throw new HostError("Existing Request belongs to a different identity or pinned Owner.");
2876
+ if (!existing.request)
2877
+ throw new HostError("This identity is already the Owner.");
2878
+ if (existing.request.v === 2 &&
2879
+ (options.role === undefined || existing.request.role === desiredRole))
2880
+ return;
2881
+ }
2882
+ const body = {
2883
+ v: 2,
2884
+ requestedAt: new Date().toISOString(),
2885
+ configUrl: url,
2886
+ owner: config.owner,
2887
+ member: identity.publicKey,
2888
+ role: desiredRole,
2889
+ };
2890
+ const request = {
2891
+ ...body,
2892
+ signature: await signEd25519(await importPrivateKeyPkcs8(identity.privateKey), requestMessageV2(body)),
2893
+ };
2894
+ await saveLocal(context, {
2895
+ configUrl: url,
2896
+ owner: config.owner,
2897
+ account: identity.publicKey,
2898
+ request,
2899
+ });
2900
+ });
2901
+ const file = options.output === undefined ? undefined : resolve(options.output);
2902
+ if (file !== undefined)
2903
+ await exportRequest(context, url, file);
2904
+ const record = await local(context, url);
2905
+ if (!record.request || record.request.v !== 2)
2906
+ throw new HostError("Stored Request is not a valid v2 Request.");
2907
+ return {
2908
+ ownerFingerprint: await keyId(record.owner),
2909
+ request: record.request,
2910
+ ...(file === undefined ? {} : { file }),
2911
+ };
2912
+ }
2913
+ export async function verifiedRequest(path) {
2914
+ if ((await lstat(path)).size > 16 * 1024)
2915
+ throw new HostError("Request file exceeds 16 KiB.");
2916
+ return verifiedRequestStream(createReadStream(path));
2917
+ }
2918
+ export async function verifiedRequestStream(input) {
2919
+ const chunks = [];
2920
+ let size = 0;
2921
+ for await (const chunk of input) {
2922
+ const bytes = typeof chunk === "string" ? Buffer.from(chunk) : chunk;
2923
+ size += bytes.byteLength;
2924
+ if (size > 16 * 1024)
2925
+ throw new HostError("Request input exceeds 16 KiB.");
2926
+ chunks.push(bytes);
2927
+ }
2928
+ let value;
2929
+ try {
2930
+ value = JSON.parse(Buffer.concat(chunks)
2931
+ .toString("utf8")
2932
+ .replace(/^\uFEFF/, ""));
2933
+ }
2934
+ catch (cause) {
2935
+ throw new HostError(`Invalid Request JSON: ${message(cause)}.`);
2936
+ }
2937
+ return verifyRequest(value);
2938
+ }
2939
+ async function verifyRequest(input) {
2940
+ const fields = object(input, "Request");
2941
+ if (fields.v === 1)
2942
+ throw new HostError("Legacy Request v1 is unsupported; ask the applicant to regenerate a Request with swarm request.");
2943
+ if (Object.keys(fields).sort().join() !==
2944
+ "configUrl,member,owner,requestedAt,role,signature,v" ||
2945
+ fields.v !== 2)
2946
+ throw new HostError("Invalid self-contained Request format.");
2947
+ const { member, owner, requestedAt, configUrl, role, signature } = fields;
2948
+ if (!isCanonicalPublicKey(member) ||
2949
+ !isCanonicalPublicKey(owner) ||
2950
+ typeof requestedAt !== "string" ||
2951
+ !Number.isFinite(Date.parse(requestedAt)) ||
2952
+ typeof configUrl !== "string" ||
2953
+ canonicalSwarmUrl(configUrl) !== configUrl ||
2954
+ (role !== "ordinary" && role !== "pivot") ||
2955
+ typeof signature !== "string")
2956
+ throw new HostError("Invalid self-contained Request.");
2957
+ const body = {
2958
+ v: 2,
2959
+ requestedAt,
2960
+ configUrl,
2961
+ owner,
2962
+ member,
2963
+ role,
2964
+ };
2965
+ if (!(await verifyEd25519(await importPublicKeyRaw(member), signature, requestMessageV2(body))))
2966
+ throw new HostError("Request member signature proof is invalid.");
2967
+ return { ...body, signature };
2968
+ }
2969
+ async function verifyLegacyRequest(input) {
2970
+ const fields = object(input, "Request");
2971
+ if (Object.keys(fields).sort().join() !==
2972
+ "configUrl,encryptionKey,id,member,name,owner,peerId,peerPublicKey,peerSignature,requestedAt,scopeId,signature,v" ||
2973
+ fields.v !== 1)
2974
+ throw new HostError("Invalid self-contained Request format.");
2975
+ const { id, member, owner, name, encryptionKey, requestedAt, configUrl, scopeId, peerId: requestPeer, peerPublicKey, peerSignature, signature, } = fields;
2976
+ if (typeof id !== "string" ||
2977
+ !POINTER_ID_PATTERN.test(id) ||
2978
+ !isCanonicalPublicKey(member) ||
2979
+ !isCanonicalPublicKey(owner) ||
2980
+ typeof name !== "string" ||
2981
+ name.length > 256 ||
2982
+ typeof encryptionKey !== "string" ||
2983
+ encryptionKey.length > 256 ||
2984
+ typeof requestedAt !== "string" ||
2985
+ !Number.isFinite(Date.parse(requestedAt)) ||
2986
+ typeof configUrl !== "string" ||
2987
+ typeof scopeId !== "string" ||
2988
+ coordinates(configUrl).scopeId !== scopeId ||
2989
+ !isCanonicalPublicKey(peerPublicKey) ||
2990
+ typeof requestPeer !== "string" ||
2991
+ peerId(peerPublicKey) !== requestPeer ||
2992
+ typeof peerSignature !== "string" ||
2993
+ typeof signature !== "string")
2994
+ throw new HostError("Invalid self-contained Request.");
2995
+ const body = {
2996
+ v: 1,
2997
+ id,
2998
+ requestedAt,
2999
+ configUrl,
3000
+ scopeId,
3001
+ owner,
3002
+ name,
3003
+ member,
3004
+ encryptionKey,
3005
+ peerId: requestPeer,
3006
+ peerPublicKey,
3007
+ };
3008
+ if (!(await verifyEd25519(await importPublicKeyRaw(peerPublicKey), peerSignature, legacyRequestMessage(body))) ||
3009
+ !(await verifyEd25519(await importPublicKeyRaw(member), signature, JSON.stringify(["IPAB-REQUEST-MEMBER/1", body, peerSignature]))))
3010
+ throw new HostError("Request member or PeerID possession proof is invalid.");
3011
+ return { ...body, peerSignature, signature };
3012
+ }
3013
+ export async function membershipRequestSummary(request) {
3014
+ return [
3015
+ `Target: ${request.configUrl}`,
3016
+ `Role: ${request.role}`,
3017
+ `Member public key: ${request.member}`,
3018
+ `Member fingerprint: ${await keyId(request.member)}`,
3019
+ `PeerID: ${peerId(request.member)}`,
3020
+ `Requested at: ${JSON.stringify(request.requestedAt)}`,
3021
+ "Verify the applicant through an independent trusted channel before approving.",
3022
+ ].join("\n");
3023
+ }
3024
+ async function ownerCheck(context, url) {
3025
+ const identity = await contextIdentity(context), record = await readyMembership(context, url);
3026
+ if (identity.publicKey !== record.owner)
3027
+ throw new HostError("Only the pinned Owner can manage membership or organization configuration.");
3028
+ const transition = await readPrivate(await directory(context), `transition-${localName(url)}`);
3029
+ if (transition && !transition.completed)
3030
+ throw new HostError("Organization switch incomplete: run swarm resume for this URL before other Owner changes.");
3031
+ return { identity, record };
3032
+ }
3033
+ export async function approveMembership(context, input, options = {}) {
3034
+ const request = typeof input === "string"
3035
+ ? await verifiedRequest(input)
3036
+ : await verifyRequest(input), url = request.configUrl;
3037
+ const dir = await directory(context);
3038
+ return withPrivateLock(dir, async () => {
3039
+ const { identity, record } = await ownerCheck(context, url);
3040
+ if (request.owner !== identity.publicKey)
3041
+ throw new HostError("Request targets a different Owner.");
3042
+ const journalName = `approval-${requestDigest(request)}.json`;
3043
+ let operation = await readPrivate(dir, journalName);
3044
+ if (operation && !operation.completed && options.again)
3045
+ throw new HostError("The prior approval is unconfirmed; resume the same Request without --again before starting a new explicit approval.");
3046
+ if (operation?.completed && !options.again) {
3047
+ if (operation.owner !== identity.publicKey ||
3048
+ JSON.stringify(operation.request) !== JSON.stringify(request))
3049
+ throw new HostError("This Request differs from advisory history; manually verify it and use --again for a new explicit approval.");
3050
+ if (Boolean(operation.pivot) !== Boolean(options.pivot))
3051
+ throw new HostError("This Request was previously approved with different Pivot authority; use swarm pivot grant or --again after fresh manual confirmation.");
3052
+ context.diagnostic?.(`Previously approved Request from ${request.member} at ${request.requestedAt}. History is advisory, not a revocation boundary.`);
3053
+ context.diagnostic?.("Reusing the completed approval result without granting new authority. Use --again only after fresh manual confirmation.");
3054
+ return url;
3055
+ }
3056
+ if (!operation || options.again) {
3057
+ operation = {
3058
+ owner: identity.publicKey,
3059
+ request,
3060
+ operation: uniqueId(),
3061
+ createdAt: new Date().toISOString(),
3062
+ ...(options.pivot ? { pivot: true } : {}),
3063
+ };
3064
+ await writePrivate(dir, journalName, operation);
3065
+ }
3066
+ if (operation.owner !== identity.publicKey ||
3067
+ JSON.stringify(operation.request) !== JSON.stringify(request) ||
3068
+ Boolean(operation.pivot) !== Boolean(options.pivot))
3069
+ throw new HostError("Saved approval does not match this exact Request.");
3070
+ const save = () => writePrivate(dir, journalName, operation);
3071
+ const c = coordinates(url), api = client(context, c.service, identity);
3072
+ const fetched = await fetchConfig(context, url);
3073
+ if (fetched.config.epoch !== record.config.epoch ||
3074
+ fetched.config.headId !== record.config.headId)
3075
+ throw new HostError("Owner local keys are not synchronized with this organization epoch.");
3076
+ if (!operation.profileId) {
3077
+ const existingProfile = fetched.config.members.find((m) => m.publicKey === request.member)?.profileId;
3078
+ if (existingProfile)
3079
+ operation.profileId = existingProfile;
3080
+ if (!operation.profileId)
3081
+ operation.profileId = (await api.create(c.scopeId, {
3082
+ name: "",
3083
+ description: "",
3084
+ addresses: [],
3085
+ ...(operation.pivot || request.role === "pivot"
3086
+ ? { pivot: true }
3087
+ : {}),
3088
+ updatedAt: operation.createdAt,
3089
+ }, `${operation.operation}.profile`)).id;
3090
+ await save();
3091
+ }
3092
+ if (!operation.value) {
3093
+ if (request.member === identity.publicKey)
3094
+ throw new HostError("Owner cannot request member approval.");
3095
+ const previous = fetched.config.members.find((m) => m.publicKey === request.member);
3096
+ const remaining = fetched.config.members.filter((m) => m.publicKey !== request.member);
3097
+ if (remaining.length >= 256)
3098
+ throw new HostError("Organization member limit is 256.");
3099
+ const pendingApprovals = {};
3100
+ const retiredVariables = [];
3101
+ if (previous?.memberId)
3102
+ retiredVariables.push(previous.memberId);
3103
+ if (typeof previous?.approvalId === "string")
3104
+ retiredVariables.push(previous.approvalId);
3105
+ const members = [];
3106
+ const ownerPrivateKey = await importPrivateKeyPkcs8(identity.privateKey);
3107
+ for (const existing of remaining) {
3108
+ const derivedPeer = peerId(existing.publicKey);
3109
+ const existingRole = existing.role ?? (existing.pivotAuthority ? "pivot" : "ordinary");
3110
+ if (existing.publicKey === identity.publicKey) {
3111
+ if (existing.memberId)
3112
+ retiredVariables.push(existing.memberId);
3113
+ members.push({
3114
+ publicKey: existing.publicKey,
3115
+ role: existingRole,
3116
+ peerId: derivedPeer,
3117
+ profileId: existing.profileId,
3118
+ approvalId: null,
3119
+ });
3120
+ continue;
3121
+ }
3122
+ if (fetched.config.v === 3) {
3123
+ members.push({
3124
+ publicKey: existing.publicKey,
3125
+ role: existingRole,
3126
+ peerId: derivedPeer,
3127
+ profileId: existing.profileId,
3128
+ approvalId: existing.approvalId ?? null,
3129
+ });
3130
+ continue;
3131
+ }
3132
+ if (existing.memberId)
3133
+ retiredVariables.push(existing.memberId);
3134
+ const migratedCertificate = await issueScopeCertificate({
3135
+ v: 1,
3136
+ service: c.service,
3137
+ scopeId: c.scopeId,
3138
+ subject: existing.publicKey,
3139
+ write: existingRole === "pivot"
3140
+ ? [fetched.config.headId, existing.profileId]
3141
+ : [existing.profileId],
3142
+ }, ownerPrivateKey);
3143
+ pendingApprovals[existing.publicKey] = sealApprovalV2({
3144
+ configUrl: url,
3145
+ owner: identity.publicKey,
3146
+ member: existing.publicKey,
3147
+ role: existingRole,
3148
+ profileId: existing.profileId,
3149
+ headId: fetched.config.headId,
3150
+ epoch: fetched.config.epoch,
3151
+ }, {
3152
+ certificate: migratedCertificate,
3153
+ swarmKey: record.secret.swarmKey,
3154
+ }, identity);
3155
+ members.push({
3156
+ publicKey: existing.publicKey,
3157
+ role: existingRole,
3158
+ peerId: derivedPeer,
3159
+ profileId: existing.profileId,
3160
+ approvalId: null,
3161
+ });
3162
+ }
3163
+ const effectiveRole = operation.pivot || request.role === "pivot" ? "pivot" : "ordinary";
3164
+ const memberPeer = peerId(request.member);
3165
+ const member = {
3166
+ publicKey: request.member,
3167
+ role: effectiveRole,
3168
+ peerId: memberPeer,
3169
+ profileId: operation.profileId,
3170
+ approvalId: null,
3171
+ };
3172
+ const config = {
3173
+ ...fetched.config,
3174
+ v: 3,
3175
+ members,
3176
+ };
3177
+ const certificate = await issueScopeCertificate({
3178
+ v: 1,
3179
+ service: c.service,
3180
+ scopeId: c.scopeId,
3181
+ subject: request.member,
3182
+ write: effectiveRole === "pivot"
3183
+ ? [config.headId, member.profileId]
3184
+ : [member.profileId],
3185
+ }, ownerPrivateKey);
3186
+ pendingApprovals[request.member] = sealApprovalV2({
3187
+ configUrl: url,
3188
+ owner: identity.publicKey,
3189
+ member: request.member,
3190
+ role: effectiveRole,
3191
+ profileId: member.profileId,
3192
+ headId: config.headId,
3193
+ epoch: config.epoch,
3194
+ }, { certificate, swarmKey: record.secret.swarmKey }, identity);
3195
+ config.members.push(member);
3196
+ operation.value = config;
3197
+ operation.pendingApprovals = pendingApprovals;
3198
+ operation.retiredVariables = retiredVariables;
3199
+ operation.baseline = fetched.variable.cid;
3200
+ await save();
3201
+ }
3202
+ if (operation.value.v === 3) {
3203
+ for (const member of operation.value.members) {
3204
+ if (member.publicKey !== identity.publicKey && !member.approvalId) {
3205
+ const envelope = operation.pendingApprovals?.[member.publicKey];
3206
+ if (!envelope)
3207
+ throw new HostError("Saved approval is missing its pending approval envelope.");
3208
+ member.approvalId = await createApprovalRecord(api, c.scopeId, envelope, `${operation.operation}.${member.publicKey}.approval`);
3209
+ delete operation.pendingApprovals[member.publicKey];
3210
+ await save();
3211
+ }
3212
+ }
3213
+ }
3214
+ const observed = await api.read(c.scopeId, c.configId);
3215
+ if (observed.cid !== (await valueCid(configValue(operation.value))))
3216
+ await api.write(c.scopeId, c.configId, configValue(operation.value), operation.baseline, `${operation.operation}.publish`);
3217
+ for (const variableId of operation.retiredVariables ?? []) {
3218
+ await retireVariable(api, c.scopeId, variableId, `${operation.operation}.retire.${variableId}`);
3219
+ }
3220
+ operation.completed = true;
3221
+ await save();
3222
+ record.config = operation.value;
3223
+ await saveLocal(context, record);
3224
+ return url;
3225
+ });
3226
+ }
3227
+ export async function grantPivotAuthority(context, url, memberPublicKey) {
3228
+ if (!isCanonicalPublicKey(memberPublicKey))
3229
+ throw new HostError("Invalid member public key.");
3230
+ const dir = await directory(context);
3231
+ return withPrivateLock(dir, async () => {
3232
+ const { identity, record } = await ownerCheck(context, url);
3233
+ if (memberPublicKey === identity.publicKey)
3234
+ throw new HostError("Owner already holds full Scope authority.");
3235
+ const c = coordinates(url), api = client(context, c.service, identity);
3236
+ for (let attempt = 0; attempt < 4; attempt++) {
3237
+ const fetched = await fetchConfig(context, url);
3238
+ if (fetched.config.epoch !== record.config.epoch ||
3239
+ fetched.config.headId !== record.config.headId)
3240
+ throw new HostError("Owner local keys are not synchronized with this organization epoch.");
3241
+ const existing = fetched.config.members.find((m) => m.publicKey === memberPublicKey);
3242
+ if (!existing)
3243
+ throw new HostError("Unknown member public key.");
3244
+ const certificate = await issueScopeCertificate({
3245
+ v: 1,
3246
+ service: c.service,
3247
+ scopeId: c.scopeId,
3248
+ subject: existing.publicKey,
3249
+ write: [fetched.config.headId, existing.profileId],
3250
+ }, await importPrivateKeyPkcs8(identity.privateKey));
3251
+ const approval = sealApprovalV2({
3252
+ configUrl: url,
3253
+ owner: identity.publicKey,
3254
+ member: existing.publicKey,
3255
+ role: "pivot",
3256
+ profileId: existing.profileId,
3257
+ headId: fetched.config.headId,
3258
+ epoch: fetched.config.epoch,
3259
+ }, { certificate, swarmKey: record.secret.swarmKey }, identity);
3260
+ const newApprovalId = await createApprovalRecord(api, c.scopeId, approval, uniqueId());
3261
+ const updatedMember = {
3262
+ publicKey: existing.publicKey,
3263
+ role: "pivot",
3264
+ peerId: peerId(existing.publicKey),
3265
+ profileId: existing.profileId,
3266
+ approvalId: newApprovalId,
3267
+ };
3268
+ const nextConfig = {
3269
+ ...fetched.config,
3270
+ v: 3,
3271
+ members: fetched.config.members.map((m) => m.publicKey === memberPublicKey ? updatedMember : m),
3272
+ };
3273
+ try {
3274
+ await api.write(c.scopeId, c.configId, configValue(nextConfig), fetched.variable.cid, uniqueId());
3275
+ }
3276
+ catch (cause) {
3277
+ if (cause instanceof ScopeApiError && cause.status === 412)
3278
+ continue;
3279
+ throw cause;
3280
+ }
3281
+ if (typeof existing.approvalId === "string")
3282
+ await retireVariable(api, c.scopeId, existing.approvalId, `grant.${existing.approvalId}`);
3283
+ record.config = nextConfig;
3284
+ await saveLocal(context, record);
3285
+ return {
3286
+ configUrl: url,
3287
+ member: existing.publicKey,
3288
+ headId: fetched.config.headId,
3289
+ };
3290
+ }
3291
+ throw new HostError("Organization configuration is busy; retry granting Pivot authority.");
3292
+ });
3293
+ }
3294
+ export async function updateSwarm(context, url, changes) {
3295
+ if ((changes.name?.length ?? 0) > 256 ||
3296
+ (changes.description?.length ?? 0) > 2048)
3297
+ throw new HostError("Organization name/description limit exceeded.");
3298
+ const { identity, record } = await ownerCheck(context, url), c = coordinates(url);
3299
+ if (changes.name === undefined && changes.description === undefined)
3300
+ throw new HostError("swarm update requires name or description.");
3301
+ const fetched = await fetchConfig(context, url), config = { ...fetched.config, ...changes };
3302
+ const result = await client(context, c.service, identity).write(c.scopeId, c.configId, configValue(config), fetched.variable.cid, uniqueId());
3303
+ record.config = config;
3304
+ await saveLocal(context, record);
3305
+ return {
3306
+ configUrl: url,
3307
+ headId: config.headId,
3308
+ valueCid: result.cid,
3309
+ properties: { name: config.name, description: config.description },
3310
+ };
3311
+ }
3312
+ export async function updateProfile(context, url, changes) {
3313
+ if ("name" in changes || "description" in changes)
3314
+ throw new HostError("Use ipab profile --name NAME --description TEXT for personal data; swarm profile configures network addresses only.");
3315
+ if ((changes.addresses?.length ?? 0) > 16)
3316
+ throw new HostError("Profile address limit is 16.");
3317
+ if (changes.addresses === undefined && changes.pivot === undefined)
3318
+ throw new HostError("swarm profile requires --address MULTIADDR or --pivot true|false; use ipab profile to read personal data.");
3319
+ const record = await readyMembership(context, url), identity = await contextIdentity(context), c = coordinates(url);
3320
+ const member = record.config.members.find((m) => m.publicKey === identity.publicKey);
3321
+ for (const address of changes.addresses ?? [])
3322
+ validateAddress(address, member.peerId);
3323
+ const api = client(context, c.service, identity, identity.publicKey === record.owner ? undefined : record.secret);
3324
+ const existing = await api.read(c.scopeId, member.profileId);
3325
+ const profile = {
3326
+ ...parseProfile(existing.value, member.peerId),
3327
+ ...changes,
3328
+ updatedAt: new Date().toISOString(),
3329
+ };
3330
+ await api.write(c.scopeId, member.profileId, profile, existing.cid, uniqueId());
3331
+ if (changes.pivot !== undefined &&
3332
+ identity.publicKey === record.owner &&
3333
+ record.config.v === 3) {
3334
+ const desiredRole = changes.pivot ? "pivot" : "ordinary";
3335
+ const fetched = await fetchConfig(context, url);
3336
+ const currentOwner = fetched.config.members.find((entry) => entry.publicKey === identity.publicKey);
3337
+ if (fetched.config.v === 3 &&
3338
+ currentOwner &&
3339
+ currentOwner.role !== desiredRole) {
3340
+ const updatedConfig = {
3341
+ ...fetched.config,
3342
+ members: fetched.config.members.map((entry) => entry.publicKey === identity.publicKey
3343
+ ? { ...entry, role: desiredRole }
3344
+ : entry),
3345
+ };
3346
+ await api.write(c.scopeId, c.configId, configValue(updatedConfig), fetched.variable.cid, uniqueId());
3347
+ record.config = updatedConfig;
3348
+ await saveLocal(context, record);
3349
+ }
3350
+ }
3351
+ if (changes.addresses !== undefined)
3352
+ await writePrivate(await directory(context), `pivot-${localName(url)}`, {
3353
+ manual: changes.addresses,
3354
+ });
3355
+ if (changes.addresses !== undefined && !context.pivot)
3356
+ context.diagnostic?.("Manual addresses saved; they are discovery candidates only when swarm.pivot=true. Ordinary nodes do not provide relay service.");
3357
+ return profile;
3358
+ }
3359
+ export async function removeMember(context, url, member) {
3360
+ const dir = await directory(context);
3361
+ await withPrivateLock(dir, async () => {
3362
+ const { identity, record: membership } = await ownerCheck(context, url);
3363
+ if (member === identity.publicKey)
3364
+ throw new HostError("Owner removal/recovery is unsupported.");
3365
+ const fetched = await fetchConfig(context, url);
3366
+ if (!fetched.config.members.some((m) => m.publicKey === member))
3367
+ throw new HostError("Unknown member public key.");
3368
+ const record = {
3369
+ owner: identity.publicKey,
3370
+ url,
3371
+ operation: uniqueId(),
3372
+ member,
3373
+ oldConfig: fetched.config,
3374
+ configCid: fetched.variable.cid,
3375
+ oldKey: membership.secret.swarmKey,
3376
+ newKey: randomBytes(32).toString("hex"),
3377
+ };
3378
+ await writePrivate(dir, `transition-${localName(url)}`, record);
3379
+ });
3380
+ await resumeRemoval(context, url);
3381
+ }
3382
+ export async function resumeRemoval(context, url) {
3383
+ const dir = await directory(context);
3384
+ return withPrivateLock(dir, async () => {
3385
+ const identity = await contextIdentity(context);
3386
+ const record = await readPrivate(dir, `transition-${localName(url)}`);
3387
+ if (!record || record.owner !== identity.publicKey || record.url !== url)
3388
+ throw new HostError("No resumable switch owned by this identity.");
3389
+ if (record.completed)
3390
+ return;
3391
+ const c = coordinates(url), api = client(context, c.service, identity);
3392
+ const save = () => writePrivate(dir, `transition-${localName(url)}`, record);
3393
+ try {
3394
+ if (!record.finalHead) {
3395
+ record.finalHead = await api.freeze(c.scopeId, record.oldConfig.headId, `${record.operation}.freeze`);
3396
+ await save();
3397
+ }
3398
+ // Fetch the frozen final DAG while the old private network is still connected.
3399
+ // A publication acknowledged immediately before freeze may not be cached on Owner.
3400
+ const membershipBeforeSwitch = await local(context, url);
3401
+ if (!record.finalCaptured) {
3402
+ membershipBeforeSwitch.config = record.oldConfig;
3403
+ membershipBeforeSwitch.secret.swarmKey = record.oldKey;
3404
+ await activate(context, membershipBeforeSwitch);
3405
+ await readSnapshot(context.store, headValue(record.finalHead).root, url);
3406
+ if (!record.finalClosureRoots) {
3407
+ record.finalClosureRoots = await frozenPublicationClosure(context.store, headValue(record.finalHead).root);
3408
+ await save();
3409
+ }
3410
+ await provideContent(context.store, record.finalClosureRoots, context.node.api, context.fetch, context.node.auth);
3411
+ record.finalCaptured = true;
3412
+ await save();
3413
+ }
3414
+ if (!record.finalClosureRoots ||
3415
+ record.finalClosureRoots[0] !== headValue(record.finalHead).root)
3416
+ throw new HostError("Frozen publication closure is missing; refusing to retire the old network or HEAD.");
3417
+ if (!record.newHeadId) {
3418
+ record.newHeadId = (await api.create(c.scopeId, record.finalHead.value, `${record.operation}.newhead`)).id;
3419
+ await save();
3420
+ }
3421
+ if (!record.nextConfig) {
3422
+ const pendingApprovals = {};
3423
+ const config = {
3424
+ ...record.oldConfig,
3425
+ v: 3,
3426
+ headId: record.newHeadId,
3427
+ epoch: record.oldConfig.epoch + 1,
3428
+ members: [],
3429
+ bootstrap: record.oldConfig.bootstrap.filter((address) => !address.endsWith(`/p2p/${record.oldConfig.members.find((m) => m.publicKey === record.member).peerId}`)),
3430
+ };
3431
+ const ownerPrivateKey = await importPrivateKeyPkcs8(identity.privateKey);
3432
+ for (const existing of record.oldConfig.members) {
3433
+ if (existing.publicKey === record.member)
3434
+ continue;
3435
+ const derivedPeer = peerId(existing.publicKey);
3436
+ const role = existing.role ?? (existing.pivotAuthority ? "pivot" : "ordinary");
3437
+ const nextMember = {
3438
+ publicKey: existing.publicKey,
3439
+ role,
3440
+ peerId: derivedPeer,
3441
+ profileId: existing.profileId,
3442
+ approvalId: null,
3443
+ };
3444
+ config.members.push(nextMember);
3445
+ if (existing.publicKey === identity.publicKey)
3446
+ continue;
3447
+ const certificate = await issueScopeCertificate({
3448
+ v: 1,
3449
+ service: c.service,
3450
+ scopeId: c.scopeId,
3451
+ subject: existing.publicKey,
3452
+ write: role === "pivot"
3453
+ ? [config.headId, existing.profileId]
3454
+ : [existing.profileId],
3455
+ }, ownerPrivateKey);
3456
+ pendingApprovals[existing.publicKey] = sealApprovalV2({
3457
+ configUrl: url,
3458
+ owner: identity.publicKey,
3459
+ member: existing.publicKey,
3460
+ role,
3461
+ profileId: existing.profileId,
3462
+ headId: config.headId,
3463
+ epoch: config.epoch,
3464
+ }, { certificate, swarmKey: record.newKey }, identity);
3465
+ }
3466
+ record.nextConfig = config;
3467
+ record.pendingApprovals = pendingApprovals;
3468
+ await save();
3469
+ }
3470
+ if (record.nextConfig.v === 3) {
3471
+ for (const member of record.nextConfig.members) {
3472
+ if (member.publicKey !== identity.publicKey && !member.approvalId) {
3473
+ const envelope = record.pendingApprovals?.[member.publicKey];
3474
+ if (!envelope)
3475
+ throw new HostError("Saved rotation is missing its pending approval envelope.");
3476
+ member.approvalId = await createApprovalRecord(api, c.scopeId, envelope, `${record.operation}.${member.publicKey}.approval`);
3477
+ delete record.pendingApprovals[member.publicKey];
3478
+ await save();
3479
+ }
3480
+ }
3481
+ }
3482
+ const leaving = record.oldConfig.members.find((m) => m.publicKey === record.member);
3483
+ // Delete the profile before exposing the new configuration. Old HEAD stays readable until final cleanup.
3484
+ try {
3485
+ await api.freeze(c.scopeId, leaving.profileId, `${record.operation}.profilefreeze`);
3486
+ }
3487
+ catch (cause) {
3488
+ if (!(cause instanceof ScopeApiError) || cause.status !== 410)
3489
+ throw cause;
3490
+ }
3491
+ try {
3492
+ await api.delete(c.scopeId, leaving.profileId, `${record.operation}.profiledelete`);
3493
+ }
3494
+ catch (cause) {
3495
+ if (!(cause instanceof ScopeApiError) || cause.status !== 410)
3496
+ throw cause;
3497
+ }
3498
+ if (!record.published) {
3499
+ const observed = await api.read(c.scopeId, c.configId);
3500
+ if (observed.cid !== (await valueCid(configValue(record.nextConfig))))
3501
+ await api.write(c.scopeId, c.configId, configValue(record.nextConfig), record.configCid, `${record.operation}.config`);
3502
+ record.published = true;
3503
+ await save();
3504
+ }
3505
+ const membership = await local(context, url);
3506
+ membership.config = record.nextConfig;
3507
+ membership.secret.swarmKey = record.newKey;
3508
+ await saveLocal(context, membership);
3509
+ await activate(context, membership);
3510
+ await provideContent(context.store, record.finalClosureRoots, context.node.api, context.fetch, context.node.auth);
3511
+ try {
3512
+ await api.delete(c.scopeId, record.oldConfig.headId, `${record.operation}.delete`);
3513
+ }
3514
+ catch (cause) {
3515
+ if (!(cause instanceof ScopeApiError) || cause.status !== 410)
3516
+ throw cause;
3517
+ }
3518
+ const nextApprovalIds = new Set(record.nextConfig.members
3519
+ .map((next) => next.approvalId)
3520
+ .filter((id) => typeof id === "string"));
3521
+ for (const member of record.oldConfig.members) {
3522
+ const oldIds = [
3523
+ ...(typeof member.approvalId === "string" &&
3524
+ !nextApprovalIds.has(member.approvalId)
3525
+ ? [member.approvalId]
3526
+ : []),
3527
+ ...(member.memberId ? [member.memberId] : []),
3528
+ ];
3529
+ for (const variableId of oldIds) {
3530
+ await retireVariable(api, c.scopeId, variableId, `${record.operation}.${member.publicKey}.${variableId}`);
3531
+ }
3532
+ }
3533
+ record.completed = true;
3534
+ await save();
3535
+ withState(context, (state) => {
3536
+ state.invalidateSwarmHeader(url);
3537
+ });
3538
+ }
3539
+ catch (cause) {
3540
+ throw new HostError(`Organization switch incomplete (old HEAD is never unfrozen): ${message(cause)}. Owner must run swarm resume ${url}.`);
3541
+ }
3542
+ });
3543
+ }
3544
+ export function formalName(name) {
3545
+ relativePath(name);
3546
+ if (name.length > 256 || name.startsWith("builtin:"))
3547
+ throw new HostError("Invalid formal Name.");
3548
+ return name;
3549
+ }
3550
+ function decodeNameComponent(value, part) {
3551
+ try {
3552
+ return decodeURIComponent(value);
3553
+ }
3554
+ catch {
3555
+ throw new HostError(`Malformed percent-encoding in IPAB URI ${part}; use valid UTF-8 escapes or copy the reference from ipab search.`);
3556
+ }
3557
+ }
3558
+ export function parseNameReference(reference) {
3559
+ if (/^name:/i.test(reference))
3560
+ throw new HostError("name: is unsupported; use ipab://ALIAS/PATH.");
3561
+ if (!/^ipab:/i.test(reference))
3562
+ return undefined;
3563
+ if (/^ipab:\/\/https?:\/\//i.test(reference))
3564
+ 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.");
3565
+ const match = /^ipab:\/\/([^/]*)\/(.*)$/is.exec(reference);
3566
+ if (!match)
3567
+ throw new HostError("Invalid IPAB URI; percent-encode the configuration URL authority and each path segment.");
3568
+ const authority = decodeNameComponent(match[1], "authority");
3569
+ if (authority && !/^[A-Za-z0-9][A-Za-z0-9._-]*$/.test(authority)) {
3570
+ if (!/^https?:\/\//i.test(authority))
3571
+ throw new HostError("Invalid IPAB URI authority; use a registered alias or the percent-encoded configuration URL.");
3572
+ canonicalSwarmUrl(authority);
3573
+ }
3574
+ if (/[?#\s]/.test(match[2]))
3575
+ throw new HostError("Invalid IPAB URI path; percent-encode each Name path segment. Queries and fragments are not supported.");
3576
+ const segments = match[2].split("/").map((segment) => {
3577
+ const decoded = decodeNameComponent(segment, "path");
3578
+ if (/[/\\]/.test(decoded))
3579
+ throw new HostError("Invalid IPAB URI path separator; use literal / between Name segments, never an encoded slash or backslash.");
3580
+ return decoded;
3581
+ });
3582
+ try {
3583
+ return {
3584
+ ...(authority ? { swarm: authority } : {}),
3585
+ name: match[2] === "" ? "" : formalName(segments.join("/")),
3586
+ };
3587
+ }
3588
+ catch (error) {
3589
+ if (!(error instanceof HostError))
3590
+ throw error;
3591
+ 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);
3592
+ }
3593
+ }
3594
+ export function formatNameReference(swarm, name) {
3595
+ const segment = (value) => encodeURIComponent(value).replace(/[!'()*]/g, (char) => `%${char.charCodeAt(0).toString(16).toUpperCase()}`);
3596
+ return `ipab://${segment(swarm)}/${name.split("/").map(segment).join("/")}`;
3597
+ }
3598
+ export async function resolveReference(context, reference, swarm, local, raw = false, mode = "active") {
3599
+ const shared = parseNameReference(reference);
3600
+ let source;
3601
+ let targetCid;
3602
+ if (shared) {
3603
+ const selected = shared.swarm
3604
+ ? withState(context, (state) => state.resolveSwarm(shared.swarm))
3605
+ : swarm;
3606
+ if (!selected)
3607
+ throw new HostError("Select a configuration URL/alias using --swarm or swarm use.");
3608
+ const warm = mode === "local-first" ? await localHeader(context, selected) : undefined;
3609
+ let header = warm?.header ?? (await swarmHeader(context, selected));
3610
+ const ensureLazyForV7 = async () => {
3611
+ if (warm && header === warm.header && !header.localSourceReady) {
3612
+ await lazyPrivateSource(context, selected, warm.account, header.config);
3613
+ header.localSourceReady = true;
3614
+ }
3615
+ };
3616
+ const target = async () => {
3617
+ if (shared.name === "")
3618
+ return header.stateCid;
3619
+ try {
3620
+ return (await resolveSnapshotName(context.store, header.snapshot, shared.name))?.toString();
3621
+ }
3622
+ catch (cause) {
3623
+ if (isV7Snapshot(header.snapshot) &&
3624
+ missingContent(cause) &&
3625
+ warm &&
3626
+ header === warm.header &&
3627
+ !header.localSourceReady) {
3628
+ await ensureLazyForV7();
3629
+ return (await resolveSnapshotName(context.store, header.snapshot, shared.name))?.toString();
3630
+ }
3631
+ throw cause;
3632
+ }
3633
+ };
3634
+ let link = await target();
3635
+ if (!link && header.source === "cache") {
3636
+ header = await swarmHeader(context, selected, true);
3637
+ link = await target();
3638
+ }
3639
+ if (!link)
3640
+ throw new HostError(`Formal Name "${shared.name}" was not found after refreshing HEAD.`);
3641
+ await ensureLazyForV7();
3642
+ targetCid = link;
3643
+ source = { configUrl: selected, header };
3644
+ }
3645
+ else {
3646
+ if (swarm)
3647
+ await readyMembership(context, swarm);
3648
+ targetCid = local(reference);
3649
+ }
3650
+ try {
3651
+ const cid = raw ? targetCid : await artifactValue(context.store, targetCid);
3652
+ return { targetCid, cid };
3653
+ }
3654
+ catch (cause) {
3655
+ if (!source)
3656
+ throw cause;
3657
+ return headContentFailure(context, source.configUrl, source.header.config, source.header.head, cause);
3658
+ }
3659
+ }
3660
+ async function artifactValue(store, targetCid, protect) {
3661
+ let cid = targetCid;
3662
+ const visited = new Set();
3663
+ for (let depth = 0;; depth++) {
3664
+ if (depth >= 64 || visited.has(cid))
3665
+ throw new HostError("Artifact resolution exceeds limits or contains a cycle.");
3666
+ visited.add(cid);
3667
+ const parsed = CID.parse(cid);
3668
+ const shallow = await openBundle(parsed, {
3669
+ shallow: true,
3670
+ resolveCid: (key) => store.block.get(key.toString()),
3671
+ });
3672
+ if (isSwarmRootSchema(shallow.schemaKey))
3673
+ break;
3674
+ await protect?.(cid);
3675
+ const bundle = await openBundle(parsed, {
3676
+ resolveCid: (key) => store.block.get(key.toString()),
3677
+ });
3678
+ if (bundle.schemaKey !== (await encodeSchema(artifactType)).cid.toString())
3679
+ break;
3680
+ cid = CID.parse(parseArtifact(await typedJson(store, cid, artifactType)).value)
3681
+ .toV1()
3682
+ .toString();
3683
+ }
3684
+ return cid;
3685
+ }
3686
+ export function pinReference(state, reference, selected) {
3687
+ const shared = parseNameReference(reference);
3688
+ if (!shared)
3689
+ return { reference: exactCid(reference) };
3690
+ const swarm = shared.swarm ? state.resolveSwarm(shared.swarm) : selected;
3691
+ if (!swarm)
3692
+ throw new HostError("Pinning a shared Name requires --swarm or swarm use, or a Swarm authority in the IPAB URI.");
3693
+ return {
3694
+ reference: formatNameReference(swarm, shared.name),
3695
+ swarm,
3696
+ name: shared.name,
3697
+ };
3698
+ }
3699
+ export async function pinNameSubscription(context, reference, selected) {
3700
+ const canonical = withState(context, (state) => pinReference(state, reference, selected));
3701
+ if (!canonical.swarm || canonical.name === undefined) {
3702
+ let roots;
3703
+ try {
3704
+ roots = [
3705
+ ...(await currentDependencies(context.store, canonical.reference)),
3706
+ ];
3707
+ }
3708
+ catch (cause) {
3709
+ if (!selected || !missingContent(cause))
3710
+ throw cause;
3711
+ const swarm = withState(context, (state) => state.resolveSwarm(selected));
3712
+ await readyMembership(context, swarm);
3713
+ roots = [
3714
+ ...(await currentDependencies(context.store, canonical.reference)),
3715
+ ];
3716
+ }
3717
+ return withStateAsync(context, (state) => pinCid(state, canonical.reference, context.store, roots));
3718
+ }
3719
+ const resolved = await resolveReference(context, canonical.reference, canonical.swarm, exactCid, false, "local-first");
3720
+ const roots = await currentDependencies(context.store, resolved.targetCid);
3721
+ const pin = withState(context, (state) => reservePin(state, canonical.reference, context.store.configuration, {
3722
+ swarm: canonical.swarm,
3723
+ name: canonical.name,
3724
+ }));
3725
+ return withStateAsync(context, (state) => retainPin(state, pin, context.store, { ...resolved, roots: [...roots] }));
3726
+ }
3727
+ async function withStateAsync(context, operation) {
3728
+ if (context.state)
3729
+ return operation(context.state);
3730
+ const state = new State(context.stateDir);
3731
+ try {
3732
+ return await operation(state);
3733
+ }
3734
+ finally {
3735
+ state.close();
3736
+ }
3737
+ }
3738
+ export async function refreshNamePins(context, url, header) {
3739
+ const pins = withState(context, (state) => state
3740
+ .contentPins()
3741
+ .filter((pin) => pin.swarm === url && pin.status !== "deleting"));
3742
+ const failures = [];
3743
+ for (const saved of pins) {
3744
+ const target = saved.name === ""
3745
+ ? header.stateCid
3746
+ : (await resolveSnapshotName(context.store, header.snapshot, saved.name))?.toString();
3747
+ if (!target) {
3748
+ withState(context, (state) => {
3749
+ failedPin(state, saved.reference, new Error("Shared Name is missing; keeping its last verified version."), true);
3750
+ });
3751
+ context.diagnostic?.(`Pin ${saved.reference} is missing; its last verified version remains retained.`);
3752
+ continue;
3753
+ }
3754
+ let claimed = false;
3755
+ try {
3756
+ // A cached HEAD can differ from the saved subscription after publication or a failed refresh.
3757
+ if (saved.targetCid === target &&
3758
+ saved.status === "ready" &&
3759
+ saved.freshness === "current")
3760
+ continue;
3761
+ const pin = withState(context, (state) => refreshPinClaim(state, saved));
3762
+ if (!pin)
3763
+ continue;
3764
+ claimed = true;
3765
+ const cid = await artifactValue(context.store, target);
3766
+ const roots = [...(await currentDependencies(context.store, target))];
3767
+ await withStateAsync(context, (state) => retainPin(state, pin, context.store, { cid, targetCid: target, roots }));
3768
+ }
3769
+ catch (cause) {
3770
+ if (claimed)
3771
+ withState(context, (state) => {
3772
+ failedPin(state, saved.reference, cause);
3773
+ });
3774
+ failures.push(`${saved.reference}: ${message(cause)}`);
3775
+ }
3776
+ }
3777
+ if (failures.length)
3778
+ throw new HostError(`Name subscription refresh failed; prior verified versions remain retained:\n${failures.join("\n")}`, 1, "PIN_STALE");
3779
+ }
3780
+ async function currentDependencies(store, root, found = new Set(), allowNonBundle = false) {
3781
+ if (found.has(root))
3782
+ return found;
3783
+ if (found.size >= 64)
3784
+ throw new HostError("Current pin dependency limit exceeded.");
3785
+ found.add(root);
3786
+ const parsed = CID.parse(root);
3787
+ if (parsed.code !== dagPb.code) {
3788
+ if (allowNonBundle)
3789
+ return found;
3790
+ }
3791
+ let shallow;
3792
+ try {
3793
+ shallow = await openBundle(parsed, {
3794
+ shallow: true,
3795
+ resolveCid: (cid) => store.block.get(cid.toString()),
3796
+ });
3797
+ }
3798
+ catch (cause) {
3799
+ if (allowNonBundle &&
3800
+ cause instanceof ContentBundleError &&
3801
+ cause.code !== "ABORTED")
3802
+ return found;
3803
+ throw cause;
3804
+ }
3805
+ if (isSwarmRootSchema(shallow.schemaKey)) {
3806
+ const snapshot = await readV7Root(store, parsed);
3807
+ const walked = await walkUnixfsNames(store, parsed, {
3808
+ skipRootFiles: v7RootSkipFiles(snapshot),
3809
+ });
3810
+ for (const entry of walked.entries)
3811
+ await currentDependencies(store, entry.targetCid, found, true);
3812
+ return found;
3813
+ }
3814
+ const bundle = await openBundle(parsed, {
3815
+ resolveCid: (cid) => store.block.get(cid.toString()),
3816
+ });
3817
+ if (bundle.schemaKey === (await encodeSchema(artifactType)).cid.toString()) {
3818
+ await currentDependencies(store, parseArtifact(await typedJson(store, root, artifactType)).value, found);
3819
+ }
3820
+ else if (bundle.schemaKey === appSchemaCid.toString()) {
3821
+ const app = object((await bundleJson(store, root)).value, "App");
3822
+ if (app.source) {
3823
+ const source = object(app.source, "source");
3824
+ if (typeof source.cid !== "string")
3825
+ throw new HostError("Invalid App source association.");
3826
+ await currentDependencies(store, source.cid, found);
3827
+ }
3828
+ }
3829
+ else if (isSwarmStateSchema(bundle.schemaKey)) {
3830
+ const snapshot = await readState(store, parsed);
3831
+ for (const target of Object.values(snapshot.names))
3832
+ await currentDependencies(store, target.toString(), found);
3833
+ }
3834
+ return found;
3835
+ }
3836
+ /**
3837
+ * Queries a v7 UnixFS Swarm via the unified Pivot service:
3838
+ * - Self-Pivot shortcut: if this node is an active Pivot with a ready local index,
3839
+ * queries local SQLite directly without dialing itself over libp2p.
3840
+ * - Otherwise, discovers declared Pivot peers, ranks them using daemon observations,
3841
+ * and queries `GET /v1/search` over Kubo P2P stream `/x/ipab-pivot/1.0.0` with failover.
3842
+ * - Never silently falls back to partial local traversal on v7.
3843
+ */
3844
+ async function searchV7ViaPivot(context, configUrl, header, params) {
3845
+ const validated = validateSearchParams(params);
3846
+ if (context.pivot === true) {
3847
+ const localResult = withState(context, (state) => queryLocalSearchIndex(state, configUrl, validated));
3848
+ if (localResult)
3849
+ return localResult;
3850
+ }
3851
+ const record = await localForRead(context, configUrl);
3852
+ const config = record.config ?? header.config;
3853
+ const self = config.members.find((member) => member.publicKey === record.account);
3854
+ if (!self)
3855
+ throw new HostError(`No Pivot search service is available for Swarm ${configUrl}: local account is not an active member.`);
3856
+ const c = coordinates(configUrl);
3857
+ let snapshot = null;
3858
+ try {
3859
+ const observed = await readNetworkingSnapshot(context.stateDir, configUrl, networkingBinding(configUrl, record.account, config), nodeScope(c.service, config.scopeId), config.epoch, self.peerId);
3860
+ if (observed.status === "current" && observed.snapshot)
3861
+ snapshot = observed.snapshot;
3862
+ }
3863
+ catch (cause) {
3864
+ context.diagnostic?.(`Local daemon observations could not be read: ${message(cause)}`);
3865
+ }
3866
+ const publicClient = client(context, c.service);
3867
+ const pivotPeers = new Set();
3868
+ const pivotAddressesByPeer = new Map();
3869
+ const profiles = await boundedMap(config.members, async (member) => {
3870
+ try {
3871
+ return await publicClient.read(c.scopeId, member.profileId);
3872
+ }
3873
+ catch {
3874
+ return undefined;
3875
+ }
3876
+ });
3877
+ let selfIsPivot = context.pivot === true;
3878
+ for (const [index, member] of config.members.entries()) {
3879
+ const profile = profiles[index];
3880
+ if (member.peerId === self.peerId) {
3881
+ if (context.pivot === undefined && profile) {
3882
+ try {
3883
+ if (parseProfile(profile.value, member.peerId).pivot === true)
3884
+ selfIsPivot = true;
3885
+ }
3886
+ catch {
3887
+ // Ignore malformed self profile.
3888
+ }
3889
+ }
3890
+ continue;
3891
+ }
3892
+ if (profile) {
3893
+ try {
3894
+ const parsed = parseProfile(profile.value, member.peerId);
3895
+ if (parsed.pivot === true) {
3896
+ pivotPeers.add(member.peerId);
3897
+ pivotAddressesByPeer.set(member.peerId, parsed.addresses);
3898
+ }
3899
+ }
3900
+ catch {
3901
+ // Ignore malformed member profile when discovering search Pivots.
3902
+ }
3903
+ }
3904
+ else {
3905
+ const observedPivot = snapshot?.pivots.find((p) => p.peerId === member.peerId);
3906
+ if (observedPivot) {
3907
+ pivotPeers.add(member.peerId);
3908
+ pivotAddressesByPeer.set(member.peerId, observedPivot.addresses);
3909
+ }
3910
+ }
3911
+ }
3912
+ if (selfIsPivot) {
3913
+ const localResult = withState(context, (state) => queryLocalSearchIndex(state, configUrl, validated));
3914
+ if (localResult)
3915
+ return localResult;
3916
+ }
3917
+ const ranked = rankPivotCandidates([...pivotPeers], snapshot);
3918
+ if (!ranked.length) {
3919
+ throw new HostError(`No Pivot search service is available for Swarm ${configUrl}${selfIsPivot ? " (local Pivot index is not yet ready and no other Pivot peers are declared)" : " (no Pivot peers are declared)"}. Ensure a Pivot node is online and running ipab daemon.`);
3920
+ }
3921
+ if (!context.node) {
3922
+ await activate(context, record);
3923
+ }
3924
+ const node = context.node;
3925
+ const failures = [];
3926
+ for (const pivotPeerId of ranked) {
3927
+ try {
3928
+ const pivotAddresses = pivotAddressesByPeer.get(pivotPeerId) ?? [];
3929
+ return await queryRemotePivotSearch({
3930
+ node,
3931
+ pivotPeerId,
3932
+ pivotAddresses,
3933
+ params: validated,
3934
+ ...(context.fetch ? { fetcher: context.fetch } : {}),
3935
+ });
3936
+ }
3937
+ catch (cause) {
3938
+ const detail = message(cause);
3939
+ failures.push(`${pivotPeerId}: ${detail}`);
3940
+ context.diagnostic?.(`[${configUrl}] Pivot search failover from ${pivotPeerId}: ${detail}`);
3941
+ }
3942
+ }
3943
+ throw new HostError(`No Pivot search service is available for Swarm ${configUrl}: all ${ranked.length} Pivot candidate(s) failed (${failures.join("; ")}). Ensure a Pivot node is online and running ipab daemon.`);
3944
+ }
3945
+ export async function searchNames(context, query, swarms, options = {}) {
3946
+ const validated = validateSearchParams({ q: query, ...options });
3947
+ const matches = [];
3948
+ const searched = [];
3949
+ for (const swarm of swarms) {
3950
+ const header = (await localHeader(context, swarm.cid))?.header ??
3951
+ (await swarmHeader(context, swarm.cid, context.forceRefresh, "local-first"));
3952
+ if (isV7Snapshot(header.snapshot)) {
3953
+ const response = await searchV7ViaPivot(context, swarm.cid, header, validated);
3954
+ searched.push({
3955
+ configUrl: swarm.cid,
3956
+ source: header.source,
3957
+ root: header.head.root,
3958
+ valueCid: header.head.cid,
3959
+ verifiedAt: header.verifiedAt,
3960
+ headCid: response.headCid,
3961
+ indexedAt: response.indexedAt,
3962
+ offset: response.offset,
3963
+ limit: response.limit,
3964
+ total: response.total,
3965
+ hasMore: response.hasMore,
3966
+ nextOffset: response.nextOffset,
3967
+ });
3968
+ for (const item of response.matches) {
3969
+ matches.push({
3970
+ swarm: swarm.cid,
3971
+ alias: swarm.alias,
3972
+ name: item.path,
3973
+ reference: formatNameReference(swarm.cid, item.path),
3974
+ targetCid: item.cid,
3975
+ kind: item.kind,
3976
+ ...(item.bundle ? { bundle: item.bundle } : {}),
3977
+ });
3978
+ }
3979
+ }
3980
+ else {
3981
+ searched.push({
3982
+ configUrl: swarm.cid,
3983
+ source: header.source,
3984
+ root: header.head.root,
3985
+ valueCid: header.head.cid,
3986
+ verifiedAt: header.verifiedAt,
3987
+ });
3988
+ const found = withState(context, (state) => state.searchSwarmNames(headerProjection(header), validated.q));
3989
+ for (const { name, targetCid } of found)
3990
+ matches.push({
3991
+ swarm: swarm.cid,
3992
+ alias: swarm.alias,
3993
+ name,
3994
+ reference: formatNameReference(swarm.cid, name),
3995
+ targetCid,
3996
+ });
3997
+ }
3998
+ }
3999
+ return { matches, swarms: searched };
4000
+ }
4001
+ function assertNamesRegistry(snapshot) {
4002
+ if (Object.keys(snapshot.registrations ?? {}).length)
4003
+ throw new HostError("Legacy shared registrations are inactive; per-association argv is unsupported and has not been dropped or migrated. Create a new seeded Swarm and explicitly register intended Apps there. Old Swarm content and history remain readable.");
4004
+ }
4005
+ export async function swarmMeta(context, header) {
4006
+ if (header.snapshot.stateBundle)
4007
+ return header.snapshot.stateBundle.meta;
4008
+ const cid = header.snapshot.names.ipab;
4009
+ if (!cid)
4010
+ throw new HostError('Swarm Meta Name "ipab" is missing. Create a new seeded Swarm or explicitly publish a typed Swarm Meta Bundle; existing Swarms are never automatically upgraded.');
4011
+ try {
4012
+ const bundle = await openBundle(cid, {
4013
+ resolveCid: (key) => context.store.block.get(key.toString()),
4014
+ });
4015
+ const type = bundle.schemaKey === legacySwarmMetaSchema.cid.toString()
4016
+ ? legacySwarmMetaType
4017
+ : swarmMetaType;
4018
+ return parseSwarmMeta(await typedJson(context.store, cid.toString(), type));
4019
+ }
4020
+ catch (cause) {
4021
+ throw new HostError(`Invalid Swarm Meta at Name "ipab": ${message(cause)}. Publish a valid typed Meta Bundle explicitly; no builtin or legacy fallback is used.`);
4022
+ }
4023
+ }
4024
+ function metaCid(snapshot) {
4025
+ return snapshot.stateBundle?.cid ?? snapshot.names.ipab.toString();
4026
+ }
4027
+ function hasMeta(snapshot) {
4028
+ return (snapshot.stateBundle !== undefined || Object.hasOwn(snapshot.names, "ipab"));
4029
+ }
4030
+ export async function swarmSkills(context, configUrl, requested, owner) {
4031
+ const warm = await localHeader(context, configUrl);
4032
+ if (warm && !warm.header.localSourceReady)
4033
+ await lazyPrivateSource(context, configUrl, warm.account, warm.header.config);
4034
+ let header = warm?.header ?? (await swarmHeader(context, configUrl));
4035
+ const roots = new Set();
4036
+ const protect = async (cid) => {
4037
+ roots.add(cid);
4038
+ const values = [...roots];
4039
+ await context.store.retain(owner, values);
4040
+ await context.store.confirmRetained(owner, values);
4041
+ };
4042
+ for (let attempt = 0;; attempt++) {
4043
+ if (!hasMeta(header.snapshot) && header.source === "cache" && !attempt) {
4044
+ header = await swarmHeader(context, configUrl, true);
4045
+ continue;
4046
+ }
4047
+ if (hasMeta(header.snapshot)) {
4048
+ if (isV7Snapshot(header.snapshot)) {
4049
+ if (context.store.supportsRetention) {
4050
+ const rootId = metaCid(header.snapshot);
4051
+ await context.store.retainDirect(owner, [rootId]);
4052
+ await context.store.confirmDirectRetained(owner, [rootId]);
4053
+ }
4054
+ }
4055
+ else {
4056
+ await protect(metaCid(header.snapshot));
4057
+ }
4058
+ }
4059
+ const meta = await swarmMeta(context, header);
4060
+ if (!meta.skillPath)
4061
+ throw new HostError(header.snapshot.stateBundle
4062
+ ? "This Swarm uses the earlier exact State Bundle type without skillPath. There is no in-place root-configuration migration command. Create a new seeded Swarm and explicitly republish reviewed Names. Publishing a user Name ipab never overrides root configuration; upgrades never rewrite it."
4063
+ : `This Swarm uses the legacy exact Meta type without skillPath. Explicitly build and publish a new typed Meta Bundle with templatePath and registryPath preserved and skillPath chosen, then run ipab publish ipab META_SOURCE --expect ${metaCid(header.snapshot)}. Upgrades never overwrite Meta.`);
4064
+ const prefix = `${meta.skillPath}/`;
4065
+ const entries = await listSubtreeNames(context.store, header.snapshot, meta.skillPath, true);
4066
+ for (const { cid: target } of entries)
4067
+ roots.add(target.toString());
4068
+ await context.store.registerOwnerAsync(owner, [...roots]);
4069
+ const result = [];
4070
+ const identities = new Set();
4071
+ for (const { name, cid: target } of entries) {
4072
+ if (name.slice(prefix.length).includes("/"))
4073
+ throw new HostError(`Skill Name "${name}" must be flat under ${meta.skillPath}.`);
4074
+ const cid = await artifactValue(context.store, target.toString(), protect);
4075
+ const bundle = await openBundle(CID.parse(cid), {
4076
+ resolveCid: (key) => context.store.block.get(key.toString()),
4077
+ });
4078
+ if (bundle.schemaKey !== skillSchema.cid.toString())
4079
+ throw new HostError(`Name "${name}" is not an exact Skill type Bundle.`);
4080
+ const identity = await skillIdentity(bundle);
4081
+ if (identities.has(identity))
4082
+ throw new HostError(`Duplicate Skill installation name "${identity}" in this Swarm.`);
4083
+ identities.add(identity);
4084
+ result.push({ name, cid, identity });
4085
+ }
4086
+ const missing = requested.filter((reference) => !result.some((skill) => skill.name === reference || skill.identity === reference));
4087
+ if (missing.length && !attempt && header.source === "cache") {
4088
+ header = await swarmHeader(context, configUrl, true);
4089
+ continue;
4090
+ }
4091
+ if (missing.length)
4092
+ throw new HostError(`Skill identities or shared Names not found under ${meta.skillPath}: ${missing.join(", ")}.`);
4093
+ return result;
4094
+ }
4095
+ }
4096
+ export async function resolveTemplateSelector(context, selector, configUrl) {
4097
+ formalName(selector);
4098
+ const warm = await localHeader(context, configUrl);
4099
+ if (warm && !warm.header.localSourceReady)
4100
+ await lazyPrivateSource(context, configUrl, warm.account, warm.header.config);
4101
+ let header = warm?.header ?? (await swarmHeader(context, configUrl));
4102
+ if (!hasMeta(header.snapshot) && header.source === "cache")
4103
+ header = await swarmHeader(context, configUrl, true);
4104
+ for (let attempt = 0;; attempt++) {
4105
+ const meta = await swarmMeta(context, header);
4106
+ const name = formalName(`${meta.templatePath}/${selector}`);
4107
+ const target = await resolveSnapshotName(context.store, header.snapshot, name);
4108
+ if (target)
4109
+ return artifactValue(context.store, target.toString());
4110
+ if (attempt || header.source !== "cache")
4111
+ throw new HostError(`Template Name "${name}" was not found after refreshing HEAD.`);
4112
+ header = await swarmHeader(context, configUrl, true);
4113
+ }
4114
+ }
4115
+ export function templateName(name) {
4116
+ if (name.includes(":"))
4117
+ throw new HostError("Template NAME must be a safe relative Name, not a URI.");
4118
+ return formalName(name);
4119
+ }
4120
+ async function templateEntry(context, configUrl, header, selector) {
4121
+ const meta = await swarmMeta(context, header);
4122
+ const name = formalName(`${meta.templatePath}/${templateName(selector)}`);
4123
+ const target = await resolveSnapshotName(context.store, header.snapshot, name);
4124
+ if (!target)
4125
+ throw new HostError(`Template Name "${name}" was not found after refreshing HEAD.`);
4126
+ const targetCid = target.toString();
4127
+ return {
4128
+ swarm: configUrl,
4129
+ templatePath: meta.templatePath,
4130
+ metaCid: metaCid(header.snapshot),
4131
+ name,
4132
+ selector,
4133
+ reference: formatNameReference(configUrl, name),
4134
+ targetCid,
4135
+ ...(await inspectTemplate(context.store, await artifactValue(context.store, targetCid))),
4136
+ };
4137
+ }
4138
+ async function retainDaemonRoots(store, owner, roots) {
4139
+ const unique = [...new Set(roots)];
4140
+ if (!store.supportsRetention) {
4141
+ for (const root of unique)
4142
+ await store.prepare(root);
4143
+ return;
4144
+ }
4145
+ await store.recoverOwner(owner, []);
4146
+ if (unique.length) {
4147
+ await store.retain(owner, unique);
4148
+ await store.confirmRetained(owner, unique);
4149
+ }
4150
+ await store.reconcile(owner, unique);
4151
+ }
4152
+ export async function syncSwarmTemplates(context, configUrl, header) {
4153
+ if (!hasMeta(header.snapshot))
4154
+ return 0;
4155
+ const meta = await swarmMeta(context, header);
4156
+ const entries = await listSubtreeNames(context.store, header.snapshot, meta.templatePath, false);
4157
+ const roots = [];
4158
+ for (const { cid: target } of entries) {
4159
+ const targetCid = target.toString();
4160
+ const templateCid = await artifactValue(context.store, targetCid);
4161
+ await inspectTemplate(context.store, templateCid);
4162
+ roots.push(targetCid, templateCid);
4163
+ }
4164
+ const owner = `daemon-templates:${createHash("sha256").update(configUrl).digest("hex")}`;
4165
+ if (roots.length) {
4166
+ if (isV7Snapshot(header.snapshot)) {
4167
+ if (context.store.supportsRetention) {
4168
+ const rootId = metaCid(header.snapshot);
4169
+ await context.store.retainDirect(owner, [rootId]);
4170
+ await context.store.confirmDirectRetained(owner, [rootId]);
4171
+ }
4172
+ }
4173
+ else {
4174
+ roots.unshift(metaCid(header.snapshot));
4175
+ }
4176
+ }
4177
+ await retainDaemonRoots(context.store, owner, roots);
4178
+ return entries.length;
4179
+ }
4180
+ export async function syncSwarmRegistry(context, configUrl, header) {
4181
+ if (!hasMeta(header.snapshot))
4182
+ return 0;
4183
+ const associations = await registryAssociations(context, header);
4184
+ const roots = [];
4185
+ for (const association of associations) {
4186
+ const app = await openBundle(CID.parse(association.appCid), {
4187
+ resolveCid: (cid) => context.store.block.get(cid.toString()),
4188
+ });
4189
+ if (app.schemaKey !== appSchemaCid.toString())
4190
+ throw new HostError("Registry Names must directly reference an App Bundle CID, not an Artifact or another content type.");
4191
+ roots.push(association.appCid);
4192
+ }
4193
+ const owner = `daemon-registry:${createHash("sha256").update(configUrl).digest("hex")}`;
4194
+ if (roots.length) {
4195
+ if (isV7Snapshot(header.snapshot)) {
4196
+ if (context.store.supportsRetention) {
4197
+ const rootId = metaCid(header.snapshot);
4198
+ await context.store.retainDirect(owner, [rootId]);
4199
+ await context.store.confirmDirectRetained(owner, [rootId]);
4200
+ }
4201
+ }
4202
+ else {
4203
+ roots.unshift(metaCid(header.snapshot));
4204
+ }
4205
+ }
4206
+ await retainDaemonRoots(context.store, owner, roots);
4207
+ return associations.length;
4208
+ }
4209
+ export async function syncPivotReplicationAndIndex(context, configUrl, header, signal) {
4210
+ if (!context.pivot || !isV7Snapshot(header.snapshot))
4211
+ return;
4212
+ const headCid = CID.parse(header.stateCid).toV1().toString();
4213
+ const previousHead = withState(context, (state) => state.searchIndexState(configUrl)?.headCid ?? null);
4214
+ if (context.node) {
4215
+ await pinAdd(context.node, headCid, true, signal);
4216
+ }
4217
+ const owner = `daemon-pivot-root:${createHash("sha256").update(configUrl).digest("hex")}`;
4218
+ await retainDaemonRoots(context.store, owner, [headCid]);
4219
+ await withStateAsync(context, (state) => indexV7UnixfsSwarm(state, context.store, configUrl, headCid, {
4220
+ skipRootFiles: v7RootSkipFiles(header.snapshot),
4221
+ ...(signal ? { signal } : {}),
4222
+ }));
4223
+ if (previousHead && previousHead !== headCid && context.node) {
4224
+ await pinRm(context.node, previousHead, true, signal).catch(() => { });
4225
+ }
4226
+ }
4227
+ export async function swarmTemplates(context, configUrl, selector) {
4228
+ if (selector !== undefined)
4229
+ templateName(selector);
4230
+ const warm = await localHeader(context, configUrl);
4231
+ if (warm && !warm.header.localSourceReady)
4232
+ await lazyPrivateSource(context, configUrl, warm.account, warm.header.config);
4233
+ let header = warm?.header ??
4234
+ (await swarmHeader(context, configUrl, undefined, "local-first"));
4235
+ for (let attempt = 0;; attempt++) {
4236
+ if (!hasMeta(header.snapshot) && header.source === "cache" && !attempt) {
4237
+ header = await swarmHeader(context, configUrl, true, "local-first");
4238
+ continue;
4239
+ }
4240
+ const meta = await swarmMeta(context, header);
4241
+ const name = selector === undefined
4242
+ ? undefined
4243
+ : formalName(`${meta.templatePath}/${selector}`);
4244
+ if (name &&
4245
+ !(await resolveSnapshotName(context.store, header.snapshot, name)) &&
4246
+ header.source === "cache" &&
4247
+ !attempt) {
4248
+ header = await swarmHeader(context, configUrl, true, "local-first");
4249
+ continue;
4250
+ }
4251
+ const selectors = selector === undefined
4252
+ ? (await listSubtreeNames(context.store, header.snapshot, meta.templatePath, false)).map((entry) => entry.name.slice(meta.templatePath.length + 1))
4253
+ : [selector];
4254
+ const items = [];
4255
+ for (const item of selectors)
4256
+ items.push(await templateEntry(context, configUrl, header, item));
4257
+ return items;
4258
+ }
4259
+ }
4260
+ export async function setSwarmTemplate(context, configUrl, selector, source, expect) {
4261
+ templateName(selector);
4262
+ await pointer(context, configUrl);
4263
+ const content = await templatePublicationSource(source, context.store);
4264
+ const details = await inspectTemplate(context.store, content);
4265
+ let location;
4266
+ const targetCid = await publishContent(context, content, {
4267
+ swarm: configUrl,
4268
+ name: selector,
4269
+ ...(expect === undefined ? {} : { expect }),
4270
+ }, async (current) => {
4271
+ const meta = await swarmMeta(context, { snapshot: current });
4272
+ const name = formalName(`${meta.templatePath}/${selector}`);
4273
+ location = {
4274
+ name,
4275
+ templatePath: meta.templatePath,
4276
+ metaCid: metaCid(current),
4277
+ };
4278
+ return name;
4279
+ });
4280
+ return {
4281
+ swarm: configUrl,
4282
+ ...location,
4283
+ selector,
4284
+ reference: formatNameReference(configUrl, location.name),
4285
+ targetCid,
4286
+ ...details,
4287
+ };
4288
+ }
4289
+ export async function removeSwarmTemplate(context, configUrl, selector, expect) {
4290
+ templateName(selector);
4291
+ const expected = exactCid(expect);
4292
+ const head = await pointer(context, configUrl);
4293
+ let basis;
4294
+ for (let attempt = 0; attempt < 8; attempt++) {
4295
+ const currentHead = await head.read();
4296
+ const current = await readSnapshot(context.store, currentHead.root, configUrl);
4297
+ const meta = await swarmMeta(context, { snapshot: current });
4298
+ const name = formalName(`${meta.templatePath}/${selector}`);
4299
+ if (basis !== undefined && basis !== name)
4300
+ throw new HostError("Template Meta path changed during removal; inspect and retry.", 3, "EDIT_CONFLICT", "publication");
4301
+ basis = name;
4302
+ const old = (await resolveSnapshotName(context.store, current, name))?.toString();
4303
+ if (!old)
4304
+ throw new HostError(`Template Name "${name}" is missing; nothing was removed.`);
4305
+ if (old !== expected)
4306
+ throw new HostError(`Edit conflict for ${name}; --expect must match the exact old Name target CID.`, 3, "EDIT_CONFLICT", "publication");
4307
+ let next;
4308
+ if (isV7Snapshot(current)) {
4309
+ next = await prepareV7PathDelete(context, configUrl, current, name);
4310
+ }
4311
+ else {
4312
+ const names = { ...current.names };
4313
+ delete names[name];
4314
+ next = await prepareNamesPublication(context, configUrl, current, names, []);
4315
+ }
4316
+ try {
4317
+ await writeNamesHead(context, configUrl, head, next, currentHead.cid);
4318
+ }
4319
+ catch (cause) {
4320
+ if (cause instanceof HostError && cause.code === "PIVOT_PIN_FAILED")
4321
+ throw cause;
4322
+ if (cause instanceof ScopeApiError && cause.status === 412)
4323
+ continue;
4324
+ throw new HostError(`Template removal unconfirmed: ${message(cause)}. Inspect HEAD before retry.`, 1, "HEAD_UNCONFIRMED", "publication");
4325
+ }
4326
+ try {
4327
+ await swarmHeader(context, configUrl, true);
4328
+ }
4329
+ catch (cause) {
4330
+ throw new HostError(`Template removal committed, but HEAD/subscription refresh failed: ${message(cause)}. No content was deleted.`, 1, "PIN_STALE", "publication");
4331
+ }
4332
+ return {
4333
+ swarm: configUrl,
4334
+ templatePath: meta.templatePath,
4335
+ metaCid: metaCid(current),
4336
+ selector,
4337
+ name,
4338
+ reference: formatNameReference(configUrl, name),
4339
+ targetCid: old,
4340
+ };
4341
+ }
4342
+ throw new HostError("HEAD is busy; retry the template removal.");
4343
+ }
4344
+ async function registryAssociations(context, header) {
4345
+ assertNamesRegistry(header.snapshot);
4346
+ const meta = await swarmMeta(context, header);
4347
+ const prefix = `${meta.registryPath}/`;
4348
+ const entries = await listSubtreeNames(context.store, header.snapshot, meta.registryPath, true);
4349
+ const result = [];
4350
+ for (const { name, cid } of entries) {
4351
+ if (!name.startsWith(prefix))
4352
+ continue;
4353
+ const schemaCid = name.slice(prefix.length);
4354
+ if (exactCid(schemaCid, true) !== schemaCid)
4355
+ throw new HostError(`Registry Name "${name}" must end in an exact canonical type CID.`);
4356
+ result.push(createAssociation(schemaCid, cid.toString(), ["%"]));
4357
+ }
4358
+ return result.sort((left, right) => left.schemaCid.localeCompare(right.schemaCid));
4359
+ }
4360
+ export async function swarmRegistrations(context, configUrl) {
4361
+ let header = await swarmHeader(context, configUrl);
4362
+ if (!hasMeta(header.snapshot) && header.source === "cache")
4363
+ header = await swarmHeader(context, configUrl, true);
4364
+ return registryAssociations(context, header);
4365
+ }
4366
+ export async function swarmAssociation(context, configUrl, schemaCid, mode = "active") {
4367
+ const warm = mode === "local-first" ? await localHeader(context, configUrl) : undefined;
4368
+ if (warm && !warm.header.localSourceReady)
4369
+ await lazyPrivateSource(context, configUrl, warm.account, warm.header.config);
4370
+ let header = warm?.header ?? (await swarmHeader(context, configUrl));
4371
+ if (!hasMeta(header.snapshot) && header.source === "cache")
4372
+ header = await swarmHeader(context, configUrl, true);
4373
+ const findAssociation = async (current) => {
4374
+ if (isV7Snapshot(current.snapshot)) {
4375
+ const meta = await swarmMeta(context, current);
4376
+ const cid = await resolveSnapshotName(context.store, current.snapshot, formalName(`${meta.registryPath}/${schemaCid}`));
4377
+ return cid
4378
+ ? createAssociation(schemaCid, cid.toString(), ["%"])
4379
+ : undefined;
4380
+ }
4381
+ return (await registryAssociations(context, current)).find((item) => item.schemaCid === schemaCid);
4382
+ };
4383
+ let association = await findAssociation(header);
4384
+ if (!association && header.source === "cache") {
4385
+ header = await swarmHeader(context, configUrl, true);
4386
+ association = await findAssociation(header);
4387
+ }
4388
+ return association;
4389
+ }
4390
+ async function prepareV7PathSet(context, configUrl, current, name, targetCid, roots, retainedRoots) {
4391
+ const { newRootCid, createdDirCids } = await setUnixfsPath(context.store, CID.parse(current.stateBundle.cid), name, targetCid);
4392
+ const recursiveRoots = [...new Set(roots)];
4393
+ const retainedRecursive = [...new Set(retainedRoots ?? roots)];
4394
+ await provideShallowContent(context.store, {
4395
+ directBlocks: createdDirCids,
4396
+ recursiveRoots,
4397
+ retainedDirect: createdDirCids,
4398
+ retainedRecursive,
4399
+ endpoint: context.node.api,
4400
+ ...(context.fetch ? { fetcher: context.fetch } : {}),
4401
+ authorizationToken: context.node.auth,
4402
+ owner: `publication:${newRootCid.toString()}`,
4403
+ });
4404
+ withState(context, (state) => {
4405
+ state.invalidateSwarmHeader(configUrl);
4406
+ });
4407
+ return newRootCid.toString();
4408
+ }
4409
+ async function prepareV7PathDelete(context, configUrl, current, name) {
4410
+ const { newRootCid, createdDirCids } = await deleteUnixfsPath(context.store, CID.parse(current.stateBundle.cid), name);
4411
+ await provideShallowContent(context.store, {
4412
+ directBlocks: createdDirCids,
4413
+ recursiveRoots: [],
4414
+ retainedDirect: createdDirCids,
4415
+ retainedRecursive: [],
4416
+ endpoint: context.node.api,
4417
+ ...(context.fetch ? { fetcher: context.fetch } : {}),
4418
+ authorizationToken: context.node.auth,
4419
+ owner: `publication:${newRootCid.toString()}`,
4420
+ });
4421
+ withState(context, (state) => {
4422
+ state.invalidateSwarmHeader(configUrl);
4423
+ });
4424
+ return newRootCid.toString();
4425
+ }
4426
+ async function prepareNamesPublication(context, configUrl, current, names, roots, retainedRoots) {
4427
+ const identity = await contextIdentity(context);
4428
+ const next = await publication(context.store, await writeSnapshot(context.store, { ...current, names }, configUrl), undefined, identity.publicKey);
4429
+ await provideContent(context.store, [...new Set([next, ...roots])], context.node.api, context.fetch, context.node.auth, [...new Set([next, ...(retainedRoots ?? roots)])]);
4430
+ withState(context, (state) => {
4431
+ state.invalidateSwarmHeader(configUrl);
4432
+ });
4433
+ return next;
4434
+ }
4435
+ async function editSwarmAssociation(context, configUrl, schemaCid, association, replace) {
4436
+ const head = await pointer(context, configUrl);
4437
+ if (association) {
4438
+ const app = await openBundle(CID.parse(association.appCid), {
4439
+ resolveCid: (cid) => context.store.block.get(cid.toString()),
4440
+ });
4441
+ if (app.schemaKey !== appSchemaCid.toString())
4442
+ throw new HostError("Registry Names must directly reference an App Bundle CID, not an Artifact or another content type.");
4443
+ }
4444
+ const roots = association
4445
+ ? await dependencies(context.store, association.appCid)
4446
+ : new Set();
4447
+ for (let attempt = 0; attempt < 8; attempt++) {
4448
+ const currentHead = await head.read();
4449
+ const current = await readSnapshot(context.store, currentHead.root, configUrl);
4450
+ assertNamesRegistry(current);
4451
+ const meta = await swarmMeta(context, { snapshot: current });
4452
+ const name = formalName(`${meta.registryPath}/${schemaCid}`);
4453
+ const oldCid = (await resolveSnapshotName(context.store, current, name))?.toString();
4454
+ if (association) {
4455
+ if (oldCid === association.appCid)
4456
+ return;
4457
+ if (oldCid && !replace)
4458
+ throw new HostError("Schema has another association; use --replace.");
4459
+ }
4460
+ else if (!oldCid) {
4461
+ throw new HostError("No association exists for this Schema. Run ipab register list --swarm URL_OR_ALIAS.");
4462
+ }
4463
+ let next;
4464
+ if (isV7Snapshot(current)) {
4465
+ next = association
4466
+ ? await prepareV7PathSet(context, configUrl, current, name, CID.parse(association.appCid), roots)
4467
+ : await prepareV7PathDelete(context, configUrl, current, name);
4468
+ }
4469
+ else {
4470
+ const names = { ...current.names };
4471
+ if (association)
4472
+ names[name] = CID.parse(association.appCid);
4473
+ else
4474
+ delete names[name];
4475
+ next = await prepareNamesPublication(context, configUrl, current, names, roots);
4476
+ }
4477
+ try {
4478
+ await writeNamesHead(context, configUrl, head, next, currentHead.cid);
4479
+ return;
4480
+ }
4481
+ catch (cause) {
4482
+ if (cause instanceof HostError && cause.code === "PIVOT_PIN_FAILED")
4483
+ throw cause;
4484
+ if (!(cause instanceof ScopeApiError) || cause.status !== 412)
4485
+ throw new HostError(`Registry publication unconfirmed for ${configUrl}: ${message(cause)}. Inspect the Swarm registry before retry.`, 1, "HEAD_UNCONFIRMED", "publication");
4486
+ continue;
4487
+ }
4488
+ }
4489
+ throw new HostError(`HEAD is busy for ${configUrl}; retry the registry edit.`);
4490
+ }
4491
+ export async function setSwarmAssociation(context, configUrl, value, replace = false) {
4492
+ if (value.argv.length !== 1 || value.argv[0] !== "%")
4493
+ throw new HostError('Custom per-association argv is unsupported. Apps opened through the registry receive only the content CID (whole "%" argument); adapt the App or use ipab exec APP_CID ARGS.');
4494
+ const association = createAssociation(value.schemaCid, value.appCid, value.argv);
4495
+ await editSwarmAssociation(context, configUrl, association.schemaCid, association, replace);
4496
+ return association;
4497
+ }
4498
+ export async function removeSwarmAssociation(context, configUrl, schemaCid) {
4499
+ const schema = exactCid(schemaCid, true);
4500
+ await editSwarmAssociation(context, configUrl, schema, undefined, false);
4501
+ return schema;
4502
+ }
4503
+ async function dependencies(store, root, found = new Set(), allowNonBundle = false) {
4504
+ if (found.has(root))
4505
+ return found;
4506
+ if (found.size >= 256)
4507
+ throw new HostError("Publication dependency/history limit exceeded.");
4508
+ found.add(root);
4509
+ const parsed = CID.parse(root);
4510
+ if (parsed.code !== dagPb.code) {
4511
+ if (allowNonBundle)
4512
+ return found;
4513
+ }
4514
+ let shallow;
4515
+ try {
4516
+ shallow = await openBundle(parsed, {
4517
+ shallow: true,
4518
+ resolveCid: (cid) => store.block.get(cid.toString()),
4519
+ });
4520
+ }
4521
+ catch (cause) {
4522
+ if (allowNonBundle &&
4523
+ cause instanceof ContentBundleError &&
4524
+ cause.code !== "ABORTED")
4525
+ return found;
4526
+ throw cause;
4527
+ }
4528
+ if (isSwarmRootSchema(shallow.schemaKey)) {
4529
+ const snapshot = await readV7Root(store, parsed);
4530
+ const walked = await walkUnixfsNames(store, parsed, {
4531
+ skipRootFiles: v7RootSkipFiles(snapshot),
4532
+ });
4533
+ for (const entry of walked.entries)
4534
+ await dependencies(store, entry.targetCid, found, true);
4535
+ return found;
4536
+ }
4537
+ const bundle = await openBundle(parsed, {
4538
+ resolveCid: (cid) => store.block.get(cid.toString()),
4539
+ });
4540
+ if (bundle.schemaKey === (await encodeSchema(artifactType)).cid.toString()) {
4541
+ const node = parseArtifact(await typedJson(store, root, artifactType));
4542
+ await dependencies(store, node.value, found);
4543
+ if (node.previous)
4544
+ await dependencies(store, node.previous, found);
4545
+ }
4546
+ else if (bundle.schemaKey === appSchemaCid.toString()) {
4547
+ const app = object(JSON.parse(new TextDecoder().decode(await bytes(await bundle.readFile(bundle.manifest.entry), 64 * 1024))), "App");
4548
+ if (app.source) {
4549
+ const source = object(app.source, "source");
4550
+ if (typeof source.cid !== "string")
4551
+ throw new HostError("Invalid App source association.");
4552
+ await dependencies(store, source.cid, found);
4553
+ }
4554
+ }
4555
+ else if (isSwarmStateSchema(bundle.schemaKey)) {
4556
+ const snapshot = await readState(store, parsed);
4557
+ for (const target of Object.values(snapshot.names))
4558
+ await dependencies(store, target.toString(), found);
4559
+ }
4560
+ return found;
4561
+ }
4562
+ export async function frozenPublicationClosure(store, root) {
4563
+ const parsedRoot = CID.parse(root);
4564
+ if (parsedRoot.code === dagPb.code) {
4565
+ const snapshot = await readV7Root(store, parsedRoot);
4566
+ const content = new Set();
4567
+ const walked = await walkUnixfsNames(store, parsedRoot, {
4568
+ skipRootFiles: v7RootSkipFiles(snapshot),
4569
+ });
4570
+ for (const entry of walked.entries)
4571
+ await dependencies(store, entry.targetCid, content, true);
4572
+ return [root, ...[...content].filter((cid) => cid !== root).sort()];
4573
+ }
4574
+ const publications = new Set(), content = new Set();
4575
+ let current = root;
4576
+ while (current !== undefined) {
4577
+ if (publications.has(current) || publications.size >= 256)
4578
+ throw new HostError("Frozen publication history exceeds limits or contains a cycle.");
4579
+ publications.add(current);
4580
+ const publication = await readPublication(store, current);
4581
+ const snapshot = await readState(store, publication.state);
4582
+ for (const target of Object.values(snapshot.names))
4583
+ await dependencies(store, target.toString(), content);
4584
+ for (const association of Object.values(snapshot.registrations ?? {}))
4585
+ await dependencies(store, association.appCid.toString(), content);
4586
+ current = publication.previous?.toString();
4587
+ }
4588
+ return [
4589
+ root,
4590
+ ...[...new Set([...publications, ...content])]
4591
+ .filter((cid) => cid !== root)
4592
+ .sort(),
4593
+ ];
4594
+ }
4595
+ export async function unpublish(context, options) {
4596
+ if (!options.swarm)
4597
+ throw new HostError("Unpublish requires a selected Swarm configuration URL or alias.");
4598
+ const name = formalName(options.name);
4599
+ const expected = exactCid(options.expect);
4600
+ const head = await pointer(context, options.swarm);
4601
+ for (let attempt = 0; attempt < 8; attempt++) {
4602
+ const currentHead = await head.read();
4603
+ const current = await readSnapshot(context.store, currentHead.root, options.swarm);
4604
+ const old = (await resolveSnapshotName(context.store, current, name))?.toString();
4605
+ if (!old)
4606
+ throw new HostError(`Name "${name}" is missing; nothing was removed.`);
4607
+ if (old !== expected)
4608
+ throw new HostError(`Edit conflict for ${name}; --expect must match the exact old Name target CID.`, 3, "EDIT_CONFLICT", "publication");
4609
+ let next;
4610
+ if (isV7Snapshot(current)) {
4611
+ next = await prepareV7PathDelete(context, options.swarm, current, name);
4612
+ }
4613
+ else {
4614
+ const names = { ...current.names };
4615
+ delete names[name];
4616
+ next = await prepareNamesPublication(context, options.swarm, current, names, []);
4617
+ }
4618
+ try {
4619
+ await head.write(next, currentHead.cid, uniqueId());
4620
+ }
4621
+ catch (cause) {
4622
+ if (cause instanceof ScopeApiError && cause.status === 412)
4623
+ continue;
4624
+ throw new HostError(`Unpublish unconfirmed: ${message(cause)}. Inspect HEAD before retry.`, 1, "HEAD_UNCONFIRMED", "publication");
4625
+ }
4626
+ try {
4627
+ await swarmHeader(context, options.swarm, true);
4628
+ }
4629
+ catch (cause) {
4630
+ throw new HostError(`Unpublish committed, but HEAD/subscription refresh failed: ${message(cause)}. No content was deleted.`, 1, "PIN_STALE", "publication");
4631
+ }
4632
+ return { name, targetCid: old };
4633
+ }
4634
+ throw new HostError("HEAD is busy; retry unpublish.");
4635
+ }
4636
+ export async function publish(context, content, options) {
4637
+ return publishContent(context, content, options);
4638
+ }
4639
+ async function publishContent(context, content, options, nameForSnapshot) {
4640
+ if (!options.swarm)
4641
+ throw new HostError("Publication requires a selected Swarm configuration URL or alias.");
4642
+ const head = await pointer(context, options.swarm);
4643
+ const roots = await dependencies(context.store, content);
4644
+ const currentRoots = [...(await currentDependencies(context.store, content))];
4645
+ await withStateAsync(context, (state) => pinCid(state, content, context.store, currentRoots));
4646
+ let name = formalName(options.name);
4647
+ let resolvedName;
4648
+ if (options.snapshot && options.expect)
4649
+ throw new HostError("Snapshots cannot replace an occupied Name.");
4650
+ const expected = options.expect
4651
+ ? CID.parse(options.expect).toV1().toString()
4652
+ : undefined;
4653
+ const contentBundle = await openBundle(CID.parse(content), {
4654
+ resolveCid: (cid) => context.store.block.get(cid.toString()),
4655
+ });
4656
+ const direct = contentBundle.schemaKey === appSchemaCid.toString() ||
4657
+ contentBundle.schemaKey === swarmMetaSchema.cid.toString() ||
4658
+ contentBundle.schemaKey === legacySwarmMetaSchema.cid.toString();
4659
+ const candidate = options.snapshot || direct
4660
+ ? content
4661
+ : await jsonBundle(context.store, artifactType, {
4662
+ value: content,
4663
+ ...(expected ? { previous: expected } : {}),
4664
+ timestamp: new Date().toISOString(),
4665
+ });
4666
+ roots.add(candidate);
4667
+ if (expected)
4668
+ for (const root of await dependencies(context.store, expected))
4669
+ roots.add(root);
4670
+ for (let attempt = 0; attempt < 8; attempt++) {
4671
+ const currentHead = await head.read(), current = await readSnapshot(context.store, currentHead.root, options.swarm);
4672
+ if (nameForSnapshot) {
4673
+ name = await nameForSnapshot(current);
4674
+ if (resolvedName !== undefined && resolvedName !== name)
4675
+ throw new HostError("Template Meta path changed during publication; inspect and retry. Content remains pinned.", 3, "EDIT_CONFLICT", "publication");
4676
+ resolvedName = name;
4677
+ }
4678
+ const existing = (await resolveSnapshotName(context.store, current, name))?.toString();
4679
+ if (existing !== expected)
4680
+ throw new HostError(`Edit conflict for ${name}; content ${content} remains pinned. Occupied Names require --expect EXACT_OLD_CID (the old Artifact CID when applicable); inspect the current Name before retrying.`, 3, "EDIT_CONFLICT", "publication");
4681
+ const retained = [
4682
+ candidate,
4683
+ ...(expected ? await dependencies(context.store, expected) : []),
4684
+ ];
4685
+ const next = isV7Snapshot(current)
4686
+ ? await prepareV7PathSet(context, options.swarm, current, name, CID.parse(candidate), roots, retained)
4687
+ : await prepareNamesPublication(context, options.swarm, current, { ...current.names, [name]: CID.parse(candidate) }, roots, retained);
4688
+ try {
4689
+ await writeNamesHead(context, options.swarm, head, next, currentHead.cid);
4690
+ }
4691
+ catch (cause) {
4692
+ if (cause instanceof HostError && cause.code === "PIVOT_PIN_FAILED")
4693
+ throw cause;
4694
+ if (!(cause instanceof ScopeApiError) || cause.status !== 412)
4695
+ throw new HostError(`HEAD publication unconfirmed: ${message(cause)}. Candidate ${candidate} remains retained; inspect HEAD before retry.`, 1, "HEAD_UNCONFIRMED", "publication");
4696
+ continue;
4697
+ }
4698
+ try {
4699
+ await swarmHeader(context, options.swarm, true);
4700
+ }
4701
+ catch (cause) {
4702
+ 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");
4703
+ }
4704
+ return candidate;
4705
+ }
4706
+ throw new HostError(`HEAD is busy; candidate ${candidate} remains retained.`);
4707
+ }
4708
+ //# sourceMappingURL=swarm.js.map