Files
calendar/packages/app-store/webex/api/callback.ts
T
Volnei MunhozGitHubClaude Opus 4.6Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
14c151be76 fix: add CSRF protection to OAuth callback via HMAC-signed nonce (#28083)
* fix: add CSRF protection to OAuth callback via HMAC-signed nonce

The OAuth state parameter was used only for passing application data
(returnTo, teamId) with no cryptographic binding to the user session.
An attacker could authorize their own account on a provider, capture the
authorization code, and trick a logged-in user into visiting the callback
URL to link the attacker's account to the victim's Cal.com profile.

Changes:
- encodeOAuthState: generate a random nonce and HMAC-sign it with
  NEXTAUTH_SECRET + userId, injecting both into the OAuth state
- decodeOAuthState: verify the HMAC on callback using timingSafeEqual;
  skip verification when nonce is absent (backwards compatible with apps
  that don't yet use encodeOAuthState)
- Stripe callback: replace raw state.returnTo redirect with
  getSafeRedirectUrl to prevent open redirect, remove redundant
  getReturnToValueFromQueryState, add missing return on access_denied

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* fix: make CSRF nonce verification mandatory with allowlist for exempt apps

Makes nonce/HMAC verification mandatory by default in decodeOAuthState,
preventing attackers from bypassing CSRF protection by omitting nonce
fields from the state parameter.

Apps not yet migrated to encodeOAuthState (stripe, basecamp3, dub,
webex, tandem) are explicitly allowlisted and pass their slug to
decodeOAuthState to skip verification.

Addresses review feedback (identified by cubic) about the conditional
check being trivially bypassable.

Co-Authored-By: unknown <>

---------

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
2026-02-20 10:35:01 +00:00

92 lines
2.9 KiB
TypeScript

import type { NextApiRequest, NextApiResponse } from "next";
import { WEBAPP_URL_FOR_OAUTH } from "@calcom/lib/constants";
import { getSafeRedirectUrl } from "@calcom/lib/getSafeRedirectUrl";
import prisma from "@calcom/prisma";
import getInstalledAppPath from "../../_utils/getInstalledAppPath";
import createOAuthAppCredential from "../../_utils/oauth/createOAuthAppCredential";
import { decodeOAuthState } from "../../_utils/oauth/decodeOAuthState";
import config from "../config.json";
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, "webex");
/** @link https://developer.webex.com/docs/integrations#getting-an-access-token **/
const redirectUri = encodeURI(`${WEBAPP_URL_FOR_OAUTH}/api/integrations/${config.slug}/callback`);
const params = new URLSearchParams([
["grant_type", "authorization_code"],
["client_id", client_id],
["client_secret", client_secret],
["code", code as string],
["redirect_uri", redirectUri],
]);
const options = {
method: "POST",
headers: {
"Content-type": "application/x-www-form-urlencoded",
},
body: params,
};
const result = await fetch("https://webexapis.com/v1/access_token", options);
if (result.status !== 200) {
let errorMessage = "Something is wrong with Webex API";
try {
const responseBody = await result.json();
errorMessage = responseBody.message;
} catch (e) {}
res.status(400).json({ message: errorMessage });
return;
}
const responseBody = await result.json();
if (responseBody.message) {
res.status(400).json({ message: responseBody.message });
return;
}
responseBody.expiry_date = Math.round(Date.now() + responseBody.expires_in * 1000);
delete responseBody.expires_in;
const userId = req.session?.user.id;
if (!userId) {
return res.status(404).json({ message: "No user found" });
}
/**
* With this we take care of no duplicate webex key for a single user
* when creating a video room we only do findFirst so the if they have more than 1
* others get ignored
* */
const existingCredentialWebexVideo = await prisma.credential.findMany({
select: {
id: true,
},
where: {
type: config.type,
userId: req.session?.user.id,
appId: config.slug,
},
});
// Making sure we only delete webex_video
const credentialIdsToDelete = existingCredentialWebexVideo.map((item) => item.id);
if (credentialIdsToDelete.length > 0) {
await prisma.credential.deleteMany({ where: { id: { in: credentialIdsToDelete }, userId } });
}
await createOAuthAppCredential({ appId: config.slug, type: config.type }, responseBody, req);
res.redirect(
getSafeRedirectUrl(state?.returnTo) ?? getInstalledAppPath({ variant: config.variant, slug: config.slug })
);
}