@kayjs/auth 0.0.0-stage → 1.104.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (407) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +78 -2
  3. package/llms/admin-and-organizations.md +70 -0
  4. package/llms/admin-pages.md +30 -0
  5. package/llms/grouped-methods.md +106 -0
  6. package/llms/hardening-and-testing.md +108 -0
  7. package/llms/oauth-passkeys-two-factor.md +111 -0
  8. package/llms/oauth-providers.md +28 -0
  9. package/llms/oauth-server-and-tokens.md +76 -0
  10. package/llms/organization-pages.md +20 -0
  11. package/llms/passwords-and-mails.md +129 -0
  12. package/llms/sessions-and-guards.md +51 -0
  13. package/llms/setup.md +122 -0
  14. package/llms/signed-in-components.md +59 -0
  15. package/llms.txt +28 -0
  16. package/package.json +85 -4
  17. package/src/access.ts +31 -0
  18. package/src/account.ts +198 -0
  19. package/src/add.ts +70 -0
  20. package/src/address.ts +51 -0
  21. package/src/admin.ts +361 -0
  22. package/src/auditWording.ts +153 -0
  23. package/src/auth.ts +219 -0
  24. package/src/authorize/clients.ts +160 -0
  25. package/src/authorize/grants.ts +44 -0
  26. package/src/authorize/metadata.ts +72 -0
  27. package/src/authorize/register.ts +38 -0
  28. package/src/authorize/reply.ts +9 -0
  29. package/src/authorize/request.ts +253 -0
  30. package/src/authorize/resource.ts +34 -0
  31. package/src/authorize/revoke.ts +36 -0
  32. package/src/authorize/routes.ts +87 -0
  33. package/src/authorize/token.ts +213 -0
  34. package/src/authorize/uris.ts +76 -0
  35. package/src/bearer.ts +208 -0
  36. package/src/bearerHeader.ts +11 -0
  37. package/src/breached.ts +47 -0
  38. package/src/browser.ts +59 -0
  39. package/src/captcha.ts +196 -0
  40. package/src/cbor.ts +129 -0
  41. package/src/components/deletion-banner.kay +20 -0
  42. package/src/components/impersonation-banner.kay +21 -0
  43. package/src/components/signed-in.kay +8 -0
  44. package/src/components/signed-out.kay +6 -0
  45. package/src/components/user-menu.kay +21 -0
  46. package/src/context.ts +5 -0
  47. package/src/core.ts +308 -0
  48. package/src/createUserCommand.ts +217 -0
  49. package/src/decide.ts +45 -0
  50. package/src/deletion.ts +80 -0
  51. package/src/devTool.ts +104 -0
  52. package/src/device.ts +37 -0
  53. package/src/email.ts +594 -0
  54. package/src/erase.ts +237 -0
  55. package/src/events.ts +297 -0
  56. package/src/export.ts +101 -0
  57. package/src/failure.ts +63 -0
  58. package/src/forwardAuth.ts +55 -0
  59. package/src/forwardRoutes.ts +68 -0
  60. package/src/gate.ts +104 -0
  61. package/src/guard.ts +22 -0
  62. package/src/guards.ts +72 -0
  63. package/src/guesses.ts +99 -0
  64. package/src/index.ts +46 -0
  65. package/src/keys.ts +51 -0
  66. package/src/limits.ts +182 -0
  67. package/src/load.ts +18 -0
  68. package/src/locale.ts +15 -0
  69. package/src/log.ts +4 -0
  70. package/src/mail.ts +225 -0
  71. package/src/memoryStore.ts +599 -0
  72. package/src/messages/fr.ts +357 -0
  73. package/src/methods/account.ts +80 -0
  74. package/src/methods/admin.ts +63 -0
  75. package/src/methods/audit.ts +15 -0
  76. package/src/methods/email.ts +39 -0
  77. package/src/methods/magicLink.ts +32 -0
  78. package/src/methods/oauth.ts +35 -0
  79. package/src/methods/oauthServer.ts +31 -0
  80. package/src/methods/organizations.ts +96 -0
  81. package/src/methods/passkeys.ts +61 -0
  82. package/src/methods/password.ts +53 -0
  83. package/src/methods/sessions.ts +18 -0
  84. package/src/methods/tokens.ts +24 -0
  85. package/src/methods/twoFactor.ts +62 -0
  86. package/src/oauth/client.ts +324 -0
  87. package/src/oauth/flow.ts +350 -0
  88. package/src/oauth/index.ts +5 -0
  89. package/src/oauth/pkce.ts +20 -0
  90. package/src/oauth/providers.ts +490 -0
  91. package/src/oauth/refresher.ts +177 -0
  92. package/src/oauth/timeout.ts +2 -0
  93. package/src/oauth/types.ts +78 -0
  94. package/src/oauthTest.ts +112 -0
  95. package/src/organizations.ts +675 -0
  96. package/src/organizationsCore.ts +60 -0
  97. package/src/own.ts +313 -0
  98. package/src/pages/components/captcha.kay +16 -0
  99. package/src/pages/components/frame.kay +11 -0
  100. package/src/pages/components/message.kay +8 -0
  101. package/src/pages/components/panel.kay +12 -0
  102. package/src/pages/components/passkey-add.kay +48 -0
  103. package/src/pages/components/passkey-sign-in.kay +34 -0
  104. package/src/pages/components/passkey-two-factor.kay +33 -0
  105. package/src/pages/components/proof.kay +15 -0
  106. package/src/pages/components/provider-buttons.kay +25 -0
  107. package/src/pages/components/recovery-codes.kay +13 -0
  108. package/src/pages/components/separator.kay +4 -0
  109. package/src/pages/english.ts +82 -0
  110. package/src/pages/forms.ts +185 -0
  111. package/src/pages/index.ts +361 -0
  112. package/src/pages/organizationPage.ts +12 -0
  113. package/src/pages/routes/account/_guard.ts +15 -0
  114. package/src/pages/routes/account/_layout.kay +37 -0
  115. package/src/pages/routes/account/clients.kay +33 -0
  116. package/src/pages/routes/account/connections.kay +57 -0
  117. package/src/pages/routes/account/data.kay +106 -0
  118. package/src/pages/routes/account/index.kay +109 -0
  119. package/src/pages/routes/account/organizations/[org].kay +188 -0
  120. package/src/pages/routes/account/organizations/_guard.ts +8 -0
  121. package/src/pages/routes/account/organizations/index.kay +86 -0
  122. package/src/pages/routes/account/security.kay +164 -0
  123. package/src/pages/routes/account/sessions.kay +51 -0
  124. package/src/pages/routes/account/tokens.kay +84 -0
  125. package/src/pages/routes/admin/_layout.kay +43 -0
  126. package/src/pages/routes/admin/audit.kay +43 -0
  127. package/src/pages/routes/admin/index.kay +60 -0
  128. package/src/pages/routes/admin/users/[id].kay +181 -0
  129. package/src/pages/routes/confirm-email.kay +39 -0
  130. package/src/pages/routes/invitation.kay +104 -0
  131. package/src/pages/routes/magic-link.kay +42 -0
  132. package/src/pages/routes/oauth/authorize.kay +80 -0
  133. package/src/pages/routes/register.kay +83 -0
  134. package/src/pages/routes/reset-password.kay +73 -0
  135. package/src/pages/routes/sign-in.kay +128 -0
  136. package/src/pages/routes/two-factor.kay +61 -0
  137. package/src/pages/routes/verify-email.kay +83 -0
  138. package/src/passkeys.ts +373 -0
  139. package/src/password.ts +316 -0
  140. package/src/payloads.ts +22 -0
  141. package/src/pg.ts +705 -0
  142. package/src/profile.ts +43 -0
  143. package/src/proof.ts +110 -0
  144. package/src/prune.ts +123 -0
  145. package/src/rates.ts +82 -0
  146. package/src/request.ts +712 -0
  147. package/src/requiredTwoFactor.ts +71 -0
  148. package/src/requirement.ts +23 -0
  149. package/src/roles.ts +18 -0
  150. package/src/routes.ts +202 -0
  151. package/src/rules-check.ts +37 -0
  152. package/src/rules.ts +108 -0
  153. package/src/securityNotice.ts +45 -0
  154. package/src/sessions.ts +184 -0
  155. package/src/setup.ts +417 -0
  156. package/src/signInOptions.ts +9 -0
  157. package/src/state.ts +34 -0
  158. package/src/store.ts +410 -0
  159. package/src/storeHelpers.ts +23 -0
  160. package/src/test.ts +46 -0
  161. package/src/testCookies.ts +9 -0
  162. package/src/testHelpers.ts +58 -0
  163. package/src/testing.ts +113 -0
  164. package/src/text.ts +6 -0
  165. package/src/totp.ts +120 -0
  166. package/src/twoFactor.ts +200 -0
  167. package/src/types.ts +23 -0
  168. package/src/userData.ts +47 -0
  169. package/src/viewer-layout/_layout.kay +11 -0
  170. package/src/viewer.ts +116 -0
  171. package/src/wayIn.ts +40 -0
  172. package/src/webauthn.ts +375 -0
  173. package/src/wsAuth.ts +53 -0
  174. package/types/access.d.ts +12 -0
  175. package/types/access.d.ts.map +1 -0
  176. package/types/account.d.ts +32 -0
  177. package/types/account.d.ts.map +1 -0
  178. package/types/add.d.ts +29 -0
  179. package/types/add.d.ts.map +1 -0
  180. package/types/address.d.ts +2 -0
  181. package/types/address.d.ts.map +1 -0
  182. package/types/admin.d.ts +84 -0
  183. package/types/admin.d.ts.map +1 -0
  184. package/types/auditWording.d.ts +9 -0
  185. package/types/auditWording.d.ts.map +1 -0
  186. package/types/auth.d.ts +3475 -0
  187. package/types/auth.d.ts.map +1 -0
  188. package/types/authorize/clients.d.ts +15 -0
  189. package/types/authorize/clients.d.ts.map +1 -0
  190. package/types/authorize/grants.d.ts +15 -0
  191. package/types/authorize/grants.d.ts.map +1 -0
  192. package/types/authorize/metadata.d.ts +20 -0
  193. package/types/authorize/metadata.d.ts.map +1 -0
  194. package/types/authorize/register.d.ts +4 -0
  195. package/types/authorize/register.d.ts.map +1 -0
  196. package/types/authorize/reply.d.ts +6 -0
  197. package/types/authorize/reply.d.ts.map +1 -0
  198. package/types/authorize/request.d.ts +48 -0
  199. package/types/authorize/request.d.ts.map +1 -0
  200. package/types/authorize/resource.d.ts +4 -0
  201. package/types/authorize/resource.d.ts.map +1 -0
  202. package/types/authorize/revoke.d.ts +4 -0
  203. package/types/authorize/revoke.d.ts.map +1 -0
  204. package/types/authorize/routes.d.ts +5 -0
  205. package/types/authorize/routes.d.ts.map +1 -0
  206. package/types/authorize/token.d.ts +7 -0
  207. package/types/authorize/token.d.ts.map +1 -0
  208. package/types/authorize/uris.d.ts +5 -0
  209. package/types/authorize/uris.d.ts.map +1 -0
  210. package/types/bearer.d.ts +45 -0
  211. package/types/bearer.d.ts.map +1 -0
  212. package/types/bearerHeader.d.ts +3 -0
  213. package/types/bearerHeader.d.ts.map +1 -0
  214. package/types/breached.d.ts +5 -0
  215. package/types/breached.d.ts.map +1 -0
  216. package/types/browser.d.ts +11 -0
  217. package/types/browser.d.ts.map +1 -0
  218. package/types/captcha.d.ts +42 -0
  219. package/types/captcha.d.ts.map +1 -0
  220. package/types/cbor.d.ts +4 -0
  221. package/types/cbor.d.ts.map +1 -0
  222. package/types/context.d.ts +3 -0
  223. package/types/context.d.ts.map +1 -0
  224. package/types/core.d.ts +180 -0
  225. package/types/core.d.ts.map +1 -0
  226. package/types/createUserCommand.d.ts +11 -0
  227. package/types/createUserCommand.d.ts.map +1 -0
  228. package/types/decide.d.ts +12 -0
  229. package/types/decide.d.ts.map +1 -0
  230. package/types/deletion.d.ts +17 -0
  231. package/types/deletion.d.ts.map +1 -0
  232. package/types/devTool.d.ts +3 -0
  233. package/types/devTool.d.ts.map +1 -0
  234. package/types/device.d.ts +7 -0
  235. package/types/device.d.ts.map +1 -0
  236. package/types/email.d.ts +73 -0
  237. package/types/email.d.ts.map +1 -0
  238. package/types/erase.d.ts +31 -0
  239. package/types/erase.d.ts.map +1 -0
  240. package/types/events.d.ts +139 -0
  241. package/types/events.d.ts.map +1 -0
  242. package/types/export.d.ts +54 -0
  243. package/types/export.d.ts.map +1 -0
  244. package/types/failure.d.ts +19 -0
  245. package/types/failure.d.ts.map +1 -0
  246. package/types/forwardAuth.d.ts +12 -0
  247. package/types/forwardAuth.d.ts.map +1 -0
  248. package/types/forwardRoutes.d.ts +11 -0
  249. package/types/forwardRoutes.d.ts.map +1 -0
  250. package/types/gate.d.ts +31 -0
  251. package/types/gate.d.ts.map +1 -0
  252. package/types/guard.d.ts +10 -0
  253. package/types/guard.d.ts.map +1 -0
  254. package/types/guards.d.ts +37 -0
  255. package/types/guards.d.ts.map +1 -0
  256. package/types/guesses.d.ts +18 -0
  257. package/types/guesses.d.ts.map +1 -0
  258. package/types/index.d.ts +47 -0
  259. package/types/index.d.ts.map +1 -0
  260. package/types/keys.d.ts +11 -0
  261. package/types/keys.d.ts.map +1 -0
  262. package/types/limits.d.ts +133 -0
  263. package/types/limits.d.ts.map +1 -0
  264. package/types/load.d.ts +18 -0
  265. package/types/load.d.ts.map +1 -0
  266. package/types/locale.d.ts +4 -0
  267. package/types/locale.d.ts.map +1 -0
  268. package/types/log.d.ts +2 -0
  269. package/types/log.d.ts.map +1 -0
  270. package/types/mail.d.ts +51 -0
  271. package/types/mail.d.ts.map +1 -0
  272. package/types/memoryStore.d.ts +3 -0
  273. package/types/memoryStore.d.ts.map +1 -0
  274. package/types/messages/fr.d.ts +409 -0
  275. package/types/messages/fr.d.ts.map +1 -0
  276. package/types/methods/account.d.ts +24 -0
  277. package/types/methods/account.d.ts.map +1 -0
  278. package/types/methods/admin.d.ts +30 -0
  279. package/types/methods/admin.d.ts.map +1 -0
  280. package/types/methods/audit.d.ts +11 -0
  281. package/types/methods/audit.d.ts.map +1 -0
  282. package/types/methods/email.d.ts +14 -0
  283. package/types/methods/email.d.ts.map +1 -0
  284. package/types/methods/magicLink.d.ts +12 -0
  285. package/types/methods/magicLink.d.ts.map +1 -0
  286. package/types/methods/oauth.d.ts +16 -0
  287. package/types/methods/oauth.d.ts.map +1 -0
  288. package/types/methods/oauthServer.d.ts +13 -0
  289. package/types/methods/oauthServer.d.ts.map +1 -0
  290. package/types/methods/organizations.d.ts +30 -0
  291. package/types/methods/organizations.d.ts.map +1 -0
  292. package/types/methods/passkeys.d.ts +19 -0
  293. package/types/methods/passkeys.d.ts.map +1 -0
  294. package/types/methods/password.d.ts +17 -0
  295. package/types/methods/password.d.ts.map +1 -0
  296. package/types/methods/sessions.d.ts +9 -0
  297. package/types/methods/sessions.d.ts.map +1 -0
  298. package/types/methods/tokens.d.ts +11 -0
  299. package/types/methods/tokens.d.ts.map +1 -0
  300. package/types/methods/twoFactor.d.ts +20 -0
  301. package/types/methods/twoFactor.d.ts.map +1 -0
  302. package/types/oauth/client.d.ts +39 -0
  303. package/types/oauth/client.d.ts.map +1 -0
  304. package/types/oauth/flow.d.ts +38 -0
  305. package/types/oauth/flow.d.ts.map +1 -0
  306. package/types/oauth/index.d.ts +6 -0
  307. package/types/oauth/index.d.ts.map +1 -0
  308. package/types/oauth/pkce.d.ts +10 -0
  309. package/types/oauth/pkce.d.ts.map +1 -0
  310. package/types/oauth/providers.d.ts +100 -0
  311. package/types/oauth/providers.d.ts.map +1 -0
  312. package/types/oauth/refresher.d.ts +55 -0
  313. package/types/oauth/refresher.d.ts.map +1 -0
  314. package/types/oauth/timeout.d.ts +2 -0
  315. package/types/oauth/timeout.d.ts.map +1 -0
  316. package/types/oauth/types.d.ts +75 -0
  317. package/types/oauth/types.d.ts.map +1 -0
  318. package/types/oauthTest.d.ts +23 -0
  319. package/types/oauthTest.d.ts.map +1 -0
  320. package/types/organizations.d.ts +111 -0
  321. package/types/organizations.d.ts.map +1 -0
  322. package/types/organizationsCore.d.ts +29 -0
  323. package/types/organizationsCore.d.ts.map +1 -0
  324. package/types/own.d.ts +55 -0
  325. package/types/own.d.ts.map +1 -0
  326. package/types/pages/english.d.ts +80 -0
  327. package/types/pages/english.d.ts.map +1 -0
  328. package/types/pages/forms.d.ts +204 -0
  329. package/types/pages/forms.d.ts.map +1 -0
  330. package/types/pages/index.d.ts +166 -0
  331. package/types/pages/index.d.ts.map +1 -0
  332. package/types/pages/organizationPage.d.ts +7 -0
  333. package/types/pages/organizationPage.d.ts.map +1 -0
  334. package/types/pages/routes/account/_guard.d.ts +3 -0
  335. package/types/pages/routes/account/_guard.d.ts.map +1 -0
  336. package/types/pages/routes/account/organizations/_guard.d.ts +3 -0
  337. package/types/pages/routes/account/organizations/_guard.d.ts.map +1 -0
  338. package/types/passkeys.d.ts +61 -0
  339. package/types/passkeys.d.ts.map +1 -0
  340. package/types/password.d.ts +49 -0
  341. package/types/password.d.ts.map +1 -0
  342. package/types/payloads.d.ts +4 -0
  343. package/types/payloads.d.ts.map +1 -0
  344. package/types/pg.d.ts +303 -0
  345. package/types/pg.d.ts.map +1 -0
  346. package/types/profile.d.ts +11 -0
  347. package/types/profile.d.ts.map +1 -0
  348. package/types/proof.d.ts +33 -0
  349. package/types/proof.d.ts.map +1 -0
  350. package/types/prune.d.ts +5 -0
  351. package/types/prune.d.ts.map +1 -0
  352. package/types/rates.d.ts +15 -0
  353. package/types/rates.d.ts.map +1 -0
  354. package/types/request.d.ts +119 -0
  355. package/types/request.d.ts.map +1 -0
  356. package/types/requiredTwoFactor.d.ts +16 -0
  357. package/types/requiredTwoFactor.d.ts.map +1 -0
  358. package/types/requirement.d.ts +4 -0
  359. package/types/requirement.d.ts.map +1 -0
  360. package/types/roles.d.ts +9 -0
  361. package/types/roles.d.ts.map +1 -0
  362. package/types/routes.d.ts +31 -0
  363. package/types/routes.d.ts.map +1 -0
  364. package/types/rules-check.d.ts +3 -0
  365. package/types/rules-check.d.ts.map +1 -0
  366. package/types/rules.d.ts +38 -0
  367. package/types/rules.d.ts.map +1 -0
  368. package/types/securityNotice.d.ts +7 -0
  369. package/types/securityNotice.d.ts.map +1 -0
  370. package/types/sessions.d.ts +32 -0
  371. package/types/sessions.d.ts.map +1 -0
  372. package/types/setup.d.ts +18 -0
  373. package/types/setup.d.ts.map +1 -0
  374. package/types/signInOptions.d.ts +6 -0
  375. package/types/signInOptions.d.ts.map +1 -0
  376. package/types/state.d.ts +25 -0
  377. package/types/state.d.ts.map +1 -0
  378. package/types/store.d.ts +295 -0
  379. package/types/store.d.ts.map +1 -0
  380. package/types/storeHelpers.d.ts +4 -0
  381. package/types/storeHelpers.d.ts.map +1 -0
  382. package/types/test.d.ts +21 -0
  383. package/types/test.d.ts.map +1 -0
  384. package/types/testCookies.d.ts +3 -0
  385. package/types/testCookies.d.ts.map +1 -0
  386. package/types/testHelpers.d.ts +34 -0
  387. package/types/testHelpers.d.ts.map +1 -0
  388. package/types/testing.d.ts +12 -0
  389. package/types/testing.d.ts.map +1 -0
  390. package/types/text.d.ts +2 -0
  391. package/types/text.d.ts.map +1 -0
  392. package/types/totp.d.ts +12 -0
  393. package/types/totp.d.ts.map +1 -0
  394. package/types/twoFactor.d.ts +41 -0
  395. package/types/twoFactor.d.ts.map +1 -0
  396. package/types/types.d.ts +17 -0
  397. package/types/types.d.ts.map +1 -0
  398. package/types/userData.d.ts +9 -0
  399. package/types/userData.d.ts.map +1 -0
  400. package/types/viewer.d.ts +23 -0
  401. package/types/viewer.d.ts.map +1 -0
  402. package/types/wayIn.d.ts +12 -0
  403. package/types/wayIn.d.ts.map +1 -0
  404. package/types/webauthn.d.ts +111 -0
  405. package/types/webauthn.d.ts.map +1 -0
  406. package/types/wsAuth.d.ts +14 -0
  407. package/types/wsAuth.d.ts.map +1 -0
package/llms.txt ADDED
@@ -0,0 +1,28 @@
1
+ # kayjs-auth
2
+
3
+ > Auth for kay apps, built on kay's `session()`: OAuth sign-in with any provider, passwords, mailed links (email verification, password reset, magic links, email change), TOTP two-factor with recovery codes, bearer tokens for devices and API clients, security mails, a proof-of-work CAPTCHA or a third party's, a breached-password check, a fail-closed gate for routes, and prebuilt sign-in and account pages. It works in kay pages, actions and guards, and in a plain Elysia app. Its data lives in a store: in memory for tests, in Postgres or SQLite through pg-orm, or in any object keeping the store contract.
4
+
5
+ Setup, three ways: `auth()` runs with no argument (hooks from `src/auth.ts`, mail from `src/mail.ts`, a SQLite store), `auth({ oauth, roles, ... })` takes the options of `authCore` inline, and `auth({ module: './src/auth' })` mounts a `createAuth` result of your own; `auth({ server: false })` is the escape for an app mounting the plugin by hand.
6
+
7
+ ## Topics
8
+
9
+ `bunx kay docs <words>` prints the section of these files or kay's that matches.
10
+
11
+ The rest is split by topic, each file read whole with one command:
12
+
13
+ - [Setup, pages and the signed-in user](llms/setup.md): `auth()`, the prebuilt pages and the signed-in user
14
+ - [Grouped methods](llms/grouped-methods.md): the methods under `auth.password`, `auth.admin`, `auth.organizations` and the other features, and the flat names they replaced
15
+ - [Sessions and guards](llms/sessions-and-guards.md): a user's sessions, guards and gates
16
+ - [OAuth sign-in, two-factor, passkeys, re-proof and the account](llms/oauth-passkeys-two-factor.md): OAuth providers, two-factor, passkeys, re-proof and the account
17
+ - [OAuth provider presets](llms/oauth-providers.md): github, discord, google, microsoft, gitlab, apple, linkedin, facebook, twitch, slack and x, their options and credentials
18
+ - [Passwords, guests, mailed links and security mails](llms/passwords-and-mails.md): passwords, guests, verification, reset and magic links, security mails
19
+ - [The OAuth server for MCP clients, bearer tokens and forward auth](llms/oauth-server-and-tokens.md): signing an AI agent in, bearer tokens, guarding other sites for a reverse proxy
20
+ - [Events, the audit log, admin and organizations](llms/admin-and-organizations.md): auth events, the audit log, admin methods, organizations and roles
21
+ - [The prebuilt admin pages](llms/admin-pages.md): users, roles, bans, impersonation, the audit log and the banner
22
+ - [The prebuilt organization pages](llms/organization-pages.md): the account tab for organizations, members, roles and invitations, and the invitation page
23
+ - [Bots, breached passwords, limits, stores, testing and the dev tool](llms/hardening-and-testing.md): proof of work, breached passwords, limits, stores, testing, the dev tool
24
+ - [The signed-in user in templates](llms/signed-in-components.md): SignedIn, SignedOut, UserMenu and ImpersonationBanner, read in the first bytes of the pages using them
25
+
26
+ ## Environment
27
+
28
+ The database url is `AUTH_DATABASE_URL`; an OAuth provider keeps its own name, `<PROVIDER>_CLIENT_ID` and `<PROVIDER>_CLIENT_SECRET`.
package/package.json CHANGED
@@ -1,6 +1,87 @@
1
1
  {
2
2
  "name": "@kayjs/auth",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "type": "module",
4
+ "version": "1.104.1",
5
+ "description": "Auth for kay apps on kay sessions: OAuth, passwords, two-factor, magic links and bearer tokens",
6
+ "author": "Kaynooo <https://github.com/Kayno0o>",
7
+ "license": "MIT",
8
+ "repository": {
9
+ "type": "git",
10
+ "url": "https://github.com/Kayno0o/kayjs",
11
+ "directory": "packages/auth"
12
+ },
13
+ "bugs": {
14
+ "url": "https://github.com/Kayno0o/kayjs/issues"
15
+ },
16
+ "exports": {
17
+ ".": {
18
+ "types": "./types/index.d.ts",
19
+ "default": "./src/index.ts"
20
+ },
21
+ "./add": "./src/add.ts",
22
+ "./browser": {
23
+ "types": "./types/browser.d.ts",
24
+ "default": "./src/browser.ts"
25
+ },
26
+ "./test": "./src/test.ts",
27
+ "./rules": {
28
+ "types": "./types/rules.d.ts",
29
+ "default": "./src/rules.ts"
30
+ },
31
+ "./components/*.kay": "./src/components/*.kay",
32
+ "./pages/*.kay": "./src/pages/routes/*.kay",
33
+ "./pg": {
34
+ "types": "./types/pg.d.ts",
35
+ "default": "./src/pg.ts"
36
+ }
37
+ },
38
+ "files": [
39
+ "LICENSE",
40
+ "README.md",
41
+ "llms",
42
+ "llms.txt",
43
+ "src",
44
+ "types"
45
+ ],
46
+ "kay": {
47
+ "messages": "./src/messages"
48
+ },
49
+ "engines": {
50
+ "bun": ">=1.4.4"
51
+ },
52
+ "scripts": {
53
+ "check": "$npm_execpath check && $npm_execpath ../../src/cli.ts check tests/fixture",
54
+ "build:types": "rm -rf types && $npm_execpath ../../src/tsgo.ts -p tsconfig.build.json",
55
+ "prepack": "$npm_execpath run build:types && $npm_execpath ../../scripts/pack-links.ts rewrite ../..",
56
+ "postpack": "rm -rf types && $npm_execpath ../../scripts/pack-links.ts restore ../..",
57
+ "prelint": "$npm_execpath run --cwd ../.. build:eslint",
58
+ "lint": "$npm_execpath ../../scripts/lint-cache.ts && keslint --cache",
59
+ "prelint:fix": "$npm_execpath run --cwd ../.. build:eslint",
60
+ "lint:fix": "$npm_execpath ../../scripts/lint-cache.ts && keslint --fix --cache",
61
+ "test": "$npm_execpath test --parallel=6 --timeout 20000 --path-ignore-patterns='**/{pgStore,lastOne,sharedDatabase}.test.ts' && $npm_execpath test --isolate --timeout 20000 pgStore.test lastOne.test sharedDatabase.test"
62
+ },
63
+ "peerDependencies": {
64
+ "@kayjs/ui": "~1.104.1",
65
+ "@kaynooo/pg-orm": "^7.1.2 || ^8.0.0",
66
+ "elysia": "^1.4.31",
67
+ "kay": "~1.104.0"
68
+ },
69
+ "peerDependenciesMeta": {
70
+ "@kaynooo/pg-orm": {
71
+ "optional": true
72
+ }
73
+ },
74
+ "dependencies": {
75
+ "@kaynooo/utils": "^3.1.0",
76
+ "jose": "^6.2.13"
77
+ },
78
+ "devDependencies": {
79
+ "@kayjs/mail": "~1.104.1",
80
+ "@kayjs/ui": "~1.104.1",
81
+ "@kaynooo/eslint": "^7.1.6",
82
+ "@kaynooo/pg-orm": "^8.1.4",
83
+ "@types/bun": "^1.4.4",
84
+ "elysia": "^1.4.31",
85
+ "typescript": "^6.0.3"
86
+ }
87
+ }
package/src/access.ts ADDED
@@ -0,0 +1,31 @@
1
+ import type { BareUser } from './core'
2
+ import type { RoleHierarchy } from './roles'
3
+ import type { Level, PolicyContext, Predicate, Requirement } from './types'
4
+ import { meetsRequirement } from './requirement'
5
+ import { roleHierarchy } from './roles'
6
+
7
+ // What decides whether a user meets a requirement, settled from the `roles` and `authorize` options when the core is made.
8
+ export interface Access<Role extends string> {
9
+ hasRole: (required: Role) => Predicate<BareUser>
10
+ isGranted: (role: Role, roles: string[]) => boolean
11
+ authorize: (user: BareUser | null, requirement: Requirement<BareUser, Role>, level: Level, ctx: PolicyContext) => Promise<boolean>
12
+ }
13
+
14
+ export function accessOf<Role extends string>(options: { roles?: Record<Role, Role[]> | undefined, authorize?: Access<Role>['authorize'] | undefined }): Access<Role> {
15
+ const { hasRole, isGranted } = roleHierarchy<BareUser, Role>(options.roles ?? {} as RoleHierarchy<Role>, user => user.roles as Role[])
16
+
17
+ // The default decision reads a string as a role and runs a predicate.
18
+ const evaluate = async (user: BareUser, requirement: Requirement<BareUser, Role>, ctx: PolicyContext): Promise<boolean> => meetsRequirement(user, requirement, ctx, (grant) => {
19
+ if (typeof grant === 'string')
20
+ return isGranted(grant, user.roles)
21
+
22
+ // A grant on one record needs the app's own `authorize`.
23
+ return grant.resourceId == null && isGranted(grant.type, user.roles)
24
+ })
25
+
26
+ return {
27
+ hasRole,
28
+ isGranted: (role, roles) => isGranted(role, roles),
29
+ authorize: options.authorize ?? (async (user, requirement, _level, ctx) => user !== null && evaluate(user, requirement, ctx)),
30
+ }
31
+ }
package/src/account.ts ADDED
@@ -0,0 +1,198 @@
1
+ import type { BareUser } from './core'
2
+ import type { AuthFailed, AuthRejected } from './failure'
3
+ import type { Proof, ProofFailure } from './proof'
4
+ import type { PasswordProblem, UsernameProblem } from './rules'
5
+ import type { RequestState } from './state'
6
+ import type { UserRecord } from './store'
7
+ import { hashPassword } from '@kaynooo/utils'
8
+ import { newPasswordProblem } from './breached'
9
+ import { publicUser } from './core'
10
+ import { eraseLeavingUser, soleOwned } from './erase'
11
+ import { failed, rejected } from './failure'
12
+ import { validLocale } from './locale'
13
+ import { reprove } from './proof'
14
+ import { normalizeUsername, usernameProblem } from './rules'
15
+ import { securityNotice } from './securityNotice'
16
+ import { endOtherSessions } from './sessions'
17
+ import { hasWayIn, putBack } from './wayIn'
18
+
19
+ // Nothing to put back when no admin feature stepped aside.
20
+ const NO_ASIDE = { restore: async () => {
21
+ await Promise.resolve()
22
+ } }
23
+
24
+ export type ChangePasswordResult = { ok: true } | AuthFailed<ProofFailure> | AuthRejected<{ password: PasswordProblem | 'breached' }>
25
+
26
+ // Sets the signed-in user's password, or a first one, and ends their other sessions.
27
+ export async function changePassword(state: RequestState, proof: Proof, password: string): Promise<ChangePasswordResult> {
28
+ const problem = await newPasswordProblem(state.core, password)
29
+
30
+ if (problem !== undefined)
31
+ return rejected({ password: problem })
32
+
33
+ const proved = await reprove(state, proof)
34
+
35
+ if (!proved.ok)
36
+ return proved
37
+
38
+ const updated = await endOtherSessions(state, proved.record, { passwordHash: await hashPassword(password) })
39
+
40
+ if (updated) {
41
+ // Links mailed before, a reset among them, no longer outrank the password just set.
42
+ await state.core.store.tokens.erase(updated.id)
43
+ await securityNotice(state, updated, 'password-changed')
44
+ }
45
+
46
+ return { ok: true }
47
+ }
48
+
49
+ export type UpdateLocaleResult = { ok: true } | AuthFailed<'signed-out' | 'invalid-locale'>
50
+
51
+ // Sets the language the signed-in user's mails are written in, a BCP 47 tag such as `fr`.
52
+ export async function updateLocale(state: RequestState, locale: string): Promise<UpdateLocaleResult> {
53
+ const record = await state.current()
54
+
55
+ if (!record)
56
+ return failed('signed-out')
57
+
58
+ if (!validLocale(locale))
59
+ return failed('invalid-locale')
60
+
61
+ state.adopt(await state.core.store.users.update(record.id, { locale }) ?? { ...record, locale })
62
+
63
+ return { ok: true }
64
+ }
65
+
66
+ export type ChangeUsernameResult = { ok: true, user: BareUser } | AuthFailed<'signed-out'> | AuthRejected<{ username: UsernameProblem | 'taken' | 'unchanged' }>
67
+
68
+ // Names the signed-in user, or renames them, under the rules register checks. A name is no credential, so it takes no proof and sends no mail; a session is needed all the same, so a device's token cannot rename the account it was given for.
69
+ export async function changeUsername(state: RequestState, username: string): Promise<ChangeUsernameResult> {
70
+ const record = await state.current()
71
+
72
+ if (!record || state.via() !== 'session')
73
+ return failed('signed-out')
74
+
75
+ const name = normalizeUsername(username)
76
+ const problem = usernameProblem(name, state.core.rules)
77
+
78
+ if (problem)
79
+ return rejected({ username: problem })
80
+
81
+ if (name === record.username)
82
+ return rejected({ username: 'unchanged' })
83
+
84
+ const holder = await state.core.store.users.findByUsername(name)
85
+
86
+ // The user's own name in another case is theirs to recase.
87
+ if (holder && holder.id !== record.id)
88
+ return rejected({ username: 'taken' })
89
+
90
+ let updated: UserRecord | undefined
91
+
92
+ try {
93
+ updated = await state.core.store.users.update(record.id, { username: name })
94
+ }
95
+ // Another request took the name in between; any other failure is the store's.
96
+ catch (error) {
97
+ const taker = await state.core.store.users.findByUsername(name)
98
+
99
+ if (taker && taker.id !== record.id)
100
+ return rejected({ username: 'taken' })
101
+
102
+ throw error
103
+ }
104
+
105
+ if (!updated)
106
+ return failed('signed-out')
107
+
108
+ await state.renew(updated)
109
+
110
+ return { ok: true, user: publicUser(updated) }
111
+ }
112
+
113
+ export type UnlinkResult = { ok: true } | AuthFailed<ProofFailure | 'not-linked' | 'last-way-in'>
114
+
115
+ // Unlinks a provider from the signed-in user, unless it is their last way in, and ends their other sessions.
116
+ export async function unlink(state: RequestState, provider: string, proof: Proof): Promise<UnlinkResult> {
117
+ const proved = await reprove(state, proof)
118
+
119
+ if (!proved.ok)
120
+ return proved
121
+
122
+ const { record } = proved
123
+ const identities = await state.core.store.identities.listByUser(record.id)
124
+ const identity = identities.find(entry => entry.provider === provider)
125
+
126
+ if (!identity)
127
+ return failed('not-linked')
128
+
129
+ if (!await hasWayIn(state.core, record.id, { identity }))
130
+ return failed('last-way-in')
131
+
132
+ await state.core.store.identities.delete(identity.provider, identity.providerId)
133
+
134
+ // Two requests can each see the other way in still there: when none is left, the identity goes back.
135
+ if (!await hasWayIn(state.core, record.id)) {
136
+ await putBack(state.core, record.id, async () => state.core.store.identities.create(identity))
137
+
138
+ return failed('last-way-in')
139
+ }
140
+
141
+ await (await import('./oauth/flow')).revokeUpstream(state.core, identity)
142
+ await endOtherSessions(state, record)
143
+ await securityNotice(state, record, 'provider-unlinked', provider)
144
+
145
+ return { ok: true }
146
+ }
147
+
148
+ // `deleteAt` is set with `account.deleteAfter`: the account is pending until then and the session stays signed in, so the user can cancel.
149
+ export type DeleteAccountResult = { ok: true, deleteAt?: Date } | AuthFailed<ProofFailure | 'last-admin' | 'last-owner' | 'refused'>
150
+
151
+ // Deletes the signed-in user and everything kayjs-auth keeps for them, then signs this session out. The last admin, and the only owner of an organization with other members, are refused before the proof is spent; an organization the user is alone in is deleted with them. With `account.deleteAfter` it only marks the account pending: the prune deletes it, `beforeDelete` and the notices included, once the period ends.
152
+ export async function deleteAccount(state: RequestState, proof: Proof, signOut: () => Promise<void>): Promise<DeleteAccountResult> {
153
+ const current = await state.current()
154
+ // Without the `admin` option nobody is an admin: no last one to keep and no roles to set aside.
155
+ const admins = state.core.admin ? await import('./admin') : undefined
156
+
157
+ if (current && admins && await admins.lastAdmin(state, current))
158
+ return failed('last-admin')
159
+
160
+ if (current && (await soleOwned(state.core, current)).some(organization => !organization.alone))
161
+ return failed('last-owner')
162
+
163
+ const proved = await reprove(state, proof)
164
+
165
+ if (!proved.ok)
166
+ return proved
167
+
168
+ if (state.core.deletion)
169
+ return (await import('./deletion')).scheduleDeletion(state, proved.record)
170
+
171
+ const aside = admins
172
+ ? await admins.stepAside(state, proved.record)
173
+ : NO_ASIDE
174
+
175
+ if (!aside)
176
+ return failed('last-admin')
177
+
178
+ let erased: Awaited<ReturnType<typeof eraseLeavingUser>>
179
+
180
+ try {
181
+ erased = await eraseLeavingUser(state, proved.record)
182
+ }
183
+ catch (error) {
184
+ await aside.restore()
185
+
186
+ throw error
187
+ }
188
+
189
+ if (!erased.ok) {
190
+ await aside.restore()
191
+
192
+ return erased
193
+ }
194
+
195
+ await signOut()
196
+
197
+ return { ok: true }
198
+ }
package/src/add.ts ADDED
@@ -0,0 +1,70 @@
1
+ interface Project {
2
+ name: string
3
+ exists: (path: string) => boolean
4
+ read: (path: string) => string | undefined
5
+ depends: (name: string) => boolean
6
+ }
7
+
8
+ const NAME_TAIL = /[^\p{L}\p{N}]+/u
9
+ const SCOPE = /^@[^/]+\//
10
+ const TABLES = /(export const tables = \[)(\s*)(\]?)/
11
+
12
+ // Puts authTables first in the list: alone in an empty one, on a line of its own in a multi-line one, ahead of the others otherwise.
13
+ function withAuthTables(_match: string, open: string, space: string, close: string): string {
14
+ if (close !== '')
15
+ return `${open}...authTables${close}`
16
+
17
+ return space.includes('\n') ? `${open}${space}...authTables,${space}` : `${open}${space}...authTables, `
18
+ }
19
+
20
+ // The site's name for mails and authenticator apps, from the package name.
21
+ function siteName(name: string): string {
22
+ const words = name.replace(SCOPE, '').split(NAME_TAIL).filter(word => word !== '')
23
+
24
+ return words.map(word => word[0]!.toUpperCase() + word.slice(1)).join(' ') || 'My site'
25
+ }
26
+
27
+ // What `kay add auth` writes: `auth({ ... })` in kay.config.ts, which builds everything else, and a guard on the whole site. A project with a pg-orm `Database` of its own keeps the users there, through a `store` function loading it as the server starts; any other keeps them in a SQLite file.
28
+ export default function auth(project: Project) {
29
+ const ownDatabase = project.exists('src/db/index.ts') && project.depends('@kaynooo/pg-orm') && project.read('src/db/index.ts')?.includes('export const db') === true
30
+ // A project kay new scaffolded keeps the tables apart from `db`, so pg-orm.config.ts reads them without building `db`.
31
+ const tablesFile = project.read('src/db/tables.ts')?.includes('export const tables') === true ? 'src/db/tables.ts' : 'src/db/index.ts'
32
+ const mailModule = project.exists('src/mail.ts') && project.read('src/mail.ts')?.includes('export const mail') === true
33
+ const mailDepended = project.depends('@kayjs/mail')
34
+ const mailed = mailModule || (mailDepended && project.read('kay.config.ts')?.includes('mail(') === true)
35
+
36
+ return {
37
+ description: 'sign-in, register and account pages on kay sessions, with passwords, magic links, OAuth and two-factor, and every page behind a signed-in user',
38
+ files: {
39
+ 'src/routes/_guard.ts': authGuard(),
40
+ },
41
+ edits: ownDatabase
42
+ ? [{ file: tablesFile, find: TABLES, replace: withAuthTables, done: '...authTables', import: 'import { authTables } from \'@kayjs/auth/pg\'' }]
43
+ : [],
44
+ example: authExample(ownDatabase),
45
+ ignore: ownDatabase ? [] : ['data'],
46
+ extension: { import: 'import { auth } from \'@kayjs/auth\'', expression: authCall(siteName(project.name), ownDatabase) },
47
+ notes: [
48
+ ownDatabase ? 'Run your migration generator (bun run db:generate) for the kay_* tables kayjs-auth added to the tables.' : 'kayjs-auth keeps its users in data/auth.sqlite: set AUTH_DATABASE_URL (a Postgres url) before production.',
49
+ ...mailed ? [] : [mailDepended ? 'Without a mailer, password resets, magic links and verification mails cannot be sent: add mail() to the extensions of kay.config.ts, and auth() sends through it.' : 'Without a mailer, password resets, magic links and verification mails cannot be sent: run `kay add mail`, and auth() sends through it.'],
50
+ 'Set KAY_SECRET and SITE_URL in production.',
51
+ ],
52
+ }
53
+ }
54
+
55
+ // The `.env.example` keys: the session secret and the site's address, and the database url of the SQLite default.
56
+ function authExample(ownDatabase: boolean): string[] {
57
+ return ['KAY_SECRET', 'SITE_URL', ...ownDatabase ? [] : ['AUTH_DATABASE_URL']]
58
+ }
59
+
60
+ // The `auth()` of kay.config.ts: the name mails and authenticator apps show, and over the app's own database a store loading it as the server starts, so the config stays off the database.
61
+ function authCall(name: string, ownDatabase: boolean): string {
62
+ const store = ownDatabase ? ', store: async () => (await import(\'@kayjs/auth/pg\')).pgAuth((await import(\'./src/db\')).db)' : ''
63
+
64
+ return `auth({ name: '${name}'${store} })`
65
+ }
66
+
67
+ // The root guard: every page below needs a signed-in visitor; the sign-in and register pages stay open.
68
+ function authGuard(): string {
69
+ return 'import { authGuard } from \'@kayjs/auth\'\n\n// Every page below needs a signed-in visitor; the sign-in and register pages stay open. Delete this file for a public site, or move it into the folder to protect.\nexport default authGuard()\n'
70
+ }
package/src/address.ts ADDED
@@ -0,0 +1,51 @@
1
+ import { isIP } from 'node:net'
2
+
3
+ // An address cut to the network it belongs to, an IPv4 one to its /24 (`203.0.113.0`) and an IPv6 one to its /48 (`2001:db8:1::`): enough to tell where a sign-in came from, not who. Anything else is returned as it is.
4
+ export function truncatedAddress(address: string): string {
5
+ const family = isIP(address)
6
+
7
+ if (family === 4) {
8
+ const [a, b, c] = address.split('.')
9
+
10
+ return `${a}.${b}.${c}.0`
11
+ }
12
+
13
+ const bytes = family === 6 ? v6Bytes(address) : undefined
14
+
15
+ if (!bytes)
16
+ return address
17
+
18
+ // IPv4 inside IPv6 (::ffff:203.0.113.7) is the IPv4 host's own.
19
+ if (bytes.slice(0, 10).every(byte => byte === 0) && bytes[10] === 0xFF && bytes[11] === 0xFF)
20
+ return truncatedAddress(bytes.slice(12).join('.'))
21
+
22
+ const group = (index: number) => ((bytes[index]! << 8) | bytes[index + 1]!).toString(16)
23
+
24
+ return `${group(0)}:${group(2)}:${group(4)}::`
25
+ }
26
+
27
+ // The 16 bytes of an IPv6 address, an embedded dotted IPv4 tail included.
28
+ function v6Bytes(address: string): number[] | undefined {
29
+ let text = address.toLowerCase()
30
+ const zone = text.indexOf('%')
31
+
32
+ if (zone !== -1)
33
+ text = text.slice(0, zone)
34
+
35
+ const dotted = !text.includes('.') ? undefined : text.slice(text.lastIndexOf(':') + 1).split('.').map(Number)
36
+
37
+ if (dotted)
38
+ text = `${text.slice(0, text.lastIndexOf(':') + 1)}${((dotted[0]! << 8) | dotted[1]!).toString(16)}:${((dotted[2]! << 8) | dotted[3]!).toString(16)}`
39
+
40
+ const halves = text.split('::')
41
+
42
+ if (halves.length > 2)
43
+ return undefined
44
+
45
+ const groups = (part: string) => part === '' ? [] : part.split(':').map(group => Number.parseInt(group, 16))
46
+ const head = groups(halves[0]!)
47
+ const tail = halves.length === 2 ? groups(halves[1]!) : []
48
+ const all = halves.length === 2 ? [...head, ...Array.from<number>({ length: Math.max(0, 8 - head.length - tail.length) }).fill(0), ...tail] : head
49
+
50
+ return all.length === 8 && all.every(group => Number.isInteger(group) && group >= 0 && group <= 0xFFFF) ? all.flatMap(group => [group >> 8, group & 0xFF]) : undefined
51
+ }