nextauthjs / next-auth

Authentication for the Web.
https://authjs.dev
ISC License
24.96k stars 3.52k forks source link

InvalidCheck: PKCE code_verifier cookie was missing on upgrade to v5 #10458

Closed jonluca closed 7 months ago

jonluca commented 7 months ago

Provider type

Apple, Discord, GitHub, Google

Environment

System: OS: macOS 14.4.1 CPU: (12) arm64 Apple M2 Max Memory: 1.95 GB / 96.00 GB Shell: 5.9 - /bin/zsh Binaries: Node: 21.7.1 - ~/.nvm/versions/node/v21.7.1/bin/node Yarn: 4.1.1 - ~/.nvm/versions/node/v21.7.1/bin/yarn npm: 10.5.0 - ~/.nvm/versions/node/v21.7.1/bin/npm pnpm: 8.11.0 - ~/Library/pnpm/pnpm bun: 1.0.29 - ~/.bun/bin/bun Watchman: 2024.03.25.00 - /opt/homebrew/bin/watchman Browsers: Brave Browser: 123.1.64.109 Chrome: 123.0.6312.87 Edge: 112.0.1722.54 Safari: 17.4.1 npmPackages: @auth/prisma-adapter: ^1.5.2 => 1.5.2 next: ^14.1.4 => 14.1.4 next-auth: ^5.0.0-beta.16 => 5.0.0-beta.16 react: ^18.2.0 => 18.2.0

Reproduction URL

https://www.weights.gg/

Describe the issue

We recently upgraded to NextAuth v5. A certain portion of our users are seeing the signin and signup error screen, and our backend logs are telling us that it is due to

InvalidCheck: PKCE code_verifier cookie was missing.. Read more at https://errors.authjs.dev#invalidcheck CleanShot 2024-04-02 at 00 40 47@2x

It is happening non deterministically - we cannot reproduce this ourselves, and it happens with any provider. It still happens when users clear their cache and their cookies.

We have 4 providers set up:

import DiscordProvider from "next-auth/providers/discord";
import GoogleProvider from "next-auth/providers/google";
import GitHubProvider from "next-auth/providers/github";
import AppleProvider from "next-auth/providers/apple";
import type { NextAuthConfig } from "next-auth";

export const providers = [
  process.env.DISCORD_CLIENT_ID &&
    DiscordProvider({
      clientId: process.env.DISCORD_CLIENT_ID || "",
      clientSecret: process.env.DISCORD_CLIENT_SECRET || "",
      allowDangerousEmailAccountLinking: true,
    }),
  process.env.GOOGLE_CLIENT_ID &&
    GoogleProvider({
      clientId: process.env.GOOGLE_CLIENT_ID || "",
      clientSecret: process.env.GOOGLE_CLIENT_SECRET || "",
      allowDangerousEmailAccountLinking: true,
    }),
  process.env.GOOGLE_CLIENT_ID &&
    GitHubProvider({
      clientId: process.env.GITHUB_CLIENT_ID || "",
      clientSecret: process.env.GITHUB_CLIENT_SECRET || "",
      allowDangerousEmailAccountLinking: true,
    }),
  process.env.APPLE_CLIENT_ID &&
    process.env.APPLE_CLIENT_SECRET &&
    AppleProvider({
      allowDangerousEmailAccountLinking: true,
      clientId: process.env.APPLE_CLIENT_ID,
      clientSecret: process.env.APPLE_CLIENT_SECRET,
      wellKnown: "https://appleid.apple.com/.well-known/openid-configuration",
      checks: ["pkce"],
      token: {
        url: `https://appleid.apple.com/auth/token`,
      },
      authorization: {
        url: "https://appleid.apple.com/auth/authorize",
        params: {
          scope: "",
          response_type: "code",
          response_mode: "query",
          state: crypto.randomUUID(),
        },
      },
      client: {
        token_endpoint_auth_method: "client_secret_post",
      },
    }),
].filter(Boolean) as NextAuthConfig["providers"];

And our auth config is fairly simple:

/**
 * Options for NextAuth.js used to configure adapters, providers, callbacks, etc.
 *
 * @see https://next-auth.js.org/configuration/options
 */
const useSecureCookies = process.env.NEXTAUTH_URL?.startsWith("https");
const cookiePrefix = useSecureCookies ? "__Secure-" : "";

export const { handlers, auth } = NextAuth({
  providers,
  events: {
    signOut: async (opts) => {
      if (!opts) {
        return;
      }
      let user = undefined;
      if ("token" in opts) {
        const token = await opts.token;
        if (token && "user" in token && token.user) {
          user = token.user;
        }
      } else if ("session" in opts) {
        const session = await opts.session;
        if (session && "user" in session && session.user) {
          user = session.user;
        }
      }
      user = user as Session["user"] | undefined;
      if (user && "id" in user && user.id) {
        const { serverLogStatsig } = await import("~/server/config/statsig");
        await serverLogStatsig(
          {
            id: user.id,
            email: user.email,
          },
          "signOut",
        );
      }
    },
  },
  callbacks: {
    session: ({ session, token }) => {
      if (!token) {
        return session;
      }
      return {
        ...session,
        user: token.user as Session["user"],
      };
    },
    async jwt({ token, user, account, trigger }) {
      // Persist the OAuth access_token and or the user id to the token right after signin
      if (user) {
        token.user = user;
      }
      return token;
    },
    async signIn(user) {
      const userObj = user.user;
      if (userObj && "isDeleted" in userObj && userObj.isDeleted) {
        // return "/error?error=This account has been deleted";
        return false;
      }

      return true;
    },
    async redirect({ url }) {
      const u = new URL(url);
      u.searchParams.set("loginRedirect", "true");
      return u.toString();
    },
  },
  adapter: PrismaAdapter(prisma as unknown as PrismaClient),
  trustHost: true,
  session: {
    maxAge: 365 * 24 * 60 * 60, // 180 days
    strategy: "jwt",
  },
  theme: {
    logo: "/android-chrome-512x512.png",
  },
  secret: process.env.NEXTAUTH_SECRET,
  debug: true,
  pkceCodeVerifier: {
    name: `${cookiePrefix}authjs.pkce.code_verifier`,
    options: {
      httpOnly: true,
      sameSite: "none",
      path: "/",
      secure: true,
      maxAge: 60 * 15, // 15 minutes in seconds
    },
  },
  // @ts-expect-error
  skipCSRFCheck,
});

export const getServerAuthSession = auth;
const { GET, POST } = handlers;
export { GET, POST };

Note: we added the pkceCodeVerifier cookie config to try and fix this issue. It is occuring both with and without that cookie config.

How to reproduce

This is non deterministic. Most of the users are able to log in and signup. There is no pattern around:

that tightens the bounds around one. It seems like the pkce cookie is not set properly on certain requests.

Expected behavior

PKCE cookie is set appropriately

github-actions[bot] commented 7 months ago

We could not detect a valid reproduction link. Make sure to follow the bug report template carefully.

Why was this issue closed?

To be able to investigate, we need access to a reproduction to identify what triggered the issue. We need a link to a public GitHub repository. Example: (NextAuth.js example repository).

The bug template that you filled out has a section called "Reproduction URL", which is where you should provide the link to the reproduction.

What should I do?

Depending on the reason the issue was closed, you can do the following:

In general, assume that we should not go through a lengthy onboarding process at your company code only to be able to verify an issue.

My repository is private and cannot make it public

In most cases, a private repo will not be a sufficient minimal reproduction, as this codebase might contain a lot of unrelated parts that would make our investigation take longer. Please do not make it public. Instead, create a new repository using the templates above, adding the relevant code to reproduce the issue. Common things to look out for:

I did not open this issue, but it is relevant to me, what can I do to help?

Anyone experiencing the same issue is welcome to provide a minimal reproduction following the above steps by opening a new issue.

I think my reproduction is good enough, why aren't you looking into it quickly?

We look into every issue and monitor open issues for new comments.

However, sometimes we might miss a few due to the popularity/high traffic of the repository. We apologize, and kindly ask you to refrain from tagging core maintainers, as that will usually not result in increased priority.

Upvoting issues to show your interest will help us prioritize and address them as quickly as possible. That said, every issue is important to us, and if an issue gets closed by accident, we encourage you to open a new one linking to the old issue and we will look into it.

Useful Resources