@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
package/src/mail.ts CHANGED
@@ -2,7 +2,7 @@ import type { Duration } from 'kay'
2
2
  import type { AuthLinkKind, AuthMailData, AuthMailKind, AuthMailWording, AuthNoticeKind } from 'kay/library/auth-mails'
3
3
  import type { EmailCore, EmailOptions } from './email'
4
4
  import { within } from '@kaynooo/utils/promise'
5
- import { configError, durationWords, escapeHtml as escape, siteLocales, trackDetached } from 'kay/library'
5
+ import { configError, durationWords, escapeHtml as escape, KayError, siteLocales, trackDetached } from 'kay/library'
6
6
  import { AUTH_LINK_KINDS, AUTH_MAIL_WORDING, AUTH_NOTICE_KINDS } from 'kay/library/auth-mails'
7
7
  import { language, pickLocale } from './locale'
8
8
  import { log } from './log'
@@ -33,6 +33,8 @@ export interface AuthMailMessage extends MailContent {
33
33
  // The language it is written in, one of the `locales` option's.
34
34
  locale: string
35
35
  // How long its link and its code work, for the ones it carries, as durations such as `'24h'`.
36
+ ttl?: { link?: Duration, code?: Duration } | undefined
37
+ /** @deprecated Written `ttl`; `deprecated-ttl-names` rewrites it. Removed in 1.108. */
36
38
  maxAge?: { link?: Duration, code?: Duration } | undefined
37
39
  }
38
40
 
@@ -102,7 +104,7 @@ export function lifetime(duration: Duration, locale: string): string {
102
104
 
103
105
  // How long what the mail carries works, a magic link being usable once.
104
106
  function lasting(words: AuthMailWording, data: MailData, once: boolean): string {
105
- const { link, code } = data.maxAge ?? {}
107
+ const { link, code } = data.ttl ?? data.maxAge ?? {}
106
108
  const linkWorks = data.url === undefined || link === undefined ? undefined : words.linkWorks.replace('{duration}', () => lifetime(link, data.locale) + (once ? words.once : ''))
107
109
  const codeWorks = data.code === undefined || code === undefined ? undefined : words.codeWorks.replace('{duration}', () => lifetime(code, data.locale))
108
110
 
@@ -181,7 +183,7 @@ export function sendAside(email: EmailCore, build: () => AuthMailMessage, what:
181
183
  trackDetached((async () => {
182
184
  try {
183
185
  if (await within(Promise.resolve(email.mailer.send(build())), ASIDE_TIMEOUT_MS, LATE) === LATE)
184
- throw new Error(`no answer from the mailer in ${ASIDE_TIMEOUT_MS / 1000} s`)
186
+ throw new KayError('helper-failed', `no answer from the mailer in ${ASIDE_TIMEOUT_MS / 1000} s`, { kind: 'mailer-aside-timeout' })
185
187
  }
186
188
  catch (error) {
187
189
  log.error(`mailing ${what} failed`, error)
@@ -1,5 +1,5 @@
1
1
  import type { AuditRecord, AuthStore, BearerTokenRecord, IdentityRecord, InvitationRecord, MemberRecord, OAuthClientRecord, OAuthCodeRecord, OAuthGrantRecord, OAuthRefreshRecord, OrganizationRecord, PasskeyRecord, PruneLimits, SessionRecord, TokenRecord, UserRecord } from './store'
2
- import { durationSeconds } from 'kay/library'
2
+ import { durationSeconds, KayError } from 'kay/library'
3
3
  import { memoryAuthRates } from './rates'
4
4
 
5
5
  // A client that registered itself and was never approved by anyone is dropped after this long.
@@ -37,7 +37,7 @@ export function memoryAuth(): AuthStore {
37
37
  const claimSlug = (organization: OrganizationRecord) => {
38
38
  for (const other of organizations.values()) {
39
39
  if (organization.slug !== null && other.slug === organization.slug && other.id !== organization.id)
40
- throw new Error(`kayjs-auth: the slug ${organization.slug} is taken`)
40
+ throw new KayError('helper-failed', `kayjs-auth: the slug ${organization.slug} is taken`)
41
41
  }
42
42
  }
43
43
 
@@ -60,7 +60,7 @@ export function memoryAuth(): AuthStore {
60
60
  const other = holder(field, user[field])
61
61
 
62
62
  if (other && other.id !== user.id)
63
- throw new Error(`kayjs-auth: the ${field} ${user[field]} is taken`)
63
+ throw new KayError('helper-failed', `kayjs-auth: the ${field} ${user[field]} is taken`)
64
64
  }
65
65
  }
66
66
 
@@ -176,7 +176,7 @@ export function memoryAuth(): AuthStore {
176
176
  const key = identityKey(identity.provider, identity.providerId)
177
177
 
178
178
  if (identities.has(key))
179
- throw new Error(`kayjs-auth: that ${identity.provider} account is linked already`)
179
+ throw new KayError('helper-failed', `kayjs-auth: that ${identity.provider} account is linked already`)
180
180
 
181
181
  identities.set(key, { ...identity })
182
182
  },
@@ -246,7 +246,7 @@ export function memoryAuth(): AuthStore {
246
246
  passkeys: {
247
247
  create(passkey) {
248
248
  if (passkeys.has(passkey.id))
249
- throw new Error(`kayjs-auth: the passkey ${passkey.id} is taken`)
249
+ throw new KayError('helper-failed', `kayjs-auth: the passkey ${passkey.id} is taken`)
250
250
 
251
251
  passkeys.set(passkey.id, copyPasskey(passkey)!)
252
252
  },
@@ -484,7 +484,7 @@ export function memoryAuth(): AuthStore {
484
484
  const key = memberKey(member.organizationId, member.userId)
485
485
 
486
486
  if (members.has(key))
487
- throw new Error(`kayjs-auth: user ${member.userId} is a member already`)
487
+ throw new KayError('helper-failed', `kayjs-auth: user ${member.userId} is a member already`)
488
488
 
489
489
  members.set(key, copyMember(member)!)
490
490
  },
@@ -11,6 +11,7 @@ export default defineMessages({
11
11
  remember: 'Rester connecté',
12
12
  signIn: {
13
13
  title: 'Connexion',
14
+ link: 'Se connecter',
14
15
  identifier: 'Adresse e-mail ou nom d’utilisateur',
15
16
  submit: 'Se connecter',
16
17
  provider: 'Continuer avec {provider}',
@@ -1,11 +1,12 @@
1
- import type { ChangeUsernameResult, DeleteAccountResult, UpdateLocaleResult } from '../account'
2
- import type { CancelDeletionResult } from '../deletion'
1
+ import type { BareUser } from '../core'
3
2
  import type { DeletionImpact } from '../erase'
4
- import type { ExportResult } from '../export'
5
- import type { ProfileFieldView } from '../pages'
6
- import type { SaveProfileResult } from '../profile'
7
- import type { Proof } from '../proof'
3
+ import type { DataExport } from '../export'
4
+ import type { Result } from '../failure'
5
+ import type { ProfileFieldView, ProfileProblem } from '../pages'
6
+ import type { Proof, ProofFailure } from '../proof'
7
+ import type { UsernameProblem } from '../rules'
8
8
  import type { RequestState } from '../state'
9
+ import { KayError } from 'kay/library'
9
10
  import { publicUser } from '../core'
10
11
  import { failed } from '../failure'
11
12
  import { load } from '../load'
@@ -15,22 +16,22 @@ export class AccountMethods {
15
16
  constructor(private readonly state: RequestState) {}
16
17
 
17
18
  // Names the signed-in user, or renames them, under the rules register checks; no proof, a name being no credential.
18
- async changeUsername(username: string): Promise<ChangeUsernameResult> {
19
+ async updateUsername(username: string): Promise<Result<{ user: BareUser }, 'signed-out', { username: UsernameProblem | 'taken' | 'unchanged' }>> {
19
20
  return (await load.account()).changeUsername(this.state, username)
20
21
  }
21
22
 
22
23
  // Sets the language the signed-in user's mails are written in, a BCP 47 tag such as `fr`; refused with `signed-out`, or `invalid-locale` for anything else than a tag.
23
- async updateLocale(locale: string): Promise<UpdateLocaleResult> {
24
+ async updateLocale(locale: string): Promise<Result<object, 'signed-out' | 'invalid-locale'>> {
24
25
  return (await load.account()).updateLocale(this.state, locale)
25
26
  }
26
27
 
27
28
  // Deletes the signed-in user, calling `beforeDelete` for the app's own records, and signs this session out, or with `account.deleteAfter` only marks the account pending (`{ ok: true, deleteAt }`) and stays signed in, the prune deleting it once the period ends; the last admin and the only owner of an organization with other members are refused, an organization they are alone in is deleted with them.
28
- async delete(proof: Proof): Promise<DeleteAccountResult> {
29
+ async delete(proof: Proof): Promise<Result<{ deleteAt?: Date }, ProofFailure | 'last-admin' | 'last-owner' | 'refused'>> {
29
30
  return (await load.account()).deleteAccount(this.state, proof, this.state.signOut)
30
31
  }
31
32
 
32
33
  // With `account.deleteAfter`, takes the pending deletion off the signed-in user's account and tells them; refused with `signed-out`, or `not-pending` when the account is not pending deletion.
33
- async cancelDeletion(): Promise<CancelDeletionResult> {
34
+ async cancelDeletion(): Promise<Result<object, 'signed-out' | 'not-pending'>> {
34
35
  return (await load.deletion()).cancelDeletion(this.state)
35
36
  }
36
37
 
@@ -47,7 +48,7 @@ export class AccountMethods {
47
48
  }
48
49
 
49
50
  // The fields of the profile form the account page shows beside the username, with what this user holds in each, or null when `pages.profile` is not set or the user is not signed in with a session.
50
- async profile(locale?: string): Promise<ProfileFieldView[] | null> {
51
+ async getProfile(locale?: string): Promise<ProfileFieldView[] | null> {
51
52
  const profile = this.state.core.pages?.profile
52
53
  const record = profile && await this.state.current()
53
54
 
@@ -58,11 +59,11 @@ export class AccountMethods {
58
59
  }
59
60
 
60
61
  // Stores the values posted from that form through `pages.profile.save`, once trimmed and checked against each field's `required` and `maxLength`: names that are no field are dropped, and nothing is stored while any field is refused.
61
- async saveProfile(values: Record<string, unknown>): Promise<SaveProfileResult> {
62
+ async updateProfile(values: Record<string, unknown>): Promise<Result<object, 'signed-out', Record<string, ProfileProblem>>> {
62
63
  const profile = this.state.core.pages?.profile
63
64
 
64
65
  if (!profile)
65
- throw new Error('kayjs-auth: account.saveProfile needs `pages.profile` in authCore')
66
+ throw new KayError('config-invalid', 'kayjs-auth: account.saveProfile needs `pages.profile` in authCore')
66
67
 
67
68
  const record = await this.state.current()
68
69
 
@@ -74,7 +75,22 @@ export class AccountMethods {
74
75
  }
75
76
 
76
77
  // Everything kayjs-auth keeps about the signed-in user, secrets left out, with the app's own from `exportData`: for a download of their data.
77
- async export(): Promise<ExportResult> {
78
+ async export(): Promise<Result<{ data: DataExport }, 'signed-out' | 'limited' | 'impersonating' | 'stale'>> {
78
79
  return (await load.exports()).exportData(this.state)
79
80
  }
81
+
82
+ /** @deprecated Use `account.updateUsername`. Removed in 1.108.0; `deprecated-auth-methods` rewrites it. */
83
+ async changeUsername(...args: Parameters<AccountMethods['updateUsername']>): ReturnType<AccountMethods['updateUsername']> {
84
+ return this.updateUsername(...args)
85
+ }
86
+
87
+ /** @deprecated Use `account.getProfile`. Removed in 1.108.0; `deprecated-auth-methods` rewrites it. */
88
+ async profile(...args: Parameters<AccountMethods['getProfile']>): ReturnType<AccountMethods['getProfile']> {
89
+ return this.getProfile(...args)
90
+ }
91
+
92
+ /** @deprecated Use `account.updateProfile`. Removed in 1.108.0; `deprecated-auth-methods` rewrites it. */
93
+ async saveProfile(...args: Parameters<AccountMethods['updateProfile']>): ReturnType<AccountMethods['updateProfile']> {
94
+ return this.updateProfile(...args)
95
+ }
80
96
  }
@@ -1,58 +1,65 @@
1
- import type { AdminAuditLogResult, BanResult, DeleteResult, GetUserResult, ImpersonateResult, ListUsersResult, RoleResult, UnbanResult } from '../admin'
2
- import type { AuditCursorInput } from '../events'
1
+ import type { AdminChangeFailure, AdminFailure, ManagedUser } from '../admin'
2
+ import type { User } from '../core'
3
+ import type { AuditCursorInput, AuditEntry } from '../events'
4
+ import type { Result } from '../failure'
3
5
  import type { RequestState } from '../state'
4
6
  import { load } from '../load'
5
7
 
6
8
  // `auth.admin`: what the `admin` option's users may do to other users, every method answering `forbidden` for anyone else.
7
- export class AdminMethods<Role extends string = string> {
8
- constructor(private readonly state: RequestState) {}
9
+ export class AdminMethods<Role extends string = string, UserData extends object = Record<string, unknown>> {
10
+ constructor(private readonly state: RequestState, private readonly asking: () => Promise<User<UserData>>) {}
11
+
12
+ // 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.
13
+ async require(): Promise<User<UserData>> {
14
+ return this.asking()
15
+ }
9
16
 
10
17
  // The users, newest first, a page of `limit` (50 by default) from `offset`; `search` matches part of an email or a username, or a whole id.
11
- async listUsers(query: { search?: string, offset?: number, limit?: number } = {}): Promise<ListUsersResult> {
18
+ async listUsers(query: { search?: string, offset?: number, limit?: number } = {}): Promise<Result<{ users: ManagedUser[], total: number }, 'forbidden' | 'two-factor-required'>> {
12
19
  return (await load.admin()).listUsers(this.state, query)
13
20
  }
14
21
 
15
22
  // One user; `admin` tells whether they meet the `admin` option, whom an admin can neither ban, impersonate nor delete.
16
- async getUser(userId: string): Promise<GetUserResult> {
23
+ async getUser(userId: string): Promise<Result<{ user: ManagedUser, admin: boolean }, AdminFailure>> {
17
24
  return (await load.admin()).getUser(this.state, userId)
18
25
  }
19
26
 
20
27
  // The roles an admin may give, those `roles` declares; none without it.
21
- roles(): string[] {
28
+ listRoles(): string[] {
22
29
  return [...this.state.core.roles ?? []]
23
30
  }
24
31
 
25
32
  // Gives a user a role the app declares, effective on their next request.
26
- async grantRole(userId: string, role: Role): Promise<RoleResult> {
33
+ async grantRole(userId: string, role: Role): Promise<Result<{ user: ManagedUser }, AdminChangeFailure | 'unknown-role' | 'self' | 'last-admin'>> {
27
34
  return (await load.admin()).changeRole(this.state, userId, role, true)
28
35
  }
29
36
 
30
37
  // Takes a role back; one that would leave the admin asking no longer an admin is refused (`self`), and one that races another admin's revoke and would leave none is undone (`last-admin`).
31
- async revokeRole(userId: string, role: Role): Promise<RoleResult> {
38
+ async revokeRole(userId: string, role: Role): Promise<Result<{ user: ManagedUser }, AdminChangeFailure | 'unknown-role' | 'self' | 'last-admin'>> {
32
39
  return (await load.admin()).changeRole(this.state, userId, role, false)
33
40
  }
34
41
 
35
42
  // Bars a user from signing in, for good or `until` then, and signs them out everywhere; another admin is refused.
36
- async ban(userId: string, options: { reason?: string, until?: Date } = {}): Promise<BanResult> {
43
+ async ban(userId: string, options: { reason?: string, until?: Date } = {}): Promise<Result<{ user: ManagedUser }, AdminChangeFailure | 'self' | 'admin' | 'until'>> {
37
44
  return (await load.admin()).banUser(this.state, userId, options)
38
45
  }
39
46
 
40
- async unban(userId: string): Promise<UnbanResult> {
47
+ async unban(userId: string): Promise<Result<{ user: ManagedUser }, AdminChangeFailure>> {
41
48
  return (await load.admin()).unbanUser(this.state, userId)
42
49
  }
43
50
 
44
51
  // Deletes a user with everything kayjs-auth keeps for them, calling `onDelete` and mailing them the account-deleted notice; oneself and another admin are refused.
45
- async deleteUser(userId: string): Promise<DeleteResult> {
52
+ async deleteUser(userId: string): Promise<Result<object, AdminChangeFailure | 'self' | 'admin' | 'refused'>> {
46
53
  return (await load.admin()).deleteUser(this.state, userId)
47
54
  }
48
55
 
49
56
  // Everyone's audit log, or `userId`'s, newest first.
50
- async auditLog(query: { userId?: string, before?: AuditCursorInput, limit?: number } = {}): Promise<AdminAuditLogResult> {
57
+ async listAuditLog(query: { userId?: string, before?: AuditCursorInput, limit?: number } = {}): Promise<Result<{ entries: AuditEntry[] }, 'forbidden' | 'two-factor-required'>> {
51
58
  return (await load.admin()).adminAuditLog(this.state, query)
52
59
  }
53
60
 
54
61
  // Signs this browser in as `userId`, the admin's own sign-in kept for `admin.stopImpersonating`; 'stale' unless the admin signed in or re-proved lately. Nothing that takes a proof works meanwhile, and another admin cannot be impersonated.
55
- async impersonate(userId: string): Promise<ImpersonateResult> {
62
+ async impersonate(userId: string): Promise<Result<object, AdminFailure | 'stale' | 'self' | 'admin' | 'banned'>> {
56
63
  return (await load.admin()).impersonate(this.state, userId)
57
64
  }
58
65
 
@@ -60,4 +67,14 @@ export class AdminMethods<Role extends string = string> {
60
67
  async stopImpersonating(): Promise<boolean> {
61
68
  return (await load.admin()).stopImpersonating(this.state)
62
69
  }
70
+
71
+ /** @deprecated Use `admin.listRoles`. Removed in 1.108.0; `deprecated-auth-methods` rewrites it. */
72
+ roles(...args: Parameters<AdminMethods<Role>['listRoles']>): ReturnType<AdminMethods<Role>['listRoles']> {
73
+ return this.listRoles(...args)
74
+ }
75
+
76
+ /** @deprecated Use `admin.listAuditLog`. Removed in 1.108.0; `deprecated-auth-methods` rewrites it. */
77
+ async auditLog(...args: Parameters<AdminMethods<Role>['listAuditLog']>): ReturnType<AdminMethods<Role>['listAuditLog']> {
78
+ return this.listAuditLog(...args)
79
+ }
63
80
  }
@@ -0,0 +1,18 @@
1
+ import type { CaptchaAction } from '../captcha'
2
+ import type { RequestState } from '../state'
3
+ import { captchaChallenge, captchaRequired } from '../captcha'
4
+
5
+ // `auth.captcha`: what a page needs to show the CAPTCHA a client's next action asks for.
6
+ export class CaptchaMethods {
7
+ constructor(private readonly state: RequestState) {}
8
+
9
+ // Whether this client's next `action` needs a CAPTCHA token, for the page to show the widget.
10
+ async required(action: CaptchaAction): Promise<boolean> {
11
+ return captchaRequired(this.state, action)
12
+ }
13
+
14
+ // 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.
15
+ async challenge(action: CaptchaAction): Promise<string | null> {
16
+ return captchaChallenge(this.state, action)
17
+ }
18
+ }
@@ -1,6 +1,10 @@
1
- import type { ChangeEmailResult, CodeResult, LinkResult, PendingEmailCode, SendVerificationResult, VerifyEmailResult } from '../email'
2
- import type { Proof } from '../proof'
1
+ import type { Off } from '../core'
2
+ import type { PendingEmailCode } from '../email'
3
+ import type { Result } from '../failure'
4
+ import type { Proof, ProofFailure } from '../proof'
5
+ import type { EmailProblem } from '../rules'
3
6
  import type { RequestState } from '../state'
7
+ import { OFF } from '../core'
4
8
  import { load } from '../load'
5
9
 
6
10
  // `auth.email`: verifying the address and changing it.
@@ -8,17 +12,22 @@ export class EmailMethods {
8
12
  constructor(private readonly state: RequestState) {}
9
13
 
10
14
  // Mails a new link verifying the address to the signed-in user or, with nobody signed in, to the account this browser registered or proved the password of with an 'unverified' answer.
11
- async sendVerification(): Promise<SendVerificationResult> {
15
+ async sendVerification(): Promise<Result<object, 'limited' | 'captcha' | 'unavailable' | 'signed-out' | 'verified'>> {
12
16
  return (await load.email()).sendVerification(this.state)
13
17
  }
14
18
 
15
19
  // Spends a verification link's token in the browser signed in as the account, that registered it or that proved its password, or given the account's password: `{ ok: false, error: { code: 'confirm' } }` asks for one of them, the link still usable.
16
- async verify(token: string, password?: string): Promise<VerifyEmailResult> {
20
+ async verify(token: string, password?: string): Promise<Result<{ redirect: string }, 'invalid' | 'limited' | 'banned' | 'confirm'>> {
17
21
  return (await load.email()).verifyEmail(this.state, token, password)
18
22
  }
19
23
 
24
+ // Signs in with the code a magic link mail carried, typed in the browser that asked for it.
25
+ async signInWithCode(code: string): Promise<Result<{ redirect: string }, 'invalid' | 'expired' | 'limited' | 'banned'> | Off> {
26
+ return !this.state.core.switches.magicLink ? OFF : (await load.email()).signInWithEmailCode(this.state, code)
27
+ }
28
+
20
29
  // Verifies the address with the code its verification mail carried, typed in the browser that asked for it.
21
- async verifyCode(code: string): Promise<CodeResult> {
30
+ async verifyCode(code: string): Promise<Result<{ redirect: string }, 'invalid' | 'expired' | 'limited' | 'banned'>> {
22
31
  return (await load.email()).verifyEmailCode(this.state, code)
23
32
  }
24
33
 
@@ -28,12 +37,12 @@ export class EmailMethods {
28
37
  }
29
38
 
30
39
  // Mails the signed-in user's new address a link confirming it.
31
- async change(proof: Proof, email: string): Promise<ChangeEmailResult> {
40
+ async change(proof: Proof, email: string): Promise<Result<object, ProofFailure | 'unavailable', { email: EmailProblem | 'taken' | 'unchanged' }>> {
32
41
  return (await load.email()).changeEmail(this.state, proof, email)
33
42
  }
34
43
 
35
44
  // Spends an email change link's token: the account moves to the new address, and the user's other sessions end.
36
- async confirmChange(token: string): Promise<LinkResult> {
45
+ async confirmChange(token: string): Promise<Result<{ redirect: string }, 'invalid' | 'limited' | 'banned'>> {
37
46
  return (await load.email()).confirmEmailChange(this.state, token)
38
47
  }
39
48
  }
@@ -1,5 +1,5 @@
1
1
  import type { Off } from '../core'
2
- import type { CodeResult, LinkResult, MailRequestResult } from '../email'
2
+ import type { Result } from '../failure'
3
3
  import type { SignInOptions } from '../signInOptions'
4
4
  import type { RequestState } from '../state'
5
5
  import { OFF } from '../core'
@@ -11,7 +11,7 @@ export class MagicLinkMethods {
11
11
  constructor(private readonly state: RequestState) {}
12
12
 
13
13
  // Mails a sign-in link to that address when an account has it; answers alike when none does. `remember` holds for the link opened in this browser, or the code typed in it.
14
- async request(email: string, options: SignInOptions = {}): Promise<MailRequestResult | Off> {
14
+ async request(email: string, options: SignInOptions = {}): Promise<Result<object, 'limited' | 'captcha' | 'unavailable'> | Off> {
15
15
  if (!this.state.core.switches.magicLink)
16
16
  return OFF
17
17
 
@@ -21,12 +21,12 @@ export class MagicLinkMethods {
21
21
  }
22
22
 
23
23
  // Spends a magic link's token, signing its user in.
24
- async signIn(token: string): Promise<LinkResult | Off> {
24
+ async signIn(token: string): Promise<Result<{ redirect: string }, 'invalid' | 'limited' | 'banned'> | Off> {
25
25
  return !this.state.core.switches.magicLink ? OFF : (await load.email()).signInWithMagicLink(this.state, token)
26
26
  }
27
27
 
28
- // Signs in with the code a magic link mail carried, typed in the browser that asked for it.
29
- async signInWithCode(code: string): Promise<CodeResult | Off> {
28
+ /** @deprecated Use `email.signInWithCode`. Removed in 1.108.0; `deprecated-auth-methods` rewrites it. */
29
+ async signInWithCode(code: string): Promise<Result<{ redirect: string }, 'invalid' | 'expired' | 'limited' | 'banned'> | Off> {
30
30
  return !this.state.core.switches.magicLink ? OFF : (await load.email()).signInWithEmailCode(this.state, code)
31
31
  }
32
32
  }
@@ -1,6 +1,5 @@
1
- import type { UnlinkResult } from '../account'
2
- import type { LinkProviderResult } from '../oauth/flow'
3
- import type { Proof } from '../proof'
1
+ import type { Result } from '../failure'
2
+ import type { Proof, ProofFailure } from '../proof'
4
3
  import type { RequestState } from '../state'
5
4
  import { failed } from '../failure'
6
5
  import { load } from '../load'
@@ -10,26 +9,36 @@ export class OAuthMethods {
10
9
  constructor(private readonly state: RequestState, private readonly forget: () => void) {}
11
10
 
12
11
  // Where to send the browser to link `provider` to the signed-in user once `proof` re-proves them, the second factor when it is on; it comes back to `redirect`.
13
- async link(provider: string, proof: Proof, options: { redirect?: string } = {}): Promise<LinkProviderResult> {
12
+ async link(provider: string, proof: Proof, options: { redirect?: string } = {}): Promise<Result<{ url: string }, ProofFailure | 'not-found' | 'unavailable'>> {
14
13
  return this.state.core.oauth.has(provider) ? (await load.flow()).startLink(this.state, provider, proof, options.redirect) : failed('not-found')
15
14
  }
16
15
 
17
16
  // Unlinks a provider from the signed-in user, unless it is their last way in.
18
- async unlink(provider: string, proof: Proof): Promise<UnlinkResult> {
17
+ async unlink(provider: string, proof: Proof): Promise<Result<object, ProofFailure | 'not-linked' | 'last-way-in'>> {
19
18
  this.forget()
20
19
 
21
20
  return (await load.account()).unlink(this.state, provider, proof)
22
21
  }
23
22
 
24
23
  // The providers the signed-in user has linked.
25
- async identities(): Promise<string[]> {
24
+ async listIdentities(): Promise<string[]> {
26
25
  const record = await this.state.current()
27
26
 
28
27
  return record ? (await this.state.core.store.identities.listByUser(record.id)).map(identity => identity.provider) : []
29
28
  }
30
29
 
31
30
  // A fresh access token for the signed-in user's account at `provider`, refreshed when about to expire; null without one, or once the provider refuses a refresh.
32
- async providerToken(provider: string): Promise<string | null> {
31
+ async getProviderToken(provider: string): Promise<string | null> {
33
32
  return (await load.flow()).providerToken(this.state, provider)
34
33
  }
34
+
35
+ /** @deprecated Use `oauth.listIdentities`. Removed in 1.108.0; `deprecated-auth-methods` rewrites it. */
36
+ async identities(...args: Parameters<OAuthMethods['listIdentities']>): ReturnType<OAuthMethods['listIdentities']> {
37
+ return this.listIdentities(...args)
38
+ }
39
+
40
+ /** @deprecated Use `oauth.getProviderToken`. Removed in 1.108.0; `deprecated-auth-methods` rewrites it. */
41
+ async providerToken(...args: Parameters<OAuthMethods['getProviderToken']>): ReturnType<OAuthMethods['getProviderToken']> {
42
+ return this.getProviderToken(...args)
43
+ }
35
44
  }
@@ -1,7 +1,8 @@
1
- import type { ApprovedClient, RevokeGrantResult } from '../authorize/grants'
2
- import type { AuthorizeOutcome, AuthorizeParams, DecideResult } from '../authorize/request'
1
+ import type { ApprovedClient } from '../authorize/grants'
2
+ import type { AuthorizeOutcome, AuthorizeParams } from '../authorize/request'
3
+ import type { Result } from '../failure'
3
4
  import type { RequestState } from '../state'
4
- import { siteRoot } from '../authorize/metadata'
5
+ import { protectedResourceMetadata, rootIsFixed, rootUsable, siteRoot } from '../authorize/metadata'
5
6
  import { failed } from '../failure'
6
7
  import { load } from '../load'
7
8
 
@@ -15,17 +16,42 @@ export class OAuthServerMethods {
15
16
  }
16
17
 
17
18
  // The user's answer on the consent page, checked again as the request is: where the browser goes next.
18
- async decide(fields: AuthorizeParams, allow: boolean): Promise<DecideResult> {
19
+ async decide(fields: AuthorizeParams, allow: boolean): Promise<Result<{ redirect: string }, 'client' | 'redirect_uri' | 'signed-out'>> {
19
20
  return this.state.core.oauthServer ? (await load.request()).decide(this.state, fields, allow, siteRoot(this.state.core, this.request)) : failed('client')
20
21
  }
21
22
 
23
+ // 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.
24
+ resource(path: string, name: string): Record<string, unknown> | null {
25
+ if (!this.state.core.oauthServer || !rootUsable(this.state.core))
26
+ return null
27
+
28
+ const root = siteRoot(this.state.core, this.request)
29
+
30
+ return protectedResourceMetadata(this.state.core, root, `${root}${path}`, name)
31
+ }
32
+
33
+ // The origin the OAuth documents are served at, which kay's 401 pointer to them names; undefined while the OAuth server is off.
34
+ origin(): string | undefined {
35
+ return this.state.core.oauthServer && rootUsable(this.state.core) ? new URL(siteRoot(this.state.core, this.request)).origin : undefined
36
+ }
37
+
38
+ // Whether that origin is configured, so the documents may be cached for everyone; else it is the request's own.
39
+ fixed(): boolean {
40
+ return rootIsFixed(this.state.core)
41
+ }
42
+
22
43
  // The apps the signed-in user approved to act as them.
23
- async clients(): Promise<ApprovedClient[]> {
44
+ async listClients(): Promise<ApprovedClient[]> {
24
45
  return (await load.grants()).approvedClients(this.state)
25
46
  }
26
47
 
27
48
  // Takes an app's approval back with every token it was given; refused with `not-found` when there was none, and `signed-out` outside the user's own session.
28
- async revokeGrant(clientId: string): Promise<RevokeGrantResult> {
49
+ async revokeGrant(clientId: string): Promise<Result<object, 'signed-out' | 'not-found'>> {
29
50
  return (await load.grants()).revokeClient(this.state, clientId)
30
51
  }
52
+
53
+ /** @deprecated Use `oauthServer.listClients`. Removed in 1.108.0; `deprecated-auth-methods` rewrites it. */
54
+ async clients(...args: Parameters<OAuthServerMethods['listClients']>): ReturnType<OAuthServerMethods['listClients']> {
55
+ return this.listClients(...args)
56
+ }
31
57
  }