@kayjs/auth 0.0.0-stage → 1.104.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (407) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +78 -2
  3. package/llms/admin-and-organizations.md +70 -0
  4. package/llms/admin-pages.md +30 -0
  5. package/llms/grouped-methods.md +106 -0
  6. package/llms/hardening-and-testing.md +108 -0
  7. package/llms/oauth-passkeys-two-factor.md +111 -0
  8. package/llms/oauth-providers.md +28 -0
  9. package/llms/oauth-server-and-tokens.md +76 -0
  10. package/llms/organization-pages.md +20 -0
  11. package/llms/passwords-and-mails.md +129 -0
  12. package/llms/sessions-and-guards.md +51 -0
  13. package/llms/setup.md +122 -0
  14. package/llms/signed-in-components.md +59 -0
  15. package/llms.txt +28 -0
  16. package/package.json +85 -4
  17. package/src/access.ts +31 -0
  18. package/src/account.ts +198 -0
  19. package/src/add.ts +70 -0
  20. package/src/address.ts +51 -0
  21. package/src/admin.ts +361 -0
  22. package/src/auditWording.ts +153 -0
  23. package/src/auth.ts +219 -0
  24. package/src/authorize/clients.ts +160 -0
  25. package/src/authorize/grants.ts +44 -0
  26. package/src/authorize/metadata.ts +72 -0
  27. package/src/authorize/register.ts +38 -0
  28. package/src/authorize/reply.ts +9 -0
  29. package/src/authorize/request.ts +253 -0
  30. package/src/authorize/resource.ts +34 -0
  31. package/src/authorize/revoke.ts +36 -0
  32. package/src/authorize/routes.ts +87 -0
  33. package/src/authorize/token.ts +213 -0
  34. package/src/authorize/uris.ts +76 -0
  35. package/src/bearer.ts +208 -0
  36. package/src/bearerHeader.ts +11 -0
  37. package/src/breached.ts +47 -0
  38. package/src/browser.ts +59 -0
  39. package/src/captcha.ts +196 -0
  40. package/src/cbor.ts +129 -0
  41. package/src/components/deletion-banner.kay +20 -0
  42. package/src/components/impersonation-banner.kay +21 -0
  43. package/src/components/signed-in.kay +8 -0
  44. package/src/components/signed-out.kay +6 -0
  45. package/src/components/user-menu.kay +21 -0
  46. package/src/context.ts +5 -0
  47. package/src/core.ts +308 -0
  48. package/src/createUserCommand.ts +217 -0
  49. package/src/decide.ts +45 -0
  50. package/src/deletion.ts +80 -0
  51. package/src/devTool.ts +104 -0
  52. package/src/device.ts +37 -0
  53. package/src/email.ts +594 -0
  54. package/src/erase.ts +237 -0
  55. package/src/events.ts +297 -0
  56. package/src/export.ts +101 -0
  57. package/src/failure.ts +63 -0
  58. package/src/forwardAuth.ts +55 -0
  59. package/src/forwardRoutes.ts +68 -0
  60. package/src/gate.ts +104 -0
  61. package/src/guard.ts +22 -0
  62. package/src/guards.ts +72 -0
  63. package/src/guesses.ts +99 -0
  64. package/src/index.ts +46 -0
  65. package/src/keys.ts +51 -0
  66. package/src/limits.ts +182 -0
  67. package/src/load.ts +18 -0
  68. package/src/locale.ts +15 -0
  69. package/src/log.ts +4 -0
  70. package/src/mail.ts +225 -0
  71. package/src/memoryStore.ts +599 -0
  72. package/src/messages/fr.ts +357 -0
  73. package/src/methods/account.ts +80 -0
  74. package/src/methods/admin.ts +63 -0
  75. package/src/methods/audit.ts +15 -0
  76. package/src/methods/email.ts +39 -0
  77. package/src/methods/magicLink.ts +32 -0
  78. package/src/methods/oauth.ts +35 -0
  79. package/src/methods/oauthServer.ts +31 -0
  80. package/src/methods/organizations.ts +96 -0
  81. package/src/methods/passkeys.ts +61 -0
  82. package/src/methods/password.ts +53 -0
  83. package/src/methods/sessions.ts +18 -0
  84. package/src/methods/tokens.ts +24 -0
  85. package/src/methods/twoFactor.ts +62 -0
  86. package/src/oauth/client.ts +324 -0
  87. package/src/oauth/flow.ts +350 -0
  88. package/src/oauth/index.ts +5 -0
  89. package/src/oauth/pkce.ts +20 -0
  90. package/src/oauth/providers.ts +490 -0
  91. package/src/oauth/refresher.ts +177 -0
  92. package/src/oauth/timeout.ts +2 -0
  93. package/src/oauth/types.ts +78 -0
  94. package/src/oauthTest.ts +112 -0
  95. package/src/organizations.ts +675 -0
  96. package/src/organizationsCore.ts +60 -0
  97. package/src/own.ts +313 -0
  98. package/src/pages/components/captcha.kay +16 -0
  99. package/src/pages/components/frame.kay +11 -0
  100. package/src/pages/components/message.kay +8 -0
  101. package/src/pages/components/panel.kay +12 -0
  102. package/src/pages/components/passkey-add.kay +48 -0
  103. package/src/pages/components/passkey-sign-in.kay +34 -0
  104. package/src/pages/components/passkey-two-factor.kay +33 -0
  105. package/src/pages/components/proof.kay +15 -0
  106. package/src/pages/components/provider-buttons.kay +25 -0
  107. package/src/pages/components/recovery-codes.kay +13 -0
  108. package/src/pages/components/separator.kay +4 -0
  109. package/src/pages/english.ts +82 -0
  110. package/src/pages/forms.ts +185 -0
  111. package/src/pages/index.ts +361 -0
  112. package/src/pages/organizationPage.ts +12 -0
  113. package/src/pages/routes/account/_guard.ts +15 -0
  114. package/src/pages/routes/account/_layout.kay +37 -0
  115. package/src/pages/routes/account/clients.kay +33 -0
  116. package/src/pages/routes/account/connections.kay +57 -0
  117. package/src/pages/routes/account/data.kay +106 -0
  118. package/src/pages/routes/account/index.kay +109 -0
  119. package/src/pages/routes/account/organizations/[org].kay +188 -0
  120. package/src/pages/routes/account/organizations/_guard.ts +8 -0
  121. package/src/pages/routes/account/organizations/index.kay +86 -0
  122. package/src/pages/routes/account/security.kay +164 -0
  123. package/src/pages/routes/account/sessions.kay +51 -0
  124. package/src/pages/routes/account/tokens.kay +84 -0
  125. package/src/pages/routes/admin/_layout.kay +43 -0
  126. package/src/pages/routes/admin/audit.kay +43 -0
  127. package/src/pages/routes/admin/index.kay +60 -0
  128. package/src/pages/routes/admin/users/[id].kay +181 -0
  129. package/src/pages/routes/confirm-email.kay +39 -0
  130. package/src/pages/routes/invitation.kay +104 -0
  131. package/src/pages/routes/magic-link.kay +42 -0
  132. package/src/pages/routes/oauth/authorize.kay +80 -0
  133. package/src/pages/routes/register.kay +83 -0
  134. package/src/pages/routes/reset-password.kay +73 -0
  135. package/src/pages/routes/sign-in.kay +128 -0
  136. package/src/pages/routes/two-factor.kay +61 -0
  137. package/src/pages/routes/verify-email.kay +83 -0
  138. package/src/passkeys.ts +373 -0
  139. package/src/password.ts +316 -0
  140. package/src/payloads.ts +22 -0
  141. package/src/pg.ts +705 -0
  142. package/src/profile.ts +43 -0
  143. package/src/proof.ts +110 -0
  144. package/src/prune.ts +123 -0
  145. package/src/rates.ts +82 -0
  146. package/src/request.ts +712 -0
  147. package/src/requiredTwoFactor.ts +71 -0
  148. package/src/requirement.ts +23 -0
  149. package/src/roles.ts +18 -0
  150. package/src/routes.ts +202 -0
  151. package/src/rules-check.ts +37 -0
  152. package/src/rules.ts +108 -0
  153. package/src/securityNotice.ts +45 -0
  154. package/src/sessions.ts +184 -0
  155. package/src/setup.ts +417 -0
  156. package/src/signInOptions.ts +9 -0
  157. package/src/state.ts +34 -0
  158. package/src/store.ts +410 -0
  159. package/src/storeHelpers.ts +23 -0
  160. package/src/test.ts +46 -0
  161. package/src/testCookies.ts +9 -0
  162. package/src/testHelpers.ts +58 -0
  163. package/src/testing.ts +113 -0
  164. package/src/text.ts +6 -0
  165. package/src/totp.ts +120 -0
  166. package/src/twoFactor.ts +200 -0
  167. package/src/types.ts +23 -0
  168. package/src/userData.ts +47 -0
  169. package/src/viewer-layout/_layout.kay +11 -0
  170. package/src/viewer.ts +116 -0
  171. package/src/wayIn.ts +40 -0
  172. package/src/webauthn.ts +375 -0
  173. package/src/wsAuth.ts +53 -0
  174. package/types/access.d.ts +12 -0
  175. package/types/access.d.ts.map +1 -0
  176. package/types/account.d.ts +32 -0
  177. package/types/account.d.ts.map +1 -0
  178. package/types/add.d.ts +29 -0
  179. package/types/add.d.ts.map +1 -0
  180. package/types/address.d.ts +2 -0
  181. package/types/address.d.ts.map +1 -0
  182. package/types/admin.d.ts +84 -0
  183. package/types/admin.d.ts.map +1 -0
  184. package/types/auditWording.d.ts +9 -0
  185. package/types/auditWording.d.ts.map +1 -0
  186. package/types/auth.d.ts +3475 -0
  187. package/types/auth.d.ts.map +1 -0
  188. package/types/authorize/clients.d.ts +15 -0
  189. package/types/authorize/clients.d.ts.map +1 -0
  190. package/types/authorize/grants.d.ts +15 -0
  191. package/types/authorize/grants.d.ts.map +1 -0
  192. package/types/authorize/metadata.d.ts +20 -0
  193. package/types/authorize/metadata.d.ts.map +1 -0
  194. package/types/authorize/register.d.ts +4 -0
  195. package/types/authorize/register.d.ts.map +1 -0
  196. package/types/authorize/reply.d.ts +6 -0
  197. package/types/authorize/reply.d.ts.map +1 -0
  198. package/types/authorize/request.d.ts +48 -0
  199. package/types/authorize/request.d.ts.map +1 -0
  200. package/types/authorize/resource.d.ts +4 -0
  201. package/types/authorize/resource.d.ts.map +1 -0
  202. package/types/authorize/revoke.d.ts +4 -0
  203. package/types/authorize/revoke.d.ts.map +1 -0
  204. package/types/authorize/routes.d.ts +5 -0
  205. package/types/authorize/routes.d.ts.map +1 -0
  206. package/types/authorize/token.d.ts +7 -0
  207. package/types/authorize/token.d.ts.map +1 -0
  208. package/types/authorize/uris.d.ts +5 -0
  209. package/types/authorize/uris.d.ts.map +1 -0
  210. package/types/bearer.d.ts +45 -0
  211. package/types/bearer.d.ts.map +1 -0
  212. package/types/bearerHeader.d.ts +3 -0
  213. package/types/bearerHeader.d.ts.map +1 -0
  214. package/types/breached.d.ts +5 -0
  215. package/types/breached.d.ts.map +1 -0
  216. package/types/browser.d.ts +11 -0
  217. package/types/browser.d.ts.map +1 -0
  218. package/types/captcha.d.ts +42 -0
  219. package/types/captcha.d.ts.map +1 -0
  220. package/types/cbor.d.ts +4 -0
  221. package/types/cbor.d.ts.map +1 -0
  222. package/types/context.d.ts +3 -0
  223. package/types/context.d.ts.map +1 -0
  224. package/types/core.d.ts +180 -0
  225. package/types/core.d.ts.map +1 -0
  226. package/types/createUserCommand.d.ts +11 -0
  227. package/types/createUserCommand.d.ts.map +1 -0
  228. package/types/decide.d.ts +12 -0
  229. package/types/decide.d.ts.map +1 -0
  230. package/types/deletion.d.ts +17 -0
  231. package/types/deletion.d.ts.map +1 -0
  232. package/types/devTool.d.ts +3 -0
  233. package/types/devTool.d.ts.map +1 -0
  234. package/types/device.d.ts +7 -0
  235. package/types/device.d.ts.map +1 -0
  236. package/types/email.d.ts +73 -0
  237. package/types/email.d.ts.map +1 -0
  238. package/types/erase.d.ts +31 -0
  239. package/types/erase.d.ts.map +1 -0
  240. package/types/events.d.ts +139 -0
  241. package/types/events.d.ts.map +1 -0
  242. package/types/export.d.ts +54 -0
  243. package/types/export.d.ts.map +1 -0
  244. package/types/failure.d.ts +19 -0
  245. package/types/failure.d.ts.map +1 -0
  246. package/types/forwardAuth.d.ts +12 -0
  247. package/types/forwardAuth.d.ts.map +1 -0
  248. package/types/forwardRoutes.d.ts +11 -0
  249. package/types/forwardRoutes.d.ts.map +1 -0
  250. package/types/gate.d.ts +31 -0
  251. package/types/gate.d.ts.map +1 -0
  252. package/types/guard.d.ts +10 -0
  253. package/types/guard.d.ts.map +1 -0
  254. package/types/guards.d.ts +37 -0
  255. package/types/guards.d.ts.map +1 -0
  256. package/types/guesses.d.ts +18 -0
  257. package/types/guesses.d.ts.map +1 -0
  258. package/types/index.d.ts +47 -0
  259. package/types/index.d.ts.map +1 -0
  260. package/types/keys.d.ts +11 -0
  261. package/types/keys.d.ts.map +1 -0
  262. package/types/limits.d.ts +133 -0
  263. package/types/limits.d.ts.map +1 -0
  264. package/types/load.d.ts +18 -0
  265. package/types/load.d.ts.map +1 -0
  266. package/types/locale.d.ts +4 -0
  267. package/types/locale.d.ts.map +1 -0
  268. package/types/log.d.ts +2 -0
  269. package/types/log.d.ts.map +1 -0
  270. package/types/mail.d.ts +51 -0
  271. package/types/mail.d.ts.map +1 -0
  272. package/types/memoryStore.d.ts +3 -0
  273. package/types/memoryStore.d.ts.map +1 -0
  274. package/types/messages/fr.d.ts +409 -0
  275. package/types/messages/fr.d.ts.map +1 -0
  276. package/types/methods/account.d.ts +24 -0
  277. package/types/methods/account.d.ts.map +1 -0
  278. package/types/methods/admin.d.ts +30 -0
  279. package/types/methods/admin.d.ts.map +1 -0
  280. package/types/methods/audit.d.ts +11 -0
  281. package/types/methods/audit.d.ts.map +1 -0
  282. package/types/methods/email.d.ts +14 -0
  283. package/types/methods/email.d.ts.map +1 -0
  284. package/types/methods/magicLink.d.ts +12 -0
  285. package/types/methods/magicLink.d.ts.map +1 -0
  286. package/types/methods/oauth.d.ts +16 -0
  287. package/types/methods/oauth.d.ts.map +1 -0
  288. package/types/methods/oauthServer.d.ts +13 -0
  289. package/types/methods/oauthServer.d.ts.map +1 -0
  290. package/types/methods/organizations.d.ts +30 -0
  291. package/types/methods/organizations.d.ts.map +1 -0
  292. package/types/methods/passkeys.d.ts +19 -0
  293. package/types/methods/passkeys.d.ts.map +1 -0
  294. package/types/methods/password.d.ts +17 -0
  295. package/types/methods/password.d.ts.map +1 -0
  296. package/types/methods/sessions.d.ts +9 -0
  297. package/types/methods/sessions.d.ts.map +1 -0
  298. package/types/methods/tokens.d.ts +11 -0
  299. package/types/methods/tokens.d.ts.map +1 -0
  300. package/types/methods/twoFactor.d.ts +20 -0
  301. package/types/methods/twoFactor.d.ts.map +1 -0
  302. package/types/oauth/client.d.ts +39 -0
  303. package/types/oauth/client.d.ts.map +1 -0
  304. package/types/oauth/flow.d.ts +38 -0
  305. package/types/oauth/flow.d.ts.map +1 -0
  306. package/types/oauth/index.d.ts +6 -0
  307. package/types/oauth/index.d.ts.map +1 -0
  308. package/types/oauth/pkce.d.ts +10 -0
  309. package/types/oauth/pkce.d.ts.map +1 -0
  310. package/types/oauth/providers.d.ts +100 -0
  311. package/types/oauth/providers.d.ts.map +1 -0
  312. package/types/oauth/refresher.d.ts +55 -0
  313. package/types/oauth/refresher.d.ts.map +1 -0
  314. package/types/oauth/timeout.d.ts +2 -0
  315. package/types/oauth/timeout.d.ts.map +1 -0
  316. package/types/oauth/types.d.ts +75 -0
  317. package/types/oauth/types.d.ts.map +1 -0
  318. package/types/oauthTest.d.ts +23 -0
  319. package/types/oauthTest.d.ts.map +1 -0
  320. package/types/organizations.d.ts +111 -0
  321. package/types/organizations.d.ts.map +1 -0
  322. package/types/organizationsCore.d.ts +29 -0
  323. package/types/organizationsCore.d.ts.map +1 -0
  324. package/types/own.d.ts +55 -0
  325. package/types/own.d.ts.map +1 -0
  326. package/types/pages/english.d.ts +80 -0
  327. package/types/pages/english.d.ts.map +1 -0
  328. package/types/pages/forms.d.ts +204 -0
  329. package/types/pages/forms.d.ts.map +1 -0
  330. package/types/pages/index.d.ts +166 -0
  331. package/types/pages/index.d.ts.map +1 -0
  332. package/types/pages/organizationPage.d.ts +7 -0
  333. package/types/pages/organizationPage.d.ts.map +1 -0
  334. package/types/pages/routes/account/_guard.d.ts +3 -0
  335. package/types/pages/routes/account/_guard.d.ts.map +1 -0
  336. package/types/pages/routes/account/organizations/_guard.d.ts +3 -0
  337. package/types/pages/routes/account/organizations/_guard.d.ts.map +1 -0
  338. package/types/passkeys.d.ts +61 -0
  339. package/types/passkeys.d.ts.map +1 -0
  340. package/types/password.d.ts +49 -0
  341. package/types/password.d.ts.map +1 -0
  342. package/types/payloads.d.ts +4 -0
  343. package/types/payloads.d.ts.map +1 -0
  344. package/types/pg.d.ts +303 -0
  345. package/types/pg.d.ts.map +1 -0
  346. package/types/profile.d.ts +11 -0
  347. package/types/profile.d.ts.map +1 -0
  348. package/types/proof.d.ts +33 -0
  349. package/types/proof.d.ts.map +1 -0
  350. package/types/prune.d.ts +5 -0
  351. package/types/prune.d.ts.map +1 -0
  352. package/types/rates.d.ts +15 -0
  353. package/types/rates.d.ts.map +1 -0
  354. package/types/request.d.ts +119 -0
  355. package/types/request.d.ts.map +1 -0
  356. package/types/requiredTwoFactor.d.ts +16 -0
  357. package/types/requiredTwoFactor.d.ts.map +1 -0
  358. package/types/requirement.d.ts +4 -0
  359. package/types/requirement.d.ts.map +1 -0
  360. package/types/roles.d.ts +9 -0
  361. package/types/roles.d.ts.map +1 -0
  362. package/types/routes.d.ts +31 -0
  363. package/types/routes.d.ts.map +1 -0
  364. package/types/rules-check.d.ts +3 -0
  365. package/types/rules-check.d.ts.map +1 -0
  366. package/types/rules.d.ts +38 -0
  367. package/types/rules.d.ts.map +1 -0
  368. package/types/securityNotice.d.ts +7 -0
  369. package/types/securityNotice.d.ts.map +1 -0
  370. package/types/sessions.d.ts +32 -0
  371. package/types/sessions.d.ts.map +1 -0
  372. package/types/setup.d.ts +18 -0
  373. package/types/setup.d.ts.map +1 -0
  374. package/types/signInOptions.d.ts +6 -0
  375. package/types/signInOptions.d.ts.map +1 -0
  376. package/types/state.d.ts +25 -0
  377. package/types/state.d.ts.map +1 -0
  378. package/types/store.d.ts +295 -0
  379. package/types/store.d.ts.map +1 -0
  380. package/types/storeHelpers.d.ts +4 -0
  381. package/types/storeHelpers.d.ts.map +1 -0
  382. package/types/test.d.ts +21 -0
  383. package/types/test.d.ts.map +1 -0
  384. package/types/testCookies.d.ts +3 -0
  385. package/types/testCookies.d.ts.map +1 -0
  386. package/types/testHelpers.d.ts +34 -0
  387. package/types/testHelpers.d.ts.map +1 -0
  388. package/types/testing.d.ts +12 -0
  389. package/types/testing.d.ts.map +1 -0
  390. package/types/text.d.ts +2 -0
  391. package/types/text.d.ts.map +1 -0
  392. package/types/totp.d.ts +12 -0
  393. package/types/totp.d.ts.map +1 -0
  394. package/types/twoFactor.d.ts +41 -0
  395. package/types/twoFactor.d.ts.map +1 -0
  396. package/types/types.d.ts +17 -0
  397. package/types/types.d.ts.map +1 -0
  398. package/types/userData.d.ts +9 -0
  399. package/types/userData.d.ts.map +1 -0
  400. package/types/viewer.d.ts +23 -0
  401. package/types/viewer.d.ts.map +1 -0
  402. package/types/wayIn.d.ts +12 -0
  403. package/types/wayIn.d.ts.map +1 -0
  404. package/types/webauthn.d.ts +111 -0
  405. package/types/webauthn.d.ts.map +1 -0
  406. package/types/wsAuth.d.ts +14 -0
  407. package/types/wsAuth.d.ts.map +1 -0
@@ -0,0 +1,253 @@
1
+ import type { Core } from '../core'
2
+ import type { AuthFailed } from '../failure'
3
+ import type { RequestState } from '../state'
4
+ import type { OAuthGrantRecord, UserRecord } from '../store'
5
+ import type { OAuthClient } from './clients'
6
+ import { banned, publicUser } from '../core'
7
+ import { impersonatorOf, report } from '../events'
8
+ import { failed } from '../failure'
9
+ import { digest, randomToken } from '../keys'
10
+ import { lacksTwoFactor } from '../requiredTwoFactor'
11
+ import { resolveClient } from './clients'
12
+ import { redirectUriRegistered, withParams } from './uris'
13
+
14
+ // How long an authorization code can be spent for, seconds.
15
+ export const CODE_LIFETIME = 60
16
+ const PARAM_MAX_LENGTH = 2048
17
+ const CHALLENGE = /^[\w-]{43}$/
18
+ const WHITESPACE = /\s+/
19
+
20
+ // Asked by clients that want a refresh token, which every client is given.
21
+ export const IMPLIED_SCOPES = new Set(['offline_access'])
22
+
23
+ // What the authorization endpoint reads off the request, as the client sent it.
24
+ export type AuthorizeParams = Partial<Record<'client_id' | 'redirect_uri' | 'response_type' | 'code_challenge' | 'code_challenge_method' | 'scope' | 'state' | 'prompt', string | undefined>> & {
25
+ // An array when the request named the parameter more than once, which is refused as it is at the token endpoint.
26
+ resource?: string | string[] | undefined
27
+ }
28
+
29
+ // What the consent form posts back to be checked again.
30
+ export interface ConsentFields {
31
+ client_id: string
32
+ redirect_uri: string
33
+ code_challenge: string
34
+ scope: string
35
+ state: string
36
+ resource: string
37
+ }
38
+
39
+ export type AuthorizeOutcome
40
+ // The client or its redirect URI cannot be trusted, so no one is sent there: the page says so.
41
+ = | { kind: 'error', error: 'client' | 'redirect_uri' }
42
+ // Back to the client, with the code or the error.
43
+ | { kind: 'redirect', url: string }
44
+ // The visitor signs in first.
45
+ | { kind: 'sign-in' }
46
+ | { kind: 'consent', client: { id: string, name: string, host: string | null }, redirectHost: string, scopes: string[] | null, fields: ConsentFields }
47
+
48
+ interface Checked {
49
+ client: OAuthClient
50
+ redirectUri: string
51
+ challenge: string
52
+ scopes: string[] | null
53
+ resource: string | null
54
+ params: AuthorizeParams
55
+ }
56
+
57
+ // A parameter as a string, an empty one counting as absent: the consent form posts the ones the client left out back empty.
58
+ function oneOf(value: unknown): string | undefined {
59
+ return typeof value === 'string' && value !== '' && value.length <= PARAM_MAX_LENGTH ? value : undefined
60
+ }
61
+
62
+ // Whether `held` covers `wanted`: null is every scope.
63
+ export function covers(held: readonly string[] | null, wanted: readonly string[] | null): boolean {
64
+ if (held === null)
65
+ return true
66
+
67
+ return wanted !== null && wanted.every(scope => held.includes(scope))
68
+ }
69
+
70
+ // Whether an approval already given covers a request: an approval for every scope, given while the app declared none, covers no scope the app declares since.
71
+ function approves(held: readonly string[] | null, wanted: readonly string[] | null): boolean {
72
+ return held === null ? wanted === null : covers(held, wanted)
73
+ }
74
+
75
+ // The scopes of an approval once the user approves more: both sets together, with the new ones alone when the approval held every scope of an app declaring none.
76
+ function together(held: readonly string[] | null, wanted: readonly string[] | null): string[] | null {
77
+ if (wanted === null)
78
+ return null
79
+
80
+ return held === null ? [...wanted] : [...new Set([...held, ...wanted])]
81
+ }
82
+
83
+ // The scopes a request asks for, null for every one (an app declaring none); undefined when it asks for one the app does not declare.
84
+ export function requestedScopes(core: Core, scope: string | undefined): string[] | null | undefined {
85
+ // An app declaring no scopes gives its tokens every one, whatever a client asks for.
86
+ if (core.scopes.size === 0)
87
+ return null
88
+
89
+ const asked = (scope ?? '').split(WHITESPACE).filter(each => each !== '' && !IMPLIED_SCOPES.has(each))
90
+
91
+ // A client asking for no scope is given the app's default ones, none unless it names some.
92
+ if (asked.length === 0)
93
+ return [...core.oauthServer?.defaultScopes ?? []]
94
+
95
+ return asked.every(each => core.scopes.has(each)) ? [...new Set(asked)] : undefined
96
+ }
97
+
98
+ function failure(checked: Pick<Checked, 'redirectUri' | 'params'>, root: string, error: string, description: string): AuthorizeOutcome {
99
+ return { kind: 'redirect', url: withParams(checked.redirectUri, { error, error_description: description, state: oneOf(checked.params.state), iss: root }) }
100
+ }
101
+
102
+ // Reads the request as far as the client and its redirect URI, then the rest; an outcome means it stops there.
103
+ async function check(state: RequestState, params: AuthorizeParams, root: string): Promise<Checked | AuthorizeOutcome> {
104
+ const clientId = oneOf(params.client_id)
105
+ const client = clientId === undefined ? undefined : await resolveClient(state.core, clientId, state.client)
106
+
107
+ if (!client)
108
+ return { kind: 'error', error: 'client' }
109
+
110
+ const redirectUri = oneOf(params.redirect_uri)
111
+
112
+ if (redirectUri === undefined || !redirectUriRegistered(client.redirectUris, redirectUri))
113
+ return { kind: 'error', error: 'redirect_uri' }
114
+
115
+ const base = { redirectUri, params }
116
+ const challenge = oneOf(params.code_challenge)
117
+
118
+ if (oneOf(params.response_type) !== 'code')
119
+ return failure(base, root, 'unsupported_response_type', 'Only the code response type is supported')
120
+
121
+ if (challenge === undefined || !CHALLENGE.test(challenge) || params.code_challenge_method !== 'S256')
122
+ return failure(base, root, 'invalid_request', 'A PKCE code_challenge with code_challenge_method S256 is required')
123
+
124
+ const scopes = requestedScopes(state.core, oneOf(params.scope))
125
+
126
+ if (scopes === undefined)
127
+ return failure(base, root, 'invalid_scope', 'A scope asked for is not one this server has')
128
+
129
+ const asked = [params.resource].flat()
130
+
131
+ if (asked.length > 1)
132
+ return failure(base, root, 'invalid_target', 'Only one resource can be asked for')
133
+
134
+ const resource = oneOf(asked[0])
135
+
136
+ if (resource !== undefined && !sameSite(resource, root))
137
+ return failure(base, root, 'invalid_target', 'The resource is not one of this server')
138
+
139
+ return { client, redirectUri, challenge, scopes, resource: resource ?? null, params }
140
+ }
141
+
142
+ // Whether two URLs are the same resource, however they are spelled.
143
+ export function sameResource(a: string, b: string): boolean {
144
+ try {
145
+ return new URL(a).href === new URL(b).href
146
+ }
147
+ catch {
148
+ return false
149
+ }
150
+ }
151
+
152
+ // Whether `resource` is a URL of the site the OAuth server is of.
153
+ export function sameSite(resource: string, root: string): boolean {
154
+ try {
155
+ const url = new URL(resource)
156
+
157
+ return url.origin === new URL(root).origin && url.hash === ''
158
+ }
159
+ catch {
160
+ return false
161
+ }
162
+ }
163
+
164
+ function isOutcome(value: Checked | AuthorizeOutcome): value is AuthorizeOutcome {
165
+ return 'kind' in value
166
+ }
167
+
168
+ // Spends the user's approval on a code for the client, and answers where the browser goes back to it.
169
+ async function approve(state: RequestState, record: UserRecord, checked: Checked, root: string): Promise<string> {
170
+ const { core } = state
171
+ const oauth = core.store.oauth!
172
+ const now = new Date()
173
+ const code = randomToken()
174
+ const held = await oauth.grants.get(record.id, checked.client.id)
175
+ const granted = held ? together(held.scopes, checked.scopes) : checked.scopes
176
+ const grant: OAuthGrantRecord = { userId: record.id, clientId: checked.client.id, clientName: checked.client.name, scopes: granted, createdAt: held?.createdAt ?? now, lastUsedAt: held?.lastUsedAt ?? null }
177
+
178
+ await oauth.grants.upsert(grant)
179
+ await oauth.codes.create({ digest: digest(code), userId: record.id, clientId: checked.client.id, redirectUri: checked.redirectUri, challenge: checked.challenge, scopes: checked.scopes, family: crypto.randomUUID(), resource: checked.resource, createdAt: now, expiresAt: new Date(now.getTime() + CODE_LIFETIME * 1000), usedAt: null })
180
+
181
+ if (!held || !approves(held.scopes, checked.scopes))
182
+ await report(state, record, 'oauth-client-approved', checked.client.name)
183
+
184
+ return withParams(checked.redirectUri, { code, state: oneOf(checked.params.state), iss: root })
185
+ }
186
+
187
+ // The user a page may approve for: signed in by a session of their own, not an admin acting as them.
188
+ export async function approver(state: RequestState): Promise<UserRecord | undefined> {
189
+ const record = await state.current()
190
+
191
+ if (!record || record.guest || banned(record) || state.via() !== 'session' || await impersonatorOf(state) !== undefined)
192
+ return undefined
193
+
194
+ return record
195
+ }
196
+
197
+ // What the authorization endpoint does with a request: the visitor signs in, sees the consent page, or goes back to the client with a code when they approved this client for these scopes already.
198
+ export async function authorize(state: RequestState, params: AuthorizeParams, root: string): Promise<AuthorizeOutcome> {
199
+ const checked = await check(state, params, root)
200
+
201
+ if (isOutcome(checked))
202
+ return checked
203
+
204
+ const record = await approver(state)
205
+
206
+ const prompt = oneOf(params.prompt)?.split(WHITESPACE) ?? []
207
+
208
+ if (!record) {
209
+ if (await impersonatorOf(state) !== undefined)
210
+ return failure(checked, root, 'access_denied', 'Not while acting as a user')
211
+
212
+ return prompt.includes('none') ? failure(checked, root, 'login_required', 'The user is signed out') : { kind: 'sign-in' }
213
+ }
214
+
215
+ if (await lacksTwoFactor(state, publicUser(record)))
216
+ return failure(checked, root, 'access_denied', 'Two-factor authentication is required')
217
+
218
+ const held = await state.core.store.oauth!.grants.get(record.id, checked.client.id)
219
+
220
+ if (held && approves(held.scopes, checked.scopes) && !prompt.includes('consent'))
221
+ return { kind: 'redirect', url: await approve(state, record, checked, root) }
222
+
223
+ if (prompt.includes('none'))
224
+ return failure(checked, root, 'consent_required', 'The user has not approved this client for these scopes')
225
+
226
+ return {
227
+ kind: 'consent',
228
+ redirectHost: new URL(checked.redirectUri).host,
229
+ client: { id: checked.client.id, name: checked.client.name, host: checked.client.host },
230
+ scopes: checked.scopes,
231
+ fields: { client_id: checked.client.id, redirect_uri: checked.redirectUri, code_challenge: checked.challenge, scope: oneOf(params.scope) ?? '', state: oneOf(params.state) ?? '', resource: checked.resource ?? '' },
232
+ }
233
+ }
234
+
235
+ export type DecideResult = { ok: true, redirect: string } | AuthFailed<'client' | 'redirect_uri' | 'signed-out'>
236
+
237
+ // The user's answer on the consent page, checked again as the request is: where the browser goes back to the client.
238
+ export async function decide(state: RequestState, fields: AuthorizeParams, allow: boolean, root: string): Promise<DecideResult> {
239
+ const checked = await check(state, { ...fields, response_type: 'code', code_challenge_method: 'S256' }, root)
240
+
241
+ if (isOutcome(checked))
242
+ return checked.kind === 'redirect' ? { ok: true, redirect: checked.url } : failed(checked.kind === 'error' ? checked.error : 'signed-out')
243
+
244
+ const record = await approver(state)
245
+
246
+ if (!record)
247
+ return failed('signed-out')
248
+
249
+ if (!allow || await lacksTwoFactor(state, publicUser(record)))
250
+ return { ok: true, redirect: withParams(checked.redirectUri, { error: 'access_denied', error_description: allow ? 'Two-factor authentication is required' : 'The user denied the request', state: oneOf(checked.params.state), iss: root }) }
251
+
252
+ return { ok: true, redirect: await approve(state, record, checked, root) }
253
+ }
@@ -0,0 +1,34 @@
1
+ import type { Core } from '../core'
2
+ import { configuredSite } from 'kay/library'
3
+
4
+ const TRAILING_SLASHES = /\/+$/
5
+
6
+ // A path as the router reads it, whether or not the proxy took the mount point `base` off.
7
+ function withoutBase(path: string, base: string): string {
8
+ return base !== '' && (path === base || path.startsWith(`${base}/`)) ? path.slice(base.length) || '/' : path
9
+ }
10
+
11
+ // The mount point of the app: the path of the `site` kay.config.ts sets, else the one of `authCore`, '' at the root.
12
+ export function siteBase(core: Core): string {
13
+ const fixed = configuredSite()?.origin ?? core.url
14
+
15
+ try {
16
+ return fixed === undefined ? '' : new URL(fixed).pathname.replace(TRAILING_SLASHES, '')
17
+ }
18
+ catch {
19
+ return ''
20
+ }
21
+ }
22
+
23
+ // Whether the request `url` is the resource or under its path (RFC 8707 audience), the query ignored, a trailing slash either way and the mount point `base` on both sides or neither.
24
+ export function underResource(resource: string, url: string, base = ''): boolean {
25
+ try {
26
+ const bound = withoutBase(new URL(resource).pathname, base).replace(TRAILING_SLASHES, '')
27
+ const path = withoutBase(new URL(url).pathname, base)
28
+
29
+ return path === bound || path.startsWith(`${bound}/`)
30
+ }
31
+ catch {
32
+ return false
33
+ }
34
+ }
@@ -0,0 +1,36 @@
1
+ import type { Core } from '../core'
2
+ import type { TokenReply } from './reply'
3
+ import { digest } from '../keys'
4
+ import { spend } from '../limits'
5
+ import { refused } from './reply'
6
+
7
+ // RFC 7009: ends the session of the client that holds the token, access or refresh, with the rest of its family. It answers 200 for a token that is unknown, expired or another client's, so it tells nothing about tokens.
8
+ export async function revokeEndpoint(core: Core, address: string, form: URLSearchParams): Promise<TokenReply> {
9
+ if (await spend(core.rates, `oauth-revoke:${address}`, core.limits.oauthToken))
10
+ return refused('invalid_request', 'Too many requests', 429)
11
+
12
+ const presented = form.get('token')
13
+ const clientId = form.get('client_id')
14
+
15
+ if (presented === null || presented === '' || clientId === null || clientId === '')
16
+ return refused('invalid_request', 'token and client_id are required')
17
+
18
+ const { bearerTokens, oauth } = core.store
19
+ const key = digest(presented)
20
+ const access = await bearerTokens.findByDigest(key)
21
+
22
+ if (access?.oauth) {
23
+ if (access.oauth.clientId === clientId)
24
+ await oauth!.refresh.revokeFamily(access.userId, access.oauth.family)
25
+
26
+ return { status: 200, body: {} }
27
+ }
28
+
29
+ // Looked at without spending it where the store can; a store without `get` can only spend it, which a holder of the token could do at the token endpoint too.
30
+ const refresh = oauth!.refresh.get ? await oauth!.refresh.get(key) : (await oauth!.refresh.use(key, new Date()))?.token
31
+
32
+ if (refresh?.clientId === clientId)
33
+ await oauth!.refresh.revokeFamily(refresh.userId, refresh.family)
34
+
35
+ return { status: 200, body: {} }
36
+ }
@@ -0,0 +1,87 @@
1
+ import type { Elysia } from 'elysia'
2
+ import type { Core } from '../core'
3
+ import type { RequestState } from '../state'
4
+ import { crossOriginPaths } from 'kay/server'
5
+ import { AUTHORIZATION_SERVER_PATH, authorizationServerMetadata, OPEN_HEADERS, OPENID_CONFIGURATION_PATH, rootIsFixed, siteRoot } from './metadata'
6
+ import { refused } from './reply'
7
+
8
+ const BODY_MAX_LENGTH = 16 * 1024
9
+ const DOCUMENT_HEADERS = { ...OPEN_HEADERS, 'content-type': 'application/json; charset=utf-8' }
10
+
11
+ function preflight(): Response {
12
+ return new Response(null, { status: 204, headers: { ...OPEN_HEADERS, 'access-control-max-age': '86400' } })
13
+ }
14
+
15
+ // The documents and endpoints an MCP client signs in through, on kayjs-auth's own plugin: nothing the app declares.
16
+ export function serveOAuthServer(plugin: Elysia, core: Core, stateOf: (ctx: unknown) => RequestState): void {
17
+ // Any site's client posts to these, so kay's own 413 for a body over the app's limit carries the same open grant.
18
+ crossOriginPaths(plugin, ['token', 'revoke', 'register'].map(name => `${core.prefix}/oauth/${name}`), { origins: '*' })
19
+
20
+ for (const path of [AUTHORIZATION_SERVER_PATH, OPENID_CONFIGURATION_PATH]) {
21
+ plugin
22
+ .get(path, ({ request }) => new Response(JSON.stringify(authorizationServerMetadata(core, siteRoot(core, request))), { headers: { ...DOCUMENT_HEADERS, 'cache-control': rootIsFixed(core) ? 'public, max-age=300' : 'private, max-age=300' } }))
23
+ .options(path, preflight)
24
+ }
25
+
26
+ const reply = (result: { status: number, body: Record<string, unknown> }): Response => new Response(JSON.stringify(result.body), { status: result.status, headers: { ...OPEN_HEADERS, 'content-type': 'application/json; charset=utf-8', 'cache-control': 'no-store', 'pragma': 'no-cache' } })
27
+
28
+ // The body is read here, not by Elysia, and stopped at the cap whatever the request claims to hold.
29
+ const read = async (request: Request): Promise<string | undefined> => {
30
+ if (!request.body)
31
+ return ''
32
+
33
+ if (Number(request.headers.get('content-length')) > BODY_MAX_LENGTH)
34
+ return undefined
35
+
36
+ const chunks: Uint8Array[] = []
37
+ let size = 0
38
+
39
+ for await (const chunk of request.body as unknown as AsyncIterable<Uint8Array>) {
40
+ size += chunk.byteLength
41
+
42
+ if (size > BODY_MAX_LENGTH)
43
+ return undefined
44
+
45
+ chunks.push(chunk)
46
+ }
47
+
48
+ return Buffer.concat(chunks).toString('utf8')
49
+ }
50
+
51
+ plugin
52
+ .post(`${core.prefix}/oauth/token`, async (ctx) => {
53
+ const state = stateOf(ctx)
54
+ const text = await read(ctx.request)
55
+
56
+ if (text === undefined)
57
+ return reply(refused('invalid_request', 'The request is too large'))
58
+
59
+ return reply(await (await import('./token')).tokenEndpoint(core, state.client, new URLSearchParams(text), siteRoot(core, ctx.request)))
60
+ }, { parse: 'none' })
61
+ .options(`${core.prefix}/oauth/token`, preflight)
62
+ .post(`${core.prefix}/oauth/revoke`, async (ctx) => {
63
+ const state = stateOf(ctx)
64
+ const text = await read(ctx.request)
65
+
66
+ if (text === undefined)
67
+ return reply(refused('invalid_request', 'The request is too large'))
68
+
69
+ return reply(await (await import('./revoke')).revokeEndpoint(core, state.client, new URLSearchParams(text)))
70
+ }, { parse: 'none' })
71
+ .options(`${core.prefix}/oauth/revoke`, preflight)
72
+ .post(`${core.prefix}/oauth/register`, async (ctx) => {
73
+ const state = stateOf(ctx)
74
+ const text = await read(ctx.request)
75
+ let document: unknown
76
+
77
+ try {
78
+ document = text === undefined ? undefined : JSON.parse(text)
79
+ }
80
+ catch {
81
+ document = undefined
82
+ }
83
+
84
+ return reply(await (await import('./register')).registerClient(core, state.client, document))
85
+ }, { parse: 'none' })
86
+ .options(`${core.prefix}/oauth/register`, preflight)
87
+ }
@@ -0,0 +1,213 @@
1
+ import type { Core } from '../core'
2
+ import type { OAuthCodeRecord, OAuthGrantRecord, OAuthRefreshRecord } from '../store'
3
+ import type { TokenReply } from './reply'
4
+ import { createHash } from 'node:crypto'
5
+ import { banned, sameText } from '../core'
6
+ import { digest, randomToken } from '../keys'
7
+ import { spend } from '../limits'
8
+ import { refused } from './reply'
9
+ import { covers, IMPLIED_SCOPES, sameResource, sameSite } from './request'
10
+
11
+ // Seconds an access token works for, a refresh token unused, and a whole family of them from its first token.
12
+ export const ACCESS_LIFETIME = 60 * 60
13
+ export const REFRESH_LIFETIME = 30 * 24 * 60 * 60
14
+ export const FAMILY_LIFETIME = 90 * 24 * 60 * 60
15
+ const VERIFIER = /^[\w.~-]{43,128}$/
16
+ const WHITESPACE = /\s+/
17
+
18
+ function matches(verifier: string, challenge: string): boolean {
19
+ return sameText(createHash('sha256').update(verifier).digest('base64url'), challenge)
20
+ }
21
+
22
+ // A bearer token and a refresh token of one family for the grant, which is how `user()`, `via()` and `requireUser({ scope })` see the client; the family ends at `familyEnd` whatever its rotations.
23
+ async function issue(core: Core, grant: OAuthGrantRecord, scopes: string[] | null, family: string, familyEnd: Date | undefined, resource: string | null): Promise<TokenReply> {
24
+ const oauth = core.store.oauth!
25
+ const now = new Date()
26
+ const access = randomToken()
27
+ const refresh = randomToken()
28
+
29
+ await core.store.bearerTokens.create({
30
+ id: crypto.randomUUID(),
31
+ userId: grant.userId,
32
+ label: grant.clientName,
33
+ digest: digest(access),
34
+ scopes,
35
+ createdAt: now,
36
+ lastUsedAt: null,
37
+ expiresAt: new Date(now.getTime() + ACCESS_LIFETIME * 1000),
38
+ oauth: { clientId: grant.clientId, family, resource },
39
+ })
40
+ await oauth.refresh.create({ digest: digest(refresh), userId: grant.userId, clientId: grant.clientId, scopes, family, resource, createdAt: now, expiresAt: familyEnd ?? new Date(now.getTime() + FAMILY_LIFETIME * 1000), usedAt: null })
41
+
42
+ return {
43
+ status: 200,
44
+ body: { access_token: access, token_type: 'Bearer', expires_in: ACCESS_LIFETIME, refresh_token: refresh, ...scopes !== null && scopes.length > 0 && { scope: scopes.join(' ') } },
45
+ }
46
+ }
47
+
48
+ // The resource the tokens are bound to: the one the code asked for, which a request may name again or leave out but not change or add. A reply when the request names another.
49
+ function boundResource(form: URLSearchParams, root: string, bound: string | null | undefined, legacy = false): { resource: string | null } | TokenReply {
50
+ const asked = form.getAll('resource')
51
+
52
+ if (asked.length === 0)
53
+ return { resource: bound ?? null }
54
+
55
+ if (asked.length > 1 || !sameSite(asked[0]!, root))
56
+ return refused('invalid_target', 'The resource is not one of this server')
57
+
58
+ // A refresh token stored before the column has no resource to compare, and a client names its resource on every refresh: it stays unbound.
59
+ if (legacy && bound == null)
60
+ return { resource: null }
61
+
62
+ return bound != null && sameResource(asked[0]!, bound) ? { resource: bound } : refused('invalid_target', 'The resource is not the one the tokens were asked for')
63
+ }
64
+
65
+ // The grant the tokens are issued under, while its user can sign in and has not revoked the client.
66
+ async function liveGrant(core: Core, userId: string, clientId: string): Promise<OAuthGrantRecord | undefined> {
67
+ const [grant, record] = await Promise.all([core.store.oauth!.grants.get(userId, clientId), core.store.users.get(userId)])
68
+
69
+ return grant && record && !banned(record) ? grant : undefined
70
+ }
71
+
72
+ function verified(verifier: string, issued: OAuthCodeRecord): boolean {
73
+ return VERIFIER.test(verifier) && matches(verifier, issued.challenge)
74
+ }
75
+
76
+ // What a code exchange asks for against the code: the resource the tokens are bound to, or the reply refusing a redirect_uri, a verifier or a resource the code does not hold.
77
+ function codeAsk(form: URLSearchParams, root: string, issued: OAuthCodeRecord, verifier: string): { resource: string | null } | TokenReply {
78
+ if (issued.redirectUri !== form.get('redirect_uri'))
79
+ return refused('invalid_grant', 'The code does not match this request')
80
+
81
+ if (!verified(verifier, issued))
82
+ return refused('invalid_grant', 'The code_verifier does not match the code_challenge')
83
+
84
+ return boundResource(form, root, issued.resource)
85
+ }
86
+
87
+ // A refresh token past the thirty days it may sit unused, or past the end of its family.
88
+ function lapsed(held: OAuthRefreshRecord): boolean {
89
+ return held.expiresAt <= new Date() || held.createdAt.getTime() + REFRESH_LIFETIME * 1000 <= Date.now()
90
+ }
91
+
92
+ async function exchangeCode(core: Core, form: URLSearchParams, root: string): Promise<TokenReply> {
93
+ const code = form.get('code')
94
+ const verifier = form.get('code_verifier')
95
+ const clientId = form.get('client_id')
96
+
97
+ if (code === null || verifier === null || clientId === null)
98
+ return refused('invalid_request', 'code, code_verifier and client_id are required')
99
+
100
+ const key = digest(code)
101
+ const peeked = await core.store.oauth!.codes.get?.(key)
102
+
103
+ // A request refused for its redirect_uri or resource leaves a live code unspent, so a mistake once does not cost the sign-in on the retry. A wrong verifier signals a stolen code, so it goes on to `use` and spends the code, as does a spent code (which revokes what it issued) and a code another client presented.
104
+ if (peeked && peeked.usedAt === null && peeked.clientId === clientId && peeked.expiresAt > new Date() && verified(verifier, peeked)) {
105
+ const asked = codeAsk(form, root, peeked, verifier)
106
+
107
+ if ('status' in asked)
108
+ return asked
109
+ }
110
+
111
+ const spent = await core.store.oauth!.codes.use(key, new Date())
112
+
113
+ if (!spent)
114
+ return refused('invalid_grant', 'The code is not valid')
115
+
116
+ if (spent.reused) {
117
+ await core.store.oauth!.refresh.revokeFamily(spent.code.userId, spent.code.family)
118
+
119
+ return refused('invalid_grant', 'The code was used already')
120
+ }
121
+
122
+ const issued = spent.code
123
+
124
+ if (issued.expiresAt <= new Date() || issued.clientId !== clientId)
125
+ return refused('invalid_grant', 'The code does not match this request')
126
+
127
+ const asked = codeAsk(form, root, issued, verifier)
128
+
129
+ if ('status' in asked)
130
+ return asked
131
+
132
+ // A code issued with every scope before the app declared some does not give them all now.
133
+ if (issued.scopes === null && core.scopes.size > 0)
134
+ return refused('invalid_grant', 'The client must be approved again')
135
+
136
+ const grant = await liveGrant(core, issued.userId, issued.clientId)
137
+
138
+ return grant ? issue(core, grant, issued.scopes, issued.family, undefined, asked.resource) : refused('invalid_grant', 'The client is not approved')
139
+ }
140
+
141
+ // What a refresh asks for: the scopes and the resource the new tokens get, or the reply refusing a scope the token lacks or a resource it is not bound to.
142
+ function refreshAsk(form: URLSearchParams, root: string, held: OAuthRefreshRecord): { scopes: string[] | null, resource: string | null } | TokenReply {
143
+ const asked = form.get('scope')
144
+ const scopes = asked === null ? held.scopes : asked.split(WHITESPACE).filter(each => each !== '' && !IMPLIED_SCOPES.has(each))
145
+
146
+ if (asked !== null && !covers(held.scopes, scopes))
147
+ return refused('invalid_scope', 'A refresh cannot add scopes')
148
+
149
+ const bound = boundResource(form, root, held.resource, true)
150
+
151
+ return 'status' in bound ? bound : { scopes, resource: bound.resource }
152
+ }
153
+
154
+ async function rotate(core: Core, form: URLSearchParams, root: string): Promise<TokenReply> {
155
+ const presented = form.get('refresh_token')
156
+ const clientId = form.get('client_id')
157
+
158
+ if (presented === null || clientId === null)
159
+ return refused('invalid_request', 'refresh_token and client_id are required')
160
+
161
+ const key = digest(presented)
162
+ const peeked = await core.store.oauth!.refresh.get?.(key)
163
+
164
+ // A request refused for what it asks leaves a live token unspent, so a mistake once does not cost the family on the retry. A spent token goes on to `use`, which revokes the family.
165
+ if (peeked && peeked.usedAt === null && peeked.clientId === clientId && !lapsed(peeked)) {
166
+ const asked = refreshAsk(form, root, peeked)
167
+
168
+ if ('status' in asked)
169
+ return asked
170
+ }
171
+
172
+ const spent = await core.store.oauth!.refresh.use(key, new Date())
173
+
174
+ if (!spent)
175
+ return refused('invalid_grant', 'The refresh token is not valid')
176
+
177
+ const held = spent.token
178
+
179
+ if (spent.reused) {
180
+ await core.store.oauth!.refresh.revokeFamily(held.userId, held.family)
181
+
182
+ return refused('invalid_grant', 'The refresh token was used already')
183
+ }
184
+
185
+ if (lapsed(held) || held.clientId !== clientId)
186
+ return refused('invalid_grant', 'The refresh token does not match this request')
187
+
188
+ // A token holding every scope, issued while the app declared none, does not cover those it declares since.
189
+ if (held.scopes === null && core.scopes.size > 0)
190
+ return refused('invalid_grant', 'The client must be approved again')
191
+
192
+ const asked = refreshAsk(form, root, held)
193
+
194
+ if ('status' in asked)
195
+ return asked
196
+
197
+ const grant = await liveGrant(core, held.userId, held.clientId)
198
+
199
+ return grant ? issue(core, grant, asked.scopes, held.family, held.expiresAt, asked.resource) : refused('invalid_grant', 'The client is not approved')
200
+ }
201
+
202
+ // The token endpoint: the authorization code grant with PKCE, and refresh tokens that rotate, a token used twice ending its family.
203
+ export async function tokenEndpoint(core: Core, address: string, form: URLSearchParams, root: string): Promise<TokenReply> {
204
+ if (await spend(core.rates, `oauth-token:${address}`, core.limits.oauthToken))
205
+ return refused('invalid_request', 'Too many requests', 429)
206
+
207
+ const type = form.get('grant_type')
208
+
209
+ if (type === 'authorization_code')
210
+ return exchangeCode(core, form, root)
211
+
212
+ return type === 'refresh_token' ? rotate(core, form, root) : refused('unsupported_grant_type', 'Only authorization_code and refresh_token are supported')
213
+ }