@kayjs/auth 1.104.2 → 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 (207) hide show
  1. package/README.md +2 -2
  2. package/llms/admin-and-organizations.md +8 -8
  3. package/llms/admin-pages.md +2 -2
  4. package/llms/grouped-methods.md +33 -17
  5. package/llms/hardening-and-testing.md +9 -9
  6. package/llms/oauth-passkeys-two-factor.md +13 -13
  7. package/llms/oauth-providers.md +1 -1
  8. package/llms/oauth-server-and-tokens.md +7 -7
  9. package/llms/passwords-and-mails.md +12 -12
  10. package/llms/sessions-and-guards.md +9 -1
  11. package/llms/setup.md +7 -7
  12. package/llms/signed-in-components.md +20 -11
  13. package/llms.txt +1 -1
  14. package/package.json +9 -5
  15. package/src/account.ts +6 -15
  16. package/src/admin.ts +9 -25
  17. package/src/auth.ts +9 -6
  18. package/src/authorize/clients.ts +1 -1
  19. package/src/authorize/grants.ts +2 -4
  20. package/src/authorize/request.ts +2 -4
  21. package/src/bearer.ts +5 -11
  22. package/src/captcha.ts +5 -3
  23. package/src/components/sign-in-link.kay +19 -0
  24. package/src/components/sign-out-button.kay +17 -0
  25. package/src/components/signed-in.kay +7 -2
  26. package/src/components/user-menu.kay +11 -8
  27. package/src/context.ts +1 -1
  28. package/src/deletion.ts +2 -4
  29. package/src/email.ts +16 -28
  30. package/src/erase.ts +5 -4
  31. package/src/export.ts +2 -4
  32. package/src/failure.ts +37 -9
  33. package/src/guard.ts +8 -1
  34. package/src/guards.ts +12 -5
  35. package/src/index.ts +14 -16
  36. package/src/limits.ts +97 -5
  37. package/src/mail.ts +5 -3
  38. package/src/memoryStore.ts +6 -6
  39. package/src/messages/fr.ts +1 -0
  40. package/src/methods/account.ts +30 -14
  41. package/src/methods/admin.ts +31 -14
  42. package/src/methods/captcha.ts +18 -0
  43. package/src/methods/email.ts +16 -7
  44. package/src/methods/magicLink.ts +5 -5
  45. package/src/methods/oauth.ts +16 -7
  46. package/src/methods/oauthServer.ts +32 -6
  47. package/src/methods/organizations.ts +51 -20
  48. package/src/methods/passkeys.ts +13 -7
  49. package/src/methods/password.ts +10 -10
  50. package/src/methods/proof.ts +22 -0
  51. package/src/methods/sessions.ts +3 -2
  52. package/src/methods/tokens.ts +17 -5
  53. package/src/methods/twoFactor.ts +10 -10
  54. package/src/oauth/flow.ts +2 -4
  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 +17 -15
  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/types/account.d.ts +10 -23
  104. package/types/account.d.ts.map +1 -1
  105. package/types/admin.d.ts +21 -39
  106. package/types/admin.d.ts.map +1 -1
  107. package/types/auth.d.ts +18 -5
  108. package/types/auth.d.ts.map +1 -1
  109. package/types/authorize/grants.d.ts +2 -5
  110. package/types/authorize/grants.d.ts.map +1 -1
  111. package/types/authorize/request.d.ts +3 -5
  112. package/types/authorize/request.d.ts.map +1 -1
  113. package/types/bearer.d.ts +9 -17
  114. package/types/bearer.d.ts.map +1 -1
  115. package/types/captcha.d.ts +3 -1
  116. package/types/captcha.d.ts.map +1 -1
  117. package/types/context.d.ts +1 -1
  118. package/types/deletion.d.ts +2 -5
  119. package/types/deletion.d.ts.map +1 -1
  120. package/types/email.d.ts +23 -28
  121. package/types/email.d.ts.map +1 -1
  122. package/types/erase.d.ts.map +1 -1
  123. package/types/export.d.ts +3 -5
  124. package/types/export.d.ts.map +1 -1
  125. package/types/failure.d.ts +22 -3
  126. package/types/failure.d.ts.map +1 -1
  127. package/types/guard.d.ts +2 -0
  128. package/types/guard.d.ts.map +1 -1
  129. package/types/guards.d.ts +2 -1
  130. package/types/guards.d.ts.map +1 -1
  131. package/types/index.d.ts +14 -16
  132. package/types/index.d.ts.map +1 -1
  133. package/types/limits.d.ts +57 -1
  134. package/types/limits.d.ts.map +1 -1
  135. package/types/mail.d.ts +5 -0
  136. package/types/mail.d.ts.map +1 -1
  137. package/types/messages/fr.d.ts +1 -0
  138. package/types/methods/account.d.ts +27 -13
  139. package/types/methods/account.d.ts.map +1 -1
  140. package/types/methods/admin.d.ts +39 -15
  141. package/types/methods/admin.d.ts.map +1 -1
  142. package/types/methods/captcha.d.ts +9 -0
  143. package/types/methods/captcha.d.ts.map +1 -0
  144. package/types/methods/email.d.ts +21 -7
  145. package/types/methods/email.d.ts.map +1 -1
  146. package/types/methods/magicLink.d.ts +9 -4
  147. package/types/methods/magicLink.d.ts.map +1 -1
  148. package/types/methods/oauth.d.ts +12 -7
  149. package/types/methods/oauth.d.ts.map +1 -1
  150. package/types/methods/oauthServer.d.ts +13 -5
  151. package/types/methods/oauthServer.d.ts.map +1 -1
  152. package/types/methods/organizations.d.ts +40 -15
  153. package/types/methods/organizations.d.ts.map +1 -1
  154. package/types/methods/passkeys.d.ts +18 -7
  155. package/types/methods/passkeys.d.ts.map +1 -1
  156. package/types/methods/password.d.ts +23 -10
  157. package/types/methods/password.d.ts.map +1 -1
  158. package/types/methods/proof.d.ts +12 -0
  159. package/types/methods/proof.d.ts.map +1 -0
  160. package/types/methods/sessions.d.ts +3 -2
  161. package/types/methods/sessions.d.ts.map +1 -1
  162. package/types/methods/tokens.d.ts +12 -5
  163. package/types/methods/tokens.d.ts.map +1 -1
  164. package/types/methods/twoFactor.d.ts +22 -10
  165. package/types/methods/twoFactor.d.ts.map +1 -1
  166. package/types/oauth/flow.d.ts +4 -6
  167. package/types/oauth/flow.d.ts.map +1 -1
  168. package/types/oauthTest.d.ts +2 -0
  169. package/types/oauthTest.d.ts.map +1 -1
  170. package/types/organizations.d.ts +24 -48
  171. package/types/organizations.d.ts.map +1 -1
  172. package/types/own.d.ts +1 -1
  173. package/types/own.d.ts.map +1 -1
  174. package/types/pages/forms.d.ts +5 -3
  175. package/types/pages/forms.d.ts.map +1 -1
  176. package/types/pages/index.d.ts +5 -2
  177. package/types/pages/index.d.ts.map +1 -1
  178. package/types/passkeys.d.ts +20 -27
  179. package/types/passkeys.d.ts.map +1 -1
  180. package/types/password.d.ts +13 -20
  181. package/types/password.d.ts.map +1 -1
  182. package/types/profile.d.ts +1 -4
  183. package/types/profile.d.ts.map +1 -1
  184. package/types/proof.d.ts +1 -4
  185. package/types/proof.d.ts.map +1 -1
  186. package/types/request.d.ts +33 -7
  187. package/types/request.d.ts.map +1 -1
  188. package/types/requiredTwoFactor.d.ts +3 -1
  189. package/types/requiredTwoFactor.d.ts.map +1 -1
  190. package/types/routes.d.ts +3 -1
  191. package/types/routes.d.ts.map +1 -1
  192. package/types/sessions.d.ts +3 -10
  193. package/types/sessions.d.ts.map +1 -1
  194. package/types/setup.d.ts.map +1 -1
  195. package/types/sqlite.d.ts +3 -0
  196. package/types/sqlite.d.ts.map +1 -0
  197. package/types/test.d.ts +4 -1
  198. package/types/test.d.ts.map +1 -1
  199. package/types/testHelpers.d.ts +1 -0
  200. package/types/testHelpers.d.ts.map +1 -1
  201. package/types/testHook.d.ts +15 -0
  202. package/types/testHook.d.ts.map +1 -0
  203. package/types/testing.d.ts.map +1 -1
  204. package/types/twoFactor.d.ts +10 -21
  205. package/types/twoFactor.d.ts.map +1 -1
  206. package/types/viewer.d.ts +3 -1
  207. package/types/viewer.d.ts.map +1 -1
package/src/own.ts CHANGED
@@ -7,11 +7,10 @@ import type { ProviderOptions } from './oauth/providers'
7
7
  import type { AuthPagesConfig, AuthPagesOptions, UserMaker } from './pages'
8
8
  import type { AuthStore } from './store'
9
9
  import type { OwnTest } from './test'
10
- import { existsSync } from 'node:fs'
11
10
  import { normalize, resolve } from 'node:path'
12
11
  import process from 'node:process'
13
12
  import { s } from 'kay'
14
- import { appStore, configError } from 'kay/library'
13
+ import { APP_SQLITE_FILE, appStore, configError, defaultSqliteFile } from 'kay/library'
15
14
  import { session } from 'kay/server'
16
15
  import { log } from './log'
17
16
  import { memoryAuth } from './memoryStore'
@@ -44,7 +43,7 @@ const PRESETS = {
44
43
  } as unknown as Record<string, (options: ProviderOptions) => OAuthApp['provider']>
45
44
 
46
45
  /** The hooks an app keeps in `src/auth.ts` as `export const hooks`, or hands to `auth({ hooks })`. */
47
- export type AuthHooks = Partial<Pick<AuthOptions<AuthSessionData, string>, 'allow' | 'authorize' | 'exportData' | 'locate' | 'onEvent' | 'beforeDelete' | 'onSignUp' | 'profileFields'>>
46
+ export type AuthHooks = Partial<Pick<AuthOptions<AuthSessionData, string>, 'allow' | 'authorize' | 'exportData' | 'locate' | 'onEvent' | 'beforeDelete' | 'afterSignUp' | 'onSignUp' | 'profileFields'>>
48
47
 
49
48
  /** Where kayjs-auth keeps its data when `store` is left out: a pg-orm database at `url`, the database of the app's `store` in kay.config.ts when it names one, else a SQLite file `data/auth.sqlite` (`data/auth.db` where an app already has it). */
50
49
  export interface StoreUrl {
@@ -155,9 +154,8 @@ function foreignTables(names: readonly string[]): RegExp {
155
154
  return new RegExp(`^(?!(?:${names.join('|')})$)`)
156
155
  }
157
156
 
158
- const OWN_FILE = 'data/auth.sqlite'
159
- // What the file was called before 1.88 gave every default data file the `.sqlite` extension: an app whose users are in it keeps it.
160
- const LEGACY_OWN_FILE = 'data/auth.db'
157
+ // The files the users were kept in before every default shared `data/app.sqlite` (`data/auth.db` before 1.88 gave the data files their extension): an app whose users are in one keeps it.
158
+ const LEGACY_OWN_FILES = ['data/auth.db', 'data/auth.sqlite']
161
159
  const warned = new Set<string>()
162
160
 
163
161
  async function storeOf(store: StoreOption | undefined, root: string, shared: string | undefined, exporting: boolean | undefined): Promise<AuthStore> {
@@ -175,9 +173,9 @@ async function storeOf(store: StoreOption | undefined, root: string, shared: str
175
173
  return memoryAuth()
176
174
 
177
175
  // The database of the app's own `store` when it names one, so `sqliteData` or `pgData(url)` in kay.config.ts is the only place to say where the data lives.
178
- // An app whose users are already in `data/auth.db` keeps them there, so an upgrade loses no one.
179
- const file = existsSync(resolve(root, LEGACY_OWN_FILE)) ? LEGACY_OWN_FILE : OWN_FILE
180
- const kept = given === undefined && shared !== undefined && existsSync(resolve(root, file))
176
+ // An app whose users are already in `data/auth.sqlite` or `data/auth.db` keeps them there, so an upgrade loses no one.
177
+ const file = defaultSqliteFile(LEGACY_OWN_FILES, root)
178
+ const kept = given === undefined && shared !== undefined && file !== APP_SQLITE_FILE
181
179
  const url = kept ? undefined : given ?? shared
182
180
 
183
181
  if (kept && !warned.has(root)) {
@@ -196,9 +194,13 @@ async function storeOf(store: StoreOption | undefined, root: string, shared: str
196
194
  throw configError('auth', 'store', 'the store of auth() is a pg-orm database, and @kaynooo/pg-orm is not installed: install it, or give `store` an AuthStore', { cause: error })
197
195
  }
198
196
 
199
- const db = new orm.Database({ url: underRoot(url ?? `sqlite://${file}`, root), tables: [...pg.authTables] })
197
+ const target = underRoot(url ?? `sqlite://${file}`, root)
198
+ const db = new orm.Database({ url: target, tables: [...pg.authTables] })
200
199
 
201
- await db.sync(!kept && url !== undefined && shared !== undefined && sameDatabase(url, shared, root) ? { ignoreTables: [foreignTables(pg.authTables.map(table => table.name))] } : undefined)
200
+ // The app's database and `data/app.sqlite` hold tables that are not kayjs-auth's, which the sync must leave alone.
201
+ const shares = !kept && ((url !== undefined && shared !== undefined && sameDatabase(url, shared, root)) || sameDatabase(target, `sqlite://${APP_SQLITE_FILE}`, root))
202
+
203
+ await db.sync(shares ? { ignoreTables: [foreignTables(pg.authTables.map(table => table.name))] } : undefined)
202
204
 
203
205
  return pg.pgAuth(db)
204
206
  }
@@ -232,17 +234,17 @@ async function registeredMailer(app: ExtensionApp): Promise<unknown> {
232
234
  if (!app.extensions.includes(MAIL_EXTENSION))
233
235
  return undefined
234
236
 
235
- let mail: typeof import('@kayjs/mail')
237
+ let mail: typeof import('@kayjs/mail/internal')
236
238
 
237
239
  try {
238
- mail = await import('@kayjs/mail')
240
+ mail = await import('@kayjs/mail/internal')
239
241
  }
240
242
  catch {
241
243
  return undefined
242
244
  }
243
245
 
244
246
  // A failure of the registered loader is the app's to see.
245
- return mail.registeredMailer()
247
+ return mail.runningMailer()
246
248
  }
247
249
 
248
250
  export async function emailOf(email: OwnOptions['email'], app: ExtensionApp): Promise<EmailOptions | undefined> {
@@ -288,7 +290,7 @@ export async function buildOwn(options: OwnOptions, app: ExtensionApp): Promise<
288
290
  const mailer = await emailOf(email, app)
289
291
 
290
292
  if (store === undefined && app.database === undefined && process.env.NODE_ENV === 'production' && databaseUrlFromEnv() === undefined) {
291
- const file = existsSync(resolve(app.root, LEGACY_OWN_FILE)) ? LEGACY_OWN_FILE : OWN_FILE
293
+ const file = defaultSqliteFile(LEGACY_OWN_FILES, app.root)
292
294
 
293
295
  log.warn(appStore()?.sql === undefined
294
296
  ? `auth() keeps its users in ${file}, a SQLite file: set the app's \`store\` (\`sqliteData\` or \`pgData\`) in kay.config.ts, AUTH_DATABASE_URL, or auth's \`store\`, for a database that outlives a deploy`
@@ -1,11 +1,11 @@
1
1
  ---
2
2
  const { size, gap, landmark = true } = props<{ size: string, gap: string, landmark?: boolean }>()
3
- const classes = `kayjs-auth mx-auto flex w-full ${size} flex-col ${gap} px-4 py-8`
3
+ const classes = () => `kayjs-auth mx-auto flex w-full ${size} flex-col ${gap} px-4 py-8`
4
4
  ---
5
5
  // A prebuilt page's frame: a `main` landmark unless `pages.main` is false, for an app whose layout writes one.
6
6
  if landmark
7
- main(class={classes})
7
+ main(class={classes()})
8
8
  slot
9
9
  else
10
- div(class={classes})
10
+ div(class={classes()})
11
11
  slot
@@ -24,11 +24,11 @@ async function add(event: SubmitEvent) {
24
24
 
25
25
  proof.delete('name')
26
26
 
27
- const options = await passkeyOptions(proof, { refresh: false })
27
+ const options = await passkeyOptions(proof, { refresh: false }).orThrow()
28
28
  const response = await makePasskey(options)
29
29
 
30
30
  if (response)
31
- await addPasskey({ response, ...(name() ? { name: name() } : {}) })
31
+ await addPasskey({ response, ...(name() ? { name: name() } : {}) }).orThrow()
32
32
  }
33
33
  catch (caught) {
34
34
  error = passkeyFailure(caught, errors, failed)
@@ -16,12 +16,12 @@ async function signIn() {
16
16
  error = ''
17
17
 
18
18
  try {
19
- const options = await passkeyOptions({}, { refresh: false })
19
+ const options = await passkeyOptions({}, { refresh: false }).orThrow()
20
20
  const response = await askPasskey(options)
21
21
  const remember = rememberChoice()
22
22
 
23
23
  if (response)
24
- await passkey({ response, redirect, ...(remember === undefined ? {} : { remember }) })
24
+ await passkey({ response, redirect, ...(remember === undefined ? {} : { remember }) }).orThrow()
25
25
  }
26
26
  catch (caught) {
27
27
  error = passkeyFailure(caught, {}, failed)
@@ -16,11 +16,11 @@ async function verify() {
16
16
  error = ''
17
17
 
18
18
  try {
19
- const options = await passkeyOptions({}, { refresh: false })
19
+ const options = await passkeyOptions({}, { refresh: false }).orThrow()
20
20
  const response = await askPasskey(options)
21
21
 
22
22
  if (response)
23
- await passkey({ response })
23
+ await passkey({ response }).orThrow()
24
24
  }
25
25
  catch (caught) {
26
26
  error = passkeyFailure(caught, {}, failed)
@@ -22,4 +22,4 @@ function carryRemember(event: Event) {
22
22
  // kay-allow unreachable-click
23
23
  .flex.flex-col.gap-2(onClick={carryRemember} onAuxClick={carryRemember})
24
24
  for provider of providers key={provider.name}
25
- Button(href={provider.href} label={provider.label} data-provider={provider.name} data-no-prefetch)
25
+ Button(href={provider.href} label={provider.label} data-provider={provider.name} data-prefetch="false")
@@ -2,7 +2,7 @@ import type { MinTimeRefusal } from 'kay'
2
2
  import type { Auth } from '../auth'
3
3
  import type { CaptchaAction } from '../captcha'
4
4
  import type { Proof } from '../proof'
5
- import type { AuthFeatures, ProfileProblem } from './index'
5
+ import type { AuthFeatures } from './index'
6
6
  import { t } from 'elysia'
7
7
  import { wording } from 'kay/words'
8
8
  import { passkeyAssertion, passkeyAttestation } from '../payloads'
@@ -115,11 +115,11 @@ export function refusedFor<Code extends string>(error: Code, input: Parameters<t
115
115
  }
116
116
 
117
117
  // Whether the page shows its CAPTCHA for `action`, with the proof of work's challenge, reading the client's attempts once.
118
- export async function captchaFor(auth: Pick<Auth, 'captchaRequired' | 'captchaChallenge'>, captcha: AuthFeatures['captcha'], action: CaptchaAction): Promise<{ shown: boolean, challenge: string | null }> {
118
+ export async function captchaFor(auth: { captcha: Pick<Auth['captcha'], 'required' | 'challenge'> }, captcha: AuthFeatures['captcha'], action: CaptchaAction): Promise<{ shown: boolean, challenge: string | null }> {
119
119
  if (captcha !== 'proof-of-work')
120
- return { shown: captcha !== null && await auth.captchaRequired(action), challenge: null }
120
+ return { shown: captcha !== null && await auth.captcha.required(action), challenge: null }
121
121
 
122
- const challenge = await auth.captchaChallenge(action)
122
+ const challenge = await auth.captcha.challenge(action)
123
123
 
124
124
  return { shown: challenge !== null, challenge }
125
125
  }
@@ -171,8 +171,8 @@ export function issue(...[field, problem, rules]: [field: 'email', problem: Prob
171
171
  }
172
172
 
173
173
  // What a page shows under a profile field the app asked for, `max` being the field's own limit when it set one.
174
- export function profileIssue(problem: ProfileProblem, max?: number): string {
175
- return typeof problem === 'object' ? problem.message : wording(`auth.fields.profile.${problem}`, FIELD_ERRORS.profile[problem], { max: max ?? PROFILE_MAX_LENGTH })
174
+ export function profileIssue(problem: string, max?: number): string {
175
+ return problem === 'required' || problem === 'too-long' ? wording(`auth.fields.profile.${problem}`, FIELD_ERRORS.profile[problem], { max: max ?? PROFILE_MAX_LENGTH }) : problem
176
176
  }
177
177
 
178
178
  // The message for the `?error=` a failed provider sign-in comes back with; undefined for none, or one kayjs-auth never sends.
@@ -2,12 +2,13 @@ import type { ExtensionApp, KayExtension, PluginInput } from 'kay/server'
2
2
  import type { CaptchaWidget } from '../captcha'
3
3
  import type { BareUser, Core } from '../core'
4
4
  import type { CodedLink, CodeMode } from '../email'
5
+ import type { Result } from '../failure'
5
6
  import type { OrganizationsCore } from '../organizationsCore'
6
7
  import type { OwnOptions, OwnPlugin } from '../own'
7
- import type { CreateUserInput, CreateUserResult } from '../password'
8
+ import type { CreateUserInput, RegisterErrors } from '../password'
8
9
  import type { LinkType } from '../store'
9
10
  import { resolve } from 'node:path'
10
- import { appModules, checkOptionKeys, configError } from 'kay/library'
11
+ import { appModules, checkOptionKeys, configError, KayError } from 'kay/library'
11
12
  import { pickLocale } from '../locale'
12
13
  import { buildOwn, MAIL_EXTENSION, ownEnv } from '../own'
13
14
 
@@ -93,7 +94,7 @@ export interface AuthFeatures {
93
94
  magicLink: boolean
94
95
  // Whether users can turn on two-step verification, `twoFactor: false` switching that off.
95
96
  twoFactor: boolean
96
- // The CAPTCHA widget to show where `captchaRequired` says one is needed, `'proof-of-work'` for kay's, whose field carries `captchaChallenge`, or null without one.
97
+ // The CAPTCHA widget to show where `captcha.required` says one is needed, `'proof-of-work'` for kay's, whose field carries `captcha.challenge`, or null without one.
97
98
  captcha: CaptchaWidget | 'proof-of-work' | null
98
99
  // What a bearer token may be limited to; any token may do anything without them.
99
100
  scopes: string[]
@@ -205,7 +206,7 @@ export const CHECK_USER = Symbol('kayjs-auth.checkUser')
205
206
  export interface UserMaker {
206
207
  // What `createUser` would refuse the login for, asked before the password is.
207
208
  [CHECK_USER]: (input: Omit<CreateUserInput, 'roles'> & { roles?: string[] | undefined }) => Promise<Partial<Record<'email' | 'username' | 'password', string>>>
208
- admin: { createUser: (input: Omit<CreateUserInput, 'roles'> & { roles?: string[] | undefined }) => Promise<CreateUserResult> }
209
+ admin: { createUser: (input: Omit<CreateUserInput, 'roles'> & { roles?: string[] | undefined }) => Promise<Result<{ user: BareUser }, never, RegisterErrors>> }
209
210
  }
210
211
 
211
212
  // The commands both extensions add.
@@ -254,12 +255,12 @@ export interface AuthExtensionOptions extends AuthPagesOptions {
254
255
  // The `auth` an app's module exports, for `prepare` to hand it the prefix and home `auth()` was given.
255
256
  function authOfExport(exported: unknown, module: string): { [PAGES_OF]?: PagesHandle | undefined } {
256
257
  if (typeof exported !== 'object' || exported === null || !('plugin' in exported))
257
- throw new Error(`kayjs-auth: ${module} exports no \`auth\`: export the \`authCore\` result as \`export const auth = authCore(...)\``)
258
+ throw new KayError('config-invalid', `kayjs-auth: ${module} exports no \`auth\`: export the \`authCore\` result as \`export const auth = authCore(...)\``)
258
259
 
259
260
  return exported as { [PAGES_OF]?: PagesHandle | undefined }
260
261
  }
261
262
 
262
- const KNOWN_OPTIONS: Record<keyof OwnOptions | keyof AuthExtensionOptions, true> = { module: true, server: true, prefix: true, pages: true, cookie: true, oauth: true, store: true, email: true, hooks: true, viewer: true, secret: true, site: true, name: true, signInPage: true, failurePage: true, twoFactorPage: true, allow: true, signUp: true, onSignUp: true, user: true, profileFields: true, beforeDelete: true, guests: true, exportData: true, onEvent: true, audit: true, scopes: true, roles: true, organizations: true, admin: true, defaultRoles: true, remember: true, rules: true, sessionsPage: true, securityPage: true, locate: true, rateLimit: true, passkeys: true, password: true, magicLink: true, twoFactor: true, captcha: true, breachedPasswords: true, proxy: true, oauthServer: true, forwardAuth: true, authorize: true, home: true, account: true }
263
+ const KNOWN_OPTIONS: Record<keyof OwnOptions | keyof AuthExtensionOptions, true> = { module: true, server: true, prefix: true, pages: true, cookie: true, oauth: true, store: true, email: true, hooks: true, viewer: true, secret: true, site: true, name: true, signInPage: true, failurePage: true, twoFactorPage: true, allow: true, signUp: true, afterSignUp: true, onSignUp: true, user: true, profileFields: true, beforeDelete: true, guests: true, exportData: true, onEvent: true, audit: true, scopes: true, roles: true, organizations: true, admin: true, defaultRoles: true, remember: true, rules: true, sessionsPage: true, securityPage: true, locate: true, rateLimit: true, passkeys: true, password: true, magicLink: true, twoFactor: true, captcha: true, breachedPasswords: true, proxy: true, oauthServer: true, forwardAuth: true, authorize: true, home: true, account: true }
263
264
 
264
265
  // kayjs-auth for `extensions` in kay.config.ts, as the whole declaration: `auth({ module: './src/auth' })`, the module exporting the `auth` made with `authCore`. Its plugin is used before the pages, so the app mounts nothing else and declares no `Register`, and `prefix` and `home` reach `authCore({ pages: true })`; the prebuilt pages come with it unless `pages: false`.
265
266
  export function auth<Role extends string = string, Prefix extends string = '/auth', const Scope extends string = never, OrgRole extends string = never, UserData extends object = Record<string, never>>(options?: OwnOptions<Role, Prefix, Scope, OrgRole, UserData>): AuthPages<OwnPlugin<Role, Prefix, Scope, OrgRole, UserData>>
@@ -309,7 +310,7 @@ function moduleAuth(options: AuthExtensionOptions): AuthPages {
309
310
  const server = options.server === false ? undefined : options.server
310
311
 
311
312
  if (module !== undefined && options.server !== undefined)
312
- throw new Error('kayjs-auth: auth() takes `module` or `server`, not both')
313
+ throw new KayError('config-invalid', 'kayjs-auth: auth() takes `module` or `server`, not both')
313
314
 
314
315
  const given = { prefix: options.prefix, home }
315
316
  const extension: AuthPages = {
@@ -355,7 +356,7 @@ export function profileValue(name: string, held: unknown): string {
355
356
  return ''
356
357
 
357
358
  if (typeof held !== 'string')
358
- throw new TypeError(`kayjs-auth: pages.profile.load answered a ${typeof held} for the field "${name}", which takes a string, null or undefined`)
359
+ throw new KayError('argument-invalid', `kayjs-auth: pages.profile.load answered a ${typeof held} for the field "${name}", which takes a string, null or undefined`)
359
360
 
360
361
  return held
361
362
  }
@@ -9,10 +9,10 @@ import EmptyState from '@kayjs/ui/empty-state.kay'
9
9
  import PageSection from '@kayjs/ui/page-section.kay'
10
10
 
11
11
  export const revoke = action(schemas.oauthClient, async ({ id }, ctx) => {
12
- return (await ctx.locals.auth.oauthServer.revokeGrant(id)).ok ? 'revoked' : ctx.fail(404, { error: 'not-found' })
12
+ return (await ctx.locals.auth.oauthServer.revokeGrant(id)).ok ? 'revoked' : ctx.deny(404, { data: { error: 'not-found' } })
13
13
  })
14
14
 
15
- const clients = await ctx.locals.auth.oauthServer.clients()
15
+ const clients = await ctx.locals.auth.oauthServer.listClients()
16
16
  const date = (value: Date) => formatDate(value, { dateStyle: 'medium' })
17
17
  ---
18
18
  PageSection(title={wording('auth.account.clients.title', 'Connected apps')})
@@ -16,20 +16,20 @@ export const connect = action(schemas.unlink, async (input, ctx) => {
16
16
  const features = auth.features()
17
17
  const started = await auth.oauth.link(input.provider, proofOf(input), { redirect: localize(`${features.pages?.prefix ?? features.prefix}/account/connections`) })
18
18
 
19
- return started.ok ? ctx.redirect(started.url) : ctx.fail(400, { error: started.error.code, provider: input.provider })
19
+ return started.ok ? ctx.redirect(started.url) : ctx.deny(400, { data: { error: started.error.code, provider: input.provider } })
20
20
  })
21
21
 
22
22
  export const disconnect = action(schemas.unlink, async (input, ctx) => {
23
23
  const result = await ctx.locals.auth.oauth.unlink(input.provider, proofOf(input))
24
24
 
25
- return result.ok ? 'disconnected' : ctx.fail(400, { error: result.error.code, provider: input.provider })
25
+ return result.ok ? 'disconnected' : ctx.deny(400, { data: { error: result.error.code, provider: input.provider } })
26
26
  })
27
27
 
28
28
  const auth = ctx.locals.auth
29
29
  const user = await auth.requireUser()
30
30
  const features = auth.features()
31
- const linked = new Set(await auth.oauth.identities())
32
- const refused = connect.failed()?.data ?? disconnect.failed()?.data
31
+ const linked = new Set(await auth.oauth.listIdentities())
32
+ const refused = connect.form.failed()?.data ?? disconnect.form.failed()?.data
33
33
  ---
34
34
  PageSection(title={wording('auth.account.connections.title', 'Connected accounts')})
35
35
  .flex.flex-col.gap-2
@@ -11,16 +11,16 @@ import PageSection from '@kayjs/ui/page-section.kay'
11
11
 
12
12
  // Re-proves the user, so the export link below shows for the next ten minutes.
13
13
  export const prove = action(schemas.proof, async (input, ctx) => {
14
- const result = await ctx.locals.auth.reprove(proofOf(input))
14
+ const result = await ctx.locals.auth.proof.renew(proofOf(input))
15
15
 
16
- return !result.ok ? ctx.fail(400, { error: result.error.code }) : undefined
16
+ return !result.ok ? ctx.deny(400, { data: { error: result.error.code } }) : undefined
17
17
  })
18
18
 
19
19
  export const remove = action(schemas.proof, async (input, ctx) => {
20
20
  const result = await ctx.locals.auth.account.delete(proofOf(input))
21
21
 
22
22
  if (!result.ok)
23
- return ctx.fail(400, { error: result.error.code })
23
+ return ctx.deny(400, { data: { error: result.error.code } })
24
24
 
25
25
  const { pages, prefix } = ctx.locals.auth.features()
26
26
 
@@ -49,9 +49,9 @@ export const signInAgain = action(async (ctx) => {
49
49
  const auth = ctx.locals.auth
50
50
  const user = await auth.requireUser()
51
51
  const features = auth.features()
52
- const refused = remove.failed()?.data?.error
53
- const notProved = prove.failed()?.data?.error
54
- const proved = await auth.provedLately()
52
+ const refused = remove.form.failed()?.data?.error
53
+ const notProved = prove.form.failed()?.data?.error
54
+ const proved = await auth.proof.recent()
55
55
  // Neither proof form can pass: an admin acting as the user proves nothing, and an account with nothing to prove it by has only its sign-in, now old.
56
56
  const impersonated = await auth.impersonator() !== null
57
57
  const impact = await auth.account.deletionImpact()
@@ -68,7 +68,7 @@ else
68
68
  .flex.flex-col.items-start.gap-3
69
69
  p {wording('auth.account.data.exportIntro', 'Everything we keep about your account, as a JSON file.')}
70
70
  if proved
71
- Button(href={`${features.prefix}/export`} label={wording('auth.account.data.export', 'Download your data')} download data-no-prefetch)
71
+ Button(href={`${features.prefix}/export`} label={wording('auth.account.data.export', 'Download your data')} download data-prefetch="false")
72
72
  else if stale
73
73
  form.flex.flex-col.items-start.gap-3(action={signInAgain})
74
74
  p {wording('auth.proof.stale', 'For your safety, sign in again before doing this.')}
@@ -12,32 +12,32 @@ import PageSection from '@kayjs/ui/page-section.kay'
12
12
  export const resend = action(async (ctx) => {
13
13
  const result = await ctx.locals.auth.email.sendVerification()
14
14
 
15
- return result.ok ? 'sent' : ctx.fail(400, { error: result.error.code })
15
+ return result.ok ? 'sent' : ctx.deny(400, { data: { error: result.error.code } })
16
16
  })
17
17
 
18
18
  export const changeEmail = action(schemas.changeEmail, async (input, ctx) => {
19
19
  const result = await ctx.locals.auth.email.change(proofOf(input), input.email)
20
20
 
21
21
  if (!result.ok)
22
- return ctx.fail(400, 'errors' in result ? { email: result.errors.email } : { error: result.error.code })
22
+ return ctx.deny(400, { data: 'errors' in result ? { email: result.errors.email } : { error: result.error.code } })
23
23
 
24
24
  return input.email
25
25
  })
26
26
 
27
27
  export const changeUsername = action(schemas.changeUsername, async ({ username }, ctx) => {
28
- const result = await ctx.locals.auth.account.changeUsername(username)
28
+ const result = await ctx.locals.auth.account.updateUsername(username)
29
29
 
30
30
  if (!result.ok)
31
- return ctx.fail(400, 'errors' in result ? { username: result.errors.username } : { error: result.error.code })
31
+ return ctx.deny(400, { data: 'errors' in result ? { username: result.errors.username } : { error: result.error.code } })
32
32
 
33
33
  return 'saved'
34
34
  })
35
35
 
36
36
  export const saveProfile = action(schemas.profile, async (input, ctx) => {
37
- const result = await ctx.locals.auth.account.saveProfile(input)
37
+ const result = await ctx.locals.auth.account.updateProfile(input)
38
38
 
39
39
  if (!result.ok)
40
- return ctx.fail(400, 'errors' in result ? { errors: result.errors } : { error: 'form' as const })
40
+ return ctx.deny(400, { data: 'errors' in result ? { errors: result.errors } : { error: 'form' as const } })
41
41
 
42
42
  return 'saved'
43
43
  })
@@ -45,15 +45,15 @@ export const saveProfile = action(schemas.profile, async (input, ctx) => {
45
45
  const auth = ctx.locals.auth
46
46
  const user = await auth.requireUser()
47
47
  const features = auth.features()
48
- const resent = resend.succeeded() !== undefined
49
- const resendError = resend.failed()?.data?.error
50
- const emailSent = changeEmail.succeeded()?.data
51
- const emailRefused = changeEmail.failed()?.data
52
- const usernameSaved = changeUsername.succeeded() !== undefined
53
- const usernameRefused = changeUsername.failed()?.data
54
- const profile = await auth.account.profile(ctx.locale)
55
- const profileSaved = saveProfile.succeeded() !== undefined
56
- const profileRefused = saveProfile.failed()?.data
48
+ const resent = resend.status() === 'ready'
49
+ const resendError = resend.form.failed()?.data?.error
50
+ const emailSent = changeEmail.data()
51
+ const emailRefused = changeEmail.form.failed()?.data
52
+ const usernameSaved = changeUsername.status() === 'ready'
53
+ const usernameRefused = changeUsername.form.failed()?.data
54
+ const profile = await auth.account.getProfile(ctx.locale)
55
+ const profileSaved = saveProfile.status() === 'ready'
56
+ const profileRefused = saveProfile.form.failed()?.data
57
57
  const profileProblems = profileRefused && 'errors' in profileRefused ? profileRefused.errors : {}
58
58
  const problemOf = (name: string) => Object.hasOwn(profileProblems, name) ? profileProblems[name] : undefined
59
59
  ---
@@ -18,7 +18,7 @@ export const rename = action(schemas.organization, async ({ name, slug }, ctx) =
18
18
  const result = await auth.organizations.update(String(ctx.params.org), { name: name.trim(), slug: slug?.trim() || null })
19
19
 
20
20
  if (!result.ok)
21
- return ctx.fail(400, { error: result.error.code })
21
+ return ctx.deny(400, { data: { error: result.error.code } })
22
22
 
23
23
  const { organization } = result
24
24
 
@@ -26,47 +26,47 @@ export const rename = action(schemas.organization, async ({ name, slug }, ctx) =
26
26
  })
27
27
 
28
28
  export const setRoles = action(schemas.memberRoles, async ({ userId, roles }, ctx) => {
29
- const result = await ctx.locals.auth.organizations.setMemberRoles(String(ctx.params.org), userId, (roles ?? []) as never[])
29
+ const result = await ctx.locals.auth.organizations.updateMemberRoles(String(ctx.params.org), userId, (roles ?? []) as never[])
30
30
 
31
- return result.ok ? 'done' : ctx.fail(400, { error: result.error.code })
31
+ return result.ok ? 'done' : ctx.deny(400, { data: { error: result.error.code } })
32
32
  })
33
33
 
34
34
  export const removeMember = action(schemas.member, async ({ userId }, ctx) => {
35
- const result = await ctx.locals.auth.organizations.removeMember(String(ctx.params.org), userId)
35
+ const result = await ctx.locals.auth.organizations.deleteMember(String(ctx.params.org), userId)
36
36
 
37
- return result.ok ? 'done' : ctx.fail(400, { error: result.error.code })
37
+ return result.ok ? 'done' : ctx.deny(400, { data: { error: result.error.code } })
38
38
  })
39
39
 
40
40
  export const invite = action(schemas.invite, async ({ email, roles }, ctx) => {
41
41
  const result = await ctx.locals.auth.organizations.invite(String(ctx.params.org), email.trim(), roles?.length ? roles as never[] : undefined)
42
42
 
43
- return result.ok ? result.invitation.email : ctx.fail(400, { error: result.error.code })
43
+ return result.ok ? result.invitation.email : ctx.deny(400, { data: { error: result.error.code } })
44
44
  })
45
45
 
46
46
  export const revoke = action(schemas.id, async ({ id }, ctx) => {
47
47
  const result = await ctx.locals.auth.organizations.revokeInvitation(String(ctx.params.org), id)
48
48
 
49
- return result.ok ? 'done' : ctx.fail(400, { error: result.error.code })
49
+ return result.ok ? 'done' : ctx.deny(400, { data: { error: result.error.code } })
50
50
  })
51
51
 
52
52
  export const leave = action(schemas.adminDelete, async ({ confirm }, ctx) => {
53
53
  if (confirm !== true)
54
- return ctx.fail(400, { error: 'form' })
54
+ return ctx.deny(400, { data: { error: 'form' } })
55
55
 
56
56
  const auth = ctx.locals.auth
57
57
  const result = await auth.organizations.leave(String(ctx.params.org))
58
58
 
59
- return result.ok ? ctx.redirect(organizationsPage(auth.features())) : ctx.fail(400, { error: result.error.code })
59
+ return result.ok ? ctx.redirect(organizationsPage(auth.features())) : ctx.deny(400, { data: { error: result.error.code } })
60
60
  })
61
61
 
62
62
  export const remove = action(schemas.adminDelete, async ({ confirm }, ctx) => {
63
63
  if (confirm !== true)
64
- return ctx.fail(400, { error: 'form' })
64
+ return ctx.deny(400, { data: { error: 'form' } })
65
65
 
66
66
  const auth = ctx.locals.auth
67
67
  const result = await auth.organizations.delete(String(ctx.params.org))
68
68
 
69
- return result.ok ? ctx.redirect(organizationsPage(auth.features())) : ctx.fail(400, { error: result.error.code })
69
+ return result.ok ? ctx.redirect(organizationsPage(auth.features())) : ctx.deny(400, { data: { error: result.error.code } })
70
70
  })
71
71
 
72
72
  const auth = ctx.locals.auth
@@ -84,15 +84,15 @@ const held = new Set(found.roles.flatMap(role => settings.grants[role] ?? []))
84
84
 
85
85
  const manages = held.has(settings.manage)
86
86
  const owns = held.has(settings.owner)
87
- const members = await auth.organizations.members(organization.id)
87
+ const members = await auth.organizations.listMembers(organization.id)
88
88
  const people = members.ok ? members.members : []
89
- const open = manages ? await auth.organizations.invitations(organization.id) : null
89
+ const open = manages ? await auth.organizations.listInvitations(organization.id) : null
90
90
  const invitations = open?.ok ? open.invitations : []
91
91
  // A manager changes only members holding no role above theirs, and gives only roles they hold.
92
92
  const editable = (roles: string[]) => manages && roles.every(role => held.has(role))
93
93
  const grantable = settings.roles.filter(role => held.has(role))
94
- const refused = [rename, setRoles, removeMember, invite, revoke, leave, remove].map(form => form.failed()?.data?.error).find(error => error !== undefined)
95
- const invited = invite.succeeded()?.data
94
+ const refused = [rename, setRoles, removeMember, invite, revoke, leave, remove].map(action => action.form.failed()?.data?.error).find(error => error !== undefined)
95
+ const invited = invite.data()
96
96
  const date = (value: Date) => formatDate(value, { dateStyle: 'medium' })
97
97
  const label = (user: { email: string | null, username: string | null, id: string }) => user.username ?? user.email ?? user.id
98
98
  ---
@@ -16,7 +16,7 @@ export const create = action(schemas.organization, async ({ name, slug }, ctx) =
16
16
  const result = await ctx.locals.auth.organizations.create({ name: name.trim(), ...slug?.trim() && { slug: slug.trim() } })
17
17
 
18
18
  if (!result.ok)
19
- return ctx.fail(400, { error: result.error.code })
19
+ return ctx.deny(400, { data: { error: result.error.code } })
20
20
 
21
21
  const { organization } = result.membership
22
22
 
@@ -28,7 +28,7 @@ export const accept = action(schemas.id, async ({ id }, ctx) => {
28
28
  const result = await ctx.locals.auth.organizations.acceptInvitation(id)
29
29
 
30
30
  if (!result.ok)
31
- return ctx.fail(400, { error: result.error.code })
31
+ return ctx.deny(400, { data: { error: result.error.code } })
32
32
 
33
33
  const { organization } = result.membership
34
34
 
@@ -38,13 +38,13 @@ export const accept = action(schemas.id, async ({ id }, ctx) => {
38
38
  export const reject = action(schemas.id, async ({ id }, ctx) => {
39
39
  const result = await ctx.locals.auth.organizations.rejectInvitation(id)
40
40
 
41
- return result.ok ? 'rejected' : ctx.fail(400, { error: result.error.code })
41
+ return result.ok ? 'rejected' : ctx.deny(400, { data: { error: result.error.code } })
42
42
  })
43
43
 
44
44
  const auth = ctx.locals.auth
45
45
  const features = auth.features()
46
- const [memberships, invitations] = await Promise.all([auth.organizations.list(), auth.organizations.myInvitations()])
47
- const refused = [create, accept, reject].map(form => form.failed()?.data?.error).find(error => error !== undefined)
46
+ const [memberships, invitations] = await Promise.all([auth.organizations.list(), auth.organizations.listMyInvitations()])
47
+ const refused = [create, accept, reject].map(action => action.form.failed()?.data?.error).find(error => error !== undefined)
48
48
  const date = (value: Date) => formatDate(value, { dateStyle: 'medium' })
49
49
  ---
50
50
  PageSection(title={wording('auth.organizations.title', 'Organizations')})
@@ -19,7 +19,7 @@ export const changePassword = action(schemas.changePassword, async (input, ctx)
19
19
  const result = await ctx.locals.auth.password.change(proofOf(input), input.newPassword)
20
20
 
21
21
  if (!result.ok)
22
- return ctx.fail(400, 'errors' in result ? { password: result.errors.password } : { error: result.error.code })
22
+ return ctx.deny(400, { data: 'errors' in result ? { password: result.errors.password } : { error: result.error.code } })
23
23
 
24
24
  return 'saved'
25
25
  })
@@ -28,59 +28,59 @@ export const changePassword = action(schemas.changePassword, async (input, ctx)
28
28
  export const setUp = action(schemas.proof, async (input, ctx) => {
29
29
  const result = await ctx.locals.auth.twoFactor.setUp(proofOf(input))
30
30
 
31
- return result.ok ? result.setup.uri : ctx.fail(400, { error: result.error.code })
31
+ return result.ok ? result.setup.uri : ctx.deny(400, { data: { error: result.error.code } })
32
32
  })
33
33
 
34
34
  // Posts the URI back with the code, so a wrong code shows the same QR code again.
35
35
  export const enable = action(schemas.enableTwoFactor, async ({ code }, ctx) => {
36
36
  const result = await ctx.locals.auth.twoFactor.enable(code)
37
37
 
38
- return result.ok ? result.recoveryCodes : ctx.fail(400, { error: result.error.code === 'invalid' ? 'code' : result.error.code })
38
+ return result.ok ? result.recoveryCodes : ctx.deny(400, { data: { error: result.error.code === 'invalid' ? 'code' : result.error.code } })
39
39
  })
40
40
 
41
41
  export const regenerate = action(schemas.proof, async (input, ctx) => {
42
42
  const result = await ctx.locals.auth.twoFactor.regenerateRecoveryCodes(proofOf(input))
43
43
 
44
- return result.ok ? result.recoveryCodes : ctx.fail(400, { error: result.error.code })
44
+ return result.ok ? result.recoveryCodes : ctx.deny(400, { data: { error: result.error.code } })
45
45
  })
46
46
 
47
47
  export const disable = action(schemas.proof, async (input, ctx) => {
48
48
  const result = await ctx.locals.auth.twoFactor.disable(proofOf(input))
49
49
 
50
- return result.ok ? 'disabled' : ctx.fail(400, { error: result.error.code })
50
+ return result.ok ? 'disabled' : ctx.deny(400, { data: { error: result.error.code } })
51
51
  })
52
52
 
53
53
  export const passkeyOptions = action(schemas.proof, async (input, ctx) => {
54
54
  const result = await ctx.locals.auth.passkeys.registrationOptions(proofOf(input))
55
55
 
56
- return result.ok ? result.options : ctx.fail(400, { error: result.error.code })
56
+ return result.ok ? result.options : ctx.deny(400, { data: { error: result.error.code } })
57
57
  })
58
58
 
59
59
  export const addPasskey = action(schemas.registerPasskey, async (input, ctx) => {
60
60
  const result = await ctx.locals.auth.passkeys.register(input.response, input.name)
61
61
 
62
- return result.ok ? result.passkey.id : ctx.fail(400, { error: result.error.code })
62
+ return result.ok ? result.passkey.id : ctx.deny(400, { data: { error: result.error.code } })
63
63
  })
64
64
 
65
65
  export const renamePasskey = action(schemas.renamePasskey, async ({ id, name }, ctx) => {
66
- return (await ctx.locals.auth.passkeys.rename(id, name)).ok ? name : ctx.fail(404, { error: 'not-found' })
66
+ return (await ctx.locals.auth.passkeys.update(id, name)).ok ? name : ctx.deny(404, { data: { error: 'not-found' } })
67
67
  })
68
68
 
69
69
  export const removePasskey = action(schemas.removePasskey, async (input, ctx) => {
70
70
  const result = await ctx.locals.auth.passkeys.revoke(input.id, proofOf(input))
71
71
 
72
- return result.ok ? 'removed' : ctx.fail(400, { error: result.error.code, id: input.id })
72
+ return result.ok ? 'removed' : ctx.deny(400, { data: { error: result.error.code, id: input.id } })
73
73
  })
74
74
 
75
75
  const auth = ctx.locals.auth
76
76
  const user = await auth.requireUser()
77
77
  const features = auth.features()
78
- const passwordSaved = changePassword.succeeded() !== undefined
79
- const passwordRefused = changePassword.failed()?.data
80
- const setupUri = setUp.succeeded()?.data ?? enable.failed()?.values.uri
78
+ const passwordSaved = changePassword.status() === 'ready'
79
+ const passwordRefused = changePassword.form.failed()?.data
80
+ const setupUri = setUp.data() ?? enable.form.failed()?.values.uri
81
81
  const setupKey = setupUri && new URL(setupUri).searchParams.get('secret')
82
- const twoFactorError = setUp.failed()?.data?.error ?? enable.failed()?.data?.error ?? regenerate.failed()?.data?.error ?? disable.failed()?.data?.error
83
- const recoveryCodes = enable.succeeded()?.data ?? regenerate.succeeded()?.data
82
+ const twoFactorError = setUp.form.failed()?.data?.error ?? enable.form.failed()?.data?.error ?? regenerate.form.failed()?.data?.error ?? disable.form.failed()?.data?.error
83
+ const recoveryCodes = enable.data() ?? regenerate.data()
84
84
  // Where a guard sent the user from to turn two-factor on: back there once it is on and its recovery codes were seen.
85
85
  const back = localPath(ctx.url.searchParams.get('redirect'), '')
86
86
 
@@ -89,7 +89,7 @@ if (back !== '' && user.twoFactor && !recoveryCodes)
89
89
 
90
90
  const codesLeft = user.twoFactor ? await auth.twoFactor.recoveryCodesLeft() : 0
91
91
  const passkeys = features.passkeys ? await auth.passkeys.list() : []
92
- const removeRefused = removePasskey.failed()?.data
92
+ const removeRefused = removePasskey.form.failed()?.data
93
93
  const passkeyErrors = Object.fromEntries((['proof', 'stale', 'limited', 'impersonating', 'expired', 'invalid', 'signed-out'] as const).map(code => [code, failure(code)]))
94
94
  ---
95
95
  if features.password