@minca/core 0.2.0 → 0.4.0

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 (420) hide show
  1. package/README.md +2 -2
  2. package/dist/{session → hosting}/hosting.d.ts +2 -8
  3. package/dist/hosting/hosting.d.ts.map +1 -0
  4. package/dist/{session → hosting}/hosting.js +3 -3
  5. package/dist/hosting/hosting.js.map +1 -0
  6. package/dist/identity/abilities.d.ts +0 -2
  7. package/dist/identity/abilities.d.ts.map +1 -1
  8. package/dist/identity/abilities.js +2 -2
  9. package/dist/identity/abilities.js.map +1 -1
  10. package/dist/identity/account-vault.d.ts +0 -2
  11. package/dist/identity/account-vault.d.ts.map +1 -1
  12. package/dist/identity/account-vault.js +1 -1
  13. package/dist/identity/account-vault.js.map +1 -1
  14. package/dist/identity/crypto-p256.d.ts +1 -1
  15. package/dist/identity/crypto-p256.d.ts.map +1 -1
  16. package/dist/identity/ucan.d.ts +2 -1
  17. package/dist/identity/ucan.d.ts.map +1 -1
  18. package/dist/identity/ucan.js +1 -1
  19. package/dist/identity/ucan.js.map +1 -1
  20. package/dist/inbox/inbox.d.ts +0 -21
  21. package/dist/inbox/inbox.d.ts.map +1 -1
  22. package/dist/inbox/inbox.js +4 -4
  23. package/dist/inbox/inbox.js.map +1 -1
  24. package/dist/inbox/index.d.ts +4 -5
  25. package/dist/inbox/index.d.ts.map +1 -1
  26. package/dist/inbox/index.js +2 -3
  27. package/dist/inbox/index.js.map +1 -1
  28. package/dist/inbox/names.d.ts +0 -4
  29. package/dist/inbox/names.d.ts.map +1 -1
  30. package/dist/inbox/names.js +2 -2
  31. package/dist/inbox/names.js.map +1 -1
  32. package/dist/index.d.ts +50 -84
  33. package/dist/index.d.ts.map +1 -1
  34. package/dist/index.js +38 -60
  35. package/dist/index.js.map +1 -1
  36. package/dist/network/mesh.d.ts.map +1 -1
  37. package/dist/network/mesh.js +23 -3
  38. package/dist/network/mesh.js.map +1 -1
  39. package/dist/network/network-manager.d.ts +5 -0
  40. package/dist/network/network-manager.d.ts.map +1 -1
  41. package/dist/network/network-manager.js +3 -0
  42. package/dist/network/network-manager.js.map +1 -1
  43. package/dist/network/peer-auth.d.ts +17 -5
  44. package/dist/network/peer-auth.d.ts.map +1 -1
  45. package/dist/network/peer-auth.js +19 -9
  46. package/dist/network/peer-auth.js.map +1 -1
  47. package/dist/network/rendezvous.d.ts +2 -0
  48. package/dist/network/rendezvous.d.ts.map +1 -1
  49. package/dist/network/rendezvous.js +5 -0
  50. package/dist/network/rendezvous.js.map +1 -1
  51. package/dist/network/rtc-transport.d.ts.map +1 -1
  52. package/dist/network/rtc-transport.js +9 -3
  53. package/dist/network/rtc-transport.js.map +1 -1
  54. package/dist/network/transport.d.ts +12 -0
  55. package/dist/network/transport.d.ts.map +1 -1
  56. package/dist/network/ws-transport.d.ts +1 -1
  57. package/dist/network/ws-transport.d.ts.map +1 -1
  58. package/dist/network/ws-transport.js +14 -4
  59. package/dist/network/ws-transport.js.map +1 -1
  60. package/dist/node/carrier.d.ts +1 -33
  61. package/dist/node/carrier.d.ts.map +1 -1
  62. package/dist/node/carrier.js +38 -68
  63. package/dist/node/carrier.js.map +1 -1
  64. package/dist/node/index.d.ts +5 -16
  65. package/dist/node/index.d.ts.map +1 -1
  66. package/dist/node/index.js +2 -9
  67. package/dist/node/index.js.map +1 -1
  68. package/dist/node/node-carriers.d.ts.map +1 -1
  69. package/dist/node/node-carriers.js +21 -52
  70. package/dist/node/node-carriers.js.map +1 -1
  71. package/dist/node/node-context.d.ts +0 -2
  72. package/dist/node/node-context.d.ts.map +1 -1
  73. package/dist/node/node-context.js.map +1 -1
  74. package/dist/node/node-hosting.d.ts.map +1 -1
  75. package/dist/node/node-hosting.js +14 -5
  76. package/dist/node/node-hosting.js.map +1 -1
  77. package/dist/node/node-records.js +2 -2
  78. package/dist/node/node-records.js.map +1 -1
  79. package/dist/node/node.d.ts.map +1 -1
  80. package/dist/node/node.js +152 -36
  81. package/dist/node/node.js.map +1 -1
  82. package/dist/node/space-checks.d.ts +3 -1
  83. package/dist/node/space-checks.d.ts.map +1 -1
  84. package/dist/node/space-checks.js +7 -3
  85. package/dist/node/space-checks.js.map +1 -1
  86. package/dist/node/space-holding.d.ts +5 -0
  87. package/dist/node/space-holding.d.ts.map +1 -1
  88. package/dist/node/space-holding.js +90 -5
  89. package/dist/node/space-holding.js.map +1 -1
  90. package/dist/node/space-lines.d.ts +3 -0
  91. package/dist/node/space-lines.d.ts.map +1 -1
  92. package/dist/node/space-lines.js +13 -1
  93. package/dist/node/space-lines.js.map +1 -1
  94. package/dist/node/space-membership.js +4 -4
  95. package/dist/node/space-membership.js.map +1 -1
  96. package/dist/node/space-mirrors.d.ts +1 -1
  97. package/dist/node/space-mirrors.d.ts.map +1 -1
  98. package/dist/node/space-mirrors.js +17 -5
  99. package/dist/node/space-mirrors.js.map +1 -1
  100. package/dist/node/space-peers.d.ts +7 -2
  101. package/dist/node/space-peers.d.ts.map +1 -1
  102. package/dist/node/space-peers.js +44 -10
  103. package/dist/node/space-peers.js.map +1 -1
  104. package/dist/node/space-runtime.d.ts +7 -3
  105. package/dist/node/space-runtime.d.ts.map +1 -1
  106. package/dist/node/space-runtime.js +32 -10
  107. package/dist/node/space-runtime.js.map +1 -1
  108. package/dist/node/space-standing.d.ts +1 -1
  109. package/dist/node/space-standing.d.ts.map +1 -1
  110. package/dist/node/space-standing.js +23 -42
  111. package/dist/node/space-standing.js.map +1 -1
  112. package/dist/node/space-warrants.js +1 -1
  113. package/dist/node/space-warrants.js.map +1 -1
  114. package/dist/node/space-writing.d.ts.map +1 -1
  115. package/dist/node/space-writing.js +21 -32
  116. package/dist/node/space-writing.js.map +1 -1
  117. package/dist/node/stores.d.ts +9 -57
  118. package/dist/node/stores.d.ts.map +1 -1
  119. package/dist/node/stores.js +1 -72
  120. package/dist/node/stores.js.map +1 -1
  121. package/dist/node/types.d.ts +19 -8
  122. package/dist/node/types.d.ts.map +1 -1
  123. package/dist/node/writer-keys.d.ts +15 -14
  124. package/dist/node/writer-keys.d.ts.map +1 -1
  125. package/dist/node/writer-keys.js +3 -115
  126. package/dist/node/writer-keys.js.map +1 -1
  127. package/dist/privacy/direct.d.ts +0 -7
  128. package/dist/privacy/direct.d.ts.map +1 -1
  129. package/dist/privacy/direct.js +2 -2
  130. package/dist/privacy/direct.js.map +1 -1
  131. package/dist/query/filter.d.ts +0 -2
  132. package/dist/query/filter.d.ts.map +1 -1
  133. package/dist/query/filter.js +1 -1
  134. package/dist/query/filter.js.map +1 -1
  135. package/dist/query/types.d.ts +2 -6
  136. package/dist/query/types.d.ts.map +1 -1
  137. package/dist/query/types.js.map +1 -1
  138. package/dist/records/key.d.ts +18 -19
  139. package/dist/records/key.d.ts.map +1 -1
  140. package/dist/records/key.js +55 -43
  141. package/dist/records/key.js.map +1 -1
  142. package/dist/records/links.js +1 -1
  143. package/dist/records/rules.d.ts +1 -1
  144. package/dist/records/rules.d.ts.map +1 -1
  145. package/dist/records/rules.js +6 -4
  146. package/dist/records/rules.js.map +1 -1
  147. package/dist/schemas/direct.d.ts +70 -0
  148. package/dist/schemas/direct.d.ts.map +1 -0
  149. package/dist/schemas/direct.js +39 -0
  150. package/dist/schemas/direct.js.map +1 -0
  151. package/dist/schemas/index.d.ts +10 -73
  152. package/dist/schemas/index.d.ts.map +1 -1
  153. package/dist/schemas/index.js +8 -66
  154. package/dist/schemas/index.js.map +1 -1
  155. package/dist/space/account-registry.d.ts +0 -3
  156. package/dist/space/account-registry.d.ts.map +1 -1
  157. package/dist/space/account-registry.js.map +1 -1
  158. package/dist/space/own-automations.d.ts +51 -95
  159. package/dist/space/own-automations.d.ts.map +1 -1
  160. package/dist/space/own-automations.js +100 -295
  161. package/dist/space/own-automations.js.map +1 -1
  162. package/dist/space/pass.d.ts +8 -3
  163. package/dist/space/pass.d.ts.map +1 -1
  164. package/dist/space/pass.js +4 -3
  165. package/dist/space/pass.js.map +1 -1
  166. package/dist/space/space-manager.d.ts +1 -3
  167. package/dist/space/space-manager.d.ts.map +1 -1
  168. package/dist/space/space-manager.js +5 -7
  169. package/dist/space/space-manager.js.map +1 -1
  170. package/dist/storage/body-cache.d.ts +29 -0
  171. package/dist/storage/body-cache.d.ts.map +1 -0
  172. package/dist/storage/body-cache.js +64 -0
  173. package/dist/storage/body-cache.js.map +1 -0
  174. package/dist/storage/encrypted-adapter.d.ts +0 -5
  175. package/dist/storage/encrypted-adapter.d.ts.map +1 -1
  176. package/dist/storage/encrypted-adapter.js +1 -1
  177. package/dist/storage/encrypted-adapter.js.map +1 -1
  178. package/dist/storage/mirror.d.ts.map +1 -1
  179. package/dist/storage/mirror.js +35 -16
  180. package/dist/storage/mirror.js.map +1 -1
  181. package/dist/storage/segment.d.ts +6 -2
  182. package/dist/storage/segment.d.ts.map +1 -1
  183. package/dist/storage/segment.js +8 -4
  184. package/dist/storage/segment.js.map +1 -1
  185. package/dist/storage/shared-store.d.ts +32 -0
  186. package/dist/storage/shared-store.d.ts.map +1 -0
  187. package/dist/storage/{folder-reconcile.js → shared-store.js} +15 -15
  188. package/dist/storage/shared-store.js.map +1 -0
  189. package/dist/storage/storage-provider.d.ts +19 -9
  190. package/dist/storage/storage-provider.d.ts.map +1 -1
  191. package/dist/storage/storage-provider.js +155 -62
  192. package/dist/storage/storage-provider.js.map +1 -1
  193. package/dist/sync/sync-engine.d.ts +17 -4
  194. package/dist/sync/sync-engine.d.ts.map +1 -1
  195. package/dist/sync/sync-engine.js +298 -84
  196. package/dist/sync/sync-engine.js.map +1 -1
  197. package/dist/sync/sync-messages.d.ts +5 -1
  198. package/dist/sync/sync-messages.d.ts.map +1 -1
  199. package/dist/sync/sync-messages.js +1 -1
  200. package/dist/sync/sync-messages.js.map +1 -1
  201. package/dist/types.d.ts +19 -7
  202. package/dist/types.d.ts.map +1 -1
  203. package/dist/types.js +4 -1
  204. package/dist/types.js.map +1 -1
  205. package/dist/utils/index.d.ts +5 -5
  206. package/dist/utils/index.d.ts.map +1 -1
  207. package/dist/utils/index.js +5 -5
  208. package/dist/utils/index.js.map +1 -1
  209. package/dist/utils/step.d.ts +8 -0
  210. package/dist/utils/step.d.ts.map +1 -0
  211. package/dist/utils/step.js +15 -0
  212. package/dist/utils/step.js.map +1 -0
  213. package/docs/README.md +4 -3
  214. package/docs/actions.md +41 -2
  215. package/docs/agents.md +13 -10
  216. package/docs/automations.md +16 -48
  217. package/docs/blueprints-and-guides.md +2 -2
  218. package/docs/bots.md +3 -3
  219. package/docs/building-an-app.md +2 -2
  220. package/docs/collections.md +2 -4
  221. package/docs/computed.md +1 -2
  222. package/docs/node.md +108 -40
  223. package/docs/proposing-collections.md +3 -3
  224. package/docs/query-format.md +6 -5
  225. package/docs/records-and-queries.md +12 -13
  226. package/docs/sign-in.md +16 -16
  227. package/docs/spaces.md +0 -5
  228. package/docs/standard-library.md +6 -8
  229. package/docs/storage.md +114 -22
  230. package/docs/usernames.md +1 -1
  231. package/package.json +15 -25
  232. package/dist/identity/account-store.d.ts +0 -83
  233. package/dist/identity/account-store.d.ts.map +0 -1
  234. package/dist/identity/account-store.js +0 -234
  235. package/dist/identity/account-store.js.map +0 -1
  236. package/dist/identity/device-key.d.ts +0 -26
  237. package/dist/identity/device-key.d.ts.map +0 -1
  238. package/dist/identity/device-key.js +0 -48
  239. package/dist/identity/device-key.js.map +0 -1
  240. package/dist/identity/idb.d.ts +0 -19
  241. package/dist/identity/idb.d.ts.map +0 -1
  242. package/dist/identity/idb.js +0 -56
  243. package/dist/identity/idb.js.map +0 -1
  244. package/dist/node/actions.d.ts +0 -85
  245. package/dist/node/actions.d.ts.map +0 -1
  246. package/dist/node/actions.js +0 -921
  247. package/dist/node/actions.js.map +0 -1
  248. package/dist/node/host.d.ts +0 -187
  249. package/dist/node/host.d.ts.map +0 -1
  250. package/dist/node/host.js +0 -818
  251. package/dist/node/host.js.map +0 -1
  252. package/dist/node/usage.d.ts +0 -32
  253. package/dist/node/usage.d.ts.map +0 -1
  254. package/dist/node/usage.js +0 -217
  255. package/dist/node/usage.js.map +0 -1
  256. package/dist/node/watch-notifications.d.ts +0 -25
  257. package/dist/node/watch-notifications.d.ts.map +0 -1
  258. package/dist/node/watch-notifications.js +0 -166
  259. package/dist/node/watch-notifications.js.map +0 -1
  260. package/dist/node/worker.d.ts +0 -83
  261. package/dist/node/worker.d.ts.map +0 -1
  262. package/dist/node/worker.js +0 -305
  263. package/dist/node/worker.js.map +0 -1
  264. package/dist/node-worker.d.ts +0 -2
  265. package/dist/node-worker.d.ts.map +0 -1
  266. package/dist/node-worker.js +0 -16
  267. package/dist/node-worker.js.map +0 -1
  268. package/dist/schemas/automations.d.ts +0 -390
  269. package/dist/schemas/automations.d.ts.map +0 -1
  270. package/dist/schemas/automations.js +0 -619
  271. package/dist/schemas/automations.js.map +0 -1
  272. package/dist/schemas/blueprints.d.ts +0 -122
  273. package/dist/schemas/blueprints.d.ts.map +0 -1
  274. package/dist/schemas/blueprints.js +0 -337
  275. package/dist/schemas/blueprints.js.map +0 -1
  276. package/dist/schemas/choosing.d.ts +0 -19
  277. package/dist/schemas/choosing.d.ts.map +0 -1
  278. package/dist/schemas/choosing.js +0 -69
  279. package/dist/schemas/choosing.js.map +0 -1
  280. package/dist/schemas/connectors.d.ts +0 -202
  281. package/dist/schemas/connectors.d.ts.map +0 -1
  282. package/dist/schemas/connectors.js +0 -140
  283. package/dist/schemas/connectors.js.map +0 -1
  284. package/dist/schemas/cron.d.ts +0 -14
  285. package/dist/schemas/cron.d.ts.map +0 -1
  286. package/dist/schemas/cron.js +0 -75
  287. package/dist/schemas/cron.js.map +0 -1
  288. package/dist/schemas/geo.d.ts +0 -63
  289. package/dist/schemas/geo.d.ts.map +0 -1
  290. package/dist/schemas/geo.js +0 -131
  291. package/dist/schemas/geo.js.map +0 -1
  292. package/dist/schemas/guides.d.ts +0 -26
  293. package/dist/schemas/guides.d.ts.map +0 -1
  294. package/dist/schemas/guides.js +0 -33
  295. package/dist/schemas/guides.js.map +0 -1
  296. package/dist/schemas/library/annotations.d.ts +0 -616
  297. package/dist/schemas/library/annotations.d.ts.map +0 -1
  298. package/dist/schemas/library/annotations.js +0 -156
  299. package/dist/schemas/library/annotations.js.map +0 -1
  300. package/dist/schemas/library/collections.d.ts +0 -211
  301. package/dist/schemas/library/collections.d.ts.map +0 -1
  302. package/dist/schemas/library/collections.js +0 -57
  303. package/dist/schemas/library/collections.js.map +0 -1
  304. package/dist/schemas/library/community.d.ts +0 -1136
  305. package/dist/schemas/library/community.d.ts.map +0 -1
  306. package/dist/schemas/library/community.js +0 -315
  307. package/dist/schemas/library/community.js.map +0 -1
  308. package/dist/schemas/library/life.d.ts +0 -1440
  309. package/dist/schemas/library/life.d.ts.map +0 -1
  310. package/dist/schemas/library/life.js +0 -202
  311. package/dist/schemas/library/life.js.map +0 -1
  312. package/dist/schemas/library/media.d.ts +0 -1002
  313. package/dist/schemas/library/media.d.ts.map +0 -1
  314. package/dist/schemas/library/media.js +0 -110
  315. package/dist/schemas/library/media.js.map +0 -1
  316. package/dist/schemas/library/money.d.ts +0 -1221
  317. package/dist/schemas/library/money.d.ts.map +0 -1
  318. package/dist/schemas/library/money.js +0 -168
  319. package/dist/schemas/library/money.js.map +0 -1
  320. package/dist/schemas/library/planning.d.ts +0 -1107
  321. package/dist/schemas/library/planning.d.ts.map +0 -1
  322. package/dist/schemas/library/planning.js +0 -214
  323. package/dist/schemas/library/planning.js.map +0 -1
  324. package/dist/schemas/library/publishing.d.ts +0 -1499
  325. package/dist/schemas/library/publishing.d.ts.map +0 -1
  326. package/dist/schemas/library/publishing.js +0 -285
  327. package/dist/schemas/library/publishing.js.map +0 -1
  328. package/dist/schemas/library/social.d.ts +0 -1257
  329. package/dist/schemas/library/social.d.ts.map +0 -1
  330. package/dist/schemas/library/social.js +0 -147
  331. package/dist/schemas/library/social.js.map +0 -1
  332. package/dist/schemas/standard.d.ts +0 -21
  333. package/dist/schemas/standard.d.ts.map +0 -1
  334. package/dist/schemas/standard.js +0 -39
  335. package/dist/schemas/standard.js.map +0 -1
  336. package/dist/session/account-hint.d.ts +0 -13
  337. package/dist/session/account-hint.d.ts.map +0 -1
  338. package/dist/session/account-hint.js +0 -54
  339. package/dist/session/account-hint.js.map +0 -1
  340. package/dist/session/auth.d.ts +0 -411
  341. package/dist/session/auth.d.ts.map +0 -1
  342. package/dist/session/auth.js +0 -1529
  343. package/dist/session/auth.js.map +0 -1
  344. package/dist/session/channel-room.d.ts +0 -26
  345. package/dist/session/channel-room.d.ts.map +0 -1
  346. package/dist/session/channel-room.js +0 -56
  347. package/dist/session/channel-room.js.map +0 -1
  348. package/dist/session/connect-code.d.ts +0 -127
  349. package/dist/session/connect-code.d.ts.map +0 -1
  350. package/dist/session/connect-code.js +0 -408
  351. package/dist/session/connect-code.js.map +0 -1
  352. package/dist/session/connect.d.ts +0 -386
  353. package/dist/session/connect.d.ts.map +0 -1
  354. package/dist/session/connect.js +0 -583
  355. package/dist/session/connect.js.map +0 -1
  356. package/dist/session/connection.d.ts +0 -135
  357. package/dist/session/connection.d.ts.map +0 -1
  358. package/dist/session/connection.js +0 -215
  359. package/dist/session/connection.js.map +0 -1
  360. package/dist/session/credentials.d.ts +0 -30
  361. package/dist/session/credentials.d.ts.map +0 -1
  362. package/dist/session/credentials.js +0 -63
  363. package/dist/session/credentials.js.map +0 -1
  364. package/dist/session/hosting.d.ts.map +0 -1
  365. package/dist/session/hosting.js.map +0 -1
  366. package/dist/session/index.d.ts +0 -29
  367. package/dist/session/index.d.ts.map +0 -1
  368. package/dist/session/index.js +0 -21
  369. package/dist/session/index.js.map +0 -1
  370. package/dist/session/pairing.d.ts +0 -97
  371. package/dist/session/pairing.d.ts.map +0 -1
  372. package/dist/session/pairing.js +0 -251
  373. package/dist/session/pairing.js.map +0 -1
  374. package/dist/session/password-strength.d.ts +0 -22
  375. package/dist/session/password-strength.d.ts.map +0 -1
  376. package/dist/session/password-strength.js +0 -130
  377. package/dist/session/password-strength.js.map +0 -1
  378. package/dist/session/places.d.ts +0 -71
  379. package/dist/session/places.d.ts.map +0 -1
  380. package/dist/session/places.js +0 -130
  381. package/dist/session/places.js.map +0 -1
  382. package/dist/session/popup.d.ts +0 -13
  383. package/dist/session/popup.d.ts.map +0 -1
  384. package/dist/session/popup.js +0 -23
  385. package/dist/session/popup.js.map +0 -1
  386. package/dist/session/stay-signed-in.d.ts +0 -49
  387. package/dist/session/stay-signed-in.d.ts.map +0 -1
  388. package/dist/session/stay-signed-in.js +0 -141
  389. package/dist/session/stay-signed-in.js.map +0 -1
  390. package/dist/storage/blob/directory.d.ts +0 -14
  391. package/dist/storage/blob/directory.d.ts.map +0 -1
  392. package/dist/storage/blob/directory.js +0 -87
  393. package/dist/storage/blob/directory.js.map +0 -1
  394. package/dist/storage/blob/memory.d.ts +0 -6
  395. package/dist/storage/blob/memory.d.ts.map +0 -1
  396. package/dist/storage/blob/memory.js +0 -20
  397. package/dist/storage/blob/memory.js.map +0 -1
  398. package/dist/storage/blob/s3.d.ts +0 -16
  399. package/dist/storage/blob/s3.d.ts.map +0 -1
  400. package/dist/storage/blob/s3.js +0 -91
  401. package/dist/storage/blob/s3.js.map +0 -1
  402. package/dist/storage/directory-access.d.ts +0 -36
  403. package/dist/storage/directory-access.d.ts.map +0 -1
  404. package/dist/storage/directory-access.js +0 -89
  405. package/dist/storage/directory-access.js.map +0 -1
  406. package/dist/storage/folder-adapter.d.ts +0 -94
  407. package/dist/storage/folder-adapter.d.ts.map +0 -1
  408. package/dist/storage/folder-adapter.js +0 -215
  409. package/dist/storage/folder-adapter.js.map +0 -1
  410. package/dist/storage/folder-reconcile.d.ts +0 -33
  411. package/dist/storage/folder-reconcile.d.ts.map +0 -1
  412. package/dist/storage/folder-reconcile.js.map +0 -1
  413. package/dist/storage/index.d.ts +0 -6
  414. package/dist/storage/index.d.ts.map +0 -1
  415. package/dist/storage/index.js +0 -5
  416. package/dist/storage/index.js.map +0 -1
  417. package/dist/storage/indexeddb-adapter.d.ts +0 -8
  418. package/dist/storage/indexeddb-adapter.d.ts.map +0 -1
  419. package/dist/storage/indexeddb-adapter.js +0 -103
  420. package/dist/storage/indexeddb-adapter.js.map +0 -1
@@ -1,1529 +0,0 @@
1
- /**
2
- * @module session/auth
3
- * Signing in, as one object any UI can draw: the whole flow as a state you
4
- * read and actions you call. The recovery code is the account (the seed,
5
- * written out); a passkey or password wraps the seed for every day; pairing
6
- * hands it to a new device. The seed stays inside this object, and signs only
7
- * the note that lets a session key write.
8
- */
9
- import { isObject } from '../utils/guards.js';
10
- import { createIdentityManager, rootFromSeed } from '../identity/identity-manager.js';
11
- import { accountDataPath, newAccountId, createBrowserAccountStore } from '../identity/account-store.js';
12
- import { createVault } from '../identity/account-vault.js';
13
- import { withWrap, wrapSeedWithDeviceKey, unwrapSeedWithDeviceKey, wrapSeedWithPassphrase, unwrapSeedWithPassphrase, deviceWrapsFor, CLI_PASSPHRASE_LABEL, deriveLocalKey, deriveAccountKey, } from '../identity/account-vault.js';
14
- import { deriveContactKeyBytes, deriveMemberKeyBytes } from '../identity/contact-key.js';
15
- import { createDeviceKey, getDeviceKey, deleteDeviceKey } from '../identity/device-key.js';
16
- import { registerPasskey, authenticatePasskey, hasPlatformAuthenticator, renamePasskey, } from '../identity/webauthn.js';
17
- import { generateSeed, seedToRecoveryCode, recoveryCodeToSeed, isValidRecoveryCode, } from '../identity/recovery-code.js';
18
- import { isFolderStorageAvailable } from '../storage/directory-access.js';
19
- import { base64UrlEncode } from '../utils/encoding.js';
20
- import { startPageNode } from '../node/worker.js';
21
- import { copyAccountData } from '../node/copy.js';
22
- import { describeHost } from './hosting.js';
23
- import { isProtocolError, protocolError } from '../utils/errors.js';
24
- import { deleteBrowserData, forgetPod, inspectPod, listAccounts, pickPod, podToReopen, recallPod, rememberPod, describeStores, storesFor, } from './places.js';
25
- import { createStaySignedIn, defaultStorage, guardedStorage, rememberedSessionKey, } from './stay-signed-in.js';
26
- import { grantTerms, GRANT_VERSION, MAX_GRANT_DAYS, checkKeyProof, requestTerms, } from './connect.js';
27
- import { fromProposal, proposalSpaces, sameAutomation } from '../space/own-automations.js';
28
- import { clearPairingTicket, receiveFromDesktop, offerToPhone as offerPairing, readPairingTicket, } from './pairing.js';
29
- /**
30
- * Which kept connection this is: an app by its origin, and a program
31
- * connected by code or a carrier by its key, since one origin has several.
32
- */
33
- export const connectionKey = (known) => known.via === 'code' || known.access === 'carry' ? known.audience : known.origin;
34
- const isSpaces = (spaces) => Array.isArray(spaces) &&
35
- spaces.every((space) => isObject(space) && typeof space.id === 'string' && typeof space.name === 'string');
36
- /** Where either of two grants to one key let it write */
37
- function widest(a, b) {
38
- if (!a)
39
- return b;
40
- if (a.scope === 'account' || b.scope === 'account')
41
- return { audience: b.audience, scope: 'account', spaces: [] };
42
- const spaces = new Map([...a.spaces, ...b.spaces].map((space) => [space.id, space]));
43
- return { audience: b.audience, scope: 'spaces', spaces: [...spaces.values()] };
44
- }
45
- /** Whether a connection already reaches everywhere a key it replaced could write */
46
- const covers = (connection, key) => connection.scope === 'account' ||
47
- (key.scope === 'spaces' &&
48
- key.spaces.every((space) => connection.spaces.some((has) => has.id === space.id)));
49
- const isRetired = (value) => isObject(value) &&
50
- Object.keys(value).every((field) => field === 'audience' || field === 'scope' || field === 'spaces') &&
51
- typeof value.audience === 'string' &&
52
- (value.scope === 'spaces' || value.scope === 'account') &&
53
- isSpaces(value.spaces);
54
- /** Every field a kept connection may have */
55
- const CONNECTION_FIELDS = new Set([
56
- 'origin',
57
- 'name',
58
- 'audience',
59
- 'access',
60
- 'scope',
61
- 'carrySpace',
62
- 'retired',
63
- 'spaces',
64
- 'grantedAt',
65
- 'expiresAt',
66
- 'via',
67
- 'recordsOnly',
68
- ]);
69
- /** Whether a kept connection has this shape, and nothing else */
70
- function isConnection(value) {
71
- if (!isObject(value) || !Object.keys(value).every((field) => CONNECTION_FIELDS.has(field)))
72
- return false;
73
- const { origin, name, audience, access, scope, carrySpace, spaces, grantedAt, expiresAt, via } = value;
74
- return (typeof origin === 'string' &&
75
- (name === null || typeof name === 'string') &&
76
- typeof audience === 'string' &&
77
- (access === 'read' || access === 'write' || access === 'carry') &&
78
- (scope === 'spaces' || scope === 'account') &&
79
- (carrySpace === undefined || typeof carrySpace === 'string') &&
80
- Array.isArray(spaces) &&
81
- spaces.every((space) => isObject(space) && typeof space.id === 'string' && typeof space.name === 'string') &&
82
- typeof grantedAt === 'string' &&
83
- typeof expiresAt === 'number' &&
84
- (via === undefined || via === 'code') &&
85
- (value.recordsOnly === undefined || value.recordsOnly === true) &&
86
- (value.retired === undefined || (Array.isArray(value.retired) && value.retired.every(isRetired))));
87
- }
88
- /** Files a new account at a place, with no wraps yet: the passkey or password comes after the recovery code. */
89
- async function fileAccount(place, did, name) {
90
- const id = newAccountId();
91
- const summary = {
92
- id,
93
- name,
94
- did,
95
- createdAt: new Date().toISOString(),
96
- dataPath: accountDataPath(id),
97
- };
98
- await place.store.write(summary, createVault({ did, label: name, wraps: [] }));
99
- return summary;
100
- }
101
- /** Turns a thrown value into something worth showing, ignoring a dismissed prompt. */
102
- function describe(error) {
103
- if (error instanceof DOMException && (error.name === 'NotAllowedError' || error.name === 'AbortError')) {
104
- return null; // the person dismissed a passkey or folder prompt
105
- }
106
- if (isProtocolError(error)) {
107
- return { message: error.message, code: error.code, ...(error.hint ? { hint: error.hint } : {}) };
108
- }
109
- return { message: error instanceof Error ? error.message : 'Something went wrong' };
110
- }
111
- const afterStorage = (accounts) => accounts.length > 0 ? 'signIn' : 'welcome';
112
- /**
113
- * The automations an app's proposals become, for the ones the person kept.
114
- * Checked whole before any is written: a proposal naming a space the app
115
- * can't reach refuses them all.
116
- */
117
- function automationsFrom(proposals, kept, context) {
118
- const made = [];
119
- for (const [index, proposal] of proposals.entries()) {
120
- if (kept && !kept.includes(index))
121
- continue;
122
- const spaces = proposalSpaces(proposal, context.reach);
123
- if (!spaces)
124
- throw new Error(`“${proposal.name}” looks at a space it was not given.`);
125
- made.push(fromProposal(proposal, { app: context.app, spaces }));
126
- }
127
- return made;
128
- }
129
- /** Adds each, unless the same origin already has the same one */
130
- async function addAutomations(node, origin, automations) {
131
- if (automations.length === 0)
132
- return [];
133
- const existing = (await node.automations.list()).filter((own) => own.app?.origin === origin);
134
- const added = [];
135
- for (const own of automations) {
136
- const made = existing.find((found) => sameAutomation(found, own)) ?? (await node.automations.add(own));
137
- added.push({ id: made.id, name: made.name });
138
- }
139
- return added;
140
- }
141
- /** How long signing out waits for its revokes to reach the peers here, at most, unless configured: offline, they wait until next time */
142
- const SIGN_OUT_GRACE_MS = 5000;
143
- /** How long `confirm` lets the recovery code be read, or the account offered to a phone */
144
- const CONFIRMED_MS = 5 * 60 * 1000;
145
- /** Creates the sign-in flow for this page. */
146
- export function createMincaAuth(config = {}) {
147
- const rpId = config.rpId ?? globalThis.location?.hostname ?? 'localhost';
148
- const signOutGraceMs = config.signOutGraceMs ?? SIGN_OUT_GRACE_MS;
149
- const appName = config.appName ?? 'Minca';
150
- const prefix = config.storageKey ?? 'minca';
151
- const storage = defaultStorage(config.storage);
152
- const stay = createStaySignedIn(storage, rpId, prefix);
153
- const { get, set, read } = guardedStorage(storage);
154
- /** Proposals being added, in turn */
155
- let subscribing = Promise.resolve();
156
- const browserAccounts = config.browser?.accounts ?? createBrowserAccountStore;
157
- const browserStores = config.browser?.stores ?? ((account) => storesFor(account));
158
- if (config.worker && config.browser?.stores)
159
- throw new Error('A node in a worker opens its own stores: pass worker or browser.stores, not both');
160
- const LAST_ACCOUNT = `${prefix}.last-account`;
161
- /** The host a new account is kept online with, with nothing to choose: the first configured */
162
- const host = config.network?.hosts?.[0] ?? null;
163
- /** Work begun during setup that goes on in the background: the username's claim, the host's handover */
164
- let background = [];
165
- let state = Object.freeze({
166
- stage: 'starting',
167
- place: null,
168
- accounts: [],
169
- selectedId: null,
170
- entry: null,
171
- session: null,
172
- freshCode: null,
173
- setup: null,
174
- busy: false,
175
- error: null,
176
- folderAvailable: isFolderStorageAvailable(),
177
- pairing: readPairingTicket(),
178
- pairingStage: null,
179
- pairingArrival: null,
180
- podChoice: null,
181
- moved: null,
182
- signingOut: false,
183
- podToReopen: null,
184
- username: null,
185
- });
186
- const listeners = new Set();
187
- const update = (patch) => {
188
- state = Object.freeze({ ...state, ...patch });
189
- for (const listener of listeners)
190
- listener(state);
191
- };
192
- /** The seed behind the open session. Never leaves this closure except as the recovery code. */
193
- let seed = null;
194
- /** When the person last proved it is them (`confirm`); nothing that hands out the seed works without it */
195
- let confirmedAt = 0;
196
- /** Which account that proof was for, so it never carries over to another */
197
- let confirmedFor = null;
198
- /** When the open account was last opened with a password, passkey or the recovery code here, and which */
199
- let signedInAt = 0;
200
- let signedInFor = null;
201
- const provedSignIn = (did) => {
202
- signedInAt = Date.now();
203
- signedInFor = did;
204
- };
205
- /**
206
- * Whether a session just landed and is choosing its first way in: only `arrive`
207
- * opens this, so no call can step back into setup to skip `confirm`.
208
- */
209
- let setupOpen = false;
210
- let localKey = null;
211
- let stopFollowingName = null;
212
- let started = null;
213
- const browserPlace = async () => ({
214
- kind: 'browser',
215
- store: await browserAccounts(),
216
- directory: null,
217
- });
218
- const storesOf = (place, account, key) => place.directory
219
- ? storesFor(account, {
220
- directory: place.directory,
221
- localKey: key,
222
- // Given stores of its own, this browser keeps a pod's beside them too.
223
- ...(config.browser
224
- ? { local: config.browser.stores({ ...account, id: `pod-${account.id}` }) }
225
- : {}),
226
- })
227
- : browserStores(account);
228
- // ─── Accounts in a place ───────────────────────────────────────────
229
- async function openEntry(place, id) {
230
- const [summary, vault] = await Promise.all([
231
- listAccounts(place).then((accounts) => accounts.find((account) => account.id === id)),
232
- place.store.read(id),
233
- ]);
234
- if (!summary || !vault)
235
- return null;
236
- // A wrap whose key is missing from this browser cannot be offered, however
237
- // confidently the vault lists it.
238
- const usable = await Promise.all(deviceWrapsFor(vault, rpId).map(async (wrap) => (await getDeviceKey(wrap.deviceKeyId).catch(() => null)) ? wrap : null));
239
- return {
240
- summary,
241
- vault,
242
- shortcuts: usable.filter((wrap) => wrap !== null),
243
- hasPassword: vault.wraps.some((wrap) => wrap.kind === 'passphrase'),
244
- };
245
- }
246
- /** Re-reads the accounts in a place and picks one to expand. */
247
- async function refresh(place) {
248
- const accounts = await listAccounts(place);
249
- const remembered = get(LAST_ACCOUNT);
250
- const chosen = accounts.find((account) => account.id === remembered) ?? accounts[0] ?? null;
251
- update({
252
- place,
253
- accounts,
254
- selectedId: chosen?.id ?? null,
255
- entry: chosen ? await openEntry(place, chosen.id) : null,
256
- });
257
- return accounts;
258
- }
259
- async function refreshEntry() {
260
- if (state.place && state.session)
261
- update({ entry: await openEntry(state.place, state.session.account.id) });
262
- }
263
- // ─── Sessions ──────────────────────────────────────────────────────
264
- /**
265
- * Stops the open session's node. The session stays in the state until
266
- * something replaces it — a restart swaps one session for the next, and
267
- * signing out moves off the signed-in screens in the same change — so a
268
- * screen never sees "ready" with no session.
269
- */
270
- async function stopNode(node = state.session?.node) {
271
- stopFollowingName?.();
272
- stopFollowingName = null;
273
- seed = null;
274
- confirmedAt = 0;
275
- confirmedFor = null;
276
- signedInAt = 0;
277
- signedInFor = null;
278
- setupOpen = false;
279
- localKey = null;
280
- await node?.close();
281
- }
282
- /**
283
- * Why a key can't be given a note here, or null: it must prove it holds
284
- * itself, and be no key this home already uses for something else, since
285
- * disconnecting later revokes it (the node's own, or another connection's).
286
- */
287
- async function audienceProblem(request, origin) {
288
- if (!(await checkKeyProof(request.audience, request.proof, requestTerms(request, origin))))
289
- return 'The app did not show it holds the key it named, for what it asked.';
290
- if (request.audience === state.session?.node.sessionDid)
291
- return 'That key is this home’s own.';
292
- // Which kept connection the request would replace (`connectionKey`).
293
- const asking = request.via === 'code' || request.access === 'carry' ? request.audience : origin;
294
- // One key is one connection: an app's and a carrier's are never the same key, even from one origin.
295
- const elsewhere = auth.connections().some((known) => (known.audience === request.audience &&
296
- (known.origin !== origin ||
297
- known.via !== request.via ||
298
- (known.access === 'carry') !== (request.access === 'carry'))) ||
299
- // A key a connection replaced is revoked when it goes, so it is no other connection's
300
- // either; the connection it replaced may ask with it again.
301
- (connectionKey(known) !== asking &&
302
- (known.retired ?? []).some((key) => key.audience === request.audience)));
303
- return elsewhere ? 'That key is already connected for something else.' : null;
304
- }
305
- /**
306
- * Disconnects the connections `goes` picks: a carrier's carry space goes, a
307
- * key that could write is revoked, and the automations an app proposed go
308
- * with it. With `waitMs`, every revoke is written first, and `delivered`
309
- * settles once a peer has taken them in, or that long has passed: they wait
310
- * together.
311
- */
312
- async function disconnectWhere(goes, waitMs = 0) {
313
- const going = auth.connections().filter(goes);
314
- const node = state.session?.node;
315
- const revoked = [];
316
- for (const connection of going) {
317
- // One that can't be done must not keep the rest from happening.
318
- if (connection.carrySpace && node)
319
- await node.carriers.remove(connection.carrySpace).catch(() => { });
320
- if (node)
321
- revoked.push(revokeConnection(node, connection, waitMs).catch(() => false));
322
- // The automations it proposed go with it. So does any its own key wrote, whichever app that one names.
323
- if (!connection.via && node) {
324
- for (const own of await node.automations.list()) {
325
- const wrote = (await node.automations.versions([own.id])).some((version) => version.author === connection.audience ||
326
- (connection.retired ?? []).some((key) => key.audience === version.author));
327
- // A carrier proposes none: the app's at its origin are the app's, and stay.
328
- const proposed = own.app?.origin === connection.origin && connection.access !== 'carry';
329
- if (proposed || wrote)
330
- await node.automations.remove(own.id).catch(() => { });
331
- }
332
- }
333
- }
334
- writeConnections(auth.connections().filter((known) => !goes(known)));
335
- // A home that closes once delivered must also have taken the removed automations' wakes off its carriers.
336
- const refilled = node && waitMs > 0 ? node.carriers.settled(waitMs) : Promise.resolve(true);
337
- return {
338
- delivered: Promise.all([Promise.all(revoked), refilled]).then(([taken]) => taken.every(Boolean)),
339
- };
340
- }
341
- /**
342
- * Revokes the key a connection was given, where it could write; never this node's own.
343
- * With `waitMs`, until a peer has each revoke or that time has passed (they wait together).
344
- */
345
- async function revokeConnection(node, connection, waitMs = 0) {
346
- // Every key it replaced, each where it was granted, with its own.
347
- const replaced = (connection.retired ?? []).map((key) => revokeWhere(node, key.audience, key.scope, key.spaces, waitMs));
348
- const own = connection.access === 'write'
349
- ? revokeWhere(node, connection.audience, connection.scope, connection.spaces, waitMs)
350
- : Promise.resolve(true);
351
- return (await Promise.all([own, ...replaced])).every(Boolean);
352
- }
353
- /** Revokes one key where a connection let it write; never this node's own */
354
- async function revokeWhere(node, key, scope, granted, waitMs) {
355
- if (key === node.sessionDid)
356
- return true;
357
- // A whole-account app acts as the account, so wrote wherever it does: its own spaces too.
358
- if (scope === 'account')
359
- return node.revokeKey(key, { waitMs });
360
- // Any other wrote only in the spaces it was given. One the account has left has nobody to tell.
361
- const writable = new Set((await node.spaces.list()).filter((space) => space.writable).map((space) => space.id));
362
- const spaces = granted.map((space) => space.id).filter((id) => writable.has(id));
363
- return node.revokeKey(key, { waitMs, spaces });
364
- }
365
- /** Starts the node for an unlocked account. */
366
- async function startSession(place, account, unlocked) {
367
- await stopNode();
368
- const { identity, signer } = await rootFromSeed(unlocked);
369
- const key = await deriveLocalKey(unlocked);
370
- const node = await startPageNode({
371
- signer,
372
- accountKey: await deriveAccountKey(unlocked),
373
- contactKey: await deriveContactKeyBytes(unlocked),
374
- stores: describeStores(account, place.directory ? { directory: place.directory, localKey: key } : undefined),
375
- ...(config.network ? { network: config.network } : {}),
376
- }, config.worker ? { worker: config.worker } : { stores: storesOf(place, account, key) });
377
- seed = unlocked;
378
- localKey = key;
379
- const session = Object.freeze({
380
- account,
381
- did: identity.did,
382
- sessionDid: node.sessionDid,
383
- node,
384
- });
385
- // The account's name follows it: a rename on another device or site
386
- // arrives through the account registry and is taken here too.
387
- const adopt = async () => {
388
- const profile = await node.account.profile().catch(() => null);
389
- const current = state.session;
390
- if (!profile || !current || current.node !== node || profile.name === current.account.name)
391
- return;
392
- await adoptName(profile.name).catch(() => { });
393
- };
394
- stopFollowingName = node.subscribe((event) => {
395
- if (event.type === 'account')
396
- void adopt();
397
- });
398
- void adopt();
399
- return session;
400
- }
401
- /** Records that an account was just used, and starts its session. */
402
- async function begin(place, summary, unlocked) {
403
- const used = { ...summary, lastUsedAt: new Date().toISOString() };
404
- try {
405
- const vault = await place.store.read(summary.id);
406
- if (vault)
407
- await place.store.write(used, vault);
408
- }
409
- catch {
410
- // The order the picker opens in is not worth failing a sign-in over.
411
- }
412
- set(LAST_ACCOUNT, summary.id);
413
- const session = await startSession(place, used, unlocked);
414
- // So a refresh does not ask again — for as long as the setting allows.
415
- await stay.remember(summary.id, place.kind, unlocked).catch(() => { });
416
- return session;
417
- }
418
- /** Where a signed-out tab only waits for the person to choose, so taking up a sign-in interrupts nothing */
419
- const IDLE_STAGES = new Set(['welcome', 'existing', 'signIn']);
420
- /** The session a take-up started: it goes when the sign-in it took up does */
421
- let takenUp = null;
422
- /** Which kept sign-in the record holds: its account and the device key that opens it */
423
- const keptNow = () => {
424
- const kept = read(rememberedSessionKey(prefix));
425
- return kept ? `${String(kept.accountId)} ${String(kept.wrap?.deviceKeyId)}` : null;
426
- };
427
- /** Whether `start()` has finished: before that, it is the one signing in */
428
- let settledStart = false;
429
- /** The take-up under way; sign-ins wait for it, so two never start a node at once */
430
- let takingUp = null;
431
- /** Sign-ins under way through `run` */
432
- let running = 0;
433
- /**
434
- * Signs in with the sign-in another tab of this browser kept, while this one
435
- * is signed out and only waiting. A phone pairs in the tab its camera
436
- * opened, while the app that sent it to sign in waits here; a refresh would
437
- * do the same.
438
- */
439
- function takeUpKept() {
440
- const place = state.place;
441
- if (takingUp || running > 0 || !settledStart || state.session || state.busy || !place)
442
- return;
443
- if (!IDLE_STAGES.has(state.stage))
444
- return;
445
- takingUp = (async () => {
446
- update({ busy: true });
447
- let started = null;
448
- try {
449
- const before = keptNow();
450
- const kept = await stay.recall(place.kind).catch(() => null);
451
- if (!kept)
452
- return;
453
- // Choosing an account here is the person's answer: another one signed in elsewhere is not.
454
- if (state.stage === 'signIn' && state.selectedId && state.selectedId !== kept.accountId)
455
- return;
456
- const summary = (await listAccounts(place)).find((account) => account.id === kept.accountId);
457
- if (!summary)
458
- return;
459
- // The record is already kept; remembering again would replace the key other tabs read.
460
- set(LAST_ACCOUNT, summary.id);
461
- started = await startSession(place, summary, kept.seed);
462
- // Signed out, or into another account, in another tab meanwhile: that wins.
463
- if (!stay.until() || keptNow() !== before)
464
- throw new Error('signed out');
465
- takenUp = started;
466
- update({ session: started, stage: 'ready', error: null });
467
- await refresh(place);
468
- }
469
- catch {
470
- // Signing in here by hand still works.
471
- if (started && state.session !== started)
472
- await stopNode(started.node).catch(() => { });
473
- }
474
- finally {
475
- update({ busy: false });
476
- }
477
- })().finally(() => {
478
- takingUp = null;
479
- });
480
- }
481
- /** Runs something that may fail, showing the failure; true when it worked. */
482
- async function run(work) {
483
- running++;
484
- try {
485
- while (takingUp)
486
- await takingUp;
487
- update({ busy: true, error: null });
488
- await work();
489
- return true;
490
- }
491
- catch (error) {
492
- update({ error: describe(error) });
493
- return false;
494
- }
495
- finally {
496
- running--;
497
- update({ busy: false });
498
- }
499
- }
500
- /** Whether an account can be opened here without its recovery code. */
501
- const hasEverydayWay = (entry) => entry !== null && (entry.shortcuts.length > 0 || entry.hasPassword);
502
- /**
503
- * Lands a new session: in, or on through the setup screens.
504
- *
505
- * With no reason to set up, or a passkey or password already here, that is
506
- * the app. Otherwise a new account's recovery code is shown first, then a way
507
- * in is chosen. A restored account skips the code, since the person just
508
- * typed it, and so does a paired device, which was never shown one.
509
- */
510
- /**
511
- * Claims a new account's username while setup goes on: a few seconds of
512
- * work, which the recovery code and the password screens cover.
513
- */
514
- function claimInBackground(session, username) {
515
- update({ username: { username, status: 'claiming' } });
516
- const settle = (claim) => {
517
- // The same account: setting a way in meanwhile starts a new session for it.
518
- if (state.session?.did === session.did)
519
- update({ username: claim });
520
- };
521
- background.push(session.node.inbox.claim(username).then(() => settle({ username, status: 'claimed' }), (error) => settle({
522
- username,
523
- status: 'failed',
524
- error: error instanceof Error ? error.message : String(error),
525
- })));
526
- }
527
- async function arrive(session, setup) {
528
- update({ podToReopen: null });
529
- const place = state.place;
530
- const entry = place ? await openEntry(place, session.account.id) : null;
531
- const landed = {
532
- session,
533
- entry,
534
- selectedId: session.account.id,
535
- accounts: place ? await listAccounts(place) : state.accounts,
536
- };
537
- if (setup === null || hasEverydayWay(entry)) {
538
- update({ ...landed, stage: 'ready', setup: null, freshCode: null });
539
- }
540
- else if (setup === 'paired' || setup === 'restored') {
541
- setupOpen = true;
542
- update({ ...landed, stage: 'unlock', setup, freshCode: null });
543
- }
544
- else {
545
- setupOpen = true;
546
- update({ ...landed, stage: 'recovery', setup, freshCode: seed ? seedToRecoveryCode(seed) : null });
547
- }
548
- }
549
- /**
550
- * Keeps a new account online with `url`: only a host that keeps accounts
551
- * with nothing paid, so nobody is signed up to pay for what they never
552
- * chose. A host that doesn't answer is tried once more a moment later;
553
- * after that the account stays in this browser, kept online from the
554
- * account page whenever the person likes.
555
- */
556
- async function keepOnline(session, url) {
557
- // The same account, not the same session: setting a way in starts a new one.
558
- for (let tries = 0; tries < 2 && state.session?.did === session.did; tries++) {
559
- try {
560
- const description = await describeHost(url);
561
- if (!description.free && !description.limits)
562
- return;
563
- const now = state.session;
564
- if (now?.did !== session.did)
565
- return;
566
- await now.node.hosting.use(url);
567
- return;
568
- }
569
- catch {
570
- await new Promise((resolve) => setTimeout(resolve, 3000));
571
- }
572
- }
573
- }
574
- /**
575
- * After a way in is set up: a new account is kept online with the host, if
576
- * there is one, with nothing to choose (stopped on the account page); with
577
- * none, it is offered a pod where it could use one. Then in.
578
- */
579
- function afterUnlock() {
580
- setupOpen = false;
581
- const session = state.session;
582
- if (state.setup === 'new' && host && session) {
583
- // Handed over in the background: the account goes in at once.
584
- background.push(keepOnline(session, host));
585
- update({ stage: 'ready', setup: null });
586
- return;
587
- }
588
- const offerPod = config.offerPod !== false &&
589
- state.setup === 'new' &&
590
- state.folderAvailable &&
591
- state.place?.kind === 'browser';
592
- update(offerPod ? { stage: 'pod' } : { stage: 'ready', setup: null });
593
- }
594
- /** Runs a way in. One that took the recovery code may lead on to setting up an everyday one. */
595
- // Every way in says whether it proved someone is there, so a new one can't count by omission.
596
- const enter = (open) => run(async () => {
597
- const { session, byCode, proved } = await open();
598
- // Opening it took the password, a passkey or the recovery code: proof enough to give an app access, for a few minutes.
599
- if (proved)
600
- provedSignIn(session.did);
601
- await arrive(session, byCode ? 'restored' : null);
602
- }).then(() => undefined);
603
- /**
604
- * Opens an account from its recovery code, filing it here if this place has
605
- * not seen it.
606
- * @param expected The account the person meant, when they picked one
607
- */
608
- async function openWithCode(code, expected) {
609
- const place = state.place;
610
- if (!place)
611
- throw new Error('No place to sign in to yet.');
612
- if (!isValidRecoveryCode(code)) {
613
- throw protocolError('VAULT_UNLOCK_FAILED', 'That is not a recovery code.', 'A recovery code is 26 letters and digits, usually in groups of four. A password only opens the account where it was ' +
614
- 'set up — on a new device, use the recovery code, or add this device from one that is signed in.');
615
- }
616
- const unlocked = recoveryCodeToSeed(code);
617
- const identity = await createIdentityManager().fromSeed(unlocked);
618
- if (expected && identity.did !== expected.did) {
619
- throw protocolError('VAULT_UNLOCK_FAILED', `That recovery code opens a different account, not ${expected.name}.`, `Check it is the code you kept for ${expected.name}, or restore the account it belongs to instead.`);
620
- }
621
- const known = (await listAccounts(place)).find((account) => account.did === identity.did);
622
- if (known)
623
- return begin(place, known, unlocked);
624
- // New to this place — a new device, or a new home. File it, so there is
625
- // somewhere to keep the passkey or password set up next.
626
- return begin(place, await fileAccount(place, identity.did, expected?.name ?? 'My account'), unlocked);
627
- }
628
- /** The account the person picked, if any */
629
- const selectedAccount = () => state.accounts.find((account) => account.id === state.selectedId) ?? null;
630
- // ─── Passkeys ──────────────────────────────────────────────────────
631
- /**
632
- * Makes a passkey to gate this device's key. Nothing is read out of a
633
- * passkey: the ceremony proves someone is present, and the key that opens
634
- * the account is in this site's storage, so every provider works. Steers to
635
- * this device's own authenticator when it has one, since the key it gates
636
- * never leaves this browser.
637
- */
638
- async function passkeyGate(label) {
639
- const platform = await hasPlatformAuthenticator();
640
- return registerPasskey({
641
- rpId,
642
- rpName: appName,
643
- userName: label,
644
- ...(platform ? { hints: ['client-device'], attachment: 'platform' } : {}),
645
- });
646
- }
647
- /** Rewrites the open account's vault. */
648
- async function updateVault(make) {
649
- const { place, session } = state;
650
- if (!place || !session)
651
- throw new Error('Not signed in.');
652
- const current = await place.store.read(session.account.id);
653
- if (!current)
654
- throw new Error('That account is no longer here.');
655
- await place.store.write(session.account, await make(current));
656
- }
657
- /** Takes a name for the open account here: the label it is filed under, and its passkey's label. */
658
- async function adoptName(name) {
659
- const { place, session } = state;
660
- if (!place || !session)
661
- throw new Error('Not signed in.');
662
- const renamed = { ...session.account, name: name.trim() || session.account.name };
663
- const vault = await place.store.read(session.account.id);
664
- if (!vault)
665
- throw new Error('That account is no longer here.');
666
- await place.store.write(renamed, { ...vault, label: renamed.name });
667
- // Recent browsers let a site relabel its passkey; older ones ignore it.
668
- for (const wrap of deviceWrapsFor(vault, rpId)) {
669
- if (wrap.userHandle)
670
- await renamePasskey({ rpId, userHandle: wrap.userHandle, name: renamed.name }).catch(() => false);
671
- }
672
- update({ session: Object.freeze({ ...session, account: renamed }), accounts: await listAccounts(place) });
673
- return renamed;
674
- }
675
- /** Whether the person proved it is them (`confirm`) in the last few minutes */
676
- const isConfirmed = () => seed !== null &&
677
- confirmedFor !== null &&
678
- state.session?.did === confirmedFor &&
679
- Date.now() - confirmedAt < CONFIRMED_MS;
680
- /**
681
- * Whether an app may be given access now: the person proved it is them, or
682
- * opened the account with a password, passkey or the recovery code, in the
683
- * last few minutes. A sign-in kept from before is neither.
684
- */
685
- const mayGrant = () => isConfirmed() ||
686
- (seed !== null &&
687
- signedInFor !== null &&
688
- state.session?.did === signedInFor &&
689
- Date.now() - signedInAt < CONFIRMED_MS);
690
- /**
691
- * Changes to the open account's shortcuts, then re-reads them. During setup,
692
- * moves the flow on. Outside setup they need `confirm` first: a new password
693
- * would otherwise both open the gate and lock the owner out.
694
- */
695
- const changeShortcut = (apply) => run(async () => {
696
- if (!seed)
697
- throw new Error('Not signed in.');
698
- if (!setupOpen && !isConfirmed())
699
- throw new Error('Confirm it is you first.');
700
- await apply(seed);
701
- await refreshEntry();
702
- if (state.stage === 'unlock' && hasEverydayWay(state.entry))
703
- afterUnlock();
704
- });
705
- /**
706
- * Connected apps are remembered per account, on this device; none when what
707
- * is kept can't be read. One kept in another shape, such as one from before
708
- * a field changed meaning, is dropped rather than read in part: its app or
709
- * program connects again.
710
- */
711
- function readConnections(account) {
712
- const connections = read(`${prefix}.connections:${account}`);
713
- return Array.isArray(connections) ? connections.filter(isConnection) : [];
714
- }
715
- function writeConnections(connections) {
716
- const account = state.session?.account.id;
717
- if (account)
718
- set(`${prefix}.connections:${account}`, JSON.stringify(connections));
719
- update({});
720
- }
721
- /** An account a pairing brought, held while a signed-in device asks whether to take it */
722
- let heldHandover = null;
723
- /** Counts pairings begun and dismissed: one that ends after a dismiss is dropped */
724
- let pairingRun = 0;
725
- /** Stops the pairing under way, so a dismissed one leaves the room rather than waiting it out */
726
- let stopPairing = null;
727
- /** Signs in with what a pairing brought, then joins its spaces */
728
- async function takeHandover(handover) {
729
- const onStage = (stage) => update({ pairingStage: stage });
730
- // Starting the node takes a moment; the code on screen is done with.
731
- onStage({ kind: 'sending' });
732
- const opened = await run(async () => {
733
- await arrive(await openWithCode(seedToRecoveryCode(handover.seed), null), 'paired');
734
- });
735
- const session = state.session;
736
- if (!opened || !session)
737
- return;
738
- let joined = 0;
739
- for (const [index, invite] of handover.spaces.entries()) {
740
- onStage({ kind: 'joining', joined: index, total: handover.spaces.length });
741
- if (await session.node.spaces.join(invite).then(() => true, () => false))
742
- joined++;
743
- }
744
- onStage({ kind: 'received', spaces: joined });
745
- }
746
- // ─── The flow ──────────────────────────────────────────────────────
747
- const auth = {
748
- getState: () => state,
749
- subscribe(listener) {
750
- listeners.add(listener);
751
- return () => listeners.delete(listener);
752
- },
753
- start() {
754
- started ??= (async () => {
755
- // Only `localStorage` tells other tabs, and only on a page.
756
- globalThis.addEventListener?.('storage', (event) => {
757
- if (event.key !== rememberedSessionKey(prefix))
758
- return;
759
- if (event.newValue)
760
- takeUpKept();
761
- // The sign-in this tab took up is gone: signed out elsewhere, so here too.
762
- else if (takenUp && state.session === takenUp)
763
- void auth.signOut();
764
- });
765
- try {
766
- // Asks nothing of the person: only whether what was granted before is still live.
767
- const pod = await recallPod(false).catch(() => null);
768
- const place = pod ?? (await browserPlace());
769
- const accounts = await refresh(place);
770
- // Remembered, but the browser wants a click first: say so, rather than start as if new.
771
- if (!pod)
772
- update({ podToReopen: await podToReopen().catch(() => null) });
773
- if (accounts.length > 0) {
774
- const kept = await stay.recall(place.kind).catch(() => null);
775
- const summary = kept && accounts.find((account) => account.id === kept.accountId);
776
- if (kept && summary) {
777
- const session = await begin(place, summary, kept.seed);
778
- // A pairing link still asks first: it would put another account here (spec 01 §15.3).
779
- update({ session, stage: state.pairing ? 'pair' : 'ready' });
780
- return;
781
- }
782
- }
783
- if (state.pairing) {
784
- update({ stage: 'pair' });
785
- return;
786
- }
787
- // Where the data lives is not asked up front: someone new has
788
- // nothing anywhere, and someone who does finds their pod under
789
- // "I already have an account".
790
- update({ stage: afterStorage(accounts) });
791
- }
792
- catch (error) {
793
- update({ error: describe(error), stage: 'welcome' });
794
- }
795
- finally {
796
- settledStart = true;
797
- }
798
- })();
799
- return started;
800
- },
801
- async reopenPod() {
802
- await run(async () => {
803
- // Signed in meanwhile (another tab's sign-in taken up, say): moving pods asks first, through choosePod.
804
- if (state.session) {
805
- update({ podToReopen: null });
806
- return;
807
- }
808
- const pod = await recallPod(true);
809
- if (!pod)
810
- throw new Error('The browser did not open the folder. Try again, or choose it with “Open a folder”.');
811
- update({ podToReopen: null });
812
- const accounts = await refresh(pod);
813
- // Kept signed in there: straight in, as a page load with the permission would have been.
814
- const kept = await stay.recall(pod.kind).catch(() => null);
815
- const summary = kept && accounts.find((account) => account.id === kept.accountId);
816
- if (kept && summary) {
817
- const session = await begin(pod, summary, kept.seed);
818
- // A pairing link still asks first, as at start (spec 01 §15.3).
819
- update({ session, stage: state.pairing ? 'pair' : 'ready' });
820
- return;
821
- }
822
- update({ stage: state.pairing ? 'pair' : afterStorage(accounts) });
823
- });
824
- },
825
- async choosePod() {
826
- const picked = await run(async () => {
827
- const pod = await pickPod();
828
- const { session, place } = state;
829
- // Signed in: look before leaping. The picker needed the click, but
830
- // switching waits for an answer.
831
- if (session && place) {
832
- const contents = await inspectPod(pod, place, session.account.did);
833
- if (contents.same)
834
- throw new Error('That is the pod you are already using.');
835
- update({ podChoice: { pod, contents, from: place } });
836
- return;
837
- }
838
- await rememberPod(pod);
839
- update({ stage: afterStorage(await refresh(pod)) });
840
- });
841
- // Setting up a new account there is nothing to decide: no pod has it
842
- // yet, so it moves, and the browser copy it leaves is only a shell.
843
- if (picked && state.stage === 'pod' && state.podChoice) {
844
- await auth.confirmPod('combine');
845
- if (state.podChoice)
846
- return;
847
- await auth.forgetBrowserCopy();
848
- update({ stage: 'ready', setup: null });
849
- }
850
- },
851
- async useBrowser() {
852
- await run(async () => {
853
- if (state.place?.kind === 'folder')
854
- await forgetPod();
855
- const place = state.place?.kind === 'browser' ? state.place : await browserPlace();
856
- update({ stage: afterStorage(await refresh(place)) });
857
- });
858
- },
859
- async select(accountId) {
860
- update({ selectedId: accountId, error: null });
861
- if (state.place)
862
- update({ entry: await openEntry(state.place, accountId) });
863
- },
864
- signInWithCode(code) {
865
- return enter(async () => ({
866
- session: await openWithCode(code, selectedAccount()),
867
- byCode: true,
868
- proved: true,
869
- }));
870
- },
871
- signInWithPassword(password) {
872
- return enter(async () => {
873
- const { place, entry } = state;
874
- // The account's password, and the CLI's passphrase if a pod has one: either opens it.
875
- const wraps = (entry?.vault.wraps ?? []).filter((candidate) => candidate.kind === 'passphrase');
876
- // Before passwords, the recovery code was this site's login, and a
877
- // password manager still fills it here. It opens the account either way.
878
- const code = isValidRecoveryCode(password) ? password : null;
879
- let failed = null;
880
- for (const wrap of place && entry ? wraps : []) {
881
- let unlocked = null;
882
- try {
883
- unlocked = await unwrapSeedWithPassphrase(wrap, password, entry.vault.did);
884
- }
885
- catch (error) {
886
- failed = error instanceof Error ? error : new Error(String(error));
887
- }
888
- if (unlocked)
889
- return { session: await begin(place, entry.summary, unlocked), byCode: false, proved: true };
890
- }
891
- if (failed && !code)
892
- throw failed;
893
- if (code)
894
- return {
895
- session: await openWithCode(code, entry?.summary ?? selectedAccount()),
896
- byCode: true,
897
- proved: true,
898
- };
899
- throw protocolError('VAULT_UNLOCK_FAILED', 'No password is set for this account here.', 'Use your recovery code, and you can set one up afterwards.');
900
- });
901
- },
902
- signInWithPasskey() {
903
- return enter(async () => {
904
- const { place, entry } = state;
905
- const target = entry?.shortcuts[entry.shortcuts.length - 1];
906
- if (!place || !entry || !target) {
907
- throw protocolError('VAULT_UNLOCK_FAILED', 'No passkey on this device can open that account.', 'Use your recovery code, and you can set one up afterwards.');
908
- }
909
- // The gate first, so the key is never reached for without someone present.
910
- if (target.credentialId)
911
- await authenticatePasskey(target.credentialId, { rpId });
912
- const key = await getDeviceKey(target.deviceKeyId);
913
- if (!key) {
914
- throw protocolError('VAULT_UNLOCK_FAILED', 'The key for that passkey is not in this browser any more.', 'Clearing site data removes it. Your recovery code still works, and a new passkey can be set up afterwards.');
915
- }
916
- return {
917
- session: await begin(place, entry.summary, await unwrapSeedWithDeviceKey(target, key, entry.vault.did)),
918
- byCode: false,
919
- // A wrap with no passkey behind it skipped the check that someone is there.
920
- proved: Boolean(target.credentialId),
921
- };
922
- });
923
- },
924
- startCreating() {
925
- update({ error: null, stage: 'create' });
926
- },
927
- showSignIn() {
928
- update({ error: null, stage: 'signIn' });
929
- // Back from "another account", which let go of the one picked: pick it again.
930
- if (!state.selectedId && state.place)
931
- void refresh(state.place).catch(() => { });
932
- },
933
- showWelcome() {
934
- update({ error: null, stage: 'welcome' });
935
- },
936
- showExisting() {
937
- // Any account, not the one the list had picked: a recovery code from
938
- // here opens whichever account it belongs to.
939
- update({ error: null, stage: 'existing', selectedId: null, entry: null });
940
- },
941
- showRestore() {
942
- update({ error: null, stage: 'restore' });
943
- },
944
- usernames: config.usernames?.trim().toLowerCase() || null,
945
- async createAccount(name, options = {}) {
946
- await run(async () => {
947
- const place = state.place;
948
- if (!place)
949
- throw new Error('No place to keep the account yet.');
950
- const unlocked = generateSeed();
951
- const identity = await createIdentityManager().fromSeed(unlocked);
952
- const summary = await fileAccount(place, identity.did, name.trim());
953
- // Kept only in this browser, the account is only as safe as the
954
- // browser's willingness to keep it. Asking costs nothing.
955
- if (place.kind === 'browser')
956
- await globalThis.navigator?.storage?.persist?.().catch(() => false);
957
- const session = await begin(place, summary, unlocked);
958
- // The name travels with the account, so the next site it is opened on
959
- // shows it. Only at creation and on rename — never on a plain start,
960
- // where a device that has not synced yet would publish a stale name.
961
- await session.node.account.setName(summary.name).catch(() => { });
962
- // Made just now, by whoever is here: an app asking next needs no more proof.
963
- provedSignIn(session.did);
964
- if (options.username)
965
- claimInBackground(session, options.username);
966
- await arrive(session, 'new');
967
- });
968
- },
969
- codeSaved() {
970
- if (!state.session || state.stage !== 'recovery')
971
- return;
972
- update({ freshCode: null, stage: 'unlock' });
973
- },
974
- finishSetup() {
975
- if (!state.session || state.stage !== 'pod')
976
- return;
977
- setupOpen = false;
978
- update({ stage: 'ready', setup: null, error: null });
979
- },
980
- async settled() {
981
- await Promise.allSettled(background);
982
- },
983
- async acceptPairing() {
984
- const ticket = state.pairing;
985
- if (!ticket)
986
- return;
987
- if (!state.place)
988
- update({ place: await browserPlace() });
989
- const onStage = (stage) => update({ pairingStage: stage });
990
- const mine = ++pairingRun;
991
- const stop = new AbortController();
992
- stopPairing = stop;
993
- const got = { handover: null };
994
- // The account arrives over the exchange, after the person has compared
995
- // the codes; the link only says where to meet.
996
- await run(async () => {
997
- try {
998
- got.handover = await receiveFromDesktop(ticket, onStage, {
999
- transport: config.pairingTransport,
1000
- signal: stop.signal,
1001
- });
1002
- }
1003
- catch (error) {
1004
- // Stopped by "Not now": nothing went wrong to tell the person about.
1005
- if (!stop.signal.aborted)
1006
- throw error;
1007
- }
1008
- });
1009
- const arrived = got.handover;
1010
- // "Not now" while the code showed: the computer may still have sent it, but it is not taken.
1011
- if (mine !== pairingRun) {
1012
- arrived?.seed.fill(0);
1013
- return;
1014
- }
1015
- clearPairingTicket();
1016
- update({ pairing: null });
1017
- if (!arrived)
1018
- return;
1019
- // Signed in to another account, the device asks first: add the one that
1020
- // arrived, or switch to it if it is already here (spec 01 §15.3).
1021
- const signedIn = state.session;
1022
- if (signedIn) {
1023
- const { did } = await createIdentityManager().fromSeed(arrived.seed);
1024
- // "Not now" while the account was being looked at: let it go.
1025
- if (mine !== pairingRun) {
1026
- arrived.seed.fill(0);
1027
- return;
1028
- }
1029
- if (did !== signedIn.did) {
1030
- heldHandover = arrived;
1031
- update({
1032
- pairingArrival: { did, account: state.accounts.find((account) => account.did === did) ?? null },
1033
- });
1034
- return;
1035
- }
1036
- }
1037
- await takeHandover(arrived);
1038
- },
1039
- async answerPairing(take) {
1040
- const arrived = heldHandover;
1041
- heldHandover = null;
1042
- update({ pairingArrival: null });
1043
- if (!arrived)
1044
- return;
1045
- if (take)
1046
- return takeHandover(arrived);
1047
- arrived.seed.fill(0);
1048
- update({ pairingStage: null, stage: state.session ? 'ready' : afterStorage(state.accounts) });
1049
- },
1050
- dismissPairing() {
1051
- pairingRun++;
1052
- stopPairing?.abort();
1053
- stopPairing = null;
1054
- clearPairingTicket();
1055
- heldHandover?.seed.fill(0);
1056
- heldHandover = null;
1057
- update({
1058
- pairing: null,
1059
- pairingStage: null,
1060
- pairingArrival: null,
1061
- stage: state.session ? 'ready' : afterStorage(state.accounts),
1062
- });
1063
- },
1064
- clearError() {
1065
- update({ error: null });
1066
- },
1067
- async rename(name) {
1068
- const session = state.session;
1069
- if (!session)
1070
- return false;
1071
- return run(async () => {
1072
- const renamed = await adoptName(name);
1073
- // Every other device and site that opens the account follows.
1074
- await session.node.account.setName(renamed.name).catch(() => { });
1075
- });
1076
- },
1077
- addPasskey: () => changeShortcut(async (unlocked) => {
1078
- const session = state.session;
1079
- const place = state.place;
1080
- const { credentialId, userHandle } = await passkeyGate(session.account.name);
1081
- const deviceKey = await createDeviceKey();
1082
- const wrap = await wrapSeedWithDeviceKey(unlocked, deviceKey, {
1083
- rpId,
1084
- credentialId,
1085
- userHandle,
1086
- label: rpId,
1087
- });
1088
- // Replacing an older passkey leaves its key behind, opening nothing.
1089
- const previous = deviceWrapsFor((await place.store.read(session.account.id)), rpId);
1090
- await updateVault(async (vault) => withWrap(vault, wrap));
1091
- for (const stale of previous)
1092
- await deleteDeviceKey(stale.deviceKeyId);
1093
- }),
1094
- setPassword: (password) => changeShortcut(async (unlocked) => {
1095
- // Any password will do; the form warns about weak ones (`passwordStrength`).
1096
- if (!password)
1097
- throw new Error('Choose a password.');
1098
- const wrap = await wrapSeedWithPassphrase(unlocked, password, 'Password');
1099
- // One password: the new one replaces the last. The CLI's passphrase is its own, and stays.
1100
- await updateVault(async (vault) => ({
1101
- ...vault,
1102
- wraps: [
1103
- ...vault.wraps.filter((kept) => kept.kind !== 'passphrase' || kept.label === CLI_PASSPHRASE_LABEL),
1104
- wrap,
1105
- ],
1106
- }));
1107
- }),
1108
- removeShortcut: (kind) => changeShortcut(async () => {
1109
- const session = state.session;
1110
- if (kind === 'passkey') {
1111
- const vault = await state.place.store.read(session.account.id);
1112
- for (const wrap of vault ? deviceWrapsFor(vault, rpId) : [])
1113
- await deleteDeviceKey(wrap.deviceKeyId);
1114
- }
1115
- // Removing every shortcut leaves the account openable by its recovery
1116
- // code alone. Another site's passkey is not this one's to remove.
1117
- await updateVault(async (vault) => ({
1118
- ...vault,
1119
- wraps: vault.wraps.filter((wrap) => kind === 'passkey' ? !(wrap.kind === 'device' && wrap.rpId === rpId) : wrap.kind !== 'passphrase'),
1120
- }));
1121
- }),
1122
- async confirmPod(how) {
1123
- const choice = state.podChoice;
1124
- const session = state.session;
1125
- if (!choice || !session || !seed || !localKey)
1126
- return;
1127
- const unlocked = seed;
1128
- const key = localKey;
1129
- await run(async () => {
1130
- const { pod, contents, from } = choice;
1131
- if (!pod.directory)
1132
- throw new Error('That is not a folder.');
1133
- const land = async (summary, moved) => {
1134
- await rememberPod(pod);
1135
- const started = await begin(pod, summary, unlocked);
1136
- update({ session: started, place: pod, accounts: await listAccounts(pod), podChoice: null, moved });
1137
- };
1138
- // Switch: use the pod's own copy and bring nothing; what was only here stays here.
1139
- if (how === 'switch' && contents.account)
1140
- return land(contents.account, null);
1141
- // Combine: every record is signed and named by its content, and deletes
1142
- // are records too, so two copies merge by keeping everything from both.
1143
- const existing = contents.account;
1144
- const id = existing?.id ?? newAccountId();
1145
- const summary = existing
1146
- ? { ...existing, lastUsedAt: new Date().toISOString() }
1147
- : { ...session.account, id, dataPath: accountDataPath(id), lastUsedAt: new Date().toISOString() };
1148
- // Ways of unlocking: the pod's, plus any from here it lacks.
1149
- const here = await from.store.read(session.account.id);
1150
- let vault = (existing ? await pod.store.read(existing.id) : null) ??
1151
- createVault({ did: session.account.did, label: session.account.name, wraps: [] });
1152
- for (const wrap of here?.wraps ?? []) {
1153
- if (!vault.wraps.some((kept) => kept.id === wrap.id))
1154
- vault = withWrap(vault, wrap);
1155
- }
1156
- await pod.store.write(summary, vault);
1157
- const copied = await copyAccountData({
1158
- from: storesOf(from, session.account, key),
1159
- to: storesOf(pod, summary, key),
1160
- did: session.account.did,
1161
- accountKey: await deriveAccountKey(unlocked),
1162
- });
1163
- await land(summary, {
1164
- merged: existing !== null,
1165
- spacesAdded: copied.spacesAdded,
1166
- recordsAdded: copied.recordsAdded,
1167
- from: from.kind === 'folder' ? (from.directory?.name ?? 'your old pod') : null,
1168
- });
1169
- });
1170
- },
1171
- cancelPod() {
1172
- update({ podChoice: null, error: null });
1173
- },
1174
- async forgetBrowserCopy() {
1175
- const session = state.session;
1176
- if (!session)
1177
- return;
1178
- await run(async () => {
1179
- const browser = await browserAccounts();
1180
- const copy = (await browser.list()).find((entry) => entry.did === session.account.did);
1181
- if (copy) {
1182
- await browser.remove(copy.id);
1183
- await deleteBrowserData(copy);
1184
- }
1185
- update({ moved: null });
1186
- });
1187
- },
1188
- async removeAccount() {
1189
- const { session, place } = state;
1190
- if (!session || place?.kind !== 'browser')
1191
- return false;
1192
- if (!isConfirmed()) {
1193
- update({ error: describe(new Error('Confirm it is you first.')) });
1194
- return false;
1195
- }
1196
- // Only this home can disconnect them, and only while it keeps them: removing it first
1197
- // would leave their keys writing for the account for good.
1198
- if (auth.connections().some((known) => known.access !== 'carry')) {
1199
- update({ error: describe(new Error('Disconnect your apps first.')) });
1200
- return false;
1201
- }
1202
- const account = session.account;
1203
- await auth.signOut();
1204
- // Its passkey keys stay, as after a move into a pod: a pod's vault may name the same one.
1205
- return run(async () => {
1206
- await place.store.remove(account.id);
1207
- await deleteBrowserData(account);
1208
- set(`${prefix}.connections:${account.id}`, null);
1209
- if (get(LAST_ACCOUNT) === account.id)
1210
- set(LAST_ACCOUNT, null);
1211
- update({ stage: afterStorage(await refresh(place)) });
1212
- });
1213
- },
1214
- dismissMoved() {
1215
- update({ moved: null });
1216
- },
1217
- confirm(proof) {
1218
- return run(async () => {
1219
- const { entry, place } = state;
1220
- const unlocked = seed;
1221
- if (!unlocked || !entry || !place)
1222
- throw new Error('Sign in first.');
1223
- const same = (other) => other.length === unlocked.length && other.every((byte, at) => byte === unlocked[at]);
1224
- const wrong = (message) => protocolError('VAULT_UNLOCK_FAILED', message);
1225
- if ('code' in proof) {
1226
- if (!isValidRecoveryCode(proof.code) || !same(recoveryCodeToSeed(proof.code)))
1227
- throw wrong('That is not this account’s recovery code.');
1228
- }
1229
- else if ('password' in proof) {
1230
- const wraps = entry.vault.wraps.filter((candidate) => candidate.kind === 'passphrase');
1231
- let opened = false;
1232
- for (const wrap of wraps) {
1233
- const tried = await unwrapSeedWithPassphrase(wrap, proof.password, entry.vault.did).catch(() => null);
1234
- if (tried && same(tried))
1235
- opened = true;
1236
- }
1237
- if (!opened)
1238
- throw wrong('That is not the password.');
1239
- }
1240
- else {
1241
- const target = entry.shortcuts[entry.shortcuts.length - 1];
1242
- // The passkey's own check that someone is there: a fingerprint, a face or a PIN.
1243
- // A wrap with no passkey behind it would skip that check, so it is no proof.
1244
- if (!target?.credentialId)
1245
- throw wrong('No passkey on this device opens this account.');
1246
- await authenticatePasskey(target.credentialId, { rpId });
1247
- const key = await getDeviceKey(target.deviceKeyId);
1248
- if (!key || !same(await unwrapSeedWithDeviceKey(target, key, entry.vault.did)))
1249
- throw wrong('That passkey does not open this account here.');
1250
- }
1251
- confirmedAt = Date.now();
1252
- confirmedFor = state.session?.did ?? null;
1253
- });
1254
- },
1255
- isConfirmed,
1256
- mayGrant,
1257
- recoveryCode() {
1258
- return seed && isConfirmed() ? seedToRecoveryCode(seed) : null;
1259
- },
1260
- offerToPhone(onStage) {
1261
- const session = state.session;
1262
- if (!session || !seed)
1263
- return Promise.reject(new Error('Sign in first.'));
1264
- // It sends the whole account: the same proof as reading the recovery code.
1265
- if (!isConfirmed())
1266
- return Promise.reject(new Error('Confirm it is you first.'));
1267
- const location = globalThis.location;
1268
- return offerPairing({
1269
- seed,
1270
- invites: async () => Promise.all((await session.node.spaces.list()).map((space) => session.node.spaces.invite(space.id))),
1271
- relays: config.network?.relays ?? [],
1272
- link: config.pairingLink ?? (location ? `${location.origin}${location.pathname}` : ''),
1273
- transport: config.pairingTransport,
1274
- }, onStage);
1275
- },
1276
- async grant(choice) {
1277
- const session = state.session;
1278
- if (!session || !seed)
1279
- throw new Error('Sign in first.');
1280
- const { node } = session;
1281
- const { request } = choice;
1282
- if (request.access === 'carry')
1283
- throw new Error('A carrier is given passes, not a note — use grantCarry.');
1284
- const access = request.access;
1285
- const recordsOnly = request.recordsOnly === true;
1286
- const byCode = request.via === 'code';
1287
- if (byCode && (!recordsOnly || access !== 'write'))
1288
- throw new Error('A program connected by code is given records only.');
1289
- const problem = await audienceProblem(request, choice.origin);
1290
- if (problem)
1291
- throw new Error(problem);
1292
- if (recordsOnly && request.create?.length)
1293
- throw new Error('A key given records only works in spaces that exist — none are made for it.');
1294
- if (recordsOnly && request.contacts)
1295
- throw new Error('A key given records only is not given your contacts.');
1296
- const whole = request.scope === 'account';
1297
- // Like any sign-in elsewhere: the person proves it is them before an app gets anything,
1298
- // not only a home that stayed signed in on a computer anyone may walk up to.
1299
- if (!mayGrant())
1300
- throw new Error('Confirm it is you first.');
1301
- const created = [];
1302
- for (const params of request.create ?? [])
1303
- created.push(await node.spaces.create(params));
1304
- // With the whole account the app derives the contacts space itself; otherwise it is one more space it is given.
1305
- const contactsSpace = request.contacts && !whole ? await node.contacts.space() : null;
1306
- const ids = [
1307
- ...new Set([
1308
- ...choice.spaceIds,
1309
- ...created.map((space) => space.id),
1310
- ...(contactsSpace ? [contactsSpace] : []),
1311
- ]),
1312
- ];
1313
- const spaces = [];
1314
- for (const id of ids) {
1315
- const space = await node.spaces.get(id);
1316
- if (!space)
1317
- throw new Error(`No space ${id} in this account.`);
1318
- // Read-only: what lets the app write is the note, under this account's own role — never a secret of the space's.
1319
- const invite = await node.spaces.invite(id, { write: false });
1320
- // Only for the spaces granted: each opens that space's next key and nothing else.
1321
- const memberKey = !whole && space.visibility === 'private'
1322
- ? base64UrlEncode(await deriveMemberKeyBytes(await deriveAccountKey(seed), id))
1323
- : null;
1324
- spaces.push({ id, name: space.name, invite, ...(memberKey ? { memberKey } : {}) });
1325
- }
1326
- const days = Math.min(Math.max(choice.days ?? request.days ?? 7, 1 / 24), MAX_GRANT_DAYS);
1327
- const expiresAt = Math.floor(Date.now() / 1000) + Math.round(days * 24 * 3600);
1328
- const { signer } = await rootFromSeed(seed);
1329
- const note = await signer.delegate({
1330
- audience: request.audience,
1331
- ...grantTerms(recordsOnly && access === 'write' ? 'records' : access, whole ? 'all' : ids),
1332
- expiration: expiresAt,
1333
- });
1334
- const connection = {
1335
- origin: choice.origin,
1336
- name: request.name?.slice(0, 80) ?? null,
1337
- audience: request.audience,
1338
- access,
1339
- scope: whole ? 'account' : 'spaces',
1340
- spaces: spaces.map(({ id, name }) => ({ id, name })),
1341
- grantedAt: new Date().toISOString(),
1342
- expiresAt,
1343
- ...(byCode ? { via: 'code' } : {}),
1344
- ...(recordsOnly ? { recordsOnly: true } : {}),
1345
- };
1346
- // Connecting again replaces the old note. A program connected by code is kept by its key: connecting one replaces only that one.
1347
- // A carrier at the same origin is not the app, and stays (§2.10).
1348
- const replaced = (known) => connectionKey(known) === connectionKey(connection);
1349
- // A key it replaces is not revoked: this home has seen little of what it wrote, and a
1350
- // revoke would withdraw the rest. The app forgets it; disconnecting revokes it too.
1351
- // Only a key that could write needs revoking; one is kept once, however often it was
1352
- // replaced, with everywhere it was ever granted. The same key asking again for less keeps
1353
- // its earlier reach here, so disconnecting still revokes it there.
1354
- const retired = new Map();
1355
- const keep = (key) => retired.set(key.audience, widest(retired.get(key.audience), key));
1356
- for (const known of auth.connections().filter(replaced)) {
1357
- for (const key of known.retired ?? [])
1358
- keep(key);
1359
- if (known.access === 'write')
1360
- keep({ audience: known.audience, scope: known.scope, spaces: known.spaces });
1361
- }
1362
- const mine = retired.get(connection.audience);
1363
- if (mine && connection.access === 'write' && covers(connection, mine))
1364
- retired.delete(connection.audience);
1365
- writeConnections([
1366
- ...(retired.size > 0 ? [{ ...connection, retired: [...retired.values()] }] : [connection]),
1367
- ...auth.connections().filter((known) => !replaced(known)),
1368
- ]);
1369
- return {
1370
- v: GRANT_VERSION,
1371
- did: session.did,
1372
- name: session.account.name,
1373
- note,
1374
- access,
1375
- scope: whole ? 'account' : 'spaces',
1376
- spaces,
1377
- ...(whole ? { accountKey: base64UrlEncode(await deriveAccountKey(seed)) } : {}),
1378
- // Never with records only: the contact key opens knocks, in your inbox and in shared spaces.
1379
- ...(!recordsOnly && (whole || request.contacts)
1380
- ? { contactKey: base64UrlEncode(await deriveContactKeyBytes(seed)) }
1381
- : {}),
1382
- ...(contactsSpace ? { contactsSpace } : {}),
1383
- ...(config.network?.relays?.length ? { relays: [...config.network.relays] } : {}),
1384
- expiresAt,
1385
- };
1386
- },
1387
- async propose({ origin, request, kept }) {
1388
- const session = state.session;
1389
- if (!session)
1390
- throw new Error('Sign in first.');
1391
- const { node } = session;
1392
- // Only the app itself: a program connected through it by code isn't what the person is looking at, and a carrier can't read what it would notify about.
1393
- const connection = auth.connections().find((known) => connectionKey(known) === origin);
1394
- if (!connection)
1395
- throw new Error('Only an app connected to your account here may suggest what to notify you about. Connect it first.');
1396
- // What it may reach: every space for a whole-account app, else the spaces it was given, less the contacts space.
1397
- let reach = 'all';
1398
- if (connection.scope === 'spaces') {
1399
- const contactsSpace = connection.spaces.length ? await node.contacts.space().catch(() => null) : null;
1400
- reach = connection.spaces.map((space) => space.id).filter((id) => id !== contactsSpace);
1401
- if (reach.length === 0)
1402
- throw new Error('It was given no spaces to notify you about.');
1403
- }
1404
- const app = {
1405
- origin,
1406
- ...(connection.name
1407
- ? { name: connection.name }
1408
- : request.name
1409
- ? { name: request.name.slice(0, 80) }
1410
- : {}),
1411
- };
1412
- const made = automationsFrom(request.automations, kept, { app, reach });
1413
- // One at a time: two popups answered together would each find the other's not there yet.
1414
- const adding = subscribing.then(() => addAutomations(node, origin, made));
1415
- subscribing = adding.catch(() => { });
1416
- const automations = await adding;
1417
- // An app with the account key reads them from its own node: handed over now, they are there on its next load.
1418
- if (reach !== 'all' || automations.length === 0)
1419
- return { v: 2, kind: 'proposed', automations };
1420
- const versions = await node.automations.versions(automations.map((own) => own.id));
1421
- return { v: 2, kind: 'proposed', automations, versions };
1422
- },
1423
- async grantCarry({ origin, request }) {
1424
- const session = state.session;
1425
- if (!session || !seed)
1426
- throw new Error('Sign in first.');
1427
- const { node } = session;
1428
- const problem = await audienceProblem(request, origin);
1429
- if (problem)
1430
- throw new Error(problem);
1431
- if (!mayGrant())
1432
- throw new Error('Confirm it is you first.');
1433
- // One carrier per origin: a new key there replaces the old one. The same key again keeps its
1434
- // carry space (`carriers.add`). An app at the same origin is not it, and stays (§2.10).
1435
- const carrierHere = (known) => known.origin === origin && known.access === 'carry';
1436
- const previous = auth.connections().find(carrierHere);
1437
- if (previous?.carrySpace && previous.audience !== request.audience)
1438
- await node.carriers.remove(previous.carrySpace).catch(() => { });
1439
- const name = request.name?.slice(0, 80) || 'Browser extension';
1440
- const carry = await node.carriers.add({ did: request.audience, name });
1441
- const connection = {
1442
- origin,
1443
- name,
1444
- audience: request.audience,
1445
- access: 'carry',
1446
- scope: 'account',
1447
- spaces: [],
1448
- grantedAt: new Date().toISOString(),
1449
- // Carrying has no end date: a pass reads nothing, and the carrier writes nothing.
1450
- expiresAt: 0,
1451
- carrySpace: carry.space,
1452
- };
1453
- writeConnections([connection, ...auth.connections().filter((known) => !carrierHere(known))]);
1454
- const place = state.place;
1455
- return {
1456
- v: 1,
1457
- kind: 'carry',
1458
- did: session.did,
1459
- name: session.account.name,
1460
- carry,
1461
- pod: place?.kind === 'folder'
1462
- ? { dataPath: session.account.dataPath, folder: place.directory?.name ?? 'your pod' }
1463
- : null,
1464
- ...(config.network?.relays?.length ? { relays: [...config.network.relays] } : {}),
1465
- };
1466
- },
1467
- connections() {
1468
- const account = state.session?.account.id;
1469
- if (!account)
1470
- return [];
1471
- return readConnections(account);
1472
- },
1473
- connectedElsewhere(origin) {
1474
- const current = state.session?.account.id;
1475
- return state.accounts
1476
- .filter((account) => account.id !== current)
1477
- .filter((account) => readConnections(account.id).some((connection) => connection.origin === origin && connection.access === 'carry'))
1478
- .map((account) => ({ id: account.id, name: account.name }));
1479
- },
1480
- async disconnect(origin, options = {}) {
1481
- // A carrier at the same origin is not the app, and goes only by its own key (§2.10).
1482
- const { delivered } = await disconnectWhere((known) => options.audience !== undefined
1483
- ? known.audience === options.audience
1484
- : known.origin === origin && known.access !== 'carry', options.waitMs ?? 0);
1485
- return delivered;
1486
- },
1487
- staySignedIn: {
1488
- choice: () => stay.choice(),
1489
- setChoice: (choice) => stay.setChoice(choice),
1490
- until: () => stay.until(),
1491
- },
1492
- async signOut(options = {}) {
1493
- // Not ready from now on: nothing may be granted from this account while it goes.
1494
- update({ stage: 'starting', signingOut: true });
1495
- await stay.forget();
1496
- const leaving = state.session?.node;
1497
- // Every app and the programs connected through it; carriers stay, holding nothing that writes.
1498
- // The node stops next and sends nothing after, so it waits for a peer to take each revoke in.
1499
- const disconnected = options.disconnect
1500
- ? await disconnectWhere((known) => known.access !== 'carry', signOutGraceMs).catch(() => null)
1501
- : null;
1502
- // Before going: revoke this device's session key, so a key left behind here can't
1503
- // write for the account again. It knows what it wrote, so the cutoff loses nothing.
1504
- // Its revokes and the apps' wait together, up to the one grace.
1505
- await Promise.all([
1506
- disconnected?.delivered,
1507
- leaving?.revokeSelf({ waitMs: signOutGraceMs }).catch(() => { }),
1508
- // Whatever changed for the carriers just now is written for them before the node stops.
1509
- leaving?.carriers.settled(signOutGraceMs).catch(() => false),
1510
- ]);
1511
- update({
1512
- stage: 'starting',
1513
- session: null,
1514
- entry: null,
1515
- freshCode: null,
1516
- setup: null,
1517
- podChoice: null,
1518
- moved: null,
1519
- username: null,
1520
- });
1521
- background = [];
1522
- await stopNode(leaving).catch(() => { });
1523
- const place = state.place;
1524
- update({ stage: place ? afterStorage(await refresh(place)) : 'welcome', signingOut: false });
1525
- },
1526
- };
1527
- return auth;
1528
- }
1529
- //# sourceMappingURL=auth.js.map