Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 25 additions & 2 deletions packages/app-store/_utils/oauth/decodeOAuthState.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,35 @@
import { createHmac, timingSafeEqual } from "node:crypto";
import process from "node:process";
import type { NextApiRequest } from "next";

import type { IntegrationOAuthCallbackState } from "../../types";

export function decodeOAuthState(req: NextApiRequest) {
const NONCE_EXEMPT_APPS = new Set(["stripe", "basecamp3", "dub", "webex", "tandem"]);

export function decodeOAuthState(req: NextApiRequest, appSlug?: string) {
if (typeof req.query.state !== "string") {
return undefined;
}
const state: IntegrationOAuthCallbackState = JSON.parse(req.query.state);

if (appSlug && NONCE_EXEMPT_APPS.has(appSlug)) {
return state;
}

if (!state.nonce || !state.nonceHash) {
return undefined;
}

const userId = req.session?.user?.id;
if (!userId || !process.env.NEXTAUTH_SECRET) {
return undefined;
}
const expected = createHmac("sha256", process.env.NEXTAUTH_SECRET)
.update(`${state.nonce}:${userId}`)
.digest();
const actual = Buffer.from(state.nonceHash, "hex");
if (expected.length !== actual.length || !timingSafeEqual(expected, actual)) {
return undefined;
}

return state;
}
11 changes: 10 additions & 1 deletion packages/app-store/_utils/oauth/encodeOAuthState.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { createHmac, randomUUID } from "node:crypto";
import process from "node:process";
import type { NextApiRequest } from "next";

import type { IntegrationOAuthCallbackState } from "../../types";

export function encodeOAuthState(req: NextApiRequest) {
Expand All @@ -8,5 +9,13 @@ export function encodeOAuthState(req: NextApiRequest) {
}
const state: IntegrationOAuthCallbackState = JSON.parse(req.query.state);

const userId = req.session?.user?.id;
if (userId && process.env.NEXTAUTH_SECRET) {
state.nonce = randomUUID();
state.nonceHash = createHmac("sha256", process.env.NEXTAUTH_SECRET)
.update(`${state.nonce}:${userId}`)
.digest("hex");
}

return JSON.stringify(state);
}
2 changes: 1 addition & 1 deletion packages/app-store/basecamp3/api/callback.ts
Original file line number Diff line number Diff line change
Expand Up @@ -87,7 +87,7 @@ export default async function handler(req: NextApiRequest, res: NextApiResponse)
},
});

const state = decodeOAuthState(req);
const state = decodeOAuthState(req, "basecamp3");

res.redirect(getInstalledAppPath({ variant: appConfig.variant, slug: appConfig.slug }));
}
2 changes: 1 addition & 1 deletion packages/app-store/dub/api/callback.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ import { dubAppKeysSchema } from "../lib/utils";
export default async function handler(req: NextApiRequest, res: NextApiResponse) {
const { code } = req.query;

const state = decodeOAuthState(req);
const state = decodeOAuthState(req, "dub");

if (typeof code !== "string") {
if (state?.onErrorReturnTo || state?.returnTo) {
Expand Down
34 changes: 11 additions & 23 deletions packages/app-store/stripepayment/api/callback.ts
Original file line number Diff line number Diff line change
@@ -1,36 +1,23 @@
import type { NextApiRequest, NextApiResponse } from "next";
import { stringify } from "node:querystring";

import { getSafeRedirectUrl } from "@calcom/lib/getSafeRedirectUrl";
import type { Prisma } from "@calcom/prisma/client";

import type { NextApiRequest, NextApiResponse } from "next";
import getInstalledAppPath from "../../_utils/getInstalledAppPath";
import createOAuthAppCredential from "../../_utils/oauth/createOAuthAppCredential";
import { decodeOAuthState } from "../../_utils/oauth/decodeOAuthState";
import type { StripeData } from "../lib/server";
import stripe from "../lib/server";

function getReturnToValueFromQueryState(req: NextApiRequest) {
let returnTo = "";
try {
returnTo = JSON.parse(`${req.query.state}`).returnTo;
} catch (error) {
console.info("No 'returnTo' in req.query.state");
}
return returnTo;
}

export default async function handler(req: NextApiRequest, res: NextApiResponse) {
const { code, error, error_description } = req.query;
const state = decodeOAuthState(req);
const state = decodeOAuthState(req, "stripe");

if (error) {
// User cancels flow
if (error === "access_denied") {
state?.onErrorReturnTo ? res.redirect(state.onErrorReturnTo) : res.redirect("/apps/installed/payment");
return res.redirect(getSafeRedirectUrl(state?.onErrorReturnTo) ?? "/apps/installed/payment");
}
const query = stringify({ error, error_description });
res.redirect(`/apps/installed?${query}`);
return;
return res.redirect(`/apps/installed?${query}`);
}

if (!req.session?.user?.id) {
Expand All @@ -43,9 +30,9 @@ export default async function handler(req: NextApiRequest, res: NextApiResponse)
});

const data: StripeData = { ...response, default_currency: "" };
if (response["stripe_user_id"]) {
const account = await stripe.accounts.retrieve(response["stripe_user_id"]);
data["default_currency"] = account.default_currency;
if (response.stripe_user_id) {
const account = await stripe.accounts.retrieve(response.stripe_user_id);
data.default_currency = account.default_currency;
}

await createOAuthAppCredential(
Expand All @@ -54,6 +41,7 @@ export default async function handler(req: NextApiRequest, res: NextApiResponse)
req
);

const returnTo = getReturnToValueFromQueryState(req);
res.redirect(returnTo || getInstalledAppPath({ variant: "payment", slug: "stripe" }));
res.redirect(
getSafeRedirectUrl(state?.returnTo) ?? getInstalledAppPath({ variant: "payment", slug: "stripe" })
);
}
2 changes: 1 addition & 1 deletion packages/app-store/tandemvideo/api/callback.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ export default async function handler(req: NextApiRequest, res: NextApiResponse)
}

const code = req.query.code as string;
const state = decodeOAuthState(req);
const state = decodeOAuthState(req, "tandem");

let clientId = "";
let clientSecret = "";
Expand Down
2 changes: 2 additions & 0 deletions packages/app-store/types.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,8 @@ export type IntegrationOAuthCallbackState = {
installGoogleVideo?: boolean;
teamId?: number;
defaultInstall?: boolean;
nonce?: string;
nonceHash?: string;
};

export type CredentialOwner = {
Expand Down
2 changes: 1 addition & 1 deletion packages/app-store/webex/api/callback.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ import { getWebexAppKeys } from "../lib/getWebexAppKeys";
export default async function handler(req: NextApiRequest, res: NextApiResponse) {
const { code } = req.query;
const { client_id, client_secret } = await getWebexAppKeys();
const state = decodeOAuthState(req);
const state = decodeOAuthState(req, "webex");

/** @link https://developer.webex.com/docs/integrations#getting-an-access-token **/

Expand Down