Skip to content

armgit / dub

Public Imported from GitHub
0

The modern link attribution platform. Loved by world-class engineering teams at Twilio, Zillow, Jobber, Vercel, Raycast, and more.

add refresh token logic

Kiran K659c0a8fe569
diff --git a/apps/web/app/api/oauth-apps/[appId]/route.ts b/apps/web/app/api/oauth-apps/[appId]/route.ts
index 20613111b0..c75e644bd4 100644
--- a/apps/web/app/api/oauth-apps/[appId]/route.ts
+++ b/apps/web/app/api/oauth-apps/[appId]/route.ts
@@ -8,7 +8,7 @@ import { NextResponse } from "next/server";
// GET /api/oauth-apps/[appId] – get an OAuth app
export const GET = withWorkspace(
async ({ params, workspace }) => {
- const app = await prisma.oAuthApp.findUnique({
+ const app = await prisma.oAuthApp.findFirst({
where: {
id: params.appId,
projectId: workspace.id,
@@ -61,7 +61,7 @@ export const PATCH = withWorkspace(
// DELETE /api/oauth-apps/[appId] - delete an OAuth app
export const DELETE = withWorkspace(
async ({ req, params, workspace }) => {
- const app = await prisma.oAuthApp.findUnique({
+ const app = await prisma.oAuthApp.findFirst({
where: {
id: params.appId,
projectId: workspace.id,
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.ts
new file mode 100644
index 0000000000..fba63820b6
--- /dev/null
+++ b/apps/web/app/api/oauth/token/exchange-code-for-token.ts
@@ -0,0 +1,145 @@
+import { DubApiError } from "@/lib/api/errors";
+import { TOKEN_EXPIRY, TOKEN_LENGTH } from "@/lib/api/oauth";
+import { getAuthTokenOrThrow, hashToken } from "@/lib/auth";
+import { prisma } from "@/lib/prisma";
+import z from "@/lib/zod";
+import { authCodeExchangeSchema } from "@/lib/zod/schemas/oauth";
+import { getCurrentPlan, nanoid } from "@dub/utils";
+import { NextRequest } from "next/server";
+
+// Exchange authorization code with access token
+export const exchangeAuthCodeForToken = async (
+ req: NextRequest,
+ params: z.infer<typeof authCodeExchangeSchema>,
+) => {
+ const { client_id, client_secret, code, redirect_uri: redirectUri } = params;
+
+ let clientId: string | undefined = client_id;
+ let clientSecret: string | undefined = client_secret;
+
+ // 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
+ if (!clientId && !clientSecret) {
+ const token = getAuthTokenOrThrow(req, "Basic");
+ const splits = Buffer.from(token, "base64").toString("utf-8").split(":");
+
+ if (splits.length > 1) {
+ clientId = splits[0];
+ clientSecret = splits[1];
+ }
+ }
+
+ if (!clientId || !clientSecret) {
+ throw new DubApiError({
+ code: "unauthorized",
+ message: "Invalid client credentials",
+ });
+ }
+
+ const app = await prisma.oAuthApp.findFirst({
+ where: {
+ clientId,
+ clientSecretHashed: await hashToken(clientSecret),
+ },
+ select: {
+ name: true,
+ },
+ });
+
+ if (!app) {
+ throw new DubApiError({
+ code: "unauthorized",
+ message: "Invalid client credentials",
+ });
+ }
+
+ const oauthGrant = await prisma.oAuthCode.findFirst({
+ where: {
+ code,
+ clientId,
+ redirectUri,
+ },
+ select: {
+ userId: true,
+ projectId: true,
+ scopes: true,
+ expiresAt: true,
+ },
+ });
+
+ if (!oauthGrant) {
+ throw new DubApiError({
+ code: "unauthorized",
+ message: "Invalid code",
+ });
+ }
+
+ if (oauthGrant.expiresAt < new Date()) {
+ await prisma.oAuthCode.delete({
+ where: {
+ code,
+ },
+ });
+
+ throw new DubApiError({
+ code: "bad_request",
+ message: "Authorization code has expired.",
+ });
+ }
+
+ const workspace = await prisma.project.findUniqueOrThrow({
+ where: {
+ id: oauthGrant.projectId,
+ },
+ select: {
+ plan: true,
+ },
+ });
+
+ const { userId, projectId, scopes } = oauthGrant;
+
+ const accessToken = `dub_${nanoid(TOKEN_LENGTH.accessToken)}`;
+ const refreshToken = `dub_${nanoid(TOKEN_LENGTH.refreshToken)}`;
+ const accessTokenExpires = new Date(Date.now() + TOKEN_EXPIRY.accessToken);
+
+ await Promise.all([
+ // Create the access token and refresh token
+ prisma.restrictedToken.create({
+ data: {
+ userId,
+ projectId,
+ scopes,
+ name: `Access token for ${app.name}`,
+ hashedKey: await hashToken(accessToken),
+ partialKey: `${accessToken.slice(0, 3)}...${accessToken.slice(-4)}`,
+ rateLimit: getCurrentPlan(workspace.plan as string).limits.api,
+ expires: accessTokenExpires,
+ refreshTokens: {
+ create: {
+ clientId,
+ refreshTokenHashed: await hashToken(refreshToken),
+ expiresAt: new Date(Date.now() + TOKEN_EXPIRY.refreshToken),
+ },
+ },
+ },
+ }),
+
+ // Delete the code after it's been used
+ prisma.oAuthCode.delete({
+ where: {
+ code,
+ },
+ }),
+ ]);
+
+ const response = {
+ access_token: accessToken,
+ refresh_token: refreshToken,
+ token_type: "Bearer",
+ expires_in: Math.floor(accessTokenExpires.getTime() / 1000),
+ };
+
+ console.log("Token exchanged", response);
+
+ 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.ts
new file mode 100644
index 0000000000..acd4a1e181
--- /dev/null
+++ b/apps/web/app/api/oauth/token/refresh-access-token.ts
@@ -0,0 +1,148 @@
+import { DubApiError } from "@/lib/api/errors";
+import { TOKEN_EXPIRY, TOKEN_LENGTH } from "@/lib/api/oauth";
+import { getAuthTokenOrThrow, hashToken } from "@/lib/auth";
+import { prisma } from "@/lib/prisma";
+import z from "@/lib/zod";
+import { refreshTokenSchema } from "@/lib/zod/schemas/oauth";
+import { getCurrentPlan, nanoid } from "@dub/utils";
+import { NextRequest } from "next/server";
+
+// Get new access token using refresh token
+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;
+
+ // 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
+ if (!clientId && !clientSecret) {
+ const token = getAuthTokenOrThrow(req, "Basic");
+ const splits = Buffer.from(token, "base64").toString("utf-8").split(":");
+
+ if (splits.length > 1) {
+ clientId = splits[0];
+ clientSecret = splits[1];
+ }
+ }
+
+ if (!clientId || !clientSecret) {
+ throw new DubApiError({
+ code: "unauthorized",
+ message: "Invalid client credentials",
+ });
+ }
+
+ const app = await prisma.oAuthApp.findFirst({
+ where: {
+ clientId,
+ clientSecretHashed: await hashToken(clientSecret),
+ },
+ select: {
+ name: true,
+ },
+ });
+
+ if (!app) {
+ throw new DubApiError({
+ code: "unauthorized",
+ message: "Invalid client credentials",
+ });
+ }
+
+ const refreshTokenRecord = await prisma.oAuthRefreshToken.findFirst({
+ where: {
+ clientId,
+ refreshTokenHashed: await hashToken(refreshToken),
+ },
+ select: {
+ id: true,
+ accessToken: {
+ select: {
+ id: true,
+ name: true,
+ userId: true,
+ projectId: true,
+ scopes: true,
+ project: {
+ select: {
+ plan: true,
+ },
+ },
+ },
+ },
+ },
+ });
+
+ if (!refreshTokenRecord) {
+ throw new DubApiError({
+ code: "unauthorized",
+ message: "Refresh token not found or invalid",
+ });
+ }
+
+ const { accessToken, id: refreshTokenId } = refreshTokenRecord;
+ const {
+ userId,
+ projectId,
+ scopes,
+ name,
+ project: workspace,
+ id: accessTokenId,
+ } = accessToken;
+
+ const newAccessToken = `dub_${nanoid(TOKEN_LENGTH.accessToken)}`;
+ const newRefreshToken = `dub_${nanoid(TOKEN_LENGTH.refreshToken)}`;
+ const accessTokenExpires = new Date(Date.now() + TOKEN_EXPIRY.accessToken);
+
+ await Promise.all([
+ // Create the access token and refresh token
+ prisma.restrictedToken.create({
+ data: {
+ userId,
+ projectId,
+ scopes,
+ name,
+ hashedKey: await hashToken(newAccessToken),
+ partialKey: `${newAccessToken.slice(0, 3)}...${newAccessToken.slice(-4)}`,
+ rateLimit: getCurrentPlan(workspace.plan as string).limits.api,
+ expires: accessTokenExpires,
+ refreshTokens: {
+ create: {
+ clientId,
+ refreshTokenHashed: await hashToken(newRefreshToken),
+ expiresAt: new Date(Date.now() + TOKEN_EXPIRY.refreshToken),
+ },
+ },
+ },
+ }),
+
+ // Delete the old access token
+ prisma.restrictedToken.delete({
+ where: {
+ id: accessTokenId,
+ },
+ }),
+
+ // Delete the old refresh token
+ prisma.oAuthRefreshToken.delete({
+ where: {
+ id: refreshTokenId,
+ },
+ }),
+ ]);
+
+ const response = {
+ access_token: newAccessToken,
+ refresh_token: newRefreshToken,
+ token_type: "Bearer",
+ expires_in: Math.floor(accessTokenExpires.getTime() / 1000),
+ };
+
+ console.log("Access token refreshed", response);
+
+ return response;
+};
diff --git a/apps/web/app/api/oauth/token/route.ts b/apps/web/app/api/oauth/token/route.ts
index ba6d02a181..30b298d422 100644
--- a/apps/web/app/api/oauth/token/route.ts
+++ b/apps/web/app/api/oauth/token/route.ts
@@ -1,139 +1,23 @@
-import { DubApiError, handleAndReturnErrorResponse } from "@/lib/api/errors";
-import { TOKEN_EXPIRY, TOKEN_LENGTH } from "@/lib/api/oauth";
-import { getAuthTokenOrThrow, hashToken } from "@/lib/auth";
-import { prisma } from "@/lib/prisma";
-import { codeExchangeSchema } from "@/lib/zod/schemas/oauth";
-import { getCurrentPlan, nanoid } from "@dub/utils";
+import { handleAndReturnErrorResponse } from "@/lib/api/errors";
+import { tokenGrantSchema } from "@/lib/zod/schemas/oauth";
import { NextRequest, NextResponse } from "next/server";
+import { exchangeAuthCodeForToken } from "./exchange-code-for-token";
+import { refreshAccessToken } from "./refresh-access-token";
-// POST /api/oauth/token - exchange `code` for an access token
+// POST /api/oauth/token - Exchange authorization code for access token and refresh access token
export async function POST(req: NextRequest) {
try {
const formData = Object.fromEntries(await req.formData());
- const {
- client_id,
- client_secret,
- code,
- redirect_uri: redirectUri,
- } = codeExchangeSchema.parse(formData);
-
- let clientId = client_id;
- let clientSecret = client_secret;
-
- if (!client_id && !client_secret) {
- // came in the format {client_id}:{client_secret}
- const token = getAuthTokenOrThrow(req, "Basic");
- const splits = Buffer.from(token, "base64").toString("utf-8").split(":");
-
- if (splits.length > 1) {
- clientId = splits[0];
- clientSecret = splits[1];
- }
- }
-
- if (!clientId || !clientSecret) {
- throw new DubApiError({
- code: "unauthorized",
- message: "Invalid client credentials",
- });
+ const validatedData = tokenGrantSchema.parse(formData);
+ const { grant_type } = validatedData;
+
+ if (grant_type === "authorization_code") {
+ const response = await exchangeAuthCodeForToken(req, validatedData);
+ return NextResponse.json(response);
+ } else if (grant_type === "refresh_token") {
+ const response = await refreshAccessToken(req, validatedData);
+ return NextResponse.json(response);
}
-
- const oauthGrant = await prisma.oAuthCode.findFirst({
- where: {
- code,
- clientId,
- redirectUri,
- app: {
- clientSecretHashed: await hashToken(clientSecret),
- },
- },
- select: {
- userId: true,
- projectId: true,
- scopes: true,
- expiresAt: true,
- app: {
- select: {
- name: true,
- },
- },
- },
- });
-
- if (!oauthGrant) {
- throw new DubApiError({
- code: "unauthorized",
- message: "Invalid code",
- });
- }
-
- if (oauthGrant.expiresAt < new Date()) {
- await prisma.oAuthCode.delete({
- where: {
- code,
- },
- });
-
- throw new DubApiError({
- code: "bad_request",
- message: "Authorization code has expired.",
- });
- }
-
- const workspace = await prisma.project.findUnique({
- where: {
- id: oauthGrant.projectId,
- },
- select: {
- plan: true,
- },
- });
-
- const { userId, projectId, scopes, app } = oauthGrant;
-
- const accessToken = `dub_${nanoid(TOKEN_LENGTH.accessToken)}`;
- const refreshToken = `dub_${nanoid(TOKEN_LENGTH.refreshToken)}`;
- const accessTokenExpires = new Date(Date.now() + TOKEN_EXPIRY.accessToken);
-
- await Promise.all([
- // Create the access token and refresh token
- prisma.restrictedToken.create({
- data: {
- userId,
- projectId,
- scopes,
- name: `Access token for ${app.name}`,
- hashedKey: await hashToken(accessToken),
- partialKey: `${accessToken.slice(0, 3)}...${accessToken.slice(-4)}`,
- rateLimit: getCurrentPlan(workspace?.plan as string).limits.api,
- expires: accessTokenExpires,
- refreshTokens: {
- create: {
- refreshToken,
- expiresAt: new Date(Date.now() + TOKEN_EXPIRY.refreshToken),
- },
- },
- },
- }),
-
- // Delete the code after it's been used
- prisma.oAuthCode.delete({
- where: {
- code,
- },
- }),
- ]);
-
- const response = {
- access_token: accessToken,
- refresh_token: refreshToken,
- token_type: "Bearer",
- expires_in: Math.floor(accessTokenExpires.getTime() / 1000),
- };
-
- console.log("Token exchanged", response);
-
- return NextResponse.json(response);
} catch (error) {
return handleAndReturnErrorResponse(error);
}
diff --git a/apps/web/lib/api/oauth.ts b/apps/web/lib/api/oauth.ts
index a2cf711933..63cf854bb1 100644
--- a/apps/web/lib/api/oauth.ts
+++ b/apps/web/lib/api/oauth.ts
@@ -7,7 +7,7 @@ export const TOKEN_LENGTH = {
};
export const TOKEN_EXPIRY = {
- code: 1000 * 60 * 2, // 2 minutes
- accessToken: 1000 * 60 * 60 * 24, // 24 hours
- refreshToken: 1000 * 60 * 60 * 24 * 30 * 6, // 6 months
+ code: 5 * 60 * 1000, // 5 minutes
+ accessToken: 2 * 60 * 60 * 1000, // 2 hours
+ refreshToken: 60 * 24 * 60 * 60 * 1000, // 60 days
};
diff --git a/apps/web/lib/oauth.ts b/apps/web/lib/oauth.ts
index 79a6772533..1aaf479c00 100644
--- a/apps/web/lib/oauth.ts
+++ b/apps/web/lib/oauth.ts
@@ -9,7 +9,7 @@ export const vaidateAuthorizeRequest = async (params: any) => {
const request = authorizeSchema.parse(params);
const { client_id: clientId, redirect_uri: redirectUri } = request;
- const app = await prisma.oAuthApp.findUnique({
+ const app = await prisma.oAuthApp.findFirst({
where: {
clientId,
},
diff --git a/apps/web/lib/zod/schemas/oauth.ts b/apps/web/lib/zod/schemas/oauth.ts
index 1a1a130665..bbc8ee2065 100644
--- a/apps/web/lib/zod/schemas/oauth.ts
+++ b/apps/web/lib/zod/schemas/oauth.ts
@@ -35,26 +35,31 @@ export const authorizeSchema = z.object({
});
// Schema for OAuth2.0 code exchange request
-export const codeExchangeSchema = z.object({
- client_id: z.string().optional(),
- client_secret: z.string().optional(),
- code: z.string().min(1, "Missing code"),
- redirect_uri: z.string().url({ message: "redirect_uri must be a valid URL" }),
+export const authCodeExchangeSchema = z.object({
grant_type: z
.literal("authorization_code")
.refine((grantType) => grantType === "authorization_code", {
message: "grant_type must be 'authorization_code'",
}),
+ client_id: z.string().optional(),
+ client_secret: z.string().optional(),
+ code: z.string().min(1, "Missing code"),
+ redirect_uri: z.string().url({ message: "redirect_uri must be a valid URL" }),
});
// Schema for OAuth2.0 token refresh request
-export const tokenRefreshSchema = z.object({
- client_id: z.string().min(1, "Missing client_id"),
- client_secret: z.string().min(1, "Missing client_secret"),
- refresh_token: z.string().min(1, "Missing refresh_token"),
+export const refreshTokenSchema = z.object({
grant_type: z
.literal("refresh_token")
.refine((grantType) => grantType === "refresh_token", {
message: "grant_type must be 'refresh_token'",
}),
+ client_id: z.string().optional(),
+ client_secret: z.string().optional(),
+ refresh_token: z.string().min(1, "Missing refresh_token"),
});
+
+export const tokenGrantSchema = z.discriminatedUnion("grant_type", [
+ authCodeExchangeSchema,
+ refreshTokenSchema,
+]);
diff --git a/apps/web/prisma/schema.prisma b/apps/web/prisma/schema.prisma
index 3c06c44f63..45ac2dffd0 100644
--- a/apps/web/prisma/schema.prisma
+++ b/apps/web/prisma/schema.prisma
@@ -398,8 +398,9 @@ model OAuthApp {
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
- project Project @relation(fields: [projectId], references: [id], onDelete: Cascade)
- Codes OAuthCode[]
+ project Project @relation(fields: [projectId], references: [id], onDelete: Cascade)
+ codes OAuthCode[]
+ refreshTokens OAuthRefreshToken[]
@@index(projectId)
}
@@ -419,13 +420,15 @@ model OAuthCode {
}
model OAuthRefreshToken {
- id String @id @default(cuid())
- accessTokenId String
- refreshToken String @unique
- expiresAt DateTime
- createdAt DateTime @default(now())
+ id String @id @default(cuid())
+ clientId String
+ accessTokenId String
+ refreshTokenHashed String @unique
+ expiresAt DateTime
+ createdAt DateTime @default(now())
accessToken RestrictedToken @relation(fields: [accessTokenId], references: [id], onDelete: Cascade)
+ app OAuthApp @relation(fields: [clientId], references: [clientId], onDelete: Cascade)
@@index(accessTokenId)
}