The modern link attribution platform. Loved by world-class engineering teams at Twilio, Zillow, Jobber, Vercel, Raycast, and more.
TypeScript clickhousemysqlnextjsopen-sourceplanetscaleprismatailwindcsstinybirdtypescriptupstashvercel
fix the permission checks
Kiran Kaa0bf39c0f8b
diff --git a/apps/web/app/api/links/route.ts b/apps/web/app/api/links/route.tsindex c3719ec506..842661eecf 100644--- a/apps/web/app/api/links/route.ts+++ b/apps/web/app/api/links/route.ts@@ -1,6 +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 { throwIfNoAccess } from "@/lib/api/tokens/permissions";import { parseRequestBody } from "@/lib/api/utils";import { withWorkspace } from "@/lib/auth";import { ratelimit } from "@/lib/upstash";@@ -14,15 +14,12 @@ import { NextResponse } from "next/server";// GET /api/links – get all links for a workspaceexport const GET = withWorkspace(async ({ req, headers, workspace, scopes }) => {- throwIfNotAllowed({+ throwIfNoAccess({scopes,- requiredScope: "links.read",+ requiredAnyOf: ["links.read", "links.write"],});- console.log("Kiran GET /api/links");-const searchParams = getSearchParamsWithArray(req.url);- console.log(scopes);const {domain,@@ -59,7 +56,12 @@ export const GET = withWorkspace(// POST /api/links – create a new linkexport const POST = withWorkspace(- async ({ req, headers, session, workspace }) => {+ async ({ req, headers, session, workspace, scopes }) => {+ throwIfNoAccess({+ scopes,+ requiredAnyOf: ["links.write"],+ });+const bodyRaw = await parseRequestBody(req);const body = createLinkBodySchema.parse(bodyRaw);diff --git a/apps/web/lib/api/tokens/permissions.ts b/apps/web/lib/api/tokens/permissions.tsindex 696b9b44fe..a1b05f9112 100644--- a/apps/web/lib/api/tokens/permissions.ts+++ b/apps/web/lib/api/tokens/permissions.ts@@ -1,17 +1,25 @@import { DubApiError } from "../errors";import { Scope } from "./scopes";-export const throwIfNotAllowed = ({+export const throwIfNoAccess = ({scopes,- requiredScope,+ requiredAnyOf,}: {scopes: Scope[];- requiredScope: Scope;+ requiredAnyOf: Scope | 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.`,- });+ const requiredScopes = Array.isArray(requiredAnyOf)+ ? requiredAnyOf+ : [requiredAnyOf];++ for (const requiredScope of requiredScopes) {+ if (scopes.includes(requiredScope)) {+ return;+ }}++ throw new DubApiError({+ code: "forbidden",+ message: `You do not have permission to make this action.`,+ });};diff --git a/apps/web/lib/api/tokens/scopes.ts b/apps/web/lib/api/tokens/scopes.tsindex b625168929..20f68f7d74 100644--- a/apps/web/lib/api/tokens/scopes.ts+++ b/apps/web/lib/api/tokens/scopes.ts@@ -1,3 +1,5 @@+import { Role } from "@prisma/client";+export const scopes = [// Workspaces"workspaces.read",@@ -6,34 +8,79 @@ export const scopes = ["links.read","links.write",- // Analytics- "analytics.read",-// Tags"tags.read","tags.write",++ // Analytics+ "analytics.read",] as const;-export type Scope = typeof scopes[number];+export const scopeDescriptions = [+ {+ name: "Workspaces",+ description: "Read workspaces",+ endpoints: ["/workspaces"],+ permissions: [+ {+ scope: "workspaces.read",+ description: "Read workspaces",+ },+ ],+ },+ {+ name: "Links",+ description: "Create, read, update, and delete links",+ endpoints: ["/links"],+ permissions: [+ {+ scope: "links.read",+ description: "Read links",+ },+ {+ scope: "links.write",+ description: "Write links",+ },+ ],+ },+ {+ name: "Tags",+ description: "Create, read, update, and delete tags",+ endpoints: ["/tags"],+ permissions: [+ {+ scope: "tags.read",+ description: "Read tags",+ },+ {+ scope: "tags.write",+ description: "Write tags",+ },+ ],+ },+ {+ name: "Analytics",+ description: "Read analytics",+ endpoints: ["/analytics"],+ permissions: [+ {+ scope: "analytics.read",+ description: "Read analytics",+ },+ ],+ },+] as const;-// TODO:-// Make the structure of the scopes more dynamic so that it can be used in the UI+export const roleToScopes: Record<Role, Scope[]> = {+ owner: [+ "workspaces.read",+ "links.read",+ "links.write",+ "tags.read",+ "tags.write",+ "analytics.read",+ ],+ member: ["workspaces.read", "links.read", "tags.read", "analytics.read"],+} as const;-// export const scopes-// = [-// {-// name: "Links",-// description: "Create, read, update, and delete links",-// endpoints: ["/links"],-// permissions: [-// {-// scope: "links.read",-// description: "Read links",-// },-// {-// scope: "links.write",-// description: "Write links",-// },-// ],-// },-// ] as const;+export type Scope = (typeof scopes)[number];diff --git a/apps/web/lib/auth/workspace.ts b/apps/web/lib/auth/workspace.tsindex 772b32acfe..e139ea20dd 100644--- a/apps/web/lib/auth/workspace.ts+++ b/apps/web/lib/auth/workspace.ts@@ -14,7 +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 { Scope, scopes as allScopes, roleToScopes } from "../api/tokens/scopes";import { hashToken } from "./hash-token";import { Session, getSession } from "./utils";@@ -212,7 +212,7 @@ export const withWorkspace = ();// @ts-ignore (TODO: fix TS error)- scopes = isRestrictedToken ? token.scopes.split("") : allScopes;+ scopes = isRestrictedToken ? token.scopes.split(" ") : allScopes;session = {user: {@@ -294,6 +294,11 @@ export const withWorkspace = (});}+ // For session requests, find the scopes based on the user's role+ if (!apiKey) {+ scopes = roleToScopes[workspace.users[0].role];+ }+// edge case where linkId is an externalId and workspaceId was not provided (they must've used projectSlug instead)// in this case, we need to try fetching the link againif (linkId && linkId.startsWith("ext_") && !link && !workspaceId) {@@ -358,15 +363,15 @@ export const withWorkspace = (}// workspace role checks- if (- !requiredRole.includes(workspace.users[0].role) &&- !(allowSelf && searchParams.userId === session.user.id)- ) {- throw new DubApiError({- code: "forbidden",- message: "Unauthorized: Insufficient permissions.",- });- }+ // if (+ // !requiredRole.includes(workspace.users[0].role) &&+ // !(allowSelf && searchParams.userId === session.user.id)+ // ) {+ // throw new DubApiError({+ // code: "forbidden",+ // message: "Unauthorized: Insufficient permissions.",+ // });+ // }// clicks usage overage checksif (needNotExceededClicks && workspace.usage > workspace.usageLimit) {