@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
package/src/request.ts ADDED
@@ -0,0 +1,712 @@
1
+ import type { GuardContext } from 'kay'
2
+ import type { KayConfig, Session } from 'kay/server'
3
+ import type { CaptchaAction } from './captcha'
4
+ import type { AuthSessionData, BareUser, Core, SignedIn, User } from './core'
5
+ import type { ScopeRequirement } from './gate'
6
+ import type { AuthFeatures } from './pages'
7
+ import type { Proof, ReproveResult } from './proof'
8
+ import type { GuestSignInResult } from './sessions'
9
+ import type { RequestState } from './state'
10
+ import type { SessionRecord, UserRecord } from './store'
11
+ import type { Requirement } from './types'
12
+ import { localPath } from 'kay'
13
+ import { durationSeconds, nameUser, overHttps, READ_METHODS, stoppers } from 'kay/library'
14
+ import { clientAddress, crossSiteRefused, crossSiteResponse, forgetLocalMirrors, forgetPushDevice, rateKey, toolCall } from 'kay/server'
15
+ import { protectedResourceMetadata, rootIsFixed, rootUsable, siteRoot } from './authorize/metadata'
16
+ import { bearerRequest, bearerToken } from './bearerHeader'
17
+ import { admit, captchaChallenge, captchaRequired } from './captcha'
18
+ import { banned, guardPageOf, isNavigation, linkedProviders, linkedUser, newUserRecord, publicUser, unlinked, withBack } from './core'
19
+ import { report } from './events'
20
+ import { failed } from './failure'
21
+ import { scopeAllows } from './gate'
22
+ import { load } from './load'
23
+ import { acceptedLocales } from './locale'
24
+ import { AccountMethods } from './methods/account'
25
+ import { AdminMethods } from './methods/admin'
26
+ import { AuditMethods } from './methods/audit'
27
+ import { EmailMethods } from './methods/email'
28
+ import { MagicLinkMethods } from './methods/magicLink'
29
+ import { OAuthMethods } from './methods/oauth'
30
+ import { OAuthServerMethods } from './methods/oauthServer'
31
+ import { OrganizationMethods } from './methods/organizations'
32
+ import { PasskeyMethods } from './methods/passkeys'
33
+ import { PasswordMethods } from './methods/password'
34
+ import { SessionMethods } from './methods/sessions'
35
+ import { TokenMethods } from './methods/tokens'
36
+ import { TwoFactorMethods } from './methods/twoFactor'
37
+ import { featuresOf } from './pages'
38
+ import { completeSignIn, provedLately, reprove } from './proof'
39
+ import { pruneWhenDue } from './prune'
40
+ import { sendToEnrolment } from './requiredTwoFactor'
41
+ import { roleHierarchy } from './roles'
42
+ import { noteSignIn, securityNotice } from './securityNotice'
43
+ import { applyLifetime, chooseRemember, liveSession, openSession, revokeBearerTokens } from './sessions'
44
+ import { registerViewer } from './viewer'
45
+
46
+ export interface RequireUserOptions<Scope extends string, Role extends string> {
47
+ redirect?: string | undefined
48
+ scope?: ScopeRequirement<Scope> | undefined
49
+ require?: AuthRequirement<Role> | undefined
50
+ bare?: true | undefined
51
+ }
52
+
53
+ export const STATE = Symbol('kayjs-auth.state')
54
+ export const TAKE_COOKIES = Symbol('kayjs-auth.takeCookies')
55
+
56
+ // Says `requireUser()` reads `require`, so kayjs-cms's `role` refuses a request rather than trust an older kayjs-auth that ignores it.
57
+ const REQUIRES: unique symbol = Symbol.for('kayjs-auth.requires')
58
+
59
+ // The readable cookie telling a script of the site that a person is signed in, so a library's script (kayjs-cms's Edit this page link) asks the server only for a browser that may get an answer.
60
+ export const SIGNED_IN_HINT = 'kay_user'
61
+ // How long a user read stays good. A request is over long before; a websocket, which keeps its `Auth` for its life, reads its user again past it, so a sign-out, a revoked token or a ban reaches it.
62
+ const USER_FRESH_MS = 30 * 1000
63
+ // The newest users `userIdsHolding` reads, a page at a time.
64
+ const USER_SCAN_MAX = 10_000
65
+ const USER_SCAN_PAGE = 200
66
+ // The close code of a socket whose user is gone: a policy violation.
67
+ const SOCKET_USER_GONE = 1008
68
+ // The sockets `socketUser` answered a user for, to close once that user is gone.
69
+ const servedSockets = new WeakSet<object>()
70
+
71
+ // What a route, a guard or a gate asks of the user: a role, a predicate, or a list of which any one passes.
72
+ export type AuthRequirement<Role extends string> = Requirement<BareUser, Role>
73
+
74
+ // A session a browser's cross-site POST or websocket upgrade reads as signed out and cannot write, a write answered with a 403: a plain Elysia app has no Origin check of kay's own.
75
+ function guardSession(session: Session<AuthSessionData>, refuse: () => boolean, refusal: () => Response): Session<AuthSessionData> {
76
+ const write = <Args extends unknown[]>(call: (...args: Args) => Promise<void>) => async (...args: Args): Promise<void> => {
77
+ if (refuse())
78
+ throw refusal()
79
+
80
+ return call(...args)
81
+ }
82
+
83
+ return {
84
+ get: async key => refuse() ? undefined : session.get(key),
85
+ set: write(async (key, value) => session.set(key, value)),
86
+ unset: write(async key => session.unset(key)),
87
+ destroy: write(async () => session.destroy()),
88
+ settings: session.settings,
89
+ regenerate: write(async () => session.regenerate()),
90
+ maxAge: write(async maxAge => session.maxAge(maxAge)),
91
+ }
92
+ }
93
+
94
+ interface Groups<Scope extends string, Role extends string, OrgRole extends string> {
95
+ password: PasswordMethods
96
+ email: EmailMethods
97
+ magicLink: MagicLinkMethods
98
+ twoFactor: TwoFactorMethods
99
+ passkeys: PasskeyMethods
100
+ sessions: SessionMethods
101
+ tokens: TokenMethods<Scope>
102
+ oauthServer: OAuthServerMethods
103
+ admin: AdminMethods<Role>
104
+ organizations: OrganizationMethods<OrgRole>
105
+ account: AccountMethods
106
+ oauth: OAuthMethods
107
+ audit: AuditMethods
108
+ }
109
+
110
+ // Auth for one request, as `auth` in the context: `ctx.locals.auth` in a page, an action or a guard.
111
+ export class Auth<Scope extends string = string, Role extends string = string, OrgRole extends string = string, UserData extends object = Record<string, unknown>> {
112
+ readonly [STATE]: RequestState
113
+ readonly [REQUIRES] = true
114
+ private known?: { record: Promise<UserRecord | null>, at: number } | undefined
115
+ private source: 'session' | 'bearer' | null = null
116
+ private tokenScopes: string[] | null = null
117
+ private linked = new WeakMap<UserRecord, Promise<User['providers']>>()
118
+ // Each group of methods, made on its first use.
119
+ private readonly groups: Partial<Groups<Scope, Role, OrgRole>> = {}
120
+
121
+ private readonly session: Session<AuthSessionData>
122
+ // Set-Cookie lines this request's sign-in or sign-out adds to its response, which the plugin sends.
123
+ private readonly cookies: string[] = []
124
+
125
+ constructor(session: Session<AuthSessionData>, private readonly core: Core, private readonly request: Request, client: string, address: string) {
126
+ const bearer = bearerRequest(request)
127
+ const crossSite = () => !bearer && crossSiteRefused(request, core.url)
128
+
129
+ this.session = guardSession(session, crossSite, () => crossSiteResponse(request, 'request', core.url))
130
+
131
+ let languages: string[] | undefined
132
+
133
+ this[STATE] = {
134
+ core,
135
+ session: this.session,
136
+ crossSite,
137
+ client,
138
+ address,
139
+ userAgent: request.headers.get('user-agent') ?? '',
140
+ // Read off the header when a flow first needs a language.
141
+ get languages() {
142
+ languages ??= acceptedLocales(request.headers.get('accept-language') ?? '')
143
+
144
+ return languages
145
+ },
146
+ current: async () => this.record(),
147
+ via: () => this.source,
148
+ complete: async (record, redirect, method) => completeSignIn(this[STATE], record, redirect, method, async (signedIn, how) => this.establish(signedIn, how)),
149
+ establish: async (record, method) => this.establish(record, method),
150
+ signOut: async () => this.signOut(),
151
+ adopt: (record) => {
152
+ this.resolving = Promise.resolve(record)
153
+ this.cookies.push(forgetLocalMirrors(this.request, record.id))
154
+ },
155
+ reload: async () => {
156
+ this.source = null
157
+ this.resolving = undefined
158
+
159
+ const record = await this.record()
160
+
161
+ if (record)
162
+ this.cookies.push(forgetLocalMirrors(this.request, record.id))
163
+ else
164
+ await this.leave()
165
+ },
166
+ renew: async (record) => {
167
+ // Read off the session, not through `record()`: the version it holds is the one just raised past.
168
+ const signedIn = await this.session.get('auth')
169
+
170
+ if (signedIn?.user !== record.id)
171
+ return
172
+
173
+ await this.session.set('auth', { ...signedIn, version: record.sessionVersion })
174
+
175
+ if (signedIn.session !== undefined)
176
+ await this.core.store.sessions.update(signedIn.session, { version: record.sessionVersion })
177
+
178
+ this.resolving = Promise.resolve(record)
179
+ },
180
+ }
181
+ }
182
+
183
+ // Marks this browser as signed in, or not, with a readable cookie any script of the site may look for before asking the server: a hint only, never trusted, new at each sign-in so a script can tell one from the next. `maxAge` is the session's, undefined for a cookie the browser drops on closing.
184
+ private markBrowser(signedIn: boolean, maxAge?: number): void {
185
+ const header = this.request.headers.get('cookie') ?? ''
186
+
187
+ if (!signedIn && !header.includes(`${SIGNED_IN_HINT}=`))
188
+ return
189
+
190
+ this.cookies.push(new Bun.Cookie(SIGNED_IN_HINT, signedIn ? crypto.randomUUID() : '', { path: '/', sameSite: 'lax', secure: overHttps(this.request), ...!signedIn && { maxAge: 0 }, ...signedIn && maxAge !== undefined && { maxAge } }).serialize())
191
+ }
192
+
193
+ // The cookies the response must carry, handed over once.
194
+ [TAKE_COOKIES](): string[] {
195
+ return this.cookies.splice(0)
196
+ }
197
+
198
+ private get resolving(): Promise<UserRecord | null> | undefined {
199
+ return this.known?.record
200
+ }
201
+
202
+ private set resolving(record: Promise<UserRecord | null> | undefined) {
203
+ this.known = record && { record, at: Date.now() }
204
+ }
205
+
206
+ // Registering, signing in, resets and changes by password.
207
+ get password(): PasswordMethods {
208
+ return this.groups.password ??= new PasswordMethods(this[STATE])
209
+ }
210
+
211
+ // Verifying the address and changing it.
212
+ get email(): EmailMethods {
213
+ return this.groups.email ??= new EmailMethods(this[STATE])
214
+ }
215
+
216
+ // Sign-in links and codes mailed to the address.
217
+ get magicLink(): MagicLinkMethods {
218
+ return this.groups.magicLink ??= new MagicLinkMethods(this[STATE])
219
+ }
220
+
221
+ // The second factor of a sign-in, and setting up an authenticator app.
222
+ get twoFactor(): TwoFactorMethods {
223
+ return this.groups.twoFactor ??= new TwoFactorMethods(this[STATE])
224
+ }
225
+
226
+ // Making passkeys, signing in and re-proving with one.
227
+ get passkeys(): PasskeyMethods {
228
+ return this.groups.passkeys ??= new PasskeyMethods(this[STATE])
229
+ }
230
+
231
+ // Where the signed-in user is signed in.
232
+ get sessions(): SessionMethods {
233
+ return this.groups.sessions ??= new SessionMethods(this[STATE])
234
+ }
235
+
236
+ // The signed-in user's bearer tokens.
237
+ get tokens(): TokenMethods<Scope> {
238
+ return this.groups.tokens ??= new TokenMethods<Scope>(this[STATE])
239
+ }
240
+
241
+ // The consent page MCP clients send the user to, and the apps they approved.
242
+ get oauthServer(): OAuthServerMethods {
243
+ return this.groups.oauthServer ??= new OAuthServerMethods(this[STATE], this.request)
244
+ }
245
+
246
+ // Listing, banning and impersonating users and granting them roles, for the `admin` option's users.
247
+ get admin(): AdminMethods<Role> {
248
+ return this.groups.admin ??= new AdminMethods<Role>(this[STATE])
249
+ }
250
+
251
+ // The organizations of the `organizations` option.
252
+ get organizations(): OrganizationMethods<OrgRole> {
253
+ return this.groups.organizations ??= new OrganizationMethods<OrgRole>(this[STATE])
254
+ }
255
+
256
+ // The signed-in user's own account: username, language, profile, data export and deletion.
257
+ get account(): AccountMethods {
258
+ return this.groups.account ??= new AccountMethods(this[STATE])
259
+ }
260
+
261
+ // The providers the signed-in user signs in with: linking, unlinking and their tokens.
262
+ get oauth(): OAuthMethods {
263
+ return this.groups.oauth ??= new OAuthMethods(this[STATE], () => {
264
+ this.linked = new WeakMap()
265
+ })
266
+ }
267
+
268
+ // The signed-in user's own audit log.
269
+ get audit(): AuditMethods {
270
+ return this.groups.audit ??= new AuditMethods(this[STATE])
271
+ }
272
+
273
+ // The signed-in user, or the owner of the request's `Authorization: Bearer` token, or null; read on first use, and again past 30 seconds on a websocket.
274
+ async user(): Promise<User<UserData> | null> {
275
+ const record = await this.record()
276
+
277
+ return record && { ...publicUser(record), providers: await this.providersOf(record) } as User<UserData>
278
+ }
279
+
280
+ // The signed-in user as `user()` finds them but without `providers`, which costs a read: for a guard or a gate that does not look at it.
281
+ async bareUser(): Promise<BareUser<UserData> | null> {
282
+ const record = await this.record()
283
+
284
+ return record && publicUser(record) as BareUser<UserData>
285
+ }
286
+
287
+ // Read once per request for the record in hand, as the user is asked for several times.
288
+ private async providersOf(record: UserRecord): Promise<User['providers']> {
289
+ let held = this.linked.get(record)
290
+
291
+ if (!held)
292
+ this.linked.set(record, held = linkedProviders(this.core, record.id))
293
+
294
+ return held
295
+ }
296
+
297
+ // The signed-in user, who must be there: an anonymous visitor opening a page goes to the sign-in page and comes back, and any other request, an action's call included, is refused with a 401, as `auth.guard()` does. For a page or an action to ask for a user without a guard above it; the user is read once per request.
298
+ // The sign-in page is the prebuilt one with `pages`, else `redirect`, else `signInPage`, else the visitor gets the 401 too. A bearer token limited to scopes is refused with a 403 unless `scope` names one it holds, and a user who does not meet `require` (a role, or any requirement `guard()` takes, with no route params) with a 403 too.
299
+ // `bare: true` answers the `BareUser` of `bareUser()`, with no providers read: for a caller that only wants the checks, as kayjs-cms's `role` does.
300
+ async requireUser(options: RequireUserOptions<Scope, Role> & { bare: true }): Promise<BareUser<UserData>>
301
+ async requireUser(options?: RequireUserOptions<Scope, Role> & { bare?: undefined }): Promise<User<UserData>>
302
+ async requireUser(options: RequireUserOptions<Scope, Role> = {}): Promise<User<UserData> | BareUser<UserData>> {
303
+ const record = await this.record()
304
+ const { redirect, deny } = stoppers(this.request)
305
+
306
+ if (!record) {
307
+ const signIn = options.redirect === undefined || options.redirect === '' ? guardPageOf(this.core) : options.redirect
308
+
309
+ if (signIn !== undefined && isNavigation(this.request))
310
+ redirect(this.signInLink(signIn))
311
+
312
+ return deny(401, 'Sign in to continue')
313
+ }
314
+
315
+ const user = publicUser(record) as BareUser<UserData>
316
+
317
+ if (options.require !== undefined && !(await this.core.access.authorize(user as BareUser, options.require, READ_METHODS.has(this.request.method) ? 'read' : 'write', {})))
318
+ return deny(403)
319
+
320
+ if (!scopeAllows(await this.scopes(), options.scope))
321
+ return deny(403)
322
+
323
+ return options.bare ? user : { ...user, providers: await this.providersOf(record) }
324
+ }
325
+
326
+ // The signed-in admin, as themselves, for an admin page to ask for: 404 while the `admin` option names no one (a `Denied`, which a plain Elysia app answers too), a visitor sent to sign in as `requireUser()` does, and 403 for anyone else, an admin acting as a user and a bearer token included.
327
+ async requireAdmin(): Promise<User<UserData>> {
328
+ if (!this.core.admin)
329
+ return stoppers(this.request).deny(404)
330
+
331
+ const user = await this.requireUser()
332
+ const acting = await (await load.admin()).askingAdmin(this[STATE])
333
+
334
+ if (acting.ok)
335
+ return user
336
+
337
+ return acting.error.code === 'two-factor-required' ? sendToEnrolment(this.core, this.request, stoppers(this.request)) : stoppers(this.request).deny(403)
338
+ }
339
+
340
+ // The `guard()` of kayjs-auth, for a `_guard.ts` that cannot import the `authCore` result: the guard of the one behind this request.
341
+ async guarded(ctx: GuardContext, options: Parameters<Core['guard']>[0]): Promise<void> {
342
+ await this.core.guard(options)(ctx)
343
+ }
344
+
345
+ // The sign-in page with `?redirect=` set to where it should lead back: this request's path and query, or `back`. A `back` that is not a path of this site leads home, so no link built from input sends anyone away.
346
+ signInUrl(back?: string): string {
347
+ return this.signInLink(this.core.signInPage, back)
348
+ }
349
+
350
+ private signInLink(page: string, back?: string): string {
351
+ const here = new URL(this.request.url)
352
+
353
+ return withBack(page, localPath(back ?? here.pathname + here.search, '/'))
354
+ }
355
+
356
+ // How `user()` found the user: their session, or a bearer token; null when anonymous.
357
+ async via(): Promise<'session' | 'bearer' | null> {
358
+ await this.record()
359
+
360
+ return this.source
361
+ }
362
+
363
+ // Signs `user` in on this session, without asking for their second factor: for a way of signing in the app proves itself. `remember` as for `password.signIn`.
364
+ async signIn(user: Pick<User, 'id'>, options: { remember?: boolean | undefined } = {}): Promise<void> {
365
+ const record = await this.core.store.users.get(user.id)
366
+
367
+ if (!record)
368
+ throw new Error(`kayjs-auth: no user ${user.id} to sign in`)
369
+
370
+ if (banned(record))
371
+ throw new Error(`kayjs-auth: user ${user.id} is banned`)
372
+
373
+ await chooseRemember(this[STATE], options.remember)
374
+ await this.establish(record, 'app')
375
+ }
376
+
377
+ // Signs this session out. A session held in the cookie alone stays valid wherever it was copied until it expires; `signOutEverywhere` ends those too.
378
+ async signOut(): Promise<void> {
379
+ const signedIn = await this.session.get('auth')
380
+ const record = signedIn && await this.core.store.users.get(signedIn.user)
381
+
382
+ if (signedIn?.impersonator) {
383
+ const actor = await this.core.store.users.get(signedIn.impersonator.user)
384
+
385
+ if (record && actor)
386
+ await report(this[STATE], record, 'impersonation-ended', undefined, actor)
387
+ }
388
+ else if (record) {
389
+ await report(this[STATE], record, 'signed-out')
390
+ }
391
+
392
+ await this.leave()
393
+ }
394
+
395
+ // Signs this session out without a word to `onEvent`, the admin behind an impersonation too.
396
+ private async leave(): Promise<void> {
397
+ const signedIn = await this.session.get('auth')
398
+
399
+ // A device the person leaves stops getting their pushes and drops the rows and queued writes their local() collections held.
400
+ if (signedIn) {
401
+ await forgetPushDevice(this.request, signedIn.user)
402
+ this.cookies.push(forgetLocalMirrors(this.request))
403
+ }
404
+
405
+ if (signedIn?.session !== undefined)
406
+ await this.core.store.sessions.delete(signedIn.user, signedIn.session)
407
+
408
+ if (signedIn?.impersonator?.session !== undefined)
409
+ await this.core.store.sessions.delete(signedIn.impersonator.user, signedIn.impersonator.session)
410
+
411
+ await this.session.unset('auth')
412
+ await this.session.unset('authRegistered')
413
+ await this.session.unset('authHeld')
414
+ await this.session.unset('authBack')
415
+ await this.session.regenerate()
416
+ this.source = null
417
+ this.resolving = Promise.resolve(null)
418
+ this.markBrowser(false)
419
+ }
420
+
421
+ // Signs the user out of every session they hold and revokes their bearer tokens, this session kept only with `keepThisOne`, as after a password change.
422
+ async signOutEverywhere(options: { keepThisOne?: boolean } = {}): Promise<void> {
423
+ const record = await this.record()
424
+
425
+ if (!record)
426
+ return
427
+
428
+ const updated = await this.core.store.users.update(record.id, { sessionVersion: record.sessionVersion + 1 })
429
+
430
+ // A device token is a session too, and one minted from a stolen session would outlive it.
431
+ await revokeBearerTokens(this.core, record.id)
432
+
433
+ await securityNotice(this[STATE], record, 'signed-out-everywhere', options.keepThisOne ? 'this-one-kept' : undefined)
434
+
435
+ if (updated && options.keepThisOne)
436
+ await this[STATE].renew(updated)
437
+ else
438
+ await this.leave()
439
+ }
440
+
441
+ // Signs this browser in as a new guest, a user with no email and no password whom registering or an OAuth sign-in later makes a real account, keeping their id; the guest signed in already answers as is. Counted as registering is, and CAPTCHA-checked as `guest`.
442
+ async signInAsGuest(options: { captcha?: string | undefined } = {}): Promise<GuestSignInResult> {
443
+ const current = await this.record()
444
+
445
+ if (current)
446
+ return current.guest ? { ok: true, user: publicUser(current) } : failed('signed-in')
447
+
448
+ if (!this.core.signUp)
449
+ return failed('off')
450
+
451
+ const refused = await admit(this[STATE], 'guest', options.captcha)
452
+
453
+ if (refused)
454
+ return failed(refused)
455
+
456
+ const fresh = newUserRecord({ guest: true, roles: [...this.core.defaultRoles], locale: this[STATE].languages[0] ?? null })
457
+ const record = (await this.core.store.users.create(fresh)) ?? fresh
458
+
459
+ await this.core.onSignUp?.(unlinked(publicUser(record)), undefined)
460
+ await this.establish(record, 'guest')
461
+
462
+ return { ok: true, user: publicUser(record) }
463
+ }
464
+
465
+ // What the config enables, for a page to show only what works: the providers, mail, passkeys, scopes and the prebuilt pages.
466
+ features(): AuthFeatures {
467
+ return featuresOf(this.core)
468
+ }
469
+
470
+ // The RFC 9728 metadata of the protected resource `name` served at `path`, which kay's MCP endpoint asks for; null while the OAuth server is off. It points MCP clients at the app's own authorization server.
471
+ oauthResource(path: string, name: string): Record<string, unknown> | null {
472
+ if (!this.core.oauthServer || !rootUsable(this.core))
473
+ return null
474
+
475
+ const root = siteRoot(this.core, this.request)
476
+
477
+ return protectedResourceMetadata(this.core, root, `${root}${path}`, name)
478
+ }
479
+
480
+ // The origin the OAuth documents are served at, which kay's 401 pointer to them names; undefined while the OAuth server is off.
481
+ oauthOrigin(): string | undefined {
482
+ return this.core.oauthServer && rootUsable(this.core) ? new URL(siteRoot(this.core, this.request)).origin : undefined
483
+ }
484
+
485
+ // Whether that origin is configured, so the documents may be cached for everyone; else it is the request's own.
486
+ oauthFixed(): boolean {
487
+ return rootIsFixed(this.core)
488
+ }
489
+
490
+ // Whether this client's next `action` needs a CAPTCHA token, for the page to show the widget.
491
+ async captchaRequired(action: CaptchaAction): Promise<boolean> {
492
+ return captchaRequired(this[STATE], action)
493
+ }
494
+
495
+ // The proof-of-work challenge for this client's next `action`, for a form field kay's script posts the solution of; null when none is needed.
496
+ async captchaChallenge(action: CaptchaAction): Promise<string | null> {
497
+ return captchaChallenge(this[STATE], action)
498
+ }
499
+
500
+ // Whether this session signed in or re-proved its user in the last ten minutes, as `exportData()` and the admin methods ask, for a page to show a form for `reprove` first.
501
+ async provedLately(): Promise<boolean> {
502
+ return provedLately(this[STATE])
503
+ }
504
+
505
+ // Re-proves the signed-in user, as before an app's own sensitive change: a proof counts for ten minutes, as a sign-in does.
506
+ async reprove(proof: Proof): Promise<ReproveResult> {
507
+ const proved = await reprove(this[STATE], proof)
508
+
509
+ return proved.ok ? { ok: true } : proved
510
+ }
511
+
512
+ // The scopes of the bearer token this request came with; null for a session, or a token with every scope.
513
+ async scopes(): Promise<string[] | null> {
514
+ await this.record()
515
+
516
+ return this.tokenScopes && [...this.tokenScopes]
517
+ }
518
+
519
+ // Whether this request may reach what `scope` guards: a session may, and a token given that scope or every one.
520
+ async hasScope(scope: Scope): Promise<boolean> {
521
+ return scopeAllows(await this.scopes(), scope)
522
+ }
523
+
524
+ // The ids of the users holding `role`, one of the `roles` option or a role above it in its hierarchy, banned users left out, for server code that tells them something (a notification). Needs a signed-in user, and reads the 10,000 newest users at most.
525
+ async userIdsHolding(role: string): Promise<string[]> {
526
+ if (await this.record() === null)
527
+ return []
528
+
529
+ const { isGranted } = roleHierarchy<string[], string>(this.core.hierarchy ?? {}, roles => roles)
530
+ const found: string[] = []
531
+
532
+ for (let offset = 0; offset < USER_SCAN_MAX; offset += USER_SCAN_PAGE) {
533
+ const { users } = await this.core.store.users.list({ offset, limit: USER_SCAN_PAGE, total: false })
534
+
535
+ for (const user of users) {
536
+ if (!banned(user) && isGranted(role, user.roles))
537
+ found.push(user.id)
538
+ }
539
+
540
+ if (users.length < USER_SCAN_PAGE)
541
+ break
542
+ }
543
+
544
+ return found
545
+ }
546
+
547
+ // The admin acting as the signed-in user, to show while they do; null otherwise.
548
+ async impersonator(): Promise<User | null> {
549
+ const signedIn = await this.session.get('auth')
550
+ const actor = signedIn?.impersonator && await this.core.store.users.get(signedIn.impersonator.user)
551
+
552
+ return actor ? linkedUser(this.core, actor) : null
553
+ }
554
+
555
+ // Under a new session id, so one planted before is worth nothing; `method` says how, for the `signed-in` event.
556
+ private async establish(record: UserRecord, method: string): Promise<void> {
557
+ const previous = await this.session.get('auth')
558
+ const remember = await this.session.get('authRemember')
559
+
560
+ // Signing in again, as another user or the same, replaces the sign-in this browser held.
561
+ if (previous?.session !== undefined)
562
+ await this.core.store.sessions.delete(previous.user, previous.session)
563
+
564
+ await this.session.unset('authChallenge')
565
+ await this.session.unset('authRemember')
566
+ await this.session.regenerate()
567
+
568
+ const session = await openSession(this.core, record, this[STATE].address, this[STATE].userAgent, await applyLifetime(this[STATE], remember))
569
+
570
+ await this.session.set('auth', { user: record.id, version: record.sessionVersion, at: Date.now(), session, ...method === 'passkey' && { passkey: true } })
571
+ this.source = 'session'
572
+ this.resolving = Promise.resolve(record)
573
+ // The mirrors of whoever held this browser before, an expired session's included, are emptied unless it was this person.
574
+ this.cookies.push(forgetLocalMirrors(this.request, record.id))
575
+ // Browser-only (`remember: false`) leaves it a session cookie like the session's; else it lasts as long as the session can, since the session's own cookie is renewed with use.
576
+ this.markBrowser(!record.guest, remember === false ? undefined : durationSeconds(this.session.settings.absoluteMaxAge, 'the session absoluteMaxAge'))
577
+ await noteSignIn(this[STATE], record)
578
+ await report(this[STATE], record, 'signed-in', method)
579
+ }
580
+
581
+ // Whether the sign-in's session is still on the user's list; one from before kayjs-auth kept them is put on it.
582
+ private async live(signedIn: SignedIn, record: UserRecord, stored: SessionRecord | undefined): Promise<boolean> {
583
+ if (signedIn.session !== undefined)
584
+ return liveSession(this[STATE], stored, record, this[STATE].address)
585
+
586
+ const session = await openSession(this.core, record, this[STATE].address, this[STATE].userAgent)
587
+
588
+ await this.session.set('auth', { ...signedIn, session })
589
+
590
+ return true
591
+ }
592
+
593
+ private async record(): Promise<UserRecord | null> {
594
+ if (!this.known || Date.now() - this.known.at > USER_FRESH_MS)
595
+ this.resolving = this.resolve()
596
+
597
+ return this.resolving!
598
+ }
599
+
600
+ private async resolve(): Promise<UserRecord | null> {
601
+ let signedIn = await this.session.get('auth')
602
+
603
+ // An impersonation past its half hour ends here, the admin back as themselves if their own sign-in still holds.
604
+ if (signedIn?.impersonator && signedIn.until !== undefined && Date.now() >= signedIn.until) {
605
+ await (await load.admin()).endImpersonation(this[STATE], signedIn, true)
606
+ signedIn = await this.session.get('auth')
607
+ // The browser is tagged as who it is again, so a local() mirror filled as the user is emptied.
608
+ this.cookies.push(forgetLocalMirrors(this.request, signedIn?.user))
609
+ }
610
+
611
+ // The user and their session do not depend on each other, so they are read together.
612
+ const [record, stored] = signedIn
613
+ ? await Promise.all([this.core.store.users.get(signedIn.user), signedIn.session === undefined ? undefined : this.core.store.sessions.get(signedIn.session)])
614
+ : []
615
+
616
+ if (record && record.sessionVersion === signedIn!.version && !banned(record) && await this.genuine(signedIn!) && await this.live(signedIn!, record, stored)) {
617
+ this.source = 'session'
618
+
619
+ return record
620
+ }
621
+
622
+ // Deleted, signed out everywhere since, banned, or its session ended.
623
+ if (signedIn) {
624
+ await this.session.unset('auth')
625
+ this.markBrowser(false)
626
+ }
627
+
628
+ const token = bearerToken(this.request)
629
+ const owner = token === undefined ? undefined : await (await load.bearer()).tokenUser(this.core, token, toolCall(this.request)?.from ?? this.request.url)
630
+
631
+ const live = owner && !banned(owner.record) ? owner : null
632
+
633
+ this.source = live ? 'bearer' : null
634
+ this.tokenScopes = live?.scopes ?? null
635
+
636
+ return live?.record ?? null
637
+ }
638
+
639
+ // Whether the admin behind an impersonation still is one, signed in as themselves, within its fixed lifetime; true when there is none.
640
+ private async genuine(signedIn: SignedIn): Promise<boolean> {
641
+ if (!signedIn.impersonator)
642
+ return true
643
+
644
+ if (signedIn.until !== undefined && Date.now() >= signedIn.until)
645
+ return false
646
+
647
+ const actor = await this.core.store.users.get(signedIn.impersonator.user)
648
+
649
+ return actor !== undefined && actor.sessionVersion === signedIn.impersonator.version && !banned(actor) && await (await load.admin()).isAdmin(this[STATE], actor)
650
+ }
651
+ }
652
+
653
+ export function authOf(ctx: object): Auth {
654
+ const auth = (ctx as { auth?: unknown }).auth
655
+
656
+ if (!(auth instanceof Auth))
657
+ throw new Error('kayjs-auth: no `auth` in this context; `.use(auth.plugin)` before the routes and pages that read it')
658
+
659
+ return auth as Auth
660
+ }
661
+
662
+ // The `Auth` of a request reaching the plugin, which it also names to kay's other libraries and to components reading the viewer.
663
+ export function requestAuth<Scope extends string, Role extends string, OrgRole extends string, UserData extends object>(ctx: { request: Request, server: Parameters<typeof clientAddress>[1] }, core: Core, proxy: KayConfig['proxy']): Auth<Scope, Role, OrgRole, UserData> {
664
+ const { session } = ctx as unknown as { session?: Session<AuthSessionData> }
665
+
666
+ // Elysia uses a plugin once per app, so a plugin of the app's own that used the session plugin first keeps it to itself, out of the routes auth reaches.
667
+ if (!session)
668
+ throw new Error('kayjs-auth: no session reaches this route. Use the session plugin on the app itself, or leave it to auth.plugin, rather than in a plugin of the app\'s own before auth.plugin')
669
+
670
+ core.settle()
671
+
672
+ const address = clientAddress(ctx.request, ctx.server, proxy)
673
+
674
+ pruneWhenDue(core, session.settings)
675
+
676
+ const auth = new Auth<Scope, Role, OrgRole, UserData>(session, core, ctx.request, core.keys.fingerprint(rateKey(address)), address)
677
+
678
+ // Lets other libraries, such as kayjs-ai counting a visitor, know the signed-in user without importing kayjs-auth; a guest costs nothing to mint, so it is not named and stays counted by address.
679
+ nameUser(ctx.request, async () => {
680
+ const user = await auth.bareUser()
681
+
682
+ return user && !user.guest ? user.id : undefined
683
+ })
684
+
685
+ registerViewer(ctx.request, { auth: auth as unknown as Auth, isGranted: (role, user) => core.access.isGranted(role, user.roles) })
686
+
687
+ return auth
688
+ }
689
+
690
+ // Who opened a websocket, read off the session cookie or bearer token its upgrade carried, which the plugin hands the socket as `ws.data.auth`, and read again past 30 seconds: null for an anonymous one, or a socket opened on an app without the plugin. A socket whose user is gone since, signed out, revoked or banned, is closed.
691
+ export async function socketUser(ws: { data?: unknown, close?: ((code?: number, reason?: string) => void) | undefined }): Promise<BareUser | null> {
692
+ const data = ws.data
693
+ const state = typeof data === 'object' && data !== null && 'auth' in data ? data.auth : undefined
694
+
695
+ if (!(state instanceof Auth))
696
+ return null
697
+
698
+ if (state[STATE].crossSite()) {
699
+ ws.close?.(SOCKET_USER_GONE, 'cross-site')
700
+
701
+ return null
702
+ }
703
+
704
+ const user = await state.bareUser()
705
+
706
+ if (user)
707
+ servedSockets.add(state)
708
+ else if (servedSockets.delete(state))
709
+ ws.close?.(SOCKET_USER_GONE, 'signed out')
710
+
711
+ return user
712
+ }