@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
@@ -46,25 +46,25 @@ With `audit: true`, or `{ maxAge }` as a string such as `'90d'` (a year by defau
46
46
 
47
47
  The prebuilt pages for the methods below are in [the admin pages](admin-pages.md).
48
48
 
49
- `admin: 'admin'`, any requirement a guard takes, names who may manage users; without it, and to anyone else, to an admin acting as someone or to a bearer token, an admin's included, every method below answers `{ ok: false, error: { code: 'forbidden' } }`, or `two-factor-required` for an admin whom `twoFactor.require` names and who has not turned two-factor on. The methods changing a user, `admin.grantRole`, `admin.revokeRole`, `admin.ban`, `admin.unban` and `admin.deleteUser`, also answer `stale` unless the admin signed in or re-proved (`reprove`) in the last ten minutes, so a session left open or stolen changes no one; reading users and the audit log takes no such proof.
49
+ `admin: 'admin'`, any requirement a guard takes, names who may manage users; without it, and to anyone else, to an admin acting as someone or to a bearer token, an admin's included, every method below answers `{ ok: false, error: { code: 'forbidden' } }`, or `two-factor-required` for an admin whom `twoFactor.require` names and who has not turned two-factor on. The methods changing a user, `admin.grantRole`, `admin.revokeRole`, `admin.ban`, `admin.unban` and `admin.deleteUser`, also answer `stale` unless the admin signed in or re-proved (`proof.renew`) in the last ten minutes, so a session left open or stolen changes no one; reading users and the audit log takes no such proof.
50
50
 
51
51
  - `userIdsHolding(role)` gives the ids of the users holding `role` or a role above it in the `roles` hierarchy, banned ones left out, for server code that tells them something (kayjs-cms notifies its reviewers with it). It answers for any signed-in user, nothing otherwise, and reads the 10,000 newest users at most.
52
- - `admin.listUsers({ search, offset, limit })` gives `{ ok: true, users, total }`, newest first, 50 a page by default and 200 at most; `search` matches part of an email or a username whatever its case, or a whole id. `admin.getUser(id)` gives one, with `admin` telling whether they meet the `admin` option; `admin.roles()` lists the roles an admin may give. Each is a `User` with `createdAt` and `ban`, `{ bannedAt, until, reason }` while banned, else null.
52
+ - `admin.listUsers({ search, offset, limit })` gives `{ ok: true, users, total }`, newest first, 50 a page by default and 200 at most; `search` matches part of an email or a username whatever its case, or a whole id. `admin.getUser(id)` gives one, with `admin` telling whether they meet the `admin` option; `admin.listRoles()` lists the roles an admin may give. Each is a `User` with `createdAt` and `ban`, `{ bannedAt, until, reason }` while banned, else null.
53
53
  - `admin.grantRole(id, role)` and `admin.revokeRole(id, role)` take a role the `roles` option declares (`unknown-role` otherwise), effective on the user's next request. An admin taking back a role of their own that leaves them no longer an admin is refused (`self`), and when two admins revoke each other at once at least one stays an admin: a revoke that would have left none is undone and answers `last-admin`.
54
54
  - `admin.ban(id, { reason, until })` bars the user from signing in, for good or until that date (`until` in the past answers `until`), and signs them out everywhere, bearer tokens revoked. Every sign-in of theirs answers `{ ok: false, error: { code: 'banned' } }`, an OAuth one `?error=banned`, and `auth.signIn` throws. An admin cannot ban themselves (`self`) or another admin (`admin`): revoke the role first. `admin.unban(id)` lifts it.
55
55
  - `admin.deleteUser(id)` deletes the user as `account.delete` does (notifications and mailing lists included), `beforeDelete({ user, context })` first (it can refuse with `refused`), and mails them the `account-deleted` notice when `email` is set and their address is verified. The audit log keeps an `account-deleted` entry with the admin as `actorId`, and `onEvent` and `beforeDelete` get the admin as `context.actor`. It gives `{ ok: true }`, or `{ ok: false, error }` with `forbidden`, `stale`, `not-found`, `self`, `admin` or `refused` as for `admin.ban`. An organization the user solely owns with other members passes to its longest-standing member, who gets an `organization-handed-over` event and mail, so an abandoned account is never a dead end; an organization they are alone in is deleted with them.
56
- - `admin.impersonate(id)` answers `stale` unless the admin signed in or re-proved within ten minutes, as the other admin changes do, and signs the admin's browser in as the user, keeping the admin's own sign-in; `impersonator()` gives the admin, to show a banner, and `admin.stopImpersonating()` signs them back in as themselves, or out when their own sign-in ended meanwhile. The user is mailed an `impersonation-started` notice, to a verified address only and best effort: an unverified address gets none, and a failing mailer is logged while the impersonation goes on. It ends 30 minutes after it starts, however busy it is: the admin's next request finds them signed in as themselves again, an `impersonation-ended` event with `expired` recorded, as it also ends once the admin is signed out everywhere, banned or no longer an admin, which signs them out. Meanwhile nothing taking a proof passes (`reprove` answers `impersonating`, and the sign-in counts as stale), every write to the user's organizations answers `impersonating` (create, update, delete, invite, revoke, accept or reject an invitation, set roles, remove, leave; the reads stay open), and no new sign-in mail goes out. Another admin, oneself and a banned user cannot be impersonated. `signOut()` ends both sign-ins.
57
- - `admin.auditLog({ userId, before, limit })` gives `{ ok: true, entries }`, everyone's audit log or one user's, paged by `before` as `audit.list` is.
56
+ - `admin.impersonate(id)` answers `stale` unless the admin signed in or re-proved within ten minutes, as the other admin changes do, and signs the admin's browser in as the user, keeping the admin's own sign-in; `impersonator()` gives the admin, to show a banner, and `admin.stopImpersonating()` signs them back in as themselves, or out when their own sign-in ended meanwhile. The user is mailed an `impersonation-started` notice, to a verified address only and best effort: an unverified address gets none, and a failing mailer is logged while the impersonation goes on. It ends 30 minutes after it starts, however busy it is: the admin's next request finds them signed in as themselves again, an `impersonation-ended` event with `expired` recorded, as it also ends once the admin is signed out everywhere, banned or no longer an admin, which signs them out. Meanwhile nothing taking a proof passes (`proof.renew` answers `impersonating`, and the sign-in counts as stale), every write to the user's organizations answers `impersonating` (create, update, delete, invite, revoke, accept or reject an invitation, set roles, remove, leave; the reads stay open), and no new sign-in mail goes out. Another admin, oneself and a banned user cannot be impersonated. `signOut()` ends both sign-ins.
57
+ - `admin.listAuditLog({ userId, before, limit })` gives `{ ok: true, entries }`, everyone's audit log or one user's, paged by `before` as `audit.list` is.
58
58
 
59
59
  ### Organization rules
60
60
 
61
61
  - `roles` is a hierarchy as the site's `roles` is, typed the same way. Whoever creates an organization holds `owner`: owners alone delete it, and the last one cannot leave, be removed, lose the role or delete their account (`last-owner`); a sole owner who is also the only member deletes the organization with the account. `account.deletionImpact()` gives `{ deleted, blocked }`, the organization names the signed-in user's deletion would delete or be refused for, and the account page shows both before the proof. A deletion not refused (an admin's `admin.deleteUser`, a stale guest, an unverified registration replaced) hands such an organization to its longest-standing member, who is told (`organization-handed-over`), and owners leaving, demoted or deleted at once cannot leave it ownerless: a write that would have left none is undone and answers `last-owner`. `manage`, `owner` by default, is what renaming, inviting, removing members and changing their roles take. `create`, any requirement a guard takes, limits who may create one; anyone signed in by default.
62
62
  - `organizations.create({ name, slug? })` answers `{ ok: true, membership }`, or `invalid-name` (1 to 100 characters, with no control characters, line breaks or direction marks, the name going into the invitation mail), `invalid-slug` (lowercase letters, digits and dashes, 64 at most, lowercased first), `slug-taken` or `limited` (past `organization`, 10 a day per account). A membership is `{ organization: { id, name, slug, createdAt }, roles, joinedAt }`.
63
63
  - `organizations.list()` lists the user's memberships; `organizations.get(ref)` gives one, by id or slug, null unless a member; `organizations.isMember(ref, role?)` says whether they are one, holding `role` when given. `organizations.update(ref, { name, slug })` renames it, `slug: null` clearing the slug, and `organizations.delete(ref)` deletes it with its memberships and invitations. Every write answers `'impersonating'` to an admin acting as the user (`OrganizationWriteFailure`), the reads do not.
64
- - `organizations.members(ref)` gives `{ ok: true, members }`, each `{ user: { id, email, username }, roles, joinedAt }`, for any member to see; only one holding the `manage` role is given the others' emails, as `email` is `null` for the rest (their own stays). `organizations.setMemberRoles(ref, userId, roles)` replaces a member's roles, `organizations.removeMember(ref, userId)` removes one, and `organizations.leave(ref)` leaves. A manager gives only roles they hold, to a member holding none above theirs: an admin cannot make an owner nor demote or remove one (`forbidden`).
65
- - `organizations.invite(ref, email, roles?)` mails the address a link to `invitationPage` + `?invitation=<id>`, the prebuilt pages' `/auth/invitation` when it is not set (`unavailable` without either, or without a mailer, or when the mailer throws), giving `roles`, `defaultRoles` without them, once accepted: `unverified` while the manager has not verified their own address, `member` when the address belongs to a member already, `limited` past `organizations.invite`, 30 an hour per manager, or `inviteAddress`, 5 a day per invited address whoever invites it, a count a stranger inviting the address can use up. Inviting an address again replaces its invitation. An invitation stands only while its sender is a member who still manages the organization and holds the roles it gives: after they leave, are removed or lose a role it gives, it is not found, deleting their account included. `organizations.invitations(ref)` lists the open ones for managers and `organizations.revokeInvitation(ref, id)` revokes one. An invitation lasts `invitations: { maxAge }`, a string such as `'7d'`, a week by default. The mail's `kind` is `'invitation'`, the organization's name its template's `detail`.
66
- - The page reads `organizations.invitation(id)`, `{ id, organization, email, roles, invitedBy, createdAt, expiresAt }` or null once revoked, accepted or expired, and posts to an action calling `organizations.acceptInvitation(id)`: only an account verified at the invited address joins (`wrong-account`, `unverified`), which an invitee without an account reaches by registering with it. `organizations.myInvitations()` lists those open to the user's verified address, `organizations.rejectInvitation(id)` turns one down, answering `{ ok }` (`not-found` for one not open to the user).
67
- - Every organization call that changes something needs a session: `organizations.create`, `organizations.update`, `organizations.delete`, `organizations.setMemberRoles`, `organizations.removeMember`, `organizations.leave`, `organizations.invite`, `organizations.invitations`, `organizations.revokeInvitation`, `organizations.acceptInvitation` and `organizations.rejectInvitation` answer `signed-out` to a bearer or OAuth token, so a leaked API key cannot join, create, invite, delete or change roles. The reads (`organizations`, `organization`, `members`, `organizations.isMember`, `myInvitations`, `invitation`) accept a token as its user.
64
+ - `organizations.listMembers(ref)` gives `{ ok: true, members }`, each `{ user: { id, email, username }, roles, joinedAt }`, for any member to see; only one holding the `manage` role is given the others' emails, as `email` is `null` for the rest (their own stays). `organizations.updateMemberRoles(ref, userId, roles)` replaces a member's roles, `organizations.deleteMember(ref, userId)` removes one, and `organizations.leave(ref)` leaves. A manager gives only roles they hold, to a member holding none above theirs: an admin cannot make an owner nor demote or remove one (`forbidden`).
65
+ - `organizations.invite(ref, email, roles?)` mails the address a link to `invitationPage` + `?invitation=<id>`, the prebuilt pages' `/auth/invitation` when it is not set (`unavailable` without either, or without a mailer, or when the mailer throws), giving `roles`, `defaultRoles` without them, once accepted: `unverified` while the manager has not verified their own address, `member` when the address belongs to a member already, `limited` past `organizations.invite`, 30 an hour per manager, or `inviteAddress`, 5 a day per invited address whoever invites it, a count a stranger inviting the address can use up. Inviting an address again replaces its invitation. An invitation stands only while its sender is a member who still manages the organization and holds the roles it gives: after they leave, are removed or lose a role it gives, it is not found, deleting their account included. `organizations.listInvitations(ref)` lists the open ones for managers and `organizations.revokeInvitation(ref, id)` revokes one. An invitation lasts `invitations: { maxAge }`, a string such as `'7d'`, a week by default. The mail's `kind` is `'invitation'`, the organization's name its template's `detail`.
66
+ - The page reads `organizations.getInvitation(id)`, `{ id, organization, email, roles, invitedBy, createdAt, expiresAt }` or null once revoked, accepted or expired, and posts to an action calling `organizations.acceptInvitation(id)`: only an account verified at the invited address joins (`wrong-account`, `unverified`), which an invitee without an account reaches by registering with it. `organizations.listMyInvitations()` lists those open to the user's verified address, `organizations.rejectInvitation(id)` turns one down, answering `{ ok }` (`not-found` for one not open to the user).
67
+ - Every organization call that changes something needs a session: `organizations.create`, `organizations.update`, `organizations.delete`, `organizations.updateMemberRoles`, `organizations.deleteMember`, `organizations.leave`, `organizations.invite`, `organizations.listInvitations`, `organizations.revokeInvitation`, `organizations.acceptInvitation` and `organizations.rejectInvitation` answer `signed-out` to a bearer or OAuth token, so a leaked API key cannot join, create, invite, delete or change roles. The reads (`organizations`, `organization`, `members`, `organizations.isMember`, `myInvitations`, `invitation`) accept a token as its user.
68
68
  - Any failure above may also be `signed-out`, `not-found` (no such organization, or one the user is no member of, so its existence does not leak) or `forbidden` (a member whose roles do not reach).
69
69
  - `auth.memberOf(role?)` is a requirement met by a member of the organization the route's `org` param names, by id or slug, holding `role` there when given: `src/routes/orgs/[org]/_guard.ts` exporting `auth.guard({ redirect: '/login', require: auth.memberOf('admin') })`, or `.get('/orgs/:org/settings', handler, { auth: auth.memberOf('admin') })` behind a gate. `organizations.param`, or `memberOf(role, { param })`, names another param. A guard checks a page's actions against the params of the page they are posted from, so an action scopes what it touches by `ctx.params.org`, never by its input. A route without the param, or kay before 1.23, whose guards get no params, is refused, never let through.
70
70
  - Deleting a user deletes their memberships; `account.delete` of the only owner of an organization with other members is refused (`last-owner`), while an admin's `admin.deleteUser`, a stale guest and a replaced registration hand it to the longest-standing member, and an organization they are alone in goes with them. `exportData()` lists the user's memberships as `organizations`.
@@ -24,7 +24,7 @@ extensions: [auth({ admin: 'admin', roles: { admin: ['editor'], editor: [] }, au
24
24
 
25
25
  ## Reference
26
26
 
27
- - `auth.requireAdmin()` is the guard of the pages for your own admin page: the signed-in admin as themselves, else the refusal above.
28
- - `features().admin` is whether an admin is named and `features().audit` whether the audit log is kept; the roles an admin may give are `auth.admin.roles()`, server-side.
27
+ - `auth.admin.require()` is the guard of the pages for your own admin page: the signed-in admin as themselves, else the refusal above.
28
+ - `features().admin` is whether an admin is named and `features().audit` whether the audit log is kept; the roles an admin may give are `auth.admin.listRoles()`, server-side.
29
29
  - The words are `auth.admin.*` and `auth.impersonation.*` in the app's catalogs; English and French ship.
30
30
  - The organization methods in [admin and organizations](admin-and-organizations.md) have their pages in [the organization pages](organization-pages.md).
@@ -6,7 +6,13 @@
6
6
 
7
7
  The methods of a feature live under it on the request's `auth`, so an editor lists one feature at a time: `ctx.locals.auth.admin.listUsers()`, `ctx.locals.auth.password.signIn(input)`, `ctx.locals.auth.organizations.invite(ref, email)`. A group is there whether its feature is on or not; a method of a feature that is off answers `{ ok: false, error: { code: 'off' } }` as before.
8
8
 
9
- The methods no feature owns stay on `auth` itself: the user (`user()`, `bareUser()`, `requireUser()`, `requireAdmin()`, `guarded()`, `signInUrl()`, `via`), signing in and out (`signIn`, `signOut`, `signOutEverywhere`, `signInAsGuest`), what the request may do (`features()`, `scopes()`, `hasScope`, `provedLately`, `reprove`, `captchaRequired`, `captchaChallenge`, `impersonator()`, `userIdsHolding`) and the OAuth server's resource (`oauthResource`, `oauthOrigin`, `oauthFixed`).
9
+ The methods no feature owns stay on `auth` itself: the user (`user()`, `bareUser()`, `requireUser()`, `guarded()`, `signInUrl()`, `via`), signing in and out (`signIn`, `signOut`, `signOutEverywhere`, `signInAsGuest`), what the request may do (`features()`, `impersonator()`, `userIdsHolding`).
10
+
11
+ ### Use the verbs of the groups
12
+
13
+ A group lists with `list` (`organizations.list()`, `organizations.listMembers(ref)`), reads with `get` (`organizations.getInvitation(id)`, `account.getProfile()`), writes with `create` and `update` (`account.updateProfile(values)`, `passkeys.update(id, name)`), removes with `delete` (`organizations.deleteMember(ref, userId)`, `account.delete(proof)`) and takes back with `revoke` (`sessions.revoke(id)`, `tokens.revoke(id)`). The admin's methods name what they act on (`admin.listUsers()`, `admin.deleteUser(id)`), and `password.change` and `email.change` keep `change`. What was on `auth` itself sits in the group it belongs to: `admin.require()` for an admin page, `captcha.required(action)` and `captcha.challenge(action)` for a form's CAPTCHA, `proof.recent(fresh?)` and `proof.renew(proof)` before a sensitive change, `tokens.scopes()` and `tokens.hasScope(scope)` for a token's scopes, `oauthServer.resource(path, name)`, `origin()` and `fixed()` for the OAuth documents, and `email.signInWithCode(code)` for the code a mail carried.
14
+
15
+ The names before 1.105 (`organizations.members`, `admin.roles`, `auth.requireAdmin()`, `magicLink.signInWithCode`...) work until 1.108: `kay check` reports each call as `deprecated-auth-methods` and `kay upgrade` writes the new name.
10
16
 
11
17
  ### Move off the flat names
12
18
 
@@ -23,15 +29,19 @@ The flat names `auth` had before 1.82 (`auth.listUsers()`, `auth.signInWithPassw
23
29
  | `password` | `requestReset` | `requestPasswordReset` |
24
30
  | `password` | `reset` | `resetPassword` |
25
31
  | `password` | `change` | `changePassword` |
32
+ | `captcha` | `required` | `captchaRequired` (on `auth` until 1.105) |
33
+ | `captcha` | `challenge` | `captchaChallenge` (on `auth` until 1.105) |
34
+ | `proof` | `recent` | `provedLately` (on `auth` until 1.105) |
35
+ | `proof` | `renew` | `reprove` (on `auth` until 1.105) |
26
36
  | `email` | `sendVerification` | `sendVerification` |
27
37
  | `email` | `verify` | `verifyEmail` |
28
38
  | `email` | `verifyCode` | `verifyEmailCode` |
39
+ | `email` | `signInWithCode` | `signInWithEmailCode` |
29
40
  | `email` | `pendingCode` | `emailCodePending` |
30
41
  | `email` | `change` | `changeEmail` |
31
42
  | `email` | `confirmChange` | `confirmEmailChange` |
32
43
  | `magicLink` | `request` | `requestMagicLink` |
33
44
  | `magicLink` | `signIn` | `signInWithMagicLink` |
34
- | `magicLink` | `signInWithCode` | `signInWithEmailCode` |
35
45
  | `twoFactor` | `pending` | `twoFactorPending` |
36
46
  | `twoFactor` | `verify` | `verifyTwoFactor` |
37
47
  | `twoFactor` | `setUp` | `setUpTwoFactor` |
@@ -44,7 +54,7 @@ The flat names `auth` had before 1.82 (`auth.listUsers()`, `auth.signInWithPassw
44
54
  | `passkeys` | `registrationOptions` | `passkeyRegistrationOptions` |
45
55
  | `passkeys` | `register` | `registerPasskey` |
46
56
  | `passkeys` | `list` | `listPasskeys` |
47
- | `passkeys` | `rename` | `updatePasskeyName` |
57
+ | `passkeys` | `update` | `updatePasskeyName` |
48
58
  | `passkeys` | `revoke` | `revokePasskey` |
49
59
  | `passkeys` | `signInOptions` | `passkeySignInOptions` |
50
60
  | `passkeys` | `signIn` | `signInWithPasskey` |
@@ -54,19 +64,25 @@ The flat names `auth` had before 1.82 (`auth.listUsers()`, `auth.signInWithPassw
54
64
  | `tokens` | `create` | `createToken` |
55
65
  | `tokens` | `list` | `listTokens` |
56
66
  | `tokens` | `revoke` | `revokeBearerToken` |
67
+ | `tokens` | `scopes` | `scopes` (on `auth` until 1.105) |
68
+ | `tokens` | `hasScope` | `hasScope` (on `auth` until 1.105) |
57
69
  | `oauthServer` | `authorize` | `oauthAuthorize` |
58
70
  | `oauthServer` | `decide` | `oauthDecide` |
59
- | `oauthServer` | `clients` | `listOAuthClients` |
71
+ | `oauthServer` | `listClients` | `listOAuthClients` |
60
72
  | `oauthServer` | `revokeGrant` | `revokeOAuthGrant` |
73
+ | `oauthServer` | `resource` | `oauthResource` (on `auth` until 1.105) |
74
+ | `oauthServer` | `origin` | `oauthOrigin` (on `auth` until 1.105) |
75
+ | `oauthServer` | `fixed` | `oauthFixed` (on `auth` until 1.105) |
61
76
  | `admin` | `listUsers` | `listUsers` |
62
77
  | `admin` | `getUser` | `getUser` |
63
- | `admin` | `roles` | `adminRoles` |
78
+ | `admin` | `require` | `requireAdmin` (on `auth` until 1.105) |
79
+ | `admin` | `listRoles` | `adminRoles` |
64
80
  | `admin` | `grantRole` | `grantRole` |
65
81
  | `admin` | `revokeRole` | `revokeRole` |
66
82
  | `admin` | `ban` | `banUser` |
67
83
  | `admin` | `unban` | `unbanUser` |
68
84
  | `admin` | `deleteUser` | `deleteUser` |
69
- | `admin` | `auditLog` | `listAdminAuditLog` |
85
+ | `admin` | `listAuditLog` | `listAdminAuditLog` |
70
86
  | `admin` | `impersonate` | `impersonate` |
71
87
  | `admin` | `stopImpersonating` | `stopImpersonating` |
72
88
  | `organizations` | `create` | `createOrganization` |
@@ -75,15 +91,15 @@ The flat names `auth` had before 1.82 (`auth.listUsers()`, `auth.signInWithPassw
75
91
  | `organizations` | `isMember` | `isMember` |
76
92
  | `organizations` | `update` | `updateOrganization` |
77
93
  | `organizations` | `delete` | `deleteOrganization` |
78
- | `organizations` | `members` | `listMembers` |
79
- | `organizations` | `setMemberRoles` | `setMemberRoles` |
80
- | `organizations` | `removeMember` | `deleteMember` |
94
+ | `organizations` | `listMembers` | `listMembers` |
95
+ | `organizations` | `updateMemberRoles` | `setMemberRoles` |
96
+ | `organizations` | `deleteMember` | `deleteMember` |
81
97
  | `organizations` | `leave` | `leaveOrganization` |
82
98
  | `organizations` | `invite` | `invite` |
83
- | `organizations` | `invitations` | `listInvitations` |
99
+ | `organizations` | `listInvitations` | `listInvitations` |
84
100
  | `organizations` | `revokeInvitation` | `revokeInvitation` |
85
- | `organizations` | `myInvitations` | `listMyInvitations` |
86
- | `organizations` | `invitation` | `getInvitation` |
101
+ | `organizations` | `listMyInvitations` | `listMyInvitations` |
102
+ | `organizations` | `getInvitation` | `getInvitation` |
87
103
  | `organizations` | `acceptInvitation` | `acceptInvitation` |
88
104
  | `organizations` | `rejectInvitation` | `rejectInvitation` |
89
105
 
@@ -91,16 +107,16 @@ The flat names `auth` had before 1.82 (`auth.listUsers()`, `auth.signInWithPassw
91
107
 
92
108
  | Group | Method | Flat name (gone in 1.91) |
93
109
  | --- | --- | --- |
94
- | `account` | `changeUsername` | `changeUsername` |
110
+ | `account` | `updateUsername` | `changeUsername` |
95
111
  | `account` | `updateLocale` | `updateLocale` |
96
112
  | `account` | `delete` | `deleteAccount` |
97
113
  | `account` | `deletionImpact` | `deletionImpact` |
98
- | `account` | `profile` | `profile` |
99
- | `account` | `saveProfile` | `saveProfile` |
114
+ | `account` | `getProfile` | `profile` |
115
+ | `account` | `updateProfile` | `saveProfile` |
100
116
  | `account` | `export` | `exportData` |
101
117
  | `oauth` | `link` | `linkProvider` |
102
118
  | `oauth` | `unlink` | `unlink` |
103
- | `oauth` | `identities` | `listIdentities` |
104
- | `oauth` | `providerToken` | `providerToken` |
119
+ | `oauth` | `listIdentities` | `listIdentities` |
120
+ | `oauth` | `getProviderToken` | `providerToken` |
105
121
  | `audit` | `list` | `listAuditLog` |
106
122
  | `admin` (on the `authCore` result) | `createUser` | `createUser` |
@@ -33,7 +33,7 @@ const page = await site.submit(signIn, { identifier: 'ada@example.com', password
33
33
  A test site signs in with one call, no form round trip. `authTest(site)` from `@kayjs/auth/test` is the auth that site's `testSite()` built (each site its own, so call it after `testSite()`), and `kay generate resource` writes its test with it:
34
34
 
35
35
  ```ts
36
- import { authTest } from '@kayjs/auth/test'
36
+ import { test as authTest } from '@kayjs/auth/test'
37
37
 
38
38
  const as = authTest(site)
39
39
 
@@ -56,27 +56,27 @@ An app with a `src/auth.ts` module calls the same on its `auth` with the site fi
56
56
  ### Bots and breached passwords rules
57
57
 
58
58
  - `captcha` is kay's proof of work unless set, `proofOfWork()`: no third party, no widget and no cookie, the browser hashing for some tens of milliseconds before the request goes through. It costs a bot CPU on each request rather than proving a human, so a site bots target anyway, or whose accounts are worth money to a spammer, sets Turnstile or hCaptcha instead. `captcha: false` turns it off.
59
- - `proofOfWork({ difficulty, maxAge, store, on })`: `difficulty` is 100,000 by default, doubled with each request past the threshold up to 16 times, `maxAge` an hour; `store` keeps the solutions already used, this process's memory by default, `sqliteRates(path)` from `kay/server` sharing them between processes; `on` asks registering, resets and magic links always, a password sign-in from the third attempt, and a guest sign-in never.
60
- - `await auth.captchaChallenge(action)` is the challenge for this client's next request, null when none is needed or the CAPTCHA is a third party's. A form carries it as `input(type="hidden" name="captcha" data-kay-work={challenge})`, kay's script posts its solution as the field's value, and the action passes it on as the token below; the prebuilt pages do, naming the field `kayjs-captcha`. `kay check` reports a call of `password.register`, `password.requestReset`, `magicLink.request` or `password.signIn` on an `auth` with no `captcha` option (`missing-captcha`), as it answers `{ ok: false, error: { code: 'captcha' } }` until the form carries the field and the call passes it on.
59
+ - `proofOfWork({ difficulty, ttl, store, on })`: `difficulty` is 100,000 by default, doubled with each request past the threshold up to 16 times, `ttl` an hour (`maxAge` until 1.108); `store` keeps the solutions already used, this process's memory by default, `sqliteRates(path)` from `kay/server` sharing them between processes; `on` asks registering, resets and magic links always, a password sign-in from the third attempt, and a guest sign-in never.
60
+ - `await auth.captcha.challenge(action)` is the challenge for this client's next request, null when none is needed or the CAPTCHA is a third party's. A form carries it as `input(type="hidden" name="captcha" data-kay-work={challenge})`, kay's script posts its solution as the field's value, and the action passes it on as the token below; the prebuilt pages do, naming the field `kayjs-captcha`. `kay check` reports a call of `password.register`, `password.requestReset`, `magicLink.request` or `password.signIn` on an `auth` with no `captcha` option (`missing-captcha`), as it answers `{ ok: false, error: { code: 'captcha' } }` until the form carries the field and the call passes it on.
61
61
  - A browser without JavaScript posts the field empty, refused as `'captcha'`, and so does a form kay's script leaves to the browser (`navigation: false` with no island, `data-reload`, a `target`); the prebuilt pages then say JavaScript is needed, and that a stale solution should be sent again, and set a honeypot and a two-second `minTime` on their forms for the requests a post without JavaScript still reaches.
62
62
  - The app's own register, reset and magic-link forms carry the field, or the app sets `captcha: false`. A client kay's script does not run in, a plain Elysia app's own pages, a mobile app or a SPA calling the API, has no solver: it sets `captcha: false` or a third party's check. A test calling `auth.password.register()` directly passes `captcha: false` to the auth it builds. A custom `verify` is given `'guest'` for `signInAsGuest`. A test posts from the page it visited, `site.submit(register, fields, { from: await site.visit('/register') })`, which `site.submit` solves the field of.
63
63
  - `turnstile(secret)` and `hcaptcha(secret)` send the provider's siteverify only the secret and the token, from the server. The widget runs in the visitor's browser, which loads the provider's script (`challenges.cloudflare.com`, `js.hcaptcha.com`) and talks to it directly, so the provider receives the visitor's address, browser and cookies: say so in the site's privacy notice and consent flow. kay's proof of work calls no third party.
64
64
  - `captcha.verify(token, action, { hostname })` checks the token the page's widget posted, `hostname` being the site's own from `site`, for `action` one of `'register'`, `'guest'`, `'sign-in'`, `'reset'` and `'magic-link'`. `turnstile(secret)` and `hcaptcha(secret)` are presets calling the provider's siteverify; their widgets post the token as `cf-turnstile-response` and `h-captcha-response`, which the action passes on. The presets refuse a token the provider says was made for another hostname, and Turnstile one made for another action (the prebuilt pages' widgets set `data-action`; a widget with none passes). The documented test secrets of both providers skip these two checks, as their answers name a hostname and action of their own.
65
65
  - The token goes in the trailing `captcha` option of `password.register`, `password.signIn`, `password.requestReset` and `magicLink.request`. A missing or refused token, or a `verify` that throws, answers `{ ok: false, error: { code: 'captcha' } }`, still counted against the client's limit.
66
- - `captcha.on` sets each request to `'always'` (every one, by default for a third party's check, a guest sign-in as registering), `false`, or a number: asked only once this client made that many of it in the limit's window, so people rarely see it. `auth.captchaRequired(action)` says whether the next one needs it, for the page to show the widget. `captcha.widget` names that widget for the prebuilt pages and `features()`.
66
+ - `captcha.on` sets each request to `'always'` (every one, by default for a third party's check, a guest sign-in as registering), `false`, or a number: asked only once this client made that many of it in the limit's window, so people rarely see it. `auth.captcha.required(action)` says whether the next one needs it, for the page to show the widget. `captcha.widget` names that widget for the prebuilt pages and `features()`.
67
67
  - `breachedPasswords` is on by default in production (`NODE_ENV=production`) and off elsewhere, `false` turning it off in production: it refuses a new password Have I Been Pwned lists, on `password.register`, `password.reset` and `password.change`, as `errors.password: 'breached'`. Only the first five characters of the password's SHA-1 leave the server, the answer padded with decoys. A function `(password) => boolean` checks against a list of the app's own instead. In production, `authCore` warns at boot when password sign-up is open with no `email`: registering then answers `taken` for a held address. A check that fails or takes over three seconds lets the password through, logged: an outage never stops anyone registering. `pwnedPassword(password)` is exported for a check of the app's own.
68
68
 
69
69
  ### Limits
70
70
 
71
- Attempts are counted in the store's `rates` (`memoryAuth` and `pgAuth` keep them), else in the app's `store.rates` from kay.config.ts (`sqliteRates` or `pgRates`: `memoryRates` drops open windows past 10,000, which a flood of typed addresses would use to lift a lockout), else in the process's memory (where they also count while a store throws, rejects or takes over 8 seconds, logged once, as kay's own limits do), per client address (kept as a keyed digest, never the address; read as kay's `rateLimit` reads it, through `proxy` in kay.config.ts) and per account. A plain Elysia app that kay's `pages()` does not serve passes the same setting to `authCore` as `proxy`, `{ hops: 1 }` behind nginx, or every client counts as the proxy. `rateLimit` overrides any of `DEFAULT_LIMITS`, each a kay `RateLimit` `{ max, window, store? }` with `window` a string such as `'1h'` (`store` counts that bucket in a store of its own), or a list of them, each counted apart and any refusing; `onLimit({ name, key, wait })` is told of each attempt a limit refused (`key` is the one kayjs-auth counted under), and a `rateLimit()` object from `kay/server` is refused at boot, as the counts are under keys of the library's own; the lockouts read `max` of the first:
71
+ Attempts are counted in the store's `rates` (`memoryAuth` and `pgAuth` keep them), else in the app's `store.rates` from kay.config.ts (`sqliteRates` or `pgRates`: `memoryRates` drops open windows past 10,000, which a flood of typed addresses would use to lift a lockout), else in the process's memory (where they also count while a store throws, rejects or takes over 8 seconds, logged once, as kay's own limits do), per client address (kept as a keyed digest, never the address; read as kay's `rateLimit` reads it, through `proxy` in kay.config.ts) and per account. A plain Elysia app that kay's `pages()` does not serve passes the same setting to `authCore` as `proxy`, `{ hops: 1 }` behind nginx, or every client counts as the proxy. `rateLimit` overrides any of the defaults below, grouped by feature (`{ signIn: { ip, account, accountAll }, forgot: { account }, oauth: { token } }`, the flat keys of before 1.105 such as `signInAccount` working until 1.108, `deprecated-auth-rate-limits`), each a kay `RateLimit` `{ max, window, store? }` with `window` a string such as `'1h'` (`store` counts that bucket in a store of its own), or a list of them, each counted apart and any refusing; `onLimit({ name, key, wait })` is told of each attempt a limit refused (`key` is the one kayjs-auth counted under), and a `rateLimit()` object from `kay/server` is refused at boot, as the counts are under keys of the library's own; the lockouts read `max` of the first:
72
72
 
73
- - `signIn` 40 per client and 15 minutes. Wrong passwords count against an account twice, a success clearing the client's hard stop only: `signInAccount` 6 per account and client, the hard stop (so a stranger's failures never lock the holder out from another address), and `signInAccountAll` 60 per account from every client, the ceiling, spent by wrong passwords alone and not given back by the holder's sign-in. Past the ceiling every sign-in answers `'limited'` until the window ends, and the first one mails the holder's verified address (`sign-in-locked`, also an event), at most once a day however often the ceiling is reached again. The same counts guard `email.verify(token, password)`. Behind one proxy without `proxy` set, every client shares the hard stop. Passkeys and the second factor have their own limits.
73
+ - `signIn.ip` 40 per client and 15 minutes. Wrong passwords count against an account twice, a success clearing the client's hard stop only: `signIn.account` 6 per account and client, the hard stop (so a stranger's failures never lock the holder out from another address), and `signIn.accountAll` 60 per account from every client, the ceiling, spent by wrong passwords alone and not given back by the holder's sign-in. Past the ceiling every sign-in answers `'limited'` until the window ends, and the first one mails the holder's verified address (`sign-in-locked`, also an event), at most once a day however often the ceiling is reached again. The same counts guard `email.verify(token, password)`. Behind one proxy without `proxy` set, every client shares the hard stop. Passkeys and the second factor have their own limits.
74
74
  - `register` 6 per hour.
75
- - `resend`, `forgot` and `magicLink` 12 per client and 3 per account per hour (`resendAccount`, `forgotAccount` and `magicLinkAccount`, the last two counted per address); `emailChange` 12 and `emailChangeAccount` 5.
76
- - `invite` 30 per manager per hour, `inviteAddress` 5 per invited address per day.
75
+ - `resend`, `forgot` and `magicLink` 12 per client (`ip`) and 3 per account (`account`, counted per address) per hour; `emailChange` 12 and 5.
76
+ - `invite.sender` 30 per manager per hour, `invite.address` 5 per invited address per day.
77
77
  - `organization` 10 per account per day, for `organizations.create`.
78
78
  - `export` 6 per account per hour, for `account.export()` and `GET <prefix>/export`.
79
- - `twoFactor` 30 and `twoFactorAccount` 8 per 15 minutes, for signing in and for turning the factor on; the first sign-in guess past `twoFactorAccount` mails the holder the `sign-in-locked` notice, at most once a day; `reprove` 6 per 15 minutes; `link` 40 per hour; `emailCode` 30 per client and `emailCodeAccount` 10 per address per 15 minutes.
79
+ - `twoFactor.ip` 30 and `twoFactor.account` 8 per 15 minutes, for signing in and for turning the factor on; the first sign-in guess past `twoFactor.account` mails the holder the `sign-in-locked` notice, at most once a day; `reprove` 6 per 15 minutes; `link` 40 per hour; `emailCode.ip` 30 per client and `emailCode.account` 10 per address per 15 minutes.
80
80
 
81
81
  ### Stores
82
82
 
@@ -7,10 +7,10 @@
7
7
  Each entry of `oauth` names a provider app: `{ provider, clientId, clientSecret }`. Its routes are `/auth/<name>` and `/auth/<name>/callback`, and the callback URL to register at the provider is `site` + `/auth/<name>/callback`.
8
8
 
9
9
  ```kay
10
- a(href="/auth/discord?redirect=/account" data-no-prefetch) Sign in with Discord
10
+ a(href="/auth/discord?redirect=/account" data-prefetch="false") Sign in with Discord
11
11
  ```
12
12
 
13
- A link to an OAuth route changes the session on GET: give it `data-no-prefetch`, so a hover starts nothing.
13
+ A link to an OAuth route changes the session on GET: give it `data-prefetch="false"`, so a hover starts nothing.
14
14
 
15
15
  ### Passkeys
16
16
 
@@ -29,11 +29,11 @@ export const addPasskey = action(s.Object({ response: passkeyAttestation, name:
29
29
  import { makePasskey, passkeyFailure } from '@kayjs/auth/browser'
30
30
 
31
31
  try {
32
- const { options } = await passkeyOptions({ password })
32
+ const { options } = await passkeyOptions({ password }).orThrow()
33
33
  const response = await makePasskey(options)
34
34
 
35
35
  if (response)
36
- await addPasskey({ response, name })
36
+ await addPasskey({ response, name }).orThrow()
37
37
  }
38
38
  catch (caught) {
39
39
  error.set(passkeyFailure(caught, { proof: 'Wrong password' }, 'That did not work'))
@@ -46,12 +46,12 @@ catch (caught) {
46
46
 
47
47
  - The provider presets (github, discord, google, microsoft, gitlab, apple, linkedin, facebook, twitch, slack, x), their options, `oidcProvider` and `kay env` names are in [OAuth provider presets](oauth-providers.md); a preset takes `{ scopes, params }` and a provider of your own is any `OAuthProvider`.
48
48
  - The flow keeps its state and PKCE verifier in the session, so a callback works once, in the browser that started it, within ten minutes. A callback whose `state` is wrong or missing is refused without spending the flow, so a page on another site loading the callback URL cannot kill a sign-in in flight. Starting the same sign-in again (`GET /auth/<provider>`, same `redirect`) goes on with the pending flow, the same `state`; a start with another `redirect` replaces a sign-in in flight, and none replaces a provider link in flight (`oauth.link`): it answers `?error=oauth`. A site whose `site` is https refuses a provider endpoint, discovered ones included, on plain http whatever `NODE_ENV` says. A provider failing the exchange is logged, and a sign-in refused for a known account (`banned`, or `taken` when linking) reports `sign-in-failed` with `method` `oauth`. `redirect` is kept to a path on the site. For the app's own redirects, kay's `localPath(path, fallback)` answers the path normalised, dot segments resolved, and `fallback` for anything that would leave the site once resolved or decoded; a bare `%` in the query or hash is kept, while a malformed escape in the path is refused.
49
- - A provider account signs into the user it is linked to. A new one signs up a new user, taking its email and its name only when no other user has them: no account is ever merged into another by email. `onSignUp({ user, profile, context })` runs for every new user, to create the app's own records; `profile` is `undefined` for a password sign-up. A throw is logged and reported (source `auth.onSignUp`) and the sign-up stands.
50
- - `profileFields({ user, profile })` runs whenever a provider answers for a user (every OAuth sign-in, the first included after `onSignUp`, and a link), before any second factor, to refresh what the app keeps from the profile, such as an avatar or a display name. A failure in it is logged and the sign-in goes on. With a `user` schema (`user: s.Object({ avatar: s.Optional(s.String()) })`) what it returns is laid over `user.data`: only declared top-level fields count, one left out or `undefined` keeps its value, and a result the schema refuses or over 16 KB of JSON drops the whole patch, logged. The update is read-modify-write, so sign-ins at once can overwrite each other's fields. With `profileFields: ({ profile }) => ({ avatar: profile.avatar ?? undefined })`, `(await auth.user()).data.avatar` is typed from the schema, and `user.providers.discord?.id` is the id a linked provider gave.
49
+ - A provider account signs into the user it is linked to. A new one signs up a new user, taking its email and its name only when no other user has them: no account is ever merged into another by email. `afterSignUp({ user, profile, context })` runs for every new user, to create the app's own records; `profile` is `undefined` for a password sign-up. A throw is logged and reported (source `auth.afterSignUp`) and the sign-up stands.
50
+ - `profileFields({ user, profile })` runs whenever a provider answers for a user (every OAuth sign-in, the first included after `afterSignUp`, and a link), before any second factor, to refresh what the app keeps from the profile, such as an avatar or a display name. A failure in it is logged and the sign-in goes on. With a `user` schema (`user: s.Object({ avatar: s.Optional(s.String()) })`) what it returns is laid over `user.data`: only declared top-level fields count, one left out or `undefined` keeps its value, and a result the schema refuses or over 16 KB of JSON drops the whole patch, logged. The update is read-modify-write, so sign-ins at once can overwrite each other's fields. With `profileFields: ({ profile }) => ({ avatar: profile.avatar ?? undefined })`, `(await auth.user()).data.avatar` is typed from the schema, and `user.providers.discord?.id` is the id a linked provider gave.
51
51
  - `allow(profile)` is asked before any user is touched; false refuses, as an allowlist of provider ids does.
52
52
  - `oauth.link(provider, proof, { redirect })` links a provider account to the signed-in user instead, refused when another user has it linked: from an action, `ctx.redirect(result.url)` sends the browser to the provider, which comes back to `redirect`. A linked provider is a way in that outlives every sign-out, so linking takes a proof, the second factor when it is on (see Re-proof); `'not-found'` for a provider the app did not configure, `'unavailable'` when the provider failed.
53
53
  - A failure goes to `failurePage` as it is when set, else to `signInPage?error=<code>`, with `&redirect=` keeping the page the sign-in was started for: `oauth` (a state or code that did not check out, or a provider account without an id), `cancelled`, `refused`, `taken`, `unavailable` (the provider failed, answered nonsense or took over 10 seconds to answer), `signed-out` (a link whose user signed out before coming back).
54
- - `oauth.providerToken('discord')` gives the signed-in user's access token, refreshed when about to expire, or `null` when it cannot be: the tokens are forgotten once the provider refuses the refresh token, and kept through an outage (a provider taking over 10 seconds counts as one). Tokens are stored encrypted only with `keepTokens: true` on the provider's `oauth` entry (`null` without it). Unlinking a provider and deleting the account revoke the token held at the provider (RFC 7009: Discord, Google, GitLab, Apple and an OpenID Connect provider whose discovery document lists a `revocation_endpoint`; a custom provider sets `revokeUrl`), a failure only logged; GitHub and Microsoft have no such endpoint, so the user ends the grant in their settings. `oauth.identities()` lists the providers the user linked.
54
+ - `oauth.getProviderToken('discord')` gives the signed-in user's access token, refreshed when about to expire, or `null` when it cannot be: the tokens are forgotten once the provider refuses the refresh token, and kept through an outage (a provider taking over 10 seconds counts as one). Tokens are stored encrypted only with `keepTokens: true` on the provider's `oauth` entry (`null` without it). Unlinking a provider and deleting the account revoke the token held at the provider (RFC 7009: Discord, Google, GitLab, Apple and an OpenID Connect provider whose discovery document lists a `revocation_endpoint`; a custom provider sets `revokeUrl`), a failure only logged; GitHub and Microsoft have no such endpoint, so the user ends the grant in their settings. `oauth.listIdentities()` lists the providers the user linked.
55
55
 
56
56
  ### Two-factor
57
57
 
@@ -63,7 +63,7 @@ catch (caught) {
63
63
 
64
64
  ### Switching features off
65
65
 
66
- - `auth({ password: false, passkeys: false, magicLink: false, twoFactor: false })`, and the same keys of `authCore`, switch a feature off; each is on by default where it works. A method of a feature that is off answers `{ ok: false, error: { code: 'off' } }`: `password.register`, `password.signIn`, `password.requestReset`, `password.reset` and `password.change` for `password`; `magicLink.request`, `magicLink.signIn` and `magicLink.signInWithCode` for `magicLink`; the passkey sign-in, adding and proof methods for `passkeys`; `twoFactor.setUp` and `twoFactor.enable` for `twoFactor`. `passkeys.signInOptions` throws.
66
+ - `auth({ password: false, passkeys: false, magicLink: false, twoFactor: false })`, and the same keys of `authCore`, switch a feature off; each is on by default where it works. A method of a feature that is off answers `{ ok: false, error: { code: 'off' } }`: `password.register`, `password.signIn`, `password.requestReset`, `password.reset` and `password.change` for `password`; `magicLink.request`, `magicLink.signIn` and `email.signInWithCode` for `magicLink`; the passkey sign-in, adding and proof methods for `passkeys`; `twoFactor.setUp` and `twoFactor.enable` for `twoFactor`. `passkeys.signInOptions` throws.
67
67
  - A default-on feature is `false | Config` and a default-off one `true | Config`: `password`, `magicLink`, `twoFactor`, `signUp` and `pages` of `auth()` take `false` (or an object), never `true`, so leaving one out is how it stays on. `oauthServer` and `breachedPasswords` keep `true`, which demands them where they would not be on by themselves.
68
68
  - The `error.code` an `{ ok: false, error }` result carries for a feature that does not run:
69
69
 
@@ -74,7 +74,7 @@ catch (caught) {
74
74
  | `'not-enabled'` | the user has not turned two-factor on | `twoFactor.regenerateRecoveryCodes` |
75
75
 
76
76
  - `features()` has `password`, `magicLink` and `twoFactor` besides `passkeys`, false for a feature off (`magicLink` also without mail), and the prebuilt pages show none of it: no password form, mail form, passkey button or account section, and the register and reset pages answer 404.
77
- - `twoFactor: { require: ['admin'] }` (a role, a predicate or a list, as a guard's `require`) makes it a must for those users. A user it names who lacks it is sent by `authGuard()` and `requireAdmin()` to the security page (`securityPage`, the prebuilt account security page by default) with `?redirect=` back, when opening a page, and gets a 403 on any other request; `auth.gate()` only answers 403, and `requireUser()` does not check it. Every `auth.admin` method answers `{ ok: false, error: { code: 'two-factor-required' } }` and OAuth consent answers `access_denied`.
77
+ - `twoFactor: { require: ['admin'] }` (a role, a predicate or a list, as a guard's `require`) makes it a must for those users. A user it names who lacks it is sent by `authGuard()` and `admin.require()` to the security page (`securityPage`, the prebuilt account security page by default) with `?redirect=` back, when opening a page, and gets a 403 on any other request; `auth.gate()` only answers 403, and `requireUser()` does not check it. Every `auth.admin` method answers `{ ok: false, error: { code: 'two-factor-required' } }` and OAuth consent answers `access_denied`.
78
78
  - The check never applies to the security page, the `twoFactorPage` and the sign-out route, whatever guard or gate runs, so a user can always turn it on; the prebuilt security page sends them back through `?redirect=` once it is on and the recovery codes were seen. An endpoint outside those, such as the app's own enrolment API, takes `auth: false` on its gate and `requireUser()`. `authGuard({ twoFactor: true })` asks every user the guard lets through.
79
79
  - A passkey sign-in counts as two factors (a passkey with user verification is phishing-resistant), a password-only or OAuth-only session does not, and an admin acting as another user is not asked, having proved theirs to start. A guest lacks it. A bearer token counts as its user. A `require` predicate that throws fails the request closed with a 500. Organization roles (`memberOf`) read the route's params, so they apply in guards and gates only, not in the admin methods or OAuth consent. Production boot warns when `admin` is on and nothing requires it.
80
80
  - `twoFactor: false` stops new enrolments only: a user who turned it on is still asked for the code at sign-in, and can still renew their recovery codes and turn it off. `forwardAuth.requireTwoFactor` needs `twoFactor` on. A switched-off way in no longer counts for the last one a user cannot unlink or revoke.
@@ -86,7 +86,7 @@ Passkeys are made for `site`'s host and checked against its origin: `passkeys: {
86
86
  - `@kayjs/auth/browser` is what an island calls, with the browser's own WebAuthn JSON methods and no library: `canAskPasskey()` and `canMakePasskey()` say whether to show the button, `askPasskey(options)` and `makePasskey(options)` take the options an action returned and answer the typed JSON for the next action, or null when the person picked none, `rememberChoice()` reads the page's "keep me signed in" box (`input[name=remember]`) for the `remember` of `passkeys.signIn`, undefined when the page has none, and `passkeyFailure(caught, errors, failed)` is the message for what threw: the one of `errors` for the code an action refused with, nothing when the person dismissed the prompt, else `failed`.
87
87
  - `passkeyAssertion` (`passkeys.signIn`, `twoFactor.verifyPasskey`, a `{ passkey }` proof) and `passkeyAttestation` (`passkeys.register`) are the schemas an action takes the answer with: typed as the method takes it, so no cast, and refused with a 422 when the answer lacks `id`, `rawId`, `type: 'public-key'` or a part of `response` the ceremony reads. The signature and challenge are the ceremony's to check.
88
88
  - `passkeys.registrationOptions(proof)` and `passkeys.register(response, name?)` add a passkey to the signed-in user, named as given (control and direction characters removed, 64 characters at most) or after the browser and system it was made on (`Safari on macOS`), and mail them. A passkey is a way in that skips the second factor and outlives every sign-out, so adding one takes a proof, the second factor when it is on, as linking a provider does (see Re-proof). The passkey is kept on the authenticator, so it signs in without a name typed first.
89
- - `passkeys.list()` lists `{ id, name, multiDevice, backedUp, userVerified, createdAt, lastUsedAt }` (a passkey with `userVerified: false`, one stored before passkeys always asked for user verification, is no way in until a sign-in or re-proof with it proves it; replace it by adding a new one); `passkeys.rename(id, name)` answers `{ ok }` or `{ ok: false, error: { code: 'not-found' | 'invalid-name' | 'signed-out' } }`; `passkeys.revoke(id, proof)` re-proves first, refuses the last passkey of an account with no other way in (`'last-way-in'`, also when a request unlinking the other way in runs at the same moment; a passkey with `userVerified: false` does not count), and mails the user.
89
+ - `passkeys.list()` lists `{ id, name, multiDevice, backedUp, userVerified, createdAt, lastUsedAt }` (a passkey with `userVerified: false`, one stored before passkeys always asked for user verification, is no way in until a sign-in or re-proof with it proves it; replace it by adding a new one); `passkeys.update(id, name)` answers `{ ok }` or `{ ok: false, error: { code: 'not-found' | 'invalid-name' | 'signed-out' } }`; `passkeys.revoke(id, proof)` re-proves first, refuses the last passkey of an account with no other way in (`'last-way-in'`, also when a request unlinking the other way in runs at the same moment; a passkey with `userVerified: false` does not count), and mails the user.
90
90
  - `passkeys.signInOptions()` and `passkeys.signIn(response, { redirect?, remember? })` sign in with a passkey alone: the options name no account, so the browser offers every passkey it holds for the site, and with `askPasskey(options, { autofill: true })` offers them in the autofill of a field with `autocomplete="username webauthn"`. The passkey must verify the user (a PIN, a fingerprint), so it is two factors in one and no second factor is asked after it. Errors: `'expired'` (no challenge, or one spent), `'invalid'`, `'limited'`.
91
91
  - `twoFactor.passkeyOptions()` and `twoFactor.verifyPasskey(response)` answer a sign-in waiting at the `twoFactorPage` with one of the user's passkeys, as `twoFactor.verify` does with a code.
92
92
  - `passkeys.proofOptions()` gives the options for a re-proof; the answer goes in as `{ passkey: response }` wherever a proof is asked, and stands for the password and the second factor both.
@@ -99,13 +99,13 @@ Changing what protects the account takes a `proof`: `password.change`, `email.ch
99
99
  - `{ passkey }`, the answer to `passkeys.proofOptions()`, from any user with a passkey.
100
100
  - `{ password }` when the user has a password; otherwise `{ code }`, an authenticator or recovery code, when they have a second factor. `email.change`, `twoFactor.disable`, `twoFactor.regenerateRecoveryCodes`, `passkeys.registrationOptions` and `oauth.link` take the `{ code }` even from a user with a password, so the password alone cannot undo or get around what stands behind it, nor move the account and its reset links to another address.
101
101
  - A user with neither proves nothing but a sign-in under ten minutes old: past that, the method answers `'stale'` and the page asks them to sign in again first. A stolen session thus cannot set a password and an address and keep the account.
102
- - `auth.reprove(proof)` proves the user without changing anything, as before an app's own sensitive change. Any proof counts for ten minutes, as a sign-in does, and `auth.provedLately()` tells whether one still does.
102
+ - `auth.proof.renew(proof)` proves the user without changing anything, as before an app's own sensitive change. Any proof counts for ten minutes, as a sign-in does, and `auth.proof.recent()` tells whether one still does; `proof.recent('5m')` asks within another time, and `authGuard({ fresh: '5m' })` refuses a request without one ([Ask for the password or passkey again](sessions-and-guards.md#ask-for-the-password-or-passkey-again)).
103
103
  - `'proof'` for a wrong or missing proof, `'limited'` after six tries in 15 minutes, `'signed-out'` without a user, `'impersonating'` while an admin acts as the user.
104
104
 
105
105
  ### Account
106
106
 
107
107
  - `password.change(proof, password)` sets the password, or a first one (`errors.password` as `password.register`'s), ends the user's other sessions and bearer tokens, and voids the links mailed before.
108
- - `account.changeUsername(username)` names or renames the signed-in user, normalised and checked as `password.register` does: `{ ok: true, user }`, `errors: { username }` with `'length'`, `'characters'`, `'mixed-scripts'`, `'taken'` or `'unchanged'`, or `'signed-out'`. Recasing one's own name is allowed. It takes no proof, sends no mail and is not limited, a name being public and no credential, but needs a session: a bearer token answers `'signed-out'`. A page asks a user without a name for one, as after an OAuth sign-up whose name was taken.
109
- - `account.export()` gives the signed-in user everything kayjs-auth keeps about them, for a download of their data: `{ ok: true, data: { exportedAt, user, identities, sessions, passkeys, tokens, recoveryCodesLeft, grants, ban, organizations, invitations, notifications, pushSubscriptions, libraries, mailingLists, audit, app } }`, `notifications` the newest 200 kay notifications of the user, `pushSubscriptions` their web push devices (`{ endpoint, createdAt }`, no keys), `libraries` what libraries registered with kay's `personalData` keep about them, by name (`ai`: their kayjs-ai conversations; `{}` when none), `account.delete` and `admin.deleteUser` erasing the same, `mailingLists` the lists of kayjs-mail their address is on (`{ list, status, askedAt, confirmedAt }`, pending ones too, empty without kayjs-mail), `grants` the apps they approved, `ban` the last ban once over, `invitations` `{ received, sent }`, `user` with `createdAt`, `emailVerifiedAt` and `twoFactorEnabledAt`, no hash, secret or token among it. `exportData({ user })` gives `app`, what the app keeps about them. It needs a session (a bearer token answers `'signed-out'`, an admin acting as the user `'impersonating'`) and a sign-in or `reprove()` under ten minutes old, else `'stale'`: the prebuilt data page asks for the password or code first (an account with neither signs in again, and an admin acting as the user is offered neither the download nor the deletion), an app's own page calls `reprove(proof)` then links the download, `provedLately()` telling whether it must. Each call counts against the `export` limit, 6 per account per hour, past which it answers `'limited'`. `GET <prefix>/export` downloads it as `<site>-data.json`: 401 signed out, 403 for the cases above, 429 past the limit.
108
+ - `account.updateUsername(username)` names or renames the signed-in user, normalised and checked as `password.register` does: `{ ok: true, user }`, `errors: { username }` with `'length'`, `'characters'`, `'mixed-scripts'`, `'taken'` or `'unchanged'`, or `'signed-out'`. Recasing one's own name is allowed. It takes no proof, sends no mail and is not limited, a name being public and no credential, but needs a session: a bearer token answers `'signed-out'`. A page asks a user without a name for one, as after an OAuth sign-up whose name was taken.
109
+ - `account.export()` gives the signed-in user everything kayjs-auth keeps about them, for a download of their data: `{ ok: true, data: { exportedAt, user, identities, sessions, passkeys, tokens, recoveryCodesLeft, grants, ban, organizations, invitations, notifications, pushSubscriptions, libraries, mailingLists, audit, app } }`, `notifications` the newest 200 kay notifications of the user, `pushSubscriptions` their web push devices (`{ endpoint, createdAt }`, no keys), `libraries` what libraries registered with kay's `personalData` keep about them, by name (`ai`: their kayjs-ai conversations; `{}` when none), `account.delete` and `admin.deleteUser` erasing the same, `mailingLists` the lists of kayjs-mail their address is on (`{ list, status, askedAt, confirmedAt }`, pending ones too, empty without kayjs-mail), `grants` the apps they approved, `ban` the last ban once over, `invitations` `{ received, sent }`, `user` with `createdAt`, `emailVerifiedAt` and `twoFactorEnabledAt`, no hash, secret or token among it. `exportData({ user })` gives `app`, what the app keeps about them. It needs a session (a bearer token answers `'signed-out'`, an admin acting as the user `'impersonating'`) and a sign-in or `proof.renew()` under ten minutes old, else `'stale'`: the prebuilt data page asks for the password or code first (an account with neither signs in again, and an admin acting as the user is offered neither the download nor the deletion), an app's own page calls `proof.renew(proof)` then links the download, `proof.recent()` telling whether it must. Each call counts against the `export` limit, 6 per account per hour, past which it answers `'limited'`. `GET <prefix>/export` downloads it as `<site>-data.json`: 401 signed out, 403 for the cases above, 429 past the limit.
110
110
  - `oauth.unlink(provider, proof)` unlinks a provider: `'not-linked'` when it is not, `'last-way-in'` when the user would have no password, no other provider, no passkey that proved user verification and no verified address to get a magic link at (also when two unlinks run at the same moment: one that would have left none is undone and answers `'last-way-in'`).
111
111
  - `account.delete(proof)` deletes the user with everything kayjs-auth keeps for them, the invitations to their address, their kay notifications and, with kayjs-mail, their verified address on its mailing lists and in its queue (`mail.erase`; an address nobody proved stays, as it may be someone else's). `auth()` hands over the mail module's `erase` and `subscriptions` whichever way `email` is written, except `email: false`, where `beforeDelete` calls `mail.erase`; `authCore` takes them on the mailer: `{ ...authMailer(mail.enqueue), erase: mail.erase, subscriptions: mail.subscriptions }`, after calling `beforeDelete({ user, context })` for the app's own records, and signs out, or waits (`account.deleteAfter`). `beforeDelete` can refuse: `false`, or throwing `refuse(message, { status })` from `kay`, keeps the account and answers `{ ok: false, error: { code: 'refused', status, message } }` (403 by default; any other throw answers 500 and is reported with source `auth.beforeDelete`). One that throws leaves the account in place and fails the call too, so the user can try again: write it to cope with records already gone. The only user meeting the `admin` option is refused (`last-admin`) before the proof is spent, so a deployment never loses its last admin (two admins deleting themselves at once: their roles are stripped first and one that would have left none is restored, answering `last-admin` after the proof is spent; this needs an `admin` option that reads roles). The only owner of an organization with other members is refused too (`last-owner`, [Organizations](admin-and-organizations.md)). Asking the user to type their name first is the page's job.
@@ -25,4 +25,4 @@ The presets `oauth: { name: true }` and `oauth: { name: { ...options } }` take,
25
25
  - `facebookProvider({ version })`: Facebook Login on the Graph API, `v27.0` by default (`version` follows Meta's retirements). Scopes `public_profile` and `email`; no email when the account has no valid address, no usernames, no revocation endpoint, and the avatar is the `large` picture.
26
26
  - `xProvider()`: OAuth 2.0 with PKCE, the user read off `users/me`. X gives no email through it (`email` is null, so the user signs up without one, and sign-in is by the X account only), and a confidential client authenticates with an HTTP Basic header, which the preset sets through `clientAuth: 'basic'` on the provider (usable by any provider of your own). Scopes `users.read` and `tweet.read`; add `offline.access` for a refresh token, since access tokens last two hours. Its env name is `X_CLIENT_ID` and `X_CLIENT_SECRET`, its route `/auth/x`.
27
27
  - Any other OpenID Connect provider needs no preset: `oauth: { name: { provider: oidcProvider({ issuer, name }), clientId, clientSecret } }`. The five above are presets rather than `oidcProvider` recipes because `oauth: { slack: true }` is the one form `kay env` lists the credentials of, and LinkedIn, Slack and Twitch skip the discovery request (Twitch also needs its `claims` parameter).
28
- - `appleProvider({ teamId, keyId, privateKey })`: `privateKey` is the `.p8` key's PEM text, the app's `clientId` its Services ID, and it takes no `clientSecret`: the preset signs one. Apple comes back with a POST to the callback, which kayjs-auth turns into a GET so the session cookie rides along. Apple names the user only on their first sign-in, so `profile.displayName` reaches `onSignUp` then and never again.
28
+ - `appleProvider({ teamId, keyId, privateKey })`: `privateKey` is the `.p8` key's PEM text, the app's `clientId` its Services ID, and it takes no `clientSecret`: the preset signs one. Apple comes back with a POST to the callback, which kayjs-auth turns into a GET so the session cookie rides along. Apple names the user only on their first sign-in, so `profile.displayName` reaches `afterSignUp` then and never again.
@@ -48,23 +48,23 @@ authCore({ scopes: ['posts:read', 'posts:write'] })
48
48
 
49
49
  ### OAuth server for MCP clients
50
50
 
51
- - With `pages` and a store keeping `oauth` (`memoryAuth` and `pgAuth` do), an app is an OAuth 2.1 authorization server with no code of its own: an MCP client (Claude Code, MCP Inspector) pointed at kay's `/mcp` is sent to sign in, the user approves it on a consent page, and it is given kayjs-auth's bearer tokens. `user()`, `via()` (`'bearer'`), `requireUser({ scope })`, gates and `scopes` work on them unchanged. `oauthServer: false` turns it off; `oauthServer: true` throws without `pages` or a store with `oauth`; `oauthServer: { fetch }` replaces the `fetch` used to read client metadata documents (tests).
52
- - Served with no setup: `/.well-known/oauth-authorization-server` and `/.well-known/openid-configuration` (RFC 8414; the issuer is the site's origin and `base` from kay.config.ts, else `site` of `authCore`, else the request's origin outside production; in production with neither, its documents and endpoints answer 500 and `/mcp` points at no authorization server, rather than take the issuer from the Host header), the protected resource metadata (RFC 9728) of `/mcp` at `/.well-known/oauth-protected-resource[/mcp]`, which kay serves when `mcp` is on unless the app serves that path itself, and the endpoints `<pages prefix>/oauth/authorize` (the consent page), `<prefix>/oauth/token`, `<prefix>/oauth/register` and `<prefix>/oauth/revoke`. The 401 of `/mcp` already points a client at the resource metadata. Documents and endpoints answer CORS `*`, and are cached for everyone only when a `site` fixes the origin, else `private`. A route of the app at one of the well-known paths replaces the server's own.
51
+ - With `pages` and a store keeping `oauth` (`memoryAuth` and `pgAuth` do), an app is an OAuth 2.1 authorization server with no code of its own: an MCP client (Claude Code, MCP Inspector) pointed at kay's `/_kay/mcp` is sent to sign in, the user approves it on a consent page, and it is given kayjs-auth's bearer tokens. `user()`, `via()` (`'bearer'`), `requireUser({ scope })`, gates and `scopes` work on them unchanged. `oauthServer: false` turns it off; `oauthServer: true` throws without `pages` or a store with `oauth`; `oauthServer: { fetch }` replaces the `fetch` used to read client metadata documents (tests).
52
+ - Served with no setup: `/.well-known/oauth-authorization-server` and `/.well-known/openid-configuration` (RFC 8414; the issuer is the site's origin and `base` from kay.config.ts, else `site` of `authCore`, else the request's origin outside production; in production with neither, its documents and endpoints answer 500 and `/_kay/mcp` points at no authorization server, rather than take the issuer from the Host header), the protected resource metadata (RFC 9728) of `/_kay/mcp` at `/.well-known/oauth-protected-resource[/_kay/mcp]`, which kay serves when `mcp` is on unless the app serves that path itself, and the endpoints `<pages prefix>/oauth/authorize` (the consent page), `<prefix>/oauth/token`, `<prefix>/oauth/register` and `<prefix>/oauth/revoke`. The 401 of `/_kay/mcp` already points a client at the resource metadata. Documents and endpoints answer CORS `*`, and are cached for everyone only when a `site` fixes the origin, else `private`. A route of the app at one of the well-known paths replaces the server's own.
53
53
  - Clients: public only (`token_endpoint_auth_method: none`), by a client ID metadata document (the client ID is an https URL whose JSON names `client_id`, `client_name` and `redirect_uris`; read with no redirect, 5 seconds, 10 KB, never from a private or loopback address, cached 5 minutes) or by dynamic registration (RFC 7591, `POST <prefix>/oauth/register`, ID `kc_...`, 20 per hour per address, `oauthRegisterAll` capping all addresses together when set; a client nobody approved is dropped after 24 hours, and its `client_id` is unknown after that, so the client registers again). Redirect URIs are 1 to 10, each `https`, or `http` on `localhost`, `127.0.0.1` or `[::1]` with the port ignored when matched; one must equal a registered URI, never a prefix. An unknown client or an unregistered URI is never redirected to: the page says so.
54
54
  - Authorization: `response_type=code`, PKCE `S256` required, `scope` from the app's `scopes` (none asked gives the `oauthServer: { defaultScopes }` the app names, else no scope at all, so the token passes only routes with `scope: false`; an app declaring none gives tokens every scope, and an `oauthServer` the app sets on itself with no `scopes`, rather than the one the prebuilt pages switch on alone, warns at boot), `resource` (RFC 8707) must be of this site and given once (several are `invalid_target`, at the token endpoint too), `state` returned with `iss` (RFC 9207). A visitor who is signed out goes to the sign-in page and back; `prompt=none` answers the client `login_required` or `consent_required` instead. Approval is remembered per user and client: signing in again skips the consent page until the user revokes the client, asks for more scopes than were approved, or the request carries `prompt=consent`. Only a user's own session approves, not a bearer token or an admin acting as the user. The consent page names the client, the host of its ID and the host the browser goes back to, lists the scopes, and is never framed; names lose bidirectional control characters.
55
- - Tokens: a code is single use and lives 60 seconds; the access token is a bearer token of the approved scopes lasting an hour; the refresh token rotates at each use, is refused after 30 days unused, and its family ends 90 days after its first token. A code or a refresh token presented twice ends everything issued under it (its family); a refresh cannot add scopes; a wrong `code_verifier` spends the code. The `resource` asked at authorize stays with the code and the tokens through each rotation: the token request and a refresh may name it again or leave it out, any other is `invalid_target`. A token bound to a resource passes only on requests whose path is that resource or under it (its query ignored, a trailing slash either way), and is a 401 anywhere else; a token asked for no resource, or stored before the binding, passes everywhere within its scopes. The calls `/mcp` makes to your tools count as made to `/mcp`, and a `base` of the site is left out of the comparison, so the token matches whether or not the proxy took it off. `userFromToken(token)` for a websocket handshake refuses a bound token unless given the handshake's address, `userFromToken(token, request.url)`. A refresh or code exchange refused for its scope, resource or `redirect_uri` leaves its token unspent when the store has `oauth.refresh.get` or `oauth.codes.get`, as the built-in ones do. `POST <prefix>/oauth/revoke` (RFC 7009, advertised as `revocation_endpoint`) takes `token` (an access or a refresh token) and `client_id` and ends the whole family of that client's tokens, answering 200 even for a token that is unknown or another client's. Revoking a client, `signOutEverywhere`, banning or deleting the user end the tokens and refresh tokens. The tokens are not in `tokens.list()`; the account page lists the client instead.
55
+ - Tokens: a code is single use and lives 60 seconds; the access token is a bearer token of the approved scopes lasting an hour; the refresh token rotates at each use, is refused after 30 days unused, and its family ends 90 days after its first token. A code or a refresh token presented twice ends everything issued under it (its family); a refresh cannot add scopes; a wrong `code_verifier` spends the code. The `resource` asked at authorize stays with the code and the tokens through each rotation: the token request and a refresh may name it again or leave it out, any other is `invalid_target`. A token bound to a resource passes only on requests whose path is that resource or under it (its query ignored, a trailing slash either way), and is a 401 anywhere else; a token asked for no resource, or stored before the binding, passes everywhere within its scopes. The calls `/_kay/mcp` makes to your tools count as made to `/_kay/mcp`, and a `base` of the site is left out of the comparison, so the token matches whether or not the proxy took it off. `userFromToken(token)` for a websocket handshake refuses a bound token unless given the handshake's address, `userFromToken(token, request.url)`. A refresh or code exchange refused for its scope, resource or `redirect_uri` leaves its token unspent when the store has `oauth.refresh.get` or `oauth.codes.get`, as the built-in ones do. `POST <prefix>/oauth/revoke` (RFC 7009, advertised as `revocation_endpoint`) takes `token` (an access or a refresh token) and `client_id` and ends the whole family of that client's tokens, answering 200 even for a token that is unknown or another client's. Revoking a client, `signOutEverywhere`, banning or deleting the user end the tokens and refresh tokens. The tokens are not in `tokens.list()`; the account page lists the client instead.
56
56
  - The consent page says that the name of a client that registered itself is its own and was not checked (`auth.consent.unverified`), and shows the host of one named by a metadata document (`auth.consent.from`).
57
57
  - The consent page, the token form and the lists of tokens and approved apps show each scope as the app words it under `auth.scopes.<scope>` in its messages (`auth: { scopes: { 'posts:read': 'Read your posts' } }`), the scope's code when no catalog has it; a label is shown as text, never as markup, and a language needs its own, as any text the app words. `scopeLabel` is not exported: an app's own page uses `wording('auth.scopes.posts:read', 'posts:read')` from `kay/words`.
58
- - `oauthServer.clients()` lists `{ id, name, scopes, createdAt, lastUsedAt }` of the apps the user approved, and `oauthServer.revokeGrant(id)` revokes one with its tokens (`{ ok: true }`, or `{ ok: false, error: { code: 'not-found' | 'signed-out' } }`; session only), for a page of the app's own. `oauthServer.authorize(params)` and `oauthServer.decide(fields, allow)` are what the consent page calls.
59
- - Limits (`rateLimit`): `oauthRegister` 20 per hour, `oauthRegisterAll` unset (a ceiling on all addresses together), `oauthDocument` 30 per 15 minutes (metadata documents read for an address), `oauthToken` 300 per 15 minutes (the token and the revocation endpoints each count their own).
58
+ - `oauthServer.listClients()` lists `{ id, name, scopes, createdAt, lastUsedAt }` of the apps the user approved, and `oauthServer.revokeGrant(id)` revokes one with its tokens (`{ ok: true }`, or `{ ok: false, error: { code: 'not-found' | 'signed-out' } }`; session only), for a page of the app's own. `oauthServer.authorize(params)` and `oauthServer.decide(fields, allow)` are what the consent page calls.
59
+ - Limits (`rateLimit.oauth`): `register` 20 per hour, `registerAll` unset (a ceiling on all addresses together), `document` 30 per 15 minutes (metadata documents read for an address), `token` 300 per 15 minutes (the token and the revocation endpoints each count their own).
60
60
 
61
61
  ### Bearer tokens
62
62
 
63
63
  - `tokens.create(proof, label, { scopes?, maxAge? })` answers `{ ok: true, token, id }`: the token, shown this once, for a device or an API client to send as `Authorization: Bearer <token>`. It is minted from a session only, never with another token. `'label'` for an empty label or one over 64 characters (control and direction characters are removed from it first), `'scope'` for an empty list or a scope the app did not declare, `'expiry'` for a `maxAge` (a string such as `'30d'`) that is not a positive duration. The token starts with `kat_`, so a secret scanner can match it. It expires after 90 days unless `maxAge` says otherwise, and `maxAge: null` is the only way to never expire.
64
- - `scopes: ['posts:read', 'posts:write']` in `authCore` declares what a token may be limited to, typed from then on. A token given `scopes` passes a gated route only when the route names one of them, `.get('/posts', handler, { scope: ['posts:read', 'posts:write'] })`, any one passing; a route naming none refuses it with a 403, so a route that forgets `scope:` stays closed to limited tokens, and `scope: false` lets every token through. `auth.gate({ scope })` sets the scope of its routes naming none, and `auth.guard({ scope })` does the same for pages. A token made without `scopes`, and a session, pass every scope: leaving `scopes` out is full access, so a token for a script or a device names the scopes it needs. `auth.scopes()` answers the request's token's scopes, null for a session or a token with every scope, and `auth.hasScope(scope)` checks one, for an app's own checks.
64
+ - `scopes: ['posts:read', 'posts:write']` in `authCore` declares what a token may be limited to, typed from then on. A token given `scopes` passes a gated route only when the route names one of them, `.get('/posts', handler, { scope: ['posts:read', 'posts:write'] })`, any one passing; a route naming none refuses it with a 403, so a route that forgets `scope:` stays closed to limited tokens, and `scope: false` lets every token through. `auth.gate({ scope })` sets the scope of its routes naming none, and `auth.guard({ scope })` does the same for pages. A token made without `scopes`, and a session, pass every scope: leaving `scopes` out is full access, so a token for a script or a device names the scopes it needs. `auth.tokens.scopes()` answers the request's token's scopes, null for a session or a token with every scope, and `auth.tokens.hasScope(scope)` checks one, for an app's own checks.
65
65
  - An expired token reads as no token at all, in `user()`, gates and `userFromToken`, and so does a banned user's.
66
66
  - `auth.issueToken(userId, label, { scopes, maxAge, token })` mints a token on the server, with no proof and no mail or event: for a flow the app gates itself, such as pairing a device whose owner signed in by provider longer than ten minutes ago, or a script. `token` adopts one the app handed out before, 32 to 4096 characters without whitespace and at least 10 distinct ones, such as a device's JWT, so its devices keep working once kayjs-auth reads them; it expires after 90 days like any other, so pass `maxAge: null` to keep a legacy device working for good. It answers `{ ok: true, token, id }`, or `not-found`, `banned`, `token` and what `tokens.create` refuses.
67
- - `tokens.list()`, `tokens.revoke(id)` and `twoFactor.enable(code)` need a session: through a bearer token they answer `[]`, `signed-out` and `signed-out`, so a leaked token cannot list or revoke its siblings nor turn on a second factor. So does everything asking for a `proof` or `reprove()` (the second factor and recovery codes, passkeys, password, address, account deletion): `signed-out`, whatever proof the token sends.
67
+ - `tokens.list()`, `tokens.revoke(id)` and `twoFactor.enable(code)` need a session: through a bearer token they answer `[]`, `signed-out` and `signed-out`, so a leaked token cannot list or revoke its siblings nor turn on a second factor. So does everything asking for a `proof` or `proof.renew()` (the second factor and recovery codes, passkeys, password, address, account deletion): `signed-out`, whatever proof the token sends.
68
68
  - `tokens.list()` lists `{ id, label, scopes, createdAt, lastUsedAt, expiresAt, expired }`, since only the token's digest is stored; `tokens.revoke(id)` revokes one, answering `{ ok }` (`not-found` for a token that is not theirs). A use is recorded at most every five minutes. A token ends with a password change, a reset and `signOutEverywhere`, each of which may answer a stolen device, so the devices sign in again after one.
69
69
  - A token reads as its user in `user()`, guards and gates. A websocket checks the token its first message carries with `auth.userFromToken(token)`, which `wsAuthStore(verify)` keeps per connection, `await store.get(ws)` checking the token again past 30 seconds and closing the socket once it is refused: the handshake for a client that cannot send a cookie or a header with its upgrade, such as a device's browser widget on another origin.
70
70
 
@@ -14,12 +14,12 @@ export const signIn = action(s.Object({ identifier: s.String({ maxLength: 254 })
14
14
  const result = await ctx.locals.auth.password.signIn(input, { redirect: ctx.url.searchParams.get('redirect') ?? '/' })
15
15
 
16
16
  if (!result.ok)
17
- return ctx.fail(400, { error: result.error.code })
17
+ return ctx.deny(400, { data: { error: result.error.code } })
18
18
 
19
19
  return ctx.redirect(result.redirect)
20
20
  })
21
21
 
22
- const failure = signIn.failed()
22
+ const failure = signIn.form.failed()
23
23
  ---
24
24
  form(action={signIn})
25
25
  input(name="identifier" autocomplete="username")
@@ -53,12 +53,12 @@ export const spend = action(s.Object({ token: s.String() }), async ({ token }, c
53
53
  const result = await ctx.locals.auth.magicLink.signIn(token)
54
54
 
55
55
  if (!result.ok)
56
- return ctx.fail(400, { error: result.error.code })
56
+ return ctx.deny(400, { data: { error: result.error.code } })
57
57
 
58
58
  return ctx.redirect(result.redirect)
59
59
  })
60
60
 
61
- const failure = spend.failed()
61
+ const failure = spend.form.failed()
62
62
  const token = ctx.query.token ?? ''
63
63
  ---
64
64
  form(action={spend})
@@ -72,21 +72,21 @@ if failure
72
72
 
73
73
  ### Passwords rules
74
74
 
75
- - A method that can fail answers `{ ok: true, ... }` or `{ ok: false, error }`, `error` the `ErrorShape` every result carries (`status`, `message`, `errors`, `data`) with the kind the page branches on as `error.code` (`'signed-out'`, `'limited'`, `'not-found'`...); a call that refused its input also puts `errors` beside it, with `error.code` `'invalid'`, holding codes such as `'too-short'` or `'taken'`, never messages: the page words them in its own language.
76
- - An action that redirects writes `return ctx.redirect(...)`, with the `return`, so `kay check` types `action.failed()` right.
75
+ - A method that can fail answers a `Result<Ok, Code>`: `{ ok: true, ... }` or `{ ok: false, error }`, `error` the `ErrorShape` every result carries (`status`, `message`, `errors`, `data`) with the kind the page branches on as `error.code` (`'signed-out'`, `'limited'`, `'not-found'`...). A failure is also a kay `Failure`, so an action returns the call as it is, `return ctx.locals.auth.password.signIn(input)`, and an island reads `{ ok: false, status, data: { code, message } }`. A call that refused its input also puts `errors` beside it, with `error.code` `'invalid'`, holding a code such as `'too-short'` or `'taken'` by field (the message itself for a profile field's own): the page words them in its own language.
76
+ - An action that redirects writes `return ctx.redirect(...)`, with the `return`, so `kay check` types `action.form.failed()` right.
77
77
  - `password.register({ email, password, username?, locale? })` answers `{ ok: true, user, signedIn: true }` once signed in, `{ ok: true, signedIn: false }` when the app requires verified addresses (`requireVerified`, on by default with a mailer), or `errors` by field (`email`: `'invalid'`, or `'taken'` with `requireVerified: false` or no mailer; `password`: `'too-short'` or `'too-long'`; `username`: `'length'`, `'characters'`, `'mixed-scripts'` or `'taken'`), or `error: 'limited'`, `'captcha'` or `'off'`. It mails a verification link when the app sends mail. `'mixed-scripts'` (and `'invalid'` for an address before its `@`) catches a name mixing Latin, Cyrillic and Greek letters only: a name wholly in Cyrillic that looks Latin passes, so show names next to something they cannot fake, such as an avatar.
78
78
  - Every way of signing in takes one trailing options object, `{ redirect, remember, captcha }`, with the ones it uses: `password.register(input, { redirect, remember, captcha })`, `password.signIn(input, { redirect, remember, captcha })`, `magicLink.request(email, { redirect, remember, captcha })`, `password.requestReset(email, { redirect, captcha })` and `passkeys.signIn(response, { redirect, remember })`. A `redirect` that is not a path of the site leads home. Registering or resetting with one keeps the page through the mailed link: the mail verifying the address, a resend included, and the reset lead on to it, the verification through the sign-in page when the browser is not signed in.
79
79
  - `password.signIn({ identifier, password }, { redirect?, remember?, captcha? })` takes an email, or a username when it holds no `@`. A wrong password and an unknown account answer alike, `'invalid'`, in the same time (a hash is checked either way, and the failed sign-in's event and the lockout notice are reported after the response). `'unverified'` comes once the password is right, under `email.requireVerified`, the default with a mailer: the page then offers `email.sendVerification()`, which this browser may call from then on. `'limited'` past the attempts allowed (see Limits): six tries from one client at one account in 15 minutes stop that client, and 60 from all clients stop the account for everyone, so a stranger's wrong passwords never keep the holder out from another address. Tries count against the account, its email and every spelling of its name alike, each counted before its password is checked, so parallel guesses do not slip past; a right password clears both counts.
80
80
  - `signUp: false` in `authCore` keeps visitors from making their own accounts, for a site whose users the app makes: `password.register` and `signInAsGuest` answer `'off'`, an OAuth sign-in with a provider account no user has linked comes back `?error=refused` as one `allow` refuses does, and a linked one still signs in. `features().signUp` says so; the prebuilt sign-in page drops its link to `password.register`, which answers 404.
81
- - `auth.admin.createUser({ email?, username?, password?, roles?, emailVerified?, locale? })` makes a user from server code, a script or an admin page, `signUp: false` or not: checked as `password.register` is, with its `errors` by field, `roles` given beside `defaultRoles` (a role the `roles` option does not declare throws), `onSignUp` run, no one signed in and no mail sent. The address counts as unverified unless `emailVerified: true`, so under `requireVerified` such a user cannot sign in with their password until they verify it. An address any account holds, an unverified one `password.register` would replace included, answers `taken`. It throws without an email or a username to sign in with, and answers `{ ok: true, user }`.
81
+ - `auth.admin.createUser({ email?, username?, password?, roles?, emailVerified?, locale? })` makes a user from server code, a script or an admin page, `signUp: false` or not: checked as `password.register` is, with its `errors` by field, `roles` given beside `defaultRoles` (a role the `roles` option does not declare throws), `afterSignUp` run, no one signed in and no mail sent. The address counts as unverified unless `emailVerified: true`, so under `requireVerified` such a user cannot sign in with their password until they verify it. An address any account holds, an unverified one `password.register` would replace included, answers `taken`. It throws without an email or a username to sign in with, and answers `{ ok: true, user }`.
82
82
  - `kay auth create-user <email or username> [--email <address>] [--username <name>] [--role <role>]... [--no-password] [--dry-run] [--quiet] [--format json]` makes a user from the terminal, in the project of the current directory with its `.env`, for the first user of a site with `signUp: false`. A name holding `@` is the email, taken as verified; the password is asked twice without echo, or read from the first line of a pipe (`echo "$PASSWORD" | kay auth create-user ada`); `--no-password` makes a user who signs in by provider, mailed link or passkey; a role the `roles` option does not declare, a taken name or a password the rules refuse exits 1 with the code. `--dry-run` checks the login's form and roles over an empty in-memory store (it creates no database and does not see a taken name) and asks no password; `--format json` prints the user made as `{ id, email, username, roles }`, or the failure document; `--quiet` prints only a failure. It finds `auth` through `auth()` in kay.config.ts, loads it and checks the login before asking the password, and needs `kay.config.ts` and the source in the current directory, so a built or compiled app alone cannot run it. Point it at the production database with the production environment.
83
83
  - Passwords are hashed with argon2id; a hash made weaker, or by bcrypt in an older app, is rehashed on the next sign-in.
84
84
  - The rules are browser-safe, so an island refuses before posting: `passwordProblem`, `emailProblem`, `usernameProblem`, `normalizeEmail` and `normalizeUsername` from `@kayjs/auth/rules`, the only entry exporting them (the root `@kayjs/auth` stopped repeating them in 1.90), with the defaults as constants for a `minlength` or `maxlength` of your own: `PASSWORD_MIN_LENGTH` and `PASSWORD_MAX_LENGTH`, `USERNAME_MIN_LENGTH` and `USERNAME_MAX_LENGTH`, and `PROFILE_MAX_LENGTH`, the longest a profile field holds unless it sets a `maxLength`. Passwords are 10 to 128 characters and usernames 2 to 32 unless the `rules` option says otherwise: `rules: { password: { min: 12, max: 64, check: p => /\d/.test(p) ? undefined : 'Add a digit.' }, username: { min: 3, max: 16 } }`. `check` returns a problem code or a message, which `password.register`, `password.reset`, `password.change` and `admin.createUser` answer as `errors.password` and the prebuilt pages show as it is. The server, the pages' hints and `minlength` follow the rules, and `features().rules` hands `{ password: { min, max }, username: { min, max } }` to a page or an island, which passes it, or the `rules` object itself, as the second argument: `passwordProblem(value, features.rules)`. A password longer than a ceiling lowered later can still sign in. Emails and usernames are stored NFKC-folded, emails lowercased, usernames compared without case, and a name or an email's local part mixing Latin with Cyrillic or Greek is refused, as is an email that is not one plain deliverable address (kay's `isEmail`, also the `email` format: no quote, comma, angle bracket, IP domain or line break, 254 characters at most), so an address that signs up is never refused as a recipient by kayjs-mail.
85
85
 
86
86
  ### Guests
87
87
 
88
- - `signInAsGuest({ captcha? })` signs the browser in as a new user with `guest: true`, no email and no password, so the app keeps their cart or their drafts before they sign up; `onSignUp` runs for them then. It is counted as registering is and CAPTCHA-checked as `'guest'`, answers the guest signed in already as is, and `{ ok: false, error: { code: 'signed-in' } }` to anyone else.
89
- - `password.register(...)` from a guest's browser makes the guest that account, keeping their id and so the app's data; it stays signed in even with `requireVerified`, and `onSignUp` does not run again. A guest registering an address another account holds stays a guest, `{ ok: true, signedIn: false }`, so a guest's browser can tell a held address from a free one, at the 6 registrations an hour `password.register` allows a client. An OAuth sign-in with a provider account no user has does the same; one a user has already signs in as that user, leaving the guest behind.
88
+ - `signInAsGuest({ captcha? })` signs the browser in as a new user with `guest: true`, no email and no password, so the app keeps their cart or their drafts before they sign up; `afterSignUp` runs for them then. It is counted as registering is and CAPTCHA-checked as `'guest'`, answers the guest signed in already as is, and `{ ok: false, error: { code: 'signed-in' } }` to anyone else.
89
+ - `password.register(...)` from a guest's browser makes the guest that account, keeping their id and so the app's data; it stays signed in even with `requireVerified`, and `afterSignUp` does not run again. A guest registering an address another account holds stays a guest, `{ ok: true, signedIn: false }`, so a guest's browser can tell a held address from a free one, at the 6 registrations an hour `password.register` allows a client. An OAuth sign-in with a provider account no user has does the same; one a user has already signs in as that user, leaving the guest behind.
90
90
  - A guest's way back in is their session: once it ends, the guest stays in the store (`admin.listUsers` shows `guest: true`) until `guests: { maxAge: '30d' }` (a Duration, 30 days by default) deletes a guest older than that who holds no session, calling `onDelete` as for any user. The store prunes at most once an hour, up to 10,000 guests a run, and a guest whose `onDelete` throws stays for the next run. A registered address never verified is deleted the same way after `email.unverifiedMaxAge` (30 days with `requireVerified`, off without it unless set), unless it has a session, a linked provider or a role beyond `defaultRoles`. A custom store lists them with `users.staleGuests(createdBefore, limit)` and `users.staleUnverified(createdBefore, limit)`; without those they are kept.
91
91
  - A guest (`signInAsGuest`) costs nothing to mint, so kayjs-auth does not name it to other libraries: kayjs-ai's limits keep counting a guest by address, a signed-in user by id.
92
92
 
@@ -110,9 +110,9 @@ if failure
110
110
  - `email.sendVerification()` mails the signed-in user a new link (awaited, a failing mailer failing the call) or, with nobody signed in, the account this browser last registered or proved the password of with an `'unverified'` answer, until it signs out (off the response's path; a browser that registered an address another account holds gets `{ ok: true }` too, mailing no one, counted alike); `'signed-out'` otherwise, as for a browser whose registered account a later registration replaced. `email.verify(token, password?)` verifies the address and never signs in: whoever opens the mail may be confirming an account a stranger registered with their address. It verifies in the browser signed in as the account, that registered it, or that proved its password with an `'unverified'` answer; elsewhere it takes the account's password, answering `{ ok: false, error: { code: 'confirm' } }` to ask for it, the link still usable (`'limited'` past the sign-in tries, which it shares). It answers the page `password.register` was given as `redirect` (else `/`) as where to go when this session is the user's, `signInPage?redirect=<that page>` otherwise.
111
111
  - A magic link or a reset that proves an address for the first time hands the account over clean: whatever was set on it before, perhaps by someone who registered the address first, is dropped (the password, the second factor and its recovery codes, passkeys, linked providers, bearer tokens), and every other session ends. A user who registered with a password and never verified the address loses that password this way, and sets another.
112
112
  - `email.change(proof, email)` mails a link to the new address (`errors.email` `'invalid'`, `'taken'` or `'unchanged'` otherwise); `email.confirmChange(token)` moves the account to it, ends its other sessions and bearer tokens and warns the address it left, when that one was verified.
113
- - `codes: 'code'` (or `'both'`, or per kind: `{ 'magic-link': 'both' }`) makes magic link and verification mails carry a six-digit code instead of the link, or beside it. A link opened on another device, or in a mail app's own browser, signs in there; a code is typed where it was asked for, and works in that browser's session only. `magicLink.request`, `password.register` and `email.sendVerification` park the code in the session, whether or not an account has the address. `email.pendingCode()` answers `{ type: 'sign-in' | 'verify', email }` or null, for the page to show the code field. `magicLink.signInWithCode(code)` signs in to where the link was asked for, verifying the address as a magic link does; `email.verifyCode(code)` verifies the address. Both answer `{ ok: true, redirect }`, or `'invalid'`, `'expired'` (no code waiting in this session, past its 10 minutes, or killed after five misses, which end that session's code only) or `'limited'` (`emailCode` 30 per client and `emailCodeAccount` 10 per address per 15 minutes). Spaces and dashes in the code are ignored. A code works once, even when two requests spend it together, and spending it spends the link of the same mail, and the other way round. Codes are stored as keyed digests, bound to the session's nonce. The mail's `code` field holds it, and templates get `code` beside `url`, either missing when the mail does not carry it.
114
- - A link works once, even when two requests spend it together: verification for 24 hours, a reset and an email change for one hour, a magic link for 15 minutes, a code for 10 minutes, unless `email.maxAge` sets them: `maxAge: { 'verify-email': '7d', 'magic-link': '30m' }` takes a `Duration` for each of `verify-email`, `reset-password`, `magic-link`, `change-email`, `sign-in-code` and `verify-code`. The built-in mails state the real figure in the reader's language (`7 days`, `2 heures`), and a template gets the seconds as `maxAge: { link?, code? }` beside `url` and `code`; `lifetime(seconds, locale)` words them. A new link of a kind voids the last one, a link to an address the account has since left opens nothing, and links are stored as digests only. A spent or unknown link answers `'invalid'`.
115
- - `requireVerified`, on by default once `email` is set, refuses password sign-in until the address is verified and signs no one in on registering. Registering then answers alike whether or not the address has an account, `{ ok: true, signedIn: false }` after the same work, and the holder of a taken address gets an `account-exists` mail, linking to `signInPage`, at most 3 an hour, instead of the verification link: neither the answer nor its time tells which addresses exist, but for a username (an unverified holder's own name is free with its address, so registering it with that name tells it is pending; the app's `onSignUp` and the `onDelete` of a replaced unverified account run after the response). `requireVerified: false` lets an unverified address sign in and registering sign in at once, and so brings back `'taken'` for a held address, which tells anyone which addresses have an account. A registration refused for a field leaves whatever account holds the address as it was. An address registered and never verified can be registered again, so no one squats an address they do not own; an account with a role beyond `defaultRoles` or a linked provider is never replaced this way, while an invited one holding only default roles counts as unclaimed: give it another role, or verify its address.
113
+ - `codes: 'code'` (or `'both'`, or per kind: `{ 'magic-link': 'both' }`) makes magic link and verification mails carry a six-digit code instead of the link, or beside it. A link opened on another device, or in a mail app's own browser, signs in there; a code is typed where it was asked for, and works in that browser's session only. `magicLink.request`, `password.register` and `email.sendVerification` park the code in the session, whether or not an account has the address. `email.pendingCode()` answers `{ type: 'sign-in' | 'verify', email }` or null, for the page to show the code field. `email.signInWithCode(code)` signs in to where the link was asked for, verifying the address as a magic link does; `email.verifyCode(code)` verifies the address. Both answer `{ ok: true, redirect }`, or `'invalid'`, `'expired'` (no code waiting in this session, past its 10 minutes, or killed after five misses, which end that session's code only) or `'limited'` (`emailCode` 30 per client and `emailCodeAccount` 10 per address per 15 minutes). Spaces and dashes in the code are ignored. A code works once, even when two requests spend it together, and spending it spends the link of the same mail, and the other way round. Codes are stored as keyed digests, bound to the session's nonce. The mail's `code` field holds it, and templates get `code` beside `url`, either missing when the mail does not carry it.
114
+ - A link works once, even when two requests spend it together: verification for 24 hours, a reset and an email change for one hour, a magic link for 15 minutes, a code for 10 minutes, unless `email.maxAge` sets them: `maxAge: { 'verify-email': '7d', 'magic-link': '30m' }` takes a `Duration` for each of `verify-email`, `reset-password`, `magic-link`, `change-email`, `sign-in-code` and `verify-code`. The built-in mails state the real figure in the reader's language (`7 days`, `2 heures`), and a template gets the durations as `ttl: { link?, code? }` (`maxAge` until 1.108) beside `url` and `code`; `lifetime(seconds, locale)` words them. A new link of a kind voids the last one, a link to an address the account has since left opens nothing, and links are stored as digests only. A spent or unknown link answers `'invalid'`.
115
+ - `requireVerified`, on by default once `email` is set, refuses password sign-in until the address is verified and signs no one in on registering. Registering then answers alike whether or not the address has an account, `{ ok: true, signedIn: false }` after the same work, and the holder of a taken address gets an `account-exists` mail, linking to `signInPage`, at most 3 an hour, instead of the verification link: neither the answer nor its time tells which addresses exist, but for a username (an unverified holder's own name is free with its address, so registering it with that name tells it is pending; the app's `afterSignUp` and the `onDelete` of a replaced unverified account run after the response). `requireVerified: false` lets an unverified address sign in and registering sign in at once, and so brings back `'taken'` for a held address, which tells anyone which addresses have an account. A registration refused for a field leaves whatever account holds the address as it was. An address registered and never verified can be registered again, so no one squats an address they do not own; an account with a role beyond `defaultRoles` or a linked provider is never replaced this way, while an invited one holding only default roles counts as unclaimed: give it another role, or verify its address.
116
116
 
117
117
  ### Security mails
118
118
 
@@ -4,7 +4,7 @@
4
4
 
5
5
  ### Guards and gates
6
6
 
7
- A `_guard.ts` default-exports kayjs-auth's guard, `authGuard({ redirect, require, scope })` from the package, which asks the request's `auth`, so imports no module (`auth.guard()` is the same):
7
+ A `_guard.ts` default-exports kayjs-auth's guard, `authGuard({ redirect, require, scope, fresh })` from the package, which asks the request's `auth`, so imports no module (`auth.guard()` is the same):
8
8
 
9
9
  ```ts
10
10
  import { authGuard } from '@kayjs/auth'
@@ -12,6 +12,14 @@ import { authGuard } from '@kayjs/auth'
12
12
  export default authGuard({ redirect: '/login', require: 'editor' })
13
13
  ```
14
14
 
15
+ ### Ask for the password or passkey again
16
+
17
+ `fresh: '10m'` on a guard, or on `requireUser({ fresh })`, asks that the user signed in or re-proved within that long, as before changing a password, an email or a payment method. A session signed in longer ago is refused with a 403 whose `data.code` is `'stale'`, and a bearer token, which has no session to prove with, always is. The page or the app's client then shows a proof form, calls `auth.proof.renew({ password })` (or `{ passkey }`, `{ code }`) and retries; `auth.proof.recent('10m')` tells whether to show it first. `proof.renew` resets the clock for every `fresh` of the session, and a `fresh` that is no duration fails where the guard is made.
18
+
19
+ ```ts
20
+ export default authGuard({ require: 'admin', fresh: '10m' })
21
+ ```
22
+
15
23
  Plain Elysia routes, such as an API, close behind a gate:
16
24
 
17
25
  ```ts