@better-auth/core 1.6.19 → 1.6.21
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.
- package/dist/context/global.mjs +1 -1
- package/dist/db/adapter/factory.mjs +1 -0
- package/dist/db/adapter/index.d.mts +8 -2
- package/dist/db/get-tables.mjs +2 -1
- package/dist/error/index.d.mts +7 -0
- package/dist/instrumentation/tracer.mjs +1 -1
- package/dist/social-providers/google.d.mts +24 -3
- package/dist/social-providers/google.mjs +41 -18
- package/dist/social-providers/index.d.mts +2 -2
- package/dist/social-providers/index.mjs +2 -2
- package/dist/social-providers/paypal.d.mts +1 -0
- package/dist/social-providers/paypal.mjs +15 -1
- package/dist/types/init-options.d.mts +16 -1
- package/dist/utils/ip.d.mts +23 -1
- package/dist/utils/ip.mjs +115 -1
- package/package.json +3 -3
- package/src/db/adapter/factory.ts +5 -0
- package/src/db/adapter/index.ts +8 -2
- package/src/db/get-tables.ts +7 -1
- package/src/error/index.ts +9 -0
- package/src/social-providers/google.ts +71 -38
- package/src/social-providers/paypal.ts +22 -1
- package/src/types/init-options.ts +16 -1
- package/src/utils/ip.ts +185 -0
package/dist/context/global.mjs
CHANGED
|
@@ -459,6 +459,7 @@ const createAdapterFactory = ({ adapter: customAdapter, config: cfg }) => (optio
|
|
|
459
459
|
where: unsafeWhere,
|
|
460
460
|
action: "update"
|
|
461
461
|
});
|
|
462
|
+
if (where.length === 0) return null;
|
|
462
463
|
debugLog({ method: "update" }, `${formatTransactionId(thisTransactionId)} ${formatStep(1, 4)}`, `${formatMethod("update")} ${formatAction("Unsafe Input")}:`, {
|
|
463
464
|
model,
|
|
464
465
|
data: unsafeData
|
|
@@ -396,8 +396,14 @@ type DBAdapter<Options extends BetterAuthOptions = BetterAuthOptions> = {
|
|
|
396
396
|
where?: Where[] | undefined;
|
|
397
397
|
}) => Promise<number>;
|
|
398
398
|
/**
|
|
399
|
-
*
|
|
400
|
-
*
|
|
399
|
+
* Update a single row matching the where clause.
|
|
400
|
+
*
|
|
401
|
+
* Returns the updated row, or `null` when no row matched. Empty `where`
|
|
402
|
+
* clauses return `null`; use `updateMany` for intentional bulk updates.
|
|
403
|
+
*
|
|
404
|
+
* This is not the race-safe primitive for guarded state transitions. Use
|
|
405
|
+
* `incrementOne` when the predicate is both selector and guard, and use
|
|
406
|
+
* `consumeOne` for single-use destructive reads.
|
|
401
407
|
*/
|
|
402
408
|
update: <T>(data: {
|
|
403
409
|
model: string;
|
package/dist/db/get-tables.mjs
CHANGED
|
@@ -8,7 +8,8 @@ const getAuthTables = (options) => {
|
|
|
8
8
|
...acc[key]?.fields,
|
|
9
9
|
...value.fields
|
|
10
10
|
},
|
|
11
|
-
modelName: value.modelName || key
|
|
11
|
+
modelName: value.modelName || key,
|
|
12
|
+
disableMigrations: value.disableMigration ?? acc[key]?.disableMigrations
|
|
12
13
|
};
|
|
13
14
|
return acc;
|
|
14
15
|
}, {});
|
package/dist/error/index.d.mts
CHANGED
|
@@ -7,7 +7,14 @@ declare class BetterAuthError extends Error {
|
|
|
7
7
|
cause?: unknown | undefined;
|
|
8
8
|
});
|
|
9
9
|
}
|
|
10
|
+
type BaseAPIErrorInstance = InstanceType<typeof APIError$1>;
|
|
10
11
|
declare class APIError extends APIError$1 {
|
|
12
|
+
status: BaseAPIErrorInstance["status"];
|
|
13
|
+
body: BaseAPIErrorInstance["body"];
|
|
14
|
+
headers: BaseAPIErrorInstance["headers"];
|
|
15
|
+
statusCode: BaseAPIErrorInstance["statusCode"];
|
|
16
|
+
message: string;
|
|
17
|
+
errorStack: BaseAPIErrorInstance["errorStack"];
|
|
11
18
|
constructor(...args: ConstructorParameters<typeof APIError$1>);
|
|
12
19
|
static fromStatus(status: ConstructorParameters<typeof APIError$1>[0], body?: ConstructorParameters<typeof APIError$1>[1]): APIError;
|
|
13
20
|
static from(status: ConstructorParameters<typeof APIError$1>[0], error: {
|
|
@@ -2,7 +2,7 @@ import { ATTR_HTTP_RESPONSE_STATUS_CODE } from "./attributes.mjs";
|
|
|
2
2
|
import { getOpenTelemetryAPI } from "./api.mjs";
|
|
3
3
|
//#region src/instrumentation/tracer.ts
|
|
4
4
|
const INSTRUMENTATION_SCOPE = "better-auth";
|
|
5
|
-
const INSTRUMENTATION_VERSION = "1.6.
|
|
5
|
+
const INSTRUMENTATION_VERSION = "1.6.21";
|
|
6
6
|
/**
|
|
7
7
|
* Better-auth uses `throw ctx.redirect(url)` for flow control (e.g. OAuth
|
|
8
8
|
* callbacks). These are APIErrors with 3xx status codes and should not be
|
|
@@ -1,4 +1,6 @@
|
|
|
1
1
|
import { OAuth2Tokens, ProviderOptions } from "../oauth2/oauth-provider.mjs";
|
|
2
|
+
import { JWTPayload } from "jose";
|
|
3
|
+
|
|
2
4
|
//#region src/social-providers/google.d.ts
|
|
3
5
|
interface GoogleProfile {
|
|
4
6
|
aud: string;
|
|
@@ -41,11 +43,30 @@ interface GoogleOptions extends ProviderOptions<GoogleProfile> {
|
|
|
41
43
|
*
|
|
42
44
|
* This is sent to Google as the `hd` authorization hint and, when set, is
|
|
43
45
|
* also enforced against the `hd` claim of the returned id token/profile.
|
|
44
|
-
*
|
|
45
|
-
*
|
|
46
|
+
* Set `hd: "*"` to require any Workspace hosted-domain claim. Sign-in is
|
|
47
|
+
* rejected when the claim is missing or does not satisfy this restriction.
|
|
46
48
|
*/
|
|
47
49
|
hd?: string | undefined;
|
|
48
50
|
}
|
|
51
|
+
interface VerifyGoogleIdTokenOptions {
|
|
52
|
+
token: string;
|
|
53
|
+
audience: string | string[];
|
|
54
|
+
nonce?: string | undefined;
|
|
55
|
+
}
|
|
56
|
+
/**
|
|
57
|
+
* Verifies a Google ID token against Google's issuer, audience, signature,
|
|
58
|
+
* expiry, and maximum token age.
|
|
59
|
+
*/
|
|
60
|
+
declare const verifyGoogleIdToken: ({
|
|
61
|
+
token,
|
|
62
|
+
audience,
|
|
63
|
+
nonce
|
|
64
|
+
}: VerifyGoogleIdTokenOptions) => Promise<JWTPayload | null>;
|
|
65
|
+
/**
|
|
66
|
+
* Checks whether Google's verified `hd` claim satisfies the configured hosted
|
|
67
|
+
* domain restriction. `hd: "*"` accepts any Google Workspace hosted domain.
|
|
68
|
+
*/
|
|
69
|
+
declare const isGoogleHostedDomainAllowed: (configuredHostedDomain: string | undefined, tokenHostedDomain: unknown) => boolean;
|
|
49
70
|
declare const google: (options: GoogleOptions) => {
|
|
50
71
|
id: "google";
|
|
51
72
|
name: string;
|
|
@@ -99,4 +120,4 @@ declare const google: (options: GoogleOptions) => {
|
|
|
99
120
|
};
|
|
100
121
|
declare const getGooglePublicKey: (kid: string) => Promise<Uint8Array<ArrayBufferLike> | CryptoKey>;
|
|
101
122
|
//#endregion
|
|
102
|
-
export { GoogleOptions, GoogleProfile, getGooglePublicKey, google };
|
|
123
|
+
export { GoogleOptions, GoogleProfile, VerifyGoogleIdTokenOptions, getGooglePublicKey, google, isGoogleHostedDomainAllowed, verifyGoogleIdToken };
|
|
@@ -7,6 +7,37 @@ import { validateAuthorizationCode } from "../oauth2/validate-authorization-code
|
|
|
7
7
|
import { betterFetch } from "@better-fetch/fetch";
|
|
8
8
|
import { decodeJwt, decodeProtectedHeader, importJWK, jwtVerify } from "jose";
|
|
9
9
|
//#region src/social-providers/google.ts
|
|
10
|
+
const GOOGLE_ID_TOKEN_MAX_AGE = "1h";
|
|
11
|
+
/**
|
|
12
|
+
* Verifies a Google ID token against Google's issuer, audience, signature,
|
|
13
|
+
* expiry, and maximum token age.
|
|
14
|
+
*/
|
|
15
|
+
const verifyGoogleIdToken = async ({ token, audience, nonce }) => {
|
|
16
|
+
try {
|
|
17
|
+
const { kid, alg: jwtAlg } = decodeProtectedHeader(token);
|
|
18
|
+
if (!kid || !jwtAlg) return null;
|
|
19
|
+
const { payload: jwtClaims } = await jwtVerify(token, await getGooglePublicKey(kid), {
|
|
20
|
+
algorithms: [jwtAlg],
|
|
21
|
+
issuer: ["https://accounts.google.com", "accounts.google.com"],
|
|
22
|
+
audience,
|
|
23
|
+
maxTokenAge: GOOGLE_ID_TOKEN_MAX_AGE
|
|
24
|
+
});
|
|
25
|
+
if (nonce && jwtClaims.nonce !== nonce) return null;
|
|
26
|
+
return jwtClaims;
|
|
27
|
+
} catch {
|
|
28
|
+
return null;
|
|
29
|
+
}
|
|
30
|
+
};
|
|
31
|
+
/**
|
|
32
|
+
* Checks whether Google's verified `hd` claim satisfies the configured hosted
|
|
33
|
+
* domain restriction. `hd: "*"` accepts any Google Workspace hosted domain.
|
|
34
|
+
*/
|
|
35
|
+
const isGoogleHostedDomainAllowed = (configuredHostedDomain, tokenHostedDomain) => {
|
|
36
|
+
if (!configuredHostedDomain) return true;
|
|
37
|
+
if (typeof tokenHostedDomain !== "string" || !tokenHostedDomain) return false;
|
|
38
|
+
if (configuredHostedDomain === "*") return true;
|
|
39
|
+
return tokenHostedDomain === configuredHostedDomain;
|
|
40
|
+
};
|
|
10
41
|
const google = (options) => {
|
|
11
42
|
return {
|
|
12
43
|
id: "google",
|
|
@@ -63,28 +94,20 @@ const google = (options) => {
|
|
|
63
94
|
async verifyIdToken(token, nonce) {
|
|
64
95
|
if (options.disableIdTokenSignIn) return false;
|
|
65
96
|
if (options.verifyIdToken) return options.verifyIdToken(token, nonce);
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
maxTokenAge: "1h"
|
|
74
|
-
});
|
|
75
|
-
if (nonce && jwtClaims.nonce !== nonce) return false;
|
|
76
|
-
if (options.hd && jwtClaims.hd !== options.hd) return false;
|
|
77
|
-
return true;
|
|
78
|
-
} catch {
|
|
79
|
-
return false;
|
|
80
|
-
}
|
|
97
|
+
const jwtClaims = await verifyGoogleIdToken({
|
|
98
|
+
token,
|
|
99
|
+
audience: options.clientId,
|
|
100
|
+
nonce
|
|
101
|
+
});
|
|
102
|
+
if (!jwtClaims) return false;
|
|
103
|
+
return isGoogleHostedDomainAllowed(options.hd, jwtClaims.hd);
|
|
81
104
|
},
|
|
82
105
|
async getUserInfo(token) {
|
|
83
106
|
if (options.getUserInfo) return options.getUserInfo(token);
|
|
84
107
|
if (!token.idToken) return null;
|
|
85
108
|
const user = decodeJwt(token.idToken);
|
|
86
|
-
if (options.hd
|
|
87
|
-
logger.error(`Google sign-in rejected: id token hosted domain (hd) "${user.hd ?? "<missing>"}" does not
|
|
109
|
+
if (!isGoogleHostedDomainAllowed(options.hd, user.hd)) {
|
|
110
|
+
logger.error(`Google sign-in rejected: id token hosted domain (hd) "${user.hd ?? "<missing>"}" does not satisfy the configured "hd" option "${options.hd}".`);
|
|
88
111
|
return null;
|
|
89
112
|
}
|
|
90
113
|
const userMap = await options.mapProfileToUser?.(user);
|
|
@@ -111,4 +134,4 @@ const getGooglePublicKey = async (kid) => {
|
|
|
111
134
|
return await importJWK(jwk, jwk.alg);
|
|
112
135
|
};
|
|
113
136
|
//#endregion
|
|
114
|
-
export { getGooglePublicKey, google };
|
|
137
|
+
export { getGooglePublicKey, google, isGoogleHostedDomainAllowed, verifyGoogleIdToken };
|
|
@@ -6,7 +6,7 @@ import { FacebookOptions, FacebookProfile, facebook } from "./facebook.mjs";
|
|
|
6
6
|
import { FigmaOptions, FigmaProfile, figma } from "./figma.mjs";
|
|
7
7
|
import { GithubOptions, GithubProfile, github } from "./github.mjs";
|
|
8
8
|
import { MicrosoftEntraIDProfile, MicrosoftOptions, getMicrosoftPublicKey, microsoft } from "./microsoft-entra-id.mjs";
|
|
9
|
-
import { GoogleOptions, GoogleProfile, getGooglePublicKey, google } from "./google.mjs";
|
|
9
|
+
import { GoogleOptions, GoogleProfile, VerifyGoogleIdTokenOptions, getGooglePublicKey, google, isGoogleHostedDomainAllowed, verifyGoogleIdToken } from "./google.mjs";
|
|
10
10
|
import { HuggingFaceOptions, HuggingFaceProfile, huggingface } from "./huggingface.mjs";
|
|
11
11
|
import { SlackOptions, SlackProfile, slack } from "./slack.mjs";
|
|
12
12
|
import { SpotifyOptions, SpotifyProfile, spotify } from "./spotify.mjs";
|
|
@@ -1831,4 +1831,4 @@ type SocialProviders = { [K in SocialProviderList[number]]?: AwaitableFunction<P
|
|
|
1831
1831
|
}> };
|
|
1832
1832
|
type SocialProviderList = typeof socialProviderList;
|
|
1833
1833
|
//#endregion
|
|
1834
|
-
export { AccountStatus, AppleNonConformUser, AppleOptions, AppleProfile, AtlassianOptions, AtlassianProfile, CognitoOptions, CognitoProfile, DiscordOptions, DiscordProfile, DropboxOptions, DropboxProfile, FacebookOptions, FacebookProfile, FigmaOptions, FigmaProfile, GithubOptions, GithubProfile, GitlabOptions, GitlabProfile, GoogleOptions, GoogleProfile, HuggingFaceOptions, HuggingFaceProfile, KakaoOptions, KakaoProfile, KickOptions, KickProfile, LineIdTokenPayload, LineOptions, LineUserInfo, LinearOptions, LinearProfile, LinearUser, LinkedInOptions, LinkedInProfile, LoginType, MicrosoftEntraIDProfile, MicrosoftOptions, NaverOptions, NaverProfile, NotionOptions, NotionProfile, PayPalOptions, PayPalProfile, PayPalTokenResponse, PaybinOptions, PaybinProfile, PhoneNumber, PolarOptions, PolarProfile, PronounOption, RailwayOptions, RailwayProfile, RedditOptions, RedditProfile, RobloxOptions, RobloxProfile, SalesforceOptions, SalesforceProfile, SlackOptions, SlackProfile, SocialProvider, SocialProviderList, SocialProviderListEnum, SocialProviders, SpotifyOptions, SpotifyProfile, TiktokOptions, TiktokProfile, TwitchOptions, TwitchProfile, TwitterOption, TwitterProfile, VercelOptions, VercelProfile, VkOption, VkProfile, WeChatOptions, WeChatProfile, ZoomOptions, ZoomProfile, apple, atlassian, cognito, discord, dropbox, facebook, figma, getApplePublicKey, getCognitoPublicKey, getGooglePublicKey, getMicrosoftPublicKey, getPayPalPublicKey, github, gitlab, google, huggingface, kakao, kick, line, linear, linkedin, microsoft, naver, notion, paybin, paypal, polar, railway, reddit, roblox, salesforce, slack, socialProviderList, socialProviders, spotify, tiktok, twitch, twitter, vercel, vk, wechat, zoom };
|
|
1834
|
+
export { AccountStatus, AppleNonConformUser, AppleOptions, AppleProfile, AtlassianOptions, AtlassianProfile, CognitoOptions, CognitoProfile, DiscordOptions, DiscordProfile, DropboxOptions, DropboxProfile, FacebookOptions, FacebookProfile, FigmaOptions, FigmaProfile, GithubOptions, GithubProfile, GitlabOptions, GitlabProfile, GoogleOptions, GoogleProfile, HuggingFaceOptions, HuggingFaceProfile, KakaoOptions, KakaoProfile, KickOptions, KickProfile, LineIdTokenPayload, LineOptions, LineUserInfo, LinearOptions, LinearProfile, LinearUser, LinkedInOptions, LinkedInProfile, LoginType, MicrosoftEntraIDProfile, MicrosoftOptions, NaverOptions, NaverProfile, NotionOptions, NotionProfile, PayPalOptions, PayPalProfile, PayPalTokenResponse, PaybinOptions, PaybinProfile, PhoneNumber, PolarOptions, PolarProfile, PronounOption, RailwayOptions, RailwayProfile, RedditOptions, RedditProfile, RobloxOptions, RobloxProfile, SalesforceOptions, SalesforceProfile, SlackOptions, SlackProfile, SocialProvider, SocialProviderList, SocialProviderListEnum, SocialProviders, SpotifyOptions, SpotifyProfile, TiktokOptions, TiktokProfile, TwitchOptions, TwitchProfile, TwitterOption, TwitterProfile, VercelOptions, VercelProfile, VerifyGoogleIdTokenOptions, VkOption, VkProfile, WeChatOptions, WeChatProfile, ZoomOptions, ZoomProfile, apple, atlassian, cognito, discord, dropbox, facebook, figma, getApplePublicKey, getCognitoPublicKey, getGooglePublicKey, getMicrosoftPublicKey, getPayPalPublicKey, github, gitlab, google, huggingface, isGoogleHostedDomainAllowed, kakao, kick, line, linear, linkedin, microsoft, naver, notion, paybin, paypal, polar, railway, reddit, roblox, salesforce, slack, socialProviderList, socialProviders, spotify, tiktok, twitch, twitter, vercel, verifyGoogleIdToken, vk, wechat, zoom };
|
|
@@ -7,7 +7,7 @@ import { facebook } from "./facebook.mjs";
|
|
|
7
7
|
import { figma } from "./figma.mjs";
|
|
8
8
|
import { github } from "./github.mjs";
|
|
9
9
|
import { gitlab } from "./gitlab.mjs";
|
|
10
|
-
import { getGooglePublicKey, google } from "./google.mjs";
|
|
10
|
+
import { getGooglePublicKey, google, isGoogleHostedDomainAllowed, verifyGoogleIdToken } from "./google.mjs";
|
|
11
11
|
import { huggingface } from "./huggingface.mjs";
|
|
12
12
|
import { kakao } from "./kakao.mjs";
|
|
13
13
|
import { kick } from "./kick.mjs";
|
|
@@ -75,4 +75,4 @@ const socialProviders = {
|
|
|
75
75
|
const socialProviderList = Object.keys(socialProviders);
|
|
76
76
|
const SocialProviderListEnum = z.enum(socialProviderList).or(z.string());
|
|
77
77
|
//#endregion
|
|
78
|
-
export { SocialProviderListEnum, apple, atlassian, cognito, discord, dropbox, facebook, figma, getApplePublicKey, getCognitoPublicKey, getGooglePublicKey, getMicrosoftPublicKey, getPayPalPublicKey, github, gitlab, google, huggingface, kakao, kick, line, linear, linkedin, microsoft, naver, notion, paybin, paypal, polar, railway, reddit, roblox, salesforce, slack, socialProviderList, socialProviders, spotify, tiktok, twitch, twitter, vercel, vk, wechat, zoom };
|
|
78
|
+
export { SocialProviderListEnum, apple, atlassian, cognito, discord, dropbox, facebook, figma, getApplePublicKey, getCognitoPublicKey, getGooglePublicKey, getMicrosoftPublicKey, getPayPalPublicKey, github, gitlab, google, huggingface, isGoogleHostedDomainAllowed, kakao, kick, line, linear, linkedin, microsoft, naver, notion, paybin, paypal, polar, railway, reddit, roblox, salesforce, slack, socialProviderList, socialProviders, spotify, tiktok, twitch, twitter, vercel, verifyGoogleIdToken, vk, wechat, zoom };
|
|
@@ -3,7 +3,7 @@ import { logger } from "../env/logger.mjs";
|
|
|
3
3
|
import { createAuthorizationURL } from "../oauth2/create-authorization-url.mjs";
|
|
4
4
|
import { base64 } from "@better-auth/utils/base64";
|
|
5
5
|
import { betterFetch } from "@better-fetch/fetch";
|
|
6
|
-
import { decodeProtectedHeader, importJWK, jwtVerify } from "jose";
|
|
6
|
+
import { decodeJwt, decodeProtectedHeader, importJWK, jwtVerify } from "jose";
|
|
7
7
|
//#region src/social-providers/paypal.ts
|
|
8
8
|
/**
|
|
9
9
|
* ID token signing algorithms advertised by PayPal's OpenID configuration.
|
|
@@ -143,6 +143,20 @@ const paypal = (options) => {
|
|
|
143
143
|
return null;
|
|
144
144
|
}
|
|
145
145
|
const userInfo = response.data;
|
|
146
|
+
if (token.idToken) {
|
|
147
|
+
let idTokenSubject;
|
|
148
|
+
try {
|
|
149
|
+
idTokenSubject = decodeJwt(token.idToken).sub;
|
|
150
|
+
} catch (error) {
|
|
151
|
+
logger.error("Failed to decode PayPal ID token:", error);
|
|
152
|
+
return null;
|
|
153
|
+
}
|
|
154
|
+
const userInfoSubject = userInfo.sub ?? userInfo.user_id;
|
|
155
|
+
if (!idTokenSubject || userInfoSubject !== idTokenSubject) {
|
|
156
|
+
logger.error("PayPal user info subject does not match ID token subject");
|
|
157
|
+
return null;
|
|
158
|
+
}
|
|
159
|
+
}
|
|
146
160
|
const userMap = await options.mapProfileToUser?.(userInfo);
|
|
147
161
|
return {
|
|
148
162
|
user: {
|
|
@@ -176,7 +176,7 @@ type BetterAuthAdvancedOptions = {
|
|
|
176
176
|
* @example ["x-client-ip", "x-forwarded-for", "cf-connecting-ip"]
|
|
177
177
|
*
|
|
178
178
|
* @default
|
|
179
|
-
* @link https://github.com/better-auth/better-auth/blob/main/packages/
|
|
179
|
+
* @link https://github.com/better-auth/better-auth/blob/main/packages/core/src/utils/ip.ts
|
|
180
180
|
*/
|
|
181
181
|
ipAddressHeaders?: string[];
|
|
182
182
|
/**
|
|
@@ -193,6 +193,21 @@ type BetterAuthAdvancedOptions = {
|
|
|
193
193
|
* @default 64
|
|
194
194
|
*/
|
|
195
195
|
ipv6Subnet?: number;
|
|
196
|
+
/**
|
|
197
|
+
* Trusted reverse-proxy IPs or CIDR ranges. When set, a forwarded IP
|
|
198
|
+
* chain is walked right to left, trusted hops are skipped, and the
|
|
199
|
+
* first untrusted address is the client IP. Unset trusts only
|
|
200
|
+
* single-value IP headers. Use the actual address or subnet of your
|
|
201
|
+
* proxies, not a broad private range that also covers clients.
|
|
202
|
+
*
|
|
203
|
+
* This only interprets the forwarded header chain and cannot verify
|
|
204
|
+
* the direct sender. It is safe only when your origin is reachable
|
|
205
|
+
* through these proxies and clients cannot set forwarded headers
|
|
206
|
+
* directly.
|
|
207
|
+
*
|
|
208
|
+
* @example ["192.0.2.10", "10.0.0.0/24"]
|
|
209
|
+
*/
|
|
210
|
+
trustedProxies?: string[];
|
|
196
211
|
} | undefined;
|
|
197
212
|
/**
|
|
198
213
|
* Force cookies to always use the `Secure` attribute. By default,
|
package/dist/utils/ip.d.mts
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { BetterAuthOptions } from "../types/init-options.mjs";
|
|
1
2
|
//#region src/utils/ip.d.ts
|
|
2
3
|
/**
|
|
3
4
|
* Normalizes an IP address for consistent rate limiting.
|
|
@@ -42,6 +43,27 @@ declare function isValidIP(ip: string): boolean;
|
|
|
42
43
|
* // -> "2001:0db8:0000:0000:0000:0000:0000:0000" (subnet /64)
|
|
43
44
|
*/
|
|
44
45
|
declare function normalizeIP(ip: string, options?: NormalizeIPOptions): string;
|
|
46
|
+
/**
|
|
47
|
+
* Trusted-proxy entries that are not a valid IP address or CIDR range.
|
|
48
|
+
*/
|
|
49
|
+
declare function findInvalidTrustedProxies(entries: string[]): string[];
|
|
50
|
+
/**
|
|
51
|
+
* Resolves the client IP from a forwarded header. The leftmost token is spoofable,
|
|
52
|
+
* so with `trustedProxies` the chain is stripped from the right to the first
|
|
53
|
+
* untrusted hop. Otherwise only a single-value header is trusted. Returns `null`
|
|
54
|
+
* when no trustworthy client IP can be resolved.
|
|
55
|
+
*/
|
|
56
|
+
declare function getIPFromHeader(value: string, options?: {
|
|
57
|
+
ipv6Subnet?: number;
|
|
58
|
+
trustedProxies?: string[];
|
|
59
|
+
}): string | null;
|
|
60
|
+
/**
|
|
61
|
+
* Resolves the client IP for a request from the configured IP headers.
|
|
62
|
+
* Honors `disableIpTracking`, walks `ipAddressHeaders` in order (default
|
|
63
|
+
* `x-forwarded-for`), and falls back to localhost in development and test.
|
|
64
|
+
* Returns `null` when tracking is disabled or no trustworthy IP can be resolved.
|
|
65
|
+
*/
|
|
66
|
+
declare function getIp(req: Request | Headers, options: BetterAuthOptions): string | null;
|
|
45
67
|
/**
|
|
46
68
|
* Creates a rate limit key from IP and path
|
|
47
69
|
* Uses a separator to prevent collision attacks
|
|
@@ -52,4 +74,4 @@ declare function normalizeIP(ip: string, options?: NormalizeIPOptions): string;
|
|
|
52
74
|
*/
|
|
53
75
|
declare function createRateLimitKey(ip: string, path: string): string;
|
|
54
76
|
//#endregion
|
|
55
|
-
export { createRateLimitKey, isValidIP, normalizeIP };
|
|
77
|
+
export { createRateLimitKey, findInvalidTrustedProxies, getIPFromHeader, getIp, isValidIP, normalizeIP };
|
package/dist/utils/ip.mjs
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { isDevelopment, isTest } from "../env/env-impl.mjs";
|
|
1
2
|
import * as z from "zod";
|
|
2
3
|
//#region src/utils/ip.ts
|
|
3
4
|
/**
|
|
@@ -102,6 +103,119 @@ function normalizeIP(ip, options = {}) {
|
|
|
102
103
|
return normalizeIPv6(ip, options.ipv6Subnet ?? 64);
|
|
103
104
|
}
|
|
104
105
|
/**
|
|
106
|
+
* Raw bytes of an IP for CIDR comparison. Returns `null` for an invalid IP.
|
|
107
|
+
*/
|
|
108
|
+
function ipToBytes(ip) {
|
|
109
|
+
if (z.ipv4().safeParse(ip).success) return Uint8Array.from(ip.split(".").map((octet) => Number(octet)));
|
|
110
|
+
if (!isIPv6(ip)) return null;
|
|
111
|
+
const mapped = extractIPv4FromMapped(ip);
|
|
112
|
+
if (mapped) return Uint8Array.from(mapped.split(".").map((octet) => Number(octet)));
|
|
113
|
+
const groups = expandIPv6(ip);
|
|
114
|
+
const bytes = new Uint8Array(16);
|
|
115
|
+
for (let i = 0; i < 8; i++) {
|
|
116
|
+
const group = Number.parseInt(groups[i] ?? "0", 16);
|
|
117
|
+
bytes[i * 2] = group >> 8 & 255;
|
|
118
|
+
bytes[i * 2 + 1] = group & 255;
|
|
119
|
+
}
|
|
120
|
+
return bytes;
|
|
121
|
+
}
|
|
122
|
+
const CIDR_PREFIX_PATTERN = /^\d+$/;
|
|
123
|
+
/**
|
|
124
|
+
* Parses an IP or `IP/prefix` string into network bytes and a prefix length.
|
|
125
|
+
* The prefix must be digits only and within the address family. `null` if the
|
|
126
|
+
* value is not a valid IP or CIDR range, which keeps a malformed entry from
|
|
127
|
+
* silently behaving like a non-match.
|
|
128
|
+
*/
|
|
129
|
+
function parseCIDR(value) {
|
|
130
|
+
const slash = value.lastIndexOf("/");
|
|
131
|
+
const bytes = ipToBytes(slash === -1 ? value : value.slice(0, slash));
|
|
132
|
+
if (!bytes) return null;
|
|
133
|
+
const maxBits = bytes.length * 8;
|
|
134
|
+
if (slash === -1) return {
|
|
135
|
+
bytes,
|
|
136
|
+
prefix: maxBits
|
|
137
|
+
};
|
|
138
|
+
const prefixPart = value.slice(slash + 1);
|
|
139
|
+
if (!CIDR_PREFIX_PATTERN.test(prefixPart)) return null;
|
|
140
|
+
const prefix = Number(prefixPart);
|
|
141
|
+
return prefix <= maxBits ? {
|
|
142
|
+
bytes,
|
|
143
|
+
prefix
|
|
144
|
+
} : null;
|
|
145
|
+
}
|
|
146
|
+
/**
|
|
147
|
+
* Whether `ipBytes` falls inside an already-parsed CIDR network.
|
|
148
|
+
*/
|
|
149
|
+
function matchesCIDR(ipBytes, net) {
|
|
150
|
+
if (ipBytes.length !== net.bytes.length) return false;
|
|
151
|
+
let bitsRemaining = net.prefix;
|
|
152
|
+
for (let i = 0; i < ipBytes.length && bitsRemaining > 0; i++) {
|
|
153
|
+
const take = bitsRemaining >= 8 ? 8 : bitsRemaining;
|
|
154
|
+
const mask = take === 8 ? 255 : 255 << 8 - take & 255;
|
|
155
|
+
if (((ipBytes[i] ?? 0) & mask) !== ((net.bytes[i] ?? 0) & mask)) return false;
|
|
156
|
+
bitsRemaining -= 8;
|
|
157
|
+
}
|
|
158
|
+
return true;
|
|
159
|
+
}
|
|
160
|
+
/**
|
|
161
|
+
* Trusted-proxy entries that are not a valid IP address or CIDR range.
|
|
162
|
+
*/
|
|
163
|
+
function findInvalidTrustedProxies(entries) {
|
|
164
|
+
return entries.filter((entry) => parseCIDR(entry) === null);
|
|
165
|
+
}
|
|
166
|
+
/**
|
|
167
|
+
* Resolves the client IP from a forwarded header. The leftmost token is spoofable,
|
|
168
|
+
* so with `trustedProxies` the chain is stripped from the right to the first
|
|
169
|
+
* untrusted hop. Otherwise only a single-value header is trusted. Returns `null`
|
|
170
|
+
* when no trustworthy client IP can be resolved.
|
|
171
|
+
*/
|
|
172
|
+
function getIPFromHeader(value, options = {}) {
|
|
173
|
+
const forwardedIps = value.split(",").map((ip) => ip.trim()).filter(Boolean);
|
|
174
|
+
if (forwardedIps.length === 0) return null;
|
|
175
|
+
const trustedProxies = (options.trustedProxies ?? []).map(parseCIDR).filter((proxy) => {
|
|
176
|
+
return proxy !== null;
|
|
177
|
+
});
|
|
178
|
+
if (trustedProxies.length > 0) {
|
|
179
|
+
for (let i = forwardedIps.length - 1; i >= 0; i--) {
|
|
180
|
+
const ip = forwardedIps[i];
|
|
181
|
+
const ipBytes = ip ? ipToBytes(ip) : null;
|
|
182
|
+
if (!ip || !ipBytes) return null;
|
|
183
|
+
if (trustedProxies.some((proxy) => matchesCIDR(ipBytes, proxy))) continue;
|
|
184
|
+
return normalizeIP(ip, { ipv6Subnet: options.ipv6Subnet });
|
|
185
|
+
}
|
|
186
|
+
return null;
|
|
187
|
+
}
|
|
188
|
+
if (forwardedIps.length !== 1) return null;
|
|
189
|
+
const selectedIp = forwardedIps[0];
|
|
190
|
+
if (!selectedIp || !isValidIP(selectedIp)) return null;
|
|
191
|
+
return normalizeIP(selectedIp, { ipv6Subnet: options.ipv6Subnet });
|
|
192
|
+
}
|
|
193
|
+
const LOCALHOST_IP = "127.0.0.1";
|
|
194
|
+
const DEFAULT_IP_HEADERS = ["x-forwarded-for"];
|
|
195
|
+
/**
|
|
196
|
+
* Resolves the client IP for a request from the configured IP headers.
|
|
197
|
+
* Honors `disableIpTracking`, walks `ipAddressHeaders` in order (default
|
|
198
|
+
* `x-forwarded-for`), and falls back to localhost in development and test.
|
|
199
|
+
* Returns `null` when tracking is disabled or no trustworthy IP can be resolved.
|
|
200
|
+
*/
|
|
201
|
+
function getIp(req, options) {
|
|
202
|
+
if (options.advanced?.ipAddress?.disableIpTracking) return null;
|
|
203
|
+
const headers = "headers" in req ? req.headers : req;
|
|
204
|
+
const ipHeaders = options.advanced?.ipAddress?.ipAddressHeaders || DEFAULT_IP_HEADERS;
|
|
205
|
+
for (const key of ipHeaders) {
|
|
206
|
+
const value = "get" in headers ? headers.get(key) : headers[key];
|
|
207
|
+
if (typeof value === "string") {
|
|
208
|
+
const ip = getIPFromHeader(value, {
|
|
209
|
+
ipv6Subnet: options.advanced?.ipAddress?.ipv6Subnet,
|
|
210
|
+
trustedProxies: options.advanced?.ipAddress?.trustedProxies
|
|
211
|
+
});
|
|
212
|
+
if (ip) return ip;
|
|
213
|
+
}
|
|
214
|
+
}
|
|
215
|
+
if (isTest() || isDevelopment()) return LOCALHOST_IP;
|
|
216
|
+
return null;
|
|
217
|
+
}
|
|
218
|
+
/**
|
|
105
219
|
* Creates a rate limit key from IP and path
|
|
106
220
|
* Uses a separator to prevent collision attacks
|
|
107
221
|
*
|
|
@@ -113,4 +227,4 @@ function createRateLimitKey(ip, path) {
|
|
|
113
227
|
return `${ip}|${path}`;
|
|
114
228
|
}
|
|
115
229
|
//#endregion
|
|
116
|
-
export { createRateLimitKey, isValidIP, normalizeIP };
|
|
230
|
+
export { createRateLimitKey, findInvalidTrustedProxies, getIPFromHeader, getIp, isValidIP, normalizeIP };
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@better-auth/core",
|
|
3
|
-
"version": "1.6.
|
|
3
|
+
"version": "1.6.21",
|
|
4
4
|
"description": "The most comprehensive authentication framework for TypeScript.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"license": "MIT",
|
|
@@ -157,7 +157,7 @@
|
|
|
157
157
|
"@opentelemetry/api": "^1.9.0",
|
|
158
158
|
"@opentelemetry/sdk-trace-base": "^1.30.0",
|
|
159
159
|
"@opentelemetry/sdk-trace-node": "^1.30.0",
|
|
160
|
-
"better-call": "1.3.
|
|
160
|
+
"better-call": "1.3.7",
|
|
161
161
|
"@cloudflare/workers-types": "^4.20250121.0",
|
|
162
162
|
"jose": "^6.1.3",
|
|
163
163
|
"kysely": "^0.28.17 || ^0.29.0",
|
|
@@ -168,7 +168,7 @@
|
|
|
168
168
|
"@better-auth/utils": "0.4.2",
|
|
169
169
|
"@better-fetch/fetch": "1.3.1",
|
|
170
170
|
"@opentelemetry/api": "^1.9.0",
|
|
171
|
-
"better-call": "1.3.
|
|
171
|
+
"better-call": "1.3.7",
|
|
172
172
|
"@cloudflare/workers-types": ">=4",
|
|
173
173
|
"jose": "^6.1.0",
|
|
174
174
|
"kysely": "^0.28.5 || ^0.29.0",
|
|
@@ -967,6 +967,11 @@ export const createAdapterFactory =
|
|
|
967
967
|
where: unsafeWhere,
|
|
968
968
|
action: "update",
|
|
969
969
|
});
|
|
970
|
+
// `update` targets a single row. Empty predicates have no
|
|
971
|
+
// target, so fail closed and leave bulk writes to `updateMany`.
|
|
972
|
+
if (where.length === 0) {
|
|
973
|
+
return null;
|
|
974
|
+
}
|
|
970
975
|
debugLog(
|
|
971
976
|
{ method: "update" },
|
|
972
977
|
`${formatTransactionId(thisTransactionId)} ${formatStep(1, 4)}`,
|
package/src/db/adapter/index.ts
CHANGED
|
@@ -434,8 +434,14 @@ export type DBAdapter<Options extends BetterAuthOptions = BetterAuthOptions> = {
|
|
|
434
434
|
where?: Where[] | undefined;
|
|
435
435
|
}) => Promise<number>;
|
|
436
436
|
/**
|
|
437
|
-
*
|
|
438
|
-
*
|
|
437
|
+
* Update a single row matching the where clause.
|
|
438
|
+
*
|
|
439
|
+
* Returns the updated row, or `null` when no row matched. Empty `where`
|
|
440
|
+
* clauses return `null`; use `updateMany` for intentional bulk updates.
|
|
441
|
+
*
|
|
442
|
+
* This is not the race-safe primitive for guarded state transitions. Use
|
|
443
|
+
* `incrementOne` when the predicate is both selector and guard, and use
|
|
444
|
+
* `consumeOne` for single-use destructive reads.
|
|
439
445
|
*/
|
|
440
446
|
update: <T>(data: {
|
|
441
447
|
model: string;
|
package/src/db/get-tables.ts
CHANGED
|
@@ -15,13 +15,19 @@ export const getAuthTables = (
|
|
|
15
15
|
...value.fields,
|
|
16
16
|
},
|
|
17
17
|
modelName: value.modelName || key,
|
|
18
|
+
disableMigrations:
|
|
19
|
+
value.disableMigration ?? acc[key]?.disableMigrations,
|
|
18
20
|
};
|
|
19
21
|
}
|
|
20
22
|
return acc;
|
|
21
23
|
},
|
|
22
24
|
{} as Record<
|
|
23
25
|
string,
|
|
24
|
-
{
|
|
26
|
+
{
|
|
27
|
+
fields: Record<string, DBFieldAttribute>;
|
|
28
|
+
modelName: string;
|
|
29
|
+
disableMigrations?: boolean | undefined;
|
|
30
|
+
}
|
|
25
31
|
>,
|
|
26
32
|
);
|
|
27
33
|
|
package/src/error/index.ts
CHANGED
|
@@ -11,7 +11,16 @@ export class BetterAuthError extends Error {
|
|
|
11
11
|
|
|
12
12
|
export { type APIErrorCode, BASE_ERROR_CODES } from "./codes";
|
|
13
13
|
|
|
14
|
+
type BaseAPIErrorInstance = InstanceType<typeof BaseAPIError>;
|
|
15
|
+
|
|
14
16
|
export class APIError extends BaseAPIError {
|
|
17
|
+
declare status: BaseAPIErrorInstance["status"];
|
|
18
|
+
declare body: BaseAPIErrorInstance["body"];
|
|
19
|
+
declare headers: BaseAPIErrorInstance["headers"];
|
|
20
|
+
declare statusCode: BaseAPIErrorInstance["statusCode"];
|
|
21
|
+
declare message: string;
|
|
22
|
+
declare errorStack: BaseAPIErrorInstance["errorStack"];
|
|
23
|
+
|
|
15
24
|
constructor(...args: ConstructorParameters<typeof BaseAPIError>) {
|
|
16
25
|
super(...args);
|
|
17
26
|
}
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { betterFetch } from "@better-fetch/fetch";
|
|
2
|
+
import type { JWTPayload } from "jose";
|
|
2
3
|
import { decodeJwt, decodeProtectedHeader, importJWK, jwtVerify } from "jose";
|
|
3
4
|
import { logger } from "../env";
|
|
4
5
|
import { APIError, BetterAuthError } from "../error";
|
|
@@ -52,12 +53,67 @@ export interface GoogleOptions extends ProviderOptions<GoogleProfile> {
|
|
|
52
53
|
*
|
|
53
54
|
* This is sent to Google as the `hd` authorization hint and, when set, is
|
|
54
55
|
* also enforced against the `hd` claim of the returned id token/profile.
|
|
55
|
-
*
|
|
56
|
-
*
|
|
56
|
+
* Set `hd: "*"` to require any Workspace hosted-domain claim. Sign-in is
|
|
57
|
+
* rejected when the claim is missing or does not satisfy this restriction.
|
|
57
58
|
*/
|
|
58
59
|
hd?: string | undefined;
|
|
59
60
|
}
|
|
60
61
|
|
|
62
|
+
const GOOGLE_ID_TOKEN_MAX_AGE = "1h";
|
|
63
|
+
|
|
64
|
+
export interface VerifyGoogleIdTokenOptions {
|
|
65
|
+
token: string;
|
|
66
|
+
audience: string | string[];
|
|
67
|
+
nonce?: string | undefined;
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
/**
|
|
71
|
+
* Verifies a Google ID token against Google's issuer, audience, signature,
|
|
72
|
+
* expiry, and maximum token age.
|
|
73
|
+
*/
|
|
74
|
+
export const verifyGoogleIdToken = async ({
|
|
75
|
+
token,
|
|
76
|
+
audience,
|
|
77
|
+
nonce,
|
|
78
|
+
}: VerifyGoogleIdTokenOptions): Promise<JWTPayload | null> => {
|
|
79
|
+
try {
|
|
80
|
+
const { kid, alg: jwtAlg } = decodeProtectedHeader(token);
|
|
81
|
+
if (!kid || !jwtAlg) return null;
|
|
82
|
+
|
|
83
|
+
const publicKey = await getGooglePublicKey(kid);
|
|
84
|
+
const { payload: jwtClaims } = await jwtVerify(token, publicKey, {
|
|
85
|
+
algorithms: [jwtAlg],
|
|
86
|
+
issuer: ["https://accounts.google.com", "accounts.google.com"],
|
|
87
|
+
audience,
|
|
88
|
+
maxTokenAge: GOOGLE_ID_TOKEN_MAX_AGE,
|
|
89
|
+
});
|
|
90
|
+
|
|
91
|
+
if (nonce && jwtClaims.nonce !== nonce) {
|
|
92
|
+
return null;
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
return jwtClaims;
|
|
96
|
+
} catch {
|
|
97
|
+
return null;
|
|
98
|
+
}
|
|
99
|
+
};
|
|
100
|
+
|
|
101
|
+
/**
|
|
102
|
+
* Checks whether Google's verified `hd` claim satisfies the configured hosted
|
|
103
|
+
* domain restriction. `hd: "*"` accepts any Google Workspace hosted domain.
|
|
104
|
+
*/
|
|
105
|
+
export const isGoogleHostedDomainAllowed = (
|
|
106
|
+
configuredHostedDomain: string | undefined,
|
|
107
|
+
tokenHostedDomain: unknown,
|
|
108
|
+
) => {
|
|
109
|
+
if (!configuredHostedDomain) return true;
|
|
110
|
+
if (typeof tokenHostedDomain !== "string" || !tokenHostedDomain) {
|
|
111
|
+
return false;
|
|
112
|
+
}
|
|
113
|
+
if (configuredHostedDomain === "*") return true;
|
|
114
|
+
return tokenHostedDomain === configuredHostedDomain;
|
|
115
|
+
};
|
|
116
|
+
|
|
61
117
|
export const google = (options: GoogleOptions) => {
|
|
62
118
|
return {
|
|
63
119
|
id: "google",
|
|
@@ -133,38 +189,16 @@ export const google = (options: GoogleOptions) => {
|
|
|
133
189
|
return options.verifyIdToken(token, nonce);
|
|
134
190
|
}
|
|
135
191
|
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
const publicKey = await getGooglePublicKey(kid);
|
|
144
|
-
const { payload: jwtClaims } = await jwtVerify(token, publicKey, {
|
|
145
|
-
algorithms: [jwtAlg],
|
|
146
|
-
issuer: ["https://accounts.google.com", "accounts.google.com"],
|
|
147
|
-
audience: options.clientId,
|
|
148
|
-
maxTokenAge: "1h",
|
|
149
|
-
});
|
|
150
|
-
|
|
151
|
-
if (nonce && jwtClaims.nonce !== nonce) {
|
|
152
|
-
return false;
|
|
153
|
-
}
|
|
154
|
-
|
|
155
|
-
// Google's `hd` authorization parameter is only a UI hint and can
|
|
156
|
-
// be removed or changed by the user. When a hosted domain is
|
|
157
|
-
// configured, the `hd` claim in the verified id token is the
|
|
158
|
-
// authoritative value and must match, otherwise accounts outside
|
|
159
|
-
// the workspace domain would be accepted.
|
|
160
|
-
if (options.hd && jwtClaims.hd !== options.hd) {
|
|
161
|
-
return false;
|
|
162
|
-
}
|
|
163
|
-
|
|
164
|
-
return true;
|
|
165
|
-
} catch {
|
|
192
|
+
const jwtClaims = await verifyGoogleIdToken({
|
|
193
|
+
token,
|
|
194
|
+
audience: options.clientId,
|
|
195
|
+
nonce,
|
|
196
|
+
});
|
|
197
|
+
if (!jwtClaims) {
|
|
166
198
|
return false;
|
|
167
199
|
}
|
|
200
|
+
|
|
201
|
+
return isGoogleHostedDomainAllowed(options.hd, jwtClaims.hd);
|
|
168
202
|
},
|
|
169
203
|
async getUserInfo(token) {
|
|
170
204
|
if (options.getUserInfo) {
|
|
@@ -174,15 +208,14 @@ export const google = (options: GoogleOptions) => {
|
|
|
174
208
|
return null;
|
|
175
209
|
}
|
|
176
210
|
const user = decodeJwt(token.idToken) as GoogleProfile;
|
|
177
|
-
// Enforce the configured hosted domain on the callback profile path
|
|
178
|
-
//
|
|
179
|
-
//
|
|
180
|
-
|
|
181
|
-
if (options.hd && user.hd !== options.hd) {
|
|
211
|
+
// Enforce the configured hosted domain on the callback profile path.
|
|
212
|
+
// The authorization-time `hd` value is only a UI hint; the verified
|
|
213
|
+
// token/profile claim is the authoritative Workspace signal.
|
|
214
|
+
if (!isGoogleHostedDomainAllowed(options.hd, user.hd)) {
|
|
182
215
|
logger.error(
|
|
183
216
|
`Google sign-in rejected: id token hosted domain (hd) "${
|
|
184
217
|
user.hd ?? "<missing>"
|
|
185
|
-
}" does not
|
|
218
|
+
}" does not satisfy the configured "hd" option "${options.hd}".`,
|
|
186
219
|
);
|
|
187
220
|
return null;
|
|
188
221
|
}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { base64 } from "@better-auth/utils/base64";
|
|
2
2
|
import { betterFetch } from "@better-fetch/fetch";
|
|
3
|
-
import { decodeProtectedHeader, importJWK, jwtVerify } from "jose";
|
|
3
|
+
import { decodeJwt, decodeProtectedHeader, importJWK, jwtVerify } from "jose";
|
|
4
4
|
import { logger } from "../env";
|
|
5
5
|
import { APIError, BetterAuthError } from "../error";
|
|
6
6
|
import type { OAuthProvider, ProviderOptions } from "../oauth2";
|
|
@@ -16,6 +16,7 @@ import { createAuthorizationURL } from "../oauth2";
|
|
|
16
16
|
const PAYPAL_ID_TOKEN_ALGORITHMS = ["RS256", "HS256"] as const;
|
|
17
17
|
|
|
18
18
|
export interface PayPalProfile {
|
|
19
|
+
sub?: string | undefined;
|
|
19
20
|
user_id: string;
|
|
20
21
|
name: string;
|
|
21
22
|
given_name: string;
|
|
@@ -298,6 +299,26 @@ export const paypal = (options: PayPalOptions) => {
|
|
|
298
299
|
}
|
|
299
300
|
|
|
300
301
|
const userInfo = response.data;
|
|
302
|
+
if (token.idToken) {
|
|
303
|
+
let idTokenSubject: string | undefined;
|
|
304
|
+
try {
|
|
305
|
+
idTokenSubject = decodeJwt(token.idToken).sub;
|
|
306
|
+
} catch (error) {
|
|
307
|
+
logger.error("Failed to decode PayPal ID token:", error);
|
|
308
|
+
return null;
|
|
309
|
+
}
|
|
310
|
+
|
|
311
|
+
// OIDC binds UserInfo to the ID Token with `sub`. Keep `user_id`
|
|
312
|
+
// as the account id below for existing PayPal account mappings.
|
|
313
|
+
const userInfoSubject = userInfo.sub ?? userInfo.user_id;
|
|
314
|
+
if (!idTokenSubject || userInfoSubject !== idTokenSubject) {
|
|
315
|
+
logger.error(
|
|
316
|
+
"PayPal user info subject does not match ID token subject",
|
|
317
|
+
);
|
|
318
|
+
return null;
|
|
319
|
+
}
|
|
320
|
+
}
|
|
321
|
+
|
|
301
322
|
const userMap = await options.mapProfileToUser?.(userInfo);
|
|
302
323
|
|
|
303
324
|
const result = {
|
|
@@ -223,7 +223,7 @@ export type BetterAuthAdvancedOptions = {
|
|
|
223
223
|
* @example ["x-client-ip", "x-forwarded-for", "cf-connecting-ip"]
|
|
224
224
|
*
|
|
225
225
|
* @default
|
|
226
|
-
* @link https://github.com/better-auth/better-auth/blob/main/packages/
|
|
226
|
+
* @link https://github.com/better-auth/better-auth/blob/main/packages/core/src/utils/ip.ts
|
|
227
227
|
*/
|
|
228
228
|
ipAddressHeaders?: string[];
|
|
229
229
|
/**
|
|
@@ -240,6 +240,21 @@ export type BetterAuthAdvancedOptions = {
|
|
|
240
240
|
* @default 64
|
|
241
241
|
*/
|
|
242
242
|
ipv6Subnet?: number;
|
|
243
|
+
/**
|
|
244
|
+
* Trusted reverse-proxy IPs or CIDR ranges. When set, a forwarded IP
|
|
245
|
+
* chain is walked right to left, trusted hops are skipped, and the
|
|
246
|
+
* first untrusted address is the client IP. Unset trusts only
|
|
247
|
+
* single-value IP headers. Use the actual address or subnet of your
|
|
248
|
+
* proxies, not a broad private range that also covers clients.
|
|
249
|
+
*
|
|
250
|
+
* This only interprets the forwarded header chain and cannot verify
|
|
251
|
+
* the direct sender. It is safe only when your origin is reachable
|
|
252
|
+
* through these proxies and clients cannot set forwarded headers
|
|
253
|
+
* directly.
|
|
254
|
+
*
|
|
255
|
+
* @example ["192.0.2.10", "10.0.0.0/24"]
|
|
256
|
+
*/
|
|
257
|
+
trustedProxies?: string[];
|
|
243
258
|
}
|
|
244
259
|
| undefined;
|
|
245
260
|
/**
|
package/src/utils/ip.ts
CHANGED
|
@@ -1,4 +1,6 @@
|
|
|
1
1
|
import * as z from "zod";
|
|
2
|
+
import { isDevelopment, isTest } from "../env";
|
|
3
|
+
import type { BetterAuthOptions } from "../types";
|
|
2
4
|
|
|
3
5
|
/**
|
|
4
6
|
* Normalizes an IP address for consistent rate limiting.
|
|
@@ -195,6 +197,189 @@ export function normalizeIP(
|
|
|
195
197
|
return normalizeIPv6(ip, subnetPrefix);
|
|
196
198
|
}
|
|
197
199
|
|
|
200
|
+
/**
|
|
201
|
+
* Raw bytes of an IP for CIDR comparison. Returns `null` for an invalid IP.
|
|
202
|
+
*/
|
|
203
|
+
function ipToBytes(ip: string): Uint8Array | null {
|
|
204
|
+
if (z.ipv4().safeParse(ip).success) {
|
|
205
|
+
return Uint8Array.from(ip.split(".").map((octet) => Number(octet)));
|
|
206
|
+
}
|
|
207
|
+
if (!isIPv6(ip)) {
|
|
208
|
+
return null;
|
|
209
|
+
}
|
|
210
|
+
const mapped = extractIPv4FromMapped(ip);
|
|
211
|
+
if (mapped) {
|
|
212
|
+
return Uint8Array.from(mapped.split(".").map((octet) => Number(octet)));
|
|
213
|
+
}
|
|
214
|
+
const groups = expandIPv6(ip);
|
|
215
|
+
const bytes = new Uint8Array(16);
|
|
216
|
+
for (let i = 0; i < 8; i++) {
|
|
217
|
+
const group = Number.parseInt(groups[i] ?? "0", 16);
|
|
218
|
+
bytes[i * 2] = (group >> 8) & 0xff;
|
|
219
|
+
bytes[i * 2 + 1] = group & 0xff;
|
|
220
|
+
}
|
|
221
|
+
return bytes;
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
// A CIDR prefix length must be decimal digits only, so values like "8x" or
|
|
225
|
+
// "1e3" that `Number()` would otherwise coerce are rejected.
|
|
226
|
+
const CIDR_PREFIX_PATTERN = /^\d+$/;
|
|
227
|
+
|
|
228
|
+
/**
|
|
229
|
+
* Parses an IP or `IP/prefix` string into network bytes and a prefix length.
|
|
230
|
+
* The prefix must be digits only and within the address family. `null` if the
|
|
231
|
+
* value is not a valid IP or CIDR range, which keeps a malformed entry from
|
|
232
|
+
* silently behaving like a non-match.
|
|
233
|
+
*/
|
|
234
|
+
function parseCIDR(
|
|
235
|
+
value: string,
|
|
236
|
+
): { bytes: Uint8Array; prefix: number } | null {
|
|
237
|
+
const slash = value.lastIndexOf("/");
|
|
238
|
+
const bytes = ipToBytes(slash === -1 ? value : value.slice(0, slash));
|
|
239
|
+
if (!bytes) {
|
|
240
|
+
return null;
|
|
241
|
+
}
|
|
242
|
+
const maxBits = bytes.length * 8;
|
|
243
|
+
if (slash === -1) {
|
|
244
|
+
return { bytes, prefix: maxBits };
|
|
245
|
+
}
|
|
246
|
+
const prefixPart = value.slice(slash + 1);
|
|
247
|
+
if (!CIDR_PREFIX_PATTERN.test(prefixPart)) {
|
|
248
|
+
return null;
|
|
249
|
+
}
|
|
250
|
+
const prefix = Number(prefixPart);
|
|
251
|
+
return prefix <= maxBits ? { bytes, prefix } : null;
|
|
252
|
+
}
|
|
253
|
+
|
|
254
|
+
/**
|
|
255
|
+
* Whether `ipBytes` falls inside an already-parsed CIDR network.
|
|
256
|
+
*/
|
|
257
|
+
function matchesCIDR(
|
|
258
|
+
ipBytes: Uint8Array,
|
|
259
|
+
net: { bytes: Uint8Array; prefix: number },
|
|
260
|
+
): boolean {
|
|
261
|
+
if (ipBytes.length !== net.bytes.length) {
|
|
262
|
+
return false;
|
|
263
|
+
}
|
|
264
|
+
let bitsRemaining = net.prefix;
|
|
265
|
+
for (let i = 0; i < ipBytes.length && bitsRemaining > 0; i++) {
|
|
266
|
+
const take = bitsRemaining >= 8 ? 8 : bitsRemaining;
|
|
267
|
+
const mask = take === 8 ? 0xff : (0xff << (8 - take)) & 0xff;
|
|
268
|
+
if (((ipBytes[i] ?? 0) & mask) !== ((net.bytes[i] ?? 0) & mask)) {
|
|
269
|
+
return false;
|
|
270
|
+
}
|
|
271
|
+
bitsRemaining -= 8;
|
|
272
|
+
}
|
|
273
|
+
return true;
|
|
274
|
+
}
|
|
275
|
+
|
|
276
|
+
/**
|
|
277
|
+
* Trusted-proxy entries that are not a valid IP address or CIDR range.
|
|
278
|
+
*/
|
|
279
|
+
export function findInvalidTrustedProxies(entries: string[]): string[] {
|
|
280
|
+
return entries.filter((entry) => parseCIDR(entry) === null);
|
|
281
|
+
}
|
|
282
|
+
|
|
283
|
+
/**
|
|
284
|
+
* Resolves the client IP from a forwarded header. The leftmost token is spoofable,
|
|
285
|
+
* so with `trustedProxies` the chain is stripped from the right to the first
|
|
286
|
+
* untrusted hop. Otherwise only a single-value header is trusted. Returns `null`
|
|
287
|
+
* when no trustworthy client IP can be resolved.
|
|
288
|
+
*/
|
|
289
|
+
export function getIPFromHeader(
|
|
290
|
+
value: string,
|
|
291
|
+
options: {
|
|
292
|
+
ipv6Subnet?: number;
|
|
293
|
+
trustedProxies?: string[];
|
|
294
|
+
} = {},
|
|
295
|
+
): string | null {
|
|
296
|
+
const forwardedIps = value
|
|
297
|
+
.split(",")
|
|
298
|
+
.map((ip) => ip.trim())
|
|
299
|
+
.filter(Boolean);
|
|
300
|
+
if (forwardedIps.length === 0) {
|
|
301
|
+
return null;
|
|
302
|
+
}
|
|
303
|
+
|
|
304
|
+
// Parse trusted proxies once, dropping malformed entries so a config typo
|
|
305
|
+
// cannot leave the chain enabled-but-empty and return a real proxy hop as
|
|
306
|
+
// the client. With no valid proxy the chain mode does not engage.
|
|
307
|
+
const trustedProxies = (options.trustedProxies ?? [])
|
|
308
|
+
.map(parseCIDR)
|
|
309
|
+
.filter((proxy): proxy is { bytes: Uint8Array; prefix: number } => {
|
|
310
|
+
return proxy !== null;
|
|
311
|
+
});
|
|
312
|
+
|
|
313
|
+
if (trustedProxies.length > 0) {
|
|
314
|
+
for (let i = forwardedIps.length - 1; i >= 0; i--) {
|
|
315
|
+
const ip = forwardedIps[i];
|
|
316
|
+
const ipBytes = ip ? ipToBytes(ip) : null;
|
|
317
|
+
// A malformed hop breaks the chain: fail closed.
|
|
318
|
+
if (!ip || !ipBytes) {
|
|
319
|
+
return null;
|
|
320
|
+
}
|
|
321
|
+
if (trustedProxies.some((proxy) => matchesCIDR(ipBytes, proxy))) {
|
|
322
|
+
continue;
|
|
323
|
+
}
|
|
324
|
+
return normalizeIP(ip, { ipv6Subnet: options.ipv6Subnet });
|
|
325
|
+
}
|
|
326
|
+
return null;
|
|
327
|
+
}
|
|
328
|
+
|
|
329
|
+
// Without valid trusted proxies a multi-hop chain is unresolvable.
|
|
330
|
+
if (forwardedIps.length !== 1) {
|
|
331
|
+
return null;
|
|
332
|
+
}
|
|
333
|
+
const selectedIp = forwardedIps[0];
|
|
334
|
+
if (!selectedIp || !isValidIP(selectedIp)) {
|
|
335
|
+
return null;
|
|
336
|
+
}
|
|
337
|
+
|
|
338
|
+
return normalizeIP(selectedIp, { ipv6Subnet: options.ipv6Subnet });
|
|
339
|
+
}
|
|
340
|
+
|
|
341
|
+
const LOCALHOST_IP = "127.0.0.1";
|
|
342
|
+
const DEFAULT_IP_HEADERS = ["x-forwarded-for"];
|
|
343
|
+
|
|
344
|
+
/**
|
|
345
|
+
* Resolves the client IP for a request from the configured IP headers.
|
|
346
|
+
* Honors `disableIpTracking`, walks `ipAddressHeaders` in order (default
|
|
347
|
+
* `x-forwarded-for`), and falls back to localhost in development and test.
|
|
348
|
+
* Returns `null` when tracking is disabled or no trustworthy IP can be resolved.
|
|
349
|
+
*/
|
|
350
|
+
export function getIp(
|
|
351
|
+
req: Request | Headers,
|
|
352
|
+
options: BetterAuthOptions,
|
|
353
|
+
): string | null {
|
|
354
|
+
if (options.advanced?.ipAddress?.disableIpTracking) {
|
|
355
|
+
return null;
|
|
356
|
+
}
|
|
357
|
+
|
|
358
|
+
const headers = "headers" in req ? req.headers : req;
|
|
359
|
+
|
|
360
|
+
const ipHeaders =
|
|
361
|
+
options.advanced?.ipAddress?.ipAddressHeaders || DEFAULT_IP_HEADERS;
|
|
362
|
+
|
|
363
|
+
for (const key of ipHeaders) {
|
|
364
|
+
const value = "get" in headers ? headers.get(key) : headers[key];
|
|
365
|
+
if (typeof value === "string") {
|
|
366
|
+
const ip = getIPFromHeader(value, {
|
|
367
|
+
ipv6Subnet: options.advanced?.ipAddress?.ipv6Subnet,
|
|
368
|
+
trustedProxies: options.advanced?.ipAddress?.trustedProxies,
|
|
369
|
+
});
|
|
370
|
+
if (ip) {
|
|
371
|
+
return ip;
|
|
372
|
+
}
|
|
373
|
+
}
|
|
374
|
+
}
|
|
375
|
+
|
|
376
|
+
if (isTest() || isDevelopment()) {
|
|
377
|
+
return LOCALHOST_IP;
|
|
378
|
+
}
|
|
379
|
+
|
|
380
|
+
return null;
|
|
381
|
+
}
|
|
382
|
+
|
|
198
383
|
/**
|
|
199
384
|
* Creates a rate limit key from IP and path
|
|
200
385
|
* Uses a separator to prevent collision attacks
|