OAuth credential sync and app integration enhancements
Tier 2 medium typescript · local · real merged PR from calcom/cal.com #11059
Ground-truth defects
The parseRefreshTokenResponse function incorrectly sets refresh_token to the hardcoded string 'refresh_token' when it's missing from the OAuth refresh token response. This invalidates the token, breaking subsequent token refreshes and causing authentication failures.
Both computed keys in minimumTokenResponseSchema stringify to the identical literal "[object Object]", so the schema collapses to {access_token} and silently strips every other field (expiry, refresh_token) from synced token-refresh responses.
parseRefreshTokenResponse returns a Zod safeParse result ({ success, data, error }), not the credential key object. Persisting that as key stores the wrapper instead of the token payload; we should store the parsed data or use schema parse.
When APP_CREDENTIAL_SHARING_ENABLED and CALCOM_CREDENTIAL_SYNC_ENDPOINT are set, the refreshFunction helper returns the fetch Response, but several callers (for example GoogleCalendarService.refreshAccessToken expecting res.data, and HubspotCalendarService.refreshAccessToken expecting a HubspotToken) assume it returns the integration-specific token object. That mismatch will cause runtime errors in the sync-enabled path unless the return type or those call sites are adjusted.
When the sync endpoint path is used, res is a fetch Response and has no .data; res?.data will be undefined and token.access_token will throw at runtime. This relies on a consistent return shape from refreshOAuthTokens, which isn’t guaranteed currently.
The new line `if (response.statusText !== "OK")` in salesforce CalendarService.getClient checks statusText, but Node's global fetch (undici) returns an empty statusText for HTTP/2 responses served by login.salesforce.com, so a successful 200 yields `"" !== "OK"` and throws HttpError on every Salesforce client construction.
In zoho-bigin's CalendarService.ts the new refreshOAuthTokens call passes credentialId (credential.id) as the userId arg, so in credential-sharing mode it posts calcomUserId=<credential row id> to the sync endpoint instead of credential.userId, fetching the wrong/non-existent user's tokens; every other adapter passes credential.userId.
The change under review
diff (truncated — full diff)
@@ -230,6 +230,19 @@ AUTH_BEARER_TOKEN_VERCEL= E2E_TEST_APPLE_CALENDAR_EMAIL="" E2E_TEST_APPLE_CALENDAR_PASSWORD="" +# - APP CREDENTIAL SYNC *********************************************************************************** +# Used for self-hosters that are implementing Cal.com into their applications that already have certain integrations +# Under settings/admin/apps ensure that all app secrets are set the same as the parent application +# You can use: `openssl rand -base64 32` to generate one +CALCOM_WEBHOOK_SECRET="" +# This is the header name that will be used to verify the webhook secret. Should be in lowercase +CALCOM_WEBHOOK_HEADER_NAME="calcom-webhook-secret" +CALCOM_CREDENTIAL_SYNC_ENDPOINT="" +# Key should match on Cal.com and your application +# must be 32 bytes for AES256 encryption algorithm +# You can use: `openssl rand -base64 24` to generate one +CALCOM_APP_CREDENTIAL_ENCRYPTION_KEY="" + # - OIDC E2E TEST ******************************************************************************************* # Ensure this ADMIN EMAIL is present in the SAML_ADMINS list @@ -243,4 +256,4 @@ E2E_TEST_OIDC_PROVIDER_DOMAIN= E2E_TEST_OIDC_USER_EMAIL= E2E_TEST_OIDC_USER_PASSWORD= -# *********************************************************************************************************** \ No newline at end of file +# *********************************************************************************************************** new file mode 100644 @@ -0,0 +1,93 @@ +import type { NextApiRequest, NextApiResponse } from "next"; +import z from "zod"; + +import { appStoreMetadata } from "@calcom/app-store/appStoreMetaData"; +import { APP_CREDENTIAL_SHARING_ENABLED } from "@calcom/lib/constants"; +import { symmetricDecrypt } from "@calcom/lib/crypto"; +import prisma from "@calcom/prisma"; + +const appCredentialWebhookRequestBodySchema = z.object({ + // UserId of the cal.com user + userId: z.number().int(), + appSlug: z.string(), + // Keys should be AES256 encrypted with the CALCOM_APP_CREDENTIAL_ENCRYPTION_KEY + keys: z.string(), +}); +/** */ +export default async function handler(req: NextApiRequest, res: NextApiResponse) { + // Check that credential sharing is enabled + if (!APP_CREDENTIAL_SHARING_ENABLED) { + return res.status(403).json({ message: "Credential sharing is not enabled" }); + } + + // Check that the webhook secret matches + if ( + req.headers[process.env.CALCOM_WEBHOOK_HEADER_NAME || "calcom-webhook-secret"] !== + process.env.CALCOM_WEBHOOK_SECRET + ) { + return res.status(403).json({ message: "Invalid webhook secret" }); + } + + const reqBody = appCredentialWebhookRequestBodySchema.parse(req.body); + + // Check that the user exists + const user = await prisma.user.findUnique({ where: { id: reqBody.userId } }); + + if (!user) { + return res.status(404).json({ message: "User not found" }); + } + + const app = await prisma.app.findUnique({ + where: { slug: reqBody.appSlug }, + select: { slug: true }, + }); + + if (!app) { + return res.status(404).json({ message: "App not found" }); + } + + // Search for the app's slug and type + const appMetadata = appStoreMetadata[app.slug as keyof typeof appStoreMetadata]; + + if (!appMetadata) { + return res.status(404).json({ message: "App not found. Ensure that you have the correct app slug" }); + } + + // Decrypt the keys + const keys = JSON.parse( + symmetricDecrypt(reqBody.keys, process.env.CALCOM_APP_CREDENTIAL_ENCRYPTION_KEY || "") + ); + + // Can't use prisma upsert as we don't know the id of the credential + const appCredential = await prisma.credential.findFirst({ + where: { + userId: reqBody.userId, + appId: appMetadata.slug, + }, + select: { + id: true, + }, + }); + + if (appCredential) { + await prisma.credential.update({ + where: { + id: appCredential.id, + }, + data: { + key: keys, + }, + }); + return res.status(200).json({ message: `Credentials updated for userId: ${reqBody.userId}` }); + } else { + await prisma.credential.create({ + data: { + key: keys, + userId: reqBody.userId, + appId: appMetadata.slug, + type: appMetadata.type, + }, + }); + return res.status(200).json({ message: `Credentials created for userId: ${reqBody.userId}` }); + } +} similarity index 92% rename from packages/app-store/_utils/createOAuthAppCredential.ts rename to packages/app-store/_utils/oauth/createOAuthAppCredential.ts @@ -3,8 +3,8 @@ import type { NextApiRequest } from "next"; import { HttpError } from "@calcom/lib/http-error"; import prisma from "@calcom/prisma"; -import { decodeOAuthState } from "./decodeOAuthState"; -import { throwIfNotHaveAdminAccessToTeam } from "./throwIfNotHaveAdminAccessToTeam"; +import { decodeOAuthState } from "../oauth/decodeOAuthState"; +import { throwIfNotHaveAdminAccessToTeam } from "../throwIfNotHaveAdminAccessToTeam"; /** * This function is used to create app credentials for either a user or a team similarity index 80% rename from packages/app-store/_utils/decodeOAuthState.ts rename to packages/app-store/_utils/oauth/decodeOAuthState.ts @@ -1,6 +1,6 @@ import type { NextApiRequest } from "next"; -import type { IntegrationOAuthCallbackState } from "../types"; +import type { IntegrationOAuthCallbackState } from "../../types"; export function decodeOAuthState(req: NextApiRequest) { if (typeof req.query.state !== "string") { similarity index 81% rename from packages/app-store/_utils/encodeOAuthState.ts rename to packages/app-store/_utils/oauth/encodeOAuthState.ts @@ -1,6 +1,6 @@ import type { NextApiRequest } from "next"; -import type { IntegrationOAuthCallbackState } from "../types"; +import type { IntegrationOAuthCallbackState } from "../../types"; export function encodeOAuthState(req: NextApiRequest) { if (typeof req.query.state !== "string") { new file mode 100644 @@ -0,0 +1,32 @@ +import { z } from "zod"; + +import { APP_CREDENTIAL_SHARING_ENABLED } from "@calcom/lib/constants"; + +const minimumTokenResponseSchema = z.object({ + access_token: z.string(), + // Assume that any property with a number is the expiry + [z.string().toString()]: z.number(), + // Allow other properties in the token response + [z.string().optional().toString()]: z.unknown().optional(), +}); + +const parseRefreshTokenResponse = (response: any, schema: z.ZodTypeAny) => { + let refreshTokenResponse; + if (APP_CREDENTIAL_SHARING_ENABLED && process.env.CALCOM_CREDENTIAL_SYNC_ENDPOINT) { + refreshTokenResponse = minimumTokenResponseSchema.safeParse(response); + } else { + refreshTokenResponse = schema.safeParse(response); + } + + if (!refreshTokenResponse.success) { + throw new Error("Invalid refreshed tokens were returned"); + } + + if (!refreshTokenResponse.data.refresh_token) { + refreshTokenResponse.data.refresh_token = "refresh_token"; + } + + return refreshTokenResponse; +}; + +export default parseRefreshTokenResponse; new file mode 100644 @@ -0,0 +1,22 @@ +import { APP_CREDENTIAL_SHARING_ENABLED } from "@calcom/lib/constants"; + +const refreshOAuthTokens = async (refreshFunction: () => any, appSlug: string, userId: number | null) => { + // Check that app syncing is enabled and that the credential belongs to a user + if (APP_CREDENTIAL_SHARING_ENABLED && process.env.CALCOM_CREDENTIAL_SYNC_ENDPOINT && userId) { + // Customize the payload based on what your endpoint requires + // The response should only contain the access token and expiry date + const response = await fetch(process.env.CALCOM_CREDENTIAL_SYNC_ENDPOINT, { + method: "POST", + body: new URLSearchParams({ + calcomUserId: userId.toString(), + appSlug, + }), + }); + return response; + } else { + const response = await refreshFunction(); + return response; + } +}; + +export default refreshOAuthTokens; @@ -3,8 +3,8 @@ import type { NextApiRequest, NextApiResponse } from "next"; import { WEBAPP_URL_FOR_OAUTH } from "@calcom/lib/constants"; -import { encodeOAuthState } from "../../_utils/encodeOAuthState"; import getAppKeysFromSlug from "../../_utils/getAppKeysFromSlug"; +import { encodeOAuthState } from "../../_utils/oauth/encodeOAuthState"; const scopes = [ "https://www.googleapis.com/auth/calendar.readonly", @@ -5,9 +5,9 @@ import { WEBAPP_URL_FOR_OAUTH, CAL_URL } from "@calcom/lib/constants"; import { getSafeRedirectUrl } from "@calcom/lib/getSafeRedirectUrl"; import prisma from "@calcom/prisma"; -import { decodeOAuthState } from "../../_utils/decodeOAuthState"; import getAppKeysFromSlug from "../../_utils/getAppKeysFromSlug"; import getInstalledAppPath from "../../_utils/getInstalledAppPath"; +import { decodeOAuthState } from "../../_utils/oauth/decodeOAuthState"; let client_id = ""; let client_secret = ""; @@ -18,6 +18,8 @@ import type { } from "@calcom/types/Calendar"; import type { CredentialPayload } from "@calcom/types/Credential"; +import parseRefreshTokenResponse from "../../_utils/oauth/parseRefreshTokenResponse"; +import refreshOAuthTokens from "../../_utils/oauth/refreshOAuthTokens"; import { getGoogleAppKeys } from "./getGoogleAppKeys"; import { googleCredentialSchema } from "./googleCredentialSchema"; @@ -81,11 +83,18 @@ export default class GoogleCalendarService implements Calendar { const refreshAccessToken = async (myGoogleAuth: Awaited<ReturnType<typeof getGoogleAuth>>) => { try { - const { res } = await myGoogleAuth.refreshToken(googleCredentials.refresh_token); + const res = await refreshOAuthTokens( + async () => { + const fetchTokens = await myGoogleAuth.refreshToken(googleCredentials.refresh_token); + return fetchTokens.res; + }, + "google-calendar", + credential.userId + ); const token = res?.data; googleCredentials.access_token = token.access_token; googleCredentials.expiry_date = token.expiry_date; - const key = googleCredentialSchema.parse(googleCredentials); + const key = parseRefreshTokenResponse(googleCredentials, googleCredentialSchema); await prisma.credential.update({ where: { id: credential.id }, data: { key }, @@ -3,8 +3,8 @@ import type { NextApiRequest, NextApiResponse } from "next"; import { WEBAPP_URL } from "@calcom/lib/constants"; -import { encodeOAuthState } from "../../_utils/encodeOAuthState"; import getAppKeysFromSlug from "../../_utils/getAppKeysFromSlug"; +import { encodeOAuthState } from "../../_utils/oauth/encodeOAuthState"; const scopes = ["crm.objects.contacts.read", "crm.objects.contacts.write"]; @@ -5,10 +5,10 @@ import type { NextApiRequest, NextApiResponse } from "next"; import { WEBAPP_URL } from "@calcom/lib/constants"; import { getSafeRedirectUrl } from "@calcom/lib/getSafeRedirectUrl"; -import createOAuthAppCredential from "../../_utils/createOAuthAppCredential"; -import { decodeOAuthState } from "../../_utils/decodeOAuthState"; import getAppKeysFromSlug from "../../_utils/getAppKeysFromSlug"; import getInstalledAppPath from "../../_utils/getInstalledAppPath"; +import createOAuthAppCredential from "../../_utils/oauth/createOAuthAppCredential"; +import { decodeOAuthState } from "../../_utils/oauth/decodeOAuthState"; let client_id = ""; let client_secret = ""; @@ -23,6 +23,7 @@ import type { import type { CredentialPayload } from "@calcom/types/Credential"; import getAppKeysFromSlug from "../../_utils/getAppKeysFromSlug"; +import refreshOAuthTokens from "../../_utils/oauth/refreshOAuthTokens"; import type { HubspotToken } from "../api/callback"; const hubspotClient = new hubspot.Client(); @@ -173,13 +174,18 @@ export default class HubspotCalendarService implements Calendar { const refreshAccessToken = async (refreshToken: string) => { try { - const hubspotRefreshToken: HubspotToken = await hubspotClient.oauth.tokensApi.createToken( - "refresh_token", - undefined, - WEBAPP_URL + "/api/integrations/hubspot/callback", - this.client_id, - this.client_secret, - refreshToken + const hubspotRefreshToken: HubspotToken = await refreshOAuthTokens( + async () => + await hubspotClient.oauth.tokensApi.createToken( + "refresh_token", + undefined, + WEBAPP_URL + "/api/integrations/hubspot/callback", + this.client_id, + this.client_secret, + refreshToken + ), + "hubspot", + credential.userId ); // set expiry date as offset from current time. @@ -5,8 +5,8 @@ import { z } from "zod"; import { WEBAPP_URL } from "@calcom/lib/constants"; import { defaultHandler, defaultResponder } from "@calcom/lib/server"; -import { encodeOAuthState } from "../../_utils/encodeOAuthState"; import getAppKeysFromSlug from "../../_utils/getAppKeysFromSlug"; +import { encodeOAuthState } from "../../_utils/oauth/encodeOAuthState"; import { LARK_HOST } from "../common"; const larkKeysSchema = z.object({ @@ -6,8 +6,8 @@ import logger from "@calcom/lib/logger"; import { defaultHandler, defaultResponder } from "@calcom/lib/server"; import prisma from "@calcom/prisma"; -import { decodeOAuthState } from "../../_utils/decodeOAuthState"; import getInstalledAppPath from "../../_utils/getInstalledAppPath"; +import { decodeOAuthState } from "../../_utils/oauth/decodeOAuthState"; import { LARK_HOST } from "../common"; import { getAppAccessToken } from "../lib/AppAccessToken"; import type { LarkAuthCredentials } from "../types/LarkCalendar"; @@ -11,6 +11,7 @@ import type { } from "@calcom/types/Calendar"; import type { CredentialPayload } from "@calcom/types/Credential"; +import refreshOAuthTokens from "../../_utils/oauth/refreshOAuthTokens"; import { handleLarkError, isExpired, LARK_HOST } from "../common"; import type { CreateAttendeesResp, @@ -63,17 +64,22 @@ export default class LarkCalendarService implements Calendar { } try { const appAccessToken = await getAppAccessToken(); - const resp = await fetch(`${this.url}/authen/v1/refresh_access_token`, { - method: "POST", - headers: { - Authorization: `Bearer ${appAccessToken}`, - "Content-Type": "application/json; charset=utf-8", - }, - body: JSON.stringify({ - grant_type: "refresh_token", - refresh_token: refreshToken, - }), - }); + const resp = await refreshOAuthTokens( + async () => + await fetch(`${this.url}/authen/v1/refresh_access_token`, { + method: "POST", + headers: { + Authorization: `Bearer ${appAccessToken}`, + "Content-Type": "application/json; charset=utf-8", + }, + body: JSON.stringify({ + grant_type: "refresh_token", + refresh_token: refreshToken, + }), + }), + "lark-calendar", + credential.userId + ); const data = await handleLarkError<RefreshTokenResp>(resp, this.log); this.log.debug( @@ -3,8 +3,8 @@ import { stringify } from "querystring"; import { WEBAPP_URL } from "@calcom/lib/constants"; -import { encodeOAuthState } from "../../_utils/encodeOAuthState"; import getAppKeysFromSlug from "../../_utils/getAppKeysFromSlug"; +import { encodeOAuthState } from "../../_utils/oauth/encodeOAuthState"; const scopes = ["User.Read", "Calendars.Read", "Calendars.ReadWrite", "offline_access"]; @@ -4,9 +4,9 @@ import { WEBAPP_URL } from "@calcom/lib/constants"; import { getSafeRedirectUrl } from "@calcom/lib/getSafeRedirectUrl"; import prisma from "@calcom/prisma"; -import { decodeOAuthState } from "../../_utils/decodeOAuthState"; import getAppKeysFromSlug from "../../_utils/getAppKeysFromSlug"; import getInstalledAppPath from "../../_utils/getInstalledAppPath"; +import { decodeOAuthState } from "../../_utils/oauth/decodeOAuthState"; const scopes = ["offline_access", "Calendars.Read", "Calendars.ReadWrite"]; @@ -17,6 +17,8 @@ import type { } from "@calcom/types/Calendar"; import type { CredentialPayload } from "@calcom/types/Credential"; +import parseRefreshTokenResponse from "../../_utils/oauth/parseRefreshTokenResponse"; +import refreshOAuthTokens from "../../_utils/oauth/refreshOAuthTokens"; import type { O365AuthCredentials } from "../types/Office365Calendar"; import { getOfficeAppKeys } from "./getOfficeAppKeys"; @@ -241,28 +243,25 @@ export default class Office365CalendarService implements Calendar { const refreshAccessToken = async (o365AuthCredentials: O365AuthCredentials) => { const { client_id, client_secret } = await getOfficeAppKeys(); - const response = await fetch("https://login.microsoftonline.com/common/oauth2/v2.0/token", { - method: "POST", - headers: { "Content-Type": "application/x-www-form-urlencoded" }, - body: new URLSearchParams({
Leaderboard for this case
medium · 5 of 9 bots fully caught it (56% solve rate) · 94% avg coverage.
| # | Bot | Result | Caught | Coverage | Findings | False alarms |
|---|---|---|---|---|---|---|
| 1 | Claude Code (Opus 5.5) | solved | 7/7 | 100.0% | 9 | 0 |
| 2 | Cubic | solved | 7/7 | 100.0% | 15 | 0 |
| 3 | Drape (Deep Review) | solved | 7/7 | 100.0% | 16 | 0 |
| 4 | Mjolnir (Opus 5.5) | solved | 7/7 | 100.0% | 15 | 0 |
| 5 | Mjolnir (Sonnet 5.5) | solved | 7/7 | 100.0% | 14 | 1 |
| 6 | cursor | partial | 6/7 | 84.6% | 6 | 0 |
| 7 | Drape (Review) | partial | 6/7 | 84.6% | 8 | 0 |
| 8 | greptile | partial | 6/7 | 84.6% | 7 | 0 |
| 9 | qodo | partial | 6/7 | 84.6% | 8 | 0 |
Bot results
Claude Code (Opus 5.5) · cross-file engine perris 0.11.1+proven.tiered0.25.call.read.subclass.type
| Defect | Severity | Found | Grade |
|---|---|---|---|
| d1 | high | ✓ | off by one |
| d2 | high | ✓ | off by one |
| d3 | high | ✓ | exact |
| d4 | high | ✓ | off by one |
| d5 | high | ✓ | off by one |
| d6 | high | ✓ | exact |
| d7 | medium | ✓ | exact |
The Salesforce CalendarService post-change imports have no prisma import, yet getClient now calls prisma.credential.update. That throws a ReferenceError, which rejects this.conn and breaks every Salesforce operation. [grounded: diff] [consensus 3/3: valid=3]
The removed lines used safeParse, logged the error and continued with the existing credentials. parseRefreshTokenResponse now throws 'Invalid refreshed tokens were returned', and the console.error that logged the MS response is gone. [grounded: diff] [consensus 3/3: valid=3]
The new endpoint compares the secret with plain !==, and its zod parse, decrypt and JSON.parse calls are unhandled, so bad input surfaces as a 500 instead of a 400. Both are real but mostly hardening concerns. [grounded: diff] [consensus 3/3: valid=3]
The decrypted JSON is stored directly in credential.key without being checked against any app key schema, so a malformed payload is persisted and can break that user's integration. [grounded: diff] [consensus 3/3: valid=3]
raw comments (9)
`prisma` is used here but never imported in this file. This fails type-checking, and at runtime it throws a ReferenceError in `getClient`, which rejects `this.conn`. Every Salesforce operation (contact create, event create, etc.) then fails.
`getClient` now calls the Salesforce token endpoint on every service construction, whether or not the token has expired, and it skips `refreshOAuthTokens`, so credential sync never applies here. The `response.statusText !== "OK"` check is brittle: HTTP/2 and some proxies send an empty statusText, so successful refreshes throw. `salesforceTokenSchema` requires `signature`, `scope` and similar fields, and `parseRefreshTokenResponse` throws on a mismatch, so the `!success` branch is unreachable and the connection can't be created. The new Connection is also built with the stale `credentialKey.access_token` instead of the token that was just refreshed.
`parseRefreshTokenResponse` returns the zod `safeParse` result (`{success, data}`), not the parsed credentials. That whole wrapper object is saved as the credential `key`, which corrupts Google credentials on every token refresh, even when credential sharing is off. Later reads of `credential.key` no longer match `googleCredentialSchema`.
When credential sync is enabled, `refreshOAuthTokens` returns a raw fetch `Response`. Its `.data` is undefined, so `token.access_token` throws a TypeError and the refresh always fails. The same mismatch affects HubSpot (expects a `HubspotToken` object) and Zoho CRM/Bigin (read `.data` from an axios response): the sync path returns a different shape than the callers expect.
`credentialId` is passed where `refreshOAuthTokens` expects a userId. With sync enabled, the external endpoint receives the credential ID as `calcomUserId` and returns the wrong user's tokens (or none). Team credentials with a null userId also skip the sync path check incorrectly.
The computed keys `[z.string().toString()]` both evaluate to the same string, "[object Object]". The second overwrites the first, so the schema only validates `access_token`, and zod strips every other field (expiry, etc.). Also, when `refresh_token` is missing, the literal string "refresh_token" is written in, and that gets persisted as the user's refresh token (for example in Zoom/Office365), which corrupts it.
`parseRefreshTokenResponse` now throws on an invalid token response. Before this change the code logged the error and continued with the existing credentials, so this changes failure behavior and the diagnostic logging of the MS response is gone.
The webhook secret is compared with `!==`, which isn't constant-time, so it can leak through timing. The endpoint also lets the caller overwrite any user's credentials. In addition, `z.parse` and `JSON.parse`/`symmetricDecrypt` exceptions are unhandled and surface as 500s instead of 400s.
The decrypted keys go straight into `credential.key` without being checked against the app's key schema. A malformed payload is persisted as is and breaks that app's integration for the user.
Cubic · cross-file engine perris 0.11.1+proven.tiered0.25.call.read.subclass.type
| Defect | Severity | Found | Grade |
|---|---|---|---|
| d1 | high | ✓ | exact |
| d2 | high | ✓ | exact |
| d3 | high | ✓ | exact |
| d4 | high | ✓ | exact |
| d5 | high | ✓ | exact |
| d6 | high | ✓ | off by one |
| d7 | medium | ✓ | off by one |
When the sync path is used, minimumTokenResponseSchema (whose computed keys collapse to "[object Object]") strips expires_in. That leaves newTokens.expires_in undefined, so expiry_date becomes NaN. [grounded: tree packages/app-store/zoomvideo/lib/VideoApiAdapter.ts] [consensus 5/5: valid=5]
appStoreMetadata is keyed by directory name (e.g. googlecalendar, zoomvideo), not by slug (google-calendar, zoom). Looking it up by slug therefore returns undefined and the webhook responds 404 for those apps. [grounded: tree apps/web/pages/api/webhook/app-credential.ts] [consensus 5/5: valid=5]
refreshOAuthTokens also checks userId, but the parser does not. For team credentials (userId null), a provider response is parsed with the minimum schema, which strips the provider-specific fields. [grounded: tree packages/app-store/_utils/oauth/parseRefreshTokenResponse.ts] [consensus 5/5: valid=5]
Incomplete change: every other adapter wraps its refresh in refreshOAuthTokens, but the new Salesforce refresh calls fetch directly and bypasses the sync endpoint. [grounded: tree packages/app-store/salesforce/lib/CalendarService.ts] [consensus 5/5: valid=5]
The sync response is documented as returning the access token and expiry date. With no expires_in, this line overwrites expiry_date with now, so the token looks expired immediately. [grounded: tree packages/app-store/office365video/lib/VideoApiAdapter.ts] [consensus 5/5: valid=5]
Zoom's appId/slug is "zoom" (the callback uses appId "zoom"), while every other adapter passes its real slug. Sending "zoomvideo" is inconsistent with that. [grounded: tree packages/app-store/zoomvideo/lib/VideoApiAdapter.ts] [consensus 5/5: valid=5]
parse throws a ZodError that is not caught, so a malformed payload gets a 500 instead of a 400. [grounded: tree apps/web/pages/api/webhook/app-credential.ts] [consensus 5/5: valid=5]
The find-then-create is not atomic, so two concurrent deliveries can both create a credential row. [grounded: tree apps/web/pages/api/webhook/app-credential.ts] [consensus 5/5: valid=5]
After the new refresh and DB update, the connection is still built from the old credentialKey access token and instance URL rather than the refreshed values. [grounded: tree packages/app-store/salesforce/lib/CalendarService.ts] [consensus 5/5: valid=5]
raw comments (16)
<!-- cubic:v=15cecf41-c4e2-4d4f-b0b9-1d00ddeb73c6 -->
<!-- cubic:review-run=bad0f17c-12eb-5572-bf96-97149e6053eb -->
<!-- metadata:{"confidence":10} -->
P1: When credential sharing is enabled, this sends the credential row ID as `calcomUserId`. Pass `credential.userId` through `refreshAccessToken` instead, or team credentials may sync against the wrong user or fail.
<details>
<summary>Prompt for AI agents</summary>
```text
Check if this issue is valid — if so, understand the root cause and fix it. At packages/app-store/zoho-bigin/lib/CalendarService.ts, line 93:
<comment>When credential sharing is enabled, this sends the credential row ID as `calcomUserId`. Pass `credential.userId` through `refreshAccessToken` instead, or team credentials may sync against the wrong user or fail.</comment>
<file context>
@@ -81,11 +82,16 @@ export default class BiginCalendarService implements Calendar {
+ },
+ }),
+ "zoho-bigin",
+ credentialId
+ );
</file context>
```
</details>
<!-- cubic:v=784f87fe-0c66-44e2-a0e1-29ded1277e98 -->
<!-- cubic:review-run=bad0f17c-12eb-5572-bf96-97149e6053eb -->
<!-- metadata:{"confidence":10} -->
P1: When credential sharing is enabled, this returns a native `Response` instead of the token JSON. Google, HubSpot, and Axios-backed integrations then read incompatible fields, so shared credential refresh fails; parse the response and align callers on one token shape.
<details>
<summary>Prompt for AI agents</summary>
```text
Check if this issue is valid — if so, understand the root cause and fix it. At packages/app-store/_utils/oauth/refreshOAuthTokens.ts, line 15:
<comment>When credential sharing is enabled, this returns a native `Response` instead of the token JSON. Google, HubSpot, and Axios-backed integrations then read incompatible fields, so shared credential refresh fails; parse the response and align callers on one token shape.</comment>
<file context>
@@ -0,0 +1,22 @@
+ appSlug,
+ }),
+ });
+ return response;
+ } else {
+ const response = await refreshFunction();
</file context>
```
</details>
<!-- cubic:v=5fa7971d-0832-461d-b382-cb8f3194f319 -->
<!-- cubic:review-run=bad0f17c-12eb-5572-bf96-97149e6053eb -->
<!-- metadata:{"confidence":10} -->
P1: After a refresh, this persists the parser’s `{ success, data }` wrapper as `credential.key` instead of the parsed Google credential. Check the parse result and persist its `.data`, otherwise the next service initialization cannot parse the saved credential.
<details>
<summary>Prompt for AI agents</summary>
```text
Check if this issue is valid — if so, understand the root cause and fix it. At packages/app-store/googlecalendar/lib/CalendarService.ts, line 97:
<comment>After a refresh, this persists the parser’s `{ success, data }` wrapper as `credential.key` instead of the parsed Google credential. Check the parse result and persist its `.data`, otherwise the next service initialization cannot parse the saved credential.</comment>
<file context>
@@ -81,11 +83,18 @@ export default class GoogleCalendarService implements Calendar {
googleCredentials.access_token = token.access_token;
googleCredentials.expiry_date = token.expiry_date;
- const key = googleCredentialSchema.parse(googleCredentials);
+ const key = parseRefreshTokenResponse(googleCredentials, googleCredentialSchema);
await prisma.credential.update({
where: { id: credential.id },
</file context>
```
</details>
```suggestion
const parsedKey = parseRefreshTokenResponse(googleCredentials, googleCredentialSchema);
if (!parsedKey.success) throw new Error("Invalid refreshed tokens were returned");
const key = parsedKey.data;
```
<!-- cubic:v=8688e4a6-10a4-4a23-80f1-f9c74d673edd -->
<!-- cubic:review-run=bad0f17c-12eb-5572-bf96-97149e6053eb -->
<!-- metadata:{"confidence":9} -->
P1: When the shared refresh endpoint returns its documented `expiry_date`, this parser leaves that field unchanged, but Zoom still reads `newTokens.expires_in` below. Normalize the shared response to `expires_in` (or update the expiry calculation to use `expiry_date`) before storing the credential.
<details>
<summary>Prompt for AI agents</summary>
```text
Check if this issue is valid — if so, understand the root cause and fix it. At packages/app-store/zoomvideo/lib/VideoApiAdapter.ts, line 104:
<comment>When the shared refresh endpoint returns its documented `expiry_date`, this parser leaves that field unchanged, but Zoom still reads `newTokens.expires_in` below. Normalize the shared response to `expires_in` (or update the expiry calculation to use `expiry_date`) before storing the credential.</comment>
<file context>
@@ -94,7 +101,7 @@ const zoomAuth = (credential: CredentialPayload) => {
}
// We check the if the new credentials matches the expected response structure
- const parsedToken = zoomRefreshedTokenSchema.safeParse(responseBody);
+ const parsedToken = parseRefreshTokenResponse(responseBody, zoomRefreshedTokenSchema);
// TODO: If the new token is invalid, initiate the fallback sequence instead of throwing
</file context>
```
</details>
<!-- cubic:v=046c08c9-025a-4829-81be-0d0769e64668 -->
<!-- cubic:review-run=bad0f17c-12eb-5572-bf96-97149e6053eb -->
<!-- metadata:{"confidence":10} -->
P1: For apps whose directory key differs from its public slug, this lookup returns undefined and the webhook always responds 404. Resolve metadata by matching `metadata.slug` instead of indexing the metadata map with `app.slug`.
<details>
<summary>Prompt for AI agents</summary>
```text
Check if this issue is valid — if so, understand the root cause and fix it. At apps/web/pages/api/webhook/app-credential.ts, line 50:
<comment>For apps whose directory key differs from its public slug, this lookup returns undefined and the webhook always responds 404. Resolve metadata by matching `metadata.slug` instead of indexing the metadata map with `app.slug`.</comment>
<file context>
@@ -0,0 +1,93 @@
+ }
+
+ // Search for the app's slug and type
+ const appMetadata = appStoreMetadata[app.slug as keyof typeof appStoreMetadata];
+
+ if (!appMetadata) {
</file context>
```
</details>
```suggestion
const appMetadata = Object.values(appStoreMetadata).find((metadata) => metadata.slug === app.slug);
```
<!-- cubic:v=ada655c0-8fed-4c01-9300-93f9d189188a -->
<!-- cubic:review-run=bad0f17c-12eb-5572-bf96-97149e6053eb -->
<!-- metadata:{"confidence":8} -->
P1: When a credential has no `userId`, `refreshOAuthTokens` uses the provider refresh path, but this condition still selects `minimumTokenResponseSchema` whenever the sync endpoint is configured. That bypasses the provider schema and strips provider-specific fields from ordinary refresh responses; pass the actual response source into this parser or use `schema` for provider responses.
<details>
<summary>Prompt for AI agents</summary>
```text
Check if this issue is valid — if so, understand the root cause and fix it. At packages/app-store/_utils/oauth/parseRefreshTokenResponse.ts, line 15:
<comment>When a credential has no `userId`, `refreshOAuthTokens` uses the provider refresh path, but this condition still selects `minimumTokenResponseSchema` whenever the sync endpoint is configured. That bypasses the provider schema and strips provider-specific fields from ordinary refresh responses; pass the actual response source into this parser or use `schema` for provider responses.</comment>
<file context>
@@ -0,0 +1,32 @@
+
+const parseRefreshTokenResponse = (response: any, schema: z.ZodTypeAny) => {
+ let refreshTokenResponse;
+ if (APP_CREDENTIAL_SHARING_ENABLED && process.env.CALCOM_CREDENTIAL_SYNC_ENDPOINT) {
+ refreshTokenResponse = minimumTokenResponseSchema.safeParse(response);
+ } else {
</file context>
```
</details>
<!-- cubic:v=4b5ca7c8-6aa9-47e4-a616-6bed95bb16c1 -->
<!-- cubic:review-run=bad0f17c-12eb-5572-bf96-97149e6053eb -->
<!-- metadata:{"confidence":10} -->
P1: When credential sharing is enabled, this schema does not match arbitrary response properties: both computed keys become `"[object Object]"`, and the optional second entry overwrites the numeric entry. Zod then strips `expires_in`/`expiry_date`, so refreshed tokens lose their expiry and Zoom can treat them as valid indefinitely. Preserve unknown token fields with `.passthrough()` or define the expiry fields explicitly.
<details>
<summary>Prompt for AI agents</summary>
```text
Check if this issue is valid — if so, understand the root cause and fix it. At packages/app-store/_utils/oauth/parseRefreshTokenResponse.ts, line 8:
<comment>When credential sharing is enabled, this schema does not match arbitrary response properties: both computed keys become `"[object Object]"`, and the optional second entry overwrites the numeric entry. Zod then strips `expires_in`/`expiry_date`, so refreshed tokens lose their expiry and Zoom can treat them as valid indefinitely. Preserve unknown token fields with `.passthrough()` or define the expiry fields explicitly.</comment>
<file context>
@@ -0,0 +1,32 @@
+const minimumTokenResponseSchema = z.object({
+ access_token: z.string(),
+ // Assume that any property with a number is the expiry
+ [z.string().toString()]: z.number(),
+ // Allow other properties in the token response
+ [z.string().optional().toString()]: z.unknown().optional(),
</file context>
```
</details>
<!-- cubic:v=a730c2de-069e-4a5e-b648-9db1b6b2648a -->
<!-- cubic:review-run=bad0f17c-12eb-5572-bf96-97149e6053eb -->
<!-- metadata:{"confidence":10} -->
P1: When an OAuth refresh response omits `refresh_token`, this helper fabricates a literal token instead of leaving the existing credential intact. Office 365 merges the parsed data over the old credential and persists that literal, causing the next refresh to fail; do not add a placeholder when the field is absent.
<details>
<summary>Prompt for AI agents</summary>
```text
Check if this issue is valid — if so, understand the root cause and fix it. At packages/app-store/_utils/oauth/parseRefreshTokenResponse.ts, line 25:
<comment>When an OAuth refresh response omits `refresh_token`, this helper fabricates a literal token instead of leaving the existing credential intact. Office 365 merges the parsed data over the old credential and persists that literal, causing the next refresh to fail; do not add a placeholder when the field is absent.</comment>
<file context>
@@ -0,0 +1,32 @@
+ throw new Error("Invalid refreshed tokens were returned");
+ }
+
+ if (!refreshTokenResponse.data.refresh_token) {
+ refreshTokenResponse.data.refresh_token = "refresh_token";
+ }
</file context>
```
</details>
<!-- cubic:v=658ce9ac-d9e1-46cc-afe1-384009fa66f8 -->
<!-- cubic:review-run=bad0f17c-12eb-5572-bf96-97149e6053eb -->
<!-- metadata:{"confidence":9} -->
P1: When credential sharing is enabled, this bypasses the configured credential-sync endpoint and refreshes with the local Salesforce token instead. Wrap the Salesforce request with `refreshOAuthTokens` using the Salesforce app slug and `credential.userId`.
<details>
<summary>Prompt for AI agents</summary>
```text
Check if this issue is valid — if so, understand the root cause and fix it. At packages/app-store/salesforce/lib/CalendarService.ts, line 75:
<comment>When credential sharing is enabled, this bypasses the configured credential-sync endpoint and refreshes with the local Salesforce token instead. Wrap the Salesforce request with `refreshOAuthTokens` using the Salesforce app slug and `credential.userId`.</comment>
<file context>
@@ -60,6 +72,32 @@ export default class SalesforceCalendarService implements Calendar {
const credentialKey = credential.key as unknown as ExtendedTokenResponse;
+ const response = await fetch("https://login.salesforce.com/services/oauth2/token", {
+ method: "POST",
+ body: new URLSearchParams({
</file context>
```
</details>
<!-- cubic:v=1c0d46f8-4789-4446-9496-e4e98f3935e7 -->
<!-- cubic:review-run=bad0f17c-12eb-5572-bf96-97149e6053eb -->
<!-- metadata:{"confidence":9} -->
P2: When credential sharing is enabled, the sync response provides `expiry_date` rather than `expires_in`, but this new wrapper feeds it into logic that overwrites the expiry with the current time. Preserve the returned `responseBody.expiry_date` and only derive it from `expires_in` when no expiry date was supplied.
<details>
<summary>Prompt for AI agents</summary>
```text
Check if this issue is valid — if so, understand the root cause and fix it. At packages/app-store/office365video/lib/VideoApiAdapter.ts, line 61:
<comment>When credential sharing is enabled, the sync response provides `expiry_date` rather than `expires_in`, but this new wrapper feeds it into logic that overwrites the expiry with the current time. Preserve the returned `responseBody.expiry_date` and only derive it from `expires_in` when no expiry date was supplied.</comment>
<file context>
@@ -57,16 +58,21 @@ const o365Auth = async (credential: CredentialPayload) => {
- client_secret,
- }),
- });
+ const response = await refreshOAuthTokens(
+ async () =>
+ await fetch("https://login.microsoftonline.com/common/oauth2/v2.0/token", {
</file context>
```
</details>
<!-- cubic:v=ec564f52-22bb-4570-8f59-6aba7c56e8f4 -->
<!-- cubic:review-run=bad0f17c-12eb-5572-bf96-97149e6053eb -->
<!-- metadata:{"confidence":9} -->
P2: When credential sharing is enabled, the sync request identifies this integration as `zoomvideo`, but Zoom's canonical app slug is `zoom`. Pass `"zoom"` so the credential-sharing service can resolve the Zoom integration.
<details>
<summary>Prompt for AI agents</summary>
```text
Check if this issue is valid — if so, understand the root cause and fix it. At packages/app-store/zoomvideo/lib/VideoApiAdapter.ts, line 92:
<comment>When credential sharing is enabled, the sync request identifies this integration as `zoomvideo`, but Zoom's canonical app slug is `zoom`. Pass `"zoom"` so the credential-sharing service can resolve the Zoom integration.</comment>
<file context>
@@ -74,17 +76,22 @@ const zoomAuth = (credential: CredentialPayload) => {
+ grant_type: "refresh_token",
+ }),
+ }),
+ "zoomvideo",
+ credential.userId
+ );
</file context>
```
</details>
```suggestion
"zoom",
```
<!-- cubic:v=dcbbb556-9f2d-40a4-b613-ecb099a2a00e -->
<!-- cubic:review-run=bad0f17c-12eb-5572-bf96-97149e6053eb -->
<!-- metadata:{"confidence":9} -->
P2: Malformed webhook payloads throw out of the handler and become 500 responses. Use `safeParse` and return 400 for validation failures.
<details>
<summary>Prompt for AI agents</summary>
```text
Check if this issue is valid — if so, understand the root cause and fix it. At apps/web/pages/api/webhook/app-credential.ts, line 31:
<comment>Malformed webhook payloads throw out of the handler and become 500 responses. Use `safeParse` and return 400 for validation failures.</comment>
<file context>
@@ -0,0 +1,93 @@
+ return res.status(403).json({ message: "Invalid webhook secret" });
+ }
+
+ const reqBody = appCredentialWebhookRequestBodySchema.parse(req.body);
+
+ // Check that the user exists
</file context>
```
</details>
```suggestion
const parsedReqBody = appCredentialWebhookRequestBodySchema.safeParse(req.body);
if (!parsedReqBody.success) {
return res.status(400).json({ message: "Invalid request body" });
}
const reqBody = parsedReqBody.data;
```
<!-- cubic:v=afdbae4b-1dca-417c-8fef-cb24ddfed17f -->
<!-- cubic:review-run=bad0f17c-12eb-5572-bf96-97149e6053eb -->
<!-- metadata:{"confidence":9} -->
P2: When two deliveries for the same user and app run concurrently, both can observe no credential and create a row, leaving duplicates. Make this operation atomic with a uniqueness constraint and an upsert or transaction.
<details>
<summary>Prompt for AI agents</summary>
```text
Check if this issue is valid — if so, understand the root cause and fix it. At apps/web/pages/api/webhook/app-credential.ts, line 62:
<comment>When two deliveries for the same user and app run concurrently, both can observe no credential and create a row, leaving duplicates. Make this operation atomic with a uniqueness constraint and an upsert or transaction.</comment>
<file context>
@@ -0,0 +1,93 @@
+ );
+
+ // Can't use prisma upsert as we don't know the id of the credential
+ const appCredential = await prisma.credential.findFirst({
+ where: {
+ userId: reqBody.userId,
</file context>
```
</details>
<!-- cubic:v=48700219-6948-45bb-8eb7-aec746c24713 -->
<!-- cubic:review-run=bad0f17c-12eb-5572-bf96-97149e6053eb -->
<!-- metadata:{"confidence":7} -->
P2: A valid 2xx token response can be rejected when its reason phrase is empty or not exactly `OK`. Check `response.ok` instead of comparing `response.statusText` to a literal.
<details>
<summary>Prompt for AI agents</summary>
```text
Check if this issue is valid — if so, understand the root cause and fix it. At packages/app-store/salesforce/lib/CalendarService.ts, line 86:
<comment>A valid 2xx token response can be rejected when its reason phrase is empty or not exactly `OK`. Check `response.ok` instead of comparing `response.statusText` to a literal.</comment>
<file context>
@@ -60,6 +72,32 @@ export default class SalesforceCalendarService implements Calendar {
+ }),
+ });
+
+ if (response.statusText !== "OK") throw new HttpError({ statusCode: 400, message: response.statusText });
+
+ const accessTokenJson = await response.json();
</file context>
```
</details>
```suggestion
if (!response.ok) throw new HttpError({ statusCode: 400, message: response.statusText });
```
<!-- cubic:v=c5269d78-3b2f-4fbe-9b00-9499ddb9bc69 -->
<!-- cubic:review-run=bad0f17c-12eb-5572-bf96-97149e6053eb -->
<!-- metadata:{"confidence":8} -->
P2: After refreshing and persisting the token, the connection still starts with the expired access token from `credentialKey`. Pass `accessTokenParsed.data.access_token` and `accessTokenParsed.data.instance_url` to `jsforce.Connection`.
<details>
<summary>Prompt for AI agents</summary>
```text
Check if this issue is valid — if so, understand the root cause and fix it. At packages/app-store/salesforce/lib/CalendarService.ts, line 90:
<comment>After refreshing and persisting the token, the connection still starts with the expired access token from `credentialKey`. Pass `accessTokenParsed.data.access_token` and `accessTokenParsed.data.instance_url` to `jsforce.Connection`.</comment>
<file context>
@@ -60,6 +72,32 @@ export default class SalesforceCalendarService implements Calendar {
+
+ const accessTokenJson = await response.json();
+
+ const accessTokenParsed = parseRefreshTokenResponse(accessTokenJson, salesforceTokenSchema);
+
+ if (!accessTokenParsed.success) {
</file context>
```
</details>
<!-- cubic:review-summary:start -->
**15 issues found** across 40 files
<!-- cubic:review-summary:end -->
<details>
<summary>Prompt for AI agents (unresolved issues)</summary>
```text
Check if these issues are valid — if so, understand the root cause of each and fix them. If appropriate, use sub-agents to investigate and fix each issue separately.
<file name="packages/app-store/zoho-bigin/lib/CalendarService.ts">
<violation number="1" location="packages/app-store/zoho-bigin/lib/CalendarService.ts:93">
P1: When credential sharing is enabled, this sends the credential row ID as `calcomUserId`. Pass `credential.userId` through `refreshAccessToken` instead, or team credentials may sync against the wrong user or fail.</violation>
</file>
<file name="packages/app-store/office365video/lib/VideoApiAdapter.ts">
<violation number="1" location="packages/app-store/office365video/lib/VideoApiAdapter.ts:61">
P2: When credential sharing is enabled, the sync response provides `expiry_date` rather than `expires_in`, but this new wrapper feeds it into logic that overwrites the expiry with the current time. Preserve the returned `responseBody.expiry_date` and only derive it from `expires_in` when no expiry date was supplied.</violation>
</file>
<file name="packages/app-store/_utils/oauth/refreshOAuthTokens.ts">
<violation number="1" location="packages/app-store/_utils/oauth/refreshOAuthTokens.ts:15">
P1: When credential sharing is enabled, this returns a native `Response` instead of the token JSON. Google, HubSpot, and Axios-backed integrations then read incompatible fields, so shared credential refresh fails; parse the response and align callers on one token shape.</violation>
</file>
<file name="packages/app-store/googlecalendar/lib/CalendarService.ts">
<violation number="1" location="packages/app-store/googlecalendar/lib/CalendarService.ts:97">
P1: After a refresh, this persists the parser’s `{ success, data }` wrapper as `credential.key` instead of the parsed Google credential. Check the parse result and persist its `.data`, otherwise the next service initialization cannot parse the saved credential.</violation>
</file>
<file name="packages/app-store/zoomvideo/lib/VideoApiAdapter.ts">
<violation number="1" location="packages/app-store/zoomvideo/lib/VideoApiAdapter.ts:92">
P2: When credential sharing is enabled, the sync request identifies this integration as `zoomvideo`, but Zoom's canonical app slug is `zoom`. Pass `"zoom"` so the credential-sharing service can resolve the Zoom integration.</violation>
<violation number="2" location="packages/app-store/zoomvideo/lib/VideoApiAdapter.ts:104">
P1: When the shared refresh endpoint returns its documented `expiry_date`, this parser leaves that field unchanged, but Zoom still reads `newTokens.expires_in` below. Normalize the shared response to `expires_in` (or update the expiry calculation to use `expiry_date`) before storing the credential.</violation>
</file>
<file name="apps/web/pages/api/webhook/app-credential.ts">
<violation number="1" location="apps/web/pages/api/webhook/app-credential.ts:31">
P2: Malformed webhook payloads throw out of the handler and become 500 responses. Use `safeParse` and return 400 for validation failures.</violation>
<violation number="2" location="apps/web/pages/api/webhook/app-credential.ts:50">
P1: For apps whose directory key differs from its public slug, this lookup returns undefined and the webhook always responds 404. Resolve metadata by matching `metadata.slug` instead of indexing the metadata map with `app.slug`.</violation>
<violation number="3" location="apps/web/pages/api/webhook/app-credential.ts:62">
P2: When two deliveries for the same user and app run concurrently, both can observe no credential and create a row, leaving duplicates. Make this operation atomic with a uniqueness constraint and an upsert or transaction.</violation>
</file>
<file name="packages/app-store/_utils/oauth/parseRefreshTokenResponse.ts">
<violation number="1" location="packages/app-store/_utils/oauth/parseRefreshTokenResponse.ts:8">
P1: When credential sharing is enabled, this schema does not match arbitrary response properties: both computed keys become `"[object Object]"`, and the optional second entry overwrites the numeric entry. Zod then strips `expires_in`/`expiry_date`, so refreshed tokens lose their expiry and Zoom can treat them as valid indefinitely. Preserve unknown token fields with `.passthrough()` or define the expiry fields explicitly.</violation>
<violation number="2" location="packages/app-store/_utils/oauth/parseRefreshTokenResponse.ts:15">
P1: When a credential has no `userId`, `refreshOAuthTokens` uses the provider refresh path, but this condition still selects `minimumTokenResponseSchema` whenever the sync endpoint is configured. That bypasses the provider schema and strips provider-specific fields from ordinary refresh responses; pass the actual response source into this parser or use `schema` for provider responses.</violation>
<violation number="3" location="packages/app-store/_utils/oauth/parseRefreshTokenResponse.ts:25">
P1: When an OAuth refresh response omits `refresh_token`, this helper fabricates a literal token instead of leaving the existing credential intact. Office 365 merges the parsed data over the old credential and persists that literal, causing the next refresh to fail; do not add a placeholder when the field is absent.</violation>
</file>
<file name="packages/app-store/salesforce/lib/CalendarService.ts">
<violation number="1" location="packages/app-store/salesforce/lib/CalendarService.ts:75">
P1: When credential sharing is enabled, this bypasses the configured credential-sync endpoint and refreshes with the local Salesforce token instead. Wrap the Salesforce request with `refreshOAuthTokens` using the Salesforce app slug and `credential.userId`.</violation>
<violation number="2" location="packages/app-store/salesforce/lib/CalendarService.ts:86">
P2: A valid 2xx token response can be rejected when its reason phrase is empty or not exactly `OK`. Check `response.ok` instead of comparing `response.statusText` to a literal.</violation>
<violation number="3" location="packages/app-store/salesforce/lib/CalendarService.ts:90">
P2: After refreshing and persisting the token, the connection still starts with the expired access token from `credentialKey`. Pass `accessTokenParsed.data.access_token` and `accessTokenParsed.data.instance_url` to `jsforce.Connection`.</violation>
</file>
```
</details>
<sub>Reply with feedback, questions, or to request a fix.<br /><br />[Re-trigger cubic](https://www.cubic.dev/action/re-review/pr/drape-io/crbench-cubic-2026-09/18/ai_pr_review_github_delivery_1df8bec2393c69e9136660d65bf412a74cab5c0f208f7db37ce3d72e69f165a7?returnTo=https%3A%2F%2Fgithub.com%2Fdrape-io%2Fcrbench-cubic-2026-09%2Fpull%2F18)</sub>
<!-- cubic:review-post:ai_pr_review_github_delivery_1df8bec2393c69e9136660d65bf412a74cab5c0f208f7db37ce3d72e69f165a7:a533fee20a976ef9278c66aded6bede9dd9b1788:bad0f17c-12eb-5572-bf96-97149e6053eb -->
cursor · cross-file engine perris 0.11.1+proven.tiered0.25.call.read.subclass.type
| Defect | Severity | Found | Grade |
|---|---|---|---|
| d1 | high | ✓ | exact |
| d2 | high | ✓ | exact |
| d3 | high | ✓ | exact |
| d4 | high | ✓ | exact |
| d5 | high | ✓ | exact |
| d6 | high | ✗ | — |
| d7 | medium | ✓ | exact |
The new code fetches a fresh token and stores accessTokenParsed.data, but the jsforce.Connection is still built from the stale credentialKey.access_token, so the refresh is ignored. jsforce may still refresh the token itself, since it is given refreshToken, clientId and clientSecret. That lowers the impact but does not make the stale-token wiring correct. [grounded: tree packages/app-store/salesforce/lib/CalendarService.ts] [consensus 3/5: valid=3, invalid=2]
raw comments (7)
### Google stores parse wrapper as credentials
**High Severity**
<!-- DESCRIPTION START -->
`parseRefreshTokenResponse` returns a Zod `safeParse` result, but that whole object is written to `credential.key`. After the first Google token refresh, later loads fail `googleCredentialSchema.parse` because the stored shape is `{ success, data }` instead of the token fields, so Google Calendar stops working for everyone, including when credential sharing is off.
<!-- DESCRIPTION END -->
<!-- BUGBOT_BUG_ID: 819fcb55-6810-4fec-9393-7503a2d0e1b0 -->
<!-- LOCATIONS START
packages/app-store/googlecalendar/lib/CalendarService.ts#L96-L100
LOCATIONS END -->
<div><a href="https://cursor.com/open?link=eyJ2ZXJzaW9uIjoxLCJ0eXBlIjoiQlVHQk9UX0ZJWF9JTl9DVVJTT1IiLCJkYXRhIjp7InJlZGlzS2V5IjoiYnVnYm90OjQyYzRiMmQwLTZkMjUtNGFlZS04NTc1LTIwNzU4ZWM4ZTM4ZCIsImVuY3J5cHRpb25LZXkiOiIyaVc1UlcxWEtzRnJQZ1dfLUVHRTBZYVhwQnRnRG0xcFdjUWRiVlZES1hBIiwiYnJhbmNoIjoidDItY2FsLWNvbS0xMTA1OSIsInJlcG9Pd25lciI6ImRyYXBlLWlvIiwicmVwb05hbWUiOiJjcmJlbmNoLWN1cnNvci0yMDI2LTA5IiwicHJvdmlkZXIiOiJnaXRodWIifX0" target="_blank" rel="noopener noreferrer"><picture><source media="(prefers-color-scheme: dark)" srcset="https://cursor.com/assets/images/fix-in-cursor-dark.png"><source media="(prefers-color-scheme: light)" srcset="https://cursor.com/assets/images/fix-in-cursor-light.png"><img alt="Fix in Cursor" width="115" height="28" src="https://cursor.com/assets/images/fix-in-cursor-dark.png"></picture></a> <a href="https://cursor.com/agents?link=eyJ2ZXJzaW9uIjoxLCJ0eXBlIjoiQlVHQk9UX0ZJWF9JTl9XRUIiLCJkYXRhIjp7InJlZGlzS2V5IjoiYnVnYm90OjQyYzRiMmQwLTZkMjUtNGFlZS04NTc1LTIwNzU4ZWM4ZTM4ZCIsImVuY3J5cHRpb25LZXkiOiIyaVc1UlcxWEtzRnJQZ1dfLUVHRTBZYVhwQnRnRG0xcFdjUWRiVlZES1hBIiwiYnJhbmNoIjoidDItY2FsLWNvbS0xMTA1OSIsInJlcG9Pd25lciI6ImRyYXBlLWlvIiwicmVwb05hbWUiOiJjcmJlbmNoLWN1cnNvci0yMDI2LTA5IiwicHJOdW1iZXIiOjE4LCJjb21taXRTaGEiOiI1M2U5ZTc2YTEyYTU1YzY0ZWNhMGQ3NzE0NmI5OWY1ZWFhMTBjZjY4IiwicHJvdmlkZXIiOiJnaXRodWIifX0" target="_blank" rel="noopener noreferrer"><picture><source media="(prefers-color-scheme: dark)" srcset="https://cursor.com/assets/images/fix-in-web-dark.png"><source media="(prefers-color-scheme: light)" srcset="https://cursor.com/assets/images/fix-in-web-light.png"><img alt="Fix in Web" width="99" height="28" src="https://cursor.com/assets/images/fix-in-web-dark.png"></picture></a></div>
<sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit 53e9e76a12a55c64eca0d77146b99f5eaa10cf68. Configure [here](https://www.cursor.com/dashboard/bugbot).</sup>
### Dummy refresh token overwrites real tokens
**High Severity**
<!-- DESCRIPTION START -->
When a refresh payload omits `refresh_token`, `parseRefreshTokenResponse` writes the literal string `refresh_token` onto the parsed data. Callers then persist that value, replacing the real refresh token. Later refreshes fail with invalid grant and the integration must be reconnected.
<!-- DESCRIPTION END -->
<!-- BUGBOT_BUG_ID: bd3dba63-7e12-4645-806d-eda42922e52c -->
<!-- LOCATIONS START
packages/app-store/_utils/oauth/parseRefreshTokenResponse.ts#L24-L27
packages/app-store/office365calendar/lib/CalendarService.ts#L262-L271
packages/app-store/zoomvideo/lib/VideoApiAdapter.ts#L103-L124
LOCATIONS END -->
<details>
<summary>Additional Locations (2)</summary>
- [`packages/app-store/office365calendar/lib/CalendarService.ts#L262-L271`](https://github.com/drape-io/crbench-cursor-2026-09/blob/53e9e76a12a55c64eca0d77146b99f5eaa10cf68/packages/app-store/office365calendar/lib/CalendarService.ts#L262-L271)
- [`packages/app-store/zoomvideo/lib/VideoApiAdapter.ts#L103-L124`](https://github.com/drape-io/crbench-cursor-2026-09/blob/53e9e76a12a55c64eca0d77146b99f5eaa10cf68/packages/app-store/zoomvideo/lib/VideoApiAdapter.ts#L103-L124)
</details>
<div><a href="https://cursor.com/open?link=eyJ2ZXJzaW9uIjoxLCJ0eXBlIjoiQlVHQk9UX0ZJWF9JTl9DVVJTT1IiLCJkYXRhIjp7InJlZGlzS2V5IjoiYnVnYm90OjQ1M2YyMzg3LTMxZGQtNGJhNC1iNjY0LWY1Njk5ZWViMzgyNiIsImVuY3J5cHRpb25LZXkiOiJLRHl4djVsY1R6bGhkQTVhS3BidHJhRDNLX2E3M3dyMk0ySzhHYll6d0NvIiwiYnJhbmNoIjoidDItY2FsLWNvbS0xMTA1OSIsInJlcG9Pd25lciI6ImRyYXBlLWlvIiwicmVwb05hbWUiOiJjcmJlbmNoLWN1cnNvci0yMDI2LTA5IiwicHJvdmlkZXIiOiJnaXRodWIifX0" target="_blank" rel="noopener noreferrer"><picture><source media="(prefers-color-scheme: dark)" srcset="https://cursor.com/assets/images/fix-in-cursor-dark.png"><source media="(prefers-color-scheme: light)" srcset="https://cursor.com/assets/images/fix-in-cursor-light.png"><img alt="Fix in Cursor" width="115" height="28" src="https://cursor.com/assets/images/fix-in-cursor-dark.png"></picture></a> <a href="https://cursor.com/agents?link=eyJ2ZXJzaW9uIjoxLCJ0eXBlIjoiQlVHQk9UX0ZJWF9JTl9XRUIiLCJkYXRhIjp7InJlZGlzS2V5IjoiYnVnYm90OjQ1M2YyMzg3LTMxZGQtNGJhNC1iNjY0LWY1Njk5ZWViMzgyNiIsImVuY3J5cHRpb25LZXkiOiJLRHl4djVsY1R6bGhkQTVhS3BidHJhRDNLX2E3M3dyMk0ySzhHYll6d0NvIiwiYnJhbmNoIjoidDItY2FsLWNvbS0xMTA1OSIsInJlcG9Pd25lciI6ImRyYXBlLWlvIiwicmVwb05hbWUiOiJjcmJlbmNoLWN1cnNvci0yMDI2LTA5IiwicHJOdW1iZXIiOjE4LCJjb21taXRTaGEiOiI1M2U5ZTc2YTEyYTU1YzY0ZWNhMGQ3NzE0NmI5OWY1ZWFhMTBjZjY4IiwicHJvdmlkZXIiOiJnaXRodWIifX0" target="_blank" rel="noopener noreferrer"><picture><source media="(prefers-color-scheme: dark)" srcset="https://cursor.com/assets/images/fix-in-web-dark.png"><source media="(prefers-color-scheme: light)" srcset="https://cursor.com/assets/images/fix-in-web-light.png"><img alt="Fix in Web" width="99" height="28" src="https://cursor.com/assets/images/fix-in-web-dark.png"></picture></a></div>
<sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit 53e9e76a12a55c64eca0d77146b99f5eaa10cf68. Configure [here](https://www.cursor.com/dashboard/bugbot).</sup>
### Minimum token schema strips required fields
**High Severity**
<!-- DESCRIPTION START -->
`minimumTokenResponseSchema` uses `[z.string().toString()]` as object keys, which become the static string `[object Object]` at definition time. Zod then keeps `access_token` and strips expiry, `refresh_token`, and other fields. Credential sharing therefore stores incomplete tokens and breaks subsequent refreshes.
<!-- DESCRIPTION END -->
<!-- BUGBOT_BUG_ID: a4fe5edd-c28e-40c8-994e-98d5753b2fb1 -->
<!-- LOCATIONS START
packages/app-store/_utils/oauth/parseRefreshTokenResponse.ts#L4-L11
LOCATIONS END -->
<div><a href="https://cursor.com/open?link=eyJ2ZXJzaW9uIjoxLCJ0eXBlIjoiQlVHQk9UX0ZJWF9JTl9DVVJTT1IiLCJkYXRhIjp7InJlZGlzS2V5IjoiYnVnYm90OjcyNGJlYTg2LTI3YmItNDBlYS05ZjhhLWZjMmUyMDU3MTQxYSIsImVuY3J5cHRpb25LZXkiOiJrVC1xaDJXekY4Zk5DeTNCOXFxMXBUOXU1ckxFUnRPYkpldXVFM3BXQnM0IiwiYnJhbmNoIjoidDItY2FsLWNvbS0xMTA1OSIsInJlcG9Pd25lciI6ImRyYXBlLWlvIiwicmVwb05hbWUiOiJjcmJlbmNoLWN1cnNvci0yMDI2LTA5IiwicHJvdmlkZXIiOiJnaXRodWIifX0" target="_blank" rel="noopener noreferrer"><picture><source media="(prefers-color-scheme: dark)" srcset="https://cursor.com/assets/images/fix-in-cursor-dark.png"><source media="(prefers-color-scheme: light)" srcset="https://cursor.com/assets/images/fix-in-cursor-light.png"><img alt="Fix in Cursor" width="115" height="28" src="https://cursor.com/assets/images/fix-in-cursor-dark.png"></picture></a> <a href="https://cursor.com/agents?link=eyJ2ZXJzaW9uIjoxLCJ0eXBlIjoiQlVHQk9UX0ZJWF9JTl9XRUIiLCJkYXRhIjp7InJlZGlzS2V5IjoiYnVnYm90OjcyNGJlYTg2LTI3YmItNDBlYS05ZjhhLWZjMmUyMDU3MTQxYSIsImVuY3J5cHRpb25LZXkiOiJrVC1xaDJXekY4Zk5DeTNCOXFxMXBUOXU1ckxFUnRPYkpldXVFM3BXQnM0IiwiYnJhbmNoIjoidDItY2FsLWNvbS0xMTA1OSIsInJlcG9Pd25lciI6ImRyYXBlLWlvIiwicmVwb05hbWUiOiJjcmJlbmNoLWN1cnNvci0yMDI2LTA5IiwicHJOdW1iZXIiOjE4LCJjb21taXRTaGEiOiI1M2U5ZTc2YTEyYTU1YzY0ZWNhMGQ3NzE0NmI5OWY1ZWFhMTBjZjY4IiwicHJvdmlkZXIiOiJnaXRodWIifX0" target="_blank" rel="noopener noreferrer"><picture><source media="(prefers-color-scheme: dark)" srcset="https://cursor.com/assets/images/fix-in-web-dark.png"><source media="(prefers-color-scheme: light)" srcset="https://cursor.com/assets/images/fix-in-web-light.png"><img alt="Fix in Web" width="99" height="28" src="https://cursor.com/assets/images/fix-in-web-dark.png"></picture></a></div>
<sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit 53e9e76a12a55c64eca0d77146b99f5eaa10cf68. Configure [here](https://www.cursor.com/dashboard/bugbot).</sup>
### Sync refresh returns incompatible response shape
**High Severity**
<!-- DESCRIPTION START -->
When credential sync is on, `refreshOAuthTokens` always returns a `fetch` `Response`, but callers still treat it as the original provider result. Google reads `res.data`, HubSpot reads `expiresIn`/`accessToken`, and Zoho reads axios `.data`. Token refresh therefore throws or writes invalid credentials whenever sharing is enabled.
<!-- DESCRIPTION END -->
<!-- BUGBOT_BUG_ID: 23fac507-6544-43c6-81cc-748f6222ce30 -->
<!-- LOCATIONS START
packages/app-store/_utils/oauth/refreshOAuthTokens.ts#L4-L15
packages/app-store/googlecalendar/lib/CalendarService.ts#L85-L96
packages/app-store/hubspot/lib/CalendarService.ts#L176-L192
LOCATIONS END -->
<details>
<summary>Additional Locations (2)</summary>
- [`packages/app-store/googlecalendar/lib/CalendarService.ts#L85-L96`](https://github.com/drape-io/crbench-cursor-2026-09/blob/53e9e76a12a55c64eca0d77146b99f5eaa10cf68/packages/app-store/googlecalendar/lib/CalendarService.ts#L85-L96)
- [`packages/app-store/hubspot/lib/CalendarService.ts#L176-L192`](https://github.com/drape-io/crbench-cursor-2026-09/blob/53e9e76a12a55c64eca0d77146b99f5eaa10cf68/packages/app-store/hubspot/lib/CalendarService.ts#L176-L192)
</details>
<div><a href="https://cursor.com/open?link=eyJ2ZXJzaW9uIjoxLCJ0eXBlIjoiQlVHQk9UX0ZJWF9JTl9DVVJTT1IiLCJkYXRhIjp7InJlZGlzS2V5IjoiYnVnYm90Ojg3N2I3OTIwLTg0YmMtNDU4OS04ZWExLTQ2ZWNlNjYyNzBlNyIsImVuY3J5cHRpb25LZXkiOiJLSU0xeDB5NUNreVE2Yi1FUGJUYkpHazhCZkkwcmFCZjhtd3N0VTB4NlVNIiwiYnJhbmNoIjoidDItY2FsLWNvbS0xMTA1OSIsInJlcG9Pd25lciI6ImRyYXBlLWlvIiwicmVwb05hbWUiOiJjcmJlbmNoLWN1cnNvci0yMDI2LTA5IiwicHJvdmlkZXIiOiJnaXRodWIifX0" target="_blank" rel="noopener noreferrer"><picture><source media="(prefers-color-scheme: dark)" srcset="https://cursor.com/assets/images/fix-in-cursor-dark.png"><source media="(prefers-color-scheme: light)" srcset="https://cursor.com/assets/images/fix-in-cursor-light.png"><img alt="Fix in Cursor" width="115" height="28" src="https://cursor.com/assets/images/fix-in-cursor-dark.png"></picture></a> <a href="https://cursor.com/agents?link=eyJ2ZXJzaW9uIjoxLCJ0eXBlIjoiQlVHQk9UX0ZJWF9JTl9XRUIiLCJkYXRhIjp7InJlZGlzS2V5IjoiYnVnYm90Ojg3N2I3OTIwLTg0YmMtNDU4OS04ZWExLTQ2ZWNlNjYyNzBlNyIsImVuY3J5cHRpb25LZXkiOiJLSU0xeDB5NUNreVE2Yi1FUGJUYkpHazhCZkkwcmFCZjhtd3N0VTB4NlVNIiwiYnJhbmNoIjoidDItY2FsLWNvbS0xMTA1OSIsInJlcG9Pd25lciI6ImRyYXBlLWlvIiwicmVwb05hbWUiOiJjcmJlbmNoLWN1cnNvci0yMDI2LTA5IiwicHJOdW1iZXIiOjE4LCJjb21taXRTaGEiOiI1M2U5ZTc2YTEyYTU1YzY0ZWNhMGQ3NzE0NmI5OWY1ZWFhMTBjZjY4IiwicHJvdmlkZXIiOiJnaXRodWIifX0" target="_blank" rel="noopener noreferrer"><picture><source media="(prefers-color-scheme: dark)" srcset="https://cursor.com/assets/images/fix-in-web-dark.png"><source media="(prefers-color-scheme: light)" srcset="https://cursor.com/assets/images/fix-in-web-light.png"><img alt="Fix in Web" width="99" height="28" src="https://cursor.com/assets/images/fix-in-web-dark.png"></picture></a></div>
<sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit 53e9e76a12a55c64eca0d77146b99f5eaa10cf68. Configure [here](https://www.cursor.com/dashboard/bugbot).</sup>
### Salesforce connection uses expired access token
**High Severity**
<!-- DESCRIPTION START -->
`getClient` now always refreshes, saves the new token, then constructs `jsforce.Connection` with `credentialKey.access_token` from before the refresh. API calls use the stale token. After expiry, Salesforce create/update/contact operations fail even though a fresh token was just stored.
<!-- DESCRIPTION END -->
<!-- BUGBOT_BUG_ID: e16291d2-8dd5-431b-bae2-a2475856a0aa -->
<!-- LOCATIONS START
packages/app-store/salesforce/lib/CalendarService.ts#L95-L108
LOCATIONS END -->
<div><a href="https://cursor.com/open?link=eyJ2ZXJzaW9uIjoxLCJ0eXBlIjoiQlVHQk9UX0ZJWF9JTl9DVVJTT1IiLCJkYXRhIjp7InJlZGlzS2V5IjoiYnVnYm90OjIxODEwOTI5LWJiODEtNGNhMS05ZDQ2LTg4OGRiYWM1NjZhYyIsImVuY3J5cHRpb25LZXkiOiJNWFh5UlVIYVZ2NHZmRVJfTXRzWEU2WXRoZHQ4US1FQmt5VDdrSWxiamdZIiwiYnJhbmNoIjoidDItY2FsLWNvbS0xMTA1OSIsInJlcG9Pd25lciI6ImRyYXBlLWlvIiwicmVwb05hbWUiOiJjcmJlbmNoLWN1cnNvci0yMDI2LTA5IiwicHJvdmlkZXIiOiJnaXRodWIifX0" target="_blank" rel="noopener noreferrer"><picture><source media="(prefers-color-scheme: dark)" srcset="https://cursor.com/assets/images/fix-in-cursor-dark.png"><source media="(prefers-color-scheme: light)" srcset="https://cursor.com/assets/images/fix-in-cursor-light.png"><img alt="Fix in Cursor" width="115" height="28" src="https://cursor.com/assets/images/fix-in-cursor-dark.png"></picture></a> <a href="https://cursor.com/agents?link=eyJ2ZXJzaW9uIjoxLCJ0eXBlIjoiQlVHQk9UX0ZJWF9JTl9XRUIiLCJkYXRhIjp7InJlZGlzS2V5IjoiYnVnYm90OjIxODEwOTI5LWJiODEtNGNhMS05ZDQ2LTg4OGRiYWM1NjZhYyIsImVuY3J5cHRpb25LZXkiOiJNWFh5UlVIYVZ2NHZmRVJfTXRzWEU2WXRoZHQ4US1FQmt5VDdrSWxiamdZIiwiYnJhbmNoIjoidDItY2FsLWNvbS0xMTA1OSIsInJlcG9Pd25lciI6ImRyYXBlLWlvIiwicmVwb05hbWUiOiJjcmJlbmNoLWN1cnNvci0yMDI2LTA5IiwicHJOdW1iZXIiOjE4LCJjb21taXRTaGEiOiI1M2U5ZTc2YTEyYTU1YzY0ZWNhMGQ3NzE0NmI5OWY1ZWFhMTBjZjY4IiwicHJvdmlkZXIiOiJnaXRodWIifX0" target="_blank" rel="noopener noreferrer"><picture><source media="(prefers-color-scheme: dark)" srcset="https://cursor.com/assets/images/fix-in-web-dark.png"><source media="(prefers-color-scheme: light)" srcset="https://cursor.com/assets/images/fix-in-web-light.png"><img alt="Fix in Web" width="99" height="28" src="https://cursor.com/assets/images/fix-in-web-dark.png"></picture></a></div>
<sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit 53e9e76a12a55c64eca0d77146b99f5eaa10cf68. Configure [here](https://www.cursor.com/dashboard/bugbot).</sup>
### Zoho Bigin passes credential id as user
**Medium Severity**
<!-- DESCRIPTION START -->
`refreshOAuthTokens` is called with `credentialId` as the third argument, which is the user id. With credential sync enabled, the parent receives `calcomUserId` set to the credential primary key, so it refreshes the wrong user's tokens or finds none.
<!-- DESCRIPTION END -->
<!-- BUGBOT_BUG_ID: 857d6d4f-5b2e-4cbf-8eff-bd4a309944ed -->
<!-- LOCATIONS START
packages/app-store/zoho-bigin/lib/CalendarService.ts#L84-L93
LOCATIONS END -->
<div><a href="https://cursor.com/open?link=eyJ2ZXJzaW9uIjoxLCJ0eXBlIjoiQlVHQk9UX0ZJWF9JTl9DVVJTT1IiLCJkYXRhIjp7InJlZGlzS2V5IjoiYnVnYm90OjM2OWQ0ZjM2LTMwMWMtNGMyYy04YzRkLTAzMWI2MDk2OWY4NiIsImVuY3J5cHRpb25LZXkiOiJ5R3ZHeWJZNDJITlZnenliMFpHV1dHaFNRcm12R0diS21Qc2NLWDFTcEFRIiwiYnJhbmNoIjoidDItY2FsLWNvbS0xMTA1OSIsInJlcG9Pd25lciI6ImRyYXBlLWlvIiwicmVwb05hbWUiOiJjcmJlbmNoLWN1cnNvci0yMDI2LTA5IiwicHJvdmlkZXIiOiJnaXRodWIifX0" target="_blank" rel="noopener noreferrer"><picture><source media="(prefers-color-scheme: dark)" srcset="https://cursor.com/assets/images/fix-in-cursor-dark.png"><source media="(prefers-color-scheme: light)" srcset="https://cursor.com/assets/images/fix-in-cursor-light.png"><img alt="Fix in Cursor" width="115" height="28" src="https://cursor.com/assets/images/fix-in-cursor-dark.png"></picture></a> <a href="https://cursor.com/agents?link=eyJ2ZXJzaW9uIjoxLCJ0eXBlIjoiQlVHQk9UX0ZJWF9JTl9XRUIiLCJkYXRhIjp7InJlZGlzS2V5IjoiYnVnYm90OjM2OWQ0ZjM2LTMwMWMtNGMyYy04YzRkLTAzMWI2MDk2OWY4NiIsImVuY3J5cHRpb25LZXkiOiJ5R3ZHeWJZNDJITlZnenliMFpHV1dHaFNRcm12R0diS21Qc2NLWDFTcEFRIiwiYnJhbmNoIjoidDItY2FsLWNvbS0xMTA1OSIsInJlcG9Pd25lciI6ImRyYXBlLWlvIiwicmVwb05hbWUiOiJjcmJlbmNoLWN1cnNvci0yMDI2LTA5IiwicHJOdW1iZXIiOjE4LCJjb21taXRTaGEiOiI1M2U5ZTc2YTEyYTU1YzY0ZWNhMGQ3NzE0NmI5OWY1ZWFhMTBjZjY4IiwicHJvdmlkZXIiOiJnaXRodWIifX0" target="_blank" rel="noopener noreferrer"><picture><source media="(prefers-color-scheme: dark)" srcset="https://cursor.com/assets/images/fix-in-web-dark.png"><source media="(prefers-color-scheme: light)" srcset="https://cursor.com/assets/images/fix-in-web-light.png"><img alt="Fix in Web" width="99" height="28" src="https://cursor.com/assets/images/fix-in-web-dark.png"></picture></a></div>
<sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit 53e9e76a12a55c64eca0d77146b99f5eaa10cf68. Configure [here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- BUGBOT_REVIEW -->
Cursor Bugbot has reviewed your changes using high effort and found 6 potential issues.
<!-- BUGBOT_FIX_ALL -->
<a href="https://cursor.com/open?link=eyJ2ZXJzaW9uIjoxLCJ0eXBlIjoiQlVHQk9UX0ZJWF9BTExfSU5fQ1VSU09SIiwiZGF0YSI6eyJyZWRpc0tleSI6ImJ1Z2JvdC1tdWx0aTpkZjk2YmU0MC01NTdmLTQ5ZWEtOGM0Ny1mZTVkYzQxNmFmZWQiLCJlbmNyeXB0aW9uS2V5IjoiNHFqeEZtQ21ZTmxsQWlyZ2VjT3E3QWE4eGkwTGFIZjJ1WlpHM0YtaWRkSSIsImJyYW5jaCI6InQyLWNhbC1jb20tMTEwNTkiLCJyZXBvT3duZXIiOiJkcmFwZS1pbyIsInJlcG9OYW1lIjoiY3JiZW5jaC1jdXJzb3ItMjAyNi0wOSIsInByb3ZpZGVyIjoiZ2l0aHViIn19" target="_blank" rel="noopener noreferrer"><picture><source media="(prefers-color-scheme: dark)" srcset="https://cursor.com/assets/images/fix-in-cursor-dark.png"><source media="(prefers-color-scheme: light)" srcset="https://cursor.com/assets/images/fix-in-cursor-light.png"><img alt="Fix All in Cursor" width="115" height="28" src="https://cursor.com/assets/images/fix-in-cursor-dark.png"></picture></a>
<!-- /BUGBOT_FIX_ALL -->
<!-- BUGBOT_AUTOFIX_REVIEW_FOOTNOTE_BEGIN -->
<sup>❌ Bugbot Autofix is OFF. To automatically fix reported issues with cloud agents, enable autofix in the [Cursor dashboard](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- BUGBOT_AUTOFIX_REVIEW_FOOTNOTE_END -->
<sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit 53e9e76a12a55c64eca0d77146b99f5eaa10cf68. Configure [here](https://www.cursor.com/dashboard/bugbot).</sup>
Drape (Deep Review) · cross-file engine perris 0.11.1+proven.tiered0.25.call.read.subclass.type
| Defect | Severity | Found | Grade |
|---|---|---|---|
| d1 | high | ✓ | off by one |
| d2 | high | ✓ | exact |
| d3 | high | ✓ | exact |
| d4 | high | ✓ | exact |
| d5 | high | ✓ | exact |
| d6 | high | ✓ | wrong severity |
| d7 | medium | ✓ | off by one |
getClient unconditionally refreshes and writes DB on each construction, then the Connection uses credentialKey.access_token (old) rather than the refreshed one. [grounded: diff] [consensus 3/3: valid=3]
New webhook compares secret with plain !==, a non-constant-time comparison on a credential-writing endpoint; practical exploitability is limited. [grounded: diff] [consensus 3/3: valid=3]
When sync is enabled refreshOAuthTokens returns a fetch Response which has no .data, so tokenInfo.data.error throws a TypeError. [grounded: diff] [consensus 3/3: valid=3]
The refreshed token is saved to DB but the jsforce Connection is still built from the old credentialKey access_token/instance_url. [grounded: tree packages/app-store/salesforce/lib/CalendarService.ts] [consensus 3/3: valid=3]
parse, symmetricDecrypt and JSON.parse throw uncaught in the new handler, producing 500s for bad client input; keys unvalidated. [grounded: diff] [consensus 3/3: valid=3]
The sync request carries no authentication secret and the response is returned without an ok check; callers then parse error bodies as tokens. [grounded: tree packages/app-store/_utils/oauth/refreshOAuthTokens.ts] [consensus 3/3: valid=3]
In sync mode the returned fetch Response has no .data, so accessing .data.error throws, gets caught and logged, and no refresh happens. [grounded: diff] [consensus 3/3: valid=3]
Previously safeParse failure was logged and execution continued; parseRefreshTokenResponse now throws on failure, changing behavior and dropping diagnostics. [grounded: diff] [consensus 3/3: valid=3]
Sync endpoint response (only access token and expiry) lacks Lark's code field, so handleLarkError throws on every sync-mode refresh, and data.data fields are also missing. [grounded: tree packages/app-store/larkcalendar/common.ts] [consensus 3/3: valid=3]
raw comments (16)
**Salesforce token refreshed on every service creation**
`getClient` now calls Salesforce's token endpoint and writes the DB every time the service is constructed, even when the token is still valid. It then builds the connection with the old `credentialKey.access_token` and throws the new one away. Refresh only when needed, and pass the new access_token/instance_url to `jsforce.Connection`.
```
packages/app-store/salesforce/lib/CalendarService.ts:75 const response = await fetch("https://login.salesforce.com/services/oauth2/token", {
packages/app-store/salesforce/lib/CalendarService.ts:76 method: "POST",
packages/app-store/salesforce/lib/CalendarService.ts:77 body: new URLSearchParams({
packages/app-store/salesforce/lib/CalendarService.ts:78 grant_type: "refresh_token",
packages/app-store/salesforce/lib/CalendarService.ts:101 return new jsforce.Connection({
packages/app-store/salesforce/lib/CalendarService.ts:102 clientId: consumer_key,
packages/app-store/salesforce/lib/CalendarService.ts:103 clientSecret: consumer_secret,
packages/app-store/salesforce/lib/CalendarService.ts:104 redirectUri: WEBAPP_URL + "/api/integrations/salesforce/callback",
packages/app-store/salesforce/lib/CalendarService.ts:105 instanceUrl: credentialKey.instance_url,
packages/app-store/salesforce/lib/CalendarService.ts:106 accessToken: credentialKey.access_token,
```
**Success check relies on statusText being "OK"**
A successful response with an empty or different reason phrase (e.g. over HTTP/2, or a proxy) is treated as a failure, so the Salesforce client throws. `response.ok` is the reliable check. Use `if (!response.ok)`.
```
packages/app-store/salesforce/lib/CalendarService.ts:86 if (response.statusText !== "OK") throw new HttpError({ statusCode: 400, message: response.statusText });
```
**Webhook secret compared with non-constant-time !==**
The shared secret is checked with a plain string comparison, which can leak how much of the secret matched through response timing on a public endpoint that writes credentials. Compare with `crypto.timingSafeEqual`.
```
apps/web/pages/api/webhook/app-credential.ts:24 if (
apps/web/pages/api/webhook/app-credential.ts:25 req.headers[process.env.CALCOM_WEBHOOK_HEADER_NAME || "calcom-webhook-secret"] !==
apps/web/pages/api/webhook/app-credential.ts:26 process.env.CALCOM_WEBHOOK_SECRET
apps/web/pages/api/webhook/app-credential.ts:27 ) {
```
**Bigin sync fetches another user's tokens**
`credentialId` is passed to `refreshOAuthTokens`, which sends it as `calcomUserId` to the sync endpoint. The parent app then returns tokens for some other user, and they get saved on this credential. Pass the credential's `userId` instead of `credentialId`.
```
packages/app-store/zoho-bigin/lib/CalendarService.ts:85 const tokenInfo = await refreshOAuthTokens(
packages/app-store/zoho-bigin/lib/CalendarService.ts:86 async () =>
packages/app-store/zoho-bigin/lib/CalendarService.ts:87 await axios.post(accountsUrl, qs.stringify(formData), {
packages/app-store/zoho-bigin/lib/CalendarService.ts:88 headers: {
packages/app-store/_utils/oauth/refreshOAuthTokens.ts:11 calcomUserId: userId.toString(),
```
**Google credential saved as zod result wrapper**
`parseRefreshTokenResponse` returns the safeParse result `{ success, data }`, and that whole object is now written as the credential `key`. On the next load, `googleCredentialSchema.parse(credential.key)` fails, so Google Calendar stops working after its first token refresh. Store `parseRefreshTokenResponse(...).data` as the key.
```
packages/app-store/googlecalendar/lib/CalendarService.ts:97 const key = parseRefreshTokenResponse(googleCredentials, googleCredentialSchema);
packages/app-store/googlecalendar/lib/CalendarService.ts:98 await prisma.credential.update({
packages/app-store/googlecalendar/lib/CalendarService.ts:99 where: { id: credential.id },
packages/app-store/googlecalendar/lib/CalendarService.ts:100 data: { key },
packages/app-store/_utils/oauth/parseRefreshTokenResponse.ts:29 return refreshTokenResponse;
packages/app-store/googlecalendar/lib/CalendarService.ts:75 const googleCredentials = googleCredentialSchema.parse(credential.key);
```
**Sync token schema strips expiry fields**
`z.string().toString()` and `z.string().optional().toString()` both give the key "[object Object]", so `minimumTokenResponseSchema` only declares `access_token`. Zod drops unknown keys, so in sync mode `expires_in` and `expiry_date` are removed and callers save NaN or missing expiry dates. Use `z.object({ access_token: z.string() }).passthrough()` or a schema with real expiry fields.
```
packages/app-store/_utils/oauth/parseRefreshTokenResponse.ts:5 const minimumTokenResponseSchema = z.object({
packages/app-store/_utils/oauth/parseRefreshTokenResponse.ts:6 access_token: z.string(),
packages/app-store/_utils/oauth/parseRefreshTokenResponse.ts:7 // Assume that any property with a number is the expiry
packages/app-store/_utils/oauth/parseRefreshTokenResponse.ts:8 [z.string().toString()]: z.number(),
packages/app-store/zoomvideo/lib/VideoApiAdapter.ts:122 key.expiry_date = Math.round(Date.now() + newTokens.expires_in * 1000);
packages/app-store/zoomvideo/lib/VideoApiAdapter.ts:54 expiry_date: z.number(),
```
**Real refresh token overwritten with literal string**
When a refresh response has no `refresh_token`, it is set to the string "refresh_token". Office 365 spreads this over the stored credentials, so the real refresh token is replaced and later refreshes fail. Leave `refresh_token` unset so callers keep the stored value.
```
packages/app-store/_utils/oauth/parseRefreshTokenResponse.ts:25 if (!refreshTokenResponse.data.refresh_token) {
packages/app-store/_utils/oauth/parseRefreshTokenResponse.ts:26 refreshTokenResponse.data.refresh_token = "refresh_token";
packages/app-store/_utils/oauth/parseRefreshTokenResponse.ts:27 }
packages/app-store/office365calendar/lib/CalendarService.ts:263 const tokenResponse = parseRefreshTokenResponse(responseJson, refreshTokenResponseSchema);
packages/app-store/office365calendar/lib/CalendarService.ts:56 refresh_token: z.string().optional(),
packages/app-store/office365calendar/lib/CalendarService.ts:264 o365AuthCredentials = { ...o365AuthCredentials, ...(tokenResponse.success && tokenResponse.data) };
```
**Hubspot saves a fetch Response as credential**
In sync mode `refreshOAuthTokens` returns a fetch `Response`, which is used as a `HubspotToken`. `expiresIn` is undefined, so `expiryDate` is NaN, and the Response object is saved as the key, so the Hubspot credential is wiped. Parse the sync endpoint's JSON and map it to `HubspotToken` fields.
```
packages/app-store/hubspot/lib/CalendarService.ts:177 const hubspotRefreshToken: HubspotToken = await refreshOAuthTokens(
packages/app-store/hubspot/lib/CalendarService.ts:178 async () =>
packages/app-store/hubspot/lib/CalendarService.ts:179 await hubspotClient.oauth.tokensApi.createToken(
packages/app-store/hubspot/lib/CalendarService.ts:180 "refresh_token",
packages/app-store/_utils/oauth/refreshOAuthTokens.ts:8 const response = await fetch(process.env.CALCOM_CREDENTIAL_SYNC_ENDPOINT, {
packages/app-store/_utils/oauth/refreshOAuthTokens.ts:9 method: "POST",
packages/app-store/_utils/oauth/refreshOAuthTokens.ts:10 body: new URLSearchParams({
packages/app-store/_utils/oauth/refreshOAuthTokens.ts:11 calcomUserId: userId.toString(),
packages/app-store/_utils/oauth/refreshOAuthTokens.ts:12 appSlug,
packages/app-store/_utils/oauth/refreshOAuthTokens.ts:13 }),
```
**Bigin refresh crashes on fetch Response**
In sync mode `refreshOAuthTokens` returns a fetch `Response`, which has no `.data`, so `tokenInfo.data.error` throws. Normalize the sync endpoint result into the axios-like `{ data }` shape, or adapt this caller.
```
packages/app-store/zoho-bigin/lib/CalendarService.ts:85 const tokenInfo = await refreshOAuthTokens(
packages/app-store/zoho-bigin/lib/CalendarService.ts:86 async () =>
packages/app-store/zoho-bigin/lib/CalendarService.ts:87 await axios.post(accountsUrl, qs.stringify(formData), {
packages/app-store/zoho-bigin/lib/CalendarService.ts:88 headers: {
packages/app-store/_utils/oauth/refreshOAuthTokens.ts:15 return response;
```
**Google refresh breaks in sync mode**
In sync mode `refreshOAuthTokens` returns a raw fetch `Response`, so `res?.data` is undefined. The resulting TypeError is caught and the expired auth is returned. Have `refreshOAuthTokens` return parsed JSON in a consistent shape.
```
packages/app-store/googlecalendar/lib/CalendarService.ts:86 const res = await refreshOAuthTokens(
packages/app-store/googlecalendar/lib/CalendarService.ts:87 async () => {
packages/app-store/googlecalendar/lib/CalendarService.ts:88 const fetchTokens = await myGoogleAuth.refreshToken(googleCredentials.refresh_token);
packages/app-store/googlecalendar/lib/CalendarService.ts:89 return fetchTokens.res;
packages/app-store/_utils/oauth/refreshOAuthTokens.ts:15 return response;
packages/app-store/googlecalendar/lib/CalendarService.ts:94 const token = res?.data;
packages/app-store/googlecalendar/lib/CalendarService.ts:95 googleCredentials.access_token = token.access_token;
```
**New Salesforce access token is ignored**
After the refresh, the connection is still built from the old `credentialKey.access_token` and `instance_url`, not the token just fetched and saved. Build the connection from `accessTokenParsed.data`.
```
packages/app-store/salesforce/lib/CalendarService.ts:96 await prisma.credential.update({
packages/app-store/salesforce/lib/CalendarService.ts:97 where: { id: credential.id },
packages/app-store/salesforce/lib/CalendarService.ts:98 data: { key: { ...accessTokenParsed.data, refresh_token: credentialKey.refresh_token } },
packages/app-store/salesforce/lib/CalendarService.ts:99 });
packages/app-store/salesforce/lib/CalendarService.ts:105 instanceUrl: credentialKey.instance_url,
packages/app-store/salesforce/lib/CalendarService.ts:106 accessToken: credentialKey.access_token,
```
**Bad webhook bodies return 500**
A malformed body (zod `parse`), bad ciphertext (`symmetricDecrypt`) or non-JSON plaintext (`JSON.parse`) throws without being caught, so the caller gets a 500 instead of a 400. Decrypted keys are also never checked against the app's schema. Use `safeParse` and try/catch here, and return 400.
```
apps/web/pages/api/webhook/app-credential.ts:31 const reqBody = appCredentialWebhookRequestBodySchema.parse(req.body);
apps/web/pages/api/webhook/app-credential.ts:57 const keys = JSON.parse(
apps/web/pages/api/webhook/app-credential.ts:58 symmetricDecrypt(reqBody.keys, process.env.CALCOM_APP_CREDENTIAL_ENCRYPTION_KEY || "")
apps/web/pages/api/webhook/app-credential.ts:59 );
```
**Sync endpoint call is unauthenticated and unchecked**
The POST to `CALCOM_CREDENTIAL_SYNC_ENDPOINT` sends no secret, so the parent app cannot tell Cal.com apart from anyone asking for a user's tokens. Error responses also go back to callers with no `response.ok` check. Send the webhook secret header and check `response.ok`.
```
packages/app-store/_utils/oauth/refreshOAuthTokens.ts:8 const response = await fetch(process.env.CALCOM_CREDENTIAL_SYNC_ENDPOINT, {
packages/app-store/_utils/oauth/refreshOAuthTokens.ts:9 method: "POST",
packages/app-store/_utils/oauth/refreshOAuthTokens.ts:10 body: new URLSearchParams({
packages/app-store/_utils/oauth/refreshOAuthTokens.ts:11 calcomUserId: userId.toString(),
packages/app-store/_utils/oauth/refreshOAuthTokens.ts:12 appSlug,
packages/app-store/_utils/oauth/refreshOAuthTokens.ts:13 }),
packages/app-store/_utils/oauth/refreshOAuthTokens.ts:14 });
```
**Zoho CRM refresh fails when sync is on**
In sync mode `refreshOAuthTokens` returns a fetch `Response`, which has no `.data`. `zohoCrmTokenInfo.data.error` throws, the error is only logged, and the token is never refreshed. Parse the sync response JSON into the shape this code expects.
```
packages/app-store/zohocrm/lib/CalendarService.ts:204 const zohoCrmTokenInfo = await refreshOAuthTokens(
packages/app-store/zohocrm/lib/CalendarService.ts:205 async () =>
packages/app-store/zohocrm/lib/CalendarService.ts:206 await axios({
packages/app-store/zohocrm/lib/CalendarService.ts:207 method: "post",
packages/app-store/_utils/oauth/refreshOAuthTokens.ts:8 const response = await fetch(process.env.CALCOM_CREDENTIAL_SYNC_ENDPOINT, {
packages/app-store/_utils/oauth/refreshOAuthTokens.ts:9 method: "POST",
packages/app-store/_utils/oauth/refreshOAuthTokens.ts:10 body: new URLSearchParams({
packages/app-store/_utils/oauth/refreshOAuthTokens.ts:11 calcomUserId: userId.toString(),
packages/app-store/_utils/oauth/refreshOAuthTokens.ts:12 appSlug,
packages/app-store/_utils/oauth/refreshOAuthTokens.ts:13 }),
```
**Outlook refresh now throws on unexpected response**
`parseRefreshTokenResponse` throws when validation fails. Before, the code logged the error and kept the existing credentials. Now any unexpected Microsoft response breaks the calendar call, and the logged diagnostics are gone. Catch the error and log the MS response like before, or keep using safeParse.
```
packages/app-store/office365calendar/lib/CalendarService.ts:263 const tokenResponse = parseRefreshTokenResponse(responseJson, refreshTokenResponseSchema);
packages/app-store/office365calendar/lib/CalendarService.ts:264 o365AuthCredentials = { ...o365AuthCredentials, ...(tokenResponse.success && tokenResponse.data) };
packages/app-store/office365calendar/lib/CalendarService.ts:258 (base) if (!tokenResponse.success) {
packages/app-store/office365calendar/lib/CalendarService.ts:259 (base) console.error(
packages/app-store/_utils/oauth/parseRefreshTokenResponse.ts:22 throw new Error("Invalid refreshed tokens were returned");
packages/app-store/_utils/oauth/parseRefreshTokenResponse.ts:23 }
```
**Lark refresh always fails with sync endpoint**
`handleLarkError` requires a Lark envelope with `code === 0`, but the sync endpoint is documented to return only the access token and expiry. Every Lark refresh in sync mode therefore throws. Skip the Lark envelope check when the tokens come from the sync endpoint.
```
packages/app-store/larkcalendar/lib/CalendarService.ts:67 const resp = await refreshOAuthTokens(
packages/app-store/larkcalendar/lib/CalendarService.ts:68 async () =>
packages/app-store/larkcalendar/lib/CalendarService.ts:69 await fetch(`${this.url}/authen/v1/refresh_access_token`, {
packages/app-store/larkcalendar/lib/CalendarService.ts:70 method: "POST",
packages/app-store/larkcalendar/common.ts:18 if (!response.ok || data.code !== 0) {
```
Drape (Review) · cross-file engine perris 0.11.1+proven.tiered0.25.call.read.subclass.type
| Defect | Severity | Found | Grade |
|---|---|---|---|
| d1 | high | ✓ | exact |
| d2 | high | ✓ | off by one |
| d3 | high | ✓ | exact |
| d4 | high | ✓ | exact |
| d5 | high | ✓ | exact |
| d6 | high | ✗ | — |
| d7 | medium | ✓ | off by one |
The old code used safeParse and only logged a failure. The new helper throws when parsing fails, so refresh now rejects, the success guard is dead code, and the error log was removed. [grounded: diff] [consensus 3/3: valid=3]
In the new handler, parse, decrypt and JSON.parse run without try/catch, so bad input gives an unhandled 500. There is no method check, so any HTTP method reaches the handler. [grounded: diff] [consensus 3/3: valid=3]
getClient always refreshes the token and updates the DB with no expiry check. The Connection is still built with credentialKey.access_token, so the refreshed token is not used. [grounded: diff] [consensus 3/3: valid=3]
raw comments (8)
**Sync-mode schema strips expiry from refreshed tokens**
In sync mode, both computed keys become "[object Object]" and the optional one wins. The schema then requires only access_token and strips everything else, including expires_in/expiry_date. Office365 keeps the old expiry and refreshes on every call. Fix: use z.object({access_token}).passthrough() and validate the expiry explicitly.
```
packages/app-store/_utils/oauth/parseRefreshTokenResponse.ts:5 const minimumTokenResponseSchema = z.object({
packages/app-store/_utils/oauth/parseRefreshTokenResponse.ts:6 access_token: z.string(),
packages/app-store/_utils/oauth/parseRefreshTokenResponse.ts:7 // Assume that any property with a number is the expiry
packages/app-store/_utils/oauth/parseRefreshTokenResponse.ts:8 [z.string().toString()]: z.number(),
packages/app-store/_utils/oauth/parseRefreshTokenResponse.ts:9 // Allow other properties in the token response
packages/app-store/_utils/oauth/parseRefreshTokenResponse.ts:10 [z.string().optional().toString()]: z.unknown().optional(),
```
**Missing refresh_token overwritten with placeholder**
When the response lacks `refresh_token`, it is set to the literal "refresh_token" even outside sync mode. Office365 merges this over the stored credential, replacing the real refresh token. Only default the field in sync mode; otherwise keep the stored token.
```
packages/app-store/_utils/oauth/parseRefreshTokenResponse.ts:25 if (!refreshTokenResponse.data.refresh_token) {
packages/app-store/_utils/oauth/parseRefreshTokenResponse.ts:26 refreshTokenResponse.data.refresh_token = "refresh_token";
packages/app-store/office365calendar/lib/CalendarService.ts:51 const refreshTokenResponseSchema = z.object({
```
**Sync response not in callers' expected shape**
In sync mode `refreshOAuthTokens` returns the raw fetch Response, but callers read `res.data` (Google, Zoho) or token fields (HubSpot). There is also no `response.ok` check. Parse the JSON and adapt it to each caller's shape; check response.ok.
```
packages/app-store/_utils/oauth/refreshOAuthTokens.ts:5 if (APP_CREDENTIAL_SHARING_ENABLED && process.env.CALCOM_CREDENTIAL_SYNC_ENDPOINT && userId) {
packages/app-store/_utils/oauth/refreshOAuthTokens.ts:6 // Customize the payload based on what your endpoint requires
packages/app-store/_utils/oauth/refreshOAuthTokens.ts:7 // The response should only contain the access token and expiry date
packages/app-store/_utils/oauth/refreshOAuthTokens.ts:8 const response = await fetch(process.env.CALCOM_CREDENTIAL_SYNC_ENDPOINT, {
packages/app-store/zohocrm/lib/CalendarService.ts:216 );
```
**Google credential saved as wrapper object, not tokens**
`parseRefreshTokenResponse` returns a zod `safeParse` result (`{success, data}`), but it replaces `googleCredentialSchema.parse(...)` and its return value is saved as the credential `key`. The stored key becomes `{success:true, data:{...}}`. Use `.data` from the parse result when saving the key (`parseRefreshTokenResponse(...).data`).
```
packages/app-store/googlecalendar/lib/CalendarService.ts:97 const key = parseRefreshTokenResponse(googleCredentials, googleCredentialSchema);
packages/app-store/googlecalendar/lib/CalendarService.ts:98 await prisma.credential.update({
packages/app-store/googlecalendar/lib/CalendarService.ts:99 where: { id: credential.id },
packages/app-store/googlecalendar/lib/CalendarService.ts:100 data: { key },
```
**Credential id passed as user id**
The third argument of `refreshOAuthTokens` is a user id, but Bigin passes `credentialId`. In sync mode the sync endpoint is asked for the wrong user's tokens. Pass the credential's userId; thread it through from the constructor's `credential.userId`.
```
packages/app-store/zoho-bigin/lib/CalendarService.ts:85 const tokenInfo = await refreshOAuthTokens(
packages/app-store/zoho-bigin/lib/CalendarService.ts:86 async () =>
packages/app-store/zoho-bigin/lib/CalendarService.ts:87 await axios.post(accountsUrl, qs.stringify(formData), {
packages/app-store/zoho-bigin/lib/CalendarService.ts:88 headers: {
```
**Invalid O365 token response now throws**
The old code used `safeParse` and logged a failure while keeping existing credentials. `parseRefreshTokenResponse` now throws on invalid data, and the error log with the MS response is removed, so the `tokenResponse.success &&` guard is dead code.
```
packages/app-store/office365calendar/lib/CalendarService.ts:262 const responseJson = await handleErrorsJson(response);
packages/app-store/office365calendar/lib/CalendarService.ts:263 const tokenResponse = parseRefreshTokenResponse(responseJson, refreshTokenResponseSchema);
packages/app-store/office365calendar/lib/CalendarService.ts:264 o365AuthCredentials = { ...o365AuthCredentials, ...(tokenResponse.success && tokenResponse.data) };
packages/app-store/office365calendar/lib/CalendarService.ts:264 (base) );
```
**Bad webhook bodies return 500 instead of 400**
An invalid body or undecryptable/non-JSON keys makes schema.parse, symmetricDecrypt or JSON.parse throw unhandled, so the caller gets a 500 instead of a 400. Any HTTP method also reaches the handler. Fix: use safeParse, wrap the decrypt/parse in try/catch returning 400, and reject methods other than POST.
```
apps/web/pages/api/webhook/app-credential.ts:20 return res.status(403).json({ message: "Credential sharing is not enabled" });
apps/web/pages/api/webhook/app-credential.ts:21 }
apps/web/pages/api/webhook/app-credential.ts:23 // Check that the webhook secret matches
apps/web/pages/api/webhook/app-credential.ts:24 if (
```
**Salesforce refreshes token on every service construction**
getClient runs from the constructor and always calls the Salesforce token endpoint and updates the DB, even when the token is still valid. The Connection then still uses the old credentialKey.access_token. Fix: refresh only when needed, and pass the refreshed access_token and instance_url to jsforce.Connection.
```
packages/app-store/salesforce/lib/CalendarService.ts:75 const response = await fetch("https://login.salesforce.com/services/oauth2/token", {
packages/app-store/salesforce/lib/CalendarService.ts:76 method: "POST",
packages/app-store/salesforce/lib/CalendarService.ts:77 body: new URLSearchParams({
packages/app-store/salesforce/lib/CalendarService.ts:78 grant_type: "refresh_token",
```
greptile · cross-file engine perris 0.11.1+proven.tiered0.25.call.read.subclass.type
| Defect | Severity | Found | Grade |
|---|---|---|---|
| d1 | high | ✓ | exact |
| d2 | high | ✓ | exact |
| d3 | high | ✓ | exact |
| d4 | high | ✓ | exact |
| d5 | high | ✓ | exact |
| d6 | high | ✗ | — |
| d7 | medium | ✓ | off by one |
The new code in getClient refreshes the token on every construction, with no expiry check, and calls fetch directly instead of going through refreshOAuthTokens. This adds an extra network call and a DB write each time, and fails if the refresh fails even when the stored token is still valid. [grounded: diff] [consensus 5/5: valid=5]
The new webhook runs findFirst and then a separate create without any locking or unique constraint. Two concurrent requests for the same user and app can both find nothing and each create a credential. [grounded: diff] [consensus 5/5: valid=5]
raw comments (8)
<a href="#"><img alt="P1" src="https://greptile-static-assets.s3.amazonaws.com/badges/p1.svg?v=9" align="top"></a> **Incompatible Refresh Response**
When credential synchronization is enabled, this branch returns a native `Response`, but the changed callers expect provider-specific result shapes. Google expects `res.data`, HubSpot expects token fields directly, and Bigin and Zoho CRM expect Axios-style `.data`. These refresh paths therefore read missing fields instead of the endpoint's token payload, preventing credentials from refreshing.
<a href="#"><img alt="P1" src="https://greptile-static-assets.s3.amazonaws.com/badges/p1.svg?v=9" align="top"></a> **Parse Wrapper Gets Persisted**
This helper returns the entire Zod `safeParse` result instead of its parsed `data`. Google writes that result directly to `credential.key`, so a successful refresh stores `{ success, data }` rather than the credential fields. The next use then fails when `googleCredentialSchema` parses the stored key.
<a href="#"><img alt="P1" src="https://greptile-static-assets.s3.amazonaws.com/badges/p1.svg?v=9" align="top"></a> **Valid Refresh Token Replaced**
When a provider omits a new refresh token, this code replaces it with the literal string `"refresh_token"`. Office 365 allows such responses and previously retained the existing token, but the fabricated value now overrides it during the credential merge. The next refresh sends this invalid token and fails.
<a href="#"><img alt="P1" src="https://greptile-static-assets.s3.amazonaws.com/badges/p1.svg?v=9" align="top"></a> **Required Token Fields Stripped**
These computed properties create literal object keys rather than allowing arbitrary Zod fields, and ordinary Zod objects strip unknown fields. In synchronization mode, parsing can therefore discard expiry and provider-specific fields. Salesforce persists that stripped result without `instance_url`, so later service construction supplies an undefined instance URL and Salesforce API operations fail.
<a href="#"><img alt="P1" src="https://greptile-static-assets.s3.amazonaws.com/badges/p1.svg?v=9" align="top"></a> **Wrong User Identifier Sent**
When synchronization is enabled, this call passes the credential row's primary key where the helper expects a Cal.com user ID. The endpoint receives `calcomUserId=<credential.id>` and may select no user or the wrong user, causing refresh failure or cross-user token selection.
<a href="#"><img alt="P1" src="https://greptile-static-assets.s3.amazonaws.com/badges/p1.svg?v=9" align="top"></a> **Salesforce Refreshes Unconditionally**
Every Salesforce service construction now refreshes directly against the provider instead of using the configured credential-synchronization helper. Generic availability, booking, and cancellation paths therefore add a network request and database write, can fail despite a still-valid stored access token, and bypass the parent application's token source in synchronized deployments.
<a href="#"><img alt="P2" src="https://greptile-static-assets.s3.amazonaws.com/badges/p2.svg?v=9" align="top"></a> **Concurrent Requests Create Duplicates**
Credential creation performs a separate `findFirst` and `create`, while the credential table has no uniqueness constraint for user and app. Concurrent deliveries for the same user and app can both find no row and create duplicate credentials, leaving later integration code with an ambiguous credential selection. Use an atomic, uniqueness-backed operation or otherwise serialize creation.
<h3>Greptile Summary</h3>
This PR introduces application-credential synchronization through a new authenticated webhook and a shared OAuth refresh route, reorganizes OAuth utilities, and integrates token refresh handling across several calendar and video providers.
- Adds encrypted credential creation and replacement by user and app.
- Routes selected OAuth refreshes through a configurable external endpoint.
- Adds shared token-response parsing and updates provider credential persistence.
- Moves OAuth state and credential utilities into an `oauth` directory.
- Adds the synchronization environment variables to the example and Turbo configuration.
<h3>Confidence Score: 0/5</h3>
This PR is not safe to merge because enabled synchronization breaks several provider refresh paths and can persist credentials in unusable forms.
The shared refresh helper returns incompatible response shapes, the parser corrupts or strips persisted token data, Bigin sends the wrong identity, and Salesforce both bypasses synchronization and refreshes unconditionally during service construction.
**Files Needing Attention:** packages/app-store/_utils/oauth/refreshOAuthTokens.ts, packages/app-store/_utils/oauth/parseRefreshTokenResponse.ts, packages/app-store/googlecalendar/lib/CalendarService.ts, packages/app-store/zoho-bigin/lib/CalendarService.ts, packages/app-store/salesforce/lib/CalendarService.ts, apps/web/pages/api/webhook/app-credential.ts
<details><summary><h3>Important Files Changed</h3></summary>
| Filename | Overview |
|----------|----------|
| packages/app-store/_utils/oauth/refreshOAuthTokens.ts | Adds the synchronization route but returns a transport response incompatible with several migrated callers. |
| packages/app-store/_utils/oauth/parseRefreshTokenResponse.ts | Adds shared parsing that returns the wrong abstraction, fabricates refresh tokens, and strips required fields in synchronization mode. |
| packages/app-store/googlecalendar/lib/CalendarService.ts | Integrates shared refresh handling but persists a SafeParse wrapper as the Google credential key. |
| packages/app-store/zoho-bigin/lib/CalendarService.ts | Routes Bigin refreshes through synchronization using a credential ID in place of the owning user ID. |
| packages/app-store/salesforce/lib/CalendarService.ts | Introduces unconditional direct token refresh and credential updates while bypassing the configured synchronization route. |
| apps/web/pages/api/webhook/app-credential.ts | Adds authenticated encrypted credential synchronization, with a duplicate-creation race under concurrent deliveries. |
| packages/lib/constants.ts | Enables credential sharing only when both required secret values are configured. |
| turbo.json | Exposes the new credential-synchronization environment variables to Turbo tasks. |
</details>
<details open><summary><h3>Sequence Diagram</h3></summary>
```mermaid
sequenceDiagram
participant Service as Calendar/Video service
participant Helper as refreshOAuthTokens
participant Sync as Credential sync endpoint
participant Provider as OAuth provider
participant DB as Credential database
Service->>Helper: refresh(appSlug, userId)
alt Synchronization enabled
Helper->>Sync: POST calcomUserId + appSlug
Sync-->>Helper: HTTP Response containing token JSON
Helper-->>Service: Native Response
Note over Service: Several callers expect Axios/SDK token shapes
else Synchronization disabled
Helper->>Provider: Provider-specific refresh
Provider-->>Helper: Provider-specific response shape
Helper-->>Service: Provider-specific response
end
Service->>DB: Persist refreshed credential
```
</details>
<!-- greptile_other_comments_section -->
<sub>Reviews (1): Last reviewed commit: ["Update .env.example and 39 more files"](https://github.com/drape-io/crbench-greptile-2026-09/commit/41a588bf2d26bcf7a1001d658295dfbfcd93dad6) | [Re-trigger Greptile](https://app.greptile.com/api/retrigger?id=64284246)</sub>
Mjolnir (Opus 5.5) · cross-file engine perris 0.11.1+proven.tiered0.25.call.read.subclass.type
| Defect | Severity | Found | Grade |
|---|---|---|---|
| d1 | high | ✓ | off by one |
| d2 | high | ✓ | off by one |
| d3 | high | ✓ | exact |
| d4 | high | ✓ | off by one |
| d5 | high | ✓ | off by one |
| d6 | high | ✓ | off by one |
| d7 | medium | ✓ | exact |
The Salesforce CalendarService imports don't include @calcom/prisma. globalThis.prisma is only set when NODE_ENV is not production, so this call throws a ReferenceError in production. [grounded: diff] [consensus 3/3: valid=3]
getClient now refreshes the token every time without calling refreshOAuthTokens, but the jsforce Connection is still built from the old credentialKey token and instance URL. [grounded: tree packages/app-store/salesforce/lib/CalendarService.ts] [consensus 3/3: valid=3]
parseRefreshTokenResponse returns the whole safeParse result ({success, data}), and that wrapper is saved as the key. The next googleCredentialSchema.parse(credential.key) then fails. [grounded: diff] [consensus 3/3: valid=3]
Same bug as finding 1: prisma is never imported, so this throws a ReferenceError in production. [grounded: diff] [consensus 3/3: valid=3]
apps.metadata.generated.ts keys appStoreMetadata by directory name (googlecalendar, zoomvideo), so looking it up by a DB slug such as google-calendar returns undefined and the handler returns 404. [grounded: diff] [consensus 3/3: valid=3]
Bigin passes credentialId into the userId parameter, and refreshOAuthTokens sends that value as calcomUserId. [grounded: diff] [consensus 3/3: valid=3]
Both computed keys evaluate to "[object Object]". A zod object strips unknown keys by default, so in sync mode expires_in and similar fields are dropped. [grounded: diff] [consensus 3/3: valid=3]
The placeholder is set even when sync mode is off. Office365 spreads tokenResponse.data over the stored credentials, so when Microsoft omits refresh_token the real one is overwritten with "refresh_token". [grounded: diff] [consensus 3/3: valid=3]
raw comments (15)
[P1] Google refresh saves the zod result wrapper as the credential key
`parseRefreshTokenResponse` returns the `safeParse` result (`{ success, data }`), not the parsed credentials. Before this change, `googleCredentialSchema.parse(...)` returned the credentials themselves. Now `data: { key }` writes `{ success: true, data: {...} }` to `credential.key`. The next time this Google credential is loaded, `googleCredentialSchema.parse(credential.key)` in `googleAuth` throws, so every Google Calendar credential breaks after its first token refresh, even when credential sharing is turned off. The code should use `.data`, or check `success` first.
[P1] Salesforce client uses `prisma` without importing it
The new `getClient` code calls `prisma.credential.update(...)`, but this file never imports `prisma` from `@calcom/prisma`. `packages/prisma/index.ts` only sets `globalThis.prisma` when `NODE_ENV !== "production"`. In production this throws a `ReferenceError`, so `this.conn` rejects and every Salesforce operation fails.
[P2] Salesforce refreshes on every instantiation but connects with the old token
`getClient` now calls the Salesforce token endpoint every time a `SalesforceCalendarService` is constructed, whether or not the token has expired. It also skips `refreshOAuthTokens`, so the sync endpoint is never used for this app. The new access token is saved to the DB, but `jsforce.Connection` is still built from the stale `credentialKey.access_token` and `credentialKey.instance_url`. Each instantiation therefore costs an extra network round-trip and can fail on a transient token-endpoint error (or a non-"OK" `statusText`), while the refreshed token is not used for the session.
[P2] Placeholder string `"refresh_token"` can replace a real refresh token
If the parsed response has no `refresh_token`, the helper sets it to the literal string `"refresh_token"`. Office365 Calendar declares `refresh_token` as optional and merges the parsed data into the stored credentials (`{ ...o365AuthCredentials, ...tokenResponse.data }`). When Microsoft's refresh response leaves out `refresh_token`, the real stored refresh token is overwritten with `"refresh_token"`, and the next refresh fails with an invalid grant. This happens in normal mode, not only with credential sharing enabled.
[P2] `minimumTokenResponseSchema` strips expiry fields
`[z.string().toString()]` is a computed key that evaluates to `"[object Object]"`. Both entries use that same key, so the second overwrites the first, and the schema ends up as just `{ access_token, "[object Object]"?: unknown }`. `z.object` strips unknown keys, so in sync mode `expires_in` and `expiry_date` never reach callers. Zoom then computes `expiry_date` from `undefined * 1000` (NaN), and Office365 keeps the old `expires_in`, so it refreshes on every call. Combined with the placeholder above, the stored refresh tokens are also replaced with `"refresh_token"`.
[P2] Sync mode returns a raw `fetch` Response to callers that expect other shapes
When `CALCOM_CREDENTIAL_SYNC_ENDPOINT` is set, the helper returns a `fetch` `Response`. Several callers expect something else: Google reads `res?.data.access_token`, HubSpot treats the result as a `HubspotToken` (`expiresIn`, `accessToken`), and Zoho Bigin and ZohoCRM read `tokenInfo.data.error` and `.data` (axios shape). On a `Response`, `.data` is undefined, so these integrations throw or save garbage (for example, HubSpot writes the `Response` object as the key) as soon as credential syncing is enabled. Only the fetch-based adapters (Zoom, Webex, Office365, Lark) work with this return value.
[P2] Zoho Bigin sends the credential id as the Cal.com user id
`refreshOAuthTokens` expects a user id as its third argument, but Zoho Bigin passes `credentialId`. In sync mode, the external endpoint receives `calcomUserId=‹credential id›`, so it returns tokens for the wrong user (or none). The other adapters pass `credential.userId`. This also skips the intended check that falls back to a normal refresh when the credential is not owned by a user (for example, team credentials).
[P1] Google refresh saves the safeParse wrapper object as the credential key
packages/app-store/googlecalendar/lib/CalendarService.ts:97-101 `parseRefreshTokenResponse` returns a zod `SafeParseReturn` (`{ success, data }`), not the parsed data that `googleCredentialSchema.parse` used to return. So after every successful token refresh, `credential.key` is overwritten with `{ success: true, data: {...} }`. The next time `googleAuth` runs `googleCredentialSchema.parse(credential.key)` it throws, which breaks every Google Calendar user whose token gets refreshed. The key should be `.data` after a success check.
[P1] Salesforce now calls `prisma` without importing it
packages/app-store/salesforce/lib/CalendarService.ts:96-99 `getClient` now calls `prisma.credential.update`, but this file never imports `@calcom/prisma`. The only fallback is `globalThis.prisma`, and `packages/prisma/index.ts` sets that only when `NODE_ENV !== "production"`. In production this throws a ReferenceError inside `getClient`, so `this.conn` rejects and every Salesforce operation fails.
[P2] Salesforce refreshes the token on every client creation but never uses the result
packages/app-store/salesforce/lib/CalendarService.ts:75-106 The new block sends a refresh_token grant to Salesforce every time the service is constructed, whether or not the token has expired. It also skips `refreshOAuthTokens`, so the credential-sync endpoint is never used for Salesforce. The `jsforce.Connection` is still built from the old `credentialKey.access_token`/`instance_url` instead of the refreshed values. Any non-"OK" `statusText` now throws a 400 and blocks all Salesforce use, even when the stored token was still valid.
[P2] Webhook looks up app metadata by DB slug, but `appStoreMetadata` is keyed by directory name
apps/web/pages/api/webhook/app-credential.ts:50 `appStoreMetadata` is keyed by app directory name (`googlecalendar`, `zoomvideo`, `office365calendar`, `office365video`), but `app.slug` from the DB is `google-calendar`, `zoom`, `office365-calendar`, `msteams`, etc. For any app whose slug differs from its directory name (including the main OAuth apps this feature targets), the lookup returns undefined and the webhook responds 404 "App not found". As a result, credentials cannot be synced for those apps.
[P2] Credential-sync path returns a raw fetch Response that several callers cannot read
packages/app-store/_utils/oauth/refreshOAuthTokens.ts:15 When the sync endpoint is configured, `refreshOAuthTokens` returns the raw `fetch` `Response`, but several callers expect their SDK's own return shape: - Google reads `res?.data.access_token`. - Zoho CRM and Zoho Bigin read `tokenInfo.data.error` / `.data.access_token` (axios shape). - HubSpot treats the result as a parsed `HubspotToken` and reads `.expiresIn` / `.accessToken`. With credential sync enabled, `.data` on a `Response` is undefined, so Google and Zoho throw a TypeError. HubSpot stores the `Response` object as the key with a NaN `expiryDate`. Token refresh is therefore broken for these apps in exactly the mode this PR adds.
[P2] Zoho Bigin sends the credential id to the sync endpoint as the user id
packages/app-store/zoho-bigin/lib/CalendarService.ts:93 The third argument to `refreshOAuthTokens` is meant to be the Cal.com user id: it is sent as `calcomUserId` and is also what gates the sync path. Bigin passes `credentialId` here instead. With sync enabled, the parent app is asked for tokens belonging to whichever user has an id equal to this credential's id, so it can return the wrong user's tokens or fail.
[P2] `minimumTokenResponseSchema` computed keys don't allow extra fields
packages/app-store/_utils/oauth/parseRefreshTokenResponse.ts:5-11 `[z.string().toString()]` and `[z.string().optional().toString()]` both evaluate to the literal key `"[object Object]"`. The schema is therefore just `{ access_token, "[object Object]"?: unknown }`, and zod strips every other property. In sync mode, expiry fields are lost: - Zoom computes `expiry_date` from an undefined `expires_in`, which gives NaN. - Office365 keeps the stale `expires_in`, so it refreshes on every call. The intended "any numeric expiry / passthrough" behaviour needs something like `.passthrough()`.
[P2] Missing refresh_token is replaced with the literal string "refresh_token", even outside sync mode
packages/app-store/_utils/oauth/parseRefreshTokenResponse.ts:25-27 The placeholder is applied unconditionally, not only when credential sync is enabled. Office365's `refreshTokenResponseSchema` makes `refresh_token` optional, and Office365 spreads `tokenResponse.data` over the stored credentials. Whenever Microsoft omits `refresh_token` from a refresh response, the user's real refresh token is overwritten with `"refresh_token"`, and every later refresh for that user fails.
Mjolnir (Sonnet 5.5) · cross-file engine perris 0.11.1+proven.tiered0.25.call.read.subclass.type
| Defect | Severity | Found | Grade |
|---|---|---|---|
| d1 | high | ✓ | exact |
| d2 | high | ✓ | exact |
| d3 | high | ✓ | off by one |
| d4 | high | ✓ | exact |
| d5 | high | ✓ | off by one |
| d6 | high | ✓ | exact |
| d7 | medium | ✓ | exact |
The diff removes the Office365 zod-error and MS-response logging, and parseRefreshTokenResponse now throws a generic error, so the failure details are lost. The userId fallback is a minor point. [grounded: diff] [consensus 3/3: valid=3]
parseRefreshTokenResponse returns the safeParse result ({success, data}), and that object is written directly as credential.key. This corrupts the stored Google credential. [grounded: diff] [consensus 3/3: valid=3]
Both computed keys evaluate to "[object Object]". The later entry overrides the first with z.unknown().optional(), so the key is not a required number and parsing does not fail as claimed. [invalid: contradiction] [consensus 3/3: invalid=3]
This runs in the non-sync path too. Office365's schema makes refresh_token optional, and its data is spread over the stored credentials, so the real refresh token is overwritten with the placeholder. [grounded: tree packages/app-store/_utils/oauth/parseRefreshTokenResponse.ts] [consensus 3/3: valid=3]
getClient now refreshes unconditionally on every construction without going through refreshOAuthTokens, and it still builds the Connection from the old access token. [grounded: tree packages/app-store/salesforce/lib/CalendarService.ts] [consensus 3/3: valid=3]
refreshOAuthTokens' third parameter is userId, but zoho-bigin passes credentialId, so the wrong id is sent to the sync endpoint as calcomUserId. [grounded: diff] [consensus 3/3: valid=3]
In the new handler, parse and JSON.parse throw uncaught on bad input, giving a 500, and the secret check uses a non-constant-time !== comparison. [grounded: tree apps/web/pages/api/webhook/app-credential.ts] [consensus 3/3: valid=3]
raw comments (14)
[P0] Google credential key overwritten with a safeParse result object
`parseRefreshTokenResponse` returns a zod `SafeParseReturnType` (`{success, data}`), but the call site uses it as the parsed key, replacing `googleCredentialSchema.parse(googleCredentials)`. Every Google token refresh then saves `{ success: true, data: {...} }` into `credential.key`. After that, `refresh_token`, `access_token` and the rest are no longer at the top level, so the Google Calendar credential is corrupted and later refreshes fail. This happens in normal, non-sharing mode. Use `.data` after checking `.success`.
[P1] Minimum token schema is built from nonsense computed keys, so it never works in credential-sharing mode
`[z.string().toString()]` and `[z.string().optional().toString()]` both evaluate to the literal key `"[object Object]"`. The second entry overwrites the first, so the schema is effectively `{access_token, "[object Object]"?: unknown}`. The "any numeric property is the expiry" intent is not implemented. Because `z.object` strips unknown keys by default, the expiry field (`expires_in` or `expiry_date`) is dropped from `data`. Callers that read `.data` get a token with no expiry (Zoom, Office365). The same applies to Salesforce, where the minimum schema also strips instance_url etc. Use `.passthrough()` or `z.record`, and validate expiry explicitly.
[P1] Salesforce now refreshes the token on every client construction, and the status check can fail even on success
`getClient` (called from the constructor) now does an unconditional POST to the Salesforce token endpoint, with a DB write, each time the service is created, even when the access token is still valid. It also bypasses `refreshOAuthTokens`, so credential sync is ignored for Salesforce. `response.statusText !== "OK"` is unreliable. On HTTP/2 responses `statusText` is an empty string, so this throws a 400 for a successful refresh. Check `response.ok` instead. The extra refresh-token call per use can also hit rate limits. The jsforce connection below still uses the old credentials rather than the refreshed ones.
[P1] Placeholder refresh token can overwrite a valid stored one
When the parsed data has no `refresh_token`, it is set to the literal string `"refresh_token"`. Office365 Calendar's schema has `refresh_token` optional, and the caller merges `tokenResponse.data` over the existing credentials. If Microsoft omits a new refresh token, or credential-sync mode returns none, the stored real refresh token is replaced by `"refresh_token"` and every later refresh fails. Only fill a placeholder when no existing token is preserved, or don't mutate the result.
[P1] Credential sync mode returns a raw fetch Response where callers expect parsed provider output
(also hubspot/lib/CalendarService.ts:177-190, zohocrm/lib/CalendarService.ts:204-216, zoho-bigin/lib/CalendarService.ts:85-95) When sharing is enabled, `refreshOAuthTokens` returns the `fetch` Response without calling `.json()`. Google reads `res?.data.access_token`, Hubspot treats it as a `HubspotToken`, and Zoho CRM and Bigin read `.data.error`/`.data`. These are axios or SDK shapes, so each throws or reads undefined on a `Response`. Credential sync therefore cannot work for these apps and the refresh fails.
[P2] Zoho Bigin passes the credential id as the user id
`refreshOAuthTokens(..., "zoho-bigin", credentialId)` supplies the credential's primary key where a user id is required. In sharing mode the sync endpoint is called with `calcomUserId` set to an unrelated id, so tokens are fetched for the wrong user, or none are found. A truthy credential id also forces the sync path for team credentials where `userId` would be null. Pass `credential.userId`.
[P3] Missing userId guard causes refresh to bypass sync silently
Office365 failure logging was also removed, and a failed refresh now throws "Invalid refreshed tokens were returned" instead of logging the zod error and continuing. The failure details (zod error and MS response) are lost, which makes diagnosis of bad token responses harder.
[P1] Google credential is overwritten with a safeParse result object
parseRefreshTokenResponse` returns the zod `SafeParseReturnType` (`{success, data}`), not the parsed data. `key` is now `{success: true, data: {...}}`, and that is what gets written to `credential.key`. After the first token refresh, the stored Google credential no longer has `access_token`, `refresh_token` or `expiry_date` at the top level. The credential then breaks permanently, and any later parse of it with `googleCredentialSchema` fails. This happens on every Google Calendar refresh, whether or not credential sharing is enabled. Callers need `.data`, and a failed parse should be handled before the write
[P1] The sync-mode schema requires a literal "[object Object]" key
[z.string().toString()]` and `[z.string().optional().toString()]` are computed property names. They evaluate to the string "[object Object]", not to a wildcard key. `minimumTokenResponseSchema` therefore requires a numeric `"[object Object]"` property. No real token response has one, so every parse fails in sync mode. With `APP_CREDENTIAL_SHARING_ENABLED` and `CALCOM_CREDENTIAL_SYNC_ENDPOINT` set, the code throws "Invalid refreshed tokens were returned" on every refresh. The "any numeric property is the expiry" intent is not implemented
[P1] A placeholder string replaces the real refresh token when the response omits one
If the refresh response has no `refresh_token`, the code sets `data.refresh_token = "refresh_token"`. This runs in the normal non-sync path too. Providers such as Microsoft, Zoho and Salesforce often omit `refresh_token` on refresh. Callers that spread `data` over the stored credential (for example Office365 calendar: `{...o365AuthCredentials, ...tokenResponse.data}`) then save the literal string "refresh_token". The user's real refresh token is lost and later refreshes fail. The placeholder should only apply in sync mode, and it must not overwrite an existing token
[P2] Salesforce refreshes the token and writes to the DB on every client construction
getClient` now always POSTs a refresh_token grant to Salesforce, ignoring expiry and `refreshOAuthTokens`. It then updates the credential, and it does this each time the service is instantiated. Three problems follow - Every booking operation adds an extra token request, with the rate-limit and latency cost that brings. - The sync endpoint is bypassed, so credential sharing does not work for Salesforce. - The `Connection` is still built from the old `credentialKey.access_token`, so the fresh token is not used. The `response.statusText !== "OK"` check is also unreliable, because it is empty over HTTP/2. `response.ok` should be used.
[P2] The zoho-bigin refresh passes the credential id where a user id is expected
The third argument of `refreshOAuthTokens` is `userId`, but this call passes `credentialId`. In sync mode, `calcomUserId` sent to `CALCOM_CREDENTIAL_SYNC_ENDPOINT` is the credential id, so the endpoint looks up the wrong user's tokens or none. The sync branch is also skipped whenever `credentialId` is 0
[P2] The sync branch returns a raw fetch `Response`, but callers expect parsed or provider-shaped results
When sync is enabled, `refreshOAuthTokens` returns the `fetch` Response without parsing it. Callers read provider-shaped fields from it - Google reads `res?.data`. - Zoho and Bigin read `tokenInfo.data`. - HubSpot reads `.accessToken` and similar fields. These are all undefined on a `Response`, so the sync path crashes or stores garbage. The response needs normalizing, for example by returning parsed JSON in each caller's expected shape.
[P3] The webhook handler is fragile on unexpected input
schema.parse(req.body)` and `JSON.parse(symmetricDecrypt(...))` throw uncaught exceptions on malformed input or a wrong key, which gives a 500 instead of a 400. The secret is compared with `!==`, which is not timing-safe, and a missing header on a mis-set env falls back to a default name. Use `safeParse`, try/catch and a constant-time comparison
qodo · cross-file engine perris 0.11.1+proven.tiered0.25.call.read.subclass.type
| Defect | Severity | Found | Grade |
|---|---|---|---|
| d1 | high | ✓ | exact |
| d2 | high | ✓ | exact |
| d3 | high | ✓ | exact |
| d4 | high | ✓ | exact |
| d5 | high | ✓ | exact |
| d6 | high | ✗ | — |
| d7 | medium | ✓ | off by one |
The Salesforce CalendarService imports don't include prisma (the full post-change file only imports getAppKeysFromSlug, parseRefreshTokenResponse, etc.), but the new code calls prisma.credential.update, so it's an unresolved identifier. [grounded: diff] [consensus 3/3: valid=3]
apps.metadata.generated.ts keys the registry by directory name (`googlecalendar: googlecalendar__metadata_ts`), so looking it up with the DB slug 'google-calendar' returns undefined and the webhook responds 404. [grounded: diff] [consensus 3/3: valid=3]
Every other integration was wrapped in refreshOAuthTokens. Salesforce's new refresh code calls the provider directly, so it skips the sync endpoint even when credential sharing is enabled. This is an incomplete change. [grounded: diff] [consensus 3/3: valid=3]
The Credential model has only plain indexes on userId and appId, with no unique constraint on the pair. Because the new webhook does a non-atomic findFirst followed by create, concurrent deliveries can insert duplicate credentials. [grounded: diff] [consensus 3/3: valid=3]
raw comments (11)
<img src="https://img.shields.io/badge/High-634FD1?style=flat-square" height="20px" alt="Action required">
1\. Salesforce integration cannot compile <code>🐞 Bug</code> <code>≡ Correctness</code>
<pre>
<b><i>SalesforceCalendarService.getClient</i></b> calls <b><i>prisma.credential.update</i></b> without importing or
declaring <b><i>prisma</i></b> in the module. Type checking fails whenever this file is compiled, preventing the
app-store package from building before any Salesforce request can run.
</pre>
<details>
<summary><strong>Agent Prompt</strong></summary>
```
## Issue description
The new Salesforce token-persistence call references `prisma` without importing it, causing a compile-time unresolved identifier error that prevents the package from building.
## Fix Focus Areas
- packages/app-store/salesforce/lib/CalendarService.ts[1-20]
- packages/app-store/salesforce/lib/CalendarService.ts[96-99]
## Recommended Fix
Add the standard shared `prisma` import from `@calcom/prisma` alongside the other Cal.com imports, then retain the existing `prisma.credential.update` call.
```
<code>ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools</code>
</details>
<img src="https://img.shields.io/badge/High-634FD1?style=flat-square" height="20px" alt="Action required">
2\. Google credentials become unreadable <code>🐞 Bug</code> <code>≡ Correctness</code>
<pre>
<b><i>parseRefreshTokenResponse</i></b> returns the complete <b><i>safeParse</i></b> result, but Google saves that wrapper
as the credential key instead of saving its <b><i>data</i></b>. The next service initialization parses the
resulting <b><i>{ success, data }</i></b> object as top-level Google credentials and rejects it because the
token fields are nested.
</pre>
<details>
<summary><strong>Agent Prompt</strong></summary>
```
## Issue description
Google stores the Zod `safeParse` wrapper instead of the parsed credential object, making the saved credential incompatible with its schema.
## Fix Focus Areas
- packages/app-store/_utils/oauth/parseRefreshTokenResponse.ts[13-29]
- packages/app-store/googlecalendar/lib/CalendarService.ts[74-100]
## Recommended Fix
Return parsed token data from `parseRefreshTokenResponse`, or explicitly persist `key.data`, and update the helper's other callers consistently with the selected return contract.
```
<code>ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools</code>
</details>
<img src="https://img.shields.io/badge/High-634FD1?style=flat-square" height="20px" alt="Action required">
3\. Synced tokens lose refresh credentials <code>🐞 Bug</code> <code>≡ Correctness</code>
<pre>
<b><i>minimumTokenResponseSchema</i></b> uses computed object-property names instead of a catch-all or explicit
normalized schema, including a <b><i>z.string().toString()</i></b> key that becomes the required literal
<b><i>"[object Object]"</i></b>; when parsing succeeds, Zod strips fields beyond <b><i>access_token</i></b> and the helper
inserts the literal value <b><i>"refresh_token"</i></b>. With credential synchronization enabled, normal refresh
responses from Google, Office 365, Zoom, and Salesforce can fail validation before saving, while
accepted responses can replace usable refresh tokens and discard expiry and provider-specific fields
such as Salesforce's instance URL before persistence.
</pre>
<details>
<summary><strong>Agent Prompt</strong></summary>
```
## Issue description
The minimum token schema uses computed JavaScript property names rather than a valid catch-all, record, or explicit normalized response schema. This creates an unintended required `"[object Object]"` field, strips arbitrary token properties from accepted responses, and fabricates a refresh token, causing synchronization-aware callers either to reject normal responses or persist corrupted credentials.
## Fix Focus Areas
- packages/app-store/_utils/oauth/parseRefreshTokenResponse.ts[5-29]
- packages/app-store/office365calendar/lib/CalendarService.ts[263-273]
- packages/app-store/salesforce/lib/CalendarService.ts[90-99]
- packages/app-store/zoomvideo/lib/VideoApiAdapter.ts[104-124]
## Recommended Fix
Replace the computed keys with an explicit normalized synchronization response schema or an appropriate passthrough, `z.record`, catch-all, or refinement that validates required fields such as `access_token` and the documented expiry field while preserving additional token and provider-specific properties. When the response omits `refresh_token`, retain the credential's existing refresh token instead of mutating the parsed response or substituting a placeholder value.
```
<code>ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools</code>
</details>
<img src="https://img.shields.io/badge/High-634FD1?style=flat-square" height="20px" alt="Action required">
4\. Valid app credentials are rejected <code>🐞 Bug</code> <code>≡ Correctness</code>
<pre>
The webhook indexes <b><i>appStoreMetadata</i></b> by the database app slug even though the registry is keyed by
directory name. Requests for apps whose names differ, including the <b><i>google-calendar</i></b> slug backed by
the <b><i>googlecalendar</i></b> registry key, pass the database lookup but incorrectly return an app-not-found
response.
</pre>
<details>
<summary><strong>Agent Prompt</strong></summary>
```
## Issue description
The credential webhook treats public app slugs as metadata registry keys, rejecting apps whose directory name differs from their slug.
## Fix Focus Areas
- apps/web/pages/api/webhook/app-credential.ts[40-54]
- packages/app-store/_appRegistry.ts[19-24]
- packages/app-store/googlecalendar/_metadata.ts[17-20]
## Recommended Fix
Resolve the metadata by searching metadata values for a matching `slug`, preferably by reusing the repository's existing app-registry slug resolver.
```
<code>ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools</code>
</details>
<img src="https://img.shields.io/badge/High-634FD1?style=flat-square" height="20px" alt="Action required">
5\. Salesforce bypasses credential sync <code>🐞 Bug</code> <code>≡ Correctness</code>
<pre>
The Salesforce refresh path always posts directly to the provider and only uses the
synchronization-aware parsing helper afterward. When credential sharing and its endpoint are
configured, Salesforce never calls the helper that routes refreshes through that endpoint, unlike
the other integrations changed by this pull request.
</pre>
<details>
<summary><strong>Agent Prompt</strong></summary>
```
## Issue description
Salesforce performs provider refreshes directly even when application credential synchronization is enabled.
## Fix Focus Areas
- packages/app-store/salesforce/lib/CalendarService.ts[19-20]
- packages/app-store/salesforce/lib/CalendarService.ts[75-90]
- packages/app-store/_utils/oauth/refreshOAuthTokens.ts[3-19]
## Recommended Fix
Wrap the Salesforce provider request with `refreshOAuthTokens`, pass the Salesforce app slug and `credential.userId`, and consume the helper's normalized token-data contract.
```
<code>ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools</code>
</details>
<img src="https://img.shields.io/badge/High-634FD1?style=flat-square" height="20px" alt="Action required">
6\. Synced calendar refreshes receive unusable tokens <code>🐞 Bug</code> <code>≡ Correctness</code>
<pre>
The synchronization branch of <b><i>refreshOAuthTokens</i></b> returns a raw Fetch <b><i>Response</i></b>, while its normal
branch returns provider-specific parsed response objects and the callers expect Gaxios, SDK, or
Axios-style token shapes. When synchronization is enabled, Google dereferences undefined <b><i>.data</i></b>,
the Zoho paths fail while accessing <b><i>.data</i></b>, and HubSpot calculates and persists fields from the
wrong object.
</pre>
<details>
<summary><strong>Agent Prompt</strong></summary>
```
## Issue description
The refresh helper returns different response abstractions depending on which branch runs: the synchronization path returns a native Fetch response, while callers expect the parsed token shape produced by their provider refresh functions.
## Fix Focus Areas
- packages/app-store/_utils/oauth/refreshOAuthTokens.ts[3-19]
- packages/app-store/googlecalendar/lib/CalendarService.ts[84-100]
- packages/app-store/hubspot/lib/CalendarService.ts[175-202]
- packages/app-store/zoho-bigin/lib/CalendarService.ts[85-115]
- packages/app-store/zohocrm/lib/CalendarService.ts[204-237]
## Recommended Fix
Define one normalized token-data return contract for `refreshOAuthTokens`. Parse and validate the synchronization endpoint response, decode provider responses into the same contract, and update every caller to consume normalized token data rather than mixing Fetch `Response`, Axios, Gaxios, SDK, and provider-specific response wrappers.
```
<code>ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools</code>
</details>
<img src="https://img.shields.io/badge/High-634FD1?style=flat-square" height="20px" alt="Action required">
7\. Zoho bigin refreshes the wrong identity <code>🐞 Bug</code> <code>≡ Correctness</code>
<pre>
<b><i>BiginCalendarService.biginAuth</i></b> passes <b><i>credential.id</i></b> through <b><i>refreshAccessToken</i></b> as the third
argument to <b><i>refreshOAuthTokens</i></b>, even though the helper serializes that value as <b><i>calcomUserId</i></b>.
When a Bigin token expires with synchronization enabled, the remote credential service receives a
credential-row ID instead of the owning user's ID, so it can fetch tokens for an unrelated user or
fail to find the intended one.
</pre>
<details>
<summary><strong>Agent Prompt</strong></summary>
```
## Issue description
Zoho Bigin sends the credential record ID in the synchronization payload field intended for the Cal.com user ID.
## Fix Focus Areas
- packages/app-store/zoho-bigin/lib/CalendarService.ts[51-69]
- packages/app-store/zoho-bigin/lib/CalendarService.ts[85-94]
- packages/app-store/_utils/oauth/refreshOAuthTokens.ts[3-13]
## Recommended Fix
Carry `credential.userId` separately into `refreshAccessToken` and pass it as the third argument to `refreshOAuthTokens`. Continue using `credential.id` only for the subsequent local credential database update.
```
<code>ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools</code>
</details>
<img src="https://img.shields.io/badge/Medium-634FD1?style=flat-square" height="20px" alt="Remediation recommended">
8\. Concurrent webhook syncs duplicate credentials <code>🐞 Bug</code> <code>☼ Reliability</code>
<pre>
The credential webhook performs a separate <b><i>findFirst</i></b> followed by <b><i>create</i></b>, while <b><i>Credential</i></b> has
no unique constraint on the <b><i>(userId, appId)</i></b> pair. Concurrent deliveries can both observe no
existing row and insert duplicates, after which later syncs update whichever duplicate <b><i>findFirst</i></b>
selects.
</pre>
<details>
<summary><strong>Agent Prompt</strong></summary>
```
## Issue description
The webhook uses a non-atomic read-then-create sequence for a credential identity that the database does not enforce as unique, allowing concurrent deliveries to create duplicate user-app credentials.
## Fix Focus Areas
- apps/web/pages/api/webhook/app-credential.ts[61-91]
- packages/prisma/schema.prisma[127-146]
## Recommended Fix
Add a database uniqueness constraint for the intended user/app credential identity and replace the check-then-create sequence with an atomic upsert against that constraint, or use a transaction that safely handles uniqueness conflicts. If existing data permits multiple credentials for an app, introduce a stable synchronization key and use it consistently for atomic writes.
```
<code>ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools</code>
</details>
<h3>Qodo is busy working</h3>
Check back in a few minutes. Qodo's code review agents are on it.
<img src="https://www.qodo.ai/wp-content/uploads/2025/11/light-grey-line.svg" height="10%" alt="Grey Divider">
<img src="https://www.qodo.ai/wp-content/uploads/2026/01/anteater-looking-at-ants-01-transparent-bg-croped-ezgif.com-optimize-1.gif" width="30%">
<h3>PR Summary by Qodo</h3>
Add self-hosted app credential synchronization
<code>✨ Enhancement</code> <code>⚙️ Configuration changes</code> <code>🕐 40+ Minutes</code>
<img src="https://www.qodo.ai/wp-content/uploads/2025/11/light-grey-line.svg" height="10%" alt="Grey Divider">
<details>
<summary>AI Description</summary>
<dl>
<dd>
<br/>
><pre>
>• Enables encrypted credential synchronization with self-hosted parent applications.
>• Routes supported OAuth refreshes through a configurable external credential endpoint.
>• Centralizes OAuth helpers and documents required runtime configuration.
></pre>
</dd>
</dl>
</details>
<details>
<summary>Diagram</summary>
<dl>
<dd>
<br/>
```mermaid
sequenceDiagram
participant Host as Parent App
participant Webhook as Credential Webhook
participant DB as Credential Store
participant App as OAuth Integration
participant Router as Refresh Router
participant Sync as Sync Endpoint
Host->>Webhook: Encrypted credentials
Webhook->>Webhook: Verify and decrypt
Webhook->>DB: Create or update
App->>Router: Refresh request
alt Credential sync enabled
Router->>Sync: User and app
Sync-->>Router: Access token
else Local provider refresh
Router->>App: Run provider refresh
App-->>Router: Token response
end
Router-->>App: Validated tokens
```
</dd>
</dl>
</details>
<details>
<summary>High-Level Assessment</summary>
<dl>
<dd>
<br/>
>The following are alternative approaches to this PR:
<details>
<summary><b>1. Dedicated credential broker</b></summary>
<dl>
<dd>
- ➕ Centralizes encryption, authorization, refresh behavior, and auditing outside integration adapters.
- ➕ Avoids exposing provider credentials to each Cal.com deployment.
- ➖ Introduces another required service and operational dependency.
- ➖ Requires a stable broker protocol and migration path for existing self-hosters.
</dd>
</dl>
</details>
<details>
<summary><b>2. Asynchronous credential events</b></summary>
<dl>
<dd>
- ➕ Decouples the parent application from Cal.com availability.
- ➕ Supports retries, delivery tracking, and credential rotation workflows.
- ➖ Adds queue infrastructure and eventual-consistency behavior.
- ➖ Does not directly solve synchronous access-token refresh requirements.
</dd>
</dl>
</details>
>**Recommendation:** The webhook plus shared refresh router is the most compatible incremental approach because credential synchronization remains optional and existing provider refreshes are retained as fallbacks. A dedicated broker would provide stronger long-term protocol and audit boundaries, but its added deployment complexity is not justified unless credential sharing becomes a core multi-tenant capability.
</dd>
</dl>
</details>
<details>
<summary> Files changed (40) <code> +375 / -119 </code> </summary>
<dl>
<dd>
<br/>
<details>
<summary>Enhancement (13) <code> +323 / -87 </code></summary>
<dl>
<dd>
<details>
<summary>app-credential.ts<code>Add encrypted app credential webhook</code> <code>+93/-0</code></summary>
<br/>
>Add encrypted app credential webhook
>
><pre>
>• Introduces an authenticated webhook that validates users and apps, decrypts shared keys, and creates or updates user credentials.
></pre>
>
><a href='https://github.com/drape-io/crbench-qodo-2026-09/pull/18/files#diff-63b0a18ea4146e22fa313cdf690f65ae499762ad6396440f8b04ad84d9b6330d'>apps/web/pages/api/webhook/app-credential.ts</a>
</details>
<details>
<summary>parseRefreshTokenResponse.ts<code>Add shared refreshed-token validation</code> <code>+32/-0</code></summary>
<br/>
>Add shared refreshed-token validation
>
><pre>
>• Validates normal provider responses against integration schemas while permitting a reduced access-token response from the configured synchronization endpoint. It also supplies a placeholder refresh token when one is omitted.
></pre>
>
><a href='https://github.com/drape-io/crbench-qodo-2026-09/pull/18/files#diff-1dbb810b9c428b806675c66b731ab1c4c83cf9015f4057ce9fd9784406a895de'>packages/app-store/_utils/oauth/parseRefreshTokenResponse.ts</a>
</details>
<details>
<summary>refreshOAuthTokens.ts<code>Add configurable OAuth refresh router</code> <code>+22/-0</code></summary>
<br/>
>Add configurable OAuth refresh router
>
><pre>
>• Routes user-owned credential refreshes to the external synchronization endpoint when enabled, otherwise invoking the integration's existing provider refresh function.
></pre>
>
><a href='https://github.com/drape-io/crbench-qodo-2026-09/pull/18/files#diff-66346f512f26fdd5abf59c14e97ea74602ef51a5d36969983730e196042a774b'>packages/app-store/_utils/oauth/refreshOAuthTokens.ts</a>
</details>
<details>
<summary>CalendarService.ts<code>Enable synchronized Google token refresh</code> <code>+11/-2</code></summary>
<br/>
>Enable synchronized Google token refresh
>
><pre>
>• Routes Google Calendar token renewal through the shared refresh helper and validates synchronized responses before persisting credentials.
></pre>
>
><a href='https://github.com/drape-io/crbench-qodo-2026-09/pull/18/files#diff-6bfbaf63c841dc9343dba0c7487e30a546ffe2a63c9d9418379d0dbb88644d27'>packages/app-store/googlecalendar/lib/CalendarService.ts</a>
</details>
<details>
<summary>CalendarService.ts<code>Enable synchronized HubSpot token refresh</code> <code>+13/-7</code></summary>
<br/>
>Enable synchronized HubSpot token refresh
>
><pre>
>• Routes HubSpot access-token renewal through the shared refresh helper with the existing HubSpot API call as fallback.
></pre>
>
><a href='https://github.com/drape-io/crbench-qodo-2026-09/pull/18/files#diff-bf69529bb58ab05f6da9448eb26df702338c9006de9e5120656057d613a95ea5'>packages/app-store/hubspot/lib/CalendarService.ts</a>
</details>
<details>
<summary>CalendarService.ts<code>Enable synchronized Lark token refresh</code> <code>+17/-11</code></summary>
<br/>
>Enable synchronized Lark token refresh
>
><pre>
>• Routes Lark Calendar token renewal through the shared refresh helper while retaining the Lark token API as fallback.
></pre>
>
><a href='https://github.com/drape-io/crbench-qodo-2026-09/pull/18/files#diff-a6aff4ec08b825b3e3be78d11a16b79ed4b91d17cc3a005f1bdb59799e642e1e'>packages/app-store/larkcalendar/lib/CalendarService.ts</a>
</details>
<details>
<summary>CalendarService.ts<code>Enable synchronized Office 365 refresh</code> <code>+19/-20</code></summary>
<br/>
>Enable synchronized Office 365 refresh
>
><pre>
>• Routes Office 365 Calendar token renewal through the shared refresh helper and centralizes validation of provider or synchronized responses.
></pre>
>
><a href='https://github.com/drape-io/crbench-qodo-2026-09/pull/18/files#diff-4f075841987a4d1474327cb5c6097757822d5df69616798d8014ff3207a3034b'>packages/app-store/office365calendar/lib/CalendarService.ts</a>
</details>
<details>
<summary>VideoApiAdapter.ts<code>Enable synchronized Teams token refresh</code> <code>+16/-10</code></summary>
<br/>
>Enable synchronized Teams token refresh
>
><pre>
>• Routes Microsoft Teams access-token renewal through the shared refresh helper with Microsoft's token endpoint as fallback.
></pre>
>
><a href='https://github.com/drape-io/crbench-qodo-2026-09/pull/18/files#diff-876c46529293e1ddbf4f6da46832b4b135c9f48ea41eb3824fe489cf20dbad21'>packages/app-store/office365video/lib/VideoApiAdapter.ts</a>
</details>
<details>
<summary>CalendarService.ts<code>Refresh and persist Salesforce credentials</code> <code>+38/-0</code></summary>
<br/>
>Refresh and persist Salesforce credentials
>
><pre>
>• Adds explicit Salesforce access-token renewal, validates the response through the shared parser, and persists refreshed credentials while preserving the original refresh token.
></pre>
>
><a href='https://github.com/drape-io/crbench-qodo-2026-09/pull/18/files#diff-22562b5993b71a352c1b37e0b336a3d15eccf430e02077903e4f135b98416ffa'>packages/app-store/salesforce/lib/CalendarService.ts</a>
</details>
<details>
<summary>VideoApiAdapter.ts<code>Enable synchronized Webex token refresh</code> <code>+18/-12</code></summary>
<br/>
>Enable synchronized Webex token refresh
>
><pre>
>• Routes Webex access-token renewal through the shared refresh helper while preserving the Webex token endpoint as fallback.
></pre>
>
><a href='https://github.com/drape-io/crbench-qodo-2026-09/pull/18/files#diff-254ddb757d5c8f692be9932c83c7b6aac19dbd8271da38734ca08ffd89f1fda3'>packages/app-store/webex/lib/VideoApiAdapter.ts</a>
</details>
<details>
<summary>CalendarService.ts<code>Enable synchronized Bigin token refresh</code> <code>+11/-5</code></summary>
<br/>
>Enable synchronized Bigin token refresh
>
><pre>
>• Routes Zoho Bigin token renewal through the shared refresh helper while retaining the Zoho accounts API as fallback.
></pre>
>
><a href='https://github.com/drape-io/crbench-qodo-2026-09/pull/18/files#diff-34b0f03542e82d428c6a8862165903827d1615fb622597f5637dd65a987dcbc9'>packages/app-store/zoho-bigin/lib/CalendarService.ts</a>
</details>
<details>
<summary>CalendarService.ts<code>Enable synchronized Zoho CRM refresh</code> <code>+14/-8</code></summary>
<br/>
>Enable synchronized Zoho CRM refresh
>
><pre>
>• Routes Zoho CRM token renewal through the shared refresh helper while retaining the Zoho accounts API as fallback.
></pre>
>
><a href='https://github.com/drape-io/crbench-qodo-2026-09/pull/18/files#diff-a838819dd88676d84c77b884d5419d84de7f2df52ac36f80a35d0bd88c1274c6'>packages/app-store/zohocrm/lib/CalendarService.ts</a>
</details>
<details>
<summary>VideoApiAdapter.ts<code>Enable synchronized Zoom token refresh</code> <code>+19/-12</code></summary>
<br/>
>Enable synchronized Zoom token refresh
>
><pre>
>• Routes Zoom token renewal through the shared refresh helper and validates synchronized responses using the centralized token parser.
></pre>
>
><a href='https://github.com/drape-io/crbench-qodo-2026-09/pull/18/files#diff-bc76c383b2dfcce8b582cb8d1b9bda1595a0107a908ddb0c46a80f66a0337302'>packages/app-store/zoomvideo/lib/VideoApiAdapter.ts</a>
</details>
</dd>
</dl>
</details>
<details>
<summary>Bug fix (1) <code> +2 / -2 </code></summary>
<dl>
<dd>
<details>
<summary>add.ts<code>Correct Bigin redirect and OAuth import</code> <code>+2/-2</code></summary>
<br/>
>Correct Bigin redirect and OAuth import
>
><pre>
>• Uses the centralized OAuth state encoder and fixes the authorization redirect URI to the explicit Zoho Bigin callback route.
></pre>
>
><a href='https://github.com/drape-io/crbench-qodo-2026-09/pull/18/files#diff-1adafe6cbdf051f03b0d482bdc4208b39fa7a95861d8a8afad9a9ef39b39e693'>packages/app-store/zoho-bigin/api/add.ts</a>
</details>
</dd>
</dl>
</details>
<details>
<summary>Refactor (23) <code> +29 / -29 </code></summary>
<dl>
<dd>
<details>
<summary>createOAuthAppCredential.ts<code>Relocate OAuth credential creation imports</code> <code>+2/-2</code></summary>
<br/>
>Relocate OAuth credential creation imports
>
><pre>
>• Updates internal imports after grouping shared state and authorization helpers under the OAuth utility directory.
></pre>
>
><a href='https://github.com/drape-io/crbench-qodo-2026-09/pull/18/files#diff-24dce95d8578ea7f11012ecacad7a4f9b0563fe2b9300cfa9db2c690d438dcc2'>packages/app-store/_utils/oauth/createOAuthAppCredential.ts</a>
</details>
<details>
<summary>decodeOAuthState.ts<code>Relocate OAuth state decoding utility</code> <code>+1/-1</code></summary>
<br/>
>Relocate OAuth state decoding utility
>
><pre>
>• Adjusts the callback-state type import for the utility's new OAuth subdirectory location.
></pre>
>
><a href='https://github.com/drape-io/crbench-qodo-2026-09/pull/18/files#diff-cc5095ce6553be4f3adcf725f212366854e83cffd2429ed24414891f79c98b94'>packages/app-store/_utils/oauth/decodeOAuthState.ts</a>
</details>
<details>
<summary>encodeOAuthState.ts<code>Relocate OAuth state encoding utility</code> <code>+1/-1</code></summary>
<br/>
>Relocate OAuth state encoding utility
>
><pre>
>• Adjusts the callback-state type import for the utility's new OAuth subdirectory location.
></pre>
>
><a href='https://github.com/drape-io/crbench-qodo-2026-09/pull/18/files#diff-b378e465db9f3f67ab9b90e39e9b773769c3c68d46776bd17bdfe3ff00816dd9'>packages/app-store/_utils/oauth/encodeOAuthState.ts</a>
</details>
<details>
<summary>add.ts<code>Use relocated OAuth state encoder</code> <code>+1/-1</code></summary>
<br/>
>Use relocated OAuth state encoder
>
><pre>
>• Updates Google Calendar authorization to import the OAuth state encoder from the centralized OAuth utilities.
></pre>
>
><a href='https://github.com/drape-io/crbench-qodo-2026-09/pull/18/files#diff-11d010bdb64bc09049154c4c09e4d50591b0914076a36be8d10033ec48002d77'>packages/app-store/googlecalendar/api/add.ts</a>
</details>
<details>
<summary>callback.ts<code>Use relocated OAuth state decoder</code> <code>+1/-1</code></summary>
<br/>
>Use relocated OAuth state decoder
>
><pre>
>• Updates the Google Calendar callback to import the OAuth state decoder from the centralized OAuth utilities.
></pre>
>
><a href='https://github.com/drape-io/crbench-qodo-2026-09/pull/18/files#diff-811b365d46364b428c606d18d23fef758b3350755bc41e0ca84c483264686777'>packages/app-store/googlecalendar/api/callback.ts</a>
</details>
<details>
<summary>add.ts<code>Use relocated OAuth state encoder</code> <code>+1/-1</code></summary>
<br/>
>Use relocated OAuth state encoder
>
><pre>
>• Updates HubSpot authorization to import the OAuth state encoder from the centralized OAuth utilities.
></pre>
>
><a href='https://github.com/drape-io/crbench-qodo-2026-09/pull/18/files#diff-1e29d9ec6cecf7fbbfaf6e11727fefbf978718eb9c9c3c10ab3939a47a938f0d'>packages/app-store/hubspot/api/add.ts</a>
</details>
<details>
<summary>callback.ts<code>Use centralized HubSpot OAuth helpers</code> <code>+2/-2</code></summary>
<br/>
>Use centralized HubSpot OAuth helpers
>
><pre>
>• Updates the HubSpot callback to use relocated state decoding and credential creation utilities.
></pre>
>
><a href='https://github.com/drape-io/crbench-qodo-2026-09/pull/18/files#diff-7cf668d7aa50aeee694ff63df755bc760ba20aaeb8594c4a9728555a83e0b121'>packages/app-store/hubspot/api/callback.ts</a>
</details>
<details>
<summary>add.ts<code>Use relocated OAuth state encoder</code> <code>+1/-1</code></summary>
<br/>
>Use relocated OAuth state encoder
>
><pre>
>• Updates Lark Calendar authorization to import the OAuth state encoder from the centralized OAuth utilities.
></pre>
>
><a href='https://github.com/drape-io/crbench-qodo-2026-09/pull/18/files#diff-7e8e1fffa34e92d93f7caf880ff802617eb58c476a25e7ed25000a6ace544773'>packages/app-store/larkcalendar/api/add.ts</a>
</details>
<details>
<summary>callback.ts<code>Use relocated OAuth state decoder</code> <code>+1/-1</code></summary>
<br/>
>Use relocated OAuth state decoder
>
><pre>
>• Updates the Lark Calendar callback to import the OAuth state decoder from the centralized OAuth utilities.
></pre>
>
><a href='https://github.com/drape-io/crbench-qodo-2026-09/pull/18/files#diff-9884c7ae73c59c4ff18fce573a8bd046d115388d485afd86f662640994755190'>packages/app-store/larkcalendar/api/callback.ts</a>
</details>
<details>
<summary>add.ts<code>Use relocated OAuth state encoder</code> <code>+1/-1</code></summary>
<br/>
>Use relocated OAuth state encoder
>
><pre>
>• Updates Office 365 Calendar authorization to import the OAuth state encoder from the centralized OAuth utilities.
></pre>
>
><a href='https://github.com/drape-io/crbench-qodo-2026-09/pull/18/files#diff-21f10d535ad43d9e38017aa09da8ecdeef18bfaaa2ffe52418a204a11a1d7a04'>packages/app-store/office365calendar/api/add.ts</a>
</details>
<details>
<summary>callback.ts<code>Use relocated OAuth state decoder</code> <code>+1/-1</code></summary>
<br/>
>Use relocated OAuth state decoder
>
><pre>
>• Updates the Office 365 Calendar callback to import the OAuth state decoder from the centralized OAuth utilities.
></pre>
>
><a href='https://github.com/drape-io/crbench-qodo-2026-09/pull/18/files#diff-04c9ed979bc6eeab4329ca160f43f467540237050834ab37f793f696511d36d5'>packages/app-store/office365calendar/api/callback.ts</a>
</details>
<details>
<summary>add.ts<code>Use relocated OAuth state encoder</code> <code>+1/-1</code></summary>
<br/>
>Use relocated OAuth state encoder
>
><pre>
>• Updates Microsoft Teams authorization to import the OAuth state encoder from the centralized OAuth utilities.
></pre>
>
><a href='https://github.com/drape-io/crbench-qodo-2026-09/pull/18/files#diff-2146091529f31820afc48376232138a4e1fef8b97d33eb50a0141d2865c30d3e'>packages/app-store/office365video/api/add.ts</a>
</details>
<details>
<summary>callback.ts<code>Use centralized Teams OAuth helpers</code> <code>+2/-2</code></summary>
<br/>
>Use centralized Teams OAuth helpers
>
><pre>
>• Updates the Microsoft Teams callback to use relocated state decoding and credential creation utilities.
></pre>
>
><a href='https://github.com/drape-io/crbench-qodo-2026-09/pull/18/files#diff-875ea7ed262611312dbaa9f28312fa3b6be490ed43811b47ae03afef7147cecd'>packages/app-store/office365video/api/callback.ts</a>
</details>
<details>
<summary>add.ts<code>Use relocated OAuth state encoder</code> <code>+1/-1</code></summary>
<br/>
>Use relocated OAuth state encoder
>
><pre>
>• Updates Salesforce authorization to import the OAuth state encoder from the centralized OAuth utilities.
></pre>
>
><a href='https://github.com/drape-io/crbench-qodo-2026-09/pull/18/files#diff-fb27bb26bf5d9cd2045dc740ace3d3c98b2d32359f85b8aa4eb944596409dcbd'>packages/app-store/salesforce/api/add.ts</a>
</details>
<details>
<summary>callback.ts<code>Use centralized Salesforce OAuth helpers</code> <code>+2/-2</code></summary>
<br/>
>Use centralized Salesforce OAuth helpers
>
><pre>
>• Updates the Salesforce callback to use relocated state decoding and credential creation utilities.
></pre>
>
><a href='https://github.com/drape-io/crbench-qodo-2026-09/pull/18/files#diff-f7513557bd8f19d7ced6e6296fb7f1c0d199955e68030f3cef98209a2992df72'>packages/app-store/salesforce/api/callback.ts</a>
</details>
<details>
<summary>callback.ts<code>Use relocated OAuth credential helper</code> <code>+1/-1</code></summary>
<br/>
>Use relocated OAuth credential helper
>
><pre>
>• Updates the Stripe callback to import credential creation from the centralized OAuth utilities.
></pre>
>
><a href='https://github.com/drape-io/crbench-qodo-2026-09/pull/18/files#diff-a352e7a1a2e40aa408bea91d207e37338fea7e84de8758fe050cf83adda4975b'>packages/app-store/stripepayment/api/callback.ts</a>
</details>
<details>
<summary>callback.ts<code>Use relocated OAuth credential helper</code> <code>+1/-1</code></summary>
<br/>
>Use relocated OAuth credential helper
>
><pre>
>• Updates the Tandem callback to import credential creation from the centralized OAuth utilities.
></pre>
>
><a href='https://github.com/drape-io/crbench-qodo-2026-09/pull/18/files#diff-84a1323b81d356e934cd5617763856e713f0875267a594cc5de159db12966264'>packages/app-store/tandemvideo/api/callback.ts</a>
</details>
<details>
<summary>callback.ts<code>Use relocated OAuth credential helper</code> <code>+1/-1</code></summary>
<br/>
>Use relocated OAuth credential helper
>
><pre>
>• Updates the Webex callback to import credential creation from the centralized OAuth utilities.
></pre>
>
><a href='https://github.com/drape-io/crbench-qodo-2026-09/pull/18/files#diff-bb7c43404d09ab5ebb46c573d741b503240994215378bdf7baa775bf2638eecd'>packages/app-store/webex/api/callback.ts</a>
</details>
<details>
<summary>callback.ts<code>Use centralized Bigin OAuth helpers</code> <code>+2/-2</code></summary>
<br/>
>Use centralized Bigin OAuth helpers
>
><pre>
>• Updates the Zoho Bigin callback to use relocated state decoding and credential creation utilities.
></pre>
>
><a href='https://github.com/drape-io/crbench-qodo-2026-09/pull/18/files#diff-b90449d3b266f620bb026480e8e90193c7f59d53dc197cb75bd1782f54945d27'>packages/app-store/zoho-bigin/api/callback.ts</a>
</details>
<details>
<summary>_getAdd.ts<code>Use relocated OAuth state encoder</code> <code>+1/-1</code></summary>
<br/>
>Use relocated OAuth state encoder
>
><pre>
>• Updates Zoho CRM authorization to import the OAuth state encoder from the centralized OAuth utilities.
></pre>
>
><a href='https://github.com/drape-io/crbench-qodo-2026-09/pull/18/files#diff-aa3fc2ed298b2423bbd1c2688dbcfbd3c8bae44e43212dd051a24aead83322c4'>packages/app-store/zohocrm/api/_getAdd.ts</a>
</details>
<details>
<summary>callback.ts<code>Use centralized Zoho CRM OAuth helpers</code> <code>+2/-2</code></summary>
<br/>
>Use centralized Zoho CRM OAuth helpers
>
><pre>
>• Updates the Zoho CRM callback to use relocated state decoding and credential creation utilities.
></pre>
>
><a href='https://github.com/drape-io/crbench-qodo-2026-09/pull/18/files#diff-1661a841906d0fed2e5ababbf7c0cd849f61cbc488324c4a76f807eff28d0b04'>packages/app-store/zohocrm/api/callback.ts</a>
</details>
<details>
<summary>add.ts<code>Use relocated OAuth state encoder</code> <code>+1/-1</code></summary>
<br/>
>Use relocated OAuth state encoder
>
><pre>
>• Updates Zoom authorization to import the OAuth state encoder from the centralized OAuth utilities.
></pre>
>
><a href='https://github.com/drape-io/crbench-qodo-2026-09/pull/18/files#diff-6c47d7e3598497f02a67a774d840e2b73b35f0eb7ea775b3471d41f29ad29467'>packages/app-store/zoomvideo/api/add.ts</a>
</details>
<details>
<summary>callback.ts<code>Use relocated OAuth credential helper</code> <code>+1/-1</code></summary>
<br/>
>Use relocated OAuth credential helper
>
><pre>
>• Updates the Zoom callback to import credential creation from the centralized OAuth utilities.
></pre>
>
><a href='https://github.com/drape-io/crbench-qodo-2026-09/pull/18/files#diff-bc570c2645630dcd19fc2d5f09a074c33b22a06db8d0e1487249d41a0a524ebb'>packages/app-store/zoomvideo/api/callback.ts</a>
</details>
</dd>
</dl>
</details>
<details>
<summary>Other (3) <code> +21 / -1 </code></summary>
<dl>
<dd>
<details>
<summary>.env.example<code>Document credential synchronization environment variables</code> <code>+14/-1</code></summary>
<br/>
>Document credential synchronization environment variables
>
><pre>
>• Adds webhook authentication, external refresh endpoint, and AES-256 credential encryption settings for self-hosted credential sharing.
></pre>
>
><a href='https://github.com/drape-io/crbench-qodo-2026-09/pull/18/files#diff-a3046da0d15a27e89f2afe639b25748a7ad4d9290af3e7b1b6c1a5533c8f0a8c'>.env.example</a>
</details>
<details>
<summary>constants.ts<code>Expose credential sharing feature flag</code> <code>+3/-0</code></summary>
<br/>
>Expose credential sharing feature flag
>
><pre>
>• Enables app credential sharing only when both the webhook secret and encryption key are configured.
></pre>
>
><a href='https://github.com/drape-io/crbench-qodo-2026-09/pull/18/files#diff-84a559b7431271bcf747be80243751e28f9e17100616987cb5776afffe63e1a6'>packages/lib/constants.ts</a>
</details>
<details>
<summary>turbo.json<code>Register credential synchronization environment variables</code> <code>+4/-0</code></summary>
<br/>
>Register credential synchronization environment variables
>
><pre>
>• Adds webhook, encryption, and external synchronization settings to Turborepo's global environment inputs.
></pre>
>
><a href='https://github.com/drape-io/crbench-qodo-2026-09/pull/18/files#diff-f8de965273949793edc0fbfe249bb458c0becde39b2e141db087bcbf5d4ad5e3'>turbo.json</a>
</details>
</dd>
</dl>
</details>
</dd>
</dl>
</details>
<h3>Code Review by Qodo</h3>
<code>🐞 Bugs (8)</code> <code>📘 Rule violations (0)</code> <code>📜 Skill insights (0)</code>
<img src="https://www.qodo.ai/wp-content/uploads/2025/11/light-grey-line.svg" height="10%" alt="Grey Divider">
<br/>
<img src="https://img.shields.io/badge/High-634FD1?style=flat-square" height="20px" alt="Action required">
<details>
<summary> 1. Salesforce integration cannot compile <code>🐞 Bug</code> <code>≡ Correctness</code></summary>
<br/>
> <details open>
><summary>Description</summary>
><br/>
>
><pre>
><b><i>SalesforceCalendarService.getClient</i></b> calls <b><i>prisma.credential.update</i></b> without importing or
>declaring <b><i>prisma</i></b> in the module. Type checking fails whenever this file is compiled, preventing the
>app-store package from building before any Salesforce request can run.
></pre>
></details>
> <details>
><summary>Code</summary>
><br/>
>
><code>[packages/app-store/salesforce/lib/CalendarService.ts[R96-99]](https://github.com/drape-io/crbench-qodo-2026-09/pull/18/files#diff-22562b5993b71a352c1b37e0b336a3d15eccf430e02077903e4f135b98416ffaR96-R99)</code>
>
>```diff
>+ await prisma.credential.update({
>+ where: { id: credential.id },
>+ data: { key: { ...accessTokenParsed.data, refresh_token: credentialKey.refresh_token } },
>+ });
>```
></details>
> <details>
><summary>Evidence</summary>
><br/>
>
><pre>
>The complete import block contains no Prisma client import, while the newly added token-persistence
>path first references <b><i>prisma</i></b> directly at line 96, proving that the identifier is unresolved in
>this module.
></pre>
>
> <code>[packages/app-store/salesforce/lib/CalendarService.ts[1-20]](https://github.com/drape-io/crbench-qodo-2026-09/blob/b8312c948386faaeba5754b0a5e0656079c89850/packages/app-store/salesforce/lib/CalendarService.ts/#L1-L20)</code>
> <code>[packages/app-store/salesforce/lib/CalendarService.ts[96-99]](https://github.com/drape-io/crbench-qodo-2026-09/blob/b8312c948386faaeba5754b0a5e0656079c89850/packages/app-store/salesforce/lib/CalendarService.ts/#L96-L99)</code>
></details>
> <details>
><summary>Agent prompt</summary>
><br/>
>
>```
>The issue below was found during a code review. Follow the provided context and guidance below and implement a solution
>
>## Issue description
>The new Salesforce token-persistence call references `prisma` without importing it, causing a compile-time unresolved identifier error that prevents the package from building.
>
>## Fix Focus Areas
>- packages/app-store/salesforce/lib/CalendarService.ts[1-20]
>- packages/app-store/salesforce/lib/CalendarService.ts[96-99]
>
>## Recommended Fix
>Add the standard shared `prisma` import from `@calcom/prisma` alongside the other Cal.com imports, then retain the existing `prisma.credential.update` call.
>```
> <code>ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools</code>
></details>
<hr/>
</details>
<details>
<summary> 2. Google credentials become unreadable <code>🐞 Bug</code> <code>≡ Correctness</code></summary>
<br/>
> <details open>
><summary>Description</summary>
><br/>
>
><pre>
><b><i>parseRefreshTokenResponse</i></b> returns the complete <b><i>safeParse</i></b> result, but Google saves that wrapper
>as the credential key instead of saving its <b><i>data</i></b>. The next service initialization parses the
>resulting <b><i>{ success, data }</i></b> object as top-level Google credentials and rejects it because the
>token fields are nested.
></pre>
></details>
> <details>
><summary>Code</summary>
><br/>
>
><code>[packages/app-store/googlecalendar/lib/CalendarService.ts[R97-100]](https://github.com/drape-io/crbench-qodo-2026-09/pull/18/files#diff-6bfbaf63c841dc9343dba0c7487e30a546ffe2a63c9d9418379d0dbb88644d27R97-R100)</code>
>
>```diff
>+ const key = parseRefreshTokenResponse(googleCredentials, googleCredentialSchema);
> await prisma.credential.update({
> where: { id: credential.id },
> data: { key },
>```
></details>
> <details>
><summary>Evidence</summary>
><br/>
>
><pre>
>The helper returns <b><i>refreshTokenResponse</i></b>, while Google later expects <b><i>credential.key</i></b> itself to
>contain the fields required by <b><i>googleCredentialSchema</i></b>.
></pre>
>
> <code>[packages/app-store/_utils/oauth/parseRefreshTokenResponse.ts[13-29]](https://github.com/drape-io/crbench-qodo-2026-09/blob/b8312c948386faaeba5754b0a5e0656079c89850/packages/app-store/_utils/oauth/parseRefreshTokenResponse.ts/#L13-L29)</code>
> <code>[packages/app-store/googlecalendar/lib/CalendarService.ts[74-76]](https://github.com/drape-io/crbench-qodo-2026-09/blob/b8312c948386faaeba5754b0a5e0656079c89850/packages/app-store/googlecalendar/lib/CalendarService.ts/#L74-L76)</code>
> <code>[packages/app-store/googlecalendar/lib/CalendarService.ts[97-100]](https://github.com/drape-io/crbench-qodo-2026-09/blob/b8312c948386faaeba5754b0a5e0656079c89850/packages/app-store/googlecalendar/lib/CalendarService.ts/#L97-L100)</code>
> <code>[packages/app-store/googlecalendar/lib/googleCredentialSchema.ts[3-9]](https://github.com/drape-io/crbench-qodo-2026-09/blob/b8312c948386faaeba5754b0a5e0656079c89850/packages/app-store/googlecalendar/lib/googleCredentialSchema.ts/#L3-L9)</code>
></details>
> <details>
><summary>Agent prompt</summary>
><br/>
>
>```
>The issue below was found during a code review. Follow the provided context and guidance below and implement a solution
>
>## Issue description
>Google stores the Zod `safeParse` wrapper instead of the parsed credential object, making the saved credential incompatible with its schema.
>
>## Fix Focus Areas
>- packages/app-store/_utils/oauth/parseRefreshTokenResponse.ts[13-29]
>- packages/app-store/googlecalendar/lib/CalendarService.ts[74-100]
>
>## Recommended Fix
>Return parsed token data from `parseRefreshTokenResponse`, or explicitly persist `key.data`, and update the helper's other callers consistently with the selected return contract.
>```
> <code>ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools</code>
></details>
<hr/>
</details>
<details>
<summary> 3. Synced tokens lose refresh credentials <code>🐞 Bug</code> <code>≡ Correctness</code></summary>
<br/>
> <details open>
><summary>Description</summary>
><br/>
>
><pre>
><b><i>minimumTokenResponseSchema</i></b> uses computed object-property names instead of a catch-all or explicit
>normalized schema, including a <b><i>z.string().toString()</i></b> key that becomes the required literal
><b><i>"[object Object]"</i></b>; when parsing succeeds, Zod strips fields beyond <b><i>access_token</i></b> and the helper
>inserts the literal value <b><i>"refresh_token"</i></b>. With credential synchronization enabled, normal refresh
>responses from Google, Office 365, Zoom, and Salesforce can fail validation before saving, while
>accepted responses can replace usable refresh tokens and discard expiry and provider-specific fields
>such as Salesforce's instance URL before persistence.
></pre>
></details>
> <details>
><summary>Code</summary>
><br/>
>
><code>[packages/app-store/_utils/oauth/parseRefreshTokenResponse.ts[R5-8]](https://github.com/drape-io/crbench-qodo-2026-09/pull/18/files#diff-1dbb810b9c428b806675c66b731ab1c4c83cf9015f4057ce9fd9784406a895deR5-R8)</code>
>
>```diff
>+const minimumTokenResponseSchema = z.object({
>+ access_token: z.string(),
>+ // Assume that any property with a number is the expiry
>+ [z.string().toString()]: z.number(),
>```
></details>
> <details>
><summary>Evidence</summary>
><br/>
>
><pre>
>The cited parser lines show that the synchronization branch selects the minimum schema, throws on
>validation failure, lacks a true catch-all, and mutates the parsed result to add a placeholder
>refresh token. The cited provider call sites show that Google, Office 365, Zoom, and Salesforce
>route refresh responses through this branch, while the Office 365, Zoom, and Salesforce callers
>depend on preserved expiry, refresh-token, or provider-specific values when updating persisted
>credentials.
></pre>
>
> <code>[packages/app-store/_utils/oauth/parseRefreshTokenResponse.ts[5-29]](https://github.com/drape-io/crbench-qodo-2026-09/blob/b8312c948386faaeba5754b0a5e0656079c89850/packages/app-store/_utils/oauth/parseRefreshTokenResponse.ts/#L5-L29)</code>
> <code>[packages/app-store/office365calendar/lib/CalendarService.ts[263-273]](https://github.com/drape-io/crbench-qodo-2026-09/blob/b8312c948386faaeba5754b0a5e0656079c89850/packages/app-store/office365calendar/lib/CalendarService.ts/#L263-L273)</code>
> <code>[packages/app-store/office365calendar/types/Office365Calendar.ts[1-5]](https://github.com/drape-io/crbench-qodo-2026-09/blob/b8312c948386faaeba5754b0a5e0656079c89850/packages/app-store/office365calendar/types/Office365Calendar.ts/#L1-L5)</code>
> <code>[packages/app-store/zoomvideo/lib/VideoApiAdapter.ts[66-72]](https://github.com/drape-io/crbench-qodo-2026-09/blob/b8312c948386faaeba5754b0a5e0656079c89850/packages/app-store/zoomvideo/lib/VideoApiAdapter.ts/#L66-L72)</code>
> <code>[packages/app-store/zoomvideo/lib/VideoApiAdapter.ts[104-124]](https://github.com/drape-io/crbench-qodo-2026-09/blob/b8312c948386faaeba5754b0a5e0656079c89850/packages/app-store/zoomvideo/lib/VideoApiAdapter.ts/#L104-L124)</code>
> <code>[packages/app-store/salesforce/lib/CalendarService.ts[39-47]](https://github.com/drape-io/crbench-qodo-2026-09/blob/b8312c948386faaeba5754b0a5e0656079c89850/packages/app-store/salesforce/lib/CalendarService.ts/#L39-L47)</code>
> <code>[packages/app-store/googlecalendar/lib/CalendarService.ts[94-102]](https://github.com/drape-io/crbench-qodo-2026-09/blob/b8312c948386faaeba5754b0a5e0656079c89850/packages/app-store/googlecalendar/lib/CalendarService.ts/#L94-L102)</code>
> <code>[packages/app-store/office365calendar/lib/CalendarService.ts[255-266]](https://github.com/drape-io/crbench-qodo-2026-09/blob/b8312c948386faaeba5754b0a5e0656079c89850/packages/app-store/office365calendar/lib/CalendarService.ts/#L255-L266)</code>
> <code>[packages/app-store/zoomvideo/lib/VideoApiAdapter.ts[96-107]](https://github.com/drape-io/crbench-qodo-2026-09/blob/b8312c948386faaeba5754b0a5e0656079c89850/packages/app-store/zoomvideo/lib/VideoApiAdapter.ts/#L96-L107)</code>
> <code>[packages/app-store/salesforce/lib/CalendarService.ts[88-99]](https://github.com/drape-io/crbench-qodo-2026-09/blob/b8312c948386faaeba5754b0a5e0656079c89850/packages/app-store/salesforce/lib/CalendarService.ts/#L88-L99)</code>
></details>
> <details>
><summary>Agent prompt</summary>
><br/>
>
>```
>The issue below was found during a code review. Follow the provided context and guidance below and implement a solution
>
>## Issue description
>The minimum token schema uses computed JavaScript property names rather than a valid catch-all, record, or explicit normalized response schema. This creates an unintended required `"[object Object]"` field, strips arbitrary token properties from accepted responses, and fabricates a refresh token, causing synchronization-aware callers either to reject normal responses or persist corrupted credentials.
>
>## Fix Focus Areas
>- packages/app-store/_utils/oauth/parseRefreshTokenResponse.ts[5-29]
>- packages/app-store/office365calendar/lib/CalendarService.ts[263-273]
>- packages/app-store/salesforce/lib/CalendarService.ts[90-99]
>- packages/app-store/zoomvideo/lib/VideoApiAdapter.ts[104-124]
>
>## Recommended Fix
>Replace the computed keys with an explicit normalized synchronization response schema or an appropriate passthrough, `z.record`, catch-all, or refinement that validates required fields such as `access_token` and the documented expiry field while preserving additional token and provider-specific properties. When the response omits `refresh_token`, retain the credential's existing refresh token instead of mutating the parsed response or substituting a placeholder value.
>```
> <code>ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools</code>
></details>
<hr/>
</details>
<details><summary><ins><strong>View high (4)</strong></ins></summary><br/>
<details>
<summary> 4. Valid app credentials are rejected <code>🐞 Bug</code> <code>≡ Correctness</code></summary>
<br/>
> <details open>
><summary>Description</summary>
><br/>
>
><pre>
>The webhook indexes <b><i>appStoreMetadata</i></b> by the database app slug even though the registry is keyed by
>directory name. Requests for apps whose names differ, including the <b><i>google-calendar</i></b> slug backed by
>the <b><i>googlecalendar</i></b> registry key, pass the database lookup but incorrectly return an app-not-found
>response.
></pre>
></details>
> <details>
><summary>Code</summary>
><br/>
>
><code>[apps/web/pages/api/webhook/app-credential.ts[R49-50]](https://github.com/drape-io/crbench-qodo-2026-09/pull/18/files#diff-63b0a18ea4146e22fa313cdf690f65ae499762ad6396440f8b04ad84d9b6330dR49-R50)</code>
>
>```diff
>+ // Search for the app's slug and type
>+ const appMetadata = appStoreMetadata[app.slug as keyof typeof appStoreMetadata];
>```
></details>
> <details>
><summary>Evidence</summary>
><br/>
>
><pre>
>Google Calendar's metadata declares different slug and directory values, the generated registry uses
>the directory value, and the existing registry helper resolves public slugs by searching metadata
>values.
></pre>
>
> <code>[apps/web/pages/api/webhook/app-credential.ts[40-53]](https://github.com/drape-io/crbench-qodo-2026-09/blob/b8312c948386faaeba5754b0a5e0656079c89850/apps/web/pages/api/webhook/app-credential.ts/#L40-L53)</code>
> <code>[packages/app-store/apps.metadata.generated.ts[97-99]](https://github.com/drape-io/crbench-qodo-2026-09/blob/b8312c948386faaeba5754b0a5e0656079c89850/packages/app-store/apps.metadata.generated.ts/#L97-L99)</code>
> <code>[packages/app-store/googlecalendar/_metadata.ts[17-20]](https://github.com/drape-io/crbench-qodo-2026-09/blob/b8312c948386faaeba5754b0a5e0656079c89850/packages/app-store/googlecalendar/_metadata.ts/#L17-L20)</code>
> <code>[packages/app-store/_appRegistry.ts[19-24]](https://github.com/drape-io/crbench-qodo-2026-09/blob/b8312c948386faaeba5754b0a5e0656079c89850/packages/app-store/_appRegistry.ts/#L19-L24)</code>
></details>
> <details>
><summary>Agent prompt</summary>
><br/>
>
>```
>The issue below was found during a code review. Follow the provided context and guidance below and implement a solution
>
>## Issue description
>The credential webhook treats public app slugs as metadata registry keys, rejecting apps whose directory name differs from their slug.
>
>## Fix Focus Areas
>- apps/web/pages/api/webhook/app-credential.ts[40-54]
>- packages/app-store/_appRegistry.ts[19-24]
>- packages/app-store/googlecalendar/_metadata.ts[17-20]
>
>## Recommended Fix
>Resolve the metadata by searching metadata values for a matching `slug`, preferably by reusing the repository's existing app-registry slug resolver.
>```
> <code>ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools</code>
></details>
<hr/>
</details>
<details>
<summary> 5. Salesforce bypasses credential sync <code>🐞 Bug</code> <code>≡ Correctness</code></summary>
<br/>
> <details open>
><summary>Description</summary>
><br/>
>
><pre>
>The Salesforce refresh path always posts directly to the provider and only uses the
>synchronization-aware parsing helper afterward. When credential sharing and its endpoint are
>configured, Salesforce never calls the helper that routes refreshes through that endpoint, unlike
>the other integrations changed by this pull request.
></pre>
></details>
> <details>
><summary>Code</summary>
><br/>
>
><code>[packages/app-store/salesforce/lib/CalendarService.ts[R75-78]](https://github.com/drape-io/crbench-qodo-2026-09/pull/18/files#diff-22562b5993b71a352c1b37e0b336a3d15eccf430e02077903e4f135b98416ffaR75-R78)</code>
>
>```diff
>+ const response = await fetch("https://login.salesforce.com/services/oauth2/token", {
>+ method: "POST",
>+ body: new URLSearchParams({
>+ grant_type: "refresh_token",
>```
></details>
> <details>
><summary>Evidence</summary>
><br/>
>
><pre>
>The Salesforce implementation imports only the parsing helper and unconditionally fetches the
>provider URL, while synchronization routing exists exclusively in <b><i>refreshOAuthTokens</i></b>.
></pre>
>
> <code>[packages/app-store/salesforce/lib/CalendarService.ts[19-20]](https://github.com/drape-io/crbench-qodo-2026-09/blob/b8312c948386faaeba5754b0a5e0656079c89850/packages/app-store/salesforce/lib/CalendarService.ts/#L19-L20)</code>
> <code>[packages/app-store/salesforce/lib/CalendarService.ts[75-90]](https://github.com/drape-io/crbench-qodo-2026-09/blob/b8312c948386faaeba5754b0a5e0656079c89850/packages/app-store/salesforce/lib/CalendarService.ts/#L75-L90)</code>
> <code>[packages/app-store/_utils/oauth/refreshOAuthTokens.ts[3-19]](https://github.com/drape-io/crbench-qodo-2026-09/blob/b8312c948386faaeba5754b0a5e0656079c89850/packages/app-store/_utils/oauth/refreshOAuthTokens.ts/#L3-L19)</code>
></details>
> <details>
><summary>Agent prompt</summary>
><br/>
>
>```
>The issue below was found during a code review. Follow the provided context and guidance below and implement a solution
>
>## Issue description
>Salesforce performs provider refreshes directly even when application credential synchronization is enabled.
>
>## Fix Focus Areas
>- packages/app-store/salesforce/lib/CalendarService.ts[19-20]
>- packages/app-store/salesforce/lib/CalendarService.ts[75-90]
>- packages/app-store/_utils/oauth/refreshOAuthTokens.ts[3-19]
>
>## Recommended Fix
>Wrap the Salesforce provider request with `refreshOAuthTokens`, pass the Salesforce app slug and `credential.userId`, and consume the helper's normalized token-data contract.
>```
> <code>ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools</code>
></details>
<hr/>
</details>
<details>
<summary> 6. Synced calendar refreshes receive unusable tokens <code>🐞 Bug</code> <code>≡ Correctness</code></summary>
<br/>
> <details open>
><summary>Description</summary>
><br/>
>
><pre>
>The synchronization branch of <b><i>refreshOAuthTokens</i></b> returns a raw Fetch <b><i>Response</i></b>, while its normal
>branch returns provider-specific parsed response objects and the callers expect Gaxios, SDK, or
>Axios-style token shapes. When synchronization is enabled, Google dereferences undefined <b><i>.data</i></b>,
>the Zoho paths fail while accessing <b><i>.data</i></b>, and HubSpot calculates and persists fields from the
>wrong object.
></pre>
></details>
> <details>
><summary>Code</summary>
><br/>
>
><code>[packages/app-store/_utils/oauth/refreshOAuthTokens.ts[R8-15]](https://github.com/drape-io/crbench-qodo-2026-09/pull/18/files#diff-66346f512f26fdd5abf59c14e97ea74602ef51a5d36969983730e196042a774bR8-R15)</code>
>
>```diff
>+ const response = await fetch(process.env.CALCOM_CREDENTIAL_SYNC_ENDPOINT, {
>+ method: "POST",
>+ body: new URLSearchParams({
>+ calcomUserId: userId.toString(),
>+ appSlug,
>+ }),
>+ });
>+ return response;
>```
></details>
> <details>
><summary>Evidence</summary>
><br/>
>
><pre>
>The cited helper returns a native Fetch response only from its synchronization branch, while the
>cited Google, HubSpot, Zoho Bigin, and Zoho CRM callers access <b><i>.data</i></b> or token properties supplied
>by their previous Gaxios, SDK, or Axios response objects. These incompatible property accesses show
>that the synchronized result cannot be consumed through the existing caller logic.
></pre>
>
> <code>[packages/app-store/_utils/oauth/refreshOAuthTokens.ts[3-19]](https://github.com/drape-io/crbench-qodo-2026-09/blob/b8312c948386faaeba5754b0a5e0656079c89850/packages/app-store/_utils/oauth/refreshOAuthTokens.ts/#L3-L19)</code>
> <code>[packages/app-store/googlecalendar/lib/CalendarService.ts[86-100]](https://github.com/drape-io/crbench-qodo-2026-09/blob/b8312c948386faaeba5754b0a5e0656079c89850/packages/app-store/googlecalendar/lib/CalendarService.ts/#L86-L100)</code>
> <code>[packages/app-store/hubspot/lib/CalendarService.ts[177-198]](https://github.com/drape-io/crbench-qodo-2026-09/blob/b8312c948386faaeba5754b0a5e0656079c89850/packages/app-store/hubspot/lib/CalendarService.ts/#L177-L198)</code>
> <code>[packages/app-store/zoho-bigin/lib/CalendarService.ts[85-115]](https://github.com/drape-io/crbench-qodo-2026-09/blob/b8312c948386faaeba5754b0a5e0656079c89850/packages/app-store/zoho-bigin/lib/CalendarService.ts/#L85-L115)</code>
> <code>[packages/app-store/zohocrm/lib/CalendarService.ts[204-220]](https://github.com/drape-io/crbench-qodo-2026-09/blob/b8312c948386faaeba5754b0a5e0656079c89850/packages/app-store/zohocrm/lib/CalendarService.ts/#L204-L220)</code>
> <code>[packages/app-store/googlecalendar/lib/CalendarService.ts[86-96]](https://github.com/drape-io/crbench-qodo-2026-09/blob/b8312c948386faaeba5754b0a5e0656079c89850/packages/app-store/googlecalendar/lib/CalendarService.ts/#L86-L96)</code>
> <code>[packages/app-store/hubspot/lib/CalendarService.ts[177-202]](https://github.com/drape-io/crbench-qodo-2026-09/blob/b8312c948386faaeba5754b0a5e0656079c89850/packages/app-store/hubspot/lib/CalendarService.ts/#L177-L202)</code>
> <code>[packages/app-store/zohocrm/lib/CalendarService.ts[204-237]](https://github.com/drape-io/crbench-qodo-2026-09/blob/b8312c948386faaeba5754b0a5e0656079c89850/packages/app-store/zohocrm/lib/CalendarService.ts/#L204-L237)</code>
></details>
> <details>
><summary>Agent prompt</summary>
><br/>
>
>```
>The issue below was found during a code review. Follow the provided context and guidance below and implement a solution
>
>## Issue description
>The refresh helper returns different response abstractions depending on which branch runs: the synchronization path returns a native Fetch response, while callers expect the parsed token shape produced by their provider refresh functions.
>
>## Fix Focus Areas
>- packages/app-store/_utils/oauth/refreshOAuthTokens.ts[3-19]
>- packages/app-store/googlecalendar/lib/CalendarService.ts[84-100]
>- packages/app-store/hubspot/lib/CalendarService.ts[175-202]
>- packages/app-store/zoho-bigin/lib/CalendarService.ts[85-115]
>- packages/app-store/zohocrm/lib/CalendarService.ts[204-237]
>
>## Recommended Fix
>Define one normalized token-data return contract for `refreshOAuthTokens`. Parse and validate the synchronization endpoint response, decode provider responses into the same contract, and update every caller to consume normalized token data rather than mixing Fetch `Response`, Axios, Gaxios, SDK, and provider-specific response wrappers.
>```
> <code>ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools</code>
></details>
<hr/>
</details>
<details>
<summary> 7. Zoho Bigin refreshes the wrong identity <code>🐞 Bug</code> <code>≡ Correctness</code></summary>
<br/>
> <details open>
><summary>Description</summary>
><br/>
>
><pre>
><b><i>BiginCalendarService.biginAuth</i></b> passes <b><i>credential.id</i></b> through <b><i>refreshAccessToken</i></b> as the third
>argument to <b><i>refreshOAuthTokens</i></b>, even though the helper serializes that value as <b><i>calcomUserId</i></b>.
>When a Bigin token expires with synchronization enabled, the remote credential service receives a
>credential-row ID instead of the owning user's ID, so it can fetch tokens for an unrelated user or
>fail to find the intended one.
></pre>
></details>
> <details>
><summary>Code</summary>
><br/>
>
><code>[packages/app-store/zoho-bigin/lib/CalendarService.ts[R85-94]](https://github.com/drape-io/crbench-qodo-2026-09/pull/18/files#diff-34b0f03542e82d428c6a8862165903827d1615fb622597f5637dd65a987dcbc9R85-R94)</code>
>
>```diff
>+ const tokenInfo = await refreshOAuthTokens(
>+ async () =>
>+ await axios.post(accountsUrl, qs.stringify(formData), {
>+ headers: {
>+ "Content-Type": "application/x-www-form-urlencoded;charset=utf-8",
>+ },
>+ }),
>+ "zoho-bigin",
>+ credentialId
>+ );
>```
></details>
> <details>
><summary>Evidence</summary>
><br/>
>
><pre>
>The Bigin service explicitly derives <b><i>credentialId</i></b> from <b><i>credential.id</i></b> and forwards it to the
>shared helper, whose third parameter is named and serialized as <b><i>calcomUserId</i></b>; the Prisma model
>confirms that the credential ID and user ID are distinct fields.
></pre>
>
> <code>[packages/app-store/zoho-bigin/lib/CalendarService.ts[51-63]](https://github.com/drape-io/crbench-qodo-2026-09/blob/b8312c948386faaeba5754b0a5e0656079c89850/packages/app-store/zoho-bigin/lib/CalendarService.ts/#L51-L63)</code>
> <code>[packages/app-store/zoho-bigin/lib/CalendarService.ts[69-115]](https://github.com/drape-io/crbench-qodo-2026-09/blob/b8312c948386faaeba5754b0a5e0656079c89850/packages/app-store/zoho-bigin/lib/CalendarService.ts/#L69-L115)</code>
> <code>[packages/app-store/_utils/oauth/refreshOAuthTokens.ts[3-13]](https://github.com/drape-io/crbench-qodo-2026-09/blob/b8312c948386faaeba5754b0a5e0656079c89850/packages/app-store/_utils/oauth/refreshOAuthTokens.ts/#L3-L13)</code>
> <code>[packages/app-store/zoho-bigin/lib/CalendarService.ts[51-69]](https://github.com/drape-io/crbench-qodo-2026-09/blob/b8312c948386faaeba5754b0a5e0656079c89850/packages/app-store/zoho-bigin/lib/CalendarService.ts/#L51-L69)</code>
> <code>[packages/app-store/zoho-bigin/lib/CalendarService.ts[85-104]](https://github.com/drape-io/crbench-qodo-2026-09/blob/b8312c948386faaeba5754b0a5e0656079c89850/packages/app-store/zoho-bigin/lib/CalendarService.ts/#L85-L104)</code>
> <code>[packages/prisma/schema.prisma[128-135]](https://github.com/drape-io/crbench-qodo-2026-09/blob/b8312c948386faaeba5754b0a5e0656079c89850/packages/prisma/schema.prisma/#L128-L135)</code>
></details>
> <details>
><summary>Agent prompt</summary>
><br/>
>
>```
>The issue below was found during a code review. Follow the provided context and guidance below and implement a solution
>
>## Issue description
>Zoho Bigin sends the credential record ID in the synchronization payload field intended for the Cal.com user ID.
>
>## Fix Focus Areas
>- packages/app-store/zoho-bigin/lib/CalendarService.ts[51-69]
>- packages/app-store/zoho-bigin/lib/CalendarService.ts[85-94]
>- packages/app-store/_utils/oauth/refreshOAuthTokens.ts[3-13]
>
>## Recommended Fix
>Carry `credential.userId` separately into `refreshAccessToken` and pass it as the third argument to `refreshOAuthTokens`. Continue using `credential.id` only for the subsequent local credential database update.
>```
> <code>ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools</code>
></details>
<hr/>
</details>
</details>
<br/>
<img src="https://img.shields.io/badge/Medium-634FD1?style=flat-square" height="20px" alt="Remediation recommended">
<details>
<summary> 8. Concurrent webhook syncs duplicate credentials <code>🐞 Bug</code> <code>☼ Reliability</code></summary>
<br/>
> <details open>
><summary>Description</summary>
><br/>
>
><pre>
>The credential webhook performs a separate <b><i>findFirst</i></b> followed by <b><i>create</i></b>, while <b><i>Credential</i></b> has
>no unique constraint on the <b><i>(userId, appId)</i></b> pair. Concurrent deliveries can both observe no
>existing row and insert duplicates, after which later syncs update whichever duplicate <b><i>findFirst</i></b>
>selects.
></pre>
></details>
> <details>
><summary>Code</summary>
><br/>
>
><code>[apps/web/pages/api/webhook/app-credential.ts[R61-70]](https://github.com/drape-io/crbench-qodo-2026-09/pull/18/files#diff-63b0a18ea4146e22fa313cdf690f65ae499762ad6396440f8b04ad84d9b6330dR61-R70)</code>
>
>```diff
>+ // Can't use prisma upsert as we don't know the id of the credential
>+ const appCredential = await prisma.credential.findFirst({
>+ where: {
>+ userId: reqBody.userId,
>+ appId: appMetadata.slug,
>+ },
>+ select: {
>+ id: true,
>+ },
>+ });
>```
></details>
> <details>
><summary>Evidence</summary>
><br/>
>
><pre>
>The route performs the existence check and insertion as separate database calls, while the
>credential schema defines only independent indexes for <b><i>userId</i></b> and <b><i>appId</i></b>, with no compound
>uniqueness constraint preventing duplicate user-app rows; together, these citations establish that
>concurrent requests can race and create duplicates.
></pre>
>
> <code>[apps/web/pages/api/webhook/app-credential.ts[61-91]](https://github.com/drape-io/crbench-qodo-2026-09/blob/b8312c948386faaeba5754b0a5e0656079c89850/apps/web/pages/api/webhook/app-credential.ts/#L61-L91)</code>
> <code>[packages/prisma/schema.prisma[127-146]](https://github.com/drape-io/crbench-qodo-2026-09/blob/b8312c948386faaeba5754b0a5e0656079c89850/packages/prisma/schema.prisma/#L127-L146)</code>
> <code>[apps/web/pages/api/webhook/app-credential.ts[61-90]](https://github.com/drape-io/crbench-qodo-2026-09/blob/b8312c948386faaeba5754b0a5e0656079c89850/apps/web/pages/api/webhook/app-credential.ts/#L61-L90)</code>
></details>
> <details>
><summary>Agent prompt</summary>
><br/>
>
>```
>The issue below was found during a code review. Follow the provided context and guidance below and implement a solution
>
>## Issue description
>The webhook uses a non-atomic read-then-create sequence for a credential identity that the database does not enforce as unique, allowing concurrent deliveries to create duplicate user-app credentials.
>
>## Fix Focus Areas
>- apps/web/pages/api/webhook/app-credential.ts[61-91]
>- packages/prisma/schema.prisma[127-146]
>
>## Recommended Fix
>Add a database uniqueness constraint for the intended user/app credential identity and replace the check-then-create sequence with an atomic upsert against that constraint, or use a transaction that safely handles uniqueness conflicts. If existing data permits multiple credentials for an app, introduce a stable synchronization key and use it consistently for atomic writes.
>```
> <code>ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools</code>
></details>
<hr/>
</details>
<img src="https://www.qodo.ai/wp-content/uploads/2025/11/light-grey-line.svg" height="10%" alt="Grey Divider">
<!-- qodo-context:start -->
<details><summary><strong>Context sources</strong></summary>
<div>Review mode: <code>🧠 Deep</code>: This security-sensitive credential-sync feature changes webhook authentication, encryption/decryption, token refresh behavior, and many independent OAuth integration paths, creating a high density of subtle defects across a broad blast radius.</div>
<!-- qodo-context:end -->
</details>
<img src="https://www.qodo.ai/wp-content/uploads/2025/11/light-grey-line.svg" height="10%" alt="Grey Divider">
<!-- qodo-daily-tip:start -->
<details>
<summary><strong>Tip of the day</strong></summary>
<br/>
<pre>💡 Did you know, you can reply 'qodo' on any finding to push back, ask questions, or dig deeper</pre>
<a href="https://docs.qodo.ai/tips-and-tricks">More tips ↗</a> | <a href="https://app.qodo.ai/configurations?tab=display-preferences">Customize Qodo ↗</a> | <a href="https://docs.qodo.ai">Qodo docs ↗</a>
</details>
<img src="https://www.qodo.ai/wp-content/uploads/2025/11/light-grey-line.svg" height="10%" alt="Grey Divider">
<!-- qodo-daily-tip:end -->
<!-- https://github.com/drape-io/crbench-qodo-2026-09/commit/b8312c948386faaeba5754b0a5e0656079c89850 -->
<a href="https://www.qodo.ai"><img src="https://www.qodo.ai/wp-content/uploads/2025/03/qodo-logo.svg" width="80" alt="Qodo Logo"></a>