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.

refactor: Improve OAuth token route and user info route

Kiran K503c46b07753
diff --git a/apps/web/app/api/oauth-apps/[appId]/route.ts b/apps/web/app/api/oauth-apps/[appId]/route.ts
index 9b663d7230..20613111b0 100644
--- a/apps/web/app/api/oauth-apps/[appId]/route.ts
+++ b/apps/web/app/api/oauth-apps/[appId]/route.ts
@@ -6,67 +6,84 @@ import { oAuthAppSchema, updateOAuthAppSchema } from "@/lib/zod/schemas/oauth";
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({
- where: {
- id: params.appId,
- projectId: workspace.id,
- },
- });
-
- if (!app) {
- throw new DubApiError({
- code: "not_found",
- message: `OAuth app with id ${params.appId} not found.`,
+export const GET = withWorkspace(
+ async ({ params, workspace }) => {
+ const app = await prisma.oAuthApp.findUnique({
+ where: {
+ id: params.appId,
+ projectId: workspace.id,
+ },
});
- }
- return NextResponse.json(oAuthAppSchema.parse(app));
-});
+ if (!app) {
+ throw new DubApiError({
+ code: "not_found",
+ message: `OAuth app with id ${params.appId} not found.`,
+ });
+ }
+
+ return NextResponse.json(oAuthAppSchema.parse(app));
+ },
+ {
+ requiredScopes: ["oauth_apps.read"],
+ },
+);
// PATCH /api/oauth-apps/[appId] – update an OAuth app
-export const PATCH = withWorkspace(async ({ req, params, workspace }) => {
- const { name, description, website, redirectUri, scopes } =
- updateOAuthAppSchema.parse(await parseRequestBody(req));
+export const PATCH = withWorkspace(
+ async ({ req, params, workspace }) => {
+ const { name, description, website, redirectUri, scopes } =
+ updateOAuthAppSchema.parse(await parseRequestBody(req));
- const app = await prisma.oAuthApp.update({
- where: {
- id: params.appId,
- projectId: workspace.id,
- },
- data: {
- name,
- description,
- website,
- redirectUri,
- scopes: scopes ? scopes.join(",") : null,
- },
- });
+ const app = await prisma.oAuthApp.update({
+ where: {
+ id: params.appId,
+ projectId: workspace.id,
+ },
+ data: {
+ ...(name && { name }),
+ ...(description && { description }),
+ ...(website && { website }),
+ ...(redirectUri && { redirectUri }),
+ ...(scopes && {
+ scopes: scopes.length > 0 ? [...new Set(scopes)].join(" ") : null,
+ }),
+ },
+ });
- return NextResponse.json(oAuthAppSchema.parse(app));
-});
+ return NextResponse.json(oAuthAppSchema.parse(app));
+ },
+ {
+ requiredScopes: ["oauth_apps.write"],
+ },
+);
// DELETE /api/oauth-apps/[appId] - delete an OAuth app
-export const DELETE = withWorkspace(async ({ req, params, workspace }) => {
- const app = await prisma.oAuthApp.findUnique({
- where: {
- id: params.appId,
- projectId: workspace.id,
- },
- });
-
- if (!app) {
- throw new DubApiError({
- code: "not_found",
- message: `OAuth app with id ${params.appId} not found.`,
+export const DELETE = withWorkspace(
+ async ({ req, params, workspace }) => {
+ const app = await prisma.oAuthApp.findUnique({
+ where: {
+ id: params.appId,
+ projectId: workspace.id,
+ },
});
- }
- await prisma.oAuthApp.delete({
- where: {
- id: params.appId,
- },
- });
+ if (!app) {
+ throw new DubApiError({
+ code: "not_found",
+ message: `OAuth app with id ${params.appId} not found.`,
+ });
+ }
+
+ await prisma.oAuthApp.delete({
+ where: {
+ id: params.appId,
+ },
+ });
- return NextResponse.json({ id: params.appId });
-});
+ return NextResponse.json({ id: params.appId });
+ },
+ {
+ requiredScopes: ["oauth_apps.write"],
+ },
+);
diff --git a/apps/web/app/api/oauth-apps/route.ts b/apps/web/app/api/oauth-apps/route.ts
index a9e22d129a..8ec47a079c 100644
--- a/apps/web/app/api/oauth-apps/route.ts
+++ b/apps/web/app/api/oauth-apps/route.ts
@@ -1,4 +1,4 @@
-import { TOKEN_LENGTHS } from "@/lib/api/oauth";
+import { TOKEN_LENGTH } from "@/lib/api/oauth";
import { parseRequestBody } from "@/lib/api/utils";
import { hashToken, withWorkspace } from "@/lib/auth";
import { prisma } from "@/lib/prisma";
@@ -8,41 +8,52 @@ import { NextResponse } from "next/server";
import { z } from "zod";
// POST /api/oauth-apps - create a new OAuth app
-export const POST = withWorkspace(async ({ req, workspace }) => {
- const { name, description, website, redirectUri, scopes } =
- createOAuthAppSchema.parse(await parseRequestBody(req));
+export const POST = withWorkspace(
+ async ({ req, workspace }) => {
+ const { name, description, website, redirectUri, scopes } =
+ createOAuthAppSchema.parse(await parseRequestBody(req));
- const clientSecret = `dub_${nanoid(TOKEN_LENGTHS.clientSecret)}`;
+ const clientSecret = `dub_${nanoid(TOKEN_LENGTH.clientSecret)}`;
- const app = await prisma.oAuthApp.create({
- data: {
- projectId: workspace.id,
- name,
- description,
- website,
- redirectUri,
- scopes: scopes ? scopes.join(",") : null,
- clientId: nanoid(TOKEN_LENGTHS.clientId),
- clientSecretHashed: await hashToken(clientSecret),
- },
- });
+ const app = await prisma.oAuthApp.create({
+ data: {
+ projectId: workspace.id,
+ name,
+ description,
+ website,
+ redirectUri,
+ scopes:
+ scopes && scopes.length > 0 ? [...new Set(scopes)].join(" ") : null,
+ clientId: nanoid(TOKEN_LENGTH.clientId),
+ clientSecretHashed: await hashToken(clientSecret),
+ },
+ });
- return NextResponse.json(
- {
- ...oAuthAppSchema.parse(app),
- clientSecret,
- },
- { status: 201 },
- );
-});
+ return NextResponse.json(
+ {
+ ...oAuthAppSchema.parse(app),
+ clientSecret,
+ },
+ { status: 201 },
+ );
+ },
+ {
+ requiredScopes: ["oauth_apps.write"],
+ },
+);
// GET /api/oauth-apps - get all OAuth apps for a specific workspace
-export const GET = withWorkspace(async ({ workspace }) => {
- const apps = await prisma.oAuthApp.findMany({
- where: {
- projectId: workspace.id,
- },
- });
+export const GET = withWorkspace(
+ async ({ workspace }) => {
+ const apps = await prisma.oAuthApp.findMany({
+ where: {
+ projectId: workspace.id,
+ },
+ });
- return NextResponse.json(z.array(oAuthAppSchema).parse(apps));
-});
+ return NextResponse.json(z.array(oAuthAppSchema).parse(apps));
+ },
+ {
+ requiredScopes: ["oauth_apps.read"],
+ },
+);
diff --git a/apps/web/app/api/oauth/token/route.ts b/apps/web/app/api/oauth/token/route.ts
index 46e4282931..8989711383 100644
--- a/apps/web/app/api/oauth/token/route.ts
+++ b/apps/web/app/api/oauth/token/route.ts
@@ -1,5 +1,5 @@
import { DubApiError, handleAndReturnErrorResponse } from "@/lib/api/errors";
-import { TOKEN_EXPIRY, TOKEN_LENGTHS } from "@/lib/api/oauth";
+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";
@@ -10,8 +10,12 @@ import { NextRequest, NextResponse } from "next/server";
export async function POST(req: NextRequest) {
try {
const formData = Object.fromEntries(await req.formData());
- const { client_id, client_secret, code, redirect_uri } =
- codeExchangeSchema.parse(formData);
+ const {
+ client_id,
+ client_secret,
+ code,
+ redirect_uri: redirectUri,
+ } = codeExchangeSchema.parse(formData);
let clientId = client_id;
let clientSecret = client_secret;
@@ -37,8 +41,8 @@ export async function POST(req: NextRequest) {
const oauthCode = await prisma.oAuthCode.findFirst({
where: {
code,
- clientId: client_id,
- redirectUri: redirect_uri,
+ clientId,
+ redirectUri,
app: {
clientSecretHashed: await hashToken(clientSecret),
},
@@ -46,9 +50,10 @@ export async function POST(req: NextRequest) {
select: {
userId: true,
projectId: true,
+ scopes: true,
+ expiresAt: true,
app: {
select: {
- id: true,
name: true,
},
},
@@ -62,36 +67,67 @@ export async function POST(req: NextRequest) {
});
}
- await prisma.oAuthCode.delete({
+ if (oauthCode.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: {
- code,
+ id: oauthCode.projectId,
+ },
+ select: {
+ plan: true,
},
});
- const accessToken = `dub_${nanoid(TOKEN_LENGTHS.accessToken)}`;
- const hashedKey = await hashToken(accessToken);
- const partialKey = `${accessToken.slice(0, 3)}...${accessToken.slice(-4)}`;
+ const accessToken = `dub_${nanoid(TOKEN_LENGTH.accessToken)}`;
+ const expires = new Date(Date.now() + TOKEN_EXPIRY.accessToken);
+ const expiresInSeconds = Math.floor(expires.getTime() / 1000);
- const { expires } = await prisma.restrictedToken.create({
- data: {
- name: `Access token for ${oauthCode.app.name}`,
- hashedKey,
- partialKey,
- userId: oauthCode.userId,
- projectId: oauthCode.projectId,
- rateLimit: getCurrentPlan("free").limits.api,
- expires: new Date(Date.now() + TOKEN_EXPIRY.accessToken),
- scopes: "",
- // scopes && scopes.length > 0 ? [...new Set(scopes)].join(" ") : null,
- },
+ await Promise.all([
+ // Create the access token
+ prisma.restrictedToken.create({
+ data: {
+ name: `Access token for ${oauthCode.app.name}`,
+ hashedKey: await hashToken(accessToken),
+ partialKey: `${accessToken.slice(0, 3)}...${accessToken.slice(-4)}`,
+ userId: oauthCode.userId,
+ projectId: oauthCode.projectId,
+ scopes: oauthCode.scopes,
+ rateLimit: getCurrentPlan(workspace?.plan as string).limits.api,
+ expires: new Date(Date.now() + TOKEN_EXPIRY.accessToken),
+ },
+ }),
+
+ // Delete the code after it's been used
+ prisma.oAuthCode.delete({
+ where: {
+ code,
+ },
+ }),
+ ]);
+
+ console.log("Token exchange", {
+ access_token: accessToken,
+ refresh_token: accessToken,
+ token_type: "Bearer",
+ expires_in: expiresInSeconds,
});
return NextResponse.json({
access_token: accessToken,
- token_type: "Bearer",
- expires_in: expires,
- scope: "read write",
refresh_token: accessToken,
+ token_type: "Bearer",
+ expires_in: expiresInSeconds,
});
} catch (error) {
return handleAndReturnErrorResponse(error);
diff --git a/apps/web/app/app.dub.co/(auth)/oauth/authorize/page.tsx b/apps/web/app/app.dub.co/(auth)/oauth/authorize/page.tsx
index 97100cb019..99d422142c 100644
--- a/apps/web/app/app.dub.co/(auth)/oauth/authorize/page.tsx
+++ b/apps/web/app/app.dub.co/(auth)/oauth/authorize/page.tsx
@@ -1,13 +1,14 @@
-import { TOKEN_LENGTHS } from "@/lib/api/oauth";
import { getSession } from "@/lib/auth";
+import { handleAuthorize, vaidateAuthorizeRequest } from "@/lib/oauth";
import { prisma } from "@/lib/prisma";
import z from "@/lib/zod";
import { authorizeSchema } from "@/lib/zod/schemas/oauth";
import { Background, Button, Footer, Nav } from "@dub/ui";
-import { nanoid } from "@dub/utils";
import { TimerOff } from "lucide-react";
import { redirect } from "next/navigation";
+export const runtime = "nodejs";
+
// export const metadata = constructMetadata({
// title: "Expired Link – Dub.co",
// description:
@@ -15,8 +16,6 @@ import { redirect } from "next/navigation";
// noIndex: true,
// });
-export const runtime = "nodejs";
-
export default async function Authorize({
searchParams,
}: {
@@ -28,28 +27,7 @@ export default async function Authorize({
redirect("/login");
}
- const result = authorizeSchema.safeParse(searchParams);
-
- if (!result.success) {
- return result.error.message;
- }
-
- const { client_id, redirect_uri, response_type, state } = result.data;
-
- const app = await prisma.oAuthApp.findFirst({
- where: {
- clientId: client_id,
- },
- });
-
- if (!app) {
- return `Could not find OAuth client with clientId ${client_id}`;
- }
-
- // Validate
- if (app.redirectUri !== redirect_uri) {
- return "Invalid redirect_uri parameter for the application.";
- }
+ const { app, request } = await vaidateAuthorizeRequest(searchParams);
const workspaces = await prisma.project.findMany({
where: {
@@ -76,12 +54,19 @@ export default async function Authorize({
<h1 className="font-display text-5xl font-bold">{app.name}</h1>
<p className="text-lg text-gray-600">{}</p>
<form action={handleAuthorize}>
- <input type="hidden" name="client_id" value={client_id} />
- <input type="hidden" name="redirect_uri" value={redirect_uri} />
- <input type="hidden" name="response_type" value={response_type} />
- <input type="hidden" name="state" value={state} />
-
- <select name="workspace_id">
+ <input type="hidden" name="client_id" value={request.client_id} />
+ <input
+ type="hidden"
+ name="redirect_uri"
+ value={request.redirect_uri}
+ />
+ <input
+ type="hidden"
+ name="response_type"
+ value={request.response_type}
+ />
+ <input type="hidden" name="state" value={request.state} />
+ <select name="workspaceId">
{workspaces.map((workspace) => (
<option key={workspace.id} value={workspace.id}>
<div>
@@ -108,42 +93,3 @@ export default async function Authorize({
</main>
);
}
-
-// Server action to create OAuth app
-const handleAuthorize = async (formData: FormData) => {
- "use server";
-
- const session = await getSession();
-
- if (!session) {
- return redirect("/login");
- }
-
- const { client_id, redirect_uri, response_type, state, workspace_id } =
- authorizeSchema
- .merge(
- z.object({
- workspace_id: z.string(),
- }),
- )
- .parse(Object.fromEntries(formData));
-
- const { code } = await prisma.oAuthCode.create({
- data: {
- clientId: client_id,
- projectId: workspace_id,
- redirectUri: redirect_uri,
- userId: session.user.id,
- scopes: "",
- code: nanoid(TOKEN_LENGTHS.code),
- expiresAt: new Date(),
- },
- });
-
- const searchParams = new URLSearchParams({
- code,
- ...(state && { state }),
- });
-
- return redirect(`${redirect_uri}?${searchParams.toString()}`);
-};
diff --git a/apps/web/lib/api/oauth.ts b/apps/web/lib/api/oauth.ts
index 0d4339525b..a2cf711933 100644
--- a/apps/web/lib/api/oauth.ts
+++ b/apps/web/lib/api/oauth.ts
@@ -1,4 +1,4 @@
-export const TOKEN_LENGTHS = {
+export const TOKEN_LENGTH = {
clientId: 32,
clientSecret: 40,
code: 64,
@@ -7,6 +7,7 @@ export const TOKEN_LENGTHS = {
};
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
};
diff --git a/apps/web/lib/api/tokens/scopes.ts b/apps/web/lib/api/tokens/scopes.ts
index 2b740e435e..68fe0a1f1b 100644
--- a/apps/web/lib/api/tokens/scopes.ts
+++ b/apps/web/lib/api/tokens/scopes.ts
@@ -13,6 +13,8 @@ export const availableScopes = [
"tokens.read",
"tokens.write",
"conversions.write",
+ "oauth_apps.write",
+ "oauth_apps.read",
"apis.all", // All API scopes
"apis.read", // All read scopes
] as const;
@@ -148,6 +150,26 @@ export const resourcePermissions = [
},
],
},
+ {
+ name: "OAuth Apps",
+ key: "oauth_apps",
+ description: "OAuth apps (create, read, update, delete)",
+ betaFeature: true,
+ permissions: [
+ {
+ permission: "Read",
+ scope: "oauth_apps.read",
+ description: "Read OAuth apps",
+ roles: ["owner", "member"],
+ },
+ {
+ permission: "Write",
+ scope: "oauth_apps.write",
+ description: "Create, update, and delete OAuth apps",
+ roles: ["owner"],
+ },
+ ],
+ },
] as const;
// Map roles to scopes
@@ -178,6 +200,8 @@ export const scopeMapping = {
"links.write": ["links.write", "links.read"],
"tags.write": ["tags.write", "tags.read"],
"domains.write": ["domains.write", "domains.read"],
+ "tokens.write": ["tokens.write", "tokens.read"],
+ "oauth_apps.write": ["oauth_apps.write", "oauth_apps.read"],
};
export const scopePresets = [
@@ -205,12 +229,14 @@ export const scopesToName = (scopes: string[]) => {
description: "full access to all resources",
};
}
+
if (scopes.includes("apis.read")) {
return {
name: "Read-only",
description: "read-only access to all resources",
};
}
+
return {
name: "Restricted",
description: "restricted access to some resources",
diff --git a/apps/web/lib/oauth.ts b/apps/web/lib/oauth.ts
new file mode 100644
index 0000000000..79a6772533
--- /dev/null
+++ b/apps/web/lib/oauth.ts
@@ -0,0 +1,72 @@
+import { prisma } from "@/lib/prisma";
+import { nanoid } from "@dub/utils";
+import { redirect } from "next/navigation";
+import { TOKEN_EXPIRY, TOKEN_LENGTH } from "./api/oauth";
+import { getSession } from "./auth";
+import { authorizeSchema } from "./zod/schemas/oauth";
+
+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({
+ where: {
+ clientId,
+ },
+ });
+
+ if (!app) {
+ throw new Error(`Could not find OAuth client with clientId ${clientId}`);
+ }
+
+ if (app.redirectUri !== redirectUri) {
+ throw new Error("Invalid redirect_uri parameter for the application.");
+ }
+
+ return {
+ app,
+ request,
+ };
+};
+
+// Handle the authorize request and create a new OAuth code
+export const handleAuthorize = async (formData: FormData) => {
+ "use server";
+
+ const session = await getSession();
+
+ if (!session) {
+ return redirect("/login");
+ }
+
+ const workspaceId = formData.get("workspaceId");
+
+ if (!workspaceId) {
+ throw new Error("Please select a workspace to authorize the app");
+ }
+
+ const { app, request } = await vaidateAuthorizeRequest(
+ Object.fromEntries(formData),
+ );
+
+ console.info("Authorize request", request);
+
+ const { code } = await prisma.oAuthCode.create({
+ data: {
+ clientId: request.client_id,
+ redirectUri: request.redirect_uri,
+ projectId: workspaceId as string,
+ userId: session.user.id,
+ scopes: app.scopes,
+ code: nanoid(TOKEN_LENGTH.code),
+ expiresAt: new Date(Date.now() + TOKEN_EXPIRY.code),
+ },
+ });
+
+ const searchParams = new URLSearchParams({
+ code,
+ ...(request.state && { state: request.state }),
+ });
+
+ return redirect(`${request.redirect_uri}?${searchParams.toString()}`);
+};