@kayjs/auth 1.104.3 → 1.105.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (206) hide show
  1. package/llms/admin-and-organizations.md +8 -8
  2. package/llms/admin-pages.md +2 -2
  3. package/llms/grouped-methods.md +33 -17
  4. package/llms/hardening-and-testing.md +9 -9
  5. package/llms/oauth-passkeys-two-factor.md +13 -13
  6. package/llms/oauth-providers.md +1 -1
  7. package/llms/oauth-server-and-tokens.md +7 -7
  8. package/llms/passwords-and-mails.md +12 -12
  9. package/llms/sessions-and-guards.md +9 -1
  10. package/llms/setup.md +6 -6
  11. package/llms/signed-in-components.md +20 -11
  12. package/llms.txt +1 -1
  13. package/package.json +9 -5
  14. package/src/account.ts +6 -15
  15. package/src/admin.ts +9 -25
  16. package/src/auth.ts +9 -6
  17. package/src/authorize/clients.ts +1 -1
  18. package/src/authorize/grants.ts +2 -4
  19. package/src/authorize/request.ts +2 -4
  20. package/src/bearer.ts +5 -11
  21. package/src/captcha.ts +5 -3
  22. package/src/components/sign-in-link.kay +19 -0
  23. package/src/components/sign-out-button.kay +17 -0
  24. package/src/components/signed-in.kay +7 -2
  25. package/src/components/user-menu.kay +11 -8
  26. package/src/context.ts +1 -1
  27. package/src/deletion.ts +2 -4
  28. package/src/email.ts +16 -28
  29. package/src/erase.ts +5 -4
  30. package/src/export.ts +2 -4
  31. package/src/failure.ts +37 -9
  32. package/src/guard.ts +8 -1
  33. package/src/guards.ts +12 -5
  34. package/src/index.ts +14 -16
  35. package/src/limits.ts +97 -5
  36. package/src/mail.ts +5 -3
  37. package/src/memoryStore.ts +6 -6
  38. package/src/messages/fr.ts +1 -0
  39. package/src/methods/account.ts +30 -14
  40. package/src/methods/admin.ts +31 -14
  41. package/src/methods/captcha.ts +18 -0
  42. package/src/methods/email.ts +16 -7
  43. package/src/methods/magicLink.ts +5 -5
  44. package/src/methods/oauth.ts +16 -7
  45. package/src/methods/oauthServer.ts +32 -6
  46. package/src/methods/organizations.ts +51 -20
  47. package/src/methods/passkeys.ts +13 -7
  48. package/src/methods/password.ts +10 -10
  49. package/src/methods/proof.ts +22 -0
  50. package/src/methods/sessions.ts +3 -2
  51. package/src/methods/tokens.ts +17 -5
  52. package/src/methods/twoFactor.ts +10 -10
  53. package/src/oauth/flow.ts +2 -4
  54. package/src/oauthTest.ts +8 -4
  55. package/src/organizations.ts +12 -30
  56. package/src/organizationsCore.ts +1 -1
  57. package/src/own.ts +17 -15
  58. package/src/pages/components/frame.kay +3 -3
  59. package/src/pages/components/passkey-add.kay +2 -2
  60. package/src/pages/components/passkey-sign-in.kay +2 -2
  61. package/src/pages/components/passkey-two-factor.kay +2 -2
  62. package/src/pages/components/provider-buttons.kay +1 -1
  63. package/src/pages/forms.ts +6 -6
  64. package/src/pages/index.ts +9 -8
  65. package/src/pages/routes/account/clients.kay +2 -2
  66. package/src/pages/routes/account/connections.kay +4 -4
  67. package/src/pages/routes/account/data.kay +7 -7
  68. package/src/pages/routes/account/index.kay +15 -15
  69. package/src/pages/routes/account/organizations/[org].kay +15 -15
  70. package/src/pages/routes/account/organizations/index.kay +5 -5
  71. package/src/pages/routes/account/security.kay +15 -15
  72. package/src/pages/routes/account/tokens.kay +4 -4
  73. package/src/pages/routes/admin/_layout.kay +1 -1
  74. package/src/pages/routes/admin/audit.kay +1 -1
  75. package/src/pages/routes/admin/users/[id].kay +11 -11
  76. package/src/pages/routes/confirm-email.kay +3 -3
  77. package/src/pages/routes/invitation.kay +8 -8
  78. package/src/pages/routes/magic-link.kay +3 -3
  79. package/src/pages/routes/oauth/authorize.kay +2 -2
  80. package/src/pages/routes/register.kay +4 -4
  81. package/src/pages/routes/reset-password.kay +6 -6
  82. package/src/pages/routes/sign-in.kay +10 -10
  83. package/src/pages/routes/two-factor.kay +4 -4
  84. package/src/pages/routes/verify-email.kay +8 -8
  85. package/src/passkeys.ts +10 -21
  86. package/src/password.ts +8 -11
  87. package/src/pg.ts +3 -3
  88. package/src/profile.ts +1 -3
  89. package/src/proof.ts +3 -5
  90. package/src/request.ts +77 -46
  91. package/src/requiredTwoFactor.ts +2 -2
  92. package/src/routes.ts +2 -2
  93. package/src/sessions.ts +3 -7
  94. package/src/setup.ts +6 -4
  95. package/src/sqlite.ts +6 -0
  96. package/src/test.ts +15 -3
  97. package/src/testHelpers.ts +16 -7
  98. package/src/testHook.ts +31 -0
  99. package/src/testing.ts +5 -4
  100. package/src/twoFactor.ts +9 -18
  101. package/src/viewer.ts +26 -4
  102. package/types/account.d.ts +10 -23
  103. package/types/account.d.ts.map +1 -1
  104. package/types/admin.d.ts +21 -39
  105. package/types/admin.d.ts.map +1 -1
  106. package/types/auth.d.ts +18 -5
  107. package/types/auth.d.ts.map +1 -1
  108. package/types/authorize/grants.d.ts +2 -5
  109. package/types/authorize/grants.d.ts.map +1 -1
  110. package/types/authorize/request.d.ts +3 -5
  111. package/types/authorize/request.d.ts.map +1 -1
  112. package/types/bearer.d.ts +9 -17
  113. package/types/bearer.d.ts.map +1 -1
  114. package/types/captcha.d.ts +3 -1
  115. package/types/captcha.d.ts.map +1 -1
  116. package/types/context.d.ts +1 -1
  117. package/types/deletion.d.ts +2 -5
  118. package/types/deletion.d.ts.map +1 -1
  119. package/types/email.d.ts +23 -28
  120. package/types/email.d.ts.map +1 -1
  121. package/types/erase.d.ts.map +1 -1
  122. package/types/export.d.ts +3 -5
  123. package/types/export.d.ts.map +1 -1
  124. package/types/failure.d.ts +22 -3
  125. package/types/failure.d.ts.map +1 -1
  126. package/types/guard.d.ts +2 -0
  127. package/types/guard.d.ts.map +1 -1
  128. package/types/guards.d.ts +2 -1
  129. package/types/guards.d.ts.map +1 -1
  130. package/types/index.d.ts +14 -16
  131. package/types/index.d.ts.map +1 -1
  132. package/types/limits.d.ts +57 -1
  133. package/types/limits.d.ts.map +1 -1
  134. package/types/mail.d.ts +5 -0
  135. package/types/mail.d.ts.map +1 -1
  136. package/types/messages/fr.d.ts +1 -0
  137. package/types/methods/account.d.ts +27 -13
  138. package/types/methods/account.d.ts.map +1 -1
  139. package/types/methods/admin.d.ts +39 -15
  140. package/types/methods/admin.d.ts.map +1 -1
  141. package/types/methods/captcha.d.ts +9 -0
  142. package/types/methods/captcha.d.ts.map +1 -0
  143. package/types/methods/email.d.ts +21 -7
  144. package/types/methods/email.d.ts.map +1 -1
  145. package/types/methods/magicLink.d.ts +9 -4
  146. package/types/methods/magicLink.d.ts.map +1 -1
  147. package/types/methods/oauth.d.ts +12 -7
  148. package/types/methods/oauth.d.ts.map +1 -1
  149. package/types/methods/oauthServer.d.ts +13 -5
  150. package/types/methods/oauthServer.d.ts.map +1 -1
  151. package/types/methods/organizations.d.ts +40 -15
  152. package/types/methods/organizations.d.ts.map +1 -1
  153. package/types/methods/passkeys.d.ts +18 -7
  154. package/types/methods/passkeys.d.ts.map +1 -1
  155. package/types/methods/password.d.ts +23 -10
  156. package/types/methods/password.d.ts.map +1 -1
  157. package/types/methods/proof.d.ts +12 -0
  158. package/types/methods/proof.d.ts.map +1 -0
  159. package/types/methods/sessions.d.ts +3 -2
  160. package/types/methods/sessions.d.ts.map +1 -1
  161. package/types/methods/tokens.d.ts +12 -5
  162. package/types/methods/tokens.d.ts.map +1 -1
  163. package/types/methods/twoFactor.d.ts +22 -10
  164. package/types/methods/twoFactor.d.ts.map +1 -1
  165. package/types/oauth/flow.d.ts +4 -6
  166. package/types/oauth/flow.d.ts.map +1 -1
  167. package/types/oauthTest.d.ts +2 -0
  168. package/types/oauthTest.d.ts.map +1 -1
  169. package/types/organizations.d.ts +24 -48
  170. package/types/organizations.d.ts.map +1 -1
  171. package/types/own.d.ts +1 -1
  172. package/types/own.d.ts.map +1 -1
  173. package/types/pages/forms.d.ts +5 -3
  174. package/types/pages/forms.d.ts.map +1 -1
  175. package/types/pages/index.d.ts +5 -2
  176. package/types/pages/index.d.ts.map +1 -1
  177. package/types/passkeys.d.ts +20 -27
  178. package/types/passkeys.d.ts.map +1 -1
  179. package/types/password.d.ts +13 -20
  180. package/types/password.d.ts.map +1 -1
  181. package/types/profile.d.ts +1 -4
  182. package/types/profile.d.ts.map +1 -1
  183. package/types/proof.d.ts +1 -4
  184. package/types/proof.d.ts.map +1 -1
  185. package/types/request.d.ts +33 -7
  186. package/types/request.d.ts.map +1 -1
  187. package/types/requiredTwoFactor.d.ts +3 -1
  188. package/types/requiredTwoFactor.d.ts.map +1 -1
  189. package/types/routes.d.ts +3 -1
  190. package/types/routes.d.ts.map +1 -1
  191. package/types/sessions.d.ts +3 -10
  192. package/types/sessions.d.ts.map +1 -1
  193. package/types/setup.d.ts.map +1 -1
  194. package/types/sqlite.d.ts +3 -0
  195. package/types/sqlite.d.ts.map +1 -0
  196. package/types/test.d.ts +4 -1
  197. package/types/test.d.ts.map +1 -1
  198. package/types/testHelpers.d.ts +1 -0
  199. package/types/testHelpers.d.ts.map +1 -1
  200. package/types/testHook.d.ts +15 -0
  201. package/types/testHook.d.ts.map +1 -0
  202. package/types/testing.d.ts.map +1 -1
  203. package/types/twoFactor.d.ts +10 -21
  204. package/types/twoFactor.d.ts.map +1 -1
  205. package/types/viewer.d.ts +3 -1
  206. package/types/viewer.d.ts.map +1 -1
@@ -1,21 +1,24 @@
1
1
  ---
2
+ import type { JSX } from 'kay'
2
3
  import { ctx } from 'kay'
3
4
  import { localize } from 'kay/i18n'
4
5
  import { wording } from 'kay/words'
5
- import Button from '@kayjs/ui/button.kay'
6
6
  import { currentViewer } from '../viewer'
7
+ import SignInLink from './sign-in-link.kay'
8
+ import SignOutButton from './sign-out-button.kay'
7
9
 
8
- // `account={false}` leaves out the link to the account page, as the account page itself does.
9
- const { account = true } = props<{ account?: boolean }>()
10
+ // `account={false}` leaves out the link to the account page, as the account page itself does, and `signIn={false}` the sign-in link a visitor sees. `redirect` is where a sign-out goes; children follow the account link; attributes go on the wrapper.
11
+ const { account = true, signIn = true, redirect, ...rest } = props<Omit<JSX.IntrinsicElements['div'], 'class'> & { account?: boolean, signIn?: boolean, redirect?: string | undefined }>()
10
12
  const features = currentViewer().auth.features()
11
13
  const accountPage = features.pages ? localize(`${features.pages.prefix}/account`) : null
12
- const home = localize(features.pages?.home ?? '/')
13
14
  ---
14
15
  if ctx.user then found
15
- .kayjs-auth.flex.flex-wrap.items-center.gap-3
16
+ .kayjs-auth.flex.flex-wrap.items-center.gap-3(part="root" {...rest})
16
17
  span.text-muted {found.username ?? found.email}
17
18
  if account && accountPage
18
19
  a(href={accountPage}) {wording('auth.account.title', 'Your account')}
19
- form(method="post" action={`${features.prefix}/sign-out`})
20
- input(type="hidden" name="redirect" value={home})
21
- Button(type="submit" label={wording('auth.account.signOut', 'Sign out')})
20
+ slot
21
+ SignOutButton(redirect={redirect})
22
+ else if signIn
23
+ .kayjs-auth.flex.flex-wrap.items-center.gap-3(part="root" {...rest})
24
+ SignInLink
package/src/context.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { defineContext } from 'kay/library'
1
+ import { defineContext } from 'kay/server'
2
2
  import { viewerValues } from './viewer'
3
3
 
4
4
  // The request values kayjs-auth gives every template as `ctx`, `ctx.user` and `ctx.can(role)`, read ahead of the pages reaching a template that reads `ctx`.
package/src/deletion.ts CHANGED
@@ -1,6 +1,6 @@
1
1
  import type { Duration } from 'kay'
2
2
  import type { Core } from './core'
3
- import type { AuthFailed } from './failure'
3
+ import type { Result } from './failure'
4
4
  import type { RequestState } from './state'
5
5
  import type { UserRecord } from './store'
6
6
  import { report } from './events'
@@ -16,8 +16,6 @@ export interface AccountOptions {
16
16
  cancelPage?: string | undefined
17
17
  }
18
18
 
19
- export type CancelDeletionResult = { ok: true } | AuthFailed<'signed-out' | 'not-pending'>
20
-
21
19
  // Where the mailed link leads: the app's own page, else the prebuilt account data page.
22
20
  function cancelPageOf(core: Core): string {
23
21
  return core.deletion?.cancelPage ?? pagePaths(core.pages?.prefix ?? core.prefix).data
@@ -62,7 +60,7 @@ function mailCancelLink(state: RequestState, record: UserRecord, deleteAt: Date)
62
60
  }
63
61
 
64
62
  // Takes the pending mark off the signed-in user, and tells them.
65
- export async function cancelDeletion(state: RequestState): Promise<CancelDeletionResult> {
63
+ export async function cancelDeletion(state: RequestState): Promise<Result<object, 'signed-out' | 'not-pending'>> {
66
64
  const record = await state.current()
67
65
 
68
66
  if (!record)
package/src/email.ts CHANGED
@@ -1,6 +1,6 @@
1
1
  import type { Duration } from 'kay'
2
2
  import type { Core } from './core'
3
- import type { AuthFailed, AuthRejected } from './failure'
3
+ import type { AuthFailed, Result } from './failure'
4
4
  import type { AuthMailer, MailData, Templates } from './mail'
5
5
  import type { Proof, ProofFailure } from './proof'
6
6
  import type { EmailProblem, PasswordProblem } from './rules'
@@ -68,23 +68,10 @@ export interface PendingCode {
68
68
  expires: number
69
69
  }
70
70
 
71
- export type CodeResult = { ok: true, redirect: string } | AuthFailed<'invalid' | 'expired' | 'limited' | 'banned'>
72
-
73
71
  // Sent whether or not an account has that address, so the answer tells nothing of which ones exist.
74
- export type MailRequestResult = { ok: true } | AuthFailed<'limited' | 'captcha' | 'unavailable'>
75
-
76
- export type LinkResult = { ok: true, redirect: string } | AuthFailed<'invalid' | 'limited' | 'banned'>
77
-
78
- export type VerifyEmailResult = LinkResult | AuthFailed<'confirm'>
79
-
80
- export type ResetPasswordResult = LinkResult | AuthRejected<{ password: PasswordProblem | 'breached' }>
81
-
82
- export type ChangeEmailResult = { ok: true } | AuthFailed<ProofFailure | 'unavailable'> | AuthRejected<{ email: EmailProblem | 'taken' | 'unchanged' }>
83
-
84
- export type SendVerificationResult = MailRequestResult | AuthFailed<'signed-out' | 'verified'>
85
72
 
86
73
  // Mails a new verification link to the signed-in user or, with nobody signed in, off the response's path to the account this browser registered or proved the password of.
87
- export async function sendVerification(state: RequestState): Promise<SendVerificationResult> {
74
+ export async function sendVerification(state: RequestState): Promise<Result<object, 'limited' | 'captcha' | 'unavailable' | 'signed-out' | 'verified'>> {
88
75
  const current = await state.current()
89
76
  const registered = current ? undefined : await state.session.get('authRegistered')
90
77
  const record = current ?? (registered === undefined ? undefined : await state.core.store.users.get(registered))
@@ -120,7 +107,7 @@ export async function sendVerification(state: RequestState): Promise<SendVerific
120
107
 
121
108
  // Verifies the address for the browser signed in as the account, the one that registered it or the one that proved its password; any other must give the account's password, since whoever opens the mail may be confirming an account a stranger registered with their address, which verified would stay the stranger's.
122
109
  // Never signs in. Refused, the link stays usable where it can be confirmed.
123
- export async function verifyEmail(state: RequestState, token: string, password?: string): Promise<VerifyEmailResult> {
110
+ export async function verifyEmail(state: RequestState, token: string, password?: string): Promise<Result<{ redirect: string }, 'invalid' | 'limited' | 'banned' | 'confirm'>> {
124
111
  const spent = await spendLink(state, token, 'verify-email')
125
112
 
126
113
  if (!spent.ok)
@@ -179,12 +166,12 @@ async function holdsPassword(state: RequestState, record: UserRecord, password:
179
166
  return true
180
167
  }
181
168
 
182
- export async function requestPasswordReset(state: RequestState, email: string, captcha?: string, redirect?: string): Promise<MailRequestResult> {
169
+ export async function requestPasswordReset(state: RequestState, email: string, captcha?: string, redirect?: string): Promise<Result<object, 'limited' | 'captcha' | 'unavailable'>> {
183
170
  return mailByAddress(state, email, 'reset-password', backOf(state.core, redirect), captcha)
184
171
  }
185
172
 
186
173
  // Sets the password the link was sent for and ends every other session the user held.
187
- export async function resetPassword(state: RequestState, token: string, password: string): Promise<ResetPasswordResult> {
174
+ export async function resetPassword(state: RequestState, token: string, password: string): Promise<Result<{ redirect: string }, 'invalid' | 'limited' | 'banned', { password: PasswordProblem | 'breached' }>> {
188
175
  // Counted before the breached-password service is asked, so forged links cannot make the server call it without end.
189
176
  if (await spend(state.core.rates, `link:${state.client}`, state.core.limits.link))
190
177
  return failed('limited')
@@ -221,11 +208,11 @@ export async function resetPassword(state: RequestState, token: string, password
221
208
  return state.complete(record, spent.token.redirect ?? homeOf(state.core), 'reset-password')
222
209
  }
223
210
 
224
- export async function requestMagicLink(state: RequestState, email: string, redirect?: string, captcha?: string): Promise<MailRequestResult> {
211
+ export async function requestMagicLink(state: RequestState, email: string, redirect?: string, captcha?: string): Promise<Result<object, 'limited' | 'captcha' | 'unavailable'>> {
225
212
  return mailByAddress(state, email, 'magic-link', localPath(redirect, homeOf(state.core)), captcha)
226
213
  }
227
214
 
228
- export async function signInWithMagicLink(state: RequestState, token: string): Promise<LinkResult> {
215
+ export async function signInWithMagicLink(state: RequestState, token: string): Promise<Result<{ redirect: string }, 'invalid' | 'limited' | 'banned'>> {
229
216
  const spent = await spendLink(state, token, 'magic-link')
230
217
 
231
218
  if (!spent.ok)
@@ -245,7 +232,7 @@ export async function signInWithMagicLink(state: RequestState, token: string): P
245
232
  }
246
233
 
247
234
  // Mails the new address a link confirming it; the account keeps the old one until then.
248
- export async function changeEmail(state: RequestState, proof: Proof, email: string): Promise<ChangeEmailResult> {
235
+ export async function changeEmail(state: RequestState, proof: Proof, email: string): Promise<Result<object, ProofFailure | 'unavailable', { email: EmailProblem | 'taken' | 'unchanged' }>> {
249
236
  const proved = await reprove(state, proof, { secondFactor: true })
250
237
 
251
238
  if (!proved.ok)
@@ -274,7 +261,7 @@ export async function changeEmail(state: RequestState, proof: Proof, email: stri
274
261
  }
275
262
 
276
263
  // Moves the account to the address the link was sent to, and ends the user's other sessions.
277
- export async function confirmEmailChange(state: RequestState, token: string): Promise<LinkResult> {
264
+ export async function confirmEmailChange(state: RequestState, token: string): Promise<Result<{ redirect: string }, 'invalid' | 'limited' | 'banned'>> {
278
265
  const spent = await spendLink(state, token, 'change-email')
279
266
 
280
267
  if (!spent.ok)
@@ -337,7 +324,7 @@ export async function warnHolder(state: RequestState, holder: UserRecord): Promi
337
324
  }
338
325
 
339
326
  // Signs in with the code a magic link mail carried, in the session that asked for it.
340
- export async function signInWithEmailCode(state: RequestState, code: string): Promise<CodeResult> {
327
+ export async function signInWithEmailCode(state: RequestState, code: string): Promise<Result<{ redirect: string }, 'invalid' | 'expired' | 'limited' | 'banned'>> {
341
328
  const spent = await spendCode(state, 'sign-in-code', code)
342
329
 
343
330
  if (!spent.ok)
@@ -351,7 +338,7 @@ export async function signInWithEmailCode(state: RequestState, code: string): Pr
351
338
  }
352
339
 
353
340
  // Verifies the address with the code its verification mail carried, in the session that asked for it, which registered the account or is signed in as it.
354
- export async function verifyEmailCode(state: RequestState, code: string): Promise<CodeResult> {
341
+ export async function verifyEmailCode(state: RequestState, code: string): Promise<Result<{ redirect: string }, 'invalid' | 'expired' | 'limited' | 'banned'>> {
355
342
  const spent = await spendCode(state, 'verify-code', code)
356
343
 
357
344
  if (!spent.ok)
@@ -424,7 +411,7 @@ function codeDigest(core: Core, nonce: string, code: string): string {
424
411
  }
425
412
 
426
413
  // Counted by address whether or not an account has it, and mailed off the response's path, so neither the answer nor its time tells which addresses exist.
427
- async function mailByAddress(state: RequestState, email: string, type: 'reset-password' | 'magic-link', redirect: string | null, captcha: string | undefined): Promise<MailRequestResult> {
414
+ async function mailByAddress(state: RequestState, email: string, type: 'reset-password' | 'magic-link', redirect: string | null, captcha: string | undefined): Promise<Result<object, 'limited' | 'captcha' | 'unavailable'>> {
428
415
  const { core } = state
429
416
 
430
417
  if (!core.email)
@@ -487,7 +474,7 @@ async function spendResend(state: RequestState, id: string, limit: 'resend' | 'e
487
474
  }
488
475
 
489
476
  // How long the link and the code of a mail work, for the ones it carries.
490
- function lifetimesOf(mail: EmailCore, type: LinkType, content: { url?: string, code?: string }): MailData['maxAge'] {
477
+ function lifetimesOf(mail: EmailCore, type: LinkType, content: { url?: string, code?: string }): MailData['ttl'] {
491
478
  return { ...content.url === undefined ? {} : { link: `${mail.maxAge[type]}s` }, ...content.code === undefined ? {} : { code: `${mail.maxAge[CODE_OF[type as CodedLink]]}s` } }
492
479
  }
493
480
 
@@ -519,9 +506,10 @@ async function issue(state: RequestState, record: UserRecord, type: LinkType, em
519
506
 
520
507
  const { locale, templates } = writing(mail, [record.locale, ...state.languages])
521
508
 
522
- const maxAge = lifetimesOf(mail, type, content)
509
+ const ttl = lifetimesOf(mail, type, content)
523
510
 
524
- await mail.mailer.send({ to: email, kind: type, name: core.name, locale, ...content, maxAge, ...templates[type]({ name: core.name, email, locale, ...content, maxAge }) })
511
+ // `maxAge` is the old name of `ttl`, still given to a template or a mailer written with it until 1.108.
512
+ await mail.mailer.send({ to: email, kind: type, name: core.name, locale, ...content, ttl, maxAge: ttl, ...templates[type]({ name: core.name, email, locale, ...content, ttl, maxAge: ttl }) })
525
513
  }
526
514
 
527
515
  // The code the same mail carried is spent with its link, once the link is used: a link refused leaves both.
package/src/erase.ts CHANGED
@@ -1,10 +1,11 @@
1
1
  import type { AuthFailed } from './failure'
2
2
  import type { RequestState } from './state'
3
3
  import type { UserRecord } from './store'
4
+ import { KayError } from 'kay/library'
4
5
  import { notifications, personalData } from 'kay/server'
5
6
  import { linkedUser } from './core'
6
7
  import { reportFrom } from './events'
7
- import { failed } from './failure'
8
+ import { failed, failedAs } from './failure'
8
9
  import { log } from './log'
9
10
  import { mailNotice, securityNotice } from './securityNotice'
10
11
 
@@ -72,7 +73,7 @@ export async function eraseUser(core: Core, record: UserRecord): Promise<void> {
72
73
 
73
74
  // Kept as a `beforeDelete` that refuses keeps it: the caller leaves the account to be tried again.
74
75
  if (!erased.ok)
75
- throw new Error(`beforeDelete refused to delete ${record.id}: ${erased.error.message}`)
76
+ throw new KayError('helper-failed', `beforeDelete refused to delete ${record.id}: ${erased.error.message}`)
76
77
  }
77
78
 
78
79
  // `eraseUser` for a user who goes, by their own hand or an admin's (`actor`): the invitations to their address go too, and the account-deleted notice is mailed. Refused with `refused` when `beforeDelete` says so, and with `last-owner` while they are the only owner of an organization with other members, unless `handOver` is set, as for an admin who cannot name an owner: the organization then passes to its longest-standing member. An organization they are alone in goes with them.
@@ -112,7 +113,7 @@ export async function eraseDue(core: Core, record: UserRecord): Promise<void> {
112
113
  }, stillDue)
113
114
 
114
115
  if (!erased.ok)
115
- throw new Error(`the deletion of ${record.id} did not go through (${erased.error.code}): ${erased.error.message}`)
116
+ throw new KayError('helper-failed', `the deletion of ${record.id} did not go through (${erased.error.code}): ${erased.error.message}`)
116
117
  }
117
118
 
118
119
  // `afterDelete` runs once the user is gone, and what it records is forgotten after it. The audit log forgets the user before and after, and a failure of either fails the erase, so none of their data stays behind unreported; only the first leaves the account to delete again.
@@ -126,7 +127,7 @@ async function eraseThen(core: Core, record: UserRecord, handOver: boolean, acto
126
127
  const refusal = await core.beforeDelete?.(await linkedUser(core, record), actor ? await linkedUser(core, actor) : null)
127
128
 
128
129
  if (refusal)
129
- return { ok: false, error: refusal }
130
+ return failedAs(refusal)
130
131
 
131
132
  if (stillDue && !await stillDue())
132
133
  return failed('refused')
package/src/export.ts CHANGED
@@ -3,7 +3,7 @@ import type { ApprovedClient } from './authorize/grants'
3
3
  import type { BearerToken } from './bearer'
4
4
  import type { User } from './core'
5
5
  import type { AuditEntry } from './events'
6
- import type { AuthFailed } from './failure'
6
+ import type { Result } from './failure'
7
7
  import type { MailingSubscription } from './mail'
8
8
  import type { Invitation, Membership } from './organizations'
9
9
  import type { Passkey } from './passkeys'
@@ -53,11 +53,9 @@ export interface DataExport {
53
53
  app: unknown
54
54
  }
55
55
 
56
- export type ExportResult = { ok: true, data: DataExport } | AuthFailed<'signed-out' | 'limited' | 'impersonating' | 'stale'>
57
-
58
56
  // Not for an admin acting as the user: they see what the user sees, not a copy of everything kept about them.
59
57
  // Only within ten minutes of signing in or re-proving, so a session left open or stolen does not download everything the account holds.
60
- export async function exportData(state: RequestState): Promise<ExportResult> {
58
+ export async function exportData(state: RequestState): Promise<Result<{ data: DataExport }, 'signed-out' | 'limited' | 'impersonating' | 'stale'>> {
61
59
  const { core } = state
62
60
  const record = await state.current()
63
61
 
package/src/failure.ts CHANGED
@@ -1,20 +1,35 @@
1
1
  import type { ErrorShape } from 'kay/library'
2
+ import { FAILURE } from 'kay/library'
2
3
 
3
4
  // 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
5
  export interface AuthFailure<Kind extends string = string> extends ErrorShape {
5
6
  code: Kind
6
7
  }
7
8
 
9
+ // What a failed result is to an action: kay's own `Failure`, which a handler returning it makes the refusal of the call, with the status, and the kind with its sentence as `data`. Hidden from the JSON a result becomes, which reads `{ ok: false, error }`.
10
+ export interface AuthRefusal<Kind extends string = string> {
11
+ readonly [FAILURE]: true
12
+ readonly status: number
13
+ readonly data: { code: Kind, message: string }
14
+ }
15
+
8
16
  // 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
17
+ export type AuthFailed<Kind extends string = string> = Kind extends string ? { ok: false, error: AuthFailure<Kind> } & AuthRefusal<Kind> : never
18
+
19
+ // A problem as `errors` holds it: the sentence of an object problem, a code as it is.
20
+ type Sentence<Problem> = Problem extends { message: string } ? string : Problem
10
21
 
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> {
22
+ // A failed result for input rejected, `errors` holding the problem of each field (its sentence when the problem is one), also on `error.errors` as every failure has it.
23
+ export interface AuthRejected<Fields extends object> extends AuthRefusal<'invalid'> {
13
24
  ok: false
14
25
  error: AuthFailure<'invalid'>
15
- errors: Fields
26
+ errors: { [Field in keyof Fields]?: Sentence<Fields[Field]> }
16
27
  }
17
28
 
29
+ // What an auth call answers, for an app's action to return as it is: `{ ok: true, ...Ok }`, or a failure of one of the kinds `Code` names, and with `Fields` a rejection of input naming the fields it refused (`errors.<field>`).
30
+ // A failure is a `Failure` of kay, so `return auth.password.signIn(...)` refuses the action with its status and `data.code`, and it carries the same `error` as a call's result.
31
+ export type Result<Ok extends object = object, Code extends string = never, Fields extends object = never> = ({ ok: true } & Ok) | AuthFailed<Code> | ([Fields] extends [never] ? never : AuthRejected<Fields>)
32
+
18
33
  const STATUS: Readonly<Record<string, number>> = {
19
34
  'signed-out': 401,
20
35
  'invalid': 401,
@@ -49,15 +64,28 @@ export function authFailure<Kind extends string>(code: Kind, errors: Record<stri
49
64
  return { code, status: failureStatus(code), message: failureMessage(code), errors, data: undefined }
50
65
  }
51
66
 
67
+ // A refusal as an action reads it: the properties stay out of the JSON the result becomes.
68
+ function refusal<Value extends object>(result: Value, status: number, data: { code: string, message: string }): Value {
69
+ return Object.defineProperties(result, { [FAILURE]: { value: true }, status: { value: status }, data: { value: data } })
70
+ }
71
+
52
72
  // The failed result of a kind: `{ ok: false, error: { code, status, message, errors, data } }`.
53
73
  export function failed<Kind extends string>(code: Kind): AuthFailed<Kind> {
54
- return { ok: false, error: authFailure(code) } as AuthFailed<Kind>
74
+ return failedAs(authFailure(code))
75
+ }
76
+
77
+ // The failed result of a failure the app made, as `beforeDelete` refuses with one.
78
+ export function failedAs<Kind extends string>(error: AuthFailure<Kind>): AuthFailed<Kind> {
79
+ const { code } = error
80
+
81
+ return refusal({ ok: false, error }, error.status, { code, message: error.message }) as unknown as AuthFailed<Kind>
55
82
  }
56
83
 
57
- // The failed result of input rejected: the problems by field on `errors`, and on `error.errors` with the message of the first.
84
+ // The failed result of input rejected: the problem of each field on `errors` and, as a sentence, on `error.errors` with the first as the message.
58
85
  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]
86
+ const sentences = Object.fromEntries(Object.entries(fields).filter(([, problem]) => problem !== undefined).map(([field, problem]) => [field, typeof problem === 'string' ? problem : (problem as { message?: string }).message ?? String(problem)]))
87
+ const first = Object.entries(sentences)[0]
88
+ const message = first === undefined ? 'Invalid' : `${failureMessage(first[0])} ${first[1]}`.trim()
61
89
 
62
- return { ok: false, error: { ...authFailure('invalid', errors), status: 422, message: first === undefined ? 'Invalid' : `${failureMessage(first[0])} ${first[1]}`.trim() }, errors: fields }
90
+ return refusal({ ok: false, error: { ...authFailure('invalid', sentences), status: 422, message }, errors: sentences }, 422, { code: 'invalid', message }) as unknown as AuthRejected<Fields>
63
91
  }
package/src/guard.ts CHANGED
@@ -1,21 +1,28 @@
1
+ import type { Duration } from 'kay'
1
2
  import type { Auth, AuthRequirement } from './auth'
2
3
  import { guard as kayGuard } from 'kay'
4
+ import { KayError } from 'kay/library'
5
+ import { freshMs } from './request'
3
6
 
4
7
  /** 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
8
  export interface GuardOptions {
6
9
  redirect?: string | undefined
7
10
  require?: AuthRequirement<string> | undefined
8
11
  scope?: string | string[] | false | undefined
12
+ fresh?: Duration | undefined
9
13
  twoFactor?: true | undefined
10
14
  }
11
15
 
12
16
  // 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
17
  export function authGuard(options: GuardOptions = {}) {
18
+ if (options.fresh !== undefined)
19
+ freshMs(options.fresh)
20
+
14
21
  return kayGuard<{ auth: Auth }>(async (ctx) => {
15
22
  const { auth } = ctx.locals
16
23
 
17
24
  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')
25
+ throw new KayError('config-invalid', 'kayjs-auth: no `auth` in this context; add auth() to kay.config.ts, or `.use(auth.plugin)` before the routes')
19
26
 
20
27
  await auth.guarded(ctx, options)
21
28
  })
package/src/guards.ts CHANGED
@@ -1,4 +1,4 @@
1
- import type { Guard } from 'kay'
1
+ import type { Duration, Guard } from 'kay'
2
2
  import type { BareUser, Core } from './core'
3
3
  import type { ScopeRequirement } from './gate'
4
4
  import type { AuthRequirement } from './request'
@@ -7,13 +7,15 @@ import { READ_METHODS } from 'kay/library'
7
7
  import { guardPageOf, isNavigation, withBack } from './core'
8
8
  import { authGate, scopeAllows } from './gate'
9
9
  import { load } from './load'
10
- import { authOf, STATE } from './request'
10
+ import { authOf, freshMs, STALE_PROOF, STATE } from './request'
11
11
  import { lacksTwoFactor, sendToEnrolment } from './requiredTwoFactor'
12
12
 
13
13
  export interface RouteGuardOptions<Role extends string, Scope extends string> {
14
14
  redirect?: string | undefined
15
15
  require?: AuthRequirement<Role> | undefined
16
16
  scope?: ScopeRequirement<Scope> | undefined
17
+ // A duration such as `'10m'`: the user must have signed in or re-proved (`auth.proof.renew`) within it, else a 403 whose `data.code` is `'stale'`, for the page to ask for the password or the passkey again. A bearer token never has, so it is refused.
18
+ fresh?: Duration | undefined
17
19
  // 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
20
  twoFactor?: true | undefined
19
21
  }
@@ -24,6 +26,8 @@ const signedIn: Predicate<BareUser> = user => user !== null
24
26
  // 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
27
  export function guardOf<Role extends string, Scope extends string>(core: Core, options: RouteGuardOptions<Role, Scope> = {}): Guard {
26
28
  const redirect = options.redirect === undefined || options.redirect === '' ? guardPageOf(core) : options.redirect
29
+ // Read here so a value that is no duration fails when the guard is made.
30
+ const fresh = options.fresh === undefined ? undefined : freshMs(options.fresh)
27
31
 
28
32
  return async (ctx) => {
29
33
  const user = await authOf(ctx.locals).bareUser()
@@ -34,16 +38,19 @@ export function guardOf<Role extends string, Scope extends string>(core: Core, o
34
38
  // kay-allow external-redirect: `redirect` is the app's own sign-in page, the visited path rides in its query
35
39
  ctx.redirect(withBack(redirect, ctx.url.pathname + ctx.url.search))
36
40
 
37
- ctx.deny(401, 'Sign in to continue')
41
+ ctx.deny(401, { message: 'Sign in to continue' })
38
42
  }
39
43
 
40
44
  // kay before 1.23 gives a guard no params, and `memberOf` then refuses rather than skip the check.
41
45
  if (options.require !== undefined && !(await core.access.authorize(user, options.require, reading ? 'read' : 'write', { params: ctx.params })))
42
46
  ctx.deny(403)
43
47
 
44
- if (!scopeAllows(await authOf(ctx.locals).scopes(), options.scope))
48
+ if (!scopeAllows(await authOf(ctx.locals).tokens.scopes(), options.scope))
45
49
  ctx.deny(403)
46
50
 
51
+ if (fresh !== undefined && !(await authOf(ctx.locals).proof.recent(options.fresh)))
52
+ ctx.deny(403, STALE_PROOF)
53
+
47
54
  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
55
  sendToEnrolment(core, ctx.request, ctx)
49
56
  }
@@ -57,7 +64,7 @@ export function gateOf<Role extends string, Scope extends string>(core: Core, op
57
64
  // 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
65
  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
66
  defaultRequirement: options.require ?? signedIn,
60
- scopes: async ctx => authOf(ctx).scopes(),
67
+ scopes: async ctx => authOf(ctx).tokens.scopes(),
61
68
  defaultScope: options.scope,
62
69
  })
63
70
  }
package/src/index.ts CHANGED
@@ -1,21 +1,20 @@
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'
1
+ export type { AdminChangeFailure, AdminFailure, ManagedUser } from './admin'
3
2
  export { auditWording, describeAuditEntry } from './auditWording'
4
3
  export type { AuditPhrase, AuditWording } from './auditWording'
5
4
  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'
5
+ export type { ApprovedClient } from './authorize/grants'
6
+ export type { AuthorizeOutcome, AuthorizeParams, ConsentFields } from './authorize/request'
7
+ export type { BearerToken, TokenOptions } from './bearer'
9
8
  export { pwnedPassword } from './breached'
10
9
  export { hcaptcha, hcaptchaWidget, proofOfWork, turnstile, turnstileWidget } from './captcha'
11
10
  export type { AuthProofOfWorkOptions, CaptchaAction, CaptchaCheck, CaptchaContext, CaptchaOptions, CaptchaRules, CaptchaWidget, ProofOfWorkCaptcha } from './captcha'
12
11
  export * from './decide'
13
12
  export type { Device } from './device'
14
- export type { ChangeEmailResult, CodedLink, CodeMode, CodeResult, EmailOptions, LinkResult, MailRequestResult, PendingEmailCode, ResetPasswordResult, SendVerificationResult, VerifyEmailResult } from './email'
13
+ export type { CodedLink, CodeMode, EmailOptions, PendingEmailCode } from './email'
15
14
  export type { DeletionImpact } from './erase'
16
15
  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'
16
+ export type { DataExport } from './export'
17
+ export type { AuthFailed, AuthFailure, AuthRefusal, AuthRejected, Result } from './failure'
19
18
  export * from './gate'
20
19
  export { authGuard } from './guard'
21
20
  export type { GuardOptions } from './guard'
@@ -26,21 +25,20 @@ export { defaultTemplates, frenchTemplates, lifetime } from './mail'
26
25
  export type { AuthMailer, AuthMailMessage, MailContent, MailData, MailingSubscription, MailKind, SecurityEvent, Templates } from './mail'
27
26
  export * from './memoryStore'
28
27
  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'
28
+ export type { OAuthFailure } from './oauth/flow'
29
+ export type { AuthMember, Invitation, Membership, Organization, OrganizationFailure, OrganizationsOptions, OrganizationWriteFailure } from './organizations'
31
30
  export type { AuthHooks, OwnOptions, PresetApp, StoreUrl } from './own'
32
31
  export { auth } from './pages'
33
32
  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'
33
+ export type { Passkey } from './passkeys'
34
+ export type { CreateUserInput, PasswordSignInInput, RegisterErrors, RegisterInput } from './password'
36
35
  export { passkeyAssertion, passkeyAttestation } from './payloads'
37
- export type { SaveProfileResult } from './profile'
38
- export type { Proof, ProofFailure, ReproveResult } from './proof'
36
+ export type { Proof, ProofFailure } from './proof'
39
37
  export type { AuthRates } from './rates'
40
38
  export * from './roles'
41
- export type { GuestSignInResult, RevokeSessionResult, UserSession } from './sessions'
39
+ export type { UserSession } from './sessions'
42
40
  export type { SignInOptions } from './signInOptions'
43
41
  export * from './store'
44
- export type { DisableTwoFactorResult, EnableTwoFactorResult, RecoveryCodesResult, SetUpTwoFactorResult, TotpEnrolment, TwoFactorResult, TwoFactorSetup } from './twoFactor'
42
+ export type { TotpEnrolment, TwoFactorSetup } from './twoFactor'
45
43
  export * from './types'
46
44
  export * from './wsAuth'
package/src/limits.ts CHANGED
@@ -56,8 +56,100 @@ export type Limits = Record<keyof typeof DEFAULT_LIMITS, AuthRateLimit> & { oaut
56
56
  // A limit as the app writes it, alone or in a list that is each counted apart.
57
57
  export type LimitOption = AuthRateLimit | AuthRateLimit[]
58
58
 
59
- // The limits `rateLimit` overrides, the rest keeping their defaults.
60
- export type LimitsOption = Partial<Record<keyof Limits, LimitOption>>
59
+ // What a feature's limits are counted per, `ip` the client's address and `account` the account the attempt is about.
60
+ export interface PerClientAndAccount {
61
+ ip?: LimitOption | undefined
62
+ account?: LimitOption | undefined
63
+ }
64
+
65
+ // The limits `rateLimit` overrides, grouped by feature and the rest keeping their defaults: `{ signIn: { ip, account, accountAll }, forgot: { ip, account }, register }`.
66
+ // A feature with a limit per address and per account, or a few, takes an object; a bare limit or a list on it is the `ip` one, as before 1.105.
67
+ export interface LimitsOption {
68
+ // Wrong passwords: `ip` per client address, `account` per client and account (tight, so it never keeps the holder out) and `accountAll` the looser ceiling on the account from every client together.
69
+ signIn?: LimitOption | (PerClientAndAccount & { accountAll?: LimitOption | undefined }) | undefined
70
+ register?: LimitOption | undefined
71
+ resend?: LimitOption | PerClientAndAccount | undefined
72
+ forgot?: LimitOption | PerClientAndAccount | undefined
73
+ magicLink?: LimitOption | PerClientAndAccount | undefined
74
+ emailChange?: LimitOption | PerClientAndAccount | undefined
75
+ twoFactor?: LimitOption | PerClientAndAccount | undefined
76
+ emailCode?: LimitOption | PerClientAndAccount | undefined
77
+ reprove?: LimitOption | undefined
78
+ link?: LimitOption | undefined
79
+ export?: LimitOption | undefined
80
+ organization?: LimitOption | undefined
81
+ // Invitations a manager sends (`sender`) and those an address receives (`address`).
82
+ invite?: LimitOption | { sender?: LimitOption | undefined, address?: LimitOption | undefined } | undefined
83
+ // The OAuth server's endpoints: `register` per address, `registerAll` a ceiling on all addresses together (none by default), `document` and `token`.
84
+ oauth?: { register?: LimitOption | undefined, registerAll?: LimitOption | undefined, document?: LimitOption | undefined, token?: LimitOption | undefined } | undefined
85
+ /** @deprecated `signIn.account`. Removed in 1.108; `deprecated-auth-rate-limits` rewrites it. */
86
+ signInAccount?: LimitOption | undefined
87
+ /** @deprecated `signIn.accountAll`. Removed in 1.108; `deprecated-auth-rate-limits` rewrites it. */
88
+ signInAccountAll?: LimitOption | undefined
89
+ /** @deprecated `resend.account`. Removed in 1.108; `deprecated-auth-rate-limits` rewrites it. */
90
+ resendAccount?: LimitOption | undefined
91
+ /** @deprecated `forgot.account`. Removed in 1.108; `deprecated-auth-rate-limits` rewrites it. */
92
+ forgotAccount?: LimitOption | undefined
93
+ /** @deprecated `magicLink.account`. Removed in 1.108; `deprecated-auth-rate-limits` rewrites it. */
94
+ magicLinkAccount?: LimitOption | undefined
95
+ /** @deprecated `emailChange.account`. Removed in 1.108; `deprecated-auth-rate-limits` rewrites it. */
96
+ emailChangeAccount?: LimitOption | undefined
97
+ /** @deprecated `twoFactor.account`. Removed in 1.108; `deprecated-auth-rate-limits` rewrites it. */
98
+ twoFactorAccount?: LimitOption | undefined
99
+ /** @deprecated `emailCode.account`. Removed in 1.108; `deprecated-auth-rate-limits` rewrites it. */
100
+ emailCodeAccount?: LimitOption | undefined
101
+ /** @deprecated `invite.address`. Removed in 1.108; `deprecated-auth-rate-limits` rewrites it. */
102
+ inviteAddress?: LimitOption | undefined
103
+ /** @deprecated `oauth.register`. Removed in 1.108; `deprecated-auth-rate-limits` rewrites it. */
104
+ oauthRegister?: LimitOption | undefined
105
+ /** @deprecated `oauth.registerAll`. Removed in 1.108; `deprecated-auth-rate-limits` rewrites it. */
106
+ oauthRegisterAll?: LimitOption | undefined
107
+ /** @deprecated `oauth.document`. Removed in 1.108; `deprecated-auth-rate-limits` rewrites it. */
108
+ oauthDocument?: LimitOption | undefined
109
+ /** @deprecated `oauth.token`. Removed in 1.108; `deprecated-auth-rate-limits` rewrites it. */
110
+ oauthToken?: LimitOption | undefined
111
+ }
112
+
113
+ // Where each part of a group is counted, under the name the bucket has in `DEFAULT_LIMITS`: the bare limit of a feature is its first part.
114
+ export const LIMIT_GROUPS: Record<string, Record<string, keyof Limits>> = {
115
+ signIn: { ip: 'signIn', account: 'signInAccount', accountAll: 'signInAccountAll' },
116
+ resend: { ip: 'resend', account: 'resendAccount' },
117
+ forgot: { ip: 'forgot', account: 'forgotAccount' },
118
+ magicLink: { ip: 'magicLink', account: 'magicLinkAccount' },
119
+ emailChange: { ip: 'emailChange', account: 'emailChangeAccount' },
120
+ twoFactor: { ip: 'twoFactor', account: 'twoFactorAccount' },
121
+ emailCode: { ip: 'emailCode', account: 'emailCodeAccount' },
122
+ invite: { sender: 'invite', address: 'inviteAddress' },
123
+ oauth: { register: 'oauthRegister', registerAll: 'oauthRegisterAll', document: 'oauthDocument', token: 'oauthToken' },
124
+ }
125
+
126
+ // The buckets `rateLimit` names, each with its limit and where the app wrote it: a group is read part by part, a bare limit on a feature that has a group is its first part.
127
+ function bucketsOf(given: LimitsOption | undefined): [keyof Limits, LimitOption | undefined, string][] {
128
+ const buckets: [keyof Limits, LimitOption | undefined, string][] = []
129
+
130
+ for (const [name, value] of Object.entries(given ?? {}) as [string, unknown][]) {
131
+ const group = Object.hasOwn(LIMIT_GROUPS, name) ? LIMIT_GROUPS[name]! : undefined
132
+
133
+ if (group === undefined || value === false || value === null || value === undefined || Array.isArray(value) || (typeof value === 'object' && value !== null && 'max' in value)) {
134
+ // A bare limit on a feature with a group is its first part, as it was before the groups.
135
+ buckets.push([(group ? Object.values(group)[0]! : name) as keyof Limits, value as LimitOption | undefined, `rateLimit.${name}`])
136
+
137
+ continue
138
+ }
139
+
140
+ if (typeof value !== 'object' || value === null)
141
+ throw configError('auth', 'rateLimit', `rateLimit.${name} is ${String(value)}; give it { ${Object.keys(group).join(', ')} } or a limit`)
142
+
143
+ for (const [part, option] of Object.entries(value)) {
144
+ if (!Object.hasOwn(group, part))
145
+ throw configError('auth', 'rateLimit', `rateLimit.${name}.${part} is not a limit of ${name}; it has ${Object.keys(group).join(', ')}`)
146
+
147
+ buckets.push([group[part]!, option as LimitOption | undefined, `rateLimit.${name}.${part}`])
148
+ }
149
+ }
150
+
151
+ return buckets
152
+ }
61
153
 
62
154
  export type ResolvedLimits = Record<keyof typeof DEFAULT_LIMITS, LimitSet> & { oauthRegisterAll?: LimitSet }
63
155
 
@@ -65,17 +157,17 @@ export type ResolvedLimits = Record<keyof typeof DEFAULT_LIMITS, LimitSet> & { o
65
157
  export function resolveLimits(given: LimitsOption | undefined): ResolvedLimits {
66
158
  const limits = Object.fromEntries(Object.entries(DEFAULT_LIMITS).map(([name, limit]) => [name, [limit]])) as unknown as ResolvedLimits
67
159
 
68
- for (const [name, option] of Object.entries(given ?? {}) as [keyof Limits, LimitOption | undefined][]) {
160
+ for (const [name, option, where] of bucketsOf(given)) {
69
161
  if (!option)
70
162
  continue
71
163
 
72
164
  const list = [option].flat()
73
165
 
74
166
  if (list.length === 0)
75
- throw configError('auth', 'rateLimit', `rateLimit.${name} is an empty list; give it a limit or leave it out`)
167
+ throw configError('auth', 'rateLimit', `${where} is an empty list; give it a limit or leave it out`)
76
168
 
77
169
  for (const [index, limit] of list.entries()) {
78
- const place = list.length === 1 ? `rateLimit.${name}` : `rateLimit.${name}[${index}]`
170
+ const place = list.length === 1 ? where : `${where}[${index}]`
79
171
 
80
172
  durationSeconds(limit.window, `${place}.window`)
81
173