@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
@@ -0,0 +1,28 @@
1
+ # kayjs-auth: OAuth provider presets
2
+
3
+ The presets `oauth: { name: true }` and `oauth: { name: { ...options } }` take, their options and what each provider gives back. The flow itself (state, PKCE, linking, failures) is in [OAuth sign-in, two-factor and passkeys](oauth-passkeys-two-factor.md).
4
+
5
+ ## Common tasks
6
+
7
+ ### Adding a provider
8
+
9
+ `auth({ oauth: { github: true, x: true } })` in `kay.config.ts` turns on two presets, each reading `<NAME>_CLIENT_ID` and `<NAME>_CLIENT_SECRET` (`X_CLIENT_ID`, `X_CLIENT_SECRET`), which `kay env` lists. An object in place of `true` takes the preset's options: `oauth: { facebook: { version: 'v27.0' } }`. A provider with no preset that speaks OpenID Connect is `oidcProvider({ issuer, name })`, below.
10
+
11
+ ## Reference
12
+
13
+ ### Provider presets
14
+
15
+ - `discordProvider()` (`identify` and `email` by default) and `githubProvider()` are presets; any `OAuthProvider` works. Every preset takes `{ scopes, params }`, `params` added to the authorize URL, and one a server can host takes its base `url`: `githubProvider({ url: 'https://git.example.com' })` for GitHub Enterprise Server (its API at `<url>/api/v3`), `gitlabProvider({ url })`, `discordProvider({ url })` for a proxy of Discord's API. A trailing slash is dropped and a path kept, and production refuses an `http://` one. A provider of your own may set `completeUser(raw, { accessToken, scope })` to add what a second request holds to the user endpoint's answer before `normalizeUser` reads it, as the GitHub preset does for `/user/emails`. A provider's `normalizeUser` reports an `email` only when the provider verified it, as the presets do. The Discord preset gives `avatar` and `banner` as CDN URLs, a gif for an animated one, null without one.
16
+ - With `scopes: ['read:user', 'user:email']` the GitHub preset reads the primary verified address off `/user/emails`, so a user hiding their email on their profile signs up with it; an unverified or non-primary address is never taken. Without the scope, or when GitHub fails to answer, the profile's public email is used as before.
17
+ - OpenID Connect providers take `{ scopes, params, algorithms }` (Apple `scopes` and `params`), `params` added to the authorize URL, such as Google's `{ access_type: 'offline', prompt: 'consent' }` for a refresh token. Their ID token is checked before anything is read off it: signed by a key of the provider's JWKS, by its issuer, for this `clientId`, unexpired, and carrying the nonce the flow sent. The `alg` of the token has to be an asymmetric one (`RS*`, `PS*`, `ES*`, `EdDSA`), never `none` or an `HS*`; `algorithms: ['RS256']` on an OpenID Connect preset narrows it. In production an `http://` issuer, GitLab `url` or discovered endpoint is refused (`NODE_ENV=production`); development and tests take one.
18
+ - `oidcProvider({ issuer, name })`: any provider by its issuer URL (Keycloak, Authentik, Auth0, Okta, Zitadel...), its endpoints read once off `<issuer>/.well-known/openid-configuration` on first use; a discovery that fails is `unavailable` and tried again on the next sign-in. Its `preferred_username` is the username.
19
+ - `googleProvider()`.
20
+ - `microsoftProvider({ tenant })`: `common` (personal and work accounts, the default), `consumers`, `organizations` or one tenant's id. A work account's email is kept only with the `xms_edov` optional claim on the app registration, saying the domain's owner vouches for it.
21
+ - `gitlabProvider({ url })`: gitlab.com, or a self-hosted instance at `url`.
22
+ - `linkedinProvider()`: "Sign In with LinkedIn using OpenID Connect", the product to add to the LinkedIn app. `email` comes only with the `email` scope and when LinkedIn sends it verified; no usernames.
23
+ - `slackProvider()`: Sign in with Slack (OpenID Connect). `params: { team: 'T0123' }` signs into one workspace. No usernames; `name` is the display name.
24
+ - `twitchProvider()`: OpenID Connect, with the `claims` authorize parameter Twitch needs to put `email`, `email_verified`, `picture` and `preferred_username` in the ID token (set by the preset; the email also needs the `user:read:email` scope, on by default). `preferred_username` is the username; Twitch revokes tokens.
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
+ - `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
+ - 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.
@@ -0,0 +1,76 @@
1
+ # kayjs-auth: The OAuth server for MCP clients and bearer tokens
2
+
3
+ ## Common tasks
4
+
5
+ ### Guard other sites for a reverse proxy
6
+
7
+ `forwardAuth: 'example.com'` in `authCore` makes the app answer a proxy's auth check, rules below. For nginx:
8
+
9
+ ```nginx
10
+ location = /_auth {
11
+ internal;
12
+ proxy_pass http://127.0.0.1:3000/auth/forward;
13
+ proxy_method GET;
14
+ proxy_pass_request_body off;
15
+ proxy_set_header Content-Length "";
16
+ proxy_set_header X-Original-URL $scheme://$http_host$request_uri;
17
+ proxy_set_header X-Forwarded-For $remote_addr;
18
+ }
19
+ location / {
20
+ auth_request /_auth;
21
+ auth_request_set $remote_user $upstream_http_remote_user;
22
+ auth_request_set $remote_name $upstream_http_remote_name;
23
+ auth_request_set $remote_email $upstream_http_remote_email;
24
+ auth_request_set $remote_groups $upstream_http_remote_groups;
25
+ auth_request_set $signin $upstream_http_location;
26
+ error_page 401 = @signin;
27
+ proxy_set_header Remote-User $remote_user;
28
+ proxy_set_header Remote-Name $remote_name;
29
+ proxy_set_header Remote-Email $remote_email;
30
+ proxy_set_header Remote-Groups $remote_groups;
31
+ proxy_pass http://127.0.0.1:8080;
32
+ }
33
+ location @signin { return 302 $signin; }
34
+ ```
35
+
36
+ Traefik: `forwardAuth: { address: 'http://auth:3000/auth/forward?redirect=1', authResponseHeaders: [Remote-User, Remote-Name, Remote-Email, Remote-Groups] }`. Caddy: `forward_auth auth:3000 { uri /auth/forward?redirect=1; copy_headers Remote-User Remote-Name Remote-Email Remote-Groups }`. Behind a proxy set `proxy: { hops: 1 }` in kay.config.ts so limits count the visitor's address.
37
+
38
+ ### Limit a token to scopes
39
+
40
+ Declare the scopes in `authCore`, then name them on the routes a limited token may reach:
41
+
42
+ ```ts
43
+ authCore({ scopes: ['posts:read', 'posts:write'] })
44
+ // a gated route: .get('/posts', handler, { scope: ['posts:read', 'posts:write'] })
45
+ ```
46
+
47
+ ## Reference
48
+
49
+ ### OAuth server for MCP clients
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.
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
+ - 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.
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
+ - 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).
60
+
61
+ ### Bearer tokens
62
+
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.
65
+ - An expired token reads as no token at all, in `user()`, gates and `userFromToken`, and so does a banned user's.
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.
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
+ - 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
+
71
+ ### Forward auth rules
72
+
73
+ - `forwardAuth: 'example.com'` in `authCore` (a domain, a list, or `{ domains, requireTwoFactor? }`) serves `GET ${prefix}/forward` for nginx `auth_request`, Traefik `forwardAuth` and Caddy `forward_auth`, and `${prefix}/forward/return`. Domains are checked at startup (two labels at least, no scheme, port or path; kay has no public suffix list, so `co.uk` or `github.io` pass and would open every site under them: name your own domain), and so is a missing `site` in production. The session cookie takes the domain the visited host is on, so it reaches the guarded sites; it never takes the `__Host-` prefix, so its name is the same whatever Host a proxy passes on, and a host on none of the domains keeps a host-only cookie. A `domain` the `session()` names wins. Name the cookie with `auth({ cookie: 'login' })`, or `session({ cookie })` in `authCore`.
74
+ - `/auth/forward` answers 204 for a person's session with `Remote-User` (username, else email, else id), `Remote-Name` (the same), `Remote-Email` and `Remote-Groups` (roles, comma-joined), always all four, empty when unknown; non-ASCII values are percent-encoded. Otherwise it answers 401 with `Location`: the sign-in page's full URL (`site` in kay.config.ts or in `authCore`), returning through `/auth/forward/return?to=` to the URL asked for when that is `https` on the domains or their subdomains, else the plain sign-in page. `?redirect=1` answers 302 instead of 401, for Traefik and Caddy, which hand the answer to the browser. Every answer is `no-store`.
75
+ - It reads the URL asked for from `X-Original-URL` (nginx sets it) or `X-Forwarded-Proto`, `-Host` and `-Uri`. A guest, a bearer token and a session stopped at the second factor are anonymous. `?role=admin` (repeatable, any of) answers 403 for a user without it, inheritance honoured; Two-factor is asked as a guard asks it: `requireTwoFactor` asks everyone, the app's `twoFactor.require` the users it names, and a session signed in with a passkey, or an admin acting as the user, has it already (a passkey merely registered does not). A user lacking it is sent to the pages' `account/security` with a 401 (a 403 without the prebuilt pages). The request's own `Remote-*` headers are never read: the proxy must overwrite them on the way to the site. The `proxy_pass` path carries the app's `base` (`/app/auth/forward`), and the shared-domain session cookie reaches the guarded sites too, so strip it there (`proxy_set_header Cookie ""`) unless they need it.
76
+ - Only GET: nginx needs `proxy_method GET`. The return route sends anything but the allowed domains (another scheme, credentials, a lookalike host, a relative URL) home.
@@ -0,0 +1,20 @@
1
+ # kayjs-auth: The prebuilt organization pages
2
+
3
+ ## Common tasks
4
+
5
+ ### Let users run their organizations from the browser
6
+
7
+ With the `organizations` option ([Organizations](admin-and-organizations.md#organizations)) and the prebuilt pages, the account area gets an `Organizations` tab under the pages' prefix, `/auth/account/organizations` by default, with no other declaration. Invitation mails link to the pages' own `/auth/invitation` when `invitationPage` is not set.
8
+
9
+ - `/auth/account/organizations`: the user's organizations, the invitations open to their verified address (`Join` or `Decline`), and a form creating one (a name, an optional address).
10
+ - `/auth/account/organizations/<org>`, `<org>` the slug or the id: the members with their roles, and for a manager (the `manage` role) the roles of each member below them, their removal, the open invitations with a form inviting an address (given roles, else `defaultRoles`) and a `Revoke` button, and the name and address of the organization. Every member can leave it behind a ticked box, and an owner can delete it behind a ticked box.
11
+ - `/auth/invitation?invitation=<id>`: the page an invitation mail opens, for anyone holding the link. A visitor sees the organization and the invited address with `Sign in` and `Create an account`, both coming back to the link. The invited, signed-in account sees `Join` and `Decline`. Another account is told the invitation is for another address and may sign out to sign in with the right one. A revoked, spent, expired or unknown id says the invitation is invalid.
12
+ - A visitor is sent to sign in as for the account pages, a stranger to an organization gets a 404 so its existence does not leak, and the pages answer 404 on a site with no `organizations`. The actions answer as the methods do, so a post that skips the page changes nothing: a member without the role gets `forbidden`, a manager cannot touch an owner, and the last owner cannot leave, be removed or lose the role (`last-owner`).
13
+ - The pages follow the prefix, the base path and the locale of the other prebuilt pages (`/fr/auth/account/organizations`), and `pages: false` leaves them out with the rest.
14
+ - The words are `auth.organizations.*` and `auth.invitation.*` in the app's catalogs; English and French ship. An invitation is mailed only with a mailer set up, and the invite form shows only then.
15
+
16
+ ## Reference
17
+
18
+ - `features().organizations` is `{ roles, owner, manage }`, or null without the `organizations` option.
19
+ - `invitationPage` still names a page of your own, which then replaces `/auth/invitation` in the mail.
20
+ - Accepting needs an account whose verified address is the invited one: an invitee without an account registers with that address, verifies it, and comes back to the link.
@@ -0,0 +1,129 @@
1
+ # kayjs-auth: Passwords, guests, mailed links and security mails
2
+
3
+ ## Common tasks
4
+
5
+ ### Passwords
6
+
7
+ An action signs a visitor in with `password.signIn` and redirects to where they were going:
8
+
9
+ ```kay
10
+ --- server
11
+ import { s, action } from 'kay'
12
+
13
+ export const signIn = action(s.Object({ identifier: s.String({ maxLength: 254 }), password: s.String() }), async (input, ctx) => {
14
+ const result = await ctx.locals.auth.password.signIn(input, { redirect: ctx.url.searchParams.get('redirect') ?? '/' })
15
+
16
+ if (!result.ok)
17
+ return ctx.fail(400, { error: result.error.code })
18
+
19
+ return ctx.redirect(result.redirect)
20
+ })
21
+
22
+ const failure = signIn.failed()
23
+ ---
24
+ form(action={signIn})
25
+ input(name="identifier" autocomplete="username")
26
+ input(name="password" type="password" autocomplete="current-password")
27
+ button Sign in
28
+ if failure?.data?.error === 'invalid'
29
+ p.error Wrong email or password
30
+ ```
31
+
32
+ ### Mailed links
33
+
34
+ The `email` option names the mailer and the page each kind of link opens:
35
+
36
+ ```ts
37
+ email: {
38
+ mailer: { send: mail.enqueue },
39
+ links: { 'verify-email': '/verify', 'reset-password': '/reset', 'magic-link': '/magic', 'change-email': '/confirm-email' },
40
+ templates: { 'magic-link': ({ name, url }) => ({ subject: `Your ${name} link`, text: url!, html: `<a href="${url}">Sign in</a>` }) },
41
+ }
42
+ ```
43
+
44
+ The page a mailed link opens shows a button posting the token to an action, so opening the link spends nothing:
45
+
46
+ ```kay
47
+ --- server
48
+ import { s, action } from 'kay'
49
+
50
+ export const query = s.Object({ token: s.Optional(s.String()) })
51
+
52
+ export const spend = action(s.Object({ token: s.String() }), async ({ token }, ctx) => {
53
+ const result = await ctx.locals.auth.magicLink.signIn(token)
54
+
55
+ if (!result.ok)
56
+ return ctx.fail(400, { error: result.error.code })
57
+
58
+ return ctx.redirect(result.redirect)
59
+ })
60
+
61
+ const failure = spend.failed()
62
+ const token = ctx.query.token ?? ''
63
+ ---
64
+ form(action={spend})
65
+ input(type="hidden" name="token" value={token})
66
+ button Sign in
67
+ if failure
68
+ p.error This link has expired or was already used
69
+ ```
70
+
71
+ ## Reference
72
+
73
+ ### Passwords rules
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.
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
+ - 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
+ - `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
+ - `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 }`.
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
+ - Passwords are hashed with argon2id; a hash made weaker, or by bcrypt in an older app, is rehashed on the next sign-in.
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
+
86
+ ### Guests
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.
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
+ - 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
+
93
+ ### Deleting an account after a grace period
94
+
95
+ `account: { deleteAfter: '14d', cancelPage? }` makes `account.delete(proof)` ask for the proof and the checks as before, then only mark the account pending (`{ ok: true, deleteAt }`) instead of deleting it: the user stays signed in, `deleteAt` is stored on them, a `cancel-deletion` mail goes to a verified address with a link to `cancelPage` (the prebuilt account data page, `<pages prefix>/account/data`, by default; `authCore` without `pages` must name one) and the `account-deletion-scheduled` event fires, `deleteAt` its date (the audit detail is the ISO date). Asking again keeps the first deadline.
96
+
97
+ - `account.deletion()` answers `{ deleteAt }` while the account is pending, else null, and `ctx.deletion` is the same date in a template (null for anyone else); `account.cancelDeletion()` takes the mark off and answers `{ ok: true }`, `'signed-out'` or `'not-pending'`, firing `account-deletion-cancelled` (mailed, as the security events are). A user who signs in during the period is offered it: `DeletionBanner` (`@kayjs/auth/components/deletion-banner.kay`, no props, like `ImpersonationBanner`) shows `Your account will be deleted on <date>` with a button posting to `<prefix>/cancel-deletion` (`redirect` for where to go, a path of the site) on every prebuilt page and, with `viewer: true`, every page; the account data page offers the button in place of the delete form. `features().deleteAfter` is the period in seconds, null when the deletion is immediate.
98
+ - The real deletion is the prune's, within an hour of `deleteAt` and on any request after it: `beforeDelete`, the erase, the `account-deleted` audit entry and event and the `account-deleted` mail follow it, not the mark, and a `beforeDelete` that refuses or throws keeps the account pending, tried again at the next run. An organization the user solely owned with other members passes to its longest-standing member, as for any deletion nobody can refuse. Admin deletions (`admin.deleteUser`), guests and unverified accounts are unchanged. A cancelled deletion is read again just before the erase, so it stays cancelled.
99
+ - The store needs `users.dueForDeletion(now, limit)`, `users.markForDeletion(id, deleteAt)` (sets it only when none is, returns whether it did) and keeps `UserRecord.deleteAt`: `memoryAuth` and `pgAuth` do (a nullable `delete_at` column, added by `db.sync()` or a generated migration), and a store without the method is refused at boot.
100
+
101
+ ### Mailed link rules
102
+
103
+ - `mailer.send(mail)` gets `{ to, kind, name, locale, subject, text, html, url?, code?, detail? }`, filled from the templates keyed by `kind`, its result ignored. The mails a visitor asks for without being signed in (verification, reset, magic link, `account-exists`) leave off the response's path, a failure logged, so the time taken tells nothing of which addresses exist; the others are awaited. Kinds are the link types, the security events, `invitation` and `account-exists`. An app with its own templating reads `kind`, `locale`, `url`, `code`, `name` (the site's name) and `detail`, the organization an invitation is to or the provider, passkey, token or new address an event is about.
104
+ - Mails are written in the user's language: `locale` on the user, a BCP 47 tag kept from the browser's `Accept-Language` on signing up, from `password.register({ locale })`, or set with `account.updateLocale(tag)` (`{ ok }`, or `invalid-locale` for anything but a tag, `signed-out`); the browser's when the user has none. `email.locales` lists the languages the site writes, `['en']` by default, the first for anyone else: a tag picks its own, else one of its language (`fr-CA` gets `fr`). kayjs-auth writes English (`defaultTemplates`) and French (`frenchTemplates`); `templates` goes over them in every language, and `translations: { de: {...} }` over both for its own.
105
+ - With `@kayjs/mail`, `mailer: authMailer(mail.enqueue)` renders each mail through its components and its own wording, which the app overrides line by line in its messages or replaces with its own view per kind, themed by the app's mail settings and in the mail's language, and leaves it to its queue, which retries a mail server that is away; `authMailer(mail.send)` sends it at once, before the call answers for the mails kayjs-auth awaits. Its llms.txt shows the setup. A mailer of it also fits as it is, `{ send: mail.enqueue }`, sending kayjs-auth's own html. In development and tests the mails go to its outbox, listed at `/_kay/mail`.
106
+ - `links` names the app's page for each kind, the prebuilt pages' by default with `pages`; the link is `site` + that path + `?token=`. A mailed link opens an app page that shows a button, or the new password's form, posting the token to an action: the page never spends the token on load, as mail scanners open links.
107
+
108
+ - `magicLink.request(email, { redirect?, remember?, captcha? })` and `password.requestReset(email, { redirect?, captcha? })` answer alike whether or not an account has that address: counted per address either way, and mailed off the response's path, so neither the answer nor its time tells which addresses exist. They answer `{ ok: true }`, `'limited'` past the mails allowed, `'captcha'` (see Bots and breached passwords), or `'unavailable'` without a mailer. `magicLink.signIn(token)` signs in, to where the link was asked for, and verifies the address.
109
+ - `password.reset(token, password)` sets the password (`errors.password` as `password.register`'s, `'breached'` included), verifies the address, ends every other session and bearer token, voids the other mailed links and signs in. A refused password leaves the link usable.
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
+ - 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
+ - `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.
116
+
117
+ ### Security mails
118
+
119
+ A change to what protects an account is mailed to its verified address, never an unverified one, and handed to `onEvent` (see Events and the audit log). A mailer or an `onEvent` that throws is logged, never turned into a failed sign-in:
120
+
121
+ - `new-sign-in`: a device or network the account had not used before; the first sign-in has nothing to compare against. The mail links to `sessionsPage` when the app has one.
122
+ - `sign-in-locked`: too many wrong passwords or second-factor codes were tried on the account, mailed at most once a day per account (see Limits).
123
+ - `password-changed`, `two-factor-enabled`, `two-factor-disabled`, `recovery-code-used`, `recovery-codes-regenerated`, `account-deleted`.
124
+ - `signed-out-everywhere`, from `signOutEverywhere` and the sessions page's button, `keptThisOne` whether the session asking stayed signed in.
125
+ - `account-deletion-cancelled`: mailed when a pending deletion is cancelled; the mark itself is the `account-deletion-scheduled` event, with the `cancel-deletion` link mail (see Deleting an account after a grace period).
126
+ - `organization-handed-over`, `organizationId`: mailed to the member an organization passes to when its only owner's account is deleted and no owner was named (an admin's `admin.deleteUser`, a stale guest or unverified account pruned), naming the organization, with no `actor`.
127
+ - `impersonation-started`, with the admin as `actor`: mailed when an admin signs in as the user, to a verified address only and best effort: an unverified address gets none, and a failing mailer is logged while the impersonation goes on (see the admin section).
128
+ - `email-change-requested`, `email` the address asked for: mailed to the address the account is leaving the moment `email.change` sends its link, while its owner can still act. `email-changed` follows, mailed to the address left, `email` the new one, once the link is confirmed.
129
+ - `provider-linked` and `provider-unlinked`, `provider`; `passkey-added` and `passkey-removed`, `name`; `token-created`, `name` its label.
@@ -0,0 +1,51 @@
1
+ # kayjs-auth: Sessions and guards
2
+
3
+ ## Common tasks
4
+
5
+ ### Guards and gates
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):
8
+
9
+ ```ts
10
+ import { authGuard } from '@kayjs/auth'
11
+
12
+ export default authGuard({ redirect: '/login', require: 'editor' })
13
+ ```
14
+
15
+ Plain Elysia routes, such as an API, close behind a gate:
16
+
17
+ ```ts
18
+ const api = new Elysia({ prefix: '/api' })
19
+ .use(auth.gate())
20
+ .get('/me', ({ auth }) => auth.user())
21
+ .get('/stats', () => stats(), { auth: 'admin' })
22
+ .get('/health', () => 'ok', { auth: false })
23
+ ```
24
+
25
+ ## Reference
26
+
27
+ ### Sessions
28
+
29
+ Each sign-in is kept on the user's list of sessions in the store, whatever holds the session itself, so one can be ended from another browser:
30
+
31
+ - `sessions.list()` lists `{ id, current, device, userAgent, ip, place, createdAt, lastSeenAt }`, oldest first, `current` the browser asking. `device` is the user agent read as `{ browser, os, mobile }`, such as `Firefox` and `Windows`, `null` for what it does not know. `place` is what `locate(ip)` answers, an option of the app's over a geolocation database of its own, `null` without one or when it throws. A visit is recorded at most every five minutes, or at once from a new address.
32
+ - `sessions.revoke(id)` ends one of them, effective on that browser's next request; ending the current one signs out. It answers `{ ok: true }`, or `{ ok: false, error: { code: 'not-found' } }` when the user has no session with that id (`signed-out` through a bearer token).
33
+ - The lifetimes are the `session()` plugin's own: a session unseen for its `maxAge` is over even when its cookie lives on, and one signed in its `absoluteMaxAge` ago is over however often it was seen, "remember me" included. Only `remember.maxAge` is kayjs-auth's, a duration (seconds or `'90d'`), 90 days by default.
34
+ - "Remember me": `remember: true` keeps the session `remember.maxAge` unseen; `remember: false` gives it a cookie the browser drops on closing, over after the plugin's `browserMaxAge` unseen. Without `remember` the session takes the plugin's `maxAge`, whatever a sign-in before chose in that browser. It goes in the trailing options object of the ways of signing in (Passwords; `magicLink.request` for the link opened, or the code typed, in that browser; `signIn(user, { remember })`), or as `?remember=1` or `?remember=0` on an OAuth link, and holds through the second factor.
35
+ - A change to how the account is signed in to ends the user's other sessions, which leave the list, and every bearer token, this browser staying signed in: a password changed or reset, the second factor turned on or off, new recovery codes, a passkey removed, a provider unlinked, a new address confirmed. So does `signOutEverywhere`.
36
+ - Through a bearer token, `sessions.list()` is empty and `sessions.revoke` ends nothing: the list belongs to the browsers.
37
+ - `sessionsPage`, such as `/account/sessions`, is where the app lists them: `new-sign-in` mails link to it, so a user who does not know the sign-in can end it.
38
+ - Every sign-in of a person (a guest excepted) sets the readable cookie `kay_user`, `Path=/`, `SameSite=Lax`, `Secure` exactly when the session cookie is, a new random value each time, `Max-Age` as long as the session can last (`absoluteMaxAge`) and a session cookie for `remember: false`; a sign-out, or a session found over, clears it. It is a hint for a script of the site, never read by the server and never a permission: kayjs-cms's script asks its guard when it sees it, so an editor sees the Edit this page link at once. Set on the response of the sign-in or sign-out, a route's own `Response` included.
39
+
40
+ ### Guard and gate rules
41
+
42
+ - An anonymous GET or HEAD that may be a page opening goes to `redirect`, with where they were going as `?redirect=`, a path to hand to `password.signIn` or an OAuth link. Without `redirect`, the pages' sign-in page or the `signInPage` of `authCore` is used; without any, and for any post, the answer is a 401. A user who does not meet `require` gets a 403.
43
+ - A requirement is a role, a predicate `(user, ctx) => boolean`, or a list of which any one passes. A role includes the roles `roles` lists under it: with `{ admin: ['editor'], editor: [] }`, an admin meets `'editor'`. A user's roles are `UserRecord.roles` in the store. `defaultRoles: ['user']` gives every new user those roles, by password or by provider; a store leaves them to kayjs-auth rather than filling them in itself, so it knows which roles were given on purpose.
44
+ - `auth.hasRole('admin')` is the predicate form, `auth.isGranted('admin', user)` the plain check.
45
+ - Exported for an app with its own principal: `roleHierarchy(hierarchy, user => user.roles)` gives `{ isGranted, hasRole }`, `authGate({ principal, authorize, defaultRequirement, scopes?, defaultScope? })` is the Elysia plugin behind `auth.gate()`, and `scopeAllows(tokenScopes, wanted)` says whether a bearer token's scopes meet a route's `scope:`, true for a session (`null`) and `false` as `wanted`. The types are `Requirement<User, Grant>` (a grant `{ type, resourceId }`, a `Predicate<User>` or a list), `Predicate`, `PolicyContext` (the `params`, `body` and `query` a predicate may read), `Principal`, `Level` and `RoleHierarchy`.
46
+ - `authorize: (user, requirement, level, ctx) => Promise<boolean>` replaces the decision, for grants on single records: `decide(grantStore, user, requirement, level, ctx)` reads a `GrantStore` of the app's. `level` is `'read'` for GET and HEAD, `'write'` otherwise.
47
+
48
+ - Every route the instance declares after `.use(auth.gate())` needs a signed-in user, or `gate({ require })`'s requirement. A route asks for more with `auth: <requirement>` and stays open with `auth: false`. Routes added through `group`, `guard`, `route`, `all`, `ws` or a used plugin are closed too, so a route that forgets `auth:` stays closed. A route declared before the gate stays open: use the gate first.
49
+ - `auth.gate()` brings `auth.plugin` along, so `auth` reaches the routes declared after it. Gates nest: a sub-router behind `auth.gate({ require: 'admin' })` inside an app behind `auth.gate()` needs both. A route's `auth:` and `scope:` change only the gate nearest it, so `auth: false` or a looser requirement in the sub-router still meets every gate around it.
50
+ - 401 to an anonymous caller, 403 to a signed-in one who is denied. A bearer token passes as its user.
51
+ - A sign-out of a signed-in person also sets `kay_local_clear`, a new value each time, which makes the browser forget the rows and queued writes of its `local()` collections ([Local collections](../../kay/llms/local-collections.md)); it names no one.
package/llms/setup.md ADDED
@@ -0,0 +1,122 @@
1
+ # kayjs-auth: Setup, pages and the signed-in user
2
+
3
+ ## Common tasks
4
+
5
+ ### Setup
6
+
7
+ kayjs-auth is published as `@kayjs/auth` to `https://git.kaynooo.fr/api/packages/kaynooo/npm/`, beside kay. kay, Elysia (an implementation detail of kay: an app names `KayPlugin` and `Schema`, never Elysia's types), kayjs-ui (for the prebuilt pages) and `@kaynooo/pg-orm` (for the default store) are peer dependencies.
8
+
9
+ One line in kay.config.ts is the whole setup, and the app has no auth file:
10
+
11
+ ```ts
12
+ // kay.config.ts
13
+ import { auth } from '@kayjs/auth'
14
+ import { defineConfig } from 'kay/server'
15
+
16
+ export default defineConfig({
17
+ extensions: [auth({ oauth: { github: true }, roles: { admin: ['editor'], editor: [] } })],
18
+ })
19
+ ```
20
+
21
+ `auth()` takes `authCore`'s options (see Setup rules) and finds the rest. The session is kay's `session()` on the app secret. The site is kay's `site`. The store is, in order: `store` (`{ url }`, a `pgAuth(db)` over the app's own database in a function, or an `AuthStore`); the database at `AUTH_DATABASE_URL`; the database of the app's `store` in kay.config.ts, `sqliteData(path)` or `pgData(url)` (a `pgData` given a connection names none), where it creates its `kay_*` tables and leaves every other table alone; else a SQLite file `data/auth.sqlite`. An existing `data/auth.db` is kept (logged once), so an upgrade loses no user. It is in memory under `bun test` unless one of the first two is given, and in a static export. An app running its own pg-orm `sync` on that database lists `authTables` in its tables. The mailer is `mail.enqueue` of `src/mail.ts` when it exports `mail`, else the one `mail()` of kay.config.ts built (kayjs-mail's `enqueue`), through `authMailer` when kay.config.ts registers `mail()`; `email: false` sends no mail, and an `email` of your own replaces it. `oauth: { github: true }` reads `GITHUB_CLIENT_ID` and `GITHUB_CLIENT_SECRET` (presets: github, discord, google, microsoft, gitlab, linkedin, facebook, twitch, slack, x), which `kay env` lists; an object adds preset options, `label`, `keepTokens` or the credentials. Hooks (`onSignUp`, `beforeDelete`, `profileFields`, `exportData`, `onEvent`, `allow`, `authorize`, `locate`) are options too (they win), or `export const hooks = {...} satisfies AuthHooks` in an optional `src/auth.ts`, found by convention, or `hooks: () => import('./src/auth')`. An executable carries both files, and `kay dev` reloads them. The pages are on under `prefix` (`/auth`), sign-ins and sign-outs going to `home` (`/`); `pages: false` leaves them out and `pages: { remember, profile }` tunes them. `cookie` names the session cookie.
22
+
23
+ `kay add auth` (needs `server` and `tailwind`) writes `auth({ name })` and kayjs-ui's `ui()` in kay.config.ts (with a `store` over the project's pg-orm `Database`, to which it adds `...authTables`), a root `src/routes/_guard.ts` exporting `authGuard()`, and `KAY_SECRET` and `SITE_URL` in `.env.example` (`AUTH_DATABASE_URL` too without a project `Database`), with no `src/auth.ts`. Delete the guard for public pages.
24
+
25
+ ### The authCore form
26
+
27
+ Session data of the app's own, or a store wired by hand, takes `auth({ module: './src/auth' })`: the module exports the `authCore` result as `auth`, and loads as the server starts (rules in Setup rules).
28
+
29
+ ```ts
30
+ // src/auth.ts
31
+ import type { AuthSessionData } from '@kayjs/auth'
32
+ import { authCore } from '@kayjs/auth'
33
+ import { authTables, pgAuth } from '@kayjs/auth/pg'
34
+ import { Database } from '@kaynooo/pg-orm'
35
+ import { session } from 'kay/server'
36
+ import { Posts } from './tables'
37
+
38
+ export const db = new Database({ url: process.env.DATABASE_URL!, tables: [...authTables, Posts] })
39
+
40
+ export const auth = authCore({
41
+ sessions: session<AuthSessionData & { cart: string[] }>(),
42
+ store: pgAuth(db),
43
+ name: 'Example',
44
+ signInPage: '/login',
45
+ })
46
+ ```
47
+
48
+ ```ts
49
+ // kay.config.ts
50
+ import { auth } from '@kayjs/auth'
51
+ import { defineConfig } from 'kay/server'
52
+
53
+ export default defineConfig({
54
+ extensions: [auth({ module: './src/auth' })],
55
+ })
56
+ ```
57
+
58
+ ### Prebuilt pages
59
+
60
+ kayjs-auth ships every sign-in and account page as a kay extension, styled with kayjs-ui, in English and French. `auth()` serves them; a `authCore` module asks for them with `pages: true`.
61
+
62
+ ### The signed-in user
63
+
64
+ ```kay
65
+ --- server
66
+ const user = await ctx.locals.auth.user()
67
+ ---
68
+ if user then signedIn
69
+ p Signed in as {signedIn.email}
70
+ else
71
+ a(href="/login") Sign in
72
+ ```
73
+
74
+ ## Reference
75
+
76
+ ### Setup rules
77
+
78
+ `auth({ module })`: `module` is the file exporting the `authCore` result as `export const auth`, relative to the project root. The extension hands `pages()` its plugin, used before the pages, so the app mounts nothing else and declares no `Register`, and `kay check` types `ctx.locals.auth` and checks links to kayjs-auth's routes off it. The module loads as `pages()` builds the app, never for `kay check`, the editor or `kay build`. `pages: false` serves the plugin alone, and `auth({ server })` takes any other plugin as a function.
79
+
80
+ A plain Elysia app, or one mounting the plugin by hand, gives `auth({ server: false })` in kay.config.ts (the escape `mail({ server: false })` takes too), uses `auth.plugin` (a `KayPlugin`, which is the Elysia instance in 1.x and holds it as `.elysia`) before the pages, `new Elysia().use(auth.plugin).use(await pages())`, and registers `locals: LocalsOf<typeof auth.plugin>` and `app: typeof auth.plugin` in kay's `Register` for `kay check`. The plugin uses the session plugin itself, puts `auth` in every request's context (`ctx.locals.auth` in pages, actions and guards, `({ auth })` in Elysia routes), and serves the OAuth routes. What it logs goes where the app's `log` setting sends kay's messages, headed `kayjs-auth:`.
81
+
82
+ `authCore` options (`auth()` takes them all but `sessions`):
83
+
84
+ - `sessions`: the plugin kay's `session()` returns, its data type including `AuthSessionData`: the signed-in state lives in the app's kay session, and kayjs-auth sets no cookie of its own.
85
+ - `secret`: derived from the session's secret ([The app secret](../../kay/llms/environment.md#the-app-secret)), so keep old session secrets in its list while sealed TOTP secrets and provider tokens exist. Pass one (32 characters or more; a list rotates) only to keep a separate one; moving from `AUTH_SECRET` takes `secret: [...sessions.deriveSecret('kayjs-auth'), process.env.AUTH_SECRET!]` until nothing sealed under the old one is left.
86
+ - The OAuth plumbing behind `oauth` (`createOAuthClient`, `createOAuthTokenRefresher`, `createTokenRefresher`, `createPkcePair`, `challengeOf`, `OAuthExchangeError`), `SIGNED_IN_HINT`, `resolveRules`, `DEFAULT_RULES`, `mixesConfusableScripts` and the modules of `@kayjs/auth/pages/*.kay` (their `load`, `page` and actions) are what the extension mounts, not API: replace a page by writing one at its path.
87
+ - `store`: see Stores. `authTables` of `@kayjs/auth/pg` is every table below, each exported on its own for an app table's foreign key: `AuthUsers`, `AuthSessions`, `AuthIdentities`, `AuthPasskeys`, `AuthRecoveryCodes`, `AuthTokens`, `AuthAttempts`, `AuthAudit`, `AuthBearerTokens`, `AuthOrganizations`, `AuthMembers`, `AuthInvitations`, `AuthOAuthClients`, `AuthOAuthCodes`, `AuthOAuthGrants` and `AuthOAuthRefresh`.
88
+ - `site`: the site's public origin, for OAuth callbacks, mailed links and passkeys; kay's `site` (kay.config.ts, else `SITE_URL`) when left out; a plain Elysia app gives its own. With OAuth or mail configured and no origin anywhere, the server refuses to start and a request answers 500, naming `SITE_URL`; `kay dev` supplies `http://localhost:<port>`. `name`: the site's name in mails and authenticator apps, the origin's host by default.
89
+ - `signInPage`: where a failed OAuth sign-in goes with `?error=`, `/` by default, and where `authGuard()` and `requireUser()` send an anonymous visitor opening a page when there are no `pages`. `failurePage`: where every failed OAuth sign-in goes instead, with no reason in the URL, so that whether an account may sign in does not leak through an `allow` list. `twoFactorPage`: where a sign-in goes to ask for the code, `/two-factor` by default. `securityPage`: where `twoFactor.require` sends a user to turn two-factor on, the pages' account security page by default. `pages`: see Prebuilt pages, which these then default to.
90
+ - The rest sit with their topic: `oauth`, `allow`, `onSignUp`, `profileFields` (OAuth); `signUp`, `rules` (Passwords); `email` (Mailed links); `beforeDelete` (Account); `account` (Deleting an account after a grace period); `onEvent` (Security mails); `roles`, `defaultRoles`, `authorize` (Guards and gates); `scopes` (Bearer tokens); `rateLimit` (Limits); `captcha`, `breachedPasswords` (Bots and breached passwords); `remember`, `sessionsPage`, `locate` (Sessions); `passkeys`; `audit` (Events and the audit log); `admin`; `organizations`; `oauthServer` (OAuth server for MCP clients). The hooks follow [kay's hook convention](../../kay/llms/hooks.md) and take one event object with a `context` (an `AuthHookContext`): `onSignUp({ user, profile, context })`, `beforeDelete({ user, context })`, `onEvent({ event, user, context, ... })`. `onSignUp` and `onEvent` only observe: a throw is logged, reported to the app's `onError` with source `auth.onSignUp` or `auth.onEvent`, and never fails the sign-up or the sign-in.
91
+
92
+ ### Prebuilt pages rules
93
+
94
+ - `prefix` and `home` are given once, to `auth()` in kay.config.ts, and reach a `authCore({ pages: true })` module too. A `prefix` in both places must match, else the server stops at start naming both; `home` in `authCore` wins when they differ, with a warning. `home` is also where mailed links, codes, registering, passkeys and providers land when nothing asked for another page; the pages localize it. `prefix` is where the pages and the OAuth routes live.
95
+ - `pages.remember` is `'checkbox'` (default), `'always'` or `'never'`: the sign-in and register pages show a "keep me signed in" box, or none and every sign-in remembered (`'always'`) or none (`'never'`). Unchecked is the same by password, passkey, register, magic link, code and each provider; checked is `remember.maxAge` on all of them. The provider and passkey buttons read the first box of the page, which a click carries, so a browser without script signs in with a provider as unchecked. A magic link carries the choice of the browser that asked for it. A page of the app's own, or a link to `/auth/<provider>` with no `remember`, gets the session plugin's `maxAge`, and the sign-out and provider routes fall back to `home` as written, unlocalized.
96
+ - The pages: `sign-in` (providers, password, magic link or code, passkey, remember me), `password.register`, `two-factor`, `reset-password`, `verify-email`, `magic-link`, `confirm-email`, and under `account`: the profile (address, username, verification), `security` (password, two-factor with its QR code and recovery codes, passkeys), `sessions`, `connections` (shown with providers), `tokens`, `clients` (the apps signed in by OAuth, with a revoke button; shown with the OAuth server) and `data` (download, asking for a recent proof first, and deletion). Each works without JavaScript but passkeys, and shows only what the config enables.
97
+ - With `pages`, `signInPage`, `twoFactorPage`, `sessionsPage` and every `email.links` default to those pages, and `auth.guard()` without `redirect` sends an anonymous GET or HEAD to the sign-in page (a browser fetch, or a request whose `Accept` names neither `text/html` nor `*/*`, gets the 401), `?redirect=` back, in the page's language (`/fr/page` goes to `/fr/auth/sign-in?redirect=%2Ffr%2Fpage`). Without `pages`, `email.links` names a page for each kind, or `authCore` throws.
98
+ - An app file at a page's path replaces that page alone: `src/routes/auth/magic-link.kay` is the app's own magic-link page. Its texts live under `auth` in kay's messages, the English in the code and the French shipped with the package: a key in the app's `src/messages/en.ts`, such as `auth: { signIn: { title: 'Welcome back' } }`, replaces that text and keeps the rest.
99
+ - The pages reached before signing in, `sign-in`, `password.register`, `two-factor`, `reset-password`, `verify-email`, `magic-link` and `confirm-email`, set `guards: false`, and the four that open from a mailed link (`reset-password`, `verify-email`, `magic-link`, `confirm-email`) send `Referrer-Policy: same-origin` so the token in the address never reaches another site: none of the app's guards above them runs there, whatever it checks. A root `_guard.ts` asking for a session, `export default auth.guard()`, keeps the rest of the site to signed-in users and still lets visitors sign in, the `account` pages keeping it; but a guard for maintenance, an IP allow-list or invite-only access skips those pages too. An app needing it on one of them replaces that page with its own, which the app's guards cover unless it sets `guards: false`; an app page replacing one under a session guard sets it. kayjs-auth's own routes, OAuth and the rest, are its plugin's, which page guards never reach.
100
+ - A site with data of its own on its users keeps these pages: `pages: { profile }` adds fields to the account page's profile form. `profile` is `{ fields, load, save }`: `fields` maps a name to `{ label, type?, autocomplete?, required?, maxLength? }` (`type` `'text'` by default, `'textarea'`, `'tel'`, `'url'` or `'email'`; `label` a string, or a map by locale such as `{ en: 'Bio', fr: 'Biographie' }`, the first when none matches); `load(user)` answers what each field holds, a string, `null` or `undefined` (anything else throws); `save(user, values)` stores the trimmed values once `required` and `maxLength` (500 by default) passed, may return `{ errors: { field: 'message' } }` to refuse, and answers 500 when it throws. `auth.account.profile(locale?)` and `auth.account.saveProfile(values)` are what the form calls, for a page of the app's own (`saveProfile` throws without `pages.profile`): both need a session, a bearer token cannot edit a profile, and an admin acting as a user can.
101
+ - `captcha.widget`, `turnstileWidget(siteKey)` or `hcaptchaWidget(siteKey)`, is the widget the pages show where `captchaRequired` asks for one; with the proof of work they carry its field instead, and say JavaScript is needed to a browser without it.
102
+ - A provider's button reads its `label`, set on each preset (`GitHub`, `Google`) and overridden by `oauth.<name>.label`.
103
+ - The pages render with the app's own kayjs-ui, which with Tailwind and `@iconify-json/tabler` the app keeps; kayjs-auth and kayjs-ui are released with kay at its version and peer on kay's minor, so the app moves them together.
104
+
105
+ Each prebuilt page writes its content in a `main` landmark; `pages: { main: false }` (`auth({ pages: { main: false } })`) writes a `div` instead, for an app whose layout already writes a `main`.
106
+
107
+ The register page's notice: `pages: { privacy: '/privacy', purpose: 'Your address signs you in.' }` draws `purpose` (stock line `auth.register.purpose` when unset) and a link to `privacy` (`auth.register.privacy`, `target="_blank"`) under the form; either one draws it, and `AuthFeatures.pages` carries both. In production `authCore` warns when the pages are on, sign-up and passwords are open and `privacy` is unset (RGPD art. 13).
108
+
109
+ `auth.features()` tells any page, prebuilt or the app's own, what the config enables: `{ providers: [{ name, label }], email, codes, signUp, requireVerified, passkeys, password, magicLink, twoFactor, captcha, scopes, prefix, oauthServer, signInPage, pages }`, `captcha` being the widget, `'proof-of-work'` or null.
110
+
111
+ ### Signed-in user rules
112
+
113
+ - `auth.user()` is a method returning a promise, `await` it. It answers `{ id, email, emailVerified, username, roles, hasPassword, twoFactor, locale, guest, data, providers }`, or `null`: `data` is what the `user` schema keeps (see OAuth), `{}` without one, and `providers` the id of each linked provider (`providers.discord?.id`), read for `user()`, `requireUser()` and the hooks (`onSignUp`, `profileFields`, `beforeDelete`, `exportData`, `admin`, `onEvent`, `impersonator()`, `userFromToken`); guards, gates, `authorize`, admin lists and results such as `password.register` give a `BareUser` without it, and `bareUser()` is `user()` without it and without the read. Returning `await auth.user()` whole to the client sends provider ids. Secrets never leave the store: no hash, no TOTP secret, no token.
114
+ - It reads the session first, then the request's `Authorization: Bearer` token. `via()` says which: `'session'`, `'bearer'` or `null`.
115
+ - `requireUser()` is `user()` for a page or an action that needs one, with no guard above it: it answers the `User`, and for an anonymous request it stops as `auth.guard()` does, a visitor reading a page going to the sign-in page with `?redirect=` set to where they were, with `pages`, and any other request, an action's call included, refused with a 401. The user is read once per request however many of them ask.
116
+ - `requireUser({ redirect, scope, require })` names the sign-in page of an app without `pages` or `signInPage` (empty by default, as in `guard`), a scope a scoped bearer token needs, and a requirement `authorize` checks, as in `authGuard({ require })` but with no `params`; either missing is a 403. `bare: true` answers the `BareUser` of `bareUser()` and reads no providers, for a caller that only wants the checks (kayjs-cms's `role` does). `signInUrl(back?)` is that URL for a link of the app's own: `a(href={ctx.locals.auth.signInUrl()}) Sign in` leads back to its page, `signInUrl('/pricing')` to another path. A `back` that is not a path of this site, `//evil.example` or `https://...`, leads home instead.
117
+ - A sign-out button is a form posting to kayjs-auth's own route, with no action of the app: `form(method="post" action={`${ctx.locals.auth.features().prefix}/sign-out`})`, with an `input(type="hidden" name="redirect" value="/")` for where to go after, a path of the site, else the pages' `home` or `/`. It answers 303, only to a post: a link or a prefetch signs no one out, and a post from another site gets a 403.
118
+ - `signOut()` signs this session out under a new session id, keeping the rest of the app's session data, and takes it off the user's sessions, so a copy of the cookie is worth nothing either. `signOutEverywhere()` ends every session of the user, copied cookies included, and every bearer token they hold; `signOutEverywhere({ keepThisOne: true })` keeps this session, the tokens still ending.
119
+ - `signIn({ id })` signs a user in directly, without their second factor, for a way of signing in the app proves itself. kayjs-auth's own flows all go through the second factor.
120
+ - A deleted user, one signed out everywhere since, or a session ended or unseen past its lifetime, reads as `null`, and the stale entry leaves the session.
121
+ - A websocket route reads its user as `await ws.data.auth.user()`, off the cookie or token its upgrade carried; `auth.socketUser(ws)` does the same for a handler typed for any socket, `null` for an anonymous one or one opened without the plugin. A socket's user is read again once 30 seconds have passed since the last read, so a sign-out, "sign out everywhere", a revoked token or a ban reaches an open socket within 30 seconds of its next read: `user()` then answers `null`, and `socketUser` also closes the socket with code 1008. A handler reads the user on each message it acts on, not once on `open`.
122
+ - A browser's cross-site POST or websocket upgrade reads the session as signed out on a plain Elysia app too, which has no Origin check of kay's, and a session write from it (a sign-in, a sign-out) answers 403: `Origin` (or `Sec-Fetch-Site`) must name the request's host or the host of `site`, so an app behind a proxy that does not pass `Host` sets `site`. `socketUser` closes such a socket with 1008. Left alone: a request with neither header (a script, a webhook), a safe method, an `Authorization: Bearer` token, the OAuth `form_post` callback, and what an `api({ cors })` module of kay admits.
@@ -0,0 +1,59 @@
1
+ # kayjs-auth: The signed-in user in templates
2
+
3
+ ## Common tasks
4
+
5
+ ### Show or hide a part for the signed-in user
6
+
7
+ `SignedIn`, `SignedOut` and `UserMenu` read the request's user themselves, so a layout or a component shows the user with no `--- server` fence. They are sugar over `ctx.user`, `ctx.can(role)` and `ctx.impersonator`, which any template reads the same way, `if ctx.user then user` or `if ctx.can('admin')` ([Request values](../../kay/llms/request-values.md)):
8
+
9
+ ```kay
10
+ ---
11
+ import SignedIn from '@kayjs/auth/components/signed-in.kay'
12
+ import SignedOut from '@kayjs/auth/components/signed-out.kay'
13
+ import UserMenu from '@kayjs/auth/components/user-menu.kay'
14
+ ---
15
+ nav
16
+ SignedOut
17
+ a(href="/auth/sign-in") Sign in
18
+ SignedIn(role="admin")
19
+ a(href="/admin") Admin
20
+ UserMenu
21
+ ```
22
+
23
+ - `SignedIn` renders its children for a signed-in user, and with `role="admin"` for one holding that role, the app's `roles` hierarchy applied. `SignedOut` renders them for a visitor.
24
+ - `UserMenu` shows the user's username or email, a link to their account when the prebuilt pages are on (`account={false}` leaves it out) and a sign-out button back to the pages' home. The account pages' own header is one.
25
+ - A guest is signed out for all three.
26
+ - `role` only hides markup, the page and its data are still served: guard the route with `auth.guard` for access.
27
+ - They read the request being answered, so a page with `prerender: true` fails the build asking you to render it per request. They nest in one another and in the app's own `await` blocks.
28
+
29
+ ### Show the impersonation banner
30
+
31
+ `ImpersonationBanner` shows an admin acting as a user, with a button back to their own account, and nothing for anyone else. The prebuilt pages carry it already; put it in a layout of your own with no fence and no option:
32
+
33
+ ```kay
34
+ ---
35
+ import ImpersonationBanner from '@kayjs/auth/components/impersonation-banner.kay'
36
+ ---
37
+ ImpersonationBanner
38
+ slot
39
+ ```
40
+
41
+ - It reads `ctx.impersonator`, the admin behind the session (null for none), so a page reaching it shows the banner in the first bytes, once per request even in a layout and a page both holding one.
42
+ - The button posts to `<prefix>/stop-impersonating` under the base and back to the admin pages (the pages' home when the admin pages are off), worded in the page's locale.
43
+
44
+ ### Show a pending deletion
45
+
46
+ With `account.deleteAfter`, `DeletionBanner` (`@kayjs/auth/components/deletion-banner.kay`, no props or fence) shows `Your account will be deleted on <date>` and a button that cancels (a post to `<prefix>/cancel-deletion`), and nothing for anyone else. The prebuilt pages carry it, as do all pages with `viewer: true`; put it in a layout of your own elsewhere, once per request. It reads `ctx.deletion`, the date or null. See [Deleting an account after a grace period](passwords-and-mails.md#deleting-an-account-after-a-grace-period).
47
+
48
+ ### Show them with the first bytes
49
+
50
+ A page reads the user before it renders when its imports reach `SignedIn`, `SignedOut`, `UserMenu` or any template reading `ctx`, through its layouts, components and helpers however deep, so they show in the first bytes, with JavaScript off too. A page not reaching them reads no session, and no option is needed.
51
+
52
+ - A page reading the session is the visitor's own: no cache shares it between visitors, and a page kept by the build is rendered per request.
53
+ - A read that fails there is left to the components, which read again and report it, showing nothing meanwhile.
54
+ - `viewer: true` in `auth({ ... })` reads the user on every page, for an app whose own components call `currentUser`; `viewer: false` and the default read it only where a template reads `ctx`.
55
+
56
+ ## Reference
57
+
58
+ - `viewer` goes beside `module` and `pages` in `auth({ ... })`: left out, the pages reaching a template reading `ctx` read the user; `true` reads it on every page.
59
+ - `SignedIn` takes `role`; `UserMenu` takes `account`; `SignedOut`, `ImpersonationBanner` and `DeletionBanner` take none. All import from `@kayjs/auth/components/<name>.kay`.