Files
cal.diy/companion/services/oauthService.ts
T
88ce7868e8 feat: companion expo and chrome (#25022)
* feat: companion expo and chrome

* fix: api-v2-fetch-bookings (#25023)

* migrated to app expo router

* feat(companion): added availability screen and fix event type fetch (#25025)

* fix(companion): add host check in bookings (#25036)

* using liquid glass bottom nav experimental

* added action sheet

* added icons to event type tabs

* added action bar for event-type details

* long press for edit event types

* added limits

* added more limits

* added more limits

* added username to event types

* feat(companion): config to set and show all the available meeting options a user has stalled (#25081)

* feat: Add tailwind support using nativewind. (#25028)

* init nativewind

* replace styles with tailwind classes

* changes

* feat(companion): all locations options, icons, and apply nativewind to remaining files (#25143)

* feat: all locations options and icons and apply nativwind to reamaining files

* icon bug fix

* cal video icon

* other location frontend

* other location api

* address cubics comment about correctly detects SVGs

* feat(companion): edit availability (#25149)

* feat: companion-edit-availability

* date override and use correct config for patch api endpoint

* Android Alert supports a maximum of 3 buttons

* feat: companion-ui-release-1 (#25150)

* feat(companion): Add event type & schedule creation flows with API expansion (#25187)

* feat(companion): event schedule creation and apis

* profile section

* limits, advanced, recurring tab

* Clean Folder Structure

* addressed cubics comments

* fix cubiics comments

* replaced text with cal.com svg logo

* added correct more button for event-types

* added copy link button

* added extension popup

* added chrome extension sidebar

* achieved liquid glass buttons

* nit

* more progress

* fixed ios bug, added icon

* added cal icon to gmail

* nit

* nit

* added dialog for one-off meeting

* added one-time dialog

* feat(companion): gmail plugin (#25327)

* Update Cal.com Companion to version 1.7.0 with enhanced background and content scripts. The background script now handles fetching event types from the Cal.com API and improved error handling. The content script has been updated to manage sidebar visibility and respond to messages more effectively. Removed deprecated dev background script and updated manifest permissions for better functionality.

* chore: update companion .gitignore to exclude build outputs and env files

* feat: insert Cal.com event link directly at cursor position in Gmail compose

- Add insertTextAtCursor function to insert booking link where user is typing
- Automatically positions cursor after inserted link for seamless typing
- Fallback to clipboard copy if compose field not found
- Improved UX: no need to manually paste the link

* feat(companion): improve notification UI and add event types caching

- Update notification to Cal.com brand style (black bg, check icon, smooth fade)
- Change notification text to 'Link inserted' for subtlety
- Move notification to bottom-right position (matching Cal.com toasts)
- Add event types caching (5min duration) to reduce API calls
- Cache automatically refreshes on page reload
- Fix TypeScript error with composeBody.focus() type assertion

* Notification toast  border

* conditional description

* conditional description

* feat(companion): Enhance UI with action buttons, tooltips, and Gmail extension improvements (#25353)

* feat: companion-and-gmail-ui-upgrade

* feat: companion-and-gmail-ui-upgrade

* feat: companion-and-gmail-ui-upgrade

* feat: companion-and-gmail-ui-upgrade

* feat(companion): one-off links (#25355)

* added one off prototype

* resolve merge conflicts

---------

Co-authored-by: Dhairyashil <dhairyashil10101010@gmail.com>

* fixed sidebar iframe

* fix: enable pointer events on sidebar while maintaining click-through on transparent area

- Added pointerEvents: 'auto' to sidebar View component in _layout.tsx
- Changed iframe width from 100% to 400px to match sidebar width
- Changed iframe pointerEvents from 'none' to 'auto' to enable clicking
- This allows sidebar items to be clickable while transparent area remains click-through

* feat(companion): center all modals on full screen in browser extension (#25380)

* fix: companion-full-width-iframe

* center the popups on extension view

* feat(companion): center all modals on full screen in browser extension

- Created FullScreenModal component that expands iframe to full width
- Updated content script to handle instant iframe expansion/collapse
- Converted 17 modals across 6 files to use FullScreenModal
- All modals now appear centered on full browser viewport
- Removed animations for instant modal appearance
- Mobile app behavior remains unchanged

Files updated:
- companion/components/FullScreenModal.tsx (new)
- companion/extension/entrypoints/content.ts
- companion/app/(tabs)/event-types.tsx (5 modals)
- companion/app/(tabs)/bookings.tsx (2 modals)
- companion/app/(tabs)/availability.tsx (3 modals)
- companion/app/booking-detail.tsx (2 modals)
- companion/app/availability-detail.tsx (4 modals)
- companion/components/Header.tsx (1 modal)

* security(companion): validate postMessage origin in content script

Add origin and source validation to postMessage listener to prevent
malicious scripts on host pages from manipulating the companion iframe.

- Verify event.source matches iframe.contentWindow
- Verify event.origin matches iframe origin (localhost:8081)
- Reject all unauthorized messages before processing

This prevents external scripts from:
- Forcing full-screen overlays
- Intercepting pointer events
- Manipulating the companion UI

* fix(companion): center 'Add new event type' modal on full screen

Replace KeyboardAvoidingView with TouchableOpacity pattern in the
create event type modal to ensure it appears centered on the full
screen like all other modals.

This was the last remaining modal that wasn't properly centered.

* fix(companion): resolve modal transition timing issue

Fixed the 'Add new event type' modal not centering properly by:

- Added 100ms delay when transitioning between modals
- Prevents conflicting expand/collapse messages
- Removed redundant postMessage calls from modal handlers
- Added max-height constraint to modal content
- Cleaned up debug console logs

The issue was that when clicking 'New Event Type' from the 'New' menu,
both modals were transitioning simultaneously, causing the create modal
to collapse immediately. The delay ensures proper sequencing.

All 17 modals now work correctly and appear centered on full screen.

* added working date range

* removed all of one-off event code

* nit

* feat(companion): Suggest `Cal.com` links and Embed using Gemini Ai in Gmail (#25406)

Co-authored-by: Peer Richelsen <peeroke@gmail.com>

* add companion build on CI

* feat: oauth companion (#25526)

* first implemenation of oauth

* fix logout for web

* revert app name

* remove isUsingOAuth

* clean up log out button

* remove logs

* clean up authcontext

* simplify code generation

* code clean up

* clean up oauthService.ts

* oauth browser extension

* add redirect uri to .env.example

* remove api key support

* clean up _layout file

* add identity

* fix + clean up

* improvements to oauth flow

* code clean up

* remove comments

* clean up comments

* add log out dialog

* add confirm modal

---------

Co-authored-by: CarinaWolli <wollencarina@gmail.com>

---------

Co-authored-by: Dhairyashil Shinde <93669429+dhairyashiil@users.noreply.github.com>
Co-authored-by: Abhijeet Singh <asingh9829@gmail.com>
Co-authored-by: Dhairyashil <dhairyashil10101010@gmail.com>
Co-authored-by: Volnei Munhoz <volnei.munhoz@gmail.com>
Co-authored-by: Carina Wollendorfer <30310907+CarinaWolli@users.noreply.github.com>
Co-authored-by: CarinaWolli <wollencarina@gmail.com>
2025-12-03 08:46:04 -03:00

497 lines
16 KiB
TypeScript

/// <reference types="chrome" />
import * as AuthSession from "expo-auth-session";
import * as WebBrowser from "expo-web-browser";
import * as Crypto from "expo-crypto";
import { Platform } from "react-native";
import { fromByteArray } from "base64-js";
// Complete warm up for WebBrowser on mobile
WebBrowser.maybeCompleteAuthSession();
export interface OAuthTokens {
accessToken: string;
refreshToken?: string;
tokenType: string;
expiresAt?: number;
scope?: string;
}
export interface OAuthConfig {
clientId: string;
redirectUri: string;
calcomBaseUrl: string;
}
export class CalComOAuthService {
private config: OAuthConfig;
private codeVerifier: string | null = null;
private state: string | null = null;
constructor(config: OAuthConfig) {
this.config = config;
}
private async generatePKCEParams(): Promise<{
codeVerifier: string;
codeChallenge: string;
state: string;
}> {
const codeVerifier = this.generateRandomBase64Url();
const codeChallenge = await this.generateCodeChallenge(codeVerifier);
const state = this.generateRandomBase64Url();
this.codeVerifier = codeVerifier;
this.state = state;
return { codeVerifier, codeChallenge, state };
}
private async generateCodeChallenge(codeVerifier: string): Promise<string> {
try {
const base64Hash = await Crypto.digestStringAsync(
Crypto.CryptoDigestAlgorithm.SHA256,
codeVerifier,
{ encoding: Crypto.CryptoEncoding.BASE64 }
);
return base64Hash.replace(/\+/g, "-").replace(/\//g, "_").replace(/=/g, "");
} catch (error) {
console.error("Failed to generate code challenge:", error);
throw new Error("Failed to generate OAuth code challenge");
}
}
private generateRandomBase64Url(): string {
const bytes = new Uint8Array(Crypto.getRandomBytes(32));
const base64 =
typeof btoa !== "undefined" ? btoa(String.fromCharCode(...bytes)) : fromByteArray(bytes);
return base64.replace(/\+/g, "-").replace(/\//g, "_").replace(/=/g, "");
}
private buildAuthorizationUrl(codeChallenge: string, state: string): string {
const params = new URLSearchParams({
client_id: this.config.clientId,
response_type: "code",
redirect_uri: this.config.redirectUri,
state: state,
code_challenge: codeChallenge,
code_challenge_method: "S256",
});
return `${this.config.calcomBaseUrl}/auth/oauth2/authorize?${params.toString()}`;
}
async startAuthorizationFlow(): Promise<OAuthTokens> {
try {
const { codeChallenge, state } = await this.generatePKCEParams();
// Web only: check for stored callback with state-specific keys to prevent race conditions
if (Platform.OS === "web" && typeof window !== "undefined") {
const storedCode = window.localStorage.getItem(`oauth_callback_code_${state}`);
const storedState = window.localStorage.getItem(`oauth_callback_state_${state}`);
if (storedCode && storedState) {
// CSRF protection: verify state matches
if (storedState !== state) {
window.localStorage.removeItem(`oauth_callback_code_${state}`);
window.localStorage.removeItem(`oauth_callback_state_${state}`);
throw new Error("Invalid state parameter - possible CSRF attack");
}
window.localStorage.removeItem(`oauth_callback_code_${state}`);
window.localStorage.removeItem(`oauth_callback_state_${state}`);
return await this.exchangeCodeForTokens(storedCode, state);
}
}
// Note: State stored in background script (iframe may not have chrome.storage access)
const authResult = await this.getAuthorizationResult(codeChallenge, state);
if (authResult.type === "success") {
const code = authResult.params?.code || authResult.params?.authorizationCode;
const returnedState = authResult.params?.state;
if (returnedState !== state) {
throw new Error("Invalid state parameter - possible CSRF attack");
}
if (!code) {
throw new Error("No authorization code received");
}
return await this.exchangeCodeForTokens(code, state);
}
if (authResult.type === "error") {
const errorDescription =
authResult.params?.error_description ||
("error" in authResult ? authResult.error?.message : undefined) ||
"Unknown error";
throw new Error(`OAuth error: ${errorDescription}`);
}
if (authResult.type === "cancel") {
throw new Error("OAuth flow was cancelled by user");
}
throw new Error("OAuth flow failed or was dismissed");
} catch (error) {
console.error("OAuth authorization error:", error);
throw error;
}
}
// Detect browser extension environment using reliable indicators
private isBrowserExtension(): boolean {
if (Platform.OS !== "web" || typeof window === "undefined") {
return false;
}
if (typeof chrome !== "undefined" && chrome.runtime?.id) {
return true;
}
if (window.location.protocol === "chrome-extension:") {
return true;
}
// Extension content script injects companion app as iframe
if (window.parent !== window) {
try {
const parentOrigin = window.parent.location.origin;
const currentOrigin = window.location.origin;
if (parentOrigin !== currentOrigin && window.location.hostname === "localhost") {
return true;
}
} catch {
// Cross-origin access blocked - expected for extension iframes
if (window.location.hostname === "localhost") {
return true;
}
}
}
return false;
}
private async launchExtensionAuthFlow(authUrl: string): Promise<string> {
return new Promise((resolve, reject) => {
if (typeof chrome !== "undefined" && chrome.identity) {
chrome.identity.launchWebAuthFlow(
{
url: authUrl,
interactive: true,
},
(responseUrl) => {
if (chrome.runtime.lastError) {
reject(new Error(`OAuth flow failed: ${chrome.runtime.lastError.message}`));
} else if (responseUrl) {
resolve(responseUrl);
} else {
reject(new Error("OAuth flow cancelled or failed"));
}
}
);
return;
}
// Iframe: communicate with parent window
if (window.parent !== window) {
let timeoutId: NodeJS.Timeout | null = null;
const messageHandler = (event: MessageEvent) => {
// Security: only accept messages from parent
if (event.source !== window.parent) {
return;
}
if (event.data.type === "cal-extension-oauth-result") {
window.removeEventListener("message", messageHandler);
if (timeoutId) {
clearTimeout(timeoutId);
}
if (event.data.success) {
resolve(event.data.responseUrl);
} else {
console.error("OAuth flow failed:", event.data.error);
reject(new Error(event.data.error || "OAuth flow failed"));
}
}
};
window.addEventListener("message", messageHandler);
window.parent.postMessage(
{
type: "cal-extension-oauth-request",
authUrl: authUrl,
},
"*"
);
timeoutId = setTimeout(() => {
console.error("OAuth flow timeout - no response from extension");
window.removeEventListener("message", messageHandler);
reject(new Error("OAuth flow timeout - no response from extension"));
}, 30000);
} else {
reject(new Error("Chrome extension context not detected"));
}
});
}
private async getAuthorizationResult(
codeChallenge: string,
state: string
): Promise<AuthSession.AuthSessionResult | { type: string; params: Record<string, string> }> {
const authUrl = this.buildAuthorizationUrl(codeChallenge, state);
const isExtension = this.isBrowserExtension();
if (isExtension) {
try {
const responseUrl = await this.launchExtensionAuthFlow(authUrl);
const params = this.parseCallbackUrl(responseUrl);
return { type: "success" as const, params };
} catch (error) {
console.error("Extension OAuth flow failed:", error);
return { type: "error", params: { error: error.message } } as {
type: string;
params: Record<string, string>;
};
}
} else if (Platform.OS === "web") {
const discovery = await this.getDiscoveryEndpoints();
const request = new AuthSession.AuthRequest({
clientId: this.config.clientId,
redirectUri: this.config.redirectUri,
responseType: AuthSession.ResponseType.Code,
state: state,
codeChallenge: codeChallenge,
codeChallengeMethod: AuthSession.CodeChallengeMethod.S256,
});
return await request.promptAsync(discovery);
} else {
const result = await WebBrowser.openAuthSessionAsync(authUrl, this.config.redirectUri);
if (result.type === "success") {
const params = this.parseCallbackUrl(result.url);
return { type: "success" as const, params };
}
return { type: result.type, params: {} } as { type: string; params: Record<string, string> };
}
}
private async getDiscoveryEndpoints(): Promise<AuthSession.DiscoveryDocument> {
try {
const discovery = await AuthSession.fetchDiscoveryAsync(
`${this.config.calcomBaseUrl}/.well-known/openid_configuration`
);
return discovery;
} catch {
return {
authorizationEndpoint: `${this.config.calcomBaseUrl}/auth/oauth2/authorize`,
tokenEndpoint: `${this.config.calcomBaseUrl}/api/auth/oauth/token`,
} as AuthSession.DiscoveryDocument;
}
}
private parseCallbackUrl(url: string): Record<string, string> {
const urlObj = new URL(url);
const params: Record<string, string> = {};
urlObj.searchParams.forEach((value, key) => {
params[key] = value;
});
if (Object.keys(params).length === 0 && urlObj.hash) {
const hashParams = new URLSearchParams(urlObj.hash.substring(1));
hashParams.forEach((value, key) => {
params[key] = value;
});
}
return params;
}
private async exchangeCodeForTokens(code: string, state?: string): Promise<OAuthTokens> {
if (!this.codeVerifier) {
throw new Error("No code verifier available");
}
// Extension: use APIs to avoid CORS
if (this.isBrowserExtension() && window.parent !== window) {
return await this.exchangeTokensViaExtension(code, state);
}
const tokenEndpoint = `${this.config.calcomBaseUrl}/api/auth/oauth/token`;
const body = new URLSearchParams();
body.append("grant_type", "authorization_code");
body.append("client_id", this.config.clientId);
body.append("code", code);
body.append("redirect_uri", this.config.redirectUri);
body.append("code_verifier", this.codeVerifier);
const response = await fetch(tokenEndpoint, {
method: "POST",
headers: {
"Content-Type": "application/x-www-form-urlencoded",
Accept: "application/json",
},
body: body.toString(),
});
if (!response.ok) {
const errorData = await response.text();
console.error("Token exchange error response:", errorData);
try {
const errorJson = JSON.parse(errorData);
console.error("Parsed error:", errorJson);
} catch {
console.error("Could not parse error response as JSON");
}
throw new Error(`Token exchange failed: ${response.status} ${errorData}`);
}
const tokenData = await response.json();
const tokens: OAuthTokens = {
accessToken: tokenData.access_token,
refreshToken: tokenData.refresh_token,
tokenType: tokenData.token_type || "Bearer",
expiresAt: tokenData.expires_in ? Date.now() + tokenData.expires_in * 1000 : undefined,
scope: tokenData.scope,
};
return tokens;
}
private async exchangeTokensViaExtension(code: string, state?: string): Promise<OAuthTokens> {
return new Promise((resolve, reject) => {
let timeoutId: NodeJS.Timeout | null = null;
const messageHandler = (event: MessageEvent) => {
// Security: only accept messages from parent
if (event.source !== window.parent) {
return;
}
if (event.data.type === "cal-extension-token-exchange-result") {
window.removeEventListener("message", messageHandler);
if (timeoutId) {
clearTimeout(timeoutId);
}
if (event.data.success) {
resolve(event.data.tokens);
} else {
console.error("Token exchange failed via extension:", event.data.error);
reject(new Error(event.data.error || "Token exchange failed"));
}
}
};
window.addEventListener("message", messageHandler);
window.parent.postMessage(
{
type: "cal-extension-token-exchange-request",
tokenRequest: {
grant_type: "authorization_code",
client_id: this.config.clientId,
code: code,
redirect_uri: this.config.redirectUri,
code_verifier: this.codeVerifier,
},
state: state, // CSRF validation in background script
tokenEndpoint: `${this.config.calcomBaseUrl}/api/auth/oauth/token`,
},
"*"
);
timeoutId = setTimeout(() => {
window.removeEventListener("message", messageHandler);
reject(new Error("Token exchange timeout"));
}, 30000);
});
}
async refreshAccessToken(refreshToken: string): Promise<OAuthTokens> {
const tokenEndpoint = `${this.config.calcomBaseUrl}/api/auth/oauth/refreshToken`;
const body = new URLSearchParams({
grant_type: "refresh_token",
client_id: this.config.clientId,
refresh_token: refreshToken,
});
const response = await fetch(tokenEndpoint, {
method: "POST",
headers: {
"Content-Type": "application/x-www-form-urlencoded",
Accept: "application/json",
},
body: body.toString(),
});
if (!response.ok) {
const errorData = await response.text();
throw new Error(`Token refresh failed: ${response.status} ${errorData}`);
}
const tokenData = await response.json();
const tokens: OAuthTokens = {
accessToken: tokenData.access_token,
refreshToken: tokenData.refresh_token || refreshToken,
tokenType: tokenData.token_type || "Bearer",
expiresAt: tokenData.expires_in ? Date.now() + tokenData.expires_in * 1000 : undefined,
scope: tokenData.scope,
};
return tokens;
}
isTokenExpired(tokens: OAuthTokens): boolean {
if (!tokens.expiresAt) {
return false;
}
// 5-minute buffer before expiry
return Date.now() >= tokens.expiresAt - 5 * 60 * 1000;
}
clearPKCEParams(): void {
this.codeVerifier = null;
this.state = null;
}
}
export function createCalComOAuthService(overrides: Partial<OAuthConfig> = {}): CalComOAuthService {
let defaultRedirectUri: string;
const defaultConfig: OAuthConfig = {
clientId: process.env.EXPO_PUBLIC_CALCOM_OAUTH_CLIENT_ID || "",
redirectUri: process.env.EXPO_PUBLIC_CALCOM_OAUTH_REDIRECT_URI,
calcomBaseUrl: "https://app.cal.com",
...overrides,
};
if (!defaultConfig.clientId) {
throw new Error(
"OAuth client ID is required. Set EXPO_PUBLIC_CALCOM_OAUTH_CLIENT_ID environment variable."
);
}
return new CalComOAuthService(defaultConfig);
}