@minca/core 0.1.15 → 0.1.17

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 (443) hide show
  1. package/README.md +10 -10
  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 +35 -9
  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 +169 -72
  8. package/dist/elements/minca-auth.js.map +1 -1
  9. package/dist/identity/abilities.d.ts +2 -0
  10. package/dist/identity/abilities.d.ts.map +1 -1
  11. package/dist/identity/abilities.js +2 -0
  12. package/dist/identity/abilities.js.map +1 -1
  13. package/dist/identity/account-vault.d.ts +15 -71
  14. package/dist/identity/account-vault.d.ts.map +1 -1
  15. package/dist/identity/account-vault.js +45 -104
  16. package/dist/identity/account-vault.js.map +1 -1
  17. package/dist/identity/channel.d.ts +3 -9
  18. package/dist/identity/channel.d.ts.map +1 -1
  19. package/dist/identity/channel.js +42 -42
  20. package/dist/identity/channel.js.map +1 -1
  21. package/dist/identity/contact-key.d.ts +14 -29
  22. package/dist/identity/contact-key.d.ts.map +1 -1
  23. package/dist/identity/contact-key.js +31 -51
  24. package/dist/identity/contact-key.js.map +1 -1
  25. package/dist/identity/crypto-p256.d.ts.map +1 -1
  26. package/dist/identity/crypto-p256.js +39 -53
  27. package/dist/identity/crypto-p256.js.map +1 -1
  28. package/dist/identity/hpke.d.ts.map +1 -1
  29. package/dist/identity/hpke.js +19 -19
  30. package/dist/identity/hpke.js.map +1 -1
  31. package/dist/identity/identity-manager.d.ts.map +1 -1
  32. package/dist/identity/identity-manager.js +1 -2
  33. package/dist/identity/identity-manager.js.map +1 -1
  34. package/dist/identity/policy.d.ts.map +1 -1
  35. package/dist/identity/policy.js +35 -61
  36. package/dist/identity/policy.js.map +1 -1
  37. package/dist/identity/recovery-code.d.ts +2 -8
  38. package/dist/identity/recovery-code.d.ts.map +1 -1
  39. package/dist/identity/recovery-code.js +4 -11
  40. package/dist/identity/recovery-code.js.map +1 -1
  41. package/dist/identity/root-signer.d.ts +1 -6
  42. package/dist/identity/root-signer.d.ts.map +1 -1
  43. package/dist/identity/root-signer.js +12 -15
  44. package/dist/identity/root-signer.js.map +1 -1
  45. package/dist/identity/ucan.d.ts.map +1 -1
  46. package/dist/identity/ucan.js +48 -39
  47. package/dist/identity/ucan.js.map +1 -1
  48. package/dist/identity/webauthn.d.ts +6 -11
  49. package/dist/identity/webauthn.d.ts.map +1 -1
  50. package/dist/identity/webauthn.js +18 -30
  51. package/dist/identity/webauthn.js.map +1 -1
  52. package/dist/inbox/inbox.d.ts.map +1 -1
  53. package/dist/inbox/inbox.js +40 -30
  54. package/dist/inbox/inbox.js.map +1 -1
  55. package/dist/inbox/index.d.ts +2 -0
  56. package/dist/inbox/index.d.ts.map +1 -1
  57. package/dist/inbox/index.js +1 -0
  58. package/dist/inbox/index.js.map +1 -1
  59. package/dist/inbox/names.d.ts +54 -0
  60. package/dist/inbox/names.d.ts.map +1 -0
  61. package/dist/inbox/names.js +299 -0
  62. package/dist/inbox/names.js.map +1 -0
  63. package/dist/index.d.ts +3 -6
  64. package/dist/index.d.ts.map +1 -1
  65. package/dist/index.js +9 -12
  66. package/dist/index.js.map +1 -1
  67. package/dist/network/mesh.d.ts +7 -20
  68. package/dist/network/mesh.d.ts.map +1 -1
  69. package/dist/network/mesh.js +267 -245
  70. package/dist/network/mesh.js.map +1 -1
  71. package/dist/network/relay-link.d.ts +31 -0
  72. package/dist/network/relay-link.d.ts.map +1 -0
  73. package/dist/network/relay-link.js +62 -0
  74. package/dist/network/relay-link.js.map +1 -0
  75. package/dist/network/relay-minca.d.ts.map +1 -1
  76. package/dist/network/relay-minca.js +11 -49
  77. package/dist/network/relay-minca.js.map +1 -1
  78. package/dist/network/relay-nostr.d.ts.map +1 -1
  79. package/dist/network/relay-nostr.js +23 -63
  80. package/dist/network/relay-nostr.js.map +1 -1
  81. package/dist/network/relay-socket.d.ts +1 -1
  82. package/dist/network/relay-socket.d.ts.map +1 -1
  83. package/dist/network/relay-socket.js +3 -1
  84. package/dist/network/relay-socket.js.map +1 -1
  85. package/dist/network/ws-transport.d.ts.map +1 -1
  86. package/dist/network/ws-transport.js +3 -0
  87. package/dist/network/ws-transport.js.map +1 -1
  88. package/dist/node/actions.d.ts +2 -0
  89. package/dist/node/actions.d.ts.map +1 -1
  90. package/dist/node/actions.js +89 -58
  91. package/dist/node/actions.js.map +1 -1
  92. package/dist/node/api.d.ts +7 -0
  93. package/dist/node/api.d.ts.map +1 -1
  94. package/dist/node/api.js +7 -0
  95. package/dist/node/api.js.map +1 -1
  96. package/dist/node/carrier.d.ts +5 -0
  97. package/dist/node/carrier.d.ts.map +1 -1
  98. package/dist/node/carrier.js +94 -73
  99. package/dist/node/carrier.js.map +1 -1
  100. package/dist/node/copy.d.ts +8 -7
  101. package/dist/node/copy.d.ts.map +1 -1
  102. package/dist/node/copy.js +54 -56
  103. package/dist/node/copy.js.map +1 -1
  104. package/dist/node/host.d.ts +39 -65
  105. package/dist/node/host.d.ts.map +1 -1
  106. package/dist/node/host.js +362 -379
  107. package/dist/node/host.js.map +1 -1
  108. package/dist/node/index.d.ts +2 -2
  109. package/dist/node/index.d.ts.map +1 -1
  110. package/dist/node/index.js +1 -1
  111. package/dist/node/index.js.map +1 -1
  112. package/dist/node/node-carriers.d.ts +35 -0
  113. package/dist/node/node-carriers.d.ts.map +1 -0
  114. package/dist/node/node-carriers.js +567 -0
  115. package/dist/node/node-carriers.js.map +1 -0
  116. package/dist/node/node-contacts.d.ts +11 -0
  117. package/dist/node/node-contacts.d.ts.map +1 -0
  118. package/dist/node/node-contacts.js +808 -0
  119. package/dist/node/node-contacts.js.map +1 -0
  120. package/dist/node/node-context.d.ts +76 -0
  121. package/dist/node/node-context.d.ts.map +1 -0
  122. package/dist/node/node-context.js +54 -0
  123. package/dist/node/node-context.js.map +1 -0
  124. package/dist/node/node-hosting.d.ts +20 -0
  125. package/dist/node/node-hosting.d.ts.map +1 -0
  126. package/dist/node/node-hosting.js +456 -0
  127. package/dist/node/node-hosting.js.map +1 -0
  128. package/dist/node/node-records.d.ts +18 -0
  129. package/dist/node/node-records.d.ts.map +1 -0
  130. package/dist/node/node-records.js +262 -0
  131. package/dist/node/node-records.js.map +1 -0
  132. package/dist/node/node.d.ts.map +1 -1
  133. package/dist/node/node.js +199 -1990
  134. package/dist/node/node.js.map +1 -1
  135. package/dist/node/remote.d.ts +5 -6
  136. package/dist/node/remote.d.ts.map +1 -1
  137. package/dist/node/remote.js +272 -260
  138. package/dist/node/remote.js.map +1 -1
  139. package/dist/node/space-catalog.d.ts +40 -0
  140. package/dist/node/space-catalog.d.ts.map +1 -0
  141. package/dist/node/space-catalog.js +158 -0
  142. package/dist/node/space-catalog.js.map +1 -0
  143. package/dist/node/space-checks.d.ts +25 -0
  144. package/dist/node/space-checks.d.ts.map +1 -0
  145. package/dist/node/space-checks.js +343 -0
  146. package/dist/node/space-checks.js.map +1 -0
  147. package/dist/node/space-history.d.ts +37 -0
  148. package/dist/node/space-history.d.ts.map +1 -0
  149. package/dist/node/space-history.js +350 -0
  150. package/dist/node/space-history.js.map +1 -0
  151. package/dist/node/space-holding.d.ts +53 -0
  152. package/dist/node/space-holding.d.ts.map +1 -0
  153. package/dist/node/space-holding.js +339 -0
  154. package/dist/node/space-holding.js.map +1 -0
  155. package/dist/node/space-index.d.ts +41 -0
  156. package/dist/node/space-index.d.ts.map +1 -0
  157. package/dist/node/space-index.js +217 -0
  158. package/dist/node/space-index.js.map +1 -0
  159. package/dist/node/space-keys.d.ts +34 -0
  160. package/dist/node/space-keys.d.ts.map +1 -0
  161. package/dist/node/space-keys.js +309 -0
  162. package/dist/node/space-keys.js.map +1 -0
  163. package/dist/node/space-lines.d.ts +33 -0
  164. package/dist/node/space-lines.d.ts.map +1 -0
  165. package/dist/node/space-lines.js +145 -0
  166. package/dist/node/space-lines.js.map +1 -0
  167. package/dist/node/space-membership.d.ts +69 -0
  168. package/dist/node/space-membership.d.ts.map +1 -0
  169. package/dist/node/space-membership.js +242 -0
  170. package/dist/node/space-membership.js.map +1 -0
  171. package/dist/node/space-mirrors.d.ts +43 -0
  172. package/dist/node/space-mirrors.d.ts.map +1 -0
  173. package/dist/node/space-mirrors.js +125 -0
  174. package/dist/node/space-mirrors.js.map +1 -0
  175. package/dist/node/space-peers.d.ts +104 -0
  176. package/dist/node/space-peers.d.ts.map +1 -0
  177. package/dist/node/space-peers.js +629 -0
  178. package/dist/node/space-peers.js.map +1 -0
  179. package/dist/node/space-profiles.d.ts +18 -0
  180. package/dist/node/space-profiles.d.ts.map +1 -0
  181. package/dist/node/space-profiles.js +105 -0
  182. package/dist/node/space-profiles.js.map +1 -0
  183. package/dist/node/space-rules.d.ts +29 -0
  184. package/dist/node/space-rules.d.ts.map +1 -0
  185. package/dist/node/space-rules.js +144 -0
  186. package/dist/node/space-rules.js.map +1 -0
  187. package/dist/node/space-runtime.d.ts +107 -140
  188. package/dist/node/space-runtime.d.ts.map +1 -1
  189. package/dist/node/space-runtime.js +331 -3985
  190. package/dist/node/space-runtime.js.map +1 -1
  191. package/dist/node/space-standing.d.ts +20 -0
  192. package/dist/node/space-standing.d.ts.map +1 -0
  193. package/dist/node/space-standing.js +317 -0
  194. package/dist/node/space-standing.js.map +1 -0
  195. package/dist/node/space-versions.d.ts +104 -0
  196. package/dist/node/space-versions.d.ts.map +1 -0
  197. package/dist/node/space-versions.js +153 -0
  198. package/dist/node/space-versions.js.map +1 -0
  199. package/dist/node/space-warrants.d.ts +25 -0
  200. package/dist/node/space-warrants.d.ts.map +1 -0
  201. package/dist/node/space-warrants.js +214 -0
  202. package/dist/node/space-warrants.js.map +1 -0
  203. package/dist/node/space-writing.d.ts +74 -0
  204. package/dist/node/space-writing.d.ts.map +1 -0
  205. package/dist/node/space-writing.js +442 -0
  206. package/dist/node/space-writing.js.map +1 -0
  207. package/dist/node/stores.d.ts +19 -50
  208. package/dist/node/stores.d.ts.map +1 -1
  209. package/dist/node/stores.js +14 -33
  210. package/dist/node/stores.js.map +1 -1
  211. package/dist/node/types.d.ts +243 -306
  212. package/dist/node/types.d.ts.map +1 -1
  213. package/dist/node/usage.d.ts +2 -24
  214. package/dist/node/usage.d.ts.map +1 -1
  215. package/dist/node/usage.js +118 -102
  216. package/dist/node/usage.js.map +1 -1
  217. package/dist/node/watch-notifications.d.ts.map +1 -1
  218. package/dist/node/watch-notifications.js +32 -29
  219. package/dist/node/watch-notifications.js.map +1 -1
  220. package/dist/node/worker.d.ts +5 -6
  221. package/dist/node/worker.d.ts.map +1 -1
  222. package/dist/node/worker.js +80 -72
  223. package/dist/node/worker.js.map +1 -1
  224. package/dist/node/writer-keys.d.ts +5 -6
  225. package/dist/node/writer-keys.d.ts.map +1 -1
  226. package/dist/node/writer-keys.js +66 -57
  227. package/dist/node/writer-keys.js.map +1 -1
  228. package/dist/node/writers.d.ts +12 -19
  229. package/dist/node/writers.d.ts.map +1 -1
  230. package/dist/node/writers.js +7 -15
  231. package/dist/node/writers.js.map +1 -1
  232. package/dist/privacy/direct.d.ts.map +1 -1
  233. package/dist/privacy/direct.js +31 -27
  234. package/dist/privacy/direct.js.map +1 -1
  235. package/dist/privacy/space-encryption.d.ts.map +1 -1
  236. package/dist/privacy/space-encryption.js +5 -9
  237. package/dist/privacy/space-encryption.js.map +1 -1
  238. package/dist/query/computed.d.ts.map +1 -1
  239. package/dist/query/computed.js +78 -77
  240. package/dist/query/computed.js.map +1 -1
  241. package/dist/query/engine.d.ts +3 -4
  242. package/dist/query/engine.d.ts.map +1 -1
  243. package/dist/query/engine.js +93 -86
  244. package/dist/query/engine.js.map +1 -1
  245. package/dist/query/filter.d.ts +8 -10
  246. package/dist/query/filter.d.ts.map +1 -1
  247. package/dist/query/filter.js +144 -161
  248. package/dist/query/filter.js.map +1 -1
  249. package/dist/records/cel-types.d.ts.map +1 -1
  250. package/dist/records/cel-types.js +13 -27
  251. package/dist/records/cel-types.js.map +1 -1
  252. package/dist/records/cel.d.ts.map +1 -1
  253. package/dist/records/cel.js +177 -242
  254. package/dist/records/cel.js.map +1 -1
  255. package/dist/records/rules.d.ts.map +1 -1
  256. package/dist/records/rules.js +46 -50
  257. package/dist/records/rules.js.map +1 -1
  258. package/dist/records/topics.d.ts.map +1 -1
  259. package/dist/records/topics.js +18 -22
  260. package/dist/records/topics.js.map +1 -1
  261. package/dist/schemas/automations.d.ts +8 -15
  262. package/dist/schemas/automations.d.ts.map +1 -1
  263. package/dist/schemas/automations.js +203 -165
  264. package/dist/schemas/automations.js.map +1 -1
  265. package/dist/schemas/blueprints.d.ts.map +1 -1
  266. package/dist/schemas/blueprints.js +14 -13
  267. package/dist/schemas/blueprints.js.map +1 -1
  268. package/dist/schemas/connectors.d.ts.map +1 -1
  269. package/dist/schemas/connectors.js +16 -11
  270. package/dist/schemas/connectors.js.map +1 -1
  271. package/dist/schemas/contacts.d.ts +57 -0
  272. package/dist/schemas/contacts.d.ts.map +1 -1
  273. package/dist/schemas/contacts.js +32 -0
  274. package/dist/schemas/contacts.js.map +1 -1
  275. package/dist/schemas/cron.d.ts.map +1 -1
  276. package/dist/schemas/cron.js +27 -28
  277. package/dist/schemas/cron.js.map +1 -1
  278. package/dist/schemas/defined.d.ts +6 -0
  279. package/dist/schemas/defined.d.ts.map +1 -0
  280. package/dist/schemas/defined.js +7 -0
  281. package/dist/schemas/defined.js.map +1 -0
  282. package/dist/schemas/guides.d.ts +3 -1
  283. package/dist/schemas/guides.d.ts.map +1 -1
  284. package/dist/schemas/guides.js +13 -12
  285. package/dist/schemas/guides.js.map +1 -1
  286. package/dist/schemas/index.d.ts +2 -2
  287. package/dist/schemas/index.d.ts.map +1 -1
  288. package/dist/schemas/index.js +18 -14
  289. package/dist/schemas/index.js.map +1 -1
  290. package/dist/schemas/library/social.d.ts +258 -0
  291. package/dist/schemas/library/social.d.ts.map +1 -1
  292. package/dist/schemas/library/social.js +28 -1
  293. package/dist/schemas/library/social.js.map +1 -1
  294. package/dist/session/account-hint.d.ts.map +1 -1
  295. package/dist/session/account-hint.js +8 -5
  296. package/dist/session/account-hint.js.map +1 -1
  297. package/dist/session/auth.d.ts +36 -2
  298. package/dist/session/auth.d.ts.map +1 -1
  299. package/dist/session/auth.js +95 -2
  300. package/dist/session/auth.js.map +1 -1
  301. package/dist/session/connect.d.ts +1 -0
  302. package/dist/session/connect.d.ts.map +1 -1
  303. package/dist/session/connect.js +3 -1
  304. package/dist/session/connect.js.map +1 -1
  305. package/dist/session/credentials.d.ts +8 -26
  306. package/dist/session/credentials.d.ts.map +1 -1
  307. package/dist/session/credentials.js +14 -32
  308. package/dist/session/credentials.js.map +1 -1
  309. package/dist/session/hosting.d.ts.map +1 -1
  310. package/dist/session/hosting.js +8 -2
  311. package/dist/session/hosting.js.map +1 -1
  312. package/dist/session/index.d.ts +1 -0
  313. package/dist/session/index.d.ts.map +1 -1
  314. package/dist/session/index.js +1 -0
  315. package/dist/session/index.js.map +1 -1
  316. package/dist/session/pairing.d.ts.map +1 -1
  317. package/dist/session/pairing.js +92 -88
  318. package/dist/session/pairing.js.map +1 -1
  319. package/dist/session/password-strength.d.ts.map +1 -1
  320. package/dist/session/password-strength.js +37 -37
  321. package/dist/session/password-strength.js.map +1 -1
  322. package/dist/session/places.d.ts.map +1 -1
  323. package/dist/session/places.js +18 -13
  324. package/dist/session/places.js.map +1 -1
  325. package/dist/session/popup.d.ts +13 -0
  326. package/dist/session/popup.d.ts.map +1 -0
  327. package/dist/session/popup.js +23 -0
  328. package/dist/session/popup.js.map +1 -0
  329. package/dist/space/constitution.d.ts.map +1 -1
  330. package/dist/space/constitution.js +22 -29
  331. package/dist/space/constitution.js.map +1 -1
  332. package/dist/space/grants.d.ts.map +1 -1
  333. package/dist/space/grants.js +37 -39
  334. package/dist/space/grants.js.map +1 -1
  335. package/dist/space/invite-link.d.ts.map +1 -1
  336. package/dist/space/invite-link.js +33 -33
  337. package/dist/space/invite-link.js.map +1 -1
  338. package/dist/space/own-automations.d.ts +13 -24
  339. package/dist/space/own-automations.d.ts.map +1 -1
  340. package/dist/space/own-automations.js +47 -37
  341. package/dist/space/own-automations.js.map +1 -1
  342. package/dist/space/presets.d.ts +2 -2
  343. package/dist/space/presets.d.ts.map +1 -1
  344. package/dist/space/presets.js +3 -2
  345. package/dist/space/presets.js.map +1 -1
  346. package/dist/space/roles.d.ts +56 -80
  347. package/dist/space/roles.d.ts.map +1 -1
  348. package/dist/space/roles.js +448 -441
  349. package/dist/space/roles.js.map +1 -1
  350. package/dist/space/space-access.d.ts +3 -4
  351. package/dist/space/space-access.d.ts.map +1 -1
  352. package/dist/space/space-access.js +3 -8
  353. package/dist/space/space-access.js.map +1 -1
  354. package/dist/storage/blob/directory.d.ts.map +1 -1
  355. package/dist/storage/blob/directory.js +39 -32
  356. package/dist/storage/blob/directory.js.map +1 -1
  357. package/dist/storage/blob/s3.d.ts.map +1 -1
  358. package/dist/storage/blob/s3.js +21 -19
  359. package/dist/storage/blob/s3.js.map +1 -1
  360. package/dist/storage/blob-store.d.ts +0 -9
  361. package/dist/storage/blob-store.d.ts.map +1 -1
  362. package/dist/storage/directory-access.d.ts +8 -32
  363. package/dist/storage/directory-access.d.ts.map +1 -1
  364. package/dist/storage/directory-access.js +11 -36
  365. package/dist/storage/directory-access.js.map +1 -1
  366. package/dist/storage/encrypted-adapter.d.ts +12 -32
  367. package/dist/storage/encrypted-adapter.d.ts.map +1 -1
  368. package/dist/storage/encrypted-adapter.js +31 -54
  369. package/dist/storage/encrypted-adapter.js.map +1 -1
  370. package/dist/storage/folder-adapter.d.ts +12 -26
  371. package/dist/storage/folder-adapter.d.ts.map +1 -1
  372. package/dist/storage/folder-adapter.js +37 -54
  373. package/dist/storage/folder-adapter.js.map +1 -1
  374. package/dist/storage/folder-reconcile.d.ts +12 -26
  375. package/dist/storage/folder-reconcile.d.ts.map +1 -1
  376. package/dist/storage/folder-reconcile.js +39 -48
  377. package/dist/storage/folder-reconcile.js.map +1 -1
  378. package/dist/storage/indexeddb-adapter.d.ts +2 -6
  379. package/dist/storage/indexeddb-adapter.d.ts.map +1 -1
  380. package/dist/storage/indexeddb-adapter.js +60 -114
  381. package/dist/storage/indexeddb-adapter.js.map +1 -1
  382. package/dist/storage/mirror.d.ts +0 -29
  383. package/dist/storage/mirror.d.ts.map +1 -1
  384. package/dist/storage/mirror.js +153 -110
  385. package/dist/storage/mirror.js.map +1 -1
  386. package/dist/storage/segment.d.ts.map +1 -1
  387. package/dist/storage/segment.js +3 -7
  388. package/dist/storage/segment.js.map +1 -1
  389. package/dist/storage/storage-provider.d.ts +6 -11
  390. package/dist/storage/storage-provider.d.ts.map +1 -1
  391. package/dist/storage/storage-provider.js +112 -116
  392. package/dist/storage/storage-provider.js.map +1 -1
  393. package/dist/sync/sync-engine.d.ts +10 -44
  394. package/dist/sync/sync-engine.d.ts.map +1 -1
  395. package/dist/sync/sync-engine.js +245 -247
  396. package/dist/sync/sync-engine.js.map +1 -1
  397. package/dist/sync/sync-messages.d.ts +1 -1
  398. package/dist/sync/sync-messages.d.ts.map +1 -1
  399. package/dist/sync/sync-messages.js +1 -1
  400. package/dist/sync/sync-messages.js.map +1 -1
  401. package/dist/utils/guards.d.ts +1 -0
  402. package/dist/utils/guards.d.ts.map +1 -1
  403. package/dist/utils/guards.js +1 -0
  404. package/dist/utils/guards.js.map +1 -1
  405. package/dist/utils/hmac.d.ts +5 -0
  406. package/dist/utils/hmac.d.ts.map +1 -0
  407. package/dist/utils/hmac.js +20 -0
  408. package/dist/utils/hmac.js.map +1 -0
  409. package/dist/utils/map.d.ts +10 -0
  410. package/dist/utils/map.d.ts.map +1 -0
  411. package/dist/utils/map.js +30 -0
  412. package/dist/utils/map.js.map +1 -0
  413. package/dist/utils/serial.d.ts +2 -0
  414. package/dist/utils/serial.d.ts.map +1 -1
  415. package/dist/utils/serial.js +9 -0
  416. package/dist/utils/serial.js.map +1 -1
  417. package/dist/validation/capability-gate.d.ts +7 -15
  418. package/dist/validation/capability-gate.d.ts.map +1 -1
  419. package/dist/validation/capability-gate.js +32 -36
  420. package/dist/validation/capability-gate.js.map +1 -1
  421. package/dist/validation/crypto-gate.d.ts.map +1 -1
  422. package/dist/validation/crypto-gate.js +12 -21
  423. package/dist/validation/crypto-gate.js.map +1 -1
  424. package/docs/README.md +1 -0
  425. package/docs/actions.md +32 -25
  426. package/docs/agents.md +28 -16
  427. package/docs/automations.md +1 -1
  428. package/docs/blueprints-and-guides.md +37 -5
  429. package/docs/building-an-app.md +7 -4
  430. package/docs/collections.md +3 -3
  431. package/docs/contacts.md +34 -1
  432. package/docs/contracts.md +1 -1
  433. package/docs/direct-messages.md +6 -2
  434. package/docs/inbox.md +5 -11
  435. package/docs/node.md +54 -22
  436. package/docs/records-and-queries.md +1 -1
  437. package/docs/sign-in.md +54 -26
  438. package/docs/spaces.md +9 -8
  439. package/docs/standard-library.md +37 -14
  440. package/docs/storage.md +5 -6
  441. package/docs/usernames.md +161 -0
  442. package/docs/warrants.md +1 -1
  443. package/package.json +1 -2
@@ -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
12
  import { createSpaceFiles, DEVICE_LIMITS } 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
- }
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,3362 +48,285 @@ 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),
295
- });
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
- }
774
- 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;
1428
- }
1429
- /** Whether a version from outside — a peer, a folder — may be stored */
1430
- async function admit(version) {
1431
- const verdict = await admitOnce(version);
1432
- // Refused for good, or a change to who may do what: perhaps proof of a broken rule (docs/warrants.md).
1433
- if ((!verdict.ok && !verdict.later && !verdict.withdrawn) || ACCESS_COLLECTIONS.has(version.collection))
1434
- void warrantIfDue(version).catch(() => { });
1435
- return verdict;
1436
- }
1437
- async function admitOnce(version) {
1438
- // Before any cached verdict: a copy with another envelope or body shares the id and signature.
1439
- const problem = await copyProblem(version);
1440
- if (problem)
1441
- return { ok: false, reason: problem };
1442
- // 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
- // A schema the validator can't build (a bad $id in an annotation, say)
1601
- // checks nothing, like a definition that is invalid (spec 02 §6.1).
1602
- try {
1603
- return validateJsonSchema(described.schema, body);
1604
- }
1605
- catch {
1606
- return null;
1607
- }
1608
- }
1609
- if (schemas.getCollection(collection)) {
1610
- const checked = await schemas.validate(collection, body);
1611
- return (checked.issues ?? []).map((issue) => ({ path: '/', message: issue.message }));
1612
- }
1613
- return null;
1614
- }
1615
- /**
1616
- * Issues with a record's links against its collection's declaration. Only
1617
- * what can be judged from what is held: a link to a record not here yet is
1618
- * fine — you routinely hold a reaction before its post.
1619
- */
1620
- async function linkIssues(collection, links) {
1621
- const malformed = checkLinks(links);
1622
- if (malformed)
1623
- return [{ path: '/links', message: malformed }];
1624
- if (links.length === 0)
1625
- return [];
1626
- const declared = (await definitionOf(collection))?.links;
1627
- // An undescribed collection says nothing about its links, so nothing is wrong.
1628
- if (!declared)
1629
- return (await definitionOf(collection))
1630
- ? [{ path: '/links', message: `${collection} declares no links` }]
1631
- : [];
1632
- const issues = [];
1633
- const perRole = new Map();
1634
- for (const [index, link] of links.entries()) {
1635
- const declaration = declared[link.rel];
1636
- if (!declaration) {
1637
- issues.push({
1638
- path: `/links/${index}`,
1639
- message: `${collection} has no "${link.rel}" link (it has: ${Object.keys(declared).join(', ')})`,
1640
- });
1641
- continue;
1642
- }
1643
- perRole.set(link.rel, (perRole.get(link.rel) ?? 0) + 1);
1644
- if (declaration.to === '*')
1645
- continue;
1646
- const target = await currentOf(link.to);
1647
- if (target && !target.deleted && !declaration.to.includes(target.collection)) {
1648
- issues.push({
1649
- path: `/links/${index}`,
1650
- message: `"${link.rel}" must point at ${declaration.to.join(' or ')}, not ${target.collection}`,
1651
- });
1652
- }
1653
- }
1654
- for (const [rel, count] of perRole) {
1655
- if (declared[rel]?.cardinality === 'one' && count > 1)
1656
- issues.push({ path: '/links', message: `At most one "${rel}" link` });
1657
- }
1658
- return issues;
1659
- }
1660
- /** Shape and link issues together; null when neither has anything to check against. */
1661
- async function contentIssues(collection, body, links) {
1662
- const shape = await shapeIssues(collection, body);
1663
- const linked = await linkIssues(collection, links);
1664
- if (shape === null && linked.length === 0 && !(await definitionOf(collection)))
1665
- return null;
1666
- return [...(shape ?? []), ...linked];
1667
- }
1668
- function describe(name, entry, records) {
1669
- const definition = entry?.definition;
1670
- const usable = usableComputed(definition?.computed, definition?.schema);
1671
- return Object.freeze({
1672
- name,
1673
- ...(definition?.title !== undefined ? { title: definition.title } : {}),
1674
- ...(definition?.description !== undefined ? { description: definition.description } : {}),
1675
- schema: definition?.schema ?? null,
1676
- version: definition?.version ?? null,
1677
- history: definition?.history ?? 'latest',
1678
- links: definition?.links ?? {},
1679
- definedBy: entry?.definedBy ?? null,
1680
- rules: definition?.rules ?? {},
1681
- ...(definition?.contract !== undefined ? { contract: definition.contract } : {}),
1682
- // Only what every reader can use: a definition written by hand arrives unchecked.
1683
- ...(usable !== undefined ? { computed: usable } : {}),
1684
- topics: definition?.topics ?? [],
1685
- records,
1686
- });
1687
- }
1688
- // ─── What points where ─────────────────────────────────────────────
1689
- //
1690
- // Derived from the records held, rebuilt when they change, never synced: any
1691
- // node holding the records can build it, and derived data travelling between
1692
- // peers would only be one more thing to disagree about.
1693
- let linkIndexCache = null;
1694
- const linkIndex = () => (linkIndexCache ??= buildLinkIndex());
1695
- async function buildLinkIndex() {
1696
- const index = new Map();
1697
- for (const version of await everyCurrent()) {
1698
- if (version.deleted)
1699
- continue;
1700
- const { links } = await openBody(version);
1701
- for (const link of links) {
1702
- const list = index.get(link.to) ?? [];
1703
- list.push({ rel: link.rel, from: version.key });
1704
- index.set(link.to, list);
1705
- }
1706
- }
1707
- return index;
1708
- }
1709
- // ─── Profiles ──────────────────────────────────────────────────────
1710
- //
1711
- // Each person says who they are in a space with one record, keyed by their
1712
- // identity (`profileKey`), whose versions are always retained. The fold
1713
- // takes the newest version signed by the identity the key names, so nobody
1714
- // can rename anyone else: a version written by someone else under your key
1715
- // is simply never the answer, and it cannot push yours out, because yours
1716
- // are kept.
1717
- let profilesCache = null;
1718
- const profileMap = () => (profilesCache ??= loadProfiles());
1719
- async function loadProfiles() {
1720
- const result = new Map();
1721
- // By key: the current version may be anyone's.
1722
- for (const [key, versions] of await storage.histories('profile:')) {
1723
- let found = null;
1724
- for (const version of versions) {
1725
- if (version.collection !== PROFILE_COLLECTION)
1726
- continue;
1727
- const verdict = await judge(version);
1728
- if (!verdict.verified || !verdict.root || (await profileKey(verdict.root)) !== key)
1729
- continue;
1730
- if (!(await standingOf(version)).ok)
1731
- continue;
1732
- if (version.deleted)
1733
- break; // they took it down
1734
- const opened = (await openBody(version)).body;
1735
- const body = isRecord(opened) ? opened : null;
1736
- if (!found) {
1737
- const name = body?.name;
1738
- if (typeof name !== 'string' || !name.trim())
1739
- break;
1740
- found = { did: verdict.root, name: name.trim().slice(0, 64), updatedAt: version.createdAt };
1741
- }
1742
- // The picture, from the newest version: one without it shows none (the older stay kept, as retained).
1743
- if (!found.avatar && found.updatedAt === version.createdAt && isAvatarRef(body?.avatar))
1744
- found = { ...found, avatar: body.avatar };
1745
- // The contact key from the newest version that has one: it never changes, and an app
1746
- // without it that wrote a newer version first must not hide it.
1747
- if (isContactPublicKey(body?.contactKey)) {
1748
- found = { ...found, contactKey: body.contactKey };
1749
- break;
1750
- }
1751
- }
1752
- if (found)
1753
- result.set(found.did, found);
1754
- }
1755
- return result;
1756
- }
1757
- /**
1758
- * Each member's member key, from their own record of it — kept in the
1759
- * clear, so someone who holds only an older key of the space can still say
1760
- * where to seal the new one.
1761
- */
1762
- let memberKeysCache = null;
1763
- const memberKeyMap = () => (memberKeysCache ??= loadMemberKeys());
1764
- /** Every key box, read once until records change */
1765
- let boxCache = null;
1766
- const boxIndex = () => (boxCache ??= storage.histories('box:'));
1767
- async function loadMemberKeys() {
1768
- const found = new Map();
1769
- // By key: the current version may be anyone's.
1770
- for (const [key, versions] of await storage.histories('memberkey:')) {
1771
- for (const version of versions) {
1772
- if (version.collection !== MEMBER_KEY_COLLECTION || version.deleted)
1773
- continue;
1774
- const verdict = await judge(version);
1775
- if (!verdict.verified || !verdict.root || (await memberKeyRecordKey(verdict.root)) !== key)
1776
- continue;
1777
- if (!(await standingOf(version)).ok)
1778
- continue;
1779
- const body = isRecord(version.body) ? version.body : null;
1780
- if (isContactPublicKey(body?.key)) {
1781
- found.set(verdict.root, body.key);
1782
- break;
1783
- }
1784
- }
1785
- }
1786
- return found;
1787
- }
1788
- /**
1789
- * Records changed: whatever is derived from them may have too. Given the
1790
- * versions that were placed, and none of them the space's own (`sys.`),
1791
- * only what those records feed is thrown away: who may do what, the
1792
- * definitions and the keys come from `sys.` records alone, so every other
1793
- * verdict still holds. Given nothing — another tab, a folder, new keys —
1794
- * everything is.
1795
- */
1796
- let spaceFiles = null;
1797
- const missingFiles = () => {
1798
- throw new Error('The space is still opening');
1799
- };
1800
- let filesTimer = null;
1801
- /** One pass at a time; a change during one runs another after it */
1802
- let filesPass = null;
1803
- let filesAgain = false;
1804
- /** After a change: which files are named is worked out again, and soon kept, dropped and fetched to match */
1805
- function filesChanged() {
1806
- spaceFiles?.changed();
1807
- if (filesPass) {
1808
- filesAgain = true;
1809
- return;
1810
- }
1811
- if (filesTimer || closed)
1812
- return;
1813
- filesTimer = setTimeout(() => {
1814
- filesTimer = null;
1815
- filesPass = (async () => {
1816
- await spaceFiles?.tidy();
1817
- await spaceFiles?.fetchMissing();
1818
- })()
1819
- .catch(() => {
1820
- // A peer or mirror out of reach; the next change tries again.
1821
- })
1822
- .finally(() => {
1823
- filesPass = null;
1824
- if (filesAgain && !closed) {
1825
- filesAgain = false;
1826
- filesChanged();
1827
- }
1828
- });
1829
- }, 2000);
1830
- unref(filesTimer);
1831
- }
1832
- const recordsChanged = (placed) => {
1833
- filesChanged();
1834
- if (placed)
1835
- noteArrived(placed);
1836
- linkIndexCache = null;
1837
- emit({ type: 'records', space: space.id });
1838
- for (const mirror of mirrors)
1839
- mirror.changed();
1840
- if (placed && placed.every((version) => !version.collection.startsWith('sys.'))) {
1841
- for (const version of placed)
1842
- staleKeys.add(version.key);
1843
- // A record waiting on a version it cites may count now.
1844
- for (const key of pendingKeys)
1845
- staleKeys.add(key);
1846
- pendingKeys.clear();
1847
- // A version in a line can make a double spend of one that counted, and undo what cites it.
1848
- if (placed.some((version) => lineCollections.has(version.collection))) {
1849
- checkVerdicts.clear();
1850
- countedIndex = null;
1851
- for (const version of placed)
1852
- lineIndexes.delete(version.collection);
1853
- }
1854
- return;
1855
- }
1856
- countedIndex = null;
1857
- catalogCache = null;
1858
- profilesCache = null;
1859
- memberKeysCache = null;
1860
- boxCache = null;
1861
- accessCache = placed && accessCache ? extendAccess(accessCache, placed) : null;
1862
- standings.clear();
1863
- checkVerdicts.clear();
1864
- lineIndexes.clear();
1865
- keepUp();
1866
- // The access history may name keepers now, or none.
1867
- void refreshHolds().catch(() => { });
1868
- // Or a new key, which someone connected may not hold.
1869
- void letGoOfOutsiders().catch(() => { });
1870
- };
1871
- // ─── The space's keys ──────────────────────────────────────────────
1872
- //
1873
- // A private space's key changes when someone loses their place in it
1874
- // (`sys.key`, part of the access history): whoever manages the space makes
1875
- // a new one, and seals a copy to each member's member key (`sys.box`). The
1876
- // key record carries every earlier key sealed under the new one, so holding
1877
- // the current key opens everything written before it — which is how
1878
- // someone who joins later reads the old records, and someone removed reads
1879
- // nothing new. This is how Keybase changes a team's key.
1880
- /** The key the history names now, if this node holds it */
1881
- function currentKey(state) {
1882
- const epoch = state.keys.at(-1);
1883
- return epoch ? (keyring.get(epoch.keyId) ?? null) : null;
1884
- }
1885
- /** The newest key this node holds that the history names — what it proves it may read with while behind */
1886
- function newestKey(state) {
1887
- for (const epoch of [...state.keys].reverse()) {
1888
- const held = keyring.get(epoch.keyId);
1889
- if (held)
1890
- return held;
1891
- }
1892
- return record.key;
1893
- }
1894
- /** Box and key record versions already opened, so each is tried once */
1895
- const opened = new Set();
1896
- /**
1897
- * Key records already opened, for the keys the history named then. Which
1898
- * key event counts, and which keys it names, can change as changes arrive,
1899
- * so they are opened again when that does.
1900
- */
1901
- const openedKeyRecords = new Set();
1902
- let openedFor = '';
1903
- /**
1904
- * Keys whose key change is malformed: its earlier keys don't open, or leave
1905
- * out the space's first key, which every reader needs for onePer keys
1906
- * (03 §9.3). Nothing is taken from them, and a manager replaces them.
1907
- */
1908
- const malformedKeys = new Set();
1909
- /** Takes in what this node can open: boxes sealed to its member key, and the earlier keys each key record carries */
1910
- async function learnKeys() {
1911
- const { history } = await access();
1912
- const epochs = history.current.keys;
1913
- const learned = [];
1914
- const take = (found) => {
1915
- if (keyring.has(found.id))
1916
- return false;
1917
- keyring.set(found.id, found);
1918
- learned.push(found);
1919
- return true;
1920
- };
1921
- if (memberPair && epochs.some((epoch) => !keyring.has(epoch.keyId))) {
1922
- for (const versions of (await boxIndex()).values()) {
1923
- for (const version of versions) {
1924
- if (version.collection !== BOX_COLLECTION || version.deleted || opened.has(version.id))
1925
- continue;
1926
- const body = isRecord(version.body) ? version.body : null;
1927
- if (body?.to !== deps.rootDid || typeof body.keyId !== 'string' || typeof body.sealed !== 'string')
1928
- continue;
1929
- const epoch = epochs.find((known) => known.keyId === body.keyId);
1930
- if (!epoch || keyring.has(epoch.keyId))
1931
- continue;
1932
- opened.add(version.id);
1933
- const content = await openValueFrom(memberPair, BOX_LABEL, boxBound(space.id, epoch.keyId, deps.rootDid), body.sealed);
1934
- if (!isRecord(content) || typeof content.key !== 'string')
1935
- continue;
1936
- // Whoever sealed it, it is the key the history names or it is nothing.
1937
- const found = await spaceKeyFromRaw(base64UrlDecode(content.key)).catch(() => null);
1938
- if (found?.id === epoch.keyId && (await deriveReadKey(found, provider)).did === epoch.readKey)
1939
- take(found);
1940
- }
1941
- }
1942
- }
1943
- const named = epochs.map((epoch) => `${epoch.keyId}/${epoch.readKey}/${epoch.event}`).join('|');
1944
- if (named !== openedFor) {
1945
- openedFor = named;
1946
- openedKeyRecords.clear();
1947
- malformedKeys.clear();
1948
- }
1949
- // Each newer key opens the ones before it — which may open more.
1950
- let more = true;
1951
- while (more) {
1952
- more = false;
1953
- for (const versions of (await storage.histories('key:')).values()) {
1954
- for (const version of versions) {
1955
- const body = isRecord(version.body) ? version.body : null;
1956
- if (version.collection !== KEY_COLLECTION ||
1957
- openedKeyRecords.has(version.id) ||
1958
- typeof body?.keyId !== 'string')
1959
- continue;
1960
- // Only the key change that counted for that key: anyone may store a version at `key:space`.
1961
- const epoch = epochs.find((known) => known.keyId === body.keyId);
1962
- if (!epoch || epoch.event !== version.id)
1963
- continue;
1964
- const holder = keyring.get(body.keyId);
1965
- if (!holder)
1966
- continue;
1967
- openedKeyRecords.add(version.id);
1968
- const earlier = await openValue(holder.seal, EARLIER_KEYS_LABEL, { space: space.id, keyId: holder.id }, body.earlier);
1969
- const found = [];
1970
- for (const raw of isStringList(earlier) ? earlier.slice(0, 1000) : []) {
1971
- const key = await spaceKeyFromRaw(base64UrlDecode(raw)).catch(() => null);
1972
- if (key)
1973
- found.push(key);
1974
- }
1975
- // Without the first key, a reader holding only this one couldn't derive onePer keys (02 §7.3).
1976
- if (!isStringList(earlier) || !found.some((key) => key.id === space.encryptionKeyId)) {
1977
- malformedKeys.add(body.keyId);
1978
- continue;
1979
- }
1980
- // And only keys the history names, each with the read key it names.
1981
- for (const key of found) {
1982
- const named = epochs.find((known) => known.keyId === key.id);
1983
- if (named && (await deriveReadKey(key, provider)).did === named.readKey && take(key))
1984
- more = true;
1985
- }
1986
- }
1987
- }
1988
- }
1989
- if (learned.length === 0)
1990
- return;
1991
- // A definition this node couldn't read may open now.
1992
- definitions.clear();
1993
- const writeWith = newestKey((await access()).history.current);
1994
- if (writeWith)
1995
- await deps.onKeys?.([...keyring.values()], writeWith.id);
1996
- recordsChanged();
1997
- }
1998
- /** Makes a new key current, with every key before it sealed inside, and seals it to each member */
1999
- async function rotateKey() {
2000
- if (space.visibility !== 'private')
2001
- throw new Error('A public space has no key to change');
2002
- const { history } = await access();
2003
- if (!may(history.current, deps.rootDid, KEY_CHANGE, {}))
2004
- throw new Error(`Only someone granted ${KEY_CHANGE} in "${space.name}" can change its key`);
2005
- if (!currentKey(history.current))
2006
- throw new Error(`This device doesn't hold the current key of "${space.name}" yet`);
2007
- // Every key change carries the first key, so every reader holds it (03 §9.3).
2008
- if (!space.encryptionKeyId || !keyring.has(space.encryptionKeyId))
2009
- throw new Error(`This device doesn't hold the first key of "${space.name}"`);
2010
- const next = await generateSpaceKey();
2011
- const earlier = [...keyring.values()].map((held) => base64UrlEncode(held.raw));
2012
- const body = {
2013
- keyId: next.id,
2014
- readKey: (await deriveReadKey(next, provider)).did,
2015
- earlier: await sealValue(next.seal, EARLIER_KEYS_LABEL, { space: space.id, keyId: next.id }, earlier),
2016
- };
2017
- keyring.set(next.id, next);
2018
- try {
2019
- await upsert(KEY_COLLECTION, SPACE_KEY_RECORD, body);
2020
- }
2021
- catch (error) {
2022
- keyring.delete(next.id);
2023
- throw error;
2024
- }
2025
- await deps.onKeys?.([...keyring.values()], next.id);
2026
- await boxForMembers();
2027
- }
2028
- /**
2029
- * Seals the current key to each member who has no copy from someone who
2030
- * manages the space. Members show their member key on their profile; one
2031
- * who hasn't yet gets their copy once they do.
2032
- */
2033
- async function boxForMembers() {
2034
- const { history } = await access();
2035
- const state = history.current;
2036
- const epoch = state.keys.at(-1);
2037
- const key = currentKey(state);
2038
- if (!epoch || !key)
2039
- return;
2040
- const boxed = new Set();
2041
- for (const versions of (await boxIndex()).values()) {
2042
- for (const version of versions) {
2043
- const body = isRecord(version.body) ? version.body : null;
2044
- if (version.collection !== BOX_COLLECTION ||
2045
- body?.keyId !== epoch.keyId ||
2046
- typeof body.to !== 'string')
2047
- continue;
2048
- const { root } = await judge(version);
2049
- if (root && (root === deps.rootDid || may(state, root, KEY_CHANGE, {})))
2050
- boxed.add(body.to);
2051
- }
2052
- }
2053
- const memberKeys = await memberKeyMap();
2054
- const raw = base64UrlEncode(key.raw);
2055
- for (const did of [...readers(state)].sort()) {
2056
- const publicKey = memberKeys.get(did);
2057
- if (boxed.has(did) || !publicKey)
2058
- continue;
2059
- const sealed = await sealValueTo(publicKey, BOX_LABEL, boxBound(space.id, epoch.keyId, did), {
2060
- key: raw,
2061
- });
2062
- await upsert(BOX_COLLECTION, await boxKey(epoch.keyId, did, deps.rootDid), {
2063
- keyId: epoch.keyId,
2064
- to: did,
2065
- sealed,
2066
- });
2067
- }
2068
- }
2069
- /**
2070
- * Keeps the keys in step with the history: says where to seal this
2071
- * account's copy, learns what it can, and — managing the space — changes
2072
- * the key when due and seals it to whoever lacks it.
2073
- */
2074
- async function upkeep() {
2075
- // A note that can't change access keeps no keys for others: it only reads.
2076
- if (!grantsBeyondRecords(session.proof(), space.id, ACCESS_COMMAND)) {
2077
- if (space.visibility === 'private')
2078
- await learnKeys();
2079
- return;
2080
- }
2081
- await nameRelays();
2082
- if (space.visibility !== 'private')
2083
- return;
2084
- if (deps.accountOnly) {
2085
- await learnKeys();
2086
- return;
2087
- }
2088
- const mine = await memberKeyMap();
2089
- if (memberPair &&
2090
- mine.get(deps.rootDid) !== memberPair.publicKey &&
2091
- actsForAccount(session.proof()) &&
2092
- !(await cannotWrite())) {
2093
- await upsert(MEMBER_KEY_COLLECTION, await memberKeyRecordKey(deps.rootDid), {
2094
- key: memberPair.publicKey,
2095
- });
2096
- }
2097
- await learnKeys();
2098
- const { history } = await access();
2099
- const state = history.current;
2100
- if (!currentKey(state))
2101
- return;
2102
- if (!may(state, deps.rootDid, KEY_CHANGE, {}))
2103
- return;
2104
- // A current key whose change left out the first key is replaced, as one that is due.
2105
- const malformed = malformedKeys.has(state.keys.at(-1)?.keyId ?? '');
2106
- if (state.keyDue || (malformed && space.encryptionKeyId && keyring.has(space.encryptionKeyId)))
2107
- await rotateKey();
2108
- else
2109
- await boxForMembers();
2110
- }
2111
- /**
2112
- * A space nobody has said where to meet yet: whoever manages it names the
2113
- * relays this node uses, so the invites and devices that follow meet there.
2114
- */
2115
- async function nameRelays() {
2116
- const own = usableRelays(deps.network).slice(0, MAX_RELAYS);
2117
- if (own.length === 0)
2118
- return;
2119
- const { history } = await access();
2120
- if (history.current.relays.length > 0 || !may(history.current, deps.rootDid, SPACE_RELAYS, {}))
2121
- return;
2122
- await upsert(RELAYS_COLLECTION, SPACE_RELAYS_RECORD, { relays: own });
2123
- }
2124
- /** Runs the upkeep once more after whatever changed — one run at a time */
2125
- const keepingUp = serial(async () => {
2126
- if (closed)
2127
- return;
2128
- await upkeep().catch(() => {
2129
- // A write refused, a peer's junk: the next change tries again.
2130
- });
2131
- });
2132
- function keepUp() {
2133
- if (!closed)
2134
- void keepingUp();
2135
- }
2136
- /** The read key each peer checked here was let in on, by session DID, and when */
2137
- const admittedOn = new Map();
2138
- /** How this node proves it may read, and checks the peers that connect — against the history at that moment */
2139
- const readAccess = space.visibility !== 'private'
2140
- ? null
2141
- : {
2142
- async key() {
2143
- const held = newestKey((await access()).history.current);
2144
- // A carrier holds the read key pair without the key it comes from: it may be served the space, and cannot open it.
2145
- return held ? deriveReadKey(held, provider) : (record.read ?? null);
2146
- },
2147
- current: () => currentReadKey,
2148
- async earlier() {
2149
- const { current } = (await access()).history;
2150
- const newest = newestKey(current);
2151
- const older = [...current.keys]
2152
- .reverse()
2153
- .map((epoch) => keyring.get(epoch.keyId))
2154
- .filter((held) => held !== undefined && held !== newest);
2155
- return Promise.all(older.slice(0, MAX_EARLIER_READ_KEYS).map((held) => deriveReadKey(held, provider)));
2156
- },
2157
- async membership() {
2158
- const held = newestKey((await access()).history.current);
2159
- return held ? sealValue(held.seal, MEMBERSHIP_LABEL, { space: space.id }, session.proof()) : null;
2160
- },
2161
- async admits(peerDid, readKey, membership) {
2162
- const { history } = await access();
2163
- const epoch = history.current.keys.find((known) => known.readKey === readKey);
2164
- const held = epoch ? keyring.get(epoch.keyId) : undefined;
2165
- if (!held)
2166
- return false;
2167
- const { account } = await accountOf(peerDid, await openValue(held.seal, MEMBERSHIP_LABEL, { space: space.id }, membership));
2168
- return account !== null && readers(history.current).has(account);
2169
- },
2170
- async removed(peerDid, readKey, membership) {
2171
- const { history } = await access();
2172
- const epoch = history.current.keys.find((known) => known.readKey === readKey);
2173
- const held = epoch ? keyring.get(epoch.keyId) : undefined;
2174
- if (!held)
2175
- return false;
2176
- const note = await openValue(held.seal, MEMBERSHIP_LABEL, { space: space.id }, membership);
2177
- const { account } = await accountOf(peerDid, note);
2178
- return account !== null && (await formerMembers({ untilNewKey: true })).has(account);
2179
- },
2180
- admitted(peerDid, readKey) {
2181
- admittedOn.set(peerDid, { readKey, at: Date.now() });
2182
- },
2183
- };
2184
- // ─── Mirrors ───────────────────────────────────────────────────────
2185
- //
2186
- // Every mirror is one more peer: what it holds goes through the same gates
2187
- // as a peer's records, and what this node holds goes out to it.
2188
- /** What a mirror holds goes through the same gates as a peer's records */
2189
- const fromMirror = async (version) => {
2190
- const verdict = await admit(version);
2191
- if (!verdict.ok && !verdict.withdrawn)
2192
- return verdict.later ? 'later' : 'refused';
2193
- await storage.addVersion(version);
2194
- return 'stored';
2195
- };
2196
- const mirrors = [];
2197
- for (const [index, store] of (deps.mirrors ?? []).entries()) {
2198
- mirrors.push(await createMirror({
2199
- store,
2200
- space: space.id,
2201
- storage,
2202
- state: await deps.stores(`mirrors/${space.id}/${index}`),
2203
- accept: fromMirror,
2204
- }));
2205
- }
2206
- // A data folder is one more: its spaces are segments, like a bucket's, and
2207
- // what this device holds of them is its own (`node/stores.ts`).
2208
- const folderMirror = deps.stores.folder
2209
- ? await createMirror({
2210
- store: deps.stores.folder,
2211
- space: space.id,
2212
- storage,
2213
- state: await deps.stores(`folder/${space.id}`),
2214
- accept: fromMirror,
2215
- // Apps and the CLI on one computer meet through the folder: soon, not in a bucket's time.
2216
- flushMs: 1000,
2217
- })
2218
- : null;
2219
- if (folderMirror)
2220
- mirrors.push(folderMirror);
2221
- /** Reads every mirror in the background: a space that opens from nothing — a host that lost its disk — fills in as it goes */
2222
- const pullMirrors = () => Promise.all(mirrors.map((mirror) => mirror
2223
- .pull()
2224
- .then(({ added }) => {
2225
- if (added === 0)
2226
- return;
2227
- recordsChanged();
2228
- announceSoon();
2229
- })
2230
- .catch(() => {
2231
- // Out of reach now; what this node holds goes out on the next change.
2232
- })));
2233
- // ─── Peers ─────────────────────────────────────────────────────────
2234
- /** How the first connect went; after that, what the networks say now (`liveConnection`) */
2235
- let connection = 'offline';
2236
- let rejected = 0;
2237
- const networks = [];
2238
- const reachable = () => networks.some((network) => network.isConnected());
2239
- /**
2240
- * Connected while some network is: a relay reachable, or a peer. Once up, a
2241
- * space whose relays are all gone and whose peers have left is trying again,
2242
- * not connected; one whose first try failed is connected once a retry works.
2243
- */
2244
- const liveConnection = () => {
2245
- if (connection === 'offline')
2246
- return connection;
2247
- if (reachable())
2248
- return 'connected';
2249
- return connection === 'connected' ? 'connecting' : connection;
2250
- };
2251
- let shown = null;
2252
- // Relays come and go without a peer doing so; say so when that changes how this space connects.
2253
- const stopWatchingMesh = deps.mesh?.subscribe(() => {
2254
- const now = liveConnection();
2255
- if (now === shown)
2256
- return;
2257
- shown = now;
2258
- emit({ type: 'status', space: space.id });
2259
- });
2260
- /** Which network a peer was met on, so replies go back the same way */
2261
- const routes = new Map();
2262
- // ─── Files ─────────────────────────────────────────────────────────
2263
- //
2264
- // Named on the outside of the versions that refer to them, fetched chunk by
2265
- // chunk and checked as they come, kept while a body that names them is
2266
- // (spec 05 §16.6).
2267
- spaceFiles = createSpaceFiles({
2268
- space: space.id,
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,
2269
56
  adapter,
2270
57
  storage,
2271
- send: (peer, message) => routes.get(peer)?.send(peer, {
2272
- type: 'sync',
2273
- from: session.did,
2274
- payload: { ...message, v: SYNC_PROTOCOL_VERSION },
2275
- }),
2276
- peers: () => connectedPeers(),
2277
- mirrors: () => mirrors.map((mirror) => ({ store: mirror.store, writer: mirror.writer })),
2278
- stands: async (version) => {
2279
- const standing = await standingOf(version);
2280
- return standing.ok || !!standing.withdrawn;
2281
- },
2282
- // Files follow records: every file a version kept whole names is fetched, within a device's limits.
2283
- ...(deps.fetchFiles === 'all' ? {} : { limits: DEVICE_LIMITS }),
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(),
2284
67
  });
2285
- const sync = createSyncEngine({
2286
- storageProvider: storage,
2287
- self: session.did,
2288
- holds,
2289
- files: (peer, message) => spaceFiles?.onMessage(peer, message) ?? Promise.resolve(),
2290
- sendToPeer: (peerId, message) => {
2291
- routes.get(peerId)?.send(peerId, { type: 'sync', from: session.did, payload: message });
2292
- },
2293
- validate: async (version) => {
2294
- const verdict = await admit(version);
2295
- return verdict.ok || verdict.withdrawn
2296
- ? { valid: true }
2297
- : { valid: false, reason: verdict.reason, ...(verdict.later ? { later: true } : {}) };
2298
- },
2299
- });
2300
- /**
2301
- * Tells every connected peer this node's root, soon after it took in
2302
- * something new — from a peer or from a folder. Without it, a record passed
2303
- * along waits for the next heartbeat at every hop: a carrier would sit on a
2304
- * friend's write for half a minute before the pod, or your phone, heard of
2305
- * it. A peer already level answers and nothing moves.
2306
- */
2307
- let announceTimer = null;
2308
- const announceSoon = () => {
2309
- if (announceTimer)
2310
- return;
2311
- announceTimer = setTimeout(() => {
2312
- announceTimer = null;
2313
- sync.notifyPeers(connectedPeers());
2314
- }, 100);
2315
- };
2316
- // Once per message from a peer, with everything it brought.
2317
- sync.on('received', (versions) => {
2318
- recordsChanged(versions);
2319
- announceSoon();
2320
- for (const version of versions)
2321
- deps.onArrived?.(version);
2322
- });
2323
- sync.on('rejected', (peer, _version, reason) => {
2324
- rejected += 1;
2325
- emit({ type: 'rejected', space: space.id, peer, reason });
2326
- });
2327
- // Both sides of a socket to a node prove who they are; in a private space the client also proves it may read.
2328
- let authenticator = null;
2329
- /** A socket to an always-on node, for this space */
2330
- function nodeNetwork(node) {
2331
- authenticator ??= createClientAuth(space.id, session, readAccess, provider);
2332
- // The space goes in the query, before any pin in the fragment.
2333
- const [base = '', ...pin] = node.split('#');
2334
- const url = `${base}${base.includes('?') ? '&' : '?'}space=${encodeURIComponent(space.id)}${pin.length ? `#${pin.join('#')}` : ''}`;
2335
- const auth = authenticator;
2336
- return createNetworkManager({
2337
- did: session.did,
2338
- createTransport: () => createWebSocketTransport({ url, did: session.did, authenticator: auth }),
2339
- });
2340
- }
2341
- /** Sockets to the hosts the account or the space uses, by address: they change while the space is open */
2342
- const hostNetworks = new Map();
2343
- const net = deps.network;
2344
- if (net) {
2345
- // Who is at the other end is asked of the history at each handshake: the space's key may change while it is open.
2346
- await access();
2347
- if (deps.mesh) {
2348
- meshRoom = await relayRoom(space.id);
2349
- deps.mesh.useRelays(meshRoom, relays);
2350
- // Every peer met through a relay proves who it is, and in a private space that it may read.
2351
- networks.push(deps.mesh.join(meshRoom, createMeshAuth(space.id, session, readAccess, provider)));
2352
- }
2353
- for (const node of net.nodes ?? [])
2354
- networks.push(nodeNetwork(node));
2355
- for (const transport of net.transports?.(space.id, session.did) ?? []) {
2356
- networks.push(createNetworkManager({ did: session.did, createTransport: () => transport }));
2357
- }
2358
- }
2359
- const connectedPeers = () => [
2360
- ...new Set(networks.flatMap((network) => network.getPeers().map((peer) => peer.did))),
2361
- ];
2362
- // ─── Live messages ─────────────────────────────────────────────────
2363
- //
2364
- // A connection proves which session key is at the other end — not whose it
2365
- // is. So the first thing each side sends is its note, the delegation from
2366
- // its account to that key: the same note its records carry. It names the
2367
- // key it was made out to, and that must be the key the connection proved,
2368
- // so a note copied off someone's record is no use to anyone else.
2369
- const peerAccounts = new Map();
2370
- /** Peers let go of because their account was removed, by session DID: turned away again when they redial */
2371
- const cutOff = new Map();
2372
- const knownAccounts = new Map();
2373
- const liveAllowance = new Map();
2374
- async function accountOf(peer, note) {
2375
- if (!isRecord(note) || canonicalize(note).length > MAX_NOTE_LENGTH)
2376
- return NO_ACCOUNT;
2377
- const checked = await verifyNote(note, provider).catch(() => null);
2378
- if (!checked?.valid || checked.audience !== peer)
2379
- return NO_ACCOUNT;
2380
- return {
2381
- account: checked.root,
2382
- // A key that writes records somewhere but can't define here. Judged on the
2383
- // whole note, so a key for another space doesn't pass as the account here.
2384
- // A note that only reads is not one: it writes nothing. The note is the
2385
- // account's own, one link, so its key can't sign itself a wider one.
2386
- recordsOnly: writesRecords(checked.note) && !grantsBeyondRecords(checked.note, space.id, DEFINE_COMMAND),
2387
- };
2388
- }
2389
- /** A peer's share of live messages: a burst, then a steady rate — as the relay limits them */
2390
- function withinAllowance(peer) {
2391
- const now = Date.now();
2392
- const held = liveAllowance.get(peer) ?? { tokens: LIVE_BURST, at: now };
2393
- const tokens = Math.min(LIVE_BURST, held.tokens + ((now - held.at) / 1000) * LIVE_PER_SECOND);
2394
- liveAllowance.set(peer, { tokens: Math.max(0, tokens - 1), at: now });
2395
- return tokens >= 1;
2396
- }
2397
- async function onLive(peer, payload) {
2398
- if (!withinAllowance(peer))
2399
- return;
2400
- if ((JSON.stringify(payload ?? null)?.length ?? 0) > MAX_LIVE_BYTES)
2401
- return;
2402
- const { account, recordsOnly } = (await peerAccounts.get(peer)) ?? NO_ACCOUNT;
2403
- // Gone while its note was being checked.
2404
- if (!routes.has(peer))
2405
- return;
2406
- if (account !== null && (await formerMembers()).has(account))
2407
- return;
2408
- emit({ type: 'message', space: space.id, from: account, peer, recordsOnly, message: payload });
2409
- }
2410
- /**
2411
- * Lets go of the peers a handshake would refuse now. A handshake checks a
2412
- * reader once, but the space's key changes when someone is removed: a peer
2413
- * let in on a key that is no longer current stays only while it acts for
2414
- * someone who may still read, as it would get in again (`checkRead`).
2415
- * Anyone else — someone removed, a view-only link from before — stops
2416
- * getting anything the moment this node knows the new key.
2417
- */
2418
- async function letGoOfOutsiders() {
2419
- const connected = new Set(connectedPeers());
2420
- // Someone removed is let go of as soon as this node knows, on any key:
2421
- // the key may not have changed yet, if nobody who manages the space is here.
2422
- const gone = await formerMembers({ untilNewKey: true });
2423
- for (const [peer, account] of cutOff)
2424
- if (!gone.has(account))
2425
- cutOff.delete(peer);
2426
- for (const peer of connected) {
2427
- const account = knownAccounts.get(peer)?.account ?? null;
2428
- if (account === null || !gone.has(account) || cutOff.has(peer))
2429
- continue;
2430
- cutOff.set(peer, account);
2431
- admittedOn.delete(peer);
2432
- // Nothing more goes to them from now; the socket closes a moment later,
2433
- // so what was already sent — the "stored" for their own leaving — arrives.
2434
- sync.removePeer(peer);
2435
- routes.delete(peer);
2436
- setTimeout(() => {
2437
- peerAccounts.delete(peer);
2438
- knownAccounts.delete(peer);
2439
- liveAllowance.delete(peer);
2440
- for (const network of networks)
2441
- network.drop(peer);
2442
- }, LET_GO_AFTER_MS);
2443
- }
2444
- if (admittedOn.size === 0)
2445
- return;
2446
- for (const [peer, { at }] of admittedOn) {
2447
- // Checked, and never let in: a handshake the other side refused.
2448
- if (!connected.has(peer) && Date.now() - at > STALE_ADMISSION_MS)
2449
- admittedOn.delete(peer);
2450
- }
2451
- const allowed = readers((await access()).history.current);
2452
- for (const peer of connected) {
2453
- const admission = admittedOn.get(peer);
2454
- if (!admission || admission.readKey === currentReadKey)
2455
- continue;
2456
- // Its note is said first, but may still be on its way; this runs again when it lands.
2457
- if (!peerAccounts.has(peer) && Date.now() - admission.at < WHO_WAIT_MS)
2458
- continue;
2459
- const { account } = (await peerAccounts.get(peer)) ?? NO_ACCOUNT;
2460
- if (account !== null && allowed.has(account))
2461
- continue;
2462
- // Let in again meanwhile, on the key it holds now.
2463
- if (admittedOn.get(peer) !== admission)
2464
- continue;
2465
- admittedOn.delete(peer);
2466
- for (const network of networks)
2467
- network.drop(peer);
2468
- }
2469
- }
2470
- function listen(network) {
2471
- network.on('message', (message) => {
2472
- if (message.type === 'sync')
2473
- void sync.handleMessage(message.from, message.payload);
2474
- else if (message.type === WHO_MESSAGE) {
2475
- const note = isRecord(message.payload) ? message.payload.note : undefined;
2476
- const checked = accountOf(message.from, note);
2477
- peerAccounts.set(message.from, checked);
2478
- void checked.then((known) => {
2479
- if (peerAccounts.get(message.from) !== checked)
2480
- return;
2481
- knownAccounts.set(message.from, known);
2482
- emit({ type: 'status', space: space.id });
2483
- void letGoOfOutsiders().catch(() => { });
2484
- });
2485
- }
2486
- else if (message.type === LIVE_MESSAGE)
2487
- void onLive(message.from, message.payload);
2488
- });
2489
- network.on('peer-connected', (info) => {
2490
- if (cutOff.has(info.did)) {
2491
- network.drop(info.did);
2492
- return;
2493
- }
2494
- // Said first, so it reaches them before any live message from here.
2495
- network.send(info.did, { type: WHO_MESSAGE, from: session.did, payload: { note: session.proof() } });
2496
- routes.set(info.did, network);
2497
- sync.addPeer(info.did);
2498
- // Reconcile at once rather than waiting for the heartbeat.
2499
- sync.notifyPeers([info.did]);
2500
- // It may hold a file nobody else had.
2501
- spaceFiles?.joined(info.did);
2502
- filesChanged();
2503
- emit({ type: 'status', space: space.id });
2504
- // The key may have changed between checking it and letting it in.
2505
- void letGoOfOutsiders().catch(() => { });
2506
- });
2507
- network.on('peer-disconnected', (info) => {
2508
- if (routes.get(info.did) === network) {
2509
- routes.delete(info.did);
2510
- sync.removePeer(info.did);
2511
- peerAccounts.delete(info.did);
2512
- knownAccounts.delete(info.did);
2513
- liveAllowance.delete(info.did);
2514
- }
2515
- if (!connectedPeers().includes(info.did))
2516
- admittedOn.delete(info.did);
2517
- emit({ type: 'status', space: space.id });
2518
- });
2519
- network.on('error', () => {
2520
- if (!networks.some((n) => n.isConnected()))
2521
- connection = 'error';
2522
- emit({ type: 'status', space: space.id });
2523
- });
2524
- }
2525
- for (const network of networks)
2526
- listen(network);
2527
- // Whether to hold part of the space is settled before the first hello says what this node holds.
2528
- await refreshHolds().catch(() => { });
2529
- if (networks.length > 0) {
2530
- connection = 'connecting';
2531
- // Online as soon as one way in works: a node that is slow to answer, or
2532
- // never does, must not keep the space saying "connecting" meanwhile.
2533
- void Promise.any(networks.map((network) => network.connect())).then(() => {
2534
- connection = 'connected';
2535
- emit({ type: 'status', space: space.id });
2536
- }, () => {
2537
- connection = 'error';
2538
- emit({ type: 'status', space: space.id });
2539
- });
2540
- sync.start();
2541
- }
2542
- // ─── Writers outside this process ──────────────────────────────────
2543
- //
2544
- // A data folder is written by other apps, and by other devices behind
2545
- // whatever syncs it; a directory store by another process (a command beside
2546
- // a daemon). Nothing announces either, so both are looked for.
2547
- /** Whether another writer changed anything this node holds */
2548
- const look = async () => {
2549
- // The same verdict as for a version from a peer.
2550
- const reconciled = isFolderAdapter(adapter)
2551
- ? (await reconcileFolder(storage, adapter, async (version) => storable(await admit(version)))).changed
2552
- : false;
2553
- const pulled = folderMirror ? (await folderMirror.pull()).added > 0 : false;
2554
- return reconciled || pulled;
68
+ const base = {
69
+ record,
70
+ space,
71
+ storage,
72
+ provider,
73
+ keyring,
74
+ session,
75
+ rootDid,
76
+ accountOnly: !!deps.accountOnly,
77
+ isClosed,
2555
78
  };
2556
- let watchTimer = null;
2557
- if (deps.watchIntervalMs > 0 && (folderMirror || isFolderAdapter(adapter))) {
2558
- let running = false;
2559
- watchTimer = setInterval(() => {
2560
- if (running)
79
+ // ─── Judging ───────────────────────────────────────────────────────
80
+ const meeting = createMeeting(record, deps.mesh, deps.onRelays);
81
+ let reportedRole;
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)
2561
90
  return;
2562
- running = true;
2563
- look()
2564
- .then((changed) => {
2565
- if (!changed)
2566
- return;
2567
- recordsChanged();
2568
- announceSoon();
2569
- })
2570
- .catch(() => {
2571
- // A revoked permission or a folder that went away; the next pass will tell.
2572
- })
2573
- .finally(() => {
2574
- running = false;
2575
- });
2576
- }, deps.watchIntervalMs);
2577
- }
2578
- // Tabs of one browser share one IndexedDB but not memory, so a write in one
2579
- // is invisible to the other until it is told. A nudge is enough: the store
2580
- // already holds the data.
2581
- const channel = typeof globalThis.BroadcastChannel === 'function'
2582
- ? new globalThis.BroadcastChannel(`minca-node:${deps.rootDid}:${space.id}`)
2583
- : null;
2584
- if (channel) {
2585
- channel.onmessage = () => {
2586
- // The other tab wrote to the store underneath: what sync compares is read again.
2587
- storage.invalidate();
2588
- recordsChanged();
2589
- };
2590
- // In Node a channel holds the process open; it must never be the only thing doing so.
2591
- unref(channel);
2592
- }
2593
- // ─── Holding part of the space ─────────────────────────────────────
2594
- //
2595
- // With `cache` set, and once the space names a keeper, this node holds only
2596
- // the collections it uses, besides the space's own. Sync takes in nothing
2597
- // else. Its own writes are pending until enough keepers have them, and a
2598
- // collection holding a pending write is never dropped. Without a keeper the
2599
- // space is held whole: then this node may be one of its copies.
2600
- const HOUR = 3_600_000;
2601
- const DAY = 24 * HOUR;
2602
- const declared = new Set((cache?.collections ?? []).filter((c) => !c.startsWith('sys.')));
2603
- let cacheTimer = null;
2604
- const saveCache = () => {
2605
- if (cacheTimer || !cache)
2606
- return;
2607
- cacheTimer = setTimeout(() => {
2608
- cacheTimer = null;
2609
- void adapter.put(CACHE_KEY, utf8Encode(JSON.stringify(cacheState))).catch(() => { });
2610
- }, 500);
2611
- unref(cacheTimer);
2612
- };
2613
- const flushCache = async () => {
2614
- if (!cacheTimer)
2615
- return;
2616
- clearTimeout(cacheTimer);
2617
- cacheTimer = null;
2618
- await adapter.put(CACHE_KEY, utf8Encode(JSON.stringify(cacheState))).catch(() => { });
2619
- };
2620
- saveCache();
2621
- /**
2622
- * Holds part of the space from the moment it names a keeper, and all of it
2623
- * again if it stops — once this node has caught up enough to know.
2624
- */
2625
- async function refreshHolds() {
2626
- if (!cache || closed)
2627
- return;
2628
- const next = (await access()).history.current.keepers.length > 0 || !cacheState.settled;
2629
- if (next === partial)
2630
- return;
2631
- partial = next;
2632
- // Peers learn what this node holds now; anything newly held comes across.
2633
- sync.notifyPeers(connectedPeers());
2634
- emit({ type: 'status', space: space.id });
2635
- }
2636
- /** Collections a query or a screen uses: held from now on. Whether all of them are here yet. */
2637
- function use(collections) {
2638
- if (!cache)
2639
- return true;
2640
- const now = Date.now();
2641
- let added = false;
2642
- for (const collection of collections) {
2643
- if (typeof collection !== 'string' || collection.startsWith('sys.'))
2644
- continue;
2645
- const was = cacheState.used[collection];
2646
- if (was === undefined)
2647
- added = true;
2648
- if (was === undefined || now - was > HOUR) {
2649
- cacheState.used[collection] = now;
2650
- saveCache();
2651
- }
2652
- }
2653
- if (added && partial)
2654
- sync.notifyPeers(connectedPeers());
2655
- return !partial || collections.every((c) => c.startsWith('sys.') || completeHere(c));
2656
- }
2657
- /** Level with a node holding everything once, and lacking nothing a writer's line in it names */
2658
- function completeHere(collection) {
2659
- return cacheState.level[collection] !== undefined && !(cacheState.missing[collection]?.length ?? 0);
2660
- }
2661
- /**
2662
- * Keeps track of what each writer's line in a held collection names that
2663
- * this node lacks: a version that names one not here adds it, and asks
2664
- * every peer for it; one that arrives takes itself off.
2665
- */
2666
- async function noteGap(version) {
2667
- if (!cache || !version.log || version.collection.startsWith('sys.'))
2668
- return;
2669
- const { collection } = version;
2670
- const missing = cacheState.missing[collection] ?? [];
2671
- const before = version.log.prev;
2672
- if (!before || missing.includes(before) || (await storage.getVersion(before)))
2673
- return;
2674
- cacheState.missing[collection] = [...missing, before];
2675
- sync.ask(collection, [before]);
2676
- saveCache();
2677
- // A query that said "complete" says so no longer.
2678
- if (partial)
2679
- emit({ type: 'records', space: space.id });
2680
- }
2681
- /**
2682
- * Takes versions just stored off what was missing — only once they are in
2683
- * the store, so a query never says "complete" for what it can't read yet.
2684
- */
2685
- function noteArrived(placed) {
2686
- if (!cache)
2687
- return;
2688
- let changed = false;
2689
- for (const version of placed) {
2690
- const missing = cacheState.missing[version.collection];
2691
- if (!missing?.includes(version.id))
2692
- continue;
2693
- const left = missing.filter((id) => id !== version.id);
2694
- if (left.length)
2695
- cacheState.missing[version.collection] = left;
2696
- else
2697
- delete cacheState.missing[version.collection];
2698
- changed = true;
2699
- }
2700
- if (changed)
2701
- saveCache();
2702
- }
2703
- /** A write of this node's, waiting for keepers — only on a node that may hold part of a space */
2704
- async function markPending(version) {
2705
- if (!cache || version.author !== session.did || version.collection.startsWith('sys.'))
2706
- return;
2707
- const pending = { collection: version.collection, by: [] };
2708
- await adapter.put(`${PENDING_PREFIX}${version.id}`, utf8Encode(JSON.stringify(pending)));
2709
- }
2710
- /**
2711
- * A keeper has some of this node's pending writes: those it named, or every
2712
- * one in a collection it is level on. Once enough keepers have one, it
2713
- * stops being pending. Only keepers the space names count.
2714
- */
2715
- async function confirm(peer, which) {
2716
- if (!cache)
2717
- return;
2718
- const state = (await access()).history.current;
2719
- if (!state.keepers.some((keeper) => keeper.did === peer))
2720
- return;
2721
- const target = Math.min(state.keepers.length, Math.max(state.copies ?? 2, cache.copies ?? 0));
2722
- for (const name of await adapter.list(PENDING_PREFIX)) {
2723
- const id = name.slice(PENDING_PREFIX.length);
2724
- if (which.ids && !which.ids.has(id))
2725
- continue;
2726
- const bytes = await adapter.get(name);
2727
- if (!bytes)
2728
- continue;
2729
- const pending = JSON.parse(utf8Decode(bytes));
2730
- if (!isPending(pending))
2731
- continue;
2732
- if (which.collection !== undefined && pending.collection !== which.collection)
2733
- continue;
2734
- if (!pending.by.includes(peer))
2735
- pending.by.push(peer);
2736
- if (pending.by.length >= target)
2737
- await adapter.delete(name);
2738
- else
2739
- await adapter.put(name, utf8Encode(JSON.stringify(pending)));
2740
- }
2741
- }
2742
- sync.on('synced', (_peer, full) => {
2743
- if (!cache || !full || cacheState.settled)
2744
- return;
2745
- // Caught up with a node holding everything: the access history here is the space's now.
2746
- cacheState.settled = true;
2747
- saveCache();
2748
- void refreshHolds().catch(() => { });
91
+ reportedRole = role;
92
+ deps.onRole?.(role);
93
+ },
2749
94
  });
2750
- sync.on('stored', (peer, ids) => {
2751
- void confirm(peer, { ids: new Set(ids) }).catch(() => { });
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,
2752
116
  });
2753
- sync.on('level', (peer, collection, full) => {
2754
- // What a line names and is not here yet: asked again, of whoever holds it now.
2755
- const missing = cacheState.missing[collection];
2756
- if (cache && missing?.length)
2757
- sync.ask(collection, missing);
2758
- if (cache && full && cacheState.level[collection] === undefined) {
2759
- cacheState.level[collection] = Date.now();
2760
- saveCache();
2761
- // A query that said "not complete" says so no longer.
2762
- if (partial)
2763
- emit({ type: 'records', space: space.id });
2764
- }
2765
- void confirm(peer, { collection }).catch(() => { });
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
+ use: holding.use,
2766
131
  });
2767
- /**
2768
- * Drops collections no query has touched for a while: their records go,
2769
- * and they are no longer held. Never one the app declared, nor one holding
2770
- * a write still waiting for keepers.
2771
- */
2772
- async function dropUnused() {
2773
- if (!cache || !partial || closed)
2774
- return;
2775
- const cutoff = Date.now() - (cache.unusedAfterDays ?? 30) * DAY;
2776
- const waiting = new Set();
2777
- for (const name of await adapter.list(PENDING_PREFIX)) {
2778
- const bytes = await adapter.get(name);
2779
- const pending = bytes ? JSON.parse(utf8Decode(bytes)) : null;
2780
- if (isPending(pending))
2781
- waiting.add(pending.collection);
2782
- }
2783
- let dropped = false;
2784
- for (const [collection, at] of Object.entries(cacheState.used)) {
2785
- if (at > cutoff || declared.has(collection) || waiting.has(collection))
2786
- continue;
2787
- // No longer held first, so nothing syncs it back while it goes.
2788
- delete cacheState.used[collection];
2789
- delete cacheState.level[collection];
2790
- delete cacheState.missing[collection];
2791
- for (const item of (await storage.items(collection)).items)
2792
- await storage.removeVersion(cidOfDigest(item.id));
2793
- dropped = true;
2794
- }
2795
- if (!dropped)
2796
- return;
2797
- saveCache();
2798
- recordsChanged();
2799
- sync.notifyPeers(connectedPeers());
2800
- }
2801
- // When the app opens the space, then every few hours while it stays open.
2802
- const dropTimer = cache ? setInterval(() => void dropUnused().catch(() => { }), 6 * HOUR) : null;
2803
- const tidying = cache ? dropUnused().catch(() => { }) : Promise.resolve();
2804
- unref(dropTimer);
2805
- /** Why this account cannot write here at all, or null when it can */
2806
- async function cannotWrite() {
2807
- const { history } = await access();
2808
- if (isMember(history.current, deps.rootDid))
2809
- return null;
2810
- return waitingInvite
2811
- ? `You've joined "${space.name}", but its invite hasn't reached this device yet — connect to someone in the space first`
2812
- : `"${space.name}" was shared with you to view — you can't change it`;
2813
- }
2814
- /**
2815
- * The heads a new version names: all of them, or past what a version may
2816
- * name, first those its own standing rests on (its author's place, its
2817
- * role, its collection's definition), then the latest applied. Naming fewer
2818
- * is safe: what it leaves out it is judged as not having seen (03 §3.2).
2819
- */
2820
- async function seenFor(history, collection) {
2821
- const roles = rolesOf(history.current, deps.rootDid);
2822
- const mine = [
2823
- await removalKey(deps.rootDid),
2824
- await stepDownKey(deps.rootDid),
2825
- ...(await Promise.all(roles.map((role) => assignKey(deps.rootDid, role)))),
2826
- ...roles.map(roleKey),
2827
- `collection:${collection}`,
2828
- ];
2829
- return history.headsFor(mine, MAX_SEEN);
2830
- }
2831
- /** Signs and stores one version. A delete carries no body. */
2832
- async function write(collection, body, version, deleted = false, links = [], options = {}) {
2833
- const writer = options.as ?? session;
2834
- const asAccount = deps.accountOnly || aboutItself(collection, body, deps.rootDid, writer.did);
2835
- if (asAccount && !actsForAccount(writer.proof()))
2836
- throw new Error(NOT_ACCOUNT);
2837
- // Every peer would ignore it (see buildEvent); say why here instead.
2838
- if (ACCESS_COLLECTIONS.has(collection) &&
2839
- !noteGrants(writer.proof(), accessRequirement(space.id, collection, version.key))) {
2840
- throw new Error(collection === CATALOG_COLLECTION ? CANNOT_DEFINE : CANNOT_CHANGE_ACCESS);
2841
- }
2842
- // Every other copy would refuse it, so refuse it here rather than show a
2843
- // change that exists on this device alone.
2844
- if (!options.joining) {
2845
- const problem = await cannotWrite();
2846
- if (problem)
2847
- throw new Error(problem);
2848
- }
2849
- let payload = null;
2850
- let tags = [];
2851
- // The files the body refers to, named on the outside so keepers fetch and keep them.
2852
- const named = deleted ? [] : fileRefsIn(body);
2853
- if (named.length > MAX_FILES)
2854
- throw new Error(`A record names at most ${MAX_FILES} files`);
2855
- if (!deleted) {
2856
- // Refused here, where the writer can fix it. On arrival a misfit is kept
2857
- // and flagged instead — see `conforms`.
2858
- const issues = await contentIssues(collection, body, links);
2859
- if (issues?.length) {
2860
- throw new Error(`Not a valid ${collection}: ${issues.map((i) => (i.path === '/' ? i.message : `${i.path} ${i.message}`)).join('; ')}`);
2861
- }
2862
- // Encrypt *before* signing: peers without the key still verify the
2863
- // signature and relay the record, they just cannot read it.
2864
- payload = body;
2865
- if (space.visibility === 'private' && !IN_THE_CLEAR.has(collection)) {
2866
- // Always the key the history names now: one someone removed still holds would do nothing.
2867
- const key = currentKey((await access()).history.current);
2868
- if (!key) {
2869
- throw new Error(keyring.size
2870
- ? `The key of "${space.name}" changed, and the new one hasn't reached this device yet — connect to someone in the space first`
2871
- : 'This private space has no key on this node');
2872
- }
2873
- // Body and links sealed together: a relay learns neither.
2874
- const content = links.length ? { body, links } : { body };
2875
- payload = await sealBody(content, key, { space: space.id, collection, key: version.key });
2876
- }
2877
- // Worked out from the body, with the key it is sealed with: what every reader will check.
2878
- const topics = collection.startsWith('sys.')
2879
- ? []
2880
- : ((await catalog()).get(collection)?.definition.topics ?? []);
2881
- if (topics.length) {
2882
- const sealedWith = looksEncrypted(payload) ? sealedKeyId(payload) : null;
2883
- const key = tagKey(sealedWith);
2884
- if (key)
2885
- tags = await tagsFor(await key, collection, topics, body, links);
2886
- }
2887
- }
2888
- // Whether superseded versions are kept is the writer's decision, carried
2889
- // on the version — never each reader's, or nodes that had seen different
2890
- // definitions would store different things and never converge. The access
2891
- // history keeps everything: it is replayed whole. A first version under
2892
- // `onePer` or `fixed` is kept whole, because those rules are checked against it.
2893
- const definition = (await catalog()).get(collection)?.definition;
2894
- const retain = ACCESS_COLLECTIONS.has(collection) ||
2895
- // Proof read back whole after anything written over it (\`flagged\`).
2896
- collection === WARRANT_COLLECTION ||
2897
- collection === PROFILE_COLLECTION ||
2898
- collection === BOX_COLLECTION ||
2899
- collection === MEMBER_KEY_COLLECTION ||
2900
- definition?.history === 'all' ||
2901
- (version.seq === 0 && !!(definition?.rules?.onePer || definition?.rules?.fixed)) ||
2902
- // Every version under a contract: it reads the one before, and others cite it.
2903
- (!deleted && hasContract(definition?.contract));
2904
- // The next place in this key's line for the collection: given back if the version is refused below.
2905
- const signed = await deps.writers.append(writer.did, space.id, collection, async (log) => {
2906
- const { history, events: held } = await access();
2907
- const seen = await seenFor(history, collection);
2908
- // Checks in force as of the very point it names: a definition arriving meanwhile can't leave it unkept.
2909
- const checkedThen = (() => {
2910
- const then = history.at(seen);
2911
- return then ? rulesAt(then, collection) : null;
2912
- })();
2913
- const then = await checkedThen;
2914
- const keep = retain || (!deleted && hasContract(then?.contract));
2915
- const made = await signer.sign(createVersion({
2916
- author: writer.did,
2917
- collection,
2918
- space: space.id,
2919
- body: payload,
2920
- proof: writer.proof(),
2921
- version,
2922
- retain: keep,
2923
- deleted,
2924
- seen,
2925
- // In the clear only where the body is: a private space sealed them above.
2926
- ...(space.visibility === 'public' && !deleted && links.length ? { links } : {}),
2927
- ...(tags.length ? { tags } : {}),
2928
- ...(named.length ? { files: named } : {}),
2929
- log,
2930
- }), writer.key);
2931
- // The same verdict every other peer will reach: refused here, with the reason, rather than there.
2932
- const judged = await judge(made);
2933
- if (!judged.verified)
2934
- throw new Error(judged.reason ?? 'This key may not write here.');
2935
- if (ACCESS_COLLECTIONS.has(collection)) {
2936
- const event = await toEvent(made);
2937
- if (!event)
2938
- throw new Error('That is not a well-formed change to who may do what');
2939
- const status = (history.extend(event) ?? replayAccess(accessGenesis, [...held, event])).status(event.id);
2940
- if (status?.status !== 'applied')
2941
- throw new Error(status?.status === 'dropped' ? status.reason : 'That change could not be made');
2942
- }
2943
- else {
2944
- const stands = await standingOf(made);
2945
- // Taken away by a change to its rules that came in after it saw the history: try again.
2946
- if (!stands.ok && stands.withdrawn)
2947
- throw Object.assign(new Error(stands.reason), { rulesMoved: true });
2948
- if (!stands.ok)
2949
- throw new Error(stands.reason);
2950
- // Its checks, here, before anyone else sees it: peers would keep it, but no reader would count it.
2951
- const passes = await checksOf(made);
2952
- if ('pending' in passes)
2953
- throw new Error('Versions it cites have not arrived yet');
2954
- if ('unjudged' in passes)
2955
- throw new Error(passes.unjudged);
2956
- if (passes.passes === false)
2957
- throw new Error(passes.reason);
2958
- }
2959
- return made;
2960
- });
2961
- await storage.addVersion(signed);
2962
- await placeInLog(signed);
2963
- await markPending(signed);
2964
- channel?.postMessage('changed');
2965
- sync.onLocalChange(signed);
2966
- recordsChanged([signed]);
2967
- return signed;
2968
- }
2969
- /**
2970
- * How a record's newest version that stands fares under its checks: kept and
2971
- * synced by every peer either way, counted by a reader only when it passes.
2972
- */
2973
- async function contractsFor(recordKey, versionId) {
2974
- // A version named is judged even when the history leaves it out (a superseded delete, say).
2975
- const named = versionId !== undefined ? await storage.getVersion(versionId) : null;
2976
- const candidates = versionId === undefined ? await storage.history(recordKey) : named?.key === recordKey ? [named] : [];
2977
- for (const version of candidates) {
2978
- if (isStub(version))
2979
- continue;
2980
- // One named whose first version hasn't arrived waits for it.
2981
- if (!(await consistent(version))) {
2982
- if (versionId !== undefined && version.seq > 0)
2983
- return { version: version.id, passes: null, pending: true };
2984
- continue;
2985
- }
2986
- const stands = await standingOf(version);
2987
- // One named that waits for what it follows is pending, as a contract waiting on what it cites.
2988
- if (!stands.ok && stands.later && versionId !== undefined)
2989
- return { version: version.id, passes: null, pending: true };
2990
- if (!stands.ok)
2991
- continue;
2992
- const verdict = await checksOf(version);
2993
- if ('pending' in verdict)
2994
- return { version: version.id, passes: null, pending: true };
2995
- if ('unjudged' in verdict)
2996
- return { version: version.id, passes: null, unjudged: true, reason: verdict.unjudged };
2997
- return { version: version.id, ...verdict };
2998
- }
2999
- return null;
3000
- }
3001
- async function get(recordKey) {
3002
- const current = await currentOf(recordKey);
3003
- return current && !current.deleted ? view(current) : null;
3004
- }
3005
- /** The live current version of a record, or a clear error. */
3006
- async function requireLive(recordKey) {
3007
- const current = await currentOf(recordKey);
3008
- if (!current || current.deleted)
3009
- throw new Error(`No record ${recordKey} in this space`);
3010
- return current;
3011
- }
3012
- /**
3013
- * The fields for writing a key again: the version after the one that counts.
3014
- * Where the store's newest version fails its checks, after the newest that
3015
- * counts, or afresh as a first version when none does: a version that fails
3016
- * can't make others build on it, or claim a key (a `onePer` key) for good.
3017
- * Otherwise after whatever the store holds, counted or not.
3018
- */
3019
- async function after(recordKey) {
3020
- const held = await storage.getCurrent(recordKey);
3021
- if (!held)
3022
- return { key: recordKey, seq: 0 };
3023
- const verdict = (await standingOf(held)).ok ? await checksOf(held) : NO_CHECKS;
3024
- // One that fails its checks, or waits for ever on what it cites, can't hold the key.
3025
- if ('passes' in verdict && verdict.passes !== false)
3026
- return nextVersion(held);
3027
- // Waiting only for its own step before: continue it, rather than fork this record.
3028
- if ('pending' in verdict && held.prev && !(await storage.getVersion(held.prev)))
3029
- return nextVersion(held);
3030
- const counted = await currentOf(recordKey);
3031
- return counted ? nextVersion(counted) : { key: recordKey, seq: 0 };
3032
- }
3033
- async function writeFirst(collection, body, recordKey, links, as) {
3034
- const current = await currentOf(recordKey);
3035
- if (current && !current.deleted)
3036
- throw new Error(`A record ${recordKey} already exists — update it instead`);
3037
- // Writing a key that was deleted brings it back: the next version after the delete.
3038
- return write(collection, body, await after(recordKey), false, links, as ? { as } : {});
3039
- }
3040
- async function upsert(collection, recordKey, body, options = {}) {
3041
- return view(await write(collection, body, await after(recordKey), false, [], options));
3042
- }
3043
- async function removeKey(recordKey, as) {
3044
- const current = await requireLive(recordKey);
3045
- await write(current.collection, null, await after(current.key), true, [], as ? { as } : {});
3046
- }
3047
- const guard = (collection) => {
3048
- if (MANAGED.has(collection))
3049
- throw new Error(`${collection} is written by the node itself`);
3050
- };
3051
- // ─── Writers' logs ─────────────────────────────────────────────────
3052
- //
3053
- // A key's writes in each collection here form one line (02 §4.10). Each
3054
- // place a key took is remembered by the version that took it, so a second
3055
- // version at the same place is found the moment it arrives. And each
3056
- // version is checked against the one it names as the place before — when it
3057
- // arrives, or when that one does. Either way the proof goes to everyone else.
3058
- // Named for this format of the log: the `log/`, `next/`, `clog/` and
3059
- // `cnext/` a node kept before it map places to versions no peer holds any
3060
- // more, so they are left unread rather than trusted.
3061
- /** `place/<author>/<collection>/<n>` → the id of the version that took that place */
3062
- const LOG_PREFIX = 'place/';
3063
- /** Key DID → the account it writes for here */
3064
- const KEY_ROOT_PREFIX = 'keyroot/';
3065
- /** `follows/<id>` → the id of a version naming that one as the place before it */
3066
- const NEXT_PREFIX = 'follows/';
3067
- async function placeInLog(version) {
3068
- if (version.space !== space.id || !version.log)
3069
- return;
3070
- const { log } = version;
3071
- // Which account each key writes for: what a cutoff is worked out from.
3072
- const root = (await judge(version)).root;
3073
- // Only an account a valid note names: a key whose note failed falls back to itself, and isn't anyone's.
3074
- if (root &&
3075
- (root !== version.author || !version.proof) &&
3076
- !(await adapter.get(`${KEY_ROOT_PREFIX}${version.author}`)))
3077
- await adapter.put(`${KEY_ROOT_PREFIX}${version.author}`, utf8Encode(root));
3078
- // Its place: a second version there is a fork.
3079
- const at = `${LOG_PREFIX}${version.author}/${version.collection}/${log.n}`;
3080
- const held = await adapter.get(at);
3081
- if (!held)
3082
- await adapter.put(at, utf8Encode(version.id));
3083
- else if (utf8Decode(held) !== version.id) {
3084
- const first = await storage.getVersion(utf8Decode(held));
3085
- if (first)
3086
- void reportFork(first, version, version.author, version.collection, log.n).catch(() => { });
3087
- }
3088
- // The place before it, if held, must be its key's; and so must it be for whatever names it.
3089
- if (log.prev) {
3090
- await adapter.put(`${NEXT_PREFIX}${log.prev}`, utf8Encode(version.id));
3091
- const previous = await storage.getVersion(log.prev);
3092
- if (previous && breaksLine(version, previous))
3093
- void reportFork(version, previous, version.author, version.collection, log.n).catch(() => { });
3094
- }
3095
- const naming = await adapter.get(`${NEXT_PREFIX}${version.id}`);
3096
- const next = naming ? await storage.getVersion(utf8Decode(naming)) : null;
3097
- if (next?.log && breaksLine(next, version))
3098
- void reportFork(next, version, next.author, next.collection, next.log.n).catch(() => { });
3099
- await noteGap(version);
3100
- }
3101
- /**
3102
- * Hands every peer the proof that a key's line for a collection is not one
3103
- * line — a fork or a break — unless a proof at or before this place stands
3104
- * already. Any member may; one whose note doesn't let it change access
3105
- * leaves it to one whose note does.
3106
- */
3107
- async function reportFork(a, b, writer, collection, from) {
3108
- if (closed)
3109
- return;
3110
- const known = (await access()).history.forked(writer, collection);
3111
- if (known && known.from <= from)
3112
- return;
3113
- if (!noteGrants(session.proof(), accessRequirement(space.id, FORK_COLLECTION, await forkKey(writer))) ||
3114
- (await cannotWrite()))
3115
- return;
3116
- await upsert(FORK_COLLECTION, await forkKey(writer), forkProof(a, b));
3117
- }
3118
- /**
3119
- * Runs a write once more when its collection's rules changed while it was
3120
- * being made — it saw the history before the change, so the change takes
3121
- * it away (03 §5.2) — this time under the new rules: a key they derive,
3122
- * what they keep whole, all worked out again.
3123
- */
3124
- async function underCurrentRules(run) {
3125
- try {
3126
- return await run();
3127
- }
3128
- catch (error) {
3129
- if (!(isRecord(error) && error.rulesMoved === true))
3130
- throw error;
3131
- return run();
3132
- }
3133
- }
3134
- async function putOnce(collection, body, options) {
3135
- guard(collection);
3136
- if (options.key !== undefined && !RECORD_KEY_PATTERN.test(options.key)) {
3137
- throw new Error('A record key is 1–128 characters of a–z, 0–9 and : . _ -');
3138
- }
3139
- const links = options.links ?? [];
3140
- // One per something: the key is derived from it, so writing again is the next version of the same record.
3141
- const onePer = (await catalog()).get(collection)?.definition.rules?.onePer;
3142
- if (onePer && options.key === undefined) {
3143
- const derived = await derivedKey(collection, onePer, { root: deps.rootDid, links, body });
3144
- if (!derived)
3145
- throw new Error(`${collection} is one per ${onePer.join(' + ')} — give it every one of those`);
3146
- await keepsCollection(derived, collection);
3147
- return view(await write(collection, body, await after(derived), false, links, options.as ? { as: options.as } : {}));
3148
- }
3149
- const recordKey = await keyToWrite(collection, options.key, onePer);
3150
- return view(await writeFirst(collection, body, recordKey, links, options.as));
3151
- }
3152
- /**
3153
- * Where a new record goes: a fresh key of this account's, or the key the
3154
- * caller names. A name is put in this account's namespace (`profile` →
3155
- * `<owner>.profile`); a key this account already owns is taken as it is.
3156
- * Not a `one:` key outside a `onePer` collection, which every peer refuses
3157
- * (02 §7.3), nor a key this node holds a record of another collection at.
3158
- */
3159
- async function keyToWrite(collection, chosen, onePer) {
3160
- if (chosen === undefined)
3161
- return newRecordKey(deps.rootDid);
3162
- let recordKey;
3163
- if (await ownsKey(chosen, deps.rootDid))
3164
- recordKey = chosen;
3165
- else if (keyKind(chosen) === 'owned')
3166
- throw new Error(`${chosen} belongs to another account`);
3167
- else
3168
- recordKey = keyKind(chosen) === 'shared' ? chosen : await ownedKey(deps.rootDid, chosen);
3169
- if (onePerForm(recordKey) && !onePer)
3170
- throw new Error(`${recordKey} is a onePer key, and ${collection} has no onePer`);
3171
- await keepsCollection(recordKey, collection);
3172
- return recordKey;
3173
- }
3174
- /**
3175
- * Refuses a write at a key this node holds a record of another collection
3176
- * at. Keys are unique in a space, and a record keeps its collection for
3177
- * life (02 §4.1, §4.2), so the write could only be refused, or continue the
3178
- * other record's chain.
3179
- */
3180
- async function keepsCollection(recordKey, collection) {
3181
- const held = (await currentOf(recordKey)) ?? (await storage.getCurrent(recordKey));
3182
- if (held && held.collection !== collection)
3183
- throw new Error(`${recordKey} already holds a ${held.collection} record, and a key keeps its collection for life: ` +
3184
- `choose a name that includes the collection`);
3185
- }
3186
- /** 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 */
3187
- async function accountable(version) {
3188
- const verdict = await judge(version);
3189
- if (!verdict.verified || !verdict.root || version.space !== space.id)
3190
- return null;
3191
- return (await access()).history.named(verdict.root) ? verdict.root : null;
3192
- }
3193
- /** Views already replayed, by the changes they hold: a set of ids always replays to the same state */
3194
- const views = new Map();
3195
- const MAX_VIEWS = 256;
3196
- /**
3197
- * The access state a writer had when it signed: the changes it names as
3198
- * seen and everything they saw, replayed alone. Unlike `history.at`, no
3199
- * change outside them — a rival that arrives late, or a change made later —
3200
- * can alter it, so a verdict on misconduct judged by it is final. Null
3201
- * while one of them hasn't arrived.
3202
- */
3203
- async function ownView(seen) {
3204
- const cacheKey = [...new Set(seen)].sort().join(',');
3205
- const known = views.get(cacheKey);
3206
- if (known)
3207
- return known;
3208
- const { events } = await access();
3209
- const byId = new Map(events.map((event) => [event.id, event]));
3210
- const cut = [];
3211
- const visited = new Set([accessGenesis.id]);
3212
- const waiting = [...seen];
3213
- while (waiting.length > 0) {
3214
- const id = waiting.pop();
3215
- if (visited.has(id))
3216
- continue;
3217
- visited.add(id);
3218
- const event = byId.get(id);
3219
- if (!event)
3220
- return null;
3221
- cut.push(event);
3222
- waiting.push(...event.seen);
3223
- }
3224
- const state = replayAccess(accessGenesis, cut).current;
3225
- if (views.size >= MAX_VIEWS)
3226
- views.delete(views.keys().next().value);
3227
- views.set(cacheKey, state);
3228
- return state;
3229
- }
3230
- /** Whether a version broke a rule of its standing, as of what it had seen: no place, or `who` or `final` against it */
3231
- async function standingBroken(version, root) {
3232
- const state = await ownView(version.seen ?? []);
3233
- if (!state)
3234
- return 'later';
3235
- return standingBrokenIn(state, version, root);
3236
- }
3237
- /** The same check, in a given state */
3238
- async function standingBrokenIn(state, version, root) {
3239
- if (!isMember(state, root))
3240
- return 'holds';
3241
- if (version.collection.startsWith('sys.'))
3242
- return 'false';
3243
- const found = await rulesAt(state, version.collection);
3244
- if (found?.rules.final && version.seq > 0)
3245
- return 'holds';
3246
- // An edit's grant may rest on whose record it is; only a first version is judged here.
3247
- if (version.seq !== 0)
3248
- return 'false';
3249
- const needs = await needsOf(version, version, root);
3250
- return needs(state) ? 'false' : 'holds';
3251
- }
3252
- /** Whether proof of one kind holds: the offending version first, then what checking it needs */
3253
- async function evidenceHolds(kind, evidence) {
3254
- // A kind this peer doesn't know flags nobody.
3255
- if (!knownKind(kind))
3256
- return 'false';
3257
- const [offending, context] = evidence;
3258
- if (!offending || !(await accountable(offending)))
3259
- return 'false';
3260
- const root = (await judge(offending)).root;
3261
- switch (kind) {
3262
- case 'chain': {
3263
- if (!context || 'body' in offending || 'body' in context)
3264
- return 'false';
3265
- if (!(await judge(context)).verified || context.id !== offending.prev)
3266
- return 'false';
3267
- return chainProblem(offending, context) ? 'holds' : 'false';
3268
- }
3269
- case 'standing':
3270
- if (context ||
3271
- 'body' in offending ||
3272
- ACCESS_COLLECTIONS.has(offending.collection) ||
3273
- offending.collection === WARRANT_COLLECTION)
3274
- return 'false';
3275
- return standingBroken(offending, root);
3276
- case 'access': {
3277
- if (context || !ACCESS_COLLECTIONS.has(offending.collection) || !('body' in offending))
3278
- return 'false';
3279
- const event = await buildEvent(offending);
3280
- if (!event)
3281
- return 'false';
3282
- const state = await ownView(event.seen);
3283
- if (!state)
3284
- return 'later';
3285
- return refusal(event, state) ? 'holds' : 'false';
3286
- }
3287
- }
132
+ const lines = createLines({
133
+ ...base,
134
+ adapter,
135
+ versions,
136
+ history,
137
+ catalog,
138
+ everyCurrent: () => index.everyCurrent(),
139
+ noteGap: holding.noteGap,
140
+ upsert,
141
+ cannotWrite,
142
+ });
143
+ const warrants = createWarrants({ ...base, versions, history, rules, standing, upsert, cannotWrite });
144
+ /** A version this node signed is in the store: its key's line, the other tabs and the peers hear of it */
145
+ async function stored(version) {
146
+ await lines.placeInLog(version);
147
+ await holding.markPending(version);
148
+ mirrors.tellTabs();
149
+ peers.sync.onLocalChange(version);
150
+ recordsChanged([version]);
3288
151
  }
3289
- /** Whether a warrant record proves what it says, against the account its key names, and is its writer's own */
3290
- async function warrantVerdict(version) {
3291
- const cacheKey = copyKey(version);
3292
- const known = judgedWarrants.get(cacheKey);
3293
- if (known)
3294
- return known;
3295
- const warrant = await warrantShape(version);
3296
- if (warrant === 'unnamed')
3297
- return 'false';
3298
- const verdict = warrant ? await evidenceHolds(warrant.kind, warrant.evidence) : 'false';
3299
- // Judged in the offending version's own view, a proof that holds, or fails, always will.
3300
- if (verdict === 'holds' || verdict === 'false')
3301
- judgedWarrants.set(cacheKey, verdict);
152
+ /** Whether a version from outside — a peer, a folder — may be stored */
153
+ async function admit(version) {
154
+ const verdict = await admitOnce(version);
155
+ // Refused for good, or a change to who may do what: perhaps proof of a broken rule (docs/warrants.md).
156
+ if ((!verdict.ok && !verdict.later && !verdict.withdrawn) || ACCESS_COLLECTIONS.has(version.collection))
157
+ void warrants.warrantIfDue(version).catch(() => { });
3302
158
  return verdict;
3303
159
  }
3304
- /** Warrants already judged: each checked once, not on every look at who is flagged */
3305
- const judgedWarrants = new Map();
3306
- /**
3307
- * A warrant's body, if the version has a warrant's shape: a first version
3308
- * of `std.warrant`, not a delete, and not against its writer. Anything else
3309
- * flags nobody.
3310
- */
3311
- async function warrantShape(version) {
3312
- if (version.deleted || version.seq !== 0 || version.collection !== WARRANT_COLLECTION)
3313
- return null;
3314
- const warrant = readWarrant((await openBody(version)).body);
3315
- const offending = warrant?.evidence[0];
3316
- if (!warrant || !offending || !(await judge(offending)).verified)
3317
- return null;
3318
- // The one answer that can change: the account may be named once more of the history arrives.
3319
- const against = await accountable(offending);
3320
- if (!against)
3321
- return 'unnamed';
3322
- const by = (await judge(version)).root;
3323
- return by && against !== by ? warrant : null;
3324
- }
3325
- /** The proof a version gives against its account, or null when it gives none */
3326
- async function violationIn(version) {
3327
- const root = await accountable(version);
3328
- if (!root)
3329
- return null;
3330
- if (version.seq > 0 && version.prev) {
3331
- const previous = await storage.getVersion(version.prev);
3332
- if (previous && chainProblem(version, previous))
3333
- return { kind: 'chain', evidence: [stubOf(version), stubOf(previous)] };
3334
- }
3335
- if (ACCESS_COLLECTIONS.has(version.collection)) {
3336
- const event = await buildEvent(version);
3337
- const quick = event && (await access()).history.at(event.seen);
3338
- if (!event || (quick && !refusal(event, quick)))
3339
- return null;
3340
- return (await evidenceHolds('access', [version])) === 'holds'
3341
- ? { kind: 'access', evidence: [version] }
3342
- : null;
3343
- }
3344
- // A warrant is a record like any other: a false one flags nobody, and proves nothing against its writer.
3345
- if (version.collection === WARRANT_COLLECTION)
3346
- return null;
3347
- // The global view first, which is cheap; the own view, a replay, only for what it finds broken.
3348
- // Proof only the own view would show goes unwritten: a flag missed, never a false one.
3349
- const quick = (await access()).history.at(version.seen ?? []);
3350
- if (quick && (await standingBrokenIn(quick, version, root)) !== 'holds')
3351
- return null;
3352
- return (await standingBroken(version, root)) === 'holds'
3353
- ? { kind: 'standing', evidence: [stubOf(version)] }
3354
- : null;
3355
- }
3356
- /**
3357
- * Writes down, as this account's own record, the proof a version gives
3358
- * against its account — unless a warrant of its own against that account
3359
- * stands already, so one account's misconduct costs each member one record
3360
- * at a time. It doesn't lean on anyone else's warrant, which would go if
3361
- * its writer were removed. One that can't write leaves it to one that can.
3362
- */
3363
- async function warrantIfDue(version) {
3364
- if (closed || (await cannotWrite()))
3365
- return;
3366
- // Only an account the history names can be warranted: anything else stops here, for free.
3367
- const root = await accountable(version);
3368
- if (!root || root === deps.rootDid)
3369
- return;
3370
- // With a warrant of its own against that account standing, its next offences cost nothing to look at.
3371
- if ((await flagged()).some((flag) => flag.account === root && flag.by === deps.rootDid))
3372
- return;
3373
- const violation = await violationIn(version);
3374
- // Taken only once there is something to write, so a decoy can't hide an offence behind it.
3375
- if (!violation || warranting.has(root))
160
+ async function admitOnce(version) {
161
+ // Before any cached verdict: a copy with another envelope or body shares the id and signature.
162
+ const problem = await versions.copyProblem(version);
163
+ if (problem)
164
+ return { ok: false, reason: problem };
165
+ // Whatever its key signed takes a place in that key's log, allowed or not: a second at one place is a fork.
166
+ if ((await versions.judge(version)).verified)
167
+ await lines.placeInLog(version);
168
+ return standing.admission(version);
169
+ }
170
+ // ─── Mirrors and files ─────────────────────────────────────────────
171
+ const mirrors = await openMirrors({
172
+ ...base,
173
+ stores: deps.stores,
174
+ adapter,
175
+ mirrors: deps.mirrors,
176
+ watchIntervalMs: deps.watchIntervalMs,
177
+ admit,
178
+ recordsChanged: () => recordsChanged(),
179
+ announceSoon: () => peers.announceSoon(),
180
+ });
181
+ // Named on the outside of the versions that refer to them, fetched chunk by
182
+ // chunk and checked as they come, kept while a body that names them is
183
+ // (spec 05 §16.6).
184
+ const files = createSpaceFiles({
185
+ space: space.id,
186
+ adapter,
187
+ storage,
188
+ send: (peer, message) => peers.toPeer(peer, {
189
+ type: 'sync',
190
+ from: session.did,
191
+ payload: { ...message, v: SYNC_PROTOCOL_VERSION },
192
+ }),
193
+ peers: () => peers.connectedPeers(),
194
+ mirrors: mirrors.all,
195
+ stands: async (version) => storable(await standing.standingOf(version)),
196
+ // Files follow records: every file a version kept whole names is fetched, within a device's limits.
197
+ ...(deps.fetchFiles === 'all' ? {} : { limits: DEVICE_LIMITS }),
198
+ });
199
+ let filesTimer = null;
200
+ /** One pass at a time; a change during one runs another after it */
201
+ let filesPass = null;
202
+ let filesAgain = false;
203
+ /** After a change: which files are named is worked out again, and soon kept, dropped and fetched to match */
204
+ function filesChanged() {
205
+ files.changed();
206
+ if (filesPass) {
207
+ filesAgain = true;
3376
208
  return;
3377
- warranting.add(root);
3378
- try {
3379
- if (!(await flagged()).some((flag) => flag.account === root && flag.by === deps.rootDid))
3380
- await warrantOnce(violation);
3381
209
  }
3382
- finally {
3383
- warranting.delete(root);
3384
- }
3385
- }
3386
- /** Accounts this node is writing a warrant against now: offences that arrive meanwhile wait for the next */
3387
- const warranting = new Set();
3388
- async function warrantOnce(violation) {
3389
- // Checked again: the space may have closed while the proof was being worked out.
3390
- if (closed)
210
+ if (filesTimer || closed)
3391
211
  return;
3392
- await upsert(WARRANT_COLLECTION, await newRecordKey(deps.rootDid), violation);
3393
- }
3394
- /** The accounts proven to have broken the protocol's rules here, by the warrants that stand */
3395
- async function flagged() {
3396
- const found = [];
3397
- // Each warrant's first version, kept whole, whatever came after it: like any record, anyone
3398
- // may write a later version or a delete, and neither takes the proof back.
3399
- const firsts = [];
3400
- for (const current of await storage.queryVersions(WARRANT_COLLECTION))
3401
- for (const version of await storage.history(current.key))
3402
- if (version.seq === 0 && version.collection === WARRANT_COLLECTION)
3403
- firsts.push(version);
3404
- for (const version of firsts) {
3405
- if (version.deleted || isStub(version) || !(await standingOf(version)).ok)
3406
- continue;
3407
- // Only proof this peer checked: one that stands unjudged, for want of rules it can't read, flags nobody.
3408
- if ((await warrantVerdict(version)) !== 'holds')
3409
- continue;
3410
- const warrant = readWarrant((await openBody(version)).body);
3411
- const offending = warrant?.evidence[0];
3412
- const account = offending && (await accountable(offending));
3413
- if (!warrant || !offending || !account || !knownKind(warrant.kind))
3414
- continue;
3415
- const by = (await judge(version)).root ?? version.author;
3416
- // One flag per offence and writer, however many records say it.
3417
- if (found.some((flag) => flag.offence === offending.id && flag.by === by))
3418
- continue;
3419
- found.push({ account, key: offending.author, kind: warrant.kind, by, offence: offending.id });
3420
- }
3421
- return found;
3422
- }
3423
- /** Display order: when a record was created, then its key. It decides nothing. */
3424
- const createdAtOf = async (version) => (await genesisOf(version))?.createdAt ?? version.createdAt;
3425
- /**
3426
- * Assigns a role to an account, or with `assigned: false` takes it away:
3427
- * one's own, to leave it. Taking a role leaves what this node has seen
3428
- * them write in it standing.
3429
- */
3430
- async function assign(did, role, assigned) {
3431
- const { history } = await access();
3432
- if (!history.current.roles.has(role))
3433
- throw new Error(`There is no role "${role}" in "${space.name}"`);
3434
- const takes = !assigned && rolesOf(history.current, did).includes(role);
3435
- const cutoff = takes ? await cutoffFor(did) : {};
3436
- const written = await upsert(ASSIGN_COLLECTION, await assignKey(did, role), {
3437
- did,
3438
- role,
3439
- assigned,
3440
- ...(Object.keys(cutoff).length ? { cutoff } : {}),
3441
- });
3442
- await changeKeyNow();
3443
- return written;
3444
- }
3445
- /** Removes an account from the space, every role it holds with it: one's own, to leave */
3446
- async function removeAccount(did) {
3447
- const { history } = await access();
3448
- if (!isMember(history.current, did))
3449
- throw new Error(`They hold no place in "${space.name}"`);
3450
- const cutoff = await cutoffFor(did);
3451
- const written = await upsert(REMOVE_COLLECTION, await removalKey(did), {
3452
- did,
3453
- ...(Object.keys(cutoff).length ? { cutoff } : {}),
3454
- });
3455
- await changeKeyNow();
3456
- return written;
3457
- }
3458
- /** What this account is here, for listing: `founder`, a role it holds, or null */
3459
- function placeOf(state, did) {
3460
- if (state.founders.has(did))
3461
- return FOUNDER;
3462
- return rolesOf(state, did)[0] ?? null;
3463
- }
3464
- /**
3465
- * A change that took someone's place makes a new key due. The node that
3466
- * made it changes the key before the call returns, not later in the
3467
- * background: one that closes straight after a removal would otherwise
3468
- * leave the removed member reading everything written since.
3469
- */
3470
- async function changeKeyNow() {
3471
- if (space.visibility === 'private' && (await access()).history.current.keyDue)
3472
- await keepingUp();
3473
- }
3474
- /**
3475
- * What a change taking power from an account leaves standing: for each of
3476
- * its keys and each collection, the end of the unbroken line this node
3477
- * holds of that key's versions in that collection, from its first place,
3478
- * each naming the one before. A place held past a gap covers nothing, so
3479
- * one planted far ahead can't cover what its writer signs after; and a node
3480
- * holding some collections keeps their lines whole (05 §9), so it covers
3481
- * all it holds.
3482
- */
3483
- async function cutoffFor(did, only) {
3484
- const cutoff = {};
3485
- // At most what a change may carry: what is left out is judged with the change.
3486
- for (const end of (await linesOf(did, only)).slice(0, MAX_CUTOFF))
3487
- (cutoff[end.author] ??= {})[end.collection] = end.log.n;
3488
- return cutoff;
212
+ filesTimer = setTimeout(() => {
213
+ filesTimer = null;
214
+ filesPass = (async () => {
215
+ await files.tidy();
216
+ await files.fetchMissing();
217
+ })()
218
+ .catch(() => {
219
+ // A peer or mirror out of reach; the next change tries again.
220
+ })
221
+ .finally(() => {
222
+ filesPass = null;
223
+ if (filesAgain && !closed) {
224
+ filesAgain = false;
225
+ filesChanged();
226
+ }
227
+ });
228
+ }, 2000);
229
+ unref(filesTimer);
3489
230
  }
3490
231
  /**
3491
- * The ends of an account's unbroken lines this node holds: defined
3492
- * collections first, then the rest, each in name order.
232
+ * Records changed: whatever is derived from them may have too. Given the
233
+ * versions that were placed, and none of them the space's own (`sys.`),
234
+ * only what those records feed is thrown away: who may do what, the
235
+ * definitions and the keys come from `sys.` records alone, so every other
236
+ * verdict still holds. Given nothing — another tab, a folder, new keys —
237
+ * everything is.
3493
238
  */
3494
- async function linesOf(did, only) {
3495
- // What it holds of theirs, whatever way it came: the lines' places are kept only for what arrived by sync.
3496
- const placed = new Map();
3497
- const add = (version) => {
3498
- if (!version.log)
3499
- return;
3500
- const line = `${version.author} ${version.collection}`;
3501
- const held = placed.get(line) ?? new Map();
3502
- if (!held.has(version.log.n))
3503
- held.set(version.log.n, version);
3504
- placed.set(line, held);
3505
- };
3506
- for (const version of await everyCurrent()) {
3507
- if (!version.log || (only && version.author !== only) || version.space !== space.id)
3508
- continue;
3509
- if ((await judge(version)).root === did)
3510
- add(version);
3511
- }
3512
- for (const name of await adapter.list(KEY_ROOT_PREFIX)) {
3513
- const key = name.slice(KEY_ROOT_PREFIX.length);
3514
- if ((only && key !== only) || utf8Decode((await adapter.get(name)) ?? new Uint8Array()) !== did)
3515
- continue;
3516
- for (const place of await adapter.list(`${LOG_PREFIX}${key}/`)) {
3517
- const id = await adapter.get(place);
3518
- const version = id ? await storage.getVersion(utf8Decode(id)) : null;
3519
- if (version?.author === key)
3520
- add(version);
3521
- }
3522
- }
3523
- const ends = [];
3524
- for (const held of placed.values()) {
3525
- let end = null;
3526
- for (let n = 0;; n++) {
3527
- const version = held.get(n);
3528
- if (!version || (n > 0 && version.log?.prev !== end?.id))
3529
- break;
3530
- end = version;
3531
- }
3532
- if (end)
3533
- ends.push(end);
239
+ function recordsChanged(placed) {
240
+ filesChanged();
241
+ if (placed)
242
+ holding.noteArrived(placed);
243
+ index.linksChanged();
244
+ emit({ type: 'records', space: space.id });
245
+ mirrors.changed();
246
+ if (placed && placed.every((version) => !version.collection.startsWith('sys.'))) {
247
+ index.stale(placed.map((version) => version.key));
248
+ // A record waiting on a version it cites may count now.
249
+ index.stale(checks.takeWaiting());
250
+ if (checks.arrived(placed))
251
+ index.forget();
252
+ return;
3534
253
  }
3535
- // Defined collections first: writing into many undefined ones costs only whoever did.
3536
- const defined = new Set((await catalog()).keys());
3537
- return ends.sort((a, b) => Number(defined.has(b.collection)) - Number(defined.has(a.collection)) ||
3538
- (a.collection < b.collection ? -1 : a.collection > b.collection ? 1 : a.author < b.author ? -1 : 1));
3539
- }
3540
- /** Whether this account holds a grant, now, to do something to a record */
3541
- async function mayNow(collection, action, first) {
3542
- const { history } = await access();
3543
- const state = history.current;
3544
- if (!isMember(state, deps.rootDid))
3545
- return false;
3546
- if (collection.startsWith('sys.'))
3547
- return true;
3548
- const found = await rulesAt(state, collection);
3549
- if (!found && state.contested.has(collection))
3550
- return false;
3551
- if (found?.rules.final && action !== 'create')
3552
- return false;
3553
- const byCreator = action === 'create' || (!!first && (await judge(first)).root === deps.rootDid);
3554
- // The body isn't known yet: a policy on it is decided when the version is written.
3555
- return may(state, deps.rootDid, action === 'delete' ? RECORD_DELETE : RECORD_WRITE, { collection, byCreator }, {
3556
- opaque: action !== 'delete',
3557
- });
254
+ history.changed(placed);
255
+ for (const derived of [index, catalog, profiles, keys, standing, checks])
256
+ derived.forget();
257
+ keys.keepUp();
258
+ // The access history may name keepers now, or none.
259
+ void holding.refreshHolds().catch(() => { });
260
+ // Or a new key, which someone connected may not hold.
261
+ void peers.letGoOfOutsiders().catch(() => { });
3558
262
  }
263
+ // ─── Peers ─────────────────────────────────────────────────────────
264
+ const peers = await openPeers({
265
+ ...base,
266
+ network: deps.network,
267
+ mesh: deps.mesh,
268
+ meeting,
269
+ history,
270
+ keys,
271
+ holds: holding.holds,
272
+ files,
273
+ emit,
274
+ statusChanged,
275
+ admit,
276
+ recordsChanged,
277
+ filesChanged,
278
+ onArrived: deps.onArrived,
279
+ });
280
+ // Whether to hold part of the space is settled before the first hello says what this node holds.
281
+ await holding.refreshHolds().catch(() => { });
282
+ peers.connect();
283
+ mirrors.watch();
284
+ // Here and not earlier: it registers sync handlers and starts timers that need the network connected.
285
+ holding.start();
286
+ const membership = createMembership({
287
+ ...base,
288
+ networked: !!deps.network,
289
+ history,
290
+ keys,
291
+ lines,
292
+ writing,
293
+ peers,
294
+ meeting,
295
+ flagged: warrants.flagged,
296
+ onJoined: deps.onJoined,
297
+ });
3559
298
  // Once at open, then after every change.
3560
- keepUp();
3561
- const pulling = pullMirrors();
3562
- // What this device holds and the folder lacks (copied in, or written before the folder was) goes out soon.
3563
- folderMirror?.changed();
299
+ keys.keepUp();
300
+ const pulling = mirrors.pull();
301
+ mirrors.fillFolder();
302
+ const { catalog: definitions, definitionOf, describe } = catalog;
303
+ const { everyCurrent } = index;
3564
304
  return Object.freeze({
3565
- async list(options = {}) {
3566
- if (options.collection)
3567
- use([options.collection]);
3568
- const shown = [];
3569
- for (const entry of (await counted()).values()) {
3570
- const { collection, deleted } = entry.version;
3571
- if (options.collection ? collection !== options.collection : collection.startsWith('sys.'))
3572
- continue;
3573
- if (deleted && !options.includeDeleted)
3574
- continue;
3575
- shown.push(entry);
3576
- }
3577
- shown.sort((a, b) => a.createdAt.localeCompare(b.createdAt) || a.version.key.localeCompare(b.version.key));
3578
- if (options.newestFirst)
3579
- shown.reverse();
3580
- const page = options.limit === undefined ? shown : shown.slice(0, options.limit);
3581
- const shownOf = (entry) => (entry.shown ??= view(entry.version).catch((error) => {
3582
- entry.shown = undefined;
3583
- throw error;
3584
- }));
3585
- // eslint-disable-next-line @typescript-eslint/consistent-type-assertions -- the caller's type for the body, as in view
3586
- return Promise.all(page.map((entry) => shownOf(entry)));
3587
- },
3588
- get,
3589
- contracts: contractsFor,
305
+ list: index.list,
306
+ get: index.get,
307
+ linked: index.linked,
308
+ history: index.history,
309
+ contracts: writing.contractsFor,
310
+ put: writing.put,
311
+ update: writing.update,
312
+ remove: writing.remove,
313
+ onePerKey: writing.onePerKey,
314
+ can: writing.can,
315
+ ...membership,
3590
316
  /** The note a record's current version was signed under; null when its account signed it itself */
3591
- noteOf: async (recordKey) => (await currentOf(recordKey))?.proof ?? null,
3592
- async put(collection, body, options = {}) {
3593
- return underCurrentRules(() => putOnce(collection, body, options));
3594
- },
317
+ noteOf: async (recordKey) => (await index.currentOf(recordKey))?.proof ?? null,
3595
318
  /** The key `name` has in an account's namespace: this account's, unless another is named */
3596
- keyFor: (name, account = deps.rootDid) => ownedKey(account, name),
3597
- /**
3598
- * The key a record with this body and these links has under its
3599
- * collection's `onePer`, written by `account` (default this one): null
3600
- * when the collection has none, or the body lacks a part it names.
3601
- */
3602
- async onePerKey(collection, body, options = {}) {
3603
- const onePer = options.onePer ?? (await catalog()).get(collection)?.definition.rules?.onePer;
3604
- if (!onePer)
3605
- return null;
3606
- return derivedKey(collection, onePer, {
3607
- root: options.account ?? deps.rootDid,
3608
- links: options.links ?? [],
3609
- body,
3610
- });
3611
- },
3612
- async can(action, target) {
3613
- if (action === 'create')
3614
- return mayNow(target, 'create', null);
3615
- const current = await currentOf(target);
3616
- if (!current || current.deleted)
3617
- return false;
3618
- return mayNow(current.collection, action, await genesisOf(current));
3619
- },
319
+ keyFor: (name, account = rootDid) => ownedKey(account, name),
3620
320
  /** Seals a file, keeps it, and gives back the reference a body names it by (spec 05 §16.6) */
3621
- addFile: (bytes) => (spaceFiles ?? missingFiles()).add(bytes),
321
+ addFile: (bytes) => files.add(bytes),
3622
322
  /** The bytes of a file a body refers to: held here, or fetched from peers or mirrors */
3623
- readFile: (ref) => (spaceFiles ?? missingFiles()).open(ref),
323
+ readFile: (ref) => files.open(ref),
3624
324
  /** For the node itself: writes the next version of a record in a collection `put` refuses, like the profile */
3625
- upsertSystem: (collection, recordKey, body) => upsert(collection, recordKey, body),
325
+ upsertSystem: writing.upsert,
326
+ /** For the node itself: deletes a record in a managed collection */
327
+ removeSystem: writing.removeKey,
3626
328
  async profiles() {
3627
- return [...(await profileMap()).values()].sort((a, b) => a.name.localeCompare(b.name) || a.did.localeCompare(b.did));
329
+ return [...(await profiles.profiles()).values()].sort((a, b) => a.name.localeCompare(b.name) || a.did.localeCompare(b.did));
3628
330
  },
3629
331
  /** For the node itself: says who this account is here, when that changed and the space takes its writes */
3630
332
  async publishProfile(profile) {
@@ -3632,82 +334,31 @@ export async function openSpaceRuntime(deps) {
3632
334
  if (!actsForAccount(session.proof()) || (await cannotWrite()))
3633
335
  return;
3634
336
  const name = profile.name.trim().slice(0, 64);
3635
- const mine = (await profileMap()).get(deps.rootDid);
337
+ const mine = (await profiles.profiles()).get(rootDid);
3636
338
  // An app without the contact key must not take away the one another device published.
3637
339
  const contactKey = profile.contactKey ?? mine?.contactKey;
3638
340
  if (!name ||
3639
341
  (mine?.name === name && mine.contactKey === contactKey && mine.avatar?.hash === profile.avatar?.hash))
3640
342
  return;
3641
- await upsert(PROFILE_COLLECTION, await profileKey(deps.rootDid), {
343
+ await upsert(PROFILE_COLLECTION, await profileKey(rootDid), {
3642
344
  name,
3643
345
  ...(contactKey ? { contactKey } : {}),
3644
346
  ...(profile.avatar ? { avatar: profile.avatar } : {}),
3645
347
  });
3646
348
  },
3647
- rotateKey,
3648
- memberKeys: memberKeyMap,
349
+ rotateKey: keys.rotateKey,
350
+ memberKeys: profiles.memberKeys,
3649
351
  ownMemberKey: () => memberPair,
3650
- readAccess: () => readAccess,
3651
- async setRelays(named) {
3652
- const problem = checkRelays(named);
3653
- if (problem)
3654
- throw new Error(problem);
3655
- await upsert(RELAYS_COLLECTION, SPACE_RELAYS_RECORD, { relays: [...named] });
3656
- },
352
+ readAccess: () => peers.readAccess,
3657
353
  async topicTag(collection, field, value) {
3658
354
  let keyId = null;
3659
355
  if (space.visibility === 'private') {
3660
- const key = currentKey((await access()).history.current);
356
+ const key = keys.currentKey((await history.access()).history.current);
3661
357
  if (!key)
3662
358
  throw new Error(`This device doesn't hold the current key of "${space.name}" yet`);
3663
359
  keyId = key.id;
3664
360
  }
3665
- return topicTag(await tagKey(keyId), collection, field, value);
3666
- },
3667
- async setKeepers(keepers, copies = null) {
3668
- const named = keepers.map((k) => ({ did: k.did, name: k.name }));
3669
- const problem = checkKeepers(named, copies);
3670
- if (problem)
3671
- throw new Error(problem);
3672
- await upsert(KEEPERS_COLLECTION, SPACE_KEEPERS_RECORD, { keepers: named, copies });
3673
- },
3674
- async update(recordKey, body, options = {}) {
3675
- return underCurrentRules(async () => {
3676
- const current = await requireLive(recordKey);
3677
- guard(current.collection);
3678
- // Links carry over unless replaced: ticking a todo should not unhook it from anything.
3679
- const links = options.links ?? (await openBody(current)).links;
3680
- return view(await write(current.collection, body, await after(recordKey), false, links, options.as ? { as: options.as } : {}));
3681
- });
3682
- },
3683
- async linked(recordKey, options = {}) {
3684
- if (options.collection)
3685
- use([options.collection]);
3686
- const pointing = (await linkIndex()).get(recordKey) ?? [];
3687
- const keys = [
3688
- ...new Set(pointing.filter((p) => !options.rel || p.rel === options.rel).map((p) => p.from)),
3689
- ];
3690
- const found = [];
3691
- for (const from of keys) {
3692
- const current = await currentOf(from);
3693
- if (!current || current.deleted)
3694
- continue;
3695
- if (options.collection && current.collection !== options.collection)
3696
- continue;
3697
- found.push(await view(current));
3698
- }
3699
- return found.sort((a, b) => a.createdAt.localeCompare(b.createdAt) || a.key.localeCompare(b.key));
3700
- },
3701
- async remove(recordKey, options = {}) {
3702
- guard((await requireLive(recordKey)).collection);
3703
- await underCurrentRules(() => removeKey(recordKey, options.as));
3704
- },
3705
- /** For the node itself: deletes a record in a managed collection */
3706
- removeSystem: removeKey,
3707
- async history(recordKey) {
3708
- // What a superseded version said is forgotten unless its writer retained it.
3709
- const versions = (await storage.history(recordKey)).filter((version) => !isStub(version));
3710
- return Promise.all(versions.map((version) => view(version)));
361
+ return topicTag(await rules.tagKey(keyId), collection, field, value);
3711
362
  },
3712
363
  /** A collection's computed fields, as its definition says now; a malformed member reads as none */
3713
364
  async computed(collection) {
@@ -3724,18 +375,18 @@ export async function openSpaceRuntime(deps) {
3724
375
  continue;
3725
376
  counts.set(version.collection, (counts.get(version.collection) ?? 0) + 1);
3726
377
  }
3727
- const described = await catalog();
378
+ const described = await definitions();
3728
379
  const names = [...new Set([...described.keys(), ...counts.keys()])].sort();
3729
380
  return names.map((name) => describe(name, described.get(name) ?? null, counts.get(name) ?? 0));
3730
381
  },
3731
382
  async define(input) {
3732
383
  const recordKey = `collection:${input.name}`;
3733
- const current = (await catalog()).get(input.name) ?? null;
384
+ const current = (await definitions()).get(input.name) ?? null;
3734
385
  // Peers don't order definitions by version (spec 02 §6.3): a stored one past what can be
3735
386
  // counted on, written to lock the collection, is simply followed by 1 again.
3736
387
  const after = current && Number.isSafeInteger(current.definition.version + 1) ? current.definition.version : 0;
3737
388
  const version = input.version ?? after + 1;
3738
- const described = await catalog();
389
+ const described = await definitions();
3739
390
  const definition = {
3740
391
  name: input.name,
3741
392
  ...(input.title !== undefined ? { title: input.title } : {}),
@@ -3749,22 +400,7 @@ export async function openSpaceRuntime(deps) {
3749
400
  ...(input.contract !== undefined ? { contract: storedContract(input) } : {}),
3750
401
  ...(input.computed !== undefined ? { computed: storedComputed(input) } : {}),
3751
402
  };
3752
- const contract = definition.contract;
3753
- const shapeProblem = contract !== undefined ? checkContractShape(contract) : null;
3754
- const lineProblem = contract?.line !== undefined ? checkLine(contract.line) : null;
3755
- const problem = checkStoredCollection(definition) ??
3756
- (shapeProblem === 'unknown' ? 'contract takes only "check" and "line"' : shapeProblem) ??
3757
- (contract?.check !== undefined
3758
- ? (checkContracts(contract.check, 'contract.check') ??
3759
- // The library's own care, not protocol: a contract that misreads the schema is refused here.
3760
- checkContractTypes(contract.check, definition.schema, 'contract.check'))
3761
- : null) ??
3762
- (lineProblem === 'unknown' ? 'contract.line takes only "once"' : lineProblem) ??
3763
- (definition.computed !== undefined
3764
- ? (checkComputed(definition.computed) ??
3765
- // The library's care, as for contracts: read against the schemas of what it links to.
3766
- checkComputedTypes(definition.name, definition.computed, definition.schema, (name) => name === definition.name ? definition : (described.get(name)?.definition ?? null)))
3767
- : null);
403
+ const problem = definitionProblem(definition, described);
3768
404
  if (problem)
3769
405
  throw new Error(problem);
3770
406
  if (!Number.isSafeInteger(version))
@@ -3774,249 +410,37 @@ export async function openSpaceRuntime(deps) {
3774
410
  }
3775
411
  // 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).
3776
412
  await upsert(CATALOG_COLLECTION, recordKey, definition);
3777
- const entry = (await catalog()).get(input.name) ?? null;
413
+ const entry = (await definitions()).get(input.name) ?? null;
3778
414
  const count = (await everyCurrent(input.name)).filter((e) => !e.deleted).length;
3779
415
  return describe(input.name, entry, count);
3780
416
  },
3781
417
  async undefine(name) {
3782
- if (!(await catalog()).has(name))
418
+ if (!(await definitions()).has(name))
3783
419
  throw new Error(`${name} is not defined in this space`);
3784
420
  // Records left behind would lose their shape and their rules, so they go first.
3785
421
  const left = (await everyCurrent(name)).filter((e) => !e.deleted).length;
3786
422
  if (left)
3787
423
  throw new Error(`${name} still has ${left} record${left === 1 ? '' : 's'}; delete them first`);
3788
- await removeKey(`collection:${name}`);
3789
- },
3790
- async access() {
3791
- const { history } = await access();
3792
- const state = history.current;
3793
- const members = [...readers(state)].sort();
3794
- return Object.freeze({
3795
- roles: [...state.roles]
3796
- .map(([name, definitions]) => ({
3797
- name,
3798
- ...(definitions[0]?.title !== undefined ? { title: definitions[0].title } : {}),
3799
- definitions: definitions.map((definition) => ({
3800
- event: definition.event,
3801
- by: definition.by,
3802
- grants: definition.grants,
3803
- nests: definition.nests,
3804
- })),
3805
- }))
3806
- .sort((a, b) => a.name.localeCompare(b.name)),
3807
- members: members.map((did) => ({
3808
- did,
3809
- founder: state.founders.has(did),
3810
- roles: rolesOf(state, did),
3811
- })),
3812
- invites: [...state.invites].map(([inviteDid, invite]) => ({
3813
- key: inviteDid,
3814
- role: invite.role,
3815
- open: invite.open,
3816
- })),
3817
- founder: state.founders.has(deps.rootDid),
3818
- top: space.top === 'none' ? 'none' : 'founders',
3819
- headless: headless(state),
3820
- successors: [...state.successors].map(([successor, by]) => ({ space: successor, by })),
3821
- mine: rolesOf(state, deps.rootDid),
3822
- heads: history.heads(),
3823
- key: state.keys.length ? { changes: state.keys.length - 1, held: currentKey(state) !== null } : null,
3824
- relays: state.relays.length ? state.relays : relays,
3825
- keepers: state.keepers,
3826
- copies: state.copies,
3827
- forks: history.forks(),
3828
- flagged: await flagged(),
3829
- });
3830
- },
3831
- /** Whether this account, or another, may invoke a command with these arguments, now */
3832
- async may(cmd, args = {}, account = deps.rootDid) {
3833
- return may((await access()).history.current, account, cmd, args);
3834
- },
3835
- /** Whether this account, or another, holds every grant a role gives, as wide or wider, now */
3836
- async holdsRole(role, account = deps.rootDid) {
3837
- return holdsRole((await access()).history.current, account, role);
3838
- },
3839
- async assign(did, role) {
3840
- await assign(did, role, true);
3841
- },
3842
- async unassign(did, role) {
3843
- await assign(did, role, false);
3844
- },
3845
- async removeMember(did) {
3846
- await removeAccount(did);
3847
- },
3848
- /** Stops being a founder, keeping the roles held, and `keep` first when given */
3849
- async stepDown(keep) {
3850
- const { history } = await access();
3851
- if (!history.current.founders.has(deps.rootDid))
3852
- throw new Error(`You are not a founder of "${space.name}"`);
3853
- if (keep !== undefined && !rolesOf(history.current, deps.rootDid).includes(keep))
3854
- await assign(deps.rootDid, keep, true);
3855
- if (rolesOf((await access()).history.current, deps.rootDid).length === 0)
3856
- throw new Error(`You hold no role in "${space.name}", so stepping down would leave it: keep a role, or leave`);
3857
- const cutoff = await cutoffFor(deps.rootDid);
3858
- await upsert(STEPDOWN_COLLECTION, await stepDownKey(deps.rootDid), {
3859
- did: deps.rootDid,
3860
- ...(Object.keys(cutoff).length ? { cutoff } : {}),
3861
- });
3862
- },
3863
- /** Names a space that succeeds this one. It changes nothing here */
3864
- async succeed(successor) {
3865
- if (!isSpaceId(successor) || successor === space.id)
3866
- throw new Error('A successor is named by its space id');
3867
- // Refused here, with the reason, when this account may not: as every peer would.
3868
- await upsert(SUCCEED_COLLECTION, await succeedKey(successor), { space: successor });
3869
- },
3870
- /**
3871
- * Gives up this account's place before it forgets the space: its own
3872
- * member record with no role, so the others stop counting it a reader and
3873
- * a key change becomes due. Nothing sends the removal once the space is
3874
- * closed, so this waits up to `waitMs` for a peer of another account to
3875
- * say it has it. False when it couldn't be written, or nobody took it in
3876
- * time.
3877
- */
3878
- async giveUpPlace(waitMs) {
3879
- const state = (await access()).history.current;
3880
- // Shared to view, or already gone: there is nothing to remove.
3881
- if (!isMember(state, deps.rootDid))
3882
- return true;
3883
- // Nobody else holds a place, so nobody else needs to know.
3884
- if ([...readers(state)].every((did) => did === deps.rootDid))
3885
- return true;
3886
- const taken = new Set();
3887
- let wanted = null;
3888
- let found = () => { };
3889
- const onStored = (peer, ids) => {
3890
- void peerAccounts.get(peer)?.then(({ account }) => {
3891
- if (account === deps.rootDid)
3892
- return;
3893
- for (const id of ids)
3894
- taken.add(id);
3895
- if (wanted !== null && taken.has(wanted))
3896
- found();
3897
- });
3898
- };
3899
- // Listening before writing: a peer can answer before the write returns.
3900
- sync.on('stored', onStored);
3901
- try {
3902
- wanted = (await removeAccount(deps.rootDid)).version;
3903
- if (taken.has(wanted))
3904
- return true;
3905
- if (waitMs <= 0)
3906
- return false;
3907
- return await new Promise((resolve) => {
3908
- const timer = setTimeout(() => resolve(false), waitMs);
3909
- found = () => {
3910
- clearTimeout(timer);
3911
- resolve(true);
3912
- };
3913
- });
3914
- }
3915
- catch {
3916
- // A note that may not change access; another of the account's devices can.
3917
- return false;
3918
- }
3919
- finally {
3920
- sync.off('stored', onStored);
3921
- }
3922
- },
3923
- /**
3924
- * Waits up to `waitMs` for this node to be level with `peer` here: nothing
3925
- * left in flight either way, so the peer holds everything this node does.
3926
- * False when that long passed first.
3927
- */
3928
- syncedWith(peer, waitMs) {
3929
- if (sync.levelWith(peer))
3930
- return Promise.resolve(true);
3931
- return new Promise((resolve) => {
3932
- const done = (level) => {
3933
- clearTimeout(timer);
3934
- sync.off('synced', onSynced);
3935
- resolve(level);
3936
- };
3937
- const onSynced = (from) => {
3938
- if (from === peer)
3939
- done(true);
3940
- };
3941
- const timer = setTimeout(() => done(false), waitMs);
3942
- sync.on('synced', onSynced);
3943
- // Behind, it would start catching up only at the next heartbeat.
3944
- sync.notifyPeers([peer]);
3945
- });
3946
- },
3947
- /** Writes a role's definition: its grants, issued by this account, and the roles it nests */
3948
- async defineRole(role) {
3949
- const problem = checkFoundingRole(role);
3950
- if (problem)
3951
- throw new Error(problem);
3952
- const nonce = () => base64UrlEncode(globalThis.crypto.getRandomValues(new Uint8Array(12)));
3953
- await upsert(ROLE_COLLECTION, roleKey(role.name), definitionBody(role, { root: deps.rootDid, spaceId: space.id }, nonce));
3954
- },
3955
- /** Opens an invite to a role, with its own fresh secret unless a short link's gives it one */
3956
- async openInvite(role, secret = generateInviteSecret()) {
3957
- const pair = await deriveInviteKey(secret, provider);
3958
- await upsert(INVITE_COLLECTION, await inviteRecordKey(pair.did), { key: pair.did, role, open: true });
3959
- return { secret, key: pair.did };
3960
- },
3961
- async closeInvite(inviteDid) {
3962
- const { history } = await access();
3963
- const invite = history.current.invites.get(inviteDid);
3964
- if (!invite)
3965
- throw new Error('There is no such invite in this space');
3966
- // Who joined with it before this node closed it stays: the close names what it saw, and the replay does the rest.
3967
- await upsert(INVITE_COLLECTION, await inviteRecordKey(inviteDid), {
3968
- key: inviteDid,
3969
- role: invite.role,
3970
- open: false,
3971
- });
424
+ await writing.removeKey(`collection:${name}`);
3972
425
  },
426
+ syncedWith: peers.syncedWith,
3973
427
  /**
3974
- * Revokes a key of this account's. With `waitMs`, it then waits up to that
3975
- * long for a peer to say it has the revoke: a device about to stop sends
3976
- * nothing after, so true means it left. A node with no network configured
3977
- * can't send it anywhere, so false at once. Without, true once written.
428
+ * Who has this node's writes from `since` on: the space's keepers, or, in a
429
+ * space that names none, where every member's node is a copy, a peer
430
+ * connected now that holds all this node does. Null when nobody, in time.
3978
431
  */
3979
- async revoke(key, options = {}) {
3980
- const waitMs = options.waitMs ?? 0;
3981
- const taken = new Set();
3982
- let wanted = null;
3983
- let found = () => { };
3984
- const onStored = (_peer, ids) => {
3985
- for (const id of ids)
3986
- taken.add(id);
3987
- if (wanted !== null && taken.has(wanted))
3988
- found();
3989
- };
3990
- // Listening before writing: a peer can answer before the write returns.
3991
- if (waitMs > 0)
3992
- sync.on('stored', onStored);
3993
- try {
3994
- const cutoff = await cutoffFor(deps.rootDid, key);
3995
- wanted = (await upsert(REVOKE_COLLECTION, await revokeKey(key, deps.rootDid), {
3996
- key,
3997
- ...(Object.keys(cutoff).length ? { cutoff } : {}),
3998
- })).version;
3999
- if (waitMs <= 0 || taken.has(wanted))
4000
- return true;
4001
- // With a network configured a peer may still be on its way, through a socket not yet
4002
- // joined or a host not yet reached; with none, nobody can come.
4003
- if (!net)
4004
- return false;
4005
- return await new Promise((resolve) => {
4006
- const timer = setTimeout(() => resolve(false), waitMs);
4007
- found = () => {
4008
- clearTimeout(timer);
4009
- resolve(true);
4010
- };
4011
- });
4012
- }
4013
- finally {
4014
- if (waitMs > 0)
4015
- sync.off('stored', onStored);
4016
- }
4017
- },
4018
- async isRevoked(key) {
4019
- return (await access()).history.revoked(key, deps.rootDid).length > 0;
432
+ async kept(waitMs, since) {
433
+ if ((await history.access()).history.current.keepers.length > 0)
434
+ return (await holding.kept(waitMs, since)) ? 'keepers' : null;
435
+ const deadline = Date.now() + waitMs;
436
+ do {
437
+ const left = Math.max(0, deadline - Date.now());
438
+ const level = await Promise.all(peers.connectedPeers().map((peer) => peers.syncedWith(peer, Math.min(2000, left))));
439
+ if (level.some(Boolean))
440
+ return 'peer';
441
+ await new Promise((resolve) => setTimeout(resolve, Math.min(250, left)));
442
+ } while (Date.now() < deadline);
443
+ return null;
4020
444
  },
4021
445
  async versionsOf(keys) {
4022
446
  return (await Promise.all(keys.map((key) => storage.history(key)))).flat();
@@ -4037,115 +461,37 @@ export async function openSpaceRuntime(deps) {
4037
461
  if (placed.length === 0)
4038
462
  return 0;
4039
463
  recordsChanged(placed);
4040
- announceSoon();
464
+ peers.announceSoon();
4041
465
  return placed.length;
4042
466
  },
4043
- /** Uses an invite's secret, once its record has arrived. True when this account is a member. */
4044
- async join(secret) {
4045
- const { history } = await access();
4046
- const pair = await deriveInviteKey(secret, provider);
4047
- const invite = history.current.invites.get(pair.did);
4048
- if (isMember(history.current, deps.rootDid) &&
4049
- (!invite || rolesOf(history.current, deps.rootDid).includes(invite.role))) {
4050
- waitingInvite = false;
4051
- deps.onJoined?.();
4052
- return true;
4053
- }
4054
- if (!invite?.open)
4055
- return false;
4056
- await upsert(ASSIGN_COLLECTION, await assignKey(deps.rootDid, invite.role), {
4057
- did: deps.rootDid,
4058
- role: invite.role,
4059
- assigned: true,
4060
- invite: { key: pair.did, signature: await signInvite(space.id, deps.rootDid, pair, provider) },
4061
- }, { joining: true });
4062
- waitingInvite = false;
4063
- deps.onJoined?.();
4064
- return true;
4065
- },
4066
467
  async status() {
468
+ const { connection, peers: connected, accounts, rejected } = peers.status();
4067
469
  return {
4068
470
  space: space.id,
4069
- connection: liveConnection(),
4070
- peers: connectedPeers(),
4071
- accounts: Object.fromEntries([...knownAccounts].flatMap(([peer, known]) => known.account && routes.has(peer) ? [[peer, known.account]] : [])),
471
+ connection,
472
+ peers: connected,
473
+ accounts,
4072
474
  fingerprint: await storage.fingerprint(),
4073
475
  rejected,
4074
- holds: partial ? Object.keys(cacheState.used).sort() : 'all',
4075
- pending: (await adapter.list(PENDING_PREFIX)).length,
476
+ holds: holding.held(),
477
+ pending: await holding.pending(),
4076
478
  };
4077
479
  },
4078
- use,
4079
- async send(message, to) {
4080
- const encoded = JSON.stringify(message ?? null);
4081
- if (encoded.length > MAX_LIVE_BYTES)
4082
- throw new Error('A live message can be at most 64 KB');
4083
- const gone = await formerMembers();
4084
- for (const peer of connectedPeers()) {
4085
- const account = (await peerAccounts.get(peer))?.account ?? null;
4086
- if (to && to !== peer && account !== to)
4087
- continue;
4088
- // Removed, or left: live messages stop with everything else.
4089
- if (account !== null && gone.has(account))
4090
- continue;
4091
- routes.get(peer)?.send(peer, { type: LIVE_MESSAGE, from: session.did, payload: message ?? null });
4092
- }
4093
- },
4094
- /**
4095
- * Always-on nodes to hold a socket to besides those configured: the hosts
4096
- * the account or the space uses. Sockets to any given before and not now
4097
- * are closed.
4098
- */
4099
- useNodes(nodes) {
4100
- if (!net || closed)
4101
- return;
4102
- const configured = new Set(net.nodes ?? []);
4103
- const wanted = new Set(nodes.filter((node) => !configured.has(node)));
4104
- for (const [node, network] of hostNetworks) {
4105
- if (wanted.has(node))
4106
- continue;
4107
- hostNetworks.delete(node);
4108
- networks.splice(networks.indexOf(network), 1);
4109
- network.disconnect();
4110
- }
4111
- for (const node of wanted) {
4112
- if (hostNetworks.has(node))
4113
- continue;
4114
- const network = nodeNetwork(node);
4115
- hostNetworks.set(node, network);
4116
- networks.push(network);
4117
- listen(network);
4118
- if (connection === 'offline')
4119
- connection = 'connecting';
4120
- sync.start();
4121
- void network.connect().then(() => {
4122
- connection = 'connected';
4123
- emit({ type: 'status', space: space.id });
4124
- }, () => emit({ type: 'status', space: space.id }));
4125
- }
4126
- },
480
+ use: holding.use,
481
+ send: peers.send,
482
+ useNodes: peers.useNodes,
4127
483
  async close() {
4128
484
  closed = true;
4129
- stopWatchingMesh?.();
4130
- if (dropTimer)
4131
- clearInterval(dropTimer);
4132
- await tidying;
4133
- await flushCache();
4134
- await keepingUp.done();
485
+ peers.quiet();
486
+ await holding.close();
487
+ await keys.keepingUp.done();
4135
488
  await pulling;
4136
- await Promise.all(mirrors.map((mirror) => mirror.close()));
489
+ await mirrors.close();
4137
490
  if (filesTimer)
4138
491
  clearTimeout(filesTimer);
4139
- spaceFiles?.close();
492
+ files.close();
4140
493
  await filesPass;
4141
- if (watchTimer)
4142
- clearInterval(watchTimer);
4143
- if (announceTimer)
4144
- clearTimeout(announceTimer);
4145
- channel?.close();
4146
- sync.stop();
4147
- for (const network of networks)
4148
- network.disconnect();
494
+ peers.close();
4149
495
  await storage.close();
4150
496
  },
4151
497
  });