@better-auth/core 1.7.0-beta.1 → 1.7.0-beta.10

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 (218) hide show
  1. package/dist/api/index.d.mts +44 -1
  2. package/dist/api/index.mjs +69 -4
  3. package/dist/context/global.mjs +1 -1
  4. package/dist/context/transaction.d.mts +7 -4
  5. package/dist/context/transaction.mjs +6 -3
  6. package/dist/db/adapter/factory.mjs +91 -3
  7. package/dist/db/adapter/get-id-field.mjs +1 -1
  8. package/dist/db/adapter/index.d.mts +87 -3
  9. package/dist/db/adapter/types.d.mts +1 -1
  10. package/dist/db/get-tables.mjs +2 -1
  11. package/dist/db/type.d.mts +17 -0
  12. package/dist/env/env-impl.mjs +1 -1
  13. package/dist/error/codes.d.mts +1 -0
  14. package/dist/error/codes.mjs +1 -0
  15. package/dist/error/index.d.mts +7 -0
  16. package/dist/index.d.mts +2 -2
  17. package/dist/instrumentation/api.mjs +12 -0
  18. package/dist/instrumentation/noop.mjs +42 -0
  19. package/dist/instrumentation/pure.index.d.mts +7 -0
  20. package/dist/instrumentation/pure.index.mjs +7 -0
  21. package/dist/instrumentation/tracer.mjs +6 -3
  22. package/dist/oauth2/authorization-params.d.mts +12 -0
  23. package/dist/oauth2/authorization-params.mjs +12 -0
  24. package/dist/oauth2/basic-credentials.d.mts +30 -0
  25. package/dist/oauth2/basic-credentials.mjs +64 -0
  26. package/dist/oauth2/client-assertion.d.mts +38 -22
  27. package/dist/oauth2/client-assertion.mjs +63 -28
  28. package/dist/oauth2/client-credentials-token.d.mts +19 -40
  29. package/dist/oauth2/client-credentials-token.mjs +20 -31
  30. package/dist/oauth2/create-authorization-url.d.mts +11 -1
  31. package/dist/oauth2/create-authorization-url.mjs +27 -7
  32. package/dist/oauth2/dpop.d.mts +142 -0
  33. package/dist/oauth2/dpop.mjs +246 -0
  34. package/dist/oauth2/index.d.mts +14 -9
  35. package/dist/oauth2/index.mjs +12 -8
  36. package/dist/oauth2/oauth-provider.d.mts +144 -10
  37. package/dist/oauth2/refresh-access-token.d.mts +20 -40
  38. package/dist/oauth2/refresh-access-token.mjs +38 -36
  39. package/dist/oauth2/reject-redirects.mjs +65 -0
  40. package/dist/oauth2/token-endpoint-auth.d.mts +17 -0
  41. package/dist/oauth2/token-endpoint-auth.mjs +89 -0
  42. package/dist/oauth2/utils.d.mts +23 -1
  43. package/dist/oauth2/utils.mjs +48 -2
  44. package/dist/oauth2/validate-authorization-code.d.mts +17 -52
  45. package/dist/oauth2/validate-authorization-code.mjs +28 -34
  46. package/dist/oauth2/verify-id-token.d.mts +27 -0
  47. package/dist/oauth2/verify-id-token.mjs +62 -0
  48. package/dist/oauth2/verify.d.mts +88 -15
  49. package/dist/oauth2/verify.mjs +203 -25
  50. package/dist/social-providers/apple.d.mts +16 -4
  51. package/dist/social-providers/apple.mjs +17 -24
  52. package/dist/social-providers/atlassian.d.mts +5 -1
  53. package/dist/social-providers/atlassian.mjs +6 -3
  54. package/dist/social-providers/cognito.d.mts +27 -3
  55. package/dist/social-providers/cognito.mjs +15 -25
  56. package/dist/social-providers/discord.d.mts +7 -3
  57. package/dist/social-providers/discord.mjs +16 -3
  58. package/dist/social-providers/dropbox.d.mts +5 -1
  59. package/dist/social-providers/dropbox.mjs +5 -4
  60. package/dist/social-providers/facebook.d.mts +24 -5
  61. package/dist/social-providers/facebook.mjs +54 -20
  62. package/dist/social-providers/figma.d.mts +5 -1
  63. package/dist/social-providers/figma.mjs +4 -3
  64. package/dist/social-providers/github.d.mts +6 -2
  65. package/dist/social-providers/github.mjs +5 -4
  66. package/dist/social-providers/gitlab.d.mts +5 -1
  67. package/dist/social-providers/gitlab.mjs +3 -2
  68. package/dist/social-providers/google.d.mts +53 -5
  69. package/dist/social-providers/google.mjs +69 -25
  70. package/dist/social-providers/huggingface.d.mts +5 -1
  71. package/dist/social-providers/huggingface.mjs +3 -2
  72. package/dist/social-providers/index.d.mts +221 -45
  73. package/dist/social-providers/index.mjs +2 -2
  74. package/dist/social-providers/kakao.d.mts +5 -1
  75. package/dist/social-providers/kakao.mjs +3 -2
  76. package/dist/social-providers/kick.d.mts +5 -1
  77. package/dist/social-providers/kick.mjs +3 -2
  78. package/dist/social-providers/line.d.mts +8 -2
  79. package/dist/social-providers/line.mjs +5 -6
  80. package/dist/social-providers/linear.d.mts +5 -1
  81. package/dist/social-providers/linear.mjs +3 -2
  82. package/dist/social-providers/linkedin.d.mts +7 -3
  83. package/dist/social-providers/linkedin.mjs +4 -3
  84. package/dist/social-providers/microsoft-entra-id.d.mts +41 -7
  85. package/dist/social-providers/microsoft-entra-id.mjs +37 -28
  86. package/dist/social-providers/naver.d.mts +5 -1
  87. package/dist/social-providers/naver.mjs +3 -2
  88. package/dist/social-providers/notion.d.mts +5 -1
  89. package/dist/social-providers/notion.mjs +5 -2
  90. package/dist/social-providers/paybin.d.mts +5 -1
  91. package/dist/social-providers/paybin.mjs +4 -3
  92. package/dist/social-providers/paypal.d.mts +6 -2
  93. package/dist/social-providers/paypal.mjs +19 -14
  94. package/dist/social-providers/polar.d.mts +5 -1
  95. package/dist/social-providers/polar.mjs +3 -2
  96. package/dist/social-providers/railway.d.mts +5 -1
  97. package/dist/social-providers/railway.mjs +3 -2
  98. package/dist/social-providers/reddit.d.mts +5 -1
  99. package/dist/social-providers/reddit.mjs +7 -5
  100. package/dist/social-providers/roblox.d.mts +6 -2
  101. package/dist/social-providers/roblox.mjs +12 -2
  102. package/dist/social-providers/salesforce.d.mts +5 -1
  103. package/dist/social-providers/salesforce.mjs +4 -3
  104. package/dist/social-providers/slack.d.mts +6 -2
  105. package/dist/social-providers/slack.mjs +11 -8
  106. package/dist/social-providers/spotify.d.mts +5 -1
  107. package/dist/social-providers/spotify.mjs +3 -2
  108. package/dist/social-providers/tiktok.d.mts +5 -1
  109. package/dist/social-providers/tiktok.mjs +14 -2
  110. package/dist/social-providers/twitch.d.mts +5 -1
  111. package/dist/social-providers/twitch.mjs +3 -2
  112. package/dist/social-providers/twitter.d.mts +4 -1
  113. package/dist/social-providers/twitter.mjs +2 -1
  114. package/dist/social-providers/vercel.d.mts +5 -1
  115. package/dist/social-providers/vercel.mjs +3 -2
  116. package/dist/social-providers/vk.d.mts +5 -1
  117. package/dist/social-providers/vk.mjs +3 -2
  118. package/dist/social-providers/wechat.d.mts +5 -1
  119. package/dist/social-providers/wechat.mjs +8 -2
  120. package/dist/social-providers/zoom.d.mts +6 -2
  121. package/dist/social-providers/zoom.mjs +10 -17
  122. package/dist/types/context.d.mts +55 -6
  123. package/dist/types/index.d.mts +1 -1
  124. package/dist/types/init-options.d.mts +182 -12
  125. package/dist/types/plugin-client.d.mts +12 -2
  126. package/dist/utils/async.d.mts +22 -0
  127. package/dist/utils/async.mjs +32 -0
  128. package/dist/utils/host.d.mts +147 -0
  129. package/dist/utils/host.mjs +298 -0
  130. package/dist/utils/ip.d.mts +28 -5
  131. package/dist/utils/ip.mjs +118 -4
  132. package/dist/utils/is-api-error.d.mts +6 -0
  133. package/dist/utils/is-api-error.mjs +8 -0
  134. package/dist/utils/redirect-uri.d.mts +20 -0
  135. package/dist/utils/redirect-uri.mjs +48 -0
  136. package/dist/utils/string.d.mts +5 -1
  137. package/dist/utils/string.mjs +20 -1
  138. package/dist/utils/url.d.mts +18 -1
  139. package/dist/utils/url.mjs +34 -4
  140. package/package.json +26 -16
  141. package/src/api/index.ts +121 -5
  142. package/src/context/transaction.ts +45 -12
  143. package/src/db/adapter/factory.ts +193 -7
  144. package/src/db/adapter/get-id-field.ts +2 -2
  145. package/src/db/adapter/index.ts +85 -2
  146. package/src/db/adapter/types.ts +2 -0
  147. package/src/db/get-tables.ts +9 -1
  148. package/src/db/schema/account.ts +4 -1
  149. package/src/db/schema/user.ts +3 -0
  150. package/src/db/type.ts +17 -0
  151. package/src/env/env-impl.ts +1 -2
  152. package/src/error/codes.ts +1 -0
  153. package/src/error/index.ts +9 -0
  154. package/src/instrumentation/api.ts +17 -0
  155. package/src/instrumentation/noop.ts +74 -0
  156. package/src/instrumentation/pure.index.ts +31 -0
  157. package/src/instrumentation/tracer.ts +8 -3
  158. package/src/oauth2/authorization-params.ts +28 -0
  159. package/src/oauth2/basic-credentials.ts +87 -0
  160. package/src/oauth2/client-assertion.ts +131 -58
  161. package/src/oauth2/client-credentials-token.ts +50 -74
  162. package/src/oauth2/create-authorization-url.ts +33 -7
  163. package/src/oauth2/dpop.ts +568 -0
  164. package/src/oauth2/index.ts +81 -11
  165. package/src/oauth2/oauth-provider.ts +153 -11
  166. package/src/oauth2/refresh-access-token.ts +82 -83
  167. package/src/oauth2/reject-redirects.ts +75 -0
  168. package/src/oauth2/token-endpoint-auth.ts +221 -0
  169. package/src/oauth2/utils.ts +72 -5
  170. package/src/oauth2/validate-authorization-code.ts +69 -89
  171. package/src/oauth2/verify-id-token.ts +115 -0
  172. package/src/oauth2/verify.ts +409 -78
  173. package/src/social-providers/apple.ts +30 -40
  174. package/src/social-providers/atlassian.ts +8 -1
  175. package/src/social-providers/cognito.ts +36 -39
  176. package/src/social-providers/discord.ts +22 -18
  177. package/src/social-providers/dropbox.ts +7 -5
  178. package/src/social-providers/facebook.ts +108 -52
  179. package/src/social-providers/figma.ts +8 -1
  180. package/src/social-providers/github.ts +5 -3
  181. package/src/social-providers/gitlab.ts +2 -0
  182. package/src/social-providers/google.ts +141 -39
  183. package/src/social-providers/huggingface.ts +8 -1
  184. package/src/social-providers/kakao.ts +2 -1
  185. package/src/social-providers/kick.ts +8 -1
  186. package/src/social-providers/line.ts +25 -27
  187. package/src/social-providers/linear.ts +8 -1
  188. package/src/social-providers/linkedin.ts +5 -3
  189. package/src/social-providers/microsoft-entra-id.ts +100 -55
  190. package/src/social-providers/naver.ts +2 -1
  191. package/src/social-providers/notion.ts +8 -1
  192. package/src/social-providers/paybin.ts +2 -0
  193. package/src/social-providers/paypal.ts +28 -17
  194. package/src/social-providers/polar.ts +8 -1
  195. package/src/social-providers/railway.ts +8 -1
  196. package/src/social-providers/reddit.ts +9 -4
  197. package/src/social-providers/roblox.ts +16 -11
  198. package/src/social-providers/salesforce.ts +8 -1
  199. package/src/social-providers/slack.ts +15 -9
  200. package/src/social-providers/spotify.ts +8 -1
  201. package/src/social-providers/tiktok.ts +22 -9
  202. package/src/social-providers/twitch.ts +2 -1
  203. package/src/social-providers/twitter.ts +1 -0
  204. package/src/social-providers/vercel.ts +8 -1
  205. package/src/social-providers/vk.ts +8 -1
  206. package/src/social-providers/wechat.ts +17 -2
  207. package/src/social-providers/zoom.ts +15 -19
  208. package/src/types/context.ts +57 -5
  209. package/src/types/index.ts +7 -0
  210. package/src/types/init-options.ts +204 -14
  211. package/src/types/plugin-client.ts +16 -2
  212. package/src/utils/async.ts +53 -0
  213. package/src/utils/host.ts +425 -0
  214. package/src/utils/ip.ts +197 -13
  215. package/src/utils/is-api-error.ts +10 -0
  216. package/src/utils/redirect-uri.ts +54 -0
  217. package/src/utils/string.ts +37 -0
  218. package/src/utils/url.ts +38 -4
@@ -0,0 +1,142 @@
1
+ import { JWK, JWTPayload } from "jose";
2
+
3
+ //#region src/oauth2/dpop.d.ts
4
+ declare const DPOP_AUTHORIZATION_SCHEME = "DPoP";
5
+ declare const BEARER_AUTHORIZATION_SCHEME = "Bearer";
6
+ declare const DPOP_PROOF_TYPE = "dpop+jwt";
7
+ declare const DPOP_SIGNING_ALGORITHMS: readonly ["EdDSA", "ES256", "ES512", "PS256", "RS256"];
8
+ type DpopSigningAlgorithm = (typeof DPOP_SIGNING_ALGORITHMS)[number];
9
+ type AccessTokenAuthorizationScheme = "Bearer" | "DPoP" | "Unknown";
10
+ interface AccessTokenAuthorization {
11
+ scheme: AccessTokenAuthorizationScheme;
12
+ token: string;
13
+ }
14
+ type DpopProofErrorCode = "invalid_dpop_proof";
15
+ type DpopProofError = Error & {
16
+ code: DpopProofErrorCode;
17
+ };
18
+ interface DpopReplayReservation {
19
+ key: string;
20
+ expiresAt: Date;
21
+ now: Date;
22
+ }
23
+ interface DpopReplayStore {
24
+ reserve: (reservation: DpopReplayReservation) => Promise<boolean> | boolean;
25
+ }
26
+ declare function createInMemoryDpopReplayStore(): DpopReplayStore;
27
+ /**
28
+ * The single-use reservation capability a {@link createDpopReplayStore} needs:
29
+ * the auth context's `internalAdapter.reserveVerificationValue`. Kept structural
30
+ * so core does not depend on the adapter implementation.
31
+ */
32
+ interface DpopReplayReservations {
33
+ reserveVerificationValue: (data: {
34
+ identifier: string;
35
+ value: string;
36
+ expiresAt: Date;
37
+ }) => Promise<boolean>;
38
+ }
39
+ /**
40
+ * Database-backed DPoP proof replay store built on the auth context's
41
+ * verification reservation primitive (`internalAdapter.reserveVerificationValue`),
42
+ * the same atomic single-use mechanism that guards SAML assertion ids and other
43
+ * one-time tokens. A replayed proof collides on the deterministic reservation id
44
+ * so `reserve` returns `false`, giving cross-instance anti-replay. Prefer this
45
+ * over {@link createInMemoryDpopReplayStore} for any multi-instance or serverless
46
+ * resource server. Requires database-backed verification storage; a
47
+ * secondary-storage-only deployment rejects the proof (fails closed).
48
+ */
49
+ declare function createDpopReplayStore(reservations: DpopReplayReservations): DpopReplayStore;
50
+ interface VerifyDpopProofOptions {
51
+ proofJwt: string;
52
+ method: string;
53
+ url: string;
54
+ accessToken?: string;
55
+ expectedJkt?: string;
56
+ requireAth?: boolean;
57
+ nowSeconds?: number;
58
+ proofMaxAgeSeconds?: number;
59
+ signingAlgorithms?: readonly string[];
60
+ replayStore?: DpopReplayStore;
61
+ }
62
+ interface VerifiedDpopProof {
63
+ jwk: JWK;
64
+ jkt: string;
65
+ jti: string;
66
+ htm: string;
67
+ htu: string;
68
+ iat: number;
69
+ ath?: string;
70
+ replayKey: string;
71
+ expiresAt: Date;
72
+ }
73
+ declare function createDpopProofError(code: DpopProofErrorCode, message: string): DpopProofError;
74
+ declare function isDpopProofError(error: unknown): error is DpopProofError;
75
+ declare function parseAccessTokenAuthorization(authorization: string | null | undefined): AccessTokenAuthorization | undefined;
76
+ declare function stripAccessTokenAuthorizationScheme(token: string): string;
77
+ declare function normalizeDpopHtu(url: string): string;
78
+ declare function deriveDpopAth(accessToken: string): Promise<string>;
79
+ declare function deriveDpopJkt(jwk: JWK): Promise<string>;
80
+ /**
81
+ * Extracts the DPoP key thumbprint from an RFC 7800 `cnf` confirmation. The
82
+ * input is untrusted (a JWT claim, a JSON column), so any shape other than an
83
+ * object carrying a non-empty string `jkt` (a primitive, an array, a different
84
+ * confirmation method such as mTLS `x5t#S256`) yields `undefined` instead of
85
+ * throwing.
86
+ */
87
+ declare function getConfirmationJkt(confirmation: unknown): string | undefined;
88
+ declare function getDpopJktFromPayload(payload: JWTPayload): string | undefined;
89
+ declare function verifyDpopProof({
90
+ proofJwt,
91
+ method,
92
+ url,
93
+ accessToken,
94
+ expectedJkt,
95
+ requireAth,
96
+ nowSeconds,
97
+ proofMaxAgeSeconds,
98
+ signingAlgorithms,
99
+ replayStore
100
+ }: VerifyDpopProofOptions): Promise<VerifiedDpopProof>;
101
+ type DpopBindingErrorCode = "invalid_token" | "invalid_dpop_proof";
102
+ type DpopBindingError = Error & {
103
+ code: DpopBindingErrorCode;
104
+ };
105
+ declare function createDpopBindingError(code: DpopBindingErrorCode, message: string): DpopBindingError;
106
+ declare function isDpopBindingError(error: unknown): error is DpopBindingError;
107
+ interface EnforceDpopBindingParams {
108
+ /** The already-verified access-token payload (from JWKS or introspection). */
109
+ payload: JWTPayload;
110
+ /** The parsed `Authorization` header (scheme + token). */
111
+ authorization: AccessTokenAuthorization;
112
+ /** The `DPoP` proof header value, if any. */
113
+ proofJwt: string | null | undefined;
114
+ method: string;
115
+ url: string;
116
+ replayStore?: DpopReplayStore;
117
+ proofMaxAgeSeconds?: number;
118
+ signingAlgorithms?: readonly string[];
119
+ }
120
+ /**
121
+ * Enforces the RFC 9449 §7.1 sender-constraint check for a resource request,
122
+ * given an access-token payload that has already been validated (by JWKS or
123
+ * introspection). This is the single source of truth for the
124
+ * "is the token DPoP-bound? then require the DPoP scheme, a proof, and a
125
+ * matching key" decision, shared by every resource-server entry point.
126
+ *
127
+ * Throws a {@link DpopBindingError} on any mismatch so callers map the
128
+ * `invalid_token` / `invalid_dpop_proof` code into their own transport. Returns
129
+ * normally for a valid bearer token (no `cnf.jkt`, no DPoP scheme).
130
+ */
131
+ declare function enforceDpopBinding({
132
+ payload,
133
+ authorization,
134
+ proofJwt,
135
+ method,
136
+ url,
137
+ replayStore,
138
+ proofMaxAgeSeconds,
139
+ signingAlgorithms
140
+ }: EnforceDpopBindingParams): Promise<void>;
141
+ //#endregion
142
+ export { AccessTokenAuthorization, AccessTokenAuthorizationScheme, BEARER_AUTHORIZATION_SCHEME, DPOP_AUTHORIZATION_SCHEME, DPOP_PROOF_TYPE, DPOP_SIGNING_ALGORITHMS, DpopBindingError, DpopBindingErrorCode, DpopProofError, DpopProofErrorCode, DpopReplayReservation, DpopReplayReservations, DpopReplayStore, DpopSigningAlgorithm, EnforceDpopBindingParams, VerifiedDpopProof, VerifyDpopProofOptions, createDpopBindingError, createDpopProofError, createDpopReplayStore, createInMemoryDpopReplayStore, deriveDpopAth, deriveDpopJkt, enforceDpopBinding, getConfirmationJkt, getDpopJktFromPayload, isDpopBindingError, isDpopProofError, normalizeDpopHtu, parseAccessTokenAuthorization, stripAccessTokenAuthorizationScheme, verifyDpopProof };
@@ -0,0 +1,246 @@
1
+ import { base64url, calculateJwkThumbprint, decodeProtectedHeader, importJWK, jwtVerify } from "jose";
2
+ //#region src/oauth2/dpop.ts
3
+ const DPOP_AUTHORIZATION_SCHEME = "DPoP";
4
+ const BEARER_AUTHORIZATION_SCHEME = "Bearer";
5
+ const DPOP_PROOF_TYPE = "dpop+jwt";
6
+ const DPOP_SIGNING_ALGORITHMS = [
7
+ "EdDSA",
8
+ "ES256",
9
+ "ES512",
10
+ "PS256",
11
+ "RS256"
12
+ ];
13
+ const DEFAULT_DPOP_PROOF_MAX_AGE_SECONDS = 300;
14
+ const MAX_DPOP_JTI_LENGTH = 512;
15
+ const JWK_PRIVATE_FIELDS = new Set([
16
+ "d",
17
+ "p",
18
+ "q",
19
+ "dp",
20
+ "dq",
21
+ "qi",
22
+ "oth",
23
+ "k"
24
+ ]);
25
+ function createInMemoryDpopReplayStore() {
26
+ const reservations = /* @__PURE__ */ new Map();
27
+ return { reserve({ key, expiresAt, now }) {
28
+ const nowMs = now.getTime();
29
+ for (const [storedKey, expiresAtMs] of reservations) if (expiresAtMs <= nowMs) reservations.delete(storedKey);
30
+ if (reservations.has(key)) return false;
31
+ reservations.set(key, expiresAt.getTime());
32
+ return true;
33
+ } };
34
+ }
35
+ /**
36
+ * Database-backed DPoP proof replay store built on the auth context's
37
+ * verification reservation primitive (`internalAdapter.reserveVerificationValue`),
38
+ * the same atomic single-use mechanism that guards SAML assertion ids and other
39
+ * one-time tokens. A replayed proof collides on the deterministic reservation id
40
+ * so `reserve` returns `false`, giving cross-instance anti-replay. Prefer this
41
+ * over {@link createInMemoryDpopReplayStore} for any multi-instance or serverless
42
+ * resource server. Requires database-backed verification storage; a
43
+ * secondary-storage-only deployment rejects the proof (fails closed).
44
+ */
45
+ function createDpopReplayStore(reservations) {
46
+ return { reserve: ({ key, expiresAt }) => reservations.reserveVerificationValue({
47
+ identifier: `dpop-proof:${key}`,
48
+ value: key,
49
+ expiresAt
50
+ }) };
51
+ }
52
+ function createDpopProofError(code, message) {
53
+ return Object.assign(new Error(message), { code });
54
+ }
55
+ function isDpopProofError(error) {
56
+ return error instanceof Error && "code" in error && error.code === "invalid_dpop_proof";
57
+ }
58
+ function parseAccessTokenAuthorization(authorization) {
59
+ if (!authorization) return void 0;
60
+ const value = authorization.trim();
61
+ if (!value) return void 0;
62
+ const match = /^([A-Za-z][A-Za-z0-9!#$%&'*+.^_`|~-]*)\s+(.+)$/.exec(value);
63
+ if (!match) return {
64
+ scheme: "Unknown",
65
+ token: value
66
+ };
67
+ const scheme = match[1] ?? "";
68
+ const token = match[2]?.trim() ?? "";
69
+ if (scheme.toLowerCase() === "bearer") return {
70
+ scheme: "Bearer",
71
+ token
72
+ };
73
+ if (scheme.toLowerCase() === "dpop") return {
74
+ scheme: "DPoP",
75
+ token
76
+ };
77
+ return {
78
+ scheme: "Unknown",
79
+ token: value
80
+ };
81
+ }
82
+ function stripAccessTokenAuthorizationScheme(token) {
83
+ return parseAccessTokenAuthorization(token)?.token ?? token;
84
+ }
85
+ function normalizeDpopHtu(url) {
86
+ const parsed = new URL(url);
87
+ if (parsed.hash) throw new Error("DPoP proof htu must not contain a fragment");
88
+ return `${parsed.origin}${parsed.pathname}`;
89
+ }
90
+ async function deriveDpopAth(accessToken) {
91
+ const digest = await crypto.subtle.digest("SHA-256", new TextEncoder().encode(accessToken));
92
+ return base64url.encode(new Uint8Array(digest));
93
+ }
94
+ async function deriveDpopJkt(jwk) {
95
+ return calculateJwkThumbprint(jwk, "sha256");
96
+ }
97
+ /**
98
+ * Extracts the DPoP key thumbprint from an RFC 7800 `cnf` confirmation. The
99
+ * input is untrusted (a JWT claim, a JSON column), so any shape other than an
100
+ * object carrying a non-empty string `jkt` (a primitive, an array, a different
101
+ * confirmation method such as mTLS `x5t#S256`) yields `undefined` instead of
102
+ * throwing.
103
+ */
104
+ function getConfirmationJkt(confirmation) {
105
+ if (!confirmation || typeof confirmation !== "object" || Array.isArray(confirmation)) return;
106
+ const jkt = confirmation.jkt;
107
+ return typeof jkt === "string" && jkt.length > 0 ? jkt : void 0;
108
+ }
109
+ function getDpopJktFromPayload(payload) {
110
+ return getConfirmationJkt(payload.cnf);
111
+ }
112
+ function getStringClaim(payload, claim) {
113
+ const value = payload[claim];
114
+ return typeof value === "string" && value.length > 0 ? value : void 0;
115
+ }
116
+ function getNumberClaim(payload, claim) {
117
+ const value = payload[claim];
118
+ return typeof value === "number" && Number.isFinite(value) ? value : void 0;
119
+ }
120
+ function assertSupportedDpopAlgorithm(alg, signingAlgorithms) {
121
+ if (!alg || alg === "none" || alg.startsWith("HS")) throw createDpopProofError("invalid_dpop_proof", "DPoP proof must use an asymmetric JWS algorithm");
122
+ if (!signingAlgorithms.includes(alg)) throw createDpopProofError("invalid_dpop_proof", "DPoP proof uses an unsupported JWS algorithm");
123
+ }
124
+ function assertPublicJwk(jwk) {
125
+ if (!jwk || typeof jwk !== "object" || Array.isArray(jwk)) throw createDpopProofError("invalid_dpop_proof", "DPoP proof header must include a public jwk");
126
+ if (jwk.kty === "oct") throw createDpopProofError("invalid_dpop_proof", "DPoP proof jwk must be asymmetric");
127
+ for (const field of JWK_PRIVATE_FIELDS) if (field in jwk) throw createDpopProofError("invalid_dpop_proof", "DPoP proof jwk must not contain private key material");
128
+ }
129
+ async function deriveDpopReplayKey(params) {
130
+ const input = `${params.jkt}\n${params.htm}\n${params.htu}\n${params.jti}`;
131
+ const digest = await crypto.subtle.digest("SHA-256", new TextEncoder().encode(input));
132
+ return base64url.encode(new Uint8Array(digest));
133
+ }
134
+ async function reserveDpopReplay(replayStore, reservation) {
135
+ if (!replayStore) return;
136
+ if (!await replayStore.reserve(reservation)) throw createDpopProofError("invalid_dpop_proof", "DPoP proof jti has already been used");
137
+ }
138
+ async function verifyDpopProof({ proofJwt, method, url, accessToken, expectedJkt, requireAth = false, nowSeconds = Math.floor(Date.now() / 1e3), proofMaxAgeSeconds = DEFAULT_DPOP_PROOF_MAX_AGE_SECONDS, signingAlgorithms = DPOP_SIGNING_ALGORITHMS, replayStore }) {
139
+ if (!proofJwt || proofJwt.split(".").length !== 3) throw createDpopProofError("invalid_dpop_proof", "DPoP proof must be a compact JWT");
140
+ let protectedHeader;
141
+ try {
142
+ protectedHeader = decodeProtectedHeader(proofJwt);
143
+ } catch (error) {
144
+ throw createDpopProofError("invalid_dpop_proof", error instanceof Error ? error.message : "DPoP proof header is invalid");
145
+ }
146
+ if (protectedHeader.typ !== "dpop+jwt") throw createDpopProofError("invalid_dpop_proof", "DPoP proof typ must be \"dpop+jwt\"");
147
+ assertSupportedDpopAlgorithm(protectedHeader.alg, signingAlgorithms);
148
+ assertPublicJwk(protectedHeader.jwk);
149
+ let payload;
150
+ try {
151
+ payload = (await jwtVerify(proofJwt, await importJWK(protectedHeader.jwk, protectedHeader.alg), { typ: DPOP_PROOF_TYPE })).payload;
152
+ } catch (error) {
153
+ throw createDpopProofError("invalid_dpop_proof", error instanceof Error ? error.message : "DPoP proof signature is invalid");
154
+ }
155
+ const htm = getStringClaim(payload, "htm");
156
+ const htu = getStringClaim(payload, "htu");
157
+ const jti = getStringClaim(payload, "jti");
158
+ const iat = getNumberClaim(payload, "iat");
159
+ if (!htm || !htu || !jti || iat === void 0) throw createDpopProofError("invalid_dpop_proof", "DPoP proof must include htm, htu, jti, and iat claims");
160
+ if (jti.length > MAX_DPOP_JTI_LENGTH) throw createDpopProofError("invalid_dpop_proof", "DPoP proof jti is too large");
161
+ if (htm.toUpperCase() !== method.toUpperCase()) throw createDpopProofError("invalid_dpop_proof", "DPoP proof htm does not match the request method");
162
+ let normalizedHtu;
163
+ let proofHtu;
164
+ try {
165
+ normalizedHtu = normalizeDpopHtu(url);
166
+ proofHtu = normalizeDpopHtu(htu);
167
+ } catch (error) {
168
+ throw createDpopProofError("invalid_dpop_proof", error instanceof Error ? error.message : "DPoP proof htu is invalid");
169
+ }
170
+ if (proofHtu !== normalizedHtu) throw createDpopProofError("invalid_dpop_proof", "DPoP proof htu does not match the request URL");
171
+ if (iat > nowSeconds + 5 || nowSeconds - iat > proofMaxAgeSeconds) throw createDpopProofError("invalid_dpop_proof", "DPoP proof iat is outside the accepted window");
172
+ const ath = getStringClaim(payload, "ath");
173
+ if (requireAth && !ath) throw createDpopProofError("invalid_dpop_proof", "DPoP proof must include an ath claim");
174
+ if (accessToken !== void 0) {
175
+ if (ath !== await deriveDpopAth(accessToken)) throw createDpopProofError("invalid_dpop_proof", "DPoP proof ath does not match the access token");
176
+ }
177
+ const jkt = await deriveDpopJkt(protectedHeader.jwk);
178
+ if (expectedJkt !== void 0 && jkt !== expectedJkt) throw createDpopProofError("invalid_dpop_proof", "DPoP proof key does not match the bound token");
179
+ const replayKey = await deriveDpopReplayKey({
180
+ jkt,
181
+ htm: htm.toUpperCase(),
182
+ htu: normalizedHtu,
183
+ jti
184
+ });
185
+ const expiresAt = /* @__PURE__ */ new Date((iat + proofMaxAgeSeconds) * 1e3);
186
+ await reserveDpopReplay(replayStore, {
187
+ key: replayKey,
188
+ expiresAt,
189
+ now: /* @__PURE__ */ new Date(nowSeconds * 1e3)
190
+ });
191
+ return {
192
+ jwk: protectedHeader.jwk,
193
+ jkt,
194
+ jti,
195
+ htm,
196
+ htu: normalizedHtu,
197
+ iat,
198
+ ath,
199
+ replayKey,
200
+ expiresAt
201
+ };
202
+ }
203
+ function createDpopBindingError(code, message) {
204
+ return Object.assign(new Error(message), { code });
205
+ }
206
+ function isDpopBindingError(error) {
207
+ return error instanceof Error && "code" in error && (error.code === "invalid_token" || error.code === "invalid_dpop_proof");
208
+ }
209
+ /**
210
+ * Enforces the RFC 9449 §7.1 sender-constraint check for a resource request,
211
+ * given an access-token payload that has already been validated (by JWKS or
212
+ * introspection). This is the single source of truth for the
213
+ * "is the token DPoP-bound? then require the DPoP scheme, a proof, and a
214
+ * matching key" decision, shared by every resource-server entry point.
215
+ *
216
+ * Throws a {@link DpopBindingError} on any mismatch so callers map the
217
+ * `invalid_token` / `invalid_dpop_proof` code into their own transport. Returns
218
+ * normally for a valid bearer token (no `cnf.jkt`, no DPoP scheme).
219
+ */
220
+ async function enforceDpopBinding({ payload, authorization, proofJwt, method, url, replayStore, proofMaxAgeSeconds, signingAlgorithms }) {
221
+ const dpopJkt = getDpopJktFromPayload(payload);
222
+ if (!dpopJkt) {
223
+ if (authorization.scheme === "DPoP") throw createDpopBindingError("invalid_token", "DPoP authorization requires a DPoP-bound access token");
224
+ return;
225
+ }
226
+ if (authorization.scheme !== "DPoP") throw createDpopBindingError("invalid_token", "DPoP-bound access token requires the DPoP authorization scheme");
227
+ if (!proofJwt) throw createDpopBindingError("invalid_dpop_proof", "DPoP proof header is required");
228
+ try {
229
+ await verifyDpopProof({
230
+ proofJwt,
231
+ method,
232
+ url,
233
+ accessToken: authorization.token,
234
+ expectedJkt: dpopJkt,
235
+ requireAth: true,
236
+ proofMaxAgeSeconds,
237
+ signingAlgorithms,
238
+ replayStore
239
+ });
240
+ } catch (error) {
241
+ if (isDpopProofError(error)) throw createDpopBindingError("invalid_dpop_proof", error.message);
242
+ throw error;
243
+ }
244
+ }
245
+ //#endregion
246
+ export { BEARER_AUTHORIZATION_SCHEME, DPOP_AUTHORIZATION_SCHEME, DPOP_PROOF_TYPE, DPOP_SIGNING_ALGORITHMS, createDpopBindingError, createDpopProofError, createDpopReplayStore, createInMemoryDpopReplayStore, deriveDpopAth, deriveDpopJkt, enforceDpopBinding, getConfirmationJkt, getDpopJktFromPayload, isDpopBindingError, isDpopProofError, normalizeDpopHtu, parseAccessTokenAuthorization, stripAccessTokenAuthorizationScheme, verifyDpopProof };
@@ -1,9 +1,14 @@
1
- import { ASSERTION_SIGNING_ALGORITHMS, AssertionSigningAlgorithm, CLIENT_ASSERTION_TYPE, ClientAssertionConfig, resolveAssertionParams, signClientAssertion } from "./client-assertion.mjs";
2
- import { OAuth2Tokens, OAuth2UserInfo, OAuthProvider, ProviderOptions } from "./oauth-provider.mjs";
3
- import { clientCredentialsToken, clientCredentialsTokenRequest, createClientCredentialsTokenRequest } from "./client-credentials-token.mjs";
4
- import { createAuthorizationURL } from "./create-authorization-url.mjs";
5
- import { createRefreshAccessTokenRequest, refreshAccessToken, refreshAccessTokenRequest } from "./refresh-access-token.mjs";
6
- import { generateCodeChallenge, getOAuth2Tokens } from "./utils.mjs";
7
- import { authorizationCodeRequest, createAuthorizationCodeRequest, validateAuthorizationCode, validateToken } from "./validate-authorization-code.mjs";
8
- import { getJwks, verifyAccessToken, verifyJwsAccessToken } from "./verify.mjs";
9
- export { ASSERTION_SIGNING_ALGORITHMS, type AssertionSigningAlgorithm, CLIENT_ASSERTION_TYPE, type ClientAssertionConfig, type OAuth2Tokens, type OAuth2UserInfo, type OAuthProvider, type ProviderOptions, authorizationCodeRequest, clientCredentialsToken, clientCredentialsTokenRequest, createAuthorizationCodeRequest, createAuthorizationURL, createClientCredentialsTokenRequest, createRefreshAccessTokenRequest, generateCodeChallenge, getJwks, getOAuth2Tokens, refreshAccessToken, refreshAccessTokenRequest, resolveAssertionParams, signClientAssertion, validateAuthorizationCode, validateToken, verifyAccessToken, verifyJwsAccessToken };
1
+ import { additionalAuthorizationParamsSchema } from "./authorization-params.mjs";
2
+ import { decodeBasicCredentials, encodeBasicCredentials } from "./basic-credentials.mjs";
3
+ import { CLIENT_ASSERTION_TYPE, ClientAssertionContext, ClientAssertionGetter, ClientAssertionGrantType, PRIVATE_KEY_JWT_SIGNING_ALGORITHMS, PrivateKeyJwtClientAssertionGetterOptions, PrivateKeyJwtSigningAlgorithm, createPrivateKeyJwtClientAssertionGetter, resolveClientAssertionParams, signPrivateKeyJwtClientAssertion } from "./client-assertion.mjs";
4
+ import { OAuth2Tokens, OAuth2UserInfo, OAuthIdTokenConfig, OAuthProvider, OAuthRefreshContext, ProviderOptions } from "./oauth-provider.mjs";
5
+ import { TokenEndpointAuth, TokenEndpointAuthMethod, TokenEndpointSecretAuthentication } from "./token-endpoint-auth.mjs";
6
+ import { clientCredentialsToken, clientCredentialsTokenRequest } from "./client-credentials-token.mjs";
7
+ import { RESERVED_AUTHORIZATION_PARAMS, RESERVED_AUTHORIZATION_PARAMS_SET, createAuthorizationURL } from "./create-authorization-url.mjs";
8
+ import { AccessTokenAuthorization, AccessTokenAuthorizationScheme, BEARER_AUTHORIZATION_SCHEME, DPOP_AUTHORIZATION_SCHEME, DPOP_PROOF_TYPE, DPOP_SIGNING_ALGORITHMS, DpopBindingError, DpopBindingErrorCode, DpopProofError, DpopProofErrorCode, DpopReplayReservation, DpopReplayReservations, DpopReplayStore, DpopSigningAlgorithm, EnforceDpopBindingParams, VerifiedDpopProof, VerifyDpopProofOptions, createDpopBindingError, createDpopProofError, createDpopReplayStore, createInMemoryDpopReplayStore, deriveDpopAth, deriveDpopJkt, enforceDpopBinding, getConfirmationJkt, getDpopJktFromPayload, isDpopBindingError, isDpopProofError, normalizeDpopHtu, parseAccessTokenAuthorization, stripAccessTokenAuthorizationScheme, verifyDpopProof } from "./dpop.mjs";
9
+ import { refreshAccessToken, refreshAccessTokenRequest } from "./refresh-access-token.mjs";
10
+ import { applyDefaultAccessTokenExpiry, generateCodeChallenge, getOAuth2Tokens, getPrimaryClientId, mergeScopes } from "./utils.mjs";
11
+ import { authorizationCodeRequest, validateAuthorizationCode, validateToken } from "./validate-authorization-code.mjs";
12
+ import { ResourceRequestInput, VerifyAccessTokenOptions, VerifyAccessTokenRequestOptions, getJwks, requestToResourceInput, verifyAccessTokenRequest, verifyBearerToken, verifyJwsAccessToken } from "./verify.mjs";
13
+ import { supportsIdTokenSignIn, verifyProviderIdToken } from "./verify-id-token.mjs";
14
+ export { type AccessTokenAuthorization, type AccessTokenAuthorizationScheme, BEARER_AUTHORIZATION_SCHEME, CLIENT_ASSERTION_TYPE, type ClientAssertionContext, type ClientAssertionGetter, type ClientAssertionGrantType, DPOP_AUTHORIZATION_SCHEME, DPOP_PROOF_TYPE, DPOP_SIGNING_ALGORITHMS, type DpopBindingError, type DpopBindingErrorCode, type DpopProofError, type DpopProofErrorCode, type DpopReplayReservation, type DpopReplayReservations, type DpopReplayStore, type DpopSigningAlgorithm, type EnforceDpopBindingParams, type OAuth2Tokens, type OAuth2UserInfo, type OAuthIdTokenConfig, type OAuthProvider, type OAuthRefreshContext, PRIVATE_KEY_JWT_SIGNING_ALGORITHMS, type PrivateKeyJwtClientAssertionGetterOptions, type PrivateKeyJwtSigningAlgorithm, type ProviderOptions, RESERVED_AUTHORIZATION_PARAMS, RESERVED_AUTHORIZATION_PARAMS_SET, type ResourceRequestInput, type TokenEndpointAuth, type TokenEndpointAuthMethod, type TokenEndpointSecretAuthentication, type VerifiedDpopProof, type VerifyAccessTokenOptions, type VerifyAccessTokenRequestOptions, type VerifyDpopProofOptions, additionalAuthorizationParamsSchema, applyDefaultAccessTokenExpiry, authorizationCodeRequest, clientCredentialsToken, clientCredentialsTokenRequest, createAuthorizationURL, createDpopBindingError, createDpopProofError, createDpopReplayStore, createInMemoryDpopReplayStore, createPrivateKeyJwtClientAssertionGetter, decodeBasicCredentials, deriveDpopAth, deriveDpopJkt, encodeBasicCredentials, enforceDpopBinding, generateCodeChallenge, getConfirmationJkt, getDpopJktFromPayload, getJwks, getOAuth2Tokens, getPrimaryClientId, isDpopBindingError, isDpopProofError, mergeScopes, normalizeDpopHtu, parseAccessTokenAuthorization, refreshAccessToken, refreshAccessTokenRequest, requestToResourceInput, resolveClientAssertionParams, signPrivateKeyJwtClientAssertion, stripAccessTokenAuthorizationScheme, supportsIdTokenSignIn, validateAuthorizationCode, validateToken, verifyAccessTokenRequest, verifyBearerToken, verifyDpopProof, verifyJwsAccessToken, verifyProviderIdToken };
@@ -1,8 +1,12 @@
1
- import { ASSERTION_SIGNING_ALGORITHMS, CLIENT_ASSERTION_TYPE, resolveAssertionParams, signClientAssertion } from "./client-assertion.mjs";
2
- import { clientCredentialsToken, clientCredentialsTokenRequest, createClientCredentialsTokenRequest } from "./client-credentials-token.mjs";
3
- import { generateCodeChallenge, getOAuth2Tokens } from "./utils.mjs";
4
- import { createAuthorizationURL } from "./create-authorization-url.mjs";
5
- import { createRefreshAccessTokenRequest, refreshAccessToken, refreshAccessTokenRequest } from "./refresh-access-token.mjs";
6
- import { authorizationCodeRequest, createAuthorizationCodeRequest, validateAuthorizationCode, validateToken } from "./validate-authorization-code.mjs";
7
- import { getJwks, verifyAccessToken, verifyJwsAccessToken } from "./verify.mjs";
8
- export { ASSERTION_SIGNING_ALGORITHMS, CLIENT_ASSERTION_TYPE, authorizationCodeRequest, clientCredentialsToken, clientCredentialsTokenRequest, createAuthorizationCodeRequest, createAuthorizationURL, createClientCredentialsTokenRequest, createRefreshAccessTokenRequest, generateCodeChallenge, getJwks, getOAuth2Tokens, refreshAccessToken, refreshAccessTokenRequest, resolveAssertionParams, signClientAssertion, validateAuthorizationCode, validateToken, verifyAccessToken, verifyJwsAccessToken };
1
+ import { applyDefaultAccessTokenExpiry, generateCodeChallenge, getOAuth2Tokens, getPrimaryClientId, mergeScopes } from "./utils.mjs";
2
+ import { RESERVED_AUTHORIZATION_PARAMS, RESERVED_AUTHORIZATION_PARAMS_SET, createAuthorizationURL } from "./create-authorization-url.mjs";
3
+ import { additionalAuthorizationParamsSchema } from "./authorization-params.mjs";
4
+ import { decodeBasicCredentials, encodeBasicCredentials } from "./basic-credentials.mjs";
5
+ import { CLIENT_ASSERTION_TYPE, PRIVATE_KEY_JWT_SIGNING_ALGORITHMS, createPrivateKeyJwtClientAssertionGetter, resolveClientAssertionParams, signPrivateKeyJwtClientAssertion } from "./client-assertion.mjs";
6
+ import { clientCredentialsToken, clientCredentialsTokenRequest } from "./client-credentials-token.mjs";
7
+ import { BEARER_AUTHORIZATION_SCHEME, DPOP_AUTHORIZATION_SCHEME, DPOP_PROOF_TYPE, DPOP_SIGNING_ALGORITHMS, createDpopBindingError, createDpopProofError, createDpopReplayStore, createInMemoryDpopReplayStore, deriveDpopAth, deriveDpopJkt, enforceDpopBinding, getConfirmationJkt, getDpopJktFromPayload, isDpopBindingError, isDpopProofError, normalizeDpopHtu, parseAccessTokenAuthorization, stripAccessTokenAuthorizationScheme, verifyDpopProof } from "./dpop.mjs";
8
+ import { refreshAccessToken, refreshAccessTokenRequest } from "./refresh-access-token.mjs";
9
+ import { authorizationCodeRequest, validateAuthorizationCode, validateToken } from "./validate-authorization-code.mjs";
10
+ import { getJwks, requestToResourceInput, verifyAccessTokenRequest, verifyBearerToken, verifyJwsAccessToken } from "./verify.mjs";
11
+ import { supportsIdTokenSignIn, verifyProviderIdToken } from "./verify-id-token.mjs";
12
+ export { BEARER_AUTHORIZATION_SCHEME, CLIENT_ASSERTION_TYPE, DPOP_AUTHORIZATION_SCHEME, DPOP_PROOF_TYPE, DPOP_SIGNING_ALGORITHMS, PRIVATE_KEY_JWT_SIGNING_ALGORITHMS, RESERVED_AUTHORIZATION_PARAMS, RESERVED_AUTHORIZATION_PARAMS_SET, additionalAuthorizationParamsSchema, applyDefaultAccessTokenExpiry, authorizationCodeRequest, clientCredentialsToken, clientCredentialsTokenRequest, createAuthorizationURL, createDpopBindingError, createDpopProofError, createDpopReplayStore, createInMemoryDpopReplayStore, createPrivateKeyJwtClientAssertionGetter, decodeBasicCredentials, deriveDpopAth, deriveDpopJkt, encodeBasicCredentials, enforceDpopBinding, generateCodeChallenge, getConfirmationJkt, getDpopJktFromPayload, getJwks, getOAuth2Tokens, getPrimaryClientId, isDpopBindingError, isDpopProofError, mergeScopes, normalizeDpopHtu, parseAccessTokenAuthorization, refreshAccessToken, refreshAccessTokenRequest, requestToResourceInput, resolveClientAssertionParams, signPrivateKeyJwtClientAssertion, stripAccessTokenAuthorizationScheme, supportsIdTokenSignIn, validateAuthorizationCode, validateToken, verifyAccessTokenRequest, verifyBearerToken, verifyDpopProof, verifyJwsAccessToken, verifyProviderIdToken };
@@ -1,5 +1,53 @@
1
1
  import { Awaitable, LiteralString } from "../types/helper.mjs";
2
+ import { JWTVerifyGetKey } from "jose";
3
+
2
4
  //#region src/oauth2/oauth-provider.d.ts
5
+ /**
6
+ * id_token verification config for a social provider.
7
+ *
8
+ * Declares how a client-submitted id_token is verified. The shared verifier
9
+ * (`verifyProviderIdToken`) consumes this instead of each provider implementing its own
10
+ * boolean check, so verification is centralized and fail-closed: a provider without a config
11
+ * cannot accept a forged token by omission.
12
+ */
13
+ type OAuthIdTokenConfig = {
14
+ /**
15
+ * JWKS resolver used to verify the JWS signature. Accepts a jose
16
+ * `createRemoteJWKSet` resolver or a key-resolving function
17
+ * `(protectedHeader) => key`.
18
+ */
19
+ jwks: JWTVerifyGetKey; /** Expected `iss`. Omit for providers whose issuer varies per tenant. */
20
+ issuer?: (string | string[]) | undefined; /** Expected `aud`, usually the client ID. */
21
+ audience: string | string[]; /** Permitted JWS algorithms. Defaults to the token's `alg` header. */
22
+ algorithms?: string[] | undefined; /** Maximum token age passed to jose (e.g. `"1h"`). */
23
+ maxTokenAge?: string | undefined;
24
+ /**
25
+ * How the `nonce` claim is compared to the expected nonce.
26
+ * - `"exact"` (default): strict equality.
27
+ * - `"exact-or-sha256"`: matches the raw nonce or its SHA-256 hex digest (Apple).
28
+ */
29
+ nonceComparison?: ("exact" | "exact-or-sha256") | undefined;
30
+ /**
31
+ * Accept non-JWS (opaque) tokens without signature verification. Identity is then
32
+ * resolved by getUserInfo from the access token via the provider userinfo endpoint,
33
+ * which validates it (e.g. Facebook Graph access tokens).
34
+ */
35
+ allowOpaqueToken?: boolean | undefined;
36
+ /**
37
+ * Provider-specific claim check applied after the signature, issuer,
38
+ * audience, max-age, and nonce checks pass. Return `false` to reject the
39
+ * token. Used to enforce constraints the standard checks cannot express,
40
+ * e.g. Google's hosted-domain (`hd`) restriction. Omitted by providers
41
+ * that have no extra claim requirement.
42
+ */
43
+ verifyClaims?: ((claims: Record<string, unknown>) => boolean) | undefined;
44
+ } | {
45
+ /**
46
+ * Custom verifier for providers that cannot verify against a local JWKS, such as a
47
+ * remote verification endpoint (e.g. LINE).
48
+ */
49
+ verify: (token: string, nonce?: string) => Promise<boolean>;
50
+ };
3
51
  interface OAuth2Tokens {
4
52
  tokenType?: string | undefined;
5
53
  accessToken?: string | undefined;
@@ -21,8 +69,30 @@ type OAuth2UserInfo = {
21
69
  image?: string | undefined;
22
70
  emailVerified: boolean;
23
71
  };
72
+ /**
73
+ * Request metadata available to provider refresh hooks.
74
+ *
75
+ * The refresh flow may be triggered by endpoints such as `getAccessToken` or
76
+ * `refreshToken`; this context gives provider hooks access to the triggering
77
+ * request without exposing the full endpoint implementation surface.
78
+ */
79
+ interface OAuthRefreshContext {
80
+ headers?: Headers | undefined;
81
+ request?: Request | undefined;
82
+ }
24
83
  interface OAuthProvider<T extends Record<string, any> = Record<string, any>, O extends Record<string, any> = Partial<ProviderOptions>> {
25
84
  id: LiteralString;
85
+ /**
86
+ * Optional path under the resolved per-request `baseURL` where this
87
+ * provider's OAuth callback handler is mounted. Providers that use the
88
+ * shared `/callback/<id>` route can omit this.
89
+ *
90
+ * Custom paths must start with `/`.
91
+ *
92
+ * Endpoints compose `redirectURI = ctx.context.baseURL + callbackPath` per
93
+ * request, so the provider must not hardcode an origin or `baseURL` here.
94
+ */
95
+ callbackPath?: string | undefined;
26
96
  createAuthorizationURL: (data: {
27
97
  state: string;
28
98
  codeVerifier: string;
@@ -30,6 +100,19 @@ interface OAuthProvider<T extends Record<string, any> = Record<string, any>, O e
30
100
  redirectURI: string;
31
101
  display?: string | undefined;
32
102
  loginHint?: string | undefined;
103
+ /**
104
+ * OIDC nonce generated by the redirect initiator and persisted in OAuth
105
+ * state. Providers that set `requiresIdTokenNonce` must forward this to
106
+ * the authorization URL as the `nonce` parameter.
107
+ */
108
+ idTokenNonce?: string | undefined;
109
+ /**
110
+ * Extra query parameters to append to the authorization URL.
111
+ * Providers forward these to the shared `createAuthorizationURL` helper,
112
+ * which drops any keys present in `RESERVED_AUTHORIZATION_PARAMS`
113
+ * before applying them.
114
+ */
115
+ additionalParams?: Record<string, string> | undefined;
33
116
  }) => Awaitable<URL>;
34
117
  name: string;
35
118
  validateAuthorizationCode: (data: {
@@ -39,6 +122,12 @@ interface OAuthProvider<T extends Record<string, any> = Record<string, any>, O e
39
122
  deviceId?: string | undefined;
40
123
  }) => Promise<OAuth2Tokens | null>;
41
124
  getUserInfo: (token: OAuth2Tokens & {
125
+ /**
126
+ * OIDC nonce recovered from OAuth state. Providers that required an
127
+ * ID-token nonce must pass this to `verifyProviderIdToken` before
128
+ * trusting ID-token claims.
129
+ */
130
+ expectedIdTokenNonce?: string | undefined;
42
131
  /**
43
132
  * The user object from the provider
44
133
  * This is only available for some providers like Apple
@@ -55,23 +144,33 @@ interface OAuthProvider<T extends Record<string, any> = Record<string, any>, O e
55
144
  data: T;
56
145
  } | null>;
57
146
  /**
58
- * Custom function to refresh a token
147
+ * Custom function to refresh a token.
148
+ *
149
+ * Receives request metadata from the endpoint that triggered the refresh.
150
+ * Providers that don't need request-scoped data can ignore the second
151
+ * argument.
59
152
  */
60
- refreshAccessToken?: ((refreshToken: string) => Promise<OAuth2Tokens>) | undefined;
153
+ refreshAccessToken?: ((refreshToken: string, ctx?: OAuthRefreshContext) => Promise<OAuth2Tokens>) | undefined;
61
154
  revokeToken?: ((token: string) => Promise<void>) | undefined;
62
155
  /**
63
- * Verify the id token
64
- * @param token - The id token
65
- * @param nonce - The nonce
66
- * @returns True if the id token is valid, false otherwise
156
+ * Declarative id_token verification config consumed by the shared
157
+ * `verifyProviderIdToken` verifier. Providers set this instead of implementing a boolean
158
+ * verify method, which keeps verification centralized and fail-closed.
67
159
  */
68
- verifyIdToken?: ((token: string, nonce?: string) => Promise<boolean>) | undefined;
160
+ idToken?: OAuthIdTokenConfig | undefined;
69
161
  /**
70
162
  * The expected issuer identifier for this provider (RFC 9207).
71
163
  * When set, the callback handler validates the `iss` query parameter
72
164
  * against this value to prevent authorization server mix-up attacks.
73
165
  */
74
166
  issuer?: string | undefined;
167
+ /**
168
+ * Require shared OAuth redirect routes to bind ID-token verification to an
169
+ * authorization request nonce. When true, routes generate `idTokenNonce`,
170
+ * pass it to `createAuthorizationURL`, persist it in state, and provide it
171
+ * back to `getUserInfo` as `expectedIdTokenNonce`.
172
+ */
173
+ requiresIdTokenNonce?: boolean | undefined;
75
174
  /**
76
175
  * Disable implicit sign up for new users. When set to true for the provider,
77
176
  * sign-in need to be called with with requestSignUp as true to create new users.
@@ -81,6 +180,17 @@ interface OAuthProvider<T extends Record<string, any> = Record<string, any>, O e
81
180
  * Disable sign up for new users.
82
181
  */
83
182
  disableSignUp?: boolean | undefined;
183
+ /**
184
+ * Accept callbacks that arrive without a `state` parameter. When true,
185
+ * the shared OAuth callback handler restarts the flow server-side with
186
+ * fresh `state` and PKCE instead of rejecting the request. Intended for
187
+ * providers that initiate OAuth without RP-side flow kickoff (e.g.
188
+ * Clever). Leave unset for any provider that always initiates from the
189
+ * RP.
190
+ *
191
+ * @default false
192
+ */
193
+ allowIdpInitiated?: boolean | undefined;
84
194
  /**
85
195
  * Options for the provider
86
196
  */
@@ -90,9 +200,10 @@ type ProviderOptions<Profile extends Record<string, any> = any> = {
90
200
  /**
91
201
  * The client ID of your application.
92
202
  *
93
- * This is usually a string but can be any type depending on the provider.
203
+ * Some providers accept multiple platform client IDs. The first entry is the
204
+ * primary client ID used for token endpoint client authentication.
94
205
  */
95
- clientId?: unknown | undefined;
206
+ clientId?: LiteralString | string[] | undefined;
96
207
  /**
97
208
  * The client secret of your application
98
209
  */
@@ -193,6 +304,29 @@ type ProviderOptions<Profile extends Record<string, any> = any> = {
193
304
  * @default false
194
305
  */
195
306
  overrideUserInfoOnSignIn?: boolean | undefined;
307
+ /**
308
+ * Require this provider's email to be verified before a session is created.
309
+ *
310
+ * When the provider reports the email as unverified, the user and account are
311
+ * still created/linked, but no session is issued: the OAuth callback redirects
312
+ * with `?error=email_not_verified` and id-token sign-in returns a `403`
313
+ * `EMAIL_NOT_VERIFIED`. A verification email is (re)sent per the
314
+ * `emailVerification` settings (`sendOnSignUp` / `sendOnSignIn`).
315
+ *
316
+ * The gate checks the local user's verification state, not the provider's
317
+ * claim on each request: a user already verified through another method (or a
318
+ * prior verified sign-in) keeps access even if the provider later reports the
319
+ * email as unverified.
320
+ *
321
+ * This is opt-in per provider and is independent of
322
+ * `emailAndPassword.requireEmailVerification`; enabling that does not gate
323
+ * social sign-in. Only enable it for providers that report a trustworthy
324
+ * `email_verified` signal: several providers always report the email as
325
+ * unverified, which would block every sign-in.
326
+ *
327
+ * @default false
328
+ */
329
+ requireEmailVerification?: boolean | undefined;
196
330
  };
197
331
  //#endregion
198
- export { OAuth2Tokens, OAuth2UserInfo, OAuthProvider, ProviderOptions };
332
+ export { OAuth2Tokens, OAuth2UserInfo, OAuthIdTokenConfig, OAuthProvider, OAuthRefreshContext, ProviderOptions };