Skip to content

fix(deps): update dependency better-auth to v1.6.2 [security]#1046

Open
renovate[bot] wants to merge 1 commit into
masterfrom
renovate/npm-better-auth-vulnerability
Open

fix(deps): update dependency better-auth to v1.6.2 [security]#1046
renovate[bot] wants to merge 1 commit into
masterfrom
renovate/npm-better-auth-vulnerability

Conversation

@renovate
Copy link
Copy Markdown
Contributor

@renovate renovate Bot commented May 15, 2026

ℹ️ Note

This PR body was truncated due to platform limits.

This PR contains the following updates:

Package Change Age Confidence
better-auth (source) 1.4.181.6.2 age confidence

Better Auth: OAuth callback accepts mismatched state when cookie-backed state storage is used without PKCE

GHSA-wxw3-q3m9-c3jr

More information

Details

Am I affected?

Users are affected if all of the following are true:

  • The application uses better-auth at a version below 1.6.2 (or @better-auth/sso paired with such a version).
  • betterAuth({ account: { storeStateStrategy } }) is set to "cookie". The default "database" is not affected.
  • The application wires at least one OAuth provider through genericOAuth({ config }) with pkce: false, or it supplies a custom getToken or tokenUrl that does not require the stored codeVerifier. Stock social providers with PKCE on are not affected.
  • The provider returns arbitrary code values to the configured callback URL.

If users are on better-auth@1.6.2 or later, they are not affected.

Fix:

  1. Upgrade to better-auth@1.6.2 or later (current stable is 1.6.10).
  2. If users cannot upgrade, see workarounds below.
Summary

In parseGenericState, the cookie branch decrypted the oauth_state cookie and validated expiry, but did not compare the incoming OAuth state query parameter to the nonce that generateGenericState issued at sign-in. Any callback to /api/auth/oauth2/callback/<providerId> that arrived with a forged state and any code was therefore accepted as long as the browser still held a live oauth_state cookie. With pkce: false (or any getToken path that does not enforce a code-verifier round-trip), an attacker who forced the victim to deliver an attacker-controlled authorization code to the callback would mint a session bound to the attacker's external identity in the victim's browser. Account-linking flows behaved the same way, binding the attacker's external account to an authenticated victim row.

Details

The cookie branch of parseGenericState did not compare the cookie's stored nonce to the incoming state parameter. The database branch (the default) was not affected because the verification row is keyed by state and the lookup itself enforces equality.

The fix re-binds the cookie to the nonce: generateGenericState writes oauthState: state into the encrypted payload before storage, and parseGenericState rejects when parsedData.oauthState !== state. The same primitive covers every caller (generic-oauth, social, account-link, oauth-proxy passthrough, OIDC SSO, SAML relay state).

Patches

Fixed in better-auth@1.6.2 via PR #​8949 (commit 9deb7936a, merged 2026-04-09). The cookie branch of parseGenericState now rejects when the encrypted payload's nonce does not match the incoming state parameter; the database branch gained a defense-in-depth equality check.

Workarounds

If users cannot upgrade immediately:

  • Switch storeStateStrategy back to "database" (the default). This closes the cookie-only bypass without a code change.
  • Enable pkce: true on every affected genericOAuth provider. The codeVerifier is the missing primitive that the attacker cannot supply.
Impact
  • Forced-login (CSRF on OAuth callback): the attacker forces the victim's browser into an authenticated session bound to the attacker's external identity, allowing the attacker to observe the victim's actions inside the application.
  • Persistent account linking: account-link flows bind the attacker's external account to the victim's authenticated row, granting persistent access until the link is removed.
Credit

Reported by @​Jvr2022 via private advisory disclosure, and by @​alavesa (PatchPilots audit) via the public duplicate issue #​8897.

Resources

Severity

  • CVSS Score: 5.3 / 10 (Medium)
  • Vector String: CVSS:3.1/AV:N/AC:H/PR:N/UI:R/S:U/C:N/I:H/A:N

References

This data is provided by the GitHub Advisory Database (CC-BY 4.0).


Release Notes

better-auth/better-auth (better-auth)

v1.6.2

Compare Source

Patch Changes
  • #​8949 9deb793 Thanks @​ping-maxwell! - security: verify OAuth state parameter against cookie-stored nonce to prevent CSRF on cookie-backed flows

  • #​8983 2cbcb9b Thanks @​jaydeep-pipaliya! - fix(oauth2): prevent cross-provider account collision in link-social callback

    The link-social callback used findAccount(accountId) which matched by account ID across all providers. When two providers return the same numeric ID (e.g. both Google and GitHub assign 99999), the lookup could match the wrong provider's account, causing a spurious account_already_linked_to_different_user error or silently updating the wrong account's tokens.

    Replaced with findAccountByProviderId(accountId, providerId) to scope the lookup to the correct provider, matching the pattern already used in the generic OAuth plugin.

  • #​9059 b20fa42 Thanks @​gustavovalverde! - fix(next-js): replace cookie probe with header-based RSC detection in nextCookies() to prevent infinite router refresh loops and eliminate leaked __better-auth-cookie-store cookie. Also fix two-factor enrollment flows to set the new session cookie before deleting the old session.

  • #​9058 608d8c3 Thanks @​gustavovalverde! - fix(sso): include RelayState in signed SAML AuthnRequests per SAML 2.0 Bindings §3.4.4.1

    • RelayState is now passed to samlify's ServiceProvider constructor so it is included in the redirect binding signature. Previously it was appended after the signature, causing spec-compliant IdPs to reject signed AuthnRequests.
    • authnRequestsSigned: true without a private key now throws instead of silently sending unsigned requests.
  • #​8772 8409843 Thanks @​aarmful! - feat(two-factor): include enabled 2fa methods in sign-in redirect response

    The 2FA sign-in redirect now returns twoFactorMethods (e.g. ["totp", "otp"]) so frontends can render the correct verification UI without guessing. The onTwoFactorRedirect client callback receives twoFactorMethods as a context parameter.

    • TOTP is included only when the user has a verified TOTP secret and TOTP is not disabled in config.
    • OTP is included when otpOptions.sendOTP is configured.
    • Unverified TOTP enrollments are excluded from the methods list.
  • #​8711 e78a7b1 Thanks @​aarmful! - fix(two-factor): prevent unverified TOTP enrollment from gating sign-in

    Adds a verified boolean column to the twoFactor table that tracks whether a TOTP secret has been confirmed by the user.

    • First-time enrollment: enableTwoFactor creates the row with verified: false. The row is promoted to verified: true only after verifyTOTP succeeds with a valid code.
    • Re-enrollment (calling enableTwoFactor when TOTP is already verified): the new row preserves verified: true, so the user is never locked out of sign-in while rotating their TOTP secret.
    • Sign-in: verifyTOTP rejects rows where verified === false, preventing abandoned enrollments from blocking authentication. Backup codes and OTP are unaffected and work as fallbacks during unfinished enrollment.

    Migration: The new column defaults to true, so existing twoFactor rows are treated as verified. No data migration is required. skipVerificationOnEnable: true is also unaffected — the row is created as verified: true in that mode.

  • Updated dependencies []:

v1.6.1

Compare Source

Patch Changes

v1.6.0

Compare Source

Minor Changes
Patch Changes

v1.5.6

Compare Source

   🚀 Features
   🐞 Bug Fixes
    View changes on GitHub

v1.5.5

Compare Source

   🚀 Features
   🐞 Bug Fixes
    View changes on GitHub

v1.5.4

Compare Source

   🐞 Bug Fixes
    View changes on GitHub

v1.5.3

Compare Source

   🐞 Bug Fixes
    View changes on GitHub

v1.5.2

Compare Source

   🐞 Bug Fixes
    View changes on GitHub

v1.5.1

Compare Source

   🐞 Bug Fixes
    View changes on GitHub

v1.5.0

Compare Source

Better Auth 1.5 Release

We’re excited to announce the release of Better Auth 1.5! 🎉

This is our biggest release yet, with over 600 commits, 70 new features, 200 bug fixes, and 7 entirely new packages. From MCP authentication to Electron desktop support, this release brings Better Auth to new platforms and use cases.

We’re also announcing our new Infrastructure product. It lets you use a full user management and analytics dashboard, security and protection tooling, audit logs, a self-service SSO UI, and more, all with your own Better Auth instance.

Starting with this release, the self-service SSO dashboard — which lets your enterprise customers onboard their own SAML providers without support tickets — is powered by Better Auth Infrastructure. If you’re using the SSO plugin in production, we recommend upgrading to the Pro or Business tier to get access to the dashboard and streamline your enterprise onboarding.

And soon, you’ll be able to host your Better Auth instance on our infrastructure as well, so you can own your auth at scale without worrying about infrastructure needs.

Sign up now: https://better-auth.com/sign-in 🚀

To upgrade, run:

npx auth upgrade

🚀 Highlights

New Better Auth CLI

We’re introducing a new standalone CLI: npx auth. This replaces the previous @better-auth/cli package, which will be deprecated in a future release.

npx auth init

With a single interactive command, npx auth init scaffolds a complete Better Auth setup — configuration file, database adapter, and framework integration.

All existing commands like migrate and generate are available through the new CLI as well:

npx auth migrate   # Run database migrations
npx auth generate  # Generate auth schema
npx auth upgrade   # Upgrade Better Auth to the latest version

The generate command now also supports a --adapter flag, letting you generate schema output tailored to your specific database adapter without needing a full Better Auth config file:

npx auth generate --adapter prisma
npx auth generate --adapter drizzle
Remote MCP Auth Client

The MCP plugin now ships a framework-agnostic remote auth client. If your MCP server is separate from your Better Auth instance, you can verify tokens and protect resources without duplicating auth logic.

👉 Read more about MCP authentication

import { createMcpAuthClient } from "better-auth/plugins/mcp/client";

const mcpAuth = createMcpAuthClient({
    authURL: "<https://my-app.com/api/auth>",
});

// Use as a handler wrapper
const handler = mcpAuth.handler(async (req, session) => {
    // session contains userId, scopes, accessToken, clientId, etc.
    return new Response("OK");
});

// Or verify tokens directly
const session = await mcpAuth.verifyToken(token);

It also comes with built-in framework adapters for Hono and Express-like servers:

import { mcpAuthHono } from "better-auth/plugins/mcp/client/adapters";

const middleware = mcpAuthHono(mcpAuth);

OAuth 2.1 Provider

The new @better-auth/oauth-provider plugin turns your Better Auth instance into a full OAuth 2.1 authorization server with OIDC compatibility. Issue access tokens, manage client registrations, and let third-party apps authenticate against your API — including MCP agents.

👉 Read more about the OAuth Provider

import { betterAuth } from "better-auth";
import { jwt } from "better-auth/plugins";
import { oauthProvider } from "@&#8203;better-auth/oauth-provider";

export const auth = betterAuth({
    plugins: [
        jwt(),
        oauthProvider({
            loginPage: "/sign-in",
            consentPage: "/consent",
        }),
    ],
});

Key features:

  • OAuth 2.1 with OIDC: Supports authorization_code, refresh_token, and client_credentials grants with openid scope support.
  • MCP-ready: Works out of the box as an authorization server for MCP tools and agents.
  • Dynamic Client Registration: Allow clients to register dynamically, with support for both public and confidential clients.
  • JWT & JWKS verification: Sign access tokens as JWTs and verify them remotely via the /jwks endpoint.
  • Consent & authorization flows: Built-in consent, account selection, and post-login redirect screens.
  • Token introspection & revocation: RFC 7662 and RFC 7009 compliant endpoints.
  • Per-endpoint rate limiting: Configurable rate limits for each OAuth endpoint.

Note:

The OAuth 2.1 Provider replaces the previous OIDC Provider plugin, which will be deprecated in a future release. The MCP plugin will also transition to use the OAuth 2.1 Provider as its foundation. See the migration guide for upgrading from the OIDC Provider plugin.


Electron Integration

Full desktop authentication support for Electron apps. The plugin handles the complete OAuth flow — opening the system browser, exchanging authorization codes via custom protocol, and managing cookies securely.

👉 Read more about Electron integration

import { betterAuth } from "better-auth";
import { electron } from "@&#8203;better-auth/electron";

export const auth = betterAuth({
    plugins: [electron()],
});
import { createAuthClient } from "better-auth/client";
import { electronClient } from "@&#8203;better-auth/electron/client";

const client = createAuthClient({
    plugins: [
        electronClient({
            protocol: "com.example.myapp",
        }),
    ],
});

// Opens system browser, handles callback, returns session
await client.requestAuth();

Internationalization (i18n)

The new i18n plugin provides type-safe error message translations with automatic locale detection from headers, cookies, or sessions.

👉 Read more about i18n

import { betterAuth } from "better-auth";
import { i18n } from "@&#8203;better-auth/i18n";

export const auth = betterAuth({
    plugins: [
        i18n({
            defaultLocale: "en",
            detection: ["header", "cookie"],
            translations: {
                en: { USER_NOT_FOUND: "User not found" },
                fr: { USER_NOT_FOUND: "Utilisateur non trouvé" },
                es: { USER_NOT_FOUND: "Usuario no encontrado" },
            },
        }),
    ],
});

Error codes are fully typed — your IDE will autocomplete all available error codes from every registered plugin.


Typed Error Codes

Every error response now includes a machine-readable code field. All first-party plugins define their own typed error codes using defineErrorCodes, and the APIError class supports them natively.

import { defineErrorCodes } from "@&#8203;better-auth/core";

export const MY_ERROR_CODES = defineErrorCodes({
    USER_NOT_FOUND: "User not found",
    INVALID_TOKEN: "The provided token is invalid",
});

// In route handlers:
throw APIError.from("BAD_REQUEST", MY_ERROR_CODES.USER_NOT_FOUND);

Error responses now look like:

{
    "code": "USER_NOT_FOUND",
    "message": "User not found"
}

This is the foundation that the i18n plugin builds on — every error code from every plugin is discoverable at compile time, so translation dictionaries are fully type-checked.


SSO — Production Ready

The SSO plugin has received extensive hardening to be production-ready, with 23+ commits improving security and compliance.

Self-Service SSO Dashboard

As part of our new Infrastructure product, the SSO plugin is now accompanied by a self-service dashboard for onboarding enterprise customers. Organization admins can generate a shareable link that walks enterprise customers through configuring their SAML identity provider — no back-and-forth support tickets required.

The dashboard is available at:

https://better-auth.com/dashboard/[project]/organization/[orgId]/enterprise

From there, you can generate onboarding links, monitor SSO connection status, and manage provider configurations for each organization.

SAML Single Logout (SLO)

Full support for both SP-initiated and IdP-initiated SAML Single Logout:

import { betterAuth } from "better-auth";
import { sso } from "@&#8203;better-auth/sso";

export const auth = betterAuth({
    plugins: [
        sso({
            saml: {
                enableSingleLogout: true, // [!code highlight]
                wantLogoutRequestSigned: true,
                wantLogoutResponseSigned: true,
            },
        }),
    ],
});
Additional SSO Improvements
  • Signed SAML AuthnRequests: Configurable signature and digest algorithms.
  • Multi-domain providers: Bind SSO providers to multiple domains.
  • InResponseTo validation: Prevent replay attacks on SAML assertions.
  • Algorithm restrictions: Block deprecated signature/digest algorithms.
  • Clock skew tolerance: Configurable tolerance for SAML timestamp validation.
  • OIDC ID token aud claim validation: Verify audience in OpenID Connect flows.
  • Provider CRUD endpoints: List, get, update, and delete SSO providers via API.
  • Shared OIDC redirect URI: Single redirect URI for all OIDC providers.

Unified Before & After Hooks

Plugin hooks and global hooks now share the same AuthMiddleware type, making the hooks system consistent and composable across the entire auth pipeline.

import { betterAuth } from "better-auth";
import { createAuthMiddleware } from "better-auth/api";

export const auth = betterAuth({
    hooks: {
        before: createAuthMiddleware(async (ctx) => {
            // Runs before every endpoint
            console.log("Request to:", ctx.path);
        }),
        after: createAuthMiddleware(async (ctx) => {
            // Runs after every endpoint, with access to the response
            console.log("Response:", ctx.context.returned);
        }),
    },
});

Plugins use the same middleware type with matchers for targeted interception:

hooks: {
    before: [{
        matcher: (ctx) => ctx.path === "/sign-in/email",
        handler: createAuthMiddleware(async (ctx) => { /* ... */ }),
    }],
},

Dynamic Base URL

Better Auth can now resolve the base URL dynamically from incoming requests, making it work seamlessly with Vercel preview deployments, multi-domain setups, and reverse proxies.

👉 Read more about dynamic base URL

import { betterAuth } from "better-auth";

export const auth = betterAuth({
    baseURL: {
        allowedHosts: [
            "myapp.com",
            "*.vercel.app",       // Any Vercel preview
            "preview-*.myapp.com", // Pattern match
        ],
        fallback: "<https://myapp.com>",
        protocol: "auto",
    },
});

Verification on Secondary Storage

Verification tokens can now be stored in secondary storage (e.g., Redis) instead of — or in addition to — the database. Identifiers can be hashed for extra security.

import { betterAuth } from "better-auth";

export const auth = betterAuth({
    secondaryStorage: {
        // ... your Redis config
    },
    verification: {
        storeIdentifier: "hashed",     // Hash verification identifiers // [!code highlight]
        storeInDatabase: false,        // Only use secondary storage // [!code highlight]
    },
});

You can also configure per-identifier overrides:

verification: {
    storeIdentifier: {
        default: "plain",
        overrides: {
            "email-verification": "hashed",
            "password-reset": "hashed",
        },
    },
},

Rate Limiter Improvements

The rate limiter has been improved with separate request/response handling, hardened defaults, and IPv6 support.

  • Separate request and response phases: Rejected requests are no longer counted against the rate limit.
  • Hardened default rules: Sign-in/sign-up limited to 3 requests per 10 seconds; password reset/OTP limited to 3 requests per 60 seconds.
  • IPv6 subnet support: Rate limiting by IPv6 prefix with configurable subnet size.
  • Plugin-level rate limit rules: Plugins can define their own rate limit rules.
  • Expired entry cleanup: Automatic cleanup for the memory storage backend.
import { betterAuth } from "better-auth";

export const auth = betterAuth({
    advanced: {
        ipAddress: {
            ipv6Subnet: 64, // Rate limit by /64 subnet
        },
    },
});

Non-Destructive Secret Key Rotation

Better Auth now supports rotating BETTER_AUTH_SECRET without invalidating existing sessions, tokens, or encrypted data. When you need to rotate your secret — whether for scheduled rotation or incident response — you can introduce a new key while keeping old keys available for decryption.

import { betterAuth } from "better-auth";

export const auth = betterAuth({
    secrets: [
        { version: 2, value: "new-secret-key-at-least-32-chars" },   // current (first = active)
        { version: 1, value: "old-secret-key-still-used-to-decrypt" }, // previous
    ],
});

Or via environment variable:

BETTER_AUTH_SECRETS="2:new-secret-key,1:old-secret-key"

New data is always encrypted with the latest key (first in the array), while decryption automatically tries all configured keys. This lets you roll secrets gradually without downtime or data loss.


Seat-Based Billing (Stripe)

The Stripe plugin now supports per-seat billing for organizations. Member changes automatically sync seat quantity with Stripe.

import { betterAuth } from "better-auth";
import { stripe } from "@&#8203;better-auth/stripe";
import { organization } from "better-auth/plugins";

exp

>  **Note**
> 
> PR body was truncated to here.


</details>

---

### Configuration

📅 **Schedule**: (UTC)

- Branch creation
  - ""
- Automerge
  - At any time (no schedule defined)

🚦 **Automerge**: Disabled by config. Please merge this manually once you are satisfied.

 **Rebasing**: Whenever PR becomes conflicted, or you tick the rebase/retry checkbox.

🔕 **Ignore**: Close this PR and you won't be reminded about this update again.

---

 - [ ] <!-- rebase-check -->If you want to rebase/retry this PR, check this box

---

This PR was generated by [Mend Renovate](https://mend.io/renovate/). View the [repository job log](https://developer.mend.io/github/mx-space/mx-admin).
<!--renovate-debug:eyJjcmVhdGVkSW5WZXIiOiI0My4xNzkuMyIsInVwZGF0ZWRJblZlciI6IjQzLjE3OS4zIiwidGFyZ2V0QnJhbmNoIjoibWFzdGVyIiwibGFiZWxzIjpbImRlcGVuZGVuY2llcyJdfQ==-->

@safedep
Copy link
Copy Markdown

safedep Bot commented May 15, 2026

SafeDep Report Summary

Green Malicious Packages Badge Green Vulnerable Packages Badge Green Risky License Badge

Package Details
Package Malware Vulnerability Risky License Report
icon @better-auth/core @ 1.6.2
pnpm-lock.yaml
ok icon
ok icon
ok icon
🔗
icon @better-auth/drizzle-adapter @ 1.6.2
pnpm-lock.yaml
ok icon
ok icon
ok icon
🔗
icon @better-auth/kysely-adapter @ 1.6.2
pnpm-lock.yaml
ok icon
ok icon
ok icon
🔗
icon @better-auth/memory-adapter @ 1.6.2
pnpm-lock.yaml
ok icon
ok icon
ok icon
🔗
icon @better-auth/mongo-adapter @ 1.6.2
pnpm-lock.yaml
ok icon
ok icon
ok icon
🔗
icon @better-auth/prisma-adapter @ 1.6.2
pnpm-lock.yaml
ok icon
ok icon
ok icon
🔗
icon @better-auth/telemetry @ 1.6.2
pnpm-lock.yaml
ok icon
ok icon
ok icon
🔗
icon @better-auth/utils @ 0.4.0
pnpm-lock.yaml
ok icon
ok icon
ok icon
🔗
icon @opentelemetry/api @ 1.9.1
pnpm-lock.yaml
ok icon
ok icon
ok icon
🔗
icon @opentelemetry/semantic-conventions @ 1.41.1
pnpm-lock.yaml
ok icon
ok icon
ok icon
🔗
icon better-auth @ 1.6.2
apps/admin/package.json pnpm-lock.yaml
ok icon
ok icon
ok icon
🔗
icon better-call @ 1.3.5
pnpm-lock.yaml
ok icon
ok icon
ok icon
🔗
icon set-cookie-parser @ 3.1.0
pnpm-lock.yaml
ok icon
ok icon
ok icon
🔗

View complete scan results →

This report is generated by SafeDep Github App

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

0 participants