@kayjs/auth 0.0.0-stage → 1.104.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (407) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +78 -2
  3. package/llms/admin-and-organizations.md +70 -0
  4. package/llms/admin-pages.md +30 -0
  5. package/llms/grouped-methods.md +106 -0
  6. package/llms/hardening-and-testing.md +108 -0
  7. package/llms/oauth-passkeys-two-factor.md +111 -0
  8. package/llms/oauth-providers.md +28 -0
  9. package/llms/oauth-server-and-tokens.md +76 -0
  10. package/llms/organization-pages.md +20 -0
  11. package/llms/passwords-and-mails.md +129 -0
  12. package/llms/sessions-and-guards.md +51 -0
  13. package/llms/setup.md +122 -0
  14. package/llms/signed-in-components.md +59 -0
  15. package/llms.txt +28 -0
  16. package/package.json +85 -4
  17. package/src/access.ts +31 -0
  18. package/src/account.ts +198 -0
  19. package/src/add.ts +70 -0
  20. package/src/address.ts +51 -0
  21. package/src/admin.ts +361 -0
  22. package/src/auditWording.ts +153 -0
  23. package/src/auth.ts +219 -0
  24. package/src/authorize/clients.ts +160 -0
  25. package/src/authorize/grants.ts +44 -0
  26. package/src/authorize/metadata.ts +72 -0
  27. package/src/authorize/register.ts +38 -0
  28. package/src/authorize/reply.ts +9 -0
  29. package/src/authorize/request.ts +253 -0
  30. package/src/authorize/resource.ts +34 -0
  31. package/src/authorize/revoke.ts +36 -0
  32. package/src/authorize/routes.ts +87 -0
  33. package/src/authorize/token.ts +213 -0
  34. package/src/authorize/uris.ts +76 -0
  35. package/src/bearer.ts +208 -0
  36. package/src/bearerHeader.ts +11 -0
  37. package/src/breached.ts +47 -0
  38. package/src/browser.ts +59 -0
  39. package/src/captcha.ts +196 -0
  40. package/src/cbor.ts +129 -0
  41. package/src/components/deletion-banner.kay +20 -0
  42. package/src/components/impersonation-banner.kay +21 -0
  43. package/src/components/signed-in.kay +8 -0
  44. package/src/components/signed-out.kay +6 -0
  45. package/src/components/user-menu.kay +21 -0
  46. package/src/context.ts +5 -0
  47. package/src/core.ts +308 -0
  48. package/src/createUserCommand.ts +217 -0
  49. package/src/decide.ts +45 -0
  50. package/src/deletion.ts +80 -0
  51. package/src/devTool.ts +104 -0
  52. package/src/device.ts +37 -0
  53. package/src/email.ts +594 -0
  54. package/src/erase.ts +237 -0
  55. package/src/events.ts +297 -0
  56. package/src/export.ts +101 -0
  57. package/src/failure.ts +63 -0
  58. package/src/forwardAuth.ts +55 -0
  59. package/src/forwardRoutes.ts +68 -0
  60. package/src/gate.ts +104 -0
  61. package/src/guard.ts +22 -0
  62. package/src/guards.ts +72 -0
  63. package/src/guesses.ts +99 -0
  64. package/src/index.ts +46 -0
  65. package/src/keys.ts +51 -0
  66. package/src/limits.ts +182 -0
  67. package/src/load.ts +18 -0
  68. package/src/locale.ts +15 -0
  69. package/src/log.ts +4 -0
  70. package/src/mail.ts +225 -0
  71. package/src/memoryStore.ts +599 -0
  72. package/src/messages/fr.ts +357 -0
  73. package/src/methods/account.ts +80 -0
  74. package/src/methods/admin.ts +63 -0
  75. package/src/methods/audit.ts +15 -0
  76. package/src/methods/email.ts +39 -0
  77. package/src/methods/magicLink.ts +32 -0
  78. package/src/methods/oauth.ts +35 -0
  79. package/src/methods/oauthServer.ts +31 -0
  80. package/src/methods/organizations.ts +96 -0
  81. package/src/methods/passkeys.ts +61 -0
  82. package/src/methods/password.ts +53 -0
  83. package/src/methods/sessions.ts +18 -0
  84. package/src/methods/tokens.ts +24 -0
  85. package/src/methods/twoFactor.ts +62 -0
  86. package/src/oauth/client.ts +324 -0
  87. package/src/oauth/flow.ts +350 -0
  88. package/src/oauth/index.ts +5 -0
  89. package/src/oauth/pkce.ts +20 -0
  90. package/src/oauth/providers.ts +490 -0
  91. package/src/oauth/refresher.ts +177 -0
  92. package/src/oauth/timeout.ts +2 -0
  93. package/src/oauth/types.ts +78 -0
  94. package/src/oauthTest.ts +112 -0
  95. package/src/organizations.ts +675 -0
  96. package/src/organizationsCore.ts +60 -0
  97. package/src/own.ts +313 -0
  98. package/src/pages/components/captcha.kay +16 -0
  99. package/src/pages/components/frame.kay +11 -0
  100. package/src/pages/components/message.kay +8 -0
  101. package/src/pages/components/panel.kay +12 -0
  102. package/src/pages/components/passkey-add.kay +48 -0
  103. package/src/pages/components/passkey-sign-in.kay +34 -0
  104. package/src/pages/components/passkey-two-factor.kay +33 -0
  105. package/src/pages/components/proof.kay +15 -0
  106. package/src/pages/components/provider-buttons.kay +25 -0
  107. package/src/pages/components/recovery-codes.kay +13 -0
  108. package/src/pages/components/separator.kay +4 -0
  109. package/src/pages/english.ts +82 -0
  110. package/src/pages/forms.ts +185 -0
  111. package/src/pages/index.ts +361 -0
  112. package/src/pages/organizationPage.ts +12 -0
  113. package/src/pages/routes/account/_guard.ts +15 -0
  114. package/src/pages/routes/account/_layout.kay +37 -0
  115. package/src/pages/routes/account/clients.kay +33 -0
  116. package/src/pages/routes/account/connections.kay +57 -0
  117. package/src/pages/routes/account/data.kay +106 -0
  118. package/src/pages/routes/account/index.kay +109 -0
  119. package/src/pages/routes/account/organizations/[org].kay +188 -0
  120. package/src/pages/routes/account/organizations/_guard.ts +8 -0
  121. package/src/pages/routes/account/organizations/index.kay +86 -0
  122. package/src/pages/routes/account/security.kay +164 -0
  123. package/src/pages/routes/account/sessions.kay +51 -0
  124. package/src/pages/routes/account/tokens.kay +84 -0
  125. package/src/pages/routes/admin/_layout.kay +43 -0
  126. package/src/pages/routes/admin/audit.kay +43 -0
  127. package/src/pages/routes/admin/index.kay +60 -0
  128. package/src/pages/routes/admin/users/[id].kay +181 -0
  129. package/src/pages/routes/confirm-email.kay +39 -0
  130. package/src/pages/routes/invitation.kay +104 -0
  131. package/src/pages/routes/magic-link.kay +42 -0
  132. package/src/pages/routes/oauth/authorize.kay +80 -0
  133. package/src/pages/routes/register.kay +83 -0
  134. package/src/pages/routes/reset-password.kay +73 -0
  135. package/src/pages/routes/sign-in.kay +128 -0
  136. package/src/pages/routes/two-factor.kay +61 -0
  137. package/src/pages/routes/verify-email.kay +83 -0
  138. package/src/passkeys.ts +373 -0
  139. package/src/password.ts +316 -0
  140. package/src/payloads.ts +22 -0
  141. package/src/pg.ts +705 -0
  142. package/src/profile.ts +43 -0
  143. package/src/proof.ts +110 -0
  144. package/src/prune.ts +123 -0
  145. package/src/rates.ts +82 -0
  146. package/src/request.ts +712 -0
  147. package/src/requiredTwoFactor.ts +71 -0
  148. package/src/requirement.ts +23 -0
  149. package/src/roles.ts +18 -0
  150. package/src/routes.ts +202 -0
  151. package/src/rules-check.ts +37 -0
  152. package/src/rules.ts +108 -0
  153. package/src/securityNotice.ts +45 -0
  154. package/src/sessions.ts +184 -0
  155. package/src/setup.ts +417 -0
  156. package/src/signInOptions.ts +9 -0
  157. package/src/state.ts +34 -0
  158. package/src/store.ts +410 -0
  159. package/src/storeHelpers.ts +23 -0
  160. package/src/test.ts +46 -0
  161. package/src/testCookies.ts +9 -0
  162. package/src/testHelpers.ts +58 -0
  163. package/src/testing.ts +113 -0
  164. package/src/text.ts +6 -0
  165. package/src/totp.ts +120 -0
  166. package/src/twoFactor.ts +200 -0
  167. package/src/types.ts +23 -0
  168. package/src/userData.ts +47 -0
  169. package/src/viewer-layout/_layout.kay +11 -0
  170. package/src/viewer.ts +116 -0
  171. package/src/wayIn.ts +40 -0
  172. package/src/webauthn.ts +375 -0
  173. package/src/wsAuth.ts +53 -0
  174. package/types/access.d.ts +12 -0
  175. package/types/access.d.ts.map +1 -0
  176. package/types/account.d.ts +32 -0
  177. package/types/account.d.ts.map +1 -0
  178. package/types/add.d.ts +29 -0
  179. package/types/add.d.ts.map +1 -0
  180. package/types/address.d.ts +2 -0
  181. package/types/address.d.ts.map +1 -0
  182. package/types/admin.d.ts +84 -0
  183. package/types/admin.d.ts.map +1 -0
  184. package/types/auditWording.d.ts +9 -0
  185. package/types/auditWording.d.ts.map +1 -0
  186. package/types/auth.d.ts +3475 -0
  187. package/types/auth.d.ts.map +1 -0
  188. package/types/authorize/clients.d.ts +15 -0
  189. package/types/authorize/clients.d.ts.map +1 -0
  190. package/types/authorize/grants.d.ts +15 -0
  191. package/types/authorize/grants.d.ts.map +1 -0
  192. package/types/authorize/metadata.d.ts +20 -0
  193. package/types/authorize/metadata.d.ts.map +1 -0
  194. package/types/authorize/register.d.ts +4 -0
  195. package/types/authorize/register.d.ts.map +1 -0
  196. package/types/authorize/reply.d.ts +6 -0
  197. package/types/authorize/reply.d.ts.map +1 -0
  198. package/types/authorize/request.d.ts +48 -0
  199. package/types/authorize/request.d.ts.map +1 -0
  200. package/types/authorize/resource.d.ts +4 -0
  201. package/types/authorize/resource.d.ts.map +1 -0
  202. package/types/authorize/revoke.d.ts +4 -0
  203. package/types/authorize/revoke.d.ts.map +1 -0
  204. package/types/authorize/routes.d.ts +5 -0
  205. package/types/authorize/routes.d.ts.map +1 -0
  206. package/types/authorize/token.d.ts +7 -0
  207. package/types/authorize/token.d.ts.map +1 -0
  208. package/types/authorize/uris.d.ts +5 -0
  209. package/types/authorize/uris.d.ts.map +1 -0
  210. package/types/bearer.d.ts +45 -0
  211. package/types/bearer.d.ts.map +1 -0
  212. package/types/bearerHeader.d.ts +3 -0
  213. package/types/bearerHeader.d.ts.map +1 -0
  214. package/types/breached.d.ts +5 -0
  215. package/types/breached.d.ts.map +1 -0
  216. package/types/browser.d.ts +11 -0
  217. package/types/browser.d.ts.map +1 -0
  218. package/types/captcha.d.ts +42 -0
  219. package/types/captcha.d.ts.map +1 -0
  220. package/types/cbor.d.ts +4 -0
  221. package/types/cbor.d.ts.map +1 -0
  222. package/types/context.d.ts +3 -0
  223. package/types/context.d.ts.map +1 -0
  224. package/types/core.d.ts +180 -0
  225. package/types/core.d.ts.map +1 -0
  226. package/types/createUserCommand.d.ts +11 -0
  227. package/types/createUserCommand.d.ts.map +1 -0
  228. package/types/decide.d.ts +12 -0
  229. package/types/decide.d.ts.map +1 -0
  230. package/types/deletion.d.ts +17 -0
  231. package/types/deletion.d.ts.map +1 -0
  232. package/types/devTool.d.ts +3 -0
  233. package/types/devTool.d.ts.map +1 -0
  234. package/types/device.d.ts +7 -0
  235. package/types/device.d.ts.map +1 -0
  236. package/types/email.d.ts +73 -0
  237. package/types/email.d.ts.map +1 -0
  238. package/types/erase.d.ts +31 -0
  239. package/types/erase.d.ts.map +1 -0
  240. package/types/events.d.ts +139 -0
  241. package/types/events.d.ts.map +1 -0
  242. package/types/export.d.ts +54 -0
  243. package/types/export.d.ts.map +1 -0
  244. package/types/failure.d.ts +19 -0
  245. package/types/failure.d.ts.map +1 -0
  246. package/types/forwardAuth.d.ts +12 -0
  247. package/types/forwardAuth.d.ts.map +1 -0
  248. package/types/forwardRoutes.d.ts +11 -0
  249. package/types/forwardRoutes.d.ts.map +1 -0
  250. package/types/gate.d.ts +31 -0
  251. package/types/gate.d.ts.map +1 -0
  252. package/types/guard.d.ts +10 -0
  253. package/types/guard.d.ts.map +1 -0
  254. package/types/guards.d.ts +37 -0
  255. package/types/guards.d.ts.map +1 -0
  256. package/types/guesses.d.ts +18 -0
  257. package/types/guesses.d.ts.map +1 -0
  258. package/types/index.d.ts +47 -0
  259. package/types/index.d.ts.map +1 -0
  260. package/types/keys.d.ts +11 -0
  261. package/types/keys.d.ts.map +1 -0
  262. package/types/limits.d.ts +133 -0
  263. package/types/limits.d.ts.map +1 -0
  264. package/types/load.d.ts +18 -0
  265. package/types/load.d.ts.map +1 -0
  266. package/types/locale.d.ts +4 -0
  267. package/types/locale.d.ts.map +1 -0
  268. package/types/log.d.ts +2 -0
  269. package/types/log.d.ts.map +1 -0
  270. package/types/mail.d.ts +51 -0
  271. package/types/mail.d.ts.map +1 -0
  272. package/types/memoryStore.d.ts +3 -0
  273. package/types/memoryStore.d.ts.map +1 -0
  274. package/types/messages/fr.d.ts +409 -0
  275. package/types/messages/fr.d.ts.map +1 -0
  276. package/types/methods/account.d.ts +24 -0
  277. package/types/methods/account.d.ts.map +1 -0
  278. package/types/methods/admin.d.ts +30 -0
  279. package/types/methods/admin.d.ts.map +1 -0
  280. package/types/methods/audit.d.ts +11 -0
  281. package/types/methods/audit.d.ts.map +1 -0
  282. package/types/methods/email.d.ts +14 -0
  283. package/types/methods/email.d.ts.map +1 -0
  284. package/types/methods/magicLink.d.ts +12 -0
  285. package/types/methods/magicLink.d.ts.map +1 -0
  286. package/types/methods/oauth.d.ts +16 -0
  287. package/types/methods/oauth.d.ts.map +1 -0
  288. package/types/methods/oauthServer.d.ts +13 -0
  289. package/types/methods/oauthServer.d.ts.map +1 -0
  290. package/types/methods/organizations.d.ts +30 -0
  291. package/types/methods/organizations.d.ts.map +1 -0
  292. package/types/methods/passkeys.d.ts +19 -0
  293. package/types/methods/passkeys.d.ts.map +1 -0
  294. package/types/methods/password.d.ts +17 -0
  295. package/types/methods/password.d.ts.map +1 -0
  296. package/types/methods/sessions.d.ts +9 -0
  297. package/types/methods/sessions.d.ts.map +1 -0
  298. package/types/methods/tokens.d.ts +11 -0
  299. package/types/methods/tokens.d.ts.map +1 -0
  300. package/types/methods/twoFactor.d.ts +20 -0
  301. package/types/methods/twoFactor.d.ts.map +1 -0
  302. package/types/oauth/client.d.ts +39 -0
  303. package/types/oauth/client.d.ts.map +1 -0
  304. package/types/oauth/flow.d.ts +38 -0
  305. package/types/oauth/flow.d.ts.map +1 -0
  306. package/types/oauth/index.d.ts +6 -0
  307. package/types/oauth/index.d.ts.map +1 -0
  308. package/types/oauth/pkce.d.ts +10 -0
  309. package/types/oauth/pkce.d.ts.map +1 -0
  310. package/types/oauth/providers.d.ts +100 -0
  311. package/types/oauth/providers.d.ts.map +1 -0
  312. package/types/oauth/refresher.d.ts +55 -0
  313. package/types/oauth/refresher.d.ts.map +1 -0
  314. package/types/oauth/timeout.d.ts +2 -0
  315. package/types/oauth/timeout.d.ts.map +1 -0
  316. package/types/oauth/types.d.ts +75 -0
  317. package/types/oauth/types.d.ts.map +1 -0
  318. package/types/oauthTest.d.ts +23 -0
  319. package/types/oauthTest.d.ts.map +1 -0
  320. package/types/organizations.d.ts +111 -0
  321. package/types/organizations.d.ts.map +1 -0
  322. package/types/organizationsCore.d.ts +29 -0
  323. package/types/organizationsCore.d.ts.map +1 -0
  324. package/types/own.d.ts +55 -0
  325. package/types/own.d.ts.map +1 -0
  326. package/types/pages/english.d.ts +80 -0
  327. package/types/pages/english.d.ts.map +1 -0
  328. package/types/pages/forms.d.ts +204 -0
  329. package/types/pages/forms.d.ts.map +1 -0
  330. package/types/pages/index.d.ts +166 -0
  331. package/types/pages/index.d.ts.map +1 -0
  332. package/types/pages/organizationPage.d.ts +7 -0
  333. package/types/pages/organizationPage.d.ts.map +1 -0
  334. package/types/pages/routes/account/_guard.d.ts +3 -0
  335. package/types/pages/routes/account/_guard.d.ts.map +1 -0
  336. package/types/pages/routes/account/organizations/_guard.d.ts +3 -0
  337. package/types/pages/routes/account/organizations/_guard.d.ts.map +1 -0
  338. package/types/passkeys.d.ts +61 -0
  339. package/types/passkeys.d.ts.map +1 -0
  340. package/types/password.d.ts +49 -0
  341. package/types/password.d.ts.map +1 -0
  342. package/types/payloads.d.ts +4 -0
  343. package/types/payloads.d.ts.map +1 -0
  344. package/types/pg.d.ts +303 -0
  345. package/types/pg.d.ts.map +1 -0
  346. package/types/profile.d.ts +11 -0
  347. package/types/profile.d.ts.map +1 -0
  348. package/types/proof.d.ts +33 -0
  349. package/types/proof.d.ts.map +1 -0
  350. package/types/prune.d.ts +5 -0
  351. package/types/prune.d.ts.map +1 -0
  352. package/types/rates.d.ts +15 -0
  353. package/types/rates.d.ts.map +1 -0
  354. package/types/request.d.ts +119 -0
  355. package/types/request.d.ts.map +1 -0
  356. package/types/requiredTwoFactor.d.ts +16 -0
  357. package/types/requiredTwoFactor.d.ts.map +1 -0
  358. package/types/requirement.d.ts +4 -0
  359. package/types/requirement.d.ts.map +1 -0
  360. package/types/roles.d.ts +9 -0
  361. package/types/roles.d.ts.map +1 -0
  362. package/types/routes.d.ts +31 -0
  363. package/types/routes.d.ts.map +1 -0
  364. package/types/rules-check.d.ts +3 -0
  365. package/types/rules-check.d.ts.map +1 -0
  366. package/types/rules.d.ts +38 -0
  367. package/types/rules.d.ts.map +1 -0
  368. package/types/securityNotice.d.ts +7 -0
  369. package/types/securityNotice.d.ts.map +1 -0
  370. package/types/sessions.d.ts +32 -0
  371. package/types/sessions.d.ts.map +1 -0
  372. package/types/setup.d.ts +18 -0
  373. package/types/setup.d.ts.map +1 -0
  374. package/types/signInOptions.d.ts +6 -0
  375. package/types/signInOptions.d.ts.map +1 -0
  376. package/types/state.d.ts +25 -0
  377. package/types/state.d.ts.map +1 -0
  378. package/types/store.d.ts +295 -0
  379. package/types/store.d.ts.map +1 -0
  380. package/types/storeHelpers.d.ts +4 -0
  381. package/types/storeHelpers.d.ts.map +1 -0
  382. package/types/test.d.ts +21 -0
  383. package/types/test.d.ts.map +1 -0
  384. package/types/testCookies.d.ts +3 -0
  385. package/types/testCookies.d.ts.map +1 -0
  386. package/types/testHelpers.d.ts +34 -0
  387. package/types/testHelpers.d.ts.map +1 -0
  388. package/types/testing.d.ts +12 -0
  389. package/types/testing.d.ts.map +1 -0
  390. package/types/text.d.ts +2 -0
  391. package/types/text.d.ts.map +1 -0
  392. package/types/totp.d.ts +12 -0
  393. package/types/totp.d.ts.map +1 -0
  394. package/types/twoFactor.d.ts +41 -0
  395. package/types/twoFactor.d.ts.map +1 -0
  396. package/types/types.d.ts +17 -0
  397. package/types/types.d.ts.map +1 -0
  398. package/types/userData.d.ts +9 -0
  399. package/types/userData.d.ts.map +1 -0
  400. package/types/viewer.d.ts +23 -0
  401. package/types/viewer.d.ts.map +1 -0
  402. package/types/wayIn.d.ts +12 -0
  403. package/types/wayIn.d.ts.map +1 -0
  404. package/types/webauthn.d.ts +111 -0
  405. package/types/webauthn.d.ts.map +1 -0
  406. package/types/wsAuth.d.ts +14 -0
  407. package/types/wsAuth.d.ts.map +1 -0
@@ -0,0 +1,490 @@
1
+ import type { OAuthProvider, OAuthTokens, OAuthUser } from './types'
2
+ import { log } from '../log'
3
+ import { PROVIDER_TIMEOUT_MS } from './timeout'
4
+
5
+ const TRAILING_SLASHES = /\/+$/
6
+ const SCOPE_SEPARATORS = /[\s,]+/
7
+
8
+ /** What every provider preset takes: other `scopes` than its own, extra authorize URL `params` such as `{ prompt: 'consent' }`, and for one a server can host (GitHub Enterprise, GitLab, Discord's API), its base `url`, any trailing slash dropped and any path kept. */
9
+ export interface ProviderOptions {
10
+ scopes?: string[]
11
+ params?: Record<string, string>
12
+ url?: string
13
+ }
14
+ // The tenant Microsoft signs personal accounts in under, whatever the app's.
15
+ const MICROSOFT_PERSONAL_TENANT = '9188040d-6c67-4c5b-b112-36a304b66dad'
16
+ const APPLE_SECRET_LIFETIME_S = 24 * 60 * 60
17
+ // A cached Apple client secret is signed again this long before it ends.
18
+ const APPLE_SECRET_MARGIN_MS = 60 * 60 * 1000
19
+
20
+ interface DiscordRawUser {
21
+ id: string
22
+ username: string
23
+ global_name?: string | null
24
+ avatar?: string | null
25
+ banner?: string | null
26
+ email?: string | null
27
+ // Whether Discord checked `email`.
28
+ verified?: boolean
29
+ }
30
+
31
+ // Discord answers bare image hashes; a hash starting `a_` is animated, served as a gif.
32
+ function discordImage(kind: 'avatars' | 'banners', userId: string, hash: string | null | undefined): string | null {
33
+ return hash == null || hash === '' ? null : `https://cdn.discordapp.com/${kind}/${userId}/${hash}.${hash.startsWith('a_') ? 'gif' : 'png'}`
34
+ }
35
+
36
+ /** Discord OAuth2 provider preset, its avatar and banner as CDN URLs. `url` is the API's base, `https://discord.com/api/v10` by default, and `params` extra authorize URL parameters. */
37
+ export function discordProvider(opts: ProviderOptions = {}): OAuthProvider<DiscordRawUser> {
38
+ const apiBase = providerUrl(opts.url, 'https://discord.com/api/v10', 'the Discord url')
39
+
40
+ return {
41
+ name: 'discord',
42
+ label: 'Discord',
43
+ authorizeUrl: 'https://discord.com/oauth2/authorize',
44
+ tokenUrl: `${apiBase}/oauth2/token`,
45
+ revokeUrl: `${apiBase}/oauth2/token/revoke`,
46
+ userUrl: `${apiBase}/users/@me`,
47
+ scopes: opts.scopes ?? ['identify', 'email'],
48
+ ...opts.params === undefined ? {} : { authorizeParams: opts.params },
49
+ parseTokens: parseStandardTokens,
50
+ normalizeUser: raw => ({
51
+ providerId: raw.id,
52
+ username: raw.username,
53
+ displayName: raw.global_name ?? undefined,
54
+ avatar: discordImage('avatars', raw.id, raw.avatar),
55
+ banner: discordImage('banners', raw.id, raw.banner),
56
+ email: raw.verified === true ? raw.email ?? null : null,
57
+ }),
58
+ }
59
+ }
60
+
61
+ interface GithubRawUser {
62
+ id: number
63
+ login: string
64
+ name?: string | null
65
+ avatar_url?: string | null
66
+ email?: string | null
67
+ }
68
+
69
+ // GitHub's `/user/emails` list: the primary address is the one the account is known by.
70
+ interface GithubEmail {
71
+ email?: unknown
72
+ primary?: unknown
73
+ verified?: unknown
74
+ }
75
+
76
+ /** GitHub OAuth provider preset. Classic OAuth-App tokens do not expire, so `expiresAt` stays undefined. With the `user:email` scope the email is the account's primary verified address read off `/user/emails`, so a user hiding their email on their profile signs in with it all the same; without it, the public one. `url` is a GitHub Enterprise Server's base, as `https://git.example.com`. */
77
+ export function githubProvider(opts: ProviderOptions = {}): OAuthProvider<GithubRawUser> {
78
+ const base = opts.url === undefined ? undefined : providerUrl(opts.url, '', 'the GitHub url')
79
+ const api = base === undefined ? 'https://api.github.com' : `${base}/api/v3`
80
+ const scopes = opts.scopes ?? ['read:user']
81
+ const headers = {
82
+ 'User-Agent': '@kayjs/auth',
83
+ 'Accept': 'application/vnd.github+json',
84
+ }
85
+
86
+ return {
87
+ name: 'github',
88
+ label: 'GitHub',
89
+ authorizeUrl: `${base ?? 'https://github.com'}/login/oauth/authorize`,
90
+ tokenUrl: `${base ?? 'https://github.com'}/login/oauth/access_token`,
91
+ userUrl: `${api}/user`,
92
+ scopes,
93
+ ...opts.params === undefined ? {} : { authorizeParams: opts.params },
94
+ authHeaders: () => headers,
95
+ async completeUser(raw, { accessToken, scope }) {
96
+ // What the token was granted when GitHub said, else what was asked for.
97
+ const granted = new Set((scope ?? scopes.join(' ')).split(SCOPE_SEPARATORS))
98
+
99
+ if (!granted.has('user:email') && !granted.has('user'))
100
+ return raw
101
+
102
+ try {
103
+ const res = await fetch(`${api}/user/emails`, { headers: { ...headers, Authorization: `Bearer ${accessToken}` }, redirect: 'error', signal: AbortSignal.timeout(PROVIDER_TIMEOUT_MS) })
104
+
105
+ if (!res.ok)
106
+ throw new Error(`answered ${res.status}`)
107
+
108
+ const list = await res.json() as unknown
109
+ const primary = Array.isArray(list) ? (list as GithubEmail[]).find(entry => entry?.primary === true && entry.verified === true && typeof entry.email === 'string' && entry.email !== '') : undefined
110
+
111
+ return { ...raw, email: primary === undefined ? raw.email ?? null : primary.email as string }
112
+ }
113
+ catch (error) {
114
+ log.warn(`GitHub's /user/emails could not be read, the sign-in goes on with the profile's email: ${error instanceof Error ? error.message : String(error)}`)
115
+
116
+ return raw
117
+ }
118
+ },
119
+ parseTokens: parseStandardTokens,
120
+ normalizeUser: raw => ({
121
+ // Not `String(raw.id)`, which makes a missing id the string "undefined".
122
+ providerId: typeof raw.id === 'number' ? String(raw.id) : '',
123
+ username: raw.login,
124
+ displayName: raw.name ?? undefined,
125
+ avatar: raw.avatar_url ?? null,
126
+ email: raw.email ?? null,
127
+ }),
128
+ }
129
+ }
130
+
131
+ /** The standard OpenID Connect claims the presets read, off the ID token and the user endpoint. */
132
+ export interface OpenIdClaims {
133
+ sub: string
134
+ email?: string
135
+ // Apple sends it as the string 'true'.
136
+ email_verified?: boolean | string
137
+ name?: string
138
+ preferred_username?: string
139
+ nickname?: string
140
+ picture?: string
141
+ }
142
+
143
+ /** Options every OpenID Connect preset takes: other scopes than its own, and extra authorize URL parameters, such as Google's `{ access_type: 'offline', prompt: 'consent' }` for a refresh token. */
144
+ export interface OpenIdOptions {
145
+ scopes?: string[]
146
+ /** The `alg` values the provider signs ID tokens with, to narrow the asymmetric ones accepted by default (`RS*`, `PS*`, `ES*`, `EdDSA`), as `['RS256']`. */
147
+ algorithms?: string[]
148
+ params?: Record<string, string>
149
+ }
150
+
151
+ const OPENID_SCOPES = ['openid', 'email', 'profile']
152
+
153
+ // Anything but https is refused in production, where a plain-http endpoint lets whoever sits on the path read the codes and tokens or answer in the provider's place.
154
+ function requireHttps(url: string, what: string): void {
155
+ if (process.env.NODE_ENV === 'production' && new URL(url).protocol !== 'https:')
156
+ throw new Error(`${what} ${url} is not https, which production refuses`)
157
+ }
158
+
159
+ // A provider's base URL without its trailing slashes, `fallback` when the app gave none.
160
+ function providerUrl(url: string | undefined, fallback: string, what: string): string {
161
+ const base = (url ?? fallback).replace(TRAILING_SLASHES, '')
162
+
163
+ if (base === '' && url !== undefined)
164
+ throw new Error(`${what} is empty`)
165
+
166
+ if (base !== '')
167
+ requireHttps(base, what)
168
+
169
+ return base
170
+ }
171
+
172
+ /** Any OpenID Connect provider by its issuer URL, its endpoints read off its discovery document on first use: Keycloak, Authentik, Auth0, Okta, Zitadel... */
173
+ export function oidcProvider(opts: OpenIdOptions & { issuer: string, name?: string }): OAuthProvider<OpenIdClaims> {
174
+ const issuer = opts.issuer.replace(TRAILING_SLASHES, '')
175
+
176
+ requireHttps(issuer, 'the OpenID Connect issuer')
177
+
178
+ return {
179
+ name: opts.name ?? new URL(issuer).host,
180
+ discoveryBase: issuer,
181
+ scopes: opts.scopes ?? OPENID_SCOPES,
182
+ ...opts.params === undefined ? {} : { authorizeParams: opts.params },
183
+ discover: async () => {
184
+ const res = await fetch(`${issuer}/.well-known/openid-configuration`, { headers: { Accept: 'application/json' }, redirect: 'error', signal: AbortSignal.timeout(PROVIDER_TIMEOUT_MS) })
185
+
186
+ if (!res.ok)
187
+ throw new Error(`discovery document answered ${res.status}`)
188
+
189
+ const doc = await res.json() as Record<string, unknown>
190
+
191
+ // A document naming another issuer would let that issuer's tokens through.
192
+ if (typeof doc.issuer !== 'string' || doc.issuer.replace(TRAILING_SLASHES, '') !== issuer)
193
+ throw new Error(`discovery document names the issuer ${String(doc.issuer)}, not ${issuer}`)
194
+
195
+ for (const field of ['authorization_endpoint', 'token_endpoint', 'jwks_uri']) {
196
+ if (typeof doc[field] !== 'string')
197
+ throw new Error(`discovery document has no ${field}`)
198
+ }
199
+
200
+ for (const field of ['authorization_endpoint', 'token_endpoint', 'userinfo_endpoint', 'revocation_endpoint', 'jwks_uri']) {
201
+ if (typeof doc[field] === 'string')
202
+ requireHttps(doc[field], `the discovery document's ${field}`)
203
+ }
204
+
205
+ return {
206
+ authorizeUrl: doc.authorization_endpoint as string,
207
+ tokenUrl: doc.token_endpoint as string,
208
+ userUrl: typeof doc.userinfo_endpoint === 'string' ? doc.userinfo_endpoint : undefined,
209
+ revokeUrl: typeof doc.revocation_endpoint === 'string' ? doc.revocation_endpoint : undefined,
210
+ openId: { issuer: doc.issuer, jwksUrl: doc.jwks_uri as string, algorithms: opts.algorithms },
211
+ }
212
+ },
213
+ parseTokens: parseStandardTokens,
214
+ normalizeUser: openIdUser,
215
+ }
216
+ }
217
+
218
+ /** Google sign-in. */
219
+ export function googleProvider(opts: OpenIdOptions = {}): OAuthProvider<OpenIdClaims> {
220
+ return {
221
+ name: 'google',
222
+ label: 'Google',
223
+ authorizeUrl: 'https://accounts.google.com/o/oauth2/v2/auth',
224
+ tokenUrl: 'https://oauth2.googleapis.com/token',
225
+ revokeUrl: 'https://oauth2.googleapis.com/revoke',
226
+ openId: { issuer: ['https://accounts.google.com', 'accounts.google.com'], jwksUrl: 'https://www.googleapis.com/oauth2/v3/certs', algorithms: opts.algorithms },
227
+ scopes: opts.scopes ?? OPENID_SCOPES,
228
+ ...opts.params === undefined ? {} : { authorizeParams: opts.params },
229
+ parseTokens: parseStandardTokens,
230
+ // Google has no usernames.
231
+ normalizeUser: claims => ({ ...openIdUser(claims), username: '' }),
232
+ }
233
+ }
234
+
235
+ /** Microsoft sign-in. `tenant` is `common` (personal and work accounts, the default), `consumers` (personal only), `organizations` (work only) or one organization's tenant id. */
236
+ export function microsoftProvider(opts: OpenIdOptions & { tenant?: string } = {}): OAuthProvider<OpenIdClaims & { tid?: string, xms_edov?: boolean | string | number }> {
237
+ const tenant = opts.tenant ?? 'common'
238
+ const base = `https://login.microsoftonline.com/${tenant}`
239
+
240
+ return {
241
+ name: 'microsoft',
242
+ label: 'Microsoft',
243
+ authorizeUrl: `${base}/oauth2/v2.0/authorize`,
244
+ tokenUrl: `${base}/oauth2/v2.0/token`,
245
+ // The issuer names the account's own tenant, so a multi-tenant app checks it against the token's `tid`.
246
+ openId: { issuer: claims => microsoftIssued(tenant, claims), jwksUrl: `${base}/discovery/v2.0/keys`, algorithms: opts.algorithms },
247
+ scopes: opts.scopes ?? OPENID_SCOPES,
248
+ ...opts.params === undefined ? {} : { authorizeParams: opts.params },
249
+ parseTokens: parseStandardTokens,
250
+ normalizeUser: (claims) => {
251
+ // A work account's `email` is whatever its organization typed, verified only when the `xms_edov` optional claim says the domain's owner vouches for it.
252
+ const verified = claims.tid === MICROSOFT_PERSONAL_TENANT || claims.xms_edov === true || claims.xms_edov === '1' || claims.xms_edov === 1
253
+
254
+ // `preferred_username` is a sign-in address, not a name.
255
+ return { ...openIdUser(claims), username: '', email: verified ? claims.email ?? null : null }
256
+ },
257
+ }
258
+ }
259
+
260
+ function microsoftIssued(tenant: string, claims: Record<string, unknown>): boolean {
261
+ const tid = claims.tid
262
+
263
+ if (typeof tid !== 'string' || claims.iss !== `https://login.microsoftonline.com/${tid}/v2.0`)
264
+ return false
265
+
266
+ if (tenant === 'common')
267
+ return true
268
+
269
+ if (tenant === 'consumers')
270
+ return tid === MICROSOFT_PERSONAL_TENANT
271
+
272
+ return tenant === 'organizations' ? tid !== MICROSOFT_PERSONAL_TENANT : tid === tenant
273
+ }
274
+
275
+ /** GitLab sign-in, on gitlab.com or a self-hosted instance at `url`. */
276
+ export function gitlabProvider(opts: OpenIdOptions & { url?: string } = {}): OAuthProvider<OpenIdClaims> {
277
+ const base = providerUrl(opts.url, 'https://gitlab.com', 'the GitLab url')
278
+
279
+ return {
280
+ name: 'gitlab',
281
+ label: 'GitLab',
282
+ authorizeUrl: `${base}/oauth/authorize`,
283
+ tokenUrl: `${base}/oauth/token`,
284
+ revokeUrl: `${base}/oauth/revoke`,
285
+ userUrl: `${base}/oauth/userinfo`,
286
+ openId: { issuer: base, jwksUrl: `${base}/oauth/discovery/keys`, algorithms: opts.algorithms },
287
+ scopes: opts.scopes ?? OPENID_SCOPES,
288
+ ...opts.params === undefined ? {} : { authorizeParams: opts.params },
289
+ parseTokens: parseStandardTokens,
290
+ normalizeUser: openIdUser,
291
+ }
292
+ }
293
+
294
+ /** LinkedIn sign-in through OpenID Connect (the "Sign In with LinkedIn using OpenID Connect" product of the LinkedIn app). LinkedIn gives `email` only with the `email` scope and only when it has one, and has no usernames. */
295
+ export function linkedinProvider(opts: OpenIdOptions = {}): OAuthProvider<OpenIdClaims> {
296
+ return {
297
+ name: 'linkedin',
298
+ label: 'LinkedIn',
299
+ authorizeUrl: 'https://www.linkedin.com/oauth/v2/authorization',
300
+ tokenUrl: 'https://www.linkedin.com/oauth/v2/accessToken',
301
+ userUrl: 'https://api.linkedin.com/v2/userinfo',
302
+ openId: { issuer: 'https://www.linkedin.com', jwksUrl: 'https://www.linkedin.com/oauth/openid/jwks', algorithms: opts.algorithms ?? ['RS256'] },
303
+ scopes: opts.scopes ?? OPENID_SCOPES,
304
+ ...opts.params === undefined ? {} : { authorizeParams: opts.params },
305
+ parseTokens: parseStandardTokens,
306
+ normalizeUser: claims => ({ ...openIdUser(claims), username: '' }),
307
+ }
308
+ }
309
+
310
+ /** Sign in with Slack (OpenID Connect). `scopes` are `openid`, `email` and `profile` by default; `team` in `params` (`{ team: 'T0123' }`) signs the user into that workspace. The user's `sub` is their Slack user id. */
311
+ export function slackProvider(opts: OpenIdOptions = {}): OAuthProvider<OpenIdClaims> {
312
+ return {
313
+ name: 'slack',
314
+ label: 'Slack',
315
+ authorizeUrl: 'https://slack.com/openid/connect/authorize',
316
+ tokenUrl: 'https://slack.com/api/openid.connect.token',
317
+ userUrl: 'https://slack.com/api/openid.connect.userInfo',
318
+ openId: { issuer: 'https://slack.com', jwksUrl: 'https://slack.com/openid/connect/keys', algorithms: opts.algorithms ?? ['RS256'] },
319
+ scopes: opts.scopes ?? OPENID_SCOPES,
320
+ ...opts.params === undefined ? {} : { authorizeParams: opts.params },
321
+ parseTokens: parseStandardTokens,
322
+ // Slack has no usernames: `name` is the display name.
323
+ normalizeUser: claims => ({ ...openIdUser(claims), username: '' }),
324
+ }
325
+ }
326
+
327
+ // What Twitch puts in the ID token only when asked: its claims are not there by scope alone.
328
+ const TWITCH_CLAIMS = JSON.stringify({ id_token: { email: null, email_verified: null, picture: null, preferred_username: null } })
329
+
330
+ /** Twitch sign-in through OpenID Connect. Twitch puts `email`, `email_verified`, `picture` and `preferred_username` in the ID token only when the authorize URL's `claims` parameter asks for them, which the preset does; the email also needs the `user:read:email` scope, both on by default, and Twitch sends it only when verified. */
331
+ export function twitchProvider(opts: OpenIdOptions = {}): OAuthProvider<OpenIdClaims> {
332
+ return {
333
+ name: 'twitch',
334
+ label: 'Twitch',
335
+ authorizeUrl: 'https://id.twitch.tv/oauth2/authorize',
336
+ tokenUrl: 'https://id.twitch.tv/oauth2/token',
337
+ revokeUrl: 'https://id.twitch.tv/oauth2/revoke',
338
+ openId: { issuer: 'https://id.twitch.tv/oauth2', jwksUrl: 'https://id.twitch.tv/oauth2/keys', algorithms: opts.algorithms ?? ['RS256'] },
339
+ scopes: opts.scopes ?? ['openid', 'user:read:email'],
340
+ authorizeParams: { claims: TWITCH_CLAIMS, ...opts.params },
341
+ parseTokens: parseStandardTokens,
342
+ normalizeUser: openIdUser,
343
+ }
344
+ }
345
+
346
+ interface XRawUser {
347
+ data?: { id?: string, name?: string, username?: string, profile_image_url?: string }
348
+ }
349
+
350
+ /** Sign in with X: OAuth 2.0 with PKCE, the user read off `users/me`. X gives no email through this flow, so a user signs up without one and `email` stays null. A confidential client is authenticated with an HTTP Basic header, which the preset sets. Default scopes are `users.read` and `tweet.read`; add `offline.access` for a refresh token, as X's access tokens last two hours. */
351
+ export function xProvider(opts: ProviderOptions = {}): OAuthProvider<XRawUser> {
352
+ const api = providerUrl(opts.url, 'https://api.x.com', 'the X url')
353
+
354
+ return {
355
+ name: 'x',
356
+ label: 'X',
357
+ authorizeUrl: 'https://x.com/i/oauth2/authorize',
358
+ tokenUrl: `${api}/2/oauth2/token`,
359
+ revokeUrl: `${api}/2/oauth2/revoke`,
360
+ userUrl: `${api}/2/users/me?user.fields=profile_image_url`,
361
+ clientAuth: 'basic',
362
+ scopes: opts.scopes ?? ['users.read', 'tweet.read'],
363
+ ...opts.params === undefined ? {} : { authorizeParams: opts.params },
364
+ parseTokens: parseStandardTokens,
365
+ normalizeUser: ({ data }) => ({
366
+ providerId: typeof data?.id === 'string' ? data.id : '',
367
+ username: data?.username ?? '',
368
+ displayName: data?.name,
369
+ avatar: data?.profile_image_url ?? null,
370
+ email: null,
371
+ }),
372
+ }
373
+ }
374
+
375
+ interface FacebookRawUser {
376
+ id: string
377
+ name?: string
378
+ email?: string
379
+ picture?: { data?: { url?: string } }
380
+ }
381
+
382
+ // The Graph API version in the URLs, as Meta's login docs show it today; Meta retires old ones, so an app can name another.
383
+ const FACEBOOK_VERSION = 'v27.0'
384
+
385
+ /** Facebook Login: OAuth 2.0 on the Graph API. Scopes are `public_profile` and `email`, and Facebook gives no email for an account with no valid address. `version` is the Graph API version in the endpoints, `v27.0` by default. Facebook has no usernames. */
386
+ export function facebookProvider(opts: Pick<ProviderOptions, 'scopes' | 'params'> & { version?: string } = {}): OAuthProvider<FacebookRawUser> {
387
+ const version = opts.version ?? FACEBOOK_VERSION
388
+
389
+ return {
390
+ name: 'facebook',
391
+ label: 'Facebook',
392
+ authorizeUrl: `https://www.facebook.com/${version}/dialog/oauth`,
393
+ tokenUrl: `https://graph.facebook.com/${version}/oauth/access_token`,
394
+ userUrl: `https://graph.facebook.com/${version}/me?fields=id,name,email,picture.type(large)`,
395
+ scopes: opts.scopes ?? ['public_profile', 'email'],
396
+ scopeSeparator: ',',
397
+ ...opts.params === undefined ? {} : { authorizeParams: opts.params },
398
+ parseTokens: parseStandardTokens,
399
+ normalizeUser: raw => ({
400
+ providerId: typeof raw.id === 'string' ? raw.id : '',
401
+ username: '',
402
+ displayName: raw.name,
403
+ avatar: raw.picture?.data?.url ?? null,
404
+ email: raw.email ?? null,
405
+ }),
406
+ }
407
+ }
408
+
409
+ /** Sign in with Apple. Its client secret is a JWT signed with the app's key from the Apple developer account: `teamId`, the key's `keyId`, and `privateKey`, the `.p8` file's PEM text. The app's `clientId` is its Services ID, and it needs no `clientSecret`. */
410
+ export function appleProvider(opts: Pick<ProviderOptions, 'scopes' | 'params'> & { teamId: string, keyId: string, privateKey: string }): OAuthProvider<OpenIdClaims> {
411
+ let key: Promise<CryptoKey> | undefined
412
+ let signed: { clientId: string, value: string, expires: number } | undefined
413
+
414
+ return {
415
+ name: 'apple',
416
+ label: 'Apple',
417
+ authorizeUrl: 'https://appleid.apple.com/auth/authorize',
418
+ tokenUrl: 'https://appleid.apple.com/auth/token',
419
+ revokeUrl: 'https://appleid.apple.com/auth/revoke',
420
+ openId: { issuer: 'https://appleid.apple.com', jwksUrl: 'https://appleid.apple.com/auth/keys' },
421
+ scopes: opts.scopes ?? ['name', 'email'],
422
+ // Apple answers a request for the name or the email only through a POST back to the callback.
423
+ authorizeParams: { ...opts.params, response_mode: 'form_post' },
424
+ async clientSecret(clientId) {
425
+ if (signed?.clientId === clientId && signed.expires - Date.now() > APPLE_SECRET_MARGIN_MS)
426
+ return signed.value
427
+
428
+ // jose loads when Apple's secret is first signed.
429
+ const { importPKCS8, SignJWT } = await import('jose')
430
+
431
+ key ??= importPKCS8(opts.privateKey, 'ES256')
432
+
433
+ const now = Math.floor(Date.now() / 1000)
434
+ const value = await new SignJWT({})
435
+ .setProtectedHeader({ alg: 'ES256', kid: opts.keyId })
436
+ .setIssuer(opts.teamId)
437
+ .setSubject(clientId)
438
+ .setAudience('https://appleid.apple.com')
439
+ .setIssuedAt(now)
440
+ .setExpirationTime(now + APPLE_SECRET_LIFETIME_S)
441
+ .sign(await key)
442
+
443
+ signed = { clientId, value, expires: (now + APPLE_SECRET_LIFETIME_S) * 1000 }
444
+
445
+ return value
446
+ },
447
+ parseTokens: parseStandardTokens,
448
+ // Apple has no usernames, and names the user only on their first sign-in, in the callback's `user` rather than the token.
449
+ normalizeUser: (claims, callback) => ({ ...openIdUser(claims), username: '', displayName: appleName(callback?.user) }),
450
+ }
451
+ }
452
+
453
+ function appleName(user: string | undefined): string | undefined {
454
+ try {
455
+ const name = (JSON.parse(user ?? '{}') as { name?: { firstName?: unknown, lastName?: unknown } }).name
456
+ const parts = [name?.firstName, name?.lastName].filter(part => typeof part === 'string' && part.trim() !== '')
457
+
458
+ return parts.length > 0 ? parts.join(' ') : undefined
459
+ }
460
+ catch {
461
+ return undefined
462
+ }
463
+ }
464
+
465
+ function openIdUser(claims: OpenIdClaims): OAuthUser {
466
+ return {
467
+ providerId: typeof claims.sub === 'string' ? claims.sub : '',
468
+ username: claims.preferred_username ?? claims.nickname ?? '',
469
+ displayName: claims.name ?? undefined,
470
+ avatar: claims.picture ?? null,
471
+ email: claims.email_verified === true || claims.email_verified === 'true' ? claims.email ?? null : null,
472
+ }
473
+ }
474
+
475
+ /** Maps a standard OAuth2 token payload (`access_token`, `expires_in`, ...) to `OAuthTokens`. */
476
+ function parseStandardTokens(raw: unknown): OAuthTokens {
477
+ const answer = (raw ?? {}) as { access_token?: unknown, refresh_token?: string | null, expires_in?: unknown, scope?: string | null, token_type?: string | null, id_token?: unknown, error?: string | null }
478
+
479
+ if (typeof answer.access_token !== 'string' || answer.access_token === '')
480
+ throw new Error(`OAuth token response missing access_token${answer.error == null || answer.error === '' ? '' : `: ${answer.error}`}`)
481
+
482
+ return {
483
+ accessToken: answer.access_token,
484
+ refreshToken: answer.refresh_token ?? undefined,
485
+ expiresAt: typeof answer.expires_in === 'number' ? new Date(Date.now() + answer.expires_in * 1000) : undefined,
486
+ scope: answer.scope ?? undefined,
487
+ tokenType: answer.token_type ?? undefined,
488
+ idToken: typeof answer.id_token === 'string' ? answer.id_token : undefined,
489
+ }
490
+ }
@@ -0,0 +1,177 @@
1
+ import type { Duration } from 'kay'
2
+ import type { OAuthTokens } from './types'
3
+ import { MINUTE_MS } from '@kaynooo/utils'
4
+ import { optionMs } from 'kay/library'
5
+ import { OAuthExchangeError } from './client'
6
+
7
+ // The answers by which a provider refuses the refresh token itself; anything else, an outage or a rate limit, may pass.
8
+ const REFUSED_STATUSES = new Set([400, 401])
9
+
10
+ /** The currently-stored credential for a subject; `expiresAt` null/undefined = non-expiring. */
11
+ export interface StoredCredential {
12
+ accessToken?: string | null | undefined
13
+ refreshToken?: string | null | undefined
14
+ expiresAt?: Date | null | undefined
15
+ }
16
+
17
+ export interface TokenRefresherDeps<K, S> {
18
+ /** Cache key for a subject (e.g. the user's id). */
19
+ key: (subject: S) => K
20
+ /** Reads the subject's stored credential. */
21
+ load: (subject: S) => StoredCredential
22
+ /** Performs the refresh + persistence; returns the new token, or `null` when refresh failed. */
23
+ exchange: (subject: S) => Promise<{ accessToken: string, expiresAt?: Date | undefined } | null>
24
+ /** How long before expiry to refresh, `'5m'` by default. */
25
+ margin?: Duration | undefined
26
+ }
27
+
28
+ /** Wraps a token `exchange` with per-subject caching + in-flight dedup; non-expiring credentials pass through. Feeds `GrantStore.hasCredential` (non-null = live). */
29
+ export function createTokenRefresher<K, S>(deps: TokenRefresherDeps<K, S>) {
30
+ const margin = deps.margin === undefined ? 5 * MINUTE_MS : optionMs(deps.margin, 'margin')
31
+ // Decisions: not kay's `cache()`, as each refresher has its own `exchange` and the expiry is only known from its answer.
32
+ const cache = new Map<K, { accessToken: string, expiresAt: number }>()
33
+ const inFlight = new Map<K, Promise<string | null>>()
34
+
35
+ return {
36
+ async getValidToken(subject: S): Promise<string | null> {
37
+ const stored = deps.load(subject)
38
+
39
+ if (stored.accessToken == null || stored.accessToken === '')
40
+ return null
41
+
42
+ if (stored.expiresAt === undefined || stored.expiresAt === null)
43
+ return stored.accessToken
44
+
45
+ const now = Date.now()
46
+ const key = deps.key(subject)
47
+ const cached = cache.get(key)
48
+
49
+ if (cached && cached.expiresAt > now + margin)
50
+ return cached.accessToken
51
+
52
+ if (cached && cached.expiresAt <= now)
53
+ cache.delete(key)
54
+
55
+ // `new Date` also reads the epoch milliseconds a store or provider written before 1.88 gives.
56
+ if (new Date(stored.expiresAt).getTime() > now + margin)
57
+ return stored.accessToken
58
+
59
+ if (stored.refreshToken == null || stored.refreshToken === '')
60
+ return null
61
+
62
+ const existing = inFlight.get(key)
63
+
64
+ if (existing)
65
+ return existing
66
+
67
+ const refresh = (async (): Promise<string | null> => {
68
+ try {
69
+ const result = await deps.exchange(subject)
70
+
71
+ if (!result) {
72
+ cache.delete(key)
73
+
74
+ return null
75
+ }
76
+
77
+ // Entries past their expiry are never read again, so they go as a new one comes.
78
+ for (const [other, entry] of cache) {
79
+ if (entry.expiresAt <= Date.now())
80
+ cache.delete(other)
81
+ }
82
+
83
+ if (result.expiresAt !== undefined)
84
+ cache.set(key, { accessToken: result.accessToken, expiresAt: new Date(result.expiresAt).getTime() })
85
+
86
+ return result.accessToken
87
+ }
88
+ catch (err) {
89
+ cache.delete(key)
90
+
91
+ throw err
92
+ }
93
+ finally {
94
+ inFlight.delete(key)
95
+ }
96
+ })()
97
+
98
+ inFlight.set(key, refresh)
99
+
100
+ return refresh
101
+ },
102
+ }
103
+ }
104
+
105
+ /** The `createOAuthClient` slice `createOAuthTokenRefresher` drives. */
106
+ export interface RefreshableOAuthClient {
107
+ refreshTokens: (refreshToken: string) => Promise<OAuthTokens>
108
+ }
109
+
110
+ /** Which step failed, for `onError` reporting. */
111
+ export type RefreshStage = 'refresh' | 'persist' | 'revoke'
112
+
113
+ export interface OAuthTokenRefresherDeps<K, S> {
114
+ /** The configured client performing the refresh (`createOAuthClient(provider, config)`). */
115
+ oauth: RefreshableOAuthClient
116
+ /** Cache key for a subject (e.g. the user's id). */
117
+ key: (subject: S) => K
118
+ /** Reads the subject's stored credential. */
119
+ load: (subject: S) => StoredCredential
120
+ /** Persists the outcome. `tokens` is `null` when the provider refused the refresh token, the credential revoked upstream: write nulls so the stale access token stops being treated as live. Keep `refreshToken` when a rotation response omits it. */
121
+ save: (subject: S, tokens: OAuthTokens | null) => Promise<void>
122
+ /** Notified when a step throws; the refresher itself never rejects. */
123
+ onError?: ((error: unknown, stage: RefreshStage) => void) | undefined
124
+ /** How long before expiry to refresh, `'5m'` by default. */
125
+ margin?: Duration | undefined
126
+ }
127
+
128
+ /**
129
+ * `createTokenRefresher` bound to an OAuth client: refreshes through `oauth.refreshTokens` and persists via `save`, so consumers supply field mapping only.
130
+ *
131
+ * A refresh the provider refuses (a 400 or a 401) calls `save(subject, null)` rather than leaving the old credential in place, since a token revoked at the provider would otherwise keep granting access. Any other failure yields null for now and keeps the credential.
132
+ * A `save` failure after a successful refresh is reported but not fatal: the token is valid, and the refresher's cache carries it until the next write succeeds.
133
+ */
134
+ export function createOAuthTokenRefresher<K, S>(deps: OAuthTokenRefresherDeps<K, S>) {
135
+ return createTokenRefresher<K, S>({
136
+ key: deps.key,
137
+ load: deps.load,
138
+ margin: deps.margin,
139
+ exchange: async (subject) => {
140
+ const refreshToken = deps.load(subject).refreshToken
141
+
142
+ if (refreshToken == null || refreshToken === '')
143
+ return null
144
+
145
+ let tokens: OAuthTokens
146
+
147
+ try {
148
+ tokens = await deps.oauth.refreshTokens(refreshToken)
149
+ }
150
+ catch (error) {
151
+ deps.onError?.(error, 'refresh')
152
+
153
+ // Kept through an outage, and through a race another process won with a rotated token: only a refusal forgets them.
154
+ if (!(error instanceof OAuthExchangeError && REFUSED_STATUSES.has(error.status)))
155
+ return null
156
+
157
+ try {
158
+ await deps.save(subject, null)
159
+ }
160
+ catch (revokeError) {
161
+ deps.onError?.(revokeError, 'revoke')
162
+ }
163
+
164
+ return null
165
+ }
166
+
167
+ try {
168
+ await deps.save(subject, tokens)
169
+ }
170
+ catch (error) {
171
+ deps.onError?.(error, 'persist')
172
+ }
173
+
174
+ return { accessToken: tokens.accessToken, expiresAt: tokens.expiresAt }
175
+ },
176
+ })
177
+ }
@@ -0,0 +1,2 @@
1
+ // How long a provider may take to answer before the sign-in or refresh waiting on it gives up.
2
+ export const PROVIDER_TIMEOUT_MS = 10_000