The modern link attribution platform. Loved by world-class engineering teams at Twilio, Zillow, Jobber, Vercel, Raycast, and more.
TypeScript clickhousemysqlnextjsopen-sourceplanetscaleprismatailwindcsstinybirdtypescriptupstashvercel
add permission checks
Kiran Ke1bda3263618
diff --git a/apps/web/app/api/links/route.ts b/apps/web/app/api/links/route.tsindex bf9170221c..c3719ec506 100644--- a/apps/web/app/api/links/route.ts+++ b/apps/web/app/api/links/route.ts@@ -1,5 +1,6 @@import { DubApiError, ErrorCodes } from "@/lib/api/errors";import { createLink, getLinksForWorkspace, processLink } from "@/lib/api/links";+import { throwIfNotAllowed } from "@/lib/api/tokens/permissions";import { parseRequestBody } from "@/lib/api/utils";import { withWorkspace } from "@/lib/auth";import { ratelimit } from "@/lib/upstash";@@ -11,40 +12,50 @@ import { LOCALHOST_IP, getSearchParamsWithArray } from "@dub/utils";import { NextResponse } from "next/server";// GET /api/links – get all links for a workspace-export const GET = withWorkspace(async ({ req, headers, workspace }) => {- const searchParams = getSearchParamsWithArray(req.url);+export const GET = withWorkspace(+ async ({ req, headers, workspace, scopes }) => {+ throwIfNotAllowed({+ scopes,+ requiredScope: "links.read",+ });++ console.log("Kiran GET /api/links");- const {- domain,- tagId,- tagIds,- search,- sort,- page,- userId,- showArchived,- withTags,- includeUser,- } = getLinksQuerySchemaExtended.parse(searchParams);+ const searchParams = getSearchParamsWithArray(req.url);+ console.log(scopes);- const response = await getLinksForWorkspace({- workspaceId: workspace.id,- domain,- tagId,- tagIds,- search,- sort,- page,- userId,- showArchived,- withTags,- includeUser,- });+ const {+ domain,+ tagId,+ tagIds,+ search,+ sort,+ page,+ userId,+ showArchived,+ withTags,+ includeUser,+ } = getLinksQuerySchemaExtended.parse(searchParams);++ const response = await getLinksForWorkspace({+ workspaceId: workspace.id,+ domain,+ tagId,+ tagIds,+ search,+ sort,+ page,+ userId,+ showArchived,+ withTags,+ includeUser,+ });- return NextResponse.json(response, {- headers,- });-});+ return NextResponse.json(response, {+ headers,+ });+ },+);// POST /api/links – create a new linkexport const POST = withWorkspace(diff --git a/apps/web/app/api/tokens/scopes/route.ts b/apps/web/app/api/tokens/scopes/route.tsindex 6d162dfe0c..415c6a1edf 100644--- a/apps/web/app/api/tokens/scopes/route.ts+++ b/apps/web/app/api/tokens/scopes/route.ts@@ -1,4 +1,4 @@-import { scopes } from "@/lib/api/api-keys/scopes";+import { scopes } from "@/lib/api/tokens/scopes";import { withWorkspace } from "@/lib/auth";import { NextResponse } from "next/server";diff --git a/apps/web/lib/api/tokens/permissions.ts b/apps/web/lib/api/tokens/permissions.tsnew file mode 100644index 0000000000..696b9b44fe--- /dev/null+++ b/apps/web/lib/api/tokens/permissions.ts@@ -0,0 +1,17 @@+import { DubApiError } from "../errors";+import { Scope } from "./scopes";++export const throwIfNotAllowed = ({+ scopes,+ requiredScope,+}: {+ scopes: Scope[];+ requiredScope: Scope;+}) => {+ if (!scopes.includes(requiredScope)) {+ throw new DubApiError({+ code: "forbidden",+ message: `You do not have permission to make this action. API key must have the "${requiredScope}" scope.`,+ });+ }+};diff --git a/apps/web/lib/api/api-keys/scopes.ts b/apps/web/lib/api/tokens/scopes.tssimilarity index 93%rename from apps/web/lib/api/api-keys/scopes.tsrename to apps/web/lib/api/tokens/scopes.tsindex 2e0b61c02f..b625168929 100644--- a/apps/web/lib/api/api-keys/scopes.ts+++ b/apps/web/lib/api/tokens/scopes.ts@@ -14,6 +14,8 @@ export const scopes = ["tags.write",] as const;+export type Scope = typeof scopes[number];+// TODO:// Make the structure of the scopes more dynamic so that it can be used in the UIdiff --git a/apps/web/lib/auth/utils.ts b/apps/web/lib/auth/utils.tsindex 4de897b43d..aba4976ff8 100644--- a/apps/web/lib/auth/utils.ts+++ b/apps/web/lib/auth/utils.ts@@ -7,6 +7,7 @@ export interface Session {id: string;name: string;image?: string;+ isMachine: boolean;};}diff --git a/apps/web/lib/auth/workspace.ts b/apps/web/lib/auth/workspace.tsindex a8f1e4c577..772b32acfe 100644--- a/apps/web/lib/auth/workspace.ts+++ b/apps/web/lib/auth/workspace.ts@@ -14,6 +14,7 @@ import {} from "@dub/utils";import { Link as LinkProps } from "@prisma/client";import { waitUntil } from "@vercel/functions";+import { Scope, scopes as allScopes } from "../api/tokens/scopes";import { hashToken } from "./hash-token";import { Session, getSession } from "./utils";@@ -27,6 +28,7 @@ interface WithWorkspaceHandler {workspace,domain,link,+ scopes,}: {req: Request;params: Record<string, string>;@@ -36,6 +38,7 @@ interface WithWorkspaceHandler {workspace: WorkspaceProps;domain: string;link?: LinkProps;+ scopes: Scope[];}): Promise<Response>;}@@ -102,6 +105,7 @@ export const withWorkspace = (let session: Session | undefined;let workspaceId: string | undefined;let workspaceSlug: string | undefined;+ let scopes: Scope[] = [];const idOrSlug =params?.idOrSlug ||@@ -136,23 +140,43 @@ export const withWorkspace = (}if (apiKey) {+ const isRestrictedToken = apiKey.startsWith("dub_");const hashedKey = await hashToken(apiKey);- const user = await prisma.user.findFirst({- where: {- tokens: {- some: {+ const token = isRestrictedToken+ ? await prisma.restrictedToken.findUnique({+ where: {hashedKey,},- },- },- select: {- id: true,- name: true,- email: true,- },- });- if (!user) {+ select: {+ scopes: true,+ user: {+ select: {+ id: true,+ name: true,+ email: true,+ isMachine: true,+ },+ },+ },+ })+ : await prisma.token.findUnique({+ where: {+ hashedKey,+ },+ select: {+ user: {+ select: {+ id: true,+ name: true,+ email: true,+ isMachine: true,+ },+ },+ },+ });++ if (!token || !token.user) {throw new DubApiError({code: "unauthorized",message: "Unauthorized: Invalid API key.",@@ -186,11 +210,16 @@ export const withWorkspace = (},}),);++ // @ts-ignore (TODO: fix TS error)+ scopes = isRestrictedToken ? token.scopes.split("") : allScopes;+session = {user: {- id: user.id,- name: user.name || "",- email: user.email || "",+ id: token.user.id,+ name: token.user.name || "",+ email: token.user.email || "",+ isMachine: token.user.isMachine,},};} else {@@ -426,6 +455,7 @@ export const withWorkspace = (workspace,domain,link,+ scopes,});} catch (error) {return handleAndReturnErrorResponse(error, headers);diff --git a/apps/web/lib/zod/schemas/token.ts b/apps/web/lib/zod/schemas/token.tsindex f561427f08..d6e8fc14a7 100644--- a/apps/web/lib/zod/schemas/token.ts+++ b/apps/web/lib/zod/schemas/token.ts@@ -1,4 +1,4 @@-import { scopes } from "@/lib/api/api-keys/scopes";+import { scopes } from "@/lib/api/tokens/scopes";import z from "@/lib/zod";// Schema to validate the request body when creating a new token