Skip to content

armgit / dub

Public Imported from GitHub
0

The modern link attribution platform. Loved by world-class engineering teams at Twilio, Zillow, Jobber, Vercel, Raycast, and more.

small refactor scopes and permissions

Kiran Kb9a4377cab25
diff --git a/apps/web/lib/api/rbac/permissions.ts b/apps/web/lib/api/rbac/permissions.ts
new file mode 100644
index 0000000000..9612441a87
--- /dev/null
+++ b/apps/web/lib/api/rbac/permissions.ts
@@ -0,0 +1,104 @@
+import { Role } from "@prisma/client";
+
+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",
+ "oauth_apps.read",
+ "oauth_apps.write",
+] as const;
+
+export type PermissionAction = (typeof PERMISSION_ACTIONS)[number];
+
+export const ROLE_PERMISSIONS: {
+ action: PermissionAction;
+ description: string;
+ roles: Role[];
+}[] = [
+ {
+ action: "links.read",
+ description: "access links",
+ roles: ["owner", "member"],
+ },
+ {
+ action: "links.write",
+ description: "create, update, or delete links",
+ roles: ["owner", "member"],
+ },
+ {
+ action: "analytics.read",
+ description: "access analytics",
+ roles: ["owner", "member"],
+ },
+ {
+ action: "workspaces.read",
+ description: "access workspaces",
+ roles: ["owner", "member"],
+ },
+ {
+ action: "workspaces.write",
+ description: "update or delete the current workspace",
+ roles: ["owner"],
+ },
+ {
+ action: "domains.read",
+ description: "access domains",
+ roles: ["owner", "member"],
+ },
+ {
+ action: "domains.write",
+ description: "create, update, or delete domains",
+ roles: ["owner"],
+ },
+ {
+ action: "tags.read",
+ description: "access tags",
+ roles: ["owner", "member"],
+ },
+ {
+ action: "tags.write",
+ description: "create, update, or delete tags",
+ roles: ["owner", "member"],
+ },
+ {
+ action: "conversions.write",
+ description: "track conversions",
+ roles: ["owner"],
+ },
+ {
+ action: "tokens.read",
+ description: "access API keys",
+ roles: ["owner", "member"],
+ },
+ {
+ action: "tokens.write",
+ description: "create, update, or delete API keys",
+ roles: ["owner", "member"],
+ },
+ {
+ action: "oauth_apps.read",
+ description: "Read OAuth apps",
+ roles: ["owner", "member"],
+ },
+ {
+ action: "oauth_apps.write",
+ description: "Create, update, or delete OAuth apps",
+ roles: ["owner"],
+ },
+];
+
+// Get permissions for a role
+export const getPermissionsByRole = (role: Role) => {
+ return ROLE_PERMISSIONS.filter(({ roles }) => roles.includes(role)).map(
+ ({ action }) => action,
+ );
+};
diff --git a/apps/web/lib/api/rbac/resources.ts b/apps/web/lib/api/rbac/resources.ts
new file mode 100644
index 0000000000..5b4d576a1f
--- /dev/null
+++ b/apps/web/lib/api/rbac/resources.ts
@@ -0,0 +1,55 @@
+export const RESOURCE_KEYS = [
+ "links",
+ "workspaces",
+ "analytics",
+ "domains",
+ "tags",
+ "tokens",
+ "conversions",
+] as const;
+
+export type ResourceKey = (typeof RESOURCE_KEYS)[number];
+
+export const RESOURCES: {
+ name: string;
+ key: ResourceKey;
+ description: string;
+ betaFeature: boolean;
+}[] = [
+ {
+ name: "Links",
+ key: "links",
+ description: "Create, read, update, and delete links",
+ betaFeature: false,
+ },
+ {
+ name: "Analytics",
+ key: "analytics",
+ description: "Read analytics",
+ betaFeature: false,
+ },
+ {
+ name: "Workspaces",
+ key: "workspaces",
+ description: "Read, update, and delete workspaces",
+ betaFeature: false,
+ },
+ {
+ name: "Domains",
+ key: "domains",
+ description: "Create, read, update, and delete domains",
+ betaFeature: false,
+ },
+ {
+ name: "Tags",
+ key: "tags",
+ description: "Create, read, update, and delete tags",
+ betaFeature: false,
+ },
+ {
+ name: "Conversions",
+ key: "conversions",
+ description: "Track conversions (customer, lead, sales)",
+ betaFeature: true,
+ },
+];
diff --git a/apps/web/lib/api/tokens/permissions.ts b/apps/web/lib/api/tokens/permissions.ts
index 1fbdc249bc..1a6f6b5b74 100644
--- a/apps/web/lib/api/tokens/permissions.ts
+++ b/apps/web/lib/api/tokens/permissions.ts
@@ -1,7 +1,7 @@
import { combineWords } from "@dub/utils";
import { Role } from "@prisma/client";
import { DubApiError } from "../errors";
-import { PERMISSIONS, PermissionAction } from "./scopes";
+import { PermissionAction, ROLE_PERMISSIONS } from "../rbac/permissions";
// Check if the required scope is in the list of user scopes
export const throwIfNoAccess = ({
@@ -40,7 +40,7 @@ export const clientAccessCheck = ({
role: Role;
customPermissionDescription?: string;
}) => {
- const permission = PERMISSIONS.find((p) => p.action === action)!;
+ const permission = ROLE_PERMISSIONS.find((p) => p.action === action)!;
const allowedRoles = permission.roles;
if (allowedRoles.includes(role)) {
diff --git a/apps/web/lib/api/tokens/scopes.ts b/apps/web/lib/api/tokens/scopes.ts
index 6eded47d3b..58e5cf59fd 100644
--- a/apps/web/lib/api/tokens/scopes.ts
+++ b/apps/web/lib/api/tokens/scopes.ts
@@ -1,6 +1,8 @@
import { Role } from "@prisma/client";
+import { PermissionAction } from "../rbac/permissions";
+import { ResourceKey } from "../rbac/resources";
-export const SCOPES_NAMES = [
+export const SCOPE_NAMES = [
"workspaces.read",
"workspaces.write",
"links.read",
@@ -15,63 +17,16 @@ export const SCOPES_NAMES = [
"apis.read", // All read scopes
] as const;
-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",
- "oauth_apps.read",
- "oauth_apps.write",
-] as const;
+export type ScopeName = (typeof SCOPE_NAMES)[number];
-export const RESOURCES: Resource[] = [
- {
- name: "Links",
- key: "links",
- description: "Create, read, update, and delete links",
- betaFeature: false,
- },
- {
- name: "Analytics",
- key: "analytics",
- description: "Read analytics",
- betaFeature: false,
- },
- {
- name: "Workspaces",
- key: "workspaces",
- description: "Read, update, and delete workspaces",
- betaFeature: false,
- },
- {
- name: "Domains",
- key: "domains",
- description: "Create, read, update, and delete domains",
- betaFeature: false,
- },
- {
- name: "Tags",
- key: "tags",
- description: "Create, read, update, and delete tags",
- betaFeature: false,
- },
- {
- name: "Conversions",
- key: "conversions",
- description: "Track conversions (customer, lead, sales)",
- betaFeature: true,
- },
-];
-
-export const SCOPES: MasterScope[] = [
+// Scopes available for Workspace API keys
+export const SCOPES: {
+ scope: ScopeName;
+ roles: Role[];
+ permissions: PermissionAction[];
+ type?: "read" | "write";
+ resource?: ResourceKey;
+}[] = [
{
scope: "links.read",
roles: ["owner", "member"],
@@ -145,140 +100,70 @@ export const SCOPES: MasterScope[] = [
{
scope: "apis.read",
roles: ["owner", "member"],
- permissions: PERMISSION_ACTIONS.filter(
- (action) => action.endsWith(".read") && !action.startsWith("tokens."),
- ),
+ permissions: [
+ "links.read",
+ "tags.read",
+ "domains.read",
+ "workspaces.read",
+ "analytics.read",
+ ],
},
{
scope: "apis.all",
roles: ["owner", "member"],
- permissions: PERMISSION_ACTIONS.map((action) => action).filter(
- (action) => !action.startsWith("tokens."),
- ),
+ permissions: [
+ "links.read",
+ "links.write",
+ "tags.read",
+ "tags.write",
+ "domains.read",
+ "domains.write",
+ "workspaces.read",
+ "workspaces.write",
+ "analytics.read",
+ ],
},
];
-export const PERMISSIONS: Permission[] = [
- {
- action: "links.read",
- description: "access links",
- roles: ["owner", "member"],
- },
- {
- action: "links.write",
- description: "create, update, or delete links",
- roles: ["owner", "member"],
- },
- {
- action: "analytics.read",
- description: "access analytics",
- roles: ["owner", "member"],
- },
- {
- action: "workspaces.read",
- description: "access workspaces",
- roles: ["owner", "member"],
- },
- {
- action: "workspaces.write",
- description: "update or delete the current workspace",
- roles: ["owner"],
- },
- {
- action: "domains.read",
- description: "access domains",
- roles: ["owner", "member"],
- },
- {
- action: "domains.write",
- description: "create, update, or delete domains",
- roles: ["owner"],
- },
- {
- action: "tags.read",
- description: "access tags",
- roles: ["owner", "member"],
- },
- {
- action: "tags.write",
- description: "create, update, or delete tags",
- roles: ["owner", "member"],
- },
- {
- action: "tokens.read",
- description: "access API keys",
- roles: ["owner", "member"],
- },
- {
- action: "tokens.write",
- description: "create, update, or delete API keys",
- roles: ["owner", "member"],
- },
- {
- action: "conversions.write",
- description: "track conversions",
- roles: ["owner"],
- },
- {
- action: "oauth_apps.read",
- description: "Read OAuth apps",
- roles: ["owner", "member"],
- },
- {
- action: "oauth_apps.write",
- description: "Create, update, or delete OAuth apps",
- roles: ["owner"],
- },
-];
-
-export const SCOPES_BY_RESOURCE: ScopeByResource = SCOPES.reduce(
- (acc, scope) => {
- if (!scope.resource || !scope.type) {
- return acc;
- }
+export const SCOPES_BY_RESOURCE = SCOPES.reduce((acc, scope) => {
+ if (!scope.resource || !scope.type) {
+ return acc;
+ }
- if (!acc[scope.resource]) {
- acc[scope.resource] = [];
- }
+ if (!acc[scope.resource]) {
+ acc[scope.resource] = [];
+ }
- acc[scope.resource].push({
- scope: scope.scope,
- type: scope.type,
- });
+ acc[scope.resource].push({
+ scope: scope.scope,
+ type: scope.type,
+ roles: scope.roles,
+ });
- return acc;
- },
- {} as ScopeByResource,
-);
+ return acc;
+}, {});
// Scope to permissions mapping
-export const SCOPE_PERMISSIONS_MAP: Record<Scope, PermissionAction[]> =
- SCOPES.reduce(
- (acc, scope) => {
- acc[scope.scope] = scope.permissions;
- return acc;
- },
- {} as Record<Scope, PermissionAction[]>,
- );
+export const SCOPE_PERMISSIONS_MAP = SCOPES.reduce((acc, scope) => {
+ acc[scope.scope] = scope.permissions;
+ return acc;
+}, {});
// Role to scopes mapping
-export const ROLE_SCOPES_MAP: Record<Role, Scope[]> = SCOPES.reduce(
- (acc, scope) => {
- scope.roles.forEach((role) => {
- if (!acc[role]) {
- acc[role] = [];
- }
+export const ROLE_SCOPES_MAP = SCOPES.reduce((acc, scope) => {
+ scope.roles.forEach((role) => {
+ if (!acc[role]) {
+ acc[role] = [];
+ }
- acc[role].push(scope.scope);
- });
+ acc[role].push(scope.scope);
+ });
- return acc;
- },
- {} as Record<Role, Scope[]>,
-);
+ return acc;
+}, {});
// // For each scope, get the permissions it grants access to and return array of permissions
-export const mapScopesToPermissions = (scopes: Scope[]) => {
+export const mapScopesToPermissions = (scopes: ScopeName[]) => {
const permissions: PermissionAction[] = [];
scopes.forEach((scope) => {
@@ -290,32 +175,27 @@ export const mapScopesToPermissions = (scopes: Scope[]) => {
return permissions;
};
-// Get permissions by roles
-export const getPermissionsByRole = (role: Role) => {
- return PERMISSIONS.filter((permission) =>
- permission.roles.includes(role),
- ).map((permission) => permission.action);
-};
-
// Get SCOPES_BY_RESOURCE based on user role in a workspace
export const getScopesByResourceForRole = (role: Role) => {
- const allowedScopes = ROLE_SCOPES_MAP[role];
- // @ts-ignore
- const scopedResources: ScopeByResource = {};
+ const groupedByResource = {};
- Object.keys(SCOPES_BY_RESOURCE).forEach((resourceKey) => {
- SCOPES_BY_RESOURCE[resourceKey].forEach((scope) => {
- if (allowedScopes.includes(scope.scope)) {
- if (!scopedResources[resourceKey]) {
- scopedResources[resourceKey] = [];
- }
+ const allowedScopes = SCOPES.map((scope) => {
+ if (scope.roles.includes(role)) {
+ return scope;
+ }
+ }).filter(Boolean);
- scopedResources[resourceKey].push(scope);
+ allowedScopes.forEach((scope) => {
+ if (scope && scope.resource) {
+ if (!groupedByResource[scope.resource]) {
+ groupedByResource[scope.resource] = [];
}
- });
+
+ groupedByResource[scope.resource].push(scope);
+ }
});
- return scopedResources;
+ return groupedByResource;
};
export const scopePresets = [
@@ -357,7 +237,7 @@ export const scopesToName = (scopes: string[]) => {
};
};
-export const validateScopesForRole = (scopes: Scope[], role: Role) => {
+export const validateScopesForRole = (scopes: ScopeName[], role: Role) => {
const allowedScopes = ROLE_SCOPES_MAP[role];
const invalidScopes = scopes.filter(
(scope) => !allowedScopes.includes(scope),
@@ -365,44 +245,3 @@ export const validateScopesForRole = (scopes: Scope[], role: Role) => {
return !(invalidScopes.length > 0);
};
-
-export type Scope = (typeof SCOPES_NAMES)[number];
-
-export type PermissionAction = (typeof PERMISSION_ACTIONS)[number];
-
-export type ResourceKeys =
- | "links"
- | "workspaces"
- | "analytics"
- | "domains"
- | "tags"
- | "tokens"
- | "conversions";
-
-type Resource = {
- name: string;
- key: ResourceKeys;
- description: string;
- betaFeature: boolean;
-};
-
-type Permission = {
- action: PermissionAction;
- description: string;
- roles: Role[];
-};
-
-type MasterScope = {
- scope: Scope;
- roles: Role[];
- permissions: PermissionAction[];
- type?: "read" | "write";
- resource?: ResourceKeys;
-};
-
-export type ScopeByResource = {
- [key in ResourceKeys]: {
- scope: Scope;
- type: "read" | "write";
- }[];
-};
diff --git a/apps/web/lib/auth/workspace-edge.ts b/apps/web/lib/auth/workspace-edge.ts
index 8f4cef1c67..378f2c2ee7 100644
--- a/apps/web/lib/auth/workspace-edge.ts
+++ b/apps/web/lib/auth/workspace-edge.ts
@@ -10,13 +10,12 @@ import { waitUntil } from "@vercel/functions";
import { StreamingTextResponse } from "ai";
import { getToken } from "next-auth/jwt";
import { NextRequest } from "next/server";
-import { throwIfNoAccess } from "../api/tokens/permissions";
import {
PermissionAction,
- Scope,
getPermissionsByRole,
- mapScopesToPermissions,
-} from "../api/tokens/scopes";
+} from "../api/rbac/permissions";
+import { throwIfNoAccess } from "../api/tokens/permissions";
+import { ScopeName, mapScopesToPermissions } from "../api/tokens/scopes";
import { isBetaTester } from "../edge-config";
import { prismaEdge } from "../prisma/edge";
import { hashToken } from "./hash-token";
@@ -276,7 +275,7 @@ export const withWorkspaceEdge = (
// Find the subset of permissions that the user has access to based on the token scopes
if (isRestrictedToken) {
- const tokenScopes: Scope[] = token.scopes.split(" ") || [];
+ const tokenScopes: ScopeName[] = token.scopes.split(" ") || [];
permissions = mapScopesToPermissions(tokenScopes).filter((p) =>
permissions.includes(p),
);
diff --git a/apps/web/lib/auth/workspace.ts b/apps/web/lib/auth/workspace.ts
index 07d7d518cf..fa936200a9 100644
--- a/apps/web/lib/auth/workspace.ts
+++ b/apps/web/lib/auth/workspace.ts
@@ -4,13 +4,12 @@ import { PlanProps, WorkspaceWithUsers } from "@/lib/types";
import { ratelimit } from "@/lib/upstash";
import { API_DOMAIN, getSearchParams } from "@dub/utils";
import { waitUntil } from "@vercel/functions";
-import { throwIfNoAccess } from "../api/tokens/permissions";
import {
PermissionAction,
- Scope,
getPermissionsByRole,
- mapScopesToPermissions,
-} from "../api/tokens/scopes";
+} from "../api/rbac/permissions";
+import { throwIfNoAccess } from "../api/tokens/permissions";
+import { ScopeName, mapScopesToPermissions } from "../api/tokens/scopes";
import { isBetaTester } from "../edge-config";
import { hashToken } from "./hash-token";
import { Session, getSession } from "./utils";
@@ -300,7 +299,7 @@ export const withWorkspace = (
// Find the subset of permissions that the user has access to based on the token scopes
if (isRestrictedToken) {
- const tokenScopes: Scope[] = token.scopes.split(" ") || [];
+ const tokenScopes: ScopeName[] = token.scopes.split(" ") || [];
permissions = mapScopesToPermissions(tokenScopes).filter((p) =>
permissions.includes(p),
);
diff --git a/apps/web/lib/zod/schemas/token.ts b/apps/web/lib/zod/schemas/token.ts
index 1e93437ddf..5efc45113e 100644
--- a/apps/web/lib/zod/schemas/token.ts
+++ b/apps/web/lib/zod/schemas/token.ts
@@ -1,4 +1,4 @@
-import { SCOPES_NAMES } from "@/lib/api/tokens/scopes";
+import { SCOPE_NAMES } 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(SCOPES_NAMES)).default([]).optional(),
+ scopes: z.array(z.enum(SCOPE_NAMES)).default([]).optional(),
});
// Schema to validate the request body when updating a token
diff --git a/apps/web/ui/modals/add-edit-token-modal.tsx b/apps/web/ui/modals/add-edit-token-modal.tsx
index bafbaac4f1..866f901359 100644
--- a/apps/web/ui/modals/add-edit-token-modal.tsx
+++ b/apps/web/ui/modals/add-edit-token-modal.tsx
@@ -1,9 +1,7 @@
+import { ResourceKey, RESOURCES } from "@/lib/api/rbac/resources";
import {
- RESOURCES,
- ResourceKeys,
- Scope,
- ScopeByResource,
getScopesByResourceForRole,
+ ScopeName,
scopePresets,
} from "@/lib/api/tokens/scopes";
import useWorkspace from "@/lib/swr/use-workspace";
@@ -37,7 +35,7 @@ import { mutate } from "swr";
type APIKeyProps = {
id?: string;
name: string;
- scopes: { [key: string]: Scope };
+ scopes: { [key: string]: ScopeName };
isMachine: boolean;
};
@@ -296,7 +294,7 @@ function AddEditTokenModal({
<RadioGroup
defaultValue={scopes[resource.key] || ""}
className="flex gap-4"
- onValueChange={(v: Scope) => {
+ onValueChange={(v: ScopeName) => {
setData({
...data,
scopes: {
@@ -398,8 +396,8 @@ export function useAddEditTokenModal(
);
}
-const transformScopesForUI = (scopedResources: ScopeByResource) => {
- return Object.keys(scopedResources).map((resourceKey: ResourceKeys) => {
+const transformScopesForUI = (scopedResources) => {
+ return Object.keys(scopedResources).map((resourceKey: ResourceKey) => {
return {
...RESOURCES.find((r) => r.key === resourceKey)!,
scopes: scopedResources[resourceKey],