NewYour coding agent can read the release notes before it upgrades.Set up the MCP server →
npm
npm, #4985 most downloaded on npm
The most comprehensive authentication framework for TypeScript.
Latest stable
1.7.20
Last release 12 days ago
10 Nov 2026
Ships fairly regularly
a new release about every 1 weeks
Nearly every release is documented
notes for 60 of the last 60 stable releases
Nothing withdrawn
no release was ever pulled
3 years old
957 releases · first in 2024
Drag across the ruler to compare, or tap a release to open it.
This beta includes all fixes from v1.7.19.
This beta includes all fixes from v1.7.19.
Thanks to everyone who contributed to this release:
@Adnan-Husayn, @AryaKesharwani, @binaryshrey, @bytaesu, @Faiziimam, @Gourav224, @jashkarangiya, @NoiceHax, @PhillJK, @Tushar-Khandelwal-2004, @Tyagiquamar, @umeraamir69, @unjica, @YIOYIOIOI
Full changelog: v1.8.0-beta.6...v1.8.0-beta.7
> - If your clients exchange their own DPoP-bound access tokens with oauthTokenExchange(), send a DPoP proof signed by the token's key, or have your c
[!IMPORTANT] Action required
- If your clients exchange their own DPoP-bound access tokens with
oauthTokenExchange(), send a DPoP proof signed by the token's key, or have yourclientAuthenticationstrategy return that key asconfirmation. (#12262)- If your clients send a standard parameter more than once in form-encoded POST requests to
/oauth2/authorize, such asstate=a&state=b, change them to send each standard parameter only once. (#12261)
@better-auth/oauth-provider/oauth2/authorize to reject repeated standard parameters with invalid_request, matching GET behavior (#12261)oauthTokenExchange() so a client exchanging its own DPoP-bound access token must prove the same key (#12262)For detailed changes, see CHANGELOG
Thanks to everyone who contributed to this release:
@gustavovalverde
Full changelog: v1.8.0-beta.5...v1.8.0-beta.6
Your coding agent can read these notes before it upgrades. Set up the MCP server →
> - If you write plugin after-hooks for credential sign-in routes, handle a null new session while two-factor verification is pending.
[!IMPORTANT] Action required
- If you write plugin after-hooks for credential sign-in routes, handle a null new session while two-factor verification is pending. (#12202)
- If you set
authenticatorSelection.userVerificationtorequired, passkey sign-in now rejects responses without user verification. (#12202)- If you use phone sign-in with
requireVerification, configuresendOTP. Without it the route returnsSEND_OTP_NOT_IMPLEMENTED. (#12202)- If users reset passwords by phone, they must verify the number first. Otherwise
resetPasswordreturnsPHONE_NUMBER_PENDING_VERIFICATION. (#12202)- If you use sessions from
enableSessionForAPIKeyson passkey registration, device-code approval, two-factor enrollment, phone number changes, social account linking, or organization invitations, those requests are now refused. If you calllinkOAuthAccountdirectly, pass the session that started the link in OAuth state. (#12202)
better-authphoneNumber with PHONE_NUMBER_CANNOT_BE_SET (#12202)For detailed changes, see CHANGELOG
@better-auth/electronFor detailed changes, see CHANGELOG
@better-auth/passkeyauthenticatorSelection.userVerification to apply to authentication as well as registration, rejecting responses without user verification when it is required (#12202)For detailed changes, see CHANGELOG
@better-auth/coreFor detailed changes, see CHANGELOG
@better-auth/oauth-providerFor detailed changes, see CHANGELOG
Thanks to everyone who contributed to this release:
@gustavovalverde @Bekacru @bytaesu
Full changelog: v1.8.0-beta.4...v1.8.0-beta.5
> Custom Twitch and Paybin ID-token sign-ins using the default getUserInfo must include idToken.accessToken. Standard redirect-based sign-in requires
[!IMPORTANT] Action required
Custom Twitch and Paybin ID-token sign-ins using the default
getUserInfomust includeidToken.accessToken. Standard redirect-based sign-in requires no changes.
@better-auth/core/oauth/* endpoints and return UserInfo data instead of stored ID-token claims, so profile mappings must handle omitted email and custom ID-token sign-ins using the default profile reader must supply accessToken (#11860)accessToken (#11848)For detailed changes, see CHANGELOG
Thanks to everyone who contributed to this release:
@bytaesu
Full changelog: v1.8.0-beta.3...v1.8.0-beta.4
> OAuth profile types for Apple, Cognito, Discord, Dropbox, Facebook, GitHub, GitLab, Gumroad, Linear, Microsoft Entra ID, Notion, Patreon, PayPal, Ra
[!IMPORTANT] Action required
OAuth profile types for Apple, Cognito, Discord, Dropbox, Facebook, GitHub, GitLab, Gumroad, Linear, Microsoft Entra ID, Notion, Patreon, PayPal, Railway, Slack, and Twitter(X) were reviewed against each provider's official resources and updated to match. If you use custom profile mappings or profile types for any of them, review the changes below and handle fields that are now optional, nullable, or retyped.
better-authundefined for accounts without a name, matching its declared profile type (#11864)SlackProfile email and profile claims, use POST for userinfo in the built-in provider and Generic OAuth helper, and reject Slack errors returned with HTTP 200 (#11851)For detailed changes, see CHANGELOG
@better-auth/coreCognitoProfile to make profile and token claims optional, accept boolean or "true"/"false" verification values, fall back to cognito:username for ID-token names, and verify tokens against both documented issuer formats (#11843)home_path required for team roots (#11846)GithubProfile types to match GitHub API responses, with numeric id and account counters, nullable details, and omitted scope-dependent fields such as twitter_username (#11839)locked a required boolean, and preserved stored images for null avatars when profile updates are enabled (#11853)LinearUser.avatarUrl to be required and typed as string | null, preserved stored images for null avatars during enabled profile updates, and made authorization scopes comma-separated (#11855)MicrosoftEntraIDProfile claim types so timestamps are numbers, groups, acrs, and xms_cc are string arrays, in_corp is boolean, and conditional claims and profile photos can be omitted (#11854)type, nullable name and avatar_url, missing image as undefined, and optional person.email_verified metadata (#11859)RailwayProfile to make email, name, and picture optional, reflecting the granted scopes (#11861)SlackProfile email and profile claims, use POST for userinfo in the built-in provider and Generic OAuth helper, and reject Slack errors returned with HTTP 200 (#11851)TwitterProfile types so nested entity objects, arrays, and URL details can be omitted or null, and added description cashtags, mentions, and URL preview metadata (#11852)For detailed changes, see CHANGELOG
Thanks to everyone who contributed to this release:
@bytaesu
Full changelog: v1.8.0-beta.2...v1.8.0-beta.3
…and read securityRestrictions instead of the deprecated SSO and MFA flags.
[!IMPORTANT] Action required
- If your Zoom profile mappings use exhaustive login-type checks, update them to handle the login types
11,21, and23. (#11850)- If you use Naver profile mappings, update them to handle omitted personal fields and supply an email when Naver does not share one. (#11858)
- If you use Kakao profile mappings, update them to handle a missing
kakao_account. (#11857)- If you use Roblox profile mappings, update them to handle optional scoped fields, a
nullpicture, andunknowncustom claims. (#11866)- If your Google profile mappings rely on ID token claims such as email verification, update them to handle claims that are now optional. (#11847)
- If you use
mapProfileToUserwith Polar, update it to read the scoped, nullable userinfo claims instead of the previous user profile fields. (#11840)- If you use custom Kick profile mappings or
getUserInfocallbacks, update them to treatKickProfile.user_idas a number instead of a string. (#11841)- If you send
reference_idto/oauth2/consentwhen accepting, configurepostLogin.consentReferenceId, otherwise acceptance fails withinvalid_request. (#11967)- If you use a VK profile callback or mapping that reads
user.phone, update it to treat the value as a string instead of a number. (#11849)- If you map LinkedIn profiles in a callback, update your code to read
localeas a string instead of a country/language object. (#11844)- If you use Hugging Face profile mappings, iterate over the organization arrays, treat organization roles as strings, and read
securityRestrictionsinstead of the deprecated SSO and MFA flags. (#11845)
@better-auth/coreGoogleProfile to reflect Google's optional ID token claims and to treat an absent email verification claim as unverified (#11847)securityRestrictions fields (#11845)KakaoProfile.kakao_account optional and to separate consent scopes with commas in authorization requests, as Kakao documents (#11857)KickProfile.user_id to be a number instead of a string (#11841)locale field to a language tag string such as en-US instead of a country/language object (#11844)NaverProfile.response to make personal profile fields optional, matching what Naver may omit (#11858)mapProfileToUser instead of unrelated user profile fields (#11840)RobloxProfile fields are optional, picture can be null, and custom claims are unknown, and preserved stored images when a Roblox avatar is missing and profile updates are enabled (#11866)user.phone is a string instead of a number (#11849)11, 21, and 23) (#11850)For detailed changes, see CHANGELOG
@better-auth/oauth-providerquery to the OAuth provider shouldRedirect hooks and postLogin.consentReferenceId, and let consent pages pass a chosen reference_id (#11967)For detailed changes, see CHANGELOG
Thanks to everyone who contributed to this release:
@bytaesu, @gustavovalverde
Full changelog: v1.8.0-beta.1...v1.8.0-beta.2
> - If you regenerate an existing Drizzle Relations v2 schema, check whether it needs a nullability migration, and backfill existing NULL values befor
[!IMPORTANT] Action required
- If you regenerate an existing Drizzle Relations v2 schema, check whether it needs a nullability migration, and backfill existing
NULLvalues before applying any neededNOT NULLconstraints. (#11836)
better-authFor detailed changes, see CHANGELOG
@better-auth/drizzle-adapterrequired flag (#11836)For detailed changes, see CHANGELOG
@better-auth/oauth-providerclient_credentials scopes during protected OAuth client registration (#11832)For detailed changes, see CHANGELOG
Thanks to everyone who contributed to this release:
@bytaesu, @gustavovalverde, @qamarq
Full changelog: v1.8.0-beta.0...v1.8.0-beta.1
Changed the custom DeviceAuthorizationGrant interface for device-code approval
better-authDeviceAuthorizationGrant interface for device-code approval (#11610)Migration: Rename
assertSessionRedemptiontoassertStandaloneUse, handle its newuseargument, and remove uses ofgetVerificationContext,verificationOpenAPIProperties, and the interface's second type parameter.
Migration: Use a
databaseHooks.user.create.beforehook to reject sign-ups instead of throwing fromsendVerificationEmailoronExistingUserSignUp, and account for logged cache-write failures no longer failing applicable sign-ins.
Migration: Replace checks for
device_code_already_processedin/device/approveerror types with checks forinvalid_request.
expired_token immediately after a code expires (#11772)Migration: Handle
expired_tokenon the first poll after expiry rather than expecting an initialslow_downresponse.
For detailed changes, see CHANGELOG
@better-auth/oauth-providerMigration: Update OAuth device verification pages to send users to
/oauth2/authorize?user_code=<code>instead of approving codes through/device/approveor/device/deny, and apply the newdeviceCodecolumns before deploying.
Migration: Stop relying on consent records for the empty
scopevalue; omit empty entries from requested and accepted scopes.
interactionRequests for extensions that route additional approval flows through OAuth provider pages (#11610)Migration: If your OAuth provider extension implements a custom approval flow, register it through
interactionRequestsand resume it through/oauth2/authorize.
Migration: Update clients and tests for the changed revocation, introspection, userinfo, and refresh-token error responses; extension grants should use
provider.requireActiveAccessTokenif an unknown token must throw.
invalid_target (#11746)Migration: Send token, introspection, and revocation form parameters only once except for
resourceandaudience, and update error handling for malformedresourcevalues frominvalid_requesttoinvalid_target.
sub values for newly registered native and loopback OAuth clients (#11650)Migration: Add the
sectorIdentifiercolumn tooauthClientwithnpx auth@latest migrate, or generate and apply the schema with your ORM, before upgrading.
null (#9923)acr and amr claims to OAuth ID tokens (#11787)For detailed changes, see CHANGELOG
@better-auth/ciba ✨auth.api.completeCibaRequest so apps can approve or deny CIBA requests from server code (#11812)For detailed changes, see CHANGELOG
@better-auth/cimdFor detailed changes, see CHANGELOG
Thanks to everyone who contributed to this release:
@erikpr1994, @gustavovalverde, @shiminshen
Full changelog: v1.7.10...v1.8.0-beta.0
> - If your issuer (baseURL, or jwt.issuer when set) uses http on a non-loopback host behind a TLS-terminating proxy, set baseURL to the public https
[!IMPORTANT] Action required
- If your issuer (
baseURL, orjwt.issuerwhen set) useshttpon a non-loopback host behind a TLS-terminating proxy, setbaseURLto the publichttpsURL, since discovery and theissparameter no longer rewrite it tohttps. (#11904)
@better-auth/oauth-providerPOST /oauth2/public-client-prelogin with allowPublicClientPrelogin to return a client only when its client_id matches the signed oauth_query, otherwise responding with 401 invalid_client (#12237)oauthProviderResourceClient(auth) defaults to accept issued access tokens when baseURL is only an origin, by including the auth path in the default issuer, JWKS, and introspection URLs (#12234)allowInsecureRedirectUri option so OAuth provider deployments served over HTTP on private networks can accept http redirect URIs (#11904)For detailed changes, see CHANGELOG
@better-auth/prisma-adapterincrementOne and update calls using mode: "insensitive" filters to match case-insensitively on PostgreSQL and MongoDB (#11809)eq null on MongoDB to also match records where the optional field was never set (#11806)For detailed changes, see CHANGELOG
@better-auth/coreallowInsecureRedirectUri option so OAuth provider deployments served over HTTP on private networks can accept http redirect URIs (#11904)For detailed changes, see CHANGELOG
@better-auth/memory-adapterne null where clauses in the memory adapter to no longer match records where the field was never set (#11806)For detailed changes, see CHANGELOG
@better-auth/ssosaml.clockSkew to the NotBefore and NotOnOrAfter checks in samlify (#12309)For detailed changes, see CHANGELOG
Thanks to everyone who contributed to this release:
@ArjunCodess, @gustavovalverde
Full changelog: v1.7.19...v1.7.20
Fixed /admin/create-user leaving a user without a credential account when creating that account failed, such as a database hook throwing, which made r
better-auth/admin/create-user leaving a user without a credential account when creating that account failed, such as a database hook throwing, which made retrying with the same email fail with USER_ALREADY_EXISTS_USE_ANOTHER_EMAIL (#12338)/admin/create-user leaving a user without a credential account when the password was rejected, such as by the Have I Been Pwned plugin, which made retrying with the same email fail with USER_ALREADY_EXISTS_USE_ANOTHER_EMAIL (#12335)get or HEAD (#12336)modelName and field names) leaking into other instances of the same plugin in one process (#12319)/device/token returning invalid_grant instead of invalid_client when validateClient rejects the client_id, matching /device/code and RFC 6749 section 5.2 (#12246)state_mismatch during the daylight saving time fall-back hour when OAuth state is stored in the database and the server's time zone observes daylight saving time (#12320)z.optional(), such as /get-session and Stripe's /subscription/list (#12337)organization.getInvitation to return the INVITATION_NOT_FOUND code for a missing, expired, or non-pending invitation (#12332)listMembers failing with a syntax error on PostgreSQL and MSSQL when the filter matches no members or the offset is past the last member (#12318)active-sessions list in secondary storage being stored without an expiry when every remaining session had less than a second left (#12323)For detailed changes, see CHANGELOG
auth--yes, and prompts appear on stderr so redirecting stdout no longer hides them (#12286)auth info --json --copy now prints valid JSON, auth secret prints only the BETTER_AUTH_SECRET line on stdout, auth login and auth logout messages go to stderr, and auth info shows tips only in an interactive terminal (#12287)--config path reports that the file doesn't exist. auth mcp and auth ai no longer report success after a failed step (#12305)auth mcp setup exit with 1 (#12275)For detailed changes, see CHANGELOG
@better-auth/oauth-providerauth.api.oauth2Consent({ headers, body }) failing with request not found when called from a server route (#12325)prefix.clientSecret getting a different error than other wrong secrets. It now gets the standard invalid_client response: 401 with a WWW-Authenticate: Basic challenge for client_secret_basic, and 400 for client_secret_post (#12327)metadata being stored as a JSON string in its json column. It is now written as an object, so Postgres jsonb operators such as -> and @> work with adapters that pass JSON through natively (Drizzle pg). Rows written as strings by earlier versions are still read (#12328)For detailed changes, see CHANGELOG
@better-auth/coreconsole.error in addition to the configured logger (#12317)getAccessToken and refreshToken returning the expired access token when a provider refuses a token refresh with a 200 status, as GitHub does (#12369)For detailed changes, see CHANGELOG
@better-auth/expoFor detailed changes, see CHANGELOG
@better-auth/mcpresource URLs on .localhost subdomains as non-HTTPS (#12322)For detailed changes, see CHANGELOG
Thanks to everyone who contributed to this release:
@Adnan-Husayn, @AryaKesharwani, @binaryshrey, @bytaesu, @Faiziimam, @Gourav224, @jashkarangiya, @NoiceHax, @PhillJK, @Tushar-Khandelwal-2004, @Tyagiquamar, @umeraamir69, @unjica, @YIOYIOIOI
Full changelog: v1.7.18...v1.7.19
#12323 a10121d Thanks @bytaesu! - Fixed the active-sessions list in secondary storage being stored without an expiry when the last remaining session had less than a second left.
#12335 c41f8ff Thanks @bytaesu! - Fixed /admin/create-user leaving a user without a credential account when the password was rejected (for example by the Have I Been Pwned plugin), which made retrying with the same email fail with USER_ALREADY_EXISTS_USE_ANOTHER_EMAIL.
#12338 e786566 Thanks @bytaesu! - Fixed /admin/create-user leaving a user without a credential account when creating that account failed, which made retrying with the same email fail with USER_ALREADY_EXISTS_USE_ANOTHER_EMAIL.
#12336 ac778b7 Thanks @bytaesu! - Client actions now send the HTTP method passed in the second-argument fetch options, the same as when it is nested under fetchOptions. Passing a lowercase get or HEAD method no longer fails because a request body was attached.
#12246 5eb69d8 Thanks @AryaKesharwani! - /device/token now returns invalid_client instead of invalid_grant when validateClient rejects the client_id, matching /device/code and RFC 6749 section 5.2.
#12319 4b0327b Thanks @bytaesu! - Plugin schema overrides (modelName and field names) no longer leak into other instances of the same plugin in one process.
#12320 2d5ef64 Thanks @bytaesu! - Fix OAuth sign-in failing with state_mismatch during the daylight saving time fall-back hour on servers that do not run in UTC. The stored OAuth state is no longer created already expired.
#12337 5f0a0fc Thanks @bytaesu! - The OpenAPI schema now documents query parameters for endpoints whose query schema is wrapped in z.optional(), such as /get-session and Stripe's /subscription/list.
#12332 89e74b8 Thanks @bytaesu! - Fixed organization.getInvitation returning a missing, expired, or non-pending invitation error without a code. It now returns INVITATION_NOT_FOUND like the other invitation endpoints.
#12318 525bd7a Thanks @bytaesu! - Fix listMembers failing with a syntax error on PostgreSQL and MSSQL when the filter or offset matches no members.
#12366 23a60a3 Thanks @bytaesu! - Fixed SIWE sign-in leaving a user behind when creating its wallet address or account failed, which blocked that wallet from signing in again.
#12340 29e45f8 Thanks @bytaesu! - Fixed social sign-up hanging on single-connection databases when the username plugin is enabled and the provider profile maps a username.
Updated dependencies [8412a5f, 34ee100]:
> - If you use getTestInstance with testWith: "mysql", run a MySQL server at 127.0.0.1:3306 with the root password set to root_password.
[!IMPORTANT] Action required
- If you use
getTestInstancewithtestWith: "mysql", run a MySQL server at127.0.0.1:3306with therootpassword set toroot_password. (#12244)
better-authsecondaryStorage and storeSessionInDatabase to also revoke sessions created while the revocation is running, except sessions created by a session.delete.after hook, which stay active (#12259)getTestInstance from better-auth/test to close its own Postgres connection pool and SQLite database when the test file finishes, while with Vitest's default sequence.hooks: "stack" your afterAll hooks still run first and can keep using the instance (#12250)getTestInstance with testWith: "mysql" hanging, and added a separate database per instance so several instances can run in one test file (#12244)For detailed changes, see CHANGELOG
@better-auth/coreverifyOptions.typ is set together with remoteVerify (#12249)For detailed changes, see CHANGELOG
Thanks to everyone who contributed to this release:
@gustavovalverde
Full changelog: v1.7.17...v1.7.18
#12259 9e2a0ec Thanks @gustavovalverde! - Fixed "revoke all sessions" with secondaryStorage and storeSessionInDatabase so that sessions created while the revocation runs are revoked too. Sessions created by a session.delete.after hook still stay active.
#12244 85f4342 Thanks @gustavovalverde! - getTestInstance with testWith: "mysql" no longer hangs. It expects a MySQL server at 127.0.0.1:3306 whose root password is root_password, and it creates and drops a separate database for each instance, so several instances can run in one test file.
#12250 278bb28 Thanks @gustavovalverde! - getTestInstance from better-auth/test now closes the Postgres connection pool and the SQLite database it created when the test file finishes. Previously both stayed open until the test worker exited. With Vitest's default sequence.hooks: "stack", afterAll hooks in your test files still run before this cleanup and can keep using the instance.
Updated dependencies [9342a73]:
Fixed sessions created by a session.delete.after hook being treated as revoked during "revoke all sessions" when using secondaryStorage with storeSess
better-authsession.delete.after hook being treated as revoked during "revoke all sessions" when using secondaryStorage with storeSessionInDatabase (#12212)rememberMe: false (#12181)exp://192.168.*.*:* matching custom-scheme hosts with out-of-range or zero-padded octets (#12217)phoneNumber on sign-up and replacing a verified number when linking an account with an empty phone number (#12219)For detailed changes, see CHANGELOG
@better-auth/expostate parameter when OAuth state is stored in a cookie (#12218)For detailed changes, see CHANGELOG
@better-auth/kysely-adaptercreate with generateId: "serial" leaving an inserted row behind when the table reports no auto-increment id (#12220)For detailed changes, see CHANGELOG
@better-auth/passkeypasskey() plugin is shared between auth instances where only some set baseURL (#12225)For detailed changes, see CHANGELOG
Thanks to everyone who contributed to this release:
@aliamanatali, @bytaesu
Full changelog: v1.7.16...v1.7.17
#12181 b6a87ad Thanks @aliamanatali! - A remembered sign-in or sign-up now refreshes its session like any other remembered session, even if an earlier sign-in in the same browser used rememberMe: false. Previously the earlier choice stayed in a dont_remember cookie until the browser closed, so the new session stopped sliding and expired expiresIn after it was created.
#12216 cff7c1c Thanks @bytaesu! - Denying a device authorization request now rejects a session that was revoked but still present in the cookie cache, matching the behavior of approving a request.
#12217 16aa412 Thanks @bytaesu! - IP wildcard trusted origins such as exp://192.168.*.*:* no longer match custom-scheme hosts with out-of-range or zero-padded octets like 192.168.999.999.
#12219 9150314 Thanks @bytaesu! - Signing up with an empty phoneNumber with the phone number plugin no longer stores the empty string or makes later sign-ups fail. Linking an account whose profile maps an empty phone number no longer replaces the user's verified number.
#12212 f5be351 Thanks @bytaesu! - Fixed sessions created by a session.delete.after hook during "revoke all sessions" being treated as revoked immediately when secondaryStorage is used with storeSessionInDatabase.
#12211 98bcd98 Thanks @bytaesu! - Fixed TOTP verification rejecting sessions created from an API key, so API-key sessions can now finish two-factor enrollment.
#12228 fbff537 Thanks @bytaesu! - Trusted devices are honored again when an app runs the two-factor sign-in step from its own hook on another sign-in path, such as email OTP.
Updated dependencies [fc2e00b]:
Fixed revoked sessions staying usable with secondary storage or the cookie cache. Bulk revocation now ends sessions missing from the cached list, and
better-authphoneNumber in the request, social profiles no longer set an unverified number, and verification codes use their own namespace (#12198)/admin/update-user changing phone numbers without permission. It now requires user:set-phone, so add set-phone to custom access control statements (#12198)allowedAttempts under concurrent requests, and bound email change codes to the requesting account (#12198)email_verified value such as "false" as verified, and bound generic OAuth profiles to the ID token subject (#12198)For detailed changes, see CHANGELOG
@better-auth/coredisableSignUp, requireEmailVerification, and overrideUserInfoOnSignIn (#12198)email_verified claims from Cognito and Microsoft Entra ID being read as verified (#12198)For detailed changes, see CHANGELOG
@better-auth/expoFor detailed changes, see CHANGELOG
@better-auth/electronFor detailed changes, see CHANGELOG
@better-auth/passkeyorigin when rpID is set and a wildcard in baseURL.allowedHosts covers it (#12198)userVerification: "required" not being enforced, and applied it to authentication as well as registration (#12198)For detailed changes, see CHANGELOG
@better-auth/stripestripeCustomerId. Server code that sets it through auth.api.updateUser must write it through the database adapter instead (#12198)For detailed changes, see CHANGELOG
@better-auth/kysely-adaptergenerateId: "serial" returning another request's record on connection pools (#12198)For detailed changes, see CHANGELOG
@better-auth/drizzle-adaptergenerateId: "serial" returning another request's record on connection pools (#12198)For detailed changes, see CHANGELOG
Thanks to everyone who contributed to this release:
@bytaesu @Bekacru @gustavovalverde @Abhishek-B-R
Full changelog: v1.7.15...v1.7.16
#12198 f25081a Thanks @bytaesu! - /admin/update-user now requires the new user:set-phone permission to change phoneNumber or phoneNumberVerified. If you use a custom access control, add set-phone to your statements and grant it to roles that should change phone numbers.
#12198 f25081a Thanks @bytaesu! - Anonymous users are no longer linked or deleted on a sign-in that is still waiting for a second factor.
#12198 f25081a Thanks @bytaesu! - Email verification and change email links now only work for the account they were issued to. Opening a change email link no longer signs the user in, and it verifies the new email only if the current one was verified.
#12198 f25081a Thanks @bytaesu! - Wildcard trusted origins now match custom-scheme URLs by their parsed scheme, host, and path, and no longer match a URL with userinfo or one that cannot be parsed as an origin. A wildcard host made only of digits, dots, and wildcards, such as 192.168.*.*, now matches only IPv4 addresses in that range.
#12198 f25081a Thanks @bytaesu! - Looking up a user by email now returns only an account whose stored address matches the requested one, ignoring case, even on databases with accent-insensitive collations. The email OTP password reset routes now validate the address and send the code to the address on the account.
#12198 f25081a Thanks @bytaesu! - Email change codes from the email OTP plugin are now bound to the requesting account and the new address. Codes sent before the upgrade must be requested again.
#12198 f25081a Thanks @bytaesu! - Fixed the email OTP checkVerificationOtp and resetPassword endpoints and the phone number resetPassword endpoint allowing more OTP guesses than allowedAttempts when requests arrive concurrently. A correct check still leaves the OTP usable for the follow-up call.
#12198 f25081a Thanks @bytaesu! - The Expo authorization proxy now sets the signed state cookie only for an unexpired state issued by the server. getAuthStateVerificationIdentifier is now exported for plugins that look up OAuth state records.
#12198 f25081a Thanks @bytaesu! - Passkey registration, device authorization, two-factor enrollment and verification, social account linking, and phone number changes now reject a session revoked in the database or secondary storage, even when cookie caching is enabled. Sessions created from API keys are refused on these routes, except two-factor enrollment and phone number changes.
#12198 f25081a Thanks @bytaesu! - Generic OAuth providers whose discovery document has a jwks_uri now reject a user profile whose sub differs from the ID token's sub. Direct ID-token sign-in and linking with a generic OAuth provider now resolve the profile from the verified ID token only and ignore a submitted access or refresh token.
#12198 f25081a Thanks @bytaesu! - Pending organization invitations are now only returned to members whose role can create invitations, and creator-role invitations only to members who hold that role.
#12198 f25081a Thanks @bytaesu! - Organization invitations use random IDs when advanced.database.generateId is not set, including on adapters with sequential default IDs such as MongoDB. On MongoDB, new invitation IDs are strings instead of ObjectIds.
#12198 f25081a Thanks @bytaesu! - Dynamic access control roles reused through hasPermission's useMemoryCache option are now cached per request and per auth instance instead of in a process-global cache, so role changes apply on the next request.
#12198 f25081a Thanks @bytaesu! - Organization role lists are now trimmed and split on commas wherever they are stored or compared, and invitations with an empty role are rejected.
#12198 f25081a Thanks @bytaesu! - With the phone number plugin, updateUserInfoOnLink no longer copies an unverified phoneNumber from the linked provider's profile. An existing verified number is kept.
#12198 f25081a Thanks @bytaesu! - With requireVerification, phone number password reset now works only for a verified number. No reset code is sent to an unverified number, and resetPassword returns PHONE_NUMBER_PENDING_VERIFICATION without adding or changing a password.
#12198 f25081a Thanks @bytaesu! - With the phone number plugin, a new user no longer stores a phoneNumber that was not verified. Sign-up and sign-in routes reject one sent in the request, and a number from a social profile or in data passed to createUser is dropped unless it is marked verified.
#12198 f25081a Thanks @bytaesu! - Phone number verification and password reset codes are now stored under their own namespaces, so a phone number request can no longer create, consume or delete verification codes that belong to other flows. Codes sent before the upgrade must be requested again.
#12198 f25081a Thanks @bytaesu! - Account linking and new OAuth users now count an email as verified only when the provider claim is true or the string "true", which covers generic OAuth, Cognito, and Microsoft Entra ID claims sent as strings. Any other emailVerified value, including a non-boolean value returned from mapProfileToUser such as 1, now reads as unverified.
#12198 f25081a Thanks @bytaesu! - With secondary storage, revoking all of a user's sessions or deleting the user now also ends sessions missing from the cached session list.
Updated dependencies [f25081a, f25081a, f25081a, f25081a, f25081a]:
Fixed organization and API key metadata, and OAuth proxy sign-ins with a constructor field in additionalData, failing with a prototype pollution error
better-authconstructor field in additionalData, failing with a prototype pollution error (#12142)BETTER_AUTH_SECRETS error messages to report the entry position instead of including the entry value (#12098)update-user endpoint to reject data.id with a 400 error instead of attempting to change the user's primary key (#12099)internalAdapter.createSession (#12100)hooks.before hook being dropped from the response, with the endpoint's value winning when both set the same header or cookie (#12145)useSession(useFetch) returning no session during Nuxt SSR when baseURL is inferred from the environment (#12109)genericOAuth HubSpot helper truncating access tokens with reserved characters and now returning null instead of requesting /access-tokens/undefined when no token is present (#12108)/sign-in/username and /is-username-available rejecting usernames that sign-up accepts when validationOrder.username is post-normalization (#12097)For detailed changes, see CHANGELOG
authauth init for Remix and React Router v7 to generate an app/routes/api.auth.$.ts resource route that mounts auth.handler instead of a second auth instance with an unsupported database option (#12118)auth ai overwriting MCP config files it cannot parse, such as those with comments or trailing commas, by leaving them unchanged and printing the config to add manually (#12111)auth login and auth logout re-launching the CLI through npx auth@latest in an endless loop (#12110)auth init hanging during database migration and removed a stray debug line about path aliases (#12148)For detailed changes, see CHANGELOG
@better-auth/stripe/subscription/success returning a 500 for non-string callbackURL and checkoutSessionId query values by rejecting them with a 400 (#12105)/subscription/success to validate callbackURL against trusted origins after replacing {CHECKOUT_SESSION_ID}, preventing redirects to untrusted origins via checkoutSessionId (#12102)For detailed changes, see CHANGELOG
@better-auth/api-key@upstash/redis (#12107)For detailed changes, see CHANGELOG
@better-auth/cimdinvalid_client (#12103)For detailed changes, see CHANGELOG
@better-auth/coreFor detailed changes, see CHANGELOG
Thanks to everyone who contributed to this release:
@bytaesu
Full changelog: v1.7.14...v1.7.15
#12100 7769e91 Thanks @bytaesu! - The admin plugin now rejects banned users when a session is created outside an endpoint, such as through internalAdapter.createSession.
#12099 3f17193 Thanks @bytaesu! - The admin update-user endpoint now rejects data.id with a 400 error instead of attempting to change the user's primary key.
#12145 804ba8a Thanks @bytaesu! - Headers and cookies set by a hooks.before hook that does not return early now reach the response instead of being dropped. When the endpoint sets the same header or cookie, the endpoint's value wins.
#12108 1391673 Thanks @bytaesu! - The HubSpot helper in genericOAuth now encodes the access token as a single path segment when fetching token info, so tokens containing reserved characters are no longer truncated, and it returns null instead of requesting /access-tokens/undefined when no access token is present.
#12142 f63fb0e Thanks @bytaesu! - Organization and API key metadata, and OAuth proxy sign-ins whose additionalData contains a constructor field, no longer fail with "Potential prototype pollution attempt detected".
#12098 4cdcb1c Thanks @bytaesu! - Error messages for a malformed BETTER_AUTH_SECRETS entry now report the entry position instead of including the entry value.
#12097 6e7fa27 Thanks @bytaesu! - Fixed /sign-in/username and /is-username-available rejecting a username that sign-up accepts when validationOrder.username is post-normalization. Both endpoints now validate the same value as sign-up.
#12109 264de2b Thanks @bytaesu! - Fix the Vue client's useSession(useFetch) returning no session during Nuxt SSR when baseURL is inferred from the environment.
Updated dependencies [9ef0c5b]:
Fixed two-factor TOTP to accept imported Base32 secrets stored as base32:
better-authbase32:<secret> (#12031)For detailed changes, see CHANGELOG
@better-auth/coreloginHint so the Kakao Account login page opens with the ID field prefilled (#12045)For detailed changes, see CHANGELOG
Thanks to everyone who contributed to this release:
@bytaesu, @honuuk
Full changelog: v1.7.13...v1.7.14
#12031 d2cb7f5 Thanks @bytaesu! - Two-factor TOTP now accepts imported Base32 secrets stored as base32:<secret>.
Updated dependencies [2947ab7]:
Added tokenEndpointAuth: { method } to the Cloudflare provider and deprecated tokenEndpointAuthMethod, which remains supported
better-authFor detailed changes, see CHANGELOG
@better-auth/coretokenEndpointAuth: { method } to the Cloudflare provider and deprecated tokenEndpointAuthMethod, which remains supported (#11997)For detailed changes, see CHANGELOG
@better-auth/stripeFor detailed changes, see CHANGELOG
Thanks to everyone who contributed to this release:
@allenzhou101, @bytaesu, @godwit-bo
Full changelog: v1.7.12...v1.7.13
#11985 9cb95fe Thanks @bytaesu! - Type declarations no longer list type-only exports as values, so importing one as a value now fails type checking instead of failing at runtime.
Updated dependencies [2712441, 1cf4b2c]:
> - If you use ID token sign-in with a provider that has no clientId, set clientId to every client ID your apps sign in with.
[!IMPORTANT] Action required
- If you use ID token sign-in with a provider that has no
clientId, setclientIdto every client ID your apps sign in with. (#11931)
better-authauth.api.getSession() to keep the original database error as error.cause when the session lookup fails (#11924)For detailed changes, see CHANGELOG
@better-auth/coremapProfileToUser failing to typecheck under exactOptionalPropertyTypes when it returns undefined for name, email, or image (#11918)getUserInfo to no longer receive client-submitted access tokens issued to another Facebook app, and ID tokens missing exp or iat are now rejected (#11919)cause option as a third argument to APIError.from() to keep the underlying error for server-side callers without exposing it in the response (#11924)For detailed changes, see CHANGELOG
@better-auth/mcprequireMcpAuth to accept only OAuth access tokens and reject session JWTs from the JWT plugin, even when they share the issuer and audience (#11934)For detailed changes, see CHANGELOG
@better-auth/ssoexp or iat and providers with an empty client ID, matching social sign-in (#11935)For detailed changes, see CHANGELOG
Thanks to everyone who contributed to this release:
@alpcanaydin, @bytaesu
Full changelog: v1.7.11...v1.7.12
#11925 fb48619 Thanks @bytaesu! - The JWT plugin now verifies JWTs and session cookie-cache JWTs with the algorithm of the stored key instead of the one named in the token header, and logs a warning when it signs or verifies a JWT without an issuer or audience.
#11924 681aa5c Thanks @bytaesu! - auth.api.getSession() now keeps the original database error as error.cause when the session lookup fails, so server code can tell a transient failure from a bug.
#11930 b18e3b8 Thanks @bytaesu! - OAuth callbacks completed through the OAuth proxy now run the same checks as the standard OAuth callback, including issuer and ID token nonce validation.
Updated dependencies [681aa5c, 4bc78ba, 876608d, 083a743, 492134a]:
Fixed repeated PostgreSQL migration diffs for int8 columns.
better-authint8 columns. (#10719)X-Retry-After value. (#11521)For detailed changes, see CHANGELOG
@better-auth/coreinit returns with options: undefined failing type checks under exactOptionalPropertyTypes. (#11907)<issuer>/.well-known/jwks.json. (#11884)For detailed changes, see CHANGELOG
@better-auth/oauth-provider/oauth2/consent and /oauth2/continue to match their redirect responses. (#10881)For detailed changes, see CHANGELOG
@better-auth/expoFor detailed changes, see CHANGELOG
Thanks to everyone who contributed to this release:
@aryan1306, @bytaesu, @cpojer, @gustavovalverde, @noobnooc, @rendermani, @sahiljagtap08
Full changelog: v1.7.10...v1.7.11
#10719 bd65db0 Thanks @rendermani! - Recognize PostgreSQL int8 as a valid number type in migration diffs. Kysely's introspector reports pg_type.typname, so Better Auth's own bigint columns (such as the database-backed rate limiter's lastRequest) came back as int8 and were reported as a type mismatch on every run.
#11521 37a75c9 Thanks @aryan1306! - Fix database-backed rate limiting returning an excessively large X-Retry-After header instead of the remaining seconds in the rate-limit window.
Updated dependencies [ce96569, 2f6ca3f, dfd8dd2]:
Fixed Captcha and OpenAPI plugin subpath imports and type resolution for better-auth/plugins/multi-session and better-auth/test.
better-authbetter-auth/plugins/multi-session and better-auth/test. (#11822)google as the last login method. (#11393)better-auth/plugins/one-tap failing with a not-exported error. (#11696)autoSelect and cancelOnTapOutside settings. (#11820)For detailed changes, see CHANGELOG
@better-auth/oauth-providerprivate_key_jwt clients. (#11695)client_id values to say client not found. (#11799)invalid_grant instead of invalid_client at the token endpoint. (#11176)/oauth2/userinfo, /oauth2/introspect, and /oauth2/revoke. (#11596)For detailed changes, see CHANGELOG
@better-auth/coreFor detailed changes, see CHANGELOG
@better-auth/mongo-adapterfindMany ignoring ID sorting and potentially repeating or skipping paginated results. (#11801)For detailed changes, see CHANGELOG
Thanks to everyone who contributed to this release:
@Bekacru, @breken-ai, @drewsephski, @gustavovalverde, @mahoor, @vhinayindia
Full changelog: v1.7.9...v1.7.10
#11393 eebd47a Thanks @breken-ai! - If you use the lastLoginMethod plugin with oneTap, signing in through Google One Tap now records "google", the same value as signing in with the Google button. Before, a One Tap sign-in recorded nothing: the better-auth.last_used_login_method cookie kept its previous value or stayed unset, and so did user.lastLoginMethod with storeInDatabase.
If your customResolveMethod includes a /one-tap/callback → "google" workaround, remove that mapping; keep the resolver if it handles other routes.
#11821 09d07e6 Thanks @gustavovalverde! - The Google One Tap prompt (authClient.oneTap() without button) no longer calls getSkippedReason(), which Google's FedCM migration guide says to remove. Before, it called it under any promptOptions.fedCM setting.
A skipped prompt now ends the flow and calls onPromptNotification right away instead of retrying. Google doesn't report why a prompt was skipped, and a prompt the user closed stays hidden for Google's cooldown period, so the retries could not bring it back. Dismissed prompts still retry as before.
Google Identity Services still logs its FedCM migration warning, because it does so whenever prompt() receives a listener. The plugin needs the listener to track dismissals and skips, so the warning is expected and safe to ignore.
#11819 eaecb72 Thanks @gustavovalverde! - Google One Tap now applies your socialProviders.google.mapProfileToUser and custom getUserInfo, the same as the standard Google sign-in. Before, One Tap ignored both and always stored the token's name, email, email_verified, and picture claims.
If you configured either one, users created through One Tap now get the fields it returns, including any extra fields such as a first name from given_name. Returning users are updated from it on each One Tap sign-in when socialProviders.google.overrideUserInfoOnSignIn is on, and so are existing users that One Tap links when account.accountLinking.updateUserInfoOnLink is on. Check that your mapper suits One Tap users too.
If you set socialProviders.google.overrideUserInfoOnSignIn, One Tap sign-ins now update returning users' name, image, and email from Google, as the redirect sign-in already does.
Setups that configure none of these, including oneTap({ clientId }) with no Google provider, are unaffected.
#11820 88c9a37 Thanks @gustavovalverde! - If you set autoSelect or cancelOnTapOutside on oneTapClient(), the One Tap prompt and the Sign in with Google button now use them. Before, only values passed to authClient.oneTap() took effect, so with autoSelect: true on the plugin, returning users still had to pick an account. Values passed to oneTap() still override the plugin's. Apps that set these options only on oneTap(), or not at all, are unaffected.
#11696 0cf1f7c Thanks @drewsephski! - You can now import the One Tap plugin from better-auth/plugins/one-tap, as you can for other plugins. Previously this import failed with a "not exported" error. Imports from better-auth/plugins and better-auth/client/plugins are unchanged.
#11822 414e845 Thanks @gustavovalverde! - You can now import the Captcha and OpenAPI plugins from better-auth/plugins/captcha and better-auth/plugins/open-api, as you can for other plugins. Previously these imports failed with a "not exported" error. Imports from better-auth/plugins are unchanged.
If your TypeScript config uses "moduleResolution": "node" (or node10), better-auth/plugins/multi-session and better-auth/test now resolve their types. Previously TypeScript reported that it could not find their declarations. Projects using bundler, node16, or nodenext resolution are unaffected.
Updated dependencies [fedd055, bbd0a19, 99cdfe7]:
Fixed onAPIError.onError handlers to finish before responses are sent and log failures without interrupting requests
better-authonAPIError.onError handlers to finish before responses are sent and log failures without interrupting requests (#11766)For detailed changes, see CHANGELOG
@better-auth/oauth-providerisContinuation to postLogin.shouldRedirect so users can complete authorization after selecting an organization (#11185)For detailed changes, see CHANGELOG
Thanks to everyone who contributed to this release:
@bytaesu, @johanneskares
Full changelog: v1.7.8...v1.7.9
#11766 6edaa61 Thanks @bytaesu! - An onAPIError.onError handler that throws or rejects no longer fails the request or causes an unhandled promise rejection. The error is logged and the original error response is returned. Async handlers now finish before the response is sent.
Updated dependencies []:
Aligned cookie security attributes with RFC 6265bis
better-authcustomSession sessions expire or are revoked (#10591)customSession treating session lookup errors as signed-out users (#11391)generateId: "uuid" (#11625)@better-auth/utils and better-call dependency versions across official packages (#11512)lastLoginMethod sign-in failures when cookieName or maxAge is explicitly undefined (#11549)oauthProvider() or mcp() with exactOptionalPropertyTypes (#10266)skipLibCheck: false (#11637)verifyOTP callback (#10698)For detailed changes, see CHANGELOG
@better-auth/coreAsyncLocalStorage initialized after importing Better Auth but before first use, and corrected misleading errors for invalid runtime-provided values in edge and browser fallbacks. (#11712)alg (#11663)generateId: "uuid" (#11625)@better-auth/utils and better-call dependency versions across official packages (#11512)For detailed changes, see CHANGELOG
@better-auth/oauth-provideradminUpdateOAuthClient (#11654)adminCreateOAuthClient (#11655)adminCreateOAuthResource and configured resources (#11655)clientId to clientPrivileges checks for actions on existing OAuth clients (#11658)generateId: "uuid" (#11625)@better-auth/utils and better-call dependency versions across official packages (#11512)oauthProvider() or mcp() with exactOptionalPropertyTypes (#10266)For detailed changes, see CHANGELOG
@better-auth/sso@better-auth/utils and better-call dependency versions across official packages (#11512)mapping values that omit defaulted fields (#11378)callbackUrl (#11743)For detailed changes, see CHANGELOG
@better-auth/scimexternalId (#11167)@better-auth/utils and better-call dependency versions across official packages (#11512)409 instead of 500 when a unique value is already claimed (#11669)null (#11638)For detailed changes, see CHANGELOG
@better-auth/mongo-adapter@better-auth/utils and better-call dependency versions across official packages (#11512)For detailed changes, see CHANGELOG
@better-auth/drizzle-adapter@better-auth/utils and better-call dependency versions across official packages (#11512)For detailed changes, see CHANGELOG
@better-auth/kysely-adapter@better-auth/utils and better-call dependency versions across official packages (#11512)For detailed changes, see CHANGELOG
@better-auth/mcp@better-auth/mcp type errors with exactOptionalPropertyTypes and skipLibCheck: false (#11635)oauthProvider() or mcp() with exactOptionalPropertyTypes (#10266)For detailed changes, see CHANGELOG
@better-auth/api-key@better-auth/utils and better-call dependency versions across official packages (#11512)For detailed changes, see CHANGELOG
@better-auth/cimdFor detailed changes, see CHANGELOG
@better-auth/electron@better-auth/utils and better-call dependency versions across official packages (#11512)For detailed changes, see CHANGELOG
@better-auth/memory-adapter@better-auth/utils and better-call dependency versions across official packages (#11512)For detailed changes, see CHANGELOG
@better-auth/passkey@better-auth/utils and better-call dependency versions across official packages (#11512)For detailed changes, see CHANGELOG
@better-auth/prisma-adapter@better-auth/utils and better-call dependency versions across official packages (#11512)For detailed changes, see CHANGELOG
@better-auth/stripeFor detailed changes, see CHANGELOG
@better-auth/telemetry@better-auth/utils and better-call dependency versions across official packages (#11512)For detailed changes, see CHANGELOG
Thanks to everyone who contributed to this release:
@aryan1306, @Bekacru, @BilalAtique, @breken-ai, @bytaesu, @codewithbharat, @disbell, @drewsephski, @gustavovalverde, @heliohm, @jashkarangiya, @jonathansamines, @kaiizer777, @kdelay, @maxnze1, @nikhilgupta58, @Sandipxg, @shiminshen, @Tushar-Khandelwal-2004
Full changelog: v1.7.7...v1.7.8
#11512 4175b34 Thanks @bytaesu! - Align the installed @better-auth/utils version with better-call while accepting ^0.4.2 || ^0.5.0 across official package peers.
#11565 b1cfc1e Thanks @bytaesu! - Omit non-returned custom fields from inferred output schema types.
#11540 678c555 Thanks @bytaesu! - Align cookie security attributes with RFC 6265bis.
#10591 193efff Thanks @kdelay! - Expired or revoked sessions now clear stale cookies when using customSession.
#11625 369176e Thanks @gustavovalverde! - Fixed single-use checks for apps that set advanced.database.generateId: "uuid". Default id generation is unaffected, and no migration is needed.
private_key_jwt client authentication, and magic link or email OTP sign-ins that adopt an unverified account failed with a NOT NULL error on the id column. They now work. SIWE sign-in ignored the email field and used the wallet-derived address; it now uses the supplied email when no other account has it.With generateId: "serial", behavior is unchanged: these checks need string ids, and Better Auth now logs a warning the first time one of these flows runs.
#11391 352d04c Thanks @breken-ai! - Fix customSession treating session lookup failures as signed-out users. Server-side getSession now throws an API error, and HTTP clients receive an error response.
#11750 e9d9921 Thanks @gustavovalverde! - Generic OAuth providers configured with discoveryUrl now recover without a restart when discovery fails at startup. Since 1.7.3, a provider whose discovery request failed at boot (for example, because the identity provider was still starting) was skipped, and every sign-in returned PROVIDER_NOT_FOUND until the app restarted. Better Auth now retries discovery on the next sign-in, callback, or account-linking request for that provider, and the provider works as soon as discovery succeeds. While discovery keeps failing, sign-in and account linking still return PROVIDER_NOT_FOUND and callbacks redirect with error=oauth_provider_not_found, and each request may wait up to 10 seconds for the retry.
#11549 1bd5c37 Thanks @bytaesu! - Fix lastLoginMethod failing sign-in when cookieName or maxAge is explicitly undefined.
#11174 766cfb3 Thanks @Bekacru! - Stop double-decoding callbackURL, newUserCallbackURL and errorCallbackURL on magic link verify so percent-encoded characters in callback query params are preserved.
#11505 c46992f Thanks @bytaesu! - Preserve the referenced model and field keys when generating Kysely migrations, so custom table names that match another model key produce the intended foreign keys.
#11718 1d95ebf Thanks @bytaesu! - Fix missing device sessions and failed automatic session switching after cache eviction when storeSessionInDatabase is enabled and preserveSessionInDatabase is disabled. Automatic switching now follows the order of held sessions, and large lists or sessions whose users no longer exist no longer cause valid sessions to disappear.
#10266 c68b2cd Thanks @shiminshen! - Projects that enable exactOptionalPropertyTypes can use the oauthProvider() and mcp() plugins again. Since 1.7.0, adding either plugin to betterAuth() failed to type-check with a TS2322 error.
#11637 2627237 Thanks @gustavovalverde! - Projects using the organization plugin with skipLibCheck: false no longer get TS2536: Type '"role"' cannot be used to index type ... from crud-members.d.mts. The role returned by getActiveMemberRole is now typed as the organization's role names directly. Projects with skipLibCheck: true (the default in most templates) were unaffected.
#10866 3d1f008 Thanks @heliohm! - The organization plugin no longer pulls every zod locale into server bundles.
#11626 67743ed Thanks @gustavovalverde! - Password resets and password changes no longer keep the new password when revoking the user's sessions fails. With revokeSessionsOnPasswordReset or revokeOtherSessions, database sessions are revoked and the password is saved in one transaction when transactions are enabled for the adapter, so a failure leaves the old password and sessions in place. Sessions in secondary storage are still removed after commit, on a best-effort basis. This covers /reset-password, the email OTP and phone number reset endpoints, and /change-password. onPasswordReset now runs after sessions are revoked, so a throwing callback no longer leaves them active, and a callback that lists the user's sessions no longer sees the revoked ones.
#10698 f0ce580 Thanks @jashkarangiya! - If you set the phone number plugin's verifyOTP option, /phone-number/reset-password now checks the code with it, as /phone-number/verify already does. Before, password reset always compared the code with the one Better Auth generated, so apps that verify codes through a provider such as Twilio Verify could not reset passwords. If your sendPasswordResetOTP sends the code Better Auth generates, make sure verifyOTP accepts that code. Apps that don't set verifyOTP are unaffected.
#11646 07a0938 Thanks @gustavovalverde! - A failed password reset no longer spends the reset link or OTP. /reset-password, /email-otp/reset-password and /phone-number/reset-password now check the token or code without consuming it, validate and hash the new password, then consume it in the same transaction as the session revocation and password write. A rejected password, such as one refused by haveIBeenPwned, always leaves the link or OTP usable. A later failure, such as a failed session revocation or password write, also leaves it usable when the adapter's transactions are enabled and verification values are stored in the database (the default without secondary storage, or verification.storeInDatabase: true). Wrong codes still count against the OTP attempt limit.
#11643 92dfcea Thanks @gustavovalverde! - A sign-up that fails after its session is created no longer leaves that session in secondary storage. With storeSessionInDatabase enabled and preserveSessionInDatabase off, the secondary-storage copy is written only after the sign-up commits, and listing a user's sessions now reads the database, so a session whose cached copy failed to write is still listed and revoked. With other secondary-storage settings, sign-up, passkey registration and SSO sign-in with resolveUser keep the session write inside their transaction, so a storage failure rolls back the new user, passkey or account instead of keeping them without a session. A session revoked by a session.create.after database hook also stays revoked.
#11488 e15625f Thanks @Bekacru! - SvelteKit 3 projects can now install Better Auth without --legacy-peer-deps. The @sveltejs/kit peer range now includes ^3.0.0; SvelteKit 2 projects are unaffected.
Updated dependencies [4175b34, 435645e, 369176e, 0cfe07d, 9904b29, e78f15a, 60525e0, 8133265, ea85d13, 916ef5c, 1d95ebf, 6214610, 67743ed, c46d2a6, 92dfcea, a9f455d, 9725f1b]:
Fixed a critical Magic Link account-takeover vulnerability.
better-authMagic Link upgrade: Upgrade servers sharing verification storage together, request new Magic Links, and restart pending OAuth/SAML sign-ins. No database migration is required. See the critical advisory for affected configurations and custom storage changes.
disableSignUp setting. (#11491)Content-Type header. (#11476)Content-Type header. (#11469)For detailed changes, see CHANGELOG
@better-auth/oauth-providervalidateRedirectUri validation for trusted deployments with dynamic OAuth redirect URIs. (#8686)verifyOAuthQueryParams to verify signed authorization queries before rendering a custom consent page. (#11402)For detailed changes, see CHANGELOG
@better-auth/drizzle-adapterFor detailed changes, see CHANGELOG
@better-auth/kysely-adapterconsumeOne deleting a record after a concurrent write invalidates its original condition. (#11495)For detailed changes, see CHANGELOG
Thanks to everyone who contributed to this release:
@aryan1306, @bytaesu, @gitmotion, @gustavovalverde, @lennondotw
Full changelog: v1.7.6...v1.7.7
#11476 4186e36 Thanks @bytaesu! - Return CAPTCHA errors with the correct JSON Content-Type header.
#11469 8620aa9 Thanks @aryan1306! - Return rate limit errors with a JSON Content-Type header.
#11491 55cb92e Thanks @bytaesu! - Respect social provider disableSignUp when signing in with an ID token.
#11375 69defbc Thanks @bytaesu! - Refresh the active organization after sign-in when a session hook selects the initial organization.
#11494 ac54bfd Thanks @gustavovalverde! - Isolate OAuth state cookies and each OAuth Proxy payload with purpose-specific encryption keys. The oAuthProxy options and supported configuration remain unchanged.
Upgrade all Better Auth nodes that handle the same cookie-backed OAuth or SAML relay-state flow together. Upgrade every OAuth Proxy participant, including production and preview or development deployments, in the same cutover. OAuth sign-in, account-linking, and cookie-backed SAML sign-in flows started before the upgrade must be restarted. Mixed old and new participants cannot exchange existing state or proxy payloads, and there is no fallback to the previous shared key.
#11494 ac54bfd Thanks @gustavovalverde! - Magic Link verification now accepts only records issued for Magic Link. Magic
Link records and database-backed OAuth or SAML state use separate verification
identifier prefixes. Links and database-backed sign-ins started before the
upgrade cannot complete; request new Magic Links and restart those sign-ins.
Upgrade servers sharing verification storage together, and update
verification.storeIdentifier.overrides rules for these flows to match the new
magic-link: and auth-state: prefixes. The link token, callback state,
endpoints, and public option types are unchanged.
Upgrade installed Better Auth adapters, plugins, and integrations released
with better-auth alongside it so participating packages use the same release
version.
Updated dependencies [35d7cd3, 07bdf7e]:
Added support for a bannedUserMessage function that receives the banned user, allowing sign-in errors to include details such as the ban reason.
better-authbannedUserMessage function that receives the banned user, allowing sign-in errors to include details such as the ban reason. (#11325)maxPasswordLength are now rejected with PASSWORD_TOO_LONG before hashing or verification. (#11324)For detailed changes, see CHANGELOG
@better-auth/kysely-adapterINTEGER PRIMARY KEY columns without AUTOINCREMENT. (#11374)For detailed changes, see CHANGELOG
@better-auth/prisma-adapterFor detailed changes, see CHANGELOG
@better-auth/coreFor detailed changes, see CHANGELOG
@better-auth/drizzle-adapterFor detailed changes, see CHANGELOG
@better-auth/memory-adapterFor detailed changes, see CHANGELOG
@better-auth/mongo-adapterFor detailed changes, see CHANGELOG
@better-auth/stripeFor detailed changes, see CHANGELOG
authcheck and check schema commands to validate your configured adapter schema on demand. (#11314)For detailed changes, see CHANGELOG
Thanks to everyone who contributed to this release:
@bytaesu, @davbrito, @rwieruch, @Smidge, @Wadiou, @XXMOHAMED012
Full changelog: v1.7.5...v1.7.6
#11325 af88385 Thanks @Wadiou! - Admin plugin bannedUserMessage can now be a function that receives the banned user, so sign-in errors can include details such as the ban reason.
#11268 2fa501c Thanks @bytaesu! - Support linking social accounts through the OAuth Proxy plugin.
#11366 d41e2ca Thanks @bytaesu! - Use targeted PRAGMA queries when a Kysely dialect cannot introspect Cloudflare D1.
#11016 3d0efa3 Thanks @davbrito! - Support Vercel BotID checks on protected authentication routes in Vercel-hosted applications.
#11333 631ac29 Thanks @bytaesu! - Preserve logical model identity when a custom model name matches another schema key.
#11324 8853419 Thanks @XXMOHAMED012! - Passwords longer than maxPasswordLength are now rejected with PASSWORD_TOO_LONG before hashing on sign-in (email, username, phone number), verify-password, change-password (currentPassword), delete-user, the two-factor endpoints that take a password, and admin create-user, matching what sign-up and password reset already did.
#11316 2ee1545 Thanks @Smidge! - Fix React hydration mismatches when a session or plugin auth query resolves before a streamed component hydrates. Preserve the server-rendered pending state during hydration, then update to the current client state without changing ordinary or computed plugin stores.
#11376 fc45d08 Thanks @bytaesu! - Prevent older auth-query responses from replacing newer results when requests overlap.
Updated dependencies [41b7dc1, d41e2ca, 631ac29, 2b13e01]:
Added database.schemaName support for direct PostgreSQL connections.
better-authdatabase.schemaName support for direct PostgreSQL connections. (#11203)better-sqlite3 peer dependency to prevent installation conflicts. (#11209)For detailed changes, see CHANGELOG
@better-auth/coredatabase.schemaName support for direct PostgreSQL connections. (#11203)For detailed changes, see CHANGELOG
@better-auth/cimdFor detailed changes, see CHANGELOG
@better-auth/drizzle-adapterFor detailed changes, see CHANGELOG
@better-auth/kysely-adapterdatabase.schemaName support for direct PostgreSQL connections. (#11203)For detailed changes, see CHANGELOG
Thanks to everyone who contributed to this release:
@bytaesu, @dshukertjr, @siam923
Full changelog: v1.7.4...v1.7.5
#11283 e56c45b Thanks @bytaesu! - Log Cloudflare Turnstile error codes and binding mismatches on the server so CAPTCHA verification failures can be diagnosed.
#11209 8d37cc3 Thanks @siam923! - Remove the unused optional better-sqlite3 peer dependency to prevent installation conflicts.
#11272 348fc26 Thanks @bytaesu! - Use MySQL's reported byte lengths when validating indexes on existing string columns.
#11203 cb627eb Thanks @dshukertjr! - Add a database.schemaName option for direct PostgreSQL connections. When set, the adapter and the CLI qualify every statement with that schema, so auth generate writes a schema-qualified migration that creates the schema before its tables instead of relying on the connection's search_path.
#11270 133f6a2 Thanks @bytaesu! - Prevent PostgreSQL migrations from treating tables in other schemas or views in the active schema as Better Auth tables.
Updated dependencies [e18bc83, cb627eb, dae97ed]:
Added experimental.instrumentation.enabled to disable OpenTelemetry span creation per auth instance.
better-authexperimental.instrumentation.enabled to disable OpenTelemetry span creation per auth instance. (#11224)testUtils auth helpers. (#11217)For detailed changes, see CHANGELOG
@better-auth/coreexperimental.instrumentation.enabled to disable OpenTelemetry span creation per auth instance. (#11224)For detailed changes, see CHANGELOG
@better-auth/expoFor detailed changes, see CHANGELOG
@better-auth/drizzle-adapterFor detailed changes, see CHANGELOG
@better-auth/test-utilsFor detailed changes, see CHANGELOG
Thanks to everyone who contributed to this release:
@bytaesu, @onmax
Full changelog: v1.7.3...v1.7.4
#11205 3f890eb Thanks @bytaesu! - Support Vitest 5 in the testing utilities while retaining support for previously supported Vitest versions.
#11224 c1756a2 Thanks @bytaesu! - Add experimental.instrumentation.enabled to disable Better Auth OpenTelemetry span creation per auth instance. Instrumentation remains enabled by default and independent of usage reporting.
#11217 9b9638e Thanks @onmax! - Allow testUtils auth helpers to accept additional session fields through the session option, including required fields without defaults and per-session overrides of configured defaults.
Updated dependencies [3ff842a, b905bfe, c1756a2]:
The legacy /oauth-proxy-callback endpoint is deprecated and will be removed in the next minor release.
Upgrading from 1.7.0–1.7.2:
We restored the 1.6 account core schema to avoid requiring a disruptive backfill for existing users. We recognize the cost to users who already migrated and are committed to keeping the core schema stable throughout v1.
If you applied the 1.7 issuer schema, follow the upgrade guide for the required cleanup. No backfill is needed.
better-authisPasswordCompromised for checking passwords against Have I Been Pwned in custom server-side flows. (#11147)getSession failures when cookie caching is disabled and cached session cookies remain. (#11120)useFetch. (#11084)useFetch integration for the Vue client's useSession hook. (#11085)(providerId, accountId) instead of issuer. (#11153)For detailed changes, see CHANGELOG
@better-auth/coreconsumeOne and incrementOne methods for custom database adapters. (#11189)clientKey and clientSecret options. (#11102)(providerId, accountId) instead of issuer. (#11153)For detailed changes, see CHANGELOG
authauth info to report installed dependency versions instead of declared specifiers. (#11126)auth init to complete when generated setup groups have no dependencies. (#11140)auth upgrade with a clear warning. (#11127)For detailed changes, see CHANGELOG
@better-auth/drizzle-adapterFor detailed changes, see CHANGELOG
@better-auth/test-utilsFor detailed changes, see CHANGELOG
@better-auth/cimdERR_INVALID_IP_ADDRESS on supported Node.js versions. (#10730)For detailed changes, see CHANGELOG
@better-auth/expoFor detailed changes, see CHANGELOG
@better-auth/kysely-adapterFor detailed changes, see CHANGELOG
@better-auth/oauth-providerlocalhost loopback redirects to use ephemeral callback ports. (#11090)For detailed changes, see CHANGELOG
@better-auth/prisma-adapterFor detailed changes, see CHANGELOG
@better-auth/sso(providerId, accountId) instead of issuer. (#11153)For detailed changes, see CHANGELOG
Thanks to everyone who contributed to this release:
@BetterAndBetterII, @bytaesu, @erikpr1994, @gustavovalverde, @harshil1712, @onmax, @Salman-Arshad, @starslingdev[bot], @supercell02, @thisismert
Full changelog: v1.7.2...v1.7.3
#11060 3660f06 Thanks @bytaesu! - Handle malformed custom-scheme callback URLs without excessive processing.
#11037 5bd7096 Thanks @bytaesu! - Prevent repeated TOTP enrollment from replacing an active authenticator and its backup codes.
#11120 7ec7146 Thanks @onmax! - Prevent getSession from failing when cookie caching is disabled while clients still have cached session cookies.
#9908 76d311f Thanks @harshil1712! - Add Cloudflare as a built-in social provider, with support for client-secret authentication and PKCE clients without a secret.
#11188 c47b765 Thanks @bytaesu! - Normalize Auth0 domains without a potentially slow trailing-slash regular expression.
#11084 2d5c63d Thanks @bytaesu! - Prevent duplicate session requests and hydration mismatches when using the Vue client with Nuxt useFetch.
#11147 a9d8c12 Thanks @bytaesu! - Add isPasswordCompromised for checking passwords against Have I Been Pwned in custom server-side flows, while ignoring padded response entries with zero occurrences.
#10988 9fc7498 Thanks @bytaesu! - Run callback hooks after proxied OAuth sign-ins and preserve server state when callback cookies are unavailable. The legacy /oauth-proxy-callback endpoint is deprecated and will be removed in the next minor release.
#11178 be0e007 Thanks @bytaesu! - Report missing tables, missing columns, and required columns Better Auth never writes during initialization, with guidance for fixing them. Kysely checks the live database schema. Authentication requests await the same check and are rejected if the schema does not match.
Validation is enabled by default, including in production. Set advanced.database.validateSchema: false to disable runtime validation. auth migrate refuses to apply changes when required unwritten columns need manual repair.
#11069 0bb0dbf Thanks @bytaesu! - Improve dynamic organization role permission check performance.
#11153 2220ee7 Thanks @bytaesu! - Restore sign-in compatibility with 1.6 databases by identifying accounts with (providerId, accountId) and removing the issuer requirement introduced in 1.7.0. Upgrading from 1.6 no longer requires an account schema migration. Ambiguous account keys are rejected instead of selecting an arbitrary account.
If you applied the 1.7.0 through 1.7.2 account schema, remove its issuer unique index before upgrading. For SQL databases, also make issuer nullable or remove the column so sign-ups and account linking can succeed. auth migrate does not perform this cleanup. Follow the upgrade guide for database-specific steps.
#10978 5fe5bc2 Thanks @BetterAndBetterII! - Skip a generic OAuth provider when discovery fails instead of taking down the rest of the auth API.
#10963 74a7369 Thanks @thisismert! - Track email OTP sign-ins in the last login method plugin.
#11085 e16b40a Thanks @bytaesu! - Provide type-safe Nuxt useFetch integration for the Vue client's useSession hook.
#11066 c0444dc Thanks @bytaesu! - Upgrade the packaged Zod dependency to 4.5. Generated OpenAPI schemas now mark required request fields consistently with runtime validation, including passkey registration responses.
Updated dependencies [352d012, 76d311f, 3e9e197, 157ec8d, baa08f4, 9e36635, be0e007, a2bae0c, 1a1b7d5, 2220ee7]:
Fixed permanent user bans to clear expiration dates from previous temporary bans.
better-auth~ in relative callback URLs validated by trusted-origin checks. (#10041)Referrer-Policy: no-referrer while continuing to reject untrusted origins. (#10959)getTestInstance performance with a faster default password hasher. (#10879){identifier}@{namespace}.placeholder.invalid format. (#10982)For detailed changes, see CHANGELOG
@better-auth/core{identifier}@{namespace}.placeholder.invalid format. (#10982)For detailed changes, see CHANGELOG
@better-auth/oauth-providerFor detailed changes, see CHANGELOG
@better-auth/drizzle-adapterusePlural is enabled. (#10941)where clauses. (#10859)For detailed changes, see CHANGELOG
@better-auth/kysely-adapterFor detailed changes, see CHANGELOG
@better-auth/ssoFor detailed changes, see CHANGELOG
Thanks to everyone who contributed to this release:
@bytaesu, @GautamBytes, @heliohm, @sosyz, @starslingdev[bot]
Full changelog: v1.7.1...v1.7.2
#10875 d5d889b Thanks @bytaesu! - Fix programmatic migrations failing on Cloudflare D1 while preserving existing-index validation across supported databases.
#10982 b4ad5a1 Thanks @bytaesu! - Built-in placeholder emails now consistently use the namespaced {identifier}@{namespace}.placeholder.invalid format.
#10934 c7a5c1a Thanks @bytaesu! - Cookie-cache reads now warn when signed session data is invalid instead of silently appearing as a signed-out session.
#10879 78f0c39 Thanks @starslingdev! - Test suites using getTestInstance now run faster because the shared fixture avoids production password-hashing costs by default. Custom emailAndPassword.password implementations continue to take precedence.
#10823 ce8a3ab Thanks @sosyz! - Ensure permanently banning a user clears any expiration from a previous temporary ban.
#10907 a021eaf Thanks @heliohm! - A client created with more plugins is again assignable to a client type declaring fewer plugins, as in 1.6.
#10959 c8dcfa5 Thanks @bytaesu! - Allow same-origin form submissions from pages using Referrer-Policy: no-referrer while continuing to reject untrusted request origins.
#10979 fced1a5 Thanks @bytaesu! - Allow relative callback and redirect URLs to use standard path, query, and fragment syntax while preserving open-redirect protections.
#10041 f6891a2 Thanks @GautamBytes! - Allow ~ in relative callback URLs validated by trusted origin checks.
#10877 649818a Thanks @bytaesu! - Prevent disabled MyISAM indexes from satisfying migration index checks.
Updated dependencies [557e19b, 64da15b, d5d889b, b4ad5a1, ea77118, 5aea9f7, fced1a5, e1d4011]:
Added native database transaction support to test instances for PostgreSQL and MySQL.
better-authjose, nanostores, noble crypto packages, SimpleWebAuthn) to their latest compatible releases, with no changes required to existing projects.For detailed changes, see CHANGELOG
@better-auth/scimactive and the primary sub-attribute of emails, phoneNumbers, addresses, roles, and entitlements at the HTTP ingress, improving Microsoft Entra interoperability.managedConnections to allow trusted server code to create runtime tenant connections and issue, rotate, and revoke bearer credentials through server-only auth.api methods, without a code-defined connection or an application-owned verifier.For detailed changes, see CHANGELOG
@better-auth/ssowantAssertionsSigned now correctly controls whether the SP requires signed assertions, matching real-world IdP signing behavior.For detailed changes, see CHANGELOG
@better-auth/cimds-maxage over max-age and Expires, honors s-maxage=0, conditionally revalidates with ETag or Last-Modified, and treats invalid or duplicate freshness directives as immediately stale. Concurrent refreshes now converge on a single client-resource link instead of failing on a unique constraint.For detailed changes, see CHANGELOG
@better-auth/kysely-adapternode:sqlite, bun:sqlite, mysql2, pg) passed directly as database, matching the behavior of the explicit { db }/{ dialect } config shapes. Plugins requiring native transactions (such as @better-auth/scim) now work correctly when using the quickstart database: new Database(...) form.For detailed changes, see CHANGELOG
@better-auth/oauth-provider403 with an RFC 6750 insufficient_scope WWW-Authenticate challenge naming every missing scope, allowing clients to request all needed scopes in a single authorization request.For detailed changes, see CHANGELOG
authFor detailed changes, see CHANGELOG
Thanks to everyone who contributed to this release:
@gustavovalverde
Full changelog: v1.7.0...v1.7.1
#10863 845bbd1 Thanks @gustavovalverde! - auth migrate no longer attempts to add a required column with no default value to a table that already has rows. It stops with an error naming the column and the backfill to run first. Previously the generated statement failed on SQLite, Postgres, and SQL Server; on MySQL it filled the new column with an empty string for every existing row and reported success. If auth migrate already ran against a MySQL database on 1.7, run the check in the upgrade guide's account identity section.
getMigrations throws the new UnsafeMigrationError (exported from better-auth/db/migration) for this refusal, so callers can distinguish it from other migration errors such as an index-definition conflict.
auth generate still emits the statements for external migration tooling, with a comment banner naming any column that needs a manual backfill first.
A required field whose database column is still nullable logs a warning instead of blocking the migration.
A CLI command that fails now prints its error and exits with a non-zero code instead of an unhandled promise rejection.
Updated dependencies []:
Removed the deprecated oidcProvider plugin
Blog post: Better Auth 1.7
better-authexperimental into the stable advanced.database.joins option (#10359)
Migration: Replace
experimental: { joins: true }withadvanced: { database: { joins: true } }. Drizzle and Prisma users should regenerate their schema (npx auth@latest generate) so it includes the required relations.
(issuer, accountId) (#10403)
Migration: Accounts now require
Account.issuer. Read provider identity fromaccountInfo.account.accountId, dropmapping.idfrom SSO configs, and give themicrosoftEntraIdhelper a concrete tenant GUID. Apply the account-identity backfill in the 1.7 upgrade guide before deploying.
Migration: Replace partial paths such as
/sign-inwith explicit wildcards like/sign-in/*or/sign-in/**.
@better-auth/mcp package built on the OAuth provider (#9992)
Migration: Install
@better-auth/mcpand@better-auth/cimd, add the now-requiredjwt()plugin, and move options nested underoidcConfigto flatmcp({ ... })options. RenamewithMcpAuthtorequireMcpAuthandmcpHandlertocreateMcpProtectedRequestHandler. Regenerate the schema (npx auth migrate):oauthApplicationbecomesoauthClient, plus newoauthRefreshTokenandoauthClientAssertiontables.
Migration: Introspecting an access token whose session has ended now returns
{ active: false }, and/oauth2/userinforejects it. Clients opt into notifications by registeringbackchannel_logout_uri. Run the schema migration for the newoauthClientandoauthAccessTokencolumns.
Migration:
validAudiencesis removed: move each resource identifier intoresourcesand link restricted clients throughoauthClientResource.@better-auth/mcpnow requires an explicitresource. Runnpx @better-auth/cli generateand apply the migration before deploying.
Migration: SCIM configuration, client APIs, database schema, and the Group model are all replaced, and provisioning state cannot migrate in place. Follow the SCIM cutover in the 1.7 upgrade guide, including a full directory reprovision, before resuming traffic.
enableTwoFactor response (#9057)
Migration:
enableTwoFactornow returns amethodfield ("otp"or"totp"); narrow on it before readingtotpURIandbackupCodes. Passmethod: "otp"for OTP enrollment, which requiresotpOptions.sendOTP.
Host by default when using a dynamic baseURL (#9134)
Migration: If your proxy exposes the public hostname only through
x-forwarded-host, setadvanced.trustedProxyHeaders: true. Deployments where the proxy rewritesHost(nginx default, Vercel, Cloudflare, Netlify) are unaffected.
deviceCode and userCode columns (#10059)
Migration: Resolve duplicate code values before applying the migration. MySQL and SQL Server installations must also convert both columns to bounded strings and clean up values longer than 191 characters.
Migration: Upgrade the
@better-auth/electronclient and server together and add your app's scheme totrustedOrigins. Thecode_challenge_methodparameter anddisableOriginOverrideoption are removed, and host-bearing custom-scheme entries now match that host exactly.
oid claim (#10204)
Migration: Migrate existing Microsoft account rows created from
subbefore upgrading. Tokens without a validoidare rejected.
Migration: Configure
oneTap({ clientId })orsocialProviders.google.clientId.
oidcProvider plugin (#10031)
Migration: Move OIDC authorization-server integrations to
@better-auth/oauth-provider.
Migration: Replace
signIn.oauth2({ providerId })withsignIn.social({ provider }),oauth2.link()withlinkSocial(), and dropgenericOAuthClient(). Callbacks move to/api/auth/callback/:id,pkcenow defaults totrue, andissuerandrequireIssuerValidationare removed in favor of OIDC discovery.
oauthDeviceAuthorization() (#10746)
Migration: The OAuth integration replaces the optional
resourcecolumn withoauthClientIdandresources, so regenerate and apply the schema. Let pending device codes expire before upgrading from an earlier 1.7 prerelease.
id_tokens with a single shared verifier (#9828)
Migration: Custom
UpstreamProviderimplementations replace the removedverifyIdTokenmethod with anidTokenconfig carrying a JWKS source, issuer, and audience. PayPal clientid_tokensign-in now returnsID_TOKEN_NOT_SUPPORTED; its redirect flow is unchanged.
clientAssertion support to the Microsoft Entra ID social provider (#9898)Auth instance directly fetchable (#9431)requireEmailVerification for social sign-in (#9929)user.validateUserInfo gate for rejecting an identity before a user is created or linked (#9864)hydrateSession so useSession returns server-fetched data on the first render (#8733)allowIdpInitiated support for IdP-initiated flows through a secure server-side bounce (#9301)signOut() can also sign users out of the OpenID provider (#9368)refreshTokenParams for forwarding extra parameters on generic OAuth token refresh (#9948)id_tokens against the provider JWKS and enabled id_token sign-in for generic OAuth (#9966)at_hash claim to ID tokens issued alongside an access token, per OIDC Core §3.1.3.6 (#9079)private_key_jwt client authentication for token endpoint requests (RFC 7523) (#8836)Cache-Control: no-store on every OAuth response that carries credentials (#10065)additionalParams and loginHint across signIn.social, linkSocial, and signIn.sso (#9305)userId and organizationId to the listUserTeams API (#8977)organization.getOrganization() for metadata-only fetches (#10397)consumePhoneNumberOTP API for custom phone OTP flows (#9766)displayUsername field (#10330)drizzle-kit peer dependency range (#10299)auth migrate to add required columns with static defaults and nullable unique columns to existing tables (#10293)nonce to the authorization request in the generic OAuth redirect flow (#10095)redirect_uri from the per-request base URL in multi-host deployments (#10127)account.scope values across re-authentication and token refresh (#10128)overrideUserInfo returns null (#10124)secondaryStorage (#9969)createAuthClient (#10505)For detailed changes, see CHANGELOG
@better-auth/oauth-provider@better-auth/mcp package built on the OAuth provider (#9992)
Migration: Install
@better-auth/mcpand@better-auth/cimd, add the now-requiredjwt()plugin, and move options nested underoidcConfigto flatmcp({ ... })options. RenamewithMcpAuthtorequireMcpAuthandmcpHandlertocreateMcpProtectedRequestHandler. Regenerate the schema (npx auth migrate):oauthApplicationbecomesoauthClient, plus newoauthRefreshTokenandoauthClientAssertiontables.
Migration: Introspecting an access token whose session has ended now returns
{ active: false }, and/oauth2/userinforejects it. Clients opt into notifications by registeringbackchannel_logout_uri. Run the schema migration for the newoauthClientandoauthAccessTokencolumns.
Migration: Add
applicationTypeand nullableclientDiscoveryIdcolumns, deduplicate existing(clientId, resourceId)links before the new compound unique index, then drop the legacytypeandpubliccolumns. ReplaceclientCredentialGrantDefaultScopeswith per-clientclientCredentialsScopes, backfilling every client to[]and reassigning approved machine scopes after an audit.mcp()no longer enables unauthenticated DCR: compose it withcimd()or enable both DCR flags explicitly.
max_age authorization request parameter (#9936)
Migration: Users who authenticated longer ago than the requested
max_ageare now sent back to log in, and the ID token'sauth_timereflects the fresh login. Flows that relied onmax_agebeing ignored will prompt again.
Migration:
customIdTokenClaims, extension claims, and per-issuanceidTokenClaimscan no longer set protocol claims such as issuer, subject, audience,nonce,auth_time,acr,amr, orazp; use namespaced custom claims instead. ID tokens now carryacr: "0"and discovery advertises only"0".
Migration:
validAudiencesis removed: move each resource identifier intoresourcesand link restricted clients throughoauthClientResource.@better-auth/mcpnow requires an explicitresource. Runnpx @better-auth/cli generateand apply the migration before deploying.
Migration: Remove
grantTypefromprovider.authenticateClient(...), and return{ clientId, confirmation? }from a customOAuthClientAuthenticationStrategy.authenticateinstead of a client record.
Migration: Token and refresh requests may only narrow the authorization's
resource; a broader request returnsinvalid_target.customAccessTokenClaimsnow receives aresourcesarray in place of theresourcestring. Run the schema migration to add the new resource columns.
Migration: Authorization errors now redirect to a registered client's trusted redirect URI with
stateandissinstead of rendering the server error page, and confidential clients must use their registeredtoken_endpoint_auth_method.
Migration: Replace
signIn.oauth2({ providerId })withsignIn.social({ provider }),oauth2.link()withlinkSocial(), and dropgenericOAuthClient(). Callbacks move to/api/auth/callback/:id,pkcenow defaults totrue, andissuerandrequireIssuerValidationare removed in favor of OIDC discovery.
oauthDeviceAuthorization() (#10746)
Migration: The OAuth integration replaces the optional
resourcecolumn withoauthClientIdandresources, so regenerate and apply the schema. Let pending device codes expire before upgrading from an earlier 1.7 prerelease.
@better-auth/cimd Client ID Metadata Document plugin (#9159)at_hash claim to ID tokens issued alongside an access token, per OIDC Core §3.1.3.6 (#9079)sessionId to id_token claim contributors (#10113)silenceWarnings option and the well-known endpoint warnings it suppressed (#10703)private_key_jwt client authentication for token endpoint requests (RFC 7523) (#8836)Cache-Control: no-store on every OAuth response that carries credentials (#10065)aud of private_key_jwt client assertions (#10811)offline_access without PKCE (#10153)401 invalid_token challenge from /oauth2/userinfo for invalid tokens (#10068)POST support and confirmation pages (#10812)acr claim requests per OIDC Core (#10790)profile and email scope claims on the UserInfo response instead of ID tokens (#10152)private_key_jwt jti single-use atomic across processes (#9964)redirect_uri conditional at the token endpoint, required only when the authorization included one (#10159)response_type to the verified client redirect URI (#10149)invalid_grant and revoked tokens issued from that code (#10150)unsupported_token_type when revoking a JWT access token (#9970)openid scope for authorization requests that use the claims parameter (#10791)invalid_grant when a client presents a refresh token issued to another client (#10154)403 with an RFC 6750 insufficient_scope challenge naming every one of them, so clients can request them in a single authorization redirect.For detailed changes, see CHANGELOG
@better-auth/coreexperimental into the stable advanced.database.joins option (#10359)
Migration: Replace
experimental: { joins: true }withadvanced: { database: { joins: true } }. Drizzle and Prisma users should regenerate their schema (npx auth@latest generate) so it includes the required relations.
(issuer, accountId) (#10403)
Migration: Accounts now require
Account.issuer. Read provider identity fromaccountInfo.account.accountId, dropmapping.idfrom SSO configs, and give themicrosoftEntraIdhelper a concrete tenant GUID. Apply the account-identity backfill in the 1.7 upgrade guide before deploying.
Migration: SCIM configuration, client APIs, database schema, and the Group model are all replaced, and provisioning state cannot migrate in place. Follow the SCIM cutover in the 1.7 upgrade guide, including a full directory reprovision, before resuming traffic.
oid claim (#10204)
Migration: Migrate existing Microsoft account rows created from
subbefore upgrading. Tokens without a validoidare rejected.
id_tokens with a single shared verifier (#9828)
Migration: Custom
UpstreamProviderimplementations replace the removedverifyIdTokenmethod with anidTokenconfig carrying a JWKS source, issuer, and audience. PayPal clientid_tokensign-in now returnsID_TOKEN_NOT_SUPPORTED; its redirect flow is unchanged.
clientAssertion support to the Microsoft Entra ID social provider (#9898)requireEmailVerification for social sign-in (#9929)user.validateUserInfo gate for rejecting an identity before a user is created or linked (#9864)allowIdpInitiated support for IdP-initiated flows through a secure server-side bounce (#9301)signOut() can also sign users out of the OpenID provider (#9368)refreshTokenParams for forwarding extra parameters on generic OAuth token refresh (#9948)includeGrantedScopes option to the Google provider (#10129)private_key_jwt client authentication for token endpoint requests (RFC 7523) (#8836)Cache-Control: no-store on every OAuth response that carries credentials (#10065)additionalParams and loginHint across signIn.social, linkSocial, and signIn.sso (#9305)client_id SSRF checks through the shared host classifier, which now rejects IPv4-compatible IPv6, the 6to4 relay prefix, and site-local addresses (#10126)redirect_uri from the per-request base URL in multi-host deployments (#10127)account.scope values across re-authentication and token refresh (#10128)createAuthClient (#10505)For detailed changes, see CHANGELOG
@better-auth/sso(issuer, accountId) (#10403)
Migration: Accounts now require
Account.issuer. SSO subjects are protocol-defined (subfor OIDC, signedNameIDfor SAML) andmapping.idis removed; a manual SAML config without metadata XML must setidpMetadata.entityID. Apply the account-identity backfill in the 1.7 upgrade guide before deploying.
Migration:
getSSOProvider,listSSOProviders, andupdateSSOProvidernow always returnsamlConfig.certificateas an array, so drop anyArray.isArraybranching. Registration rejects SAML configs with no signing-cert source withCERT_SOURCE_MISSING.
validateUserInfo source contract so it cannot be bypassed or spoofed (#9940)
Migration:
createUsernow fails closed whenvalidateUserInfois configured but no endpoint context or provisioning source is available. Read SSO metadata fromsource.ssoinstead ofsource.oauth, and handle thesource.methodvaluessso-oidcandsso-saml.
InResponseTo, audience restriction, and SessionIndex (#9055)
Migration:
allowIdpInitiatednow defaults tofalse. Setsaml.allowIdpInitiated: trueto keep accepting unsolicited SAML responses.
spMetadata optional, and fixed Single Logout (#9117)
Migration: Point your IdP's ACS URL at
/sso/saml2/sp/acs/:providerId;/sso/saml2/callback/:providerIdis removed.callbackUrlis now the post-auth redirect only, and the unuseddecryptionPvk,additionalParams,idpMetadata.entityURL, andidpMetadata.redirectURLfields are gone.
user.validateUserInfo gate for rejecting an identity before a user is created or linked (#9864)allowIdpInitiated support for IdP-initiated flows through a secure server-side bounce (#9301)private_key_jwt client authentication for token endpoint requests (RFC 7523) (#8836)additionalParams and loginHint across signIn.social, linkSocial, and signIn.sso (#9305)resolveUser to SAML sign-ins and hardened the provider lifecycle (#10621)additionalFields support on ssoProvider (#9445)wantAssertionsSigned now controls whether signed assertions are required rather than signed response messages, matching how IdPs sign SAML responses in practice.For detailed changes, see CHANGELOG
@better-auth/scimMigration: SCIM configuration, client APIs, database schema, and the Group model are all replaced, and provisioning state cannot migrate in place. Follow the SCIM cutover in the 1.7 upgrade guide, including a full directory reprovision, before resuming traffic.
Migration: Define connections statically, resolve them with
authentication.verifyBearerToken, or use the optionalmanagedConnectionscatalog, and connect SCIM resources to users and roles through identity and projection callbacks. Legacy SCIM state is not migrated: back it up, issue new credentials, and fully reprovision Users and Groups.
Migration: The legacy connection management endpoints and
providerOwnershipare gone, so authorize SCIM administration in your own application. LegacyscimProviderrows and credentials are not migrated: follow the 1.7 SCIM upgrade guide, issue new credentials, and reprovision Users and Groups.
user.validateUserInfo gate for rejecting an identity before a user is created or linked (#9864)acquireActiveSCIMUserLink for transaction-safe authentication of provisioned users (#10474)active and the primary sub-attribute of emails, phoneNumbers, addresses, roles, and entitlements at the HTTP ingress, for Microsoft Entra interoperability.managedConnections so trusted server code can create runtime tenant connections and issue, rotate, and revoke their bearer credentials through server-only auth.api methods, without a code-defined connection or an application-owned verifier.For detailed changes, see CHANGELOG
@better-auth/mcp ✨@better-auth/mcp package built on the OAuth provider (#9992)
Migration: Install
@better-auth/mcpand@better-auth/cimd, add the now-requiredjwt()plugin, and move options nested underoidcConfigto flatmcp({ ... })options. RenamewithMcpAuthtorequireMcpAuthandmcpHandlertocreateMcpProtectedRequestHandler. Regenerate the schema (npx auth migrate):oauthApplicationbecomesoauthClient, plus newoauthRefreshTokenandoauthClientAssertiontables.
Migration: Add
applicationTypeand nullableclientDiscoveryIdcolumns, deduplicate existing(clientId, resourceId)links before the new compound unique index, then drop the legacytypeandpubliccolumns. ReplaceclientCredentialGrantDefaultScopeswith per-clientclientCredentialsScopes, backfilling every client to[]and reassigning approved machine scopes after an audit.mcp()no longer enables unauthenticated DCR: compose it withcimd()or enable both DCR flags explicitly.
Migration:
mcp()now requires an explicitresourceidentifier, for exampleresource: "https://api.example.com/mcp".validAudiencesis removed: move each resource identifier intoresources. Runnpx @better-auth/cli generateand apply the migration before deploying.
For detailed changes, see CHANGELOG
@better-auth/electronMigration: Upgrade the
@better-auth/electronclient and server together and add your app's scheme totrustedOrigins. Thecode_challenge_methodparameter anddisableOriginOverrideoption are removed, and host-bearing custom-scheme entries now match that host exactly.
Migration: Replace
signIn.oauth2({ providerId })withsignIn.social({ provider }),oauth2.link()withlinkSocial(), and dropgenericOAuthClient(). Callbacks move to/api/auth/callback/:id,pkcenow defaults totrue, andissuerandrequireIssuerValidationare removed in favor of OIDC discovery.
createAuthClient (#10505)For detailed changes, see CHANGELOG
@better-auth/expoMigration:
getCookie()now returns a promise, and custom storage implementations must provide both synchronous and asynchronous SecureStore methods.storageAdapter.setItem()stays synchronous, so usesetItemAsync()when the write must be awaited.
Migration: Replace
signIn.oauth2({ providerId })withsignIn.social({ provider }),oauth2.link()withlinkSocial(), and dropgenericOAuthClient(). Callbacks move to/api/auth/callback/:id,pkcenow defaults totrue, andissuerandrequireIssuerValidationare removed in favor of OIDC discovery.
createAuthClient (#10505)For detailed changes, see CHANGELOG
@better-auth/stripeevent parameter of onSubscriptionCancel required (#9531)
Migration: Declare
eventas a required parameter in your callback and remove anyundefinedguards around it.
onSubscriptionCancel event parameter (#9359)
Migration:
eventis always supplied, so dropundefinedhandling from the callback.
For detailed changes, see CHANGELOG
authgrantedScopes string array (#9825)
Migration:
grantedScopesreplaces the comma-joinedaccount.scopestring with no read-time fallback, so backfill it from the existing values. The client provider contract is renamed fromOAuthProvidertoUpstreamProvider.
create-admin command for creating an initial admin user (#9547)Account.accountId alongside the required issuer (#10668)pgSchema binding so drizzle-kit can emit CREATE SCHEMA for custom PostgreSQL namespaces (#10770)resolveModule, adding support for the export default { auth } shape (#9477)account.scope storage (#10123)For detailed changes, see CHANGELOG
@better-auth/drizzle-adapterexperimental into the stable advanced.database.joins option (#10359)
Migration: Replace
experimental: { joins: true }withadvanced: { database: { joins: true } }, and regenerate the schema (npx auth@latest generate) so it includes the required relations.
relations-v2 entry point for projects using Drizzle Relations v2 (#9489)schemaName option that generates the Drizzle schema inside a pgSchema namespace (#7169)pgSchema binding so drizzle-kit can emit CREATE SCHEMA for custom PostgreSQL namespaces (#10770)For detailed changes, see CHANGELOG
@better-auth/cimd ✨Migration: Add
applicationTypeand nullableclientDiscoveryIdcolumns, deduplicate existing(clientId, resourceId)links before the new compound unique index, then drop the legacytypeandpubliccolumns. Client ID Metadata Documents preserve an omittedapplication_typeasnulland cannot assignclientCredentialsScopes. Composemcp()withcimd()for metadata-document clients.
@better-auth/cimd Client ID Metadata Document plugin (#9159)s-maxage over max-age and Expires, honors s-maxage=0, revalidates conditionally with ETag or Last-Modified, and treats invalid or duplicate freshness directives as immediately stale. Concurrent refreshes converge on one client-resource link instead of failing on its unique constraint.For detailed changes, see CHANGELOG
@better-auth/api-keyMigration: Custom adapters must implement native
consumeOneandincrementOne, secondary storage needs atomic consume and increment operations, and custom rate-limit storage makes oneconsumedecision per request. The read-then-delete and read-then-update fallbacks are removed.
For detailed changes, see CHANGELOG
@better-auth/kysely-adapternode:sqlite, bun:sqlite, mysql2, pg) passed directly as database now get native adapter transactions automatically, matching the behavior of the explicit { db } and { dialect } config shapes. This unblocks plugins that require native transactions (such as @better-auth/scim) when the database is provided in the quickstart database: new Database(...) shape.For detailed changes, see CHANGELOG
@better-auth/i18nFor detailed changes, see CHANGELOG
@better-auth/mongo-adapterFor detailed changes, see CHANGELOG
@better-auth/passkeycreateSession setting that signs the user in on successful passkey registration (#9873)For detailed changes, see CHANGELOG
Thanks to everyone who contributed to this release:
@adrianmxb, @brentmitchell25, @bytaesu, @dvanmali, @eluce2, @GautamBytes, @gustavovalverde, @ItalyPaleAle, @jonathansamines, @KingIronMan2011, @momomuchu, @OscarCornish, @pi0, @ping-maxwell, @ruban-s, @sovetski, @yordis
Full changelog: v1.6.30...v1.7.0
#8733 4e8e4c7 Thanks @bytaesu! - Add hydrateSession to seed the client with a server-fetched session so useSession returns data on the first render.
#9930 0cbaf81 Thanks @gustavovalverde! - Anonymous account linking now works after social and generic OAuth sign-in in Expo and other in-app browsers, where the OAuth callback returns without the session cookie. onLinkAccount fires and the anonymous user is migrated; before, it was silently skipped.
Plugins can now carry server-trusted data across an OAuth redirect with the new addOAuthServerContext API, read back on the callback via getOAuthState().serverContext. Unlike additionalData, it cannot be set from the request body, so it is the right place for values the server must trust.
For @better-auth/oauth-provider, the post-login authorization query now travels through that server-only channel, so it can no longer be injected through additionalData.
#10004 b36c38f Thanks @bytaesu! - The captcha plugin now requires endpoint entries to match full auth paths unless they use wildcard patterns. This prevents requests like /sign-in//email from bypassing captcha while preserving trailing-slash matches like /sign-in/email/. To protect multiple routes, replace partial paths like /sign-in with explicit wildcards such as /sign-in/* or /sign-in/**.
#10746 6782647 Thanks @gustavovalverde! - OAuth device grants now use oauthDeviceAuthorization() alongside oauthProvider() or mcp(). This single integration replaces both the standalone deviceCodeGrant() plugin and the shared-grant configuration. Standalone Device Authorization no longer accepts or stores RFC 8707 resources, and onDeviceAuthRequest receives only clientId and scope. The OAuth integration rejects resource indicators that are not absolute, fragment-free URIs.
The OAuth integration replaces the optional resource column with oauthClientId and resources. Regenerate and apply the schema when using it. Before upgrading from an earlier 1.7 prerelease, let pending OAuth device codes expire or delete them because they cannot be exchanged through the new integration.
#10402 763a267 Thanks @gustavovalverde! - Plugin database schemas can now define named or generated table-level indexes across multiple fields. SQL migrations and generated Drizzle or Prisma schemas resolve configured table and column names consistently, while the MongoDB adapter creates the same indexes before the first index-enforcing write.
#9766 bf39cbf Thanks @GautamBytes! - Add a server-only auth.api.consumePhoneNumberOTP API for custom phone OTP flows that need to verify and consume a code without creating or updating users or sessions.
#10330 081d3c3 Thanks @ping-maxwell! - Allow the username plugin's separate displayUsername field to be omitted by
setting displayUsername: false on both the server and client plugins.
#10059 49b5cf6 Thanks @GautamBytes! - Device Authorization now creates unique database indexes for deviceCode and userCode, so each generated code must be unique in its column. Existing installations on every adapter must resolve duplicate values before applying the migration. MySQL and SQL Server installations must also convert both columns to bounded strings and clean up values longer than 191 characters before running it.
Generated codes are limited to 191 characters. Issuance makes up to 3 attempts to overcome unique-key collisions, then returns server_error if it cannot create a unique deviceCode and userCode. Default-generated user codes accept case changes and readability separators during verification, approval, and denial; custom codes outside the default alphabet are matched exactly. The /device limiter allows 5 requests over a window equal to the configured code lifetime, while /device/token polling keeps its separate interval behavior.
#9645 e014029 Thanks @ping-maxwell! - Harden the Electron OAuth flow and tighten custom-scheme trusted-origin matching.
The Electron sign-in flow now mandates PKCE S256. Plain PKCE is rejected: the code_challenge_method parameter is gone and every authorization code is verified by hashing the verifier with SHA-256. The server no longer trusts an electron-origin header to set the request Origin. The Electron client now sends a real Origin (for example myapp:/), so upgrade the @better-auth/electron client and server together and make sure your app's scheme is in trustedOrigins. The unused disableOriginOverride option is removed.
Custom-scheme entries in trustedOrigins now match by scheme and authority instead of string prefix. A host-less entry such as myapp:// or exp:// still trusts every host of that scheme, but a host-bearing entry such as myapp://callback matches that host exactly, so it is no longer satisfied by myapp://callback.attacker.tld.
#9948 3d04fab Thanks @yordis! - feat(generic-oauth): add refreshTokenParams config to forward extra params on token refresh
Multi-tenant OIDC providers (Zitadel multi-org, Auth0 with audience) need to send extra body params on the refresh call to rescope tokens without a full authorization redirect. The generic-oauth plugin now accepts a refreshTokenParams option (object or sync/async function) that is merged into the refresh request body, with grant_type and refresh_token protected from override. The function form receives request metadata for the request that triggered the refresh, so request-scoped data (headers, cookies) is available without out-of-band state like AsyncLocalStorage.
UpstreamProvider.refreshAccessToken now accepts an optional second ctx argument; the change is backwards compatible because existing implementations that take only refreshToken remain valid. See #7554.
#9069 c7d2253 Thanks @gustavovalverde! - Rewrite the generic OAuth plugin as a first-class social provider with OAuth 2.1 security defaults. Providers now use signIn.social + callback/:id instead of dedicated plugin endpoints, with PKCE required by default (OAuth 2.1), RFC 9207 issuer validation, OIDC auto-discovery with openid scope injection, and typed provider IDs.
Breaking changes:
signIn.oauth2({ providerId }) replaced by signIn.social({ provider })oauth2.link() replaced by linkSocial()/api/auth/oauth2/callback/:id to /api/auth/callback/:idgenericOAuthClient() removed; generic OAuth providers now use the standard social client APIspkce defaults to true (was false); set pkce: false for providers that reject PKCEauthorizationUrlParams and tokenUrlParams only accept Record<string, string>issuer and requireIssuerValidation config fields removed; issuer validation is automatic via OIDC discoverymapProfileToUser profile typed as OAuth2UserInfo & Record<string, unknown>#9966 ec8a38c Thanks @gustavovalverde! - genericOAuth providers configured with a discoveryUrl now verify the provider's id_token against its published JWKS (signature, issuer, audience, and advertised algorithms) and bind it to the authorization request with a server-generated OIDC nonce. A sign-in whose id_token fails verification, or does not echo the expected nonce, is rejected.
Set disableIdTokenNonceBinding: true on a provider that does not return the nonce claim in the authorization-code flow.
These providers also accept client-submitted id_token sign-in through signIn.social({ idToken }), which previously returned ID_TOKEN_NOT_SUPPORTED.
Providers configured with explicit endpoints instead of discoveryUrl are unchanged.
#9368 430c895 Thanks @GautamBytes! - Generic OAuth users can now sign out from the configured OpenID provider when they call authClient.signOut(). When a provider exposes a discovered or configured logout endpoint, Better Auth redirects to it and includes the stored id_token_hint when available. Pass callbackURL or configure postLogoutRedirectURI for the return flow, with optional state, or set disableRedirect to handle the returned url yourself. When multiple linked providers support logout, Better Auth selects the most recently updated account. Set disableProviderLogout: true to keep sign-out local.
#9431 523f95c Thanks @pi0! - feat: make Auth instance fetchable
#10577 5c45abc Thanks @gustavovalverde! - MCP clients that hit a scope wall now learn exactly which scopes to ask for. Missing protected scopes produce a 403 with an RFC 6750 insufficient_scope WWW-Authenticate challenge that names every missing scope. Clients can union those scopes into one authorization request instead of opening one browser redirect per scope.
requiredScopes through RequireMcpAuthOptions or the matching createMcpProtectedRequestHandler verifier option. Exact membership remains the default; isScopeSatisfied can define hierarchical policies.createInsufficientScopeError when an operation determines its required scopes dynamically. createResourceServerChallenge converts that signal and recognized token failures into safe RFC 6750 challenges.challengeScopes only as the unauthenticated challenge hint.Handler-produced responses, ordinary permission denials, configuration failures, and unrelated thrown values keep their original status and identity.
#10403 dbd302e Thanks @gustavovalverde! - Scope account identity by trusted issuer instead of provider configuration. Accounts now use the unique (issuer, accountId) key, so aliases for one OpenID Connect issuer deduplicate one external identity while equal subjects from different issuers remain separate. This identity deduplication does not introduce independent grant or provider lifecycle records for aliases.
This release requires Account.issuer but preserves Account.accountId as the provider-assigned account identifier. Account-specific APIs select the local Account.id through the accountId request property; token and provider-profile APIs can instead select the signed account cookie with useAccountCookie: true. Credential accounts use local:credential and the linked user's stable id as their provider identity.
OAuth provider identity now comes from raw verified profiles. OpenID Connect discovery uses sub, plain OAuth uses id, and providers can declare accountSubject for another immutable field; Better Auth no longer switches between sub and id at runtime. getUserInfo().user no longer carries provider identity, and mapProfileToUser cannot return id. Read the selected identity from accountInfo.account.accountId instead of accountInfo.user.id. The generic microsoftEntraId helper now requires a concrete tenant GUID; use the built-in Microsoft provider for multi-tenant authorities.
SSO account subjects are now protocol-defined. OIDC uses the verified sub claim, and SAML uses the signed NameID; mapping.id is removed from both configurations. A manual SAML configuration without metadata XML must set idpMetadata.entityID, because samlConfig.issuer identifies the service provider and no longer acts as the IdP identity.
Apply the reviewed account-identity backfill in the Better Auth 1.7 upgrade guide before deploying. The generated schema migration cannot assign trusted issuers or resolve existing identity collisions automatically.
#10359 8784c1c Thanks @ping-maxwell! - Database joins have moved out of experimental into a stable option at advanced.database.joins (default: false).
If you previously set experimental: { joins: true }, update your config to:
advanced: {
database: {
joins: true,
},
}
Adapters that support native joins use them when enabled. If an adapter cannot return joined data for a query, Better Auth falls back to additional queries and combines the results. Drizzle and Prisma users should ensure their schema includes the required relations (npx auth@latest generate).
#9992 e53582c Thanks @gustavovalverde! - The MCP plugin moves out of better-auth into its own package, @better-auth/mcp, built on @better-auth/oauth-provider. Import the authorization plugin and protected-request helpers from the package root. The in-core MCP client (createMcpAuthClient and its adapters) is removed; MCP protocol and transport clients come from the official version 2 @modelcontextprotocol/client and @modelcontextprotocol/server packages. The OAuth endpoints move from /mcp/* to /oauth2/*, with discovery at /.well-known/oauth-authorization-server and protected resource metadata at /.well-known/oauth-protected-resource. Discovery-based MCP clients pick up the new locations on their own.
The shared-auth route helper is renamed from withMcpAuth to requireMcpAuth. The standalone protected-resource factory is renamed from mcpHandler to createMcpProtectedRequestHandler; pass one flat McpProtectedRequestHandlerOptions object with issuer, a single audience, optional jwtVerifyOptions, token-verification fields, and challenge fields. Its callback receives accessTokenClaims. requireMcpAuth verifies the access token against the published JWKS, validates DPoP proofs for DPoP-bound tokens, and passes the verified access-token claims to your handler.
createInsufficientScopeError now validates a custom description against the RFC 6750 error_description character set when the error is constructed. Invalid descriptions throw TypeError("invalid error_description") before an error can reach resource-challenge serialization.
MCP 2026-07-28 uses a stateless request and response transport. Serve MCP routes with version 2 of @modelcontextprotocol/server, configure createMcpHandler with legacy: "reject", wrap it with requireMcpAuth, and export only POST. Remove MCP-route GET and DELETE exports and session-store options such as redisUrl. OAuth clients, consent, authorization codes, refresh tokens, and security records remain durable authorization state.
To migrate, install @better-auth/mcp, @better-auth/cimd, and the official version 2 MCP client or server package needed by your application; add the jwt() plugin, which is now required for token signing; and move options that were nested under oidcConfig to flat options on mcp({ ... }). The database models change: oauthApplication becomes oauthClient, with new oauthRefreshToken and oauthClientAssertion tables. Regenerate or migrate your schema with npx auth migrate or npx auth generate.
#10204 0683a5f Thanks @GautamBytes! - Microsoft sign-in now identifies Entra accounts with the stable oid claim in both the built-in microsoft provider and the Generic OAuth microsoftEntraId helper. Tokens without a valid oid are rejected, and the Generic OAuth helper refuses to initialize unless Microsoft discovery provides ID-token verification metadata. Existing Microsoft account rows created from sub must be migrated before upgrading.
#9305 e7eb45b Thanks @gustavovalverde! - feat(oauth): per-request additionalParams and loginHint parity across signIn.social, linkSocial, and signIn.sso
Unified escape hatch for customizing the provider authorization URL on a per-request basis. Previously, dynamic parameters like Google's access_type=offline / prompt=consent, Cognito's identity_provider=Google, or Microsoft's domain_hint could only be set as static server configuration.
signIn.social, linkSocial, and signIn.sso accept additionalParams: Record<string, string>. Values are appended to the authorization URL as query parameters.linkSocial also accepts loginHint, matching the surface of signIn.social and signIn.sso.OAuthProvider.createAuthorizationURL gains additionalParams in its input contract; every built-in provider forwards it to the shared helper.additionalParams with the config-level authorizationUrlParams; call-time wins on key collision.identityProvider?: string config option that maps to the identity_provider query parameter, avoiding magic strings.createAuthorizationURL helper silently drops any caller-supplied key in RESERVED_AUTHORIZATION_PARAMS (state, client_id, redirect_uri, response_type, code_challenge, code_challenge_method, nonce, scope). The request-body Zod schema rejects the same keys with 400, so misuse is visible at the edge rather than silently overriding security-critical parameters. nonce is reserved so a caller cannot replace the OIDC nonce Better Auth generates when binding a discovery provider's id_token to the authorization request.wechat → appid, tiktok → client_key) additionally filter those keys so a caller cannot swap the configured OAuth app.atlassian → audience, notion → owner) are merged last so caller-supplied additionalParams cannot override them. Configured defaults that represent operator intent (e.g. Google include_granted_scopes, Cognito identityProvider) remain caller-overridable.signIn.sso rejects additionalParams with 400 when the resolved provider is SAML; the SAML AuthnRequest is signed and cannot carry caller-supplied query parameters, so silently dropping them would mislead integrators.ZodRecord handling to the OpenAPI generator so z.record() fields emit type: object with typed additionalProperties. Incidentally fixes a long-standing bug where additionalData was rendered as type: string.discord, roblox, zoom, and slack providers now delegate to the shared createAuthorizationURL helper and inherit its RFC behavior and reserved-key guard.tiktok and wechat keep their manual URL construction (non-standard OAuth2 parameter names and URL fragment requirements) but thread additionalParams with the same reserved-key filter.Closes #2351. Closes #5441. Closes #5592. Closes #5604. Supersedes #4992 and #5443.
#10127 7c7313c Thanks @gustavovalverde! - OAuth sign-in, account linking, callback, and proxy flows now build redirect_uri from the current request base URL when baseURL.allowedHosts is configured. Built-in social providers and generic OAuth providers now use the resolved request host for redirects in multi-host deployments.
Custom OAuthProvider implementations can omit callbackPath when using the shared /callback/<provider-id> route. Set callbackPath only for custom callback routes.
#10039 aedcb97 Thanks @gustavovalverde! - feat(oauth-provider)!: DPoP-bound access tokens (RFC 9449)
OAuth provider integrations can issue and verify DPoP sender-constrained tokens. Clients request them with dpop_bound_access_tokens at registration, dpop_jkt on the authorization request, or by targeting a resource configured with dpopBoundAccessTokensRequired. Issued tokens carry cnf.jkt, return token_type: "DPoP", and stay bound through refresh-token rotation, introspection, and userinfo.
Resource servers verify DPoP requests with verifyAccessTokenRequest, which checks the Authorization: DPoP scheme, the proof, the request target, the access-token hash, and proof replay. The MCP package advertises DPoP in protected resource metadata and verifies DPoP-bound requests. Proof replay is rejected through the database-backed verification store, so anti-replay holds across instances. verifyAccessTokenRequest and requireMcpAuth use that store by default; build one with createDpopReplayStore(internalAdapter) or pass a custom dpop.replayStore. This needs database-backed verification storage: a secondary-storage-only deployment rejects DPoP requests rather than skipping replay protection.
Breaking: the raw-token verifier verifyAccessToken is renamed to verifyBearerToken, both in better-auth/oauth2 and as the oauthProviderResourceClient action, and it rejects DPoP-bound tokens. Use verifyAccessTokenRequest on any endpoint that may receive them. The resource-request input type is renamed from AccessTokenRequestInput to ResourceRequestInput, and the DPoP algorithm option is signingAlgorithms everywhere.
Run a schema migration for the DPoP token-binding fields: the confirmation column on the access-token and refresh-token tables. DPoP-bound clients also gain dpopBoundAccessTokens and resources dpopBoundAccessTokensRequired. No dedicated replay table is added; proof replay reuses the verification store.
#9828 4f53b61 Thanks @gustavovalverde! - Verify social-provider id_tokens with a single shared verifier.
Client-submitted id_token sign-in (signIn.social({ idToken }) and account linking) is verified by one function instead of a per-provider verifyIdToken method. Each provider declares an idToken config with a JWKS source, issuer, and audience, and the core verifier runs the signature, issuer, audience, and nonce checks. A provider that declares no config rejects the client id_token path.
PayPal previously accepted any decodable id_token without verifying its signature. PayPal derives identity from the access token, so it now declares no idToken config, and the client id_token path returns ID_TOKEN_NOT_SUPPORTED. PayPal sign-in through the redirect flow is unchanged.
Custom providers that implement UpstreamProvider directly replace the removed verifyIdToken method with an idToken config:
idToken: {
jwks: createRemoteJWKSet(new URL("https://issuer.example/.well-known/jwks.json")),
issuer: "https://issuer.example",
audience: clientId,
},
For verification that cannot use a local JWKS, pass idToken: { verify: async (token, nonce) => boolean }. The verifyIdToken and disableIdTokenSignIn provider options are unchanged.
#9079 6f2948e Thanks @gustavovalverde! - feat(oauth-provider): compute at_hash in ID tokens per OIDC Core §3.1.3.6
ID tokens issued alongside an access token now include the at_hash claim, which cryptographically binds the two tokens to prevent token substitution attacks. The hash algorithm is selected based on the actual signing key's algorithm (EdDSA/Ed25519 uses SHA-512, RS/ES/PS384 uses SHA-384, RS/ES/PS512 uses SHA-512, all others use SHA-256).
A new resolveSigningKey() export is available from better-auth/plugins to resolve the current JWKS signing key (including its algorithm). When using a custom jwt.sign callback, the signed ID token's header is validated against the declared algorithm to prevent at_hash mismatches.
#10135 f68044d Thanks @brentmitchell25! - Registered OAuth clients can now use the RFC 8628 device flow to obtain OAuth access tokens. Add oauthDeviceAuthorization() alongside oauthProvider() or mcp(), request a code at /device/code, and exchange it at /oauth2/token after the user approves it. OAuth and OpenID discovery advertise the device_authorization_endpoint.
Device authorization requests can bind RFC 8707 resource indicators. GET /device returns the requested client, scopes, and resources to the authenticated user who owns the request. Token requests can reuse or narrow the approved resources, but cannot add new ones. Existing first-party device clients continue to receive Better Auth session tokens from /device/token.
Enabling oauthDeviceAuthorization() adds nullable oauthClientId and resources fields to deviceCode. Regenerate and apply the database schema after adding the integration.
Confidential clients authenticate at /device/code with their registered method, while public clients send client_id. Empty client_id, scope, user_id, and authentication values are treated as omitted; multiple non-empty values for any of these parameters return invalid_request, while multiple resource values remain supported. Unknown OAuth client IDs enter the standalone device flow only when oauthDeviceAuthorization({ validateClient }) accepts them.
#9929 91f235f Thanks @gustavovalverde! - Add requireEmailVerification to OAuth provider options, for built-in social providers and the Generic OAuth plugin. When a provider reports an unverified email, the user and account are still created or linked, but no session is issued: the OAuth callback redirects with ?error=email_not_verified, and ID token and One Tap sign-in return 403 EMAIL_NOT_VERIFIED. Verification emails follow the existing emailVerification.sendOnSignUp / sendOnSignIn settings.
It is opt-in per provider and does not inherit emailAndPassword.requireEmailVerification, so existing social logins keep working. The gate checks the local user's verification state, so a user verified through another method keeps access. Only enable it for providers that report a trustworthy email_verified signal.
#9648 d2a79ba Thanks @brentmitchell25! - OAuth provider now models protected resources explicitly. Configure them with resources or create them through the oauthResource admin API. Each resource can define token TTLs, allowed scopes, custom JWT claims, and JWT signing pins.
validAudiences is removed. Move each existing resource identifier into resources; link clients that should be limited to specific resources through oauthClientResource or Dynamic Client Registration resources.
Access-token issuance now applies resource policy to the requested RFC 8707 resource values. The OAuth provider narrows scopes to resource allowlists, uses the shortest configured TTL, strips reserved RFC 9068 claim names from custom claims, emits jti, and keeps repeated resource form parameters.
Refresh-token TTLs now use the shortest applicable lifetime. Deployments with a per-resource refreshTokenTtl longer than refreshTokenExpiresIn will see refresh tokens expire at the provider default instead of the longer resource value.
JWT signing can now honor per-resource pins. signJWT() accepts signingKeyId and signingAlgorithm; JWKS adapters expose getKeyById() and getLatestKeyByAlg(). The jwks table adds nullable alg and crv columns, and keyPairConfigs can provision multiple algorithms in one keyring.
After upgrading, run npx auth generate and apply the migration before deploying. The migration adds oauthResource, oauthClientResource, and the new jwks columns. Without it, resources using signingAlgorithm cannot find matching keys.
Resource servers should publish RFC 9728 protected-resource metadata at their own origin. The OAuth provider exposes challenge helpers that point clients at that metadata.
@better-auth/mcp now requires an explicit resource option. The plugin stores that identifier as an OAuth resource, publishes RFC 9728 protected-resource metadata for it, and binds issued access tokens to that resource. Existing mcp({ loginPage, consentPage }) setups should add a protected MCP resource identifier, for example resource: "https://api.example.com/mcp".
#10397 bb6c102 Thanks @ping-maxwell! - Add organization.getOrganization() to fetch organization metadata without members or invitations.
#8931 34558bc Thanks @GautamBytes! - Add opt-in JWKS-backed asymmetric JWT support for session_data cookie cache tokens, so services can verify cookie-cache JWTs with public keys instead of shared secrets. Enable it with jwt({ sessionCookieCache: true }) alongside session.cookieCache.strategy = "jwt".
#8977 954b664 Thanks @ruban-s! - allow passing userId and organizationId to the listUserTeams API. userId lets callers list teams for another member of an organization (gated behind the member:update permission). organizationId scopes the result to a specific organization without needing to switch the session's active organization, matching the pattern used by addTeamMember/removeTeamMember.
#9969 76a3342 Thanks @gustavovalverde! - Signing out with secondaryStorage and session.preserveSessionInDatabase now runs your configured session.delete hooks and marks the preserved session row as ended. OAuth Provider access and refresh tokens bound to that session are revoked and back-channel logout is dispatched on sign-out. Previously these hooks were skipped in this setup, so the tokens stayed valid until they expired.
#9657 1e5b808 Thanks @gustavovalverde! - Harden private_key_jwt and token endpoint client authentication, and add the helpers that make the fix structural.
@better-auth/core/oauth2 now exposes encodeBasicCredentials and decodeBasicCredentials, a round-trip-tested pair that follows RFC 6749 §2.3.1 (application/x-www-form-urlencoded each value, split on the first : only). The decoder accepts the scheme case-insensitively and tolerates one or more spaces before the credentials per RFC 7235 §2.1. client_secret_basic on the client side and the Better Auth OAuth provider on the server side both go through these helpers, so credentials containing reserved characters round-trip cleanly across the stack and headers like basic xxx or Basic xxx are accepted.
createPrivateKeyJwtClientAssertionGetter validates options eagerly. Unsupported algorithms (HS256, none), a JWK with no key material, and disagreement between an explicit algorithm and the JWK-embedded alg all throw at construction rather than on the first token request. signPrivateKeyJwtClientAssertion enforces the same checks for direct callers. Breaking: configurations that paired an unsupported JWK alg with a different explicit algorithm used to silently sign with the explicit option; they now fail at construction.
Breaking: @better-auth/oauth-provider accepts client jwks metadata only as an RFC 7517 JWK Set object with a non-empty keys array. Replace jwks: [key] with jwks: { keys: [key] } in DCR payloads, administrative and user client creation, Client ID Metadata Documents, test fixtures, and generated client code. Remotely fetched jwks_uri responses must use the same object shape. EC keys must use P-256, P-384, or P-521; OKP keys must use Ed25519. When a key declares alg, it must be a supported private_key_jwt algorithm that matches the key type and curve; omit alg when the client chooses the algorithm in its assertion header. OAuth client rows previously written through oauthToSchema are already stored as JWK Set objects, so this is a request, configuration, and type migration rather than another database rewrite; audit rows written outside Better Auth separately.
The SSO private_key_jwt flow redirects with error_description=no_private_key_available when a resolvePrivateKey callback returns no privateKeyJwk or privateKeyPem. The redirect path previously short-circuited only when the resolver was absent entirely; an empty resolver return fell through into an internal signing error.
better-auth/test adds getHttpTestInstance, a counterpart to getTestInstance that binds a real HTTP listener on an OS-assigned port and constructs the auth instance against the discovered URL. It removes the temp-server-then-rebind race that test files have been individually copy-pasting.
#8836 93d3871 Thanks @gustavovalverde! - Add client authentication configuration for token endpoint requests across the stack, including private_key_jwt (RFC 7523).
Generic OAuth providers now accept tokenEndpointAuth for token endpoint client authentication. Use tokenEndpointAuth: { method: "private_key_jwt", getClientAssertion } for JWT client assertions, { method: "none" } for public clients, and { method: "client_secret_basic" } or { method: "client_secret_post" } with clientSecret for explicit secret-based client authentication. The existing authentication: "basic" | "post" option remains available for secret-based token requests.
Use createPrivateKeyJwtClientAssertionGetter() to sign RFC 7523 assertions from a private key. The assertion getter receives { clientId, tokenEndpoint, grantType }, so integrations do not duplicate client ID or token endpoint values inside assertion helpers. Core OAuth2 now exports private-key JWT-specific helpers and types: signPrivateKeyJwtClientAssertion, createPrivateKeyJwtClientAssertionGetter, PrivateKeyJwtSigningAlgorithm, and PRIVATE_KEY_JWT_SIGNING_ALGORITHMS.
Token endpoint client authentication parameters are derived from clientId, clientSecret, and tokenEndpointAuth. Configured token endpoint authentication requires clientId; secret-based token endpoint authentication also requires clientSecret. Custom token parameters are for provider-specific fields and do not replace the configured client authentication values.
refreshAccessToken() now forwards resource values to refresh-token requests, so RFC 8707 resource indicators work through both the high-level refresh helper and refreshAccessTokenRequest().
The synchronous OAuth2 request builders createAuthorizationCodeRequest, createRefreshAccessTokenRequest, and createClientCredentialsTokenRequest have been removed. Use the async authorizationCodeRequest, refreshAccessTokenRequest, and clientCredentialsTokenRequest helpers instead.
Servers verify JWT client assertions signed with asymmetric keys, and clients can use the same token endpoint authentication contract for authorization code, refresh, and client credentials token requests.
#9134 652fa53 Thanks @gustavovalverde! - The dynamic baseURL config now ignores x-forwarded-host and x-forwarded-proto unless you set advanced.trustedProxyHeaders: true.
Requests using baseURL: { allowedHosts } now resolve the auth origin from Host by default, so forwarded headers cannot select another allowed host unless trusted proxy headers are enabled.
Breaking change: if your proxy exposes the public hostname only through x-forwarded-host, set advanced.trustedProxyHeaders: true. Deployments where the proxy rewrites Host to the public hostname (nginx default, Vercel, Cloudflare, and Netlify) are unaffected.
Migration:
betterAuth({
baseURL: { allowedHosts: [...] },
advanced: {
trustedProxyHeaders: true,
},
});
#9240 729c00d Thanks @adrianmxb! - feat(username): add immutable username option
This allows users to set their username during sign-up or first update, but prevents changing it to a different value afterwards. Users can still update other profile fields.
#10031 6fe9faa Thanks @gustavovalverde! - Remove the deprecated oidcProvider plugin from better-auth/plugins. Migrate OIDC authorization-server integrations to @better-auth/oauth-provider.
#10473 ed61b47 Thanks @gustavovalverde! - Add transactional OIDC user resolution so applications can link verified issuer and subject pairs to exact existing users while preserving or updating the local profile.
#10234 973fdde Thanks @gustavovalverde! - The SIWE plugin now issues nonces before the wallet address or Chain ID is known. authClient.siwe.nonce() and authClient.siwe.getNonce() no longer accept wallet fields, getNonce must return an ERC-4361 nonce (8-250 alphanumeric characters), and SIWE verification now reads the wallet address and Chain ID from the signed ERC-4361 message.
#9864 41cca60 Thanks @GautamBytes! - Add a user.validateUserInfo provisioning gate that lets applications reject an identity before a user is created or a new account is linked. It runs once at the creation step for every method that provisions a user (OAuth, SSO/SAML, email/password, magic link, email OTP, anonymous, SIWE, phone number, admin-created users, and SCIM), including stateless setups with no persistent database.
It also re-runs when an existing OAuth or SSO user signs in again (source.action is "sign-in"), where it receives the fresh provider email and profile so a domain or org policy can reject a user whose provider identity moved out of bounds. Non-provider returning sign-ins are not re-validated.
The callback receives the mapped user plus a source describing the action (create-user, link-account, or sign-in), the method, and provider metadata: source.oauth for OAuth providers and source.sso for OIDC/SAML SSO providers. Return { error, errorDescription } to reject: browser flows redirect to the error URL and programmatic flows return a 403.
#10036 ad35ead Thanks @bytaesu! - Require Google One Tap server callbacks to resolve a Google client ID before verifying ID tokens. Configure oneTap({ clientId }) or socialProviders.google.clientId when using the One Tap plugin.
#9057 544f1c6 Thanks @gustavovalverde! - feat(two-factor)!: add OTP-only enablement and a discriminated response
enableTwoFactor now accepts a method parameter ("otp" | "totp", default "totp") and returns a discriminated response with a method field.
method: "otp"twoFactorEnabled: true immediately.{ method: "otp" }.otpOptions.sendOTP to be configured on the server; rejects with OTP_NOT_CONFIGURED otherwise.method: "totp" (default){ method: "totp", totpURI, backupCodes }.TOTP_NOT_CONFIGURED if totpOptions.disable is set.The existing skipVerificationOnEnable option remains supported for TOTP enrollment.
enableTwoFactor includes a method field in the response ("otp" or "totp").#10014 73541c1 Thanks @gustavovalverde! - Cloudflare Workers apps can now start when importing Better Auth subpaths such as better-auth/db. Beta builds were crashing during module initialization before application code ran.
#10299 cf8eaac Thanks @momomuchu! - widen drizzle-kit peer dependency range
#10501 65fc17c Thanks @KingIronMan2011! - Expand the optional drizzle-orm peer range to ^0.45.2 || >=1.0.0-rc.1 <2.0.0, matching @better-auth/drizzle-adapter and allowing Drizzle ORM v1 RC installations without peer dependency warnings.
#10622 ecd83da Thanks @gustavovalverde! - Sign-up no longer deadlocks when session cookie caching uses the JWT strategy on a single-connection SQLite database with native transactions enabled. JWKS key lookups and creation now resolve the transaction-scoped adapter instead of always querying the root connection, so minting a signing key during sign-up joins the surrounding transaction instead of racing it for the only available connection. On multi-connection databases (Postgres, MySQL) this also fixes a silent atomicity gap where a JWKS key created mid-transaction could commit independently of the transaction it was minted in.
#10293 fe4c820 Thanks @gustavovalverde! - npx auth migrate can now add required columns with static defaults and nullable
unique columns to existing SQLite, PostgreSQL, and MySQL tables. Required unique
columns still need distinct values to be backfilled manually before applying the
unique constraint.
#9898 7fe0e2b Thanks @ItalyPaleAle! - Add clientAssertion support to the Microsoft Entra ID social provider.
#9301 03e6c94 Thanks @gustavovalverde! - Add allowIdpInitiated to GenericOAuthConfig and SSO OIDCConfig to support providers that initiate OAuth without a state parameter (e.g. Clever). When enabled, stateless callbacks restart the OAuth flow server-side with fresh state and PKCE, preserving CSRF protection. Also hardens parseState against undefined request bodies on GET callbacks.
#10065 2196ea6 Thanks @gustavovalverde! - OAuth and device-authorization responses that carry credentials now consistently send Cache-Control: no-store and Pragma: no-cache, so proxies, CDNs, and browsers never cache them. This covers the token, introspection, and userinfo endpoints, dynamic and admin client registration, client secret rotation, and the device code and device token responses, including the error responses from those endpoints.
Endpoints declare this with metadata: { noStore: true }, and the header set is exported from @better-auth/core as NO_STORE_HEADERS for responses built by hand.
#10124 06daf70 Thanks @gustavovalverde! - Preserve the resolved OAuth user when overrideUserInfo returns null during account linking.
#9304 e0d2b9e Thanks @gustavovalverde! - Propagate sign-out to every connected app and cut off API access immediately, via OIDC Back-Channel Logout 1.0.
When a user's session ends at the OP (sign-out, /oauth2/end-session, admin revoke, ban), @better-auth/oauth-provider now notifies every Relying Party that holds tokens for that session. The user's API access is cut off right away, instead of access tokens staying usable until their own TTL. Each client opts in by registering a backchannel_logout_uri (and optionally backchannel_logout_session_required) via DCR or the admin client-create endpoint. The provider signs a logout+jwt Logout Token per client and POSTs it to that client in parallel, with a short per-RP timeout.
Breaking change. Introspection of an opaque or JWT access token whose bound session has ended now returns { active: false }, and /oauth2/userinfo rejects it with invalid_token. Previously the token stayed active until its own TTL. If you relied on access tokens outliving the user's session, that no longer holds.
Refresh tokens without offline_access are revoked on session end; offline_access refresh tokens are preserved so long-lived API access can survive the browser session (OIDC Back-Channel Logout 1.0 §2.7). Access-token invalidation on session end is an additional OP hardening choice beyond §2.7, enforced by session liveness, so it holds even when the JWT plugin is disabled.
Delivery runs through the host's background task handler when one is configured (Vercel waitUntil, Cloudflare ctx.waitUntil); without a handler it completes inline so notifications are not lost on request teardown. Configure advanced.backgroundTasks.handler on serverless runtimes to keep sign-out fast.
Discovery at /.well-known/openid-configuration and /.well-known/oauth-authorization-server advertises backchannel_logout_supported: true and backchannel_logout_session_supported: true when the JWT plugin is enabled. Every registered backchannel_logout_uri must be a credential-free public HTTPS URL without a fragment; loopback HTTP is rejected for both public and confidential clients. CIMD documents cannot register back-channel logout metadata. The SSRF host guard, which blocks private, reserved, tunneled, and cloud-metadata hosts, also covers a private_key_jwt client's jwks_uri.
Schema changes on @better-auth/oauth-provider:
oauthClient.backchannelLogoutUri: string | nulloauthClient.backchannelLogoutSessionRequired: booleanoauthAccessToken.revoked: Date | nullbetter-auth's signJWT gains an optional header argument, forwarded to custom remote signers. JWT profiles that need an explicit media type, such as typ: "logout+jwt", can now set it without reaching for the low-level signing primitives.
#10125 a83152e Thanks @gustavovalverde! - Create new OAuth accounts in the user creation transaction. Adapters with native
transaction support roll back the user when the account write fails, while other
adapters still perform the writes sequentially.
#10128 97903c9 Thanks @gustavovalverde! - Preserve previously granted OAuth scopes across sign-in re-authentication and refresh-token requests. account.scope now accumulates monotonically: newly granted scopes are merged in only when added via linkSocial, and providers returning a narrower scope claim than the user has granted no longer shrink the stored value.
#10170 6ddb555 Thanks @gustavovalverde! - Bundled dependencies were refreshed to their latest compatible releases, including jose, nanostores, the noble crypto packages, and SimpleWebAuthn. These updates are backward compatible and require no changes to existing projects.
#10390 0de88f5 Thanks @gustavovalverde! - SCIM connections can now provision Users, Groups, and direct memberships into application-defined provisioning domains without the organization or SSO plugins. Applications can map Group membership to validated custom roles through projections. The service also supports SCIM 2.0 discovery, filtering, pagination, response attribute selection, atomic PATCH operations, and common request patterns used by Microsoft Entra ID and Okta.
This replaces the previous SCIM configuration, client APIs, database schema, and organization-backed Group model. Existing SCIM installations cannot migrate provisioning state in place. Follow the SCIM cutover in the 1.7 upgrade guide, including full directory reprovisioning, before resuming traffic.
Deferred database side effects now run only after a successful transaction. A rolled-back User update no longer refreshes its cached profile, and a rolled-back bulk session revocation no longer invalidates sessions.
#10505 d701f90 Thanks @gustavovalverde! - One Tap, Electron, and Expo client plugins now compose with createAuthClient without TypeScript errors, and the resulting client preserves each plugin's inferred actions.
#10621 59c4c83 Thanks @gustavovalverde! - Allow test instances to enable native database transactions for postgres and mysql.
Updated dependencies [5c45abc, 763a267, 5d38b13, 692b22c, ea06c5a, 3d04fab, 430c895, de8394d, dbd302e, 8784c1c, ecd83da, e4818b5, 7fe0e2b, 0683a5f, e7eb45b, 7c7313c, aedcb97, 03e6c94, 4f53b61, 2196ea6, 91f235f, 34558bc, 1e5b808, 93d3871, 97903c9, ed61b47, 0de88f5, 3a79aff, 41cca60, d701f90
Restored client plugin declaration compatibility for downstream TypeScript consumers.
better-authFor detailed changes, see CHANGELOG
@better-auth/oauth-providerprivate_key_jwt client assertions to accept the issuer URL as a valid aud claim (string or array) on token, introspection, and revocation requests. (#10811)POST support, explicit confirmation pages, and strict post_logout_redirect_uri validation. (#10812)openid scope. (#10791)For detailed changes, see CHANGELOG
@better-auth/drizzle-adapterpgSchema export so drizzle-kit can emit CREATE SCHEMA for custom PostgreSQL namespaces. (#10770)For detailed changes, see CHANGELOG
@better-auth/electronFor detailed changes, see CHANGELOG
@better-auth/expoFor detailed changes, see CHANGELOG
authpgSchema export so drizzle-kit can emit CREATE SCHEMA for custom PostgreSQL namespaces. (#10770)For detailed changes, see CHANGELOG
Thanks to everyone who contributed to this release:
@bytaesu, @gustavovalverde, @ping-maxwell
Full changelog: v1.7.0-rc.5...v1.7.0-rc.6
#10769 773de54 Thanks @bytaesu! - Prevent duplicate session requests during transient remounts while ensuring incomplete refreshes are revalidated.
#10794 2ad2928 Thanks @bytaesu! - Restore client plugin declaration compatibility for downstream TypeScript consumers.
Updated dependencies [692b22c]:
Refactored OAuth device grant ownership to use oauthDeviceAuthorization() alongside oauthProvider() or mcp()
better-authoauthDeviceAuthorization() alongside oauthProvider() or mcp() (#10746)Migration: Replace the standalone
deviceCodeGrant()plugin withoauthDeviceAuthorization()used alongsideoauthProvider()ormcp(). Regenerate and apply the schema (resourcecolumn is replaced byoauthClientIdandresources). Let any pending device codes expire or delete them before upgrading, as they cannot be exchanged through the new integration.
displayName in the username plugin (#10330)For detailed changes, see CHANGELOG
@better-auth/oauth-provideroauthDeviceAuthorization() alongside oauthProvider() or mcp() (#10746)Migration: Replace the standalone
deviceCodeGrant()plugin withoauthDeviceAuthorization()used alongsideoauthProvider()ormcp(). Regenerate and apply the schema (resourcecolumn is replaced byoauthClientIdandresources). Let any pending device codes expire or delete them before upgrading, as they cannot be exchanged through the new integration.
silenceWarnings config option and startup warnings for well-known metadata endpoints (#10703)For detailed changes, see CHANGELOG
@better-auth/scimbetter-call (#10657)For detailed changes, see CHANGELOG
authFor detailed changes, see CHANGELOG
Thanks to everyone who contributed to this release:
@bytaesu, @gustavovalverde, @ping-maxwell
Full changelog: v1.7.0-rc.4...v1.7.0-rc.5
#10746 6782647 Thanks @gustavovalverde! - OAuth device grants now use oauthDeviceAuthorization() alongside oauthProvider() or mcp(). This single integration replaces both the standalone deviceCodeGrant() plugin and the shared-grant configuration. Standalone Device Authorization no longer accepts or stores RFC 8707 resources, and onDeviceAuthRequest receives only clientId and scope. The OAuth integration rejects resource indicators that are not absolute, fragment-free URIs.
The OAuth integration replaces the optional resource column with oauthClientId and resources. Regenerate and apply the schema when using it. Before upgrading from an earlier 1.7 prerelease, let pending OAuth device codes expire or delete them because they cannot be exchanged through the new integration.
#10330 081d3c3 Thanks @ping-maxwell! - Allow the username plugin's separate displayUsername field to be omitted by setting displayUsername: false on both the server and client plugins.
Added a placeholder email utility for generating temporary email addresses
better-authfindSessions to skip null-parsed session tokens instead of returning early (#10580)jwtClient (#10513)oneTapClient (#10635)$fetch and $store not being exposed on the Solid client (#10444)next/headers import promise in production (#10467)For detailed changes, see CHANGELOG
@better-auth/expoMigration:
getCookie()now returns a Promise. Custom storage implementations must provide both sync and asyncSecureStoremethods, and should usesetItemAsync()when the write must be awaited.
For detailed changes, see CHANGELOG
@better-auth/redis-storageSCAN instead of KEYS to avoid blocking the server (#10507)For detailed changes, see CHANGELOG
@better-auth/scimnoTarget error (#10682)For detailed changes, see CHANGELOG
authFor detailed changes, see CHANGELOG
Thanks to everyone who contributed to this release:
@birkskyum, @bytaesu, @Emmaccen, @gustavovalverde, @jashkarangiya, @jeroenvandermerwe, @jlucaso1, @jsj, @krish-vachhani, @mrosberghaus, @XXMOHAMED012
Full changelog: v1.7.0-rc.3...v1.7.0-rc.4
#10676 90b5093 Thanks @bytaesu! - Deduplicate in-flight session requests when React retries a suspended component.
Updated dependencies []:
Added database indexes for device and user code lookups in the device authorization flow
better-authMigration: MySQL and SQL Server users must convert device code and user code columns to bounded strings (max 191 characters) and resolve any oversized values before applying the migration.
microsoftEntraId accounts to use the stable oid claim as the account identifier instead of sub (#10204)Migration: Migrate existing Microsoft account rows keyed by
subtooidbefore upgrading; tokens without a validoidclaim are rejected after the update.
createAuthClient (#10505)For detailed changes, see CHANGELOG
@better-auth/coremicrosoftEntraId accounts to use the stable oid claim as the account identifier instead of sub (#10204)Migration: Migrate existing Microsoft account rows keyed by
subtooidbefore upgrading; tokens without a validoidclaim are rejected after the update.
createAuthClient (#10505)For detailed changes, see CHANGELOG
@better-auth/oauth-providertype/public client fields with applicationType and enforcing stricter redirect validation and scope controls (#10577)Migration: Apply a database migration to add
applicationType, nullableclientDiscoveryId, andclientCredentialsScopescolumns; backfillapplicationTypefrom existing values andclientCredentialsScopesto[]for all clients; deduplicate(clientId, resourceId)pairs before applying the new unique index. ReplaceOAuthClientstring-index accesses withOAuthClient & YourExtensionMetadata, and composemcp()withcimd()explicitly if using Client ID Metadata Documents.
403 with an RFC 6750 insufficient_scope WWW-Authenticate challenge listing all missing scopes, allowing clients to request them in a single authorization request.For detailed changes, see CHANGELOG
@better-auth/cimdtype/public client fields with applicationType and enforcing stricter redirect validation and scope controls (#10577)Migration: Apply a database migration to add
applicationType, nullableclientDiscoveryId, andclientCredentialsScopescolumns; backfillapplicationTypefrom existing values andclientCredentialsScopesto[]for all clients; deduplicate(clientId, resourceId)pairs before applying the new unique index. ReplaceOAuthClientstring-index accesses withOAuthClient & YourExtensionMetadata, and composemcp()withcimd()explicitly if using Client ID Metadata Documents.
s-maxage, honoring conditional revalidation, and treating ambiguous or duplicate freshness directives as immediately stale to prevent unique-constraint failures on concurrent refreshes.For detailed changes, see CHANGELOG
@better-auth/mcptype/public client fields with applicationType and enforcing stricter redirect validation and scope controls (#10577)Migration: Apply a database migration to add
applicationType, nullableclientDiscoveryId, andclientCredentialsScopescolumns; backfillapplicationTypefrom existing values andclientCredentialsScopesto[]for all clients; deduplicate(clientId, resourceId)pairs before applying the new unique index. ReplaceOAuthClientstring-index accesses withOAuthClient & YourExtensionMetadata, and composemcp()withcimd()explicitly if using Client ID Metadata Documents.
For detailed changes, see CHANGELOG
@better-auth/scimauth.api methods (#10592)active field and primary sub-attributes of emails, phoneNumbers, addresses, roles, and entitlements at the HTTP ingress.managedConnections configuration to allow trusted server code to create, issue, rotate, and revoke SCIM tenant connections and bearer credentials through server-only auth.api methods without a code-defined connection.For detailed changes, see CHANGELOG
@better-auth/ssoresolveUser to SAML sign-ins with a discriminated protocol field, and added guardProviderMutation to authorize SSO provider updates and deletions (#10621)wantAssertionsSigned to control assertion signing instead of response signing.For detailed changes, see CHANGELOG
@better-auth/electroncreateAuthClient (#10505)For detailed changes, see CHANGELOG
@better-auth/expocreateAuthClient (#10505)For detailed changes, see CHANGELOG
@better-auth/kysely-adapternode:sqlite, bun:sqlite, mysql2, pg) passed directly as database to automatically receive native adapter transactions, matching the explicit { db }/{ dialect } config shapes and unblocking plugins like @better-auth/scim when using the quickstart configuration.For detailed changes, see CHANGELOG
@better-auth/passkeycreateSession setting to passkey registration that signs the user in automatically on successful registration (#9873)For detailed changes, see CHANGELOG
Thanks to everyone who contributed to this release:
@brentmitchell25, @GautamBytes, @gustavovalverde
Full changelog: v1.7.0-rc.2...v1.7.0-rc.3
#10059 49b5cf6 Thanks @GautamBytes! - Device Authorization now creates database indexes for device and user code lookups. Codes longer than 191 characters are rejected. Existing MySQL and SQL Server installations must convert these columns to bounded strings and resolve oversized values before running the migration.
#9368 430c895 Thanks @GautamBytes! - Generic OAuth users can now sign out from the configured OpenID provider when they call authClient.signOut(). When a provider exposes a discovered or configured logout endpoint, Better Auth redirects to it and includes the stored id_token_hint when available. Pass callbackURL or configure postLogoutRedirectURI for the return flow, with optional state, or set disableRedirect to handle the returned url yourself. When multiple linked providers support logout, Better Auth selects the most recently updated account. Set disableProviderLogout: true to keep sign-out local.
#10577 5c45abc Thanks @gustavovalverde! - MCP clients that hit a scope wall now learn exactly which scopes to ask for. Missing protected scopes produce a 403 with an RFC 6750 insufficient_scope WWW-Authenticate challenge that names every missing scope. Clients can union those scopes into one authorization request instead of opening one browser redirect per scope.
requiredScopes through RequireMcpAuthOptions or the matching createMcpProtectedRequestHandler verifier option. Exact membership remains the default; isScopeSatisfied can define hierarchical policies.createInsufficientScopeError when an operation determines its required scopes dynamically. createResourceServerChallenge converts that signal and recognized token failures into safe RFC 6750 challenges.challengeScopes only as the unauthenticated challenge hint.Handler-produced responses, ordinary permission denials, configuration failures, and unrelated thrown values keep their original status and identity.
#10204 0683a5f Thanks @GautamBytes! - Microsoft sign-in now identifies Entra accounts with the stable oid claim in both the built-in microsoft provider and the Generic OAuth microsoftEntraId helper. Tokens without a valid oid are rejected, and the Generic OAuth helper refuses to initialize unless Microsoft discovery provides ID-token verification metadata. Existing Microsoft account rows created from sub must be migrated before upgrading.
#10135 f68044d Thanks @brentmitchell25! - Registered OAuth clients can now use the RFC 8628 device flow to obtain provider-managed OAuth tokens. Add deviceCodeGrant() alongside deviceAuthorization() and oauthProvider(); clients request a code at /device/code and exchange it at /oauth2/token after the user approves it. OAuth and OpenID discovery now advertise device_authorization_endpoint.
Device authorization requests can bind RFC 8707 resource indicators. GET /device now returns the requesting client_id, scope, and resource values to the authenticated user who owns the request, and onDeviceAuthRequest receives the resource as its third argument. Token requests can reuse or narrow the approved resource set, but requests that add a resource are rejected. Existing first-party device clients continue to receive Better Auth session tokens from /device/token.
The deviceCode table adds an optional resource field. Run npx @better-auth/cli generate and apply the migration before deploying this update.
#10622 ecd83da Thanks @gustavovalverde! - Sign-up no longer deadlocks when session cookie caching uses the JWT strategy on a single-connection SQLite database with native transactions enabled. JWKS key lookups and creation now resolve the transaction-scoped adapter instead of always querying the root connection, so minting a signing key during sign-up joins the surrounding transaction instead of racing it for the only available connection. On multi-connection databases (Postgres, MySQL) this also fixes a silent atomicity gap where a JWKS key created mid-transaction could commit independently of the transaction it was minted in.
#10505 d701f90 Thanks @gustavovalverde! - One Tap, Electron, and Expo client plugins now compose with createAuthClient without TypeScript errors, and the resulting client preserves each plugin's inferred actions.
#10621 59c4c83 Thanks @gustavovalverde! - Allow test instances to enable native database transactions for postgres and mysql.
Updated dependencies [5c45abc, 430c895, 5c45abc, ecd83da, 0683a5f, d701f90]:
chore!: move joins to advanced.database.joins
better-authchore!: move joins to advanced.database.joins (#10359)
If you previously set experimental: { joins: true }, update your config to:
advanced: {
database: {
joins: true,
},
}
Adapters that support native joins use them when enabled. If an adapter cannot return joined data for a query, Better Auth falls back to additional queries and combines the results. Drizzle and Prisma users should ensure their schema includes the required relations (npx auth@latest generate).
feat(auth)!: scope accounts by issuer (#10403)
This release is breaking. Account.accountId is renamed to Account.providerAccountId, and Account.issuer is required. Account-specific APIs select the local Account.id through accountId; token and provider-profile APIs can instead select the signed account cookie with useAccountCookie: true. Credential accounts use local:credential and the linked user's stable id as their provider identity.
OAuth provider identity now comes from raw verified profiles. OpenID Connect discovery uses sub, plain OAuth uses id, and providers can declare accountSubject for another immutable field; Better Auth no longer switches between sub and id at runtime. getUserInfo().user no longer carries provider identity, and mapProfileToUser cannot return id. Read the selected identity from accountInfo.account.providerAccountId instead of accountInfo.user.id. The generic microsoftEntraId helper now requires a concrete tenant GUID; use the built-in Microsoft provider for multi-tenant authorities.
SSO account subjects are now protocol-defined. OIDC uses the verified sub claim, and SAML uses the signed NameID; mapping.id is removed from both configurations. A manual SAML configuration without metadata XML must set idpMetadata.entityID, because samlConfig.issuer identifies the service provider and no longer acts as the IdP identity.
Apply the reviewed account-identity backfill in the Better Auth 1.7 upgrade guide before deploying. The generated schema migration cannot assign trusted issuers or resolve existing identity collisions automatically.
feat(scim)!: decouple provisioning from the organization plugin (#10390)
This replaces the previous SCIM configuration, client APIs, database schema, and organization-backed Group model. Existing SCIM installations cannot migrate provisioning state in place. Follow the SCIM cutover in the 1.7 upgrade guide, including full directory reprovisioning, before resuming traffic.
Deferred database side effects now run only after a successful transaction. A rolled-back User update no longer refreshes its cached profile, and a rolled-back bulk session revocation no longer invalidates sessions.
ctx to verifyIdToken (#10376)beforeStoreCookie option for GDPR compliance (#5753)no-cache cache control headers (#10222)For detailed changes, see CHANGELOG
@better-auth/corechore!: move joins to advanced.database.joins (#10359)
If you previously set experimental: { joins: true }, update your config to:
advanced: {
database: {
joins: true,
},
}
Adapters that support native joins use them when enabled. If an adapter cannot return joined data for a query, Better Auth falls back to additional queries and combines the results. Drizzle and Prisma users should ensure their schema includes the required relations (npx auth@latest generate).
feat(auth)!: scope accounts by issuer (#10403)
This release is breaking. Account.accountId is renamed to Account.providerAccountId, and Account.issuer is required. Account-specific APIs select the local Account.id through accountId; token and provider-profile APIs can instead select the signed account cookie with useAccountCookie: true. Credential accounts use local:credential and the linked user's stable id as their provider identity.
OAuth provider identity now comes from raw verified profiles. OpenID Connect discovery uses sub, plain OAuth uses id, and providers can declare accountSubject for another immutable field; Better Auth no longer switches between sub and id at runtime. getUserInfo().user no longer carries provider identity, and mapProfileToUser cannot return id. Read the selected identity from accountInfo.account.providerAccountId instead of accountInfo.user.id. The generic microsoftEntraId helper now requires a concrete tenant GUID; use the built-in Microsoft provider for multi-tenant authorities.
SSO account subjects are now protocol-defined. OIDC uses the verified sub claim, and SAML uses the signed NameID; mapping.id is removed from both configurations. A manual SAML configuration without metadata XML must set idpMetadata.entityID, because samlConfig.issuer identifies the service provider and no longer acts as the IdP identity.
Apply the reviewed account-identity backfill in the Better Auth 1.7 upgrade guide before deploying. The generated schema migration cannot assign trusted issuers or resolve existing identity collisions automatically.
feat(scim)!: decouple provisioning from the organization plugin (#10390)
This replaces the previous SCIM configuration, client APIs, database schema, and organization-backed Group model. Existing SCIM installations cannot migrate provisioning state in place. Follow the SCIM cutover in the 1.7 upgrade guide, including full directory reprovisioning, before resuming traffic.
Deferred database side effects now run only after a successful transaction. A rolled-back User update no longer refreshes its cached profile, and a rolled-back bulk session revocation no longer invalidates sessions.
For detailed changes, see CHANGELOG
@better-auth/drizzle-adapterchore!: move joins to advanced.database.joins (#10359)
If you previously set experimental: { joins: true }, update your config to:
advanced: {
database: {
joins: true,
},
}
Adapters that support native joins use them when enabled. If an adapter cannot return joined data for a query, Better Auth falls back to additional queries and combines the results. Drizzle and Prisma users should ensure their schema includes the required relations (npx auth@latest generate).
For detailed changes, see CHANGELOG
@better-auth/ssofeat(auth)!: scope accounts by issuer (#10403)
This release is breaking. Account.accountId is renamed to Account.providerAccountId, and Account.issuer is required. Account-specific APIs select the local Account.id through accountId; token and provider-profile APIs can instead select the signed account cookie with useAccountCookie: true. Credential accounts use local:credential and the linked user's stable id as their provider identity.
OAuth provider identity now comes from raw verified profiles. OpenID Connect discovery uses sub, plain OAuth uses id, and providers can declare accountSubject for another immutable field; Better Auth no longer switches between sub and id at runtime. getUserInfo().user no longer carries provider identity, and mapProfileToUser cannot return id. Read the selected identity from accountInfo.account.providerAccountId instead of accountInfo.user.id. The generic microsoftEntraId helper now requires a concrete tenant GUID; use the built-in Microsoft provider for multi-tenant authorities.
SSO account subjects are now protocol-defined. OIDC uses the verified sub claim, and SAML uses the signed NameID; mapping.id is removed from both configurations. A manual SAML configuration without metadata XML must set idpMetadata.entityID, because samlConfig.issuer identifies the service provider and no longer acts as the IdP identity.
Apply the reviewed account-identity backfill in the Better Auth 1.7 upgrade guide before deploying. The generated schema migration cannot assign trusted issuers or resolve existing identity collisions automatically.
For detailed changes, see CHANGELOG
@better-auth/scimfeat(scim)!: decouple provisioning from the organization plugin (#10390)
This replaces the previous SCIM configuration, client APIs, database schema, and organization-backed Group model. Existing SCIM installations cannot migrate provisioning state in place. Follow the SCIM cutover in the 1.7 upgrade guide, including full directory reprovisioning, before resuming traffic.
Deferred database side effects now run only after a successful transaction. A rolled-back User update no longer refreshes its cached profile, and a rolled-back bulk session revocation no longer invalidates sessions.
For detailed changes, see CHANGELOG
authFor detailed changes, see CHANGELOG
@better-auth/electronFor detailed changes, see CHANGELOG
@better-auth/kysely-adapterFor detailed changes, see CHANGELOG
@better-auth/mongo-adapterFor detailed changes, see CHANGELOG
@better-auth/oauth-providerFor detailed changes, see CHANGELOG
@better-auth/stripeFor detailed changes, see CHANGELOG
Thanks to everyone who contributed to this release:
@akshatmalik-bruh, @ayushman46, @c-nicol, @gaurav-init, @gaurav0107, @GautamBytes, @gustavovalverde, @momomuchu, @OrangeManLi, @paoloricciuti, @ping-maxwell, @shiminshen, @swithek, @Tushar-Khandelwal-2004, @vinay-oppuri
Full changelog: v1.7.0-rc.1...v1.7.0-rc.2
#10402 763a267 Thanks @gustavovalverde! - Plugin database schemas can now define named or generated table-level indexes across multiple fields. SQL migrations and generated Drizzle or Prisma schemas resolve configured table and column names consistently, while the MongoDB adapter creates the same indexes before the first index-enforcing write.
#10403 dbd302e Thanks @gustavovalverde! - Scope account identity by trusted issuer instead of provider configuration. Accounts now use the unique (issuer, providerAccountId) key, so aliases for one OpenID Connect issuer deduplicate one external identity while equal subjects from different issuers remain separate. This identity deduplication does not introduce independent grant or provider lifecycle records for aliases.
This release is breaking. Account.accountId is renamed to Account.providerAccountId, and Account.issuer is required. Account-specific APIs select the local Account.id through accountId; token and provider-profile APIs can instead select the signed account cookie with useAccountCookie: true. Credential accounts use local:credential and the linked user's stable id as their provider identity.
OAuth provider identity now comes from raw verified profiles. OpenID Connect discovery uses sub, plain OAuth uses id, and providers can declare accountSubject for another immutable field; Better Auth no longer switches between sub and id at runtime. getUserInfo().user no longer carries provider identity, and mapProfileToUser cannot return id. Read the selected identity from accountInfo.account.providerAccountId instead of accountInfo.user.id. The generic microsoftEntraId helper now requires a concrete tenant GUID; use the built-in Microsoft provider for multi-tenant authorities.
SSO account subjects are now protocol-defined. OIDC uses the verified sub claim, and SAML uses the signed NameID; mapping.id is removed from both configurations. A manual SAML configuration without metadata XML must set idpMetadata.entityID, because samlConfig.issuer identifies the service provider and no longer acts as the IdP identity.
Apply the reviewed account-identity backfill in the Better Auth 1.7 upgrade guide before deploying. The generated schema migration cannot assign trusted issuers or resolve existing identity collisions automatically.
#10359 8784c1c Thanks @ping-maxwell! - Database joins have moved out of experimental into a stable option at advanced.database.joins (default: false).
If you previously set experimental: { joins: true }, update your config to:
advanced: {
database: {
joins: true,
},
}
Adapters that support native joins use them when enabled. If an adapter cannot return joined data for a query, Better Auth falls back to additional queries and combines the results. Drizzle and Prisma users should ensure their schema includes the required relations (npx auth@latest generate).
#10397 bb6c102 Thanks @ping-maxwell! - Add organization.getOrganization() to fetch organization metadata without members or invitations.
#10473 ed61b47 Thanks @gustavovalverde! - Add transactional OIDC user resolution so applications can link verified issuer and subject pairs to exact existing users while preserving or updating the local profile.
#10234 973fdde Thanks @gustavovalverde! - The SIWE plugin now issues nonces before the wallet address or Chain ID is known. authClient.siwe.nonce() and authClient.siwe.getNonce() no longer accept wallet fields, getNonce must return an ERC-4361 nonce (8-250 alphanumeric characters), and SIWE verification now reads the wallet address and Chain ID from the signed ERC-4361 message.
#10299 cf8eaac Thanks @momomuchu! - widen drizzle-kit peer dependency range
#10390 0de88f5 Thanks @gustavovalverde! - SCIM connections can now provision Users, Groups, and direct memberships into application-defined provisioning domains without the organization or SSO plugins. Applications can map Group membership to validated custom roles through projections. The service also supports SCIM 2.0 discovery, filtering, pagination, response attribute selection, atomic PATCH operations, and common request patterns used by Microsoft Entra ID and Okta.
This replaces the previous SCIM configuration, client APIs, database schema, and organization-backed Group model. Existing SCIM installations cannot migrate provisioning state in place. Follow the SCIM cutover in the 1.7 upgrade guide, including full directory reprovisioning, before resuming traffic.
Deferred database side effects now run only after a successful transaction. A rolled-back User update no longer refreshes its cached profile, and a rolled-back bulk session revocation no longer invalidates sessions.
Updated dependencies [763a267, 5d38b13, dbd302e, 8784c1c, e4818b5, ed61b47, 0de88f5]:
Added Yandex as a supported OAuth social provider
better-authauth migrate to no longer abort when adding required or unique columns to an existing table (#10293)For detailed changes, see CHANGELOG
@better-auth/drizzle-adapterFor detailed changes, see CHANGELOG
authFor detailed changes, see CHANGELOG
Thanks to everyone who contributed to this release:
@bytaesu, @gustavovalverde, @vladflotsky
Full changelog: v1.7.0-rc.0...v1.7.0-rc.1
#10293 fe4c820 Thanks @gustavovalverde! - npx auth migrate no longer aborts when adding a column to an existing table. A required column with a default value, or a unique column, now migrates on SQLite and on populated Postgres and MySQL databases. Upgrading a database that already has organization teams previously failed on the new team.memberCount and teamMember.membershipKey columns.
Updated dependencies []:
Breaking change. Introspection of an opaque or JWT access token whose bound session has ended now returns { active: false }, and /oauth2/userinfo reje…
better-authfeat(captcha)!: support wildcard endpoint matching (#10004)
feat(mcp)!: ship MCP as its own package built on the OAuth provider (#9992)
The route helper is renamed requireMcpAuth (was withMcpAuth), and the remote client is createMcpResourceClient (was createMcpAuthClient). requireMcpAuth verifies the bearer token against the published JWKS and passes the verified JWT claims to your handler.
To migrate, install @better-auth/mcp, add the jwt() plugin (now required for token signing), and move options that were nested under oidcConfig to flat options on mcp({ ... }). The database models change: oauthApplication becomes oauthClient, with new oauthRefreshToken and oauthClientAssertion tables. Regenerate or migrate your schema with npx auth migrate or npx auth generate.
feat(oauth-provider)!: add OIDC back-channel logout (#9304)
When a user's session ends at the OP (sign-out, /oauth2/end-session, admin revoke, ban), @better-auth/oauth-provider now notifies every Relying Party that holds tokens for that session. The user's API access is cut off right away, instead of access tokens staying usable until their own TTL. Each client opts in by registering a backchannel_logout_uri (and optionally backchannel_logout_session_required) via DCR or the admin client-create endpoint. The provider signs a logout+jwt Logout Token per client and POSTs it to that client in parallel, with a short per-RP timeout.
Breaking change. Introspection of an opaque or JWT access token whose bound session has ended now returns { active: false }, and /oauth2/userinfo rejects it with invalid_token. Previously the token stayed active until its own TTL. If you relied on access tokens outliving the user's session, that no longer holds.
Refresh tokens without offline_access are revoked on session end; offline_access refresh tokens are preserved so long-lived API access can survive the browser session (OIDC Back-Channel Logout 1.0 §2.7). Access-token invalidation on session end is an additional OP hardening choice beyond §2.7, enforced by session liveness, so it holds even when the JWT plugin is disabled.
Delivery runs through the host's background task handler when one is configured (Vercel waitUntil, Cloudflare ctx.waitUntil); without a handler it completes inline so notifications are not lost on request teardown. Configure advanced.backgroundTasks.handler on serverless runtimes to keep sign-out fast.
Discovery at /.well-known/openid-configuration and /.well-known/oauth-authorization-server advertises backchannel_logout_supported: true and backchannel_logout_session_supported: true when the JWT plugin is enabled. Registering a backchannel_logout_uri rejects fragments, non-http(s) schemes, and non-HTTPS targets on confidential clients. Its SSRF host guard, which blocks private, reserved, tunneled, and cloud-metadata hosts, now also covers a private_key_jwt client's jwks_uri.
Schema changes on @better-auth/oauth-provider:
oauthClient.backchannelLogoutUri: string | nulloauthClient.backchannelLogoutSessionRequired: booleanoauthAccessToken.revoked: Date | nullbetter-auth's signJWT gains an optional header argument, forwarded to custom remote signers. JWT profiles that need an explicit media type, such as typ: "logout+jwt", can now set it without reaching for the low-level signing primitives.
feat(oauth-provider)!: model OAuth protected resources explicitly (#9648)
validAudiences is removed. Move each existing resource identifier into resources; link clients that should be limited to specific resources through oauthClientResource or Dynamic Client Registration resources.
Access-token issuance now applies resource policy to the requested RFC 8707 resource values. The OAuth provider narrows scopes to resource allowlists, uses the shortest configured TTL, strips reserved RFC 9068 claim names from custom claims, emits jti, and keeps repeated resource form parameters.
Refresh-token TTLs now use the shortest applicable lifetime. Deployments with a per-resource refreshTokenTtl longer than refreshTokenExpiresIn will see refresh tokens expire at the provider default instead of the longer resource value.
JWT signing can now honor per-resource pins. signJWT() accepts signingKeyId and signingAlgorithm; JWKS adapters expose getKeyById() and getLatestKeyByAlg(). The jwks table adds nullable alg and crv columns, and keyPairConfigs can provision multiple algorithms in one keyring.
After upgrading, run npx @better-auth/cli generate and apply the migration before deploying. The migration adds oauthResource, oauthClientResource, and the new jwks columns. Without it, resources using signingAlgorithm cannot find matching keys.
Resource servers should publish RFC 9728 protected-resource metadata at their own origin. The OAuth provider exposes challenge helpers that point clients at that metadata.
@better-auth/mcp now requires an explicit resource option. The plugin stores that identifier as an OAuth resource, publishes RFC 9728 protected-resource metadata for it, and binds issued access tokens to that resource. Existing mcp({ loginPage, consentPage }) setups should add a protected MCP resource identifier, for example resource: "https://api.example.com/mcp".
feat(two-factor)!: add OTP enablement and discriminated response (#9057)
enableTwoFactor now accepts a method parameter ("otp" | "totp", default "totp") and returns a discriminated response with a method field.
method: "otp"twoFactorEnabled: true immediately.{ method: "otp" }.otpOptions.sendOTP to be configured on the server; rejects with OTP_NOT_CONFIGURED otherwise.method: "totp" (default){ method: "totp", totpURI, backupCodes }.TOTP_NOT_CONFIGURED if totpOptions.disable is set.skipVerificationOnEnable: use method: "otp" for immediate activation, or the standard TOTP verification flow.enableTwoFactor includes a method field in the response ("otp" or "totp").fix(auth)!: ignore x-forwarded headers by default on dynamic baseURL (#9134)
Requests using baseURL: { allowedHosts } now resolve the auth origin from Host by default, so forwarded headers cannot select another allowed host unless trusted proxy headers are enabled.
Breaking change: if your proxy exposes the public hostname only through x-forwarded-host, set advanced.trustedProxyHeaders: true. Deployments where the proxy rewrites Host to the public hostname (nginx default, Vercel, Cloudflare, and Netlify) are unaffected.
Migration:
betterAuth({
baseURL: { allowedHosts: [...] },
advanced: {
trustedProxyHeaders: true,
},
});
fix(electron)!: enforce S256 PKCE and harden origin checks (#9645)
The Electron sign-in flow now mandates PKCE S256. Plain PKCE is rejected: the code_challenge_method parameter is gone and every authorization code is verified by hashing the verifier with SHA-256. The server no longer trusts an electron-origin header to set the request Origin. The Electron client now sends a real Origin (for example myapp:/), so upgrade the @better-auth/electron client and server together and make sure your app's scheme is in trustedOrigins. The unused disableOriginOverride option is removed.
Custom-scheme entries in trustedOrigins now match by scheme and authority instead of string prefix. A host-less entry such as myapp:// or exp:// still trusts every host of that scheme, but a host-bearing entry such as myapp://callback matches that host exactly, so it is no longer satisfied by myapp://callback.attacker.tld.
fix(one-tap)!: require client id for audience validation (#10036)
refactor!: remove deprecated oidc-provider plugin (#10031)
refactor(generic-oauth)!: rewrite as first-class social provider with RFC compliance (#9069)
Breaking changes:
signIn.oauth2({ providerId }) replaced by signIn.social({ provider })oauth2.link() replaced by linkSocial()/api/auth/oauth2/callback/:id to /api/auth/callback/:idgenericOAuthClient() removed; generic OAuth providers now use the standard social client APIspkce defaults to true (was false); set pkce: false for providers that reject PKCEauthorizationUrlParams and tokenUrlParams only accept Record<string, string>issuer and requireIssuerValidation config fields removed; issuer validation is automatic via OIDC discoverymapProfileToUser profile typed as OAuth2UserInfo & Record<string, unknown>refactor(oauth)!: verify provider id_tokens with a single shared verifier (#9828)
Client-submitted id_token sign-in (signIn.social({ idToken }) and account linking) is verified by one function instead of a per-provider verifyIdToken method. Each provider declares an idToken config with a JWKS source, issuer, and audience, and the core verifier runs the signature, issuer, audience, and nonce checks. A provider that declares no config rejects the client id_token path.
PayPal previously accepted any decodable id_token without verifying its signature. PayPal derives identity from the access token, so it now declares no idToken config, and the client id_token path returns ID_TOKEN_NOT_SUPPORTED. PayPal sign-in through the redirect flow is unchanged.
Custom providers that implement UpstreamProvider directly replace the removed verifyIdToken method with an idToken config:
idToken: {
jwks: createRemoteJWKSet(new URL("https://issuer.example/.well-known/jwks.json")),
issuer: "https://issuer.example",
audience: clientId,
},
For verification that cannot use a local JWKS, pass idToken: { verify: async (token, nonce) => boolean }. The verifyIdToken and disableIdTokenSignIn provider options are unchanged.
clientAssertion support to the Microsoft Entra ID social provider (#9898)Auth instance fetchable (#9431)requireEmailVerification for social sign-in (#9929)hydrateSession for SSR session hydration (#8733)refreshTokenParams to token endpoint (#9948)id_tokens and enable id_token sign-in (#9966)at_hash in id tokens per OIDC Core §3.1.3.6 (#9079)private_key_jwt client authentication (RFC 7523) (#8836)additionalParams and loginHint (#9305)For detailed changes, see CHANGELOG
@better-auth/oauth-providerfeat(mcp)!: ship MCP as its own package built on the OAuth provider (#9992)
The route helper is renamed requireMcpAuth (was withMcpAuth), and the remote client is createMcpResourceClient (was createMcpAuthClient). requireMcpAuth verifies the bearer token against the published JWKS and passes the verified JWT claims to your handler.
To migrate, install @better-auth/mcp, add the jwt() plugin (now required for token signing), and move options that were nested under oidcConfig to flat options on mcp({ ... }). The database models change: oauthApplication becomes oauthClient, with new oauthRefreshToken and oauthClientAssertion tables. Regenerate or migrate your schema with npx auth migrate or npx auth generate.
feat(oauth-provider)!: add OIDC back-channel logout (#9304)
When a user's session ends at the OP (sign-out, /oauth2/end-session, admin revoke, ban), @better-auth/oauth-provider now notifies every Relying Party that holds tokens for that session. The user's API access is cut off right away, instead of access tokens staying usable until their own TTL. Each client opts in by registering a backchannel_logout_uri (and optionally backchannel_logout_session_required) via DCR or the admin client-create endpoint. The provider signs a logout+jwt Logout Token per client and POSTs it to that client in parallel, with a short per-RP timeout.
Breaking change. Introspection of an opaque or JWT access token whose bound session has ended now returns { active: false }, and /oauth2/userinfo rejects it with invalid_token. Previously the token stayed active until its own TTL. If you relied on access tokens outliving the user's session, that no longer holds.
Refresh tokens without offline_access are revoked on session end; offline_access refresh tokens are preserved so long-lived API access can survive the browser session (OIDC Back-Channel Logout 1.0 §2.7). Access-token invalidation on session end is an additional OP hardening choice beyond §2.7, enforced by session liveness, so it holds even when the JWT plugin is disabled.
Delivery runs through the host's background task handler when one is configured (Vercel waitUntil, Cloudflare ctx.waitUntil); without a handler it completes inline so notifications are not lost on request teardown. Configure advanced.backgroundTasks.handler on serverless runtimes to keep sign-out fast.
Discovery at /.well-known/openid-configuration and /.well-known/oauth-authorization-server advertises backchannel_logout_supported: true and backchannel_logout_session_supported: true when the JWT plugin is enabled. Registering a backchannel_logout_uri rejects fragments, non-http(s) schemes, and non-HTTPS targets on confidential clients. Its SSRF host guard, which blocks private, reserved, tunneled, and cloud-metadata hosts, now also covers a private_key_jwt client's jwks_uri.
Schema changes on @better-auth/oauth-provider:
oauthClient.backchannelLogoutUri: string | nulloauthClient.backchannelLogoutSessionRequired: booleanoauthAccessToken.revoked: Date | nullbetter-auth's signJWT gains an optional header argument, forwarded to custom remote signers. JWT profiles that need an explicit media type, such as typ: "logout+jwt", can now set it without reaching for the low-level signing primitives.
feat(oauth-provider)!: enforce max_age (#9936)
feat(oauth-provider)!: make id-token claim authority explicit (#10140)
customIdTokenClaims, extension ID-token claims, and per-issuance idTokenClaims can no longer set OIDC/JWT protocol claims such as issuer, subject, audience, token lifetime, nonce, session or hash binding, auth_time, acr, amr, or azp. Namespaced custom claims still appear in ID tokens.
feat(oauth-provider)!: model OAuth protected resources explicitly (#9648)
validAudiences is removed. Move each existing resource identifier into resources; link clients that should be limited to specific resources through oauthClientResource or Dynamic Client Registration resources.
Access-token issuance now applies resource policy to the requested RFC 8707 resource values. The OAuth provider narrows scopes to resource allowlists, uses the shortest configured TTL, strips reserved RFC 9068 claim names from custom claims, emits jti, and keeps repeated resource form parameters.
Refresh-token TTLs now use the shortest applicable lifetime. Deployments with a per-resource refreshTokenTtl longer than refreshTokenExpiresIn will see refresh tokens expire at the provider default instead of the longer resource value.
JWT signing can now honor per-resource pins. signJWT() accepts signingKeyId and signingAlgorithm; JWKS adapters expose getKeyById() and getLatestKeyByAlg(). The jwks table adds nullable alg and crv columns, and keyPairConfigs can provision multiple algorithms in one keyring.
After upgrading, run npx @better-auth/cli generate and apply the migration before deploying. The migration adds oauthResource, oauthClientResource, and the new jwks columns. Without it, resources using signingAlgorithm cannot find matching keys.
Resource servers should publish RFC 9728 protected-resource metadata at their own origin. The OAuth provider exposes challenge helpers that point clients at that metadata.
@better-auth/mcp now requires an explicit resource option. The plugin stores that identifier as an OAuth resource, publishes RFC 9728 protected-resource metadata for it, and binds issued access tokens to that resource. Existing mcp({ loginPage, consentPage }) setups should add a protected MCP resource identifier, for example resource: "https://api.example.com/mcp".
fix(oauth-provider)!: bind client authentication to the issuing grant (#10063)
fix(oauth-provider)!: bind RFC 8707 resource indicators to the authorization grant (#9836)
Breaking change: when the authorization includes a resource, the token and refresh requests may only narrow it. A request for a resource the authorization did not cover returns invalid_target. The customAccessTokenClaims callback now receives a resources array in place of the resource string.
Migration: run the schema migration (npx @better-auth/cli migrate, or generate if you manage the schema yourself) to add the new resource columns.
fix(oauth-provider)!: return RFC-compliant error envelopes from validation failures (#9277)
An internal createOAuthEndpoint wrapper now translates zod validation failures into the envelope required by RFC 6749 §5.2, 7009 §2.2.1, 7662 §2.3, and 7591 §3.2.2. Failing issues are routed per field:
errorCodesByField[name].missing or the endpoint's defaultError.errorCodesByField[name].invalid or defaultError.defaultError, so RFC 6749 §3.1 malformed requests emit the endpoint's default code regardless of field.All six OAuth endpoints (/oauth2/token, /oauth2/authorize, /oauth2/revoke, /oauth2/introspect, /oauth2/register, /oauth2/end-session) now return RFC-compliant errors for malformed requests. /oauth2/authorize validation failures redirect to the relying party with error, error_description, echoed state, and iss whenever client_id and redirect_uri resolve against the registered client; requests without a trusted RP fall back to the server error page.
Additional RFC compliance fixes on the same endpoints:
/oauth2/revoke and /oauth2/introspect now ignore an unknown token_type_hint instead of rejecting it. RFC 7009 §2.2.1 and RFC 7662 §2.1 reserve unsupported_token_type for the token itself, not the hint value; servers MAY ignore unrecognized hints and search across supported token types./oauth2/authorize error redirects now respect OIDC Core 1.0 §5 response modes. Errors for response_type=token or id_token are delivered in the URL fragment per RFC 6749 §4.2.2.1; an explicit response_mode=query overrides the default.refactor(generic-oauth)!: rewrite as first-class social provider with RFC compliance (#9069)
Breaking changes:
signIn.oauth2({ providerId }) replaced by signIn.social({ provider })oauth2.link() replaced by linkSocial()/api/auth/oauth2/callback/:id to /api/auth/callback/:idgenericOAuthClient() removed; generic OAuth providers now use the standard social client APIspkce defaults to true (was false); set pkce: false for providers that reject PKCEauthorizationUrlParams and tokenUrlParams only accept Record<string, string>issuer and requireIssuerValidation config fields removed; issuer validation is automatic via OIDC discoverymapProfileToUser profile typed as OAuth2UserInfo & Record<string, unknown>at_hash in id tokens per OIDC Core §3.1.3.6 (#9079)id_token claim contributors (#10113)private_key_jwt client authentication (RFC 7523) (#8836)private_key_jwt jti single-use atomic across processes (#9964)redirect_uri conditional at the token endpoint (#10159)response_type errors (#10149)unsupported_token_type for JWT access-token revocation (#9970)For detailed changes, see CHANGELOG
@better-auth/ssofeat(sso)!: support multiple IdP signing certificates (#8805)
SAML signing certificates now accept an array of PEM strings, so administrators can publish a new IdP cert alongside the old one and complete the rotation without forcing every active session to re-authenticate. Responses signed by any listed cert are accepted.
samlConfig: {
idpMetadata: {
cert: [currentPem, nextPem],
},
}
Both samlConfig.cert and samlConfig.idpMetadata.cert accept either a single PEM string or an array. When both are set, idpMetadata.cert wins.
Breaking: response shape
The management endpoints (getSSOProvider, listSSOProviders, updateSSOProvider) now return samlConfig.certificate as an array of parsed certificates in every case, even when a single cert is configured. The field is absent only when certs live inside idpMetadata.metadata. Update consumers to read an array; no more Array.isArray branching.
Validation
Registration now rejects SAML configs that supply no signing-cert source. samlify needs either an idpMetadata.metadata XML document (which embeds the certs) or an explicit PEM under cert or idpMetadata.cert. Configs missing both fail with CERT_SOURCE_MISSING.
Fix
SAML Single Logout could fail to decrypt encrypted LogoutResponse payloads because the IdP entity was constructed without privateKey, encPrivateKey, or encPrivateKeyPass on that code path. All three are now applied on every IdP construction.
fix(auth)!: harden validateUserInfo source contract (#9940)
fix(sso)!: harden SAML response validation (InResponseTo, Audience, SessionIndex) (#9055)
allowIdpInitiated now defaults to false — IdP-initiated SSO (unsolicited SAML responses) is disabled by default. Set saml.allowIdpInitiated: true to restore the previous behavior. This aligns with the SAML2Int interoperability profile which recommends against IdP-initiated SSO due to its susceptibility to injection attacks.extract.inResponseTo (always undefined) instead of samlify's actual path extract.response.inResponseTo. SP-initiated InResponseTo validation now works as intended in both ACS handlers.<AudienceRestriction> element. Audience is now validated against the configured samlConfig.audience value per SAML 2.0 Core §2.5.1.sessionIndex from login responses as { authnInstant, sessionNotOnOrAfter, sessionIndex }, but the code stored the whole object. SLO session-index comparisons always failed silently. The correct inner sessionIndex string is now extracted.validateInResponseTo() and validateAudience() into packages/sso/src/saml/response-validation.ts, eliminating ~160 lines of duplicated validation logic between the two ACS handlers.SAMLAssertionExtract type to match samlify's actual extractor output shape.refactor(sso)!: remove callbackUrl, consolidate ACS endpoint, fix SLO (#9117)
callbackUrl removed from samlConfig.
The ACS URL is now always derived from your baseURL and providerId. Remove callbackUrl from your SAML provider configuration. The post-login redirect destination is set per sign-in via callbackURL in signIn.sso():
await authClient.signIn.sso({
providerId: "my-provider",
callbackURL: "/dashboard",
});
/sso/saml2/callback/:providerId endpoint removed.
Update your IdP's ACS URL to /sso/saml2/sp/acs/:providerId. This endpoint handles both GET and POST requests.
spMetadata is now optional.
You no longer need to pass spMetadata: {} when registering a provider. SP metadata is auto-generated from your configuration.
Removed unused fields from SAMLConfig:
decryptionPvk, additionalParams, idpMetadata.entityURL, idpMetadata.redirectURL. These were stored but never read. Remove them from your configuration if present.
audience is not configured, per SAML Core section 2.5.1.AllowCreate in AuthnRequests, required by IdPs that use JIT provisioning.private_key_jwt client authentication (RFC 7523) (#8836)additionalParams and loginHint (#9305)For detailed changes, see CHANGELOG
@better-auth/mcp ✨feat(mcp)!: ship MCP as its own package built on the OAuth provider (#9992)
The route helper is renamed requireMcpAuth (was withMcpAuth), and the remote client is createMcpResourceClient (was createMcpAuthClient). requireMcpAuth verifies the bearer token against the published JWKS and passes the verified JWT claims to your handler.
To migrate, install @better-auth/mcp, add the jwt() plugin (now required for token signing), and move options that were nested under oidcConfig to flat options on mcp({ ... }). The database models change: oauthApplication becomes oauthClient, with new oauthRefreshToken and oauthClientAssertion tables. Regenerate or migrate your schema with npx auth migrate or npx auth generate.
feat(oauth-provider)!: model OAuth protected resources explicitly (#9648)
validAudiences is removed. Move each existing resource identifier into resources; link clients that should be limited to specific resources through oauthClientResource or Dynamic Client Registration resources.
Access-token issuance now applies resource policy to the requested RFC 8707 resource values. The OAuth provider narrows scopes to resource allowlists, uses the shortest configured TTL, strips reserved RFC 9068 claim names from custom claims, emits jti, and keeps repeated resource form parameters.
Refresh-token TTLs now use the shortest applicable lifetime. Deployments with a per-resource refreshTokenTtl longer than refreshTokenExpiresIn will see refresh tokens expire at the provider default instead of the longer resource value.
JWT signing can now honor per-resource pins. signJWT() accepts signingKeyId and signingAlgorithm; JWKS adapters expose getKeyById() and getLatestKeyByAlg(). The jwks table adds nullable alg and crv columns, and keyPairConfigs can provision multiple algorithms in one keyring.
After upgrading, run npx @better-auth/cli generate and apply the migration before deploying. The migration adds oauthResource, oauthClientResource, and the new jwks columns. Without it, resources using signingAlgorithm cannot find matching keys.
Resource servers should publish RFC 9728 protected-resource metadata at their own origin. The OAuth provider exposes challenge helpers that point clients at that metadata.
@better-auth/mcp now requires an explicit resource option. The plugin stores that identifier as an OAuth resource, publishes RFC 9728 protected-resource metadata for it, and binds issued access tokens to that resource. Existing mcp({ loginPage, consentPage }) setups should add a protected MCP resource identifier, for example resource: "https://api.example.com/mcp".
For detailed changes, see CHANGELOG
@better-auth/scimfeat(scim)!: isolate provider connections by organization (#10249)
SCIM-managed accounts now use namespaced provider IDs (scim:{organizationId}:{providerId} or scim:{providerId} for app-level static providers). Migrate only known SCIM-managed account rows before upgrading; leave non-SCIM accounts unchanged even when they share the same provider ID.
Organization-scoped active: false now makes a user inactive in that organization while keeping SCIM group and team associations available for reactivation. Use DELETE to fully deprovision organization-scoped SCIM state.
defaultSCIM has been replaced by staticProviders. linkExistingUsers.trustedDomains has been removed; use requireExistingOrgMembership, shouldLinkUser, or explicit true instead.
fix(scim)!: always bind personal SCIM connections to their creator (#9840)
generateSCIMToken now records the creator's userId on every personal connection. The generate-token, list-provider-connections, get-provider-connection, and delete-provider-connection endpoints grant access only to that owner. Organization-scoped connections keep their existing behavior and continue to use organization membership and the configured requiredRole checks.
This release is breaking. It removes the providerOwnership option, and owner binding can no longer be disabled. The scimProvider.userId column is now a permanent part of the schema, so run a migration after upgrading with npx auth migrate or npx auth generate.
Connections created before this release carry no owner. Access now fails closed, so those connections are no longer reachable through the management endpoints, including token regeneration. Reclaim them at the database level: delete scimProvider rows that have neither organizationId nor userId, or set userId to the intended owner, then regenerate tokens as needed. Organization-scoped connections are not affected.
For detailed changes, see CHANGELOG
@better-auth/electronfix(electron)!: enforce S256 PKCE and harden origin checks (#9645)
The Electron sign-in flow now mandates PKCE S256. Plain PKCE is rejected: the code_challenge_method parameter is gone and every authorization code is verified by hashing the verifier with SHA-256. The server no longer trusts an electron-origin header to set the request Origin. The Electron client now sends a real Origin (for example myapp:/), so upgrade the @better-auth/electron client and server together and make sure your app's scheme is in trustedOrigins. The unused disableOriginOverride option is removed.
Custom-scheme entries in trustedOrigins now match by scheme and authority instead of string prefix. A host-less entry such as myapp:// or exp:// still trusts every host of that scheme, but a host-bearing entry such as myapp://callback matches that host exactly, so it is no longer satisfied by myapp://callback.attacker.tld.
refactor(generic-oauth)!: rewrite as first-class social provider with RFC compliance (#9069)
Breaking changes:
signIn.oauth2({ providerId }) replaced by signIn.social({ provider })oauth2.link() replaced by linkSocial()/api/auth/oauth2/callback/:id to /api/auth/callback/:idgenericOAuthClient() removed; generic OAuth providers now use the standard social client APIspkce defaults to true (was false); set pkce: false for providers that reject PKCEauthorizationUrlParams and tokenUrlParams only accept Record<string, string>issuer and requireIssuerValidation config fields removed; issuer validation is automatic via OIDC discoverymapProfileToUser profile typed as OAuth2UserInfo & Record<string, unknown>For detailed changes, see CHANGELOG
@better-auth/stripeonSubscriptionCancel.event required (#9531)event (#9359)For detailed changes, see CHANGELOG
@better-auth/corerefactor(oauth)!: verify provider id_tokens with a single shared verifier (#9828)
Client-submitted id_token sign-in (signIn.social({ idToken }) and account linking) is verified by one function instead of a per-provider verifyIdToken method. Each provider declares an idToken config with a JWKS source, issuer, and audience, and the core verifier runs the signature, issuer, audience, and nonce checks. A provider that declares no config rejects the client id_token path.
PayPal previously accepted any decodable id_token without verifying its signature. PayPal derives identity from the access token, so it now declares no idToken config, and the client id_token path returns ID_TOKEN_NOT_SUPPORTED. PayPal sign-in through the redirect flow is unchanged.
Custom providers that implement UpstreamProvider directly replace the removed verifyIdToken method with an idToken config:
idToken: {
jwks: createRemoteJWKSet(new URL("https://issuer.example/.well-known/jwks.json")),
issuer: "https://issuer.example",
audience: clientId,
},
For verification that cannot use a local JWKS, pass idToken: { verify: async (token, nonce) => boolean }. The verifyIdToken and disableIdTokenSignIn provider options are unchanged.
clientAssertion support to the Microsoft Entra ID social provider (#9898)requireEmailVerification for social sign-in (#9929)refreshTokenParams to token endpoint (#9948)includeGrantedScopes option (#10129)private_key_jwt client authentication (RFC 7523) (#8836)additionalParams and loginHint (#9305)client_id SSRF checks through the shared host classifier (#10126)For detailed changes, see CHANGELOG
authgrantedScopes string[] (#9825)resolveModule for auth config loading (#9477)For detailed changes, see CHANGELOG
@better-auth/api-keyFor detailed changes, see CHANGELOG
@better-auth/exporefactor(generic-oauth)!: rewrite as first-class social provider with RFC compliance (#9069)
Breaking changes:
signIn.oauth2({ providerId }) replaced by signIn.social({ provider })oauth2.link() replaced by linkSocial()/api/auth/oauth2/callback/:id to /api/auth/callback/:idgenericOAuthClient() removed; generic OAuth providers now use the standard social client APIspkce defaults to true (was false); set pkce: false for providers that reject PKCEauthorizationUrlParams and tokenUrlParams only accept Record<string, string>issuer and requireIssuerValidation config fields removed; issuer validation is automatic via OIDC discoverymapProfileToUser profile typed as OAuth2UserInfo & Record<string, unknown>For detailed changes, see CHANGELOG
@better-auth/cimd ✨For detailed changes, see CHANGELOG
@better-auth/drizzle-adapterFor detailed changes, see CHANGELOG
@better-auth/i18nFor detailed changes, see CHANGELOG
Thanks to everyone who contributed to this release:
@adrianmxb, @app/better-release, @brentmitchell25, @bytaesu, @GautamBytes, @gustavovalverde, @ItalyPaleAle, @OscarCornish, @pi0, @ping-maxwell, @ruban-s, @sovetski, @yordis
Full changelog: v1.6.22...v1.7.0-rc.0
Bundled dependencies were refreshed to their latest compatible releases, including jose, nanostores, the noble crypto packages, and SimpleWebAuthn. Th
better-authAPIError properties (#8734)schema option in device authorization to be optional under Zod v4 (#9939)Max-Age to be capped at the configured expiresIn value (#9621)displayUsername fallbacks (#10182)For detailed changes, see CHANGELOG
@better-auth/ssohttp and https schemes (#10225)For detailed changes, see CHANGELOG
authdisableMigration to be honored for plugin schema tables (#10198)BETTER_AUTH_SECRET to use 32 characters instead of 16 (#10186)For detailed changes, see CHANGELOG
@better-auth/api-keyFor detailed changes, see CHANGELOG
@better-auth/drizzle-adapter@better-auth/drizzle-adapter/relations-v2 entry point (#9489)For detailed changes, see CHANGELOG
@better-auth/i18nFor detailed changes, see CHANGELOG
@better-auth/kysely-adapternull when an update matches no rows (#10180)For detailed changes, see CHANGELOG
@better-auth/mcprefreshTokenReuseInterval option, defaulting to 30 seconds, so native/public clients can retry a refresh if a prior token rotation raced against it (#10145)For detailed changes, see CHANGELOG
@better-auth/oauth-providerrefreshTokenReuseInterval to allow the OAuth provider to replay refresh token responses for duplicate requests within a configurable time window (#10145)For detailed changes, see CHANGELOG
@better-auth/scimactive attribute (#10242)For detailed changes, see CHANGELOG
Thanks to everyone who contributed to this release:
@adityachaudhary99, @Bekacru, @benpsnyder, @bytaesu, @dipan-ck, @gustavovalverde, @moonevm, @Paola3stefania, @ping-maxwell, @rachit367, @sleepe229, @WilsonnnTan
Full changelog: v1.7.0-beta.9...v1.7.0-beta.10
#10170 6ddb555 Thanks @gustavovalverde! - Bundled dependencies were refreshed to their latest compatible releases, including jose, nanostores, the noble crypto packages, and SimpleWebAuthn. These updates are backward compatible and require no changes to existing projects.
Updated dependencies [ea06c5a]:
Restricted customIdTokenClaims, extension ID-token claims, and per-issuance idTokenClaims from overriding protected OIDC/JWT protocol claims
@better-auth/oauth-providercustomIdTokenClaims, extension ID-token claims, and per-issuance idTokenClaims from overriding protected OIDC/JWT protocol claims (#10140)Migration: Remove any
iss,sub,aud,exp,nonce,auth_time,acr,amr, orazpfields fromcustomIdTokenClaims, extension ID-token claims, and per-issuanceidTokenClaims. Use namespaced custom claims (e.g.,"https://example.com/role") for application-specific data instead.
clientRegistrationRequirePKCE: false is set (#10146)claims.userinfo authorization request parameter, allowing clients to request specific standard claims from the UserInfo endpoint (#10156)application/x-www-form-urlencoded POST request bodies (#10155)offline_access when the authorization includes both openid scope and a nonce (#10153)request and request_uri parameters (#10151)profile and email scope claims, and added rejection of unsupported acr_values in authorization requests (#10152)redirect_uri when the original authorization request included one, and to return invalid_grant on mismatches (#10159)response_type to redirect errors to the client redirect URI instead of the provider error page (#10149)invalid_grant and revoke all tokens previously issued from the replayed code (#10150)invalid_grant when a client attempts to use a refresh token issued to a different client (#10154)For detailed changes, see CHANGELOG
Thanks to everyone who contributed to this release:
@gustavovalverde
Full changelog: v1.7.0-beta.8...v1.7.0-beta.9
Fixed OAuth account creation to roll back the user row when account writes fail
better-authoverrideUserInfo returns null during account linking (#10124)For detailed changes, see CHANGELOG
@better-auth/coreincludeGrantedScopes option to the Google provider to control scope accumulation across OAuth flows (#10129)For detailed changes, see CHANGELOG
authFor detailed changes, see CHANGELOG
Thanks to everyone who contributed to this release:
@gustavovalverde
Full changelog: v1.7.0-beta.7...v1.7.0-beta.8
#10127 7c7313c Thanks @gustavovalverde! - OAuth sign-in, account linking, callback, and proxy flows now build redirect_uri from the current request base URL when baseURL.allowedHosts is configured. Built-in social providers and generic OAuth providers now use the resolved request host for redirects in multi-host deployments.
Custom OAuthProvider implementations can omit callbackPath when using the shared /callback/<provider-id> route. Set callbackPath only for custom callback routes.
#10124 06daf70 Thanks @gustavovalverde! - Preserve the resolved OAuth user when overrideUserInfo returns null during account linking.
#10125 a83152e Thanks @gustavovalverde! - Create new OAuth accounts in the user creation transaction so failed account writes roll back the user row.
#10128 97903c9 Thanks @gustavovalverde! - Preserve previously granted OAuth scopes across sign-in re-authentication and refresh-token requests. account.scope now accumulates monotonically: newly granted scopes are merged in only when added via linkSocial, and providers returning a narrower scope claim than the user has granted no longer shrink the stored value.
Updated dependencies [7c7313c, 97903c9, 3a79aff]:
Added refreshTokenParams config to forward extra parameters to the token endpoint during token refresh
better-authrefreshTokenParams config to forward extra parameters to the token endpoint during token refresh (#9948)For detailed changes, see CHANGELOG
@better-auth/corerefreshTokenParams config to forward extra parameters to the token endpoint during token refresh (#9948)client_id host validation by routing checks through the shared host classifier, blocking additional non-public address forms (#10126)For detailed changes, see CHANGELOG
@better-auth/oauth-providersessionId to ID token claim contributors, accessible via input.sessionId in claims.idToken and claims.accessToken contributors (#10113)For detailed changes, see CHANGELOG
Thanks to everyone who contributed to this release:
@gustavovalverde, @yordis
Full changelog: v1.7.0-beta.6...v1.7.0-beta.7
#9948 3d04fab Thanks @yordis! - feat(generic-oauth): add refreshTokenParams config to forward extra params on token refresh
Multi-tenant OIDC providers (Zitadel multi-org, Auth0 with audience) need to send extra body params on the refresh call to rescope tokens without a full authorization redirect. The generic-oauth plugin now accepts a refreshTokenParams option (object or sync/async function) that is merged into the refresh request body, with grant_type and refresh_token protected from override. The function form receives request metadata for the request that triggered the refresh, so request-scoped data (headers, cookies) is available without out-of-band state like AsyncLocalStorage.
UpstreamProvider.refreshAccessToken now accepts an optional second ctx argument; the change is backwards compatible because existing implementations that take only refreshToken remain valid. See #7554.
3d04fab, de8394d]:
Removed the deprecated oidcProvider plugin from better-auth/plugins
better-authMigration: Replace partial endpoint paths like
/sign-inwith explicit wildcards such as/sign-in/*or/sign-in/**in your captcha plugin configuration.
@better-auth/mcp, built on @better-auth/oauth-provider (#9992)Migration: Install
@better-auth/mcp, add thejwt()plugin, update imports frombetter-auth/pluginsto@better-auth/mcp, renamewithMcpAuthtorequireMcpAuthandcreateMcpAuthClienttocreateMcpResourceClient, then runnpx auth migrateto apply schema changes (oauthApplicationbecomesoauthClient, with newoauthRefreshTokenandoauthClientAssertiontables).
validAudiences with a resource-first configuration API (#9648)Migration: Replace
validAudienceswithresources, link clients throughoauthClientResource, then runnpx @better-auth/cli generateand apply the migration to addoauthResource,oauthClientResource, and newjwkscolumns before deploying.
baseURL resolution to ignore x-forwarded-host by default, preventing forwarded headers from selecting an unintended allowed host (#9134)Migration: If your proxy exposes the public hostname only through
x-forwarded-host, addadvanced: { trustedProxyHeaders: true }to yourbetterAuth()config. Deployments where the proxy rewritesHostdirectly (nginx default, Vercel, Cloudflare, Netlify) are unaffected.
Migration: Configure
oneTap({ clientId: "your-google-client-id" })or setsocialProviders.google.clientIdin your Better Auth config.
oidcProvider plugin from better-auth/plugins (#10031)Migration: Replace
oidcProviderfrombetter-auth/pluginswith@better-auth/oauth-providerfor OIDC authorization-server integrations.
Cache-Control: no-store on all OAuth credential responses to prevent proxies and browsers from caching tokens (#10065)auth.api.consumePhoneNumberOTP for verifying and consuming phone OTP codes server-side without modifying users or sessions (#9766)sendVerificationEmail errors to propagate to callers instead of being silently swallowed (#8863)setUserPassword in the admin plugin to create a credential account when one does not already exist (#9482)updateSession to include plugin-defined session fields (#9777)last-login-method cookie clearing to include the domain attribute, ensuring cross-subdomain cookies are removed correctly (#9319)additionalData returned to the caller (#10067)updateMemberRole to reject unknown or empty role values with a proper error (#9962)For detailed changes, see CHANGELOG
@better-auth/oauth-provider@better-auth/mcp, built on @better-auth/oauth-provider (#9992)Migration: Install
@better-auth/mcp, add thejwt()plugin, update imports frombetter-auth/pluginsto@better-auth/mcp, renamewithMcpAuthtorequireMcpAuthandcreateMcpAuthClienttocreateMcpResourceClient, then runnpx auth migrateto apply schema changes (oauthApplicationbecomesoauthClient, with newoauthRefreshTokenandoauthClientAssertiontables).
validAudiences with a resource-first configuration API (#9648)Migration: Replace
validAudienceswithresources, link clients throughoauthClientResource, then runnpx @better-auth/cli generateand apply the migration to addoauthResource,oauthClientResource, and newjwkscolumns before deploying.
Migration: Update custom
clientAuthenticationstrategies to return{ clientId }instead of{ clientId, client }, and remove thegrantTypeargument fromprovider.authenticateClient()calls in custom grant handlers.
Cache-Control: no-store on all OAuth credential responses to prevent proxies and browsers from caching tokens (#10065)/oauth2/userinfo to return a WWW-Authenticate challenge when the access token is invalid, expired, or revoked (#10068)For detailed changes, see CHANGELOG
@better-auth/mcp ✨@better-auth/mcp, built on @better-auth/oauth-provider (#9992)Migration: Install
@better-auth/mcp, add thejwt()plugin, update imports frombetter-auth/pluginsto@better-auth/mcp, renamewithMcpAuthtorequireMcpAuthandcreateMcpAuthClienttocreateMcpResourceClient, then runnpx auth migrateto apply schema changes (oauthApplicationbecomesoauthClient, with newoauthRefreshTokenandoauthClientAssertiontables).
validAudiences with a resource-first configuration API (#9648)Migration: Add a
resourceoption to yourmcp({ ... })configuration (for example,resource: "https://api.example.com/mcp"), replacevalidAudienceswithresources, then runnpx @better-auth/cli generateand apply the migration before deploying.
For detailed changes, see CHANGELOG
@better-auth/api-keyMigration: Custom adapters must implement the new
incrementOneprimitive natively. CustomBetterAuthRateLimitStorageimplementations must replace the separateget/setpattern with a single atomicconsumemethod.
For detailed changes, see CHANGELOG
authgenerate command to correctly handle a directory path passed to --output (#9564)defaultValue for additionalField definitions (#10048)Unsupported() field types without failing (#10011)For detailed changes, see CHANGELOG
@better-auth/ssoadditionalFields support to ssoProvider for storing and returning custom SSO provider data (#9445)For detailed changes, see CHANGELOG
@better-auth/coreCache-Control: no-store on all OAuth credential responses to prevent proxies and browsers from caching tokens (#10065)For detailed changes, see CHANGELOG
@better-auth/expolinkSocial flow to send the session cookie when linking an account via an ID token (#9953)For detailed changes, see CHANGELOG
@better-auth/scimFor detailed changes, see CHANGELOG
@better-auth/drizzle-adapterFor detailed changes, see CHANGELOG
@better-auth/electronFor detailed changes, see CHANGELOG
@better-auth/kysely-adapterFor detailed changes, see CHANGELOG
@better-auth/mongo-adapterFor detailed changes, see CHANGELOG
@better-auth/passkeyFor detailed changes, see CHANGELOG
@better-auth/stripeFor detailed changes, see CHANGELOG
Thanks to everyone who contributed to this release:
@arnnvv, @Bekacru, @brentmitchell25, @brone1323, @bytaesu, @ChrisMGeo, @ElGauchooooo, @GautamBytes, @gustavovalverde, @ping-maxwell, @SferaDev, @tsushanth, @Tushar-Khandelwal-2004
Full changelog: v1.7.0-beta.5...v1.7.0-beta.6
#10004 b36c38f Thanks @bytaesu! - The captcha plugin now requires endpoint entries to match full auth paths unless they use wildcard patterns. This prevents requests like /sign-in//email from bypassing captcha while preserving trailing-slash matches like /sign-in/email/. To protect multiple routes, replace partial paths like /sign-in with explicit wildcards such as /sign-in/* or /sign-in/**.
#9766 bf39cbf Thanks @GautamBytes! - Add a server-only auth.api.consumePhoneNumberOTP API for custom phone OTP flows that need to verify and consume a code without creating or updating users or sessions.
#9992 e53582c Thanks @gustavovalverde! - The MCP plugin moves out of better-auth into its own package, @better-auth/mcp, built on @better-auth/oauth-provider. Import the server plugin and its helpers from @better-auth/mcp, and the remote client and adapters from @better-auth/mcp/client and @better-auth/mcp/client/adapters (previously imported from better-auth/plugins and better-auth/plugins/mcp/client). The OAuth endpoints move from /mcp/* to /oauth2/*, with discovery at /.well-known/oauth-authorization-server and protected resource metadata at /.well-known/oauth-protected-resource. Discovery-based MCP clients pick up the new locations on their own.
The route helper is renamed requireMcpAuth (was withMcpAuth), and the remote client is createMcpResourceClient (was createMcpAuthClient). requireMcpAuth verifies the bearer token against the published JWKS and passes the verified JWT claims to your handler.
To migrate, install @better-auth/mcp, add the jwt() plugin (now required for token signing), and move options that were nested under oidcConfig to flat options on mcp({ ... }). The database models change: oauthApplication becomes oauthClient, with new oauthRefreshToken and oauthClientAssertion tables. Regenerate or migrate your schema with npx auth migrate or npx auth generate.
#10039 aedcb97 Thanks @gustavovalverde! - feat(oauth-provider)!: DPoP-bound access tokens (RFC 9449)
OAuth provider integrations can issue and verify DPoP sender-constrained tokens. Clients request them with dpop_bound_access_tokens at registration, dpop_jkt on the authorization request, or by targeting a resource configured with dpopBoundAccessTokensRequired. Issued tokens carry cnf.jkt, return token_type: "DPoP", and stay bound through refresh-token rotation, introspection, and userinfo.
Resource servers verify DPoP requests with verifyAccessTokenRequest, which checks the Authorization: DPoP scheme, the proof, the request target, the access-token hash, and proof replay. The MCP package advertises DPoP in protected resource metadata and verifies DPoP-bound requests. Proof replay is rejected through the database-backed verification store, so anti-replay holds across instances. verifyAccessTokenRequest and requireMcpAuth use that store by default; build one with createDpopReplayStore(internalAdapter) or pass a custom dpop.replayStore. This needs database-backed verification storage: a secondary-storage-only deployment rejects DPoP requests rather than skipping replay protection.
Breaking: the raw-token verifier verifyAccessToken is renamed to verifyBearerToken, both in better-auth/oauth2 and as the oauthProviderResourceClient action, and it rejects DPoP-bound tokens. Use verifyAccessTokenRequest on any endpoint that may receive them. The resource-request input type is renamed from AccessTokenRequestInput to ResourceRequestInput, and the DPoP algorithm option is signingAlgorithms everywhere.
Run a schema migration for the DPoP token-binding fields: the confirmation column on the access-token and refresh-token tables. DPoP-bound clients also gain dpopBoundAccessTokens and resources dpopBoundAccessTokensRequired. No dedicated replay table is added; proof replay reuses the verification store.
#9648 d2a79ba Thanks @brentmitchell25! - OAuth provider now models protected resources explicitly. Configure them with resources or create them through the oauthResource admin API. Each resource can define token TTLs, allowed scopes, custom JWT claims, and JWT signing pins.
validAudiences is removed. Move each existing resource identifier into resources; link clients that should be limited to specific resources through oauthClientResource or Dynamic Client Registration resources.
Access-token issuance now applies resource policy to the requested RFC 8707 resource values. The OAuth provider narrows scopes to resource allowlists, uses the shortest configured TTL, strips reserved RFC 9068 claim names from custom claims, emits jti, and keeps repeated resource form parameters.
Refresh-token TTLs now use the shortest applicable lifetime. Deployments with a per-resource refreshTokenTtl longer than refreshTokenExpiresIn will see refresh tokens expire at the provider default instead of the longer resource value.
JWT signing can now honor per-resource pins. signJWT() accepts signingKeyId and signingAlgorithm; JWKS adapters expose getKeyById() and getLatestKeyByAlg(). The jwks table adds nullable alg and crv columns, and keyPairConfigs can provision multiple algorithms in one keyring.
After upgrading, run npx @better-auth/cli generate and apply the migration before deploying. The migration adds oauthResource, oauthClientResource, and the new jwks columns. Without it, resources using signingAlgorithm cannot find matching keys.
Resource servers should publish RFC 9728 protected-resource metadata at their own origin. The OAuth provider exposes challenge helpers that point clients at that metadata.
@better-auth/mcp now requires an explicit resource option. The plugin stores that identifier as an OAuth resource, publishes RFC 9728 protected-resource metadata for it, and binds issued access tokens to that resource. Existing mcp({ loginPage, consentPage }) setups should add a protected MCP resource identifier, for example resource: "https://api.example.com/mcp".
#8931 34558bc Thanks @GautamBytes! - Add opt-in JWKS-backed asymmetric JWT support for session_data cookie cache tokens, so services can verify cookie-cache JWTs with public keys instead of shared secrets.
#9134 652fa53 Thanks @gustavovalverde! - The dynamic baseURL config now ignores x-forwarded-host and x-forwarded-proto unless you set advanced.trustedProxyHeaders: true.
Requests using baseURL: { allowedHosts } now resolve the auth origin from Host by default, so forwarded headers cannot select another allowed host unless trusted proxy headers are enabled.
Breaking change: if your proxy exposes the public hostname only through x-forwarded-host, set advanced.trustedProxyHeaders: true. Deployments where the proxy rewrites Host to the public hostname (nginx default, Vercel, Cloudflare, and Netlify) are unaffected.
Migration:
betterAuth({
baseURL: { allowedHosts: [...] },
advanced: {
trustedProxyHeaders: true,
},
});
#10031 6fe9faa Thanks @gustavovalverde! - Remove the deprecated oidcProvider plugin from better-auth/plugins. Migrate OIDC authorization-server integrations to @better-auth/oauth-provider.
#10036 ad35ead Thanks @bytaesu! - Require Google One Tap server callbacks to resolve a Google client ID before verifying ID tokens. Configure oneTap({ clientId }) or socialProviders.google.clientId when using the One Tap plugin.
#10014 73541c1 Thanks @gustavovalverde! - Cloudflare Workers apps can now start when importing Better Auth subpaths such as better-auth/db. Beta builds were crashing during module initialization before application code ran.
#10065 2196ea6 Thanks @gustavovalverde! - OAuth and device-authorization responses that carry credentials now consistently send Cache-Control: no-store and Pragma: no-cache, so proxies, CDNs, and browsers never cache them. This covers the token, introspection, and userinfo endpoints, dynamic and admin client registration, client secret rotation, and the device code and device token responses, including the error responses from those endpoints.
Endpoints declare this with metadata: { noStore: true }, and the header set is exported from @better-auth/core as NO_STORE_HEADERS for responses built by hand.
Updated dependencies [aedcb97, 2196ea6]:
Consolidated id_token verification for social providers into a single shared verifier
better-authid_token verification for social providers into a single shared verifier (#9828)Migration: Custom providers implementing
UpstreamProvidermust replace the removedverifyIdTokenmethod with anidTokenconfig object containingjwks,issuer, andaudience. For verification without a local JWKS, passidToken: { verify: async (token, nonce) => boolean }. PayPal no longer supports client-submittedid_tokensign-in (signIn.social({ idToken })); the redirect flow is unchanged.
clientAssertion support to the Microsoft Entra ID social provider (#9898)requireEmailVerification option for social sign-in (#9929)id_token verification and client-submitted id_token sign-in for genericOAuth providers configured with a discoveryUrl (#9966)null for optional fields (#9841)listSessions (#9865)USER_NOT_FOUND when attempting to update a non-existent user (#9875)Origin/Referer validation on cookieless email sign-in and sign-up (#9973)getSessionCookie to prefer the __Secure- prefixed cookie when available (#9806)listUserInvitations always requires a verified session, and requireEmailVerificationOnInvitation applies only to by-ID recipient operations (#9877)secondaryStorage (#9969)update-session and token routes to respect server-side session deletion (#9967)For detailed changes, see CHANGELOG
@better-auth/oauth-providerMigration: Access tokens whose bound session has ended now return
{ active: false }at introspection and are rejected at/oauth2/userinfo. Runmigrate/generateto add three new schema fields:oauthClient.backchannelLogoutUri,oauthClient.backchannelLogoutSessionRequired, andoauthAccessToken.revoked. On serverless runtimes, configureadvanced.backgroundTasks.handlerto keep sign-out latency low.
max_age parameter so users are now prompted to re-authenticate when their session exceeds the requested age (#9936)Migration: Flows that relied on
max_agebeing silently ignored will now prompt users to log in again. No configuration change is required.
private_key_jwt JTI replay prevention to be atomic across processes (#9964)unsupported_token_type instead of a misleading success response (#9970)For detailed changes, see CHANGELOG
@better-auth/ssovalidateUserInfo source contract for SSO providers (#9940)Migration: In
validateUserInfocallbacks, OIDC and SAML SSO sign-ins now passsource.sso(withssoProviderIdand provider claims or assertion attributes) instead ofsource.oauth. Update any callbacks that inspect provider data for SSO flows to read fromsource.ssowhensource.methodis'sso'.
user.validateUserInfo provisioning gate to allow rejecting identities before user creation or account linking (#9864)AuthnRequest consumption to be atomic (#9972)ERR_SUBJECT_UNCONFIRMED errors by passing clockSkew to samlify's clockDrifts (#9748)For detailed changes, see CHANGELOG
@better-auth/electronMigration: Upgrade both the
@better-auth/electronclient and server together, and ensure your app's custom scheme is listed intrustedOrigins. ThedisableOriginOverrideoption is removed. Custom-scheme entries intrustedOriginsnow match by scheme and authority instead of string prefix, somyapp://callbackno longer matchesmyapp://callback.attacker.tld.
For detailed changes, see CHANGELOG
authscope string to an accumulated grantedScopes array, preserving incremental grants across sign-ins (#9825)Migration: Run
migrate/generateto add thegrantedScopescolumn, then backfill fromaccount.scopeby splitting on commas and whitespace, trimming and deduping tokens. Encoding varies by adapter: native array on PostgreSQL with Drizzle/Prisma,jsonbwith Kysely, JSON string array on MySQL/SQLite/MSSQL. Drop the legacyscopecolumn after verifying. Custom providers must renameOAuthProvidertoUpstreamProviderand removedefaultScopes.
For detailed changes, see CHANGELOG
@better-auth/kysely-adapterkysely/migration (#9811)For detailed changes, see CHANGELOG
@better-auth/passkeyFor detailed changes, see CHANGELOG
Thanks to everyone who contributed to this release:
@Bekacru, @bytaesu, @GautamBytes, @gustavovalverde, @ItalyPaleAle, @ping-maxwell, @seebykilian, @WilsonnnTan, @zeroknowledge0x
Full changelog: v1.7.0-beta.4...v1.7.0-beta.5
#9930 0cbaf81 Thanks @gustavovalverde! - Anonymous account linking now works after social and generic OAuth sign-in in Expo and other in-app browsers, where the OAuth callback returns without the session cookie. onLinkAccount fires and the anonymous user is migrated; before, it was silently skipped.
Plugins can now carry server-trusted data across an OAuth redirect with the new addOAuthServerContext API, read back on the callback via getOAuthState().serverContext. Unlike additionalData, it cannot be set from the request body, so it is the right place for values the server must trust.
For @better-auth/oauth-provider, the post-login authorization query now travels through that server-only channel, so it can no longer be injected through additionalData.
#9645 e014029 Thanks @ping-maxwell! - Harden the Electron OAuth flow and tighten custom-scheme trusted-origin matching.
The Electron sign-in flow now mandates PKCE S256. Plain PKCE is rejected: the code_challenge_method parameter is gone and every authorization code is verified by hashing the verifier with SHA-256. The server no longer trusts an electron-origin header to set the request Origin. The Electron client now sends a real Origin (for example myapp:/), so upgrade the @better-auth/electron client and server together and make sure your app's scheme is in trustedOrigins. The unused disableOriginOverride option is removed.
Custom-scheme entries in trustedOrigins now match by scheme and authority instead of string prefix. A host-less entry such as myapp:// or exp:// still trusts every host of that scheme, but a host-bearing entry such as myapp://callback matches that host exactly, so it is no longer satisfied by myapp://callback.attacker.tld.
#9966 ec8a38c Thanks @gustavovalverde! - genericOAuth providers configured with a discoveryUrl now verify the provider's id_token against its published JWKS (signature, issuer, audience, and advertised algorithms). A sign-in whose id_token fails verification is rejected.
These providers also accept client-submitted id_token sign-in through signIn.social({ idToken }), which previously returned ID_TOKEN_NOT_SUPPORTED.
Providers configured with explicit endpoints instead of discoveryUrl are unchanged.
#9828 4f53b61 Thanks @gustavovalverde! - Verify social-provider id_tokens with a single shared verifier.
Client-submitted id_token sign-in (signIn.social({ idToken }) and account linking) is verified by one function instead of a per-provider verifyIdToken method. Each provider declares an idToken config with a JWKS source, issuer, and audience, and the core verifier runs the signature, issuer, audience, and nonce checks. A provider that declares no config rejects the client id_token path.
PayPal previously accepted any decodable id_token without verifying its signature. PayPal derives identity from the access token, so it now declares no idToken config, and the client id_token path returns ID_TOKEN_NOT_SUPPORTED. PayPal sign-in through the redirect flow is unchanged.
Custom providers that implement OAuthProvider directly replace the removed verifyIdToken method with an idToken config:
idToken: {
jwks: createRemoteJWKSet(new URL("https://issuer.example/.well-known/jwks.json")),
issuer: "https://issuer.example",
audience: clientId,
},
For verification that cannot use a local JWKS, pass idToken: { verify: async (token, nonce) => boolean }. The verifyIdToken and disableIdTokenSignIn provider options are unchanged.
#9929 91f235f Thanks @gustavovalverde! - Add requireEmailVerification to OAuth provider options, for built-in social providers and the Generic OAuth plugin. When a provider reports an unverified email, the user and account are still created or linked, but no session is issued: the OAuth callback redirects with ?error=email_not_verified, and ID token and One Tap sign-in return 403 EMAIL_NOT_VERIFIED. Verification emails follow the existing emailVerification.sendOnSignUp / sendOnSignIn settings.
It is opt-in per provider and does not inherit emailAndPassword.requireEmailVerification, so existing social logins keep working. The gate checks the local user's verification state, so a user verified through another method keeps access. Only enable it for providers that report a trustworthy email_verified signal.
#9969 76a3342 Thanks @gustavovalverde! - Signing out with secondaryStorage and session.preserveSessionInDatabase now runs your configured session.delete hooks and marks the preserved session row as ended. OAuth Provider access and refresh tokens bound to that session are revoked and back-channel logout is dispatched on sign-out. Previously these hooks were skipped in this setup, so the tokens stayed valid until they expired.
#9864 41cca60 Thanks @GautamBytes! - Add a user.validateUserInfo provisioning gate that lets applications reject an identity before a user is created or a new account is linked. It runs once at the creation step for every method that provisions a user (OAuth, SSO/SAML, email/password, magic link, email OTP, anonymous, SIWE, phone number, admin-created users, and SCIM), including stateless setups with no persistent database.
It also re-runs when an existing OAuth or SSO user signs in again (source.action is "sign-in"), where it receives the fresh provider email and profile so a domain or org policy can reject a user whose provider identity moved out of bounds. Non-provider returning sign-ins are not re-validated.
The callback receives the mapped user plus a source describing the action (create-user, link-account, or sign-in), the method, and provider metadata: source.oauth for OAuth providers and source.sso for OIDC/SAML SSO providers. Return { error, errorDescription } to reject: browser flows redirect to the error URL and programmatic flows return a 403.
#9898 7fe0e2b Thanks @ItalyPaleAle! - Add clientAssertion support to the Microsoft Entra ID social provider.
#9304 e0d2b9e Thanks @gustavovalverde! - Propagate sign-out to every connected app and cut off API access immediately, via OIDC Back-Channel Logout 1.0.
When a user's session ends at the OP (sign-out, /oauth2/end-session, admin revoke, ban), @better-auth/oauth-provider now notifies every Relying Party that holds tokens for that session. The user's API access is cut off right away, instead of access tokens staying usable until their own TTL. Each client opts in by registering a backchannel_logout_uri (and optionally backchannel_logout_session_required) via DCR or the admin client-create endpoint. The provider signs a logout+jwt Logout Token per client and POSTs it to that client in parallel, with a short per-RP timeout.
Breaking change. Introspection of an opaque or JWT access token whose bound session has ended now returns { active: false }, and /oauth2/userinfo rejects it with invalid_token. Previously the token stayed active until its own TTL. If you relied on access tokens outliving the user's session, that no longer holds.
Refresh tokens without offline_access are revoked on session end; offline_access refresh tokens are preserved so long-lived API access can survive the browser session (OIDC Back-Channel Logout 1.0 §2.7). Access-token invalidation on session end is an additional OP hardening choice beyond §2.7, enforced by session liveness, so it holds even when the JWT plugin is disabled.
Delivery runs through the host's background task handler when one is configured (Vercel waitUntil, Cloudflare ctx.waitUntil); without a handler it completes inline so notifications are not lost on request teardown. Configure advanced.backgroundTasks.handler on serverless runtimes to keep sign-out fast.
Discovery at /.well-known/openid-configuration and /.well-known/oauth-authorization-server advertises backchannel_logout_supported: true and backchannel_logout_session_supported: true when the JWT plugin is enabled. Registering a backchannel_logout_uri rejects fragments, non-http(s) schemes, and non-HTTPS targets on confidential clients. Its SSRF host guard, which blocks private, reserved, tunneled, and cloud-metadata hosts, now also covers a private_key_jwt client's jwks_uri.
Schema changes on @better-auth/oauth-provider:
oauthClient.backchannelLogoutUri: string | nulloauthClient.backchannelLogoutSessionRequired: booleanoauthAccessToken.revoked: Date | nullbetter-auth's signJWT gains an optional header argument, forwarded to custom remote signers. JWT profiles that need an explicit media type, such as typ: "logout+jwt", can now set it without reaching for the low-level signing primitives.
Updated dependencies [7fe0e2b, 4f53b61, 91f235f, 41cca60]:
Fixed security vulnerabilities flagged by Dependabot
better-authaccountInfo calls without requiring session headers (#9813)getMigration field index order (#9691)changeEmail config gate and URL-encoded the callbackURL (#9614)callbackURL in verify-email links (#9792)storeStateStrategy to default to "database" when using secondaryStorage (#9591)AdminClientOptions and OrganizationClientOptions (#9642)onLinkAccount callback not being called during email verification sign-in (#9548)/sign-in/email-otp endpoint (#9596)parseJSON to correctly decode escape sequences in quoted strings (#9617)getTrustedOrigins to respect the dynamic baseURL protocol option (#9644)consumeOne fallback to throw on non-numeric deleteMany results (#9831)sendVerificationEmail callback to receive a cloned request (#9619)accessTokenExpiresIn for OAuth providers that omit expires_in (#9799)result.error verbatim in callback redirects (#9723)updateUserInfoOnLink not being applied during OAuth account linking (#8758)redirectOnError (#9788)errorCallbackURL when state validation fails (#9789)jose token verification errors (#9655)refresh_token grant (#9576)none algorithm, disable plain PKCE by default, and reject requests missing a PKCE method (#9575)operationIds for multi-method endpoints (#9721)null logo (#9842)ipv6Subnet type to accept wider values (#9545)createUser endpoint (#9464)For detailed changes, see CHANGELOG
@better-auth/oauth-providerMigration: The
customAccessTokenClaimscallback now receives aresourcesarray instead of aresourcestring. Runnpx @better-auth/cli migrate(orgenerateif you manage the schema yourself) to add the new resource columns.
consumeVerificationValue to return null for expired rows (#9624)clientPrivileges (#9837)NOT_FOUND when referencing a missing client (#9600)redirect_uri scheme validation in OIDC provider and MCP (#9838)For detailed changes, see CHANGELOG
@better-auth/ssoMigration:
samlConfig.certificatefromgetSSOProvider,listSSOProviders, andupdateSSOProvidernow always returns an array, even when a single certificate is configured. Update consumers to read an array unconditionally.
additionalParams and loginHint to signIn.social, linkSocial, and signIn.sso (#9305)errorCallbackURL across auth callback flows (#9702)internalAdapter helpers (#9818)For detailed changes, see CHANGELOG
@better-auth/scimMigration: The
providerOwnershipoption has been removed and owner binding is now always enforced. Runnpx auth migrateornpx auth generateto add thescimProvider.userIdcolumn. Connections created before this release with no owner are no longer reachable via management endpoints; reclaim them by settinguserIdat the database level, then regenerate tokens as needed.
For detailed changes, see CHANGELOG
@better-auth/stripeonSubscriptionCancel event parameter required (#9531)Migration: Update your
onSubscriptionCancelcallback to declareeventas a required parameter and remove anyundefinedguards around it.
For detailed changes, see CHANGELOG
@better-auth/api-keybetter-call as a peer dependency (#9759)429 instead of 401 (#9505)configId is omitted (#9794)requireEmailVerificationOnInvitation to be enabled by default and extended the gate to get and list endpoints (#9577)For detailed changes, see CHANGELOG
authcreate-admin CLI command for creating an initial admin user (#9547)claimOne adapter primitive (#9560)claimOne adapter primitive to consumeOne (#9568)For detailed changes, see CHANGELOG
@better-auth/drizzle-adapterAND/OR query handling in the Drizzle adapter (#9756)For detailed changes, see CHANGELOG
@better-auth/passkeyFor detailed changes, see CHANGELOG
@better-auth/electronFor detailed changes, see CHANGELOG
@better-auth/expoFor detailed changes, see CHANGELOG
@better-auth/kysely-adapterFor detailed changes, see CHANGELOG
Thanks to everyone who contributed to this release:
@app/better-release, @bytaesu, @chdanielmueller, @cyphercodes, @dipan-ck, @GautamBytes, @gustavovalverde, @ItalyPaleAle, @jsj, @kgarg2468, @Kvizas, @OscarCornish, @Paola3stefania, @ping-maxwell, @reslear, @stewartjarod, @Vishesh-Verma-07
Full changelog: v1.7.0-beta.3...v1.7.0-beta.4
Made the Auth instance directly fetchable
better-authAuth instance directly fetchable (#9431)hydrateSession to seed the client with a server-fetched session so useSession returns data on the first render (#8733)POST /sign-in/social which incorrectly declared required fields (#9268)useSession to revalidate correctly after admin impersonation (#9402)Set-Cookie headers being sent on redirect responses (#9497)autoSignIn is disabled (#8839)TypeError caused by non-ASCII characters in an OAuth error_description during redirect (#9065)deleteAccount parameter name from accountId to id in the internal adapter (#9503)mapProfileToUser to serve as a fallback for OAuth providers that may omit the email field (#9331)beforeCreateTeam and beforeCreateInvitation hooks to allow passing a custom id (#9253)cancelPendingInvitationsOnReInvite being unreachable because re-invite incorrectly returned 400 (#9453)TS2742 error by re-exporting field types when using additionalFields (#9349)setActiveTeam to correctly scope team selection to the active organization (#9239)getNonce client alias in the SIWE plugin (#9461)callbackURL on sign-in (#9475)For detailed changes, see CHANGELOG
@better-auth/stripeonSubscriptionUpdate to expose the stripeSubscription object and corrected a stale snapshot issue (#9354)getCheckoutSessionParams (#9481)onSubscriptionDeleted and trial callbacks to receive the post-update subscription instead of the stale one (#9356)getCheckoutSessionParams to preserve freeTrial and internal metadata during merging (#9474)For detailed changes, see CHANGELOG
@better-auth/oauth-providerstate parameter is provided (#9328)prompt=login to be honored correctly throughout the consent continuation flow (#9344)For detailed changes, see CHANGELOG
@better-auth/passkeyexactOptionalPropertyTypes incompatibility in the passkey plugin (#9270)For detailed changes, see CHANGELOG
authc12 v4's resolveModule for more reliable module resolution (#9477)For detailed changes, see CHANGELOG
@better-auth/api-keyapi.verifyApiKey to correctly validate keys against the configId (#9393)For detailed changes, see CHANGELOG
@better-auth/i18nFor detailed changes, see CHANGELOG
@better-auth/ssospMetadata to use findSAMLProvider so that the default SSO configuration works correctly (#9398)For detailed changes, see CHANGELOG
Thanks to everyone who contributed to this release:
@adrianmxb, @baptisteArno, @bytaesu, @Craga89, @cyphercodes, @dipan-ck, @erquhart, @GautamBytes, @gustavovalverde, @IcanDivideBy0, @jaydeep-pipaliya, @mausic, @onmax, @pi0, @ping-maxwell, @sovetski, @zllovesuki
Full changelog: v1.7.0-beta.2...v1.7.0-beta.3
#8733 4e8e4c7 Thanks @bytaesu! - Add hydrateSession to seed the client with a server-fetched session so useSession returns data on the first render.
#9431 523f95c Thanks @pi0! - feat: make Auth instance fetchable
#9240 729c00d Thanks @adrianmxb! - feat(username): add immutable username option
This allows users to set their username during sign-up or first update, but prevents changing it to a different value afterwards. Users can still update other profile fields.
Required patched drizzle-orm ^0.45.2 and kysely ^0.28.14 peer versions to track vulnerability fixes
better-authuserId and organizationId parameters to the listUserTeams API for scoped team lookups without switching the active organization (#8977)forceAllowId UUIDs being ignored on PostgreSQL adapters when advanced.database.generateId is set to "uuid" (#9068)APIError is thrown (#9211)$sessionSignal not being triggered for session-rotating endpoints (#9087)partitioned cookie attribute being dropped on set-cookie round-trips (#9235)./instrumentation module to export a no-op in browser and edge environments (#9281)disableRefresh query parameter validation in custom sessions to correctly coerce string values to booleans (#9214)updateUser to allow removing a phone number (#9219)callbackOnVerification not being called when updatePhoneNumber is enabled (#4894)For detailed changes, see CHANGELOG
@better-auth/oauth-provider{ error, error_description } error envelopes for validation failures (#9277)Migration: All six OAuth endpoints (
/oauth2/token,/oauth2/authorize,/oauth2/revoke,/oauth2/introspect,/oauth2/register,/oauth2/end-session) now emit structured{ error, error_description }responses per RFC 6749 §5.2. Update any client code that previously parsed the raw validation error format from these endpoints.
Authorization header when called via auth.api (#9244)For detailed changes, see CHANGELOG
@better-auth/api-keymapConcurrent utility for bounded-concurrency iteration (#9227)For detailed changes, see CHANGELOG
@better-auth/drizzle-adapterdrizzle-orm ^0.45.2 and kysely ^0.28.14 peer versions to track vulnerability fixes (#9165)For detailed changes, see CHANGELOG
@better-auth/expoSecureStore on app startup (#8953)For detailed changes, see CHANGELOG
@better-auth/passkeyFor detailed changes, see CHANGELOG
Thanks to everyone who contributed to this release:
@bytaesu, @GautamBytes, @gustavovalverde, @Kinfe123, @ouwargui, @ping-maxwell, @ramonclaudio, @ruban-s, @stewartjarod, @TanishValesha, @terijaki
Full changelog: v1.7.0-beta.1...v1.7.0-beta.2
954b664 Thanks @ruban-s! - allow passing userId and organizationId to the listUserTeams API. userId lets callers list teams for another member of an organization (gated behind the member:update permission). organizationId scopes the result to a specific organization without needing to switch the session's active organization, matching the pattern used by addTeamMember/removeTeamMember.#9205 9aed910 Thanks @gustavovalverde! - fix(two-factor): revert enforcement broadening from #9122
Restores the pre-#9122 enforcement scope. 2FA is challenged only on /sign-in/email, /sign-in/username, and /sign-in/phone-number, matching the behavior that shipped through v1.6.2. Non-credential sign-in flows (magic link, email OTP, OAuth, SSO, passkey, SIWE, one-tap, phone-number OTP, device authorization, email-verification auto-sign-in) are no longer gated by a 2FA challenge by default.
A broader enforcement scope with per-method opt-outs and alignment to NIST SP 800-63B-4 authenticator assurance levels is planned for a future minor release.
#9068 acbd6ef Thanks @GautamBytes! - Fix forced UUID user IDs from create hooks being ignored on PostgreSQL adapters when advanced.database.generateId is set to "uuid".
#9165 39d6af2 Thanks @gustavovalverde! - chore(adapters): require patched drizzle-orm and kysely peer versions
Narrows the drizzle-orm peer to ^0.45.2 and the kysely peer to ^0.28.14. Both new ranges track the minor line that carries the vulnerability fix and nothing newer, so the adapters only advertise support for versions that have actually been tested against. Consumers on older ORM releases see an install-time warning and can upgrade alongside the adapter; the peer is marked optional, so installs do not hard-fail.
Updated dependencies [39d6af2]:
Fixed a prototype pollution vulnerability in the Stripe plugin when handling user-supplied metadata
better-authbaseURL resolution from request headers for direct auth.api calls (#9113)isMounted timing issues (#9078)storeBackupCodes storage strategy after verification (#7231)For detailed changes, see CHANGELOG
@better-auth/oauth-providerMigration: Replace
signIn.oauth2({ providerId })withsignIn.social({ provider }),oauth2.link()withlinkSocial(), and update your IdP callback URLs from/api/auth/oauth2/callback/:idto/api/auth/callback/:id. RemovegenericOAuthClient(),issuer, andrequireIssuerValidationfrom your config. Setpkce: falsefor providers that reject PKCE challenges.
customTokenResponseFields callback to inject custom fields into token endpoint responses, and hardened authorization code validation (#9118)at_hash claim to ID tokens to cryptographically bind them to their access tokens, per OIDC Core §3.1.3.6 (#9079)baseURL resolution to correctly handle trusted proxy headers, loopback addresses, and forwarded requests in plugin metadata helpers (#9131)For detailed changes, see CHANGELOG
@better-auth/ssocallbackUrl from samlConfig, and fixed SLO session matching (#9117)Migration: Remove
callbackUrlfromsamlConfig(the ACS URL is now auto-derived frombaseURLandproviderId) and update your IdP's ACS URL to/sso/saml2/sp/acs/:providerId. RemovedecryptionPvk,additionalParams,idpMetadata.entityURL, andidpMetadata.redirectURLfromSAMLConfigif present. ThespMetadatafield is now optional and can be removed.
samlify to 2.12.0, adding XPath injection protection and XXE prevention for SAML XML processing (#9121)For detailed changes, see CHANGELOG
@better-auth/cimd ✨@better-auth/cimd plugin for Client ID Metadata Document support, enabling URL-based client identification for MCP and dynamic client discovery flows (#9159)For package details, see README
@better-auth/stripeFor detailed changes, see CHANGELOG
Thanks to everyone who contributed to this release:
@bytaesu, @Byte-Biscuit, @gustavovalverde, @ping-maxwell
Full changelog: v1.7.0-beta.0...v1.7.0-beta.1
#9069 c7d2253 Thanks @gustavovalverde! - Rewrite the generic OAuth plugin as a first-class social provider with OAuth 2.1 security defaults. Providers now use signIn.social + callback/:id instead of dedicated plugin endpoints, with PKCE required by default (OAuth 2.1), RFC 9207 issuer validation, OIDC auto-discovery with openid scope injection, and typed provider IDs.
Breaking changes:
signIn.oauth2({ providerId }) replaced by signIn.social({ provider })oauth2.link() replaced by linkSocial()/api/auth/oauth2/callback/:id to /api/auth/callback/:idgenericOAuthClient() removed; generic OAuth providers now use the standard social client APIspkce defaults to true (was false); set pkce: false for providers that reject PKCEauthorizationUrlParams and tokenUrlParams only accept Record<string, string>issuer and requireIssuerValidation config fields removed; issuer validation is automatic via OIDC discoverymapProfileToUser profile typed as OAuth2UserInfo & Record<string, unknown>#9079 6f2948e Thanks @gustavovalverde! - feat(oauth-provider): compute at_hash in ID tokens per OIDC Core §3.1.3.6
ID tokens issued alongside an access token now include the at_hash claim, which cryptographically binds the two tokens to prevent token substitution attacks. The hash algorithm is selected based on the actual signing key's algorithm (EdDSA/Ed25519 uses SHA-512, RS/ES/PS384 uses SHA-384, RS/ES/PS512 uses SHA-512, all others use SHA-256).
A new resolveSigningKey() export is available from better-auth/plugins to resolve the current JWKS signing key (including its algorithm). When using a custom jwt.sign callback, the signed ID token's header is validated against the declared algorithm to prevent at_hash mismatches.
#9131 5142e9c Thanks @gustavovalverde! - harden dynamic baseURL handling for direct auth.api.* calls and plugin metadata helpers
Direct auth.api.* calls
APIError with a clear message when the baseURL can't be resolved (no source and no fallback), instead of leaving ctx.context.baseURL = "" for downstream plugins to crash on.allowedHosts mismatches on the direct-API path to APIError.advanced.trustedProxyHeaders on the dynamic path (default true, unchanged). Previously x-forwarded-host / -proto were unconditionally trusted with allowedHosts; they now go through the same gate as the static path. The default flip to false ships in a follow-up PR.resolveRequestContext rehydrates trustedProviders and cookies per call (in addition to trustedOrigins). User-defined trustedOrigins(req) / trustedProviders(req) callbacks receive a Request synthesized from forwarded headers when no full Request is available.http for loopback hosts (localhost, 127.0.0.1, [::1], 0.0.0.0) on the headers-only protocol fallback, so local-dev calls don't silently resolve to https://localhost:3000.hasRequest uses isRequestLike, which now rejects objects that spoof Symbol.toStringTag without a real url / headers.get shape.Plugin metadata helpers
oauthProviderAuthServerMetadata, oauthProviderOpenIdConfigMetadata, oAuthDiscoveryMetadata, and oAuthProtectedResourceMetadata forward the incoming request to their chained auth.api calls, so issuer and discovery URLs reflect the request host on dynamic configs.withMcpAuth forwards the incoming request to getMcpSession, threads trustedProxyHeaders, and emits a bare Bearer challenge when baseURL can't be resolved (instead of Bearer resource_metadata="undefined/...").metadataResponse in @better-auth/oauth-provider normalizes headers via new Headers() so callers can pass Headers, tuple arrays, or records without silently dropping entries.#9122 484ce6a Thanks @gustavovalverde! - fix(two-factor): enforce 2FA on all sign-in paths
The 2FA after-hook now triggers on any endpoint that creates a new session, covering magic-link, OAuth, passkey, email-OTP, SIWE, and all future sign-in methods. Authenticated requests (session refreshes, profile updates) are excluded.
#7231 f875897 Thanks @Byte-Biscuit! - fix(two-factor): preserve backup codes storage format after verification
After using a backup code, remaining codes are now re-saved using the same storeBackupCodes strategy (plain, encrypted, or custom) configured by the user. Previously, codes were always re-encrypted with the built-in symmetric encryption, breaking subsequent verifications for plain or custom storage modes.
#9078 9a6d475 Thanks @ping-maxwell! - fix(client): prevent isMounted race condition causing many rps
#9113 513dabb Thanks @bytaesu! - resolve dynamic baseURL from request headers on direct auth.api calls
Updated dependencies []:
feat(two-factor)!: add OTP enablement and discriminated response
better-authfeat(two-factor)!: add OTP enablement and discriminated response (#9057)
enableTwoFactor now accepts a method parameter ("otp" | "totp", default "totp") and returns a discriminated response with a method field.
method: "otp"twoFactorEnabled: true immediately.{ method: "otp" }.otpOptions.sendOTP to be configured on the server; rejects with OTP_NOT_CONFIGURED otherwise.method: "totp" (default){ method: "totp", totpURI, backupCodes }.TOTP_NOT_CONFIGURED if totpOptions.disable is set.skipVerificationOnEnable: use method: "otp" for immediate activation, or the standard TOTP verification flow.enableTwoFactor includes a method field in the response ("otp" or "totp").operationId in password reset callback endpoint (#9072)For detailed changes, see CHANGELOG
@better-auth/ssofix(sso)!: harden SAML response validation (InResponseTo, Audience, SessionIndex) (#9055)
allowIdpInitiated now defaults to false — IdP-initiated SSO (unsolicited SAML responses) is disabled by default. Set saml.allowIdpInitiated: true to restore the previous behavior. This aligns with the SAML2Int interoperability profile which recommends against IdP-initiated SSO due to its susceptibility to injection attacks.extract.inResponseTo (always undefined) instead of samlify's actual path extract.response.inResponseTo. SP-initiated InResponseTo validation now works as intended in both ACS handlers.<AudienceRestriction> element. Audience is now validated against the configured samlConfig.audience value per SAML 2.0 Core §2.5.1.sessionIndex from login responses as { authnInstant, sessionNotOnOrAfter, sessionIndex }, but the code stored the whole object. SLO session-index comparisons always failed silently. The correct inner sessionIndex string is now extracted.validateInResponseTo() and validateAudience() into packages/sso/src/saml/response-validation.ts, eliminating ~160 lines of duplicated validation logic between the two ACS handlers.SAMLAssertionExtract type to match samlify's actual extractor output shape.For detailed changes, see CHANGELOG
@better-auth/oauth-providerprivate_key_jwt client authentication (RFC 7523) (#8836)For detailed changes, see CHANGELOG
authFor detailed changes, see CHANGELOG
Thanks to everyone who contributed to this release:
@bytaesu, @gustavovalverde, @Oluwatobi-Mustapha, @ramonclaudio
Full changelog: v1.6.2...v1.7.0-beta.0
#8836 93d3871 Thanks @gustavovalverde! - Add private_key_jwt (RFC 7523) client authentication across the stack. Servers verify JWT client assertions signed with asymmetric keys; clients sign them for authorization code, refresh, and client credentials flows.
#9057 544f1c6 Thanks @gustavovalverde! - feat(two-factor)!: add OTP-only enablement and remove skipVerificationOnEnable
enableTwoFactor now accepts a method parameter ("otp" | "totp", default "totp") and returns a discriminated response with a method field.
method: "otp"twoFactorEnabled: true immediately.{ method: "otp" }.otpOptions.sendOTP to be configured on the server; rejects with OTP_NOT_CONFIGURED otherwise.method: "totp" (default){ method: "totp", totpURI, backupCodes }.TOTP_NOT_CONFIGURED if totpOptions.disable is set.skipVerificationOnEnable: use method: "otp" for immediate activation, or the standard TOTP verification flow.enableTwoFactor includes a method field in the response ("otp" or "totp").Fixed ACCOUNT_NOT_FOUND when retrieving an access token after stateless OAuth sign-in links a new provider to an existing user
better-authACCOUNT_NOT_FOUND when retrieving an access token after stateless OAuth sign-in links a new provider to an existing user (#11300)For detailed changes, see CHANGELOG
@better-auth/ssosamlConfig.callbackUrl as their ACS URL without spMetadata.metadata, which had failed with invalid_saml_response since 1.6.21 (#11730)For detailed changes, see CHANGELOG
Thanks to everyone who contributed to this release:
@bytaesu, @gustavovalverde
Full changelog: v1.6.33...v1.6.34
Fixed database option type inference for projects that do not use Cloudflare Workers.
@better-auth/coreFor detailed changes, see CHANGELOG
Thanks to everyone who contributed to this release:
@better-release[bot]
Full changelog: v1.6.32...v1.6.33
Improved diagnostics for Cloudflare Turnstile verification failures
better-authFor detailed changes, see CHANGELOG
Thanks to everyone who contributed to this release:
@better-release[bot]
Full changelog: v1.6.31...v1.6.32
Added an option to disable OpenTelemetry span creation for individual auth instances
better-authFor detailed changes, see CHANGELOG
@better-auth/coreFor detailed changes, see CHANGELOG
Thanks to everyone who contributed to this release:
@better-release[bot]
Full changelog: v1.6.30...v1.6.31
Fixed concurrent cold-start requests from intermittently losing authentication or transaction context due to an async storage initialization race
better-authFor detailed changes, see CHANGELOG
@better-auth/sso409 with SSO_PROVIDER_CHANGED if the provider changes during DNS resolution so callers can reload and retry.For detailed changes, see CHANGELOG
Thanks to everyone who contributed to this release:
@bytaesu
Full changelog: v1.6.29...v1.6.30
07c1718]:
Improved deleteSessions performance by running deletes in parallel instead of sequentially
better-authdeleteSessions performance by running deletes in parallel instead of sequentially (#10805)For detailed changes, see CHANGELOG
@better-auth/sso409 with SSO_PROVIDER_CHANGED if the provider changes during DNS verification so callers can reload and retry.For detailed changes, see CHANGELOG
Thanks to everyone who contributed to this release:
@Emmaccen
Full changelog: v1.6.28...v1.6.29
#10805 e6e1b4e Thanks @Emmaccen! - Speed up batch session revocation when secondary storage is enabled by deleting sessions in parallel.
Updated dependencies []:
Prevented duplicate session requests during React Suspense retries while preserving revalidation for interrupted refreshes
better-authFor detailed changes, see the CHANGELOG.
@better-auth/electronFor detailed changes, see the CHANGELOG.
@better-auth/expoFor detailed changes, see the CHANGELOG.
Thanks to everyone who contributed to this release:
Full changelog: v1.6.27...v1.6.28
#10769 773de54 Thanks @bytaesu! - Prevent duplicate session requests during transient remounts while ensuring incomplete refreshes are revalidated.
#10794 2ad2928 Thanks @bytaesu! - Restore client plugin declaration compatibility for downstream TypeScript consumers.
Updated dependencies []:
Fixed duplicate session requests being made across Suspense retries
better-authFor detailed changes, see CHANGELOG
@better-auth/scimbetter-call (#10657)For detailed changes, see CHANGELOG
authFor detailed changes, see CHANGELOG
Thanks to everyone who contributed to this release:
@bytaesu
Full changelog: v1.6.26...v1.6.27
#10657 2ae491e Thanks @bytaesu! - Aligned endpoint and middleware context types with runtime route parameters, and preserved response headers when resolving sessions from endpoint contexts.
#10676 90b5093 Thanks @bytaesu! - Deduplicate in-flight session requests when React retries a suspended component.
Updated dependencies [2ae491e]:
Fixed session cleanup on user deletion to also remove sessions from secondary storage
better-authfindSessions to skip invalid secondary-storage session entries without discarding other valid sessions (#10580)jwtClient() collapsing createAuthClient type inference when combined with other client plugins (#10513)oAuthProxy to preserve Apple user data from form_post callbacks (#10599)oneTapClient() collapsing createAuthClient type inference when combined with other client plugins (#10635)nextCookies performance in instrumented Next.js applications by reusing the next/headers import promise (#10467)For detailed changes, see CHANGELOG
@better-auth/coreplaceholder.invalid domain (#10576)For detailed changes, see CHANGELOG
@better-auth/redis-storagelistKeys() and clear() to use SCAN instead of KEYS so large keyspaces no longer block the Redis server (#10507)For detailed changes, see CHANGELOG
Thanks to everyone who contributed to this release:
@bytaesu, @Emmaccen, @gustavovalverde, @jashkarangiya, @jeroenvandermerwe, @jlucaso1, @krish-vachhani, @mrosberghaus, @XXMOHAMED012
Full changelog: v1.6.25...v1.6.26
#10619 9ede805 Thanks @jeroenvandermerwe! - Ensure database rate-limit cleanup completes when no background task handler is configured.
#10608 5a811f1 Thanks @bytaesu! - Pass the email verification type to custom OTP generators after email sign-up.
#10605 d8327f1 Thanks @XXMOHAMED012! - The email OTP verification check no longer reveals whether an email is registered before the OTP itself is verified.
#10513 e2c73fb Thanks @mrosberghaus! - Fix jwtClient() collapsing createAuthClient type inference when combined with other client plugins such as inferAdditionalFields. Additional user fields (for example on updateUser) are preserved again.
#10635 af50c45 Thanks @krish-vachhani! - Fix oneTapClient() collapsing createAuthClient type inference when combined with other client plugins. The oneTap action is available on the client again.
#10633 701cd43 Thanks @gustavovalverde! - Minting or reading a JWKS signing key inside an active database transaction now uses the transaction-scoped adapter instead of the root connection. On a single-connection SQLite database with native transactions enabled, this no longer deadlocks, and on Postgres and MySQL the key commits with the surrounding transaction instead of independently of it.
#10599 e7b0eba Thanks @bytaesu! - Preserve Apple user data from form_post callbacks when using oAuthProxy.
#10552 2b4a14f Thanks @bytaesu! - Allow users to retry email OTP password resets after entering an invalid password.
#10467 7552a3b Thanks @jlucaso1! - Improve nextCookies performance in instrumented Next.js applications.
#10580 ea38fca Thanks @Emmaccen! - Skip invalid secondary-storage session entries without discarding other valid sessions.
#10520 a03e4c1 Thanks @bytaesu! - Ensure deleting a user also removes their sessions from secondary storage.
Updated dependencies [a30e274]:
Fixed Apple OAuth not sending the PKCE code challenge during authorization, causing token exchange failures
better-auth$fetch and $store not being exposed on the Solid client (#10444)modelName was set to another table's schema key (e.g. user.modelName = "account").For detailed changes, see CHANGELOG
Thanks to everyone who contributed to this release:
@birkskyum, @jsj, @krish-vachhani
Full changelog: v1.6.24...v1.6.25
#10479 5124c34 Thanks @krish-vachhani! - Prevent Google One Tap from creating new users when sign-up is disabled for the Google provider.
#10444 7439359 Thanks @birkskyum! - Expose the real $fetch instance and $store atoms from the Solid client instead of resolving them as dynamic API routes.
Updated dependencies [0ffd1fb]:
Added request context (ctx) as a third argument to verifyIdToken, enabling custom ID token verifiers to read request headers
better-authctx) as a third argument to verifyIdToken, enabling custom ID token verifiers to read request headers (#10376)beforeStoreCookie option to the last-login-method plugin for GDPR compliance (#5753)get-session endpoint to include no-store cache control headers, preventing stale session data from being served (#10222)BIGINT as a valid number type, preventing spurious pending changes on rate limiter columns (#10316)useSession({ throw: true }) incorrectly excluding null from its data type (#9787)CookieAttributes index signature type to be more precise (#10442)user.modelName was set to a value that collides with another schema key (#10235)unique and index (#10357)Origin header on cookieless requests, preventing cross-origin abuse (#10368)username and displayUsername) in /sign-up/email and /update-user request bodies (#10453)organization.listMembers failing with "User not found for member" for organizations with more than ~100 members (#10342)advanced.database.generateId is configured, matching the behavior of other models (#10040)getDefaultModelName to prefer exact schema key matches over modelName aliases, preventing adapter queries from being misrouted when a built-in table's name collides with another schema keyFor detailed changes, see CHANGELOG
authunique and index (#10333)relationName values (#10352)auth generate failing when the config file imports the not-yet-generated output file (e.g. on a Convex first run) (#10302)For detailed changes, see CHANGELOG
@better-auth/electron>=36.0.0) (#10440)/electron/init-oauth-proxy forwarding multiple Set-Cookie headers as a single comma-joined string, which caused the browser to drop the transfer-token cookie during OAuth handoff (#9672)For detailed changes, see CHANGELOG
@better-auth/coreAsyncLocalStorage initialization on serverless cold starts (e.g. Cloudflare Workers) (#9862)For detailed changes, see CHANGELOG
@better-auth/ssoidpInitiatedCallbackUrl (#10388)For detailed changes, see CHANGELOG
@better-auth/stripebeforeDeleteOrganization and afterDeleteOrganization hooks not receiving the endpoint context as the second argument (#10190)For detailed changes, see CHANGELOG
Thanks to everyone who contributed to this release:
@akshatmalik-bruh, @ayushman46, @c-nicol, @gaurav-init, @gaurav0107, @GautamBytes, @momomuchu, @OrangeManLi, @paoloricciuti, @ping-maxwell, @shiminshen, @swithek, @Tushar-Khandelwal-2004, @vinay-oppuri
Full changelog: v1.6.23...v1.6.24
#10235 03dc5a0 Thanks @ping-maxwell! - Fixes silent foreign-key and adapter-join misrouting when a user remaps a built-in model name to a string that collides with another schema key
#10357 7508940 Thanks @c-nicol! - Fixes Kysely migration generation for new-table fields that are both unique: true and index: true.
#10342 bae7198 Thanks @ping-maxwell! - Fix organization.listMembers failing with "User not found for member" for orgs with more than ~100 members by applying the same membership limit to the users query.
#10336 ef4d273 Thanks @Tushar-Khandelwal-2004! - Prevent verification callbacks from failing auth requests when cloning the request throws.
#10333 99dbdd7 Thanks @c-nicol! - Fixes Drizzle schema generation for fields that are both unique: true and index: true.
#10368 086ca91 Thanks @gaurav0107! - Force-validate the request Origin on the magic-link (/sign-in/magic-link) and email-otp (/email-otp/send-verification-otp) send endpoints, including cookieless requests, to match the built-in /sign-in/email and /sign-up/email routes. A cookieless cross-origin POST can no longer trigger a magic-link or verification-OTP email to an arbitrary address. Cookieless requests that carry no Origin (server-to-server) are unaffected.
#10290 8f2dedd Thanks @GautamBytes! - Expose the remote MCP auth client's 401 challenge headers to browser clients using CORS.
#10453 4e685ee Thanks @ping-maxwell! - OpenAPI now includes user.additionalFields and plugin user schema fields (e.g. username plugin username / displayUsername) on /sign-up/email and /update-user request bodies.
#10190 3bf0e49 Thanks @gaurav-init! - Pass the endpoint context as the second argument to beforeDeleteOrganization and afterDeleteOrganization hooks in the organization plugin, matching the signature shown in the docs and the existing databaseHooks pattern. The Stripe plugin's beforeDeleteOrganization wrapper now forwards the context to user-supplied hooks instead of dropping it.
#10040 f59a0ee Thanks @shiminshen! - Organization invitations now let the database generate their id when ID generation is delegated to the database (e.g. advanced.database.generateId: "uuid" with a UUID-capable adapter such as Postgres), matching every other model. Previously createInvitation always generated the invitation id in application code, so invitation rows received an app-generated value instead of a database-generated one while organizations, members and teams correctly deferred to the database (better-auth/better-auth#10024). A caller-provided id (e.g. via beforeCreateInvitation) is still honored.
#10302 0f2cc1b Thanks @momomuchu! - Prefer exact schema-key matches over modelName aliases in getDefaultModelName, so remapping a built-in table onto another table's schema key (e.g. user.modelName = "account") does not reroute internal adapter queries to the wrong table.
#9787 ae78109 Thanks @ping-maxwell! - Fixes an issue where useSession({ throw: true }) incorrectly excluded null from its data type.
#10222 46d2bf0 Thanks @ping-maxwell! - fix: add no-store cache-control headers to get-session route
#10316 29a373e Thanks @vinay-oppuri! - Recognize SQLite BIGINT as a valid number type in migration diffs so database-backed rate limiter columns like lastRequest no longer report spurious pending changes on every run.
#10379 f6d18fa Thanks @ping-maxwell! - fix(client): restore auth query revalidation and signal listeners after remount
#5753 f23ce50 Thanks @ping-maxwell! - feat(last-login-method): beforeStoreCookie option for GDPR compliance
#10376 c4d1dda Thanks @ping-maxwell! - Pass the request endpoint context as a third argument to verifyIdToken, so custom ID token verifiers can read request headers (for example Apple's user-agent requirement).
Updated dependencies [6758231, 54fab08, c4d1dda]:
Added Yandex as a social OAuth provider
better-authFor detailed changes, see CHANGELOG
@better-auth/drizzle-adapterFor detailed changes, see CHANGELOG
@better-auth/stripeFor detailed changes, see CHANGELOG
authFor detailed changes, see CHANGELOG
Thanks to everyone who contributed to this release:
@bytaesu, @vladflotsky
Full changelog: v1.6.22...v1.6.23
#9138 8581f97 Thanks @vladflotsky! - Add a pre-configured Yandex provider helper for the generic OAuth plugin.
Updated dependencies [930b260]:
Fixed unproven credentials not being revoked during magic link and email OTP sign-in
better-authFor detailed changes, see CHANGELOG
@better-auth/scimactive attribute (#10242)For detailed changes, see CHANGELOG
@better-auth/stripeFor detailed changes, see CHANGELOG
authFor detailed changes, see CHANGELOG
Thanks to everyone who contributed to this release:
@gustavovalverde
Full changelog: v1.6.21...v1.6.22
#10239 c06a56d Thanks @gustavovalverde! - Magic-link and email-OTP sign-in now reset the credentials on an account whose email had never been confirmed. When verification resolves to such an account, any existing password on it is removed and its sessions are revoked before the user is signed in, so proven control of the mailbox is the source of truth for the account.
If you signed up with email and password but first signed in through a magic link or email OTP rather than confirming the verification email, your password is cleared and you will need to set a new one through password reset.
#10240 3a035e9 Thanks @gustavovalverde! - Add account-level lockout for two-factor verification. The attempt limit applies per account across sign-in challenges and across factors: TOTP, email-OTP, and backup codes share one counter, and a successful verification resets it.
Enabled by default: an account locks for 15 minutes after 10 consecutive failed verifications, and locked attempts return 429 with the ACCOUNT_TEMPORARILY_LOCKED error code. Configure it with twoFactor({ accountLockout: { enabled, maxFailedAttempts, durationSeconds } }).
Run a database migration after upgrading: this adds failedVerificationCount and lockedUntil columns to the twoFactor table.
Updated dependencies [8bd43d9]:
One column per month.