@kayjs/auth 0.0.0-stage → 1.104.2

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/limits.ts ADDED
@@ -0,0 +1,182 @@
1
+ import type { RateLimit, RateWindow } from 'kay'
2
+ import type { Core } from './core'
3
+ import type { AuthLimiters } from './rates'
4
+ import { configError, durationSeconds, limitRefused } from 'kay/library'
5
+
6
+ // `max` attempts every `window`, a string such as '15m', as in kay's own `rateLimit`, counted in `store` when given. kayjs-auth counts under keys of its own, so it takes no `key`.
7
+ // A `rateLimit()` object is not taken: its counter is under the client's address, where kayjs-auth counts under keys of its own. `onLimit` is told of each attempt refused.
8
+ export type AuthRateLimit = Omit<RateLimit, 'key'> & { hit?: never, enforce?: never }
9
+
10
+ // The limits of one bucket once resolved: the first, which the lockouts read `max` of, and the others counted beside it.
11
+ export type LimitSet = [AuthRateLimit, ...AuthRateLimit[]]
12
+
13
+ // Loose per client address, which an office or a carrier may share, and tight per account, which only one person guesses at.
14
+ // Wrong passwords only count: `signInAccount` is tight per client and account, so it never keeps the holder out, and `signInAccountAll` is the looser ceiling on the account from every client together.
15
+ export const DEFAULT_LIMITS = {
16
+ signIn: { max: 40, window: '15m' },
17
+ signInAccount: { max: 6, window: '15m' },
18
+ signInAccountAll: { max: 60, window: '15m' },
19
+ register: { max: 6, window: '1h' },
20
+ // Each of these mails a way into an account, so none may flood an inbox someone else owns.
21
+ resend: { max: 12, window: '1h' },
22
+ resendAccount: { max: 3, window: '1h' },
23
+ forgot: { max: 12, window: '1h' },
24
+ forgotAccount: { max: 3, window: '1h' },
25
+ magicLink: { max: 12, window: '1h' },
26
+ magicLinkAccount: { max: 3, window: '1h' },
27
+ emailChange: { max: 12, window: '1h' },
28
+ emailChangeAccount: { max: 5, window: '1h' },
29
+ // A six-digit code is guessed in minutes without these: they are what makes the second factor strong.
30
+ twoFactor: { max: 30, window: '15m' },
31
+ twoFactorAccount: { max: 8, window: '15m' },
32
+ // Re-proving is a password guess like any other.
33
+ reprove: { max: 6, window: '15m' },
34
+ // Guesses at an emailed code, on top of the few misses each code takes.
35
+ emailCode: { max: 30, window: '15m' },
36
+ emailCodeAccount: { max: 10, window: '15m' },
37
+ // Each invitation mails an inbox someone else owns, with the organization's name in it: neither one manager nor many may flood one.
38
+ invite: { max: 30, window: '1h' },
39
+ inviteAddress: { max: 5, window: '1d' },
40
+ // Each organization is a row and a slug nobody else can take, so one account may not mint them without end.
41
+ organization: { max: 10, window: '1d' },
42
+ // An export walks every table the app's exportData reads, so asking for one again and again is not free.
43
+ export: { max: 6, window: '1h' },
44
+ // Registering a client writes a row for anyone who asks, and reading a client's metadata document makes a request for them.
45
+ oauthRegister: { max: 20, window: '1h' },
46
+ oauthDocument: { max: 30, window: '15m' },
47
+ // Loose, as a client refreshes its token for every user behind one address; a wrong code or refresh token is hopeless to guess.
48
+ oauthToken: { max: 300, window: '15m' },
49
+ // Guessing a token is hopeless; this keeps trying from being free.
50
+ link: { max: 40, window: '1h' },
51
+ } satisfies Record<string, AuthRateLimit>
52
+
53
+ // `oauthRegisterAll` has no default: one address cannot use up a budget every other client shares, so it is a ceiling an app chooses to add on all addresses together.
54
+ export type Limits = Record<keyof typeof DEFAULT_LIMITS, AuthRateLimit> & { oauthRegisterAll?: AuthRateLimit }
55
+
56
+ // A limit as the app writes it, alone or in a list that is each counted apart.
57
+ export type LimitOption = AuthRateLimit | AuthRateLimit[]
58
+
59
+ // The limits `rateLimit` overrides, the rest keeping their defaults.
60
+ export type LimitsOption = Partial<Record<keyof Limits, LimitOption>>
61
+
62
+ export type ResolvedLimits = Record<keyof typeof DEFAULT_LIMITS, LimitSet> & { oauthRegisterAll?: LimitSet }
63
+
64
+ // The defaults over what the app set in `rateLimit`; a bad limit throws naming it.
65
+ export function resolveLimits(given: LimitsOption | undefined): ResolvedLimits {
66
+ const limits = Object.fromEntries(Object.entries(DEFAULT_LIMITS).map(([name, limit]) => [name, [limit]])) as unknown as ResolvedLimits
67
+
68
+ for (const [name, option] of Object.entries(given ?? {}) as [keyof Limits, LimitOption | undefined][]) {
69
+ if (!option)
70
+ continue
71
+
72
+ const list = [option].flat()
73
+
74
+ if (list.length === 0)
75
+ throw configError('auth', 'rateLimit', `rateLimit.${name} is an empty list; give it a limit or leave it out`)
76
+
77
+ for (const [index, limit] of list.entries()) {
78
+ const place = list.length === 1 ? `rateLimit.${name}` : `rateLimit.${name}[${index}]`
79
+
80
+ durationSeconds(limit.window, `${place}.window`)
81
+
82
+ if (limit.store !== undefined && typeof limit.store?.hit !== 'function')
83
+ throw configError('auth', 'rateLimit', `${place}.store has no hit(key, window) method; give it a RateStore`)
84
+
85
+ if (limit.onLimit !== undefined && typeof limit.onLimit !== 'function')
86
+ throw configError('auth', 'rateLimit', `${place}.onLimit is not a function; give it a function of the refusal`)
87
+
88
+ if (typeof (limit as { hit?: unknown }).hit === 'function')
89
+ throw configError('auth', 'rateLimit', `${place} is a rateLimit() object, which counts under the client's address; kayjs-auth counts under keys of its own, so give it { max, window, store?, onLimit? }`)
90
+ }
91
+
92
+ limits[name] = list.map(({ max, window, store, onLimit }) => ({ max, window, store, onLimit })) as LimitSet
93
+ }
94
+
95
+ return limits
96
+ }
97
+
98
+ // Counts one attempt against each limit of the bucket and answers whether any was over.
99
+ // The attempt is refused once whatever the number of limits it is over: the one with the longest wait is told to `onLimit`.
100
+ export async function spend(rates: AuthLimiters, key: string, limits: LimitSet): Promise<boolean> {
101
+ let worst: { limit: AuthRateLimit, wait: number } | undefined
102
+
103
+ for (const [index, limit] of limits.entries()) {
104
+ const wait = await rates(limit).enforce(apart(key, index))
105
+
106
+ if (wait !== undefined && (!worst || wait > worst.wait))
107
+ worst = { limit, wait }
108
+ }
109
+
110
+ if (worst)
111
+ limitRefused('kayjs-auth', worst.limit, { key, wait: worst.wait })
112
+
113
+ return worst !== undefined
114
+ }
115
+
116
+ // The attempts counted under `key` in the first limit's open window, none once it ended.
117
+ export async function counted(rates: AuthLimiters, key: string, limits: LimitSet): Promise<number> {
118
+ return (await rates(limits[0]).peek(key))?.count ?? 0
119
+ }
120
+
121
+ // Counts one attempt without refusing it, in each limit of the bucket: the first's window, which the caller compares to `max`, whether any of the others is over, and the one with the longest wait it is over, for the caller to tell `onLimit` if it refuses.
122
+ export async function tally(rates: AuthLimiters, key: string, limits: LimitSet): Promise<RateWindow & { beside: boolean, over: { limit: AuthRateLimit, wait: number } | undefined }> {
123
+ const first = await rates(limits[0]).hit(key)
124
+ let beside = false
125
+ let over = first.count > limits[0].max ? { limit: limits[0], wait: secondsTo(first.resetAt) } : undefined
126
+
127
+ for (const [index, limit] of limits.entries()) {
128
+ if (index === 0)
129
+ continue
130
+
131
+ const window = await rates(limit).hit(apart(key, index))
132
+
133
+ if (window.count > limit.max) {
134
+ beside = true
135
+
136
+ if (!over || secondsTo(window.resetAt) > over.wait)
137
+ over = { limit, wait: secondsTo(window.resetAt) }
138
+ }
139
+ }
140
+
141
+ return { ...first, beside, over }
142
+ }
143
+
144
+ // Forgets the count under `key` in each limit of the bucket.
145
+ export async function forget(rates: AuthLimiters, key: string, limits: LimitSet): Promise<void> {
146
+ for (const [index, limit] of limits.entries())
147
+ await rates(limit).reset(apart(key, index))
148
+ }
149
+
150
+ // The first limit counts under the key itself, the others under their place in the list, in front of it as no key of the library starts with `#`.
151
+ function apart(key: string, index: number): string {
152
+ return index === 0 ? key : `#${index}:${key}`
153
+ }
154
+
155
+ // Whether the count under `key` has reached `max` in any limit of the bucket, told once to `onLimit` for the first. Called only where the request is refused for it, after a `spend` that did not refuse.
156
+ export async function reached(rates: AuthLimiters, key: string, limits: LimitSet): Promise<boolean> {
157
+ for (const [index, limit] of limits.entries()) {
158
+ const window = await rates(limit).peek(apart(key, index))
159
+
160
+ if (window && window.count >= limit.max) {
161
+ limitRefused('kayjs-auth', limit, { key, wait: secondsTo(window.resetAt) })
162
+
163
+ return true
164
+ }
165
+ }
166
+
167
+ return false
168
+ }
169
+
170
+ function secondsTo(resetAt: number): number {
171
+ return Math.max(1, Math.ceil((resetAt - Date.now()) / 1000))
172
+ }
173
+
174
+ // A limit that only names a window in milliseconds, for a count nothing is refused by.
175
+ export function windowOf(ms: number): AuthRateLimit {
176
+ return { max: Number.MAX_SAFE_INTEGER, window: `${ms}ms` }
177
+ }
178
+
179
+ // The key counting attempts against what a visitor typed, such as an address: kept as a keyed digest, so the table holds no email.
180
+ export function typedKey(core: Core, scope: string, typed: string): string {
181
+ return `${scope}:${core.keys.fingerprint(typed)}`
182
+ }
package/src/load.ts ADDED
@@ -0,0 +1,18 @@
1
+ // Each feature's module, read when a request first reaches it: an app that leaves a feature off, or never calls it, never loads it.
2
+ export const load = {
3
+ account: async () => import('./account'),
4
+ admin: async () => import('./admin'),
5
+ bearer: async () => import('./bearer'),
6
+ deletion: async () => import('./deletion'),
7
+ email: async () => import('./email'),
8
+ erase: async () => import('./erase'),
9
+ profile: async () => import('./profile'),
10
+ exports: async () => import('./export'),
11
+ flow: async () => import('./oauth/flow'),
12
+ grants: async () => import('./authorize/grants'),
13
+ organizations: async () => import('./organizations'),
14
+ passkeys: async () => import('./passkeys'),
15
+ password: async () => import('./password'),
16
+ request: async () => import('./authorize/request'),
17
+ twoFactor: async () => import('./twoFactor'),
18
+ }
package/src/locale.ts ADDED
@@ -0,0 +1,15 @@
1
+ import { matchLocale } from 'kay/library'
2
+
3
+ export { acceptedLocales, validLocale } from 'kay/library'
4
+
5
+ // The first of `available` matching a wanted tag, exactly or by its language alone, else the first of `available`.
6
+ export function pickLocale(available: readonly string[], wanted: readonly (string | null | undefined)[]): string {
7
+ return matchLocale(available, wanted.filter((tag): tag is string => typeof tag === 'string' && tag !== '')) ?? available[0]!
8
+ }
9
+
10
+ // The language of a tag alone, lowercase: `pt` for `pt-BR`.
11
+ export function language(tag: string): string {
12
+ const end = tag.indexOf('-')
13
+
14
+ return (end === -1 ? tag : tag.slice(0, end)).toLowerCase()
15
+ }
package/src/log.ts ADDED
@@ -0,0 +1,4 @@
1
+ import { logFrom } from 'kay'
2
+
3
+ // Where kayjs-auth reports what it catches and goes on from: where the app's `log` setting sends kay's own messages, under the request being answered.
4
+ export const log = logFrom('kayjs-auth')
package/src/mail.ts ADDED
@@ -0,0 +1,225 @@
1
+ import type { Duration } from 'kay'
2
+ import type { AuthLinkKind, AuthMailData, AuthMailKind, AuthMailWording, AuthNoticeKind } from 'kay/library/auth-mails'
3
+ import type { EmailCore, EmailOptions } from './email'
4
+ import { within } from '@kaynooo/utils/promise'
5
+ import { configError, durationWords, escapeHtml as escape, siteLocales, trackDetached } from 'kay/library'
6
+ import { AUTH_LINK_KINDS, AUTH_MAIL_WORDING, AUTH_NOTICE_KINDS } from 'kay/library/auth-mails'
7
+ import { language, pickLocale } from './locale'
8
+ import { log } from './log'
9
+
10
+ // A change to what protects an account, mailed to its verified address and given to `onEvent`.
11
+ export type SecurityEvent = AuthNoticeKind
12
+
13
+ // What a mail is about: a link to follow, news of a change to the account, an invitation to join an organization, or a registration for an address that has an account already.
14
+ export type MailKind = AuthMailKind
15
+
16
+ export interface MailContent {
17
+ subject: string
18
+ text: string
19
+ html: string
20
+ }
21
+
22
+ // A mail for the app's mailer to send: `subject`, `text` and `html` are filled from the templates, and `kind`, `name`, `detail` and `url` let an app with its own templating ignore them.
23
+ export interface AuthMailMessage extends MailContent {
24
+ to: string
25
+ kind: MailKind
26
+ // The site's name, as the templates write it.
27
+ name: string
28
+ // The organization an invitation is to, or the provider, passkey, token or new address an event is about.
29
+ detail?: string
30
+ url?: string
31
+ // The code to type instead of following `url`, when the app sends codes.
32
+ code?: string
33
+ // The language it is written in, one of the `locales` option's.
34
+ locale: string
35
+ // How long its link and its code work, for the ones it carries, as durations such as `'24h'`.
36
+ maxAge?: { link?: Duration, code?: Duration } | undefined
37
+ }
38
+
39
+ // One address on one mailing list, as kayjs-mail's `subscriptions` answers it.
40
+ export interface MailingSubscription {
41
+ list: string
42
+ status: 'pending' | 'confirmed'
43
+ askedAt: Date
44
+ confirmedAt: Date | null
45
+ }
46
+
47
+ export interface AuthMailer {
48
+ // Awaited, its result ignored, so a queue's enqueue fits as it is.
49
+ send: (mail: AuthMailMessage) => unknown
50
+ // Takes an address off the mailing lists and out of the queue when an account is erased: kayjs-mail's `mail.erase`, which `auth()` hands over when kayjs-mail is in the app.
51
+ erase?: ((address: string) => unknown) | undefined
52
+ // What an address is on, for the export of a user's data: kayjs-mail's `mail.subscriptions`.
53
+ subscriptions?: ((address: string) => Promise<MailingSubscription[]>) | undefined
54
+ }
55
+
56
+ // What a template is given, the data kayjs-mail's views render from too.
57
+ export type MailData = AuthMailData
58
+
59
+ export type Templates = Record<MailKind, (data: MailData) => MailContent>
60
+
61
+ const PLACEHOLDER = /\{(\w+)\}/g
62
+
63
+ // Fills the placeholders of a mail's lines of the shared wording.
64
+ function filler(words: AuthMailWording, data: MailData): (line: string) => string {
65
+ const values: Record<string, string> = { site: data.name, email: data.email, detail: data.detail ?? '', what: data.url === undefined ? words.code : words.link }
66
+
67
+ return line => line.replace(PLACEHOLDER, (placeholder, name: string) => Object.hasOwn(values, name) ? values[name]! : placeholder)
68
+ }
69
+
70
+ // The two plain shells, link and notice, of kayjs-auth's own mails, for a mailer other than kayjs-mail's `authMailer`, whose views render them themed. Both parts always: a mail with text only trips spam filters, and one with HTML only is unreadable where HTML is refused. Inline styles only, since mail clients drop stylesheets.
71
+ // A link mail may carry a link, a code to type, or both.
72
+ function linkMail(words: AuthMailWording, data: MailData, subject: string, lead: string, button: string, ending: string): MailContent {
73
+ const url = data.url === undefined ? undefined : escape(data.url)
74
+ const codeLead = data.url === undefined ? words.yourCode : words.orTypeCode
75
+ const text = [lead, data.url, data.code === undefined ? undefined : `${codeLead} ${data.code}`, ending].filter(part => part !== undefined).join('\n\n')
76
+
77
+ return {
78
+ subject,
79
+ text,
80
+ html: `<div lang="${escape(data.locale)}" style="font-family:system-ui,sans-serif;max-width:520px;margin:0 auto;padding:24px;color:#1a1a1a">
81
+ <p style="font-size:16px;line-height:1.5;margin:0 0 20px">${escape(lead)}</p>${url === undefined
82
+ ? ''
83
+ : `
84
+ <p style="margin:0 0 20px"><a href="${url}" style="display:inline-block;padding:12px 20px;background:#1a1a1a;color:#ffffff;text-decoration:none;border-radius:6px">${escape(button)}</a></p>
85
+ <p style="font-size:13px;line-height:1.5;color:#555555;margin:0 0 12px">${escape(words.orPaste)}<br><span style="word-break:break-all">${url}</span></p>`}${data.code === undefined
86
+ ? ''
87
+ : `
88
+ <p style="font-size:13px;line-height:1.5;color:#555555;margin:0 0 4px">${escape(codeLead)}</p>
89
+ <p style="font-size:28px;letter-spacing:6px;font-family:ui-monospace,monospace;margin:0 0 20px">${escape(data.code)}</p>`}
90
+ <p style="font-size:13px;line-height:1.5;color:#555555;margin:0">${escape(ending)}</p>
91
+ </div>`,
92
+ }
93
+ }
94
+
95
+ // A lifetime, a duration such as `'24h'`, as words in a language: `24 hours`, `7 days`, `1 heure`, from kay's `durationWords`.
96
+ export function lifetime(duration: Duration, locale: string): string {
97
+ if (typeof duration === 'number')
98
+ throw configError('auth', 'lifetime', `lifetime() takes a duration with its unit, such as '24h' or '90s', not ${String(duration)}; ${String(duration)} seconds is '${String(duration)}s'`)
99
+
100
+ return durationWords(duration, locale)
101
+ }
102
+
103
+ // How long what the mail carries works, a magic link being usable once.
104
+ function lasting(words: AuthMailWording, data: MailData, once: boolean): string {
105
+ const { link, code } = data.maxAge ?? {}
106
+ const linkWorks = data.url === undefined || link === undefined ? undefined : words.linkWorks.replace('{duration}', () => lifetime(link, data.locale) + (once ? words.once : ''))
107
+ const codeWorks = data.code === undefined || code === undefined ? undefined : words.codeWorks.replace('{duration}', () => lifetime(code, data.locale))
108
+
109
+ return [linkWorks, codeWorks].filter(part => part !== undefined).join(' ')
110
+ }
111
+
112
+ // With a `url`, a link to where the user reviews what happened, such as the list of where they are signed in.
113
+ function noticeMail(words: AuthMailWording, data: MailData, subject: string, lead: string, ending: string): MailContent {
114
+ return {
115
+ subject,
116
+ text: [lead, data.url === undefined ? undefined : `${words.review} ${data.url}`, ending].filter(part => part !== undefined).join('\n\n'),
117
+ html: `<div lang="${escape(data.locale)}" style="font-family:system-ui,sans-serif;max-width:520px;margin:0 auto;padding:24px;color:#1a1a1a">
118
+ <p style="font-size:16px;line-height:1.5;margin:0 0 20px">${escape(lead)}</p>${data.url === undefined
119
+ ? ''
120
+ : `
121
+ <p style="font-size:14px;line-height:1.5;margin:0 0 20px">${escape(words.review)} <a href="${escape(data.url)}" style="color:#1a1a1a">${escape(data.url)}</a></p>`}
122
+ <p style="font-size:13px;line-height:1.5;color:#555555;margin:0">${escape(ending)}</p>
123
+ </div>`,
124
+ }
125
+ }
126
+
127
+ // A link mail says how long it works before its ending, unless its `lasts` is empty, as for an invitation; the figure is the one kayjs-auth sends, `lasts` itself being the fallback text of kayjs-mail's views.
128
+ function linkTemplate(words: AuthMailWording, kind: AuthLinkKind): Templates[MailKind] {
129
+ const lines = words[kind]
130
+
131
+ return (data) => {
132
+ const fill = filler(words, data)
133
+ const ending = fill(lines.ending)
134
+
135
+ return linkMail(words, data, fill(lines.subject), fill(lines.lead), lines.button, lines.lasts === '' ? ending : `${lasting(words, data, kind === 'magic-link')} ${ending}`)
136
+ }
137
+ }
138
+
139
+ function noticeTemplate(words: AuthMailWording, kind: AuthNoticeKind): Templates[MailKind] {
140
+ const lines = words[kind]
141
+
142
+ return (data) => {
143
+ const fill = filler(words, data)
144
+
145
+ return noticeMail(words, data, fill(lines.subject), fill(lines.lead), fill(lines.ending))
146
+ }
147
+ }
148
+
149
+ function templatesIn(words: AuthMailWording): Templates {
150
+ return Object.fromEntries([...AUTH_LINK_KINDS.map(kind => [kind, linkTemplate(words, kind)]), ...AUTH_NOTICE_KINDS.map(kind => [kind, noticeTemplate(words, kind)])]) as Templates
151
+ }
152
+
153
+ // kayjs-auth's own templates by language, the wording it shares with kayjs-mail, English for any other.
154
+ export const builtInTemplates: Record<string, Templates> = Object.fromEntries(Object.entries(AUTH_MAIL_WORDING).map(([lang, words]) => [lang, templatesIn(words)]))
155
+
156
+ export const defaultTemplates: Templates = builtInTemplates.en!
157
+
158
+ export const frenchTemplates: Templates = builtInTemplates.fr!
159
+
160
+ // How long a notice mail may stay with the mailer before it is given up on, and how many may be with it at once: a relay that hangs costs memory for at most this many mails, the rest being logged and dropped.
161
+ const ASIDE_TIMEOUT_MS = 30_000
162
+ const LATE = Symbol('late')
163
+ const ASIDE_MAX = 200
164
+ let aside = 0
165
+ // Whether the drop in the current burst is logged already: one line says it, and the next burst, once room is back, says it again.
166
+ let dropping = false
167
+
168
+ // Sends the mail `build` makes without making the request wait on the mailer: a slow or down relay costs the response nothing, and a failure, a sync throw included, is logged. The mail is handed to the mailer before the first await, so a mailer that answers at once has it by the time this returns. A mailer silent for 30 seconds is given up on, and with 200 mails waiting on it a new one is dropped.
169
+ export function sendAside(email: EmailCore, build: () => AuthMailMessage, what: string): void {
170
+ if (aside >= ASIDE_MAX) {
171
+ if (!dropping)
172
+ log.error(`mailing ${what} dropped, and the mails sent aside after it while ${ASIDE_MAX} are waiting on the mailer`)
173
+
174
+ dropping = true
175
+
176
+ return
177
+ }
178
+
179
+ dropping = false
180
+ aside++
181
+ trackDetached((async () => {
182
+ try {
183
+ if (await within(Promise.resolve(email.mailer.send(build())), ASIDE_TIMEOUT_MS, LATE) === LATE)
184
+ throw new Error(`no answer from the mailer in ${ASIDE_TIMEOUT_MS / 1000} s`)
185
+ }
186
+ catch (error) {
187
+ log.error(`mailing ${what} failed`, error)
188
+ }
189
+ finally {
190
+ aside--
191
+ }
192
+ })())
193
+ }
194
+
195
+ // The language to write in for a reader wanting `wanted`, most wanted first, and its templates.
196
+ export function writing(email: EmailCore, wanted: readonly (string | null | undefined)[]): { locale: string, templates: Templates } {
197
+ const locale = pickLocale(email.locales, wanted)
198
+
199
+ return { locale, templates: email.templates[locale]! }
200
+ }
201
+
202
+ // Each of `locales` with kayjs-auth's templates in its language, `templates` over them and its translation over both.
203
+ export function localeTemplates(locales: readonly string[], templates: Partial<Templates> = {}, translations: Record<string, Partial<Templates>> = {}): Record<string, Templates> {
204
+ return Object.fromEntries(locales.map(locale => [locale, { ...builtInTemplates[language(locale)] ?? defaultTemplates, ...templates, ...translations[locale] }]))
205
+ }
206
+
207
+ // The languages mails are written in and their templates: `locales` as given, else the site's own, which a server knows once it set up, so an auth made while the app's modules load asks again at each use; the templates are built again only when the languages change.
208
+ export function mailLanguages(email: Pick<EmailOptions, 'locales' | 'templates' | 'translations'>): { locales: () => string[], templates: () => Record<string, Templates> } {
209
+ const given = email.locales !== undefined && email.locales.length > 0 ? [...email.locales] : undefined
210
+ let built: { key: string, templates: Record<string, Templates> } | undefined
211
+ const locales = (): string[] => given ?? [...siteLocales()]
212
+
213
+ return {
214
+ locales,
215
+ templates: () => {
216
+ const now = locales()
217
+ const key = now.join('\n')
218
+
219
+ if (built?.key !== key)
220
+ built = { key, templates: localeTemplates(now, email.templates, email.translations) }
221
+
222
+ return built.templates
223
+ },
224
+ }
225
+ }