@kayjs/auth 1.104.3 → 1.106.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 (208) 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 +14 -14
  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 +15 -15
  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 +10 -6
  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/oauth/providers.ts +1 -1
  55. package/src/oauthTest.ts +8 -4
  56. package/src/organizations.ts +12 -30
  57. package/src/organizationsCore.ts +1 -1
  58. package/src/own.ts +21 -19
  59. package/src/pages/components/frame.kay +3 -3
  60. package/src/pages/components/passkey-add.kay +2 -2
  61. package/src/pages/components/passkey-sign-in.kay +2 -2
  62. package/src/pages/components/passkey-two-factor.kay +2 -2
  63. package/src/pages/components/provider-buttons.kay +1 -1
  64. package/src/pages/forms.ts +6 -6
  65. package/src/pages/index.ts +9 -8
  66. package/src/pages/routes/account/clients.kay +2 -2
  67. package/src/pages/routes/account/connections.kay +4 -4
  68. package/src/pages/routes/account/data.kay +7 -7
  69. package/src/pages/routes/account/index.kay +15 -15
  70. package/src/pages/routes/account/organizations/[org].kay +15 -15
  71. package/src/pages/routes/account/organizations/index.kay +5 -5
  72. package/src/pages/routes/account/security.kay +15 -15
  73. package/src/pages/routes/account/tokens.kay +4 -4
  74. package/src/pages/routes/admin/_layout.kay +1 -1
  75. package/src/pages/routes/admin/audit.kay +1 -1
  76. package/src/pages/routes/admin/users/[id].kay +11 -11
  77. package/src/pages/routes/confirm-email.kay +3 -3
  78. package/src/pages/routes/invitation.kay +8 -8
  79. package/src/pages/routes/magic-link.kay +3 -3
  80. package/src/pages/routes/oauth/authorize.kay +2 -2
  81. package/src/pages/routes/register.kay +4 -4
  82. package/src/pages/routes/reset-password.kay +6 -6
  83. package/src/pages/routes/sign-in.kay +10 -10
  84. package/src/pages/routes/two-factor.kay +4 -4
  85. package/src/pages/routes/verify-email.kay +8 -8
  86. package/src/passkeys.ts +10 -21
  87. package/src/password.ts +8 -11
  88. package/src/pg.ts +3 -3
  89. package/src/profile.ts +1 -3
  90. package/src/proof.ts +3 -5
  91. package/src/request.ts +77 -46
  92. package/src/requiredTwoFactor.ts +2 -2
  93. package/src/routes.ts +2 -2
  94. package/src/sessions.ts +3 -7
  95. package/src/setup.ts +6 -4
  96. package/src/sqlite.ts +6 -0
  97. package/src/test.ts +15 -3
  98. package/src/testHelpers.ts +16 -7
  99. package/src/testHook.ts +31 -0
  100. package/src/testing.ts +5 -4
  101. package/src/twoFactor.ts +9 -18
  102. package/src/viewer.ts +26 -4
  103. package/src/webauthn.ts +2 -2
  104. package/types/account.d.ts +10 -23
  105. package/types/account.d.ts.map +1 -1
  106. package/types/admin.d.ts +21 -39
  107. package/types/admin.d.ts.map +1 -1
  108. package/types/auth.d.ts +18 -5
  109. package/types/auth.d.ts.map +1 -1
  110. package/types/authorize/grants.d.ts +2 -5
  111. package/types/authorize/grants.d.ts.map +1 -1
  112. package/types/authorize/request.d.ts +3 -5
  113. package/types/authorize/request.d.ts.map +1 -1
  114. package/types/bearer.d.ts +9 -17
  115. package/types/bearer.d.ts.map +1 -1
  116. package/types/captcha.d.ts +3 -1
  117. package/types/captcha.d.ts.map +1 -1
  118. package/types/context.d.ts +1 -1
  119. package/types/deletion.d.ts +2 -5
  120. package/types/deletion.d.ts.map +1 -1
  121. package/types/email.d.ts +23 -28
  122. package/types/email.d.ts.map +1 -1
  123. package/types/erase.d.ts.map +1 -1
  124. package/types/export.d.ts +3 -5
  125. package/types/export.d.ts.map +1 -1
  126. package/types/failure.d.ts +22 -3
  127. package/types/failure.d.ts.map +1 -1
  128. package/types/guard.d.ts +2 -0
  129. package/types/guard.d.ts.map +1 -1
  130. package/types/guards.d.ts +2 -1
  131. package/types/guards.d.ts.map +1 -1
  132. package/types/index.d.ts +14 -16
  133. package/types/index.d.ts.map +1 -1
  134. package/types/limits.d.ts +57 -1
  135. package/types/limits.d.ts.map +1 -1
  136. package/types/mail.d.ts +5 -0
  137. package/types/mail.d.ts.map +1 -1
  138. package/types/messages/fr.d.ts +1 -0
  139. package/types/methods/account.d.ts +27 -13
  140. package/types/methods/account.d.ts.map +1 -1
  141. package/types/methods/admin.d.ts +39 -15
  142. package/types/methods/admin.d.ts.map +1 -1
  143. package/types/methods/captcha.d.ts +9 -0
  144. package/types/methods/captcha.d.ts.map +1 -0
  145. package/types/methods/email.d.ts +21 -7
  146. package/types/methods/email.d.ts.map +1 -1
  147. package/types/methods/magicLink.d.ts +9 -4
  148. package/types/methods/magicLink.d.ts.map +1 -1
  149. package/types/methods/oauth.d.ts +12 -7
  150. package/types/methods/oauth.d.ts.map +1 -1
  151. package/types/methods/oauthServer.d.ts +13 -5
  152. package/types/methods/oauthServer.d.ts.map +1 -1
  153. package/types/methods/organizations.d.ts +40 -15
  154. package/types/methods/organizations.d.ts.map +1 -1
  155. package/types/methods/passkeys.d.ts +18 -7
  156. package/types/methods/passkeys.d.ts.map +1 -1
  157. package/types/methods/password.d.ts +23 -10
  158. package/types/methods/password.d.ts.map +1 -1
  159. package/types/methods/proof.d.ts +12 -0
  160. package/types/methods/proof.d.ts.map +1 -0
  161. package/types/methods/sessions.d.ts +3 -2
  162. package/types/methods/sessions.d.ts.map +1 -1
  163. package/types/methods/tokens.d.ts +12 -5
  164. package/types/methods/tokens.d.ts.map +1 -1
  165. package/types/methods/twoFactor.d.ts +22 -10
  166. package/types/methods/twoFactor.d.ts.map +1 -1
  167. package/types/oauth/flow.d.ts +4 -6
  168. package/types/oauth/flow.d.ts.map +1 -1
  169. package/types/oauthTest.d.ts +2 -0
  170. package/types/oauthTest.d.ts.map +1 -1
  171. package/types/organizations.d.ts +24 -48
  172. package/types/organizations.d.ts.map +1 -1
  173. package/types/own.d.ts +1 -1
  174. package/types/own.d.ts.map +1 -1
  175. package/types/pages/forms.d.ts +5 -3
  176. package/types/pages/forms.d.ts.map +1 -1
  177. package/types/pages/index.d.ts +5 -2
  178. package/types/pages/index.d.ts.map +1 -1
  179. package/types/passkeys.d.ts +20 -27
  180. package/types/passkeys.d.ts.map +1 -1
  181. package/types/password.d.ts +13 -20
  182. package/types/password.d.ts.map +1 -1
  183. package/types/profile.d.ts +1 -4
  184. package/types/profile.d.ts.map +1 -1
  185. package/types/proof.d.ts +1 -4
  186. package/types/proof.d.ts.map +1 -1
  187. package/types/request.d.ts +33 -7
  188. package/types/request.d.ts.map +1 -1
  189. package/types/requiredTwoFactor.d.ts +3 -1
  190. package/types/requiredTwoFactor.d.ts.map +1 -1
  191. package/types/routes.d.ts +3 -1
  192. package/types/routes.d.ts.map +1 -1
  193. package/types/sessions.d.ts +3 -10
  194. package/types/sessions.d.ts.map +1 -1
  195. package/types/setup.d.ts.map +1 -1
  196. package/types/sqlite.d.ts +3 -0
  197. package/types/sqlite.d.ts.map +1 -0
  198. package/types/test.d.ts +4 -1
  199. package/types/test.d.ts.map +1 -1
  200. package/types/testHelpers.d.ts +1 -0
  201. package/types/testHelpers.d.ts.map +1 -1
  202. package/types/testHook.d.ts +15 -0
  203. package/types/testHook.d.ts.map +1 -0
  204. package/types/testing.d.ts.map +1 -1
  205. package/types/twoFactor.d.ts +10 -21
  206. package/types/twoFactor.d.ts.map +1 -1
  207. package/types/viewer.d.ts +3 -1
  208. package/types/viewer.d.ts.map +1 -1
package/src/password.ts CHANGED
@@ -1,11 +1,12 @@
1
1
  import type { BareUser, Core } from './core'
2
- import type { AuthFailed, AuthRejected } from './failure'
2
+ import type { Result } from './failure'
3
3
  import type { EmailProblem, PasswordProblem, UsernameProblem } from './rules'
4
4
  import type { SignInOptions } from './signInOptions'
5
5
  import type { RequestState } from './state'
6
6
  import type { UserRecord } from './store'
7
7
  import { hashPassword, passwordNeedsRehash } from '@kaynooo/utils'
8
8
  import { localPath } from 'kay'
9
+ import { KayError } from 'kay/library'
9
10
  import { newPasswordProblem } from './breached'
10
11
  import { admit } from './captcha'
11
12
  import { backOf, homeOf, newUserRecord, publicUser, unlinked } from './core'
@@ -32,7 +33,6 @@ export interface RegisterErrors {
32
33
  }
33
34
 
34
35
  // `signedIn` is false, with no user, when the app wants the address verified first: the same answer whether the address was free or held, its holder mailed instead. `off` with `signUp: false`.
35
- export type RegisterResult = { ok: true, user: BareUser, signedIn: true } | { ok: true, signedIn: false } | AuthRejected<RegisterErrors> | AuthFailed<'limited' | 'captcha' | 'off'>
36
36
 
37
37
  export interface CreateUserInput {
38
38
  // At least one of the two, the user signing in with either.
@@ -47,8 +47,6 @@ export interface CreateUserInput {
47
47
  locale?: string | undefined
48
48
  }
49
49
 
50
- export type CreateUserResult = { ok: true, user: BareUser } | AuthRejected<RegisterErrors>
51
-
52
50
  export interface PasswordSignInInput {
53
51
  // An email, or a username when it holds no `@`.
54
52
  identifier: string
@@ -57,10 +55,9 @@ export interface PasswordSignInInput {
57
55
 
58
56
  // `invalid` whether no account matches or the password is wrong, so the answer tells nothing of which accounts exist.
59
57
  // `unverified` once the password is right, when the app wants the address verified first.
60
- export type PasswordSignInResult = { ok: true, redirect: string } | AuthFailed<'invalid' | 'limited' | 'captcha' | 'unverified' | 'banned'>
61
58
 
62
59
  // A new user with a password, signed in on this session; a guest signed in becomes it, keeping their id.
63
- export async function register(state: RequestState, input: RegisterInput, options: Pick<SignInOptions, 'redirect' | 'captcha'> = {}): Promise<RegisterResult> {
60
+ export async function register(state: RequestState, input: RegisterInput, options: Pick<SignInOptions, 'redirect' | 'captcha'> = {}): Promise<Result<{ user: BareUser, signedIn: true } | { signedIn: false }, 'limited' | 'captcha' | 'off', RegisterErrors>> {
64
61
  const { store } = state.core
65
62
 
66
63
  if (!state.core.signUp)
@@ -165,12 +162,12 @@ export async function userProblems(core: Core, input: CreateUserInput): Promise<
165
162
  const username = input.username === undefined ? null : normalizeUsername(input.username)
166
163
 
167
164
  if (email === null && username === null)
168
- throw new Error('kayjs-auth: createUser needs an email or a username to sign in with')
165
+ throw new KayError('argument-invalid', 'kayjs-auth: createUser needs an email or a username to sign in with')
169
166
 
170
167
  const undeclared = core.roles && input.roles?.find(role => !core.roles!.has(role))
171
168
 
172
169
  if (undeclared !== undefined)
173
- throw new Error(`kayjs-auth: createUser was given the role '${undeclared}', which the \`roles\` option does not declare`)
170
+ throw new KayError('argument-invalid', `kayjs-auth: createUser was given the role '${undeclared}', which the \`roles\` option does not declare`)
174
171
 
175
172
  const errors: RegisterErrors = {
176
173
  email: email === null ? undefined : emailProblem(email),
@@ -188,7 +185,7 @@ export async function userProblems(core: Core, input: CreateUserInput): Promise<
188
185
  }
189
186
 
190
187
  // A user made by the app, checked as registering is but signing no one in and mailing no one, open with `signUp: false` too.
191
- export async function createUser(core: Core, input: CreateUserInput): Promise<CreateUserResult> {
188
+ export async function createUser(core: Core, input: CreateUserInput): Promise<Result<{ user: BareUser }, never, RegisterErrors>> {
192
189
  const errors = await userProblems(core, input)
193
190
 
194
191
  if (Object.keys(errors).length > 0)
@@ -241,7 +238,7 @@ async function replaceUnclaimed(state: RequestState, holder: UserRecord): Promis
241
238
  }
242
239
 
243
240
  // Spends the time hashing a new password takes, so a held address answers no faster than a free one, and leaves this session as a new account's, which `email.sendVerification` answers alike, mailing no one.
244
- async function answerHeld(state: RequestState, holder: UserRecord, password: string | null): Promise<RegisterResult> {
241
+ async function answerHeld(state: RequestState, holder: UserRecord, password: string | null): Promise<Result<{ user: BareUser, signedIn: true } | { signedIn: false }, 'limited' | 'captcha' | 'off', RegisterErrors>> {
245
242
  if (password !== null)
246
243
  await hashPassword(password)
247
244
 
@@ -264,7 +261,7 @@ async function keepBack(state: RequestState, redirect: string | undefined): Prom
264
261
  await state.session.set('authBack', back)
265
262
  }
266
263
 
267
- export async function signInWithPassword(state: RequestState, input: PasswordSignInInput, options: Pick<SignInOptions, 'redirect' | 'captcha'>): Promise<PasswordSignInResult> {
264
+ export async function signInWithPassword(state: RequestState, input: PasswordSignInInput, options: Pick<SignInOptions, 'redirect' | 'captcha'>): Promise<Result<{ redirect: string }, 'invalid' | 'limited' | 'captcha' | 'unverified' | 'banned'>> {
268
265
  const { store } = state.core
269
266
  // Registration reads the address NFKC-normalised, so a fullwidth at sign names an email here too.
270
267
  const byEmail = input.identifier.normalize('NFKC').includes('@')
package/src/pg.ts CHANGED
@@ -1,7 +1,7 @@
1
1
  import type { Database, InferEntity } from '@kaynooo/pg-orm'
2
2
  import type { AuditRecord, AuthStore, BearerTokenRecord, IdentityRecord, InvitationRecord, MemberRecord, OAuthClientRecord, OAuthCodeRecord, OAuthGrantRecord, OAuthRefreshRecord, OrganizationRecord, PasskeyRecord, PruneLimits, SessionRecord, TokenRecord, TokenType, UserRecord } from './store'
3
3
  import { defineTable } from '@kaynooo/pg-orm'
4
- import { durationSeconds } from 'kay/library'
4
+ import { durationSeconds, KayError, lengthMs } from 'kay/library'
5
5
  import { log } from './log'
6
6
 
7
7
  // Each table keeps the `renamedFrom` of its pre-1.71 `auth_*` name for good, unlike a deprecated form: an app jumping several minors at once still gets its users renamed rather than empty tables beside them, and a rename finding no old table does nothing.
@@ -203,7 +203,7 @@ const UNUSED_CLIENT_MS = 24 * 60 * 60 * 1000
203
203
  // kayjs-auth's data in the app's Postgres or SQLite database, through pg-orm: list `authTables` in the database's tables.
204
204
  export function pgAuth(db: Database): AuthStore {
205
205
  if (typeof (db as Partial<Database> | null)?.repo !== 'function')
206
- throw new TypeError('kayjs-auth: pgAuth takes a pg-orm `Database` listing `authTables`, not a connection URL or a Bun `SQL`: give `auth({ store: { url } })` for a URL')
206
+ throw new KayError('config-invalid', 'kayjs-auth: pgAuth takes a pg-orm `Database` listing `authTables`, not a connection URL or a Bun `SQL`: give `auth({ store: { url } })` for a URL')
207
207
 
208
208
  const users = db.repo(AuthUsers)
209
209
  const identities = db.repo(AuthIdentities)
@@ -482,7 +482,7 @@ export function pgAuth(db: Database): AuthStore {
482
482
 
483
483
  // One statement, so two attempts at once both count: a window still open is raised, an ended one starts over.
484
484
  const [row] = await db.raw<{ count: number, reset_at: Date | string | number }>`
485
- INSERT INTO "kay_attempts" ("key", "count", "reset_at") VALUES (${key}, ${weight}, ${new Date(now.getTime() + window)})
485
+ INSERT INTO "kay_attempts" ("key", "count", "reset_at") VALUES (${key}, ${weight}, ${new Date(now.getTime() + lengthMs(window))})
486
486
  ON CONFLICT ("key") DO UPDATE SET
487
487
  "count" = CASE WHEN "kay_attempts"."reset_at" > ${now} THEN "kay_attempts"."count" + ${weight} ELSE ${weight} END,
488
488
  "reset_at" = CASE WHEN "kay_attempts"."reset_at" > ${now} THEN "kay_attempts"."reset_at" ELSE EXCLUDED."reset_at" END
package/src/profile.ts CHANGED
@@ -1,12 +1,10 @@
1
1
  import type { BareUser } from './core'
2
- import type { AuthFailed, AuthRejected } from './failure'
2
+ import type { AuthRejected } from './failure'
3
3
  import type { ProfileFieldView, ProfileOptions, ProfileProblem } from './pages'
4
4
  import { rejected } from './failure'
5
5
  import { profileLabel, profileValue } from './pages'
6
6
  import { PROFILE_MAX_LENGTH } from './rules'
7
7
 
8
- export type SaveProfileResult = { ok: true } | AuthFailed<'signed-out'> | AuthRejected<Record<string, ProfileProblem>>
9
-
10
8
  // The fields of the profile form with what `user` holds in each.
11
9
  export async function profileFields(profile: ProfileOptions, user: BareUser, locale: string | undefined): Promise<ProfileFieldView[]> {
12
10
  const held = await profile.load(user)
package/src/proof.ts CHANGED
@@ -23,8 +23,6 @@ export interface Proof {
23
23
  // `proof` when the proof was wrong or missing; `stale` when the account has neither a password nor a second factor and was signed into too long ago, so the user signs in again first; `impersonating` when an admin acts as the user, who proves nothing for them.
24
24
  export type ProofFailure = 'signed-out' | 'proof' | 'stale' | 'limited' | 'impersonating'
25
25
 
26
- export type ReproveResult = { ok: true } | AuthFailed<ProofFailure>
27
-
28
26
  // What a sign-in waiting for its second factor keeps in the session.
29
27
  export interface Challenge {
30
28
  user: string
@@ -102,9 +100,9 @@ export async function reprove(state: RequestState, proof: Proof, options: { seco
102
100
  return { ok: true, record }
103
101
  }
104
102
 
105
- // Whether this session signed in or re-proved its user in the last ten minutes.
106
- export async function provedLately(state: RequestState): Promise<boolean> {
103
+ // Whether this session signed in or re-proved its user within `within` milliseconds, the last ten minutes by default.
104
+ export async function provedLately(state: RequestState, within = FRESH_SIGN_IN_MS): Promise<boolean> {
107
105
  const signedIn = await state.session.get('auth')
108
106
 
109
- return signedIn !== undefined && Date.now() - signedIn.at < FRESH_SIGN_IN_MS
107
+ return signedIn !== undefined && Date.now() - signedIn.at < within
110
108
  }
package/src/request.ts CHANGED
@@ -1,20 +1,20 @@
1
- import type { GuardContext } from 'kay'
1
+ import type { Duration, GuardContext } from 'kay'
2
2
  import type { KayConfig, Session } from 'kay/server'
3
3
  import type { CaptchaAction } from './captcha'
4
4
  import type { AuthSessionData, BareUser, Core, SignedIn, User } from './core'
5
+ import type { Result } from './failure'
5
6
  import type { ScopeRequirement } from './gate'
6
7
  import type { AuthFeatures } from './pages'
7
- import type { Proof, ReproveResult } from './proof'
8
- import type { GuestSignInResult } from './sessions'
8
+ import type { Proof, ProofFailure } from './proof'
9
9
  import type { RequestState } from './state'
10
10
  import type { SessionRecord, UserRecord } from './store'
11
11
  import type { Requirement } from './types'
12
12
  import { localPath } from 'kay'
13
- import { durationSeconds, nameUser, overHttps, READ_METHODS, stoppers } from 'kay/library'
13
+ import { durationSeconds, KayError, nameUser, overHttps, READ_METHODS, stoppers } from 'kay/library'
14
14
  import { clientAddress, crossSiteRefused, crossSiteResponse, forgetLocalMirrors, forgetPushDevice, rateKey, toolCall } from 'kay/server'
15
- import { protectedResourceMetadata, rootIsFixed, rootUsable, siteRoot } from './authorize/metadata'
15
+
16
16
  import { bearerRequest, bearerToken } from './bearerHeader'
17
- import { admit, captchaChallenge, captchaRequired } from './captcha'
17
+ import { admit } from './captcha'
18
18
  import { banned, guardPageOf, isNavigation, linkedProviders, linkedUser, newUserRecord, publicUser, unlinked, withBack } from './core'
19
19
  import { report } from './events'
20
20
  import { failed } from './failure'
@@ -24,6 +24,7 @@ import { acceptedLocales } from './locale'
24
24
  import { AccountMethods } from './methods/account'
25
25
  import { AdminMethods } from './methods/admin'
26
26
  import { AuditMethods } from './methods/audit'
27
+ import { CaptchaMethods } from './methods/captcha'
27
28
  import { EmailMethods } from './methods/email'
28
29
  import { MagicLinkMethods } from './methods/magicLink'
29
30
  import { OAuthMethods } from './methods/oauth'
@@ -31,11 +32,12 @@ import { OAuthServerMethods } from './methods/oauthServer'
31
32
  import { OrganizationMethods } from './methods/organizations'
32
33
  import { PasskeyMethods } from './methods/passkeys'
33
34
  import { PasswordMethods } from './methods/password'
35
+ import { ProofMethods } from './methods/proof'
34
36
  import { SessionMethods } from './methods/sessions'
35
37
  import { TokenMethods } from './methods/tokens'
36
38
  import { TwoFactorMethods } from './methods/twoFactor'
37
39
  import { featuresOf } from './pages'
38
- import { completeSignIn, provedLately, reprove } from './proof'
40
+ import { completeSignIn } from './proof'
39
41
  import { pruneWhenDue } from './prune'
40
42
  import { sendToEnrolment } from './requiredTwoFactor'
41
43
  import { roleHierarchy } from './roles'
@@ -47,6 +49,8 @@ export interface RequireUserOptions<Scope extends string, Role extends string> {
47
49
  redirect?: string | undefined
48
50
  scope?: ScopeRequirement<Scope> | undefined
49
51
  require?: AuthRequirement<Role> | undefined
52
+ // A duration such as `'10m'`: the user signed in or re-proved (`reprove`) within it, else a 403, as `guard({ fresh })` does.
53
+ fresh?: Duration | undefined
50
54
  bare?: true | undefined
51
55
  }
52
56
 
@@ -71,6 +75,14 @@ const servedSockets = new WeakSet<object>()
71
75
  // What a route, a guard or a gate asks of the user: a role, a predicate, or a list of which any one passes.
72
76
  export type AuthRequirement<Role extends string> = Requirement<BareUser, Role>
73
77
 
78
+ // What a request with a `fresh` requirement is refused with while the user's last proof is older: the page or the app's client then asks for the password or the passkey again (`reprove`) and retries.
79
+ export const STALE_PROOF = { message: 'Confirm your identity to continue', data: { code: 'stale' } } as const
80
+
81
+ // The milliseconds of a `fresh` duration; a value that is no positive duration throws where the guard is made, not on a request.
82
+ export function freshMs(fresh: Duration): number {
83
+ return durationSeconds(fresh, 'fresh') * 1000
84
+ }
85
+
74
86
  // A session a browser's cross-site POST or websocket upgrade reads as signed out and cannot write, a write answered with a 403: a plain Elysia app has no Origin check of kay's own.
75
87
  function guardSession(session: Session<AuthSessionData>, refuse: () => boolean, refusal: () => Response): Session<AuthSessionData> {
76
88
  const write = <Args extends unknown[]>(call: (...args: Args) => Promise<void>) => async (...args: Args): Promise<void> => {
@@ -88,10 +100,11 @@ function guardSession(session: Session<AuthSessionData>, refuse: () => boolean,
88
100
  settings: session.settings,
89
101
  regenerate: write(async () => session.regenerate()),
90
102
  maxAge: write(async maxAge => session.maxAge(maxAge)),
103
+ start: write(async (data, options) => session.start(data, options)),
91
104
  }
92
105
  }
93
106
 
94
- interface Groups<Scope extends string, Role extends string, OrgRole extends string> {
107
+ interface Groups<Scope extends string, Role extends string, OrgRole extends string, UserData extends object> {
95
108
  password: PasswordMethods
96
109
  email: EmailMethods
97
110
  magicLink: MagicLinkMethods
@@ -100,11 +113,13 @@ interface Groups<Scope extends string, Role extends string, OrgRole extends stri
100
113
  sessions: SessionMethods
101
114
  tokens: TokenMethods<Scope>
102
115
  oauthServer: OAuthServerMethods
103
- admin: AdminMethods<Role>
116
+ admin: AdminMethods<Role, UserData>
104
117
  organizations: OrganizationMethods<OrgRole>
105
118
  account: AccountMethods
106
119
  oauth: OAuthMethods
107
120
  audit: AuditMethods
121
+ captcha: CaptchaMethods
122
+ proof: ProofMethods
108
123
  }
109
124
 
110
125
  // Auth for one request, as `auth` in the context: `ctx.locals.auth` in a page, an action or a guard.
@@ -116,7 +131,7 @@ export class Auth<Scope extends string = string, Role extends string = string, O
116
131
  private tokenScopes: string[] | null = null
117
132
  private linked = new WeakMap<UserRecord, Promise<User['providers']>>()
118
133
  // Each group of methods, made on its first use.
119
- private readonly groups: Partial<Groups<Scope, Role, OrgRole>> = {}
134
+ private readonly groups: Partial<Groups<Scope, Role, OrgRole, UserData>> = {}
120
135
 
121
136
  private readonly session: Session<AuthSessionData>
122
137
  // Set-Cookie lines this request's sign-in or sign-out adds to its response, which the plugin sends.
@@ -235,7 +250,7 @@ export class Auth<Scope extends string = string, Role extends string = string, O
235
250
 
236
251
  // The signed-in user's bearer tokens.
237
252
  get tokens(): TokenMethods<Scope> {
238
- return this.groups.tokens ??= new TokenMethods<Scope>(this[STATE])
253
+ return this.groups.tokens ??= new TokenMethods<Scope>(this[STATE], async () => this.heldScopes())
239
254
  }
240
255
 
241
256
  // The consent page MCP clients send the user to, and the apps they approved.
@@ -244,8 +259,8 @@ export class Auth<Scope extends string = string, Role extends string = string, O
244
259
  }
245
260
 
246
261
  // Listing, banning and impersonating users and granting them roles, for the `admin` option's users.
247
- get admin(): AdminMethods<Role> {
248
- return this.groups.admin ??= new AdminMethods<Role>(this[STATE])
262
+ get admin(): AdminMethods<Role, UserData> {
263
+ return this.groups.admin ??= new AdminMethods<Role, UserData>(this[STATE], async () => this.adminUser())
249
264
  }
250
265
 
251
266
  // The organizations of the `organizations` option.
@@ -270,6 +285,16 @@ export class Auth<Scope extends string = string, Role extends string = string, O
270
285
  return this.groups.audit ??= new AuditMethods(this[STATE])
271
286
  }
272
287
 
288
+ // What a page needs to show the CAPTCHA the next action asks for.
289
+ get captcha(): CaptchaMethods {
290
+ return this.groups.captcha ??= new CaptchaMethods(this[STATE])
291
+ }
292
+
293
+ // Whether the user proved themselves lately, and proving again before a sensitive change.
294
+ get proof(): ProofMethods {
295
+ return this.groups.proof ??= new ProofMethods(this[STATE], freshMs)
296
+ }
297
+
273
298
  // The signed-in user, or the owner of the request's `Authorization: Bearer` token, or null; read on first use, and again past 30 seconds on a websocket.
274
299
  async user(): Promise<User<UserData> | null> {
275
300
  const record = await this.record()
@@ -309,7 +334,7 @@ export class Auth<Scope extends string = string, Role extends string = string, O
309
334
  if (signIn !== undefined && isNavigation(this.request))
310
335
  redirect(this.signInLink(signIn))
311
336
 
312
- return deny(401, 'Sign in to continue')
337
+ return deny(401, { message: 'Sign in to continue' })
313
338
  }
314
339
 
315
340
  const user = publicUser(record) as BareUser<UserData>
@@ -317,14 +342,22 @@ export class Auth<Scope extends string = string, Role extends string = string, O
317
342
  if (options.require !== undefined && !(await this.core.access.authorize(user as BareUser, options.require, READ_METHODS.has(this.request.method) ? 'read' : 'write', {})))
318
343
  return deny(403)
319
344
 
320
- if (!scopeAllows(await this.scopes(), options.scope))
345
+ if (!scopeAllows(await this.heldScopes(), options.scope))
321
346
  return deny(403)
322
347
 
348
+ if (options.fresh !== undefined && !(await this.proof.recent(options.fresh)))
349
+ return deny(403, STALE_PROOF)
350
+
323
351
  return options.bare ? user : { ...user, providers: await this.providersOf(record) }
324
352
  }
325
353
 
326
- // The signed-in admin, as themselves, for an admin page to ask for: 404 while the `admin` option names no one (a `Denied`, which a plain Elysia app answers too), a visitor sent to sign in as `requireUser()` does, and 403 for anyone else, an admin acting as a user and a bearer token included.
354
+ /** @deprecated Use `admin.require()`. Removed in 1.108.0; `deprecated-auth-methods` rewrites it. */
327
355
  async requireAdmin(): Promise<User<UserData>> {
356
+ return this.admin.require()
357
+ }
358
+
359
+ // What `admin.require()` answers with.
360
+ private async adminUser(): Promise<User<UserData>> {
328
361
  if (!this.core.admin)
329
362
  return stoppers(this.request).deny(404)
330
363
 
@@ -365,10 +398,10 @@ export class Auth<Scope extends string = string, Role extends string = string, O
365
398
  const record = await this.core.store.users.get(user.id)
366
399
 
367
400
  if (!record)
368
- throw new Error(`kayjs-auth: no user ${user.id} to sign in`)
401
+ throw new KayError('helper-failed', `kayjs-auth: no user ${user.id} to sign in`)
369
402
 
370
403
  if (banned(record))
371
- throw new Error(`kayjs-auth: user ${user.id} is banned`)
404
+ throw new KayError('helper-failed', `kayjs-auth: user ${user.id} is banned`)
372
405
 
373
406
  await chooseRemember(this[STATE], options.remember)
374
407
  await this.establish(record, 'app')
@@ -439,7 +472,7 @@ export class Auth<Scope extends string = string, Role extends string = string, O
439
472
  }
440
473
 
441
474
  // Signs this browser in as a new guest, a user with no email and no password whom registering or an OAuth sign-in later makes a real account, keeping their id; the guest signed in already answers as is. Counted as registering is, and CAPTCHA-checked as `guest`.
442
- async signInAsGuest(options: { captcha?: string | undefined } = {}): Promise<GuestSignInResult> {
475
+ async signInAsGuest(options: { captcha?: string | undefined } = {}): Promise<Result<{ user: BareUser }, 'limited' | 'captcha' | 'signed-in' | 'off'>> {
443
476
  const current = await this.record()
444
477
 
445
478
  if (current)
@@ -467,58 +500,56 @@ export class Auth<Scope extends string = string, Role extends string = string, O
467
500
  return featuresOf(this.core)
468
501
  }
469
502
 
470
- // The RFC 9728 metadata of the protected resource `name` served at `path`, which kay's MCP endpoint asks for; null while the OAuth server is off. It points MCP clients at the app's own authorization server.
503
+ /** @deprecated Use `oauthServer.resource()`. Removed in 1.108.0; `deprecated-auth-methods` rewrites it. */
471
504
  oauthResource(path: string, name: string): Record<string, unknown> | null {
472
- if (!this.core.oauthServer || !rootUsable(this.core))
473
- return null
474
-
475
- const root = siteRoot(this.core, this.request)
476
-
477
- return protectedResourceMetadata(this.core, root, `${root}${path}`, name)
505
+ return this.oauthServer.resource(path, name)
478
506
  }
479
507
 
480
- // The origin the OAuth documents are served at, which kay's 401 pointer to them names; undefined while the OAuth server is off.
508
+ /** @deprecated Use `oauthServer.origin()`. Removed in 1.108.0; `deprecated-auth-methods` rewrites it. */
481
509
  oauthOrigin(): string | undefined {
482
- return this.core.oauthServer && rootUsable(this.core) ? new URL(siteRoot(this.core, this.request)).origin : undefined
510
+ return this.oauthServer.origin()
483
511
  }
484
512
 
485
- // Whether that origin is configured, so the documents may be cached for everyone; else it is the request's own.
513
+ /** @deprecated Use `oauthServer.fixed()`. Removed in 1.108.0; `deprecated-auth-methods` rewrites it. */
486
514
  oauthFixed(): boolean {
487
- return rootIsFixed(this.core)
515
+ return this.oauthServer.fixed()
488
516
  }
489
517
 
490
- // Whether this client's next `action` needs a CAPTCHA token, for the page to show the widget.
518
+ /** @deprecated Use `captcha.required()`. Removed in 1.108.0; `deprecated-auth-methods` rewrites it. */
491
519
  async captchaRequired(action: CaptchaAction): Promise<boolean> {
492
- return captchaRequired(this[STATE], action)
520
+ return this.captcha.required(action)
493
521
  }
494
522
 
495
- // The proof-of-work challenge for this client's next `action`, for a form field kay's script posts the solution of; null when none is needed.
523
+ /** @deprecated Use `captcha.challenge()`. Removed in 1.108.0; `deprecated-auth-methods` rewrites it. */
496
524
  async captchaChallenge(action: CaptchaAction): Promise<string | null> {
497
- return captchaChallenge(this[STATE], action)
525
+ return this.captcha.challenge(action)
498
526
  }
499
527
 
500
- // Whether this session signed in or re-proved its user in the last ten minutes, as `exportData()` and the admin methods ask, for a page to show a form for `reprove` first.
501
- async provedLately(): Promise<boolean> {
502
- return provedLately(this[STATE])
528
+ /** @deprecated Use `proof.recent()`. Removed in 1.108.0; `deprecated-auth-methods` rewrites it. */
529
+ async provedLately(fresh?: Duration): Promise<boolean> {
530
+ return this.proof.recent(fresh)
503
531
  }
504
532
 
505
- // Re-proves the signed-in user, as before an app's own sensitive change: a proof counts for ten minutes, as a sign-in does.
506
- async reprove(proof: Proof): Promise<ReproveResult> {
507
- const proved = await reprove(this[STATE], proof)
533
+ /** @deprecated Use `proof.renew()`. Removed in 1.108.0; `deprecated-auth-methods` rewrites it. */
534
+ async reprove(proof: Proof): Promise<Result<object, ProofFailure>> {
535
+ return this.proof.renew(proof)
536
+ }
508
537
 
509
- return proved.ok ? { ok: true } : proved
538
+ /** @deprecated Use `tokens.scopes()`. Removed in 1.108.0; `deprecated-auth-methods` rewrites it. */
539
+ async scopes(): Promise<string[] | null> {
540
+ return this.heldScopes()
510
541
  }
511
542
 
512
543
  // The scopes of the bearer token this request came with; null for a session, or a token with every scope.
513
- async scopes(): Promise<string[] | null> {
544
+ private async heldScopes(): Promise<string[] | null> {
514
545
  await this.record()
515
546
 
516
547
  return this.tokenScopes && [...this.tokenScopes]
517
548
  }
518
549
 
519
- // Whether this request may reach what `scope` guards: a session may, and a token given that scope or every one.
550
+ /** @deprecated Use `tokens.hasScope()`. Removed in 1.108.0; `deprecated-auth-methods` rewrites it. */
520
551
  async hasScope(scope: Scope): Promise<boolean> {
521
- return scopeAllows(await this.scopes(), scope)
552
+ return this.tokens.hasScope(scope)
522
553
  }
523
554
 
524
555
  // The ids of the users holding `role`, one of the `roles` option or a role above it in its hierarchy, banned users left out, for server code that tells them something (a notification). Needs a signed-in user, and reads the 10,000 newest users at most.
@@ -654,7 +685,7 @@ export function authOf(ctx: object): Auth {
654
685
  const auth = (ctx as { auth?: unknown }).auth
655
686
 
656
687
  if (!(auth instanceof Auth))
657
- throw new Error('kayjs-auth: no `auth` in this context; `.use(auth.plugin)` before the routes and pages that read it')
688
+ throw new KayError('config-invalid', 'kayjs-auth: no `auth` in this context; `.use(auth.plugin)` before the routes and pages that read it')
658
689
 
659
690
  return auth as Auth
660
691
  }
@@ -665,7 +696,7 @@ export function requestAuth<Scope extends string, Role extends string, OrgRole e
665
696
 
666
697
  // Elysia uses a plugin once per app, so a plugin of the app's own that used the session plugin first keeps it to itself, out of the routes auth reaches.
667
698
  if (!session)
668
- throw new Error('kayjs-auth: no session reaches this route. Use the session plugin on the app itself, or leave it to auth.plugin, rather than in a plugin of the app\'s own before auth.plugin')
699
+ throw new KayError('outside-request', 'kayjs-auth: no session reaches this route. Use the session plugin on the app itself, or leave it to auth.plugin, rather than in a plugin of the app\'s own before auth.plugin')
669
700
 
670
701
  core.settle()
671
702
 
@@ -55,7 +55,7 @@ export async function lacksTwoFactor(state: RequestState, user: BareUser, ask: T
55
55
  // What `ctx.redirect` and `ctx.deny` are in a guard, a page or an action.
56
56
  export interface Stoppers {
57
57
  redirect: (location: string) => never
58
- deny: (status?: number, message?: string) => never
58
+ deny: (status?: number, options?: { message?: string | undefined }) => never
59
59
  }
60
60
 
61
61
  // A page opening goes to the security page to turn two-factor on, coming back after; anything else, and an app with no such page, gets the 403.
@@ -67,5 +67,5 @@ export function sendToEnrolment(core: Core, request: Request, { redirect, deny }
67
67
  redirect(withBack(core.securityPage, localPath(here.pathname + here.search, '/')))
68
68
  }
69
69
 
70
- return deny(403, 'Two-factor authentication is required')
70
+ return deny(403, { message: 'Two-factor authentication is required' })
71
71
  }
package/src/routes.ts CHANGED
@@ -20,7 +20,7 @@ const UNSAFE_FILE_NAME = /[^\w.-]/g
20
20
 
21
21
  // What the routes read of Elysia's context.
22
22
  interface RouteContext {
23
- auth: Pick<Auth, typeof STATE | 'account' | 'signOut' | 'admin'>
23
+ auth: Pick<Auth, typeof STATE | 'account' | 'signOut'> & { admin: Pick<Auth['admin'], 'stopImpersonating'> }
24
24
  request: Request
25
25
  body: unknown
26
26
  query: Record<string, unknown>
@@ -117,7 +117,7 @@ export async function cancelDeletionRoute({ auth, body, redirect, request }: Rou
117
117
  return redirect(afterwards(body, core), 303)
118
118
  }
119
119
 
120
- // A GET, so a sign-in link works without JavaScript: give it `data-no-prefetch` so a hover starts nothing.
120
+ // A GET, so a sign-in link works without JavaScript: give it `data-prefetch="false"` so a hover starts nothing.
121
121
  export async function startOAuthRoute({ auth, params: { provider = '' }, query, redirect, status }: RouteContext, core: Core, failurePage: string | undefined) {
122
122
  const started = !core.oauth.has(provider) ? undefined : await (await load.flow()).startOAuth(auth[STATE], provider, { redirect: text(query.redirect), remember: query.remember === undefined ? undefined : query.remember === '1' })
123
123
 
package/src/sessions.ts CHANGED
@@ -1,7 +1,7 @@
1
1
  import type { SessionSettings } from 'kay/server'
2
- import type { BareUser, Core } from './core'
2
+ import type { Core } from './core'
3
3
  import type { Device } from './device'
4
- import type { AuthFailed } from './failure'
4
+ import type { Result } from './failure'
5
5
  import type { RequestState } from './state'
6
6
  import type { SessionRecord, UserRecord } from './store'
7
7
  import { durationSeconds } from 'kay/library'
@@ -12,10 +12,6 @@ import { log } from './log'
12
12
 
13
13
  const USER_AGENT_MAX_LENGTH = 512
14
14
 
15
- export type RevokeSessionResult = { ok: true } | AuthFailed<'signed-out' | 'not-found'>
16
-
17
- export type GuestSignInResult = { ok: true, user: BareUser } | AuthFailed<'limited' | 'captcha' | 'signed-in' | 'off'>
18
-
19
15
  // Where the user is signed in, as the app lists it.
20
16
  export interface UserSession {
21
17
  id: string
@@ -55,7 +51,7 @@ export async function liveSession(state: RequestState, found: SessionRecord | un
55
51
  }
56
52
 
57
53
  // Ends one of the signed-in user's sessions, effective on its next request; ending this one signs out through `signOut`.
58
- export async function revokeSession(state: RequestState, id: string, signOut: () => Promise<void>): Promise<RevokeSessionResult> {
54
+ export async function revokeSession(state: RequestState, id: string, signOut: () => Promise<void>): Promise<Result<object, 'signed-out' | 'not-found'>> {
59
55
  const record = await state.current()
60
56
  const signedIn = await state.session.get('auth')
61
57
 
package/src/setup.ts CHANGED
@@ -70,9 +70,11 @@ function hooked<Args extends unknown[], Result>(hook: ((...args: never[]) => Res
70
70
  return hook && ((...args: Args) => hook(event(...args) as never))
71
71
  }
72
72
 
73
- // `onSignUp` as the flows call it: told through `dispatch`, so a throw is reported and never fails the sign-up that happened.
74
- function signUpHook(hook: AuthOptions<AuthSessionData, string>['onSignUp']): Core['onSignUp'] {
75
- return hook && (async (user, profile) => dispatch('auth.onSignUp', [hook as never], { user, profile }, { context: await authContext() }))
73
+ // `afterSignUp` as the flows call it: told through `dispatch`, so a throw is reported and never fails the sign-up that happened.
74
+ function signUpHook({ afterSignUp: hook = undefined, onSignUp }: Pick<AuthOptions<AuthSessionData, string>, 'afterSignUp' | 'onSignUp'>): Core['onSignUp'] {
75
+ hook ??= onSignUp
76
+
77
+ return hook && (async (user, profile) => dispatch('auth.afterSignUp', [hook as never], { user, profile }, { context: await authContext() }))
76
78
  }
77
79
 
78
80
  // `beforeDelete` as the erase asks it: a refusal answers the failure of kind `refused`, carrying the status and message the hook gave.
@@ -329,7 +331,7 @@ export function createCore<Data extends AuthSessionData, Role extends string, Pr
329
331
  access: access as unknown as Access<string>,
330
332
  ...admin !== undefined && { admin: async user => access.authorize(user, admin, 'write', {}) },
331
333
  guard: guardOptions => guardOf(core, guardOptions),
332
- onSignUp: signUpHook(options.onSignUp),
334
+ onSignUp: signUpHook(options),
333
335
  onProviderProfile: hooked(options.profileFields, (user, profile) => ({ user, profile })),
334
336
  userData: options.user && userDataRules(options.user),
335
337
  beforeDelete: deleteHook(options.beforeDelete),
package/src/sqlite.ts ADDED
@@ -0,0 +1,6 @@
1
+ import type { StoreUrl } from './own'
2
+
3
+ // kayjs-auth's data in a SQLite file, through pg-orm: `auth({ store: sqliteAuth('data/users.sqlite') })`. The file is made, and its `kay_*` tables with it, when the server starts; a relative path is kept under the project root.
4
+ export function sqliteAuth(path: string): StoreUrl {
5
+ return { url: `sqlite://${path}` }
6
+ }
package/src/test.ts CHANGED
@@ -2,7 +2,9 @@ import type { BareUser } from './core'
2
2
  import type { OAuthSite, OAuthTest } from './oauthTest'
3
3
  import type { CreateUserInput } from './password'
4
4
  import type { TotpEnrolment } from './twoFactor'
5
+ import { KayError } from 'kay/library'
5
6
  import { builtOwn } from './own'
7
+ import { signInHook } from './testHook'
6
8
 
7
9
  // What `auth.test(site)` gives.
8
10
  export interface AuthTest {
@@ -10,6 +12,8 @@ export interface AuthTest {
10
12
  signInAs: (who: Omit<CreateUserInput, 'roles'> & { roles?: string[] | undefined, data?: object | undefined }) => Promise<BareUser>
11
13
  // Signs the site out, its other cookies kept.
12
14
  signOut: () => void
15
+ // Signs the site out, as the start of a test wants.
16
+ reset: () => void
13
17
  // The `Cookie` header of a new session signed in as that user.
14
18
  sessionCookie: (userId: string, options?: { secure?: boolean }) => Promise<string>
15
19
  // Turns two-factor on for that member as the app would, so a password sign-in asks for a code: the authenticator's `secret`, `code(offset?)` for the current step and the `recoveryCodes`, all usable at the next sign-in. Throws for a missing member or one who has it already.
@@ -23,19 +27,20 @@ export interface OwnTest {
23
27
  }
24
28
 
25
29
  // The `auth.test(site)` of an app whose kay.config.ts holds `auth()` and no `src/auth.ts` module: the auth that site's `testSite()` built, found as a call needs it, so call it after `testSite()`.
26
- export function authTest(site: OAuthSite): AuthTest {
30
+ export function test(site: OAuthSite): AuthTest {
27
31
  const made = () => {
28
32
  const own = builtOwn(site)
29
33
 
30
34
  if (!own)
31
- throw new Error('kayjs-auth: authTest found no `auth()` built for this test site: await `testSite()` first, and give `authTest` the site it returned, of a project whose kay.config.ts registers `auth()` with no `module`')
35
+ throw new KayError('config-invalid', 'kayjs-auth: test(site) found no `auth()` built for this test site: await `testSite()` first, and give `test` the site it returned, of a project whose kay.config.ts registers `auth()` with no `module`')
32
36
 
33
37
  return own.test(site)
34
38
  }
35
39
 
36
- return {
40
+ const helper: AuthTest = {
37
41
  signInAs: async who => made().signInAs(who),
38
42
  signOut: () => made().signOut(),
43
+ reset: () => made().signOut(),
39
44
  sessionCookie: async (userId, options) => made().sessionCookie(userId, options),
40
45
  enrollTotp: async userId => made().enrollTotp(userId),
41
46
  oauth: {
@@ -43,4 +48,11 @@ export function authTest(site: OAuthSite): AuthTest {
43
48
  signIn: async (provider, options) => made().oauth.signIn(provider, options),
44
49
  },
45
50
  }
51
+
52
+ site.joinSignIn?.(signInHook(helper))
53
+
54
+ return helper
46
55
  }
56
+
57
+ /** @deprecated `test(site)`, the same helper under the name every library's test entry shares. Removed in 1.108.0; `deprecated-test-helpers` rewrites it. */
58
+ export const authTest = test