@minca/core 0.1.14 → 0.1.16

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 (528) hide show
  1. package/README.md +4 -4
  2. package/dist/elements/auth-styles.d.ts +1 -1
  3. package/dist/elements/auth-styles.d.ts.map +1 -1
  4. package/dist/elements/auth-styles.js +21 -4
  5. package/dist/elements/auth-styles.js.map +1 -1
  6. package/dist/elements/minca-auth.d.ts.map +1 -1
  7. package/dist/elements/minca-auth.js +151 -57
  8. package/dist/elements/minca-auth.js.map +1 -1
  9. package/dist/files/space-files.d.ts +15 -3
  10. package/dist/files/space-files.d.ts.map +1 -1
  11. package/dist/files/space-files.js +225 -37
  12. package/dist/files/space-files.js.map +1 -1
  13. package/dist/identity/abilities.d.ts +2 -0
  14. package/dist/identity/abilities.d.ts.map +1 -1
  15. package/dist/identity/abilities.js +2 -0
  16. package/dist/identity/abilities.js.map +1 -1
  17. package/dist/identity/account-vault.d.ts +15 -71
  18. package/dist/identity/account-vault.d.ts.map +1 -1
  19. package/dist/identity/account-vault.js +45 -104
  20. package/dist/identity/account-vault.js.map +1 -1
  21. package/dist/identity/channel.d.ts +3 -9
  22. package/dist/identity/channel.d.ts.map +1 -1
  23. package/dist/identity/channel.js +42 -42
  24. package/dist/identity/channel.js.map +1 -1
  25. package/dist/identity/contact-key.d.ts +14 -29
  26. package/dist/identity/contact-key.d.ts.map +1 -1
  27. package/dist/identity/contact-key.js +31 -51
  28. package/dist/identity/contact-key.js.map +1 -1
  29. package/dist/identity/crypto-p256.d.ts.map +1 -1
  30. package/dist/identity/crypto-p256.js +39 -53
  31. package/dist/identity/crypto-p256.js.map +1 -1
  32. package/dist/identity/hpke.d.ts.map +1 -1
  33. package/dist/identity/hpke.js +19 -19
  34. package/dist/identity/hpke.js.map +1 -1
  35. package/dist/identity/identity-manager.d.ts.map +1 -1
  36. package/dist/identity/identity-manager.js +1 -2
  37. package/dist/identity/identity-manager.js.map +1 -1
  38. package/dist/identity/policy.d.ts.map +1 -1
  39. package/dist/identity/policy.js +35 -61
  40. package/dist/identity/policy.js.map +1 -1
  41. package/dist/identity/recovery-code.d.ts +2 -8
  42. package/dist/identity/recovery-code.d.ts.map +1 -1
  43. package/dist/identity/recovery-code.js +4 -11
  44. package/dist/identity/recovery-code.js.map +1 -1
  45. package/dist/identity/root-signer.d.ts +1 -6
  46. package/dist/identity/root-signer.d.ts.map +1 -1
  47. package/dist/identity/root-signer.js +12 -15
  48. package/dist/identity/root-signer.js.map +1 -1
  49. package/dist/identity/ucan.d.ts.map +1 -1
  50. package/dist/identity/ucan.js +48 -39
  51. package/dist/identity/ucan.js.map +1 -1
  52. package/dist/identity/webauthn.d.ts +6 -11
  53. package/dist/identity/webauthn.d.ts.map +1 -1
  54. package/dist/identity/webauthn.js +18 -30
  55. package/dist/identity/webauthn.js.map +1 -1
  56. package/dist/inbox/inbox.d.ts.map +1 -1
  57. package/dist/inbox/inbox.js +40 -30
  58. package/dist/inbox/inbox.js.map +1 -1
  59. package/dist/inbox/index.d.ts +2 -0
  60. package/dist/inbox/index.d.ts.map +1 -1
  61. package/dist/inbox/index.js +1 -0
  62. package/dist/inbox/index.js.map +1 -1
  63. package/dist/inbox/names.d.ts +54 -0
  64. package/dist/inbox/names.d.ts.map +1 -0
  65. package/dist/inbox/names.js +299 -0
  66. package/dist/inbox/names.js.map +1 -0
  67. package/dist/index.d.ts +3 -6
  68. package/dist/index.d.ts.map +1 -1
  69. package/dist/index.js +9 -12
  70. package/dist/index.js.map +1 -1
  71. package/dist/network/mesh.d.ts +7 -20
  72. package/dist/network/mesh.d.ts.map +1 -1
  73. package/dist/network/mesh.js +267 -245
  74. package/dist/network/mesh.js.map +1 -1
  75. package/dist/network/relay-link.d.ts +31 -0
  76. package/dist/network/relay-link.d.ts.map +1 -0
  77. package/dist/network/relay-link.js +62 -0
  78. package/dist/network/relay-link.js.map +1 -0
  79. package/dist/network/relay-minca.d.ts +12 -1
  80. package/dist/network/relay-minca.d.ts.map +1 -1
  81. package/dist/network/relay-minca.js +25 -55
  82. package/dist/network/relay-minca.js.map +1 -1
  83. package/dist/network/relay-nostr.d.ts +14 -3
  84. package/dist/network/relay-nostr.d.ts.map +1 -1
  85. package/dist/network/relay-nostr.js +34 -72
  86. package/dist/network/relay-nostr.js.map +1 -1
  87. package/dist/network/relay-socket.d.ts +1 -1
  88. package/dist/network/relay-socket.d.ts.map +1 -1
  89. package/dist/network/relay-socket.js +3 -1
  90. package/dist/network/relay-socket.js.map +1 -1
  91. package/dist/network/relays.d.ts +26 -17
  92. package/dist/network/relays.d.ts.map +1 -1
  93. package/dist/network/relays.js +21 -28
  94. package/dist/network/relays.js.map +1 -1
  95. package/dist/network/rendezvous.d.ts +1 -1
  96. package/dist/network/rendezvous.d.ts.map +1 -1
  97. package/dist/network/rendezvous.js +2 -2
  98. package/dist/network/rendezvous.js.map +1 -1
  99. package/dist/node/actions.d.ts.map +1 -1
  100. package/dist/node/actions.js +56 -39
  101. package/dist/node/actions.js.map +1 -1
  102. package/dist/node/api.d.ts +6 -0
  103. package/dist/node/api.d.ts.map +1 -1
  104. package/dist/node/api.js +6 -0
  105. package/dist/node/api.js.map +1 -1
  106. package/dist/node/carrier.d.ts +5 -0
  107. package/dist/node/carrier.d.ts.map +1 -1
  108. package/dist/node/carrier.js +94 -73
  109. package/dist/node/carrier.js.map +1 -1
  110. package/dist/node/copy.d.ts +8 -7
  111. package/dist/node/copy.d.ts.map +1 -1
  112. package/dist/node/copy.js +54 -56
  113. package/dist/node/copy.js.map +1 -1
  114. package/dist/node/host.d.ts +39 -65
  115. package/dist/node/host.d.ts.map +1 -1
  116. package/dist/node/host.js +362 -379
  117. package/dist/node/host.js.map +1 -1
  118. package/dist/node/index.d.ts +2 -2
  119. package/dist/node/index.d.ts.map +1 -1
  120. package/dist/node/index.js +1 -1
  121. package/dist/node/index.js.map +1 -1
  122. package/dist/node/node-carriers.d.ts +35 -0
  123. package/dist/node/node-carriers.d.ts.map +1 -0
  124. package/dist/node/node-carriers.js +562 -0
  125. package/dist/node/node-carriers.js.map +1 -0
  126. package/dist/node/node-contacts.d.ts +11 -0
  127. package/dist/node/node-contacts.d.ts.map +1 -0
  128. package/dist/node/node-contacts.js +808 -0
  129. package/dist/node/node-contacts.js.map +1 -0
  130. package/dist/node/node-context.d.ts +76 -0
  131. package/dist/node/node-context.d.ts.map +1 -0
  132. package/dist/node/node-context.js +54 -0
  133. package/dist/node/node-context.js.map +1 -0
  134. package/dist/node/node-hosting.d.ts +20 -0
  135. package/dist/node/node-hosting.d.ts.map +1 -0
  136. package/dist/node/node-hosting.js +449 -0
  137. package/dist/node/node-hosting.js.map +1 -0
  138. package/dist/node/node-records.d.ts +18 -0
  139. package/dist/node/node-records.d.ts.map +1 -0
  140. package/dist/node/node-records.js +262 -0
  141. package/dist/node/node-records.js.map +1 -0
  142. package/dist/node/node.d.ts.map +1 -1
  143. package/dist/node/node.js +197 -1989
  144. package/dist/node/node.js.map +1 -1
  145. package/dist/node/remote.d.ts +5 -6
  146. package/dist/node/remote.d.ts.map +1 -1
  147. package/dist/node/remote.js +272 -260
  148. package/dist/node/remote.js.map +1 -1
  149. package/dist/node/space-catalog.d.ts +40 -0
  150. package/dist/node/space-catalog.d.ts.map +1 -0
  151. package/dist/node/space-catalog.js +158 -0
  152. package/dist/node/space-catalog.js.map +1 -0
  153. package/dist/node/space-checks.d.ts +25 -0
  154. package/dist/node/space-checks.d.ts.map +1 -0
  155. package/dist/node/space-checks.js +343 -0
  156. package/dist/node/space-checks.js.map +1 -0
  157. package/dist/node/space-history.d.ts +37 -0
  158. package/dist/node/space-history.d.ts.map +1 -0
  159. package/dist/node/space-history.js +350 -0
  160. package/dist/node/space-history.js.map +1 -0
  161. package/dist/node/space-holding.d.ts +49 -0
  162. package/dist/node/space-holding.d.ts.map +1 -0
  163. package/dist/node/space-holding.js +267 -0
  164. package/dist/node/space-holding.js.map +1 -0
  165. package/dist/node/space-index.d.ts +41 -0
  166. package/dist/node/space-index.d.ts.map +1 -0
  167. package/dist/node/space-index.js +217 -0
  168. package/dist/node/space-index.js.map +1 -0
  169. package/dist/node/space-keys.d.ts +34 -0
  170. package/dist/node/space-keys.d.ts.map +1 -0
  171. package/dist/node/space-keys.js +309 -0
  172. package/dist/node/space-keys.js.map +1 -0
  173. package/dist/node/space-lines.d.ts +33 -0
  174. package/dist/node/space-lines.d.ts.map +1 -0
  175. package/dist/node/space-lines.js +145 -0
  176. package/dist/node/space-lines.js.map +1 -0
  177. package/dist/node/space-membership.d.ts +69 -0
  178. package/dist/node/space-membership.d.ts.map +1 -0
  179. package/dist/node/space-membership.js +242 -0
  180. package/dist/node/space-membership.js.map +1 -0
  181. package/dist/node/space-mirrors.d.ts +43 -0
  182. package/dist/node/space-mirrors.d.ts.map +1 -0
  183. package/dist/node/space-mirrors.js +125 -0
  184. package/dist/node/space-mirrors.js.map +1 -0
  185. package/dist/node/space-peers.d.ts +104 -0
  186. package/dist/node/space-peers.d.ts.map +1 -0
  187. package/dist/node/space-peers.js +595 -0
  188. package/dist/node/space-peers.js.map +1 -0
  189. package/dist/node/space-profiles.d.ts +18 -0
  190. package/dist/node/space-profiles.d.ts.map +1 -0
  191. package/dist/node/space-profiles.js +105 -0
  192. package/dist/node/space-profiles.js.map +1 -0
  193. package/dist/node/space-rules.d.ts +29 -0
  194. package/dist/node/space-rules.d.ts.map +1 -0
  195. package/dist/node/space-rules.js +144 -0
  196. package/dist/node/space-rules.js.map +1 -0
  197. package/dist/node/space-runtime.d.ts +104 -143
  198. package/dist/node/space-runtime.d.ts.map +1 -1
  199. package/dist/node/space-runtime.js +293 -3954
  200. package/dist/node/space-runtime.js.map +1 -1
  201. package/dist/node/space-standing.d.ts +20 -0
  202. package/dist/node/space-standing.d.ts.map +1 -0
  203. package/dist/node/space-standing.js +317 -0
  204. package/dist/node/space-standing.js.map +1 -0
  205. package/dist/node/space-versions.d.ts +104 -0
  206. package/dist/node/space-versions.d.ts.map +1 -0
  207. package/dist/node/space-versions.js +153 -0
  208. package/dist/node/space-versions.js.map +1 -0
  209. package/dist/node/space-warrants.d.ts +25 -0
  210. package/dist/node/space-warrants.d.ts.map +1 -0
  211. package/dist/node/space-warrants.js +214 -0
  212. package/dist/node/space-warrants.js.map +1 -0
  213. package/dist/node/space-writing.d.ts +72 -0
  214. package/dist/node/space-writing.d.ts.map +1 -0
  215. package/dist/node/space-writing.js +440 -0
  216. package/dist/node/space-writing.js.map +1 -0
  217. package/dist/node/stores.d.ts +19 -50
  218. package/dist/node/stores.d.ts.map +1 -1
  219. package/dist/node/stores.js +14 -33
  220. package/dist/node/stores.js.map +1 -1
  221. package/dist/node/types.d.ts +225 -305
  222. package/dist/node/types.d.ts.map +1 -1
  223. package/dist/node/usage.d.ts +2 -24
  224. package/dist/node/usage.d.ts.map +1 -1
  225. package/dist/node/usage.js +118 -102
  226. package/dist/node/usage.js.map +1 -1
  227. package/dist/node/watch-notifications.d.ts.map +1 -1
  228. package/dist/node/watch-notifications.js +32 -29
  229. package/dist/node/watch-notifications.js.map +1 -1
  230. package/dist/node/worker.d.ts +5 -6
  231. package/dist/node/worker.d.ts.map +1 -1
  232. package/dist/node/worker.js +80 -72
  233. package/dist/node/worker.js.map +1 -1
  234. package/dist/node/writer-keys.d.ts +5 -6
  235. package/dist/node/writer-keys.d.ts.map +1 -1
  236. package/dist/node/writer-keys.js +66 -57
  237. package/dist/node/writer-keys.js.map +1 -1
  238. package/dist/node/writers.d.ts +12 -19
  239. package/dist/node/writers.d.ts.map +1 -1
  240. package/dist/node/writers.js +7 -15
  241. package/dist/node/writers.js.map +1 -1
  242. package/dist/privacy/direct.d.ts.map +1 -1
  243. package/dist/privacy/direct.js +31 -27
  244. package/dist/privacy/direct.js.map +1 -1
  245. package/dist/privacy/space-encryption.d.ts.map +1 -1
  246. package/dist/privacy/space-encryption.js +5 -9
  247. package/dist/privacy/space-encryption.js.map +1 -1
  248. package/dist/query/computed.d.ts.map +1 -1
  249. package/dist/query/computed.js +78 -77
  250. package/dist/query/computed.js.map +1 -1
  251. package/dist/query/engine.d.ts +3 -4
  252. package/dist/query/engine.d.ts.map +1 -1
  253. package/dist/query/engine.js +93 -86
  254. package/dist/query/engine.js.map +1 -1
  255. package/dist/query/filter.d.ts +8 -10
  256. package/dist/query/filter.d.ts.map +1 -1
  257. package/dist/query/filter.js +144 -161
  258. package/dist/query/filter.js.map +1 -1
  259. package/dist/records/cel-types.d.ts.map +1 -1
  260. package/dist/records/cel-types.js +13 -27
  261. package/dist/records/cel-types.js.map +1 -1
  262. package/dist/records/cel.d.ts.map +1 -1
  263. package/dist/records/cel.js +177 -242
  264. package/dist/records/cel.js.map +1 -1
  265. package/dist/records/rules.d.ts.map +1 -1
  266. package/dist/records/rules.js +46 -50
  267. package/dist/records/rules.js.map +1 -1
  268. package/dist/records/topics.d.ts.map +1 -1
  269. package/dist/records/topics.js +18 -22
  270. package/dist/records/topics.js.map +1 -1
  271. package/dist/schema/collection-def.d.ts.map +1 -1
  272. package/dist/schema/collection-def.js +16 -5
  273. package/dist/schema/collection-def.js.map +1 -1
  274. package/dist/schemas/automations.d.ts +16 -15
  275. package/dist/schemas/automations.d.ts.map +1 -1
  276. package/dist/schemas/automations.js +203 -165
  277. package/dist/schemas/automations.js.map +1 -1
  278. package/dist/schemas/blueprints.d.ts.map +1 -1
  279. package/dist/schemas/blueprints.js +14 -13
  280. package/dist/schemas/blueprints.js.map +1 -1
  281. package/dist/schemas/connectors.d.ts +12 -0
  282. package/dist/schemas/connectors.d.ts.map +1 -1
  283. package/dist/schemas/connectors.js +16 -11
  284. package/dist/schemas/connectors.js.map +1 -1
  285. package/dist/schemas/contacts.d.ts +57 -0
  286. package/dist/schemas/contacts.d.ts.map +1 -1
  287. package/dist/schemas/contacts.js +32 -0
  288. package/dist/schemas/contacts.js.map +1 -1
  289. package/dist/schemas/cron.d.ts.map +1 -1
  290. package/dist/schemas/cron.js +27 -28
  291. package/dist/schemas/cron.js.map +1 -1
  292. package/dist/schemas/defined.d.ts +6 -0
  293. package/dist/schemas/defined.d.ts.map +1 -0
  294. package/dist/schemas/defined.js +7 -0
  295. package/dist/schemas/defined.js.map +1 -0
  296. package/dist/schemas/fragments.d.ts +22 -2
  297. package/dist/schemas/fragments.d.ts.map +1 -1
  298. package/dist/schemas/fragments.js +20 -12
  299. package/dist/schemas/fragments.js.map +1 -1
  300. package/dist/schemas/guides.d.ts +3 -1
  301. package/dist/schemas/guides.d.ts.map +1 -1
  302. package/dist/schemas/guides.js +13 -12
  303. package/dist/schemas/guides.js.map +1 -1
  304. package/dist/schemas/index.d.ts +2 -2
  305. package/dist/schemas/index.d.ts.map +1 -1
  306. package/dist/schemas/index.js +18 -14
  307. package/dist/schemas/index.js.map +1 -1
  308. package/dist/schemas/library/annotations.d.ts +30 -0
  309. package/dist/schemas/library/annotations.d.ts.map +1 -1
  310. package/dist/schemas/library/annotations.js +1 -0
  311. package/dist/schemas/library/annotations.js.map +1 -1
  312. package/dist/schemas/library/community.d.ts +28 -0
  313. package/dist/schemas/library/community.d.ts.map +1 -1
  314. package/dist/schemas/library/life.d.ts +62 -2
  315. package/dist/schemas/library/life.d.ts.map +1 -1
  316. package/dist/schemas/library/media.d.ts +36 -0
  317. package/dist/schemas/library/media.d.ts.map +1 -1
  318. package/dist/schemas/library/money.d.ts +74 -2
  319. package/dist/schemas/library/money.d.ts.map +1 -1
  320. package/dist/schemas/library/planning.d.ts +56 -0
  321. package/dist/schemas/library/planning.d.ts.map +1 -1
  322. package/dist/schemas/library/publishing.d.ts +80 -4
  323. package/dist/schemas/library/publishing.d.ts.map +1 -1
  324. package/dist/schemas/library/social.d.ts +44 -0
  325. package/dist/schemas/library/social.d.ts.map +1 -1
  326. package/dist/session/account-hint.d.ts.map +1 -1
  327. package/dist/session/account-hint.js +8 -5
  328. package/dist/session/account-hint.js.map +1 -1
  329. package/dist/session/auth.d.ts +36 -2
  330. package/dist/session/auth.d.ts.map +1 -1
  331. package/dist/session/auth.js +95 -2
  332. package/dist/session/auth.js.map +1 -1
  333. package/dist/session/connect.d.ts +1 -0
  334. package/dist/session/connect.d.ts.map +1 -1
  335. package/dist/session/connect.js +3 -1
  336. package/dist/session/connect.js.map +1 -1
  337. package/dist/session/credentials.d.ts +8 -26
  338. package/dist/session/credentials.d.ts.map +1 -1
  339. package/dist/session/credentials.js +14 -32
  340. package/dist/session/credentials.js.map +1 -1
  341. package/dist/session/index.d.ts +1 -0
  342. package/dist/session/index.d.ts.map +1 -1
  343. package/dist/session/index.js +1 -0
  344. package/dist/session/index.js.map +1 -1
  345. package/dist/session/pairing.d.ts.map +1 -1
  346. package/dist/session/pairing.js +92 -88
  347. package/dist/session/pairing.js.map +1 -1
  348. package/dist/session/password-strength.d.ts.map +1 -1
  349. package/dist/session/password-strength.js +37 -37
  350. package/dist/session/password-strength.js.map +1 -1
  351. package/dist/session/places.d.ts.map +1 -1
  352. package/dist/session/places.js +18 -13
  353. package/dist/session/places.js.map +1 -1
  354. package/dist/session/popup.d.ts +13 -0
  355. package/dist/session/popup.d.ts.map +1 -0
  356. package/dist/session/popup.js +23 -0
  357. package/dist/session/popup.js.map +1 -0
  358. package/dist/space/constitution.d.ts.map +1 -1
  359. package/dist/space/constitution.js +22 -29
  360. package/dist/space/constitution.js.map +1 -1
  361. package/dist/space/grants.d.ts.map +1 -1
  362. package/dist/space/grants.js +37 -39
  363. package/dist/space/grants.js.map +1 -1
  364. package/dist/space/invite-link.d.ts.map +1 -1
  365. package/dist/space/invite-link.js +33 -33
  366. package/dist/space/invite-link.js.map +1 -1
  367. package/dist/space/own-automations.d.ts +13 -24
  368. package/dist/space/own-automations.d.ts.map +1 -1
  369. package/dist/space/own-automations.js +47 -37
  370. package/dist/space/own-automations.js.map +1 -1
  371. package/dist/space/roles.d.ts +56 -80
  372. package/dist/space/roles.d.ts.map +1 -1
  373. package/dist/space/roles.js +448 -441
  374. package/dist/space/roles.js.map +1 -1
  375. package/dist/space/space-access.d.ts +3 -4
  376. package/dist/space/space-access.d.ts.map +1 -1
  377. package/dist/space/space-access.js +3 -8
  378. package/dist/space/space-access.js.map +1 -1
  379. package/dist/storage/blob/directory.d.ts.map +1 -1
  380. package/dist/storage/blob/directory.js +39 -32
  381. package/dist/storage/blob/directory.js.map +1 -1
  382. package/dist/storage/blob/s3.d.ts.map +1 -1
  383. package/dist/storage/blob/s3.js +21 -19
  384. package/dist/storage/blob/s3.js.map +1 -1
  385. package/dist/storage/blob-store.d.ts +0 -9
  386. package/dist/storage/blob-store.d.ts.map +1 -1
  387. package/dist/storage/directory-access.d.ts +8 -32
  388. package/dist/storage/directory-access.d.ts.map +1 -1
  389. package/dist/storage/directory-access.js +11 -36
  390. package/dist/storage/directory-access.js.map +1 -1
  391. package/dist/storage/encrypted-adapter.d.ts +12 -32
  392. package/dist/storage/encrypted-adapter.d.ts.map +1 -1
  393. package/dist/storage/encrypted-adapter.js +31 -54
  394. package/dist/storage/encrypted-adapter.js.map +1 -1
  395. package/dist/storage/folder-adapter.d.ts +12 -26
  396. package/dist/storage/folder-adapter.d.ts.map +1 -1
  397. package/dist/storage/folder-adapter.js +37 -54
  398. package/dist/storage/folder-adapter.js.map +1 -1
  399. package/dist/storage/folder-reconcile.d.ts +12 -26
  400. package/dist/storage/folder-reconcile.d.ts.map +1 -1
  401. package/dist/storage/folder-reconcile.js +39 -48
  402. package/dist/storage/folder-reconcile.js.map +1 -1
  403. package/dist/storage/indexeddb-adapter.d.ts +2 -6
  404. package/dist/storage/indexeddb-adapter.d.ts.map +1 -1
  405. package/dist/storage/indexeddb-adapter.js +60 -114
  406. package/dist/storage/indexeddb-adapter.js.map +1 -1
  407. package/dist/storage/mirror.d.ts +0 -29
  408. package/dist/storage/mirror.d.ts.map +1 -1
  409. package/dist/storage/mirror.js +153 -110
  410. package/dist/storage/mirror.js.map +1 -1
  411. package/dist/storage/segment.d.ts.map +1 -1
  412. package/dist/storage/segment.js +3 -7
  413. package/dist/storage/segment.js.map +1 -1
  414. package/dist/storage/storage-provider.d.ts +6 -11
  415. package/dist/storage/storage-provider.d.ts.map +1 -1
  416. package/dist/storage/storage-provider.js +112 -116
  417. package/dist/storage/storage-provider.js.map +1 -1
  418. package/dist/sync/sync-engine.d.ts +10 -44
  419. package/dist/sync/sync-engine.d.ts.map +1 -1
  420. package/dist/sync/sync-engine.js +245 -247
  421. package/dist/sync/sync-engine.js.map +1 -1
  422. package/dist/sync/sync-messages.d.ts +1 -1
  423. package/dist/sync/sync-messages.d.ts.map +1 -1
  424. package/dist/sync/sync-messages.js +1 -1
  425. package/dist/sync/sync-messages.js.map +1 -1
  426. package/dist/utils/guards.d.ts +1 -0
  427. package/dist/utils/guards.d.ts.map +1 -1
  428. package/dist/utils/guards.js +1 -0
  429. package/dist/utils/guards.js.map +1 -1
  430. package/dist/utils/hmac.d.ts +5 -0
  431. package/dist/utils/hmac.d.ts.map +1 -0
  432. package/dist/utils/hmac.js +20 -0
  433. package/dist/utils/hmac.js.map +1 -0
  434. package/dist/utils/map.d.ts +10 -0
  435. package/dist/utils/map.d.ts.map +1 -0
  436. package/dist/utils/map.js +30 -0
  437. package/dist/utils/map.js.map +1 -0
  438. package/dist/utils/serial.d.ts +2 -0
  439. package/dist/utils/serial.d.ts.map +1 -1
  440. package/dist/utils/serial.js +9 -0
  441. package/dist/utils/serial.js.map +1 -1
  442. package/dist/validation/capability-gate.d.ts +7 -15
  443. package/dist/validation/capability-gate.d.ts.map +1 -1
  444. package/dist/validation/capability-gate.js +32 -36
  445. package/dist/validation/capability-gate.js.map +1 -1
  446. package/dist/validation/crypto-gate.d.ts.map +1 -1
  447. package/dist/validation/crypto-gate.js +12 -21
  448. package/dist/validation/crypto-gate.js.map +1 -1
  449. package/docs/README.md +3 -2
  450. package/docs/actions.md +47 -20
  451. package/docs/automations.md +1 -1
  452. package/docs/blueprints-and-guides.md +57 -13
  453. package/docs/building-an-app.md +11 -8
  454. package/docs/collections.md +33 -5
  455. package/docs/contacts.md +34 -1
  456. package/docs/contracts.md +1 -1
  457. package/docs/direct-messages.md +1 -1
  458. package/docs/inbox.md +5 -11
  459. package/docs/node.md +36 -26
  460. package/docs/records-and-queries.md +1 -1
  461. package/docs/sign-in.md +54 -26
  462. package/docs/spaces.md +6 -6
  463. package/docs/standard-library.md +33 -31
  464. package/docs/storage.md +37 -15
  465. package/docs/usernames.md +161 -0
  466. package/docs/warrants.md +1 -1
  467. package/package.json +2 -21
  468. package/dist/calls/calls.d.ts +0 -140
  469. package/dist/calls/calls.d.ts.map +0 -1
  470. package/dist/calls/calls.js +0 -861
  471. package/dist/calls/calls.js.map +0 -1
  472. package/dist/calls/index.d.ts +0 -4
  473. package/dist/calls/index.d.ts.map +0 -1
  474. package/dist/calls/index.js +0 -3
  475. package/dist/calls/index.js.map +0 -1
  476. package/dist/react/context.d.ts +0 -81
  477. package/dist/react/context.d.ts.map +0 -1
  478. package/dist/react/context.js +0 -97
  479. package/dist/react/context.js.map +0 -1
  480. package/dist/react/follow.d.ts +0 -11
  481. package/dist/react/follow.d.ts.map +0 -1
  482. package/dist/react/follow.js +0 -7
  483. package/dist/react/follow.js.map +0 -1
  484. package/dist/react/index.d.ts +0 -44
  485. package/dist/react/index.d.ts.map +0 -1
  486. package/dist/react/index.js +0 -40
  487. package/dist/react/index.js.map +0 -1
  488. package/dist/react/minca-auth.d.ts +0 -19
  489. package/dist/react/minca-auth.d.ts.map +0 -1
  490. package/dist/react/minca-auth.js +0 -36
  491. package/dist/react/minca-auth.js.map +0 -1
  492. package/dist/react/use-calls.d.ts +0 -21
  493. package/dist/react/use-calls.d.ts.map +0 -1
  494. package/dist/react/use-calls.js +0 -39
  495. package/dist/react/use-calls.js.map +0 -1
  496. package/dist/react/use-invite-link.d.ts +0 -24
  497. package/dist/react/use-invite-link.d.ts.map +0 -1
  498. package/dist/react/use-invite-link.js +0 -62
  499. package/dist/react/use-invite-link.js.map +0 -1
  500. package/dist/react/use-live.d.ts +0 -16
  501. package/dist/react/use-live.d.ts.map +0 -1
  502. package/dist/react/use-live.js +0 -56
  503. package/dist/react/use-live.js.map +0 -1
  504. package/dist/react/use-my-name.d.ts +0 -12
  505. package/dist/react/use-my-name.d.ts.map +0 -1
  506. package/dist/react/use-my-name.js +0 -38
  507. package/dist/react/use-my-name.js.map +0 -1
  508. package/dist/react/use-names.d.ts +0 -7
  509. package/dist/react/use-names.d.ts.map +0 -1
  510. package/dist/react/use-names.js +0 -13
  511. package/dist/react/use-names.js.map +0 -1
  512. package/dist/react/use-network.d.ts +0 -9
  513. package/dist/react/use-network.d.ts.map +0 -1
  514. package/dist/react/use-network.js +0 -33
  515. package/dist/react/use-network.js.map +0 -1
  516. package/dist/react/use-query.d.ts +0 -14
  517. package/dist/react/use-query.d.ts.map +0 -1
  518. package/dist/react/use-query.js +0 -26
  519. package/dist/react/use-query.js.map +0 -1
  520. package/dist/react/use-space.d.ts +0 -29
  521. package/dist/react/use-space.d.ts.map +0 -1
  522. package/dist/react/use-space.js +0 -57
  523. package/dist/react/use-space.js.map +0 -1
  524. package/dist/react/use-spaces.d.ts +0 -29
  525. package/dist/react/use-spaces.d.ts.map +0 -1
  526. package/dist/react/use-spaces.js +0 -78
  527. package/dist/react/use-spaces.js.map +0 -1
  528. package/docs/calls.md +0 -189
@@ -1,267 +1,46 @@
1
- /**
2
- * @module node/space-runtime
3
- * One open space: its store, its gatekeeper, its peers, its sync.
4
- *
5
- * A space is the unit of storage and of sync — its own store, its own
6
- * rooms and sockets — so two spaces never mix, and a peer you share one space
7
- * with learns nothing about the others.
8
- *
9
- * **A record keeps its key; changes are versions.** Editing a record writes its
10
- * next version — same key, `seq` one higher, `prev` naming the one replaced —
11
- * and deleting it writes a version marked deleted. Which version is current is
12
- * decided by `seq` and id alone (`records/version.ts`), never by a clock, so
13
- * every node agrees and nothing replayed can roll a record back.
14
- *
15
- * **Who may write is the space's access history** (`space/roles.ts`): roles,
16
- * members, invites, revoked notes and collection definitions, as records every
17
- * version points into with `seen`. A version stands when its author held what
18
- * its collection's rules ask, as of what it saw, and nothing it had not seen
19
- * took that away. A version that stops standing — its author was removed, and
20
- * the remover never saw it — is passed over when reading, and the version
21
- * before it counts again, where the store still has one.
22
- */
23
- import { contactKeyPair, isContactPublicKey } from '../identity/contact-key.js';
24
- import { openValueFrom, sealValueTo } from '../identity/hpke.js';
25
- import { openValue, sealValue } from '../identity/envelope.js';
26
- import { verifyNote } from '../identity/ucan.js';
27
- import { ACCESS_COMMAND, accessRequirement, actsForAccount, DEFINE_COMMAND, noteGrants, writeRequirement, writesRecords, } from '../identity/abilities.js';
28
- import { bodyProblem, canonicalize, createVersion, getVersionId, isStub, signedPart, stubOf, } from '../schema/version.js';
1
+ import { actsForAccount } from '../identity/abilities.js';
2
+ import { contactKeyPair } from '../identity/contact-key.js';
3
+ import { ownedKey } from '../records/key.js';
4
+ import { topicTag } from '../records/topics.js';
5
+ import { storedComputed, storedContract } from '../records/contract-builder.js';
6
+ import { usableComputed } from '../query/computed.js';
29
7
  import { createStorageProvider } from '../storage/storage-provider.js';
30
- import { chainProblem, MAX_SEEN, nextVersion } from '../records/version.js';
31
- import { keyKind, lineKey, newRecordKey, onePerForm, ownedKey, ownsKey, RECORD_KEY_PATTERN, } from '../records/key.js';
32
- import { checkLinks } from '../records/links.js';
33
- import { checkContractShape, checkContracts, checkContractTypes, checkLine, hasContract, onceCitations, runContracts, } from '../records/contracts.js';
34
- import { changedFixedField, onePerKey, onePerSecret } from '../records/rules.js';
35
- import { reconcileFolder } from '../storage/folder-reconcile.js';
36
- import { createMirror } from '../storage/mirror.js';
37
- import { createVersionCheck } from '../validation/check-version.js';
38
- import { breaksLine, checkFork, forkProof } from '../records/fork.js';
39
- import { knownKind, readWarrant } from '../records/warrant.js';
40
- import { EARLIER_KEYS_LABEL, generateSpaceKey, isSealedBody, MEMBERSHIP_LABEL, openBody as openSealedBody, sealBody, spaceKeyFromRaw, } from '../privacy/space-encryption.js';
41
- import { createNetworkManager } from '../network/network-manager.js';
42
- import { createMesh } from '../network/mesh.js';
43
- import { createWebSocketTransport } from '../network/ws-transport.js';
44
- import { createClientAuth, createMeshAuth, MAX_EARLIER_READ_KEYS, } from '../network/peer-auth.js';
45
- import { BOX_COLLECTION, MEMBER_KEY_COLLECTION, SPACE_KEY_RECORD, SPACE_RELAYS_RECORD, SPACE_KEEPERS_RECORD, memberKeyRecordKey, BOX_LABEL, boxBound, boxKey, deriveInviteKey, deriveReadKey, generateInviteSecret, inviteKey as inviteRecordKey, assignKey, removalKey, revokeKey, roleKey, signInvite, verifyInvite, forkKey, stepDownKey, succeedKey, WARRANT_COLLECTION, } from '../space/space-access.js';
46
- import { accessGenesisOf, isSpaceId } from '../space/constitution.js';
47
- import { ACCESS_COLLECTIONS, ACCESS_KINDS, ASSIGN_COLLECTION, DEFINITION_COLLECTION, INVITE_COLLECTION, KEY_COLLECTION, MAX_RELAYS, RELAYS_COLLECTION, checkRelays, KEEPERS_COLLECTION, FORK_COLLECTION, checkKeepers, REMOVE_COLLECTION, REVOKE_COLLECTION, ROLE_COLLECTION, STEPDOWN_COLLECTION, SUCCEED_COLLECTION, headless, isMember, holdsRole, may, readers, replayAccess, refusal, rolesOf, } from '../space/roles.js';
48
- import { checkFoundingRole, definitionBody, KEY_CHANGE, readDefinition, RECORD_DELETE, RECORD_WRITE, SPACE_RELAYS, } from '../space/grants.js';
8
+ import { ACCESS_COLLECTIONS, rolesOf } from '../space/roles.js';
49
9
  import { FOUNDER } from '../space/space-manager.js';
50
- import { createSyncEngine } from '../sync/sync-engine.js';
10
+ import { PROFILE_COLLECTION } from '../space/account-registry.js';
51
11
  import { SYNC_PROTOCOL_VERSION } from '../sync/sync-messages.js';
52
- import { createSpaceFiles } from '../files/space-files.js';
53
- import { fileRefsIn, MAX_FILES } from '../files/file-id.js';
54
- import { CATALOG_COLLECTION, checkStoredCollection, isStoredCollection, toJsonSchema, validateJsonSchema, } from '../schema/collection-def.js';
55
- import { CARRIER_COLLECTION, MEMBERSHIP_COLLECTION, PROFILE_COLLECTION, isAvatarRef, } from '../space/account-registry.js';
56
- import { PASS_COLLECTION } from '../space/pass.js';
57
- import { base32Encode, cidOfDigest, hashedKey, sha256 } from '../utils/hash.js';
58
- import { sameTags, tagsFor, topicKey, topicTag } from '../records/topics.js';
59
- import { base64UrlDecode, base64UrlEncode, utf8Decode, utf8Encode } from '../utils/encoding.js';
60
- import { isRecord, unref } from '../utils/guards.js';
61
- import { serial } from '../utils/serial.js';
62
- /** Collections the node writes itself, through their own calls — never through `put` */
63
- const MANAGED = new Set([
64
- MEMBERSHIP_COLLECTION,
65
- WARRANT_COLLECTION,
66
- PROFILE_COLLECTION,
67
- CARRIER_COLLECTION,
68
- PASS_COLLECTION,
69
- BOX_COLLECTION,
70
- MEMBER_KEY_COLLECTION,
71
- ...ACCESS_COLLECTIONS,
72
- ]);
73
- /**
74
- * Access records a peer without the space key must still be able to judge:
75
- * who holds which role decides every write. Kept in the clear, even in a
76
- * private space. Collection definitions stay sealed — a peer that cannot
77
- * read the records has no use for their rules.
78
- */
79
- const IN_THE_CLEAR = new Set([
80
- ...Object.values(ACCESS_KINDS)
81
- .filter(({ clear }) => clear)
82
- .map(({ collection }) => collection),
83
- BOX_COLLECTION,
84
- MEMBER_KEY_COLLECTION,
85
- ]);
86
- /** How many keys a cutoff may name */
87
- const MAX_CUTOFF = 1024;
88
- /** A change that takes nothing away covers nothing */
89
- const NO_CUTOFF = new Map();
90
- /** A cutoff from a record's body — key DID → collection → the place covered up to — or null when it isn't one */
91
- function readCutoff(value) {
92
- if (value === undefined)
93
- return new Map();
94
- if (!isRecord(value))
95
- return null;
96
- const cutoff = new Map();
97
- let entries = 0;
98
- for (const [key, lines] of Object.entries(value)) {
99
- if (!key.startsWith('did:key:') || !isRecord(lines))
100
- return null;
101
- const byCollection = new Map();
102
- for (const [collection, n] of Object.entries(lines)) {
103
- if (typeof n !== 'number' || !Number.isSafeInteger(n) || n < 0 || ++entries > MAX_CUTOFF)
104
- return null;
105
- byCollection.set(collection, n);
106
- }
107
- cutoff.set(key, byCollection);
108
- }
109
- return cutoff;
110
- }
111
- /** Freezes a value and everything inside it, in place */
112
- function deepFreeze(value) {
113
- if (value === null || typeof value !== 'object' || Object.isFrozen(value))
114
- return;
115
- Object.freeze(value);
116
- for (const inner of Object.values(value))
117
- deepFreeze(inner);
118
- }
119
- /** Decrypted bodies kept in memory per space, the oldest let go first */
120
- const MAX_OPENED = 100_000;
121
- /** Line heads whose `once` claims are kept: each set holds its whole chain's, so fewer */
122
- const MAX_ONCE_CLAIMED = 1024;
123
- /**
124
- * The key of a person's profile record in a space: one per identity, named by
125
- * a hash of it (record keys are lower case; a did:key is not).
126
- */
127
- export async function profileKey(did) {
128
- return hashedKey('profile', did);
129
- }
130
- /**
131
- * The room a space's peers meet in on a relay. A hash of the space's id, so a
132
- * relay learns which connections belong together but not which space they are
133
- * — it cannot match the room to an invite, or to the same space elsewhere.
134
- */
135
- export async function relayRoom(spaceId) {
136
- return base32Encode((await sha256(new TextEncoder().encode(`minca-room/v1|${spaceId}`))).subarray(0, 20));
137
- }
138
- /** The one mesh a node's spaces share, when it has relays to meet on */
139
- export function meshFor(network, session) {
140
- if (!network?.relays?.length)
141
- return undefined;
142
- return createMesh({
143
- did: session.did,
144
- key: session.key,
145
- relays: network.relays,
146
- ...(network.iceServers ? { iceServers: network.iceServers } : {}),
147
- ...(network.createTransport ? { createTransport: network.createTransport } : {}),
148
- });
149
- }
150
- /** The relays a node was configured with that a space may name */
151
- export const usableRelays = (network) => (network?.relays ?? []).filter((url) => checkRelays([url]) === null);
152
- /**
153
- * Whether a proof would let its key do anything in a space beyond writing
154
- * records: define a collection there, or change who may do what. For what a
155
- * node offers and shows; a version's own needs are judged on its own.
156
- */
157
- const grantsBeyondRecords = (proof, spaceId, cmd) => noteGrants(proof, { space: spaceId, cmd, args: { space: spaceId } });
158
- /** Said when a key's note doesn't let it define collections — it can propose them instead */
159
- export const CANNOT_DEFINE = "This key's note doesn't let it add or change collections. Propose them instead (collections_propose), and someone who may adds them.";
160
- const CANNOT_CHANGE_ACCESS = "This key's note doesn't let it change who may do what in a space. Ask the person.";
161
- const NOT_ACCOUNT = "This key's note doesn't let it change the account itself. Ask the person.";
162
- /**
163
- * Whether a version is about the account that signs it: its own place in the
164
- * space (taking or giving up a role, leaving, stepping down), what others
165
- * seal to it or see of it, or another of its keys. Only a key acting as the
166
- * account itself writes one (spec 01 §8), so an app given a space never
167
- * changes the account's standing there.
168
- */
169
- function aboutItself(collection, body, root, author) {
170
- if (collection === STEPDOWN_COLLECTION || collection === MEMBER_KEY_COLLECTION)
171
- return true;
172
- if (collection === PROFILE_COLLECTION)
173
- return true;
174
- if (!isRecord(body))
175
- return false;
176
- if (collection === ASSIGN_COLLECTION || collection === REMOVE_COLLECTION)
177
- return body.did === root;
178
- return collection === REVOKE_COLLECTION && body.key !== author;
179
- }
180
- const NO_ACCOUNT = Object.freeze({ account: null, recordsOnly: false });
181
- /** How long a peer checked here has to become a peer before the check is forgotten: past any handshake's timeout */
182
- const STALE_ADMISSION_MS = 60_000;
183
- /** How long a removed member's socket stays open after nothing more is sent on it, for frames already on their way */
184
- const LET_GO_AFTER_MS = 1000;
185
- /** How long a peer let in on an older key has to show its account before it counts as nobody's */
186
- const WHO_WAIT_MS = 10_000;
187
- /** A peer's note, sent once when it connects (see "Live messages") */
188
- const WHO_MESSAGE = 'who';
189
- /** A live message: `spaces.send` */
190
- const LIVE_MESSAGE = 'live';
191
- const MAX_LIVE_BYTES = 64 * 1024;
192
- const MAX_NOTE_LENGTH = 16 * 1024;
193
- /** Live messages a peer may send at once, and per second after that */
194
- const LIVE_BURST = 60;
195
- const LIVE_PER_SECOND = 20;
196
- const STANDS = { ok: true };
197
- const ACCESS_LATER = Object.freeze({
198
- ok: false,
199
- reason: 'Access changes it depends on have not arrived yet',
200
- later: true,
201
- });
202
- import { checkComputed, checkComputedTypes, usableComputed } from '../query/computed.js';
203
- import { storedComputed, storedContract } from '../records/contract-builder.js';
204
- const NO_CHECKS = { passes: null };
205
- /** Records waiting on a cited version that are read again whenever anything arrives */
206
- const MAX_PENDING_REREAD = 256;
207
- /** Checks this node can't judge yet: what they read can't be opened here. Never cached. */
208
- const UNJUDGED = Object.freeze({
209
- passes: null,
210
- unjudged: 'Something it reads is sealed with a key this node doesn’t hold',
211
- });
212
- const storable = (standing) => standing.ok || !!standing.withdrawn;
213
- /**
214
- * What the caches of verdicts on a version are keyed by: its id and signature,
215
- * which a stub shares with the whole version, and which of the two it is. A
216
- * verdict on a stub, judged without its body, never stands for the whole.
217
- */
218
- const copyKey = (version) => `${version.id}|${version.signature}|${isStub(version) ? 'stub' : 'whole'}`;
219
- const looksEncrypted = isSealedBody;
220
- /** The key a sealed body names, as the keyring is looked up by */
221
- function sealedKeyId(body) {
222
- return String(isRecord(body) ? body.keyId : undefined);
223
- }
224
- function isFolderAdapter(adapter) {
225
- return 'reload' in adapter && typeof adapter.reload === 'function';
226
- }
227
- const isLinks = (links) => checkLinks(links) === null;
228
- const isLine = (line) => checkLine(line) === null;
229
- const areKeepers = (keepers) => checkKeepers(keepers) === null;
230
- function isPending(value) {
231
- return isRecord(value) && typeof value.collection === 'string' && isStringList(value.by);
232
- }
233
- const isStringList = (value) => Array.isArray(value) && value.every((v) => typeof v === 'string');
234
- // ─── What a node holding part of a space remembers ──────────────────
235
- /** Where it is kept in the space's store */
236
- const CACHE_KEY = 'cache';
237
- /** One entry per write of this node's still waiting for keepers: `pending/<id>` */
238
- const PENDING_PREFIX = 'pending/';
239
- async function loadCacheState(adapter) {
240
- try {
241
- const bytes = await adapter.get(CACHE_KEY);
242
- const parsed = bytes ? JSON.parse(utf8Decode(bytes)) : null;
243
- const saved = isRecord(parsed) ? parsed : {};
244
- const numbers = (value) => Object.fromEntries(Object.entries(typeof value === 'object' && value !== null ? value : {}).filter(([, v]) => typeof v === 'number'));
245
- const lists = (value) => Object.fromEntries(Object.entries(isRecord(value) ? value : {}).flatMap(([name, ids]) => Array.isArray(ids) ? [[name, ids.filter((id) => typeof id === 'string')]] : []));
246
- return {
247
- settled: saved.settled === true,
248
- used: numbers(saved.used),
249
- level: numbers(saved.level),
250
- missing: lists(saved.missing),
251
- };
252
- }
253
- catch {
254
- return { settled: false, used: {}, level: {}, missing: {} };
255
- }
12
+ import { createSpaceFiles, DEVICE_LIMITS } from '../files/space-files.js';
13
+ import { CATALOG_COLLECTION, toJsonSchema } from '../schema/collection-def.js';
14
+ import { unref } from '../utils/guards.js';
15
+ import { openSpaceHolding } from './space-holding.js';
16
+ import { createVersions, storable, } from './space-versions.js';
17
+ import { createHistory } from './space-history.js';
18
+ import { createRules } from './space-rules.js';
19
+ import { createStanding } from './space-standing.js';
20
+ import { createChecks } from './space-checks.js';
21
+ import { createCatalog, definitionProblem } from './space-catalog.js';
22
+ import { createIndex } from './space-index.js';
23
+ import { createProfiles, profileKey } from './space-profiles.js';
24
+ import { createKeys } from './space-keys.js';
25
+ import { createWriting } from './space-writing.js';
26
+ import { createLines } from './space-lines.js';
27
+ import { createWarrants } from './space-warrants.js';
28
+ import { openMirrors } from './space-mirrors.js';
29
+ import { createMeeting, openPeers } from './space-peers.js';
30
+ import { createMembership } from './space-membership.js';
31
+ /** What this account is here, for listing: `founder`, a role it holds, or null */
32
+ function placeOf(state, did) {
33
+ if (state.founders.has(did))
34
+ return FOUNDER;
35
+ return rolesOf(state, did)[0] ?? null;
256
36
  }
257
37
  export async function openSpaceRuntime(deps) {
258
- const { record, provider, signer, schemas, session, emit } = deps;
38
+ const { record, provider, signer, schemas, session, emit, rootDid } = deps;
259
39
  const { space } = record;
260
40
  let closed = false;
261
- /**
262
- * Every key of the space this node holds, by id. Encrypted bodies name the
263
- * key they were sealed with; the history names which one is current.
264
- */
41
+ const isClosed = () => closed;
42
+ const statusChanged = () => emit({ type: 'status', space: space.id });
43
+ /** Every key of the space this node holds, by id: a sealed body names its key, the history the current one */
265
44
  const keyring = new Map();
266
45
  for (const held of record.keys ?? [])
267
46
  keyring.set(held.id, held);
@@ -269,3350 +48,284 @@ export async function openSpaceRuntime(deps) {
269
48
  keyring.set(record.key.id, record.key);
270
49
  /** This account's member key here, which new keys are sealed to */
271
50
  const memberPair = deps.memberKey ? await contactKeyPair(deps.memberKey) : null;
272
- /** An invite waiting to be used — forgotten here once it is, whatever the stored record still says */
273
- let waitingInvite = record.invite !== null;
274
51
  const adapter = await deps.stores(`spaces/${space.id}`);
275
52
  const storage = createStorageProvider(adapter);
276
- // What this node holds of the space (see "Holding part of the space" below).
277
- // Here, before anything can ask: sync asks on every hello.
278
- const cache = deps.cache ?? null;
279
- const cacheState = await loadCacheState(adapter);
280
- // The collections the app declared are held from the start.
281
- for (const collection of cache?.collections ?? [])
282
- if (!collection.startsWith('sys.'))
283
- cacheState.used[collection] ??= Date.now();
284
- // A node that may hold part of the space starts by holding only what it
285
- // uses: whether the space names keepers is only known once it has caught up.
286
- let partial = cache !== null;
287
- const holds = () => (partial ? new Set(Object.keys(cacheState.used)) : 'all');
288
- // Body shape is checked when a record is written here, and reported as
289
- // `conforms` when it is read. The note behind a key must cover this space;
290
- // whether its account may write here is the access history's question, asked below.
291
- // Judged for this space, whatever space a version claims: standing refuses a claim of another.
292
- const checkVersion = createVersionCheck({
293
- provider,
294
- required: (version) => writeRequirement(space.id, version.collection),
53
+ // What this node holds (`node/space-holding.ts`): settled here, since sync asks on every hello.
54
+ const holding = await openSpaceHolding({
55
+ cache: deps.cache ?? null,
56
+ adapter,
57
+ storage,
58
+ spaceId: space.id,
59
+ sessionDid: session.did,
60
+ emit,
61
+ statusChanged,
62
+ isClosed,
63
+ access: () => history.access(),
64
+ sync: () => peers.sync,
65
+ connectedPeers: () => peers.connectedPeers(),
66
+ recordsChanged: () => recordsChanged(),
295
67
  });
296
- // A signature never changes, so a verdict on one holds forever. Keyed on the
297
- // id *and* the signature: the id does not cover it, so a copy with a broken
298
- // signature shares the genuine one's id. Only passes are kept — a failure
299
- // remembered by id would let anyone who sends a mangled copy first get the
300
- // real record refused; and failures are what a stranger can mint for free.
301
- const verdicts = new Map();
302
- const verdictKey = (e) => `${e.id}|${e.signature}`;
303
- /** Copies checked to be what their id names, envelope and body: the caches are keyed by id and signature alone */
304
- const copiesChecked = new WeakSet();
305
- /**
306
- * Why a copy isn't what its id names, or null when it is: its id must be the
307
- * hash of its own envelope, and its body the one its `bodyHash` names. Asked
308
- * before any verdict cached by id and signature is used, so a copy with the
309
- * real id and signature but another envelope or body never passes on the
310
- * real one's.
311
- */
312
- async function copyProblem(version) {
313
- if (copiesChecked.has(version))
314
- return null;
315
- const problem = (await bodyProblem(version)) ??
316
- (version.id === (await getVersionId(signedPart(version)))
317
- ? null
318
- : 'Its id is not the hash of what it says');
319
- if (!problem)
320
- copiesChecked.add(version);
321
- return problem;
322
- }
323
- /** Whether a version is signed, and by a key whose note covers this space — and which account that is */
324
- async function judge(version) {
325
- const problem = await copyProblem(version);
326
- if (problem)
327
- return { verified: false, root: null, reason: problem };
328
- const cached = verdicts.get(verdictKey(version));
329
- if (cached)
330
- return cached;
331
- const result = await checkVersion(version);
332
- let verdict;
333
- if (!result.passed) {
334
- verdict = { verified: false, root: null, ...(result.reason ? { reason: result.reason } : {}) };
335
- }
336
- else {
337
- const checked = version.proof !== undefined ? await verifyNote(version.proof, provider, { untimed: true }) : null;
338
- verdict = { verified: true, root: checked?.valid ? checked.root : version.author };
339
- verdicts.set(verdictKey(version), verdict);
340
- }
341
- return verdict;
342
- }
343
- /**
344
- * Bodies already decrypted, by version id. Only a version whose signature
345
- * checked out is ever opened, and a failure is not kept: a key that arrives
346
- * later may open it.
347
- */
348
- const openedBodies = new Map();
349
- /**
350
- * A version's content: its body and its links. In a private space both are
351
- * sealed together, so a relay learns neither what a record says nor what it
352
- * points at.
353
- */
354
- async function openBody(version) {
355
- // A stub's content is forgotten: read like one this node holds no key for.
356
- if (isStub(version))
357
- return { body: null, links: version.links ?? [], encrypted: false };
358
- if (!looksEncrypted(version.body))
359
- return { body: version.body, links: version.links ?? [], encrypted: false };
360
- const known = openedBodies.get(version.id);
361
- if (known)
362
- return known;
363
- const sealedWith = keyring.get(sealedKeyId(version.body));
364
- if (!sealedWith)
365
- return { body: null, links: [], encrypted: true };
366
- try {
367
- // Bound to this record: a body copied from another record, space or collection does not open.
368
- const content = await openSealedBody(version.body, sealedWith, {
369
- space: space.id,
370
- collection: version.collection,
371
- key: version.key,
372
- });
373
- const opened = isRecord(content) ? content : null;
374
- const sealedLinks = opened?.links ?? [];
375
- const links = isLinks(sealedLinks) ? sealedLinks : [];
376
- const result = Object.freeze({ body: opened?.body ?? null, links, encrypted: true });
377
- // An id names its content, so what opened once opens the same way again.
378
- openedBodies.set(version.id, result);
379
- if (openedBodies.size > MAX_OPENED)
380
- openedBodies.delete(openedBodies.keys().next().value);
381
- return result;
382
- }
383
- catch {
384
- return { body: null, links: [], encrypted: true };
385
- }
386
- }
387
- /**
388
- * Whether `first` can be the first version of the record `version` belongs
389
- * to. A later version names its first version itself, and a check that took
390
- * that on trust would let anyone point at a record with no rules — or in
391
- * another collection — and be judged by that instead.
392
- */
393
- const firstOf = (version, first) => !!first && first.seq === 0 && first.key === version.key && first.collection === version.collection;
394
- /**
395
- * A version's first version: itself at seq 0, else the one its chain names
396
- * (02 §4.5). Never the lowest id held at its key, which anyone who may
397
- * create there could grind.
398
- */
399
- async function genesisOf(version) {
400
- if (version.seq === 0)
401
- return version;
402
- const first = version.genesis ? await storage.getVersion(version.genesis) : null;
403
- return firstOf(version, first) ? first : null;
404
- }
405
- /**
406
- * Whether a version is one this node should show: a later version whose
407
- * first version is held and is its record's. Every version stored passed
408
- * that check on arrival (02 §4.7); this keeps a read from trusting it.
409
- */
410
- async function consistent(version) {
411
- return version.seq === 0 || (await genesisOf(version)) !== null;
412
- }
413
- // ─── Record keys ───────────────────────────────────────────────────
414
- //
415
- // Outside sys.*, a first version is at a key its account owns, or at a
416
- // shared onePer key (02 §4.1, `records/key.ts`), so no member can write a
417
- // first version at another's key and become its creator.
418
- let oneSecret = null;
419
- /**
420
- * What this space's onePer keys are keyed with: its first space key in a
421
- * private space, its id in a public one (02 §7.3). Null when this node
422
- * holds no key of a private space.
423
- */
424
- function onePerKeying() {
425
- if (oneSecret)
426
- return oneSecret;
427
- if (space.visibility !== 'private')
428
- return (oneSecret = onePerSecret({ spaceId: space.id }));
429
- const first = space.encryptionKeyId ? keyring.get(space.encryptionKeyId) : undefined;
430
- return first ? (oneSecret = onePerSecret({ spaceKey: first.raw })) : null;
431
- }
432
- /** The key `put` writes a body at under a collection's `onePer`, for `root`; null when a part it names is missing */
433
- async function derivedKey(collection, onePer, record) {
434
- const keying = onePerKeying();
435
- if (!keying)
436
- throw new Error('This private space has no key on this node');
437
- return onePerKey(await keying, collection, onePer, record);
438
- }
439
- /** Why a first version's key isn't one its account may write first, from the version alone; null when it may */
440
- async function keyProblem(version, root) {
441
- if (version.seq !== 0)
442
- return null;
443
- const kind = keyKind(version.key);
444
- // The protocol's own records keep keys of their own, so none can be current at someone's key.
445
- if (version.collection.startsWith('sys.'))
446
- return kind === null
447
- ? null
448
- : { ok: false, reason: 'A sys.* record is never at an owned or a one: key' };
449
- if (kind === 'shared')
450
- return null;
451
- if (kind === 'owned' && (await ownsKey(version.key, root)))
452
- return null;
453
- return {
454
- ok: false,
455
- reason: kind === 'owned'
456
- ? 'Its key belongs to another account'
457
- : 'A new record needs a key its account owns, or a shared one: key',
458
- };
459
- }
460
- /**
461
- * Why a first version at a key of a `onePer` key's form, shared `one:<hex>`
462
- * or owned `<owner>.one:<hex>`, can't be there, as of one state of the
463
- * history (02 §7.3): only a collection whose rules have `onePer` gives one,
464
- * owned when it names `@author` and shared when it doesn't. Judged from the
465
- * definition alone, so peers that can't derive the key agree. Null when it
466
- * can, or when this node can't read the definition to tell.
467
- */
468
- async function onePerKeyProblem(version, state) {
469
- const form = onePerForm(version.key);
470
- if (version.seq !== 0 || !form || version.collection.startsWith('sys.'))
471
- return null;
472
- const id = await inForce(state, version.collection);
473
- const found = id ? await definitionIn(id) : 'missing';
474
- if (found === 'unreadable')
475
- return null;
476
- const onePer = typeof found === 'string' ? undefined : found.definition.rules?.onePer;
477
- if (!onePer)
478
- return { ok: false, reason: 'A one: key is only for a collection whose rules have onePer' };
479
- if (form === 'shared' && onePer.includes('@author'))
480
- return { ok: false, reason: 'A shared one: key is only for a onePer that does not name @author' };
481
- if (form === 'owned' && !onePer.includes('@author'))
482
- return { ok: false, reason: 'An owned one: key is only for a onePer that names @author' };
483
- return null;
484
- }
485
- // ─── The access history ────────────────────────────────────────────
486
- //
487
- // Every version in the access collections, kept whole (`retain`), turned
488
- // into plain events and replayed. Rebuilt when records change; everything
489
- // about who may do what is read from the replay.
490
- const accessGenesis = accessGenesisOf(space);
491
- /** Events, by version id — building one checks signatures and invites, so they are kept */
492
- const events = new Map();
493
- const eventKey = (version) => `${version.id}|${version.signature}`;
494
- async function toEvent(version) {
495
- if (await copyProblem(version))
496
- return null;
497
- const cacheKey = eventKey(version);
498
- if (events.has(cacheKey))
499
- return events.get(cacheKey);
500
- const event = await buildEvent(version);
501
- // A failed signature is what a stranger can mint for free; only settled answers from a valid one are kept.
502
- if (event || (await judge(version)).verified)
503
- events.set(cacheKey, event);
504
- return event;
505
- }
506
- async function buildEvent(version) {
507
- if (!ACCESS_COLLECTIONS.has(version.collection) || !version.retain)
508
- return null;
509
- // Only a note that grants it changes the space's collections, or who may do what.
510
- if (!noteGrants(version.proof, accessRequirement(space.id, version.collection, version.key)))
511
- return null;
512
- const verdict = await judge(version);
513
- if (!verdict.verified || !verdict.root)
514
- return null;
515
- if (!actsForAccount(version.proof) &&
516
- aboutItself(version.collection, version.body, verdict.root, version.author))
517
- return null;
518
- const seen = version.seen ?? [];
519
- const base = {
520
- id: version.id,
521
- key: version.key,
522
- root: verdict.root,
523
- author: version.author,
524
- seen,
525
- cutoff: NO_CUTOFF,
526
- ...(version.log ? { line: version.log.n } : {}),
527
- };
528
- if (version.collection === DEFINITION_COLLECTION) {
529
- if (!version.key.startsWith('collection:'))
530
- return null;
531
- return {
532
- ...base,
533
- kind: 'definition',
534
- name: version.key.slice('collection:'.length),
535
- deleted: !!version.deleted,
536
- };
537
- }
538
- // Everything else in the history is taken away by a change, never deleted: a delete has no body to carry a cutoff.
539
- if (version.deleted || looksEncrypted(version.body))
540
- return null;
541
- const body = version.body;
542
- if (!isRecord(body))
543
- return null;
544
- const cutoff = readCutoff(body.cutoff);
545
- if (!cutoff)
546
- return null;
547
- switch (version.collection) {
548
- case ROLE_COLLECTION: {
549
- // A definition carries no cutoff: it takes nothing from anyone, and binds what saw it.
550
- if (body.cutoff !== undefined)
551
- return null;
552
- const defined = readDefinition(body, { root: verdict.root, spaceId: space.id });
553
- if (!defined || version.key !== roleKey(defined.name))
554
- return null;
555
- return {
556
- ...base,
557
- kind: 'role',
558
- name: defined.name,
559
- ...(defined.title !== undefined ? { title: defined.title } : {}),
560
- grants: defined.grants,
561
- nests: defined.nests,
562
- };
563
- }
564
- case ASSIGN_COLLECTION: {
565
- const { did, role, assigned } = body;
566
- // Roles go to accounts, never to roles: an assignee is a did:key.
567
- if (typeof did !== 'string' || !did.startsWith('did:key:') || typeof role !== 'string')
568
- return null;
569
- if (typeof assigned !== 'boolean')
570
- return null;
571
- if (version.key !== (await assignKey(did, role)))
572
- return null;
573
- const invite = body.invite;
574
- let viaInvite;
575
- if (invite !== undefined) {
576
- if (!isRecord(invite) || typeof invite.key !== 'string' || typeof invite.signature !== 'string')
577
- return null;
578
- if (!(await verifyInvite(space.id, did, invite.key, invite.signature, provider)))
579
- return null;
580
- viaInvite = invite.key;
581
- }
582
- return {
583
- ...base,
584
- cutoff,
585
- kind: 'assign',
586
- did,
587
- role,
588
- assigned,
589
- ...(viaInvite !== undefined ? { viaInvite } : {}),
590
- };
591
- }
592
- case REMOVE_COLLECTION: {
593
- const { did } = body;
594
- if (typeof did !== 'string' || version.key !== (await removalKey(did)))
595
- return null;
596
- return { ...base, cutoff, kind: 'remove', did };
597
- }
598
- case STEPDOWN_COLLECTION: {
599
- const { did } = body;
600
- if (typeof did !== 'string' || version.key !== (await stepDownKey(did)))
601
- return null;
602
- return { ...base, cutoff, kind: 'stepdown', did };
603
- }
604
- case SUCCEED_COLLECTION: {
605
- // It names a space by id, never this one: the successor's constitution names this one, so can't be it.
606
- if (body.cutoff !== undefined || !isSpaceId(body.space) || body.space === space.id)
607
- return null;
608
- if (version.key !== (await succeedKey(body.space)))
609
- return null;
610
- return { ...base, kind: 'succeed', space: body.space };
611
- }
612
- case INVITE_COLLECTION: {
613
- const inviteDid = body.key;
614
- // An invite carries no cutoff: closing it takes nothing from anyone but who joins through it unseen.
615
- if (body.cutoff !== undefined || typeof inviteDid !== 'string' || typeof body.role !== 'string')
616
- return null;
617
- if (typeof body.open !== 'boolean' || version.key !== (await inviteRecordKey(inviteDid)))
618
- return null;
619
- return { ...base, kind: 'invite', inviteKey: inviteDid, role: body.role, open: body.open };
620
- }
621
- case KEY_COLLECTION: {
622
- if (version.key !== SPACE_KEY_RECORD || typeof body.keyId !== 'string' || body.keyId.length > 64)
623
- return null;
624
- if (typeof body.readKey !== 'string' || !body.readKey.startsWith('did:key:'))
625
- return null;
626
- return { ...base, kind: 'key', keyId: body.keyId, readKey: body.readKey };
627
- }
628
- case RELAYS_COLLECTION: {
629
- if (version.key !== SPACE_RELAYS_RECORD ||
630
- !isStringList(body.relays) ||
631
- body.relays.length > MAX_RELAYS)
632
- return null;
633
- return { ...base, kind: 'relays', relays: body.relays };
634
- }
635
- case FORK_COLLECTION: {
636
- // The proof stands on its own: every peer checks both signatures itself.
637
- const fork = await checkFork(body.a, body.b, space.id, provider);
638
- if (typeof fork === 'string' || version.key !== (await forkKey(fork.writer)))
639
- return null;
640
- return { ...base, kind: 'fork', writer: fork.writer, collection: fork.collection, from: fork.from };
641
- }
642
- case KEEPERS_COLLECTION: {
643
- const { keepers } = body;
644
- const copies = body.copies ?? null;
645
- if (version.key !== SPACE_KEEPERS_RECORD ||
646
- checkKeepers(keepers, copies) !== null ||
647
- !areKeepers(keepers) ||
648
- !(copies === null || typeof copies === 'number'))
649
- return null;
650
- return { ...base, kind: 'keepers', keepers, copies };
651
- }
652
- case REVOKE_COLLECTION: {
653
- // An account's revoke of one of its keys sits at a key naming both, so no one else's can take its place.
654
- if (typeof body.key !== 'string' || !body.key.startsWith('did:key:'))
655
- return null;
656
- if (version.key !== (await revokeKey(body.key, verdict.root)))
657
- return null;
658
- return { ...base, cutoff, kind: 'revoke', target: body.key };
659
- }
660
- }
661
- return null;
662
- }
663
- let accessCache = null;
664
- /** The read key readers must prove now — kept at hand, since a handshake asks for it without waiting */
665
- let currentReadKey = space.readKey ?? '';
666
- /**
667
- * Where the members meet: the relays the space names once it names some,
668
- * and until then the ones the invite that brought it here named. Handed to
669
- * the mesh for this space's room alone.
670
- */
671
- let relays = record.relays ?? [];
672
- let meshRoom = null;
673
- function useRelays(named) {
674
- if (named.length === 0 || (named.length === relays.length && named.every((url, i) => url === relays[i])))
675
- return;
676
- relays = [...named];
677
- if (meshRoom)
678
- deps.mesh?.useRelays(meshRoom, relays);
679
- void deps.onRelays?.(relays).catch(() => { });
680
- }
681
- const access = () => (accessCache ??= loadAccess());
682
- /**
683
- * Accounts that held a place in this private space and hold none now:
684
- * removed, or left. No live message goes to them, and while a new key is
685
- * due (`untilNewKey`) — they may hold the current one — nothing else does
686
- * either. Empty in a public space, which anyone may read.
687
- */
688
- async function formerMembers(options = {}) {
689
- if (space.visibility !== 'private')
690
- return new Set();
691
- const { history, events } = await access();
692
- // A key made since: it does the work, and someone invited back holds it.
693
- if (options.untilNewKey && !history.current.keyDue)
694
- return new Set();
695
- const allowed = readers(history.current);
696
- const gone = new Set();
697
- for (const event of events) {
698
- if ((event.kind !== 'assign' && event.kind !== 'remove') || allowed.has(event.did))
699
- continue;
700
- if (history.status(event.id)?.status === 'applied')
701
- gone.add(event.did);
702
- }
703
- return gone;
704
- }
705
- async function loadAccess() {
706
- const found = [];
707
- let unsettled = false;
708
- // By key, not by the current version's collection: whatever sits on top
709
- // may be anyone's, and every version of the history counts.
710
- for (const { prefix, collection } of Object.values(ACCESS_KINDS)) {
711
- for (const versions of (await storage.histories(prefix)).values()) {
712
- for (const held of versions) {
713
- if (held.collection !== collection)
714
- continue;
715
- const event = await toEvent(held);
716
- if (event)
717
- found.push(event);
718
- else
719
- unsettled ||= !events.has(eventKey(held));
720
- }
721
- }
722
- }
723
- return accessFrom(replayAccess(accessGenesis, found), found, unsettled);
724
- }
725
- function accessFrom(history, found, unsettled) {
726
- reportRole(history.current);
727
- currentReadKey = history.current.keys.at(-1)?.readKey ?? currentReadKey;
728
- useRelays(history.current.relays);
729
- return { history, events: found, unsettled };
730
- }
731
- /**
732
- * The history with versions just stored: each change added to the one
733
- * there was, the way a whole replay would place it, and the whole history
734
- * read and replayed again when one can't be (`AccessHistory.extend`).
735
- * Adding a member or changing a role costs as much as the members, not
736
- * the history twice over.
737
- */
738
- async function extendAccess(before, placed) {
739
- const previous = await before.catch(() => null);
740
- if (!previous || previous.unsettled)
741
- return loadAccess();
742
- let pending = [];
743
- for (const version of placed) {
744
- if (!Object.values(ACCESS_KINDS).some(({ prefix, collection }) => version.key.startsWith(prefix) && version.collection === collection))
745
- continue;
746
- const event = await toEvent(version);
747
- if (event)
748
- pending.push(event);
749
- else if (!events.has(eventKey(version)))
750
- return loadAccess();
751
- }
752
- if (pending.length === 0)
753
- return previous;
754
- let history = previous.history;
755
- const found = [...previous.events];
756
- // A batch from a peer may hold a change before the one it saw: whichever follows on goes first.
757
- while (pending.length > 0) {
758
- const left = [];
759
- for (const event of pending) {
760
- const next = history.extend(event);
761
- if (!next)
762
- left.push(event);
763
- else if (next !== history) {
764
- found.push(event);
765
- history = next;
766
- }
767
- }
768
- if (left.length === pending.length)
769
- return loadAccess();
770
- pending = left;
771
- }
772
- return accessFrom(history, found, false);
773
- }
68
+ const base = {
69
+ record,
70
+ space,
71
+ storage,
72
+ provider,
73
+ keyring,
74
+ session,
75
+ rootDid,
76
+ accountOnly: !!deps.accountOnly,
77
+ isClosed,
78
+ };
79
+ // ─── Judging ───────────────────────────────────────────────────────
80
+ const meeting = createMeeting(record, deps.mesh, deps.onRelays);
774
81
  let reportedRole;
775
- function reportRole(state) {
776
- const role = placeOf(state, deps.rootDid);
777
- if (role === reportedRole)
778
- return;
779
- reportedRole = role;
780
- deps.onRole?.(role);
781
- }
782
- /** The note a version was written under, when it was delegated */
783
- /**
784
- * The command a version invokes, and its arguments (03 §5.2): a delete, or
785
- * a write with its body. `opaque` when this node can't read the body, so
786
- * policies on it are left to those who can.
787
- */
788
- async function invocationOf(version, first, root) {
789
- const byCreator = version.seq === 0 || (await judge(first)).root === root;
790
- const collection = version.collection;
791
- if (version.deleted)
792
- return { cmd: RECORD_DELETE, args: { collection, byCreator }, opaque: false };
793
- const opened = await openBody(version);
794
- const opaque = isStub(version) || (opened.encrypted && opened.body === null);
795
- return {
796
- cmd: RECORD_WRITE,
797
- args: { collection, byCreator, ...(opaque ? {} : { body: opened.body }) },
798
- opaque,
799
- };
800
- }
801
- /**
802
- * What a version asks of its author: in `sys.*`, a place; elsewhere, a grant
803
- * for what it does. `strict`: a body this node can't read holds no policy on it.
804
- */
805
- async function needsOf(version, first, root, options = {}) {
806
- if (version.collection.startsWith('sys.'))
807
- return (state) => isMember(state, root);
808
- const { cmd, args, opaque } = await invocationOf(version, first, root);
809
- return (state) => may(state, root, cmd, args, { opaque: opaque && !options.strict });
810
- }
811
- /** Whether this node reads the space's bodies: a public space, or a private one whose key it holds */
812
- const readsBodies = () => space.visibility !== 'private' || keyring.size > 0;
813
- const definitions = new Map();
814
- /** The definition held in one version of `sys.collection` */
815
- function definitionIn(id) {
816
- let found = definitions.get(id);
817
- if (!found) {
818
- found = (async () => {
819
- const version = await storage.getVersion(id);
820
- if (!version)
821
- return 'missing';
822
- if (version.collection !== CATALOG_COLLECTION || version.deleted)
823
- return 'invalid';
824
- const opened = await openBody(version);
825
- if (opened.body === null)
826
- return 'unreadable';
827
- const body = opened.body;
828
- if (!isStoredCollection(body) || version.key !== `collection:${body.name}`)
829
- return 'invalid';
830
- return { definition: body };
831
- })();
832
- definitions.set(id, found);
833
- // Something missing may turn up; only settled answers are worth keeping.
834
- void found.then((answer) => answer === 'missing' && definitions.delete(id));
835
- }
836
- return found;
837
- }
838
- /**
839
- * The id of the definition in force for a collection in one state of the
840
- * history (02 §6.3): the replay's, or, while rival first definitions stand,
841
- * the lowest of them only when they all say the same, so no ground id picks
842
- * the rules. One this node can't read when it can't read them all; null
843
- * when none is in force.
844
- */
845
- async function inForce(state, collection) {
846
- const entry = state.definitions.get(collection);
847
- if (entry)
848
- return entry.event;
849
- const rivals = state.contested.get(collection);
850
- if (!rivals?.length)
851
- return null;
852
- const found = await Promise.all(rivals.map((id) => definitionIn(id)));
853
- const unreadable = rivals.find((_, i) => found[i] === 'unreadable');
854
- if (unreadable)
855
- return unreadable;
856
- const said = new Set(found.map((one) => (typeof one === 'string' ? one : canonicalize(one.definition))));
857
- return said.size === 1 && typeof found[0] !== 'string' ? rivals[0] : null;
858
- }
859
- /** The rules and topics in force for a collection in one state of the history — null when there are none to judge by */
860
- async function rulesAt(state, collection) {
861
- if (collection.startsWith('sys.'))
862
- return null;
863
- const id = await inForce(state, collection);
864
- if (!id)
865
- return null;
866
- const found = await definitionIn(id);
867
- return typeof found === 'string'
868
- ? null
869
- : {
870
- rules: found.definition.rules ?? {},
871
- topics: found.definition.topics ?? [],
872
- contract: found.definition.contract,
873
- };
874
- }
875
- // ─── Topic tags ────────────────────────────────────────────────────
876
- //
877
- // Keyed from the key a record's body was sealed with, in a private space;
878
- // from the space id in a public one (`records/topics.ts`).
879
- const topicKeys = new Map();
880
- /** The tag key for one of the space's keys, or the public one; null when this node doesn't hold that key */
881
- function tagKey(keyId) {
882
- const name = keyId ?? 'public';
883
- let found = topicKeys.get(name);
884
- if (!found) {
885
- const held = keyId === null ? null : keyring.get(keyId);
886
- if (keyId !== null && !held)
887
- return null;
888
- found = topicKey(held ? { spaceKey: held.raw } : { spaceId: space.id });
889
- topicKeys.set(name, found);
890
- }
891
- return found;
892
- }
893
- /**
894
- * Why a version's tags don't match its body under the topics in force, or
895
- * null when they do — or when this node can't read the body to tell.
896
- */
897
- async function tagProblem(version, topics) {
898
- if (topics.length === 0 && !version.tags?.length)
899
- return null;
900
- const opened = await openBody(version);
901
- if (opened.body === null)
902
- return null;
903
- const key = tagKey(opened.encrypted ? sealedKeyId(version.body) : null);
904
- if (!key)
905
- return null;
906
- const expected = await tagsFor(await key, version.collection, topics, opened.body, opened.links);
907
- return sameTags(version.tags, expected)
908
- ? null
909
- : { ok: false, reason: `Its topic tags don't match what it says` };
910
- }
911
- const standings = new Map();
912
- /** Checks verdicts, by version and the view it was judged in */
913
- const checkVerdicts = new Map();
914
- /** Records whose newest version waits on a version it cites: read again when anything arrives */
915
- const pendingKeys = new Set();
916
- /**
917
- * Whether a version stands: signed, in this space, consistent with its first
918
- * version, and — by the access history — written by someone allowed to.
919
- * The same verdict for a version from a peer, from a folder, or written
920
- * here, and for one read back later. `within`, for a version another cites:
921
- * judged as of what the citing version saw, so a change that came after it
922
- * can't undo a proof that held when it was made (02 §7.6).
923
- */
924
- async function standingOf(version, within) {
925
- const problem = await copyProblem(version);
926
- if (problem)
927
- return { ok: false, reason: problem };
928
- const cacheKey = within
929
- ? `${copyKey(version)}|${[...new Set(within)].sort().join(',')}`
930
- : copyKey(version);
931
- let found = standings.get(cacheKey);
932
- if (!found) {
933
- found = judgeStanding(version, within);
934
- standings.set(cacheKey, found);
935
- // Only a verdict that stands is kept: one waiting on something not here
936
- // yet changes when it arrives, and a failing verdict is never cached (02 §9.5).
937
- found.then((standing) => !standing.ok && standings.delete(cacheKey), () => standings.delete(cacheKey));
938
- }
939
- return found;
940
- }
941
- /**
942
- * @param within For a version another cites: what the citing version saw.
943
- * Only access changes among those can take it away.
944
- */
945
- async function judgeStanding(version, within) {
946
- // A version may only claim the space it actually sits in.
947
- if (version.space !== space.id)
948
- return { ok: false, reason: 'It belongs to a different space' };
949
- const verdict = await judge(version);
950
- if (!verdict.verified || !verdict.root)
951
- return { ok: false, reason: verdict.reason ?? 'Its signature does not check out' };
952
- const asAccount = deps.accountOnly || aboutItself(version.collection, version.body, verdict.root, version.author);
953
- if (asAccount && !actsForAccount(version.proof))
954
- return { ok: false, reason: "Its note doesn't let it act as the account itself" };
955
- const { history } = await access();
956
- if (ACCESS_COLLECTIONS.has(version.collection)) {
957
- const event = await toEvent(version);
958
- if (!event)
959
- return { ok: false, reason: 'It is not a well-formed change to who may do what' };
960
- const status = history.status(event.id);
961
- if (!status || status.status === 'waiting')
962
- return ACCESS_LATER;
963
- return status.status === 'applied' ? STANDS : { ok: false, reason: status.reason };
964
- }
965
- const first = version.seq === 0 ? version : version.genesis ? await storage.getVersion(version.genesis) : null;
966
- if (!first)
967
- return { ok: false, reason: 'Its first version has not arrived yet', later: true };
968
- if (!firstOf(version, first))
969
- return { ok: false, reason: "The first version it names is not this record's" };
970
- // Whose key it is depends on nothing that can change: refused, never withdrawn.
971
- const owned = await keyProblem(version, verdict.root);
972
- if (owned)
973
- return owned;
974
- const seen = version.seen ?? [];
975
- // Judged by the changes that stand; refused only by what its writer saw (03 §5.1).
976
- const state = history.at(seen, within);
977
- const wrote = history.seenAs(seen);
978
- if (!state || !wrote)
979
- return ACCESS_LATER;
980
- const form = await onePerKeyProblem(version, state);
981
- if (form)
982
- return form;
983
- // Rival definitions that differ give no rules, which must not mean anything goes (02 §6.3).
984
- if (state.contested.has(version.collection) && !(await inForce(state, version.collection)))
985
- return {
986
- ok: false,
987
- reason: `Rival definitions of ${version.collection} stand: nothing is written in it until a manager settles them`,
988
- };
989
- const root = verdict.root;
990
- const found = await rulesAt(state, version.collection);
991
- const rules = found?.rules;
992
- const needs = await needsOf(version, first, root);
993
- // The two refusals worth telling apart: not a member at all, and no grant for what it does.
994
- if (!isMember(wrote, root))
995
- return { ok: false, reason: 'Its author was not a member of this space, as of what it had seen' };
996
- if (!needs(wrote)) {
997
- return {
998
- ok: false,
999
- reason: `Its author holds no grant to ${version.deleted ? 'delete' : 'write'} this ${version.collection} record, as of what it had seen`,
1000
- };
1001
- }
1002
- // A stub's grant may hold only because its body isn't here to read. A node that reads the
1003
- // space waits for the body rather than take it on trust: it judges the whole version afresh.
1004
- if (isStub(version) && readsBodies() && !(await needsOf(version, first, root, { strict: true }))(wrote))
1005
- return {
1006
- ok: false,
1007
- reason: 'Its grant reads its body, which a stub does not carry',
1008
- later: true,
1009
- bodyNeeded: true,
1010
- };
1011
- // Written once: no later version, not even a delete.
1012
- if (rules?.final && version.seq > 0)
1013
- return {
1014
- ok: false,
1015
- reason: `A ${version.collection} record is final: it can't be edited or deleted`,
1016
- };
1017
- const judged = history.judge({
1018
- id: version.id,
1019
- root,
1020
- seen,
1021
- writer: version.author,
1022
- collection: version.collection,
1023
- ...(version.log ? { line: version.log.n } : {}),
1024
- }, needs, within);
1025
- // Withdrawn by a later change: still judged on everything else, since it
1026
- // is kept and others may cite it.
1027
- if (!judged.ok && !judged.withdrawn)
1028
- return judged;
1029
- const content = await judgeContent(version, first, root, found);
1030
- return judged.ok || !content.ok ? content : judged;
1031
- }
1032
- /** The rest of a version's standing: what its definition's topics and rules ask of what it says */
1033
- async function judgeContent(version, first, root, found, options = {}) {
1034
- const rules = found?.rules;
1035
- if (found && !version.deleted && options.tags !== false) {
1036
- const problem = await tagProblem(version, found.topics);
1037
- if (problem)
1038
- return problem;
1039
- }
1040
- if (!rules || version.deleted)
1041
- return STANDS;
1042
- // Their checks read the first version's body, so every peer must hold it,
1043
- // however late it joins: a first version kept whole, not as a stub.
1044
- if (version.seq === 0 && (rules.onePer || rules.fixed) && !version.retain)
1045
- return {
1046
- ok: false,
1047
- reason: `A new ${version.collection} record must be kept whole: its rules are checked against it`,
1048
- };
1049
- if (version.seq === 0 && rules.onePer) {
1050
- const opened = await openBody(version);
1051
- const keying = onePerKeying();
1052
- // Only a reader can compute a private space's onePer keys; the rest take it on the other checks.
1053
- if ((opened.body === null && opened.encrypted) || !keying)
1054
- return STANDS;
1055
- const expected = await onePerKey(await keying, version.collection, rules.onePer, {
1056
- root,
1057
- links: opened.links,
1058
- body: opened.body,
1059
- });
1060
- if (expected !== version.key) {
1061
- return {
1062
- ok: false,
1063
- reason: `${version.collection} allows one per ${rules.onePer.join(' + ')} — its key must be derived from them`,
1064
- };
1065
- }
1066
- }
1067
- // Only against a first version kept whole, so a peer that joined after it
1068
- // was superseded judges the same way as one that saw it.
1069
- if (version.seq > 0 && rules.fixed?.length && first.retain) {
1070
- const [now, then] = await Promise.all([openBody(version), openBody(first)]);
1071
- if (now.body !== null && then.body !== null) {
1072
- const field = changedFixedField(rules.fixed, then.body, now.body);
1073
- if (field)
1074
- return {
1075
- ok: false,
1076
- reason: `"${field}" is fixed once a ${version.collection} record is created`,
1077
- };
1078
- }
1079
- }
1080
- return STANDS;
1081
- }
1082
- // ─── Checks ────────────────────────────────────────────────────────
1083
- //
1084
- // Conditions a collection's versions must meet (`packages/core/src/records/contracts.ts`). They
1085
- // read only what never changes: this version, the one before when it was
1086
- // kept whole, and versions cited by id, kept whole and standing.
1087
- /** A version as a check reads it: its author's account, and its content when it was kept whole */
1088
- async function checkedVersion(version, whole) {
1089
- let body = null;
1090
- // Public links are on the outside, the same for every peer; sealed ones only with the body.
1091
- let links = version.links ?? [];
1092
- if (whole && !version.deleted) {
1093
- const opened = await openBody(version);
1094
- if (opened.body === null && opened.encrypted)
1095
- return { unreadable: true };
1096
- body = opened.body;
1097
- links = opened.links;
1098
- }
1099
- return Object.freeze({
1100
- id: version.id,
1101
- key: version.key,
1102
- collection: version.collection,
1103
- seq: version.seq,
1104
- author: (await judge(version)).root ?? version.author,
1105
- createdAt: version.createdAt,
1106
- deleted: !!version.deleted,
1107
- body,
1108
- links,
1109
- });
1110
- }
1111
- /** A version a check cites: here, kept whole, and standing — or why it can't count */
1112
- async function cited(id, within) {
1113
- const version = await storage.getVersion(id);
1114
- if (!version)
1115
- return { later: true };
1116
- // Whether it was kept is on the version, signed: the same answer on every peer.
1117
- if (!version.retain && !version.deleted)
1118
- return { refused: `it cites ${id}, which was not kept whole` };
1119
- if (!(await consistent(version)))
1120
- return { refused: `it cites ${id}, which is not its record's` };
1121
- // As of what the citing version saw: a removal after it doesn't undo it.
1122
- const stands = await standingOf(version, within);
1123
- if (!stands.ok)
1124
- return stands.later ? { later: true } : { refused: `it cites ${id}, which does not stand` };
1125
- // Its own checks too, as of what the citing version saw.
1126
- const passes = await checksOf(version, within);
1127
- if ('pending' in passes)
1128
- return { later: true };
1129
- if (passes.passes === false)
1130
- return { refused: `it cites ${id}, which fails its checks` };
1131
- if (passes === UNJUDGED)
1132
- return { unreadable: true };
1133
- if ('unjudged' in passes)
1134
- return { unjudged: true };
1135
- return checkedVersion(version, true);
1136
- }
1137
- /**
1138
- * Whether a version passes its collection's checks: the library reads them,
1139
- * peers don’t enforce them (spec/09-contracts.md). `passes: null`
1140
- * when there are none, or this node can't read what they need; `pending`
1141
- * while a version it cites hasn't arrived. Judged as of what it saw, or, for
1142
- * a version another cites, as of what that one saw (`within`).
1143
- */
1144
- async function checksOf(version, within) {
1145
- if (ACCESS_COLLECTIONS.has(version.collection) || version.collection.startsWith('sys.'))
1146
- return NO_CHECKS;
1147
- const cacheKey = `${copyKey(version)}|${within ? [...new Set(within)].sort().join(',') : ''}`;
1148
- const cached = checkVerdicts.get(cacheKey);
1149
- if (cached)
1150
- return cached;
1151
- const verdict = (async () => {
1152
- const first = version.seq === 0 ? version : version.genesis ? await storage.getVersion(version.genesis) : null;
1153
- const root = (await judge(version)).root;
1154
- if (!first || !root)
1155
- return NO_CHECKS;
1156
- const state = (await access()).history.at(version.seen ?? [], within);
1157
- if (!state)
1158
- return { pending: true };
1159
- const defined = await rulesAt(state, version.collection);
1160
- const contract = defined?.contract;
1161
- if (contract === undefined)
1162
- return NO_CHECKS;
1163
- // A contract with a key this library doesn't know: not judged, as a line's below.
1164
- const shape = checkContractShape(contract);
1165
- if (shape === 'unknown')
1166
- return { passes: null, unjudged: `${version.collection} has a contract this library doesn't know` };
1167
- if (shape !== null || !isRecord(contract))
1168
- return { passes: false, reason: `The contract of ${version.collection} can't be read` };
1169
- const listed = contract.check;
1170
- const checks = Array.isArray(listed) && listed.length === 0 ? undefined : listed;
1171
- const line = contract.line;
1172
- if (checks === undefined && line === undefined)
1173
- return NO_CHECKS;
1174
- // Peers keep any list; one its author's node would have refused can't be read, so nothing passes it.
1175
- if (checks !== undefined &&
1176
- (checkContracts(checks, 'contract.check') !== null || !Array.isArray(checks)))
1177
- return { passes: false, reason: `The contract of ${version.collection} can't be read` };
1178
- // A line declaration with a key this library doesn't know: not judged, as a space with an unknown resolver.
1179
- const lineProblem = line === undefined ? null : checkLine(line);
1180
- if (lineProblem === 'unknown')
1181
- return { passes: null, unjudged: `${version.collection} declares a line this library doesn't know` };
1182
- if (lineProblem !== null)
1183
- return { passes: false, reason: `The line of ${version.collection} can't be read` };
1184
- if (line !== undefined)
1185
- lineCollections.add(version.collection);
1186
- // What this node can't open, it can't judge: unjudged, so not counted, until it can (spec 09 §2).
1187
- if (!version.deleted) {
1188
- const opened = await openBody(version);
1189
- if (opened.body === null && opened.encrypted)
1190
- return UNJUDGED;
1191
- }
1192
- // It continues the version before: one that follows a version failing its checks fails too,
1193
- // or a forged step would be laundered by the next.
1194
- let previous = version.seq > 0 && version.prev ? await storage.getVersion(version.prev) : null;
1195
- if (version.seq > 0 && version.prev && !previous)
1196
- return { pending: true };
1197
- // In a line, a delete is a step that ends it for good: nothing after it counts (spec 09 §7.5).
1198
- if (line !== undefined && previous?.deleted)
1199
- return { passes: false, reason: 'It follows a delete, which ends its line' };
1200
- // A delete in between hides nothing: the chain is judged by the step before it.
1201
- while (previous?.deleted && previous.seq > 0 && previous.prev) {
1202
- const before = await storage.getVersion(previous.prev);
1203
- if (!before)
1204
- return { pending: true };
1205
- previous = before;
1206
- }
1207
- // A step under checks is kept whole by an honest writer (it is signed, so every reader sees the same):
1208
- // one that wasn't can't be judged, and what follows it doesn't count.
1209
- if (previous && !previous.retain && !previous.deleted) {
1210
- const then = (await access()).history.at(previous.seen ?? []);
1211
- const before = then ? await rulesAt(then, previous.collection) : null;
1212
- if (hasContract(before?.contract))
1213
- return { passes: false, reason: 'It follows a version under a contract that was not kept whole' };
1214
- }
1215
- if (previous && !isStub(previous)) {
1216
- if (previous.retain && !previous.deleted) {
1217
- const before = await openBody(previous);
1218
- if (before.body === null && before.encrypted)
1219
- return UNJUDGED;
1220
- }
1221
- if (!(await standingOf(previous)).ok)
1222
- return { passes: false, reason: 'It follows a version that does not stand' };
1223
- const before = await checksOf(previous);
1224
- if ('pending' in before)
1225
- return { pending: true };
1226
- // A step this node couldn't judge leaves what follows unjudged too, so neither is kept as a pass.
1227
- if (before === UNJUDGED)
1228
- return UNJUDGED;
1229
- if ('unjudged' in before)
1230
- return before;
1231
- if (before.passes === false)
1232
- return { passes: false, reason: `It follows a version that fails its checks: ${before.reason}` };
1233
- }
1234
- // A delete has no content to check, but it continues the chain like any step: one that follows a
1235
- // failing step fails too, so it can't hide the record from readers or make its key unwritable.
1236
- if (line !== undefined) {
1237
- const broken = await lineBreak(version, root, isLine(line) ? (line.once ?? []) : []);
1238
- if (broken === UNJUDGED)
1239
- return UNJUDGED;
1240
- if (typeof broken === 'string')
1241
- return { passes: false, reason: broken };
1242
- }
1243
- if (version.deleted || checks === undefined || !Array.isArray(checks))
1244
- return NO_CHECKS;
1245
- const outcome = await checkStanding(version, first, root, state, checks);
1246
- if (outcome === 'unreadable')
1247
- return UNJUDGED;
1248
- if (outcome === 'unjudged')
1249
- return { passes: null, unjudged: 'It cites a version in a collection this library doesn’t judge' };
1250
- if (outcome.ok)
1251
- return { passes: true };
1252
- return outcome.later ? { pending: true } : { passes: false, reason: outcome.reason };
1253
- })();
1254
- checkVerdicts.set(cacheKey, verdict);
1255
- // Only what can't change is kept: a pending verdict changes when what it cites arrives,
1256
- // and one this node couldn't judge may change once it can open what it needs.
1257
- void verdict.then((found) => ('pending' in found || found === UNJUDGED) && checkVerdicts.delete(cacheKey));
1258
- return verdict;
1259
- }
1260
- /** Whether a version counts for this node's reader: it stands, and passes its contract */
1261
- async function counts(version) {
1262
- if (!(await standingOf(version)).ok)
1263
- return false;
1264
- const passes = await checksOf(version);
1265
- // Bounded: past it, a waiting record is read again only when the index is rebuilt.
1266
- if ('pending' in passes && pendingKeys.size < MAX_PENDING_REREAD)
1267
- pendingKeys.add(version.key);
1268
- return !('pending' in passes) && !('unjudged' in passes) && passes.passes !== false;
1269
- }
1270
- /** Collections this node has judged as lines: a version arriving in one can undo a verdict (a double spend) */
1271
- const lineCollections = new Set();
1272
- /**
1273
- * Every version held in a line collection, by key and the version it
1274
- * names before it: deletes and stubs included, whatever `retain` says, so
1275
- * no twin hides from the double-spend check. Dropped when one arrives.
1276
- */
1277
- const lineIndexes = new Map();
1278
- const twinKey = (version) => `${version.key}\n${version.prev ?? ''}`;
1279
- function lineIndex(collection) {
1280
- let index = lineIndexes.get(collection);
1281
- if (!index) {
1282
- index = storage.keptVersions(collection).then((held) => {
1283
- const byPlace = new Map();
1284
- for (const version of held) {
1285
- const at = byPlace.get(twinKey(version));
1286
- if (at)
1287
- at.push(version);
1288
- else
1289
- byPlace.set(twinKey(version), [version]);
1290
- }
1291
- return byPlace;
1292
- });
1293
- lineIndexes.set(collection, index);
1294
- }
1295
- return index;
1296
- }
1297
- /**
1298
- * Why a version breaks its line's rule (spec 09 §6), or null. Its key is its
1299
- * author's line key; no other version at that key names the same version
1300
- * before it (a double spend: neither counts, nor anything after either);
1301
- * and no citation in a `once` field appears twice along the counted chain,
1302
- * this version and every one before it.
1303
- */
1304
- async function lineBreak(version, root, once) {
1305
- if (version.key !== (await lineKey(root, version.collection)))
1306
- return 'It is not at its author’s line key';
1307
- for (const other of (await lineIndex(version.collection)).get(twinKey(version)) ?? []) {
1308
- if (other.id === version.id || other.seq !== version.seq)
1309
- continue;
1310
- // At an owned key only its owner's versions stand; one that doesn't is no twin.
1311
- if ((await judge(other)).root !== root)
1312
- continue;
1313
- return 'A double spend: another version of this line follows the same one';
1314
- }
1315
- if (once.length === 0 || version.deleted)
1316
- return null;
1317
- // Back to the nearest step whose claims are known, then forward: judging a line is linear.
1318
- const fields = JSON.stringify(once);
1319
- const path = [];
1320
- let known;
1321
- for (let step = version; step;) {
1322
- known = onceClaimed.get(`${step.id}|${fields}`);
1323
- if (known)
1324
- break;
1325
- path.push(step);
1326
- step = step.seq > 0 && step.prev ? await storage.getVersion(step.prev) : null;
1327
- }
1328
- const claimed = new Set(known);
1329
- // A stub's claims can't be read yet, so a walk through one isn't kept: the whole version may arrive.
1330
- let throughStub = false;
1331
- for (const step of path.reverse()) {
1332
- if (step.deleted)
1333
- continue;
1334
- if (isStub(step))
1335
- throughStub = true;
1336
- const opened = await openBody(step);
1337
- if (opened.body === null && opened.encrypted)
1338
- return UNJUDGED;
1339
- for (const citation of onceCitations(opened.body, once)) {
1340
- if (claimed.has(citation))
1341
- return 'It claims something its line has already claimed';
1342
- claimed.add(citation);
1343
- }
1344
- }
1345
- // An id names its content, and so its whole chain: what it claimed never changes.
1346
- if (throughStub)
1347
- return null;
1348
- onceClaimed.set(`${version.id}|${fields}`, claimed);
1349
- if (onceClaimed.size > MAX_ONCE_CLAIMED)
1350
- onceClaimed.delete(onceClaimed.keys().next().value);
1351
- return null;
1352
- }
1353
- /** What a line's `once` fields claimed along the chain ending at a version, by its id and the fields */
1354
- const onceClaimed = new Map();
1355
- async function checkStanding(version, first, root, state, checks) {
1356
- const opened = await openBody(version);
1357
- // Without the key, a peer can't tell: unjudged, as for a cited version it can't open.
1358
- if (opened.body === null && opened.encrypted)
1359
- return 'unreadable';
1360
- const previous = version.seq > 0 && version.prev ? await storage.getVersion(version.prev) : null;
1361
- const prev = previous ? await checkedVersion(previous, !!previous.retain) : null;
1362
- if (prev && 'unreadable' in prev)
1363
- return 'unreadable';
1364
- const outcome = await runContracts(checks, {
1365
- values: {
1366
- body: opened.body,
1367
- links: opened.links,
1368
- key: version.key,
1369
- seq: version.seq,
1370
- collection: version.collection,
1371
- author: root,
1372
- creator: (await judge(first)).root ?? first.author,
1373
- createdAt: version.createdAt,
1374
- prev,
1375
- },
1376
- cite: (id) => cited(id, version.seen ?? []),
1377
- member: (did) => isMember(state, did),
1378
- });
1379
- if ('later' in outcome)
1380
- return { ok: false, reason: 'Versions it cites have not arrived yet', later: true };
1381
- if ('unjudged' in outcome)
1382
- return 'unjudged';
1383
- if ('unreadable' in outcome)
1384
- return 'unreadable';
1385
- if (outcome.passed)
1386
- return STANDS;
1387
- return { ok: false, reason: outcome.reason };
1388
- }
1389
- /**
1390
- * Whether a change to the access history may be stored. Not whether it
1391
- * counts — that can change as other changes arrive, so every well-formed one
1392
- * is kept and the replay decides. Only what never changes is asked: that
1393
- * what it saw is here, and that its author is someone the history has heard
1394
- * of, or holds an invite it has.
1395
- */
1396
- async function admissible(version) {
1397
- if (version.space !== space.id)
1398
- return { ok: false, reason: 'It belongs to a different space' };
1399
- if (!version.retain)
1400
- return { ok: false, reason: 'A change to who may do what must be kept' };
1401
- const event = await toEvent(version);
1402
- if (!event)
1403
- return {
1404
- ok: false,
1405
- reason: (await judge(version)).reason ?? 'It is not a well-formed change to who may do what',
1406
- };
1407
- const { history } = await access();
1408
- if (!history.at(event.seen))
1409
- return ACCESS_LATER;
1410
- const known = history.named(event.root) ||
1411
- (event.kind === 'assign' && event.viaInvite !== undefined && history.knownInvite(event.viaInvite));
1412
- return known ? STANDS : { ok: false, reason: 'Its author has never been a member of this space' };
1413
- }
1414
- /**
1415
- * Whether a later version follows the version its `prev` names: the same
1416
- * record, one more `seq`, the same first version. Asked on arrival, once
1417
- * that version is held, so a writer can't skip ahead to a `seq` nobody can
1418
- * outrank.
1419
- */
1420
- async function chainStanding(version) {
1421
- if (version.seq === 0 || typeof version.prev !== 'string')
1422
- return STANDS;
1423
- const previous = await storage.getVersion(version.prev);
1424
- if (!previous)
1425
- return { ok: false, reason: 'The version it follows has not arrived yet', later: true };
1426
- const problem = chainProblem(version, previous);
1427
- return problem ? { ok: false, reason: problem } : STANDS;
82
+ const versions = createVersions(base);
83
+ const history = createHistory({
84
+ ...base,
85
+ versions,
86
+ onRead(state) {
87
+ meeting.heard(state);
88
+ const role = placeOf(state, rootDid);
89
+ if (role === reportedRole)
90
+ return;
91
+ reportedRole = role;
92
+ deps.onRole?.(role);
93
+ },
94
+ });
95
+ const rules = createRules({ ...base, versions });
96
+ const standing = createStanding({ ...base, versions, history, rules });
97
+ const checks = createChecks({ ...base, versions, history, rules, standing });
98
+ const catalog = createCatalog({ schemas, history, rules, currentOf: (key) => index.currentOf(key) });
99
+ const index = createIndex({ ...base, versions, standing, checks, catalog, use: holding.use });
100
+ const profiles = createProfiles({ ...base, versions, standing });
101
+ // ─── Writing ───────────────────────────────────────────────────────
102
+ const upsert = (collection, recordKey, body) => writing.upsert(collection, recordKey, body);
103
+ const cannotWrite = () => writing.cannotWrite();
104
+ const keys = createKeys({
105
+ ...base,
106
+ memberPair,
107
+ network: deps.network,
108
+ versions,
109
+ history,
110
+ rules,
111
+ profiles,
112
+ upsert,
113
+ cannotWrite,
114
+ recordsChanged: () => recordsChanged(),
115
+ onKeys: deps.onKeys,
116
+ });
117
+ const writing = createWriting({
118
+ ...base,
119
+ signer,
120
+ writers: deps.writers,
121
+ versions,
122
+ history,
123
+ rules,
124
+ standing,
125
+ checks,
126
+ catalog,
127
+ index,
128
+ keys,
129
+ stored,
130
+ });
131
+ const lines = createLines({
132
+ ...base,
133
+ adapter,
134
+ versions,
135
+ history,
136
+ catalog,
137
+ everyCurrent: () => index.everyCurrent(),
138
+ noteGap: holding.noteGap,
139
+ upsert,
140
+ cannotWrite,
141
+ });
142
+ const warrants = createWarrants({ ...base, versions, history, rules, standing, upsert, cannotWrite });
143
+ /** A version this node signed is in the store: its key's line, the other tabs and the peers hear of it */
144
+ async function stored(version) {
145
+ await lines.placeInLog(version);
146
+ await holding.markPending(version);
147
+ mirrors.tellTabs();
148
+ peers.sync.onLocalChange(version);
149
+ recordsChanged([version]);
1428
150
  }
1429
151
  /** Whether a version from outside — a peer, a folder — may be stored */
1430
152
  async function admit(version) {
1431
153
  const verdict = await admitOnce(version);
1432
154
  // Refused for good, or a change to who may do what: perhaps proof of a broken rule (docs/warrants.md).
1433
155
  if ((!verdict.ok && !verdict.later && !verdict.withdrawn) || ACCESS_COLLECTIONS.has(version.collection))
1434
- void warrantIfDue(version).catch(() => { });
156
+ void warrants.warrantIfDue(version).catch(() => { });
1435
157
  return verdict;
1436
158
  }
1437
159
  async function admitOnce(version) {
1438
160
  // Before any cached verdict: a copy with another envelope or body shares the id and signature.
1439
- const problem = await copyProblem(version);
161
+ const problem = await versions.copyProblem(version);
1440
162
  if (problem)
1441
163
  return { ok: false, reason: problem };
1442
164
  // Whatever its key signed takes a place in that key's log, allowed or not: a second at one place is a fork.
1443
- if ((await judge(version)).verified)
1444
- await placeInLog(version);
1445
- if (version.retain && isStub(version))
1446
- return { ok: false, reason: 'A version its writer retained travels whole' };
1447
- const chain = await chainStanding(version);
1448
- if (!chain.ok)
1449
- return chain;
1450
- if (ACCESS_COLLECTIONS.has(version.collection))
1451
- return admissible(version);
1452
- const standing = await standingOf(version);
1453
- // Kept as its record's history; it counts only once whole, and its body is judged then.
1454
- return !standing.ok && standing.bodyNeeded ? STANDS : standing;
1455
- }
1456
- /**
1457
- * The version of a record that counts: the current one, unless it no longer
1458
- * stands — then the newest one before it that does, if the store kept one.
1459
- */
1460
- async function currentOf(recordKey) {
1461
- const current = await storage.getCurrent(recordKey);
1462
- if (!current || !(await consistent(current)))
1463
- return null;
1464
- // A stub on top: the body of the version after it is on its way.
1465
- if (!isStub(current) && (await counts(current)))
1466
- return current;
1467
- for (const version of await storage.history(recordKey)) {
1468
- if (version.id === current.id || isStub(version) || !(await consistent(version)))
1469
- continue;
1470
- if (await counts(version))
1471
- return version;
1472
- }
1473
- return null;
1474
- }
1475
- let countedIndex = null;
1476
- const staleKeys = new Set();
1477
- /** One read of the index at a time, so a key is never brought up to date twice at once */
1478
- let indexing = Promise.resolve();
1479
- const countedEntry = async (version) => ({
1480
- version,
1481
- createdAt: await createdAtOf(version),
1482
- });
1483
- async function buildIndex() {
1484
- staleKeys.clear();
1485
- const index = new Map();
1486
- for (const version of await storage.listCurrent()) {
1487
- const counted = !isStub(version) && (await counts(version)) && (await consistent(version))
1488
- ? version
1489
- : await currentOf(version.key);
1490
- if (counted)
1491
- index.set(counted.key, await countedEntry(counted));
1492
- }
1493
- return index;
1494
- }
1495
- function counted() {
1496
- const run = indexing.then(async () => {
1497
- const index = await (countedIndex ??= buildIndex().catch((error) => {
1498
- countedIndex = null;
1499
- throw error;
1500
- }));
1501
- for (const key of [...staleKeys]) {
1502
- staleKeys.delete(key);
1503
- const version = await currentOf(key);
1504
- if (version)
1505
- index.set(key, await countedEntry(version));
1506
- else
1507
- index.delete(key);
1508
- }
1509
- return index;
1510
- });
1511
- indexing = run.catch(() => { });
1512
- return run;
1513
- }
1514
- /** Every record that counts, current version each — deletes included */
1515
- async function everyCurrent(collection) {
1516
- const shown = [];
1517
- for (const entry of (await counted()).values())
1518
- if (!collection || entry.version.collection === collection)
1519
- shown.push(entry.version);
1520
- return shown;
1521
- }
1522
- async function view(version) {
1523
- const [{ body, links, encrypted }, verdict, genesis, stands] = await Promise.all([
1524
- openBody(version),
1525
- judge(version),
1526
- genesisOf(version),
1527
- standingOf(version),
1528
- ]);
1529
- const creator = genesis ? await judge(genesis) : null;
1530
- // One record is handed to every reader, so nobody may change it under the others.
1531
- deepFreeze(body);
1532
- deepFreeze(links);
1533
- const issues = body === null || version.deleted ? null : await contentIssues(version.collection, body, links);
1534
- const failing = verdict.verified && stands.ok ? await checksOf(version) : NO_CHECKS;
1535
- const reason = !verdict.verified
1536
- ? verdict.reason
1537
- : !stands.ok
1538
- ? stands.reason
1539
- : 'passes' in failing && failing.passes === false
1540
- ? `It fails its checks: ${failing.reason}`
1541
- : undefined;
1542
- return Object.freeze({
1543
- key: version.key,
1544
- version: version.id,
1545
- seq: version.seq,
1546
- space: space.id,
1547
- collection: version.collection,
1548
- author: version.author,
1549
- root: verdict.root,
1550
- createdBy: creator?.verified ? creator.root : null,
1551
- createdAt: genesis?.createdAt ?? version.createdAt,
1552
- updatedAt: version.createdAt,
1553
- // The caller names the body's type; nothing here checks it against one.
1554
- // eslint-disable-next-line @typescript-eslint/consistent-type-assertions -- the caller's type for the body
1555
- body: body,
1556
- links,
1557
- encrypted,
1558
- verified: verdict.verified && stands.ok,
1559
- ...(!grantsBeyondRecords(version.proof, space.id, DEFINE_COMMAND)
1560
- ? { recordsOnly: true }
1561
- : {}),
1562
- ...(reason ? { reason } : {}),
1563
- ...(version.deleted ? { deleted: true } : {}),
1564
- conforms: issues === null ? null : issues.length === 0,
1565
- ...(issues?.length ? { issues } : {}),
1566
- });
1567
- }
1568
- let catalogCache = null;
1569
- const catalog = () => (catalogCache ??= loadCatalog());
1570
- async function loadCatalog() {
1571
- const result = new Map();
1572
- const { history } = await access();
1573
- const { definitions, contested } = history.current;
1574
- for (const name of new Set([...definitions.keys(), ...contested.keys()])) {
1575
- const id = await inForce(history.current, name);
1576
- const found = id ? await definitionIn(id) : 'missing';
1577
- if (!id || typeof found === 'string')
1578
- continue;
1579
- if (found.definition.name !== name)
1580
- continue;
1581
- result.set(name, {
1582
- definition: found.definition,
1583
- definedBy: definitions.get(name)?.definedBy ?? null,
1584
- version: id,
1585
- });
1586
- }
1587
- return result;
1588
- }
1589
- /** A collection's definition: what the space says. The protocol knows no kinds of record of its own. */
1590
- async function definitionOf(collection) {
1591
- return (await catalog()).get(collection)?.definition ?? null;
1592
- }
1593
- /** Issues with a body against its collection's schema; null when there is no schema to check against. */
1594
- async function shapeIssues(collection, body) {
1595
- // The protocol's own bookkeeping — definitions, profiles, roles — has no user-facing schema.
1596
- if (collection.startsWith('sys.'))
1597
- return null;
1598
- const described = await definitionOf(collection);
1599
- if (described)
1600
- return validateJsonSchema(described.schema, body);
1601
- if (schemas.getCollection(collection)) {
1602
- const checked = await schemas.validate(collection, body);
1603
- return (checked.issues ?? []).map((issue) => ({ path: '/', message: issue.message }));
1604
- }
1605
- return null;
1606
- }
1607
- /**
1608
- * Issues with a record's links against its collection's declaration. Only
1609
- * what can be judged from what is held: a link to a record not here yet is
1610
- * fine — you routinely hold a reaction before its post.
1611
- */
1612
- async function linkIssues(collection, links) {
1613
- const malformed = checkLinks(links);
1614
- if (malformed)
1615
- return [{ path: '/links', message: malformed }];
1616
- if (links.length === 0)
1617
- return [];
1618
- const declared = (await definitionOf(collection))?.links;
1619
- // An undescribed collection says nothing about its links, so nothing is wrong.
1620
- if (!declared)
1621
- return (await definitionOf(collection))
1622
- ? [{ path: '/links', message: `${collection} declares no links` }]
1623
- : [];
1624
- const issues = [];
1625
- const perRole = new Map();
1626
- for (const [index, link] of links.entries()) {
1627
- const declaration = declared[link.rel];
1628
- if (!declaration) {
1629
- issues.push({
1630
- path: `/links/${index}`,
1631
- message: `${collection} has no "${link.rel}" link (it has: ${Object.keys(declared).join(', ')})`,
1632
- });
1633
- continue;
1634
- }
1635
- perRole.set(link.rel, (perRole.get(link.rel) ?? 0) + 1);
1636
- if (declaration.to === '*')
1637
- continue;
1638
- const target = await currentOf(link.to);
1639
- if (target && !target.deleted && !declaration.to.includes(target.collection)) {
1640
- issues.push({
1641
- path: `/links/${index}`,
1642
- message: `"${link.rel}" must point at ${declaration.to.join(' or ')}, not ${target.collection}`,
1643
- });
1644
- }
1645
- }
1646
- for (const [rel, count] of perRole) {
1647
- if (declared[rel]?.cardinality === 'one' && count > 1)
1648
- issues.push({ path: '/links', message: `At most one "${rel}" link` });
1649
- }
1650
- return issues;
1651
- }
1652
- /** Shape and link issues together; null when neither has anything to check against. */
1653
- async function contentIssues(collection, body, links) {
1654
- const shape = await shapeIssues(collection, body);
1655
- const linked = await linkIssues(collection, links);
1656
- if (shape === null && linked.length === 0 && !(await definitionOf(collection)))
1657
- return null;
1658
- return [...(shape ?? []), ...linked];
1659
- }
1660
- function describe(name, entry, records) {
1661
- const definition = entry?.definition;
1662
- const usable = usableComputed(definition?.computed, definition?.schema);
1663
- return Object.freeze({
1664
- name,
1665
- ...(definition?.title !== undefined ? { title: definition.title } : {}),
1666
- ...(definition?.description !== undefined ? { description: definition.description } : {}),
1667
- schema: definition?.schema ?? null,
1668
- version: definition?.version ?? null,
1669
- history: definition?.history ?? 'latest',
1670
- links: definition?.links ?? {},
1671
- definedBy: entry?.definedBy ?? null,
1672
- rules: definition?.rules ?? {},
1673
- ...(definition?.contract !== undefined ? { contract: definition.contract } : {}),
1674
- // Only what every reader can use: a definition written by hand arrives unchecked.
1675
- ...(usable !== undefined ? { computed: usable } : {}),
1676
- topics: definition?.topics ?? [],
1677
- records,
1678
- });
1679
- }
1680
- // ─── What points where ─────────────────────────────────────────────
1681
- //
1682
- // Derived from the records held, rebuilt when they change, never synced: any
1683
- // node holding the records can build it, and derived data travelling between
1684
- // peers would only be one more thing to disagree about.
1685
- let linkIndexCache = null;
1686
- const linkIndex = () => (linkIndexCache ??= buildLinkIndex());
1687
- async function buildLinkIndex() {
1688
- const index = new Map();
1689
- for (const version of await everyCurrent()) {
1690
- if (version.deleted)
1691
- continue;
1692
- const { links } = await openBody(version);
1693
- for (const link of links) {
1694
- const list = index.get(link.to) ?? [];
1695
- list.push({ rel: link.rel, from: version.key });
1696
- index.set(link.to, list);
1697
- }
1698
- }
1699
- return index;
1700
- }
1701
- // ─── Profiles ──────────────────────────────────────────────────────
1702
- //
1703
- // Each person says who they are in a space with one record, keyed by their
1704
- // identity (`profileKey`), whose versions are always retained. The fold
1705
- // takes the newest version signed by the identity the key names, so nobody
1706
- // can rename anyone else: a version written by someone else under your key
1707
- // is simply never the answer, and it cannot push yours out, because yours
1708
- // are kept.
1709
- let profilesCache = null;
1710
- const profileMap = () => (profilesCache ??= loadProfiles());
1711
- async function loadProfiles() {
1712
- const result = new Map();
1713
- // By key: the current version may be anyone's.
1714
- for (const [key, versions] of await storage.histories('profile:')) {
1715
- let found = null;
1716
- for (const version of versions) {
1717
- if (version.collection !== PROFILE_COLLECTION)
1718
- continue;
1719
- const verdict = await judge(version);
1720
- if (!verdict.verified || !verdict.root || (await profileKey(verdict.root)) !== key)
1721
- continue;
1722
- if (!(await standingOf(version)).ok)
1723
- continue;
1724
- if (version.deleted)
1725
- break; // they took it down
1726
- const opened = (await openBody(version)).body;
1727
- const body = isRecord(opened) ? opened : null;
1728
- if (!found) {
1729
- const name = body?.name;
1730
- if (typeof name !== 'string' || !name.trim())
1731
- break;
1732
- found = { did: verdict.root, name: name.trim().slice(0, 64), updatedAt: version.createdAt };
1733
- }
1734
- // The picture, from the newest version: one without it shows none (the older stay kept, as retained).
1735
- if (!found.avatar && found.updatedAt === version.createdAt && isAvatarRef(body?.avatar))
1736
- found = { ...found, avatar: body.avatar };
1737
- // The contact key from the newest version that has one: it never changes, and an app
1738
- // without it that wrote a newer version first must not hide it.
1739
- if (isContactPublicKey(body?.contactKey)) {
1740
- found = { ...found, contactKey: body.contactKey };
1741
- break;
1742
- }
1743
- }
1744
- if (found)
1745
- result.set(found.did, found);
1746
- }
1747
- return result;
1748
- }
1749
- /**
1750
- * Each member's member key, from their own record of it — kept in the
1751
- * clear, so someone who holds only an older key of the space can still say
1752
- * where to seal the new one.
1753
- */
1754
- let memberKeysCache = null;
1755
- const memberKeyMap = () => (memberKeysCache ??= loadMemberKeys());
1756
- /** Every key box, read once until records change */
1757
- let boxCache = null;
1758
- const boxIndex = () => (boxCache ??= storage.histories('box:'));
1759
- async function loadMemberKeys() {
1760
- const found = new Map();
1761
- // By key: the current version may be anyone's.
1762
- for (const [key, versions] of await storage.histories('memberkey:')) {
1763
- for (const version of versions) {
1764
- if (version.collection !== MEMBER_KEY_COLLECTION || version.deleted)
1765
- continue;
1766
- const verdict = await judge(version);
1767
- if (!verdict.verified || !verdict.root || (await memberKeyRecordKey(verdict.root)) !== key)
1768
- continue;
1769
- if (!(await standingOf(version)).ok)
1770
- continue;
1771
- const body = isRecord(version.body) ? version.body : null;
1772
- if (isContactPublicKey(body?.key)) {
1773
- found.set(verdict.root, body.key);
1774
- break;
1775
- }
1776
- }
1777
- }
1778
- return found;
1779
- }
1780
- /**
1781
- * Records changed: whatever is derived from them may have too. Given the
1782
- * versions that were placed, and none of them the space's own (`sys.`),
1783
- * only what those records feed is thrown away: who may do what, the
1784
- * definitions and the keys come from `sys.` records alone, so every other
1785
- * verdict still holds. Given nothing — another tab, a folder, new keys —
1786
- * everything is.
1787
- */
1788
- let spaceFiles = null;
1789
- const missingFiles = () => {
1790
- throw new Error('The space is still opening');
1791
- };
1792
- let filesTimer = null;
1793
- /** One pass at a time; a change during one runs another after it */
1794
- let filesPass = null;
1795
- let filesAgain = false;
1796
- /** After a change: which files are named is worked out again, and soon kept, dropped and fetched to match */
1797
- function filesChanged() {
1798
- spaceFiles?.changed();
1799
- if (filesPass) {
1800
- filesAgain = true;
1801
- return;
1802
- }
1803
- if (filesTimer || closed)
1804
- return;
1805
- filesTimer = setTimeout(() => {
1806
- filesTimer = null;
1807
- filesPass = (async () => {
1808
- await spaceFiles?.tidy();
1809
- if (deps.fetchFiles === 'all')
1810
- await spaceFiles?.fetchAll();
1811
- })()
1812
- .catch(() => {
1813
- // A peer or mirror out of reach; the next change tries again.
1814
- })
1815
- .finally(() => {
1816
- filesPass = null;
1817
- if (filesAgain && !closed) {
1818
- filesAgain = false;
1819
- filesChanged();
1820
- }
1821
- });
1822
- }, 2000);
1823
- unref(filesTimer);
1824
- }
1825
- const recordsChanged = (placed) => {
1826
- filesChanged();
1827
- if (placed)
1828
- noteArrived(placed);
1829
- linkIndexCache = null;
1830
- emit({ type: 'records', space: space.id });
1831
- for (const mirror of mirrors)
1832
- mirror.changed();
1833
- if (placed && placed.every((version) => !version.collection.startsWith('sys.'))) {
1834
- for (const version of placed)
1835
- staleKeys.add(version.key);
1836
- // A record waiting on a version it cites may count now.
1837
- for (const key of pendingKeys)
1838
- staleKeys.add(key);
1839
- pendingKeys.clear();
1840
- // A version in a line can make a double spend of one that counted, and undo what cites it.
1841
- if (placed.some((version) => lineCollections.has(version.collection))) {
1842
- checkVerdicts.clear();
1843
- countedIndex = null;
1844
- for (const version of placed)
1845
- lineIndexes.delete(version.collection);
1846
- }
1847
- return;
1848
- }
1849
- countedIndex = null;
1850
- catalogCache = null;
1851
- profilesCache = null;
1852
- memberKeysCache = null;
1853
- boxCache = null;
1854
- accessCache = placed && accessCache ? extendAccess(accessCache, placed) : null;
1855
- standings.clear();
1856
- checkVerdicts.clear();
1857
- lineIndexes.clear();
1858
- keepUp();
1859
- // The access history may name keepers now, or none.
1860
- void refreshHolds().catch(() => { });
1861
- // Or a new key, which someone connected may not hold.
1862
- void letGoOfOutsiders().catch(() => { });
1863
- };
1864
- // ─── The space's keys ──────────────────────────────────────────────
1865
- //
1866
- // A private space's key changes when someone loses their place in it
1867
- // (`sys.key`, part of the access history): whoever manages the space makes
1868
- // a new one, and seals a copy to each member's member key (`sys.box`). The
1869
- // key record carries every earlier key sealed under the new one, so holding
1870
- // the current key opens everything written before it — which is how
1871
- // someone who joins later reads the old records, and someone removed reads
1872
- // nothing new. This is how Keybase changes a team's key.
1873
- /** The key the history names now, if this node holds it */
1874
- function currentKey(state) {
1875
- const epoch = state.keys.at(-1);
1876
- return epoch ? (keyring.get(epoch.keyId) ?? null) : null;
1877
- }
1878
- /** The newest key this node holds that the history names — what it proves it may read with while behind */
1879
- function newestKey(state) {
1880
- for (const epoch of [...state.keys].reverse()) {
1881
- const held = keyring.get(epoch.keyId);
1882
- if (held)
1883
- return held;
1884
- }
1885
- return record.key;
1886
- }
1887
- /** Box and key record versions already opened, so each is tried once */
1888
- const opened = new Set();
1889
- /**
1890
- * Key records already opened, for the keys the history named then. Which
1891
- * key event counts, and which keys it names, can change as changes arrive,
1892
- * so they are opened again when that does.
1893
- */
1894
- const openedKeyRecords = new Set();
1895
- let openedFor = '';
1896
- /**
1897
- * Keys whose key change is malformed: its earlier keys don't open, or leave
1898
- * out the space's first key, which every reader needs for onePer keys
1899
- * (03 §9.3). Nothing is taken from them, and a manager replaces them.
1900
- */
1901
- const malformedKeys = new Set();
1902
- /** Takes in what this node can open: boxes sealed to its member key, and the earlier keys each key record carries */
1903
- async function learnKeys() {
1904
- const { history } = await access();
1905
- const epochs = history.current.keys;
1906
- const learned = [];
1907
- const take = (found) => {
1908
- if (keyring.has(found.id))
1909
- return false;
1910
- keyring.set(found.id, found);
1911
- learned.push(found);
1912
- return true;
1913
- };
1914
- if (memberPair && epochs.some((epoch) => !keyring.has(epoch.keyId))) {
1915
- for (const versions of (await boxIndex()).values()) {
1916
- for (const version of versions) {
1917
- if (version.collection !== BOX_COLLECTION || version.deleted || opened.has(version.id))
1918
- continue;
1919
- const body = isRecord(version.body) ? version.body : null;
1920
- if (body?.to !== deps.rootDid || typeof body.keyId !== 'string' || typeof body.sealed !== 'string')
1921
- continue;
1922
- const epoch = epochs.find((known) => known.keyId === body.keyId);
1923
- if (!epoch || keyring.has(epoch.keyId))
1924
- continue;
1925
- opened.add(version.id);
1926
- const content = await openValueFrom(memberPair, BOX_LABEL, boxBound(space.id, epoch.keyId, deps.rootDid), body.sealed);
1927
- if (!isRecord(content) || typeof content.key !== 'string')
1928
- continue;
1929
- // Whoever sealed it, it is the key the history names or it is nothing.
1930
- const found = await spaceKeyFromRaw(base64UrlDecode(content.key)).catch(() => null);
1931
- if (found?.id === epoch.keyId && (await deriveReadKey(found, provider)).did === epoch.readKey)
1932
- take(found);
1933
- }
1934
- }
1935
- }
1936
- const named = epochs.map((epoch) => `${epoch.keyId}/${epoch.readKey}/${epoch.event}`).join('|');
1937
- if (named !== openedFor) {
1938
- openedFor = named;
1939
- openedKeyRecords.clear();
1940
- malformedKeys.clear();
1941
- }
1942
- // Each newer key opens the ones before it — which may open more.
1943
- let more = true;
1944
- while (more) {
1945
- more = false;
1946
- for (const versions of (await storage.histories('key:')).values()) {
1947
- for (const version of versions) {
1948
- const body = isRecord(version.body) ? version.body : null;
1949
- if (version.collection !== KEY_COLLECTION ||
1950
- openedKeyRecords.has(version.id) ||
1951
- typeof body?.keyId !== 'string')
1952
- continue;
1953
- // Only the key change that counted for that key: anyone may store a version at `key:space`.
1954
- const epoch = epochs.find((known) => known.keyId === body.keyId);
1955
- if (!epoch || epoch.event !== version.id)
1956
- continue;
1957
- const holder = keyring.get(body.keyId);
1958
- if (!holder)
1959
- continue;
1960
- openedKeyRecords.add(version.id);
1961
- const earlier = await openValue(holder.seal, EARLIER_KEYS_LABEL, { space: space.id, keyId: holder.id }, body.earlier);
1962
- const found = [];
1963
- for (const raw of isStringList(earlier) ? earlier.slice(0, 1000) : []) {
1964
- const key = await spaceKeyFromRaw(base64UrlDecode(raw)).catch(() => null);
1965
- if (key)
1966
- found.push(key);
1967
- }
1968
- // Without the first key, a reader holding only this one couldn't derive onePer keys (02 §7.3).
1969
- if (!isStringList(earlier) || !found.some((key) => key.id === space.encryptionKeyId)) {
1970
- malformedKeys.add(body.keyId);
1971
- continue;
1972
- }
1973
- // And only keys the history names, each with the read key it names.
1974
- for (const key of found) {
1975
- const named = epochs.find((known) => known.keyId === key.id);
1976
- if (named && (await deriveReadKey(key, provider)).did === named.readKey && take(key))
1977
- more = true;
1978
- }
1979
- }
1980
- }
1981
- }
1982
- if (learned.length === 0)
1983
- return;
1984
- // A definition this node couldn't read may open now.
1985
- definitions.clear();
1986
- const writeWith = newestKey((await access()).history.current);
1987
- if (writeWith)
1988
- await deps.onKeys?.([...keyring.values()], writeWith.id);
1989
- recordsChanged();
1990
- }
1991
- /** Makes a new key current, with every key before it sealed inside, and seals it to each member */
1992
- async function rotateKey() {
1993
- if (space.visibility !== 'private')
1994
- throw new Error('A public space has no key to change');
1995
- const { history } = await access();
1996
- if (!may(history.current, deps.rootDid, KEY_CHANGE, {}))
1997
- throw new Error(`Only someone granted ${KEY_CHANGE} in "${space.name}" can change its key`);
1998
- if (!currentKey(history.current))
1999
- throw new Error(`This device doesn't hold the current key of "${space.name}" yet`);
2000
- // Every key change carries the first key, so every reader holds it (03 §9.3).
2001
- if (!space.encryptionKeyId || !keyring.has(space.encryptionKeyId))
2002
- throw new Error(`This device doesn't hold the first key of "${space.name}"`);
2003
- const next = await generateSpaceKey();
2004
- const earlier = [...keyring.values()].map((held) => base64UrlEncode(held.raw));
2005
- const body = {
2006
- keyId: next.id,
2007
- readKey: (await deriveReadKey(next, provider)).did,
2008
- earlier: await sealValue(next.seal, EARLIER_KEYS_LABEL, { space: space.id, keyId: next.id }, earlier),
2009
- };
2010
- keyring.set(next.id, next);
2011
- try {
2012
- await upsert(KEY_COLLECTION, SPACE_KEY_RECORD, body);
2013
- }
2014
- catch (error) {
2015
- keyring.delete(next.id);
2016
- throw error;
2017
- }
2018
- await deps.onKeys?.([...keyring.values()], next.id);
2019
- await boxForMembers();
2020
- }
2021
- /**
2022
- * Seals the current key to each member who has no copy from someone who
2023
- * manages the space. Members show their member key on their profile; one
2024
- * who hasn't yet gets their copy once they do.
2025
- */
2026
- async function boxForMembers() {
2027
- const { history } = await access();
2028
- const state = history.current;
2029
- const epoch = state.keys.at(-1);
2030
- const key = currentKey(state);
2031
- if (!epoch || !key)
2032
- return;
2033
- const boxed = new Set();
2034
- for (const versions of (await boxIndex()).values()) {
2035
- for (const version of versions) {
2036
- const body = isRecord(version.body) ? version.body : null;
2037
- if (version.collection !== BOX_COLLECTION ||
2038
- body?.keyId !== epoch.keyId ||
2039
- typeof body.to !== 'string')
2040
- continue;
2041
- const { root } = await judge(version);
2042
- if (root && (root === deps.rootDid || may(state, root, KEY_CHANGE, {})))
2043
- boxed.add(body.to);
2044
- }
2045
- }
2046
- const memberKeys = await memberKeyMap();
2047
- const raw = base64UrlEncode(key.raw);
2048
- for (const did of [...readers(state)].sort()) {
2049
- const publicKey = memberKeys.get(did);
2050
- if (boxed.has(did) || !publicKey)
2051
- continue;
2052
- const sealed = await sealValueTo(publicKey, BOX_LABEL, boxBound(space.id, epoch.keyId, did), {
2053
- key: raw,
2054
- });
2055
- await upsert(BOX_COLLECTION, await boxKey(epoch.keyId, did, deps.rootDid), {
2056
- keyId: epoch.keyId,
2057
- to: did,
2058
- sealed,
2059
- });
2060
- }
2061
- }
2062
- /**
2063
- * Keeps the keys in step with the history: says where to seal this
2064
- * account's copy, learns what it can, and — managing the space — changes
2065
- * the key when due and seals it to whoever lacks it.
2066
- */
2067
- async function upkeep() {
2068
- // A note that can't change access keeps no keys for others: it only reads.
2069
- if (!grantsBeyondRecords(session.proof(), space.id, ACCESS_COMMAND)) {
2070
- if (space.visibility === 'private')
2071
- await learnKeys();
2072
- return;
2073
- }
2074
- await nameRelays();
2075
- if (space.visibility !== 'private')
2076
- return;
2077
- if (deps.accountOnly) {
2078
- await learnKeys();
2079
- return;
2080
- }
2081
- const mine = await memberKeyMap();
2082
- if (memberPair &&
2083
- mine.get(deps.rootDid) !== memberPair.publicKey &&
2084
- actsForAccount(session.proof()) &&
2085
- !(await cannotWrite())) {
2086
- await upsert(MEMBER_KEY_COLLECTION, await memberKeyRecordKey(deps.rootDid), {
2087
- key: memberPair.publicKey,
2088
- });
2089
- }
2090
- await learnKeys();
2091
- const { history } = await access();
2092
- const state = history.current;
2093
- if (!currentKey(state))
2094
- return;
2095
- if (!may(state, deps.rootDid, KEY_CHANGE, {}))
2096
- return;
2097
- // A current key whose change left out the first key is replaced, as one that is due.
2098
- const malformed = malformedKeys.has(state.keys.at(-1)?.keyId ?? '');
2099
- if (state.keyDue || (malformed && space.encryptionKeyId && keyring.has(space.encryptionKeyId)))
2100
- await rotateKey();
2101
- else
2102
- await boxForMembers();
2103
- }
2104
- /**
2105
- * A space nobody has said where to meet yet: whoever manages it names the
2106
- * relays this node uses, so the invites and devices that follow meet there.
2107
- */
2108
- async function nameRelays() {
2109
- const own = usableRelays(deps.network).slice(0, MAX_RELAYS);
2110
- if (own.length === 0)
2111
- return;
2112
- const { history } = await access();
2113
- if (history.current.relays.length > 0 || !may(history.current, deps.rootDid, SPACE_RELAYS, {}))
2114
- return;
2115
- await upsert(RELAYS_COLLECTION, SPACE_RELAYS_RECORD, { relays: own });
2116
- }
2117
- /** Runs the upkeep once more after whatever changed — one run at a time */
2118
- const keepingUp = serial(async () => {
2119
- if (closed)
2120
- return;
2121
- await upkeep().catch(() => {
2122
- // A write refused, a peer's junk: the next change tries again.
2123
- });
2124
- });
2125
- function keepUp() {
2126
- if (!closed)
2127
- void keepingUp();
2128
- }
2129
- /** The read key each peer checked here was let in on, by session DID, and when */
2130
- const admittedOn = new Map();
2131
- /** How this node proves it may read, and checks the peers that connect — against the history at that moment */
2132
- const readAccess = space.visibility !== 'private'
2133
- ? null
2134
- : {
2135
- async key() {
2136
- const held = newestKey((await access()).history.current);
2137
- // A carrier holds the read key pair without the key it comes from: it may be served the space, and cannot open it.
2138
- return held ? deriveReadKey(held, provider) : (record.read ?? null);
2139
- },
2140
- current: () => currentReadKey,
2141
- async earlier() {
2142
- const { current } = (await access()).history;
2143
- const newest = newestKey(current);
2144
- const older = [...current.keys]
2145
- .reverse()
2146
- .map((epoch) => keyring.get(epoch.keyId))
2147
- .filter((held) => held !== undefined && held !== newest);
2148
- return Promise.all(older.slice(0, MAX_EARLIER_READ_KEYS).map((held) => deriveReadKey(held, provider)));
2149
- },
2150
- async membership() {
2151
- const held = newestKey((await access()).history.current);
2152
- return held ? sealValue(held.seal, MEMBERSHIP_LABEL, { space: space.id }, session.proof()) : null;
2153
- },
2154
- async admits(peerDid, readKey, membership) {
2155
- const { history } = await access();
2156
- const epoch = history.current.keys.find((known) => known.readKey === readKey);
2157
- const held = epoch ? keyring.get(epoch.keyId) : undefined;
2158
- if (!held)
2159
- return false;
2160
- const { account } = await accountOf(peerDid, await openValue(held.seal, MEMBERSHIP_LABEL, { space: space.id }, membership));
2161
- return account !== null && readers(history.current).has(account);
2162
- },
2163
- async removed(peerDid, readKey, membership) {
2164
- const { history } = await access();
2165
- const epoch = history.current.keys.find((known) => known.readKey === readKey);
2166
- const held = epoch ? keyring.get(epoch.keyId) : undefined;
2167
- if (!held)
2168
- return false;
2169
- const note = await openValue(held.seal, MEMBERSHIP_LABEL, { space: space.id }, membership);
2170
- const { account } = await accountOf(peerDid, note);
2171
- return account !== null && (await formerMembers({ untilNewKey: true })).has(account);
2172
- },
2173
- admitted(peerDid, readKey) {
2174
- admittedOn.set(peerDid, { readKey, at: Date.now() });
2175
- },
2176
- };
2177
- // ─── Mirrors ───────────────────────────────────────────────────────
2178
- //
2179
- // Every mirror is one more peer: what it holds goes through the same gates
2180
- // as a peer's records, and what this node holds goes out to it.
2181
- /** What a mirror holds goes through the same gates as a peer's records */
2182
- const fromMirror = async (version) => {
2183
- const verdict = await admit(version);
2184
- if (!verdict.ok && !verdict.withdrawn)
2185
- return verdict.later ? 'later' : 'refused';
2186
- await storage.addVersion(version);
2187
- return 'stored';
2188
- };
2189
- const mirrors = [];
2190
- for (const [index, store] of (deps.mirrors ?? []).entries()) {
2191
- mirrors.push(await createMirror({
2192
- store,
2193
- space: space.id,
2194
- storage,
2195
- state: await deps.stores(`mirrors/${space.id}/${index}`),
2196
- accept: fromMirror,
2197
- }));
2198
- }
2199
- // A data folder is one more: its spaces are segments, like a bucket's, and
2200
- // what this device holds of them is its own (`node/stores.ts`).
2201
- const folderMirror = deps.stores.folder
2202
- ? await createMirror({
2203
- store: deps.stores.folder,
2204
- space: space.id,
2205
- storage,
2206
- state: await deps.stores(`folder/${space.id}`),
2207
- accept: fromMirror,
2208
- // Apps and the CLI on one computer meet through the folder: soon, not in a bucket's time.
2209
- flushMs: 1000,
2210
- })
2211
- : null;
2212
- if (folderMirror)
2213
- mirrors.push(folderMirror);
2214
- /** Reads every mirror in the background: a space that opens from nothing — a host that lost its disk — fills in as it goes */
2215
- const pullMirrors = () => Promise.all(mirrors.map((mirror) => mirror
2216
- .pull()
2217
- .then(({ added }) => {
2218
- if (added === 0)
2219
- return;
2220
- recordsChanged();
2221
- announceSoon();
2222
- })
2223
- .catch(() => {
2224
- // Out of reach now; what this node holds goes out on the next change.
2225
- })));
2226
- // ─── Peers ─────────────────────────────────────────────────────────
2227
- /** How the first connect went; after that, what the networks say now (`liveConnection`) */
2228
- let connection = 'offline';
2229
- let rejected = 0;
2230
- const networks = [];
2231
- const reachable = () => networks.some((network) => network.isConnected());
2232
- /**
2233
- * Connected while some network is: a relay reachable, or a peer. Once up, a
2234
- * space whose relays are all gone and whose peers have left is trying again,
2235
- * not connected; one whose first try failed is connected once a retry works.
2236
- */
2237
- const liveConnection = () => {
2238
- if (connection === 'offline')
2239
- return connection;
2240
- if (reachable())
2241
- return 'connected';
2242
- return connection === 'connected' ? 'connecting' : connection;
2243
- };
2244
- let shown = null;
2245
- // Relays come and go without a peer doing so; say so when that changes how this space connects.
2246
- const stopWatchingMesh = deps.mesh?.subscribe(() => {
2247
- const now = liveConnection();
2248
- if (now === shown)
2249
- return;
2250
- shown = now;
2251
- emit({ type: 'status', space: space.id });
165
+ if ((await versions.judge(version)).verified)
166
+ await lines.placeInLog(version);
167
+ return standing.admission(version);
168
+ }
169
+ // ─── Mirrors and files ─────────────────────────────────────────────
170
+ const mirrors = await openMirrors({
171
+ ...base,
172
+ stores: deps.stores,
173
+ adapter,
174
+ mirrors: deps.mirrors,
175
+ watchIntervalMs: deps.watchIntervalMs,
176
+ admit,
177
+ recordsChanged: () => recordsChanged(),
178
+ announceSoon: () => peers.announceSoon(),
2252
179
  });
2253
- /** Which network a peer was met on, so replies go back the same way */
2254
- const routes = new Map();
2255
- // ─── Files ─────────────────────────────────────────────────────────
2256
- //
2257
180
  // Named on the outside of the versions that refer to them, fetched chunk by
2258
181
  // chunk and checked as they come, kept while a body that names them is
2259
182
  // (spec 05 §16.6).
2260
- spaceFiles = createSpaceFiles({
183
+ const files = createSpaceFiles({
2261
184
  space: space.id,
2262
185
  adapter,
2263
186
  storage,
2264
- send: (peer, message) => routes.get(peer)?.send(peer, {
187
+ send: (peer, message) => peers.toPeer(peer, {
2265
188
  type: 'sync',
2266
189
  from: session.did,
2267
190
  payload: { ...message, v: SYNC_PROTOCOL_VERSION },
2268
191
  }),
2269
- peers: () => connectedPeers(),
2270
- mirrors: () => mirrors.map((mirror) => ({ store: mirror.store, writer: mirror.writer })),
2271
- stands: async (version) => {
2272
- const standing = await standingOf(version);
2273
- return standing.ok || !!standing.withdrawn;
2274
- },
192
+ peers: () => peers.connectedPeers(),
193
+ mirrors: mirrors.all,
194
+ stands: async (version) => storable(await standing.standingOf(version)),
195
+ // Files follow records: every file a version kept whole names is fetched, within a device's limits.
196
+ ...(deps.fetchFiles === 'all' ? {} : { limits: DEVICE_LIMITS }),
2275
197
  });
2276
- const sync = createSyncEngine({
2277
- storageProvider: storage,
2278
- self: session.did,
2279
- holds,
2280
- files: (peer, message) => spaceFiles?.onMessage(peer, message) ?? Promise.resolve(),
2281
- sendToPeer: (peerId, message) => {
2282
- routes.get(peerId)?.send(peerId, { type: 'sync', from: session.did, payload: message });
2283
- },
2284
- validate: async (version) => {
2285
- const verdict = await admit(version);
2286
- return verdict.ok || verdict.withdrawn
2287
- ? { valid: true }
2288
- : { valid: false, reason: verdict.reason, ...(verdict.later ? { later: true } : {}) };
2289
- },
2290
- });
2291
- /**
2292
- * Tells every connected peer this node's root, soon after it took in
2293
- * something new — from a peer or from a folder. Without it, a record passed
2294
- * along waits for the next heartbeat at every hop: a carrier would sit on a
2295
- * friend's write for half a minute before the pod, or your phone, heard of
2296
- * it. A peer already level answers and nothing moves.
2297
- */
2298
- let announceTimer = null;
2299
- const announceSoon = () => {
2300
- if (announceTimer)
2301
- return;
2302
- announceTimer = setTimeout(() => {
2303
- announceTimer = null;
2304
- sync.notifyPeers(connectedPeers());
2305
- }, 100);
2306
- };
2307
- // Once per message from a peer, with everything it brought.
2308
- sync.on('received', (versions) => {
2309
- recordsChanged(versions);
2310
- announceSoon();
2311
- for (const version of versions)
2312
- deps.onArrived?.(version);
2313
- });
2314
- sync.on('rejected', (peer, _version, reason) => {
2315
- rejected += 1;
2316
- emit({ type: 'rejected', space: space.id, peer, reason });
2317
- });
2318
- // Both sides of a socket to a node prove who they are; in a private space the client also proves it may read.
2319
- let authenticator = null;
2320
- /** A socket to an always-on node, for this space */
2321
- function nodeNetwork(node) {
2322
- authenticator ??= createClientAuth(space.id, session, readAccess, provider);
2323
- // The space goes in the query, before any pin in the fragment.
2324
- const [base = '', ...pin] = node.split('#');
2325
- const url = `${base}${base.includes('?') ? '&' : '?'}space=${encodeURIComponent(space.id)}${pin.length ? `#${pin.join('#')}` : ''}`;
2326
- const auth = authenticator;
2327
- return createNetworkManager({
2328
- did: session.did,
2329
- createTransport: () => createWebSocketTransport({ url, did: session.did, authenticator: auth }),
2330
- });
2331
- }
2332
- /** Sockets to the hosts the account or the space uses, by address: they change while the space is open */
2333
- const hostNetworks = new Map();
2334
- const net = deps.network;
2335
- if (net) {
2336
- // Who is at the other end is asked of the history at each handshake: the space's key may change while it is open.
2337
- await access();
2338
- if (deps.mesh) {
2339
- meshRoom = await relayRoom(space.id);
2340
- deps.mesh.useRelays(meshRoom, relays);
2341
- // Every peer met through a relay proves who it is, and in a private space that it may read.
2342
- networks.push(deps.mesh.join(meshRoom, createMeshAuth(space.id, session, readAccess, provider)));
2343
- }
2344
- for (const node of net.nodes ?? [])
2345
- networks.push(nodeNetwork(node));
2346
- for (const transport of net.transports?.(space.id, session.did) ?? []) {
2347
- networks.push(createNetworkManager({ did: session.did, createTransport: () => transport }));
2348
- }
2349
- }
2350
- const connectedPeers = () => [
2351
- ...new Set(networks.flatMap((network) => network.getPeers().map((peer) => peer.did))),
2352
- ];
2353
- // ─── Live messages ─────────────────────────────────────────────────
2354
- //
2355
- // A connection proves which session key is at the other end — not whose it
2356
- // is. So the first thing each side sends is its note, the delegation from
2357
- // its account to that key: the same note its records carry. It names the
2358
- // key it was made out to, and that must be the key the connection proved,
2359
- // so a note copied off someone's record is no use to anyone else.
2360
- const peerAccounts = new Map();
2361
- /** Peers let go of because their account was removed, by session DID: turned away again when they redial */
2362
- const cutOff = new Map();
2363
- const knownAccounts = new Map();
2364
- const liveAllowance = new Map();
2365
- async function accountOf(peer, note) {
2366
- if (!isRecord(note) || canonicalize(note).length > MAX_NOTE_LENGTH)
2367
- return NO_ACCOUNT;
2368
- const checked = await verifyNote(note, provider).catch(() => null);
2369
- if (!checked?.valid || checked.audience !== peer)
2370
- return NO_ACCOUNT;
2371
- return {
2372
- account: checked.root,
2373
- // A key that writes records somewhere but can't define here. Judged on the
2374
- // whole note, so a key for another space doesn't pass as the account here.
2375
- // A note that only reads is not one: it writes nothing. The note is the
2376
- // account's own, one link, so its key can't sign itself a wider one.
2377
- recordsOnly: writesRecords(checked.note) && !grantsBeyondRecords(checked.note, space.id, DEFINE_COMMAND),
2378
- };
2379
- }
2380
- /** A peer's share of live messages: a burst, then a steady rate — as the relay limits them */
2381
- function withinAllowance(peer) {
2382
- const now = Date.now();
2383
- const held = liveAllowance.get(peer) ?? { tokens: LIVE_BURST, at: now };
2384
- const tokens = Math.min(LIVE_BURST, held.tokens + ((now - held.at) / 1000) * LIVE_PER_SECOND);
2385
- liveAllowance.set(peer, { tokens: Math.max(0, tokens - 1), at: now });
2386
- return tokens >= 1;
2387
- }
2388
- async function onLive(peer, payload) {
2389
- if (!withinAllowance(peer))
2390
- return;
2391
- if ((JSON.stringify(payload ?? null)?.length ?? 0) > MAX_LIVE_BYTES)
2392
- return;
2393
- const { account, recordsOnly } = (await peerAccounts.get(peer)) ?? NO_ACCOUNT;
2394
- // Gone while its note was being checked.
2395
- if (!routes.has(peer))
2396
- return;
2397
- if (account !== null && (await formerMembers()).has(account))
198
+ let filesTimer = null;
199
+ /** One pass at a time; a change during one runs another after it */
200
+ let filesPass = null;
201
+ let filesAgain = false;
202
+ /** After a change: which files are named is worked out again, and soon kept, dropped and fetched to match */
203
+ function filesChanged() {
204
+ files.changed();
205
+ if (filesPass) {
206
+ filesAgain = true;
2398
207
  return;
2399
- emit({ type: 'message', space: space.id, from: account, peer, recordsOnly, message: payload });
2400
- }
2401
- /**
2402
- * Lets go of the peers a handshake would refuse now. A handshake checks a
2403
- * reader once, but the space's key changes when someone is removed: a peer
2404
- * let in on a key that is no longer current stays only while it acts for
2405
- * someone who may still read, as it would get in again (`checkRead`).
2406
- * Anyone else — someone removed, a view-only link from before — stops
2407
- * getting anything the moment this node knows the new key.
2408
- */
2409
- async function letGoOfOutsiders() {
2410
- const connected = new Set(connectedPeers());
2411
- // Someone removed is let go of as soon as this node knows, on any key:
2412
- // the key may not have changed yet, if nobody who manages the space is here.
2413
- const gone = await formerMembers({ untilNewKey: true });
2414
- for (const [peer, account] of cutOff)
2415
- if (!gone.has(account))
2416
- cutOff.delete(peer);
2417
- for (const peer of connected) {
2418
- const account = knownAccounts.get(peer)?.account ?? null;
2419
- if (account === null || !gone.has(account) || cutOff.has(peer))
2420
- continue;
2421
- cutOff.set(peer, account);
2422
- admittedOn.delete(peer);
2423
- // Nothing more goes to them from now; the socket closes a moment later,
2424
- // so what was already sent — the "stored" for their own leaving — arrives.
2425
- sync.removePeer(peer);
2426
- routes.delete(peer);
2427
- setTimeout(() => {
2428
- peerAccounts.delete(peer);
2429
- knownAccounts.delete(peer);
2430
- liveAllowance.delete(peer);
2431
- for (const network of networks)
2432
- network.drop(peer);
2433
- }, LET_GO_AFTER_MS);
2434
208
  }
2435
- if (admittedOn.size === 0)
209
+ if (filesTimer || closed)
2436
210
  return;
2437
- for (const [peer, { at }] of admittedOn) {
2438
- // Checked, and never let in: a handshake the other side refused.
2439
- if (!connected.has(peer) && Date.now() - at > STALE_ADMISSION_MS)
2440
- admittedOn.delete(peer);
2441
- }
2442
- const allowed = readers((await access()).history.current);
2443
- for (const peer of connected) {
2444
- const admission = admittedOn.get(peer);
2445
- if (!admission || admission.readKey === currentReadKey)
2446
- continue;
2447
- // Its note is said first, but may still be on its way; this runs again when it lands.
2448
- if (!peerAccounts.has(peer) && Date.now() - admission.at < WHO_WAIT_MS)
2449
- continue;
2450
- const { account } = (await peerAccounts.get(peer)) ?? NO_ACCOUNT;
2451
- if (account !== null && allowed.has(account))
2452
- continue;
2453
- // Let in again meanwhile, on the key it holds now.
2454
- if (admittedOn.get(peer) !== admission)
2455
- continue;
2456
- admittedOn.delete(peer);
2457
- for (const network of networks)
2458
- network.drop(peer);
2459
- }
2460
- }
2461
- function listen(network) {
2462
- network.on('message', (message) => {
2463
- if (message.type === 'sync')
2464
- void sync.handleMessage(message.from, message.payload);
2465
- else if (message.type === WHO_MESSAGE) {
2466
- const note = isRecord(message.payload) ? message.payload.note : undefined;
2467
- const checked = accountOf(message.from, note);
2468
- peerAccounts.set(message.from, checked);
2469
- void checked.then((known) => {
2470
- if (peerAccounts.get(message.from) !== checked)
2471
- return;
2472
- knownAccounts.set(message.from, known);
2473
- emit({ type: 'status', space: space.id });
2474
- void letGoOfOutsiders().catch(() => { });
2475
- });
2476
- }
2477
- else if (message.type === LIVE_MESSAGE)
2478
- void onLive(message.from, message.payload);
2479
- });
2480
- network.on('peer-connected', (info) => {
2481
- if (cutOff.has(info.did)) {
2482
- network.drop(info.did);
2483
- return;
2484
- }
2485
- // Said first, so it reaches them before any live message from here.
2486
- network.send(info.did, { type: WHO_MESSAGE, from: session.did, payload: { note: session.proof() } });
2487
- routes.set(info.did, network);
2488
- sync.addPeer(info.did);
2489
- // Reconcile at once rather than waiting for the heartbeat.
2490
- sync.notifyPeers([info.did]);
2491
- emit({ type: 'status', space: space.id });
2492
- // The key may have changed between checking it and letting it in.
2493
- void letGoOfOutsiders().catch(() => { });
2494
- });
2495
- network.on('peer-disconnected', (info) => {
2496
- if (routes.get(info.did) === network) {
2497
- routes.delete(info.did);
2498
- sync.removePeer(info.did);
2499
- peerAccounts.delete(info.did);
2500
- knownAccounts.delete(info.did);
2501
- liveAllowance.delete(info.did);
2502
- }
2503
- if (!connectedPeers().includes(info.did))
2504
- admittedOn.delete(info.did);
2505
- emit({ type: 'status', space: space.id });
2506
- });
2507
- network.on('error', () => {
2508
- if (!networks.some((n) => n.isConnected()))
2509
- connection = 'error';
2510
- emit({ type: 'status', space: space.id });
2511
- });
2512
- }
2513
- for (const network of networks)
2514
- listen(network);
2515
- // Whether to hold part of the space is settled before the first hello says what this node holds.
2516
- await refreshHolds().catch(() => { });
2517
- if (networks.length > 0) {
2518
- connection = 'connecting';
2519
- // Online as soon as one way in works: a node that is slow to answer, or
2520
- // never does, must not keep the space saying "connecting" meanwhile.
2521
- void Promise.any(networks.map((network) => network.connect())).then(() => {
2522
- connection = 'connected';
2523
- emit({ type: 'status', space: space.id });
2524
- }, () => {
2525
- connection = 'error';
2526
- emit({ type: 'status', space: space.id });
2527
- });
2528
- sync.start();
2529
- }
2530
- // ─── Writers outside this process ──────────────────────────────────
2531
- //
2532
- // A data folder is written by other apps, and by other devices behind
2533
- // whatever syncs it; a directory store by another process (a command beside
2534
- // a daemon). Nothing announces either, so both are looked for.
2535
- /** Whether another writer changed anything this node holds */
2536
- const look = async () => {
2537
- // The same verdict as for a version from a peer.
2538
- const reconciled = isFolderAdapter(adapter)
2539
- ? (await reconcileFolder(storage, adapter, async (version) => storable(await admit(version)))).changed
2540
- : false;
2541
- const pulled = folderMirror ? (await folderMirror.pull()).added > 0 : false;
2542
- return reconciled || pulled;
2543
- };
2544
- let watchTimer = null;
2545
- if (deps.watchIntervalMs > 0 && (folderMirror || isFolderAdapter(adapter))) {
2546
- let running = false;
2547
- watchTimer = setInterval(() => {
2548
- if (running)
2549
- return;
2550
- running = true;
2551
- look()
2552
- .then((changed) => {
2553
- if (!changed)
2554
- return;
2555
- recordsChanged();
2556
- announceSoon();
2557
- })
211
+ filesTimer = setTimeout(() => {
212
+ filesTimer = null;
213
+ filesPass = (async () => {
214
+ await files.tidy();
215
+ await files.fetchMissing();
216
+ })()
2558
217
  .catch(() => {
2559
- // A revoked permission or a folder that went away; the next pass will tell.
218
+ // A peer or mirror out of reach; the next change tries again.
2560
219
  })
2561
220
  .finally(() => {
2562
- running = false;
221
+ filesPass = null;
222
+ if (filesAgain && !closed) {
223
+ filesAgain = false;
224
+ filesChanged();
225
+ }
2563
226
  });
2564
- }, deps.watchIntervalMs);
2565
- }
2566
- // Tabs of one browser share one IndexedDB but not memory, so a write in one
2567
- // is invisible to the other until it is told. A nudge is enough: the store
2568
- // already holds the data.
2569
- const channel = typeof globalThis.BroadcastChannel === 'function'
2570
- ? new globalThis.BroadcastChannel(`minca-node:${deps.rootDid}:${space.id}`)
2571
- : null;
2572
- if (channel) {
2573
- channel.onmessage = () => {
2574
- // The other tab wrote to the store underneath: what sync compares is read again.
2575
- storage.invalidate();
2576
- recordsChanged();
2577
- };
2578
- // In Node a channel holds the process open; it must never be the only thing doing so.
2579
- unref(channel);
2580
- }
2581
- // ─── Holding part of the space ─────────────────────────────────────
2582
- //
2583
- // With `cache` set, and once the space names a keeper, this node holds only
2584
- // the collections it uses, besides the space's own. Sync takes in nothing
2585
- // else. Its own writes are pending until enough keepers have them, and a
2586
- // collection holding a pending write is never dropped. Without a keeper the
2587
- // space is held whole: then this node may be one of its copies.
2588
- const HOUR = 3_600_000;
2589
- const DAY = 24 * HOUR;
2590
- const declared = new Set((cache?.collections ?? []).filter((c) => !c.startsWith('sys.')));
2591
- let cacheTimer = null;
2592
- const saveCache = () => {
2593
- if (cacheTimer || !cache)
2594
- return;
2595
- cacheTimer = setTimeout(() => {
2596
- cacheTimer = null;
2597
- void adapter.put(CACHE_KEY, utf8Encode(JSON.stringify(cacheState))).catch(() => { });
2598
- }, 500);
2599
- unref(cacheTimer);
2600
- };
2601
- const flushCache = async () => {
2602
- if (!cacheTimer)
2603
- return;
2604
- clearTimeout(cacheTimer);
2605
- cacheTimer = null;
2606
- await adapter.put(CACHE_KEY, utf8Encode(JSON.stringify(cacheState))).catch(() => { });
2607
- };
2608
- saveCache();
2609
- /**
2610
- * Holds part of the space from the moment it names a keeper, and all of it
2611
- * again if it stops — once this node has caught up enough to know.
2612
- */
2613
- async function refreshHolds() {
2614
- if (!cache || closed)
2615
- return;
2616
- const next = (await access()).history.current.keepers.length > 0 || !cacheState.settled;
2617
- if (next === partial)
2618
- return;
2619
- partial = next;
2620
- // Peers learn what this node holds now; anything newly held comes across.
2621
- sync.notifyPeers(connectedPeers());
2622
- emit({ type: 'status', space: space.id });
2623
- }
2624
- /** Collections a query or a screen uses: held from now on. Whether all of them are here yet. */
2625
- function use(collections) {
2626
- if (!cache)
2627
- return true;
2628
- const now = Date.now();
2629
- let added = false;
2630
- for (const collection of collections) {
2631
- if (typeof collection !== 'string' || collection.startsWith('sys.'))
2632
- continue;
2633
- const was = cacheState.used[collection];
2634
- if (was === undefined)
2635
- added = true;
2636
- if (was === undefined || now - was > HOUR) {
2637
- cacheState.used[collection] = now;
2638
- saveCache();
2639
- }
2640
- }
2641
- if (added && partial)
2642
- sync.notifyPeers(connectedPeers());
2643
- return !partial || collections.every((c) => c.startsWith('sys.') || completeHere(c));
2644
- }
2645
- /** Level with a node holding everything once, and lacking nothing a writer's line in it names */
2646
- function completeHere(collection) {
2647
- return cacheState.level[collection] !== undefined && !(cacheState.missing[collection]?.length ?? 0);
2648
- }
2649
- /**
2650
- * Keeps track of what each writer's line in a held collection names that
2651
- * this node lacks: a version that names one not here adds it, and asks
2652
- * every peer for it; one that arrives takes itself off.
2653
- */
2654
- async function noteGap(version) {
2655
- if (!cache || !version.log || version.collection.startsWith('sys.'))
2656
- return;
2657
- const { collection } = version;
2658
- const missing = cacheState.missing[collection] ?? [];
2659
- const before = version.log.prev;
2660
- if (!before || missing.includes(before) || (await storage.getVersion(before)))
2661
- return;
2662
- cacheState.missing[collection] = [...missing, before];
2663
- sync.ask(collection, [before]);
2664
- saveCache();
2665
- // A query that said "complete" says so no longer.
2666
- if (partial)
2667
- emit({ type: 'records', space: space.id });
2668
- }
2669
- /**
2670
- * Takes versions just stored off what was missing — only once they are in
2671
- * the store, so a query never says "complete" for what it can't read yet.
2672
- */
2673
- function noteArrived(placed) {
2674
- if (!cache)
2675
- return;
2676
- let changed = false;
2677
- for (const version of placed) {
2678
- const missing = cacheState.missing[version.collection];
2679
- if (!missing?.includes(version.id))
2680
- continue;
2681
- const left = missing.filter((id) => id !== version.id);
2682
- if (left.length)
2683
- cacheState.missing[version.collection] = left;
2684
- else
2685
- delete cacheState.missing[version.collection];
2686
- changed = true;
2687
- }
2688
- if (changed)
2689
- saveCache();
2690
- }
2691
- /** A write of this node's, waiting for keepers — only on a node that may hold part of a space */
2692
- async function markPending(version) {
2693
- if (!cache || version.author !== session.did || version.collection.startsWith('sys.'))
2694
- return;
2695
- const pending = { collection: version.collection, by: [] };
2696
- await adapter.put(`${PENDING_PREFIX}${version.id}`, utf8Encode(JSON.stringify(pending)));
227
+ }, 2000);
228
+ unref(filesTimer);
2697
229
  }
2698
230
  /**
2699
- * A keeper has some of this node's pending writes: those it named, or every
2700
- * one in a collection it is level on. Once enough keepers have one, it
2701
- * stops being pending. Only keepers the space names count.
231
+ * Records changed: whatever is derived from them may have too. Given the
232
+ * versions that were placed, and none of them the space's own (`sys.`),
233
+ * only what those records feed is thrown away: who may do what, the
234
+ * definitions and the keys come from `sys.` records alone, so every other
235
+ * verdict still holds. Given nothing — another tab, a folder, new keys —
236
+ * everything is.
2702
237
  */
2703
- async function confirm(peer, which) {
2704
- if (!cache)
2705
- return;
2706
- const state = (await access()).history.current;
2707
- if (!state.keepers.some((keeper) => keeper.did === peer))
238
+ function recordsChanged(placed) {
239
+ filesChanged();
240
+ if (placed)
241
+ holding.noteArrived(placed);
242
+ index.linksChanged();
243
+ emit({ type: 'records', space: space.id });
244
+ mirrors.changed();
245
+ if (placed && placed.every((version) => !version.collection.startsWith('sys.'))) {
246
+ index.stale(placed.map((version) => version.key));
247
+ // A record waiting on a version it cites may count now.
248
+ index.stale(checks.takeWaiting());
249
+ if (checks.arrived(placed))
250
+ index.forget();
2708
251
  return;
2709
- const target = Math.min(state.keepers.length, Math.max(state.copies ?? 2, cache.copies ?? 0));
2710
- for (const name of await adapter.list(PENDING_PREFIX)) {
2711
- const id = name.slice(PENDING_PREFIX.length);
2712
- if (which.ids && !which.ids.has(id))
2713
- continue;
2714
- const bytes = await adapter.get(name);
2715
- if (!bytes)
2716
- continue;
2717
- const pending = JSON.parse(utf8Decode(bytes));
2718
- if (!isPending(pending))
2719
- continue;
2720
- if (which.collection !== undefined && pending.collection !== which.collection)
2721
- continue;
2722
- if (!pending.by.includes(peer))
2723
- pending.by.push(peer);
2724
- if (pending.by.length >= target)
2725
- await adapter.delete(name);
2726
- else
2727
- await adapter.put(name, utf8Encode(JSON.stringify(pending)));
2728
252
  }
253
+ history.changed(placed);
254
+ for (const derived of [index, catalog, profiles, keys, standing, checks])
255
+ derived.forget();
256
+ keys.keepUp();
257
+ // The access history may name keepers now, or none.
258
+ void holding.refreshHolds().catch(() => { });
259
+ // Or a new key, which someone connected may not hold.
260
+ void peers.letGoOfOutsiders().catch(() => { });
2729
261
  }
2730
- sync.on('synced', (_peer, full) => {
2731
- if (!cache || !full || cacheState.settled)
2732
- return;
2733
- // Caught up with a node holding everything: the access history here is the space's now.
2734
- cacheState.settled = true;
2735
- saveCache();
2736
- void refreshHolds().catch(() => { });
2737
- });
2738
- sync.on('stored', (peer, ids) => {
2739
- void confirm(peer, { ids: new Set(ids) }).catch(() => { });
262
+ // ─── Peers ─────────────────────────────────────────────────────────
263
+ const peers = await openPeers({
264
+ ...base,
265
+ network: deps.network,
266
+ mesh: deps.mesh,
267
+ meeting,
268
+ history,
269
+ keys,
270
+ holds: holding.holds,
271
+ files,
272
+ emit,
273
+ statusChanged,
274
+ admit,
275
+ recordsChanged,
276
+ filesChanged,
277
+ onArrived: deps.onArrived,
2740
278
  });
2741
- sync.on('level', (peer, collection, full) => {
2742
- // What a line names and is not here yet: asked again, of whoever holds it now.
2743
- const missing = cacheState.missing[collection];
2744
- if (cache && missing?.length)
2745
- sync.ask(collection, missing);
2746
- if (cache && full && cacheState.level[collection] === undefined) {
2747
- cacheState.level[collection] = Date.now();
2748
- saveCache();
2749
- // A query that said "not complete" says so no longer.
2750
- if (partial)
2751
- emit({ type: 'records', space: space.id });
2752
- }
2753
- void confirm(peer, { collection }).catch(() => { });
279
+ // Whether to hold part of the space is settled before the first hello says what this node holds.
280
+ await holding.refreshHolds().catch(() => { });
281
+ peers.connect();
282
+ mirrors.watch();
283
+ // Here and not earlier: it registers sync handlers and starts timers that need the network connected.
284
+ holding.start();
285
+ const membership = createMembership({
286
+ ...base,
287
+ networked: !!deps.network,
288
+ history,
289
+ keys,
290
+ lines,
291
+ writing,
292
+ peers,
293
+ meeting,
294
+ flagged: warrants.flagged,
295
+ onJoined: deps.onJoined,
2754
296
  });
2755
- /**
2756
- * Drops collections no query has touched for a while: their records go,
2757
- * and they are no longer held. Never one the app declared, nor one holding
2758
- * a write still waiting for keepers.
2759
- */
2760
- async function dropUnused() {
2761
- if (!cache || !partial || closed)
2762
- return;
2763
- const cutoff = Date.now() - (cache.unusedAfterDays ?? 30) * DAY;
2764
- const waiting = new Set();
2765
- for (const name of await adapter.list(PENDING_PREFIX)) {
2766
- const bytes = await adapter.get(name);
2767
- const pending = bytes ? JSON.parse(utf8Decode(bytes)) : null;
2768
- if (isPending(pending))
2769
- waiting.add(pending.collection);
2770
- }
2771
- let dropped = false;
2772
- for (const [collection, at] of Object.entries(cacheState.used)) {
2773
- if (at > cutoff || declared.has(collection) || waiting.has(collection))
2774
- continue;
2775
- // No longer held first, so nothing syncs it back while it goes.
2776
- delete cacheState.used[collection];
2777
- delete cacheState.level[collection];
2778
- delete cacheState.missing[collection];
2779
- for (const item of (await storage.items(collection)).items)
2780
- await storage.removeVersion(cidOfDigest(item.id));
2781
- dropped = true;
2782
- }
2783
- if (!dropped)
2784
- return;
2785
- saveCache();
2786
- recordsChanged();
2787
- sync.notifyPeers(connectedPeers());
2788
- }
2789
- // When the app opens the space, then every few hours while it stays open.
2790
- const dropTimer = cache ? setInterval(() => void dropUnused().catch(() => { }), 6 * HOUR) : null;
2791
- const tidying = cache ? dropUnused().catch(() => { }) : Promise.resolve();
2792
- unref(dropTimer);
2793
- /** Why this account cannot write here at all, or null when it can */
2794
- async function cannotWrite() {
2795
- const { history } = await access();
2796
- if (isMember(history.current, deps.rootDid))
2797
- return null;
2798
- return waitingInvite
2799
- ? `You've joined "${space.name}", but its invite hasn't reached this device yet — connect to someone in the space first`
2800
- : `"${space.name}" was shared with you to view — you can't change it`;
2801
- }
2802
- /**
2803
- * The heads a new version names: all of them, or past what a version may
2804
- * name, first those its own standing rests on (its author's place, its
2805
- * role, its collection's definition), then the latest applied. Naming fewer
2806
- * is safe: what it leaves out it is judged as not having seen (03 §3.2).
2807
- */
2808
- async function seenFor(history, collection) {
2809
- const roles = rolesOf(history.current, deps.rootDid);
2810
- const mine = [
2811
- await removalKey(deps.rootDid),
2812
- await stepDownKey(deps.rootDid),
2813
- ...(await Promise.all(roles.map((role) => assignKey(deps.rootDid, role)))),
2814
- ...roles.map(roleKey),
2815
- `collection:${collection}`,
2816
- ];
2817
- return history.headsFor(mine, MAX_SEEN);
2818
- }
2819
- /** Signs and stores one version. A delete carries no body. */
2820
- async function write(collection, body, version, deleted = false, links = [], options = {}) {
2821
- const writer = options.as ?? session;
2822
- const asAccount = deps.accountOnly || aboutItself(collection, body, deps.rootDid, writer.did);
2823
- if (asAccount && !actsForAccount(writer.proof()))
2824
- throw new Error(NOT_ACCOUNT);
2825
- // Every peer would ignore it (see buildEvent); say why here instead.
2826
- if (ACCESS_COLLECTIONS.has(collection) &&
2827
- !noteGrants(writer.proof(), accessRequirement(space.id, collection, version.key))) {
2828
- throw new Error(collection === CATALOG_COLLECTION ? CANNOT_DEFINE : CANNOT_CHANGE_ACCESS);
2829
- }
2830
- // Every other copy would refuse it, so refuse it here rather than show a
2831
- // change that exists on this device alone.
2832
- if (!options.joining) {
2833
- const problem = await cannotWrite();
2834
- if (problem)
2835
- throw new Error(problem);
2836
- }
2837
- let payload = null;
2838
- let tags = [];
2839
- // The files the body refers to, named on the outside so keepers fetch and keep them.
2840
- const named = deleted ? [] : fileRefsIn(body);
2841
- if (named.length > MAX_FILES)
2842
- throw new Error(`A record names at most ${MAX_FILES} files`);
2843
- if (!deleted) {
2844
- // Refused here, where the writer can fix it. On arrival a misfit is kept
2845
- // and flagged instead — see `conforms`.
2846
- const issues = await contentIssues(collection, body, links);
2847
- if (issues?.length) {
2848
- throw new Error(`Not a valid ${collection}: ${issues.map((i) => (i.path === '/' ? i.message : `${i.path} ${i.message}`)).join('; ')}`);
2849
- }
2850
- // Encrypt *before* signing: peers without the key still verify the
2851
- // signature and relay the record, they just cannot read it.
2852
- payload = body;
2853
- if (space.visibility === 'private' && !IN_THE_CLEAR.has(collection)) {
2854
- // Always the key the history names now: one someone removed still holds would do nothing.
2855
- const key = currentKey((await access()).history.current);
2856
- if (!key) {
2857
- throw new Error(keyring.size
2858
- ? `The key of "${space.name}" changed, and the new one hasn't reached this device yet — connect to someone in the space first`
2859
- : 'This private space has no key on this node');
2860
- }
2861
- // Body and links sealed together: a relay learns neither.
2862
- const content = links.length ? { body, links } : { body };
2863
- payload = await sealBody(content, key, { space: space.id, collection, key: version.key });
2864
- }
2865
- // Worked out from the body, with the key it is sealed with: what every reader will check.
2866
- const topics = collection.startsWith('sys.')
2867
- ? []
2868
- : ((await catalog()).get(collection)?.definition.topics ?? []);
2869
- if (topics.length) {
2870
- const sealedWith = looksEncrypted(payload) ? sealedKeyId(payload) : null;
2871
- const key = tagKey(sealedWith);
2872
- if (key)
2873
- tags = await tagsFor(await key, collection, topics, body, links);
2874
- }
2875
- }
2876
- // Whether superseded versions are kept is the writer's decision, carried
2877
- // on the version — never each reader's, or nodes that had seen different
2878
- // definitions would store different things and never converge. The access
2879
- // history keeps everything: it is replayed whole. A first version under
2880
- // `onePer` or `fixed` is kept whole, because those rules are checked against it.
2881
- const definition = (await catalog()).get(collection)?.definition;
2882
- const retain = ACCESS_COLLECTIONS.has(collection) ||
2883
- // Proof read back whole after anything written over it (\`flagged\`).
2884
- collection === WARRANT_COLLECTION ||
2885
- collection === PROFILE_COLLECTION ||
2886
- collection === BOX_COLLECTION ||
2887
- collection === MEMBER_KEY_COLLECTION ||
2888
- definition?.history === 'all' ||
2889
- (version.seq === 0 && !!(definition?.rules?.onePer || definition?.rules?.fixed)) ||
2890
- // Every version under a contract: it reads the one before, and others cite it.
2891
- (!deleted && hasContract(definition?.contract));
2892
- // The next place in this key's line for the collection: given back if the version is refused below.
2893
- const signed = await deps.writers.append(writer.did, space.id, collection, async (log) => {
2894
- const { history, events: held } = await access();
2895
- const seen = await seenFor(history, collection);
2896
- // Checks in force as of the very point it names: a definition arriving meanwhile can't leave it unkept.
2897
- const checkedThen = (() => {
2898
- const then = history.at(seen);
2899
- return then ? rulesAt(then, collection) : null;
2900
- })();
2901
- const then = await checkedThen;
2902
- const keep = retain || (!deleted && hasContract(then?.contract));
2903
- const made = await signer.sign(createVersion({
2904
- author: writer.did,
2905
- collection,
2906
- space: space.id,
2907
- body: payload,
2908
- proof: writer.proof(),
2909
- version,
2910
- retain: keep,
2911
- deleted,
2912
- seen,
2913
- // In the clear only where the body is: a private space sealed them above.
2914
- ...(space.visibility === 'public' && !deleted && links.length ? { links } : {}),
2915
- ...(tags.length ? { tags } : {}),
2916
- ...(named.length ? { files: named } : {}),
2917
- log,
2918
- }), writer.key);
2919
- // The same verdict every other peer will reach: refused here, with the reason, rather than there.
2920
- const judged = await judge(made);
2921
- if (!judged.verified)
2922
- throw new Error(judged.reason ?? 'This key may not write here.');
2923
- if (ACCESS_COLLECTIONS.has(collection)) {
2924
- const event = await toEvent(made);
2925
- if (!event)
2926
- throw new Error('That is not a well-formed change to who may do what');
2927
- const status = (history.extend(event) ?? replayAccess(accessGenesis, [...held, event])).status(event.id);
2928
- if (status?.status !== 'applied')
2929
- throw new Error(status?.status === 'dropped' ? status.reason : 'That change could not be made');
2930
- }
2931
- else {
2932
- const stands = await standingOf(made);
2933
- // Taken away by a change to its rules that came in after it saw the history: try again.
2934
- if (!stands.ok && stands.withdrawn)
2935
- throw Object.assign(new Error(stands.reason), { rulesMoved: true });
2936
- if (!stands.ok)
2937
- throw new Error(stands.reason);
2938
- // Its checks, here, before anyone else sees it: peers would keep it, but no reader would count it.
2939
- const passes = await checksOf(made);
2940
- if ('pending' in passes)
2941
- throw new Error('Versions it cites have not arrived yet');
2942
- if ('unjudged' in passes)
2943
- throw new Error(passes.unjudged);
2944
- if (passes.passes === false)
2945
- throw new Error(passes.reason);
2946
- }
2947
- return made;
2948
- });
2949
- await storage.addVersion(signed);
2950
- await placeInLog(signed);
2951
- await markPending(signed);
2952
- channel?.postMessage('changed');
2953
- sync.onLocalChange(signed);
2954
- recordsChanged([signed]);
2955
- return signed;
2956
- }
2957
- /**
2958
- * How a record's newest version that stands fares under its checks: kept and
2959
- * synced by every peer either way, counted by a reader only when it passes.
2960
- */
2961
- async function contractsFor(recordKey, versionId) {
2962
- // A version named is judged even when the history leaves it out (a superseded delete, say).
2963
- const named = versionId !== undefined ? await storage.getVersion(versionId) : null;
2964
- const candidates = versionId === undefined ? await storage.history(recordKey) : named?.key === recordKey ? [named] : [];
2965
- for (const version of candidates) {
2966
- if (isStub(version))
2967
- continue;
2968
- // One named whose first version hasn't arrived waits for it.
2969
- if (!(await consistent(version))) {
2970
- if (versionId !== undefined && version.seq > 0)
2971
- return { version: version.id, passes: null, pending: true };
2972
- continue;
2973
- }
2974
- const stands = await standingOf(version);
2975
- // One named that waits for what it follows is pending, as a contract waiting on what it cites.
2976
- if (!stands.ok && stands.later && versionId !== undefined)
2977
- return { version: version.id, passes: null, pending: true };
2978
- if (!stands.ok)
2979
- continue;
2980
- const verdict = await checksOf(version);
2981
- if ('pending' in verdict)
2982
- return { version: version.id, passes: null, pending: true };
2983
- if ('unjudged' in verdict)
2984
- return { version: version.id, passes: null, unjudged: true, reason: verdict.unjudged };
2985
- return { version: version.id, ...verdict };
2986
- }
2987
- return null;
2988
- }
2989
- async function get(recordKey) {
2990
- const current = await currentOf(recordKey);
2991
- return current && !current.deleted ? view(current) : null;
2992
- }
2993
- /** The live current version of a record, or a clear error. */
2994
- async function requireLive(recordKey) {
2995
- const current = await currentOf(recordKey);
2996
- if (!current || current.deleted)
2997
- throw new Error(`No record ${recordKey} in this space`);
2998
- return current;
2999
- }
3000
- /**
3001
- * The fields for writing a key again: the version after the one that counts.
3002
- * Where the store's newest version fails its checks, after the newest that
3003
- * counts, or afresh as a first version when none does: a version that fails
3004
- * can't make others build on it, or claim a key (a `onePer` key) for good.
3005
- * Otherwise after whatever the store holds, counted or not.
3006
- */
3007
- async function after(recordKey) {
3008
- const held = await storage.getCurrent(recordKey);
3009
- if (!held)
3010
- return { key: recordKey, seq: 0 };
3011
- const verdict = (await standingOf(held)).ok ? await checksOf(held) : NO_CHECKS;
3012
- // One that fails its checks, or waits for ever on what it cites, can't hold the key.
3013
- if ('passes' in verdict && verdict.passes !== false)
3014
- return nextVersion(held);
3015
- // Waiting only for its own step before: continue it, rather than fork this record.
3016
- if ('pending' in verdict && held.prev && !(await storage.getVersion(held.prev)))
3017
- return nextVersion(held);
3018
- const counted = await currentOf(recordKey);
3019
- return counted ? nextVersion(counted) : { key: recordKey, seq: 0 };
3020
- }
3021
- async function writeFirst(collection, body, recordKey, links, as) {
3022
- const current = await currentOf(recordKey);
3023
- if (current && !current.deleted)
3024
- throw new Error(`A record ${recordKey} already exists — update it instead`);
3025
- // Writing a key that was deleted brings it back: the next version after the delete.
3026
- return write(collection, body, await after(recordKey), false, links, as ? { as } : {});
3027
- }
3028
- async function upsert(collection, recordKey, body, options = {}) {
3029
- return view(await write(collection, body, await after(recordKey), false, [], options));
3030
- }
3031
- async function removeKey(recordKey, as) {
3032
- const current = await requireLive(recordKey);
3033
- await write(current.collection, null, await after(current.key), true, [], as ? { as } : {});
3034
- }
3035
- const guard = (collection) => {
3036
- if (MANAGED.has(collection))
3037
- throw new Error(`${collection} is written by the node itself`);
3038
- };
3039
- // ─── Writers' logs ─────────────────────────────────────────────────
3040
- //
3041
- // A key's writes in each collection here form one line (02 §4.10). Each
3042
- // place a key took is remembered by the version that took it, so a second
3043
- // version at the same place is found the moment it arrives. And each
3044
- // version is checked against the one it names as the place before — when it
3045
- // arrives, or when that one does. Either way the proof goes to everyone else.
3046
- // Named for this format of the log: the `log/`, `next/`, `clog/` and
3047
- // `cnext/` a node kept before it map places to versions no peer holds any
3048
- // more, so they are left unread rather than trusted.
3049
- /** `place/<author>/<collection>/<n>` → the id of the version that took that place */
3050
- const LOG_PREFIX = 'place/';
3051
- /** Key DID → the account it writes for here */
3052
- const KEY_ROOT_PREFIX = 'keyroot/';
3053
- /** `follows/<id>` → the id of a version naming that one as the place before it */
3054
- const NEXT_PREFIX = 'follows/';
3055
- async function placeInLog(version) {
3056
- if (version.space !== space.id || !version.log)
3057
- return;
3058
- const { log } = version;
3059
- // Which account each key writes for: what a cutoff is worked out from.
3060
- const root = (await judge(version)).root;
3061
- // Only an account a valid note names: a key whose note failed falls back to itself, and isn't anyone's.
3062
- if (root &&
3063
- (root !== version.author || !version.proof) &&
3064
- !(await adapter.get(`${KEY_ROOT_PREFIX}${version.author}`)))
3065
- await adapter.put(`${KEY_ROOT_PREFIX}${version.author}`, utf8Encode(root));
3066
- // Its place: a second version there is a fork.
3067
- const at = `${LOG_PREFIX}${version.author}/${version.collection}/${log.n}`;
3068
- const held = await adapter.get(at);
3069
- if (!held)
3070
- await adapter.put(at, utf8Encode(version.id));
3071
- else if (utf8Decode(held) !== version.id) {
3072
- const first = await storage.getVersion(utf8Decode(held));
3073
- if (first)
3074
- void reportFork(first, version, version.author, version.collection, log.n).catch(() => { });
3075
- }
3076
- // The place before it, if held, must be its key's; and so must it be for whatever names it.
3077
- if (log.prev) {
3078
- await adapter.put(`${NEXT_PREFIX}${log.prev}`, utf8Encode(version.id));
3079
- const previous = await storage.getVersion(log.prev);
3080
- if (previous && breaksLine(version, previous))
3081
- void reportFork(version, previous, version.author, version.collection, log.n).catch(() => { });
3082
- }
3083
- const naming = await adapter.get(`${NEXT_PREFIX}${version.id}`);
3084
- const next = naming ? await storage.getVersion(utf8Decode(naming)) : null;
3085
- if (next?.log && breaksLine(next, version))
3086
- void reportFork(next, version, next.author, next.collection, next.log.n).catch(() => { });
3087
- await noteGap(version);
3088
- }
3089
- /**
3090
- * Hands every peer the proof that a key's line for a collection is not one
3091
- * line — a fork or a break — unless a proof at or before this place stands
3092
- * already. Any member may; one whose note doesn't let it change access
3093
- * leaves it to one whose note does.
3094
- */
3095
- async function reportFork(a, b, writer, collection, from) {
3096
- if (closed)
3097
- return;
3098
- const known = (await access()).history.forked(writer, collection);
3099
- if (known && known.from <= from)
3100
- return;
3101
- if (!noteGrants(session.proof(), accessRequirement(space.id, FORK_COLLECTION, await forkKey(writer))) ||
3102
- (await cannotWrite()))
3103
- return;
3104
- await upsert(FORK_COLLECTION, await forkKey(writer), forkProof(a, b));
3105
- }
3106
- /**
3107
- * Runs a write once more when its collection's rules changed while it was
3108
- * being made — it saw the history before the change, so the change takes
3109
- * it away (03 §5.2) — this time under the new rules: a key they derive,
3110
- * what they keep whole, all worked out again.
3111
- */
3112
- async function underCurrentRules(run) {
3113
- try {
3114
- return await run();
3115
- }
3116
- catch (error) {
3117
- if (!(isRecord(error) && error.rulesMoved === true))
3118
- throw error;
3119
- return run();
3120
- }
3121
- }
3122
- async function putOnce(collection, body, options) {
3123
- guard(collection);
3124
- if (options.key !== undefined && !RECORD_KEY_PATTERN.test(options.key)) {
3125
- throw new Error('A record key is 1–128 characters of a–z, 0–9 and : . _ -');
3126
- }
3127
- const links = options.links ?? [];
3128
- // One per something: the key is derived from it, so writing again is the next version of the same record.
3129
- const onePer = (await catalog()).get(collection)?.definition.rules?.onePer;
3130
- if (onePer && options.key === undefined) {
3131
- const derived = await derivedKey(collection, onePer, { root: deps.rootDid, links, body });
3132
- if (!derived)
3133
- throw new Error(`${collection} is one per ${onePer.join(' + ')} — give it every one of those`);
3134
- await keepsCollection(derived, collection);
3135
- return view(await write(collection, body, await after(derived), false, links, options.as ? { as: options.as } : {}));
3136
- }
3137
- const recordKey = await keyToWrite(collection, options.key, onePer);
3138
- return view(await writeFirst(collection, body, recordKey, links, options.as));
3139
- }
3140
- /**
3141
- * Where a new record goes: a fresh key of this account's, or the key the
3142
- * caller names. A name is put in this account's namespace (`profile` →
3143
- * `<owner>.profile`); a key this account already owns is taken as it is.
3144
- * Not a `one:` key outside a `onePer` collection, which every peer refuses
3145
- * (02 §7.3), nor a key this node holds a record of another collection at.
3146
- */
3147
- async function keyToWrite(collection, chosen, onePer) {
3148
- if (chosen === undefined)
3149
- return newRecordKey(deps.rootDid);
3150
- let recordKey;
3151
- if (await ownsKey(chosen, deps.rootDid))
3152
- recordKey = chosen;
3153
- else if (keyKind(chosen) === 'owned')
3154
- throw new Error(`${chosen} belongs to another account`);
3155
- else
3156
- recordKey = keyKind(chosen) === 'shared' ? chosen : await ownedKey(deps.rootDid, chosen);
3157
- if (onePerForm(recordKey) && !onePer)
3158
- throw new Error(`${recordKey} is a onePer key, and ${collection} has no onePer`);
3159
- await keepsCollection(recordKey, collection);
3160
- return recordKey;
3161
- }
3162
- /**
3163
- * Refuses a write at a key this node holds a record of another collection
3164
- * at. Keys are unique in a space, and a record keeps its collection for
3165
- * life (02 §4.1, §4.2), so the write could only be refused, or continue the
3166
- * other record's chain.
3167
- */
3168
- async function keepsCollection(recordKey, collection) {
3169
- const held = (await currentOf(recordKey)) ?? (await storage.getCurrent(recordKey));
3170
- if (held && held.collection !== collection)
3171
- throw new Error(`${recordKey} already holds a ${held.collection} record, and a key keeps its collection for life: ` +
3172
- `choose a name that includes the collection`);
3173
- }
3174
- /** Whether a version's account is one the space has known: only those can be warranted, so a stranger minting keys costs nobody a write */
3175
- async function accountable(version) {
3176
- const verdict = await judge(version);
3177
- if (!verdict.verified || !verdict.root || version.space !== space.id)
3178
- return null;
3179
- return (await access()).history.named(verdict.root) ? verdict.root : null;
3180
- }
3181
- /** Views already replayed, by the changes they hold: a set of ids always replays to the same state */
3182
- const views = new Map();
3183
- const MAX_VIEWS = 256;
3184
- /**
3185
- * The access state a writer had when it signed: the changes it names as
3186
- * seen and everything they saw, replayed alone. Unlike `history.at`, no
3187
- * change outside them — a rival that arrives late, or a change made later —
3188
- * can alter it, so a verdict on misconduct judged by it is final. Null
3189
- * while one of them hasn't arrived.
3190
- */
3191
- async function ownView(seen) {
3192
- const cacheKey = [...new Set(seen)].sort().join(',');
3193
- const known = views.get(cacheKey);
3194
- if (known)
3195
- return known;
3196
- const { events } = await access();
3197
- const byId = new Map(events.map((event) => [event.id, event]));
3198
- const cut = [];
3199
- const visited = new Set([accessGenesis.id]);
3200
- const waiting = [...seen];
3201
- while (waiting.length > 0) {
3202
- const id = waiting.pop();
3203
- if (visited.has(id))
3204
- continue;
3205
- visited.add(id);
3206
- const event = byId.get(id);
3207
- if (!event)
3208
- return null;
3209
- cut.push(event);
3210
- waiting.push(...event.seen);
3211
- }
3212
- const state = replayAccess(accessGenesis, cut).current;
3213
- if (views.size >= MAX_VIEWS)
3214
- views.delete(views.keys().next().value);
3215
- views.set(cacheKey, state);
3216
- return state;
3217
- }
3218
- /** Whether a version broke a rule of its standing, as of what it had seen: no place, or `who` or `final` against it */
3219
- async function standingBroken(version, root) {
3220
- const state = await ownView(version.seen ?? []);
3221
- if (!state)
3222
- return 'later';
3223
- return standingBrokenIn(state, version, root);
3224
- }
3225
- /** The same check, in a given state */
3226
- async function standingBrokenIn(state, version, root) {
3227
- if (!isMember(state, root))
3228
- return 'holds';
3229
- if (version.collection.startsWith('sys.'))
3230
- return 'false';
3231
- const found = await rulesAt(state, version.collection);
3232
- if (found?.rules.final && version.seq > 0)
3233
- return 'holds';
3234
- // An edit's grant may rest on whose record it is; only a first version is judged here.
3235
- if (version.seq !== 0)
3236
- return 'false';
3237
- const needs = await needsOf(version, version, root);
3238
- return needs(state) ? 'false' : 'holds';
3239
- }
3240
- /** Whether proof of one kind holds: the offending version first, then what checking it needs */
3241
- async function evidenceHolds(kind, evidence) {
3242
- // A kind this peer doesn't know flags nobody.
3243
- if (!knownKind(kind))
3244
- return 'false';
3245
- const [offending, context] = evidence;
3246
- if (!offending || !(await accountable(offending)))
3247
- return 'false';
3248
- const root = (await judge(offending)).root;
3249
- switch (kind) {
3250
- case 'chain': {
3251
- if (!context || 'body' in offending || 'body' in context)
3252
- return 'false';
3253
- if (!(await judge(context)).verified || context.id !== offending.prev)
3254
- return 'false';
3255
- return chainProblem(offending, context) ? 'holds' : 'false';
3256
- }
3257
- case 'standing':
3258
- if (context ||
3259
- 'body' in offending ||
3260
- ACCESS_COLLECTIONS.has(offending.collection) ||
3261
- offending.collection === WARRANT_COLLECTION)
3262
- return 'false';
3263
- return standingBroken(offending, root);
3264
- case 'access': {
3265
- if (context || !ACCESS_COLLECTIONS.has(offending.collection) || !('body' in offending))
3266
- return 'false';
3267
- const event = await buildEvent(offending);
3268
- if (!event)
3269
- return 'false';
3270
- const state = await ownView(event.seen);
3271
- if (!state)
3272
- return 'later';
3273
- return refusal(event, state) ? 'holds' : 'false';
3274
- }
3275
- }
3276
- }
3277
- /** Whether a warrant record proves what it says, against the account its key names, and is its writer's own */
3278
- async function warrantVerdict(version) {
3279
- const cacheKey = copyKey(version);
3280
- const known = judgedWarrants.get(cacheKey);
3281
- if (known)
3282
- return known;
3283
- const warrant = await warrantShape(version);
3284
- if (warrant === 'unnamed')
3285
- return 'false';
3286
- const verdict = warrant ? await evidenceHolds(warrant.kind, warrant.evidence) : 'false';
3287
- // Judged in the offending version's own view, a proof that holds, or fails, always will.
3288
- if (verdict === 'holds' || verdict === 'false')
3289
- judgedWarrants.set(cacheKey, verdict);
3290
- return verdict;
3291
- }
3292
- /** Warrants already judged: each checked once, not on every look at who is flagged */
3293
- const judgedWarrants = new Map();
3294
- /**
3295
- * A warrant's body, if the version has a warrant's shape: a first version
3296
- * of `std.warrant`, not a delete, and not against its writer. Anything else
3297
- * flags nobody.
3298
- */
3299
- async function warrantShape(version) {
3300
- if (version.deleted || version.seq !== 0 || version.collection !== WARRANT_COLLECTION)
3301
- return null;
3302
- const warrant = readWarrant((await openBody(version)).body);
3303
- const offending = warrant?.evidence[0];
3304
- if (!warrant || !offending || !(await judge(offending)).verified)
3305
- return null;
3306
- // The one answer that can change: the account may be named once more of the history arrives.
3307
- const against = await accountable(offending);
3308
- if (!against)
3309
- return 'unnamed';
3310
- const by = (await judge(version)).root;
3311
- return by && against !== by ? warrant : null;
3312
- }
3313
- /** The proof a version gives against its account, or null when it gives none */
3314
- async function violationIn(version) {
3315
- const root = await accountable(version);
3316
- if (!root)
3317
- return null;
3318
- if (version.seq > 0 && version.prev) {
3319
- const previous = await storage.getVersion(version.prev);
3320
- if (previous && chainProblem(version, previous))
3321
- return { kind: 'chain', evidence: [stubOf(version), stubOf(previous)] };
3322
- }
3323
- if (ACCESS_COLLECTIONS.has(version.collection)) {
3324
- const event = await buildEvent(version);
3325
- const quick = event && (await access()).history.at(event.seen);
3326
- if (!event || (quick && !refusal(event, quick)))
3327
- return null;
3328
- return (await evidenceHolds('access', [version])) === 'holds'
3329
- ? { kind: 'access', evidence: [version] }
3330
- : null;
3331
- }
3332
- // A warrant is a record like any other: a false one flags nobody, and proves nothing against its writer.
3333
- if (version.collection === WARRANT_COLLECTION)
3334
- return null;
3335
- // The global view first, which is cheap; the own view, a replay, only for what it finds broken.
3336
- // Proof only the own view would show goes unwritten: a flag missed, never a false one.
3337
- const quick = (await access()).history.at(version.seen ?? []);
3338
- if (quick && (await standingBrokenIn(quick, version, root)) !== 'holds')
3339
- return null;
3340
- return (await standingBroken(version, root)) === 'holds'
3341
- ? { kind: 'standing', evidence: [stubOf(version)] }
3342
- : null;
3343
- }
3344
- /**
3345
- * Writes down, as this account's own record, the proof a version gives
3346
- * against its account — unless a warrant of its own against that account
3347
- * stands already, so one account's misconduct costs each member one record
3348
- * at a time. It doesn't lean on anyone else's warrant, which would go if
3349
- * its writer were removed. One that can't write leaves it to one that can.
3350
- */
3351
- async function warrantIfDue(version) {
3352
- if (closed || (await cannotWrite()))
3353
- return;
3354
- // Only an account the history names can be warranted: anything else stops here, for free.
3355
- const root = await accountable(version);
3356
- if (!root || root === deps.rootDid)
3357
- return;
3358
- // With a warrant of its own against that account standing, its next offences cost nothing to look at.
3359
- if ((await flagged()).some((flag) => flag.account === root && flag.by === deps.rootDid))
3360
- return;
3361
- const violation = await violationIn(version);
3362
- // Taken only once there is something to write, so a decoy can't hide an offence behind it.
3363
- if (!violation || warranting.has(root))
3364
- return;
3365
- warranting.add(root);
3366
- try {
3367
- if (!(await flagged()).some((flag) => flag.account === root && flag.by === deps.rootDid))
3368
- await warrantOnce(violation);
3369
- }
3370
- finally {
3371
- warranting.delete(root);
3372
- }
3373
- }
3374
- /** Accounts this node is writing a warrant against now: offences that arrive meanwhile wait for the next */
3375
- const warranting = new Set();
3376
- async function warrantOnce(violation) {
3377
- // Checked again: the space may have closed while the proof was being worked out.
3378
- if (closed)
3379
- return;
3380
- await upsert(WARRANT_COLLECTION, await newRecordKey(deps.rootDid), violation);
3381
- }
3382
- /** The accounts proven to have broken the protocol's rules here, by the warrants that stand */
3383
- async function flagged() {
3384
- const found = [];
3385
- // Each warrant's first version, kept whole, whatever came after it: like any record, anyone
3386
- // may write a later version or a delete, and neither takes the proof back.
3387
- const firsts = [];
3388
- for (const current of await storage.queryVersions(WARRANT_COLLECTION))
3389
- for (const version of await storage.history(current.key))
3390
- if (version.seq === 0 && version.collection === WARRANT_COLLECTION)
3391
- firsts.push(version);
3392
- for (const version of firsts) {
3393
- if (version.deleted || isStub(version) || !(await standingOf(version)).ok)
3394
- continue;
3395
- // Only proof this peer checked: one that stands unjudged, for want of rules it can't read, flags nobody.
3396
- if ((await warrantVerdict(version)) !== 'holds')
3397
- continue;
3398
- const warrant = readWarrant((await openBody(version)).body);
3399
- const offending = warrant?.evidence[0];
3400
- const account = offending && (await accountable(offending));
3401
- if (!warrant || !offending || !account || !knownKind(warrant.kind))
3402
- continue;
3403
- const by = (await judge(version)).root ?? version.author;
3404
- // One flag per offence and writer, however many records say it.
3405
- if (found.some((flag) => flag.offence === offending.id && flag.by === by))
3406
- continue;
3407
- found.push({ account, key: offending.author, kind: warrant.kind, by, offence: offending.id });
3408
- }
3409
- return found;
3410
- }
3411
- /** Display order: when a record was created, then its key. It decides nothing. */
3412
- const createdAtOf = async (version) => (await genesisOf(version))?.createdAt ?? version.createdAt;
3413
- /**
3414
- * Assigns a role to an account, or with `assigned: false` takes it away:
3415
- * one's own, to leave it. Taking a role leaves what this node has seen
3416
- * them write in it standing.
3417
- */
3418
- async function assign(did, role, assigned) {
3419
- const { history } = await access();
3420
- if (!history.current.roles.has(role))
3421
- throw new Error(`There is no role "${role}" in "${space.name}"`);
3422
- const takes = !assigned && rolesOf(history.current, did).includes(role);
3423
- const cutoff = takes ? await cutoffFor(did) : {};
3424
- const written = await upsert(ASSIGN_COLLECTION, await assignKey(did, role), {
3425
- did,
3426
- role,
3427
- assigned,
3428
- ...(Object.keys(cutoff).length ? { cutoff } : {}),
3429
- });
3430
- await changeKeyNow();
3431
- return written;
3432
- }
3433
- /** Removes an account from the space, every role it holds with it: one's own, to leave */
3434
- async function removeAccount(did) {
3435
- const { history } = await access();
3436
- if (!isMember(history.current, did))
3437
- throw new Error(`They hold no place in "${space.name}"`);
3438
- const cutoff = await cutoffFor(did);
3439
- const written = await upsert(REMOVE_COLLECTION, await removalKey(did), {
3440
- did,
3441
- ...(Object.keys(cutoff).length ? { cutoff } : {}),
3442
- });
3443
- await changeKeyNow();
3444
- return written;
3445
- }
3446
- /** What this account is here, for listing: `founder`, a role it holds, or null */
3447
- function placeOf(state, did) {
3448
- if (state.founders.has(did))
3449
- return FOUNDER;
3450
- return rolesOf(state, did)[0] ?? null;
3451
- }
3452
- /**
3453
- * A change that took someone's place makes a new key due. The node that
3454
- * made it changes the key before the call returns, not later in the
3455
- * background: one that closes straight after a removal would otherwise
3456
- * leave the removed member reading everything written since.
3457
- */
3458
- async function changeKeyNow() {
3459
- if (space.visibility === 'private' && (await access()).history.current.keyDue)
3460
- await keepingUp();
3461
- }
3462
- /**
3463
- * What a change taking power from an account leaves standing: for each of
3464
- * its keys and each collection, the end of the unbroken line this node
3465
- * holds of that key's versions in that collection, from its first place,
3466
- * each naming the one before. A place held past a gap covers nothing, so
3467
- * one planted far ahead can't cover what its writer signs after; and a node
3468
- * holding some collections keeps their lines whole (05 §9), so it covers
3469
- * all it holds.
3470
- */
3471
- async function cutoffFor(did, only) {
3472
- const cutoff = {};
3473
- // At most what a change may carry: what is left out is judged with the change.
3474
- for (const end of (await linesOf(did, only)).slice(0, MAX_CUTOFF))
3475
- (cutoff[end.author] ??= {})[end.collection] = end.log.n;
3476
- return cutoff;
3477
- }
3478
- /**
3479
- * The ends of an account's unbroken lines this node holds: defined
3480
- * collections first, then the rest, each in name order.
3481
- */
3482
- async function linesOf(did, only) {
3483
- // What it holds of theirs, whatever way it came: the lines' places are kept only for what arrived by sync.
3484
- const placed = new Map();
3485
- const add = (version) => {
3486
- if (!version.log)
3487
- return;
3488
- const line = `${version.author} ${version.collection}`;
3489
- const held = placed.get(line) ?? new Map();
3490
- if (!held.has(version.log.n))
3491
- held.set(version.log.n, version);
3492
- placed.set(line, held);
3493
- };
3494
- for (const version of await everyCurrent()) {
3495
- if (!version.log || (only && version.author !== only) || version.space !== space.id)
3496
- continue;
3497
- if ((await judge(version)).root === did)
3498
- add(version);
3499
- }
3500
- for (const name of await adapter.list(KEY_ROOT_PREFIX)) {
3501
- const key = name.slice(KEY_ROOT_PREFIX.length);
3502
- if ((only && key !== only) || utf8Decode((await adapter.get(name)) ?? new Uint8Array()) !== did)
3503
- continue;
3504
- for (const place of await adapter.list(`${LOG_PREFIX}${key}/`)) {
3505
- const id = await adapter.get(place);
3506
- const version = id ? await storage.getVersion(utf8Decode(id)) : null;
3507
- if (version?.author === key)
3508
- add(version);
3509
- }
3510
- }
3511
- const ends = [];
3512
- for (const held of placed.values()) {
3513
- let end = null;
3514
- for (let n = 0;; n++) {
3515
- const version = held.get(n);
3516
- if (!version || (n > 0 && version.log?.prev !== end?.id))
3517
- break;
3518
- end = version;
3519
- }
3520
- if (end)
3521
- ends.push(end);
3522
- }
3523
- // Defined collections first: writing into many undefined ones costs only whoever did.
3524
- const defined = new Set((await catalog()).keys());
3525
- return ends.sort((a, b) => Number(defined.has(b.collection)) - Number(defined.has(a.collection)) ||
3526
- (a.collection < b.collection ? -1 : a.collection > b.collection ? 1 : a.author < b.author ? -1 : 1));
3527
- }
3528
- /** Whether this account holds a grant, now, to do something to a record */
3529
- async function mayNow(collection, action, first) {
3530
- const { history } = await access();
3531
- const state = history.current;
3532
- if (!isMember(state, deps.rootDid))
3533
- return false;
3534
- if (collection.startsWith('sys.'))
3535
- return true;
3536
- const found = await rulesAt(state, collection);
3537
- if (!found && state.contested.has(collection))
3538
- return false;
3539
- if (found?.rules.final && action !== 'create')
3540
- return false;
3541
- const byCreator = action === 'create' || (!!first && (await judge(first)).root === deps.rootDid);
3542
- // The body isn't known yet: a policy on it is decided when the version is written.
3543
- return may(state, deps.rootDid, action === 'delete' ? RECORD_DELETE : RECORD_WRITE, { collection, byCreator }, {
3544
- opaque: action !== 'delete',
3545
- });
3546
- }
3547
297
  // Once at open, then after every change.
3548
- keepUp();
3549
- const pulling = pullMirrors();
3550
- // What this device holds and the folder lacks (copied in, or written before the folder was) goes out soon.
3551
- folderMirror?.changed();
298
+ keys.keepUp();
299
+ const pulling = mirrors.pull();
300
+ mirrors.fillFolder();
301
+ const { catalog: definitions, definitionOf, describe } = catalog;
302
+ const { everyCurrent } = index;
3552
303
  return Object.freeze({
3553
- async list(options = {}) {
3554
- if (options.collection)
3555
- use([options.collection]);
3556
- const shown = [];
3557
- for (const entry of (await counted()).values()) {
3558
- const { collection, deleted } = entry.version;
3559
- if (options.collection ? collection !== options.collection : collection.startsWith('sys.'))
3560
- continue;
3561
- if (deleted && !options.includeDeleted)
3562
- continue;
3563
- shown.push(entry);
3564
- }
3565
- shown.sort((a, b) => a.createdAt.localeCompare(b.createdAt) || a.version.key.localeCompare(b.version.key));
3566
- if (options.newestFirst)
3567
- shown.reverse();
3568
- const page = options.limit === undefined ? shown : shown.slice(0, options.limit);
3569
- const shownOf = (entry) => (entry.shown ??= view(entry.version).catch((error) => {
3570
- entry.shown = undefined;
3571
- throw error;
3572
- }));
3573
- // eslint-disable-next-line @typescript-eslint/consistent-type-assertions -- the caller's type for the body, as in view
3574
- return Promise.all(page.map((entry) => shownOf(entry)));
3575
- },
3576
- get,
3577
- contracts: contractsFor,
304
+ list: index.list,
305
+ get: index.get,
306
+ linked: index.linked,
307
+ history: index.history,
308
+ contracts: writing.contractsFor,
309
+ put: writing.put,
310
+ update: writing.update,
311
+ remove: writing.remove,
312
+ onePerKey: writing.onePerKey,
313
+ can: writing.can,
314
+ ...membership,
3578
315
  /** The note a record's current version was signed under; null when its account signed it itself */
3579
- noteOf: async (recordKey) => (await currentOf(recordKey))?.proof ?? null,
3580
- async put(collection, body, options = {}) {
3581
- return underCurrentRules(() => putOnce(collection, body, options));
3582
- },
316
+ noteOf: async (recordKey) => (await index.currentOf(recordKey))?.proof ?? null,
3583
317
  /** The key `name` has in an account's namespace: this account's, unless another is named */
3584
- keyFor: (name, account = deps.rootDid) => ownedKey(account, name),
3585
- /**
3586
- * The key a record with this body and these links has under its
3587
- * collection's `onePer`, written by `account` (default this one): null
3588
- * when the collection has none, or the body lacks a part it names.
3589
- */
3590
- async onePerKey(collection, body, options = {}) {
3591
- const onePer = options.onePer ?? (await catalog()).get(collection)?.definition.rules?.onePer;
3592
- if (!onePer)
3593
- return null;
3594
- return derivedKey(collection, onePer, {
3595
- root: options.account ?? deps.rootDid,
3596
- links: options.links ?? [],
3597
- body,
3598
- });
3599
- },
3600
- async can(action, target) {
3601
- if (action === 'create')
3602
- return mayNow(target, 'create', null);
3603
- const current = await currentOf(target);
3604
- if (!current || current.deleted)
3605
- return false;
3606
- return mayNow(current.collection, action, await genesisOf(current));
3607
- },
318
+ keyFor: (name, account = rootDid) => ownedKey(account, name),
3608
319
  /** Seals a file, keeps it, and gives back the reference a body names it by (spec 05 §16.6) */
3609
- addFile: (bytes) => (spaceFiles ?? missingFiles()).add(bytes),
320
+ addFile: (bytes) => files.add(bytes),
3610
321
  /** The bytes of a file a body refers to: held here, or fetched from peers or mirrors */
3611
- readFile: (ref) => (spaceFiles ?? missingFiles()).open(ref),
322
+ readFile: (ref) => files.open(ref),
3612
323
  /** For the node itself: writes the next version of a record in a collection `put` refuses, like the profile */
3613
- upsertSystem: (collection, recordKey, body) => upsert(collection, recordKey, body),
324
+ upsertSystem: writing.upsert,
325
+ /** For the node itself: deletes a record in a managed collection */
326
+ removeSystem: writing.removeKey,
3614
327
  async profiles() {
3615
- return [...(await profileMap()).values()].sort((a, b) => a.name.localeCompare(b.name) || a.did.localeCompare(b.did));
328
+ return [...(await profiles.profiles()).values()].sort((a, b) => a.name.localeCompare(b.name) || a.did.localeCompare(b.did));
3616
329
  },
3617
330
  /** For the node itself: says who this account is here, when that changed and the space takes its writes */
3618
331
  async publishProfile(profile) {
@@ -3620,82 +333,31 @@ export async function openSpaceRuntime(deps) {
3620
333
  if (!actsForAccount(session.proof()) || (await cannotWrite()))
3621
334
  return;
3622
335
  const name = profile.name.trim().slice(0, 64);
3623
- const mine = (await profileMap()).get(deps.rootDid);
336
+ const mine = (await profiles.profiles()).get(rootDid);
3624
337
  // An app without the contact key must not take away the one another device published.
3625
338
  const contactKey = profile.contactKey ?? mine?.contactKey;
3626
339
  if (!name ||
3627
340
  (mine?.name === name && mine.contactKey === contactKey && mine.avatar?.hash === profile.avatar?.hash))
3628
341
  return;
3629
- await upsert(PROFILE_COLLECTION, await profileKey(deps.rootDid), {
342
+ await upsert(PROFILE_COLLECTION, await profileKey(rootDid), {
3630
343
  name,
3631
344
  ...(contactKey ? { contactKey } : {}),
3632
345
  ...(profile.avatar ? { avatar: profile.avatar } : {}),
3633
346
  });
3634
347
  },
3635
- rotateKey,
3636
- memberKeys: memberKeyMap,
348
+ rotateKey: keys.rotateKey,
349
+ memberKeys: profiles.memberKeys,
3637
350
  ownMemberKey: () => memberPair,
3638
- readAccess: () => readAccess,
3639
- async setRelays(named) {
3640
- const problem = checkRelays(named);
3641
- if (problem)
3642
- throw new Error(problem);
3643
- await upsert(RELAYS_COLLECTION, SPACE_RELAYS_RECORD, { relays: [...named] });
3644
- },
351
+ readAccess: () => peers.readAccess,
3645
352
  async topicTag(collection, field, value) {
3646
353
  let keyId = null;
3647
354
  if (space.visibility === 'private') {
3648
- const key = currentKey((await access()).history.current);
355
+ const key = keys.currentKey((await history.access()).history.current);
3649
356
  if (!key)
3650
357
  throw new Error(`This device doesn't hold the current key of "${space.name}" yet`);
3651
358
  keyId = key.id;
3652
359
  }
3653
- return topicTag(await tagKey(keyId), collection, field, value);
3654
- },
3655
- async setKeepers(keepers, copies = null) {
3656
- const named = keepers.map((k) => ({ did: k.did, name: k.name }));
3657
- const problem = checkKeepers(named, copies);
3658
- if (problem)
3659
- throw new Error(problem);
3660
- await upsert(KEEPERS_COLLECTION, SPACE_KEEPERS_RECORD, { keepers: named, copies });
3661
- },
3662
- async update(recordKey, body, options = {}) {
3663
- return underCurrentRules(async () => {
3664
- const current = await requireLive(recordKey);
3665
- guard(current.collection);
3666
- // Links carry over unless replaced: ticking a todo should not unhook it from anything.
3667
- const links = options.links ?? (await openBody(current)).links;
3668
- return view(await write(current.collection, body, await after(recordKey), false, links, options.as ? { as: options.as } : {}));
3669
- });
3670
- },
3671
- async linked(recordKey, options = {}) {
3672
- if (options.collection)
3673
- use([options.collection]);
3674
- const pointing = (await linkIndex()).get(recordKey) ?? [];
3675
- const keys = [
3676
- ...new Set(pointing.filter((p) => !options.rel || p.rel === options.rel).map((p) => p.from)),
3677
- ];
3678
- const found = [];
3679
- for (const from of keys) {
3680
- const current = await currentOf(from);
3681
- if (!current || current.deleted)
3682
- continue;
3683
- if (options.collection && current.collection !== options.collection)
3684
- continue;
3685
- found.push(await view(current));
3686
- }
3687
- return found.sort((a, b) => a.createdAt.localeCompare(b.createdAt) || a.key.localeCompare(b.key));
3688
- },
3689
- async remove(recordKey, options = {}) {
3690
- guard((await requireLive(recordKey)).collection);
3691
- await underCurrentRules(() => removeKey(recordKey, options.as));
3692
- },
3693
- /** For the node itself: deletes a record in a managed collection */
3694
- removeSystem: removeKey,
3695
- async history(recordKey) {
3696
- // What a superseded version said is forgotten unless its writer retained it.
3697
- const versions = (await storage.history(recordKey)).filter((version) => !isStub(version));
3698
- return Promise.all(versions.map((version) => view(version)));
360
+ return topicTag(await rules.tagKey(keyId), collection, field, value);
3699
361
  },
3700
362
  /** A collection's computed fields, as its definition says now; a malformed member reads as none */
3701
363
  async computed(collection) {
@@ -3712,18 +374,18 @@ export async function openSpaceRuntime(deps) {
3712
374
  continue;
3713
375
  counts.set(version.collection, (counts.get(version.collection) ?? 0) + 1);
3714
376
  }
3715
- const described = await catalog();
377
+ const described = await definitions();
3716
378
  const names = [...new Set([...described.keys(), ...counts.keys()])].sort();
3717
379
  return names.map((name) => describe(name, described.get(name) ?? null, counts.get(name) ?? 0));
3718
380
  },
3719
381
  async define(input) {
3720
382
  const recordKey = `collection:${input.name}`;
3721
- const current = (await catalog()).get(input.name) ?? null;
383
+ const current = (await definitions()).get(input.name) ?? null;
3722
384
  // Peers don't order definitions by version (spec 02 §6.3): a stored one past what can be
3723
385
  // counted on, written to lock the collection, is simply followed by 1 again.
3724
386
  const after = current && Number.isSafeInteger(current.definition.version + 1) ? current.definition.version : 0;
3725
387
  const version = input.version ?? after + 1;
3726
- const described = await catalog();
388
+ const described = await definitions();
3727
389
  const definition = {
3728
390
  name: input.name,
3729
391
  ...(input.title !== undefined ? { title: input.title } : {}),
@@ -3737,22 +399,7 @@ export async function openSpaceRuntime(deps) {
3737
399
  ...(input.contract !== undefined ? { contract: storedContract(input) } : {}),
3738
400
  ...(input.computed !== undefined ? { computed: storedComputed(input) } : {}),
3739
401
  };
3740
- const contract = definition.contract;
3741
- const shapeProblem = contract !== undefined ? checkContractShape(contract) : null;
3742
- const lineProblem = contract?.line !== undefined ? checkLine(contract.line) : null;
3743
- const problem = checkStoredCollection(definition) ??
3744
- (shapeProblem === 'unknown' ? 'contract takes only "check" and "line"' : shapeProblem) ??
3745
- (contract?.check !== undefined
3746
- ? (checkContracts(contract.check, 'contract.check') ??
3747
- // The library's own care, not protocol: a contract that misreads the schema is refused here.
3748
- checkContractTypes(contract.check, definition.schema, 'contract.check'))
3749
- : null) ??
3750
- (lineProblem === 'unknown' ? 'contract.line takes only "once"' : lineProblem) ??
3751
- (definition.computed !== undefined
3752
- ? (checkComputed(definition.computed) ??
3753
- // The library's care, as for contracts: read against the schemas of what it links to.
3754
- checkComputedTypes(definition.name, definition.computed, definition.schema, (name) => name === definition.name ? definition : (described.get(name)?.definition ?? null)))
3755
- : null);
402
+ const problem = definitionProblem(definition, described);
3756
403
  if (problem)
3757
404
  throw new Error(problem);
3758
405
  if (!Number.isSafeInteger(version))
@@ -3762,250 +409,20 @@ export async function openSpaceRuntime(deps) {
3762
409
  }
3763
410
  // Not retroactive: a change to the rules binds what saw it, and what a change to its author's standing that saw it reaches (03 §5).
3764
411
  await upsert(CATALOG_COLLECTION, recordKey, definition);
3765
- const entry = (await catalog()).get(input.name) ?? null;
412
+ const entry = (await definitions()).get(input.name) ?? null;
3766
413
  const count = (await everyCurrent(input.name)).filter((e) => !e.deleted).length;
3767
414
  return describe(input.name, entry, count);
3768
415
  },
3769
416
  async undefine(name) {
3770
- if (!(await catalog()).has(name))
417
+ if (!(await definitions()).has(name))
3771
418
  throw new Error(`${name} is not defined in this space`);
3772
419
  // Records left behind would lose their shape and their rules, so they go first.
3773
420
  const left = (await everyCurrent(name)).filter((e) => !e.deleted).length;
3774
421
  if (left)
3775
422
  throw new Error(`${name} still has ${left} record${left === 1 ? '' : 's'}; delete them first`);
3776
- await removeKey(`collection:${name}`);
3777
- },
3778
- async access() {
3779
- const { history } = await access();
3780
- const state = history.current;
3781
- const members = [...readers(state)].sort();
3782
- return Object.freeze({
3783
- roles: [...state.roles]
3784
- .map(([name, definitions]) => ({
3785
- name,
3786
- ...(definitions[0]?.title !== undefined ? { title: definitions[0].title } : {}),
3787
- definitions: definitions.map((definition) => ({
3788
- event: definition.event,
3789
- by: definition.by,
3790
- grants: definition.grants,
3791
- nests: definition.nests,
3792
- })),
3793
- }))
3794
- .sort((a, b) => a.name.localeCompare(b.name)),
3795
- members: members.map((did) => ({
3796
- did,
3797
- founder: state.founders.has(did),
3798
- roles: rolesOf(state, did),
3799
- })),
3800
- invites: [...state.invites].map(([inviteDid, invite]) => ({
3801
- key: inviteDid,
3802
- role: invite.role,
3803
- open: invite.open,
3804
- })),
3805
- founder: state.founders.has(deps.rootDid),
3806
- top: space.top === 'none' ? 'none' : 'founders',
3807
- headless: headless(state),
3808
- successors: [...state.successors].map(([successor, by]) => ({ space: successor, by })),
3809
- mine: rolesOf(state, deps.rootDid),
3810
- heads: history.heads(),
3811
- key: state.keys.length ? { changes: state.keys.length - 1, held: currentKey(state) !== null } : null,
3812
- relays: state.relays.length ? state.relays : relays,
3813
- keepers: state.keepers,
3814
- copies: state.copies,
3815
- forks: history.forks(),
3816
- flagged: await flagged(),
3817
- });
3818
- },
3819
- /** Whether this account, or another, may invoke a command with these arguments, now */
3820
- async may(cmd, args = {}, account = deps.rootDid) {
3821
- return may((await access()).history.current, account, cmd, args);
3822
- },
3823
- /** Whether this account, or another, holds every grant a role gives, as wide or wider, now */
3824
- async holdsRole(role, account = deps.rootDid) {
3825
- return holdsRole((await access()).history.current, account, role);
3826
- },
3827
- async assign(did, role) {
3828
- await assign(did, role, true);
3829
- },
3830
- async unassign(did, role) {
3831
- await assign(did, role, false);
3832
- },
3833
- async removeMember(did) {
3834
- await removeAccount(did);
3835
- },
3836
- /** Stops being a founder, keeping the roles held, and `keep` first when given */
3837
- async stepDown(keep) {
3838
- const { history } = await access();
3839
- if (!history.current.founders.has(deps.rootDid))
3840
- throw new Error(`You are not a founder of "${space.name}"`);
3841
- if (keep !== undefined && !rolesOf(history.current, deps.rootDid).includes(keep))
3842
- await assign(deps.rootDid, keep, true);
3843
- if (rolesOf((await access()).history.current, deps.rootDid).length === 0)
3844
- throw new Error(`You hold no role in "${space.name}", so stepping down would leave it: keep a role, or leave`);
3845
- const cutoff = await cutoffFor(deps.rootDid);
3846
- await upsert(STEPDOWN_COLLECTION, await stepDownKey(deps.rootDid), {
3847
- did: deps.rootDid,
3848
- ...(Object.keys(cutoff).length ? { cutoff } : {}),
3849
- });
3850
- },
3851
- /** Names a space that succeeds this one. It changes nothing here */
3852
- async succeed(successor) {
3853
- if (!isSpaceId(successor) || successor === space.id)
3854
- throw new Error('A successor is named by its space id');
3855
- // Refused here, with the reason, when this account may not: as every peer would.
3856
- await upsert(SUCCEED_COLLECTION, await succeedKey(successor), { space: successor });
3857
- },
3858
- /**
3859
- * Gives up this account's place before it forgets the space: its own
3860
- * member record with no role, so the others stop counting it a reader and
3861
- * a key change becomes due. Nothing sends the removal once the space is
3862
- * closed, so this waits up to `waitMs` for a peer of another account to
3863
- * say it has it. False when it couldn't be written, or nobody took it in
3864
- * time.
3865
- */
3866
- async giveUpPlace(waitMs) {
3867
- const state = (await access()).history.current;
3868
- // Shared to view, or already gone: there is nothing to remove.
3869
- if (!isMember(state, deps.rootDid))
3870
- return true;
3871
- // Nobody else holds a place, so nobody else needs to know.
3872
- if ([...readers(state)].every((did) => did === deps.rootDid))
3873
- return true;
3874
- const taken = new Set();
3875
- let wanted = null;
3876
- let found = () => { };
3877
- const onStored = (peer, ids) => {
3878
- void peerAccounts.get(peer)?.then(({ account }) => {
3879
- if (account === deps.rootDid)
3880
- return;
3881
- for (const id of ids)
3882
- taken.add(id);
3883
- if (wanted !== null && taken.has(wanted))
3884
- found();
3885
- });
3886
- };
3887
- // Listening before writing: a peer can answer before the write returns.
3888
- sync.on('stored', onStored);
3889
- try {
3890
- wanted = (await removeAccount(deps.rootDid)).version;
3891
- if (taken.has(wanted))
3892
- return true;
3893
- if (waitMs <= 0)
3894
- return false;
3895
- return await new Promise((resolve) => {
3896
- const timer = setTimeout(() => resolve(false), waitMs);
3897
- found = () => {
3898
- clearTimeout(timer);
3899
- resolve(true);
3900
- };
3901
- });
3902
- }
3903
- catch {
3904
- // A note that may not change access; another of the account's devices can.
3905
- return false;
3906
- }
3907
- finally {
3908
- sync.off('stored', onStored);
3909
- }
3910
- },
3911
- /**
3912
- * Waits up to `waitMs` for this node to be level with `peer` here: nothing
3913
- * left in flight either way, so the peer holds everything this node does.
3914
- * False when that long passed first.
3915
- */
3916
- syncedWith(peer, waitMs) {
3917
- if (sync.levelWith(peer))
3918
- return Promise.resolve(true);
3919
- return new Promise((resolve) => {
3920
- const done = (level) => {
3921
- clearTimeout(timer);
3922
- sync.off('synced', onSynced);
3923
- resolve(level);
3924
- };
3925
- const onSynced = (from) => {
3926
- if (from === peer)
3927
- done(true);
3928
- };
3929
- const timer = setTimeout(() => done(false), waitMs);
3930
- sync.on('synced', onSynced);
3931
- // Behind, it would start catching up only at the next heartbeat.
3932
- sync.notifyPeers([peer]);
3933
- });
3934
- },
3935
- /** Writes a role's definition: its grants, issued by this account, and the roles it nests */
3936
- async defineRole(role) {
3937
- const problem = checkFoundingRole(role);
3938
- if (problem)
3939
- throw new Error(problem);
3940
- const nonce = () => base64UrlEncode(globalThis.crypto.getRandomValues(new Uint8Array(12)));
3941
- await upsert(ROLE_COLLECTION, roleKey(role.name), definitionBody(role, { root: deps.rootDid, spaceId: space.id }, nonce));
3942
- },
3943
- /** Opens an invite to a role, with its own fresh secret unless a short link's gives it one */
3944
- async openInvite(role, secret = generateInviteSecret()) {
3945
- const pair = await deriveInviteKey(secret, provider);
3946
- await upsert(INVITE_COLLECTION, await inviteRecordKey(pair.did), { key: pair.did, role, open: true });
3947
- return { secret, key: pair.did };
3948
- },
3949
- async closeInvite(inviteDid) {
3950
- const { history } = await access();
3951
- const invite = history.current.invites.get(inviteDid);
3952
- if (!invite)
3953
- throw new Error('There is no such invite in this space');
3954
- // Who joined with it before this node closed it stays: the close names what it saw, and the replay does the rest.
3955
- await upsert(INVITE_COLLECTION, await inviteRecordKey(inviteDid), {
3956
- key: inviteDid,
3957
- role: invite.role,
3958
- open: false,
3959
- });
3960
- },
3961
- /**
3962
- * Revokes a key of this account's. With `waitMs`, it then waits up to that
3963
- * long for a peer to say it has the revoke: a device about to stop sends
3964
- * nothing after, so true means it left. A node with no network configured
3965
- * can't send it anywhere, so false at once. Without, true once written.
3966
- */
3967
- async revoke(key, options = {}) {
3968
- const waitMs = options.waitMs ?? 0;
3969
- const taken = new Set();
3970
- let wanted = null;
3971
- let found = () => { };
3972
- const onStored = (_peer, ids) => {
3973
- for (const id of ids)
3974
- taken.add(id);
3975
- if (wanted !== null && taken.has(wanted))
3976
- found();
3977
- };
3978
- // Listening before writing: a peer can answer before the write returns.
3979
- if (waitMs > 0)
3980
- sync.on('stored', onStored);
3981
- try {
3982
- const cutoff = await cutoffFor(deps.rootDid, key);
3983
- wanted = (await upsert(REVOKE_COLLECTION, await revokeKey(key, deps.rootDid), {
3984
- key,
3985
- ...(Object.keys(cutoff).length ? { cutoff } : {}),
3986
- })).version;
3987
- if (waitMs <= 0 || taken.has(wanted))
3988
- return true;
3989
- // With a network configured a peer may still be on its way, through a socket not yet
3990
- // joined or a host not yet reached; with none, nobody can come.
3991
- if (!net)
3992
- return false;
3993
- return await new Promise((resolve) => {
3994
- const timer = setTimeout(() => resolve(false), waitMs);
3995
- found = () => {
3996
- clearTimeout(timer);
3997
- resolve(true);
3998
- };
3999
- });
4000
- }
4001
- finally {
4002
- if (waitMs > 0)
4003
- sync.off('stored', onStored);
4004
- }
4005
- },
4006
- async isRevoked(key) {
4007
- return (await access()).history.revoked(key, deps.rootDid).length > 0;
423
+ await writing.removeKey(`collection:${name}`);
4008
424
  },
425
+ syncedWith: peers.syncedWith,
4009
426
  async versionsOf(keys) {
4010
427
  return (await Promise.all(keys.map((key) => storage.history(key)))).flat();
4011
428
  },
@@ -4025,115 +442,37 @@ export async function openSpaceRuntime(deps) {
4025
442
  if (placed.length === 0)
4026
443
  return 0;
4027
444
  recordsChanged(placed);
4028
- announceSoon();
445
+ peers.announceSoon();
4029
446
  return placed.length;
4030
447
  },
4031
- /** Uses an invite's secret, once its record has arrived. True when this account is a member. */
4032
- async join(secret) {
4033
- const { history } = await access();
4034
- const pair = await deriveInviteKey(secret, provider);
4035
- const invite = history.current.invites.get(pair.did);
4036
- if (isMember(history.current, deps.rootDid) &&
4037
- (!invite || rolesOf(history.current, deps.rootDid).includes(invite.role))) {
4038
- waitingInvite = false;
4039
- deps.onJoined?.();
4040
- return true;
4041
- }
4042
- if (!invite?.open)
4043
- return false;
4044
- await upsert(ASSIGN_COLLECTION, await assignKey(deps.rootDid, invite.role), {
4045
- did: deps.rootDid,
4046
- role: invite.role,
4047
- assigned: true,
4048
- invite: { key: pair.did, signature: await signInvite(space.id, deps.rootDid, pair, provider) },
4049
- }, { joining: true });
4050
- waitingInvite = false;
4051
- deps.onJoined?.();
4052
- return true;
4053
- },
4054
448
  async status() {
449
+ const { connection, peers: connected, accounts, rejected } = peers.status();
4055
450
  return {
4056
451
  space: space.id,
4057
- connection: liveConnection(),
4058
- peers: connectedPeers(),
4059
- accounts: Object.fromEntries([...knownAccounts].flatMap(([peer, known]) => known.account && routes.has(peer) ? [[peer, known.account]] : [])),
452
+ connection,
453
+ peers: connected,
454
+ accounts,
4060
455
  fingerprint: await storage.fingerprint(),
4061
456
  rejected,
4062
- holds: partial ? Object.keys(cacheState.used).sort() : 'all',
4063
- pending: (await adapter.list(PENDING_PREFIX)).length,
457
+ holds: holding.held(),
458
+ pending: await holding.pending(),
4064
459
  };
4065
460
  },
4066
- use,
4067
- async send(message, to) {
4068
- const encoded = JSON.stringify(message ?? null);
4069
- if (encoded.length > MAX_LIVE_BYTES)
4070
- throw new Error('A live message can be at most 64 KB');
4071
- const gone = await formerMembers();
4072
- for (const peer of connectedPeers()) {
4073
- const account = (await peerAccounts.get(peer))?.account ?? null;
4074
- if (to && to !== peer && account !== to)
4075
- continue;
4076
- // Removed, or left: live messages stop with everything else.
4077
- if (account !== null && gone.has(account))
4078
- continue;
4079
- routes.get(peer)?.send(peer, { type: LIVE_MESSAGE, from: session.did, payload: message ?? null });
4080
- }
4081
- },
4082
- /**
4083
- * Always-on nodes to hold a socket to besides those configured: the hosts
4084
- * the account or the space uses. Sockets to any given before and not now
4085
- * are closed.
4086
- */
4087
- useNodes(nodes) {
4088
- if (!net || closed)
4089
- return;
4090
- const configured = new Set(net.nodes ?? []);
4091
- const wanted = new Set(nodes.filter((node) => !configured.has(node)));
4092
- for (const [node, network] of hostNetworks) {
4093
- if (wanted.has(node))
4094
- continue;
4095
- hostNetworks.delete(node);
4096
- networks.splice(networks.indexOf(network), 1);
4097
- network.disconnect();
4098
- }
4099
- for (const node of wanted) {
4100
- if (hostNetworks.has(node))
4101
- continue;
4102
- const network = nodeNetwork(node);
4103
- hostNetworks.set(node, network);
4104
- networks.push(network);
4105
- listen(network);
4106
- if (connection === 'offline')
4107
- connection = 'connecting';
4108
- sync.start();
4109
- void network.connect().then(() => {
4110
- connection = 'connected';
4111
- emit({ type: 'status', space: space.id });
4112
- }, () => emit({ type: 'status', space: space.id }));
4113
- }
4114
- },
461
+ use: holding.use,
462
+ send: peers.send,
463
+ useNodes: peers.useNodes,
4115
464
  async close() {
4116
465
  closed = true;
4117
- stopWatchingMesh?.();
4118
- if (dropTimer)
4119
- clearInterval(dropTimer);
4120
- await tidying;
4121
- await flushCache();
4122
- await keepingUp.done();
466
+ peers.quiet();
467
+ await holding.close();
468
+ await keys.keepingUp.done();
4123
469
  await pulling;
4124
- await Promise.all(mirrors.map((mirror) => mirror.close()));
470
+ await mirrors.close();
4125
471
  if (filesTimer)
4126
472
  clearTimeout(filesTimer);
4127
- spaceFiles?.close();
473
+ files.close();
4128
474
  await filesPass;
4129
- if (watchTimer)
4130
- clearInterval(watchTimer);
4131
- if (announceTimer)
4132
- clearTimeout(announceTimer);
4133
- channel?.close();
4134
- sync.stop();
4135
- for (const network of networks)
4136
- network.disconnect();
475
+ peers.close();
4137
476
  await storage.close();
4138
477
  },
4139
478
  });