@kayjs/auth 0.0.0-stage → 1.104.1

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 (407) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +78 -2
  3. package/llms/admin-and-organizations.md +70 -0
  4. package/llms/admin-pages.md +30 -0
  5. package/llms/grouped-methods.md +106 -0
  6. package/llms/hardening-and-testing.md +108 -0
  7. package/llms/oauth-passkeys-two-factor.md +111 -0
  8. package/llms/oauth-providers.md +28 -0
  9. package/llms/oauth-server-and-tokens.md +76 -0
  10. package/llms/organization-pages.md +20 -0
  11. package/llms/passwords-and-mails.md +129 -0
  12. package/llms/sessions-and-guards.md +51 -0
  13. package/llms/setup.md +122 -0
  14. package/llms/signed-in-components.md +59 -0
  15. package/llms.txt +28 -0
  16. package/package.json +85 -4
  17. package/src/access.ts +31 -0
  18. package/src/account.ts +198 -0
  19. package/src/add.ts +70 -0
  20. package/src/address.ts +51 -0
  21. package/src/admin.ts +361 -0
  22. package/src/auditWording.ts +153 -0
  23. package/src/auth.ts +219 -0
  24. package/src/authorize/clients.ts +160 -0
  25. package/src/authorize/grants.ts +44 -0
  26. package/src/authorize/metadata.ts +72 -0
  27. package/src/authorize/register.ts +38 -0
  28. package/src/authorize/reply.ts +9 -0
  29. package/src/authorize/request.ts +253 -0
  30. package/src/authorize/resource.ts +34 -0
  31. package/src/authorize/revoke.ts +36 -0
  32. package/src/authorize/routes.ts +87 -0
  33. package/src/authorize/token.ts +213 -0
  34. package/src/authorize/uris.ts +76 -0
  35. package/src/bearer.ts +208 -0
  36. package/src/bearerHeader.ts +11 -0
  37. package/src/breached.ts +47 -0
  38. package/src/browser.ts +59 -0
  39. package/src/captcha.ts +196 -0
  40. package/src/cbor.ts +129 -0
  41. package/src/components/deletion-banner.kay +20 -0
  42. package/src/components/impersonation-banner.kay +21 -0
  43. package/src/components/signed-in.kay +8 -0
  44. package/src/components/signed-out.kay +6 -0
  45. package/src/components/user-menu.kay +21 -0
  46. package/src/context.ts +5 -0
  47. package/src/core.ts +308 -0
  48. package/src/createUserCommand.ts +217 -0
  49. package/src/decide.ts +45 -0
  50. package/src/deletion.ts +80 -0
  51. package/src/devTool.ts +104 -0
  52. package/src/device.ts +37 -0
  53. package/src/email.ts +594 -0
  54. package/src/erase.ts +237 -0
  55. package/src/events.ts +297 -0
  56. package/src/export.ts +101 -0
  57. package/src/failure.ts +63 -0
  58. package/src/forwardAuth.ts +55 -0
  59. package/src/forwardRoutes.ts +68 -0
  60. package/src/gate.ts +104 -0
  61. package/src/guard.ts +22 -0
  62. package/src/guards.ts +72 -0
  63. package/src/guesses.ts +99 -0
  64. package/src/index.ts +46 -0
  65. package/src/keys.ts +51 -0
  66. package/src/limits.ts +182 -0
  67. package/src/load.ts +18 -0
  68. package/src/locale.ts +15 -0
  69. package/src/log.ts +4 -0
  70. package/src/mail.ts +225 -0
  71. package/src/memoryStore.ts +599 -0
  72. package/src/messages/fr.ts +357 -0
  73. package/src/methods/account.ts +80 -0
  74. package/src/methods/admin.ts +63 -0
  75. package/src/methods/audit.ts +15 -0
  76. package/src/methods/email.ts +39 -0
  77. package/src/methods/magicLink.ts +32 -0
  78. package/src/methods/oauth.ts +35 -0
  79. package/src/methods/oauthServer.ts +31 -0
  80. package/src/methods/organizations.ts +96 -0
  81. package/src/methods/passkeys.ts +61 -0
  82. package/src/methods/password.ts +53 -0
  83. package/src/methods/sessions.ts +18 -0
  84. package/src/methods/tokens.ts +24 -0
  85. package/src/methods/twoFactor.ts +62 -0
  86. package/src/oauth/client.ts +324 -0
  87. package/src/oauth/flow.ts +350 -0
  88. package/src/oauth/index.ts +5 -0
  89. package/src/oauth/pkce.ts +20 -0
  90. package/src/oauth/providers.ts +490 -0
  91. package/src/oauth/refresher.ts +177 -0
  92. package/src/oauth/timeout.ts +2 -0
  93. package/src/oauth/types.ts +78 -0
  94. package/src/oauthTest.ts +112 -0
  95. package/src/organizations.ts +675 -0
  96. package/src/organizationsCore.ts +60 -0
  97. package/src/own.ts +313 -0
  98. package/src/pages/components/captcha.kay +16 -0
  99. package/src/pages/components/frame.kay +11 -0
  100. package/src/pages/components/message.kay +8 -0
  101. package/src/pages/components/panel.kay +12 -0
  102. package/src/pages/components/passkey-add.kay +48 -0
  103. package/src/pages/components/passkey-sign-in.kay +34 -0
  104. package/src/pages/components/passkey-two-factor.kay +33 -0
  105. package/src/pages/components/proof.kay +15 -0
  106. package/src/pages/components/provider-buttons.kay +25 -0
  107. package/src/pages/components/recovery-codes.kay +13 -0
  108. package/src/pages/components/separator.kay +4 -0
  109. package/src/pages/english.ts +82 -0
  110. package/src/pages/forms.ts +185 -0
  111. package/src/pages/index.ts +361 -0
  112. package/src/pages/organizationPage.ts +12 -0
  113. package/src/pages/routes/account/_guard.ts +15 -0
  114. package/src/pages/routes/account/_layout.kay +37 -0
  115. package/src/pages/routes/account/clients.kay +33 -0
  116. package/src/pages/routes/account/connections.kay +57 -0
  117. package/src/pages/routes/account/data.kay +106 -0
  118. package/src/pages/routes/account/index.kay +109 -0
  119. package/src/pages/routes/account/organizations/[org].kay +188 -0
  120. package/src/pages/routes/account/organizations/_guard.ts +8 -0
  121. package/src/pages/routes/account/organizations/index.kay +86 -0
  122. package/src/pages/routes/account/security.kay +164 -0
  123. package/src/pages/routes/account/sessions.kay +51 -0
  124. package/src/pages/routes/account/tokens.kay +84 -0
  125. package/src/pages/routes/admin/_layout.kay +43 -0
  126. package/src/pages/routes/admin/audit.kay +43 -0
  127. package/src/pages/routes/admin/index.kay +60 -0
  128. package/src/pages/routes/admin/users/[id].kay +181 -0
  129. package/src/pages/routes/confirm-email.kay +39 -0
  130. package/src/pages/routes/invitation.kay +104 -0
  131. package/src/pages/routes/magic-link.kay +42 -0
  132. package/src/pages/routes/oauth/authorize.kay +80 -0
  133. package/src/pages/routes/register.kay +83 -0
  134. package/src/pages/routes/reset-password.kay +73 -0
  135. package/src/pages/routes/sign-in.kay +128 -0
  136. package/src/pages/routes/two-factor.kay +61 -0
  137. package/src/pages/routes/verify-email.kay +83 -0
  138. package/src/passkeys.ts +373 -0
  139. package/src/password.ts +316 -0
  140. package/src/payloads.ts +22 -0
  141. package/src/pg.ts +705 -0
  142. package/src/profile.ts +43 -0
  143. package/src/proof.ts +110 -0
  144. package/src/prune.ts +123 -0
  145. package/src/rates.ts +82 -0
  146. package/src/request.ts +712 -0
  147. package/src/requiredTwoFactor.ts +71 -0
  148. package/src/requirement.ts +23 -0
  149. package/src/roles.ts +18 -0
  150. package/src/routes.ts +202 -0
  151. package/src/rules-check.ts +37 -0
  152. package/src/rules.ts +108 -0
  153. package/src/securityNotice.ts +45 -0
  154. package/src/sessions.ts +184 -0
  155. package/src/setup.ts +417 -0
  156. package/src/signInOptions.ts +9 -0
  157. package/src/state.ts +34 -0
  158. package/src/store.ts +410 -0
  159. package/src/storeHelpers.ts +23 -0
  160. package/src/test.ts +46 -0
  161. package/src/testCookies.ts +9 -0
  162. package/src/testHelpers.ts +58 -0
  163. package/src/testing.ts +113 -0
  164. package/src/text.ts +6 -0
  165. package/src/totp.ts +120 -0
  166. package/src/twoFactor.ts +200 -0
  167. package/src/types.ts +23 -0
  168. package/src/userData.ts +47 -0
  169. package/src/viewer-layout/_layout.kay +11 -0
  170. package/src/viewer.ts +116 -0
  171. package/src/wayIn.ts +40 -0
  172. package/src/webauthn.ts +375 -0
  173. package/src/wsAuth.ts +53 -0
  174. package/types/access.d.ts +12 -0
  175. package/types/access.d.ts.map +1 -0
  176. package/types/account.d.ts +32 -0
  177. package/types/account.d.ts.map +1 -0
  178. package/types/add.d.ts +29 -0
  179. package/types/add.d.ts.map +1 -0
  180. package/types/address.d.ts +2 -0
  181. package/types/address.d.ts.map +1 -0
  182. package/types/admin.d.ts +84 -0
  183. package/types/admin.d.ts.map +1 -0
  184. package/types/auditWording.d.ts +9 -0
  185. package/types/auditWording.d.ts.map +1 -0
  186. package/types/auth.d.ts +3475 -0
  187. package/types/auth.d.ts.map +1 -0
  188. package/types/authorize/clients.d.ts +15 -0
  189. package/types/authorize/clients.d.ts.map +1 -0
  190. package/types/authorize/grants.d.ts +15 -0
  191. package/types/authorize/grants.d.ts.map +1 -0
  192. package/types/authorize/metadata.d.ts +20 -0
  193. package/types/authorize/metadata.d.ts.map +1 -0
  194. package/types/authorize/register.d.ts +4 -0
  195. package/types/authorize/register.d.ts.map +1 -0
  196. package/types/authorize/reply.d.ts +6 -0
  197. package/types/authorize/reply.d.ts.map +1 -0
  198. package/types/authorize/request.d.ts +48 -0
  199. package/types/authorize/request.d.ts.map +1 -0
  200. package/types/authorize/resource.d.ts +4 -0
  201. package/types/authorize/resource.d.ts.map +1 -0
  202. package/types/authorize/revoke.d.ts +4 -0
  203. package/types/authorize/revoke.d.ts.map +1 -0
  204. package/types/authorize/routes.d.ts +5 -0
  205. package/types/authorize/routes.d.ts.map +1 -0
  206. package/types/authorize/token.d.ts +7 -0
  207. package/types/authorize/token.d.ts.map +1 -0
  208. package/types/authorize/uris.d.ts +5 -0
  209. package/types/authorize/uris.d.ts.map +1 -0
  210. package/types/bearer.d.ts +45 -0
  211. package/types/bearer.d.ts.map +1 -0
  212. package/types/bearerHeader.d.ts +3 -0
  213. package/types/bearerHeader.d.ts.map +1 -0
  214. package/types/breached.d.ts +5 -0
  215. package/types/breached.d.ts.map +1 -0
  216. package/types/browser.d.ts +11 -0
  217. package/types/browser.d.ts.map +1 -0
  218. package/types/captcha.d.ts +42 -0
  219. package/types/captcha.d.ts.map +1 -0
  220. package/types/cbor.d.ts +4 -0
  221. package/types/cbor.d.ts.map +1 -0
  222. package/types/context.d.ts +3 -0
  223. package/types/context.d.ts.map +1 -0
  224. package/types/core.d.ts +180 -0
  225. package/types/core.d.ts.map +1 -0
  226. package/types/createUserCommand.d.ts +11 -0
  227. package/types/createUserCommand.d.ts.map +1 -0
  228. package/types/decide.d.ts +12 -0
  229. package/types/decide.d.ts.map +1 -0
  230. package/types/deletion.d.ts +17 -0
  231. package/types/deletion.d.ts.map +1 -0
  232. package/types/devTool.d.ts +3 -0
  233. package/types/devTool.d.ts.map +1 -0
  234. package/types/device.d.ts +7 -0
  235. package/types/device.d.ts.map +1 -0
  236. package/types/email.d.ts +73 -0
  237. package/types/email.d.ts.map +1 -0
  238. package/types/erase.d.ts +31 -0
  239. package/types/erase.d.ts.map +1 -0
  240. package/types/events.d.ts +139 -0
  241. package/types/events.d.ts.map +1 -0
  242. package/types/export.d.ts +54 -0
  243. package/types/export.d.ts.map +1 -0
  244. package/types/failure.d.ts +19 -0
  245. package/types/failure.d.ts.map +1 -0
  246. package/types/forwardAuth.d.ts +12 -0
  247. package/types/forwardAuth.d.ts.map +1 -0
  248. package/types/forwardRoutes.d.ts +11 -0
  249. package/types/forwardRoutes.d.ts.map +1 -0
  250. package/types/gate.d.ts +31 -0
  251. package/types/gate.d.ts.map +1 -0
  252. package/types/guard.d.ts +10 -0
  253. package/types/guard.d.ts.map +1 -0
  254. package/types/guards.d.ts +37 -0
  255. package/types/guards.d.ts.map +1 -0
  256. package/types/guesses.d.ts +18 -0
  257. package/types/guesses.d.ts.map +1 -0
  258. package/types/index.d.ts +47 -0
  259. package/types/index.d.ts.map +1 -0
  260. package/types/keys.d.ts +11 -0
  261. package/types/keys.d.ts.map +1 -0
  262. package/types/limits.d.ts +133 -0
  263. package/types/limits.d.ts.map +1 -0
  264. package/types/load.d.ts +18 -0
  265. package/types/load.d.ts.map +1 -0
  266. package/types/locale.d.ts +4 -0
  267. package/types/locale.d.ts.map +1 -0
  268. package/types/log.d.ts +2 -0
  269. package/types/log.d.ts.map +1 -0
  270. package/types/mail.d.ts +51 -0
  271. package/types/mail.d.ts.map +1 -0
  272. package/types/memoryStore.d.ts +3 -0
  273. package/types/memoryStore.d.ts.map +1 -0
  274. package/types/messages/fr.d.ts +409 -0
  275. package/types/messages/fr.d.ts.map +1 -0
  276. package/types/methods/account.d.ts +24 -0
  277. package/types/methods/account.d.ts.map +1 -0
  278. package/types/methods/admin.d.ts +30 -0
  279. package/types/methods/admin.d.ts.map +1 -0
  280. package/types/methods/audit.d.ts +11 -0
  281. package/types/methods/audit.d.ts.map +1 -0
  282. package/types/methods/email.d.ts +14 -0
  283. package/types/methods/email.d.ts.map +1 -0
  284. package/types/methods/magicLink.d.ts +12 -0
  285. package/types/methods/magicLink.d.ts.map +1 -0
  286. package/types/methods/oauth.d.ts +16 -0
  287. package/types/methods/oauth.d.ts.map +1 -0
  288. package/types/methods/oauthServer.d.ts +13 -0
  289. package/types/methods/oauthServer.d.ts.map +1 -0
  290. package/types/methods/organizations.d.ts +30 -0
  291. package/types/methods/organizations.d.ts.map +1 -0
  292. package/types/methods/passkeys.d.ts +19 -0
  293. package/types/methods/passkeys.d.ts.map +1 -0
  294. package/types/methods/password.d.ts +17 -0
  295. package/types/methods/password.d.ts.map +1 -0
  296. package/types/methods/sessions.d.ts +9 -0
  297. package/types/methods/sessions.d.ts.map +1 -0
  298. package/types/methods/tokens.d.ts +11 -0
  299. package/types/methods/tokens.d.ts.map +1 -0
  300. package/types/methods/twoFactor.d.ts +20 -0
  301. package/types/methods/twoFactor.d.ts.map +1 -0
  302. package/types/oauth/client.d.ts +39 -0
  303. package/types/oauth/client.d.ts.map +1 -0
  304. package/types/oauth/flow.d.ts +38 -0
  305. package/types/oauth/flow.d.ts.map +1 -0
  306. package/types/oauth/index.d.ts +6 -0
  307. package/types/oauth/index.d.ts.map +1 -0
  308. package/types/oauth/pkce.d.ts +10 -0
  309. package/types/oauth/pkce.d.ts.map +1 -0
  310. package/types/oauth/providers.d.ts +100 -0
  311. package/types/oauth/providers.d.ts.map +1 -0
  312. package/types/oauth/refresher.d.ts +55 -0
  313. package/types/oauth/refresher.d.ts.map +1 -0
  314. package/types/oauth/timeout.d.ts +2 -0
  315. package/types/oauth/timeout.d.ts.map +1 -0
  316. package/types/oauth/types.d.ts +75 -0
  317. package/types/oauth/types.d.ts.map +1 -0
  318. package/types/oauthTest.d.ts +23 -0
  319. package/types/oauthTest.d.ts.map +1 -0
  320. package/types/organizations.d.ts +111 -0
  321. package/types/organizations.d.ts.map +1 -0
  322. package/types/organizationsCore.d.ts +29 -0
  323. package/types/organizationsCore.d.ts.map +1 -0
  324. package/types/own.d.ts +55 -0
  325. package/types/own.d.ts.map +1 -0
  326. package/types/pages/english.d.ts +80 -0
  327. package/types/pages/english.d.ts.map +1 -0
  328. package/types/pages/forms.d.ts +204 -0
  329. package/types/pages/forms.d.ts.map +1 -0
  330. package/types/pages/index.d.ts +166 -0
  331. package/types/pages/index.d.ts.map +1 -0
  332. package/types/pages/organizationPage.d.ts +7 -0
  333. package/types/pages/organizationPage.d.ts.map +1 -0
  334. package/types/pages/routes/account/_guard.d.ts +3 -0
  335. package/types/pages/routes/account/_guard.d.ts.map +1 -0
  336. package/types/pages/routes/account/organizations/_guard.d.ts +3 -0
  337. package/types/pages/routes/account/organizations/_guard.d.ts.map +1 -0
  338. package/types/passkeys.d.ts +61 -0
  339. package/types/passkeys.d.ts.map +1 -0
  340. package/types/password.d.ts +49 -0
  341. package/types/password.d.ts.map +1 -0
  342. package/types/payloads.d.ts +4 -0
  343. package/types/payloads.d.ts.map +1 -0
  344. package/types/pg.d.ts +303 -0
  345. package/types/pg.d.ts.map +1 -0
  346. package/types/profile.d.ts +11 -0
  347. package/types/profile.d.ts.map +1 -0
  348. package/types/proof.d.ts +33 -0
  349. package/types/proof.d.ts.map +1 -0
  350. package/types/prune.d.ts +5 -0
  351. package/types/prune.d.ts.map +1 -0
  352. package/types/rates.d.ts +15 -0
  353. package/types/rates.d.ts.map +1 -0
  354. package/types/request.d.ts +119 -0
  355. package/types/request.d.ts.map +1 -0
  356. package/types/requiredTwoFactor.d.ts +16 -0
  357. package/types/requiredTwoFactor.d.ts.map +1 -0
  358. package/types/requirement.d.ts +4 -0
  359. package/types/requirement.d.ts.map +1 -0
  360. package/types/roles.d.ts +9 -0
  361. package/types/roles.d.ts.map +1 -0
  362. package/types/routes.d.ts +31 -0
  363. package/types/routes.d.ts.map +1 -0
  364. package/types/rules-check.d.ts +3 -0
  365. package/types/rules-check.d.ts.map +1 -0
  366. package/types/rules.d.ts +38 -0
  367. package/types/rules.d.ts.map +1 -0
  368. package/types/securityNotice.d.ts +7 -0
  369. package/types/securityNotice.d.ts.map +1 -0
  370. package/types/sessions.d.ts +32 -0
  371. package/types/sessions.d.ts.map +1 -0
  372. package/types/setup.d.ts +18 -0
  373. package/types/setup.d.ts.map +1 -0
  374. package/types/signInOptions.d.ts +6 -0
  375. package/types/signInOptions.d.ts.map +1 -0
  376. package/types/state.d.ts +25 -0
  377. package/types/state.d.ts.map +1 -0
  378. package/types/store.d.ts +295 -0
  379. package/types/store.d.ts.map +1 -0
  380. package/types/storeHelpers.d.ts +4 -0
  381. package/types/storeHelpers.d.ts.map +1 -0
  382. package/types/test.d.ts +21 -0
  383. package/types/test.d.ts.map +1 -0
  384. package/types/testCookies.d.ts +3 -0
  385. package/types/testCookies.d.ts.map +1 -0
  386. package/types/testHelpers.d.ts +34 -0
  387. package/types/testHelpers.d.ts.map +1 -0
  388. package/types/testing.d.ts +12 -0
  389. package/types/testing.d.ts.map +1 -0
  390. package/types/text.d.ts +2 -0
  391. package/types/text.d.ts.map +1 -0
  392. package/types/totp.d.ts +12 -0
  393. package/types/totp.d.ts.map +1 -0
  394. package/types/twoFactor.d.ts +41 -0
  395. package/types/twoFactor.d.ts.map +1 -0
  396. package/types/types.d.ts +17 -0
  397. package/types/types.d.ts.map +1 -0
  398. package/types/userData.d.ts +9 -0
  399. package/types/userData.d.ts.map +1 -0
  400. package/types/viewer.d.ts +23 -0
  401. package/types/viewer.d.ts.map +1 -0
  402. package/types/wayIn.d.ts +12 -0
  403. package/types/wayIn.d.ts.map +1 -0
  404. package/types/webauthn.d.ts +111 -0
  405. package/types/webauthn.d.ts.map +1 -0
  406. package/types/wsAuth.d.ts +14 -0
  407. package/types/wsAuth.d.ts.map +1 -0
@@ -0,0 +1,675 @@
1
+ import type { Core } from './core'
2
+ import type { AuthFailed } from './failure'
3
+ import type { OrganizationsCore } from './organizationsCore'
4
+ import type { RequestState } from './state'
5
+ import type { AuthStore, InvitationRecord, MaybePromise, MemberRecord, OrganizationRecord, UserRecord } from './store'
6
+ import { configError } from 'kay/library'
7
+ import { publicUser } from './core'
8
+ import { impersonatorOf, report } from './events'
9
+ import { failed } from './failure'
10
+ import { spend, typedKey } from './limits'
11
+ import { log } from './log'
12
+ import { writing } from './mail'
13
+ import { emailProblem, normalizeEmail } from './rules'
14
+ import { organizationsById, usersById } from './storeHelpers'
15
+
16
+ const NAME_MAX_LENGTH = 100
17
+ // Control characters, line and paragraph separators, and the marks that turn text around.
18
+ const UNPRINTABLE = /[\p{Cc}\p{Zl}\p{Zp}\u061C\u200E\u200F\u202A-\u202E\u2066-\u2069]/u
19
+ const SLUG = /^[a-z0-9]+(?:-[a-z0-9]+)*$/
20
+ const SLUG_MAX_LENGTH = 64
21
+
22
+ export interface Organization {
23
+ id: string
24
+ name: string
25
+ slug: string | null
26
+ createdAt: Date
27
+ }
28
+
29
+ // An organization the user belongs to, with their roles there.
30
+ export interface Membership<Role extends string = string> {
31
+ organization: Organization
32
+ roles: Role[]
33
+ joinedAt: Date
34
+ }
35
+
36
+ export interface AuthMember<Role extends string = string> {
37
+ user: { id: string, email: string | null, username: string | null }
38
+ roles: Role[]
39
+ joinedAt: Date
40
+ }
41
+
42
+ export interface Invitation<Role extends string = string> {
43
+ id: string
44
+ organization: Organization
45
+ email: string
46
+ roles: Role[]
47
+ invitedBy: string | null
48
+ createdAt: Date
49
+ expiresAt: Date
50
+ }
51
+
52
+ // `not-found` for an organization the user is no member of, so its existence does not leak; `forbidden` for a member whose roles do not reach.
53
+ export type OrganizationFailure = 'signed-out' | 'not-found' | 'forbidden'
54
+
55
+ // A write adds `impersonating`: an admin acting as the user changes nothing about their organizations.
56
+ export type OrganizationWriteFailure = OrganizationFailure | 'impersonating'
57
+
58
+ export type CreateOrganizationResult<Role extends string = string> = { ok: true, membership: Membership<Role> } | AuthFailed<'signed-out' | 'impersonating' | 'forbidden' | 'invalid-name' | 'invalid-slug' | 'slug-taken' | 'limited'>
59
+
60
+ export type UpdateOrganizationResult = { ok: true, organization: Organization } | AuthFailed<OrganizationWriteFailure | 'invalid-name' | 'invalid-slug' | 'slug-taken'>
61
+
62
+ // `last-owner` keeps an organization from being left without one.
63
+ export type MemberResult = { ok: true } | AuthFailed<OrganizationWriteFailure | 'unknown-role' | 'last-owner'>
64
+
65
+ export type InviteResult<Role extends string = string> = { ok: true, invitation: Invitation<Role> } | AuthFailed<OrganizationWriteFailure | 'unverified' | 'unknown-role' | 'invalid-email' | 'member' | 'limited' | 'unavailable'>
66
+
67
+ export type ListMembersResult<Role extends string = string> = { ok: true, members: AuthMember<Role>[] } | AuthFailed<OrganizationFailure>
68
+
69
+ export type ListInvitationsResult<Role extends string = string> = { ok: true, invitations: Invitation<Role>[] } | AuthFailed<OrganizationFailure>
70
+
71
+ // `wrong-account` when the signed-in user's address is not the one invited, `unverified` while it is but unproven.
72
+ export type AcceptResult<Role extends string = string> = { ok: true, membership: Membership<Role> } | AuthFailed<'signed-out' | 'impersonating' | 'not-found' | 'wrong-account' | 'unverified' | 'member'>
73
+
74
+ interface Found { ok: true, record: UserRecord, organization: OrganizationRecord, member: MemberRecord }
75
+
76
+ interface Stores {
77
+ organizations: NonNullable<AuthStore['organizations']>
78
+ members: NonNullable<AuthStore['members']>
79
+ invitations: NonNullable<AuthStore['invitations']>
80
+ }
81
+
82
+ export function organizationsOf(core: Core): { config: OrganizationsCore, store: Stores } {
83
+ const { organizations: config } = core
84
+ const { organizations, members, invitations } = core.store
85
+
86
+ if (!config)
87
+ throw configError('auth', 'organizations', 'organizations need the `organizations` option')
88
+
89
+ if (!organizations || !members || !invitations)
90
+ throw configError('auth', 'organizations', 'the `organizations` option needs a store keeping organizations, members and invitations, as memoryAuth and pgAuth do')
91
+
92
+ return { config, store: { organizations, members, invitations } }
93
+ }
94
+
95
+ // By id, or by slug.
96
+ export async function findOrganization(core: Core, ref: string): Promise<OrganizationRecord | undefined> {
97
+ const { store } = organizationsOf(core)
98
+
99
+ return await store.organizations.get(ref) ?? await store.organizations.findBySlug(ref.toLowerCase())
100
+ }
101
+
102
+ // Whether the user is a member of the organization `ref` names, holding `role` there when given.
103
+ export async function holdsInOrganization(core: Core, userId: string, ref: string, role?: string): Promise<boolean> {
104
+ const { config, store } = organizationsOf(core)
105
+ const organization = await findOrganization(core, ref)
106
+ const member = organization && await store.members.get(organization.id, userId)
107
+
108
+ return member !== undefined && (role === undefined || config.isGranted(role, member.roles))
109
+ }
110
+
111
+ export async function createOrganization(state: RequestState, input: { name: string, slug?: string | null | undefined }): Promise<CreateOrganizationResult> {
112
+ const { config, store } = organizationsOf(state.core)
113
+ const record = await state.current()
114
+
115
+ if (!record || state.via() !== 'session')
116
+ return failed('signed-out')
117
+
118
+ if (await impersonatorOf(state) !== undefined)
119
+ return failed('impersonating')
120
+
121
+ if (config.create && !(await config.create(publicUser(record))))
122
+ return failed('forbidden')
123
+
124
+ if (await spend(state.core.rates, `organization:${record.id}`, state.core.limits.organization))
125
+ return failed('limited')
126
+
127
+ const name = input.name.trim()
128
+ const slug = slugOf(input.slug)
129
+
130
+ if (!validName(name))
131
+ return failed('invalid-name')
132
+
133
+ if (slug !== null && !validSlug(slug))
134
+ return failed('invalid-slug')
135
+
136
+ if (slug !== null && await store.organizations.findBySlug(slug))
137
+ return failed('slug-taken')
138
+
139
+ const organization: OrganizationRecord = { id: crypto.randomUUID(), name, slug, createdAt: new Date() }
140
+ const member: MemberRecord = { organizationId: organization.id, userId: record.id, roles: [config.owner], createdAt: organization.createdAt }
141
+
142
+ try {
143
+ await store.organizations.create(organization)
144
+ }
145
+ // Taken between the check and the write.
146
+ catch {
147
+ return failed('slug-taken')
148
+ }
149
+
150
+ await store.members.add(member)
151
+ await report(state, record, 'organization-created', organization.id)
152
+
153
+ return { ok: true, membership: membership(organization, member) }
154
+ }
155
+
156
+ // Every organization the signed-in user belongs to, oldest joined first.
157
+ export async function listMemberships(state: RequestState): Promise<Membership[]> {
158
+ const { store } = organizationsOf(state.core)
159
+ const record = await state.current()
160
+
161
+ if (!record)
162
+ return []
163
+
164
+ const memberships: Membership[] = []
165
+ const held = await store.members.listByUser(record.id)
166
+ const organizations = await organizationsById(store.organizations, held.map(member => member.organizationId))
167
+
168
+ for (const member of held) {
169
+ const organization = organizations.get(member.organizationId)
170
+
171
+ if (organization)
172
+ memberships.push(membership(organization, member))
173
+ }
174
+
175
+ return memberships
176
+ }
177
+
178
+ // The organization `ref` names, by id or slug, with the signed-in user's roles there; null unless they are a member.
179
+ export async function getMembership(state: RequestState, ref: string): Promise<Membership | null> {
180
+ const found = await asMember(state, ref)
181
+
182
+ return found.ok ? membership(found.organization, found.member) : null
183
+ }
184
+
185
+ export async function updateOrganization(state: RequestState, ref: string, patch: { name?: string | undefined, slug?: string | null | undefined }): Promise<UpdateOrganizationResult> {
186
+ const { config, store } = organizationsOf(state.core)
187
+ const found = await asMember(state, ref, config.manage, 'write')
188
+
189
+ if (!found.ok)
190
+ return found
191
+
192
+ const name = patch.name?.trim()
193
+ const slug = patch.slug === undefined ? undefined : slugOf(patch.slug)
194
+
195
+ if (name !== undefined && !validName(name))
196
+ return failed('invalid-name')
197
+
198
+ if (slug != null && !validSlug(slug))
199
+ return failed('invalid-slug')
200
+
201
+ if (slug != null && slug !== found.organization.slug && await store.organizations.findBySlug(slug))
202
+ return failed('slug-taken')
203
+
204
+ let updated: OrganizationRecord | undefined
205
+
206
+ try {
207
+ updated = await store.organizations.update(found.organization.id, { ...name === undefined ? {} : { name }, ...slug === undefined ? {} : { slug } })
208
+ }
209
+ catch (error) {
210
+ // Only a slug another organization took meanwhile is a conflict, any other failure is the store's.
211
+ const holder = slug == null ? undefined : await store.organizations.findBySlug(slug)
212
+
213
+ if (holder && holder.id !== found.organization.id)
214
+ return failed('slug-taken')
215
+
216
+ throw error
217
+ }
218
+
219
+ return updated ? { ok: true, organization: publicOrganization(updated) } : failed('not-found')
220
+ }
221
+
222
+ export type DeleteOrganizationResult = { ok: true } | AuthFailed<OrganizationWriteFailure>
223
+
224
+ // Owners only, from a session: every membership and invitation goes with it.
225
+ export async function deleteOrganization(state: RequestState, ref: string): Promise<DeleteOrganizationResult> {
226
+ const { config, store } = organizationsOf(state.core)
227
+ const found = await asMember(state, ref, config.owner, 'write')
228
+
229
+ if (!found.ok)
230
+ return found
231
+
232
+ await store.organizations.delete(found.organization.id)
233
+ await report(state, found.record, 'organization-deleted', found.organization.id)
234
+
235
+ return { ok: true }
236
+ }
237
+
238
+ // Any member may list the others; only one who manages members is given their emails, the others' `email` is null (their own stays).
239
+ export async function listMembers(state: RequestState, ref: string): Promise<ListMembersResult> {
240
+ const { config, store } = organizationsOf(state.core)
241
+ const found = await asMember(state, ref)
242
+
243
+ if (!found.ok)
244
+ return found
245
+
246
+ const members: AuthMember[] = []
247
+ const managing = config.isGranted(config.manage, found.member.roles)
248
+
249
+ const held = await store.members.listByOrganization(found.organization.id)
250
+ const users = await usersById(state.core.store, held.map(member => member.userId))
251
+
252
+ for (const member of held) {
253
+ const user = users.get(member.userId)
254
+
255
+ if (user)
256
+ members.push({ user: { id: user.id, email: managing || user.id === found.record.id ? user.email : null, username: user.username }, roles: [...member.roles], joinedAt: member.createdAt })
257
+ }
258
+
259
+ return { ok: true, members }
260
+ }
261
+
262
+ // From a session only. A manager gives only roles they hold, to a member holding none above theirs: an admin cannot make an owner, nor demote one.
263
+ export async function setMemberRoles(state: RequestState, ref: string, userId: string, roles: string[]): Promise<MemberResult> {
264
+ const { config, store } = organizationsOf(state.core)
265
+ const found = await asMember(state, ref, config.manage, 'write')
266
+
267
+ if (!found.ok)
268
+ return found
269
+
270
+ if (roles.some(role => !config.roles.has(role)))
271
+ return failed('unknown-role')
272
+
273
+ const target = await store.members.get(found.organization.id, userId)
274
+
275
+ if (!target)
276
+ return failed('not-found')
277
+
278
+ if (!reaches(config, found.member.roles, [...target.roles, ...roles]))
279
+ return failed('forbidden')
280
+
281
+ if (target.roles.includes(config.owner) && !roles.includes(config.owner) && await lastOwner(config, store, found.organization.id))
282
+ return failed('last-owner')
283
+
284
+ await store.members.update(found.organization.id, userId, { roles: [...new Set(roles)] })
285
+
286
+ if (target.roles.includes(config.owner) && !roles.includes(config.owner) && !await ownerKept(config, store, found.organization.id, async () => store.members.update(found.organization.id, userId, { roles: target.roles })))
287
+ return failed('last-owner')
288
+
289
+ await reportOn(state, userId, 'member-roles-changed', `${found.organization.id} ${roles.join(' ')}`, found.record)
290
+
291
+ return { ok: true }
292
+ }
293
+
294
+ // From a session only: the signed-in user leaves, or a manager removes a member holding no role above theirs.
295
+ export async function removeMember(state: RequestState, ref: string, userId: string): Promise<MemberResult> {
296
+ const { config, store } = organizationsOf(state.core)
297
+ const self = (await state.current())?.id === userId
298
+ const found = await asMember(state, ref, self ? undefined : config.manage, 'write')
299
+
300
+ if (!found.ok)
301
+ return found
302
+
303
+ const target = self ? found.member : await store.members.get(found.organization.id, userId)
304
+
305
+ if (!target)
306
+ return failed('not-found')
307
+
308
+ if (!self && !reaches(config, found.member.roles, target.roles))
309
+ return failed('forbidden')
310
+
311
+ if (target.roles.includes(config.owner) && await lastOwner(config, store, found.organization.id))
312
+ return failed('last-owner')
313
+
314
+ await store.members.delete(found.organization.id, userId)
315
+
316
+ if (target.roles.includes(config.owner) && !await ownerKept(config, store, found.organization.id, async () => store.members.add(target)))
317
+ return failed('last-owner')
318
+
319
+ if (self)
320
+ await report(state, found.record, 'member-left', found.organization.id)
321
+ else
322
+ await reportOn(state, userId, 'member-removed', found.organization.id, found.record)
323
+
324
+ return { ok: true }
325
+ }
326
+
327
+ // The page an invitation link opens: the app's `invitationPage`, else the prebuilt pages' own, and none without either.
328
+ export function invitationPageOf(core: Core): string | undefined {
329
+ return core.organizations?.invitationPage ?? (core.pages ? `${core.pages.prefix}/invitation` : undefined)
330
+ }
331
+
332
+ // Mails the address a link to the invitation page; an invitation the address already had is replaced.
333
+ export async function invite(state: RequestState, ref: string, email: string, roles?: string[]): Promise<InviteResult> {
334
+ const { core } = state
335
+ const { config, store } = organizationsOf(core)
336
+ const found = await asMember(state, ref, config.manage, 'write')
337
+
338
+ if (!found.ok)
339
+ return found
340
+
341
+ // The mail goes out from the site's domain in the inviter's words, the organization's name: only someone who proved an address of their own may send it.
342
+ if (found.record.emailVerifiedAt === null)
343
+ return failed('unverified')
344
+
345
+ const given = roles ?? config.defaultRoles
346
+
347
+ if (given.some(role => !config.roles.has(role)))
348
+ return failed('unknown-role')
349
+
350
+ if (!reaches(config, found.member.roles, given))
351
+ return failed('forbidden')
352
+
353
+ if (emailProblem(email))
354
+ return failed('invalid-email')
355
+
356
+ const mail = core.email
357
+
358
+ const page = invitationPageOf(core)
359
+
360
+ if (!mail || page === undefined)
361
+ return failed('unavailable')
362
+
363
+ const address = normalizeEmail(email)
364
+ const invitee = await core.store.users.findByEmail(address)
365
+
366
+ if (invitee && await store.members.get(found.organization.id, invitee.id))
367
+ return failed('member')
368
+
369
+ // Each mail goes to an inbox someone else owns, so neither a manager nor many managers together may flood it.
370
+ if (await spend(core.rates, `invite:${found.record.id}`, core.limits.invite) || await spend(core.rates, typedKey(core, 'invite-address', address), core.limits.inviteAddress))
371
+ return failed('limited')
372
+
373
+ for (const earlier of await store.invitations.listByOrganization(found.organization.id)) {
374
+ if (earlier.email === address)
375
+ await store.invitations.delete(earlier.id)
376
+ }
377
+
378
+ const now = new Date()
379
+ const invitation: InvitationRecord = { id: crypto.randomUUID(), organizationId: found.organization.id, email: address, roles: [...new Set(given)], invitedBy: found.record.id, createdAt: now, expiresAt: new Date(now.getTime() + config.invitationMaxAge * 1000) }
380
+
381
+ await store.invitations.create(invitation)
382
+
383
+ const url = `${core.url}${page}?invitation=${invitation.id}`
384
+ const { locale, templates } = writing(mail, [invitee?.locale, found.record.locale, ...state.languages])
385
+
386
+ try {
387
+ await mail.mailer.send({ to: address, kind: 'invitation', name: core.name, detail: found.organization.name, locale, url, ...templates.invitation({ name: core.name, email: address, url, detail: found.organization.name, locale }) })
388
+ }
389
+ // Nobody would ever hear of an invitation left behind.
390
+ catch (error) {
391
+ log.error('mailing an invitation failed', error)
392
+ await store.invitations.delete(invitation.id)
393
+
394
+ return failed('unavailable')
395
+ }
396
+
397
+ return { ok: true, invitation: publicInvitation(invitation, found.organization) }
398
+ }
399
+
400
+ // The organization's invitations still open, oldest first, for its managers; expired ones are left out.
401
+ export async function listInvitations(state: RequestState, ref: string): Promise<ListInvitationsResult> {
402
+ const { config, store } = organizationsOf(state.core)
403
+ const found = await asMember(state, ref, config.manage, 'session')
404
+
405
+ if (!found.ok)
406
+ return found
407
+
408
+ return { ok: true, invitations: (await standing(config, store, open(await store.invitations.listByOrganization(found.organization.id)))).map(invitation => publicInvitation(invitation, found.organization)) }
409
+ }
410
+
411
+ export type RevokeInvitationResult = { ok: true } | AuthFailed<OrganizationWriteFailure>
412
+
413
+ export async function revokeInvitation(state: RequestState, ref: string, invitationId: string): Promise<RevokeInvitationResult> {
414
+ const { config, store } = organizationsOf(state.core)
415
+ const found = await asMember(state, ref, config.manage, 'write')
416
+
417
+ if (!found.ok)
418
+ return found
419
+
420
+ const invitation = await store.invitations.get(invitationId)
421
+
422
+ if (invitation?.organizationId !== found.organization.id)
423
+ return failed('not-found')
424
+
425
+ await store.invitations.delete(invitation.id)
426
+
427
+ return { ok: true }
428
+ }
429
+
430
+ // The invitations open to the signed-in user's verified address, oldest first.
431
+ export async function myInvitations(state: RequestState): Promise<Invitation[]> {
432
+ const { config, store } = organizationsOf(state.core)
433
+ const record = await state.current()
434
+
435
+ if (record?.email == null || record.email === '' || record.emailVerifiedAt === null)
436
+ return []
437
+
438
+ const invitations: Invitation[] = []
439
+ const pending = await standing(config, store, open(await store.invitations.listByEmail(record.email)))
440
+ const organizations = await organizationsById(store.organizations, pending.map(invitation => invitation.organizationId))
441
+
442
+ for (const invitation of pending) {
443
+ const organization = organizations.get(invitation.organizationId)
444
+
445
+ if (organization)
446
+ invitations.push(publicInvitation(invitation, organization))
447
+ }
448
+
449
+ return invitations
450
+ }
451
+
452
+ // Every invitation that names the signed-in user: those to their address, expired ones included, and those they sent from the organizations they belong to.
453
+ export async function exportedInvitations(state: RequestState): Promise<{ received: Invitation[], sent: Invitation[] }> {
454
+ const { store } = organizationsOf(state.core)
455
+ const record = await state.current()
456
+ const none = { received: [], sent: [] }
457
+
458
+ if (!record)
459
+ return none
460
+
461
+ const received = record.email === null || record.email === '' ? [] : await store.invitations.listByEmail(record.email)
462
+ const held = (await store.members.listByUser(record.id)).map(member => member.organizationId)
463
+ const sent = (await Promise.all(held.map(async id => store.invitations.listByOrganization(id)))).flat().filter(invitation => invitation.invitedBy === record.id)
464
+ const organizations = await organizationsById(store.organizations, [...new Set([...received, ...sent].map(invitation => invitation.organizationId))])
465
+ const named = (invitations: InvitationRecord[]) => invitations.flatMap((invitation) => {
466
+ const organization = organizations.get(invitation.organizationId)
467
+
468
+ return organization ? [publicInvitation(invitation, organization)] : []
469
+ })
470
+
471
+ return { received: named(received), sent: named(sent) }
472
+ }
473
+
474
+ // What the link's page shows anyone holding it: which organization, for which address; null once revoked, spent or expired.
475
+ export async function getInvitation(state: RequestState, invitationId: string): Promise<Invitation | null> {
476
+ const { config, store } = organizationsOf(state.core)
477
+ const found = await live(store, invitationId)
478
+ const invitation = found && await senderMay(config, store, found) ? found : undefined
479
+ const organization = invitation && await store.organizations.get(invitation.organizationId)
480
+
481
+ return invitation && organization ? publicInvitation(invitation, organization) : null
482
+ }
483
+
484
+ // Only an account verified at the invited address accepts, so a forwarded link is worth nothing to anyone else.
485
+ export async function acceptInvitation(state: RequestState, invitationId: string): Promise<AcceptResult> {
486
+ const { config, store } = organizationsOf(state.core)
487
+ const record = await state.current()
488
+
489
+ if (!record || state.via() !== 'session')
490
+ return failed('signed-out')
491
+
492
+ if (await impersonatorOf(state) !== undefined)
493
+ return failed('impersonating')
494
+
495
+ const found = await live(store, invitationId)
496
+ const invitation = found && await senderMay(config, store, found) ? found : undefined
497
+ const organization = invitation && await store.organizations.get(invitation.organizationId)
498
+
499
+ if (!invitation || !organization)
500
+ return failed('not-found')
501
+
502
+ if (record.email !== invitation.email)
503
+ return failed('wrong-account')
504
+
505
+ if (record.emailVerifiedAt === null)
506
+ return failed('unverified')
507
+
508
+ if (await store.members.get(organization.id, record.id))
509
+ return failed('member')
510
+
511
+ // Deleted first, so of two requests accepting it only one adds the member.
512
+ if (!(await store.invitations.delete(invitation.id)))
513
+ return failed('not-found')
514
+
515
+ const member: MemberRecord = { organizationId: organization.id, userId: record.id, roles: invitation.roles, createdAt: new Date() }
516
+
517
+ await store.members.add(member)
518
+ await report(state, record, 'member-joined', `${organization.id} ${member.roles.join(' ')}`)
519
+
520
+ return { ok: true, membership: membership(organization, member) }
521
+ }
522
+
523
+ export type RejectInvitationResult = { ok: true } | AuthFailed<'signed-out' | 'impersonating' | 'not-found'>
524
+
525
+ // The invited user turns it down; `not-found` when it is not open to them, whoever it was meant for.
526
+ export async function declineInvitation(state: RequestState, invitationId: string): Promise<RejectInvitationResult> {
527
+ const { store } = organizationsOf(state.core)
528
+ const record = await state.current()
529
+
530
+ if (!record || state.via() !== 'session')
531
+ return failed('signed-out')
532
+
533
+ if (await impersonatorOf(state) !== undefined)
534
+ return failed('impersonating')
535
+
536
+ const invitation = await live(store, invitationId)
537
+
538
+ if (record.email == null || record.email === '' || record.emailVerifiedAt === null || invitation?.email !== record.email)
539
+ return failed('not-found')
540
+
541
+ return (await store.invitations.delete(invitation.id)) ? { ok: true } : failed('not-found')
542
+ }
543
+
544
+ // The signed-in user's membership of the organization `ref` names, holding `role` there when given; with `access`, a bearer or OAuth token is refused as signed out, and 'write' also refuses an admin acting as the user.
545
+ async function asMember(state: RequestState, ref: string, role: string | undefined, access: 'write'): Promise<Found | AuthFailed<OrganizationWriteFailure>>
546
+ async function asMember(state: RequestState, ref: string, role?: string, access?: 'session'): Promise<Found | AuthFailed<OrganizationFailure>>
547
+
548
+ async function asMember(state: RequestState, ref: string, role?: string, access?: 'session' | 'write'): Promise<Found | AuthFailed<OrganizationWriteFailure>> {
549
+ const { config, store } = organizationsOf(state.core)
550
+ const record = await state.current()
551
+
552
+ if (!record || (access !== undefined && state.via() !== 'session'))
553
+ return failed('signed-out')
554
+
555
+ if (access === 'write' && await impersonatorOf(state) !== undefined)
556
+ return failed('impersonating')
557
+
558
+ const organization = await findOrganization(state.core, ref)
559
+ const member = organization && await store.members.get(organization.id, record.id)
560
+
561
+ if (!organization || !member)
562
+ return failed('not-found')
563
+
564
+ if (role !== undefined && !config.isGranted(role, member.roles))
565
+ return failed('forbidden')
566
+
567
+ return { ok: true, record, organization, member }
568
+ }
569
+
570
+ // Whether `held` includes every one of `roles`.
571
+ function reaches(config: OrganizationsCore, held: string[], roles: string[]): boolean {
572
+ return roles.every(role => config.isGranted(role, held))
573
+ }
574
+
575
+ async function lastOwner(config: OrganizationsCore, store: Stores, organizationId: string, atMost = 1): Promise<boolean> {
576
+ return (await store.members.listByOrganization(organizationId)).filter(member => member.roles.includes(config.owner)).length <= atMost
577
+ }
578
+
579
+ // Checked again after the write, as two requests can each see the other owner still there: when none is left, `restore` puts the member back, so of two racing the last owners at least one stays.
580
+ async function ownerKept(config: OrganizationsCore, store: Stores, organizationId: string, restore: () => Promise<unknown>): Promise<boolean> {
581
+ if (!await lastOwner(config, store, organizationId, 0))
582
+ return true
583
+
584
+ // An organization deleted meanwhile has nothing to put the member back in.
585
+ if (await store.organizations.get(organizationId)) {
586
+ try {
587
+ await restore()
588
+ }
589
+ catch (error) {
590
+ // The member is back already, or gone with their account: nothing is left to undo. Otherwise the store failed and the organization has no owner, so the error is not hidden.
591
+ if (await store.organizations.get(organizationId) && await lastOwner(config, store, organizationId, 0))
592
+ throw error
593
+ }
594
+ }
595
+
596
+ return false
597
+ }
598
+
599
+ async function live(store: Stores, invitationId: string): Promise<InvitationRecord | undefined> {
600
+ const invitation = await store.invitations.get(invitationId)
601
+
602
+ return invitation && invitation.expiresAt.getTime() > Date.now() ? invitation : undefined
603
+ }
604
+
605
+ // Whether a sender, as the member they are of the organization, still may grant the roles: they manage it and hold them.
606
+ function mayGrant(config: OrganizationsCore, sender: MemberRecord | undefined, roles: string[]): boolean {
607
+ return sender !== undefined && config.isGranted(config.manage, sender.roles) && reaches(config, sender.roles, roles)
608
+ }
609
+
610
+ // Whether whoever sent the invitation still may grant what it gives. One whose sender is gone, their account deleted included, is dead.
611
+ async function senderMay(config: OrganizationsCore, store: Stores, invitation: InvitationRecord): Promise<boolean> {
612
+ return mayGrant(config, invitation.invitedBy === null ? undefined : await store.members.get(invitation.organizationId, invitation.invitedBy), invitation.roles)
613
+ }
614
+
615
+ // The invitations whose sender still may grant them, each sender of an organization looked up once.
616
+ async function standing(config: OrganizationsCore, store: Stores, invitations: InvitationRecord[]): Promise<InvitationRecord[]> {
617
+ const senders = new Map<string, MaybePromise<MemberRecord | undefined>>()
618
+ const may = await Promise.all(invitations.map(async (invitation) => {
619
+ if (invitation.invitedBy === null)
620
+ return false
621
+
622
+ const key = `${invitation.organizationId}\0${invitation.invitedBy}`
623
+ const sender = senders.get(key) ?? store.members.get(invitation.organizationId, invitation.invitedBy)
624
+
625
+ senders.set(key, sender)
626
+
627
+ return mayGrant(config, await sender, invitation.roles)
628
+ }))
629
+
630
+ return invitations.filter((_invitation, index) => may[index])
631
+ }
632
+
633
+ // The invitations not yet expired; the store's pruning deletes the others.
634
+ function open(invitations: InvitationRecord[]): InvitationRecord[] {
635
+ const now = Date.now()
636
+
637
+ return invitations.filter(invitation => invitation.expiresAt.getTime() > now)
638
+ }
639
+
640
+ async function reportOn(state: RequestState, userId: string, event: 'member-roles-changed' | 'member-removed', detail: string, actor: UserRecord): Promise<void> {
641
+ const record = await state.core.store.users.get(userId)
642
+
643
+ if (record)
644
+ await report(state, record, event, detail, actor)
645
+ }
646
+
647
+ // A slug as typed, trimmed and lowercased; none when left blank.
648
+ function slugOf(typed: string | null | undefined): string | null {
649
+ const slug = typed?.trim().toLowerCase()
650
+
651
+ return slug === undefined || slug === '' ? null : slug
652
+ }
653
+
654
+ // A name goes into the invitation mail's subject and lead, where a line break or a direction override would let it pass for something else.
655
+ function validName(name: string): boolean {
656
+ return name.length > 0 && name.length <= NAME_MAX_LENGTH && !UNPRINTABLE.test(name)
657
+ }
658
+
659
+ function validSlug(slug: string): boolean {
660
+ return slug.length <= SLUG_MAX_LENGTH && SLUG.test(slug)
661
+ }
662
+
663
+ function publicOrganization(record: OrganizationRecord): Organization {
664
+ return { id: record.id, name: record.name, slug: record.slug, createdAt: record.createdAt }
665
+ }
666
+
667
+ function membership(organization: OrganizationRecord, member: MemberRecord): Membership {
668
+ return { organization: publicOrganization(organization), roles: [...member.roles], joinedAt: member.createdAt }
669
+ }
670
+
671
+ function publicInvitation(invitation: InvitationRecord, organization: OrganizationRecord): Invitation {
672
+ return { id: invitation.id, organization: publicOrganization(organization), email: invitation.email, roles: [...invitation.roles], invitedBy: invitation.invitedBy, createdAt: invitation.createdAt, expiresAt: invitation.expiresAt }
673
+ }
674
+
675
+ export type { OrganizationsCore, OrganizationsOptions } from './organizationsCore'