The modern link attribution platform. Loved by world-class engineering teams at Twilio, Zillow, Jobber, Vercel, Raycast, and more.
TypeScript clickhousemysqlnextjsopen-sourceplanetscaleprismatailwindcsstinybirdtypescriptupstashvercel
wip
Kiran Kb2e57d8e6fe0
diff --git a/apps/web/app/api/oauth-clients/[id]/route.ts b/apps/web/app/api/oauth-clients/[clientId]/route.tssimilarity index 78%rename from apps/web/app/api/oauth-clients/[id]/route.tsrename to apps/web/app/api/oauth-clients/[clientId]/route.tsindex d29d4a1b3e..0bf3ae442a 100644--- a/apps/web/app/api/oauth-clients/[id]/route.ts+++ b/apps/web/app/api/oauth-clients/[clientId]/route.ts@@ -8,12 +8,12 @@ import {} from "@/lib/zod/schemas/oauth";import { NextResponse } from "next/server";-// GET /api/oauth-clients/[id] – get an OAuth client+// GET /api/oauth-clients/[clientId] – get an OAuth clientexport const GET = withWorkspace(async ({ params, workspace }) => {const app = await prisma.oAuthClient.findFirst({where: {- id: params.id,+ clientId: params.clientId,projectId: workspace.id,},});@@ -21,7 +21,7 @@ export const GET = withWorkspace(if (!app) {throw new DubApiError({code: "not_found",- message: `OAuth app with id ${params.id} not found.`,+ message: `OAuth app with id ${params.clientId} not found.`,});}@@ -32,7 +32,7 @@ export const GET = withWorkspace(},);-// PATCH /api/oauth-clients/[id] – update an OAuth client+// PATCH /api/oauth-clients/[clientId] – update an OAuth clientexport const PATCH = withWorkspace(async ({ req, params, workspace }) => {const { name, description, website, redirectUri, scopes } =@@ -40,7 +40,7 @@ export const PATCH = withWorkspace(const app = await prisma.oAuthClient.update({where: {- id: params.id,+ clientId: params.clientId,projectId: workspace.id,},data: {@@ -61,12 +61,12 @@ export const PATCH = withWorkspace(},);-// DELETE /api/oauth-clients/[id] - delete an OAuth client+// DELETE /api/oauth-clients/[clientId] - delete an OAuth clientexport const DELETE = withWorkspace(async ({ params, workspace }) => {const app = await prisma.oAuthClient.findFirst({where: {- id: params.id,+ clientId: params.clientId,projectId: workspace.id,},});@@ -74,17 +74,17 @@ export const DELETE = withWorkspace(if (!app) {throw new DubApiError({code: "not_found",- message: `OAuth app with id ${params.id} not found.`,+ message: `OAuth app with id ${params.clientId} not found.`,});}await prisma.oAuthClient.delete({where: {- id: params.id,+ clientId: params.clientId,},});- return NextResponse.json({ id: params.id });+ return NextResponse.json({ id: params.clientId });},{requiredScopes: ["oauth_apps.write"],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 fba63820b6..570ae02cce 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@@ -36,7 +36,7 @@ export const exchangeAuthCodeForToken = async (});}- const app = await prisma.oAuthApp.findFirst({+ const app = await prisma.oAuthClient.findFirst({where: {clientId,clientSecretHashed: await hashToken(clientSecret),diff --git a/apps/web/app/api/oauth/token/refresh-access-token.ts b/apps/web/app/api/oauth/token/refresh-access-token.tsindex acd4a1e181..08b5f37f3d 100644--- a/apps/web/app/api/oauth/token/refresh-access-token.ts+++ b/apps/web/app/api/oauth/token/refresh-access-token.ts@@ -36,7 +36,7 @@ export const refreshAccessToken = async (});}- const app = await prisma.oAuthApp.findFirst({+ const app = await prisma.oAuthClient.findFirst({where: {clientId,clientSecretHashed: await hashToken(clientSecret),diff --git a/apps/web/app/api/oauth/userinfo/route.ts b/apps/web/app/api/oauth/userinfo/route.tsindex 9c309f332c..5e33eb97cd 100644--- a/apps/web/app/api/oauth/userinfo/route.ts+++ b/apps/web/app/api/oauth/userinfo/route.ts@@ -11,9 +11,14 @@ export async function GET(req: NextRequest) {const tokenRecord = await prisma.restrictedToken.findFirst({where: {hashedKey: await hashToken(accessToken),+ expires: {+ gte: new Date(),+ },+ clientId: {+ not: null,+ },},select: {- id: true,user: {select: {id: true,@@ -25,6 +30,8 @@ export async function GET(req: NextRequest) {},});+ console.log("/api/oauth/userinfo", tokenRecord);+if (!tokenRecord) {throw new DubApiError({code: "unauthorized",diff --git a/apps/web/app/app.dub.co/(auth)/oauth/authorize/AuthorizeForm.tsx b/apps/web/app/app.dub.co/(auth)/oauth/authorize/AuthorizeForm.tsxnew file mode 100644index 0000000000..86e61ab87b--- /dev/null+++ b/apps/web/app/app.dub.co/(auth)/oauth/authorize/AuthorizeForm.tsx@@ -0,0 +1,52 @@+"use client";++import { handleAuthorize } from "@/lib/oauth";+import z from "@/lib/zod";+import { authorizeSchema } from "@/lib/zod/schemas/oauth";+import { Button } from "@dub/ui";+import { OAuthClient, Project } from "@prisma/client";++type AuthorizeFormProps = {+ workspaces: Pick<Project, "id" | "name" | "logo">[];+ oAuthClient: Pick<OAuthClient, "name">;+} & z.infer<typeof authorizeSchema>;++export const AuthorizeForm = (props: AuthorizeFormProps) => {+ const {+ workspaces,+ oAuthClient,+ client_id,+ redirect_uri,+ response_type,+ state,+ } = props;++ return (+ <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="workspaceId">+ {workspaces.map((workspace) => (+ <option key={workspace.id} value={workspace.id}>+ <div>+ <img+ src={workspace.logo!}+ className="h-8 w-8 rounded-full"+ alt=""+ />+ {workspace.name}+ </div>+ </option>+ ))}+ </select>+ <Button+ text={`Authorize ${oAuthClient.name}`}+ type="submit"+ // loading={clickedGithub}+ // icon={<Github className="h-4 w-4" />}+ />+ </form>+ );+};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.tsxindex 99d422142c..0ecb8c67a8 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,11 +1,12 @@import { getSession } from "@/lib/auth";-import { handleAuthorize, vaidateAuthorizeRequest } from "@/lib/oauth";+import { 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 { Background, Footer, Nav } from "@dub/ui";import { TimerOff } from "lucide-react";import { redirect } from "next/navigation";+import { AuthorizeForm } from "./AuthorizeForm";export const runtime = "nodejs";@@ -27,7 +28,7 @@ export default async function Authorize({redirect("/login");}- const { app, request } = await vaidateAuthorizeRequest(searchParams);+ const { oAuthClient, request } = await vaidateAuthorizeRequest(searchParams);const workspaces = await prisma.project.findMany({where: {@@ -51,42 +52,13 @@ export default async function Authorize({<div className="mx-auto flex h-20 w-20 items-center justify-center rounded-full border border-gray-300 bg-white/30"><TimerOff className="h-6 w-6 text-gray-400" /></div>- <h1 className="font-display text-5xl font-bold">{app.name}</h1>+ <h1 className="font-display text-5xl font-bold">{oAuthClient.name}</h1><p className="text-lg text-gray-600">{}</p>- <form action={handleAuthorize}>- <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>- <img- src={workspace.logo!}- className="h-8 w-8 rounded-full"- alt=""- />- {workspace.name}- </div>- </option>- ))}- </select>- <Button- text={`Authorize ${app.name}`}- type="submit"- // loading={clickedGithub}- // icon={<Github className="h-4 w-4" />}- />- </form>+ <AuthorizeForm+ oAuthClient={oAuthClient}+ workspaces={workspaces}+ {...request}+ /></div><Footer /><Background />diff --git a/apps/web/lib/oauth.ts b/apps/web/lib/oauth.tsindex 1aaf479c00..fa62040f79 100644--- a/apps/web/lib/oauth.ts+++ b/apps/web/lib/oauth.ts@@ -9,22 +9,22 @@ export const vaidateAuthorizeRequest = async (params: any) => {const request = authorizeSchema.parse(params);const { client_id: clientId, redirect_uri: redirectUri } = request;- const app = await prisma.oAuthApp.findFirst({+ const oAuthClient = await prisma.oAuthClient.findFirst({where: {clientId,},});- if (!app) {+ if (!oAuthClient) {throw new Error(`Could not find OAuth client with clientId ${clientId}`);}- if (app.redirectUri !== redirectUri) {+ if (oAuthClient.redirectUri !== redirectUri) {throw new Error("Invalid redirect_uri parameter for the application.");}return {- app,+ oAuthClient,request,};};@@ -45,7 +45,7 @@ export const handleAuthorize = async (formData: FormData) => {throw new Error("Please select a workspace to authorize the app");}- const { app, request } = await vaidateAuthorizeRequest(+ const { oAuthClient, request } = await vaidateAuthorizeRequest(Object.fromEntries(formData),);@@ -57,7 +57,7 @@ export const handleAuthorize = async (formData: FormData) => {redirectUri: request.redirect_uri,projectId: workspaceId as string,userId: session.user.id,- scopes: app.scopes,+ scopes: oAuthClient.scopes,code: nanoid(TOKEN_LENGTH.code),expiresAt: new Date(Date.now() + TOKEN_EXPIRY.code),},diff --git a/apps/web/lib/zod/schemas/oauth.ts b/apps/web/lib/zod/schemas/oauth.tsindex 79b0a65680..b8fdf49b46 100644--- a/apps/web/lib/zod/schemas/oauth.ts+++ b/apps/web/lib/zod/schemas/oauth.ts@@ -2,7 +2,7 @@ import { availableScopes } from "@/lib/api/tokens/scopes";import { z } from "zod";export const oAuthClientSchema = z.object({- id: z.string(),+ clientId: z.string(),name: z.string(),description: z.string().nullable(),website: z.string(),@@ -11,7 +11,6 @@ export const oAuthClientSchema = z.object({.string().nullable().transform((val) => val?.split(" ") ?? []),- clientId: z.string(),});export const createOAuthClientSchema = z.object({diff --git a/apps/web/prisma/schema.prisma b/apps/web/prisma/schema.prismaindex 7b2faa276a..34845ca98f 100644--- a/apps/web/prisma/schema.prisma+++ b/apps/web/prisma/schema.prisma@@ -90,23 +90,23 @@ model Token {}model RestrictedToken {- id String @id @default(cuid())- name String- hashedKey String @unique- partialKey String- scopes String? // space separated (Eg: "read:links write:links")- expires DateTime?- lastUsed DateTime?- rateLimit Int @default(600) // rate limit per minute- createdAt DateTime @default(now())- updatedAt DateTime @updatedAt- userId String- projectId String- oAuthClientId String? // if the token is generated by an OAuth client (access token)+ id String @id @default(cuid())+ name String+ hashedKey String @unique+ partialKey String+ scopes String? // space separated (Eg: "read:links write:links")+ expires DateTime?+ lastUsed DateTime?+ rateLimit Int @default(600) // rate limit per minute+ createdAt DateTime @default(now())+ updatedAt DateTime @updatedAt+ userId String+ projectId String+ clientId String? // if the token is generated by an OAuth client (access token)user User @relation(fields: [userId], references: [id], onDelete: Cascade)project Project @relation(fields: [projectId], references: [id], onDelete: Cascade)- oAuthClient OAuthClient? @relation(fields: [oAuthClientId], references: [id], onDelete: Cascade)+ oAuthClient OAuthClient? @relation(fields: [clientId], references: [clientId], onDelete: Cascade)refreshTokens OAuthRefreshToken[]@@index([userId])@@ -360,17 +360,16 @@ model Customer {}model OAuthClient {- id String @id @default(cuid())- projectId String+ clientId String @id @uniquename Stringwebsite Stringdescription String?- clientId String @uniqueclientSecretHashed StringredirectUri Stringscopes String?createdAt DateTime @default(now())updatedAt DateTime @updatedAt+ projectId Stringproject Project @relation(fields: [projectId], references: [id], onDelete: Cascade)accessCodes OAuthCode[]@@ -381,28 +380,28 @@ model OAuthClient {}model OAuthCode {- id String @id @default(cuid())- oAuthClientId String- userId String // User who granted access- projectId String // Workspace that user granted access to- code String @unique- scopes String?- redirectUri String- expiresAt DateTime- createdAt DateTime @default(now())-- oAuthClient OAuthClient @relation(fields: [oAuthClientId], references: [clientId], onDelete: Cascade)+ id String @id @default(cuid())+ clientId String+ userId String // User who granted access+ projectId String // Workspace that user granted access to+ code String @unique+ scopes String?+ redirectUri String+ expiresAt DateTime+ createdAt DateTime @default(now())++ oAuthClient OAuthClient @relation(fields: [clientId], references: [clientId], onDelete: Cascade)}model OAuthRefreshToken {id String @id @default(cuid())- oAuthClientId String+ clientId StringaccessTokenId StringrefreshTokenHashed String @uniqueexpiresAt DateTimecreatedAt DateTime @default(now())- oAuthClient OAuthClient @relation(fields: [oAuthClientId], references: [clientId], onDelete: Cascade)+ oAuthClient OAuthClient @relation(fields: [clientId], references: [clientId], onDelete: Cascade)accessToken RestrictedToken @relation(fields: [accessTokenId], references: [id], onDelete: Cascade)@@index(accessTokenId)