@better-auth/core 1.5.0-beta.2 → 1.5.0-beta.20

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 (331) hide show
  1. package/LICENSE.md +15 -12
  2. package/README.md +17 -0
  3. package/dist/api/index.d.mts +280 -2
  4. package/dist/api/index.mjs +4 -2
  5. package/dist/api/index.mjs.map +1 -0
  6. package/dist/async_hooks/index.d.mts +2 -1
  7. package/dist/async_hooks/index.mjs +2 -1
  8. package/dist/async_hooks/index.mjs.map +1 -0
  9. package/dist/async_hooks/pure.index.d.mts +2 -1
  10. package/dist/async_hooks/pure.index.mjs +2 -1
  11. package/dist/async_hooks/pure.index.mjs.map +1 -0
  12. package/dist/context/endpoint-context.d.mts +20 -0
  13. package/dist/context/endpoint-context.mjs +32 -0
  14. package/dist/context/endpoint-context.mjs.map +1 -0
  15. package/dist/context/global.d.mts +7 -0
  16. package/dist/context/global.mjs +38 -0
  17. package/dist/context/global.mjs.map +1 -0
  18. package/dist/context/index.d.mts +5 -53
  19. package/dist/context/index.mjs +5 -2
  20. package/dist/context/request-state.d.mts +28 -0
  21. package/dist/context/request-state.mjs +50 -0
  22. package/dist/context/request-state.mjs.map +1 -0
  23. package/dist/context/transaction.d.mts +25 -0
  24. package/dist/context/transaction.mjs +96 -0
  25. package/dist/context/transaction.mjs.map +1 -0
  26. package/dist/db/adapter/factory.d.mts +20 -0
  27. package/dist/db/adapter/factory.mjs +725 -0
  28. package/dist/db/adapter/factory.mjs.map +1 -0
  29. package/dist/db/adapter/get-default-field-name.d.mts +19 -0
  30. package/dist/db/adapter/get-default-field-name.mjs +39 -0
  31. package/dist/db/adapter/get-default-field-name.mjs.map +1 -0
  32. package/dist/db/adapter/get-default-model-name.d.mts +13 -0
  33. package/dist/db/adapter/get-default-model-name.mjs +33 -0
  34. package/dist/db/adapter/get-default-model-name.mjs.map +1 -0
  35. package/dist/db/adapter/get-field-attributes.d.mts +30 -0
  36. package/dist/db/adapter/get-field-attributes.mjs +40 -0
  37. package/dist/db/adapter/get-field-attributes.mjs.map +1 -0
  38. package/dist/db/adapter/get-field-name.d.mts +19 -0
  39. package/dist/db/adapter/get-field-name.mjs +34 -0
  40. package/dist/db/adapter/get-field-name.mjs.map +1 -0
  41. package/dist/db/adapter/get-id-field.d.mts +40 -0
  42. package/dist/db/adapter/get-id-field.mjs +68 -0
  43. package/dist/db/adapter/get-id-field.mjs.map +1 -0
  44. package/dist/db/adapter/get-model-name.d.mts +13 -0
  45. package/dist/db/adapter/get-model-name.mjs +24 -0
  46. package/dist/db/adapter/get-model-name.mjs.map +1 -0
  47. package/dist/db/adapter/index.d.mts +520 -2
  48. package/dist/db/adapter/index.mjs +27 -972
  49. package/dist/db/adapter/index.mjs.map +1 -0
  50. package/dist/db/adapter/types.d.mts +108 -0
  51. package/dist/db/adapter/utils.d.mts +8 -0
  52. package/dist/db/adapter/utils.mjs +39 -0
  53. package/dist/db/adapter/utils.mjs.map +1 -0
  54. package/dist/db/get-tables.d.mts +9 -0
  55. package/dist/{get-tables-CMc_Emww.mjs → db/get-tables.mjs} +52 -39
  56. package/dist/db/get-tables.mjs.map +1 -0
  57. package/dist/db/index.d.mts +10 -2
  58. package/dist/db/index.mjs +7 -60
  59. package/dist/db/plugin.d.mts +13 -0
  60. package/dist/db/schema/account.d.mts +30 -0
  61. package/dist/db/schema/account.mjs +20 -0
  62. package/dist/db/schema/account.mjs.map +1 -0
  63. package/dist/db/schema/rate-limit.d.mts +20 -0
  64. package/dist/db/schema/rate-limit.mjs +12 -0
  65. package/dist/db/schema/rate-limit.mjs.map +1 -0
  66. package/dist/db/schema/session.d.mts +25 -0
  67. package/dist/db/schema/session.mjs +15 -0
  68. package/dist/db/schema/session.mjs.map +1 -0
  69. package/dist/db/schema/shared.d.mts +11 -0
  70. package/dist/db/schema/shared.mjs +12 -0
  71. package/dist/db/schema/shared.mjs.map +1 -0
  72. package/dist/db/schema/user.d.mts +24 -0
  73. package/dist/db/schema/user.mjs +14 -0
  74. package/dist/db/schema/user.mjs.map +1 -0
  75. package/dist/db/schema/verification.d.mts +23 -0
  76. package/dist/db/schema/verification.mjs +13 -0
  77. package/dist/db/schema/verification.mjs.map +1 -0
  78. package/dist/db/type.d.mts +169 -0
  79. package/dist/env/color-depth.d.mts +5 -0
  80. package/dist/env/color-depth.mjs +89 -0
  81. package/dist/env/color-depth.mjs.map +1 -0
  82. package/dist/env/env-impl.d.mts +33 -0
  83. package/dist/env/env-impl.mjs +83 -0
  84. package/dist/env/env-impl.mjs.map +1 -0
  85. package/dist/env/index.d.mts +4 -2
  86. package/dist/env/index.mjs +3 -1
  87. package/dist/{index-BRBu0-5h.d.mts → env/logger.d.mts} +2 -35
  88. package/dist/env/logger.mjs +82 -0
  89. package/dist/env/logger.mjs.map +1 -0
  90. package/dist/error/codes.d.mts +69 -0
  91. package/dist/{error-C7mY-p0f.mjs → error/codes.mjs} +7 -30
  92. package/dist/error/codes.mjs.map +1 -0
  93. package/dist/error/index.d.mts +6 -187
  94. package/dist/error/index.mjs +29 -4
  95. package/dist/error/index.mjs.map +1 -0
  96. package/dist/index.d.mts +8 -2
  97. package/dist/oauth2/client-credentials-token.d.mts +58 -0
  98. package/dist/oauth2/client-credentials-token.mjs +67 -0
  99. package/dist/oauth2/client-credentials-token.mjs.map +1 -0
  100. package/dist/oauth2/create-authorization-url.d.mts +48 -0
  101. package/dist/oauth2/create-authorization-url.mjs +44 -0
  102. package/dist/oauth2/create-authorization-url.mjs.map +1 -0
  103. package/dist/oauth2/index.d.mts +8 -2
  104. package/dist/oauth2/index.mjs +7 -3
  105. package/dist/oauth2/oauth-provider.d.mts +195 -0
  106. package/dist/oauth2/refresh-access-token.d.mts +56 -0
  107. package/dist/oauth2/refresh-access-token.mjs +76 -0
  108. package/dist/oauth2/refresh-access-token.mjs.map +1 -0
  109. package/dist/oauth2/utils.d.mts +8 -0
  110. package/dist/oauth2/utils.mjs +28 -0
  111. package/dist/oauth2/utils.mjs.map +1 -0
  112. package/dist/oauth2/validate-authorization-code.d.mts +88 -0
  113. package/dist/oauth2/validate-authorization-code.mjs +83 -0
  114. package/dist/oauth2/validate-authorization-code.mjs.map +1 -0
  115. package/dist/oauth2/verify.d.mts +43 -0
  116. package/dist/oauth2/verify.mjs +96 -0
  117. package/dist/oauth2/verify.mjs.map +1 -0
  118. package/dist/social-providers/apple.d.mts +120 -0
  119. package/dist/social-providers/apple.mjs +105 -0
  120. package/dist/social-providers/apple.mjs.map +1 -0
  121. package/dist/social-providers/atlassian.d.mts +73 -0
  122. package/dist/social-providers/atlassian.mjs +84 -0
  123. package/dist/social-providers/atlassian.mjs.map +1 -0
  124. package/dist/social-providers/cognito.d.mts +88 -0
  125. package/dist/social-providers/cognito.mjs +166 -0
  126. package/dist/social-providers/cognito.mjs.map +1 -0
  127. package/dist/social-providers/discord.d.mts +127 -0
  128. package/dist/social-providers/discord.mjs +65 -0
  129. package/dist/social-providers/discord.mjs.map +1 -0
  130. package/dist/social-providers/dropbox.d.mts +72 -0
  131. package/dist/social-providers/dropbox.mjs +76 -0
  132. package/dist/social-providers/dropbox.mjs.map +1 -0
  133. package/dist/social-providers/facebook.d.mts +82 -0
  134. package/dist/social-providers/facebook.mjs +121 -0
  135. package/dist/social-providers/facebook.mjs.map +1 -0
  136. package/dist/social-providers/figma.d.mts +64 -0
  137. package/dist/social-providers/figma.mjs +87 -0
  138. package/dist/social-providers/figma.mjs.map +1 -0
  139. package/dist/social-providers/github.d.mts +105 -0
  140. package/dist/social-providers/github.mjs +97 -0
  141. package/dist/social-providers/github.mjs.map +1 -0
  142. package/dist/social-providers/gitlab.d.mts +126 -0
  143. package/dist/social-providers/gitlab.mjs +83 -0
  144. package/dist/social-providers/gitlab.mjs.map +1 -0
  145. package/dist/social-providers/google.d.mts +100 -0
  146. package/dist/social-providers/google.mjs +113 -0
  147. package/dist/social-providers/google.mjs.map +1 -0
  148. package/dist/social-providers/huggingface.d.mts +86 -0
  149. package/dist/social-providers/huggingface.mjs +76 -0
  150. package/dist/social-providers/huggingface.mjs.map +1 -0
  151. package/dist/social-providers/index.d.mts +1777 -2
  152. package/dist/social-providers/index.mjs +37 -2570
  153. package/dist/social-providers/index.mjs.map +1 -0
  154. package/dist/social-providers/kakao.d.mts +164 -0
  155. package/dist/social-providers/kakao.mjs +73 -0
  156. package/dist/social-providers/kakao.mjs.map +1 -0
  157. package/dist/social-providers/kick.d.mts +76 -0
  158. package/dist/social-providers/kick.mjs +72 -0
  159. package/dist/social-providers/kick.mjs.map +1 -0
  160. package/dist/social-providers/line.d.mts +108 -0
  161. package/dist/social-providers/line.mjs +114 -0
  162. package/dist/social-providers/line.mjs.map +1 -0
  163. package/dist/social-providers/linear.d.mts +71 -0
  164. package/dist/social-providers/linear.mjs +89 -0
  165. package/dist/social-providers/linear.mjs.map +1 -0
  166. package/dist/social-providers/linkedin.d.mts +70 -0
  167. package/dist/social-providers/linkedin.mjs +77 -0
  168. package/dist/social-providers/linkedin.mjs.map +1 -0
  169. package/dist/social-providers/microsoft-entra-id.d.mts +177 -0
  170. package/dist/social-providers/microsoft-entra-id.mjs +140 -0
  171. package/dist/social-providers/microsoft-entra-id.mjs.map +1 -0
  172. package/dist/social-providers/naver.d.mts +95 -0
  173. package/dist/social-providers/naver.mjs +68 -0
  174. package/dist/social-providers/naver.mjs.map +1 -0
  175. package/dist/social-providers/notion.d.mts +67 -0
  176. package/dist/social-providers/notion.mjs +76 -0
  177. package/dist/social-providers/notion.mjs.map +1 -0
  178. package/dist/social-providers/paybin.d.mts +74 -0
  179. package/dist/social-providers/paybin.mjs +86 -0
  180. package/dist/social-providers/paybin.mjs.map +1 -0
  181. package/dist/social-providers/paypal.d.mts +132 -0
  182. package/dist/social-providers/paypal.mjs +145 -0
  183. package/dist/social-providers/paypal.mjs.map +1 -0
  184. package/dist/social-providers/polar.d.mts +77 -0
  185. package/dist/social-providers/polar.mjs +74 -0
  186. package/dist/social-providers/polar.mjs.map +1 -0
  187. package/dist/social-providers/railway.d.mts +68 -0
  188. package/dist/social-providers/railway.mjs +78 -0
  189. package/dist/social-providers/railway.mjs.map +1 -0
  190. package/dist/social-providers/reddit.d.mts +65 -0
  191. package/dist/social-providers/reddit.mjs +84 -0
  192. package/dist/social-providers/reddit.mjs.map +1 -0
  193. package/dist/social-providers/roblox.d.mts +73 -0
  194. package/dist/social-providers/roblox.mjs +60 -0
  195. package/dist/social-providers/roblox.mjs.map +1 -0
  196. package/dist/social-providers/salesforce.d.mts +82 -0
  197. package/dist/social-providers/salesforce.mjs +92 -0
  198. package/dist/social-providers/salesforce.mjs.map +1 -0
  199. package/dist/social-providers/slack.d.mts +86 -0
  200. package/dist/social-providers/slack.mjs +69 -0
  201. package/dist/social-providers/slack.mjs.map +1 -0
  202. package/dist/social-providers/spotify.d.mts +66 -0
  203. package/dist/social-providers/spotify.mjs +72 -0
  204. package/dist/social-providers/spotify.mjs.map +1 -0
  205. package/dist/social-providers/tiktok.d.mts +171 -0
  206. package/dist/social-providers/tiktok.mjs +63 -0
  207. package/dist/social-providers/tiktok.mjs.map +1 -0
  208. package/dist/social-providers/twitch.d.mts +82 -0
  209. package/dist/social-providers/twitch.mjs +79 -0
  210. package/dist/social-providers/twitch.mjs.map +1 -0
  211. package/dist/social-providers/twitter.d.mts +129 -0
  212. package/dist/social-providers/twitter.mjs +88 -0
  213. package/dist/social-providers/twitter.mjs.map +1 -0
  214. package/dist/social-providers/vercel.d.mts +65 -0
  215. package/dist/social-providers/vercel.mjs +62 -0
  216. package/dist/social-providers/vercel.mjs.map +1 -0
  217. package/dist/social-providers/vk.d.mts +73 -0
  218. package/dist/social-providers/vk.mjs +84 -0
  219. package/dist/social-providers/vk.mjs.map +1 -0
  220. package/dist/social-providers/zoom.d.mts +166 -0
  221. package/dist/social-providers/zoom.mjs +73 -0
  222. package/dist/social-providers/zoom.mjs.map +1 -0
  223. package/dist/types/context.d.mts +274 -0
  224. package/dist/types/cookie.d.mts +16 -0
  225. package/dist/types/helper.d.mts +11 -0
  226. package/dist/types/index.d.mts +8 -0
  227. package/dist/types/init-options.d.mts +1298 -0
  228. package/dist/types/plugin-client.d.mts +113 -0
  229. package/dist/types/plugin.d.mts +125 -0
  230. package/dist/utils/db.d.mts +12 -0
  231. package/dist/utils/db.mjs +17 -0
  232. package/dist/utils/db.mjs.map +1 -0
  233. package/dist/utils/deprecate.d.mts +10 -0
  234. package/dist/utils/deprecate.mjs +18 -0
  235. package/dist/utils/deprecate.mjs.map +1 -0
  236. package/dist/utils/{index.d.mts → error-codes.d.mts} +9 -16
  237. package/dist/utils/error-codes.mjs +12 -0
  238. package/dist/utils/error-codes.mjs.map +1 -0
  239. package/dist/utils/id.d.mts +5 -0
  240. package/dist/utils/id.mjs +10 -0
  241. package/dist/utils/id.mjs.map +1 -0
  242. package/dist/utils/ip.d.mts +55 -0
  243. package/dist/utils/ip.mjs +119 -0
  244. package/dist/utils/ip.mjs.map +1 -0
  245. package/dist/utils/json.d.mts +5 -0
  246. package/dist/utils/json.mjs +26 -0
  247. package/dist/utils/json.mjs.map +1 -0
  248. package/dist/utils/string.d.mts +5 -0
  249. package/dist/utils/string.mjs +8 -0
  250. package/dist/utils/string.mjs.map +1 -0
  251. package/dist/utils/url.d.mts +21 -0
  252. package/dist/utils/url.mjs +33 -0
  253. package/dist/utils/url.mjs.map +1 -0
  254. package/package.json +36 -18
  255. package/src/context/endpoint-context.ts +7 -6
  256. package/src/context/global.ts +57 -0
  257. package/src/context/index.ts +2 -0
  258. package/src/context/request-state.ts +7 -6
  259. package/src/context/transaction.ts +77 -14
  260. package/src/db/adapter/factory.ts +54 -86
  261. package/src/db/adapter/get-default-model-name.ts +1 -1
  262. package/src/db/adapter/get-id-field.ts +4 -6
  263. package/src/db/adapter/index.ts +20 -15
  264. package/src/db/adapter/types.ts +2 -41
  265. package/src/db/get-tables.ts +54 -37
  266. package/src/db/index.ts +30 -5
  267. package/src/db/schema/account.ts +16 -3
  268. package/src/db/schema/rate-limit.ts +16 -1
  269. package/src/db/schema/session.ts +15 -3
  270. package/src/db/schema/user.ts +15 -3
  271. package/src/db/schema/verification.ts +16 -3
  272. package/src/db/test/get-tables.test.ts +33 -0
  273. package/src/db/type.ts +154 -1
  274. package/src/env/env-impl.ts +2 -2
  275. package/src/env/logger.ts +1 -1
  276. package/src/error/codes.ts +18 -1
  277. package/src/error/index.ts +2 -3
  278. package/src/oauth2/client-credentials-token.ts +26 -2
  279. package/src/oauth2/create-authorization-url.ts +4 -2
  280. package/src/oauth2/index.ts +3 -0
  281. package/src/oauth2/oauth-provider.ts +7 -1
  282. package/src/oauth2/refresh-access-token.test.ts +90 -0
  283. package/src/oauth2/refresh-access-token.ts +37 -4
  284. package/src/oauth2/validate-authorization-code.ts +55 -29
  285. package/src/oauth2/validate-token.test.ts +229 -0
  286. package/src/social-providers/apple.ts +38 -29
  287. package/src/social-providers/cognito.ts +6 -5
  288. package/src/social-providers/dropbox.ts +1 -1
  289. package/src/social-providers/facebook.ts +3 -3
  290. package/src/social-providers/figma.ts +5 -3
  291. package/src/social-providers/github.ts +26 -4
  292. package/src/social-providers/gitlab.ts +2 -2
  293. package/src/social-providers/google.ts +18 -14
  294. package/src/social-providers/huggingface.ts +1 -1
  295. package/src/social-providers/index.ts +9 -5
  296. package/src/social-providers/kakao.ts +1 -1
  297. package/src/social-providers/line.ts +1 -1
  298. package/src/social-providers/microsoft-entra-id.ts +84 -1
  299. package/src/social-providers/naver.ts +1 -1
  300. package/src/social-providers/notion.ts +1 -1
  301. package/src/social-providers/paybin.ts +1 -5
  302. package/src/social-providers/polar.ts +1 -1
  303. package/src/social-providers/railway.ts +100 -0
  304. package/src/social-providers/tiktok.ts +2 -1
  305. package/src/social-providers/vercel.ts +1 -1
  306. package/src/social-providers/zoom.ts +0 -8
  307. package/src/types/context.ts +241 -132
  308. package/src/types/cookie.ts +6 -4
  309. package/src/types/helper.ts +9 -0
  310. package/src/types/index.ts +19 -2
  311. package/src/types/init-options.ts +301 -186
  312. package/src/types/plugin-client.ts +1 -0
  313. package/src/types/plugin.ts +11 -6
  314. package/src/utils/db.ts +20 -0
  315. package/src/utils/deprecate.test.ts +71 -0
  316. package/src/utils/deprecate.ts +21 -0
  317. package/src/utils/error-codes.ts +12 -9
  318. package/src/utils/ip.test.ts +255 -0
  319. package/src/utils/ip.ts +211 -0
  320. package/src/utils/url.ts +43 -0
  321. package/.turbo/turbo-build.log +0 -43
  322. package/dist/context-DblZrIwO.mjs +0 -114
  323. package/dist/env-DbssmzoK.mjs +0 -245
  324. package/dist/index-BpRqx5_q.d.mts +0 -7833
  325. package/dist/oauth2-BjWM15hm.mjs +0 -326
  326. package/dist/utils/index.mjs +0 -4
  327. package/dist/utils-s65Fz0OM.mjs +0 -47
  328. package/src/utils/index.ts +0 -4
  329. package/tsconfig.json +0 -7
  330. package/tsdown.config.ts +0 -22
  331. package/vitest.config.ts +0 -3
@@ -0,0 +1,83 @@
1
+ import { getOAuth2Tokens } from "./utils.mjs";
2
+ import "./index.mjs";
3
+ import { base64 } from "@better-auth/utils/base64";
4
+ import { betterFetch } from "@better-fetch/fetch";
5
+ import { createRemoteJWKSet, jwtVerify } from "jose";
6
+
7
+ //#region src/oauth2/validate-authorization-code.ts
8
+ async function authorizationCodeRequest({ code, codeVerifier, redirectURI, options, authentication, deviceId, headers, additionalParams = {}, resource }) {
9
+ options = typeof options === "function" ? await options() : options;
10
+ return createAuthorizationCodeRequest({
11
+ code,
12
+ codeVerifier,
13
+ redirectURI,
14
+ options,
15
+ authentication,
16
+ deviceId,
17
+ headers,
18
+ additionalParams,
19
+ resource
20
+ });
21
+ }
22
+ /**
23
+ * @deprecated use async'd authorizationCodeRequest instead
24
+ */
25
+ function createAuthorizationCodeRequest({ code, codeVerifier, redirectURI, options, authentication, deviceId, headers, additionalParams = {}, resource }) {
26
+ const body = new URLSearchParams();
27
+ const requestHeaders = {
28
+ "content-type": "application/x-www-form-urlencoded",
29
+ accept: "application/json",
30
+ ...headers
31
+ };
32
+ body.set("grant_type", "authorization_code");
33
+ body.set("code", code);
34
+ codeVerifier && body.set("code_verifier", codeVerifier);
35
+ options.clientKey && body.set("client_key", options.clientKey);
36
+ deviceId && body.set("device_id", deviceId);
37
+ body.set("redirect_uri", options.redirectURI || redirectURI);
38
+ if (resource) if (typeof resource === "string") body.append("resource", resource);
39
+ else for (const _resource of resource) body.append("resource", _resource);
40
+ if (authentication === "basic") {
41
+ const primaryClientId = Array.isArray(options.clientId) ? options.clientId[0] : options.clientId;
42
+ requestHeaders["authorization"] = `Basic ${base64.encode(`${primaryClientId}:${options.clientSecret ?? ""}`)}`;
43
+ } else {
44
+ const primaryClientId = Array.isArray(options.clientId) ? options.clientId[0] : options.clientId;
45
+ body.set("client_id", primaryClientId);
46
+ if (options.clientSecret) body.set("client_secret", options.clientSecret);
47
+ }
48
+ for (const [key, value] of Object.entries(additionalParams)) if (!body.has(key)) body.append(key, value);
49
+ return {
50
+ body,
51
+ headers: requestHeaders
52
+ };
53
+ }
54
+ async function validateAuthorizationCode({ code, codeVerifier, redirectURI, options, tokenEndpoint, authentication, deviceId, headers, additionalParams = {}, resource }) {
55
+ const { body, headers: requestHeaders } = await authorizationCodeRequest({
56
+ code,
57
+ codeVerifier,
58
+ redirectURI,
59
+ options,
60
+ authentication,
61
+ deviceId,
62
+ headers,
63
+ additionalParams,
64
+ resource
65
+ });
66
+ const { data, error } = await betterFetch(tokenEndpoint, {
67
+ method: "POST",
68
+ body,
69
+ headers: requestHeaders
70
+ });
71
+ if (error) throw error;
72
+ return getOAuth2Tokens(data);
73
+ }
74
+ async function validateToken(token, jwksEndpoint, options) {
75
+ return await jwtVerify(token, createRemoteJWKSet(new URL(jwksEndpoint)), {
76
+ audience: options?.audience,
77
+ issuer: options?.issuer
78
+ });
79
+ }
80
+
81
+ //#endregion
82
+ export { authorizationCodeRequest, createAuthorizationCodeRequest, validateAuthorizationCode, validateToken };
83
+ //# sourceMappingURL=validate-authorization-code.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"validate-authorization-code.mjs","names":[],"sources":["../../src/oauth2/validate-authorization-code.ts"],"sourcesContent":["import { base64 } from \"@better-auth/utils/base64\";\nimport { betterFetch } from \"@better-fetch/fetch\";\nimport { createRemoteJWKSet, jwtVerify } from \"jose\";\nimport type { AwaitableFunction } from \"../types\";\nimport type { ProviderOptions } from \"./index\";\nimport { getOAuth2Tokens } from \"./index\";\n\nexport async function authorizationCodeRequest({\n\tcode,\n\tcodeVerifier,\n\tredirectURI,\n\toptions,\n\tauthentication,\n\tdeviceId,\n\theaders,\n\tadditionalParams = {},\n\tresource,\n}: {\n\tcode: string;\n\tredirectURI: string;\n\toptions: AwaitableFunction<Partial<ProviderOptions>>;\n\tcodeVerifier?: string | undefined;\n\tdeviceId?: string | undefined;\n\tauthentication?: (\"basic\" | \"post\") | undefined;\n\theaders?: Record<string, string> | undefined;\n\tadditionalParams?: Record<string, string> | undefined;\n\tresource?: (string | string[]) | undefined;\n}) {\n\toptions = typeof options === \"function\" ? await options() : options;\n\treturn createAuthorizationCodeRequest({\n\t\tcode,\n\t\tcodeVerifier,\n\t\tredirectURI,\n\t\toptions,\n\t\tauthentication,\n\t\tdeviceId,\n\t\theaders,\n\t\tadditionalParams,\n\t\tresource,\n\t});\n}\n\n/**\n * @deprecated use async'd authorizationCodeRequest instead\n */\nexport function createAuthorizationCodeRequest({\n\tcode,\n\tcodeVerifier,\n\tredirectURI,\n\toptions,\n\tauthentication,\n\tdeviceId,\n\theaders,\n\tadditionalParams = {},\n\tresource,\n}: {\n\tcode: string;\n\tredirectURI: string;\n\toptions: Partial<ProviderOptions>;\n\tcodeVerifier?: string | undefined;\n\tdeviceId?: string | undefined;\n\tauthentication?: (\"basic\" | \"post\") | undefined;\n\theaders?: Record<string, string> | undefined;\n\tadditionalParams?: Record<string, string> | undefined;\n\tresource?: (string | string[]) | undefined;\n}) {\n\tconst body = new URLSearchParams();\n\tconst requestHeaders: Record<string, any> = {\n\t\t\"content-type\": \"application/x-www-form-urlencoded\",\n\t\taccept: \"application/json\",\n\t\t...headers,\n\t};\n\n\tbody.set(\"grant_type\", \"authorization_code\");\n\tbody.set(\"code\", code);\n\tcodeVerifier && body.set(\"code_verifier\", codeVerifier);\n\toptions.clientKey && body.set(\"client_key\", options.clientKey);\n\tdeviceId && body.set(\"device_id\", deviceId);\n\tbody.set(\"redirect_uri\", options.redirectURI || redirectURI);\n\tif (resource) {\n\t\tif (typeof resource === \"string\") {\n\t\t\tbody.append(\"resource\", resource);\n\t\t} else {\n\t\t\tfor (const _resource of resource) {\n\t\t\t\tbody.append(\"resource\", _resource);\n\t\t\t}\n\t\t}\n\t}\n\t// Use standard Base64 encoding for HTTP Basic Auth (OAuth2 spec, RFC 7617)\n\t// Fixes compatibility with providers like Notion, Twitter, etc.\n\tif (authentication === \"basic\") {\n\t\tconst primaryClientId = Array.isArray(options.clientId)\n\t\t\t? options.clientId[0]\n\t\t\t: options.clientId;\n\t\tconst encodedCredentials = base64.encode(\n\t\t\t`${primaryClientId}:${options.clientSecret ?? \"\"}`,\n\t\t);\n\t\trequestHeaders[\"authorization\"] = `Basic ${encodedCredentials}`;\n\t} else {\n\t\tconst primaryClientId = Array.isArray(options.clientId)\n\t\t\t? options.clientId[0]\n\t\t\t: options.clientId;\n\t\tbody.set(\"client_id\", primaryClientId);\n\t\tif (options.clientSecret) {\n\t\t\tbody.set(\"client_secret\", options.clientSecret);\n\t\t}\n\t}\n\n\tfor (const [key, value] of Object.entries(additionalParams)) {\n\t\tif (!body.has(key)) body.append(key, value);\n\t}\n\n\treturn {\n\t\tbody,\n\t\theaders: requestHeaders,\n\t};\n}\n\nexport async function validateAuthorizationCode({\n\tcode,\n\tcodeVerifier,\n\tredirectURI,\n\toptions,\n\ttokenEndpoint,\n\tauthentication,\n\tdeviceId,\n\theaders,\n\tadditionalParams = {},\n\tresource,\n}: {\n\tcode: string;\n\tredirectURI: string;\n\toptions: AwaitableFunction<Partial<ProviderOptions>>;\n\tcodeVerifier?: string | undefined;\n\tdeviceId?: string | undefined;\n\ttokenEndpoint: string;\n\tauthentication?: (\"basic\" | \"post\") | undefined;\n\theaders?: Record<string, string> | undefined;\n\tadditionalParams?: Record<string, string> | undefined;\n\tresource?: (string | string[]) | undefined;\n}) {\n\tconst { body, headers: requestHeaders } = await authorizationCodeRequest({\n\t\tcode,\n\t\tcodeVerifier,\n\t\tredirectURI,\n\t\toptions,\n\t\tauthentication,\n\t\tdeviceId,\n\t\theaders,\n\t\tadditionalParams,\n\t\tresource,\n\t});\n\n\tconst { data, error } = await betterFetch<object>(tokenEndpoint, {\n\t\tmethod: \"POST\",\n\t\tbody: body,\n\t\theaders: requestHeaders,\n\t});\n\tif (error) {\n\t\tthrow error;\n\t}\n\tconst tokens = getOAuth2Tokens(data);\n\treturn tokens;\n}\n\nexport async function validateToken(\n\ttoken: string,\n\tjwksEndpoint: string,\n\toptions?: {\n\t\taudience?: string | string[];\n\t\tissuer?: string | string[];\n\t},\n) {\n\tconst jwks = createRemoteJWKSet(new URL(jwksEndpoint));\n\tconst verified = await jwtVerify(token, jwks, {\n\t\taudience: options?.audience,\n\t\tissuer: options?.issuer,\n\t});\n\treturn verified;\n}\n"],"mappings":";;;;;;;AAOA,eAAsB,yBAAyB,EAC9C,MACA,cACA,aACA,SACA,gBACA,UACA,SACA,mBAAmB,EAAE,EACrB,YAWE;AACF,WAAU,OAAO,YAAY,aAAa,MAAM,SAAS,GAAG;AAC5D,QAAO,+BAA+B;EACrC;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA,CAAC;;;;;AAMH,SAAgB,+BAA+B,EAC9C,MACA,cACA,aACA,SACA,gBACA,UACA,SACA,mBAAmB,EAAE,EACrB,YAWE;CACF,MAAM,OAAO,IAAI,iBAAiB;CAClC,MAAM,iBAAsC;EAC3C,gBAAgB;EAChB,QAAQ;EACR,GAAG;EACH;AAED,MAAK,IAAI,cAAc,qBAAqB;AAC5C,MAAK,IAAI,QAAQ,KAAK;AACtB,iBAAgB,KAAK,IAAI,iBAAiB,aAAa;AACvD,SAAQ,aAAa,KAAK,IAAI,cAAc,QAAQ,UAAU;AAC9D,aAAY,KAAK,IAAI,aAAa,SAAS;AAC3C,MAAK,IAAI,gBAAgB,QAAQ,eAAe,YAAY;AAC5D,KAAI,SACH,KAAI,OAAO,aAAa,SACvB,MAAK,OAAO,YAAY,SAAS;KAEjC,MAAK,MAAM,aAAa,SACvB,MAAK,OAAO,YAAY,UAAU;AAMrC,KAAI,mBAAmB,SAAS;EAC/B,MAAM,kBAAkB,MAAM,QAAQ,QAAQ,SAAS,GACpD,QAAQ,SAAS,KACjB,QAAQ;AAIX,iBAAe,mBAAmB,SAHP,OAAO,OACjC,GAAG,gBAAgB,GAAG,QAAQ,gBAAgB,KAC9C;QAEK;EACN,MAAM,kBAAkB,MAAM,QAAQ,QAAQ,SAAS,GACpD,QAAQ,SAAS,KACjB,QAAQ;AACX,OAAK,IAAI,aAAa,gBAAgB;AACtC,MAAI,QAAQ,aACX,MAAK,IAAI,iBAAiB,QAAQ,aAAa;;AAIjD,MAAK,MAAM,CAAC,KAAK,UAAU,OAAO,QAAQ,iBAAiB,CAC1D,KAAI,CAAC,KAAK,IAAI,IAAI,CAAE,MAAK,OAAO,KAAK,MAAM;AAG5C,QAAO;EACN;EACA,SAAS;EACT;;AAGF,eAAsB,0BAA0B,EAC/C,MACA,cACA,aACA,SACA,eACA,gBACA,UACA,SACA,mBAAmB,EAAE,EACrB,YAYE;CACF,MAAM,EAAE,MAAM,SAAS,mBAAmB,MAAM,yBAAyB;EACxE;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA,CAAC;CAEF,MAAM,EAAE,MAAM,UAAU,MAAM,YAAoB,eAAe;EAChE,QAAQ;EACF;EACN,SAAS;EACT,CAAC;AACF,KAAI,MACH,OAAM;AAGP,QADe,gBAAgB,KAAK;;AAIrC,eAAsB,cACrB,OACA,cACA,SAIC;AAMD,QAJiB,MAAM,UAAU,OADpB,mBAAmB,IAAI,IAAI,aAAa,CAAC,EACR;EAC7C,UAAU,SAAS;EACnB,QAAQ,SAAS;EACjB,CAAC"}
@@ -0,0 +1,43 @@
1
+ import { JSONWebKeySet, JWTPayload, JWTVerifyOptions } from "jose";
2
+
3
+ //#region src/oauth2/verify.d.ts
4
+ interface VerifyAccessTokenRemote {
5
+ /** Full url of the introspect endpoint. Should end with `/oauth2/introspect` */
6
+ introspectUrl: string;
7
+ /** Client Secret */
8
+ clientId: string;
9
+ /** Client Secret */
10
+ clientSecret: string;
11
+ /**
12
+ * Forces remote verification of a token.
13
+ * This ensures attached session (if applicable)
14
+ * is also still active.
15
+ */
16
+ force?: boolean;
17
+ }
18
+ /**
19
+ * Performs local verification of an access token for your APIs.
20
+ *
21
+ * Can also be configured for remote verification.
22
+ */
23
+ declare function verifyJwsAccessToken(token: string, opts: {
24
+ /** Jwks url or promise of a Jwks */jwksFetch: string | (() => Promise<JSONWebKeySet | undefined>); /** Verify options */
25
+ verifyOptions: JWTVerifyOptions & Required<Pick<JWTVerifyOptions, "audience" | "issuer">>;
26
+ }): Promise<JWTPayload>;
27
+ declare function getJwks(token: string, opts: {
28
+ /** Jwks url or promise of a Jwks */jwksFetch: string | (() => Promise<JSONWebKeySet | undefined>);
29
+ }): Promise<JSONWebKeySet>;
30
+ /**
31
+ * Performs local verification of an access token for your API.
32
+ *
33
+ * Can also be configured for remote verification.
34
+ */
35
+ declare function verifyAccessToken(token: string, opts: {
36
+ /** Verify options */verifyOptions: JWTVerifyOptions & Required<Pick<JWTVerifyOptions, "audience" | "issuer">>; /** Scopes to additionally verify. Token must include all but not exact. */
37
+ scopes?: string[]; /** Required to verify access token locally */
38
+ jwksUrl?: string; /** If provided, can verify a token remotely */
39
+ remoteVerify?: VerifyAccessTokenRemote;
40
+ }): Promise<JWTPayload>;
41
+ //#endregion
42
+ export { getJwks, verifyAccessToken, verifyJwsAccessToken };
43
+ //# sourceMappingURL=verify.d.mts.map
@@ -0,0 +1,96 @@
1
+ import { logger } from "../env/logger.mjs";
2
+ import "../env/index.mjs";
3
+ import { APIError } from "better-call";
4
+ import { betterFetch } from "@better-fetch/fetch";
5
+ import { UnsecuredJWT, createLocalJWKSet, decodeProtectedHeader, jwtVerify } from "jose";
6
+
7
+ //#region src/oauth2/verify.ts
8
+ /** Last fetched jwks used locally in getJwks @internal */
9
+ let jwks;
10
+ /**
11
+ * Performs local verification of an access token for your APIs.
12
+ *
13
+ * Can also be configured for remote verification.
14
+ */
15
+ async function verifyJwsAccessToken(token, opts) {
16
+ try {
17
+ const jwt = await jwtVerify(token, createLocalJWKSet(await getJwks(token, opts)), opts.verifyOptions);
18
+ if (jwt.payload.azp) jwt.payload.client_id = jwt.payload.azp;
19
+ return jwt.payload;
20
+ } catch (error) {
21
+ if (error instanceof Error) throw error;
22
+ throw new Error(error);
23
+ }
24
+ }
25
+ async function getJwks(token, opts) {
26
+ let jwtHeaders;
27
+ try {
28
+ jwtHeaders = decodeProtectedHeader(token);
29
+ } catch (error) {
30
+ if (error instanceof Error) throw error;
31
+ throw new Error(error);
32
+ }
33
+ if (!jwtHeaders.kid) throw new Error("Missing jwt kid");
34
+ if (!jwks || !jwks.keys.find((jwk) => jwk.kid === jwtHeaders.kid)) {
35
+ jwks = typeof opts.jwksFetch === "string" ? await betterFetch(opts.jwksFetch, { headers: { Accept: "application/json" } }).then(async (res) => {
36
+ if (res.error) throw new Error(`Jwks failed: ${res.error.message ?? res.error.statusText}`);
37
+ return res.data;
38
+ }) : await opts.jwksFetch();
39
+ if (!jwks) throw new Error("No jwks found");
40
+ }
41
+ return jwks;
42
+ }
43
+ /**
44
+ * Performs local verification of an access token for your API.
45
+ *
46
+ * Can also be configured for remote verification.
47
+ */
48
+ async function verifyAccessToken(token, opts) {
49
+ let payload;
50
+ if (opts.jwksUrl && !opts?.remoteVerify?.force) try {
51
+ payload = await verifyJwsAccessToken(token, {
52
+ jwksFetch: opts.jwksUrl,
53
+ verifyOptions: opts.verifyOptions
54
+ });
55
+ } catch (error) {
56
+ if (error instanceof Error) if (error.name === "TypeError" || error.name === "JWSInvalid") {} else if (error.name === "JWTExpired") throw new APIError("UNAUTHORIZED", { message: "token expired" });
57
+ else if (error.name === "JWTInvalid") throw new APIError("UNAUTHORIZED", { message: "token invalid" });
58
+ else throw error;
59
+ else throw new Error(error);
60
+ }
61
+ if (opts?.remoteVerify) {
62
+ const { data: introspect, error: introspectError } = await betterFetch(opts.remoteVerify.introspectUrl, {
63
+ method: "POST",
64
+ headers: {
65
+ Accept: "application/json",
66
+ "Content-Type": "application/x-www-form-urlencoded"
67
+ },
68
+ body: new URLSearchParams({
69
+ client_id: opts.remoteVerify.clientId,
70
+ client_secret: opts.remoteVerify.clientSecret,
71
+ token,
72
+ token_type_hint: "access_token"
73
+ }).toString()
74
+ });
75
+ if (introspectError) logger.error(`Introspection failed: ${introspectError.message ?? introspectError.statusText}`);
76
+ if (!introspect) throw new APIError("INTERNAL_SERVER_ERROR", { message: "introspection failed" });
77
+ if (!introspect.active) throw new APIError("UNAUTHORIZED", { message: "token inactive" });
78
+ try {
79
+ const unsecuredJwt = new UnsecuredJWT(introspect).encode();
80
+ const { audience: _audience, ...verifyOptions } = opts.verifyOptions;
81
+ payload = (introspect.aud ? UnsecuredJWT.decode(unsecuredJwt, opts.verifyOptions) : UnsecuredJWT.decode(unsecuredJwt, verifyOptions)).payload;
82
+ } catch (error) {
83
+ throw new Error(error);
84
+ }
85
+ }
86
+ if (!payload) throw new APIError("UNAUTHORIZED", { message: `no token payload` });
87
+ if (opts.scopes) {
88
+ const validScopes = new Set(payload.scope?.split(" "));
89
+ for (const sc of opts.scopes) if (!validScopes.has(sc)) throw new APIError("FORBIDDEN", { message: `invalid scope ${sc}` });
90
+ }
91
+ return payload;
92
+ }
93
+
94
+ //#endregion
95
+ export { getJwks, verifyAccessToken, verifyJwsAccessToken };
96
+ //# sourceMappingURL=verify.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"verify.mjs","names":[],"sources":["../../src/oauth2/verify.ts"],"sourcesContent":["import { betterFetch } from \"@better-fetch/fetch\";\nimport { APIError } from \"better-call\";\nimport type {\n\tJSONWebKeySet,\n\tJWTPayload,\n\tJWTVerifyOptions,\n\tProtectedHeaderParameters,\n} from \"jose\";\nimport {\n\tcreateLocalJWKSet,\n\tdecodeProtectedHeader,\n\tjwtVerify,\n\tUnsecuredJWT,\n} from \"jose\";\nimport { logger } from \"../env\";\n\n/** Last fetched jwks used locally in getJwks @internal */\nlet jwks: JSONWebKeySet | undefined;\n\nexport interface VerifyAccessTokenRemote {\n\t/** Full url of the introspect endpoint. Should end with `/oauth2/introspect` */\n\tintrospectUrl: string;\n\t/** Client Secret */\n\tclientId: string;\n\t/** Client Secret */\n\tclientSecret: string;\n\t/**\n\t * Forces remote verification of a token.\n\t * This ensures attached session (if applicable)\n\t * is also still active.\n\t */\n\tforce?: boolean;\n}\n\n/**\n * Performs local verification of an access token for your APIs.\n *\n * Can also be configured for remote verification.\n */\nexport async function verifyJwsAccessToken(\n\ttoken: string,\n\topts: {\n\t\t/** Jwks url or promise of a Jwks */\n\t\tjwksFetch: string | (() => Promise<JSONWebKeySet | undefined>);\n\t\t/** Verify options */\n\t\tverifyOptions: JWTVerifyOptions &\n\t\t\tRequired<Pick<JWTVerifyOptions, \"audience\" | \"issuer\">>;\n\t},\n) {\n\ttry {\n\t\tconst jwks = await getJwks(token, opts);\n\t\tconst jwt = await jwtVerify<JWTPayload>(\n\t\t\ttoken,\n\t\t\tcreateLocalJWKSet(jwks),\n\t\t\topts.verifyOptions,\n\t\t);\n\t\t// Return the JWT payload in introspection format\n\t\t// https://datatracker.ietf.org/doc/html/rfc7662#section-2.2\n\t\tif (jwt.payload.azp) {\n\t\t\tjwt.payload.client_id = jwt.payload.azp;\n\t\t}\n\t\treturn jwt.payload;\n\t} catch (error) {\n\t\tif (error instanceof Error) throw error;\n\t\tthrow new Error(error as unknown as string);\n\t}\n}\n\nexport async function getJwks(\n\ttoken: string,\n\topts: {\n\t\t/** Jwks url or promise of a Jwks */\n\t\tjwksFetch: string | (() => Promise<JSONWebKeySet | undefined>);\n\t},\n) {\n\t// Attempt to decode the token and find a matching kid in jwks\n\tlet jwtHeaders: ProtectedHeaderParameters | undefined;\n\ttry {\n\t\tjwtHeaders = decodeProtectedHeader(token);\n\t} catch (error) {\n\t\tif (error instanceof Error) throw error;\n\t\tthrow new Error(error as unknown as string);\n\t}\n\n\tif (!jwtHeaders.kid) throw new Error(\"Missing jwt kid\");\n\n\t// Fetch jwks if not set or has a different kid than the one stored\n\tif (!jwks || !jwks.keys.find((jwk) => jwk.kid === jwtHeaders.kid)) {\n\t\tjwks =\n\t\t\ttypeof opts.jwksFetch === \"string\"\n\t\t\t\t? await betterFetch<JSONWebKeySet>(opts.jwksFetch, {\n\t\t\t\t\t\theaders: {\n\t\t\t\t\t\t\tAccept: \"application/json\",\n\t\t\t\t\t\t},\n\t\t\t\t\t}).then(async (res) => {\n\t\t\t\t\t\tif (res.error)\n\t\t\t\t\t\t\tthrow new Error(\n\t\t\t\t\t\t\t\t`Jwks failed: ${res.error.message ?? res.error.statusText}`,\n\t\t\t\t\t\t\t);\n\t\t\t\t\t\treturn res.data;\n\t\t\t\t\t})\n\t\t\t\t: await opts.jwksFetch();\n\t\tif (!jwks) throw new Error(\"No jwks found\");\n\t}\n\n\treturn jwks;\n}\n\n/**\n * Performs local verification of an access token for your API.\n *\n * Can also be configured for remote verification.\n */\nexport async function verifyAccessToken(\n\ttoken: string,\n\topts: {\n\t\t/** Verify options */\n\t\tverifyOptions: JWTVerifyOptions &\n\t\t\tRequired<Pick<JWTVerifyOptions, \"audience\" | \"issuer\">>;\n\t\t/** Scopes to additionally verify. Token must include all but not exact. */\n\t\tscopes?: string[];\n\t\t/** Required to verify access token locally */\n\t\tjwksUrl?: string;\n\t\t/** If provided, can verify a token remotely */\n\t\tremoteVerify?: VerifyAccessTokenRemote;\n\t},\n) {\n\tlet payload: JWTPayload | undefined;\n\t// Locally verify\n\tif (opts.jwksUrl && !opts?.remoteVerify?.force) {\n\t\ttry {\n\t\t\tpayload = await verifyJwsAccessToken(token, {\n\t\t\t\tjwksFetch: opts.jwksUrl,\n\t\t\t\tverifyOptions: opts.verifyOptions,\n\t\t\t});\n\t\t} catch (error) {\n\t\t\tif (error instanceof Error) {\n\t\t\t\tif (error.name === \"TypeError\" || error.name === \"JWSInvalid\") {\n\t\t\t\t\t// likely an opaque token (continue)\n\t\t\t\t} else if (error.name === \"JWTExpired\") {\n\t\t\t\t\tthrow new APIError(\"UNAUTHORIZED\", {\n\t\t\t\t\t\tmessage: \"token expired\",\n\t\t\t\t\t});\n\t\t\t\t} else if (error.name === \"JWTInvalid\") {\n\t\t\t\t\tthrow new APIError(\"UNAUTHORIZED\", {\n\t\t\t\t\t\tmessage: \"token invalid\",\n\t\t\t\t\t});\n\t\t\t\t} else {\n\t\t\t\t\tthrow error;\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tthrow new Error(error as unknown as string);\n\t\t\t}\n\t\t}\n\t}\n\n\t// Remote verify\n\tif (opts?.remoteVerify) {\n\t\tconst { data: introspect, error: introspectError } = await betterFetch<\n\t\t\tJWTPayload & {\n\t\t\t\tactive: boolean;\n\t\t\t}\n\t\t>(opts.remoteVerify.introspectUrl, {\n\t\t\tmethod: \"POST\",\n\t\t\theaders: {\n\t\t\t\tAccept: \"application/json\",\n\t\t\t\t\"Content-Type\": \"application/x-www-form-urlencoded\",\n\t\t\t},\n\t\t\tbody: new URLSearchParams({\n\t\t\t\tclient_id: opts.remoteVerify.clientId,\n\t\t\t\tclient_secret: opts.remoteVerify.clientSecret,\n\t\t\t\ttoken,\n\t\t\t\ttoken_type_hint: \"access_token\",\n\t\t\t}).toString(),\n\t\t});\n\t\tif (introspectError)\n\t\t\tlogger.error(\n\t\t\t\t`Introspection failed: ${introspectError.message ?? introspectError.statusText}`,\n\t\t\t);\n\t\tif (!introspect)\n\t\t\tthrow new APIError(\"INTERNAL_SERVER_ERROR\", {\n\t\t\t\tmessage: \"introspection failed\",\n\t\t\t});\n\t\tif (!introspect.active)\n\t\t\tthrow new APIError(\"UNAUTHORIZED\", {\n\t\t\t\tmessage: \"token inactive\",\n\t\t\t});\n\t\t// Verifies payload using verify options (token valid through introspect)\n\t\ttry {\n\t\t\tconst unsecuredJwt = new UnsecuredJWT(introspect).encode();\n\t\t\tconst { audience: _audience, ...verifyOptions } = opts.verifyOptions;\n\t\t\tconst verify = introspect.aud\n\t\t\t\t? UnsecuredJWT.decode(unsecuredJwt, opts.verifyOptions)\n\t\t\t\t: UnsecuredJWT.decode(unsecuredJwt, verifyOptions);\n\t\t\tpayload = verify.payload;\n\t\t} catch (error) {\n\t\t\tthrow new Error(error as unknown as string);\n\t\t}\n\t}\n\n\tif (!payload)\n\t\tthrow new APIError(\"UNAUTHORIZED\", {\n\t\t\tmessage: `no token payload`,\n\t\t});\n\n\t// Check scopes if provided\n\tif (opts.scopes) {\n\t\tconst validScopes = new Set(\n\t\t\t(payload.scope as string | undefined)?.split(\" \"),\n\t\t);\n\t\tfor (const sc of opts.scopes) {\n\t\t\tif (!validScopes.has(sc)) {\n\t\t\t\tthrow new APIError(\"FORBIDDEN\", {\n\t\t\t\t\tmessage: `invalid scope ${sc}`,\n\t\t\t\t});\n\t\t\t}\n\t\t}\n\t}\n\n\treturn payload;\n}\n"],"mappings":";;;;;;;;AAiBA,IAAI;;;;;;AAsBJ,eAAsB,qBACrB,OACA,MAOC;AACD,KAAI;EAEH,MAAM,MAAM,MAAM,UACjB,OACA,kBAHY,MAAM,QAAQ,OAAO,KAAK,CAGf,EACvB,KAAK,cACL;AAGD,MAAI,IAAI,QAAQ,IACf,KAAI,QAAQ,YAAY,IAAI,QAAQ;AAErC,SAAO,IAAI;UACH,OAAO;AACf,MAAI,iBAAiB,MAAO,OAAM;AAClC,QAAM,IAAI,MAAM,MAA2B;;;AAI7C,eAAsB,QACrB,OACA,MAIC;CAED,IAAI;AACJ,KAAI;AACH,eAAa,sBAAsB,MAAM;UACjC,OAAO;AACf,MAAI,iBAAiB,MAAO,OAAM;AAClC,QAAM,IAAI,MAAM,MAA2B;;AAG5C,KAAI,CAAC,WAAW,IAAK,OAAM,IAAI,MAAM,kBAAkB;AAGvD,KAAI,CAAC,QAAQ,CAAC,KAAK,KAAK,MAAM,QAAQ,IAAI,QAAQ,WAAW,IAAI,EAAE;AAClE,SACC,OAAO,KAAK,cAAc,WACvB,MAAM,YAA2B,KAAK,WAAW,EACjD,SAAS,EACR,QAAQ,oBACR,EACD,CAAC,CAAC,KAAK,OAAO,QAAQ;AACtB,OAAI,IAAI,MACP,OAAM,IAAI,MACT,gBAAgB,IAAI,MAAM,WAAW,IAAI,MAAM,aAC/C;AACF,UAAO,IAAI;IACV,GACD,MAAM,KAAK,WAAW;AAC1B,MAAI,CAAC,KAAM,OAAM,IAAI,MAAM,gBAAgB;;AAG5C,QAAO;;;;;;;AAQR,eAAsB,kBACrB,OACA,MAWC;CACD,IAAI;AAEJ,KAAI,KAAK,WAAW,CAAC,MAAM,cAAc,MACxC,KAAI;AACH,YAAU,MAAM,qBAAqB,OAAO;GAC3C,WAAW,KAAK;GAChB,eAAe,KAAK;GACpB,CAAC;UACM,OAAO;AACf,MAAI,iBAAiB,MACpB,KAAI,MAAM,SAAS,eAAe,MAAM,SAAS,cAAc,YAEpD,MAAM,SAAS,aACzB,OAAM,IAAI,SAAS,gBAAgB,EAClC,SAAS,iBACT,CAAC;WACQ,MAAM,SAAS,aACzB,OAAM,IAAI,SAAS,gBAAgB,EAClC,SAAS,iBACT,CAAC;MAEF,OAAM;MAGP,OAAM,IAAI,MAAM,MAA2B;;AAM9C,KAAI,MAAM,cAAc;EACvB,MAAM,EAAE,MAAM,YAAY,OAAO,oBAAoB,MAAM,YAIzD,KAAK,aAAa,eAAe;GAClC,QAAQ;GACR,SAAS;IACR,QAAQ;IACR,gBAAgB;IAChB;GACD,MAAM,IAAI,gBAAgB;IACzB,WAAW,KAAK,aAAa;IAC7B,eAAe,KAAK,aAAa;IACjC;IACA,iBAAiB;IACjB,CAAC,CAAC,UAAU;GACb,CAAC;AACF,MAAI,gBACH,QAAO,MACN,yBAAyB,gBAAgB,WAAW,gBAAgB,aACpE;AACF,MAAI,CAAC,WACJ,OAAM,IAAI,SAAS,yBAAyB,EAC3C,SAAS,wBACT,CAAC;AACH,MAAI,CAAC,WAAW,OACf,OAAM,IAAI,SAAS,gBAAgB,EAClC,SAAS,kBACT,CAAC;AAEH,MAAI;GACH,MAAM,eAAe,IAAI,aAAa,WAAW,CAAC,QAAQ;GAC1D,MAAM,EAAE,UAAU,WAAW,GAAG,kBAAkB,KAAK;AAIvD,cAHe,WAAW,MACvB,aAAa,OAAO,cAAc,KAAK,cAAc,GACrD,aAAa,OAAO,cAAc,cAAc,EAClC;WACT,OAAO;AACf,SAAM,IAAI,MAAM,MAA2B;;;AAI7C,KAAI,CAAC,QACJ,OAAM,IAAI,SAAS,gBAAgB,EAClC,SAAS,oBACT,CAAC;AAGH,KAAI,KAAK,QAAQ;EAChB,MAAM,cAAc,IAAI,IACtB,QAAQ,OAA8B,MAAM,IAAI,CACjD;AACD,OAAK,MAAM,MAAM,KAAK,OACrB,KAAI,CAAC,YAAY,IAAI,GAAG,CACvB,OAAM,IAAI,SAAS,aAAa,EAC/B,SAAS,iBAAiB,MAC1B,CAAC;;AAKL,QAAO"}
@@ -0,0 +1,120 @@
1
+ import { OAuth2Tokens, ProviderOptions } from "../oauth2/oauth-provider.mjs";
2
+ import "../oauth2/index.mjs";
3
+
4
+ //#region src/social-providers/apple.d.ts
5
+ interface AppleProfile {
6
+ /**
7
+ * The subject registered claim identifies the principal that’s the subject
8
+ * of the identity token. Because this token is for your app, the value is
9
+ * the unique identifier for the user.
10
+ */
11
+ sub: string;
12
+ /**
13
+ * A String value representing the user's email address.
14
+ * The email address is either the user's real email address or the proxy
15
+ * address, depending on their status private email relay service.
16
+ */
17
+ email: string;
18
+ /**
19
+ * A string or Boolean value that indicates whether the service verifies
20
+ * the email. The value can either be a string ("true" or "false") or a
21
+ * Boolean (true or false). The system may not verify email addresses for
22
+ * Sign in with Apple at Work & School users, and this claim is "false" or
23
+ * false for those users.
24
+ */
25
+ email_verified: true | "true";
26
+ /**
27
+ * A string or Boolean value that indicates whether the email that the user
28
+ * shares is the proxy address. The value can either be a string ("true" or
29
+ * "false") or a Boolean (true or false).
30
+ */
31
+ is_private_email: boolean;
32
+ /**
33
+ * An Integer value that indicates whether the user appears to be a real
34
+ * person. Use the value of this claim to mitigate fraud. The possible
35
+ * values are: 0 (or Unsupported), 1 (or Unknown), 2 (or LikelyReal). For
36
+ * more information, see ASUserDetectionStatus. This claim is present only
37
+ * in iOS 14 and later, macOS 11 and later, watchOS 7 and later, tvOS 14
38
+ * and later. The claim isn’t present or supported for web-based apps.
39
+ */
40
+ real_user_status: number;
41
+ /**
42
+ * The user’s full name in the format provided during the authorization
43
+ * process.
44
+ */
45
+ name: string;
46
+ /**
47
+ * The URL to the user's profile picture.
48
+ */
49
+ picture: string;
50
+ user?: AppleNonConformUser | undefined;
51
+ }
52
+ /**
53
+ * This is the shape of the `user` query parameter that Apple sends the first
54
+ * time the user consents to the app.
55
+ * @see https://developer.apple.com/documentation/signinwithapplerestapi/request-an-authorization-to-the-sign-in-with-apple-server./
56
+ */
57
+ interface AppleNonConformUser {
58
+ name: {
59
+ firstName: string;
60
+ lastName: string;
61
+ };
62
+ email: string;
63
+ }
64
+ interface AppleOptions extends ProviderOptions<AppleProfile> {
65
+ clientId: string;
66
+ appBundleIdentifier?: string | undefined;
67
+ audience?: (string | string[]) | undefined;
68
+ }
69
+ declare const apple: (options: AppleOptions) => {
70
+ id: "apple";
71
+ name: string;
72
+ createAuthorizationURL({
73
+ state,
74
+ scopes,
75
+ redirectURI
76
+ }: {
77
+ state: string;
78
+ codeVerifier: string;
79
+ scopes?: string[] | undefined;
80
+ redirectURI: string;
81
+ display?: string | undefined;
82
+ loginHint?: string | undefined;
83
+ }): Promise<URL>;
84
+ validateAuthorizationCode: ({
85
+ code,
86
+ codeVerifier,
87
+ redirectURI
88
+ }: {
89
+ code: string;
90
+ redirectURI: string;
91
+ codeVerifier?: string | undefined;
92
+ deviceId?: string | undefined;
93
+ }) => Promise<OAuth2Tokens>;
94
+ verifyIdToken(token: string, nonce: string | undefined): Promise<boolean>;
95
+ refreshAccessToken: (refreshToken: string) => Promise<OAuth2Tokens>;
96
+ getUserInfo(token: OAuth2Tokens & {
97
+ user?: {
98
+ name?: {
99
+ firstName?: string;
100
+ lastName?: string;
101
+ };
102
+ email?: string;
103
+ } | undefined;
104
+ }): Promise<{
105
+ user: {
106
+ id: string;
107
+ name?: string;
108
+ email?: string | null;
109
+ image?: string;
110
+ emailVerified: boolean;
111
+ [key: string]: any;
112
+ };
113
+ data: any;
114
+ } | null>;
115
+ options: AppleOptions;
116
+ };
117
+ declare const getApplePublicKey: (kid: string) => Promise<Uint8Array<ArrayBufferLike> | CryptoKey>;
118
+ //#endregion
119
+ export { AppleNonConformUser, AppleOptions, AppleProfile, apple, getApplePublicKey };
120
+ //# sourceMappingURL=apple.d.mts.map
@@ -0,0 +1,105 @@
1
+ import { APIError } from "../error/index.mjs";
2
+ import { createAuthorizationURL } from "../oauth2/create-authorization-url.mjs";
3
+ import { refreshAccessToken } from "../oauth2/refresh-access-token.mjs";
4
+ import { validateAuthorizationCode } from "../oauth2/validate-authorization-code.mjs";
5
+ import "../oauth2/index.mjs";
6
+ import { betterFetch } from "@better-fetch/fetch";
7
+ import { decodeJwt, decodeProtectedHeader, importJWK, jwtVerify } from "jose";
8
+
9
+ //#region src/social-providers/apple.ts
10
+ const apple = (options) => {
11
+ const tokenEndpoint = "https://appleid.apple.com/auth/token";
12
+ return {
13
+ id: "apple",
14
+ name: "Apple",
15
+ async createAuthorizationURL({ state, scopes, redirectURI }) {
16
+ const _scope = options.disableDefaultScope ? [] : ["email", "name"];
17
+ if (options.scope) _scope.push(...options.scope);
18
+ if (scopes) _scope.push(...scopes);
19
+ return await createAuthorizationURL({
20
+ id: "apple",
21
+ options,
22
+ authorizationEndpoint: "https://appleid.apple.com/auth/authorize",
23
+ scopes: _scope,
24
+ state,
25
+ redirectURI,
26
+ responseMode: "form_post",
27
+ responseType: "code id_token"
28
+ });
29
+ },
30
+ validateAuthorizationCode: async ({ code, codeVerifier, redirectURI }) => {
31
+ return validateAuthorizationCode({
32
+ code,
33
+ codeVerifier,
34
+ redirectURI,
35
+ options,
36
+ tokenEndpoint
37
+ });
38
+ },
39
+ async verifyIdToken(token, nonce) {
40
+ if (options.disableIdTokenSignIn) return false;
41
+ if (options.verifyIdToken) return options.verifyIdToken(token, nonce);
42
+ try {
43
+ const { kid, alg: jwtAlg } = decodeProtectedHeader(token);
44
+ if (!kid || !jwtAlg) return false;
45
+ const { payload: jwtClaims } = await jwtVerify(token, await getApplePublicKey(kid), {
46
+ algorithms: [jwtAlg],
47
+ issuer: "https://appleid.apple.com",
48
+ audience: options.audience && options.audience.length ? options.audience : options.appBundleIdentifier ? options.appBundleIdentifier : options.clientId,
49
+ maxTokenAge: "1h"
50
+ });
51
+ ["email_verified", "is_private_email"].forEach((field) => {
52
+ if (jwtClaims[field] !== void 0) jwtClaims[field] = Boolean(jwtClaims[field]);
53
+ });
54
+ if (nonce && jwtClaims.nonce !== nonce) return false;
55
+ return !!jwtClaims;
56
+ } catch {
57
+ return false;
58
+ }
59
+ },
60
+ refreshAccessToken: options.refreshAccessToken ? options.refreshAccessToken : async (refreshToken) => {
61
+ return refreshAccessToken({
62
+ refreshToken,
63
+ options,
64
+ tokenEndpoint: "https://appleid.apple.com/auth/token"
65
+ });
66
+ },
67
+ async getUserInfo(token) {
68
+ if (options.getUserInfo) return options.getUserInfo(token);
69
+ if (!token.idToken) return null;
70
+ const profile = decodeJwt(token.idToken);
71
+ if (!profile) return null;
72
+ let name;
73
+ if (token.user?.name) name = `${token.user.name.firstName || ""} ${token.user.name.lastName || ""}`.trim();
74
+ else name = profile.name || "";
75
+ const emailVerified = typeof profile.email_verified === "boolean" ? profile.email_verified : profile.email_verified === "true";
76
+ const enrichedProfile = {
77
+ ...profile,
78
+ name
79
+ };
80
+ const userMap = await options.mapProfileToUser?.(enrichedProfile);
81
+ return {
82
+ user: {
83
+ id: profile.sub,
84
+ name: enrichedProfile.name,
85
+ emailVerified,
86
+ email: profile.email,
87
+ ...userMap
88
+ },
89
+ data: enrichedProfile
90
+ };
91
+ },
92
+ options
93
+ };
94
+ };
95
+ const getApplePublicKey = async (kid) => {
96
+ const { data } = await betterFetch(`https://appleid.apple.com/auth/keys`);
97
+ if (!data?.keys) throw new APIError("BAD_REQUEST", { message: "Keys not found" });
98
+ const jwk = data.keys.find((key) => key.kid === kid);
99
+ if (!jwk) throw new Error(`JWK with kid ${kid} not found`);
100
+ return await importJWK(jwk, jwk.alg);
101
+ };
102
+
103
+ //#endregion
104
+ export { apple, getApplePublicKey };
105
+ //# sourceMappingURL=apple.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"apple.mjs","names":[],"sources":["../../src/social-providers/apple.ts"],"sourcesContent":["import { betterFetch } from \"@better-fetch/fetch\";\n\nimport { decodeJwt, decodeProtectedHeader, importJWK, jwtVerify } from \"jose\";\nimport { APIError } from \"../error\";\nimport type { OAuthProvider, ProviderOptions } from \"../oauth2\";\nimport {\n\tcreateAuthorizationURL,\n\trefreshAccessToken,\n\tvalidateAuthorizationCode,\n} from \"../oauth2\";\nexport interface AppleProfile {\n\t/**\n\t * The subject registered claim identifies the principal that’s the subject\n\t * of the identity token. Because this token is for your app, the value is\n\t * the unique identifier for the user.\n\t */\n\tsub: string;\n\t/**\n\t * A String value representing the user's email address.\n\t * The email address is either the user's real email address or the proxy\n\t * address, depending on their status private email relay service.\n\t */\n\temail: string;\n\t/**\n\t * A string or Boolean value that indicates whether the service verifies\n\t * the email. The value can either be a string (\"true\" or \"false\") or a\n\t * Boolean (true or false). The system may not verify email addresses for\n\t * Sign in with Apple at Work & School users, and this claim is \"false\" or\n\t * false for those users.\n\t */\n\temail_verified: true | \"true\";\n\t/**\n\t * A string or Boolean value that indicates whether the email that the user\n\t * shares is the proxy address. The value can either be a string (\"true\" or\n\t * \"false\") or a Boolean (true or false).\n\t */\n\tis_private_email: boolean;\n\t/**\n\t * An Integer value that indicates whether the user appears to be a real\n\t * person. Use the value of this claim to mitigate fraud. The possible\n\t * values are: 0 (or Unsupported), 1 (or Unknown), 2 (or LikelyReal). For\n\t * more information, see ASUserDetectionStatus. This claim is present only\n\t * in iOS 14 and later, macOS 11 and later, watchOS 7 and later, tvOS 14\n\t * and later. The claim isn’t present or supported for web-based apps.\n\t */\n\treal_user_status: number;\n\t/**\n\t * The user’s full name in the format provided during the authorization\n\t * process.\n\t */\n\tname: string;\n\t/**\n\t * The URL to the user's profile picture.\n\t */\n\tpicture: string;\n\tuser?: AppleNonConformUser | undefined;\n}\n\n/**\n * This is the shape of the `user` query parameter that Apple sends the first\n * time the user consents to the app.\n * @see https://developer.apple.com/documentation/signinwithapplerestapi/request-an-authorization-to-the-sign-in-with-apple-server./\n */\nexport interface AppleNonConformUser {\n\tname: {\n\t\tfirstName: string;\n\t\tlastName: string;\n\t};\n\temail: string;\n}\n\nexport interface AppleOptions extends ProviderOptions<AppleProfile> {\n\tclientId: string;\n\tappBundleIdentifier?: string | undefined;\n\taudience?: (string | string[]) | undefined;\n}\n\nexport const apple = (options: AppleOptions) => {\n\tconst tokenEndpoint = \"https://appleid.apple.com/auth/token\";\n\treturn {\n\t\tid: \"apple\",\n\t\tname: \"Apple\",\n\t\tasync createAuthorizationURL({ state, scopes, redirectURI }) {\n\t\t\tconst _scope = options.disableDefaultScope ? [] : [\"email\", \"name\"];\n\t\t\tif (options.scope) _scope.push(...options.scope);\n\t\t\tif (scopes) _scope.push(...scopes);\n\t\t\tconst url = await createAuthorizationURL({\n\t\t\t\tid: \"apple\",\n\t\t\t\toptions,\n\t\t\t\tauthorizationEndpoint: \"https://appleid.apple.com/auth/authorize\",\n\t\t\t\tscopes: _scope,\n\t\t\t\tstate,\n\t\t\t\tredirectURI,\n\t\t\t\tresponseMode: \"form_post\",\n\t\t\t\tresponseType: \"code id_token\",\n\t\t\t});\n\t\t\treturn url;\n\t\t},\n\t\tvalidateAuthorizationCode: async ({ code, codeVerifier, redirectURI }) => {\n\t\t\treturn validateAuthorizationCode({\n\t\t\t\tcode,\n\t\t\t\tcodeVerifier,\n\t\t\t\tredirectURI,\n\t\t\t\toptions,\n\t\t\t\ttokenEndpoint,\n\t\t\t});\n\t\t},\n\t\tasync verifyIdToken(token, nonce) {\n\t\t\tif (options.disableIdTokenSignIn) {\n\t\t\t\treturn false;\n\t\t\t}\n\t\t\tif (options.verifyIdToken) {\n\t\t\t\treturn options.verifyIdToken(token, nonce);\n\t\t\t}\n\t\t\ttry {\n\t\t\t\tconst decodedHeader = decodeProtectedHeader(token);\n\t\t\t\tconst { kid, alg: jwtAlg } = decodedHeader;\n\t\t\t\tif (!kid || !jwtAlg) return false;\n\t\t\t\tconst publicKey = await getApplePublicKey(kid);\n\t\t\t\tconst { payload: jwtClaims } = await jwtVerify(token, publicKey, {\n\t\t\t\t\talgorithms: [jwtAlg],\n\t\t\t\t\tissuer: \"https://appleid.apple.com\",\n\t\t\t\t\taudience:\n\t\t\t\t\t\toptions.audience && options.audience.length\n\t\t\t\t\t\t\t? options.audience\n\t\t\t\t\t\t\t: options.appBundleIdentifier\n\t\t\t\t\t\t\t\t? options.appBundleIdentifier\n\t\t\t\t\t\t\t\t: options.clientId,\n\t\t\t\t\tmaxTokenAge: \"1h\",\n\t\t\t\t});\n\t\t\t\t[\"email_verified\", \"is_private_email\"].forEach((field) => {\n\t\t\t\t\tif (jwtClaims[field] !== undefined) {\n\t\t\t\t\t\tjwtClaims[field] = Boolean(jwtClaims[field]);\n\t\t\t\t\t}\n\t\t\t\t});\n\t\t\t\tif (nonce && jwtClaims.nonce !== nonce) {\n\t\t\t\t\treturn false;\n\t\t\t\t}\n\t\t\t\treturn !!jwtClaims;\n\t\t\t} catch {\n\t\t\t\treturn false;\n\t\t\t}\n\t\t},\n\t\trefreshAccessToken: options.refreshAccessToken\n\t\t\t? options.refreshAccessToken\n\t\t\t: async (refreshToken) => {\n\t\t\t\t\treturn refreshAccessToken({\n\t\t\t\t\t\trefreshToken,\n\t\t\t\t\t\toptions,\n\t\t\t\t\t\ttokenEndpoint: \"https://appleid.apple.com/auth/token\",\n\t\t\t\t\t});\n\t\t\t\t},\n\t\tasync getUserInfo(token) {\n\t\t\tif (options.getUserInfo) {\n\t\t\t\treturn options.getUserInfo(token);\n\t\t\t}\n\t\t\tif (!token.idToken) {\n\t\t\t\treturn null;\n\t\t\t}\n\t\t\tconst profile = decodeJwt<AppleProfile>(token.idToken);\n\t\t\tif (!profile) {\n\t\t\t\treturn null;\n\t\t\t}\n\n\t\t\t// TODO: \"\" masking will be removed when the name field is made optional\n\t\t\tlet name: string;\n\t\t\tif (token.user?.name) {\n\t\t\t\tconst firstName = token.user.name.firstName || \"\";\n\t\t\t\tconst lastName = token.user.name.lastName || \"\";\n\t\t\t\tconst fullName = `${firstName} ${lastName}`.trim();\n\t\t\t\tname = fullName;\n\t\t\t} else {\n\t\t\t\tname = profile.name || \"\";\n\t\t\t}\n\n\t\t\tconst emailVerified =\n\t\t\t\ttypeof profile.email_verified === \"boolean\"\n\t\t\t\t\t? profile.email_verified\n\t\t\t\t\t: profile.email_verified === \"true\";\n\t\t\tconst enrichedProfile = {\n\t\t\t\t...profile,\n\t\t\t\tname,\n\t\t\t};\n\t\t\tconst userMap = await options.mapProfileToUser?.(enrichedProfile);\n\t\t\treturn {\n\t\t\t\tuser: {\n\t\t\t\t\tid: profile.sub,\n\t\t\t\t\tname: enrichedProfile.name,\n\t\t\t\t\temailVerified: emailVerified,\n\t\t\t\t\temail: profile.email,\n\t\t\t\t\t...userMap,\n\t\t\t\t},\n\t\t\t\tdata: enrichedProfile,\n\t\t\t};\n\t\t},\n\t\toptions,\n\t} satisfies OAuthProvider<AppleProfile>;\n};\n\nexport const getApplePublicKey = async (kid: string) => {\n\tconst APPLE_BASE_URL = \"https://appleid.apple.com\";\n\tconst JWKS_APPLE_URI = \"/auth/keys\";\n\tconst { data } = await betterFetch<{\n\t\tkeys: Array<{\n\t\t\tkid: string;\n\t\t\talg: string;\n\t\t\tkty: string;\n\t\t\tuse: string;\n\t\t\tn: string;\n\t\t\te: string;\n\t\t}>;\n\t}>(`${APPLE_BASE_URL}${JWKS_APPLE_URI}`);\n\tif (!data?.keys) {\n\t\tthrow new APIError(\"BAD_REQUEST\", {\n\t\t\tmessage: \"Keys not found\",\n\t\t});\n\t}\n\tconst jwk = data.keys.find((key) => key.kid === kid);\n\tif (!jwk) {\n\t\tthrow new Error(`JWK with kid ${kid} not found`);\n\t}\n\treturn await importJWK(jwk, jwk.alg);\n};\n"],"mappings":";;;;;;;;;AA6EA,MAAa,SAAS,YAA0B;CAC/C,MAAM,gBAAgB;AACtB,QAAO;EACN,IAAI;EACJ,MAAM;EACN,MAAM,uBAAuB,EAAE,OAAO,QAAQ,eAAe;GAC5D,MAAM,SAAS,QAAQ,sBAAsB,EAAE,GAAG,CAAC,SAAS,OAAO;AACnE,OAAI,QAAQ,MAAO,QAAO,KAAK,GAAG,QAAQ,MAAM;AAChD,OAAI,OAAQ,QAAO,KAAK,GAAG,OAAO;AAWlC,UAVY,MAAM,uBAAuB;IACxC,IAAI;IACJ;IACA,uBAAuB;IACvB,QAAQ;IACR;IACA;IACA,cAAc;IACd,cAAc;IACd,CAAC;;EAGH,2BAA2B,OAAO,EAAE,MAAM,cAAc,kBAAkB;AACzE,UAAO,0BAA0B;IAChC;IACA;IACA;IACA;IACA;IACA,CAAC;;EAEH,MAAM,cAAc,OAAO,OAAO;AACjC,OAAI,QAAQ,qBACX,QAAO;AAER,OAAI,QAAQ,cACX,QAAO,QAAQ,cAAc,OAAO,MAAM;AAE3C,OAAI;IAEH,MAAM,EAAE,KAAK,KAAK,WADI,sBAAsB,MAAM;AAElD,QAAI,CAAC,OAAO,CAAC,OAAQ,QAAO;IAE5B,MAAM,EAAE,SAAS,cAAc,MAAM,UAAU,OAD7B,MAAM,kBAAkB,IAAI,EACmB;KAChE,YAAY,CAAC,OAAO;KACpB,QAAQ;KACR,UACC,QAAQ,YAAY,QAAQ,SAAS,SAClC,QAAQ,WACR,QAAQ,sBACP,QAAQ,sBACR,QAAQ;KACb,aAAa;KACb,CAAC;AACF,KAAC,kBAAkB,mBAAmB,CAAC,SAAS,UAAU;AACzD,SAAI,UAAU,WAAW,OACxB,WAAU,SAAS,QAAQ,UAAU,OAAO;MAE5C;AACF,QAAI,SAAS,UAAU,UAAU,MAChC,QAAO;AAER,WAAO,CAAC,CAAC;WACF;AACP,WAAO;;;EAGT,oBAAoB,QAAQ,qBACzB,QAAQ,qBACR,OAAO,iBAAiB;AACxB,UAAO,mBAAmB;IACzB;IACA;IACA,eAAe;IACf,CAAC;;EAEL,MAAM,YAAY,OAAO;AACxB,OAAI,QAAQ,YACX,QAAO,QAAQ,YAAY,MAAM;AAElC,OAAI,CAAC,MAAM,QACV,QAAO;GAER,MAAM,UAAU,UAAwB,MAAM,QAAQ;AACtD,OAAI,CAAC,QACJ,QAAO;GAIR,IAAI;AACJ,OAAI,MAAM,MAAM,KAIf,QADiB,GAFC,MAAM,KAAK,KAAK,aAAa,GAEjB,GADb,MAAM,KAAK,KAAK,YAAY,KACD,MAAM;OAGlD,QAAO,QAAQ,QAAQ;GAGxB,MAAM,gBACL,OAAO,QAAQ,mBAAmB,YAC/B,QAAQ,iBACR,QAAQ,mBAAmB;GAC/B,MAAM,kBAAkB;IACvB,GAAG;IACH;IACA;GACD,MAAM,UAAU,MAAM,QAAQ,mBAAmB,gBAAgB;AACjE,UAAO;IACN,MAAM;KACL,IAAI,QAAQ;KACZ,MAAM,gBAAgB;KACP;KACf,OAAO,QAAQ;KACf,GAAG;KACH;IACD,MAAM;IACN;;EAEF;EACA;;AAGF,MAAa,oBAAoB,OAAO,QAAgB;CAGvD,MAAM,EAAE,SAAS,MAAM,YASpB,sCAAqC;AACxC,KAAI,CAAC,MAAM,KACV,OAAM,IAAI,SAAS,eAAe,EACjC,SAAS,kBACT,CAAC;CAEH,MAAM,MAAM,KAAK,KAAK,MAAM,QAAQ,IAAI,QAAQ,IAAI;AACpD,KAAI,CAAC,IACJ,OAAM,IAAI,MAAM,gBAAgB,IAAI,YAAY;AAEjD,QAAO,MAAM,UAAU,KAAK,IAAI,IAAI"}
@@ -0,0 +1,73 @@
1
+ import { OAuth2Tokens, ProviderOptions } from "../oauth2/oauth-provider.mjs";
2
+ import "../oauth2/index.mjs";
3
+
4
+ //#region src/social-providers/atlassian.d.ts
5
+ interface AtlassianProfile {
6
+ account_type?: string | undefined;
7
+ account_id: string;
8
+ email?: string | undefined;
9
+ name: string;
10
+ picture?: string | undefined;
11
+ nickname?: string | undefined;
12
+ locale?: string | undefined;
13
+ extended_profile?: {
14
+ job_title?: string;
15
+ organization?: string;
16
+ department?: string;
17
+ location?: string;
18
+ } | undefined;
19
+ }
20
+ interface AtlassianOptions extends ProviderOptions<AtlassianProfile> {
21
+ clientId: string;
22
+ }
23
+ declare const atlassian: (options: AtlassianOptions) => {
24
+ id: "atlassian";
25
+ name: string;
26
+ createAuthorizationURL({
27
+ state,
28
+ scopes,
29
+ codeVerifier,
30
+ redirectURI
31
+ }: {
32
+ state: string;
33
+ codeVerifier: string;
34
+ scopes?: string[] | undefined;
35
+ redirectURI: string;
36
+ display?: string | undefined;
37
+ loginHint?: string | undefined;
38
+ }): Promise<URL>;
39
+ validateAuthorizationCode: ({
40
+ code,
41
+ codeVerifier,
42
+ redirectURI
43
+ }: {
44
+ code: string;
45
+ redirectURI: string;
46
+ codeVerifier?: string | undefined;
47
+ deviceId?: string | undefined;
48
+ }) => Promise<OAuth2Tokens>;
49
+ refreshAccessToken: (refreshToken: string) => Promise<OAuth2Tokens>;
50
+ getUserInfo(token: OAuth2Tokens & {
51
+ user?: {
52
+ name?: {
53
+ firstName?: string;
54
+ lastName?: string;
55
+ };
56
+ email?: string;
57
+ } | undefined;
58
+ }): Promise<{
59
+ user: {
60
+ id: string;
61
+ name?: string;
62
+ email?: string | null;
63
+ image?: string;
64
+ emailVerified: boolean;
65
+ [key: string]: any;
66
+ };
67
+ data: any;
68
+ } | null>;
69
+ options: AtlassianOptions;
70
+ };
71
+ //#endregion
72
+ export { AtlassianOptions, AtlassianProfile, atlassian };
73
+ //# sourceMappingURL=atlassian.d.mts.map
@@ -0,0 +1,84 @@
1
+ import { logger } from "../env/logger.mjs";
2
+ import "../env/index.mjs";
3
+ import { BetterAuthError } from "../error/index.mjs";
4
+ import { createAuthorizationURL } from "../oauth2/create-authorization-url.mjs";
5
+ import { refreshAccessToken } from "../oauth2/refresh-access-token.mjs";
6
+ import { validateAuthorizationCode } from "../oauth2/validate-authorization-code.mjs";
7
+ import "../oauth2/index.mjs";
8
+ import { betterFetch } from "@better-fetch/fetch";
9
+
10
+ //#region src/social-providers/atlassian.ts
11
+ const atlassian = (options) => {
12
+ return {
13
+ id: "atlassian",
14
+ name: "Atlassian",
15
+ async createAuthorizationURL({ state, scopes, codeVerifier, redirectURI }) {
16
+ if (!options.clientId || !options.clientSecret) {
17
+ logger.error("Client Id and Secret are required for Atlassian");
18
+ throw new BetterAuthError("CLIENT_ID_AND_SECRET_REQUIRED");
19
+ }
20
+ if (!codeVerifier) throw new BetterAuthError("codeVerifier is required for Atlassian");
21
+ const _scopes = options.disableDefaultScope ? [] : ["read:jira-user", "offline_access"];
22
+ if (options.scope) _scopes.push(...options.scope);
23
+ if (scopes) _scopes.push(...scopes);
24
+ return createAuthorizationURL({
25
+ id: "atlassian",
26
+ options,
27
+ authorizationEndpoint: "https://auth.atlassian.com/authorize",
28
+ scopes: _scopes,
29
+ state,
30
+ codeVerifier,
31
+ redirectURI,
32
+ additionalParams: { audience: "api.atlassian.com" },
33
+ prompt: options.prompt
34
+ });
35
+ },
36
+ validateAuthorizationCode: async ({ code, codeVerifier, redirectURI }) => {
37
+ return validateAuthorizationCode({
38
+ code,
39
+ codeVerifier,
40
+ redirectURI,
41
+ options,
42
+ tokenEndpoint: "https://auth.atlassian.com/oauth/token"
43
+ });
44
+ },
45
+ refreshAccessToken: options.refreshAccessToken ? options.refreshAccessToken : async (refreshToken) => {
46
+ return refreshAccessToken({
47
+ refreshToken,
48
+ options: {
49
+ clientId: options.clientId,
50
+ clientSecret: options.clientSecret
51
+ },
52
+ tokenEndpoint: "https://auth.atlassian.com/oauth/token"
53
+ });
54
+ },
55
+ async getUserInfo(token) {
56
+ if (options.getUserInfo) return options.getUserInfo(token);
57
+ if (!token.accessToken) return null;
58
+ try {
59
+ const { data: profile } = await betterFetch("https://api.atlassian.com/me", { headers: { Authorization: `Bearer ${token.accessToken}` } });
60
+ if (!profile) return null;
61
+ const userMap = await options.mapProfileToUser?.(profile);
62
+ return {
63
+ user: {
64
+ id: profile.account_id,
65
+ name: profile.name,
66
+ email: profile.email,
67
+ image: profile.picture,
68
+ emailVerified: false,
69
+ ...userMap
70
+ },
71
+ data: profile
72
+ };
73
+ } catch (error) {
74
+ logger.error("Failed to fetch user info from Figma:", error);
75
+ return null;
76
+ }
77
+ },
78
+ options
79
+ };
80
+ };
81
+
82
+ //#endregion
83
+ export { atlassian };
84
+ //# sourceMappingURL=atlassian.mjs.map