The modern link attribution platform. Loved by world-class engineering teams at Twilio, Zillow, Jobber, Vercel, Raycast, and more.
TypeScript clickhousemysqlnextjsopen-sourceplanetscaleprismatailwindcsstinybirdtypescriptupstashvercel
refresh token support for pkce
Kiran K8d0964ffacdb
diff --git a/apps/web/app/api/oauth/authorize/route.ts b/apps/web/app/api/oauth/authorize/route.tsindex c1d33c34fb..c91c2880e4 100644--- a/apps/web/app/api/oauth/authorize/route.ts+++ b/apps/web/app/api/oauth/authorize/route.ts@@ -21,19 +21,31 @@ export const POST = withWorkspace(async ({ session, req, workspace }) => {code_challenge_method: codeChallengeMethod,} = authorizeRequestSchema.parse(await parseRequestBody(req));- const oAuthApp = await prisma.oAuthApp.findUniqueOrThrow({+ const app = await prisma.oAuthApp.findUniqueOrThrow({where: {clientId,},+ select: {+ redirectUri: true,+ pkce: true,+ },});- if (oAuthApp.redirectUri !== redirectUri) {+ if (app.redirectUri !== redirectUri) {throw new DubApiError({code: "bad_request",message: "Invalid redirect_uri parameter for the application.",});}+ // If PKCE is required, ensure that the code_challenge and code_challenge_method are present+ if (app.pkce && (!codeChallenge || !codeChallengeMethod)) {+ throw new DubApiError({+ code: "bad_request",+ message: "Missing code_challenge or code_challenge_method parameters.",+ });+ }+const { code } = await prisma.oAuthCode.create({data: {clientId,@@ -43,8 +55,7 @@ export const POST = withWorkspace(async ({ session, req, workspace }) => {scopes: scope.join(" "),code: nanoid(OAUTH_CODE_LENGTH),expiresAt: new Date(Date.now() + OAUTH_CODE_LIFETIME * 1000),- ...(codeChallenge && { codeChallenge }),- ...(codeChallengeMethod && { codeChallengeMethod }),+ ...(app.pkce && { codeChallenge, codeChallengeMethod }),},});diff --git a/apps/web/app/api/oauth/token/exchange-code-for-token.ts b/apps/web/app/api/oauth/token/exchange-code-for-token.tsindex 4f40ce2b76..3e10fae732 100644--- a/apps/web/app/api/oauth/token/exchange-code-for-token.ts+++ b/apps/web/app/api/oauth/token/exchange-code-for-token.ts@@ -27,11 +27,10 @@ export const exchangeAuthCodeForToken = async (} = params;let { client_id: clientId, client_secret: clientSecret } = params;- const isPKCE = codeVerifier !== undefined;// If no client_id or client_secret is provided in the request body// then it should be provided in the Authorization header as Basic Auth for non-PKCE- if (!clientId && !clientSecret && !isPKCE) {+ if (!clientId && !clientSecret) {const authorizationHeader = req.headers.get("Authorization") || "";const [type, token] = authorizationHeader.split(" ");@@ -45,32 +44,56 @@ export const exchangeAuthCodeForToken = async (}}- if (!clientId || (!clientSecret && !isPKCE)) {+ if (!clientId) {throw new DubApiError({code: "unauthorized",- message: "Missing client credentials",+ message: "Missing client_id",});}const app = await prisma.oAuthApp.findFirst({where: {clientId,- ...(clientSecret && {- clientSecretHashed: await hashToken(clientSecret),- }),},select: {name: true,+ pkce: true,+ clientSecretHashed: true,},});if (!app) {throw new DubApiError({code: "unauthorized",- message: "Invalid client credentials",+ message: "OAuth app not found for the provided client_id",});}+ if (app.pkce && !codeVerifier) {+ throw new DubApiError({+ code: "bad_request",+ message: "Missing code_verifier parameter",+ });+ }++ if (!app.pkce && !clientSecret) {+ throw new DubApiError({+ code: "unauthorized",+ message: "Missing client_secret",+ });+ }++ if (+ clientSecret &&+ app.clientSecretHashed !== (await hashToken(clientSecret))+ ) {+ throw new DubApiError({+ code: "unauthorized",+ message: "Invalid client_secret",+ });+ }++ // Now let's find the access code and validate itconst accessCode = await prisma.oAuthCode.findUnique({where: {code,@@ -94,10 +117,10 @@ export const exchangeAuthCodeForToken = async (});}- if (isPKCE) {+ if (app.pkce) {const codeChallenge =accessCode.codeChallengeMethod === "S256"- ? await generateCodeChallengeHash(codeVerifier)+ ? await generateCodeChallengeHash(codeVerifier!): codeVerifier;if (accessCode.codeChallenge != codeChallenge) {@@ -209,13 +232,11 @@ export const exchangeAuthCodeForToken = async (]);// https://www.oauth.com/oauth2-servers/access-tokens/access-token-response/- const response = {+ return {access_token: accessToken,refresh_token: refreshToken,token_type: "Bearer",expires_in: OAUTH_ACCESS_TOKEN_LIFETIME,scope: scopes,};-- return response;};diff --git a/apps/web/app/api/oauth/token/refresh-access-token.ts b/apps/web/app/api/oauth/token/refresh-access-token.tsindex 216cb4ea86..2696b19ffe 100644--- a/apps/web/app/api/oauth/token/refresh-access-token.ts+++ b/apps/web/app/api/oauth/token/refresh-access-token.ts@@ -7,7 +7,7 @@ import {OAUTH_REFRESH_TOKEN_LIFETIME,OAUTH_REFRESH_TOKEN_PREFIX,} from "@/lib/api/oauth/constants";-import { getAuthTokenOrThrow, hashToken } from "@/lib/auth";+import { hashToken } from "@/lib/auth";import { prisma } from "@/lib/prisma";import z from "@/lib/zod";import { refreshTokenSchema } from "@/lib/zod/schemas/oauth";@@ -19,54 +19,80 @@ export const refreshAccessToken = async (req: NextRequest,params: z.infer<typeof refreshTokenSchema>,) => {- const { client_id, client_secret, refresh_token: refreshToken } = params;-- let clientId: string | undefined = client_id;- let clientSecret: string | undefined = client_secret;+ let {+ refresh_token,+ client_id: clientId,+ client_secret: clientSecret,+ } = params;// If no client_id or client_secret is provided in the request body- // then it should be provided in the Authorization header as Basic Auth+ // then it should be provided in the Authorization header as Basic Auth for non-PKCEif (!clientId && !clientSecret) {- const token = getAuthTokenOrThrow(req, "Basic");- const splits = Buffer.from(token, "base64").toString("utf-8").split(":");+ const authorizationHeader = req.headers.get("Authorization") || "";+ const [type, token] = authorizationHeader.split(" ");++ if (type === "Basic") {+ const splits = Buffer.from(token, "base64").toString("utf-8").split(":");- if (splits.length > 1) {- clientId = splits[0];- clientSecret = splits[1];+ if (splits.length > 1) {+ clientId = splits[0];+ clientSecret = splits[1];+ }}}- if (!clientId || !clientSecret) {+ if (!clientId) {throw new DubApiError({code: "unauthorized",- message: "Invalid client credentials",+ message: "Missing client_id",});}const app = await prisma.oAuthApp.findFirst({where: {clientId,- clientSecretHashed: await hashToken(clientSecret),},select: {name: true,+ pkce: true,+ clientSecretHashed: true,},});if (!app) {throw new DubApiError({code: "unauthorized",- message: "Invalid client credentials",+ message: "OAuth app not found for the provided client_id",});}+ if (!app.pkce) {+ if (!clientSecret) {+ throw new DubApiError({+ code: "unauthorized",+ message: "Missing client_secret",+ });+ }++ if (app.clientSecretHashed !== (await hashToken(clientSecret))) {+ throw new DubApiError({+ code: "unauthorized",+ message: "Invalid client_secret",+ });+ }+ }+const refreshTokenRecord = await prisma.oAuthRefreshToken.findFirst({where: {clientId,- refreshTokenHashed: await hashToken(refreshToken),+ refreshTokenHashed: await hashToken(refresh_token),+ // expiresAt: {+ // gte: new Date(),+ // },},select: {id: true,+ expiresAt: true,accessToken: {select: {id: true,@@ -87,11 +113,17 @@ export const refreshAccessToken = async (if (!refreshTokenRecord) {throw new DubApiError({code: "unauthorized",- message: "Refresh token not found or invalid",+ message: "Refresh token not found or expired",+ });+ }++ if (refreshTokenRecord.expiresAt < new Date()) {+ throw new DubApiError({+ code: "unauthorized",+ message: "Refresh token expired",});}- const { accessToken, id: refreshTokenId } = refreshTokenRecord;const {userId,projectId,@@ -99,7 +131,7 @@ export const refreshAccessToken = async (name,project: workspace,id: accessTokenId,- } = accessToken;+ } = refreshTokenRecord.accessToken;const newAccessToken = `${OAUTH_ACCESS_TOKEN_PREFIX}${nanoid(OAUTH_ACCESS_TOKEN_LENGTH)}`;const newRefreshToken = `${OAUTH_REFRESH_TOKEN_PREFIX}${nanoid(OAUTH_REFRESH_TOKEN_LENGTH)}`;@@ -141,12 +173,10 @@ export const refreshAccessToken = async (]);// https://www.oauth.com/oauth2-servers/making-authenticated-requests/refreshing-an-access-token/- const response = {+ return {access_token: newAccessToken,refresh_token: newRefreshToken,token_type: "Bearer",expires_in: OAUTH_ACCESS_TOKEN_LIFETIME,};-- return response;};diff --git a/apps/web/prisma/schema.prisma b/apps/web/prisma/schema.prismaindex 6bcd69a862..b6b9d058e6 100644--- a/apps/web/prisma/schema.prisma+++ b/apps/web/prisma/schema.prisma@@ -376,6 +376,7 @@ model OAuthApp {clientSecretHashed StringredirectUri Stringlogo String?+ pkce Boolean @default(false)createdAt DateTime @default(now())updatedAt DateTime @updatedAtcreatedBy String?