@kayjs/auth 0.0.0-stage → 1.104.1

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 (407) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +78 -2
  3. package/llms/admin-and-organizations.md +70 -0
  4. package/llms/admin-pages.md +30 -0
  5. package/llms/grouped-methods.md +106 -0
  6. package/llms/hardening-and-testing.md +108 -0
  7. package/llms/oauth-passkeys-two-factor.md +111 -0
  8. package/llms/oauth-providers.md +28 -0
  9. package/llms/oauth-server-and-tokens.md +76 -0
  10. package/llms/organization-pages.md +20 -0
  11. package/llms/passwords-and-mails.md +129 -0
  12. package/llms/sessions-and-guards.md +51 -0
  13. package/llms/setup.md +122 -0
  14. package/llms/signed-in-components.md +59 -0
  15. package/llms.txt +28 -0
  16. package/package.json +85 -4
  17. package/src/access.ts +31 -0
  18. package/src/account.ts +198 -0
  19. package/src/add.ts +70 -0
  20. package/src/address.ts +51 -0
  21. package/src/admin.ts +361 -0
  22. package/src/auditWording.ts +153 -0
  23. package/src/auth.ts +219 -0
  24. package/src/authorize/clients.ts +160 -0
  25. package/src/authorize/grants.ts +44 -0
  26. package/src/authorize/metadata.ts +72 -0
  27. package/src/authorize/register.ts +38 -0
  28. package/src/authorize/reply.ts +9 -0
  29. package/src/authorize/request.ts +253 -0
  30. package/src/authorize/resource.ts +34 -0
  31. package/src/authorize/revoke.ts +36 -0
  32. package/src/authorize/routes.ts +87 -0
  33. package/src/authorize/token.ts +213 -0
  34. package/src/authorize/uris.ts +76 -0
  35. package/src/bearer.ts +208 -0
  36. package/src/bearerHeader.ts +11 -0
  37. package/src/breached.ts +47 -0
  38. package/src/browser.ts +59 -0
  39. package/src/captcha.ts +196 -0
  40. package/src/cbor.ts +129 -0
  41. package/src/components/deletion-banner.kay +20 -0
  42. package/src/components/impersonation-banner.kay +21 -0
  43. package/src/components/signed-in.kay +8 -0
  44. package/src/components/signed-out.kay +6 -0
  45. package/src/components/user-menu.kay +21 -0
  46. package/src/context.ts +5 -0
  47. package/src/core.ts +308 -0
  48. package/src/createUserCommand.ts +217 -0
  49. package/src/decide.ts +45 -0
  50. package/src/deletion.ts +80 -0
  51. package/src/devTool.ts +104 -0
  52. package/src/device.ts +37 -0
  53. package/src/email.ts +594 -0
  54. package/src/erase.ts +237 -0
  55. package/src/events.ts +297 -0
  56. package/src/export.ts +101 -0
  57. package/src/failure.ts +63 -0
  58. package/src/forwardAuth.ts +55 -0
  59. package/src/forwardRoutes.ts +68 -0
  60. package/src/gate.ts +104 -0
  61. package/src/guard.ts +22 -0
  62. package/src/guards.ts +72 -0
  63. package/src/guesses.ts +99 -0
  64. package/src/index.ts +46 -0
  65. package/src/keys.ts +51 -0
  66. package/src/limits.ts +182 -0
  67. package/src/load.ts +18 -0
  68. package/src/locale.ts +15 -0
  69. package/src/log.ts +4 -0
  70. package/src/mail.ts +225 -0
  71. package/src/memoryStore.ts +599 -0
  72. package/src/messages/fr.ts +357 -0
  73. package/src/methods/account.ts +80 -0
  74. package/src/methods/admin.ts +63 -0
  75. package/src/methods/audit.ts +15 -0
  76. package/src/methods/email.ts +39 -0
  77. package/src/methods/magicLink.ts +32 -0
  78. package/src/methods/oauth.ts +35 -0
  79. package/src/methods/oauthServer.ts +31 -0
  80. package/src/methods/organizations.ts +96 -0
  81. package/src/methods/passkeys.ts +61 -0
  82. package/src/methods/password.ts +53 -0
  83. package/src/methods/sessions.ts +18 -0
  84. package/src/methods/tokens.ts +24 -0
  85. package/src/methods/twoFactor.ts +62 -0
  86. package/src/oauth/client.ts +324 -0
  87. package/src/oauth/flow.ts +350 -0
  88. package/src/oauth/index.ts +5 -0
  89. package/src/oauth/pkce.ts +20 -0
  90. package/src/oauth/providers.ts +490 -0
  91. package/src/oauth/refresher.ts +177 -0
  92. package/src/oauth/timeout.ts +2 -0
  93. package/src/oauth/types.ts +78 -0
  94. package/src/oauthTest.ts +112 -0
  95. package/src/organizations.ts +675 -0
  96. package/src/organizationsCore.ts +60 -0
  97. package/src/own.ts +313 -0
  98. package/src/pages/components/captcha.kay +16 -0
  99. package/src/pages/components/frame.kay +11 -0
  100. package/src/pages/components/message.kay +8 -0
  101. package/src/pages/components/panel.kay +12 -0
  102. package/src/pages/components/passkey-add.kay +48 -0
  103. package/src/pages/components/passkey-sign-in.kay +34 -0
  104. package/src/pages/components/passkey-two-factor.kay +33 -0
  105. package/src/pages/components/proof.kay +15 -0
  106. package/src/pages/components/provider-buttons.kay +25 -0
  107. package/src/pages/components/recovery-codes.kay +13 -0
  108. package/src/pages/components/separator.kay +4 -0
  109. package/src/pages/english.ts +82 -0
  110. package/src/pages/forms.ts +185 -0
  111. package/src/pages/index.ts +361 -0
  112. package/src/pages/organizationPage.ts +12 -0
  113. package/src/pages/routes/account/_guard.ts +15 -0
  114. package/src/pages/routes/account/_layout.kay +37 -0
  115. package/src/pages/routes/account/clients.kay +33 -0
  116. package/src/pages/routes/account/connections.kay +57 -0
  117. package/src/pages/routes/account/data.kay +106 -0
  118. package/src/pages/routes/account/index.kay +109 -0
  119. package/src/pages/routes/account/organizations/[org].kay +188 -0
  120. package/src/pages/routes/account/organizations/_guard.ts +8 -0
  121. package/src/pages/routes/account/organizations/index.kay +86 -0
  122. package/src/pages/routes/account/security.kay +164 -0
  123. package/src/pages/routes/account/sessions.kay +51 -0
  124. package/src/pages/routes/account/tokens.kay +84 -0
  125. package/src/pages/routes/admin/_layout.kay +43 -0
  126. package/src/pages/routes/admin/audit.kay +43 -0
  127. package/src/pages/routes/admin/index.kay +60 -0
  128. package/src/pages/routes/admin/users/[id].kay +181 -0
  129. package/src/pages/routes/confirm-email.kay +39 -0
  130. package/src/pages/routes/invitation.kay +104 -0
  131. package/src/pages/routes/magic-link.kay +42 -0
  132. package/src/pages/routes/oauth/authorize.kay +80 -0
  133. package/src/pages/routes/register.kay +83 -0
  134. package/src/pages/routes/reset-password.kay +73 -0
  135. package/src/pages/routes/sign-in.kay +128 -0
  136. package/src/pages/routes/two-factor.kay +61 -0
  137. package/src/pages/routes/verify-email.kay +83 -0
  138. package/src/passkeys.ts +373 -0
  139. package/src/password.ts +316 -0
  140. package/src/payloads.ts +22 -0
  141. package/src/pg.ts +705 -0
  142. package/src/profile.ts +43 -0
  143. package/src/proof.ts +110 -0
  144. package/src/prune.ts +123 -0
  145. package/src/rates.ts +82 -0
  146. package/src/request.ts +712 -0
  147. package/src/requiredTwoFactor.ts +71 -0
  148. package/src/requirement.ts +23 -0
  149. package/src/roles.ts +18 -0
  150. package/src/routes.ts +202 -0
  151. package/src/rules-check.ts +37 -0
  152. package/src/rules.ts +108 -0
  153. package/src/securityNotice.ts +45 -0
  154. package/src/sessions.ts +184 -0
  155. package/src/setup.ts +417 -0
  156. package/src/signInOptions.ts +9 -0
  157. package/src/state.ts +34 -0
  158. package/src/store.ts +410 -0
  159. package/src/storeHelpers.ts +23 -0
  160. package/src/test.ts +46 -0
  161. package/src/testCookies.ts +9 -0
  162. package/src/testHelpers.ts +58 -0
  163. package/src/testing.ts +113 -0
  164. package/src/text.ts +6 -0
  165. package/src/totp.ts +120 -0
  166. package/src/twoFactor.ts +200 -0
  167. package/src/types.ts +23 -0
  168. package/src/userData.ts +47 -0
  169. package/src/viewer-layout/_layout.kay +11 -0
  170. package/src/viewer.ts +116 -0
  171. package/src/wayIn.ts +40 -0
  172. package/src/webauthn.ts +375 -0
  173. package/src/wsAuth.ts +53 -0
  174. package/types/access.d.ts +12 -0
  175. package/types/access.d.ts.map +1 -0
  176. package/types/account.d.ts +32 -0
  177. package/types/account.d.ts.map +1 -0
  178. package/types/add.d.ts +29 -0
  179. package/types/add.d.ts.map +1 -0
  180. package/types/address.d.ts +2 -0
  181. package/types/address.d.ts.map +1 -0
  182. package/types/admin.d.ts +84 -0
  183. package/types/admin.d.ts.map +1 -0
  184. package/types/auditWording.d.ts +9 -0
  185. package/types/auditWording.d.ts.map +1 -0
  186. package/types/auth.d.ts +3475 -0
  187. package/types/auth.d.ts.map +1 -0
  188. package/types/authorize/clients.d.ts +15 -0
  189. package/types/authorize/clients.d.ts.map +1 -0
  190. package/types/authorize/grants.d.ts +15 -0
  191. package/types/authorize/grants.d.ts.map +1 -0
  192. package/types/authorize/metadata.d.ts +20 -0
  193. package/types/authorize/metadata.d.ts.map +1 -0
  194. package/types/authorize/register.d.ts +4 -0
  195. package/types/authorize/register.d.ts.map +1 -0
  196. package/types/authorize/reply.d.ts +6 -0
  197. package/types/authorize/reply.d.ts.map +1 -0
  198. package/types/authorize/request.d.ts +48 -0
  199. package/types/authorize/request.d.ts.map +1 -0
  200. package/types/authorize/resource.d.ts +4 -0
  201. package/types/authorize/resource.d.ts.map +1 -0
  202. package/types/authorize/revoke.d.ts +4 -0
  203. package/types/authorize/revoke.d.ts.map +1 -0
  204. package/types/authorize/routes.d.ts +5 -0
  205. package/types/authorize/routes.d.ts.map +1 -0
  206. package/types/authorize/token.d.ts +7 -0
  207. package/types/authorize/token.d.ts.map +1 -0
  208. package/types/authorize/uris.d.ts +5 -0
  209. package/types/authorize/uris.d.ts.map +1 -0
  210. package/types/bearer.d.ts +45 -0
  211. package/types/bearer.d.ts.map +1 -0
  212. package/types/bearerHeader.d.ts +3 -0
  213. package/types/bearerHeader.d.ts.map +1 -0
  214. package/types/breached.d.ts +5 -0
  215. package/types/breached.d.ts.map +1 -0
  216. package/types/browser.d.ts +11 -0
  217. package/types/browser.d.ts.map +1 -0
  218. package/types/captcha.d.ts +42 -0
  219. package/types/captcha.d.ts.map +1 -0
  220. package/types/cbor.d.ts +4 -0
  221. package/types/cbor.d.ts.map +1 -0
  222. package/types/context.d.ts +3 -0
  223. package/types/context.d.ts.map +1 -0
  224. package/types/core.d.ts +180 -0
  225. package/types/core.d.ts.map +1 -0
  226. package/types/createUserCommand.d.ts +11 -0
  227. package/types/createUserCommand.d.ts.map +1 -0
  228. package/types/decide.d.ts +12 -0
  229. package/types/decide.d.ts.map +1 -0
  230. package/types/deletion.d.ts +17 -0
  231. package/types/deletion.d.ts.map +1 -0
  232. package/types/devTool.d.ts +3 -0
  233. package/types/devTool.d.ts.map +1 -0
  234. package/types/device.d.ts +7 -0
  235. package/types/device.d.ts.map +1 -0
  236. package/types/email.d.ts +73 -0
  237. package/types/email.d.ts.map +1 -0
  238. package/types/erase.d.ts +31 -0
  239. package/types/erase.d.ts.map +1 -0
  240. package/types/events.d.ts +139 -0
  241. package/types/events.d.ts.map +1 -0
  242. package/types/export.d.ts +54 -0
  243. package/types/export.d.ts.map +1 -0
  244. package/types/failure.d.ts +19 -0
  245. package/types/failure.d.ts.map +1 -0
  246. package/types/forwardAuth.d.ts +12 -0
  247. package/types/forwardAuth.d.ts.map +1 -0
  248. package/types/forwardRoutes.d.ts +11 -0
  249. package/types/forwardRoutes.d.ts.map +1 -0
  250. package/types/gate.d.ts +31 -0
  251. package/types/gate.d.ts.map +1 -0
  252. package/types/guard.d.ts +10 -0
  253. package/types/guard.d.ts.map +1 -0
  254. package/types/guards.d.ts +37 -0
  255. package/types/guards.d.ts.map +1 -0
  256. package/types/guesses.d.ts +18 -0
  257. package/types/guesses.d.ts.map +1 -0
  258. package/types/index.d.ts +47 -0
  259. package/types/index.d.ts.map +1 -0
  260. package/types/keys.d.ts +11 -0
  261. package/types/keys.d.ts.map +1 -0
  262. package/types/limits.d.ts +133 -0
  263. package/types/limits.d.ts.map +1 -0
  264. package/types/load.d.ts +18 -0
  265. package/types/load.d.ts.map +1 -0
  266. package/types/locale.d.ts +4 -0
  267. package/types/locale.d.ts.map +1 -0
  268. package/types/log.d.ts +2 -0
  269. package/types/log.d.ts.map +1 -0
  270. package/types/mail.d.ts +51 -0
  271. package/types/mail.d.ts.map +1 -0
  272. package/types/memoryStore.d.ts +3 -0
  273. package/types/memoryStore.d.ts.map +1 -0
  274. package/types/messages/fr.d.ts +409 -0
  275. package/types/messages/fr.d.ts.map +1 -0
  276. package/types/methods/account.d.ts +24 -0
  277. package/types/methods/account.d.ts.map +1 -0
  278. package/types/methods/admin.d.ts +30 -0
  279. package/types/methods/admin.d.ts.map +1 -0
  280. package/types/methods/audit.d.ts +11 -0
  281. package/types/methods/audit.d.ts.map +1 -0
  282. package/types/methods/email.d.ts +14 -0
  283. package/types/methods/email.d.ts.map +1 -0
  284. package/types/methods/magicLink.d.ts +12 -0
  285. package/types/methods/magicLink.d.ts.map +1 -0
  286. package/types/methods/oauth.d.ts +16 -0
  287. package/types/methods/oauth.d.ts.map +1 -0
  288. package/types/methods/oauthServer.d.ts +13 -0
  289. package/types/methods/oauthServer.d.ts.map +1 -0
  290. package/types/methods/organizations.d.ts +30 -0
  291. package/types/methods/organizations.d.ts.map +1 -0
  292. package/types/methods/passkeys.d.ts +19 -0
  293. package/types/methods/passkeys.d.ts.map +1 -0
  294. package/types/methods/password.d.ts +17 -0
  295. package/types/methods/password.d.ts.map +1 -0
  296. package/types/methods/sessions.d.ts +9 -0
  297. package/types/methods/sessions.d.ts.map +1 -0
  298. package/types/methods/tokens.d.ts +11 -0
  299. package/types/methods/tokens.d.ts.map +1 -0
  300. package/types/methods/twoFactor.d.ts +20 -0
  301. package/types/methods/twoFactor.d.ts.map +1 -0
  302. package/types/oauth/client.d.ts +39 -0
  303. package/types/oauth/client.d.ts.map +1 -0
  304. package/types/oauth/flow.d.ts +38 -0
  305. package/types/oauth/flow.d.ts.map +1 -0
  306. package/types/oauth/index.d.ts +6 -0
  307. package/types/oauth/index.d.ts.map +1 -0
  308. package/types/oauth/pkce.d.ts +10 -0
  309. package/types/oauth/pkce.d.ts.map +1 -0
  310. package/types/oauth/providers.d.ts +100 -0
  311. package/types/oauth/providers.d.ts.map +1 -0
  312. package/types/oauth/refresher.d.ts +55 -0
  313. package/types/oauth/refresher.d.ts.map +1 -0
  314. package/types/oauth/timeout.d.ts +2 -0
  315. package/types/oauth/timeout.d.ts.map +1 -0
  316. package/types/oauth/types.d.ts +75 -0
  317. package/types/oauth/types.d.ts.map +1 -0
  318. package/types/oauthTest.d.ts +23 -0
  319. package/types/oauthTest.d.ts.map +1 -0
  320. package/types/organizations.d.ts +111 -0
  321. package/types/organizations.d.ts.map +1 -0
  322. package/types/organizationsCore.d.ts +29 -0
  323. package/types/organizationsCore.d.ts.map +1 -0
  324. package/types/own.d.ts +55 -0
  325. package/types/own.d.ts.map +1 -0
  326. package/types/pages/english.d.ts +80 -0
  327. package/types/pages/english.d.ts.map +1 -0
  328. package/types/pages/forms.d.ts +204 -0
  329. package/types/pages/forms.d.ts.map +1 -0
  330. package/types/pages/index.d.ts +166 -0
  331. package/types/pages/index.d.ts.map +1 -0
  332. package/types/pages/organizationPage.d.ts +7 -0
  333. package/types/pages/organizationPage.d.ts.map +1 -0
  334. package/types/pages/routes/account/_guard.d.ts +3 -0
  335. package/types/pages/routes/account/_guard.d.ts.map +1 -0
  336. package/types/pages/routes/account/organizations/_guard.d.ts +3 -0
  337. package/types/pages/routes/account/organizations/_guard.d.ts.map +1 -0
  338. package/types/passkeys.d.ts +61 -0
  339. package/types/passkeys.d.ts.map +1 -0
  340. package/types/password.d.ts +49 -0
  341. package/types/password.d.ts.map +1 -0
  342. package/types/payloads.d.ts +4 -0
  343. package/types/payloads.d.ts.map +1 -0
  344. package/types/pg.d.ts +303 -0
  345. package/types/pg.d.ts.map +1 -0
  346. package/types/profile.d.ts +11 -0
  347. package/types/profile.d.ts.map +1 -0
  348. package/types/proof.d.ts +33 -0
  349. package/types/proof.d.ts.map +1 -0
  350. package/types/prune.d.ts +5 -0
  351. package/types/prune.d.ts.map +1 -0
  352. package/types/rates.d.ts +15 -0
  353. package/types/rates.d.ts.map +1 -0
  354. package/types/request.d.ts +119 -0
  355. package/types/request.d.ts.map +1 -0
  356. package/types/requiredTwoFactor.d.ts +16 -0
  357. package/types/requiredTwoFactor.d.ts.map +1 -0
  358. package/types/requirement.d.ts +4 -0
  359. package/types/requirement.d.ts.map +1 -0
  360. package/types/roles.d.ts +9 -0
  361. package/types/roles.d.ts.map +1 -0
  362. package/types/routes.d.ts +31 -0
  363. package/types/routes.d.ts.map +1 -0
  364. package/types/rules-check.d.ts +3 -0
  365. package/types/rules-check.d.ts.map +1 -0
  366. package/types/rules.d.ts +38 -0
  367. package/types/rules.d.ts.map +1 -0
  368. package/types/securityNotice.d.ts +7 -0
  369. package/types/securityNotice.d.ts.map +1 -0
  370. package/types/sessions.d.ts +32 -0
  371. package/types/sessions.d.ts.map +1 -0
  372. package/types/setup.d.ts +18 -0
  373. package/types/setup.d.ts.map +1 -0
  374. package/types/signInOptions.d.ts +6 -0
  375. package/types/signInOptions.d.ts.map +1 -0
  376. package/types/state.d.ts +25 -0
  377. package/types/state.d.ts.map +1 -0
  378. package/types/store.d.ts +295 -0
  379. package/types/store.d.ts.map +1 -0
  380. package/types/storeHelpers.d.ts +4 -0
  381. package/types/storeHelpers.d.ts.map +1 -0
  382. package/types/test.d.ts +21 -0
  383. package/types/test.d.ts.map +1 -0
  384. package/types/testCookies.d.ts +3 -0
  385. package/types/testCookies.d.ts.map +1 -0
  386. package/types/testHelpers.d.ts +34 -0
  387. package/types/testHelpers.d.ts.map +1 -0
  388. package/types/testing.d.ts +12 -0
  389. package/types/testing.d.ts.map +1 -0
  390. package/types/text.d.ts +2 -0
  391. package/types/text.d.ts.map +1 -0
  392. package/types/totp.d.ts +12 -0
  393. package/types/totp.d.ts.map +1 -0
  394. package/types/twoFactor.d.ts +41 -0
  395. package/types/twoFactor.d.ts.map +1 -0
  396. package/types/types.d.ts +17 -0
  397. package/types/types.d.ts.map +1 -0
  398. package/types/userData.d.ts +9 -0
  399. package/types/userData.d.ts.map +1 -0
  400. package/types/viewer.d.ts +23 -0
  401. package/types/viewer.d.ts.map +1 -0
  402. package/types/wayIn.d.ts +12 -0
  403. package/types/wayIn.d.ts.map +1 -0
  404. package/types/webauthn.d.ts +111 -0
  405. package/types/webauthn.d.ts.map +1 -0
  406. package/types/wsAuth.d.ts +14 -0
  407. package/types/wsAuth.d.ts.map +1 -0
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Kaynooo
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,79 @@
1
- # Temporary Holding Version
1
+ # kayjs-auth
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Auth for kay apps, built on kay's sessions: OAuth and OpenID Connect sign-in (Discord, GitHub, Google, Apple, Microsoft, GitLab or any OpenID provider), passwords, mailed links (verification, reset, magic links, email change), TOTP two-factor with recovery codes, passkeys, a list of sessions to end one by one, bearer tokens, security mails, sign-in events with an optional audit log, admin tools (roles, bans, impersonation, deletion), organizations with their own roles and email invitations, a CAPTCHA hook and a breached-password check. It works in kay pages, actions and guards, and in a plain Elysia app, with its data in memory, in Postgres through pg-orm, or in a store of your own. It ships every sign-in and account page, styled with kayjs-ui, in English and French, which an app turns on with one line, then overrides page by page and text by text; or the app writes its own pages calling it.
4
+
5
+ ## Install
6
+
7
+ kayjs-auth is published to npm as `@kayjs/auth`, beside kay, and to the Forgejo registry at git.kaynooo.fr under the same name.
8
+
9
+ ```sh
10
+ bun add @kayjs/auth
11
+ ```
12
+
13
+ kay, Elysia and kayjs-ui (for the prebuilt pages) are peers, and `@kaynooo/pg-orm` too for the Postgres and SQLite store. It is released with kay, at kay's own version, and peers on kay's minor: install the one matching your kay, and move them together. An app on a `^0.x` range moves to kay's version by hand, as a caret on 0.x never reaches it.
14
+
15
+ ## Set up
16
+
17
+ ```ts
18
+ // src/auth.ts
19
+ import type { AuthSessionData } from '@kayjs/auth'
20
+ import { authCore, memoryAuth } from '@kayjs/auth'
21
+ import { session } from 'kay/server'
22
+
23
+ export const auth = authCore({
24
+ sessions: session<AuthSessionData>(),
25
+ // The session takes kay's KAY_SECRET, and kayjs-auth its key from the session's secret; pass `secret` (32+ characters) to keep a separate one.
26
+ // OAuth callbacks and mailed links are built on kay's `site` (kay.config.ts or SITE_URL); `url` gives another.
27
+ // In the process, for trying it out; `pgAuth(db)` from '@kayjs/auth/pg' keeps it in Postgres, or in SQLite on a pg-orm `Database` opened at a `sqlite://` URL, whose `tables` list `...authTables` and are migrated with the app's own.
28
+ store: memoryAuth(),
29
+ signInPage: '/login',
30
+ })
31
+ ```
32
+
33
+ kay.config.ts hands kay the plugin, imported only when the server builds the app, so the config never loads the app's database. kay uses it before the pages and types `ctx.locals.auth` from it, with no other line in the app:
34
+
35
+ ```ts
36
+ // kay.config.ts
37
+ import { auth } from '@kayjs/auth'
38
+ import { defineConfig } from 'kay/server'
39
+
40
+ export default defineConfig({
41
+ extensions: [auth({ module: './src/auth' })],
42
+ })
43
+ ```
44
+
45
+ `auth()` also serves the prebuilt pages below; an app keeping its own gives `pages: false`. A plain Elysia server gives `auth({ server: false })` and uses the plugin before the pages, `new Elysia().use(auth.plugin).use(await pages())`, and registers its types in kay's `Register`, as llms.txt shows.
46
+
47
+ ## A first page
48
+
49
+ Any page, action or guard reads the signed-in user from `ctx.locals.auth`:
50
+
51
+ ```kay
52
+ --- server
53
+ const user = await ctx.locals.auth.user()
54
+ ---
55
+ if user then signedIn
56
+ p Signed in as {signedIn.email}
57
+ else
58
+ a(href="/login") Sign in
59
+ ```
60
+
61
+ A `_guard.ts` keeps a folder of pages to signed-in users, sending the others to the sign-in page:
62
+
63
+ ```ts
64
+ import { auth } from '../../auth'
65
+
66
+ export default auth.guard({ redirect: '/login' })
67
+ ```
68
+
69
+ ## Prebuilt pages
70
+
71
+ `auth()` in kay.config.ts serves them. With `pages: true` in `authCore`, kayjs-auth sends users to `/auth/sign-in`, `/auth/account` and the rest. A file of the app's at one of those paths replaces that page, and a key under `auth` in its messages replaces that text.
72
+
73
+ ## Reference
74
+
75
+ The full reference, written for people and coding agents alike, is [llms.txt](llms.txt), which lists its topic files in [llms/](llms), with the sign-in action, OAuth providers, mailed links, two-factor and the gate for plain Elysia routes.
76
+
77
+ ## Contributing
78
+
79
+ This library is developed in [kay's repository](https://github.com/Kayno0o/kayjs), whose [CONTRIBUTING.md](https://github.com/Kayno0o/kayjs/blob/main/CONTRIBUTING.md) says how to work on it.
@@ -0,0 +1,70 @@
1
+ # kayjs-auth: Events, the audit log, admin and organizations
2
+
3
+ ## Common tasks
4
+
5
+ ### Organizations
6
+
7
+ Teams or workspaces users belong to, with roles of their own in each:
8
+
9
+ ```ts
10
+ authCore({
11
+ // ...
12
+ organizations: {
13
+ roles: { owner: ['admin'], admin: ['member'], member: [] },
14
+ owner: 'owner',
15
+ manage: 'admin',
16
+ defaultRoles: ['member'],
17
+ },
18
+ })
19
+ ```
20
+
21
+ The prebuilt pages have a screen for the members, roles and invitations, and the page an invitation mail opens, and take `invitationPage` off your hands: see [the organization pages](organization-pages.md).
22
+
23
+ ## Reference
24
+
25
+ ### Events and the audit log
26
+
27
+ `onEvent(info)` hears every security mail's event above, mailed or not, and these, never mailed. `info` is one object, `{ event, user, context, ...fields }`: `context` is an `AuthHookContext`, kay's `HookContext` (`request`, `ip`, `userAgent`, `userId`, `locale`) and the `actor` (the user who acted, an admin or a manager, else `null`), and the fields are the event's own, as below. Switch on `info.event` and the fields are typed. A failed password sign-in is reported after the response, so a hook or an audit read right after the call may not see it yet.
28
+
29
+ - `signed-in`, `method` how: `password`, `register`, `reset-password`, `magic-link`, `email-code`, `oauth` with the `provider`, `passkey`, `guest`, or `app` for `auth.signIn`. A sign-in through the second factor is heard once it is answered, with its first factor.
30
+ - `signed-out`.
31
+ - `sign-in-failed`, for an account that exists only: `method` `password`, `two-factor`, `passkey` or `oauth`.
32
+ - An admin's doing, `actor` the admin: `role-granted` and `role-revoked`, `role`; `banned`, `reason` when given; `unbanned`; `impersonation-started` (also mailed to the user, as the security events are) and `impersonation-ended`, `expired: true` when the 30 minutes ran out (the audit `detail` is `expired`).
33
+ - In an organization, `organizationId`: `organization-created` and `organization-deleted`; `member-joined` and `member-roles-changed`, with the `roles` given; `member-left`; `member-removed`. A manager's doing names them as `actor`.
34
+ - `oauth-client-approved` (first approval of an app, or more scopes) and `oauth-client-revoked`, `client` the app's name.
35
+ - `account-deletion-scheduled`, `deleteAt` (a `Date`): `account.delete` marked the account pending under `account.deleteAfter`; `account-deleted` follows at the real deletion, and `account-deletion-cancelled` (mailed) if the user cancels.
36
+
37
+ The audit log keeps the fields packed in a string as an entry's `detail` (`oauth:<provider>`, `<orgId> <role> <role>`).
38
+
39
+ `actor` is the user who acted when it was not the one it happened to, such as an admin; while an admin acts as a user, every event names the admin as `actor`, in the audit log too (an organization created or a member removed, a sign-out everywhere).
40
+
41
+ With `audit: true`, or `{ maxAge }` as a string such as `'90d'` (a year by default), the same events are kept in the store's audit log too, pruned of older ones at most hourly. `audit.list({ before, limit })` gives the signed-in user their own, newest first (entries of one millisecond newest written first, as their ids are time-ordered): `{ id, userId, event, detail, ip, userAgent, actorId, at }`, `ip` cut to its network (the /24 of an IPv4 address, the /48 of an IPv6 one) unless `audit: { ip: 'full' }`; entries written before 1.55 keep the whole address. Pass the last entry of a page as `before` for the next one, which skips and repeats none, as is or after a JSON hop; a bare `Date` (or its ISO text) excludes that whole millisecond, and a cursor that is no date answers an empty page. The log is kept past a user's deletion, so it still says what happened, but nothing in it leads back to them: their entries take a new random `userId` and lose the address, browser and detail (which can hold an address or a passkey's name), and the entries they acted in, as an admin or a manager, take it as `actorId` and lose the address and browser. A failure to strip the log fails the erase (`account.delete`, `admin.deleteUser`), the account still there to delete again. Writing an entry never fails what it records: a failure is logged.
42
+
43
+ `describeAuditEntry(entry, { locale, wording })` words an entry for a person, its detail included (`Role editor granted`, `Signed in with discord`), in English or French as the pages are, English for another locale. `wording` takes the app's own phrase for any event, a string or a function of the detail, over kayjs-auth's; `auditWording` holds kayjs-auth's by language.
44
+
45
+ ### Admin
46
+
47
+ The prebuilt pages for the methods below are in [the admin pages](admin-pages.md).
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.
50
+
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.
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
+ - `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
+ - `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.
58
+
59
+ ### Organization rules
60
+
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
+ - `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
+ - `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.
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
+ - `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
+ - 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`.
@@ -0,0 +1,30 @@
1
+ # kayjs-auth: The prebuilt admin pages
2
+
3
+ ## Common tasks
4
+
5
+ ### Manage users from the browser
6
+
7
+ With `admin: 'admin'` set (or any requirement a guard takes), the prebuilt pages serve an admin area under the pages' prefix, `/auth/admin` by default, with no other declaration:
8
+
9
+ ```ts
10
+ // kay.config.ts
11
+ extensions: [auth({ admin: 'admin', roles: { admin: ['editor'], editor: [] }, audit: true })]
12
+ ```
13
+
14
+ - `/auth/admin`: the users, newest first, 25 a page, with a search over part of an email or a username or a whole id (`?q=`, `?page=`).
15
+ - `/auth/admin/users/<id>`: one user, with their roles (give one of the declared `roles`, so declare them to grant from the page; take one back), a ban with a reason and an optional last day (the close of that day, UTC), the lift of a ban, `Act as this user`, and the deletion behind a ticked box; the last three are left out for another admin, whom they refuse. With `audit` on, their last 20 audit entries show too.
16
+ - `/auth/admin/audit`: everyone's audit log (its tab shows with `audit` on, the page says it is off otherwise), 50 entries a page, an `Older entries` link paging by the last entry.
17
+ - Each page is as open as the method behind it: a visitor is sent to sign in, anyone else (a member, an admin already acting as a user, who still sees the banner and the way back, a bearer token) gets a 403, and a site naming no `admin` gets a 404. The actions answer the same through the methods, so a post that skips the page changes nothing.
18
+ - A change asks for a sign-in under ten minutes old, as the methods do: the page says so with a `Sign in again` button that comes back to the user.
19
+ - The pages follow the prefix, the base path and the locale of the other prebuilt pages (`/fr/auth/admin`), and `pages: false` leaves them out with the rest.
20
+
21
+ ### Show who an admin acts as
22
+
23
+ `admin.impersonate` signs the admin in as the user, and a banner says so on every prebuilt page and, with `viewer: true`, on every page of the app: `You are acting as ada@example.com.` with a `Back to my account` button that posts to `<prefix>/stop-impersonating` (`redirect` for where to go, a path of the site) and lands on the admin pages. Put `ImpersonationBanner` in a layout of your own where `viewer: true` does not reach ([the signed-in user in templates](signed-in-components.md#show-the-impersonation-banner)).
24
+
25
+ ## Reference
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.
29
+ - The words are `auth.admin.*` and `auth.impersonation.*` in the app's catalogs; English and French ship.
30
+ - The organization methods in [admin and organizations](admin-and-organizations.md) have their pages in [the organization pages](organization-pages.md).
@@ -0,0 +1,106 @@
1
+ # kayjs-auth: Grouped methods
2
+
3
+ ## Common tasks
4
+
5
+ ### Call a feature's methods
6
+
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
+
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`).
10
+
11
+ ### Move off the flat names
12
+
13
+ The flat names `auth` had before 1.82 (`auth.listUsers()`, `auth.signInWithPassword(input)`) are gone since 1.86, and those before 1.87 (`auth.deleteAccount(proof)`, `auth.createUser(input)`) since 1.91, along with their lints: call the grouped method the tables give, `auth.admin.createUser(input)` on the `authCore` result. An app still on them runs `kay upgrade` on 1.85 or 1.90 first, which renames the calls.
14
+
15
+ ## Reference
16
+
17
+ ### The groups
18
+
19
+ | Group | Method | Flat name (gone in 1.86) |
20
+ | --- | --- | --- |
21
+ | `password` | `register` | `register` |
22
+ | `password` | `signIn` | `signInWithPassword` |
23
+ | `password` | `requestReset` | `requestPasswordReset` |
24
+ | `password` | `reset` | `resetPassword` |
25
+ | `password` | `change` | `changePassword` |
26
+ | `email` | `sendVerification` | `sendVerification` |
27
+ | `email` | `verify` | `verifyEmail` |
28
+ | `email` | `verifyCode` | `verifyEmailCode` |
29
+ | `email` | `pendingCode` | `emailCodePending` |
30
+ | `email` | `change` | `changeEmail` |
31
+ | `email` | `confirmChange` | `confirmEmailChange` |
32
+ | `magicLink` | `request` | `requestMagicLink` |
33
+ | `magicLink` | `signIn` | `signInWithMagicLink` |
34
+ | `magicLink` | `signInWithCode` | `signInWithEmailCode` |
35
+ | `twoFactor` | `pending` | `twoFactorPending` |
36
+ | `twoFactor` | `verify` | `verifyTwoFactor` |
37
+ | `twoFactor` | `setUp` | `setUpTwoFactor` |
38
+ | `twoFactor` | `enable` | `enableTwoFactor` |
39
+ | `twoFactor` | `disable` | `disableTwoFactor` |
40
+ | `twoFactor` | `regenerateRecoveryCodes` | `regenerateRecoveryCodes` |
41
+ | `twoFactor` | `recoveryCodesLeft` | `recoveryCodesLeft` |
42
+ | `twoFactor` | `passkeyOptions` | `twoFactorPasskeyOptions` |
43
+ | `twoFactor` | `verifyPasskey` | `verifyTwoFactorPasskey` |
44
+ | `passkeys` | `registrationOptions` | `passkeyRegistrationOptions` |
45
+ | `passkeys` | `register` | `registerPasskey` |
46
+ | `passkeys` | `list` | `listPasskeys` |
47
+ | `passkeys` | `rename` | `updatePasskeyName` |
48
+ | `passkeys` | `revoke` | `revokePasskey` |
49
+ | `passkeys` | `signInOptions` | `passkeySignInOptions` |
50
+ | `passkeys` | `signIn` | `signInWithPasskey` |
51
+ | `passkeys` | `proofOptions` | `passkeyProofOptions` |
52
+ | `sessions` | `list` | `listSessions` |
53
+ | `sessions` | `revoke` | `revokeSession` |
54
+ | `tokens` | `create` | `createToken` |
55
+ | `tokens` | `list` | `listTokens` |
56
+ | `tokens` | `revoke` | `revokeBearerToken` |
57
+ | `oauthServer` | `authorize` | `oauthAuthorize` |
58
+ | `oauthServer` | `decide` | `oauthDecide` |
59
+ | `oauthServer` | `clients` | `listOAuthClients` |
60
+ | `oauthServer` | `revokeGrant` | `revokeOAuthGrant` |
61
+ | `admin` | `listUsers` | `listUsers` |
62
+ | `admin` | `getUser` | `getUser` |
63
+ | `admin` | `roles` | `adminRoles` |
64
+ | `admin` | `grantRole` | `grantRole` |
65
+ | `admin` | `revokeRole` | `revokeRole` |
66
+ | `admin` | `ban` | `banUser` |
67
+ | `admin` | `unban` | `unbanUser` |
68
+ | `admin` | `deleteUser` | `deleteUser` |
69
+ | `admin` | `auditLog` | `listAdminAuditLog` |
70
+ | `admin` | `impersonate` | `impersonate` |
71
+ | `admin` | `stopImpersonating` | `stopImpersonating` |
72
+ | `organizations` | `create` | `createOrganization` |
73
+ | `organizations` | `list` | `listOrganizations` |
74
+ | `organizations` | `get` | `getOrganization` |
75
+ | `organizations` | `isMember` | `isMember` |
76
+ | `organizations` | `update` | `updateOrganization` |
77
+ | `organizations` | `delete` | `deleteOrganization` |
78
+ | `organizations` | `members` | `listMembers` |
79
+ | `organizations` | `setMemberRoles` | `setMemberRoles` |
80
+ | `organizations` | `removeMember` | `deleteMember` |
81
+ | `organizations` | `leave` | `leaveOrganization` |
82
+ | `organizations` | `invite` | `invite` |
83
+ | `organizations` | `invitations` | `listInvitations` |
84
+ | `organizations` | `revokeInvitation` | `revokeInvitation` |
85
+ | `organizations` | `myInvitations` | `listMyInvitations` |
86
+ | `organizations` | `invitation` | `getInvitation` |
87
+ | `organizations` | `acceptInvitation` | `acceptInvitation` |
88
+ | `organizations` | `rejectInvitation` | `rejectInvitation` |
89
+
90
+ ### The groups added in 1.87
91
+
92
+ | Group | Method | Flat name (gone in 1.91) |
93
+ | --- | --- | --- |
94
+ | `account` | `changeUsername` | `changeUsername` |
95
+ | `account` | `updateLocale` | `updateLocale` |
96
+ | `account` | `delete` | `deleteAccount` |
97
+ | `account` | `deletionImpact` | `deletionImpact` |
98
+ | `account` | `profile` | `profile` |
99
+ | `account` | `saveProfile` | `saveProfile` |
100
+ | `account` | `export` | `exportData` |
101
+ | `oauth` | `link` | `linkProvider` |
102
+ | `oauth` | `unlink` | `unlink` |
103
+ | `oauth` | `identities` | `listIdentities` |
104
+ | `oauth` | `providerToken` | `providerToken` |
105
+ | `audit` | `list` | `listAuditLog` |
106
+ | `admin` (on the `authCore` result) | `createUser` | `createUser` |
@@ -0,0 +1,108 @@
1
+ # kayjs-auth: Bots, breached passwords, limits, stores, testing and the dev tool
2
+
3
+ ## Common tasks
4
+
5
+ ### Bots and breached passwords
6
+
7
+ A CAPTCHA and the breached-password check are options of `authCore`:
8
+
9
+ ```ts
10
+ import { authCore, turnstile, turnstileWidget } from '@kayjs/auth'
11
+
12
+ authCore({
13
+ // ...
14
+ captcha: { verify: turnstile(process.env.TURNSTILE_SECRET!), widget: turnstileWidget(process.env.TURNSTILE_SITE_KEY!), on: { 'sign-in': 3, 'reset': 'always' } },
15
+ breachedPasswords: true, // the default in production
16
+ })
17
+ ```
18
+
19
+ ### Testing
20
+
21
+ kay's `testSite` builds the site as `pages()` does, the plugin mounted by the extension before the pages, so a test signs in through the site's own forms and stays signed in. An app mounting the plugin by hand passes it as `testSite({ use: [auth.plugin] })`.
22
+
23
+ ```ts
24
+ import { testSite } from 'kay/test'
25
+ import { signIn } from '../src/routes/login.kay'
26
+
27
+ const site = await testSite()
28
+ const page = await site.submit(signIn, { identifier: 'ada@example.com', password: 'correct horse battery' }, { from: '/login' })
29
+ ```
30
+
31
+ ### Sign a test site in
32
+
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
+
35
+ ```ts
36
+ import { authTest } from '@kayjs/auth/test'
37
+
38
+ const as = authTest(site)
39
+
40
+ await as.signInAs({ email: 'ada@example.com', username: 'Ada', emailVerified: true })
41
+ expect((await site.visit('/auth/account')).status).toBe(200)
42
+ as.signOut()
43
+ expect((await site.visit('/auth/account')).url).toBe('/auth/sign-in?redirect=%2Fauth%2Faccount')
44
+ ```
45
+
46
+ `signInAs` makes the member when no user has that email or username (`admin.createUser`'s fields: `email`, `username`, `password`, `roles`, `emailVerified`, `locale`, and `data` for the fields of the app's `user` schema), signs an existing one in as they are (it throws when the email, username or data given differ from theirs, or a role given is one they lack), sets the session cookie in the site's cookie jar and returns the user. A second call switches member and `signOut()` makes the site anonymous again, its other cookies kept. It goes through the store, so it works on `pgAuth` as on `memoryAuth`.
47
+
48
+ `await as.enrollTotp(user.id)` turns two-factor on for a member as the app would, so a password sign-in asks for a code: it answers `{ secret, code(offset?), recoveryCodes }`, the code of the current step and the recovery codes usable at the next sign-in. It throws for a missing member or one who has two-factor already, so a test never writes the user row's `totpEnabledAt`.
49
+
50
+ `await as.oauth.stub('discord', { id, email, username?, displayName?, avatar? })` makes a configured provider answer with that account, with no request to it and no `fetch` spy, until the function it returns is called (`stub` is async, so await it); `{ error: 'access_denied' | 'invalid_grant' | 'server_error' }` simulates a refused consent, a rejected code or a provider down. `await as.oauth.signIn('discord', { redirect? })` leaves for the provider and comes back through the site (a `testSite()`, or any `{ cookies }` object, which the plugin is then driven for), answering the callback's response: a redirect to where the sign-in goes, or to the sign-in page with `?error=cancelled|oauth|unavailable`. It throws without a stub. A provider found by OpenID discovery is not asked for its endpoints.
51
+
52
+ An app with a `src/auth.ts` module calls the same on its `auth` with the site first: `await auth.signInAs(site, { email })`, `auth.signOut(site)`, `await auth.sessionCookie(userId)`, `await auth.enrollTotp(userId)`; `auth.test(site)` names the site once, as `authTest` does.
53
+
54
+ ## Reference
55
+
56
+ ### Bots and breached passwords rules
57
+
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.
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
+ - 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
+ - `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
+ - `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
+ - 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()`.
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
+
69
+ ### Limits
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:
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.
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.
77
+ - `organization` 10 per account per day, for `organizations.create`.
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.
80
+
81
+ ### Stores
82
+
83
+ - `memoryAuth()` keeps everything in the process: for tests, and for trying kayjs-auth before a database is wired.
84
+ - `pgAuth(db)` from `@kayjs/auth/pg` keeps it in Postgres through pg-orm, or in a SQLite file when the `Database` opens a `sqlite://` URL (`new Database({ url: 'sqlite://data/auth.db', tables: [...authTables] })`, opened in WAL mode with foreign keys on, waiting up to 5 seconds on another process writing), once `authTables` are among its tables, all named `kay_*`: `users`, `identities`, `tokens`, `recovery_codes`, `bearer_tokens` (with `oauth_client`, `oauth_family` and `oauth_resource` columns), `oauth_clients`, `oauth_grants`, `oauth_codes`, `oauth_refresh_tokens`, `auth_sessions`, `passkeys`, `audits`, `organizations`, `members`, `invitations` and `attempts`. What belongs to a user, the audit log and their invitations aside, is deleted with them, and members and invitations with their organization.
85
+ - Any object with the `AuthStore` methods is a store: `users` (keeping `UserRecord.data`, the app's JSON from the `user` option, as given; `pgAuth` adds its `data` column on `db.sync()`), `identities`, `tokens`, `recoveryCodes`, `bearerTokens`, `sessions` and `passkeys`, plus `oauth` (`clients`, `grants`, `codes`, `refresh`) for the OAuth server, `audit` for the `audit` option and `organizations`, `members` and `invitations` for the `organizations` option, each method sync or async. One verb per operation: `create` adds a row, `delete` removes one (answering whether there was a row), `erase` removes what a user has in a table (`deleteForUser` before 1.88) and answers a count, `upsert` creates or replaces, `consume` deletes a row and answers it, or whether it had it, once only, and `use` marks an OAuth code or refresh token spent and keeps it, to tell a reuse. What must hold is written on each method: emails are looked up exactly, usernames without case; a mailed token, a recovery code and a TOTP step are spent once even by two requests together; deleting a user deletes what kayjs-auth keeps for them; `audit.list` orders by `at` then `id`, both descending, and takes `before` as a `Date` or an entry's `{ at, id }`; `audit.erase` strips a user from the log; `users.list` pages newest first and searches emails and usernames without case. `rates`, kay's `RateStore` with `peek` and `reset` (type `AuthRates`), is where a store counts attempts in its own database; a store without it counts them in the app's `store.rates`, or the process's memory. Optional methods save queries and a store without them still works: `users.getMany`, `organizations.getMany`, `identities.deleteForUser`, `bearerTokens.deleteForUser`, `bearerTokens.findByDigestWithUser` (a token and its user in one read) and `prune(limits)`, which kayjs-auth starts at most once an hour from a request without making it wait, and the built-in stores use to delete expired links, codes, invitations and sessions (past their lifetime unseen, or the session plugin's `absoluteMaxAge` old), ended attempt windows, and bearer tokens expired for more than 30 days. A store without `prune` keeps those rows, with the IP and browser of a session and the address of a link, until the app deletes them. Attempt counts key an address by a keyed digest, never the address itself.
86
+ - A store over an app's own tables: `users.create(user)` answers the user as stored when the store picks its own id, such as a serial column's, `user` whole with only its `id` changed, and kayjs-auth goes on with it (ids are strings, so the store converts); answering nothing keeps the id kayjs-auth picked. TOTP secrets are stored sealed with the auth `secret`: a store whose rows hold plain base32 secrets from before seals each on read with `sealTotpSecret(secret, userId, plain)`, from `@kayjs/auth`, `secret` being the value `authCore` takes, a list included. A plain base32 value matches `/^[A-Z2-7]+=*$/`, which a sealed one in practice never does, and what kayjs-auth writes afterwards is sealed already.
87
+
88
+ ### Testing rules
89
+
90
+ The prebuilt pages' actions import as `@kayjs/auth/pages/<page>.kay`, such as `import { password } from '@kayjs/auth/pages/sign-in.kay'` and `import { changeUsername } from '@kayjs/auth/pages/account/index.kay'`, and a test submits them as it does its own; the sign-out button, a post to `/auth/sign-out`, a test makes with `site.fetch('/auth/sign-out', { method: 'POST' })`. `kay check` types such a module's named exports as the file declares them, so the test imports an action without a cast (`examples/noticeboard/tests/pages.ts` re-exports them).
91
+
92
+ A test needing a signed-in request without a form takes `await auth.sessionCookie(userId)`, the `Cookie` header of a new session signed in as that user, against the app's own auth, to send by hand: `app.handle(new Request(url, { headers: { cookie } }))`. It mints the cookie a request with no `x-forwarded-proto` reads, `__Host-kay_session` in production when kay.config.ts `site` is https, else `kay_session` (a request over https reads `__Host-kay_session` alone). `{ secure: true }` asks for `__Host-kay_session` and `{ secure: false }` for `kay_session`, as for a request sent over https in a test, or a site with no `site` behind a proxy sending `x-forwarded-proto: https`. It may be minted before the first `testSite()`: a cookie holding its session reads as signed in under the store the site brings.
93
+
94
+ Each `testSite` keeps its own cookies, one browser each. `memoryAuth()` keeps each test's users apart, and a mailer pushing into an array hands the test the links it would have mailed, `url` included; with kayjs-mail, its `outbox` holds what was sent.
95
+
96
+ ### Dev tool
97
+
98
+ - Under `kay dev`, the dev tool every dev page carries has an Auth tab, brought by `auth()` with nothing to add in the app: the session's user (id, email, roles, how they signed in, password, two-factor) with a Sign out button that posts to the pages' `/auth/sign-out`. It reads `/_kay/auth`, a route mounted under `kay dev` alone.
99
+
100
+ ### Errors
101
+
102
+ Each class extends `KayError` (from `kay/library`): `code` is the name `kay explain <code>` documents, `kind` tells apart what a code covers, `status` is the HTTP status it stands for, and `cause` the error underneath. The message of the class below opens with `kayjs-auth: `, and an option the config refuses at boot opens with `kay: `.
103
+
104
+ | Class | `code` | `kind` | Thrown for |
105
+ | --- | --- | --- | --- |
106
+ | `OAuthExchangeError` | `oauth-exchange` | `oauth-exchange` | The provider rejected the token exchange, the ID token or the user fetch, or was down. `status` is the provider's, or 400 for a bad code and 502 for an outage, so an action can answer a client's bad code with a 4xx. |
107
+
108
+ What a visitor did wrong is a result, `{ ok: false, error }` or `{ ok: false, errors }` by field; a wrong setup (a missing `auth` in the context, an option the config refuses) throws an error opening with `kayjs-auth: ` or `kay: `.
@@ -0,0 +1,111 @@
1
+ # kayjs-auth: OAuth sign-in, two-factor, passkeys, re-proof and the account
2
+
3
+ ## Common tasks
4
+
5
+ ### OAuth
6
+
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
+
9
+ ```kay
10
+ a(href="/auth/discord?redirect=/account" data-no-prefetch) Sign in with Discord
11
+ ```
12
+
13
+ A link to an OAuth route changes the session on GET: give it `data-no-prefetch`, so a hover starts nothing.
14
+
15
+ ### Passkeys
16
+
17
+ Two actions and an island add a passkey to the signed-in user:
18
+
19
+ ```ts
20
+ import { passkeyAttestation } from '@kayjs/auth'
21
+
22
+ // The app's actions, `response` typed as `passkeys.register` takes it and refused before the handler when a part is missing
23
+ export const passkeyOptions = action(proofSchema, async (proof, ctx) => ctx.locals.auth.passkeys.registrationOptions(proof))
24
+ export const addPasskey = action(s.Object({ response: passkeyAttestation, name: s.Optional(s.String()) }), async ({ response, name }, ctx) => ctx.locals.auth.passkeys.register(response, name))
25
+ ```
26
+
27
+ ```ts
28
+ // In an island on the account page
29
+ import { makePasskey, passkeyFailure } from '@kayjs/auth/browser'
30
+
31
+ try {
32
+ const { options } = await passkeyOptions({ password })
33
+ const response = await makePasskey(options)
34
+
35
+ if (response)
36
+ await addPasskey({ response, name })
37
+ }
38
+ catch (caught) {
39
+ error.set(passkeyFailure(caught, { proof: 'Wrong password' }, 'That did not work'))
40
+ }
41
+ ```
42
+
43
+ ## Reference
44
+
45
+ ### OAuth rules
46
+
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
+ - 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.
51
+ - `allow(profile)` is asked before any user is touched; false refuses, as an allowlist of provider ids does.
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
+ - 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.
55
+
56
+ ### Two-factor
57
+
58
+ - `twoFactor.setUp(proof)` answers `setup: { secret, uri }`: the base32 secret to type in and its `otpauth://` URI, to draw with kayjs-ui's `QrCode`. `twoFactor.enable(code)` turns the factor on once the authenticator gives a right code, and answers ten recovery codes, `abcde-fghij-klmno`, to show this once. Its tries count as a sign-in code's do, `'limited'` past them.
59
+ - From then on every way of signing in stops at the `twoFactorPage`: `password.signIn`, `magicLink.signIn`, `password.reset` and the OAuth callback answer it as where to go, and the user is signed in once `twoFactor.verify` gets the code, so redirect to the `redirect` they answer, never to a path of your own. It carries `?redirect=` carrying the page asked for when there is one, which the prebuilt page links back to sign-in with if no sign-in waits any more. `twoFactor.pending()` says whether a sign-in waits there (for ten minutes), and `twoFactor.verify(code)` finishes it with an authenticator code or a recovery code, answering `{ ok: true, redirect }`, or `'invalid'`, `'expired'` or `'limited'`.
60
+ - An authenticator code works once, even at two sign-ins at the same moment, and the step either side of now is accepted. A recovery code works once and mails a warning. Eight tries in 15 minutes stop the account's attempts.
61
+ - `twoFactor.regenerateRecoveryCodes(proof)` voids the old set, `twoFactor.recoveryCodesLeft()` counts the unused ones, `twoFactor.disable(proof)` turns the factor off and voids the codes. TOTP secrets are stored encrypted, bound to their user.
62
+ - A user with a passkey may answer the `twoFactorPage` with it instead of a code: see Passkeys.
63
+
64
+ ### Switching features off
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.
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
+ - The `error.code` an `{ ok: false, error }` result carries for a feature that does not run:
69
+
70
+ | Word | Means | Seen from |
71
+ | --- | --- | --- |
72
+ | `'off'` | the app switched the feature off or never set it up | `password.*`, `magicLink.*`, `twoFactor.setUp`, `passkeys.*`, `password.register` and `signInAsGuest` with `signUp: false` |
73
+ | `'unavailable'` | the feature is on but lacks what it needs, such as mail, an invitation page or a reachable provider | `email.*`, `magicLink.request`, `organizations.invite`, OAuth link and sign-in |
74
+ | `'not-enabled'` | the user has not turned two-factor on | `twoFactor.regenerateRecoveryCodes` |
75
+
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`.
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
+ - 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
+ - `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.
81
+
82
+ ### Passkey rules
83
+
84
+ Passkeys are made for `site`'s host and checked against its origin: `passkeys: { rpId, origins }` widens them to a parent domain, or lists every origin the pages are served from. A passkey ceremony run in a frame of another origin, its client data saying `crossOrigin` or naming a `topOrigin`, is refused, as kay's `frame-ancestors 'self'` keeps other origins from framing the pages. `passkeys: { rpName }` is the name the authenticator shows, `name` by default. `passkeys: { userVerification }` (`'required'`, `'preferred'` by default, or `'discouraged'`) is how hard answering a second factor with a passkey asks for a PIN or a biometric; `'required'` also refuses an answer given without it. Adding a passkey, signing in with one and re-proving always require it, as a passkey alone is two factors. Each method below gives the options for the browser, kept as a challenge in the session that works once, for five minutes.
85
+
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
+ - `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
+ - `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.
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
+ - `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
+ - `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.
93
+ - The authenticator's signature counter is checked: an answer that does not count past the last one, as a cloned key sends, is refused. Passkeys are stored as their public key only.
94
+
95
+ ### Re-proof
96
+
97
+ Changing what protects the account takes a `proof`: `password.change`, `email.change`, `twoFactor.setUp`, `twoFactor.disable`, `twoFactor.regenerateRecoveryCodes`, `passkeys.registrationOptions`, `passkeys.revoke`, `oauth.link`, `oauth.unlink`, `account.delete` and `tokens.create`.
98
+
99
+ - `{ passkey }`, the answer to `passkeys.proofOptions()`, from any user with a passkey.
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
+ - 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.
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
+
105
+ ### Account
106
+
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.
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
+ - `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.