@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/failure.ts ADDED
@@ -0,0 +1,63 @@
1
+ import type { ErrorShape } from 'kay/library'
2
+
3
+ // What every auth result answers when it fails: the `ErrorShape` every result of kay and its libraries carries, with the kind the app branches on as `code` (`'signed-out'`, `'limited'`, `'not-found'`...).
4
+ export interface AuthFailure<Kind extends string = string> extends ErrorShape {
5
+ code: Kind
6
+ }
7
+
8
+ // A failed result, `error` holding the kind as `error.code`.
9
+ export type AuthFailed<Kind extends string = string> = Kind extends string ? { ok: false, error: AuthFailure<Kind> } : never
10
+
11
+ // A failed result for input rejected, `errors` holding a problem by field, also on `error.errors` as every failure has it.
12
+ export interface AuthRejected<Fields extends object> {
13
+ ok: false
14
+ error: AuthFailure<'invalid'>
15
+ errors: Fields
16
+ }
17
+
18
+ const STATUS: Readonly<Record<string, number>> = {
19
+ 'signed-out': 401,
20
+ 'invalid': 401,
21
+ 'stale': 401,
22
+ 'proof': 401,
23
+ 'two-factor-required': 401,
24
+ 'forbidden': 403,
25
+ 'banned': 403,
26
+ 'impersonating': 403,
27
+ 'self': 403,
28
+ 'admin': 403,
29
+ 'off': 404,
30
+ 'not-found': 404,
31
+ 'none': 404,
32
+ 'limited': 429,
33
+ 'unavailable': 503,
34
+ }
35
+
36
+ // Kinds that conflict with the state of the account or the organization.
37
+ const CONFLICTS = new Set(['last-owner', 'last-admin', 'last-way-in', 'slug-taken', 'taken', 'member', 'enabled', 'verified', 'signed-in', 'not-enabled', 'not-set-up', 'not-linked', 'unverified', 'not-pending'])
38
+
39
+ export function failureStatus(kind: string): number {
40
+ return STATUS[kind] ?? (CONFLICTS.has(kind) ? 409 : 400)
41
+ }
42
+
43
+ // A kind as a sentence: `last-owner` is `Last owner`.
44
+ export function failureMessage(kind: string): string {
45
+ return kind.charAt(0).toUpperCase() + kind.slice(1).replaceAll(/[-_]/g, ' ')
46
+ }
47
+
48
+ export function authFailure<Kind extends string>(code: Kind, errors: Record<string, string> = {}): AuthFailure<Kind> {
49
+ return { code, status: failureStatus(code), message: failureMessage(code), errors, data: undefined }
50
+ }
51
+
52
+ // The failed result of a kind: `{ ok: false, error: { code, status, message, errors, data } }`.
53
+ export function failed<Kind extends string>(code: Kind): AuthFailed<Kind> {
54
+ return { ok: false, error: authFailure(code) } as AuthFailed<Kind>
55
+ }
56
+
57
+ // The failed result of input rejected: the problems by field on `errors`, and on `error.errors` with the message of the first.
58
+ export function rejected<Fields extends object>(fields: Fields): AuthRejected<Fields> {
59
+ const errors = Object.fromEntries(Object.entries(fields).filter(([, problem]) => problem !== undefined).map(([field, problem]) => [field, typeof problem === 'string' ? problem : (problem as { message?: string }).message ?? String(problem)]))
60
+ const first = Object.entries(errors)[0]
61
+
62
+ return { ok: false, error: { ...authFailure('invalid', errors), status: 422, message: first === undefined ? 'Invalid' : `${failureMessage(first[0])} ${first[1]}`.trim() }, errors: fields }
63
+ }
@@ -0,0 +1,55 @@
1
+ import { configError } from 'kay/library'
2
+
3
+ // A domain, or several: the sites behind the proxy are on them or on their subdomains.
4
+ export type ForwardDomains = string | string[]
5
+
6
+ export interface ForwardAuthOptions {
7
+ domains: ForwardDomains
8
+ // Refuses a user without two-factor, sending them to set it up on the account page, instead of letting a password alone open the sites. Off by default.
9
+ requireTwoFactor?: boolean | undefined
10
+ }
11
+
12
+ export interface ForwardAuthCore {
13
+ domains: string[]
14
+ requireTwoFactor: boolean
15
+ }
16
+
17
+ const MAX_URL_LENGTH = 2048
18
+
19
+ // The domains `forwardAuth` names, each a hostname of two labels at least with no scheme, port or path, so one misspelt as `com` or `https://example.com/` stops the app at startup rather than opening a whole suffix or nothing. A public suffix of two labels (`co.uk`, `github.io`) passes: kay carries no suffix list, so naming the app's own domain is the app's to get right.
20
+ export function forwardOf(option: ForwardDomains | ForwardAuthOptions | undefined, twoFactor = true): ForwardAuthCore | undefined {
21
+ if (option === undefined)
22
+ return undefined
23
+
24
+ const { domains, requireTwoFactor = false } = typeof option === 'string' || Array.isArray(option) ? { domains: option } : option
25
+ const listed = (typeof domains === 'string' ? [domains] : domains).map(domain => domain.trim().toLowerCase())
26
+
27
+ if (listed.length === 0)
28
+ throw configError('auth', 'forwardAuth', '`forwardAuth` needs at least one domain: `forwardAuth: \'example.com\'`')
29
+
30
+ for (const domain of listed) {
31
+ const labels = domain.split('.')
32
+ const parsed = labels.length > 1 && labels.every(label => label !== '') ? URL.parse(`https://${domain}`) : null
33
+
34
+ if (parsed === null || parsed.hostname !== domain)
35
+ throw configError('auth', 'forwardAuth', `\`forwardAuth\` domain '${domain}' is not a hostname such as 'example.com': no scheme, port or path, and at least two labels`)
36
+ }
37
+
38
+ if (requireTwoFactor && !twoFactor)
39
+ throw configError('auth', 'forwardAuth', '`forwardAuth.requireTwoFactor` sends users to set two-factor up, which `twoFactor: false` switches off: turn one of them off')
40
+
41
+ return { domains: listed, requireTwoFactor }
42
+ }
43
+
44
+ // Where to send the visitor once signed in: an https URL on one of `domains` or their subdomains, as the browser normalised it, else nothing. Credentials in the URL, another scheme, a lookalike host and a URL of the portal's own sites all fall to nothing.
45
+ export function returnTarget(to: string | null | undefined, domains: string[]): string | undefined {
46
+ if (to === null || to === undefined || to === '' || to.length > MAX_URL_LENGTH)
47
+ return undefined
48
+
49
+ const url = URL.parse(to)
50
+
51
+ if (url === null || url.protocol !== 'https:' || url.username !== '' || url.password !== '')
52
+ return undefined
53
+
54
+ return domains.some(domain => url.hostname === domain || url.hostname.endsWith(`.${domain}`)) ? url.href : undefined
55
+ }
@@ -0,0 +1,68 @@
1
+ import type { BareUser, Core } from './core'
2
+ import type { ForwardAuthCore } from './forwardAuth'
3
+ import { siteRoot } from './authorize/metadata'
4
+ import { returnTarget } from './forwardAuth'
5
+
6
+ // Printable ASCII, which a header carries as it is.
7
+ const PLAIN_HEADER = /^[\u0020-\u007E]*$/
8
+
9
+ // What the route reads of the request's `auth`.
10
+ interface ForwardUser {
11
+ bareUser: () => Promise<BareUser | null>
12
+ via: () => Promise<'session' | 'bearer' | null>
13
+ }
14
+
15
+ // The URL the proxy was asked for: nginx's `X-Original-URL`, which the config sets to `$scheme://$http_host$request_uri`, else the `X-Forwarded-*` headers Traefik and Caddy send.
16
+ function requestedUrl(headers: Headers): string | null {
17
+ const given = headers.get('x-original-url')
18
+
19
+ if (given !== null)
20
+ return given
21
+
22
+ const host = headers.get('x-forwarded-host')
23
+
24
+ return host === null ? null : `${headers.get('x-forwarded-proto') ?? 'https'}://${host}${headers.get('x-forwarded-uri') ?? '/'}`
25
+ }
26
+
27
+ // A value a header carries: printable ASCII as it is, anything else percent-encoded, as a name with an accent or a line break would be refused or split by the proxy.
28
+ function headerValue(value: string): string {
29
+ return PLAIN_HEADER.test(value) ? value : encodeURIComponent(value.toWellFormed())
30
+ }
31
+
32
+ // The answer to the route a reverse proxy asks before it lets a request through to a site it guards.
33
+ export async function answerForward(ctx: { request: Request }, core: Core, forward: ForwardAuthCore, auth: ForwardUser, granted: (role: string, user: BareUser) => boolean, lacksTwoFactor: (user: BareUser) => Promise<boolean>): Promise<Response> {
34
+ const route = `${core.prefix}/forward`
35
+ const { request } = ctx
36
+ const { searchParams } = new URL(request.url)
37
+ // A guest costs nothing to make, and a bearer token opens no site: only a person's session does.
38
+ const user = await auth.bareUser()
39
+ const person = user !== null && !user.guest && await auth.via() === 'session' ? user : null
40
+ const headers = { 'cache-control': 'no-store' }
41
+
42
+ if (person !== null) {
43
+ const wanted = searchParams.getAll('role')
44
+
45
+ if (wanted.length > 0 && !wanted.some(role => granted(role, person)))
46
+ return new Response(null, { status: 403, headers })
47
+
48
+ // The same test as a sign-in's: the app's `twoFactor.require`, and everyone with `requireTwoFactor`; a passkey sign-in, or an admin acting as the user, satisfies it.
49
+ if (!await lacksTwoFactor(person)) {
50
+ const name = person.username ?? person.email ?? person.id
51
+
52
+ return new Response(null, { status: 204, headers: { ...headers, 'remote-user': headerValue(name), 'remote-name': headerValue(name), 'remote-email': headerValue(person.email ?? ''), 'remote-groups': headerValue(person.roles.join(',')) } })
53
+ }
54
+ }
55
+
56
+ const root = siteRoot(core, request)
57
+ const original = returnTarget(requestedUrl(request.headers), forward.domains)
58
+ // A signed-in user the second factor is missing for sets it up on the app's security page, where a passkey user adds an authenticator app, which the prebuilt pages have; without them there is nowhere to send them.
59
+ const setup = person !== null ? core.securityPage : undefined
60
+
61
+ if (person !== null && setup === undefined)
62
+ return new Response(null, { status: 403, headers })
63
+
64
+ const where = setup ?? `${core.signInPage}${original === undefined ? '' : `?redirect=${encodeURIComponent(`${route}/return?to=${encodeURIComponent(original)}`)}`}`
65
+
66
+ // A proxy that hands the answer to the browser as it is (Traefik, Caddy) wants the redirect itself; nginx's `auth_request` takes a 401 and its `Location`.
67
+ return new Response(null, { status: searchParams.get('redirect') === '1' ? 302 : 401, headers: { ...headers, location: `${root}${where}` } })
68
+ }
package/src/gate.ts ADDED
@@ -0,0 +1,104 @@
1
+ import type { DefinitionBase, Elysia, EphemeralType, MetadataBase, RouteBase, SingletonBase } from 'elysia'
2
+ import type { Level, PolicyContext, Requirement } from './types'
3
+ import { READ_METHODS } from 'kay/library'
4
+
5
+ const DECIDED = Symbol('auth.decided')
6
+
7
+ // The scope a route asks of a scoped bearer token, any one of a list, or false to let every token through.
8
+ export type ScopeRequirement<S extends string> = S | S[] | false
9
+
10
+ // What the gate needs wired in: who is asking and whether they may.
11
+ export interface GateDeps<P, G extends string, S extends string = string> {
12
+ principal: (ctx: object) => Promise<P | null>
13
+ authorize: (principal: P | null, requirement: Requirement<P, G>, level: Level, ctx: PolicyContext) => Promise<boolean>
14
+ // Whether a principal who met the requirement is refused all the same, with a 403: for a condition of the principal rather than of the route, such as a missing second factor.
15
+ refuse?: ((ctx: object, principal: P) => Promise<boolean>) | undefined
16
+ // Applied to routes with no `auth:`, so a route that forgets one stays closed.
17
+ defaultRequirement: Requirement<P, G>
18
+ // The scopes of the bearer token a request came with; null for a session, or a token with every scope.
19
+ scopes?: ((ctx: object) => Promise<readonly string[] | null>) | undefined
20
+ // Applied to routes with no `scope:`; without it a scoped token passes only routes naming one of its scopes.
21
+ defaultScope?: ScopeRequirement<S> | undefined
22
+ }
23
+
24
+ // The slice of the Elysia context the gate reads, plus the stamps it leaves on it, each gate's own under its own symbols.
25
+ interface GateContext<P, G extends string> extends PolicyContext {
26
+ request: Request
27
+ set: { status?: number | string }
28
+ [DECIDED]?: Set<Requirement<P, G>>
29
+ [stamp: symbol]: unknown
30
+ }
31
+
32
+ // Whether `scopes`, a token's, meet what a route asks; a session, or a token with every scope, meets anything.
33
+ export function scopeAllows(scopes: readonly string[] | null, wanted: ScopeRequirement<string> | undefined): boolean {
34
+ if (scopes === null || wanted === false)
35
+ return true
36
+
37
+ return wanted !== undefined && [wanted].flat().some(scope => scopes.includes(scope))
38
+ }
39
+
40
+ // The macro only stamps the route's requirement; one local beforeHandle enforces it, so routes added through `group`, `guard`, `use`, `route`, `all` or `ws` fall back to `defaultRequirement` too.
41
+ // Routes of the instance it is used on take `auth: <Requirement>` to override the default and `auth: false` to opt out, and `scope:` for what a scoped bearer token needs. Answers 401 to an anonymous caller and 403 to a signed-in one who is denied.
42
+ export function authGate<P, G extends string, S extends string = string>(deps: GateDeps<P, G, S>) {
43
+ // Generic over the app's own types, so what it holds already, such as `auth`, reaches the routes after it.
44
+ return <Base extends string, Single extends SingletonBase, Defs extends DefinitionBase, Meta extends MetadataBase, Routes extends RouteBase, Eph extends EphemeralType, Vol extends EphemeralType>(app: Elysia<Base, Single, Defs, Meta, Routes, Eph, Vol>) => {
45
+ // Elysia runs a route's `auth:` through the nearest gate's macro only, while every enclosing gate's hook runs: stamped under this gate's own symbols, the route's choice binds this gate alone, and the gates around it keep their own requirement.
46
+ const ownRequirement = Symbol('auth.requirement')
47
+ const ownScope = Symbol('auth.scope')
48
+ const gated = app
49
+ .macro({
50
+ auth: (requirement: Requirement<P, G> | false | undefined) => ({
51
+ transform(ctx: object) {
52
+ (ctx as GateContext<P, G>)[ownRequirement] = requirement ?? deps.defaultRequirement
53
+ },
54
+ }),
55
+ scope: (scope: ScopeRequirement<S> | undefined) => ({
56
+ transform(ctx: object) {
57
+ if (scope !== undefined)
58
+ (ctx as GateContext<P, G>)[ownScope] = scope
59
+ },
60
+ }),
61
+ })
62
+
63
+ // Hooked as a plain instance: the hook changes no type, and the app's own make its context too deep to check.
64
+ const plain = gated as unknown as Elysia
65
+
66
+ plain.onBeforeHandle({ as: 'local' }, async (context) => {
67
+ const ctx = context as unknown as GateContext<P, G>
68
+ const requirement = (ctx[ownRequirement] as Requirement<P, G> | false | undefined) ?? deps.defaultRequirement
69
+
70
+ if (requirement === false)
71
+ return undefined
72
+
73
+ // A route nested in two gated instances runs this once per gate: each holds it to its own requirement, and a requirement already met is not asked again.
74
+ if (!ctx[DECIDED]?.has(requirement)) {
75
+ const user = await deps.principal(ctx)
76
+ const level: Level = READ_METHODS.has(ctx.request.method) ? 'read' : 'write'
77
+
78
+ if (!(await deps.authorize(user, requirement, level, { params: ctx.params, body: ctx.body, query: ctx.query }))) {
79
+ ctx.set.status = user === null ? 401 : 403
80
+
81
+ return user === null ? 'Unauthorized' : 'Forbidden'
82
+ }
83
+
84
+ if (user !== null && await deps.refuse?.(ctx, user)) {
85
+ ctx.set.status = 403
86
+
87
+ return 'Forbidden'
88
+ }
89
+
90
+ (ctx[DECIDED] ??= new Set()).add(requirement)
91
+ }
92
+
93
+ if (deps.scopes && !scopeAllows(await deps.scopes(ctx), (ctx[ownScope] as ScopeRequirement<string> | undefined) ?? deps.defaultScope)) {
94
+ ctx.set.status = 403
95
+
96
+ return 'Forbidden'
97
+ }
98
+
99
+ return undefined
100
+ })
101
+
102
+ return gated
103
+ }
104
+ }
package/src/guard.ts ADDED
@@ -0,0 +1,22 @@
1
+ import type { Auth, AuthRequirement } from './auth'
2
+ import { guard as kayGuard } from 'kay'
3
+
4
+ /** What `authGuard()` takes, as `auth.guard()` does: where an anonymous visitor goes, the requirement a user meets and the scope a token holds, and whether two-factor is asked of the user (see `twoFactor.require`). */
5
+ export interface GuardOptions {
6
+ redirect?: string | undefined
7
+ require?: AuthRequirement<string> | undefined
8
+ scope?: string | string[] | false | undefined
9
+ twoFactor?: true | undefined
10
+ }
11
+
12
+ // The `auth.guard()` of the app's `auth()`, for a `_guard.ts` with no module to import it from: `export default authGuard()`. It asks the `auth` of the request, so it works with a `authCore` of the app's own too.
13
+ export function authGuard(options: GuardOptions = {}) {
14
+ return kayGuard<{ auth: Auth }>(async (ctx) => {
15
+ const { auth } = ctx.locals
16
+
17
+ if (typeof auth?.guarded !== 'function')
18
+ throw new Error('kayjs-auth: no `auth` in this context; add auth() to kay.config.ts, or `.use(auth.plugin)` before the routes')
19
+
20
+ await auth.guarded(ctx, options)
21
+ })
22
+ }
package/src/guards.ts ADDED
@@ -0,0 +1,72 @@
1
+ import type { Guard } from 'kay'
2
+ import type { BareUser, Core } from './core'
3
+ import type { ScopeRequirement } from './gate'
4
+ import type { AuthRequirement } from './request'
5
+ import type { PolicyContext, Predicate } from './types'
6
+ import { READ_METHODS } from 'kay/library'
7
+ import { guardPageOf, isNavigation, withBack } from './core'
8
+ import { authGate, scopeAllows } from './gate'
9
+ import { load } from './load'
10
+ import { authOf, STATE } from './request'
11
+ import { lacksTwoFactor, sendToEnrolment } from './requiredTwoFactor'
12
+
13
+ export interface RouteGuardOptions<Role extends string, Scope extends string> {
14
+ redirect?: string | undefined
15
+ require?: AuthRequirement<Role> | undefined
16
+ scope?: ScopeRequirement<Scope> | undefined
17
+ // true asks every user this guard lets through for two-factor; left out, `twoFactor.require` of the app decides. The security page and the second-factor page are never held back, whatever guard runs.
18
+ twoFactor?: true | undefined
19
+ }
20
+
21
+ const signedIn: Predicate<BareUser> = user => user !== null
22
+
23
+ // A `_guard.ts` default export. An anonymous GET or HEAD that may be a page opening (not a browser fetch, nor a request for JSON) goes to `redirect`, the prebuilt sign-in page with `pages`, else `signInPage`, with where they were going as `?redirect=`, or gets a 401 without any, as does any post; a user who does not meet `require` gets a 403.
24
+ // A scoped bearer token passes only with one of `scope`. A user lacking a two-factor the app asks of them (`twoFactor`) goes to the security page when opening a page, else gets a 403.
25
+ export function guardOf<Role extends string, Scope extends string>(core: Core, options: RouteGuardOptions<Role, Scope> = {}): Guard {
26
+ const redirect = options.redirect === undefined || options.redirect === '' ? guardPageOf(core) : options.redirect
27
+
28
+ return async (ctx) => {
29
+ const user = await authOf(ctx.locals).bareUser()
30
+ const reading = READ_METHODS.has(ctx.request.method)
31
+
32
+ if (!user) {
33
+ if (redirect !== undefined && isNavigation(ctx.request))
34
+ // kay-allow external-redirect: `redirect` is the app's own sign-in page, the visited path rides in its query
35
+ ctx.redirect(withBack(redirect, ctx.url.pathname + ctx.url.search))
36
+
37
+ ctx.deny(401, 'Sign in to continue')
38
+ }
39
+
40
+ // kay before 1.23 gives a guard no params, and `memberOf` then refuses rather than skip the check.
41
+ if (options.require !== undefined && !(await core.access.authorize(user, options.require, reading ? 'read' : 'write', { params: ctx.params })))
42
+ ctx.deny(403)
43
+
44
+ if (!scopeAllows(await authOf(ctx.locals).scopes(), options.scope))
45
+ ctx.deny(403)
46
+
47
+ if (user !== null && await lacksTwoFactor(authOf(ctx.locals)[STATE], user, { wanted: options.twoFactor, path: ctx.url.pathname, locale: ctx.locale, ctx: { params: ctx.params } }))
48
+ sendToEnrolment(core, ctx.request, ctx)
49
+ }
50
+ }
51
+
52
+ // The gate of `auth.gate()`, before the plugin is used on the instance it closes.
53
+ export function gateOf<Role extends string, Scope extends string>(core: Core, options: { require?: AuthRequirement<Role>, scope?: ScopeRequirement<Scope> }) {
54
+ return authGate<BareUser, Role, Scope>({
55
+ principal: async ctx => authOf(ctx).bareUser(),
56
+ authorize: core.access.authorize,
57
+ // A user lacking the two-factor the app asks of them is denied like one missing a role, bar the library's own enrolment pages.
58
+ refuse: async (ctx, user) => lacksTwoFactor(authOf(ctx)[STATE], user, { path: new URL((ctx as { request: Request }).request.url).pathname, ctx: { params: (ctx as PolicyContext).params, body: (ctx as PolicyContext).body, query: (ctx as PolicyContext).query } }),
59
+ defaultRequirement: options.require ?? signedIn,
60
+ scopes: async ctx => authOf(ctx).scopes(),
61
+ defaultScope: options.scope,
62
+ })
63
+ }
64
+
65
+ // A requirement met by a member of the organization the route's `param` names, by id or slug, holding `role` there when given: `auth: auth.memberOf('admin')`.
66
+ export function memberOf<OrgRole extends string>(core: Core, role?: OrgRole, options: { param?: string } = {}): Predicate<BareUser> {
67
+ return async (user, ctx) => {
68
+ const ref: unknown = ctx.params?.[options.param ?? core.organizations?.param ?? 'org']
69
+
70
+ return user !== null && typeof ref === 'string' && (await load.organizations()).holdsInOrganization(core, user.id, ref, role)
71
+ }
72
+ }
package/src/guesses.ts ADDED
@@ -0,0 +1,99 @@
1
+ import type { LimitSet } from './limits'
2
+ import type { RequestState } from './state'
3
+ import type { UserRecord } from './store'
4
+ import { comparePasswords, hashPassword } from '@kaynooo/utils'
5
+ import { limitRefused } from 'kay/library'
6
+ import { afterResponse } from './events'
7
+ import { randomToken } from './keys'
8
+ import { forget, reached, spend, tally, windowOf } from './limits'
9
+ import { securityNotice } from './securityNotice'
10
+
11
+ // The counts one password guess is held to: a hard stop for this client on this account, and a looser ceiling for the account from every client together.
12
+ export interface Guess {
13
+ // Forgotten when the password proves right: this client's own failures and the guesses of this burst still in flight.
14
+ keys: { key: string, limit: LimitSet }[]
15
+ // The wrong guesses of every client on the account, which a right password does not give back.
16
+ failures: string
17
+ limit: LimitSet
18
+ }
19
+
20
+ // Counts a guess at an account's password before the password is checked, so a burst of parallel guesses cannot all pass a count that only a failure would raise; `forgive` takes it back once the password proves right.
21
+ // The hard stop is per client, so someone failing at an email cannot keep its holder out from another address. Without a record the count is kept against what was typed, so a missing account runs out the same way.
22
+ export async function startGuess(state: RequestState, record: UserRecord | undefined, typed: string): Promise<Guess | 'limited'> {
23
+ const { core, client } = state
24
+ const { rates } = core
25
+ const ceiling = core.limits.signInAccountAll
26
+ const account = record ? record.id : core.keys.fingerprint(typed.toLowerCase())
27
+ // A record's id and a digest never share a prefix with the other, whatever the app's ids look like.
28
+ const kind = record ? 'id' : 'typed'
29
+ const hard = `sign-in-account:${kind}:${account}\n${client}`
30
+ const pending = `sign-in-ceiling:${kind}:${account}`
31
+ const failures = `sign-in-failures:${kind}:${account}`
32
+
33
+ if (await spend(rates, hard, core.limits.signInAccount))
34
+ return 'limited'
35
+
36
+ // `pending` is every guess since the last right password, so a burst in parallel stops at the ceiling; `failures` is what the ceiling is spent on.
37
+ if (await spend(rates, pending, ceiling) || await reached(rates, failures, ceiling)) {
38
+ if (record)
39
+ await mailLockout(state, record)
40
+
41
+ return 'limited'
42
+ }
43
+
44
+ return { keys: [{ key: hard, limit: core.limits.signInAccount }, { key: pending, limit: ceiling }], failures, limit: ceiling }
45
+ }
46
+
47
+ // Counts a wrong password against the account's ceiling, which no right password gives back.
48
+ export async function failGuess(state: RequestState, guess: Guess): Promise<void> {
49
+ await tally(state.core.rates, guess.failures, guess.limit)
50
+ }
51
+
52
+ // A right password costs this client and the burst in flight nothing: the guesses they hold are forgotten, but not the failures of other clients, so signing in does not hand an attacker a fresh ceiling.
53
+ export async function forgive(state: RequestState, guess: Guess): Promise<void> {
54
+ for (const { key, limit } of guess.keys)
55
+ await forget(state.core.rates, key, limit)
56
+ }
57
+
58
+ // Mails the holder that signing in is paused, at most once a day however often the lockout comes back, so guessing cannot flood their inbox.
59
+ export async function mailLockout(state: RequestState, record: UserRecord): Promise<void> {
60
+ if ((await state.core.rates(windowOf(86_400_000)).hit(`sign-in-locked-mail:${record.id}`)).count === 1)
61
+ await afterResponse('reporting a sign-in lockout', async () => securityNotice(state, record, 'sign-in-locked'))
62
+ }
63
+
64
+ let decoy: Promise<string> | undefined
65
+
66
+ // Spends as long on an account without a password as on a wrong one, so the time taken tells nothing either.
67
+ export async function passwordMatches(record: UserRecord | undefined, password: string): Promise<boolean> {
68
+ if (record?.passwordHash != null && record.passwordHash !== '')
69
+ return comparePasswords(password, record.passwordHash)
70
+
71
+ decoy ??= hashPassword(randomToken())
72
+ await comparePasswords(password, await decoy)
73
+
74
+ return false
75
+ }
76
+
77
+ // Counts one sign-in guess at the second factor, per client and per account, and says whether it is past the cap.
78
+ // Only the first guess past the account's cap mails the holder, and at most once a day, as for passwords.
79
+ export async function secondFactorLimited(state: RequestState, record: UserRecord): Promise<boolean> {
80
+ const { rates, limits } = state.core
81
+
82
+ if (await spend(rates, `two-factor:${state.client}`, limits.twoFactor))
83
+ return true
84
+
85
+ const key = `two-factor:${record.id}`
86
+ const { count: guesses, beside, over } = await tally(rates, key, limits.twoFactorAccount)
87
+ const { max } = limits.twoFactorAccount[0]
88
+
89
+ if (over)
90
+ limitRefused('kayjs-auth', over.limit, { key, wait: over.wait })
91
+
92
+ if (guesses <= max)
93
+ return beside
94
+
95
+ if (guesses === max + 1)
96
+ await mailLockout(state, record)
97
+
98
+ return true
99
+ }
package/src/index.ts ADDED
@@ -0,0 +1,46 @@
1
+ export type { ChangePasswordResult, ChangeUsernameResult, DeleteAccountResult, UnlinkResult, UpdateLocaleResult } from './account'
2
+ export type { AdminAuditLogResult, AdminChangeFailure, AdminFailure, BanResult, DeleteResult, GetUserResult, ImpersonateResult, ListUsersResult, ManagedUser, RoleResult, UnbanResult } from './admin'
3
+ export { auditWording, describeAuditEntry } from './auditWording'
4
+ export type { AuditPhrase, AuditWording } from './auditWording'
5
+ export * from './auth'
6
+ export type { ApprovedClient, RevokeGrantResult } from './authorize/grants'
7
+ export type { AuthorizeOutcome, AuthorizeParams, ConsentFields, DecideResult } from './authorize/request'
8
+ export type { BearerToken, CreateTokenResult, IssueTokenResult, RevokeTokenResult, TokenOptions } from './bearer'
9
+ export { pwnedPassword } from './breached'
10
+ export { hcaptcha, hcaptchaWidget, proofOfWork, turnstile, turnstileWidget } from './captcha'
11
+ export type { AuthProofOfWorkOptions, CaptchaAction, CaptchaCheck, CaptchaContext, CaptchaOptions, CaptchaRules, CaptchaWidget, ProofOfWorkCaptcha } from './captcha'
12
+ export * from './decide'
13
+ export type { Device } from './device'
14
+ export type { ChangeEmailResult, CodedLink, CodeMode, CodeResult, EmailOptions, LinkResult, MailRequestResult, PendingEmailCode, ResetPasswordResult, SendVerificationResult, VerifyEmailResult } from './email'
15
+ export type { DeletionImpact } from './erase'
16
+ export type { ActivityEvent, AuditEntry, AuthEvent, AuthEventInfo, AuthHookContext, EventContext, EventFields } from './events'
17
+ export type { DataExport, ExportResult } from './export'
18
+ export type { AuthFailed, AuthFailure, AuthRejected } from './failure'
19
+ export * from './gate'
20
+ export { authGuard } from './guard'
21
+ export type { GuardOptions } from './guard'
22
+ export { sealTotpSecret } from './keys'
23
+ export { DEFAULT_LIMITS } from './limits'
24
+ export type { AuthRateLimit, LimitOption, Limits, LimitsOption } from './limits'
25
+ export { defaultTemplates, frenchTemplates, lifetime } from './mail'
26
+ export type { AuthMailer, AuthMailMessage, MailContent, MailData, MailingSubscription, MailKind, SecurityEvent, Templates } from './mail'
27
+ export * from './memoryStore'
28
+ export * from './oauth'
29
+ export type { LinkProviderResult, OAuthFailure } from './oauth/flow'
30
+ export type { AcceptResult, AuthMember, CreateOrganizationResult, DeleteOrganizationResult, Invitation, InviteResult, ListInvitationsResult, ListMembersResult, MemberResult, Membership, Organization, OrganizationFailure, OrganizationsOptions, OrganizationWriteFailure, RejectInvitationResult, RevokeInvitationResult, UpdateOrganizationResult } from './organizations'
31
+ export type { AuthHooks, OwnOptions, PresetApp, StoreUrl } from './own'
32
+ export { auth } from './pages'
33
+ export type { AuthExtensionOptions, AuthFeatures, AuthModule, AuthPages, AuthPagesConfig, AuthPagesOptions, PluginOf, ProfileField, ProfileFieldView, ProfileOptions, ProfileProblem } from './pages'
34
+ export type { Passkey, PasskeyOptionsResult, PasskeySignInResult, RegisterPasskeyResult, RenamePasskeyResult, RevokePasskeyResult } from './passkeys'
35
+ export type { CreateUserInput, CreateUserResult, PasswordSignInInput, PasswordSignInResult, RegisterErrors, RegisterInput, RegisterResult } from './password'
36
+ export { passkeyAssertion, passkeyAttestation } from './payloads'
37
+ export type { SaveProfileResult } from './profile'
38
+ export type { Proof, ProofFailure, ReproveResult } from './proof'
39
+ export type { AuthRates } from './rates'
40
+ export * from './roles'
41
+ export type { GuestSignInResult, RevokeSessionResult, UserSession } from './sessions'
42
+ export type { SignInOptions } from './signInOptions'
43
+ export * from './store'
44
+ export type { DisableTwoFactorResult, EnableTwoFactorResult, RecoveryCodesResult, SetUpTwoFactorResult, TotpEnrolment, TwoFactorResult, TwoFactorSetup } from './twoFactor'
45
+ export * from './types'
46
+ export * from './wsAuth'
package/src/keys.ts ADDED
@@ -0,0 +1,51 @@
1
+ import { Buffer } from 'node:buffer'
2
+ import { createHash, createHmac, hkdfSync, randomBytes } from 'node:crypto'
3
+ import { configError, GENERATE_SECRET, MIN_SECRET_LENGTH, openWith, sealWith, weakSecrets } from 'kay/library'
4
+
5
+ const KEY_BYTES = 32
6
+
7
+ export interface Keys {
8
+ // AES-256-GCM, bound to `context` (such as the row it is stored in) so a value moved to another row no longer opens.
9
+ encrypt: (text: string, context: string) => string
10
+ // The text, or undefined when no secret in the list opens it.
11
+ decrypt: (value: string, context: string) => string | undefined
12
+ // A keyed digest, for values that must be compared but never read back, such as where a sign-in came from.
13
+ fingerprint: (text: string) => string
14
+ }
15
+
16
+ // Each use gets its own key derived from the secret, so what one use gives away says nothing of another. A list rotates secrets: the first writes, every one reads.
17
+ export function deriveKeys(secret: string | string[]): Keys {
18
+ const secrets = [secret].flat()
19
+
20
+ if (weakSecrets(secrets))
21
+ throw configError('auth', 'secret', `a secret is at least ${MIN_SECRET_LENGTH} characters; generate one with ${GENERATE_SECRET}`)
22
+
23
+ const derive = (purpose: string) => secrets.map(value => Buffer.from(hkdfSync('sha256', value, '', `kayjs-auth ${purpose}`, KEY_BYTES)))
24
+ const encryption = derive('encryption')
25
+ const fingerprint = derive('fingerprint')[0]!
26
+
27
+ return {
28
+ encrypt: (text, context) => sealWith(encryption[0]!, text, context),
29
+ decrypt: (value, context) => openWith(encryption, value, context)?.text,
30
+ fingerprint: text => createHmac('sha256', fingerprint).update(text).digest('base64url'),
31
+ }
32
+ }
33
+
34
+ // How a random token is stored: a plain digest is enough for a value with this much entropy, and needs no secret to look it up.
35
+ export function digest(token: string): string {
36
+ return createHash('sha256').update(token).digest('base64url')
37
+ }
38
+
39
+ // 32 random bytes, as URL-safe text.
40
+ export function randomToken(): string {
41
+ return randomBytes(32).toString('base64url')
42
+ }
43
+
44
+ export function totpContext(userId: string): string {
45
+ return `totp:${userId}`
46
+ }
47
+
48
+ // A TOTP secret sealed as kayjs-auth stores it, for a store whose rows hold plain ones from before: it seals each on read. `secret` is the value `authCore` takes, a list included.
49
+ export function sealTotpSecret(secret: string | string[], userId: string, plain: string): string {
50
+ return deriveKeys(secret).encrypt(plain, totpContext(userId))
51
+ }