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.

fix: Bitly OAuth callback does not perform authentication

Kiran Kf62eab492047
diff --git a/apps/web/.env.example b/apps/web/.env.example
index 0dbef05666..a3548cc208 100644
--- a/apps/web/.env.example
+++ b/apps/web/.env.example
@@ -84,7 +84,7 @@ EDGE_CONFIG_ID=
# Bitly Importer: https://dub.co/blog/migration-assistants
# Apply for an API key here: https://dev.bitly.com/
-NEXT_PUBLIC_BITLY_CLIENT_ID=
+BITLY_CLIENT_ID=
BITLY_CLIENT_SECRET=
# Used for Custom Link Previews feature
diff --git a/apps/web/app/(ee)/api/hubspot/callback/route.ts b/apps/web/app/(ee)/api/hubspot/callback/route.ts
index 81489795da..63437ad362 100644
--- a/apps/web/app/(ee)/api/hubspot/callback/route.ts
+++ b/apps/web/app/(ee)/api/hubspot/callback/route.ts
@@ -37,7 +37,7 @@ export const GET = async (req: Request) => {
}
const { token, contextId: workspaceId } =
- await hubSpotOAuthProvider.exchangeCodeForToken(req);
+ await hubSpotOAuthProvider.exchangeCodeForToken<string>(req);
workspace = await prisma.project.findUniqueOrThrow({
where: {
diff --git a/apps/web/app/(ee)/api/paypal/callback/route.ts b/apps/web/app/(ee)/api/paypal/callback/route.ts
index 402cf075d4..d127f2ce38 100644
--- a/apps/web/app/(ee)/api/paypal/callback/route.ts
+++ b/apps/web/app/(ee)/api/paypal/callback/route.ts
@@ -33,7 +33,7 @@ export const GET = async (req: Request) => {
}
const { token, contextId } =
- await paypalOAuthProvider.exchangeCodeForToken(req);
+ await paypalOAuthProvider.exchangeCodeForToken<string>(req);
await prisma.user.findUniqueOrThrow({
where: {
diff --git a/apps/web/app/api/callback/bitly/route.ts b/apps/web/app/api/callback/bitly/route.ts
index ed7e56ddf6..b90622554b 100644
--- a/apps/web/app/api/callback/bitly/route.ts
+++ b/apps/web/app/api/callback/bitly/route.ts
@@ -1,37 +1,30 @@
-import { normalizeWorkspaceId } from "@/lib/api/workspaces/workspace-id";
+import { DubApiError } from "@/lib/api/errors";
+import { getSession } from "@/lib/auth";
+import { bitlyOAuthProvider } from "@/lib/integrations/bitly/oauth";
import { redis } from "@/lib/upstash";
import { prisma } from "@dub/prisma";
-import { APP_DOMAIN, APP_DOMAIN_WITH_NGROK } from "@dub/utils";
+import { APP_DOMAIN } from "@dub/utils";
import { NextResponse } from "next/server";
+// GET /api/callback/bitly – bitly OAuth callback
export async function GET(req: Request) {
- const { searchParams } = new URL(req.url);
+ try {
+ const session = await getSession();
- // get code and workspace id from query params
- const code = searchParams.get("code") as string;
- const state = searchParams.get("state") as string;
+ if (!session?.user.id) {
+ throw new DubApiError({
+ code: "unauthorized",
+ message: "Unauthorized.",
+ });
+ }
- if (!code || !state) {
- return NextResponse.redirect(APP_DOMAIN);
- }
-
- try {
- const stateJSON = JSON.parse(state);
- let { workspaceId, folderId } = stateJSON;
-
- workspaceId = normalizeWorkspaceId(workspaceId);
-
- // get access token from bitly
- const response = await fetch(
- "https://api-ssl.bitly.com/oauth/access_token",
- {
- method: "POST",
- headers: {
- "Content-Type": "application/x-www-form-urlencoded",
- },
- body: `client_id=${process.env.NEXT_PUBLIC_BITLY_CLIENT_ID}&client_secret=${process.env.BITLY_CLIENT_SECRET}&code=${code}&redirect_uri=${APP_DOMAIN_WITH_NGROK}/api/callback/bitly`,
- },
- ).then((r) => r.text());
+ const {
+ token: response,
+ contextId: { workspaceId, folderId },
+ } = await bitlyOAuthProvider.exchangeCodeForToken<{
+ workspaceId: string;
+ folderId?: string;
+ }>(req);
if (!response || response.includes("error")) {
return NextResponse.redirect(APP_DOMAIN);
@@ -49,15 +42,24 @@ export async function GET(req: Request) {
slug: true,
},
}),
+
// store access token in redis
redis.set(`import:bitly:${workspaceId}`, params.get("access_token")),
]);
- // redirect to workspace page with import query param
- return NextResponse.redirect(
- `${APP_DOMAIN}${workspace ? `/${workspace.slug}?import=bitly${folderId ? `&folderId=${folderId}` : ""}` : ""}`,
- );
+ const queryParams = new URLSearchParams({
+ import: "bitly",
+ ...(folderId ? { folderId } : {}),
+ });
+
+ const redirectUrl = workspace
+ ? `${APP_DOMAIN}/${workspace.slug}?${queryParams.toString()}`
+ : APP_DOMAIN;
+
+ return NextResponse.redirect(redirectUrl);
} catch (error) {
+ console.error("[/api/callback/bitly]", error);
+
return NextResponse.redirect(APP_DOMAIN);
}
}
diff --git a/apps/web/app/api/slack/callback/route.ts b/apps/web/app/api/slack/callback/route.ts
index 004058fb90..44dbb76f0b 100644
--- a/apps/web/app/api/slack/callback/route.ts
+++ b/apps/web/app/api/slack/callback/route.ts
@@ -28,7 +28,7 @@ export const GET = async (req: Request) => {
}
const { token, contextId: workspaceId } =
- await slackOAuthProvider.exchangeCodeForToken(req);
+ await slackOAuthProvider.exchangeCodeForToken<string>(req);
workspace = await prisma.project.findUniqueOrThrow({
where: {
diff --git a/apps/web/lib/actions/create-oauth-url.ts b/apps/web/lib/actions/create-oauth-url.ts
new file mode 100644
index 0000000000..b1c6c76b97
--- /dev/null
+++ b/apps/web/lib/actions/create-oauth-url.ts
@@ -0,0 +1,38 @@
+"use server";
+
+import z from "zod";
+import { verifyFolderAccess } from "../folder/permissions";
+import { bitlyOAuthProvider } from "../integrations/bitly/oauth";
+import { authActionClient } from "./safe-action";
+
+const schema = z.object({
+ provider: z.literal("bitly"),
+ workspaceId: z.string(),
+ folderId: z.string().optional(),
+});
+
+// Generate the OAuth sigin URL based on the provider
+export const createOAuthUrl = authActionClient
+ .schema(schema)
+ .action(async ({ ctx, parsedInput }) => {
+ const { workspace, user } = ctx;
+ const { provider, folderId } = parsedInput;
+
+ if (folderId) {
+ await verifyFolderAccess({
+ workspace,
+ userId: user.id,
+ folderId,
+ requiredPermission: "folders.links.write",
+ });
+ }
+
+ if (provider === "bitly") {
+ return {
+ url: await bitlyOAuthProvider.generateAuthUrl({
+ workspaceId: workspace.id,
+ ...(folderId ? { folderId } : {}),
+ }),
+ };
+ }
+ });
diff --git a/apps/web/lib/integrations/bitly/oauth.ts b/apps/web/lib/integrations/bitly/oauth.ts
new file mode 100644
index 0000000000..3bab799505
--- /dev/null
+++ b/apps/web/lib/integrations/bitly/oauth.ts
@@ -0,0 +1,17 @@
+import { APP_DOMAIN_WITH_NGROK } from "@dub/utils";
+import { z } from "zod";
+import { OAuthProvider } from "../oauth-provider";
+
+export const bitlyOAuthProvider = new OAuthProvider({
+ name: "Bitly",
+ clientId: process.env.BITLY_CLIENT_ID!,
+ clientSecret: process.env.BITLY_CLIENT_SECRET!,
+ authUrl: "https://bitly.com/oauth/authorize",
+ tokenUrl: "https://api-ssl.bitly.com/oauth/access_token",
+ redirectUri: `${APP_DOMAIN_WITH_NGROK}/api/callback/bitly`,
+ redisStatePrefix: "bitly:oauth:state",
+ tokenSchema: z.string(),
+ bodyFormat: "form",
+ authorizationMethod: "body",
+ responseFormat: "text",
+});
diff --git a/apps/web/lib/integrations/oauth-provider.ts b/apps/web/lib/integrations/oauth-provider.ts
index e547aacfbc..6c14a9433b 100644
--- a/apps/web/lib/integrations/oauth-provider.ts
+++ b/apps/web/lib/integrations/oauth-provider.ts
@@ -10,10 +10,11 @@ export interface OAuthProviderConfig {
authUrl: string;
tokenUrl: string;
redirectUri: string;
- scopes: string;
+ scopes?: string;
redisStatePrefix: string;
tokenSchema: z.ZodSchema;
bodyFormat: "form" | "json";
+ responseFormat?: "json" | "text";
authorizationMethod: "header" | "body";
}
@@ -26,7 +27,7 @@ export class OAuthProvider<T extends z.ZodSchema> {
constructor(private provider: OAuthProviderConfig) {}
// Generate the authorization URL for the OAuth provider
- async generateAuthUrl(contextId: string) {
+ async generateAuthUrl(contextId: string | Record<string, string>) {
const state = nanoid(16);
await redis.set(`${this.provider.redisStatePrefix}:${state}`, contextId, {
ex: 30 * 60,
@@ -35,7 +36,7 @@ export class OAuthProvider<T extends z.ZodSchema> {
const searchParams = new URLSearchParams({
client_id: this.provider.clientId,
redirect_uri: this.provider.redirectUri,
- scope: this.provider.scopes,
+ ...(this.provider.scopes ? { scope: this.provider.scopes } : {}),
response_type: "code",
state,
});
@@ -44,15 +45,15 @@ export class OAuthProvider<T extends z.ZodSchema> {
}
// Exchange the authorization code for a token
- async exchangeCodeForToken(request: Request): Promise<{
- contextId: string;
+ async exchangeCodeForToken<K>(request: Request): Promise<{
+ contextId: K;
token: z.infer<T>;
}> {
const { code, state } = codeExchangeSchema.parse(
getSearchParams(request.url),
);
- const contextId = await redis.getdel<string>(
+ const contextId = await redis.get<K>(
`${this.provider.redisStatePrefix}:${state}`,
);
@@ -119,7 +120,10 @@ export class OAuthProvider<T extends z.ZodSchema> {
body,
});
- const data = await response.json();
+ const responseFormat = this.provider.responseFormat || "json";
+
+ const data =
+ responseFormat === "json" ? await response.json() : await response.text();
if (!response.ok) {
console.error(`[${this.provider.name}] exchangeCodeForToken`, data);
@@ -152,16 +156,19 @@ export class OAuthProvider<T extends z.ZodSchema> {
}),
});
- const result = await response.json();
+ const responseFormat = this.provider.responseFormat || "json";
+
+ const data =
+ responseFormat === "json" ? await response.json() : await response.text();
if (!response.ok) {
- console.error(`[${this.provider.name}] refreshToken`, result);
+ console.error(`[${this.provider.name}] refreshToken`, data);
throw new Error(
`[${this.provider.name}] Failed to refresh the access token. Please try again.`,
);
}
- return this.provider.tokenSchema.parse(result);
+ return this.provider.tokenSchema.parse(data);
}
}
diff --git a/apps/web/ui/modals/import-bitly-modal.tsx b/apps/web/ui/modals/import-bitly-modal.tsx
index a6b7db4be5..e9205e45cb 100644
--- a/apps/web/ui/modals/import-bitly-modal.tsx
+++ b/apps/web/ui/modals/import-bitly-modal.tsx
@@ -1,3 +1,4 @@
+import { createOAuthUrl } from "@/lib/actions/create-oauth-url";
import useCurrentFolderId from "@/lib/swr/use-current-folder-id";
import useWorkspace from "@/lib/swr/use-workspace";
import { BitlyGroupProps } from "@/lib/types";
@@ -10,8 +11,9 @@ import {
Tooltip,
useRouterStuff,
} from "@dub/ui";
-import { APP_DOMAIN_WITH_NGROK, fetcher } from "@dub/utils";
+import { fetcher } from "@dub/utils";
import { ArrowRight, ServerOff } from "lucide-react";
+import { useAction } from "next-safe-action/hooks";
import { useRouter, useSearchParams } from "next/navigation";
import {
Dispatch,
@@ -35,8 +37,22 @@ function ImportBitlyModal({
const searchParams = useSearchParams();
const { folderId } = useCurrentFolderId();
const { id: workspaceId } = useWorkspace();
+ const [importing, setImporting] = useState(false);
+ const { queryParams } = useRouterStuff();
+
+ const { executeAsync, isPending } = useAction(createOAuthUrl, {
+ onSuccess: ({ data }) => {
+ if (!data?.url) {
+ toast.error("Failed to generate OAuth URL.");
+ return;
+ }
- const [redirecting, setRedirecting] = useState(false);
+ router.push(data.url);
+ },
+ onError: ({ error }) => {
+ toast.error(error.serverError || "Failed to generate OAuth URL.");
+ },
+ });
const {
data: groups,
@@ -64,8 +80,6 @@ function ImportBitlyModal({
>([]);
const [selectedGroupTags, setSelectedGroupTags] = useState<string[]>([]);
- const [importing, setImporting] = useState(false);
-
useEffect(() => {
if (searchParams?.get("import") === "bitly") {
mutate();
@@ -75,18 +89,21 @@ function ImportBitlyModal({
}
}, [searchParams]);
- const bitlyOAuthURL = `https://bitly.com/oauth/authorize?client_id=${process.env.NEXT_PUBLIC_BITLY_CLIENT_ID}&redirect_uri=${APP_DOMAIN_WITH_NGROK}/api/callback/bitly&state=${JSON.stringify(
- {
- workspaceId,
- ...(folderId ? { folderId } : {}),
- },
- )}`;
-
const isSelected = (domain: string) => {
return selectedDomains.find((d) => d.domain === domain) ? true : false;
};
- const { queryParams } = useRouterStuff();
+ const signInWithBitly = async () => {
+ if (!workspaceId) {
+ return;
+ }
+
+ await executeAsync({
+ provider: "bitly",
+ workspaceId,
+ ...(folderId ? { folderId } : {}),
+ });
+ };
return (
<Modal
@@ -235,19 +252,21 @@ function ImportBitlyModal({
loading={importing}
disabled={selectedDomains.length === 0}
/>
- <a
- href={bitlyOAuthURL}
- className="text-center text-xs text-neutral-500 underline underline-offset-4 transition-colors hover:text-neutral-800"
+ <button
+ type="button"
+ onClick={signInWithBitly}
+ disabled={isPending}
+ className="text-center text-xs text-neutral-500 underline underline-offset-4 transition-colors hover:text-neutral-800 disabled:cursor-not-allowed disabled:opacity-50"
>
Sign in to a different Bitly account?
- </a>
+ </button>
</form>
) : (
<div className="flex flex-col space-y-2">
<Button
text="Sign in with Bitly"
variant="secondary"
- loading={redirecting}
+ loading={isPending}
icon={
<img
src="https://assets.dub.co/misc/icons/bitly.svg"
@@ -255,10 +274,7 @@ function ImportBitlyModal({
className="h-5 w-5 rounded-full border border-neutral-200"
/>
}
- onClick={() => {
- setRedirecting(true);
- router.push(bitlyOAuthURL);
- }}
+ onClick={signInWithBitly}
/>
<a
href="https://dub.co/help/article/migrating-from-bitly"