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.

Show which OAuth scopes a workspace role can grant on the consent screen.

Kiran K30f58a457bc5
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 d3a02882f8..06ac770fa0 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
@@ -5,14 +5,13 @@ import {
UNVERIFIED_APP_INSTALL_MESSAGE,
} from "@/lib/api/oauth/can-install-oauth-app";
import { clientAccessCheck } from "@/lib/client-access-check";
-import useWorkspaces from "@/lib/swr/use-workspaces";
import { WorkspaceProps } from "@/lib/types";
import { authorizeRequestSchema } from "@/lib/zod/schemas/oauth";
import { WorkspaceSelector } from "@/ui/workspaces/workspace-selector";
import { Button } from "@dub/ui";
import { Integration } from "@prisma/client";
import { useSession } from "next-auth/react";
-import { useEffect, useState } from "react";
+import { useState } from "react";
import { toast } from "sonner";
import * as z from "zod/v4";
import { useAuthorizeWorkspace } from "./authorize-workspace-context";
@@ -32,43 +31,15 @@ export const AuthorizeForm = ({
integration,
}: AuthorizeFormProps) => {
const { data: session } = useSession();
- const { workspaces, loading: workspacesLoading } = useWorkspaces();
const [submitting, setSubmitting] = useState(false);
- const { selectedWorkspace, setSelectedWorkspace } = useAuthorizeWorkspace();
-
- const userId = session?.user?.id;
-
- useEffect(() => {
- if (!workspaces || workspacesLoading || !userId || selectedWorkspace) {
- return;
- }
-
- const defaultSlug = session?.user?.["defaultWorkspace"] || null;
- const defaultWorkspace = defaultSlug
- ? workspaces.find((workspace) => workspace.slug === defaultSlug)
- : undefined;
-
- if (
- defaultWorkspace &&
- canInstallOAuthApp({ integration, workspace: defaultWorkspace, userId })
- ) {
- setSelectedWorkspace(defaultWorkspace.slug);
- return;
- }
-
- const firstAllowed = workspaces.find((workspace) =>
- canInstallOAuthApp({ integration, workspace, userId }),
- );
- setSelectedWorkspace(firstAllowed?.slug ?? defaultSlug);
- }, [
- workspaces,
- workspacesLoading,
- session,
- userId,
+ const {
selectedWorkspace,
- integration,
setSelectedWorkspace,
- ]);
+ workspaces,
+ workspacesLoading,
+ } = useAuthorizeWorkspace();
+
+ const userId = session?.user?.id;
const authorizeDisabledTooltip = getAuthorizeError({
selectedWorkspace,
@@ -97,19 +68,10 @@ export const AuthorizeForm = ({
return;
}
- const workspaceId = workspaces?.find(
- (workspace) => workspace.slug === selectedWorkspace,
- )?.id;
-
- if (!workspaceId) {
- toast.error("Please select a workspace to continue");
- return;
- }
-
setSubmitting(true);
const response = await fetch(
- `/api/oauth/authorize?workspaceId=${workspaceId}`,
+ `/api/oauth/authorize?workspaceId=${selectedWorkspace.id}`,
{
method: "POST",
body: JSON.stringify(Object.fromEntries(new FormData(e.currentTarget))),
@@ -149,8 +111,12 @@ export const AuthorizeForm = ({
</p>
<div className="max-w-md py-2">
<WorkspaceSelector
- selectedWorkspace={selectedWorkspace || ""}
- setSelectedWorkspace={setSelectedWorkspace}
+ selectedWorkspace={selectedWorkspace?.slug || ""}
+ setSelectedWorkspace={(slug) => {
+ setSelectedWorkspace(
+ workspaces?.find((workspace) => workspace.slug === slug) ?? null,
+ );
+ }}
/>
</div>
<div className="mt-4 flex justify-between gap-4">
@@ -179,7 +145,7 @@ const getAuthorizeError = ({
integration,
userId,
}: {
- selectedWorkspace: string | null;
+ selectedWorkspace: WorkspaceProps | null;
workspaces: WorkspaceProps[] | undefined;
workspacesLoading: boolean;
integration: AuthorizeFormProps["integration"];
@@ -193,28 +159,16 @@ const getAuthorizeError = ({
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,
- })
+ !canInstallOAuthApp({ integration, workspace: selectedWorkspace, userId })
) {
return UNVERIFIED_APP_INSTALL_MESSAGE;
}
const { error: permissionsError } = clientAccessCheck({
action: "integrations.write",
- role: workspace.users[0].role,
+ role: selectedWorkspace.users[0].role,
customPermissionDescription: "install this integration",
});
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
index 6602335e9f..29e93ff035 100644
--- 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
@@ -1,33 +1,73 @@
"use client";
+import { canInstallOAuthApp } from "@/lib/api/oauth/can-install-oauth-app";
+import useWorkspaces from "@/lib/swr/use-workspaces";
+import { WorkspaceProps } from "@/lib/types";
+import { Integration } from "@prisma/client";
+import { useSession } from "next-auth/react";
import {
createContext,
Dispatch,
ReactNode,
SetStateAction,
useContext,
+ useMemo,
useState,
} from "react";
-const AuthorizeWorkspaceContext = createContext<{
- selectedWorkspace: string | null;
- setSelectedWorkspace: Dispatch<SetStateAction<string | null>>;
-} | null>(null);
+type AuthorizeIntegration = Pick<
+ Integration,
+ "verified" | "projectId" | "userId"
+>;
+
+type AuthorizeWorkspaceContextValue = {
+ selectedWorkspace: WorkspaceProps | null;
+ setSelectedWorkspace: Dispatch<SetStateAction<WorkspaceProps | null>>;
+ workspaces: WorkspaceProps[] | undefined;
+ workspacesLoading: boolean;
+};
+
+const AuthorizeWorkspaceContext =
+ createContext<AuthorizeWorkspaceContextValue | 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,
+ integration,
}: {
children: ReactNode;
+ integration: AuthorizeIntegration;
}) {
- const [selectedWorkspace, setSelectedWorkspace] = useState<string | null>(
- null,
- );
+ const { data: session } = useSession();
+ const [selectedWorkspace, setSelectedWorkspace] =
+ useState<WorkspaceProps | null>(null);
+ const { workspaces, loading: workspacesLoading } = useWorkspaces();
+
+ const userId = session?.user?.id;
+ const defaultSlug = session?.user?.["defaultWorkspace"] || null;
+
+ const defaultWorkspace = useMemo(() => {
+ if (!workspaces || !userId) {
+ return null;
+ }
+
+ return getDefaultAuthorizeWorkspace({
+ workspaces,
+ defaultSlug,
+ integration,
+ userId,
+ });
+ }, [workspaces, defaultSlug, integration, userId]);
return (
<AuthorizeWorkspaceContext.Provider
- value={{ selectedWorkspace, setSelectedWorkspace }}
+ value={{
+ selectedWorkspace: selectedWorkspace ?? defaultWorkspace,
+ setSelectedWorkspace,
+ workspaces,
+ workspacesLoading,
+ }}
>
{children}
</AuthorizeWorkspaceContext.Provider>
@@ -45,3 +85,32 @@ export function useAuthorizeWorkspace() {
return context;
}
+
+function getDefaultAuthorizeWorkspace({
+ workspaces,
+ defaultSlug,
+ integration,
+ userId,
+}: {
+ workspaces: WorkspaceProps[];
+ defaultSlug: string | null;
+ integration: AuthorizeIntegration;
+ userId: string;
+}) {
+ const defaultWorkspace = defaultSlug
+ ? workspaces.find((workspace) => workspace.slug === defaultSlug)
+ : undefined;
+
+ if (
+ defaultWorkspace &&
+ canInstallOAuthApp({ integration, workspace: defaultWorkspace, userId })
+ ) {
+ return defaultWorkspace;
+ }
+
+ const firstAllowed = workspaces.find((workspace) =>
+ canInstallOAuthApp({ integration, workspace, userId }),
+ );
+
+ return firstAllowed ?? defaultWorkspace ?? null;
+}
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 5d1dfa8c54..f47b64a6f7 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
@@ -100,7 +100,7 @@ export default async function Authorize(props: {
</Callout>
)}
</div>
- <AuthorizeWorkspaceProvider>
+ <AuthorizeWorkspaceProvider integration={integration}>
<div className="flex flex-col space-y-3 px-4 py-6 sm:px-10">
<ScopesRequested scopes={requestParams.scope} />
</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 f57f2e7885..31be1e2ad7 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,19 +1,14 @@
"use client";
import { OAUTH_SCOPE_DESCRIPTIONS } from "@/lib/api/oauth/constants";
-import {
- consolidateScopes,
- getMissingScopesForRole,
-} from "@/lib/api/tokens/scopes";
-import useWorkspaces from "@/lib/swr/use-workspaces";
+import { getDisplayedScopesForRole } from "@/lib/api/tokens/scopes";
import { Tooltip } from "@dub/ui";
-import { TriangleWarning } from "@dub/ui/icons";
+import { LoadingSpinner, TriangleWarning } from "@dub/ui/icons";
import { cn } from "@dub/utils";
import { Check } from "lucide-react";
import { useAuthorizeWorkspace } from "./authorize-workspace-context";
export const ScopesRequested = ({ scopes }: { scopes: string[] }) => {
- const { workspaces } = useWorkspaces();
const { selectedWorkspace } = useAuthorizeWorkspace();
// Add default scopes if not present
@@ -21,48 +16,28 @@ export const ScopesRequested = ({ scopes }: { scopes: string[] }) => {
? 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(
- "Write",
- "<strong className='font-medium'>Write</strong>",
- );
+ if (!selectedWorkspace) {
+ return <ScopesRequestedPlaceholder />;
+ }
- scope.description = scope.description.replace(
- "Read",
- "<strong className='font-medium'>Read</strong>",
- );
+ const displayedScopes = getDisplayedScopesForRole({
+ scopes: requestedScopes,
+ role: selectedWorkspace.users[0].role,
});
return (
<>
<span className="text-neutral-600">Grant permissions:</span>
<ul className="text-md space-y-1">
- {scopeWithDescriptions.map((scope) => {
+ {displayedScopes.map((scope) => {
+ const catalog = OAUTH_SCOPE_DESCRIPTIONS[scope.scope];
+ // Denied write rows: "Write access to …" (not "Read and Write …")
+ // so granted read can sit beside them without sounding like write still includes read.
+ const description =
+ scope.missing && catalog.startsWith("Read and Write")
+ ? catalog.replace("Read and Write", "Write")
+ : catalog;
+
return (
<li className="flex items-center gap-2" key={scope.scope}>
{scope.missing ? (
@@ -70,9 +45,9 @@ export const ScopesRequested = ({ scopes }: { scopes: string[] }) => {
) : (
<Check className="size-4 shrink-0 text-green-500" />
)}
- <div
- className={cn(scope.missing && "text-neutral-500")}
- dangerouslySetInnerHTML={{ __html: scope.description }}
+ <ScopeDescription
+ description={description}
+ missing={scope.missing}
/>
</li>
);
@@ -82,6 +57,39 @@ export const ScopesRequested = ({ scopes }: { scopes: string[] }) => {
);
};
+const ScopesRequestedPlaceholder = () => {
+ return (
+ <>
+ <span className="text-neutral-600">Grant permissions:</span>
+ <div className="flex min-h-24 items-center justify-center">
+ <LoadingSpinner className="size-4" />
+ </div>
+ </>
+ );
+};
+
+const ScopeDescription = ({
+ description,
+ missing,
+}: {
+ description: string;
+ missing: boolean;
+}) => {
+ const parts = description.split(/(Read|Write)/g);
+
+ return (
+ <div className={cn(missing && "text-neutral-500")}>
+ {parts.map((part, index) =>
+ part === "Read" || part === "Write" ? (
+ <strong key={index}>{part}</strong>
+ ) : (
+ part
+ ),
+ )}
+ </div>
+ );
+};
+
const MissingScopeWarning = () => {
return (
<Tooltip content="Your role in this workspace doesn't include this permission, so it won't be granted.">
diff --git a/apps/web/lib/api/tokens/scopes.ts b/apps/web/lib/api/tokens/scopes.ts
index af7d1700dd..517a71addb 100644
--- a/apps/web/lib/api/tokens/scopes.ts
+++ b/apps/web/lib/api/tokens/scopes.ts
@@ -342,7 +342,7 @@ export const getGrantedScopesForRole = ({
);
};
-// Requested scopes the role cannot grant (consolidated for display)
+// Requested scopes the role cannot grant (raw intersection, same basis as grant)
export const getMissingScopesForRole = ({
scopes,
role,
@@ -350,7 +350,33 @@ export const getMissingScopesForRole = ({
scopes: string[];
role: WorkspaceRole;
}) => {
- return consolidateScopes(scopes).filter(
- (scope) => !isScopeGrantedForRole({ scope, role }),
+ return scopes.filter((scope) => !isScopeGrantedForRole({ scope, role }));
+};
+
+// Consent rows: consolidate granted and missing separately so a granted
+// `{resource}.read` is still shown when `{resource}.write` is denied.
+export const getDisplayedScopesForRole = ({
+ scopes,
+ role,
+}: {
+ scopes: string[];
+ role: WorkspaceRole;
+}) => {
+ const grantedScopes = consolidateScopes(
+ getGrantedScopesForRole({ scopes, role }),
+ );
+
+ const missingScopes = consolidateScopes(
+ getMissingScopesForRole({ scopes, role }),
+ );
+
+ const order = new Map(scopes.map((scope, index) => [scope, index]));
+
+ return [
+ ...grantedScopes.map((scope) => ({ scope, missing: false })),
+ ...missingScopes.map((scope) => ({ scope, missing: true })),
+ ].sort(
+ (a, b) =>
+ (order.get(a.scope) ?? Infinity) - (order.get(b.scope) ?? Infinity),
);
};
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
index ffdca69f93..5b301f53ed 100644
--- a/apps/web/tests/tokens/get-granted-scopes-for-role.test.ts
+++ b/apps/web/tests/tokens/get-granted-scopes-for-role.test.ts
@@ -1,5 +1,9 @@
import { OAUTH_SCOPES } from "@/lib/api/oauth/constants";
-import { getGrantedScopesForRole } from "@/lib/api/tokens/scopes";
+import {
+ getDisplayedScopesForRole,
+ getGrantedScopesForRole,
+ getMissingScopesForRole,
+} from "@/lib/api/tokens/scopes";
import { WorkspaceRole } from "@prisma/client";
import { describe, expect, test } from "vitest";
@@ -81,4 +85,46 @@ describe("getGrantedScopesForRole", () => {
}),
).toEqual([]);
});
+
+ test("member is granted domains.read and not domains.write when both are requested", () => {
+ const scopes = ["domains.read", "domains.write"];
+
+ expect(
+ getGrantedScopesForRole({
+ scopes,
+ role: "member",
+ }),
+ ).toEqual(["domains.read"]);
+
+ expect(
+ getMissingScopesForRole({
+ scopes,
+ role: "member",
+ }),
+ ).toEqual(["domains.write"]);
+
+ expect(
+ getDisplayedScopesForRole({
+ scopes,
+ role: "member",
+ }),
+ ).toEqual([
+ { scope: "domains.read", missing: false },
+ { scope: "domains.write", missing: true },
+ ]);
+ });
+
+ test("surfaces granted domains.read when domains.write is requested first", () => {
+ const scopes = ["domains.write", "domains.read"];
+
+ expect(
+ getDisplayedScopesForRole({
+ scopes,
+ role: "member",
+ }),
+ ).toEqual([
+ { scope: "domains.write", missing: true },
+ { scope: "domains.read", missing: false },
+ ]);
+ });
});