The modern link attribution platform. Loved by world-class engineering teams at Twilio, Zillow, Jobber, Vercel, Raycast, and more.
TypeScript clickhousemysqlnextjsopen-sourceplanetscaleprismatailwindcsstinybirdtypescriptupstashvercel
use the installationId
Kiran K363c8ae843d5
diff --git a/apps/web/app/api/integrations/uninstall/route.ts b/apps/web/app/api/integrations/uninstall/route.tsindex 538196077a..d2f54e50a3 100644--- a/apps/web/app/api/integrations/uninstall/route.ts+++ b/apps/web/app/api/integrations/uninstall/route.ts@@ -1,13 +1,11 @@-// GET /api/integrations/[slug]/installation - get an installation by slug-import { DubApiError } from "@/lib/api/errors";import { withWorkspace } from "@/lib/auth";import { prisma } from "@/lib/prisma";import { NextResponse } from "next/server";-// DELETE /api/integrations/[slug]/installation - delete an installation by slug+// DELETE /api/integrations/uninstall - delete an installation by idexport const DELETE = withWorkspace(- async ({ searchParams, workspace }) => {+ async ({ searchParams, session }) => {const { installationId } = searchParams;const installation = await prisma.oAuthAuthorizedApp.findUnique({@@ -23,22 +21,18 @@ export const DELETE = withWorkspace(});}- await prisma.$transaction([- prisma.oAuthAuthorizedApp.delete({- where: {- id: installationId,- },- }),- prisma.restrictedToken.delete({- where: {- userId_projectId_clientId: {- userId: installation.userId,- projectId: workspace.id,- clientId: installation.clientId,- },- },- }),- ]);+ if (installation.userId !== session.user.id) {+ throw new DubApiError({+ code: "unauthorized",+ message: "You are not authorized to uninstall this integration",+ });+ }++ await prisma.oAuthAuthorizedApp.delete({+ where: {+ id: installationId,+ },+ });return NextResponse.json({ id: installationId });},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 f9451109d5..e3af9b7f61 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@@ -163,49 +163,63 @@ export const exchangeAuthCodeForToken = async (length: OAUTH_CONFIG.ACCESS_TOKEN_LENGTH,prefix: OAUTH_CONFIG.ACCESS_TOKEN_PREFIX,});+const refreshToken = createToken({length: OAUTH_CONFIG.REFRESH_TOKEN_LENGTH,});+const accessTokenExpires = new Date(Date.now() + OAUTH_CONFIG.ACCESS_TOKEN_LIFETIME * 1000,);- // Delete the existing token issued to the client for the user for the selected workspace before creating a new one+ // Add to authorized apps// We only support one token per client per user per workspace at a time+ const installation = await prisma.oAuthAuthorizedApp.upsert({+ create: {+ userId,+ projectId,+ clientId,+ },+ update: {},+ where: {+ userId_projectId_clientId: {+ clientId,+ userId,+ projectId,+ },+ },+ });+await prisma.$transaction([+ // Remove all existing tokens for this clientprisma.restrictedToken.deleteMany({where: {- userId,- projectId,- clientId,+ installationId: installation.id,},}),- prisma.oAuthAuthorizedApp.deleteMany({+ // Delete the code after it's been used+ prisma.oAuthCode.delete({where: {- userId,- projectId,- clientId,+ code,},}),- ]);- await prisma.$transaction([// Create the access token and refresh tokenprisma.restrictedToken.create({data: {- clientId,- 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,+ scopes,expires: accessTokenExpires,+ rateLimit: getCurrentPlan(workspace.plan as string).limits.api,+ userId,+ projectId,+ installationId: installation.id,refreshTokens: {create: {- clientId,+ installationId: installation.id,hashedRefreshToken: await hashToken(refreshToken),expiresAt: new Date(Date.now() + OAUTH_CONFIG.REFRESH_TOKEN_LIFETIME * 1000,@@ -214,22 +228,6 @@ export const exchangeAuthCodeForToken = async (},},}),-- // Delete the code after it's been used- prisma.oAuthCode.delete({- where: {- code,- },- }),-- // Add to authorized apps- prisma.oAuthAuthorizedApp.create({- data: {- clientId,- userId,- projectId,- },- }),]);// https://www.oauth.com/oauth2-servers/access-tokens/access-token-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 5d33a312a0..7edd4216ff 100644--- a/apps/web/app/api/oauth/token/refresh-access-token.ts+++ b/apps/web/app/api/oauth/token/refresh-access-token.ts@@ -78,19 +78,17 @@ export const refreshAccessToken = async (const refreshTokenRecord = await prisma.oAuthRefreshToken.findFirst({where: {- clientId,hashedRefreshToken: await hashToken(refresh_token),},select: {id: true,expiresAt: true,- accessToken: {+ authorizedApp: {select: {id: true,- name: true,userId: true,+ clientId: true,projectId: true,- scopes: true,project: {select: {plan: true,@@ -98,66 +96,76 @@ export const refreshAccessToken = async (},},},+ accessToken: {+ select: {+ id: true,+ name: true,+ scopes: true,+ },+ },},});if (!refreshTokenRecord) {throw new DubApiError({code: "unauthorized",- message: "Refresh token not found or expired",+ message: "Refresh token not found.",});}- if (refreshTokenRecord.expiresAt < new Date()) {+ if (refreshTokenRecord.authorizedApp.clientId !== clientId) {throw new DubApiError({code: "unauthorized",- message: "Refresh token expired",+ message: "Client ID mismatch.",});}- const {- userId,- projectId,- scopes,- name,- project: workspace,- id: accessTokenId,- } = refreshTokenRecord.accessToken;+ if (refreshTokenRecord.expiresAt < new Date()) {+ throw new DubApiError({+ code: "unauthorized",+ message: "Refresh token expired.",+ });+ }const newAccessToken = createToken({length: OAUTH_CONFIG.ACCESS_TOKEN_LENGTH,prefix: OAUTH_CONFIG.ACCESS_TOKEN_PREFIX,});+const newRefreshToken = createToken({length: OAUTH_CONFIG.REFRESH_TOKEN_LENGTH,});+const accessTokenExpires = new Date(Date.now() + OAUTH_CONFIG.ACCESS_TOKEN_LIFETIME * 1000,);+ const { accessToken, authorizedApp } = refreshTokenRecord;+await prisma.$transaction([// Delete the old access tokenprisma.restrictedToken.delete({where: {- id: accessTokenId,+ id: accessToken.id,},}),// Create the access token and refresh tokenprisma.restrictedToken.create({data: {- clientId,- userId,- projectId,- scopes,- name,+ name: accessToken.name,hashedKey: await hashToken(newAccessToken),partialKey: `${newAccessToken.slice(0, 3)}...${newAccessToken.slice(-4)}`,- rateLimit: getCurrentPlan(workspace.plan as string).limits.api,+ scopes: accessToken.scopes,expires: accessTokenExpires,+ rateLimit: getCurrentPlan(authorizedApp.project.plan as string).limits+ .api,+ userId: authorizedApp.userId,+ projectId: authorizedApp.projectId,+ installationId: authorizedApp.id,refreshTokens: {create: {- clientId,+ installationId: authorizedApp.id,hashedRefreshToken: await hashToken(newRefreshToken),expiresAt: new Date(Date.now() + OAUTH_CONFIG.REFRESH_TOKEN_LIFETIME * 1000,diff --git a/apps/web/app/api/oauth/userinfo/route.ts b/apps/web/app/api/oauth/userinfo/route.tsindex 1f4ca77e9d..2e38479adb 100644--- a/apps/web/app/api/oauth/userinfo/route.ts+++ b/apps/web/app/api/oauth/userinfo/route.ts@@ -14,7 +14,7 @@ export async function GET(req: NextRequest) {expires: {gte: new Date(),},- clientId: {+ installationId: {not: null,},},diff --git a/apps/web/app/app.dub.co/(dashboard)/[slug]/integrations/add-edit-integration-form.tsx b/apps/web/app/app.dub.co/(dashboard)/[slug]/integrations/add-edit-integration-form.tsxindex 2fcd9091bf..0c60ab36e5 100644--- a/apps/web/app/app.dub.co/(dashboard)/[slug]/integrations/add-edit-integration-form.tsx+++ b/apps/web/app/app.dub.co/(dashboard)/[slug]/integrations/add-edit-integration-form.tsx@@ -15,13 +15,13 @@ import { toast } from "sonner";import { mutate } from "swr";const defaultValues: NewIntegration = {- name: "Demo",- slug: "demo",+ name: "",+ slug: "",description: "",- developer: "Kiran",- website: "http://localhost:3000/api/oauth/callback",- redirectUri: "http://localhost:3000/api/oauth/callback",- logo: "http://localhost:3000/api/oauth/callback",+ developer: "",+ website: "",+ redirectUri: "",+ logo: "",pkce: false,};@@ -247,7 +247,7 @@ export default function AddEditIntegrationForm({<div className="flex items-center justify-between pb-4 pt-2"><label htmlFor="pkce" className="flex items-center space-x-2"><h2 className="text-sm font-medium text-gray-900">Allow PKCE</h2>- <InfoTooltip content="We strongly recommend using the PKCE flow for increased security" />+ <InfoTooltip content="We strongly recommend using the PKCE flow for increased security. Make sure your application supports it." /></label><Switchchecked={pkce}diff --git a/apps/web/prisma/schema/oauth.prisma b/apps/web/prisma/schema/oauth.prismaindex c599d91620..0d2a55ebb4 100644--- a/apps/web/prisma/schema/oauth.prisma+++ b/apps/web/prisma/schema/oauth.prisma@@ -19,8 +19,6 @@ model OAuthApp {user User? @relation(fields: [userId], references: [id], onDelete: SetNull)project Project @relation(fields: [projectId], references: [id], onDelete: Cascade)oAuthCodes OAuthCode[]- accessTokens RestrictedToken[]- refreshTokens OAuthRefreshToken[]authorizedApps OAuthAuthorizedApp[]@@index(projectId)@@ -52,16 +50,16 @@ model OAuthCode {model OAuthRefreshToken {id String @id @default(cuid())- clientId String+ installationId StringaccessTokenId StringhashedRefreshToken String @uniqueexpiresAt DateTimecreatedAt DateTime @default(now())- oAuthApp OAuthApp @relation(fields: [clientId], references: [clientId], onDelete: Cascade)- accessToken RestrictedToken @relation(fields: [accessTokenId], references: [id], onDelete: Cascade)+ accessToken RestrictedToken @relation(fields: [accessTokenId], references: [id], onDelete: Cascade)+ authorizedApp OAuthAuthorizedApp @relation(fields: [installationId], references: [id], onDelete: Cascade)- @@index([clientId])+ @@index([installationId])@@index([accessTokenId])}@@ -72,9 +70,11 @@ model OAuthAuthorizedApp {userId String // user who granted accesscreatedAt DateTime @default(now())- oAuthApp OAuthApp @relation(fields: [clientId], references: [clientId], onDelete: Cascade)- user User @relation(fields: [userId], references: [id], onDelete: Cascade)- project Project @relation(fields: [projectId], references: [id], onDelete: Cascade)+ oAuthApp OAuthApp @relation(fields: [clientId], references: [clientId], onDelete: Cascade)+ user User @relation(fields: [userId], references: [id], onDelete: Cascade)+ project Project @relation(fields: [projectId], references: [id], onDelete: Cascade)+ accessTokens RestrictedToken[]+ refreshTokens OAuthRefreshToken[]@@unique([userId, projectId, clientId])@@index([clientId])diff --git a/apps/web/prisma/schema/token.prisma b/apps/web/prisma/schema/token.prismaindex 978ccd6ebe..60468412c8 100644--- a/apps/web/prisma/schema/token.prisma+++ b/apps/web/prisma/schema/token.prisma@@ -14,29 +14,28 @@ model Token {}model RestrictedToken {- id String @id @default(cuid())- name String- hashedKey String @unique- partialKey String- scopes String? // space separated (Eg: "links:write", "domains:read")- 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+ id String @id @default(cuid())+ name String+ hashedKey String @unique+ partialKey String+ scopes String? // space separated (Eg: "links:write", "domains:read")+ expires DateTime?+ lastUsed DateTime?+ rateLimit Int @default(600) // rate limit per minute+ createdAt DateTime @default(now())+ updatedAt DateTime @updatedAt+ userId String+ projectId String+ installationId String? // if the token is generated by an OAuth clientuser User @relation(fields: [userId], references: [id], onDelete: Cascade)project Project @relation(fields: [projectId], references: [id], onDelete: Cascade)- oAuthApp OAuthApp? @relation(fields: [clientId], references: [clientId], onDelete: Cascade)+ authorizedApp OAuthAuthorizedApp? @relation(fields: [installationId], references: [id], onDelete: Cascade)refreshTokens OAuthRefreshToken[]- @@unique([userId, projectId, clientId])@@index([userId])@@index([projectId])- @@index([clientId])+ @@index([installationId])}model VerificationToken {