@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/src/auth.ts ADDED
@@ -0,0 +1,219 @@
1
+ import type { DefinitionBase, EphemeralType, MetadataBase, RouteBase, SingletonBase } from 'elysia'
2
+ import type { Duration, Guard, Schema } from 'kay'
3
+ import type { KayConfig, Session } from 'kay/server'
4
+ import type { Access } from './access'
5
+ import type { IssueTokenResult, TokenOptions } from './bearer'
6
+ import type { CaptchaOptions } from './captcha'
7
+ import type { AuthSessionData, BareUser, OAuthApp, Profile, User } from './core'
8
+ import type { AccountOptions } from './deletion'
9
+ import type { EmailOptions } from './email'
10
+ import type { AuthEventInfo, AuthHookContext } from './events'
11
+ import type { ForwardAuthOptions, ForwardDomains } from './forwardAuth'
12
+ import type { ScopeRequirement } from './gate'
13
+ import type { RouteGuardOptions } from './guards'
14
+ import type { LimitsOption } from './limits'
15
+ import type { OrganizationsOptions } from './organizations'
16
+ import type { AuthPagesConfig } from './pages'
17
+ import type { CreateUserInput, CreateUserResult } from './password'
18
+ import type { AuthRequirement } from './request'
19
+ import type { CredentialRules } from './rules'
20
+ import type { AuthStore } from './store'
21
+ import type { Level, PolicyContext } from './types'
22
+ import { Elysia } from 'elysia'
23
+ import { kayPlugin, requestOfContext } from 'kay/library'
24
+ import { banned, linkedUser } from './core'
25
+ import { gateOf, guardOf, memberOf } from './guards'
26
+ import { load } from './load'
27
+ import { AUTH_OF, CHECK_USER, PAGES_OF } from './pages'
28
+ import { requestAuth, socketUser } from './request'
29
+ import { callbackRoute, cancelDeletionRoute, exportRoute, formPostRoute, sendCookies, serveUntypedRoutes, signOutRoute, startOAuthRoute, stopImpersonatingRoute } from './routes'
30
+ import { createCore, pagesHandle } from './setup'
31
+ import { testHelpers } from './testHelpers'
32
+ import { readRequestWith } from './viewer'
33
+
34
+ export type { AuthSessionData, BareUser, OAuthApp, Off, Profile, User } from './core'
35
+ export { Auth, SIGNED_IN_HINT } from './request'
36
+ export type { AuthRequirement, RequireUserOptions } from './request'
37
+
38
+ // The plugin kay's `session()` returns, whichever data the app keeps beside kayjs-auth's.
39
+ export interface SessionPlugin<Data extends AuthSessionData> {
40
+ '~Ephemeral': { derive: { readonly session: Session<Data> } }
41
+ // A key for one purpose from each of the session's secrets, in their order.
42
+ 'deriveSecret'?: (purpose: string) => string[]
43
+ // Tells the plugin kayjs-auth ends sessions itself, so it does not warn that a cookie with no store cannot be revoked.
44
+ 'endsSessionsElsewhere'?: () => void
45
+ // Names the domains `forwardAuth` shares the session under, which the cookie takes when the visited host is on one and the session names no `domain`.
46
+ 'sharesUnder'?: (domains: string[]) => void
47
+ }
48
+
49
+ export interface AuthOptions<Data extends AuthSessionData, Role extends string, Prefix extends string = '/auth', Scope extends string = never, OrgRole extends string = never, UserData extends object = Record<string, never>> {
50
+ sessions: SessionPlugin<Data>
51
+ // At least 32 characters, from the environment; each use gets its own key derived from it. A list rotates them: the first writes, every one reads. Left out, kayjs-auth derives its own from the session's secret, so one secret serves both.
52
+ secret?: string | string[] | undefined
53
+ store: AuthStore
54
+ // The site's public origin, such as `https://example.com`, which OAuth callbacks, mailed links and passkeys are built on: the `site` of kay.config.ts (or SITE_URL) when left out, so an app on kay sets it once.
55
+ site?: string | undefined
56
+ // Where kayjs-auth's routes live, `/auth` by default: `/auth/discord` starts a Discord sign-in.
57
+ prefix?: Prefix | undefined
58
+ // The site's name, as mails and authenticator apps show it; the origin's host by default.
59
+ name?: string | undefined
60
+ // Where a sign-in that failed goes, with `?error=` saying why; the prebuilt sign-in page with `pages`, else `/`. Without `pages`, it is also where `guard()` and `requireUser()` send an anonymous visitor opening a page.
61
+ signInPage?: string | undefined
62
+ // 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, as with an `allow` list.
63
+ failurePage?: string | undefined
64
+ // Where a sign-in goes to ask for the second factor, `/two-factor` by default: a page whose form posts the code to an action calling `twoFactor.verify`.
65
+ twoFactorPage?: string | undefined
66
+ // The prebuilt pages, `auth()` as kay.config.ts lists it or `true` for its defaults: the sign-in, two-factor and sessions pages and the mailed links default to them.
67
+ pages?: boolean | AuthPagesConfig | undefined
68
+ // Mail for email verification, password resets, magic links and email changes.
69
+ email?: EmailOptions | undefined
70
+ // OAuth apps by the name their routes take: `{ discord: { provider: discordProvider(), clientId, clientSecret } }`.
71
+ oauth?: Record<string, OAuthApp> | undefined
72
+ // Asked with every provider account before any user is touched; false refuses the sign-in, as an allowlist does.
73
+ allow?: ((profile: Profile) => boolean | Promise<boolean>) | undefined
74
+ // Whether visitors make their own accounts, by registering, as a guest or with a provider account no user has linked: on by default, `false` closes it. Then registering and `signInAsGuest` answer `{ ok: false, error: { code: 'off' } }`, users come from `auth.admin.createUser` alone, and the prebuilt pages offer no registering. `true` is not accepted, it is the default.
75
+ signUp?: false | undefined
76
+ // Called once a new user exists, to create the app's own records for them. It gets one object: `user`, the provider's `profile` for a sign-up by a provider account, and `context`. A throw is logged and reported to the app's `onError` with source `auth.onSignUp`, and never fails the sign-up.
77
+ onSignUp?: ((event: { user: User, profile: Profile | undefined, context: AuthHookContext }) => unknown) | undefined
78
+ // Called with the provider's profile whenever one answers for a user: every OAuth sign-in, the first included after `onSignUp`, and a link.
79
+ // What the app keeps on each user, an object schema such as `s.Object({ avatar: s.Optional(s.String()) })`: `auth.user()` returns it typed as `data`, `profileFields` fills it, and a store keeps it as JSON.
80
+ user?: (Schema & { static: UserData }) | undefined
81
+ // Called on every provider sign-in, the first and a link included, with `{ user, profile }`: the user as the app has them and the provider's profile. It runs before any second factor. What it returns is laid over `user().data`, only the fields `user` declares, and kept when the result fits the schema; return nothing to keep what is there, such as an avatar.
82
+ profileFields?: ((event: { user: User<UserData>, profile: Profile }) => { [Field in keyof UserData]?: UserData[Field] | undefined } | void | Promise<{ [Field in keyof UserData]?: UserData[Field] | undefined } | void>) | undefined
83
+ // Called before a user is deleted, with `{ user, context }`, to delete the app's own records for them or to keep the account: `false`, or throwing `refuse(message)`, refuses, and `account.delete` and `admin.deleteUser` answer `{ ok: false, error: { code: 'refused', status, message } }`. A throw of any other kind refuses with 500 and is reported with source `auth.beforeDelete`. An account no one asked to delete, a stale guest or unverified one, stays and is tried again the next run.
84
+ beforeDelete?: ((event: { user: User, context: AuthHookContext }) => void | false | Promise<void | false>) | undefined
85
+
86
+ // Deletes a guest whose account is older than `maxAge` (a string such as '30d') and who has no session left, calling `beforeDelete` as for any user; 30 days by default.
87
+ guests?: { maxAge: Duration } | undefined
88
+ // How `account.delete` behaves: `deleteAfter` (a string such as '14d') marks the account pending instead of deleting it, mails a link to cancel, and leaves the deletion to the prune once the period ends, `beforeDelete`, the audit log and the mails following the real deletion; `cancelPage` is the page that link opens, the prebuilt account data page by default. Without `deleteAfter` the deletion is immediate. Needs a store with `users.dueForDeletion`, as `memoryAuth` and `pgAuth` have.
89
+ account?: AccountOptions | undefined
90
+ // What the app keeps about a user, added to their `exportData()` as `app`: their posts, their orders. Called with `{ user }`.
91
+ exportData?: ((event: { user: User }) => unknown) | undefined
92
+ // Called with every change to what protects an account, the ones mailed to the user, and with every sign-in, sign-out and failed sign-in of a known account, for an audit log of the app's own. A throw is logged and reported with source `auth.onEvent`. It gets one object: `event`, `user`, `context` (where from, and who acted when not the user), and the fields of its kind, such as the `role` of a `role-granted` or the `method` of a `signed-in`.
93
+ onEvent?: ((info: AuthEventInfo) => unknown) | undefined
94
+
95
+ // Keeps the same events in the store's audit log, for `auditLog()`; `maxAge` a string such as '365d', a year by default. Each entry keeps the address cut to its /24 (IPv4) or /48 (IPv6) unless `ip` is 'full'.
96
+ audit?: boolean | { maxAge?: Duration, ip?: 'full' | 'truncated' } | undefined
97
+ // What a bearer token may be limited to, such as `['posts:read', 'posts:write']`: a route asks for one with `scope:`.
98
+ scopes?: readonly Scope[] | undefined
99
+ // Each role and the roles it includes: `{ admin: ['editor'], editor: [] }`.
100
+ roles?: Record<Role, NoInfer<Role>[]> | undefined
101
+ // Teams or workspaces users belong to, with roles of their own in each: `{ roles: { owner: ['admin'], admin: ['member'], member: [] }, owner: 'owner' }`.
102
+ organizations?: OrganizationsOptions<OrgRole, NoInfer<Role>> | undefined
103
+ // Who may list, ban and impersonate users and grant them roles, such as `'admin'`; nobody without it.
104
+ admin?: AuthRequirement<NoInfer<Role>> | undefined
105
+ // The roles every new user starts with, by password or by provider, such as a site's `user`. An unverified account holding only these counts as given none: see `requireVerified`.
106
+ defaultRoles?: NoInfer<Role>[] | undefined
107
+ // How long a session lives unseen when its sign-in asked to be remembered, `remember: true`: `remember: { maxAge: '90d' }`, 90 days by default. The other lifetimes are the session plugin's own: its `maxAge` without a choice, its `browserMaxAge` for `remember: false`, and its `absoluteMaxAge` from the sign-in however much it is used, "remember me" included.
108
+ remember?: { maxAge?: Duration | undefined } | undefined
109
+ // The password and username rules, over the defaults of 10 to 128 characters and 2 to 32: `{ password: { min: 12, check: p => /\d/.test(p) ? undefined : 'Add a digit.' }, username: { min: 3, max: 16 } }`. The server, the prebuilt pages and `features().rules` all follow them, and an island passes the same object, or `features().rules`, to `passwordProblem` and `usernameProblem` from `@kayjs/auth/rules`.
110
+ rules?: CredentialRules | undefined
111
+ // The app's page listing where the user is signed in, linked from new sign-in mails: `/account/sessions`.
112
+ sessionsPage?: string | undefined
113
+ // The app's page for turning two-factor on, where `twoFactor.require` sends a user lacking it and which it never holds back: the prebuilt account security page by default.
114
+ securityPage?: string | undefined
115
+ // Where an address is, shown beside each session, from a geolocation database of the app's: `ip => cityOf(ip)`.
116
+ locate?: ((ip: string) => string | null | undefined | Promise<string | null | undefined>) | undefined
117
+ // Attempts allowed per client address and per account, over `DEFAULT_LIMITS`: `rateLimit: { signIn: { max: 10, window: '15m' } }`.
118
+ rateLimit?: LimitsOption | undefined
119
+ // Passkeys are made for `site`'s host and its origin; `rpId` widens them to a parent domain, `origins` lists every origin the site's pages are served from, and `rpName` is the name the authenticator shows (`name` by default). `userVerification` is how hard answering a second factor with a passkey asks for a PIN or a biometric, `'preferred'` by default: adding a passkey, signing in with one and re-proving always require it, as a passkey alone is two factors.
120
+ passkeys?: { rpId?: string, origins?: string[], rpName?: string, userVerification?: 'required' | 'preferred' | 'discouraged' } | false | undefined
121
+ // Password sign-in, registering, resets and changes; `false` answers `{ ok: false, error: { code: 'off' } }` from their methods and hides them from the prebuilt pages. On by default, so it takes `false` alone.
122
+ password?: false | undefined
123
+ // Sign-in links and codes mailed to the address (they need `email`); `false` answers `off` from their methods and the pages show none. On by default, so it takes `false` alone.
124
+ magicLink?: false | undefined
125
+ // Authenticator-app two-step verification: `false` answers `off` from setting it up, turning it on and new recovery codes, and the account page offers none. A user who turned it on before is still asked for the code at sign-in. On by default, so it takes `false` or `{ require }`.
126
+ // `{ require }` makes two-factor a must for the users it names (a role, a predicate or a list, as a guard's `require`): their guards and gates, the admin pages and `auth.admin`, and OAuth consent send them to the security page, or answer 403 (`two-factor-required` from `auth.admin`) when they cannot be sent. An app's own security page sits behind `guard({ twoFactor: false })`.
127
+ twoFactor?: false | { require?: AuthRequirement<Role> | undefined } | undefined
128
+ // A CAPTCHA asked of registering, password sign-in, password resets and magic links: kay's proof of work by default, `proofOfWork({ difficulty })` to tune it, `{ verify: turnstile(secret) }` for a third party's, false for none.
129
+ captcha?: CaptchaOptions | false | undefined
130
+ // Refuses a new password Have I Been Pwned lists, with `true`, or that a check of the app's own finds. On by default in production, `false` turns it off; a check that fails lets the password through.
131
+ breachedPasswords?: boolean | ((password: string) => boolean | Promise<boolean>) | undefined
132
+ // The proxies in front, read as kay.config.ts's `proxy` is, for a plain Elysia app that kay's `pages()` does not serve; a kay app sets it in kay.config.ts instead.
133
+ proxy?: KayConfig['proxy'] | undefined
134
+ // MCP clients sign in to the app by OAuth, on by default with `pages` and a store keeping it (`memoryAuth` and `pgAuth` do): kayjs-auth serves the discovery documents, the authorization and token endpoints and the consent page, and the tokens it issues are bearer tokens. `false` turns it off; `fetch` reads the metadata document a client names by its URL, over the public internet only unless the app's own says otherwise.
135
+ oauthServer?: boolean | { fetch?: ((url: string) => Promise<Response>) | undefined, defaultScopes?: readonly Scope[] | undefined } | undefined
136
+ // A route for a reverse proxy to ask before it lets a request through to a site it guards (nginx `auth_request`, Traefik or Caddy forward auth): `${prefix}/forward` answers 204 with `Remote-User`, `Remote-Name`, `Remote-Email` and `Remote-Groups` for a signed-in person's session, or 401 with the sign-in page's URL as `Location`, which returns to the guarded site afterwards when it is on these domains or their subdomains. `requireTwoFactor` also refuses a user who has not set it up.
137
+ forwardAuth?: ForwardDomains | ForwardAuthOptions | undefined
138
+ // Replaces the default decision, which reads a string as a role and runs a predicate; use it with `decide` for grants on single records.
139
+ authorize?: ((user: BareUser | null, requirement: AuthRequirement<Role>, level: Level, ctx: PolicyContext) => Promise<boolean>) | undefined
140
+ }
141
+
142
+ readRequestWith(requestOfContext)
143
+
144
+ // Auth for a kay app or a plain Elysia one, on the app's kay session.
145
+ export function authCore<Data extends AuthSessionData, Role extends string = string, Prefix extends string = '/auth', const Scope extends string = never, OrgRole extends string = never, UserData extends object = Record<string, never>>(options: AuthOptions<Data, Role, Prefix, Scope, OrgRole, UserData>) {
146
+ const core = createCore(options)
147
+ const access = core.access as unknown as Access<Role>
148
+
149
+ options.sessions.endsSessionsElsewhere?.()
150
+
151
+ if (core.forward)
152
+ options.sessions.sharesUnder?.(core.forward.domains)
153
+
154
+ const plugin = new Elysia({ name: 'kayjs-auth' })
155
+ // Typed as a plain instance: `AnyElysia` would merge `any` routes into the app's, and every link would check.
156
+ .use(options.sessions as unknown as Elysia)
157
+ .onStart(() => core.settle())
158
+ .derive(ctx => ({ auth: requestAuth<Scope, Role, OrgRole, UserData>(ctx, core, options.proxy) }))
159
+ .onAfterHandle({ as: 'global' }, sendCookies)
160
+ // The session's derive reaches this instance only; lifting both globally lets them reach every route the app declares after it, however deep the plugin is used.
161
+ .as('global')
162
+ // Typed as their literal paths, so `kay check` checks links to them once the app registers its Elysia app.
163
+ .get(`${core.prefix}/export` as `${Prefix}/export`, async ctx => exportRoute(ctx, core))
164
+ .post(`${core.prefix}/sign-out` as `${Prefix}/sign-out`, async ctx => signOutRoute(ctx, core))
165
+ .post(`${core.prefix}/stop-impersonating` as `${Prefix}/stop-impersonating`, async ctx => stopImpersonatingRoute(ctx, core))
166
+ .post(`${core.prefix}/cancel-deletion` as `${Prefix}/cancel-deletion`, async ctx => cancelDeletionRoute(ctx, core))
167
+ .get(`${core.prefix}/:provider` as `${Prefix}/:provider`, async ctx => startOAuthRoute(ctx, core, options.failurePage))
168
+ .get(`${core.prefix}/:provider/callback` as `${Prefix}/:provider/callback`, async ctx => callbackRoute(ctx, core, options.failurePage))
169
+ .post(`${core.prefix}/:provider/callback` as `${Prefix}/:provider/callback`, ctx => formPostRoute(ctx, core))
170
+
171
+ serveUntypedRoutes(plugin as unknown as Elysia, core)
172
+
173
+ return withPluginOwner({
174
+ [PAGES_OF]: core.pages && pagesHandle(core, options),
175
+ // What `kay auth create-user` asks before the password: what `createUser` would refuse the login for.
176
+ [CHECK_USER]: async (input: CreateUserInput) => (await load.password()).userProblems(core, input),
177
+ // `.use(auth.plugin)` before kay's pages: it adds `auth` to the context and kayjs-auth's routes, and uses the session plugin itself.
178
+ plugin: kayPlugin(plugin),
179
+ hasRole: access.hasRole,
180
+ isGranted: (role: Role, user: BareUser) => access.isGranted(role, user.roles),
181
+ memberOf: (role?: OrgRole, memberOptions: { param?: string } = {}) => memberOf(core, role, memberOptions),
182
+ socketUser,
183
+ ...testHelpers<Role, UserData>(core, plugin as unknown as Elysia),
184
+
185
+ admin: {
186
+ // A user made by the app, as a script or an admin page makes one: checked as registering is, open with `signUp: false` too, signing no one in and mailing no one.
187
+ async createUser(input: Omit<CreateUserInput, 'roles'> & { roles?: Role[] | undefined }): Promise<CreateUserResult> {
188
+ return (await load.password()).createUser(core, input)
189
+ },
190
+ },
191
+
192
+ // A bearer token for `userId` taking no proof and sending no mail, for a flow the app gates itself, such as pairing a device, or a script. `token` adopts one the app handed out before, so its devices keep working through a migration.
193
+ async issueToken(userId: string, label: string, tokenOptions: TokenOptions<Scope> & { token?: string | undefined } = {}): Promise<IssueTokenResult> {
194
+ return (await load.bearer()).issueToken(core, userId, label, tokenOptions)
195
+ },
196
+
197
+ // The user a bearer token belongs to, for a websocket handshake sending one in its first message; null for a banned one. A token bound to a resource (an OAuth token asked for one) is accepted only with `url`, the address of the handshake, under that resource.
198
+ async userFromToken(token: string, url?: string): Promise<User | null> {
199
+ const owner = await (await load.bearer()).tokenUser(core, token, url ?? null)
200
+
201
+ return owner && !banned(owner.record) ? linkedUser(core, owner.record) : null
202
+ },
203
+
204
+ // Closes every route of the Elysia instance it is used on unless the user meets `require`, signed in by default. A route takes `auth: <requirement>` to ask for more and `auth: false` to stay open.
205
+ gate(gateOptions: { require?: AuthRequirement<Role>, scope?: ScopeRequirement<Scope> } = {}) {
206
+ const gate = gateOf<Role, Scope>(core, gateOptions)
207
+
208
+ return <Base extends string, Single extends SingletonBase, Defs extends DefinitionBase, Meta extends MetadataBase, Routes extends RouteBase, Eph extends EphemeralType, Vol extends EphemeralType>(app: Elysia<Base, Single, Defs, Meta, Routes, Eph, Vol>) => gate(app.use(plugin))
209
+ },
210
+ guard: (guardOptions: RouteGuardOptions<Role, Scope> = {}): Guard => guardOf(core, guardOptions),
211
+ })
212
+ }
213
+
214
+ // `kay auth create-user` reaches the app's auth through its plugin when the extension was given the plugin alone.
215
+ function withPluginOwner<Auth extends { plugin: object }>(auth: Auth): Auth {
216
+ Object.defineProperty(auth.plugin, AUTH_OF, { value: auth })
217
+
218
+ return auth
219
+ }
@@ -0,0 +1,160 @@
1
+ import type { FetchPublicOptions, Kv } from 'kay/library'
2
+ import type { Core } from '../core'
3
+ import { isIP } from 'node:net'
4
+ import { fetchPublic } from 'kay/library'
5
+ import { spend } from '../limits'
6
+ import { validRedirectUris } from './uris'
7
+
8
+ const DOCUMENT_MAX_BYTES = 10 * 1024
9
+ const DOCUMENT_TIMEOUT_MS = 5000
10
+ const CACHE_MS = 5 * 60 * 1000
11
+
12
+ const NAME_MAX_LENGTH = 100
13
+ // eslint-disable-next-line no-control-regex -- control characters are what it finds
14
+ const CONTROL = /[\0-\x1F\x7F]/g
15
+ // Characters that reorder the text around them, which could make a name read as another.
16
+ const BIDI = /[\u202A-\u202E\u2066-\u2069]/g
17
+ const JSON_TYPE = /\bjson\b/
18
+
19
+ // A client as the authorization endpoint knows it.
20
+ export interface OAuthClient {
21
+ id: string
22
+ name: string
23
+ redirectUris: string[]
24
+ // The host a client named by a metadata document URL lives at, which the consent page shows beside its name; null for one that registered itself.
25
+ host: string | null
26
+ }
27
+
28
+ // Reads a client's metadata document: its parsed JSON, or why not.
29
+ export type DocumentFetcher = (url: string) => Promise<unknown>
30
+
31
+ // A client ID that is the URL of its own metadata document: https, with a path, no login, fragment or dot segments.
32
+ export function documentUrl(clientId: string): URL | undefined {
33
+ if (!clientId.startsWith('https://') || clientId.length > 2048)
34
+ return undefined
35
+
36
+ try {
37
+ const url = new URL(clientId)
38
+
39
+ // An address as the host has no name to hold to account, and its notations are many.
40
+ if (isIP(url.hostname.startsWith('[') ? url.hostname.slice(1, -1) : url.hostname) !== 0)
41
+ return undefined
42
+
43
+ return url.pathname !== '/' && url.hash === '' && !clientId.includes('#') && url.username === '' && url.password === '' && url.href === clientId ? url : undefined
44
+ }
45
+ catch {
46
+ return undefined
47
+ }
48
+ }
49
+
50
+ // Reads a document over the public internet: https only, from an address that is not on a private network, with no redirect followed, a short time and a small size.
51
+ // `testing` only lets a test replace the name lookup and which hosts may be private.
52
+ export async function fetchPublicDocument(url: string, testing: Pick<FetchPublicOptions, 'allowPrivate' | 'resolve'> = {}): Promise<unknown> {
53
+ const response = await fetchPublic(url, { ...testing, timeout: DOCUMENT_TIMEOUT_MS, maxBytes: DOCUMENT_MAX_BYTES, redirect: 'error', headers: { accept: 'application/json' } })
54
+
55
+ if (response.status !== 200 || !JSON_TYPE.test(response.headers.get('content-type') ?? ''))
56
+ throw new Error('the document did not answer 200 with JSON')
57
+
58
+ return await response.json() as unknown
59
+ }
60
+
61
+ // The reader of metadata documents: the app's own, which then also decides which hosts it may reach, else one that stays on the public internet.
62
+ export function documentFetcher(custom: ((url: string) => Promise<Response>) | undefined): DocumentFetcher {
63
+ if (!custom)
64
+ return fetchPublicDocument
65
+
66
+ return async (url) => {
67
+ const response = await custom(url)
68
+
69
+ if (!response.ok)
70
+ throw new Error('the document did not answer 200')
71
+
72
+ return await response.json() as unknown
73
+ }
74
+ }
75
+
76
+ export function plainName(value: unknown): string | undefined {
77
+ if (typeof value !== 'string')
78
+ return undefined
79
+
80
+ const name = value.replaceAll(CONTROL, ' ').replaceAll(BIDI, '').trim().slice(0, NAME_MAX_LENGTH)
81
+
82
+ return name === '' ? undefined : name
83
+ }
84
+
85
+ function isRecord(value: unknown): value is Record<string, unknown> {
86
+ return typeof value === 'object' && value !== null && !Array.isArray(value)
87
+ }
88
+
89
+ // The client a metadata document describes, or undefined when it is not one for this URL.
90
+ function clientOf(url: URL, document: unknown): OAuthClient | undefined {
91
+ if (!isRecord(document) || document.client_id !== url.href)
92
+ return undefined
93
+
94
+ const uris = document.redirect_uris
95
+
96
+ if (!validRedirectUris(uris))
97
+ return undefined
98
+
99
+ // A client holding a secret signs its token requests, which this server does not read.
100
+ const method = document.token_endpoint_auth_method
101
+
102
+ if (method !== undefined && method !== 'none')
103
+ return undefined
104
+
105
+ return { id: url.href, name: plainName(document.client_name) ?? url.hostname, redirectUris: [...uris], host: url.host }
106
+ }
107
+
108
+ // The client with that ID: a metadata document at the URL a client ID is, else a client that registered itself. Undefined for one this server does not know, or whose document is not valid.
109
+ export async function resolveClient(core: Core, clientId: string, address: string): Promise<OAuthClient | undefined> {
110
+ const url = documentUrl(clientId)
111
+
112
+ if (!url) {
113
+ const stored = clientId.length <= 200 ? await core.store.oauth?.clients.get(clientId) : undefined
114
+
115
+ return stored && { id: stored.id, name: stored.name, redirectUris: stored.redirectUris, host: null }
116
+ }
117
+
118
+ const server = core.oauthServer
119
+ const known = server && await cachedClient(server.documents, url.href)
120
+
121
+ if (known !== undefined)
122
+ return known
123
+
124
+ // Each read of a document is a request this server makes for whoever asked, so it is counted against them.
125
+ if (!server || await spend(core.rates, `oauth-document:${address}`, core.limits.oauthDocument))
126
+ return undefined
127
+
128
+ try {
129
+ const client = clientOf(url, await server.fetchDocument(url.href))
130
+
131
+ if (client)
132
+ await cacheClient(server.documents, url.href, client)
133
+
134
+ return client
135
+ }
136
+ catch {
137
+ return undefined
138
+ }
139
+ }
140
+
141
+ // A store that fails to read or keep a document only costs the app a fetch of it.
142
+ async function cachedClient(documents: Kv, href: string): Promise<OAuthClient | undefined> {
143
+ try {
144
+ const kept = await documents.get(href)
145
+
146
+ return kept === undefined ? undefined : JSON.parse(kept) as OAuthClient
147
+ }
148
+ catch {
149
+ return undefined
150
+ }
151
+ }
152
+
153
+ async function cacheClient(documents: Kv, href: string, client: OAuthClient): Promise<void> {
154
+ try {
155
+ await documents.set(href, JSON.stringify(client), CACHE_MS)
156
+ }
157
+ catch {
158
+ // Fetched again on the next ask.
159
+ }
160
+ }
@@ -0,0 +1,44 @@
1
+ import type { AuthFailed } from '../failure'
2
+ import type { RequestState } from '../state'
3
+ import { report } from '../events'
4
+ import { failed } from '../failure'
5
+ import { approver } from './request'
6
+
7
+ // An app the signed-in user approved to act as them.
8
+ export interface ApprovedClient {
9
+ id: string
10
+ name: string
11
+ // Null for every scope.
12
+ scopes: string[] | null
13
+ createdAt: Date
14
+ lastUsedAt: Date | null
15
+ }
16
+
17
+ export async function approvedClients(state: RequestState): Promise<ApprovedClient[]> {
18
+ const record = await state.current()
19
+
20
+ if (!record || !state.core.store.oauth)
21
+ return []
22
+
23
+ return (await state.core.store.oauth.grants.listByUser(record.id)).map(grant => ({ id: grant.clientId, name: grant.clientName, scopes: grant.scopes, createdAt: grant.createdAt, lastUsedAt: grant.lastUsedAt }))
24
+ }
25
+
26
+ export type RevokeGrantResult = { ok: true } | AuthFailed<'signed-out' | 'not-found'>
27
+
28
+ // Takes the approval back with every token the app was given; `not-found` when there was none, `signed-out` when this is not the user's own session.
29
+ export async function revokeClient(state: RequestState, clientId: string): Promise<RevokeGrantResult> {
30
+ const record = await approver(state)
31
+ const oauth = state.core.store.oauth
32
+
33
+ if (!record)
34
+ return failed('signed-out')
35
+
36
+ const grant = await oauth?.grants.get(record.id, clientId)
37
+
38
+ if (!oauth || !grant || !await oauth.grants.revoke(record.id, clientId))
39
+ return failed('not-found')
40
+
41
+ await report(state, record, 'oauth-client-revoked', grant.clientName)
42
+
43
+ return { ok: true }
44
+ }
@@ -0,0 +1,72 @@
1
+ import type { Core } from '../core'
2
+ import { configError, configuredSite } from 'kay/library'
3
+
4
+ export const AUTHORIZATION_SERVER_PATH = '/.well-known/oauth-authorization-server'
5
+ export const OPENID_CONFIGURATION_PATH = '/.well-known/openid-configuration'
6
+ const TRAILING_SLASH = /\/$/
7
+
8
+ // Shared by every document and endpoint a client reads before it has a token, which a page of another site may ask for.
9
+ export const OPEN_HEADERS = { 'access-control-allow-origin': '*', 'access-control-allow-methods': 'GET, POST, OPTIONS', 'access-control-allow-headers': 'content-type, authorization, mcp-protocol-version' }
10
+
11
+ // Whether the issuer can be named: the site's origin is configured, or the app is not in production, where the Host header would name it.
12
+ export function rootUsable(core: Core): boolean {
13
+ return rootIsFixed(core) || process.env.NODE_ENV !== 'production'
14
+ }
15
+
16
+ // Where the app is served, mount point included: the `site` and `base` kay.config.ts sets, else the `site` of `authCore`, else the request's origin outside production, where the Host header would name the issuer.
17
+ export function siteRoot(core: Core, request: Request): string {
18
+ const fixed = configuredSite()?.origin ?? core.url
19
+
20
+ if (!rootUsable(core))
21
+ throw configError('auth', 'site', 'the OAuth server needs the site\'s origin in production: set `site` in kay.config.ts or in authCore, as the Host header cannot name the issuer')
22
+
23
+ return (fixed ?? new URL(request.url).origin).replace(TRAILING_SLASH, '')
24
+ }
25
+
26
+ // The endpoints of the OAuth server, under the site's root.
27
+ export function endpoints(core: Core, root: string) {
28
+ return {
29
+ authorization: `${root}${core.pages!.prefix}/oauth/authorize`,
30
+ token: `${root}${core.prefix}/oauth/token`,
31
+ registration: `${root}${core.prefix}/oauth/register`,
32
+ revocation: `${root}${core.prefix}/oauth/revoke`,
33
+ }
34
+ }
35
+
36
+ // RFC 8414 metadata, which an MCP client reads from the OpenID Connect location too.
37
+ export function authorizationServerMetadata(core: Core, root: string): Record<string, unknown> {
38
+ const where = endpoints(core, root)
39
+
40
+ return {
41
+ issuer: root,
42
+ authorization_endpoint: where.authorization,
43
+ token_endpoint: where.token,
44
+ registration_endpoint: where.registration,
45
+ revocation_endpoint: where.revocation,
46
+ revocation_endpoint_auth_methods_supported: ['none'],
47
+ response_types_supported: ['code'],
48
+ response_modes_supported: ['query'],
49
+ grant_types_supported: ['authorization_code', 'refresh_token'],
50
+ code_challenge_methods_supported: ['S256'],
51
+ token_endpoint_auth_methods_supported: ['none'],
52
+ ...core.scopes.size > 0 && { scopes_supported: [...core.scopes] },
53
+ client_id_metadata_document_supported: true,
54
+ authorization_response_iss_parameter_supported: true,
55
+ }
56
+ }
57
+
58
+ // RFC 9728 metadata of the MCP endpoint at `resource`.
59
+ export function protectedResourceMetadata(core: Core, root: string, resource: string, name: string): Record<string, unknown> {
60
+ return {
61
+ resource,
62
+ authorization_servers: [root],
63
+ bearer_methods_supported: ['header'],
64
+ resource_name: name,
65
+ ...core.scopes.size > 0 && { scopes_supported: [...core.scopes] },
66
+ }
67
+ }
68
+
69
+ // Whether the site's origin is configured, else it is the request's own, which anyone sending a Host header names.
70
+ export function rootIsFixed(core: Core): boolean {
71
+ return (configuredSite()?.origin ?? core.url) !== undefined
72
+ }
@@ -0,0 +1,38 @@
1
+ import type { Core } from '../core'
2
+ import type { TokenReply } from './reply'
3
+ import { randomToken } from '../keys'
4
+ import { spend } from '../limits'
5
+ import { plainName } from './clients'
6
+ import { refused } from './reply'
7
+ import { validRedirectUris } from './uris'
8
+
9
+ // Dynamic client registration (RFC 7591): a public client names its redirect URIs and is given an ID, with no secret to keep.
10
+ export async function registerClient(core: Core, address: string, document: unknown): Promise<TokenReply> {
11
+ const all = core.limits.oauthRegisterAll
12
+
13
+ if (await spend(core.rates, `oauth-register:${address}`, core.limits.oauthRegister) || (all !== undefined && await spend(core.rates, 'oauth-register:all', all)))
14
+ return refused('invalid_client_metadata', 'Too many registrations', 429)
15
+
16
+ if (typeof document !== 'object' || document === null || Array.isArray(document))
17
+ return refused('invalid_client_metadata', 'The body must be a JSON object')
18
+
19
+ const given = document as Record<string, unknown>
20
+ const uris = given.redirect_uris
21
+
22
+ if (!validRedirectUris(uris))
23
+ return refused('invalid_redirect_uri', 'redirect_uris must be 1 to 10 https URLs or loopback http URLs, 2048 characters in all')
24
+
25
+ if (given.token_endpoint_auth_method !== undefined && given.token_endpoint_auth_method !== 'none')
26
+ return refused('invalid_client_metadata', 'Only public clients (token_endpoint_auth_method none) are supported')
27
+
28
+ const name = plainName(given.client_name) ?? 'Unnamed client'
29
+ const id = `kc_${randomToken()}`
30
+ const createdAt = new Date()
31
+
32
+ await core.store.oauth!.clients.create({ id, name, redirectUris: [...new Set(uris)], createdAt })
33
+
34
+ return {
35
+ status: 201,
36
+ body: { client_id: id, client_id_issued_at: Math.floor(createdAt.getTime() / 1000), client_name: name, redirect_uris: [...new Set(uris)], token_endpoint_auth_method: 'none', grant_types: ['authorization_code', 'refresh_token'], response_types: ['code'] },
37
+ }
38
+ }
@@ -0,0 +1,9 @@
1
+ export interface TokenReply {
2
+ status: number
3
+ body: Record<string, unknown>
4
+ }
5
+
6
+ // An OAuth error answer: the code and a sentence for the developer.
7
+ export function refused(error: string, description: string, status = 400): TokenReply {
8
+ return { status, body: { error, error_description: description } }
9
+ }