Files
calendar/packages/features/oauth/services/OAuthService.ts
T
+1
Peer RichelsenGitHublauris@cal.com <lauris@cal.com>Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>eunjae@cal.com <hey@eunjae.dev>Lauris Skraucissupalarrycubic-dev-ai[bot] <1082092+cubic-dev-ai[bot]@users.noreply.github.com>CarinaWollilauris@cal.com <lauris@cal.com>Morgan
a03722fd7f feat: add OAuth client developer settings page with approval workflow (#25556)
* feat: add OAuth client developer settings page with approval workflow

- Add new developer OAuth page at /settings/developer/oAuth for users to submit OAuth client requests
- Transform admin OAuth page into management dashboard for reviewing/approving submissions
- Add OAuthClientApprovalStatus enum (PENDING, APPROVED, REJECTED) to track submission status
- Add userId and createdAt fields to OAuthClient model for tracking submissions
- Create email notifications for admin (new submission) and user (approval)
- Add sidebar navigation link in developer section below API keys
- Add comprehensive translations for new UI strings
- Create OAuthClientRepository for data access following repository pattern

Co-Authored-By: peer@cal.com <peer@cal.com>

* fix: re-export generateSecret for backward compatibility

Co-Authored-By: peer@cal.com <peer@cal.com>

* feat: make logo mandatory and list items clickable for OAuth clients

Co-Authored-By: peer@cal.com <peer@cal.com>

* fix: add missing translation keys and remove client secret from details dialog

Co-Authored-By: peer@cal.com <peer@cal.com>

* fix: address cubic AI reviewer comments

- Remove duplicate 'there' JSON key in common.json
- Add select clause to findByUserId to avoid exposing clientSecret
- Add @@index([userId]) to OAuthClient model for query performance
- Update migration to include the index

Co-Authored-By: peer@cal.com <peer@cal.com>

* fix: address PR review comments - fix indentation and use useCopy hook

Co-Authored-By: eunjae@cal.com <hey@eunjae.dev>

* fix: change react-dom/server import to fix Turbopack compatibility

Co-Authored-By: eunjae@cal.com <hey@eunjae.dev>

* Revert "fix: change react-dom/server import to fix Turbopack compatibility"

This reverts commit c3e0b709c2d88fd221143cb4ce9cd25bb8c94277.

* fix: use email service pattern for OAuth client notifications

Co-Authored-By: eunjae@cal.com <hey@eunjae.dev>

* fix: add try-catch around email sending to handle Turbopack react-dom/server issue

Co-Authored-By: eunjae@cal.com <hey@eunjae.dev>

* Revert "fix: add try-catch around email sending to handle Turbopack react-dom/server issue"

This reverts commit fc9d47cd773505ebc5ee2696718aad4a8a98be77.

* fix: improve OAuth client UI with skeleton loaders and smaller dialog styling

- Replace 'Loading...' text with proper skeleton loaders in both developer and admin OAuth client views
- Make client_id and copy button smaller in dialogs using size='sm' and text-sm styling
- Add 'client_id' translation key to common.json for proper i18n

Co-Authored-By: eunjae@cal.com <hey@eunjae.dev>

* fix: improve skeleton loader to match actual OAuth client list structure

- Remove divide-y from container and use conditional border-b on rows
- Match the exact structure from oauth-clients-view.tsx L126-160
- Use proper spacing for text elements (mt-1 instead of space-y-2)

Co-Authored-By: eunjae@cal.com <hey@eunjae.dev>

* fix skeleton

* rename the selected oauth client dialog

* fix: address PR feedback - admin auth, dropdown styling, sidebar label

- Add defense-in-depth admin authorization check in updateClientStatus handler
- Fix broken dropdown menu by using DropdownItem with StartIcon prop
- Fix sidebar menu label from 'oAuth' to 'oauth_clients' to match developer view

Co-Authored-By: eunjae@cal.com <hey@eunjae.dev>

* update common.json

* feat: show client secret in approval email for confidential OAuth clients

- Add regenerateSecret method to OAuthClientRepository
- Regenerate secret when admin approves a PENDING confidential client
- Include client secret in approval notification email
- Add one-time warning message about storing the secret securely
- Only regenerate on first approval (not re-approvals)

Co-Authored-By: eunjae@cal.com <hey@eunjae.dev>

* feat: add Website URL field, fix logo styling, show client secret after approval

- Add Website URL field to OAuth client forms (admin and developer views)
- Fix Upload Logo section styling by wrapping in Label div with proper gap
- Display client secret in dialog after admin approves a confidential OAuth client
- Add websiteUrl field to Prisma schema with migration
- Update tRPC handlers and repository to support websiteUrl
- Add translation keys for new UI elements

Co-Authored-By: peer@cal.com <peer@cal.com>

* fix: move clientSecret variable declaration outside if block for proper scoping

Co-Authored-By: peer@cal.com <peer@cal.com>

* refactor: dont expose client secret in emails

* refactor: dont regenerate secret upon status change

* refactor: reuse existing hash function

* refactor: rename admin/oAuth to admin/oauth page

* refactor: deduplicate oauth repositories

* refactor: remove withGlobalPrisma from oauth repository

* refactor: developer oauth page

* refactor: oauth status by default accepted

* refactor: request oauth status when creating

* refactor ux

* fix: address Cubic AI code review feedback

- Add purpose field to plain text email body for accessibility
- Convert NewOAuthClientButton to inline JSX to avoid React anti-pattern
- Trigger re-approval when redirectUri changes for security
- Add e.preventDefault() for Space key to prevent page scroll
- Change default approvalStatus to PENDING for defense-in-depth
- Use oauth_clients translation key for consistency
- Add meaningful alt text to Avatar for accessibility
- Remove onClick from DialogClose to prevent double-run close effects
- Return NOT_FOUND for non-owner delete to prevent resource enumeration

Co-Authored-By: unknown <>

* common.json file

* refactor: delete all prisma migrations

* refactor: have just 1 prisma migration

* revert: some devin changes

* fix: typecheck

* test: owner OAuth crud

* test: admin OAuth approval / rejection

* fix: address Cubic AI review feedback (confidence 9/10 issues)

- schema.prisma: Remove @default("") from purpose field to make it required
- schema.prisma: Use UTC-aware timezone expression for createdAt default
- OAuthClientFormFields.tsx: Localize redirect URI placeholder using t()
- common.json: Add redirect_uri_placeholder translation key

Co-Authored-By: unknown <>

* cubic changes

* refactor: dont log sensitive info and rethrow error

* cubic feedback

* refactor: make oauth client purpose optional

* refactor: admin/oauth not allowed if not logged in

* refactor: admin view skeleton

* refactor: rename state

* refactor: get rid of redundant mapping

* refactor: remove redundant handler

* refactor: remove redundant handler

* refactor: re-usable new oauth client button

* refactor: dialogs

* refactor: modals

* refactor: handler names, dialog, skeleton

* fix: purpose being null

* refactor: rename handler and delete old oauth admin page

* fix: purpose in submission

* refactor: handler names

* refactor: rename

* refactor: update handler

* refactor: rename approvalStatus -> status

* refactor: simplify modal

* refactor: name

* dont require repproval if redirectUri changes

* fix: remove integration sync index creation

* refactor: require re-approval if redirectUri updated

* fix: flaky e2e test

* fix: flaky e2e test

* fix: flaky e2e test

* fix: remove duplicate common.json keys

* refactor: replace team@cal.com with SUPPORT_MAIL_ADDRESS

* refactor: generate client secret on handler level

* fix: authorization code only available to approved clients

* refactor: cubic review dont display exclamation

* refactor: cubic review website_url in common json

* fix: dont default in ui to approved status

* refactor: optiona logo in schema create handler

* fix: tests

* fix: tests

* fix: /authorize redirect if client not approved or show error

* test: authorize page with invalid client id

* refactor: dont allow refreshing tokens unless approved client

* fix: flaky e2e test

* fix: flaky e2e test

* fix: flaky e2e test

* fix: flaky e2e test

* fix: flaky e2e test

* fix: flaky e2e test

* chore: warn that pending client is not usable

* fix: approve and reject buttons

* fix: /authorize show error if client not approved

* refactor: info message about editing oauth client and status

* change info alert to warning

* try to fix ci test

* debug: failing e2e test

* fix: improve session propagation in oauth-client-admin E2E test

- Add navigateToAdminOAuthPage helper that waits for listClients API call
- If the API call doesn't arrive (session issue), reload page to force session refresh
- This fixes the CI flakiness where admin page wasn't loading due to session not having ADMIN role

Co-Authored-By: lauris@cal.com <lauris@cal.com>

* fix: register waitForResponse before navigating in E2E test

- Register the listClients waitForResponse promise BEFORE page.goto()
- This ensures the response isn't missed during page load
- Also register the promise before reload in the catch block

Co-Authored-By: lauris@cal.com <lauris@cal.com>

* fix: rename oAuth folder to oauth for case-sensitive filesystems

The admin OAuth page route was at /settings/admin/oAuth (capital A) but the
code references /settings/admin/oauth (lowercase). This caused 404 errors
on case-sensitive filesystems (Linux).

Also improved the E2E test navigation helper to retry with delays if the
admin page doesn't load immediately, handling session propagation timing.

Co-Authored-By: lauris@cal.com <lauris@cal.com>

* test style

---------

Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
Co-authored-by: eunjae@cal.com <hey@eunjae.dev>
Co-authored-by: Lauris Skraucis <lauris.skraucis@gmail.com>
Co-authored-by: supalarry <laurisskraucis@gmail.com>
Co-authored-by: cubic-dev-ai[bot] <1082092+cubic-dev-ai[bot]@users.noreply.github.com>
Co-authored-by: CarinaWolli <wollencarina@gmail.com>
Co-authored-by: lauris@cal.com <lauris@cal.com>
Co-authored-by: Morgan <33722304+ThyMinimalDev@users.noreply.github.com>
2026-01-21 12:23:51 -03:00

490 lines
15 KiB
TypeScript

import { randomBytes } from "node:crypto";
import jwt from "jsonwebtoken";
import { TeamRepository } from "@calcom/features/ee/teams/repositories/TeamRepository";
import { AccessCodeRepository } from "@calcom/features/oauth/repositories/AccessCodeRepository";
import { OAuthClientRepository } from "@calcom/features/oauth/repositories/OAuthClientRepository";
import { generateSecret } from "@calcom/features/oauth/utils/generateSecret";
import { ErrorCode } from "@calcom/lib/errorCodes";
import { ErrorWithCode } from "@calcom/lib/errors";
import { verifyCodeChallenge } from "@calcom/lib/pkce";
import { OAuthClientStatus } from "@calcom/prisma/enums";
import type { AccessScope, OAuthClientType } from "@calcom/prisma/enums";
export interface OAuth2Client {
clientId: string;
redirectUri: string;
name: string;
logo: string | null;
isTrusted: boolean;
clientType: OAuthClientType;
}
export interface OAuth2Tokens {
accessToken: string;
tokenType: string;
refreshToken: string;
expiresIn: number;
}
export interface AuthorizeResult {
redirectUrl: string;
authorizationCode: string;
client: OAuth2Client;
}
export interface OAuthError {
error: string;
errorDescription?: string;
}
interface DecodedRefreshToken {
userId?: number | null;
teamId?: number | null;
scope: AccessScope[];
token_type: string;
clientId: string;
codeChallenge?: string | null;
codeChallengeMethod?: string | null;
}
export class OAuthService {
private readonly accessCodeRepository: AccessCodeRepository;
private readonly teamsRepository: TeamRepository;
private readonly oAuthClientRepository: OAuthClientRepository;
constructor(
private readonly deps: {
oAuthClientRepository: OAuthClientRepository;
accessCodeRepository: AccessCodeRepository;
teamsRepository: TeamRepository;
}
) {
this.accessCodeRepository = deps.accessCodeRepository;
this.teamsRepository = deps.teamsRepository;
this.oAuthClientRepository = deps.oAuthClientRepository;
}
async getClient(clientId: string): Promise<OAuth2Client> {
const client = await this.oAuthClientRepository.findByClientId(clientId);
if (!client) {
throw new ErrorWithCode(ErrorCode.NotFound, "unauthorized_client", { reason: "client_not_found" });
}
return {
clientId: client.clientId,
redirectUri: client.redirectUri,
name: client.name,
logo: client.logo,
isTrusted: client.isTrusted,
clientType: client.clientType,
};
}
async getClientForAuthorization(clientId: string, redirectUri: string): Promise<OAuth2Client> {
const client = await this.oAuthClientRepository.findByClientId(clientId);
if (!client) {
throw new ErrorWithCode(ErrorCode.NotFound, "unauthorized_client", { reason: "client_not_found" });
}
this.validateRedirectUri(client.redirectUri, redirectUri);
this.ensureClientIsApproved(client);
return {
clientId: client.clientId,
redirectUri: client.redirectUri,
name: client.name,
logo: client.logo,
isTrusted: client.isTrusted,
clientType: client.clientType,
};
}
async generateAuthorizationCode(
clientId: string,
userId: number,
redirectUri: string,
scopes: AccessScope[],
state?: string,
teamSlug?: string,
codeChallenge?: string,
codeChallengeMethod?: string
): Promise<AuthorizeResult> {
const client = await this.oAuthClientRepository.findByClientId(clientId);
if (!client) {
throw new ErrorWithCode(ErrorCode.Unauthorized, "unauthorized_client", { reason: "client_not_found" });
}
this.ensureClientIsApproved(client);
// RFC 6749 4.1.2.1: Redirect URI mismatch on Auth step is 'invalid_request'
this.validateRedirectUri(client.redirectUri, redirectUri);
if (client.clientType === "PUBLIC") {
if (!codeChallenge) {
throw new ErrorWithCode(ErrorCode.BadRequest, "invalid_request", { reason: "pkce_required" });
}
if (!codeChallengeMethod || codeChallengeMethod !== "S256") {
throw new ErrorWithCode(ErrorCode.BadRequest, "invalid_request", {
reason: "invalid_code_challenge_method",
});
}
} else if (client.clientType === "CONFIDENTIAL") {
if (codeChallenge && (!codeChallengeMethod || codeChallengeMethod !== "S256")) {
throw new ErrorWithCode(ErrorCode.BadRequest, "invalid_request", {
reason: "invalid_code_challenge_method",
});
}
}
let teamId: number | undefined;
if (teamSlug) {
const team = await this.teamsRepository.findTeamBySlugWithAdminRole(teamSlug, userId);
if (!team) {
// Specific OAuth error for user denying or failing permission
throw new ErrorWithCode(ErrorCode.Unauthorized, "access_denied", {
reason: "team_not_found_or_no_access",
});
}
teamId = team.id;
}
const authorizationCode = this.generateAuthorizationCodeString();
await this.accessCodeRepository.create({
code: authorizationCode,
clientId,
userId: teamSlug ? undefined : userId,
teamId,
scopes,
codeChallenge,
codeChallengeMethod,
});
const redirectUrl = this.buildRedirectUrl(redirectUri, {
code: authorizationCode,
state,
});
return { redirectUrl, authorizationCode, client };
}
private ensureClientIsApproved(client: { status: OAuthClientStatus }): void {
if (client.status !== OAuthClientStatus.APPROVED) {
throw new ErrorWithCode(ErrorCode.Unauthorized, "unauthorized_client", { reason: "client_not_approved" });
}
}
private validateRedirectUri(registeredUri: string, providedUri: string): void {
if (providedUri !== registeredUri) {
throw new ErrorWithCode(ErrorCode.BadRequest, "invalid_request", { reason: "redirect_uri_mismatch" });
}
}
buildRedirectUrl(baseUrl: string, params: Record<string, string | undefined>): string {
const url = new URL(baseUrl);
for (const [key, value] of Object.entries(params)) {
if (value !== undefined) {
url.searchParams.set(key, value);
}
}
return url.toString();
}
buildErrorRedirectUrl(redirectUri: string, error: unknown, state?: string): string {
const oauthError = this.mapErrorToOAuthError(error);
return this.buildRedirectUrl(redirectUri, {
error: oauthError.error,
error_description: oauthError.errorDescription,
state,
});
}
private mapErrorToOAuthError(error: unknown): OAuthError {
const validOAuthErrors = [
"invalid_request",
"unauthorized_client",
"access_denied",
"unsupported_response_type",
"invalid_scope",
"server_error",
"temporarily_unavailable",
"invalid_client",
"invalid_grant",
];
if (error instanceof ErrorWithCode) {
if (validOAuthErrors.includes(error.message)) {
return {
error: error.message,
errorDescription: (error.data?.cause as string | undefined) ?? error.message,
};
}
switch (error.code) {
case ErrorCode.BadRequest:
return {
error: "invalid_request",
errorDescription: (error.data?.cause as string | undefined) ?? error.message,
};
case ErrorCode.Unauthorized:
return {
error: "unauthorized_client",
errorDescription: (error.data?.cause as string | undefined) ?? error.message,
};
default:
return {
error: "server_error",
errorDescription: (error.data?.cause as string | undefined) ?? error.message,
};
}
}
return {
error: "server_error",
errorDescription: "An unexpected error occurred",
};
}
async exchangeCodeForTokens(
clientId: string,
code: string,
clientSecret?: string,
redirectUri?: string,
codeVerifier?: string
): Promise<OAuth2Tokens> {
const client = await this.oAuthClientRepository.findByClientIdWithSecret(clientId);
if (!client) {
throw new ErrorWithCode(ErrorCode.Unauthorized, "invalid_client", { reason: "client_not_found" });
}
// RFC 6749 5.2: Redirect URI mismatch during Token exchange is 'invalid_grant'
if (redirectUri && client.redirectUri !== redirectUri) {
throw new ErrorWithCode(ErrorCode.BadRequest, "invalid_grant", { reason: "redirect_uri_mismatch" });
}
if (!this.validateClient(client, clientSecret)) {
throw new ErrorWithCode(ErrorCode.Unauthorized, "invalid_client", {
reason: "invalid_client_credentials",
});
}
const accessCode = await this.accessCodeRepository.findValidCode(code, clientId);
await this.accessCodeRepository.deleteExpiredAndUsedCodes(code, clientId);
if (!accessCode) {
throw new ErrorWithCode(ErrorCode.BadRequest, "invalid_grant", { reason: "code_invalid_or_expired" });
}
const pkceError = this.verifyPKCE(client, accessCode, codeVerifier);
if (pkceError) {
// RFC 7636 4.4.1: If verification fails, return 'invalid_grant'
throw new ErrorWithCode(ErrorCode.BadRequest, pkceError.error, { reason: pkceError.reason });
}
const tokens = this.createTokens({
clientId,
userId: accessCode.userId,
teamId: accessCode.teamId,
scopes: accessCode.scopes,
codeChallenge: accessCode.codeChallenge,
codeChallengeMethod: accessCode.codeChallengeMethod,
});
return tokens;
}
async refreshAccessToken(
clientId: string,
refreshToken: string,
clientSecret?: string
): Promise<OAuth2Tokens> {
const client = await this.oAuthClientRepository.findByClientIdWithSecret(clientId);
if (!client) {
throw new ErrorWithCode(ErrorCode.Unauthorized, "invalid_client", { reason: "client_not_found" });
}
if (!this.validateClient(client, clientSecret)) {
throw new ErrorWithCode(ErrorCode.Unauthorized, "invalid_client", {
reason: "invalid_client_credentials",
});
}
this.ensureClientIsApproved(client);
const decodedToken = this.verifyRefreshToken(refreshToken);
if (!decodedToken || decodedToken.token_type !== "Refresh Token") {
throw new ErrorWithCode(ErrorCode.BadRequest, "invalid_grant", { reason: "invalid_refresh_token" });
}
if (decodedToken.clientId !== clientId) {
throw new ErrorWithCode(ErrorCode.BadRequest, "invalid_grant", { reason: "client_id_mismatch" });
}
const tokens = this.createTokens({
clientId,
userId: decodedToken.userId,
teamId: decodedToken.teamId,
scopes: decodedToken.scope,
});
return tokens;
}
private validateClient(
client: { clientType: string; clientSecret?: string | null },
clientSecret?: string
): boolean {
if (client.clientType === "CONFIDENTIAL") {
if (!clientSecret) return false;
const [hashedSecret] = generateSecret(clientSecret);
if (client.clientSecret !== hashedSecret) return false;
}
return true;
}
private verifyPKCE(
client: { clientType: string },
source: { codeChallenge?: string | null; codeChallengeMethod?: string | null },
codeVerifier?: string
): {
error: "invalid_request" | "invalid_grant";
reason: "pkce_missing_parameters_or_invalid_method" | "pkce_verification_failed";
} | null {
const shouldEnforcePKCE =
client.clientType === "PUBLIC" || (client.clientType === "CONFIDENTIAL" && source.codeChallenge);
if (!shouldEnforcePKCE) return null;
const method = source.codeChallengeMethod || "S256";
// Structural missing params
if (!source.codeChallenge || !codeVerifier || method !== "S256") {
return { error: "invalid_request", reason: "pkce_missing_parameters_or_invalid_method" };
}
// Logical mismatch
if (!verifyCodeChallenge(codeVerifier, source.codeChallenge, method)) {
return { error: "invalid_grant", reason: "pkce_verification_failed" };
}
return null;
}
private generateAuthorizationCodeString(): string {
const randomBytesValue = randomBytes(40);
return randomBytesValue.toString("base64").replace(/=/g, "").replace(/\+/g, "-").replace(/\//g, "_");
}
private createTokens(input: {
clientId: string;
userId?: number | null;
teamId?: number | null;
scopes: AccessScope[];
codeChallenge?: string | null;
codeChallengeMethod?: string | null;
}): OAuth2Tokens {
const secretKey = process.env.CALENDSO_ENCRYPTION_KEY;
if (!secretKey) {
throw new ErrorWithCode(ErrorCode.InternalServerError, "server_error", {
reason: "encryption_key_missing",
});
}
const accessTokenPayload = {
userId: input.userId,
teamId: input.teamId,
scope: input.scopes,
token_type: "Access Token",
clientId: input.clientId,
};
const refreshTokenPayload = {
userId: input.userId,
teamId: input.teamId,
scope: input.scopes,
token_type: "Refresh Token",
clientId: input.clientId,
...(input.codeChallenge && {
codeChallenge: input.codeChallenge,
codeChallengeMethod: input.codeChallengeMethod,
}),
};
const accessTokenExpiresIn = 1800; // 30 minutes
const accessToken = jwt.sign(accessTokenPayload, secretKey, {
expiresIn: accessTokenExpiresIn,
});
const refreshToken = jwt.sign(refreshTokenPayload, secretKey, {
expiresIn: 30 * 24 * 60 * 60, // 30 days
});
return {
accessToken,
tokenType: "bearer",
refreshToken,
expiresIn: accessTokenExpiresIn,
};
}
private verifyRefreshToken(refreshToken: string): DecodedRefreshToken | null {
const secretKey = process.env.CALENDSO_ENCRYPTION_KEY;
if (!secretKey) {
throw new ErrorWithCode(ErrorCode.InternalServerError, "server_error", {
reason: "encryption_key_missing",
});
}
try {
const decoded = jwt.verify(refreshToken, secretKey) as DecodedRefreshToken;
return decoded;
} catch {
return null;
}
}
}
export type OAuthErrorReason =
| "client_not_found"
| "client_not_approved"
| "redirect_uri_mismatch"
| "pkce_required"
| "invalid_code_challenge_method"
| "team_not_found_or_no_access"
| "access_denied"
| "invalid_client_credentials"
| "code_invalid_or_expired"
| "pkce_missing_parameters_or_invalid_method"
| "pkce_verification_failed"
| "invalid_refresh_token"
| "client_id_mismatch"
| "encryption_key_missing";
// Mapping of OAuth error reasons to descriptive messages, keeping previous messages for compatibility
export const OAUTH_ERROR_REASONS: Record<OAuthErrorReason, string> = {
client_not_found: "OAuth client with ID not found",
client_not_approved: "OAuth client is not approved",
redirect_uri_mismatch: "redirect_uri does not match OAuth client's redirect URI",
pkce_required: "code_challenge required for public clients",
invalid_code_challenge_method: "code_challenge_method must be S256",
team_not_found_or_no_access: "Team not found or user is not an admin/owner",
access_denied: "The resource owner or authorization server denied the request.",
invalid_client_credentials: "invalid_client",
code_invalid_or_expired: "invalid_grant",
pkce_missing_parameters_or_invalid_method: "invalid_request",
pkce_verification_failed: "invalid_grant",
invalid_refresh_token: "invalid_grant",
client_id_mismatch: "invalid_grant",
encryption_key_missing: "CALENDSO_ENCRYPTION_KEY is not set",
};