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.

chore: Refactor OAuth authorize route to handle PKCE flow and generate code challenge hash

Kiran K4f3c77c42436
diff --git a/apps/web/app/api/oauth/authorize/route.ts b/apps/web/app/api/oauth/authorize/route.ts
index 773da6cd13..c1d33c34fb 100644
--- a/apps/web/app/api/oauth/authorize/route.ts
+++ b/apps/web/app/api/oauth/authorize/route.ts
@@ -42,9 +42,9 @@ export const POST = withWorkspace(async ({ session, req, workspace }) => {
userId: session.user.id,
scopes: scope.join(" "),
code: nanoid(OAUTH_CODE_LENGTH),
- codeChallenge,
- codeChallengeMethod,
expiresAt: new Date(Date.now() + OAUTH_CODE_LIFETIME * 1000),
+ ...(codeChallenge && { codeChallenge }),
+ ...(codeChallengeMethod && { codeChallengeMethod }),
},
});
diff --git a/apps/web/app/api/oauth/token/create-token.ts b/apps/web/app/api/oauth/token/create-token.ts
deleted file mode 100644
index e69de29bb2..0000000000
diff --git a/apps/web/app/api/oauth/token/exchange-code-for-token.ts b/apps/web/app/api/oauth/token/exchange-code-for-token.ts
index 70cc9526fe..4f40ce2b76 100644
--- a/apps/web/app/api/oauth/token/exchange-code-for-token.ts
+++ b/apps/web/app/api/oauth/token/exchange-code-for-token.ts
@@ -7,7 +7,8 @@ import {
OAUTH_REFRESH_TOKEN_LIFETIME,
OAUTH_REFRESH_TOKEN_PREFIX,
} from "@/lib/api/oauth/constants";
-import { getAuthTokenOrThrow, hashToken } from "@/lib/auth";
+import { generateCodeChallengeHash } from "@/lib/api/oauth/utils";
+import { hashToken } from "@/lib/auth";
import { prisma } from "@/lib/prisma";
import z from "@/lib/zod";
import { authCodeExchangeSchema } from "@/lib/zod/schemas/oauth";
@@ -19,34 +20,44 @@ export const exchangeAuthCodeForToken = async (
req: NextRequest,
params: z.infer<typeof authCodeExchangeSchema>,
) => {
- const { client_id, client_secret, code, redirect_uri: redirectUri } = params;
+ const {
+ code,
+ redirect_uri: redirectUri,
+ code_verifier: codeVerifier,
+ } = params;
- let clientId: string | undefined = client_id;
- let clientSecret: string | undefined = client_secret;
+ let { client_id: clientId, client_secret: clientSecret } = params;
+ const isPKCE = codeVerifier !== undefined;
// If no client_id or client_secret is provided in the request body
- // then it should be provided in the Authorization header as Basic Auth
- if (!clientId && !clientSecret) {
- const token = getAuthTokenOrThrow(req, "Basic");
- const splits = Buffer.from(token, "base64").toString("utf-8").split(":");
-
- if (splits.length > 1) {
- clientId = splits[0];
- clientSecret = splits[1];
+ // then it should be provided in the Authorization header as Basic Auth for non-PKCE
+ if (!clientId && !clientSecret && !isPKCE) {
+ const authorizationHeader = req.headers.get("Authorization") || "";
+ const [type, token] = authorizationHeader.split(" ");
+
+ if (type === "Basic") {
+ const splits = Buffer.from(token, "base64").toString("utf-8").split(":");
+
+ if (splits.length > 1) {
+ clientId = splits[0];
+ clientSecret = splits[1];
+ }
}
}
- if (!clientId || !clientSecret) {
+ if (!clientId || (!clientSecret && !isPKCE)) {
throw new DubApiError({
code: "unauthorized",
- message: "Invalid client credentials",
+ message: "Missing client credentials",
});
}
const app = await prisma.oAuthApp.findFirst({
where: {
clientId,
- clientSecretHashed: await hashToken(clientSecret),
+ ...(clientSecret && {
+ clientSecretHashed: await hashToken(clientSecret),
+ }),
},
select: {
name: true,
@@ -71,6 +82,8 @@ export const exchangeAuthCodeForToken = async (
scopes: true,
redirectUri: true,
expiresAt: true,
+ codeChallenge: true,
+ codeChallengeMethod: true,
},
});
@@ -81,6 +94,21 @@ export const exchangeAuthCodeForToken = async (
});
}
+ if (isPKCE) {
+ const codeChallenge =
+ accessCode.codeChallengeMethod === "S256"
+ ? await generateCodeChallengeHash(codeVerifier)
+ : codeVerifier;
+
+ if (accessCode.codeChallenge != codeChallenge) {
+ throw new DubApiError({
+ code: "unauthorized",
+ message: "invalid_grant",
+ });
+ }
+ }
+
+ // If the code has expired, delete it and throw an error
if (accessCode.expiresAt < new Date()) {
await prisma.oAuthCode.delete({
where: {
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 da281c1276..0dbac0e3fa 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
@@ -19,6 +19,8 @@ export const AuthorizeForm = ({
response_type,
state,
scope,
+ code_challenge,
+ code_challenge_method,
}: AuthorizeFormProps) => {
const { workspaces } = useWorkspaces();
const [submitting, setSubmitting] = useState(false);
@@ -76,6 +78,12 @@ export const AuthorizeForm = ({
<input type="hidden" name="response_type" value={response_type} />
<input type="hidden" name="state" value={state} />
<input type="hidden" name="scope" value={scope.join(",")} />
+ <input type="hidden" name="code_challenge" value={code_challenge} />
+ <input
+ type="hidden"
+ name="code_challenge_method"
+ value={code_challenge_method}
+ />
<p className="text-sm text-gray-500">
Select a workspace to grant API access to
</p>
diff --git a/apps/web/lib/api/oauth/actions.ts b/apps/web/lib/api/oauth/actions.ts
index 588569ef45..8a63c8aedf 100644
--- a/apps/web/lib/api/oauth/actions.ts
+++ b/apps/web/lib/api/oauth/actions.ts
@@ -15,12 +15,7 @@ export const vaidateAuthorizeRequest = async (params: any) => {
};
}
- const requestParams = request.data;
- const {
- client_id: clientId,
- redirect_uri: redirectUri,
- scope,
- } = requestParams;
+ const { client_id: clientId, redirect_uri: redirectUri } = request.data;
const oAuthApp = await prisma.oAuthApp.findFirst({
where: {
@@ -40,11 +35,8 @@ export const vaidateAuthorizeRequest = async (params: any) => {
};
}
- // TODO:
- // Validate scope requested are valid
-
return {
oAuthApp,
- requestParams,
+ requestParams: request.data,
};
};
diff --git a/apps/web/lib/api/oauth/utils.ts b/apps/web/lib/api/oauth/utils.ts
new file mode 100644
index 0000000000..13c1426c6e
--- /dev/null
+++ b/apps/web/lib/api/oauth/utils.ts
@@ -0,0 +1,14 @@
+export const generateCodeChallengeHash = async (codeVerifier: string) => {
+ const encoder = new TextEncoder();
+ const data = encoder.encode(codeVerifier);
+ const hashBuffer = await crypto.subtle.digest("SHA-256", data);
+ const hashArray = Array.from(new Uint8Array(hashBuffer));
+ const base64url = hashArray.map((byte) => String.fromCharCode(byte)).join("");
+ const hashBase64 = Buffer.from(base64url, "binary")
+ .toString("base64")
+ .replace(/\+/g, "-")
+ .replace(/\//g, "_")
+ .replace(/=+$/, "");
+
+ return hashBase64;
+};
diff --git a/apps/web/lib/zod/schemas/oauth.ts b/apps/web/lib/zod/schemas/oauth.ts
index b6436132c8..7d666cc27c 100644
--- a/apps/web/lib/zod/schemas/oauth.ts
+++ b/apps/web/lib/zod/schemas/oauth.ts
@@ -72,7 +72,7 @@ export const authorizeRequestSchema = z.object({
// PKCE flow
code_challenge: z.string().max(255).optional(),
- code_challenge_method: z.string().optional().default("plain"),
+ code_challenge_method: z.string().optional(),
});
// Schema for OAuth2.0 code exchange request
@@ -82,6 +82,9 @@ export const authCodeExchangeSchema = z.object({
client_secret: z.string().optional(),
code: z.string().min(1, "Missing code"),
redirect_uri: z.string().url({ message: "redirect_uri must be a valid URL" }),
+
+ // PKCE flow
+ code_verifier: z.string().max(255).optional(),
});
// Schema for OAuth2.0 token refresh request