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.

Allow OAuth installs with the subset of scopes the user's role can grant.

Kiran Ke9e8ad6fe01c
diff --git a/apps/web/app/api/oauth/authorize/route.ts b/apps/web/app/api/oauth/authorize/route.ts
index 2f01f1125b..2f092dc003 100644
--- a/apps/web/app/api/oauth/authorize/route.ts
+++ b/apps/web/app/api/oauth/authorize/route.ts
@@ -5,7 +5,7 @@ import {
} from "@/lib/api/oauth/can-install-oauth-app";
import { OAUTH_CONFIG } from "@/lib/api/oauth/constants";
import { createToken } from "@/lib/api/oauth/utils";
-import { consolidateScopes, getScopesForRole } from "@/lib/api/tokens/scopes";
+import { getGrantedScopesForRole } from "@/lib/api/tokens/scopes";
import { parseRequestBody } from "@/lib/api/utils";
import { withWorkspace } from "@/lib/auth";
import { prisma } from "@/lib/prisma";
@@ -25,19 +25,11 @@ export const POST = withWorkspace(
code_challenge_method: codeChallengeMethod,
} = authorizeRequestSchema.parse(await parseRequestBody(req));
- // Check if the user has the required scopes for the workspace selected
- const userRole = workspace.users[0].role;
- const scopesForRole = getScopesForRole(userRole);
- const scopesMissing = consolidateScopes(scope).filter(
- (scope) => !scopesForRole.includes(scope) && scope !== "user.read",
- );
-
- if (scopesMissing.length > 0) {
- throw new DubApiError({
- code: "bad_request",
- message: "You don't have the permission to install this integration.",
- });
- }
+ // Grant the subset of requested scopes the user can actually authorize
+ const grantedScopes = getGrantedScopesForRole({
+ scopes: scope,
+ role: workspace.users[0].role,
+ });
const app = await prisma.oAuthApp.findUniqueOrThrow({
where: {
@@ -113,7 +105,7 @@ export const POST = withWorkspace(
redirectUri,
projectId: workspace.id,
userId: session.user.id,
- scopes: scope.join(" "),
+ scopes: grantedScopes.join(" "),
code: createToken({ length: OAUTH_CONFIG.CODE_LENGTH }),
expiresAt: new Date(Date.now() + OAUTH_CONFIG.CODE_LIFETIME * 1000),
...(app.pkce && { codeChallenge, codeChallengeMethod }),
diff --git a/apps/web/app/app.dub.co/(auth)/oauth/authorize/authorize-form.tsx b/apps/web/app/app.dub.co/(auth)/oauth/authorize/authorize-form.tsx
index d4a2658c5b..d3a02882f8 100644
--- a/apps/web/app/app.dub.co/(auth)/oauth/authorize/authorize-form.tsx
+++ b/apps/web/app/app.dub.co/(auth)/oauth/authorize/authorize-form.tsx
@@ -4,7 +4,6 @@ import {
canInstallOAuthApp,
UNVERIFIED_APP_INSTALL_MESSAGE,
} from "@/lib/api/oauth/can-install-oauth-app";
-import { consolidateScopes, getScopesForRole } from "@/lib/api/tokens/scopes";
import { clientAccessCheck } from "@/lib/client-access-check";
import useWorkspaces from "@/lib/swr/use-workspaces";
import { WorkspaceProps } from "@/lib/types";
@@ -13,9 +12,10 @@ import { WorkspaceSelector } from "@/ui/workspaces/workspace-selector";
import { Button } from "@dub/ui";
import { Integration } from "@prisma/client";
import { useSession } from "next-auth/react";
-import { useCallback, useEffect, useMemo, useState } from "react";
+import { useEffect, useState } from "react";
import { toast } from "sonner";
import * as z from "zod/v4";
+import { useAuthorizeWorkspace } from "./authorize-workspace-context";
interface AuthorizeFormProps extends z.infer<typeof authorizeRequestSchema> {
integration: Pick<Integration, "verified" | "projectId" | "userId">;
@@ -34,27 +34,10 @@ export const AuthorizeForm = ({
const { data: session } = useSession();
const { workspaces, loading: workspacesLoading } = useWorkspaces();
const [submitting, setSubmitting] = useState(false);
- const [selectedWorkspace, setSelectedWorkspace] = useState<string | null>(
- null,
- );
+ const { selectedWorkspace, setSelectedWorkspace } = useAuthorizeWorkspace();
const userId = session?.user?.id;
- const isWorkspaceAllowed = useCallback(
- (workspace: WorkspaceProps) => {
- if (!userId) {
- return false;
- }
-
- return canInstallOAuthApp({
- integration,
- workspace,
- userId,
- });
- },
- [integration, userId],
- );
-
useEffect(() => {
if (!workspaces || workspacesLoading || !userId || selectedWorkspace) {
return;
@@ -65,12 +48,17 @@ export const AuthorizeForm = ({
? workspaces.find((workspace) => workspace.slug === defaultSlug)
: undefined;
- if (defaultWorkspace && isWorkspaceAllowed(defaultWorkspace)) {
+ if (
+ defaultWorkspace &&
+ canInstallOAuthApp({ integration, workspace: defaultWorkspace, userId })
+ ) {
setSelectedWorkspace(defaultWorkspace.slug);
return;
}
- const firstAllowed = workspaces.find(isWorkspaceAllowed);
+ const firstAllowed = workspaces.find((workspace) =>
+ canInstallOAuthApp({ integration, workspace, userId }),
+ );
setSelectedWorkspace(firstAllowed?.slug ?? defaultSlug);
}, [
workspaces,
@@ -78,59 +66,17 @@ export const AuthorizeForm = ({
session,
userId,
selectedWorkspace,
- isWorkspaceAllowed,
+ integration,
+ setSelectedWorkspace,
]);
- const authorizeDisabledTooltip = useMemo((): string | undefined => {
- if (!selectedWorkspace) {
- return "Please select a workspace to continue";
- }
-
- if (workspacesLoading || workspaces === undefined) {
- return "Loading workspaces...";
- }
-
- const workspace = workspaces.find(
- (workspace) => workspace.slug === selectedWorkspace,
- );
-
- if (!workspace) {
- return "Please select a valid workspace";
- }
-
- if (!isWorkspaceAllowed(workspace)) {
- return UNVERIFIED_APP_INSTALL_MESSAGE;
- }
-
- const userRole = workspace.users[0].role;
-
- const permissionsError = clientAccessCheck({
- action: "integrations.write",
- role: userRole,
- customPermissionDescription: "install this integration",
- }).error;
-
- if (typeof permissionsError === "string") {
- return permissionsError;
- }
-
- const missingScopes = consolidateScopes(scope).filter(
- (scope) =>
- !getScopesForRole(userRole).includes(scope) && scope !== "user.read",
- );
-
- if (missingScopes.length > 0) {
- return "You don't have the permission to install this integration";
- }
-
- return undefined;
- }, [
+ const authorizeDisabledTooltip = getAuthorizeError({
+ selectedWorkspace,
workspaces,
workspacesLoading,
- selectedWorkspace,
- scope,
- isWorkspaceAllowed,
- ]);
+ integration,
+ userId,
+ });
// Decline the request
const onDecline = () => {
@@ -225,3 +171,56 @@ export const AuthorizeForm = ({
</form>
);
};
+
+const getAuthorizeError = ({
+ selectedWorkspace,
+ workspaces,
+ workspacesLoading,
+ integration,
+ userId,
+}: {
+ selectedWorkspace: string | null;
+ workspaces: WorkspaceProps[] | undefined;
+ workspacesLoading: boolean;
+ integration: AuthorizeFormProps["integration"];
+ userId: string | undefined;
+}) => {
+ if (!selectedWorkspace) {
+ return "Please select a workspace to continue";
+ }
+
+ if (workspacesLoading || workspaces === undefined) {
+ return "Loading workspaces...";
+ }
+
+ const workspace = workspaces.find(
+ (workspace) => workspace.slug === selectedWorkspace,
+ );
+
+ if (!workspace) {
+ return "Please select a valid workspace";
+ }
+
+ if (
+ !userId ||
+ !canInstallOAuthApp({
+ integration,
+ workspace,
+ userId,
+ })
+ ) {
+ return UNVERIFIED_APP_INSTALL_MESSAGE;
+ }
+
+ const { error: permissionsError } = clientAccessCheck({
+ action: "integrations.write",
+ role: workspace.users[0].role,
+ customPermissionDescription: "install this integration",
+ });
+
+ if (typeof permissionsError === "string") {
+ return permissionsError;
+ }
+
+ return undefined;
+};
diff --git a/apps/web/app/app.dub.co/(auth)/oauth/authorize/authorize-workspace-context.tsx b/apps/web/app/app.dub.co/(auth)/oauth/authorize/authorize-workspace-context.tsx
new file mode 100644
index 0000000000..6602335e9f
--- /dev/null
+++ b/apps/web/app/app.dub.co/(auth)/oauth/authorize/authorize-workspace-context.tsx
@@ -0,0 +1,47 @@
+"use client";
+
+import {
+ createContext,
+ Dispatch,
+ ReactNode,
+ SetStateAction,
+ useContext,
+ useState,
+} from "react";
+
+const AuthorizeWorkspaceContext = createContext<{
+ selectedWorkspace: string | null;
+ setSelectedWorkspace: Dispatch<SetStateAction<string | null>>;
+} | null>(null);
+
+// Shares the selected workspace between the scopes list and the authorize form
+// so missing-scope warnings update when the workspace changes.
+export function AuthorizeWorkspaceProvider({
+ children,
+}: {
+ children: ReactNode;
+}) {
+ const [selectedWorkspace, setSelectedWorkspace] = useState<string | null>(
+ null,
+ );
+
+ return (
+ <AuthorizeWorkspaceContext.Provider
+ value={{ selectedWorkspace, setSelectedWorkspace }}
+ >
+ {children}
+ </AuthorizeWorkspaceContext.Provider>
+ );
+}
+
+export function useAuthorizeWorkspace() {
+ const context = useContext(AuthorizeWorkspaceContext);
+
+ if (!context) {
+ throw new Error(
+ "useAuthorizeWorkspace must be used within AuthorizeWorkspaceProvider",
+ );
+ }
+
+ return context;
+}
diff --git a/apps/web/app/app.dub.co/(auth)/oauth/authorize/page.tsx b/apps/web/app/app.dub.co/(auth)/oauth/authorize/page.tsx
index b892c74e58..5d1dfa8c54 100644
--- a/apps/web/app/app.dub.co/(auth)/oauth/authorize/page.tsx
+++ b/apps/web/app/app.dub.co/(auth)/oauth/authorize/page.tsx
@@ -11,6 +11,7 @@ import { redirect } from "next/navigation";
import { Suspense } from "react";
import * as z from "zod/v4";
import { AuthorizeForm } from "./authorize-form";
+import { AuthorizeWorkspaceProvider } from "./authorize-workspace-context";
import { ScopesRequested } from "./scopes-requested";
export const metadata = constructMetadata({
@@ -99,14 +100,16 @@ export default async function Authorize(props: {
</Callout>
)}
</div>
- <div className="flex flex-col space-y-3 px-4 py-6 sm:px-10">
- <ScopesRequested scopes={requestParams.scope} />
- </div>
- <div className="flex flex-col space-y-2 border-t border-neutral-200 px-4 py-6 sm:rounded-b-2xl sm:px-10">
- <Suspense>
- <AuthorizeForm {...requestParams} integration={integration} />
- </Suspense>
- </div>
+ <AuthorizeWorkspaceProvider>
+ <div className="flex flex-col space-y-3 px-4 py-6 sm:px-10">
+ <ScopesRequested scopes={requestParams.scope} />
+ </div>
+ <div className="flex flex-col space-y-2 border-t border-neutral-200 px-4 py-6 sm:rounded-b-2xl sm:px-10">
+ <Suspense>
+ <AuthorizeForm {...requestParams} integration={integration} />
+ </Suspense>
+ </div>
+ </AuthorizeWorkspaceProvider>
</div>
);
}
diff --git a/apps/web/app/app.dub.co/(auth)/oauth/authorize/scopes-requested.tsx b/apps/web/app/app.dub.co/(auth)/oauth/authorize/scopes-requested.tsx
index ba325fd6b1..f57f2e7885 100644
--- a/apps/web/app/app.dub.co/(auth)/oauth/authorize/scopes-requested.tsx
+++ b/apps/web/app/app.dub.co/(auth)/oauth/authorize/scopes-requested.tsx
@@ -1,25 +1,50 @@
"use client";
import { OAUTH_SCOPE_DESCRIPTIONS } from "@/lib/api/oauth/constants";
-import { consolidateScopes } from "@/lib/api/tokens/scopes";
+import {
+ consolidateScopes,
+ getMissingScopesForRole,
+} from "@/lib/api/tokens/scopes";
+import useWorkspaces from "@/lib/swr/use-workspaces";
+import { Tooltip } from "@dub/ui";
+import { TriangleWarning } from "@dub/ui/icons";
+import { cn } from "@dub/utils";
import { Check } from "lucide-react";
+import { useAuthorizeWorkspace } from "./authorize-workspace-context";
-interface ScopesProps {
- scopes: string[];
-}
+export const ScopesRequested = ({ scopes }: { scopes: string[] }) => {
+ const { workspaces } = useWorkspaces();
+ const { selectedWorkspace } = useAuthorizeWorkspace();
-export const ScopesRequested = ({ scopes }: ScopesProps) => {
// Add default scopes if not present
- if (!scopes.includes("user.read")) {
- scopes.push("user.read");
- }
-
- const scopeWithDescriptions = consolidateScopes(scopes).map((scope) => {
- return {
- scope,
- description: OAUTH_SCOPE_DESCRIPTIONS[scope],
- };
- });
+ const requestedScopes = scopes.includes("user.read")
+ ? scopes
+ : [...scopes, "user.read"];
+
+ const workspace = workspaces?.find(
+ (workspace) => workspace.slug === selectedWorkspace,
+ );
+
+ const workspaceRole = workspace?.users[0]?.role;
+
+ const missingScopes = workspaceRole
+ ? getMissingScopesForRole({
+ scopes: requestedScopes,
+ role: workspaceRole,
+ })
+ : [];
+
+ const missingScopeSet = new Set(missingScopes);
+
+ const scopeWithDescriptions = consolidateScopes(requestedScopes).map(
+ (scope) => {
+ return {
+ scope,
+ description: OAUTH_SCOPE_DESCRIPTIONS[scope],
+ missing: missingScopeSet.has(scope),
+ };
+ },
+ );
scopeWithDescriptions.forEach((scope) => {
scope.description = scope.description.replace(
@@ -40,8 +65,15 @@ export const ScopesRequested = ({ scopes }: ScopesProps) => {
{scopeWithDescriptions.map((scope) => {
return (
<li className="flex items-center gap-2" key={scope.scope}>
- <Check className="h-4 w-4 text-green-500" />
- <div dangerouslySetInnerHTML={{ __html: scope.description }} />
+ {scope.missing ? (
+ <MissingScopeWarning />
+ ) : (
+ <Check className="size-4 shrink-0 text-green-500" />
+ )}
+ <div
+ className={cn(scope.missing && "text-neutral-500")}
+ dangerouslySetInnerHTML={{ __html: scope.description }}
+ />
</li>
);
})}
@@ -49,3 +81,13 @@ export const ScopesRequested = ({ scopes }: ScopesProps) => {
</>
);
};
+
+const MissingScopeWarning = () => {
+ return (
+ <Tooltip content="Your role in this workspace doesn't include this permission, so it won't be granted.">
+ <span className="inline-flex shrink-0 cursor-help">
+ <TriangleWarning className="size-4 text-amber-500" variant="fill" />
+ </span>
+ </Tooltip>
+ );
+};
diff --git a/apps/web/lib/api/tokens/scopes.ts b/apps/web/lib/api/tokens/scopes.ts
index bf9faf2f18..af7d1700dd 100644
--- a/apps/web/lib/api/tokens/scopes.ts
+++ b/apps/web/lib/api/tokens/scopes.ts
@@ -313,3 +313,44 @@ export const consolidateScopes = (scopes: string[]) => {
return Array.from(consolidated) as string[];
};
+
+const isScopeGrantedForRole = ({
+ scope,
+ role,
+}: {
+ scope: string;
+ role: WorkspaceRole;
+}) => {
+ const scopesForRole: string[] = getScopesForRole(role) ?? [];
+
+ return scope === "user.read" || scopesForRole.includes(scope);
+};
+
+// Scopes that can be granted for the given role (intersection with requested)
+export const getGrantedScopesForRole = ({
+ scopes,
+ role,
+}: {
+ scopes: string[];
+ role: WorkspaceRole;
+}) => {
+ return scopes.filter((scope) =>
+ isScopeGrantedForRole({
+ scope,
+ role,
+ }),
+ );
+};
+
+// Requested scopes the role cannot grant (consolidated for display)
+export const getMissingScopesForRole = ({
+ scopes,
+ role,
+}: {
+ scopes: string[];
+ role: WorkspaceRole;
+}) => {
+ return consolidateScopes(scopes).filter(
+ (scope) => !isScopeGrantedForRole({ scope, role }),
+ );
+};
diff --git a/apps/web/tests/tokens/get-granted-scopes-for-role.test.ts b/apps/web/tests/tokens/get-granted-scopes-for-role.test.ts
new file mode 100644
index 0000000000..ffdca69f93
--- /dev/null
+++ b/apps/web/tests/tokens/get-granted-scopes-for-role.test.ts
@@ -0,0 +1,84 @@
+import { OAUTH_SCOPES } from "@/lib/api/oauth/constants";
+import { getGrantedScopesForRole } from "@/lib/api/tokens/scopes";
+import { WorkspaceRole } from "@prisma/client";
+import { describe, expect, test } from "vitest";
+
+const ALL_OAUTH_SCOPES = [...OAUTH_SCOPES];
+
+const OWNER_ONLY_OAUTH_SCOPES = ["domains.write", "webhooks.write"];
+
+const READ_OAUTH_SCOPES = ALL_OAUTH_SCOPES.filter(
+ (scope) => scope === "user.read" || scope.endsWith(".read"),
+);
+
+describe("getGrantedScopesForRole", () => {
+ test("owner is granted every requested OAuth scope including user.read", () => {
+ expect(
+ getGrantedScopesForRole({
+ scopes: ALL_OAUTH_SCOPES,
+ role: "owner",
+ }),
+ ).toEqual(ALL_OAUTH_SCOPES);
+ });
+
+ test("member is granted write scopes except owner-only ones", () => {
+ expect(
+ getGrantedScopesForRole({
+ scopes: ALL_OAUTH_SCOPES,
+ role: "member",
+ }),
+ ).toEqual(
+ ALL_OAUTH_SCOPES.filter(
+ (scope) => !OWNER_ONLY_OAUTH_SCOPES.includes(scope),
+ ),
+ );
+ });
+
+ test.each(["viewer", "billing"] as const)(
+ "%s is only granted read OAuth scopes and user.read",
+ (role: WorkspaceRole) => {
+ expect(
+ getGrantedScopesForRole({
+ scopes: ALL_OAUTH_SCOPES,
+ role,
+ }),
+ ).toEqual(READ_OAUTH_SCOPES);
+ },
+ );
+
+ test("always grants user.read even when other requested scopes are not allowed", () => {
+ expect(
+ getGrantedScopesForRole({
+ scopes: ["user.read", "domains.write", "webhooks.write"],
+ role: "viewer",
+ }),
+ ).toEqual(["user.read"]);
+ });
+
+ test("drops unknown scopes", () => {
+ expect(
+ getGrantedScopesForRole({
+ scopes: ["links.read", "not.a.scope", "user.read"],
+ role: "owner",
+ }),
+ ).toEqual(["links.read", "user.read"]);
+ });
+
+ test("preserves the order of requested scopes", () => {
+ expect(
+ getGrantedScopesForRole({
+ scopes: ["user.read", "webhooks.write", "links.read"],
+ role: "owner",
+ }),
+ ).toEqual(["user.read", "webhooks.write", "links.read"]);
+ });
+
+ test("returns an empty array when no requested scopes can be granted", () => {
+ expect(
+ getGrantedScopesForRole({
+ scopes: ["domains.write", "webhooks.write"],
+ role: "billing",
+ }),
+ ).toEqual([]);
+ });
+});