GLM-5.3 · Heavy

oauth-credential-sync-and-app-integration-enhancements-cal-com

cal.com · TypeScript · M · 100–299 lines · 6 files

The generalist plus 9 specialist lens agents in parallel, then the same verify and dedup steps. Judge: Claude Haiku 5.5.

Gold bugs found
5 of 9
Comments published
15
Comments matching a bug
5
Comments not matching
10
Cost of this PR
$2.931

Published comments (15)

highbugapps/web/pages/api/webhook/app-credential.ts:50-54

Metadata lookup uses slug to index a map keyed by dirName — The metadata lookup `appStoreMetadata[app.slug]` indexes a map that is keyed by app dirName, not by slug (apps.metadata.generated.ts:98 keys entries as `googlecalendar:`, and _appRegistry.ts:17 indexes the same map with `app.dirName`). For every app whose slug differs from its dirName — google-calendar, office365-calendar, msteams, lark-calendar, zoom — the lookup returns undefined and the webhook responds 404 "App not found", and the caller cannot work around it because the earlier `prisma.app.findUnique({ where: { slug } })` only accepts the slug.

highbugpackages/app-store/zoomvideo/lib/VideoApiAdapter.ts:92

Wrong app slug passed to refreshOAuthTokens: "zoomvideo" should be "zoom" — The appSlug passed to `refreshOAuthTokens` is `"zoomvideo"`, but the Zoom app's actual slug is `"zoom"` (zoomvideo/_metadata.ts:16 and getZoomAppKeys.ts:11 both use "zoom"). When credential sharing is enabled, the sync endpoint receives an app identifier that matches no App row, so it cannot resolve the user's Zoom credentials and Zoom token refresh fails.

highbugpackages/app-store/salesforce/lib/CalendarService.ts:90-99

Refresh parses direct Salesforce response with stripping minimum schema, dropping instance_url — `parseRefreshTokenResponse` chooses the stripping `minimumTokenResponseSchema` whenever `APP_CREDENTIAL_SHARING_ENABLED && CALCOM_CREDENTIAL_SYNC_ENDPOINT` are set, but Salesforce never calls `refreshOAuthTokens` — the parsed response always comes from the direct `login.salesforce.com` token endpoint. In sharing mode the full Salesforce response is parsed with the minimum schema, so the credential update saves `{access_token, refresh_token}` and drops `instance_url`/`signature`/`scope`; the next instantiation builds the jsforce connection from the DB key and loses `instance_url`, breaking Salesforce.

highbugpackages/app-store/googlecalendar/lib/CalendarService.ts:97-100

Persisted Google credential is the safeParse envelope, breaking future parses — The refreshed credential persisted to the database is the zod safeParse result envelope, not the parsed data: `parseRefreshTokenResponse` returns `{success, data}` and `const key = parseRefreshTokenResponse(googleCredentials, googleCredentialSchema)` stores that whole envelope via `prisma.credential.update({data: {key}})`. On the next service construction, `googleCredentialSchema.parse(credential.key)` (line 75) throws a ZodError because the envelope lacks scope/token_type/expiry_date/access_token/refresh_token at the top level, permanently breaking the user's Google Calendar integration after the first routine token refresh — in default (non-sharing) deployments.

highbugpackages/app-store/_utils/oauth/refreshOAuthTokens.ts:8-15

Credential sync path returns raw fetch Response, breaking OAuth refresh at all call sites — When credential sync is enabled this function returns the raw `fetch` Response of the sync endpoint, but the call sites it wraps were written against provider-specific response shapes and immediately break: googlecalendar reads `res?.data` (gaxios shape) so `token` is undefined and `token.access_token` throws a TypeError (swallowed by the catch, silently reusing the stale token); zoho-bigin (`tokenInfo.data.error`) and zohocrm (`zohoCrmTokenInfo.data.error`) throw TypeError on undefined `.data`; hubspot expects the SDK `HubspotToken` so `hubspotRefreshToken.expiresIn` is undefined (NaN expiryDate, `setAccessToken(undefined)`, and the Response object is persisted to Prisma at CalendarService.ts:193-200). OAuth refresh is broken for these apps in any sharing-enabled deployment; the helper must return a normalized shape all callers agree on (or parse the JSON once and let each adapter map it). **Also found in:** - `packages/app-store/googlecalendar/lib/CalendarService.ts:86-96` - `packages/app-store/hubspot/lib/CalendarService.ts:177-191`

highbugpackages/app-store/_utils/oauth/parseRefreshTokenResponse.ts:5-27

Invalid computed keys strip all but access_token; fake refresh_token saved — The "minimum" schema's computed keys `[z.string().toString()]` and `[z.string().optional().toString()]` both evaluate to the literal string "[object Object]" (ZodString has no custom toString, and the duplicate object-literal key is overwritten), so the schema effectively validates only `access_token`. Zod objects strip unknown keys by default, so in the credential-sharing path the parsed output contains only `access_token` — refresh_token, expiry_date, instance_url, etc. are all stripped.

highbugpackages/app-store/_utils/oauth/parseRefreshTokenResponse.ts:5-11

Computed keys collapse to "[object Object]", stripping fields from parsed token — The computed catch-all keys `[z.string().toString()]` and `[z.string().optional().toString()]` both evaluate to the literal property name `"[object Object]"` (zod 3.x ZodString has no toString override, and the second key overwrites the first), so the intended "any numeric property is the expiry" / "allow other properties" semantics do not exist and `z.object`'s default strip mode removes every field except `access_token` from the parsed data. In sharing mode this corrupts persisted credentials: salesforce stores a key without `instance_url` (next instantiation builds the jsforce connection with `instanceUrl: undefined`) and office365calendar never receives the transformed `expires_in`, so its stored expiry stays expired and every getToken triggers a new refresh.

highbugpackages/app-store/_utils/oauth/parseRefreshTokenResponse.ts:5-11

Computed schema keys collapse, stripping refresh_token and breaking credentials — The computed keys `[z.string().toString()]` and `[z.string().optional().toString()]` both evaluate to the literal string `"[object Object]"` (Zod schemas don't override `toString`, and z.object has no wildcard shape keys), so the duplicate key collapses and the declared validations — "any property with a number is the expiry" and "allow other properties" — never run. The schema is effectively just `{access_token: string}`, and since z.object strips unknown keys, `data` contains only `access_token`; the injected dummy `refresh_token = "refresh_token"` then overwrites consumers' real refresh tokens (e.g. office365calendar's spread at CalendarService.ts:264 saves `refresh_token: "refresh_token"` to the DB, permanently breaking the credential in sharing mode).

highbugpackages/app-store/_utils/oauth/parseRefreshTokenResponse.ts:5-11

Computed key `[z.string().toString()]` collapses to "[object Object]"; schema silently drops… — The comments on lines 7-10 do not describe what the schema does. "Assume that any property with a number is the expiry" — the computed key `[z.string().toString()]` does not create a wildcard for numeric properties; zod schemas have no `toString` override, so this evaluates to the single literal key "[object Object]" (which the second, identical computed key then overwrites).

highsecuritypackages/app-store/_utils/oauth/parseRefreshTokenResponse.ts:5-11

Computed schema keys collapse to duplicate "[object Object]", stripping unvalidated token fields — The computed schema keys `[z.string().toString()]` and `[z.string().optional().toString()]` both evaluate to the literal string "[object Object]" (zod schemas don't override toString), and since they are duplicate keys the second silently overrides the first — so minimumTokenResponseSchema actually only requires `access_token: z.string()`. The intended validation ("any property with a number is the expiry") does not exist, and zod's default key-stripping drops every other field from the parsed token response, so unvalidated/partial token data flows into stored credentials in sharing mode.

highbugpackages/app-store/_utils/oauth/parseRefreshTokenResponse.ts:25-27

Fabricated "refresh_token" placeholder overwrites real stored refresh token — When the parsed data has no `refresh_token` (always the case in sharing mode, since the broken minimum schema strips it), this function injects the literal placeholder string `"refresh_token"` into the data, and callers persist it over the real stored token: zoomvideo (VideoApiAdapter.ts lines 120-122) writes `key.refresh_token = "refresh_token"` so the next refresh POSTs the literal and fails with invalid_grant (integration permanently broken until re-auth) and computes `expiry_date = NaN` from the undefined `expires_in`; office365calendar (CalendarService.ts line 264) spreads the placeholder over the real refresh token. Preserve the previously stored refresh_token instead of fabricating one.

mediumperformancepackages/app-store/salesforce/lib/CalendarService.ts:75-99

Constructor eagerly refreshes Salesforce token on every instantiation, discarding result — The constructor now triggers an unconditional POST to `login.salesforce.com/services/oauth2/token` plus a `prisma.credential.update` on every service instantiation, and `getCalendar` (packages/app-store/_utils/getCalendar.ts line 47) builds a new service per credential per operation with no caching — so every availability check and booking involving a Salesforce credential pays a blocking network roundtrip and a DB write even while the stored token is still valid. The fetched token is additionally never used: line 106 constructs the jsforce connection with the stale `credentialKey.access_token`, so jsforce still refreshes on demand and refresh traffic is doubled.

mediumbugapps/web/pages/api/webhook/app-credential.ts:62-90

Race in check-then-insert credential upsert allows duplicate credential rows — The upsert is a check-then-act sequence (`credential.findFirst` followed by `create`) with no transaction and no unique constraint on (userId, appId) — the code's own comment confirms no compound unique exists. Two concurrent webhook deliveries for the same userId+appSlug (retry storms and duplicate deliveries are normal for webhooks) both observe no existing credential and both insert, leaving duplicate credential rows that make the app appear installed twice and cause the same calendar/video integration to be loaded twice.

mediumsecurityapps/web/pages/api/webhook/app-credential.ts:24-29

Webhook secret compared with non-constant-time equality, leaking it via timing — The webhook secret is authenticated with a plain `!==` string comparison (req.headers[...] !== process.env.CALCOM_WEBHOOK_SECRET). String equality in V8 short-circuits at the first differing byte, so response timing leaks how many leading bytes of the shared secret an attacker guessed, allowing progressive recovery of the secret — and this secret gates an endpoint that writes attacker-supplied keys directly into any user's credential row.

mediumbugpackages/app-store/zoho-bigin/lib/CalendarService.ts:92-94

refreshOAuthTokens called with credentialId instead of owner userId — The third argument to `refreshOAuthTokens` is documented and used as the owner's `userId` (it is sent as `calcomUserId` to the sync endpoint), but this call site passes `credentialId` — which is `credential.id` (line 53), the credential row's id, not a user id. With credential sharing enabled the sync endpoint is invoked with the wrong identifier, so it either fails to find the user or syncs tokens onto the wrong user's credential.

Gold bugs found (5)

highparseRefreshTokenResponse writes the hardcoded string 'refresh_token' when the refresh response omits a refresh token, so the stored credential gets an invalid refresh token and later refreshes fail.
mediumminimumTokenResponseSchema uses computed keys from z.string().toString(), which produce a literal key rather than a wildcard, so the sync-mode schema does not validate or keep expiry and other token fields as intended.
highGoogle Calendar persists the safeParse result object instead of its data as the credential key, corrupting the stored credential so later reads fail.
mediumSalesforce getClient now refreshes the OAuth token and writes the credential on every service construction, adding a network round trip and DB write even when the access token is valid.
highThe app-credential webhook looks up appStoreMetadata by app.slug, but the map is keyed by dirName, so apps whose slug differs from their directory (e.g. google-calendar) always get a 404 and their credentials cannot be synced.

Gold bugs missed (4)

mediumThe webhook parses the body with zod .parse and decrypts/JSON-parses the keys without error handling, so invalid payloads produce 500 errors instead of 400 responses.
highThe new Salesforce token refresh uses prisma without importing it, so the code fails type checking and throws a ReferenceError at runtime.
highSalesforce checks response.statusText !== 'OK' instead of response.ok when refreshing the token, which can misclassify successful responses, and then ignores the refreshed token.
highAfter refreshing the Salesforce token, jsforce.Connection is created with the stale access_token and instance_url instead of the newly refreshed values.