The modern link attribution platform. Loved by world-class engineering teams at Twilio, Zillow, Jobber, Vercel, Raycast, and more.
TypeScript clickhousemysqlnextjsopen-sourceplanetscaleprismatailwindcsstinybirdtypescriptupstashvercel
imrove the permission checking and scope handling
Kiran K0a5cd0ce1c0d
diff --git a/apps/web/app/admin.dub.co/revenue/page.tsx b/apps/web/app/admin.dub.co/revenue/page.tsxindex d328787c65..91f1f88f83 100644--- a/apps/web/app/admin.dub.co/revenue/page.tsx+++ b/apps/web/app/admin.dub.co/revenue/page.tsx@@ -11,6 +11,10 @@ export default function Revenue() {}async function RevenueRSC() {+ if (!process.env.PROFITWELL_API_KEY) {+ return null;+ }+const res = await fetch("https://api.profitwell.com/v2/metrics/monthly/?metrics=recurring_revenue",{diff --git a/apps/web/app/api/analytics/events/export/route.ts b/apps/web/app/api/analytics/events/export/route.tsindex e7c04f5ec7..fb1995ec95 100644--- a/apps/web/app/api/analytics/events/export/route.ts+++ b/apps/web/app/api/analytics/events/export/route.ts@@ -96,6 +96,6 @@ export const GET = withWorkspace(});},{- requiredScopes: ["analytics.read"],+ requiredPermissions: ["analytics.read"],},);diff --git a/apps/web/app/api/analytics/events/route.ts b/apps/web/app/api/analytics/events/route.tsindex 803aa249d6..e88fb72cdc 100644--- a/apps/web/app/api/analytics/events/route.ts+++ b/apps/web/app/api/analytics/events/route.ts@@ -51,6 +51,6 @@ export const GET = withWorkspace(},{betaFeature: true,- requiredScopes: ["analytics.read"],+ requiredPermissions: ["analytics.read"],},);diff --git a/apps/web/app/api/analytics/export/route.ts b/apps/web/app/api/analytics/export/route.tsindex 547f31da50..23945da714 100644--- a/apps/web/app/api/analytics/export/route.ts+++ b/apps/web/app/api/analytics/export/route.ts@@ -68,6 +68,6 @@ export const GET = withWorkspace(});},{- requiredScopes: ["analytics.read"],+ requiredPermissions: ["analytics.read"],},);diff --git a/apps/web/app/api/analytics/public-stats/route.ts b/apps/web/app/api/analytics/public-stats/route.tsindex e93be7ce4e..ab77b65e85 100644--- a/apps/web/app/api/analytics/public-stats/route.ts+++ b/apps/web/app/api/analytics/public-stats/route.ts@@ -25,7 +25,7 @@ export const GET = withWorkspace(return NextResponse.json({ publicStats: response?.publicStats });},{- requiredScopes: ["links.read"],+ requiredPermissions: ["links.read"],},);@@ -49,6 +49,6 @@ export const PUT = withWorkspace(return NextResponse.json(response);},{- requiredScopes: ["links.write"],+ requiredPermissions: ["links.write"],},);diff --git a/apps/web/app/api/analytics/route.ts b/apps/web/app/api/analytics/route.tsindex 0bc92cf80a..1f0ee4bd8d 100644--- a/apps/web/app/api/analytics/route.ts+++ b/apps/web/app/api/analytics/route.ts@@ -86,6 +86,6 @@ export const GET = withWorkspace(return NextResponse.json(response);},{- requiredScopes: ["analytics.read"],+ requiredPermissions: ["analytics.read"],},);diff --git a/apps/web/app/api/domains/[domain]/primary/route.ts b/apps/web/app/api/domains/[domain]/primary/route.tsindex 48d358d227..f9902c27f6 100644--- a/apps/web/app/api/domains/[domain]/primary/route.ts+++ b/apps/web/app/api/domains/[domain]/primary/route.ts@@ -41,6 +41,6 @@ export const POST = withWorkspace(return NextResponse.json(DomainSchema.parse(domainRecord), { headers });},{- requiredScopes: ["domains.write"],+ requiredPermissions: ["domains.write"],},);diff --git a/apps/web/app/api/domains/[domain]/route.ts b/apps/web/app/api/domains/[domain]/route.tsindex 1ed1dbdb66..bdb06b379e 100644--- a/apps/web/app/api/domains/[domain]/route.ts+++ b/apps/web/app/api/domains/[domain]/route.ts@@ -30,7 +30,7 @@ export const GET = withWorkspace(return NextResponse.json(DomainSchema.parse(domainRecord));},{- requiredScopes: ["domains.read"],+ requiredPermissions: ["domains.read"],},);@@ -130,7 +130,7 @@ export const PATCH = withWorkspace(return NextResponse.json(DomainSchema.parse(domainRecord));},{- requiredScopes: ["domains.write"],+ requiredPermissions: ["domains.write"],},);@@ -148,6 +148,6 @@ export const DELETE = withWorkspace(return NextResponse.json({ slug: domain });},{- requiredScopes: ["domains.write"],+ requiredPermissions: ["domains.write"],},);diff --git a/apps/web/app/api/domains/[domain]/transfer/route.ts b/apps/web/app/api/domains/[domain]/transfer/route.tsindex 2875a75787..b7e4a64908 100644--- a/apps/web/app/api/domains/[domain]/transfer/route.ts+++ b/apps/web/app/api/domains/[domain]/transfer/route.ts@@ -139,6 +139,6 @@ export const POST = withWorkspace(return NextResponse.json(DomainSchema.parse(domainResponse), { headers });},{- requiredScopes: ["domains.write"],+ requiredPermissions: ["domains.write"],},);diff --git a/apps/web/app/api/domains/[domain]/verify/route.ts b/apps/web/app/api/domains/[domain]/verify/route.tsindex df03c31ce6..a526b465ff 100644--- a/apps/web/app/api/domains/[domain]/verify/route.ts+++ b/apps/web/app/api/domains/[domain]/verify/route.ts@@ -103,6 +103,6 @@ export const GET = withWorkspace(});},{- requiredScopes: ["domains.write"],+ requiredPermissions: ["domains.write"],},);diff --git a/apps/web/app/api/domains/default/route.ts b/apps/web/app/api/domains/default/route.tsindex 6eb0fd9577..ef0ca59edc 100644--- a/apps/web/app/api/domains/default/route.ts+++ b/apps/web/app/api/domains/default/route.ts@@ -34,7 +34,7 @@ export const GET = withWorkspace(return NextResponse.json(defaultDomainsArray);},{- requiredScopes: ["domains.read"],+ requiredPermissions: ["domains.read"],},);@@ -66,6 +66,6 @@ export const PUT = withWorkspace(return NextResponse.json(response);},{- requiredScopes: ["domains.write"],+ requiredPermissions: ["domains.write"],},);diff --git a/apps/web/app/api/domains/route.ts b/apps/web/app/api/domains/route.tsindex 0643a1b1b1..2655f3bd56 100644--- a/apps/web/app/api/domains/route.ts+++ b/apps/web/app/api/domains/route.ts@@ -33,7 +33,7 @@ export const GET = withWorkspace(return NextResponse.json(z.array(DomainSchema).parse(domains));},{- requiredScopes: ["domains.read"],+ requiredPermissions: ["domains.read"],},);@@ -104,6 +104,6 @@ export const POST = withWorkspace(});},{- requiredScopes: ["domains.write"],+ requiredPermissions: ["domains.write"],},);diff --git a/apps/web/app/api/links/[linkId]/route.ts b/apps/web/app/api/links/[linkId]/route.tsindex f7efe8d6f5..86854d1b55 100644--- a/apps/web/app/api/links/[linkId]/route.ts+++ b/apps/web/app/api/links/[linkId]/route.ts@@ -47,7 +47,7 @@ export const GET = withWorkspace(return NextResponse.json(response, { headers });},{- requiredScopes: ["links.read"],+ requiredPermissions: ["links.read"],},);@@ -136,7 +136,7 @@ export const PATCH = withWorkspace(}},{- requiredScopes: ["links.write"],+ requiredPermissions: ["links.write"],},);@@ -156,6 +156,6 @@ export const DELETE = withWorkspace(return NextResponse.json({ id: link.id }, { headers });},{- requiredScopes: ["links.write"],+ requiredPermissions: ["links.write"],},);diff --git a/apps/web/app/api/links/[linkId]/transfer/route.ts b/apps/web/app/api/links/[linkId]/transfer/route.tsindex 071432f4e5..6108e00a50 100644--- a/apps/web/app/api/links/[linkId]/transfer/route.ts+++ b/apps/web/app/api/links/[linkId]/transfer/route.ts@@ -130,6 +130,6 @@ export const POST = withWorkspace(});},{- requiredScopes: ["links.write"],+ requiredPermissions: ["links.write"],},);diff --git a/apps/web/app/api/links/bulk/route.ts b/apps/web/app/api/links/bulk/route.tsindex 0f42e11936..4c3bacacac 100644--- a/apps/web/app/api/links/bulk/route.ts+++ b/apps/web/app/api/links/bulk/route.ts@@ -132,7 +132,7 @@ export const POST = withWorkspace(});},{- requiredScopes: ["links.write"],+ requiredPermissions: ["links.write"],},);diff --git a/apps/web/app/api/links/count/route.ts b/apps/web/app/api/links/count/route.tsindex 57ce201558..0cbc9c4222 100644--- a/apps/web/app/api/links/count/route.ts+++ b/apps/web/app/api/links/count/route.ts@@ -25,6 +25,6 @@ export const GET = withWorkspace(});},{- requiredScopes: ["links.read"],+ requiredPermissions: ["links.read"],},);diff --git a/apps/web/app/api/links/info/route.ts b/apps/web/app/api/links/info/route.tsindex 7c591ed523..c3df9bb5d3 100644--- a/apps/web/app/api/links/info/route.ts+++ b/apps/web/app/api/links/info/route.ts@@ -56,6 +56,6 @@ export const GET = withWorkspace(});},{- requiredScopes: ["links.read"],+ requiredPermissions: ["links.read"],},);diff --git a/apps/web/app/api/links/route.ts b/apps/web/app/api/links/route.tsindex acb2efcb6c..b64430c4be 100644--- a/apps/web/app/api/links/route.ts+++ b/apps/web/app/api/links/route.ts@@ -53,7 +53,7 @@ export const GET = withWorkspace(});},{- requiredScopes: ["links.read"],+ requiredPermissions: ["links.read"],},);@@ -111,6 +111,6 @@ export const POST = withWorkspace(},{allowAnonymous: true,- requiredScopes: ["links.write"],+ requiredPermissions: ["links.write"],},);diff --git a/apps/web/app/api/links/sync/route.ts b/apps/web/app/api/links/sync/route.tsindex 074c040247..780eb5bec1 100644--- a/apps/web/app/api/links/sync/route.ts+++ b/apps/web/app/api/links/sync/route.ts@@ -81,6 +81,6 @@ export const POST = withWorkspace(return NextResponse.json(response);},{- requiredScopes: ["links.write"],+ requiredPermissions: ["links.write"],},);diff --git a/apps/web/app/api/links/upsert/route.ts b/apps/web/app/api/links/upsert/route.tsindex 4f9861e98a..8363f6486c 100644--- a/apps/web/app/api/links/upsert/route.ts+++ b/apps/web/app/api/links/upsert/route.ts@@ -152,6 +152,6 @@ export const PUT = withWorkspace(}},{- requiredScopes: ["links.write"],+ requiredPermissions: ["links.write"],},);diff --git a/apps/web/app/api/tags/[id]/route.ts b/apps/web/app/api/tags/[id]/route.tsindex 3c0d817803..82de6659ca 100644--- a/apps/web/app/api/tags/[id]/route.ts+++ b/apps/web/app/api/tags/[id]/route.ts@@ -49,7 +49,7 @@ export const PATCH = withWorkspace(}},{- requiredScopes: ["tags.write"],+ requiredPermissions: ["tags.write"],},);@@ -115,6 +115,6 @@ export const DELETE = withWorkspace(}},{- requiredScopes: ["tags.write"],+ requiredPermissions: ["tags.write"],},);diff --git a/apps/web/app/api/tags/route.ts b/apps/web/app/api/tags/route.tsindex 534492faf3..c012d5a9ef 100644--- a/apps/web/app/api/tags/route.ts+++ b/apps/web/app/api/tags/route.ts@@ -25,7 +25,7 @@ export const GET = withWorkspace(return NextResponse.json(tags, { headers });},{- requiredScopes: ["tags.read"],+ requiredPermissions: ["tags.read"],},);@@ -82,6 +82,6 @@ export const POST = withWorkspace(});},{- requiredScopes: ["tags.write"],+ requiredPermissions: ["tags.write"],},);diff --git a/apps/web/app/api/tokens/[id]/route.ts b/apps/web/app/api/tokens/[id]/route.tsindex 49bd13d970..d48f513d4c 100644--- a/apps/web/app/api/tokens/[id]/route.ts+++ b/apps/web/app/api/tokens/[id]/route.ts@@ -43,7 +43,7 @@ export const GET = withWorkspace(return NextResponse.json(tokenSchema.parse(token));},{- requiredScopes: ["tokens.read"],+ requiredPermissions: ["tokens.read"],},);@@ -106,7 +106,7 @@ export const PATCH = withWorkspace(return NextResponse.json(tokenSchema.parse(token));},{- requiredScopes: ["tokens.write"],+ requiredPermissions: ["tokens.write"],},);@@ -142,6 +142,6 @@ export const DELETE = withWorkspace(});},{- requiredScopes: ["tokens.write"],+ requiredPermissions: ["tokens.write"],},);diff --git a/apps/web/app/api/tokens/route.ts b/apps/web/app/api/tokens/route.tsindex 7f62662c40..76a06534c6 100644--- a/apps/web/app/api/tokens/route.ts+++ b/apps/web/app/api/tokens/route.ts@@ -43,6 +43,7 @@ export const POST = withWorkspace(// Check given scopes are valid based on user's roleconst userScopes = getScopesByRole(role);+if (scopes && scopes.every((scope) => !userScopes.includes(scope))) {throw new DubApiError({code: "unprocessable_entity",@@ -111,7 +112,7 @@ export const POST = withWorkspace(return NextResponse.json({ token });},{- requiredScopes: ["tokens.write"],+ requiredPermissions: ["tokens.write"],},);@@ -145,6 +146,6 @@ export const GET = withWorkspace(return NextResponse.json(tokenSchema.array().parse(tokens));},{- requiredScopes: ["tokens.read"],+ requiredPermissions: ["tokens.read"],},);diff --git a/apps/web/app/api/track/customer/route.ts b/apps/web/app/api/track/customer/route.tsindex d29c80feab..6c9cfb503b 100644--- a/apps/web/app/api/track/customer/route.ts+++ b/apps/web/app/api/track/customer/route.ts@@ -65,6 +65,6 @@ export const POST = withWorkspaceEdge(},{betaFeature: true,- requiredScopes: ["conversions.write"],+ requiredPermissions: ["conversions.write"],},);diff --git a/apps/web/app/api/track/lead/route.ts b/apps/web/app/api/track/lead/route.tsindex 2e314ab411..06d12a59dd 100644--- a/apps/web/app/api/track/lead/route.ts+++ b/apps/web/app/api/track/lead/route.ts@@ -128,6 +128,6 @@ export const POST = withWorkspaceEdge(},{betaFeature: true,- requiredScopes: ["conversions.write"],+ requiredPermissions: ["conversions.write"],},);diff --git a/apps/web/app/api/track/sale/route.ts b/apps/web/app/api/track/sale/route.tsindex 52586c245a..3c12d1fed3 100644--- a/apps/web/app/api/track/sale/route.ts+++ b/apps/web/app/api/track/sale/route.ts@@ -96,6 +96,6 @@ export const POST = withWorkspaceEdge(},{betaFeature: true,- requiredScopes: ["conversions.write"],+ requiredPermissions: ["conversions.write"],},);diff --git a/apps/web/app/api/workspaces/[idOrSlug]/invites/reset/route.ts b/apps/web/app/api/workspaces/[idOrSlug]/invites/reset/route.tsindex e4cabf6d18..e45b813efd 100644--- a/apps/web/app/api/workspaces/[idOrSlug]/invites/reset/route.ts+++ b/apps/web/app/api/workspaces/[idOrSlug]/invites/reset/route.ts@@ -17,6 +17,6 @@ export const POST = withWorkspace(return NextResponse.json(response);},{- requiredScopes: ["workspaces.write"],+ requiredPermissions: ["workspaces.write"],},);diff --git a/apps/web/app/api/workspaces/[idOrSlug]/invites/route.tsx b/apps/web/app/api/workspaces/[idOrSlug]/invites/route.tsxindex f7826b0d2b..c6c3e9b148 100644--- a/apps/web/app/api/workspaces/[idOrSlug]/invites/route.tsx+++ b/apps/web/app/api/workspaces/[idOrSlug]/invites/route.tsx@@ -24,7 +24,7 @@ export const GET = withWorkspace(return NextResponse.json(invites);},{- requiredScopes: ["workspaces.read"],+ requiredPermissions: ["workspaces.read"],},);@@ -85,7 +85,7 @@ export const POST = withWorkspace(return NextResponse.json({ message: "Invite sent" });},{- requiredScopes: ["workspaces.write"],+ requiredPermissions: ["workspaces.write"],},);@@ -104,6 +104,6 @@ export const DELETE = withWorkspace(return NextResponse.json(response);},{- requiredScopes: ["workspaces.write"],+ requiredPermissions: ["workspaces.write"],},);diff --git a/apps/web/app/api/workspaces/[idOrSlug]/logo/route.ts b/apps/web/app/api/workspaces/[idOrSlug]/logo/route.tsindex a252ec13fe..8bdba1388e 100644--- a/apps/web/app/api/workspaces/[idOrSlug]/logo/route.ts+++ b/apps/web/app/api/workspaces/[idOrSlug]/logo/route.ts@@ -23,6 +23,6 @@ export const POST = withWorkspace(return NextResponse.json(response);},{- requiredScopes: ["workspaces.write"],+ requiredPermissions: ["workspaces.write"],},);diff --git a/apps/web/app/api/workspaces/[idOrSlug]/route.ts b/apps/web/app/api/workspaces/[idOrSlug]/route.tsindex 19f6525664..69d6a881cb 100644--- a/apps/web/app/api/workspaces/[idOrSlug]/route.ts+++ b/apps/web/app/api/workspaces/[idOrSlug]/route.ts@@ -34,7 +34,7 @@ export const GET = withWorkspace();},{- requiredScopes: ["workspaces.read"],+ requiredPermissions: ["workspaces.read"],},);@@ -92,7 +92,7 @@ export const PATCH = withWorkspace(}},{- requiredScopes: ["workspaces.write"],+ requiredPermissions: ["workspaces.write"],},);@@ -106,6 +106,6 @@ export const DELETE = withWorkspace(return NextResponse.json(workspace);},{- requiredScopes: ["workspaces.write"],+ requiredPermissions: ["workspaces.write"],},);diff --git a/apps/web/app/api/workspaces/[idOrSlug]/saml/route.ts b/apps/web/app/api/workspaces/[idOrSlug]/saml/route.tsindex a799bc51fd..84ff4a9763 100644--- a/apps/web/app/api/workspaces/[idOrSlug]/saml/route.ts+++ b/apps/web/app/api/workspaces/[idOrSlug]/saml/route.ts@@ -45,7 +45,7 @@ export const GET = withWorkspace(return NextResponse.json(response);},{- requiredScopes: ["workspaces.read"],+ requiredPermissions: ["workspaces.read"],},);@@ -69,7 +69,7 @@ export const POST = withWorkspace(return NextResponse.json(data);},{- requiredScopes: ["workspaces.write"],+ requiredPermissions: ["workspaces.write"],requiredPlan: ["enterprise"],},);@@ -90,6 +90,6 @@ export const DELETE = withWorkspace(return NextResponse.json({ response: "removed SAML connection" });},{- requiredScopes: ["workspaces.write"],+ requiredPermissions: ["workspaces.write"],},);diff --git a/apps/web/app/api/workspaces/[idOrSlug]/scim/route.ts b/apps/web/app/api/workspaces/[idOrSlug]/scim/route.tsindex e44ae37ad5..f95ddae128 100644--- a/apps/web/app/api/workspaces/[idOrSlug]/scim/route.ts+++ b/apps/web/app/api/workspaces/[idOrSlug]/scim/route.ts@@ -35,7 +35,7 @@ export const GET = withWorkspace(});},{- requiredScopes: ["workspaces.read"],+ requiredPermissions: ["workspaces.read"],},);@@ -61,7 +61,7 @@ export const POST = withWorkspace(return NextResponse.json(data);},{- requiredScopes: ["workspaces.write"],+ requiredPermissions: ["workspaces.write"],requiredPlan: ["enterprise"],},);@@ -86,6 +86,6 @@ export const DELETE = withWorkspace(return NextResponse.json(data);},{- requiredScopes: ["workspaces.write"],+ requiredPermissions: ["workspaces.write"],},);diff --git a/apps/web/app/api/workspaces/[idOrSlug]/users/route.ts b/apps/web/app/api/workspaces/[idOrSlug]/users/route.tsindex f5f3ccf966..b70d61ae0b 100644--- a/apps/web/app/api/workspaces/[idOrSlug]/users/route.ts+++ b/apps/web/app/api/workspaces/[idOrSlug]/users/route.ts@@ -48,7 +48,7 @@ export const GET = withWorkspace();},{- requiredScopes: ["workspaces.read"],+ requiredPermissions: ["workspaces.read"],},);@@ -73,19 +73,19 @@ export const PUT = withWorkspace(return NextResponse.json(response);},{- requiredScopes: ["workspaces.write"],+ requiredPermissions: ["workspaces.write"],},);// DELETE /api/workspaces/[idOrSlug]/users – remove a user from a workspace or leave a workspaceexport const DELETE = withWorkspace(- async ({ searchParams, workspace, session, scopes }) => {+ async ({ searchParams, workspace, session, permissions }) => {const { userId } = removeUserSchema.parse(searchParams);if (userId !== session.user.id) {throwIfNoAccess({- scopes,- requiredScopes: ["workspaces.write"],+ permissions,+ requiredPermissions: ["workspaces.write"],workspaceId: workspace.id,});}@@ -167,6 +167,6 @@ export const DELETE = withWorkspace(return NextResponse.json(response);},{- skipScopeChecks: true,+ skipPermissionChecks: true,},);diff --git a/apps/web/lib/api/tokens/permissions.ts b/apps/web/lib/api/tokens/permissions.tsindex 5536437628..6a6db7f01c 100644--- a/apps/web/lib/api/tokens/permissions.ts+++ b/apps/web/lib/api/tokens/permissions.ts@@ -1,30 +1,30 @@import { DubApiError } from "../errors";-import { Scope } from "./scopes";+import { PermissionAction } from "./scopes";// Check if the required scope is in the list of user scopesexport const throwIfNoAccess = ({- scopes,- requiredScopes,+ permissions,+ requiredPermissions,workspaceId,}: {- scopes: Scope[];- requiredScopes: Scope[];+ permissions: PermissionAction[]; // user or token permissions+ requiredPermissions: PermissionAction[];workspaceId: string;}) => {- if (requiredScopes.length === 0) {+ if (requiredPermissions.length === 0) {return;}- const missingScopes = requiredScopes- .filter((requiredScope) => !scopes.includes(requiredScope))- .join(", ");+ const missingPermissions = requiredPermissions.filter(+ (p) => !permissions.includes(p),+ );- for (const requiredScope of requiredScopes) {- if (!scopes.includes(requiredScope)) {- throw new DubApiError({- code: "forbidden",- message: `The provided key does not have the required permissions for this endpoint on the workspace 'ws_${workspaceId}'. Having the '${missingScopes}' permission would allow this request to continue.`,- });- }+ if (missingPermissions.length === 0) {+ return;}++ throw new DubApiError({+ code: "forbidden",+ message: `The provided key does not have the required permissions for this endpoint on the workspace 'ws_${workspaceId}'. Having the '${missingPermissions.join(" ")}' permission would allow this request to continue.`,+ });};diff --git a/apps/web/lib/api/tokens/scopes.ts b/apps/web/lib/api/tokens/scopes.tsindex a88a69217c..f5f94d494a 100644--- a/apps/web/lib/api/tokens/scopes.ts+++ b/apps/web/lib/api/tokens/scopes.ts@@ -1,6 +1,6 @@import { Role } from "@prisma/client";-export const availableScopes = [+export const SCOPES = ["workspaces.read","workspaces.write","links.read",@@ -17,184 +17,312 @@ export const availableScopes = ["apis.read", // All read scopes] as const;-export type Scope = (typeof availableScopes)[number];+export const PERMISSION_ACTIONS = [+ "workspaces.read",+ "workspaces.write",+ "links.read",+ "links.write",+ "tags.read",+ "tags.write",+ "analytics.read",+ "domains.read",+ "domains.write",+ "tokens.read",+ "tokens.write",+ "conversions.write",+] as const;-export const resourcePermissions = [+export const RESOURCES: Resource[] = [{name: "Links",key: "links",description: "Create, read, update, and delete links",betaFeature: false,- permissions: [- {- permission: "Read",- scope: "links.read",- description: "Read links",- roles: ["owner", "member"],- },- {- permission: "Write",- scope: "links.write",- description: "Update and delete links",- roles: ["owner", "member"],- },- ],},{name: "Analytics",key: "analytics",description: "Read analytics",betaFeature: false,- permissions: [- {- permission: "Read",- scope: "analytics.read",- description: "Read analytics and events",- roles: ["owner", "member"],- },- ],},{name: "Workspaces",key: "workspaces",description: "Read, update, and delete workspaces",betaFeature: false,- permissions: [- {- permission: "Read",- scope: "workspaces.read",- description: "Read workspaces",- roles: ["owner", "member"],- },- {- permission: "Write",- scope: "workspaces.write",- description: "Update and delete workspaces",- roles: ["owner"],- },- ],},{name: "Domains",key: "domains",description: "Create, read, update, and delete domains",betaFeature: false,- permissions: [- {- permission: "Read",- scope: "domains.read",- description: "Read domains",- roles: ["owner", "member"],- },- {- permission: "Write",- scope: "domains.write",- description: "Update and delete domains",- roles: ["owner"],- },- ],},{name: "Tags",key: "tags",description: "Create, read, update, and delete tags",betaFeature: false,- permissions: [- {- permission: "Read",- scope: "tags.read",- description: "Read tags",- roles: ["owner", "member"],- },- {- permission: "Write",- scope: "tags.write",- description: "Update and delete tags",- roles: ["owner", "member"],- },- ],},{name: "API Keys",key: "tokens",description: "Create, read, update, and delete API keys",betaFeature: false,- permissions: [- {- permission: "Read",- scope: "tokens.read",- description: "Read tokens",- roles: ["owner", "member"],- },- {- permission: "Write",- scope: "tokens.write",- description: "Update and delete tokens",- roles: ["owner", "member"],- },- ],},{name: "Conversions",key: "conversions",description: "Track conversions (customer, lead, sales)",betaFeature: true,- permissions: [- {- permission: "Write",- scope: "conversions.write",- description: "Track customer, lead, and sales events",- roles: ["owner"],- },- ],},];-// Get scopes by role-export const getScopesByRole = (role: Role) => {- const scopes: string[] = ["apis.read", "apis.all"];-- resourcePermissions.forEach((resource) => {- resource.permissions.forEach((permission) => {- if (permission.roles.includes(role)) {- scopes.push(permission.scope);- }- });- });-- return scopes as Scope[];+export const SCOPES_BY_RESOURCE: ScopeByResource = {+ links: [+ {+ type: "read",+ scope: "links.read",+ description: "Read access to links",+ },+ {+ type: "write",+ scope: "links.write",+ description: "Read and Write access to links",+ },+ ],+ analytics: [+ {+ type: "read",+ scope: "analytics.read",+ description: "Read access to analytics and events",+ },+ ],+ workspaces: [+ {+ type: "read",+ scope: "workspaces.read",+ description: "Read access to workspace",+ },+ {+ type: "write",+ scope: "workspaces.write",+ description: "Read and Write access to workspace",+ },+ ],+ domains: [+ {+ type: "read",+ scope: "domains.read",+ description: "Read access to domains",+ },+ {+ type: "write",+ scope: "domains.write",+ description: "Read and Write access to domains",+ },+ ],+ tags: [+ {+ type: "read",+ scope: "tags.read",+ description: "Read access to tags",+ },+ {+ type: "write",+ scope: "tags.write",+ description: "Read and Write access to tags",+ },+ ],+ tokens: [+ {+ type: "read",+ scope: "tokens.read",+ description: "Read access to Workspace API keys",+ },+ {+ type: "write",+ scope: "tokens.write",+ description: "Read and Write access to Workspace API keys",+ },+ ],+ conversions: [+ {+ type: "write",+ scope: "conversions.write",+ description:+ "Read and Write access to conversions. Able to track customer, lead, and sales events",+ },+ ],};-// Get resource permissions by role-export const getResourcePermissionsByRole = (role: Role) => {- return resourcePermissions- .map((resource) => {- const filteredPermissions = resource.permissions.filter((permission) =>- permission.roles.includes(role),+export const PERMISSIONS: Permission[] = [+ {+ action: "links.read",+ scope: "links.read",+ roles: ["owner", "member"],+ resource: "links",+ betaFeature: false,+ },+ {+ action: "links.write",+ scope: "links.write",+ roles: ["owner", "member"],+ resource: "links",+ betaFeature: false,+ },+ {+ action: "analytics.read",+ scope: "analytics.read",+ roles: ["owner", "member"],+ resource: "analytics",+ betaFeature: false,+ },+ {+ action: "workspaces.read",+ scope: "workspaces.read",+ roles: ["owner", "member"],+ resource: "workspaces",+ betaFeature: false,+ },+ {+ action: "workspaces.write",+ scope: "workspaces.write",+ roles: ["owner"],+ resource: "workspaces",+ betaFeature: false,+ },+ {+ action: "domains.read",+ scope: "domains.read",+ roles: ["owner", "member"],+ resource: "domains",+ betaFeature: false,+ },+ {+ action: "domains.write",+ scope: "domains.write",+ roles: ["owner"],+ resource: "domains",+ betaFeature: false,+ },+ {+ action: "tags.read",+ scope: "tags.read",+ roles: ["owner", "member"],+ resource: "tags",+ betaFeature: false,+ },+ {+ action: "tags.write",+ scope: "tags.write",+ roles: ["owner", "member"],+ resource: "tags",+ betaFeature: false,+ },+ {+ action: "tokens.read",+ scope: "tokens.read",+ roles: ["owner", "member"],+ resource: "tokens",+ betaFeature: false,+ },+ {+ action: "tokens.write",+ scope: "tokens.write",+ roles: ["owner", "member"],+ resource: "tokens",+ betaFeature: false,+ },+ {+ action: "conversions.write",+ scope: "conversions.write",+ roles: ["owner"],+ resource: "conversions",+ betaFeature: true,+ },+];++// For each scope, get the permissions it grants access to and return array of permissions+export const mapScopesToPermissions = (scopes: Scope[]) => {+ const permissions: PermissionAction[] = [];++ scopes.forEach((scope) => {+ if (scope === "apis.all") {+ // Add all individual scopes to permissions+ permissions.push(+ ...SCOPES.filter((s) => s !== "apis.all" && s !== "apis.read").flatMap(+ (s) => PERMISSIONS.filter((p) => p.scope === s).map((p) => p.action),+ ),+ );+ } else if (scope === "apis.read") {+ // Add all read scopes to permissions+ permissions.push(+ ...SCOPES.filter((s) => s.endsWith(".read")).flatMap((s) =>+ PERMISSIONS.filter((p) => p.scope === s).map((p) => p.action),+ ),+ );+ } else {+ // Add the scope as is+ permissions.push(+ ...PERMISSIONS.filter((permission) => permission.scope === scope).map(+ (permission) => permission.action,+ ),);+ }+ });- return {- ...resource,- permissions: filteredPermissions,- };- })- .filter((resource) => resource.permissions.length > 0);+ return permissions;};-// Expand the scopes to include all the required scopes-export const normalizeScopes = (scopes: string[]): Scope[] => {- return (scopes || [])- .map((scope: Scope) => scopeMapping[scope] || scope)- .flat();+// Get permissions by roles+export const getPermissionsByRole = (role: Role) => {+ return PERMISSIONS.filter((permission) =>+ permission.roles.includes(role),+ ).map((permission) => permission.action);};-export const scopeMapping = {- "apis.all": availableScopes,- "apis.read": availableScopes.filter((scope) => scope.endsWith(".read")),- "workspaces.write": ["workspaces.write", "workspaces.read"],- "links.write": ["links.write", "links.read"],- "tags.write": ["tags.write", "tags.read"],- "domains.write": ["domains.write", "domains.read"],+// Get SCOPES_BY_RESOURCE based on user role in a workspace+export const getScopesByResourceForRole = (role: Role) => {+ const allowedResources: string[] = [];++ // Filter permissions by the role+ const allowedPermissions = PERMISSIONS.filter((permission) =>+ permission.roles.includes(role),+ );++ // Get resources allowed by permissions+ allowedPermissions.forEach((permission) => {+ if (!allowedResources.includes(permission.resource)) {+ allowedResources.push(permission.resource);+ }+ });++ // Filter SCOPES_BY_RESOURCE based on allowed resources and scopes+ // @ts-ignore+ const scopedResources: ScopeByResource = {};+ allowedResources.forEach((resource) => {+ scopedResources[resource] = SCOPES_BY_RESOURCE[resource].filter((scope) =>+ allowedPermissions.some(+ (permission) =>+ permission.scope === scope.scope && permission.resource === resource,+ ),+ );+ });++ return scopedResources;+};++// Get scopes by role+export const getScopesByRole = (role: Role) => {+ const permissions = getPermissionsByRole(role);++ const scopes = PERMISSIONS.filter((p) => permissions.includes(p.action)).map(+ (permission) => permission.scope,+ );++ scopes.push("apis.read", "apis.all");++ return scopes;};export const scopePresets = [@@ -222,14 +350,52 @@ 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",};};++export type Scope = (typeof SCOPES)[number];++export type PermissionAction = (typeof PERMISSION_ACTIONS)[number];++type ResourceKeys =+ | "links"+ | "workspaces"+ | "analytics"+ | "domains"+ | "tags"+ | "tokens"+ | "conversions";++type Resource = {+ name: string;+ key: ResourceKeys;+ description: string;+ betaFeature: boolean;+};++type Permission = {+ action: PermissionAction;+ scope: Scope;+ roles: Role[];+ resource: ResourceKeys;+ betaFeature: boolean;+};++export type ScopeByResource = {+ [key in ResourceKeys]: {+ scope: Scope;+ type: "read" | "write";+ description: string;+ }[];+};diff --git a/apps/web/lib/auth/workspace-edge.ts b/apps/web/lib/auth/workspace-edge.tsindex 647510ff9f..654104fee3 100644--- a/apps/web/lib/auth/workspace-edge.ts+++ b/apps/web/lib/auth/workspace-edge.ts@@ -11,7 +11,11 @@ import { StreamingTextResponse } from "ai";import { getToken } from "next-auth/jwt";import { NextRequest } from "next/server";import { throwIfNoAccess } from "../api/tokens/permissions";-import { Scope, getScopesByRole, normalizeScopes } from "../api/tokens/scopes";+import {+ PermissionAction,+ getPermissionsByRole,+ mapScopesToPermissions,+} from "../api/tokens/scopes";import { isBetaTester } from "../edge-config";import { prismaEdge } from "../prisma/edge";import { hashToken } from "./hash-token";@@ -25,7 +29,7 @@ interface WithWorkspaceEdgeHandler {headers,session,workspace,- scopes,+ permissions,}: {req: Request;params: Record<string, string>;@@ -33,7 +37,7 @@ interface WithWorkspaceEdgeHandler {headers?: Record<string, string>;session: Session;workspace: WorkspaceProps;- scopes: Scope[];+ permissions: PermissionAction[];}): Promise<Response | StreamingTextResponse>;}@@ -53,14 +57,14 @@ export const withWorkspaceEdge = (needNotExceededLinks, // if the action needs the user to not have exceeded their links usageneedNotExceededAI, // if the action needs the user to not have exceeded their AI usagebetaFeature, // if the action is a beta feature- requiredScopes = [],+ requiredPermissions = [],}: {requiredPlan?: Array<PlanProps>;needNotExceededClicks?: boolean;needNotExceededLinks?: boolean;needNotExceededAI?: boolean;betaFeature?: boolean;- requiredScopes?: Scope[];+ requiredPermissions?: PermissionAction[];} = {},) => {return async (@@ -88,7 +92,7 @@ export const withWorkspaceEdge = (let session: Session | undefined;let workspaceId: string | undefined;let workspaceSlug: string | undefined;- let scopes: Scope[] = [];+ let permissions: PermissionAction[] = [];let token: any | null = null;const isRestrictedToken = apiKey?.startsWith("dub_");@@ -252,25 +256,22 @@ export const withWorkspaceEdge = (});}- // Find the subset of permissions that the user has access to based on their role- // Only owner can create machine users now- const userScopes = getScopesByRole(- session.user.isMachine ? "owner" : workspace.users[0].role,- );+ // By default, the user has access to all permissions based on their role+ permissions = getPermissionsByRole(workspace.users[0].role);+ // Find the subset of permissions that the user has access to based on the token scopesif (isRestrictedToken) {- const tokenScopes = (token.scopes.split(" ") || []) as Scope[];- scopes = normalizeScopes(tokenScopes).filter((scope) =>- userScopes.includes(scope),+ const tokenScopes = token.scopes.split(" ") || [];++ mapScopesToPermissions(tokenScopes).filter((permission) =>+ permissions.includes(permission),);- } else {- scopes = userScopes;}// Check user has permission to make the actionthrowIfNoAccess({- scopes,- requiredScopes,+ permissions,+ requiredPermissions,workspaceId: workspace.id,});@@ -384,7 +385,7 @@ export const withWorkspaceEdge = (headers,session,workspace,- scopes,+ permissions,});} catch (error) {return handleAndReturnErrorResponse(error, headers);diff --git a/apps/web/lib/auth/workspace.ts b/apps/web/lib/auth/workspace.tsindex 14536c8d35..7a3210858b 100644--- a/apps/web/lib/auth/workspace.ts+++ b/apps/web/lib/auth/workspace.ts@@ -5,7 +5,11 @@ import { ratelimit } from "@/lib/upstash";import { API_DOMAIN, getSearchParams } from "@dub/utils";import { waitUntil } from "@vercel/functions";import { throwIfNoAccess } from "../api/tokens/permissions";-import { Scope, getScopesByRole, normalizeScopes } from "../api/tokens/scopes";+import {+ PermissionAction,+ getPermissionsByRole,+ mapScopesToPermissions,+} from "../api/tokens/scopes";import { isBetaTester } from "../edge-config";import { hashToken } from "./hash-token";import { Session, getSession } from "./utils";@@ -18,14 +22,14 @@ interface WithWorkspaceHandler {headers,session,workspace,- scopes,+ permissions,}: {req: Request;params: Record<string, string>;searchParams: Record<string, string>;headers?: Record<string, string>;session: Session;- scopes: Scope[];+ permissions: PermissionAction[];workspace: WorkspaceWithUsers;}): Promise<Response>;}@@ -44,14 +48,14 @@ export const withWorkspace = (], // if the action needs a specific planallowAnonymous, // special case for /api/links (POST /api/links) – allow no sessionbetaFeature, // if the action is a beta feature- requiredScopes = [],- skipScopeChecks, // if the action doesn't need to check for required scopes+ requiredPermissions = [],+ skipPermissionChecks, // if the action doesn't need to check for required permission(s)}: {requiredPlan?: Array<PlanProps>;allowAnonymous?: boolean;betaFeature?: boolean;- requiredScopes?: Scope[];- skipScopeChecks?: boolean;+ requiredPermissions?: PermissionAction[];+ skipPermissionChecks?: boolean;} = {},) => {return async (@@ -79,7 +83,7 @@ export const withWorkspace = (let session: Session | undefined;let workspaceId: string | undefined;let workspaceSlug: string | undefined;- let scopes: Scope[] = [];+ let permissions: PermissionAction[] = [];let token: any | null = null;const isRestrictedToken = apiKey?.startsWith("dub_");@@ -277,26 +281,25 @@ export const withWorkspace = (}}- // Find the subset of permissions that the user has access to based on their role- // Only owner can create machine users now- const userScopes = getScopesByRole(- session.user.isMachine ? "owner" : workspace.users[0].role,- );+ // By default, the user has access to all permissions based on their role+ permissions = getPermissionsByRole(workspace.users[0].role);+ // Find the subset of permissions that the user has access to based on the token scopesif (isRestrictedToken) {- const tokenScopes = (token.scopes.split(" ") || []) as Scope[];- scopes = normalizeScopes(tokenScopes).filter((scope) =>- userScopes.includes(scope),+ const tokenScopes = token.scopes.split(" ") || [];++ mapScopesToPermissions(tokenScopes).filter((permission) =>+ permissions.includes(permission),);- } else {- scopes = userScopes;}+ console.log(permissions);+// Check user has permission to make the action- if (!skipScopeChecks) {+ if (!skipPermissionChecks) {throwIfNoAccess({- scopes,- requiredScopes,+ permissions,+ requiredPermissions,workspaceId: workspace.id,});}@@ -340,7 +343,7 @@ export const withWorkspace = (headers,session,workspace,- scopes,+ permissions,});} catch (error) {return handleAndReturnErrorResponse(error, headers);diff --git a/apps/web/lib/zod/schemas/token.ts b/apps/web/lib/zod/schemas/token.tsindex f2bf826a0f..a14805f7c1 100644--- a/apps/web/lib/zod/schemas/token.ts+++ b/apps/web/lib/zod/schemas/token.ts@@ -1,4 +1,4 @@-import { availableScopes } from "@/lib/api/tokens/scopes";+import { SCOPES } from "@/lib/api/tokens/scopes";import z from "@/lib/zod";// Schema to validate the request body when creating a new token@@ -10,7 +10,7 @@ export const createTokenSchema = z.object({.min(1).max(50),isMachine: z.boolean().optional().default(false),- scopes: z.array(z.enum(availableScopes)).default([]).optional(),+ scopes: z.array(z.enum(SCOPES)).default([]).optional(),});// Schema to validate the request body when updating a tokendiff --git a/apps/web/ui/modals/add-edit-token-modal.tsx b/apps/web/ui/modals/add-edit-token-modal.tsxindex 59c94bbb86..443ce894ce 100644--- a/apps/web/ui/modals/add-edit-token-modal.tsx+++ b/apps/web/ui/modals/add-edit-token-modal.tsx@@ -1,6 +1,8 @@import {+ RESOURCES,Scope,- getResourcePermissionsByRole,+ ScopeByResource,+ getScopesByResourceForRole,scopePresets,} from "@/lib/api/tokens/scopes";import useWorkspace from "@/lib/swr/use-workspace";@@ -124,8 +126,9 @@ function AddEditTokenModal({const { name, scopes } = data;const buttonDisabled =(!name || token?.name === name) && token?.scopes === scopes;- const resourcePermissions = getResourcePermissionsByRole(- isOwner ? "owner" : "member",++ const scopesByResources = transformScopesForUI(+ getScopesByResourceForRole(isOwner ? "owner" : "member"),);return (@@ -267,51 +270,46 @@ function AddEditTokenModal({</div>{preset === "restricted" && (<div className="flex flex-col divide-y text-sm">- {resourcePermissions- .filter(- // filter out beta features- (resource) => !resource.betaFeature || betaTester,- )- .map((resource) => (- <div- className="flex items-center justify-between py-4"- key={resource.key}- >- <div className="flex items-center gap-1.5 text-gray-500">- <p>{resource.name}</p>- <InfoTooltip content={resource.description} />- </div>- <div>- <RadioGroup- defaultValue={scopes[resource.key] || ""}- className="flex gap-4"- onValueChange={(v: Scope) => {- setData({- ...data,- scopes: {- ...scopes,- [resource.key]: v,- },- });- }}- >- <div className="flex items-center space-x-2">- <RadioGroupItem value="" />- <div>None</div>+ {scopesByResources.map((resource) => (+ <div+ className="flex items-center justify-between py-4"+ key={resource.key}+ >+ <div className="flex items-center gap-1.5 text-gray-500">+ <p>{resource.name}</p>+ <InfoTooltip content={resource.description} />+ </div>+ <div>+ <RadioGroup+ defaultValue={scopes[resource.key] || ""}+ className="flex gap-4"+ onValueChange={(v: Scope) => {+ setData({+ ...data,+ scopes: {+ ...scopes,+ [resource.key]: v,+ },+ });+ }}+ >+ <div className="flex items-center space-x-2">+ <RadioGroupItem value="" />+ <div>None</div>+ </div>+ {resource.scopes.map((scope) => (+ <div+ className="flex items-center space-x-2"+ key={scope}+ >+ <RadioGroupItem value={scope.scope} />+ <div className="capitalize">{scope.type}</div></div>- {resource.permissions.map((permission) => (- <div- className="flex items-center space-x-2"- key={permission.scope}- >- <RadioGroupItem value={permission.scope} />- <div>{permission.permission}</div>- </div>- ))}- </RadioGroup>- </div>+ ))}+ </RadioGroup></div>- ))}+ </div>+ ))}</div>)}</AnimatedSizeContainer>@@ -386,3 +384,20 @@ export function useAddEditTokenModal(],);}++const transformScopesForUI = (scopedResources: ScopeByResource) => {+ return Object.keys(scopedResources).map((resourceKey) => {+ const resource = RESOURCES.find((r) => r.key === resourceKey);++ return {+ key: resource?.key || resourceKey,+ name: resource?.name || resourceKey,+ description: resource?.description,+ scopes: scopedResources[resourceKey].map((scope) => ({+ scope: scope.scope,+ type: scope.type,+ description: scope.description,+ })),+ };+ });+};