* chore: Upgrade prisma to 6.7.0 * Build fixes * type fixes Signed-off-by: Omar López <zomars@me.com> * Update schema.prisma * Patching * Revert "Update schema.prisma" This reverts commit 47d8618bf89ef4d007b30084df766f17281e21a1. * Revert "Patching" This reverts commit a1d2e3040e71690a44d4324db95d73b4d68c6adb. * Revert schema changes Signed-off-by: Omar López <zomars@me.com> * WIP Signed-off-by: Omar López <zomars@me.com> * Update getPublicEvent.ts * Update imports Signed-off-by: Omar López <zomars@me.com> * Update gitignore Signed-off-by: Omar López <zomars@me.com> * update remaining imports Signed-off-by: Omar López <zomars@me.com> * Delete .cursor/config.json * Discard changes to packages/features/eventtypes/lib/getPublicEvent.ts * Update _get.ts * Update user.ts * Update .gitignore * update * Update WorkflowStepContainer.tsx * Update next-auth-custom-adapter.ts * Update getPublicEvent.ts * Update workflow.ts * Update next-auth-custom-adapter.ts * Update next-auth-options.ts * Update bookingScenario.ts * fix missing imports * upgrades prismock Signed-off-by: Omar López <zomars@me.com> * patches prismock Signed-off-by: Omar López <zomars@me.com> * Update reschedule.test.ts * Update prisma.ts * patch prismock Signed-off-by: Omar López <zomars@me.com> * fix enums imports Signed-off-by: Omar López <zomars@me.com> * Revert "Update prisma.ts" This reverts commit 64edcf8db54171ff4456c209d563b5d431d99619. * Revert "patch prismock" This reverts commit e95819113dc9d88e7130947aa120cd42710977c8. * fix patch * Fix test that overrun the boundary, it shouldn't test too much * Move prisma import to changeSMSLockState * Bring back broken test without illegal imports * Merge with main and fix filter hosts by same round robin host * Fixed buildDryRunBooking fn tests * Fix and move ooo create or update handler test * Fix packages/features/eventtypes/lib/isCurrentlyAvailable.test.ts * Fix packages/trpc/server/routers/viewer/organizations/listMembers.handler.test.ts * Mock @calcom/prisma * Fix: verify-email.test.ts * fix: Moved WebhookService test and fixed default import mock * Fix: Added missing prisma mock, handleNewBooking uses that of course * We're not testing createContext here * fix: Prisma mock fix for listMembers.test.ts * More fixes to broken testcases * Forgot to remove borked test * Prevent the need to mock a lot of dependencies by moving out buildBaseWhereCondition to its own file * Temporarily skip getCalendarEvents, needs a rewrite * Fix: turns out you can access protected in testcases * fix further mocks * Added packages/features/insights/server/buildBaseWhereCondition.ts, types * Always great to have a mock and then not use it * And one less again. * fix: confirm.handler.test, didn't mock prisma * fix: Address minor nit by @eunjae & fix ImpersonationProvider test * Updated isPrismaAvailableCheck that doesn't crash on import * fix: Get Prisma directly from the client, it usually involves the Validator and does not need 'local' inclusion * Add zod-prisma-types without the generator enabled (commented out) * Uncomment and see what happens * Change method of import as imports did not work in Input Schemas * Remove custom 'zod' booking model, it does not belong with Prisma * Fix all other global Model imports * Rewrite most schema includes AND remove barrel file * Add bookingCreateBodySchema to features/bookings * Flurry of type fixes for compatibility with new zod gen * Refactor out the custom prisma type createEventTypeInput * Work around nullable eventTypeLocations * HandlePayment type fix * More fixes, final fix remaining is CompleteEventType * Should fix a bunch more booking related type errors * Missed one * Some props missing from BookingCreateBodySchema * Fix location type in handleChildrenEventTypes * Little bit hacky imo but it works * Final type error \o/ * Forgot to include Prisma * Do not include zod-utils in booker/types * Oops, was already including Booker/types * Fix membership type, also disallow updating createdAt/updatedAt, make part of patch/post * Fix api v1 type errors * Fix EventTypeDescription typings * Remove getParserWithGeneric, use userBodySchema with UserSchema * use centralized timeZoneSchema * Implement feedback by @zomars * Couple of WIP pushes * Fix tests * Type fixes in `handleChildrenEventTypes` test * Try and parse metadata before use * Change zod-prisma-types configuration for optimal performance * Fix prisma validator error in `prisma/selects/credential` * Disable seperate relations model, hits a bug * Import absolute - this makes rollup work in @platform/libraries * Attempt at removing resolutions override * Refactor using `Prisma.validator` to `satisfies` * Build atoms using @calcom/prisma/client * Build atoms using @calcom/prisma/client * fixes * Update eventTypeSelect.ts * Adjust `eventTypeMetaDataSchemaWithUntypedApps` from `unknown` to `record(any)` * `EventTypeDescription` rely on `descriptionAsSafeHTML` instead of `description` * Add `seatsPerTimeSlot` to event type public select * Fix typing in `users-public-view` getServerSide props * Add missing `schedulingType` to prop * chore: bump platform libraries * Function return type is illegal, not sure how this passed eslint (#21567) * Merged with main * Update updateTokenObject.ts * Update handleResponse.ts * Update index.ts * Update handleChildrenEventTypes.ts * Update booking-idempotency-key.ts * Update WebhookService.test.ts * Update events.test.ts * Update queued-response.test.ts * Update events.test.ts * Update getRoutedUrl.test.ts * fix: type checks Signed-off-by: Omar López <zomars@me.com> * fixes Signed-off-by: Omar López <zomars@me.com> * chore: bump platform libraries * Update yarn.lock * more fixes Signed-off-by: Omar López <zomars@me.com> * fixes Signed-off-by: Omar López <zomars@me.com> * biuld fixes * chore: bump platform libraries * Update conferencing.repository.ts * Update conferencing.repository.ts * Update getCalendarsEvents.test.ts * Update vite.config.js * chore: bump platform libraries * Update users.ts * Discard changes to docs/api-reference/v2/openapi.json * Update vite.config.ts * updated platform libraries * Update get.handler.test.ts * Update get.handler.test.ts * Update schema.prisma * Discard changes to docs/api-reference/v2/openapi.json * Update next-auth-custom-adapter.ts * Update team.ts * Flurry of type fixes * Fix majority of insight related type errors * Type fixes for unlink of account * Make user nullable again * Fixed a bunch of unit tests and one type error * Attempted mock fix * Attempted fix for Attribute type * Ensure default import becomes prisma, but not direct usage * Import default as prisma in prisma.module * Add attributeOption to attribute type * Fix calcom/prisma mock * Refactor Prisma client imports to @calcom/prisma/client Updated all imports from '@prisma/client' to '@calcom/prisma/client' across tests and repository files for consistency and to use the correct Prisma client package. This change improves maintainability and ensures the correct client is referenced throughout the codebase. * Undo removal of max-warnings=0 to get main to merge * Remove unit tests for e2e fixtures, provide new prisma mock * Mock @calcom/prisma in event manager * Mock @calcom/prisma in event manager * Add correct format even with --no-verify * Mock prisma in CalendarManager * Add mock for permission-check.service * Better injection in PrismaApiKeyRepository imports * More mock fixes :) * Fix listMembers.handler.test * Fix User import * Appropriately adjust all types to be imported as types, there were a lot of types imported as normal deps * Why was this a thing? * Strictly speaking; Not using prismock anymore * Ditched patch file for prismock * Fix output.service.ts platform type imports, need concrete for plainToClass * Better typing and tests for unlinkConnectedAccount.handler * Small type fix * Disable calendar cache tests as they are dependent on prismock * chore: bump platform lib * getRoutedUrl test remove of unused import * Extract select to external const on getEventTypesFromDB * Direct select of userSelect from selects/user * fix type error from merging 23653 * Fixed integration tests by removing hardcoded values that were possible due to mocking, but as its now directly hitting the db no longer * fix: vite config atoms prisma client type location * revert: example app prisma client * revert: example app prisma client * bump platform libs * fix: use class instead of type for DI of PlatformBookingsService * update platform libs * remove unused variable * chore: generate prisma client for api v2 * fix: api v2 e2e * fix: atoms e2e * fix: atoms e2e * fix: atoms e2e * fix: api v2 e2e * fix: tsconfig apiv2 enums * publish libraries * Simplify check for existence teamId --------- Signed-off-by: Omar López <zomars@me.com> Co-authored-by: Alex van Andel <me@alexvanandel.com> Co-authored-by: Joe Au-Yeung <j.auyeung419@gmail.com> Co-authored-by: supalarry <laurisskraucis@gmail.com> Co-authored-by: cal.com <morgan@cal.com> Co-authored-by: Morgan <33722304+ThyMinimalDev@users.noreply.github.com> Co-authored-by: Benny Joo <sldisek783@gmail.com>
290 lines
11 KiB
TypeScript
290 lines
11 KiB
TypeScript
/* eslint-disable @typescript-eslint/no-explicit-any */
|
|
import { calendar_v3 } from "@googleapis/calendar";
|
|
import { OAuth2Client, JWT } from "googleapis-common";
|
|
|
|
import {
|
|
CalendarAppDelegationCredentialClientIdNotAuthorizedError,
|
|
CalendarAppDelegationCredentialInvalidGrantError,
|
|
CalendarAppDelegationCredentialError,
|
|
} from "@calcom/lib/CalendarAppError";
|
|
import {
|
|
APP_CREDENTIAL_SHARING_ENABLED,
|
|
CREDENTIAL_SYNC_ENDPOINT,
|
|
CREDENTIAL_SYNC_SECRET,
|
|
CREDENTIAL_SYNC_SECRET_HEADER_NAME,
|
|
} from "@calcom/lib/constants";
|
|
import logger from "@calcom/lib/logger";
|
|
import type { Prisma } from "@calcom/prisma/client";
|
|
import type { CredentialForCalendarServiceWithEmail } from "@calcom/types/Credential";
|
|
|
|
import { invalidateCredential } from "../../_utils/invalidateCredential";
|
|
import { OAuthManager } from "../../_utils/oauth/OAuthManager";
|
|
import { oAuthManagerHelper } from "../../_utils/oauth/oAuthManagerHelper";
|
|
import { OAuth2UniversalSchema } from "../../_utils/oauth/universalSchema";
|
|
import { metadata } from "../_metadata";
|
|
import { getGoogleAppKeys } from "./getGoogleAppKeys";
|
|
|
|
type DelegatedTo = NonNullable<CredentialForCalendarServiceWithEmail["delegatedTo"]>;
|
|
const log = logger.getSubLogger({ prefix: ["app-store/googlecalendar/lib/CalendarAuth"] });
|
|
|
|
class MyGoogleOAuth2Client extends OAuth2Client {
|
|
constructor(client_id: string, client_secret: string, redirect_uri: string) {
|
|
super({
|
|
clientId: client_id,
|
|
clientSecret: client_secret,
|
|
redirectUri: redirect_uri,
|
|
// default: 5 * 60 * 1000, 5 minutes
|
|
// tho, fn will never run in excess of 60 seconds
|
|
eagerRefreshThresholdMillis: 60000,
|
|
});
|
|
}
|
|
|
|
isTokenExpiring() {
|
|
return super.isTokenExpiring();
|
|
}
|
|
|
|
async refreshToken(token: string | null | undefined) {
|
|
return super.refreshToken(token);
|
|
}
|
|
}
|
|
|
|
export class CalendarAuth {
|
|
private credential: CredentialForCalendarServiceWithEmail;
|
|
private jwtAuthClient: JWT | null = null;
|
|
private oAuthClient: MyGoogleOAuth2Client | null = null;
|
|
public authManager!: OAuthManager;
|
|
private authMechanism: ReturnType<CalendarAuth["initAuthMechanism"]>;
|
|
|
|
constructor(credential: CredentialForCalendarServiceWithEmail) {
|
|
this.credential = credential;
|
|
this.authMechanism = this.initAuthMechanism(credential);
|
|
}
|
|
|
|
private getAuthStrategy(): "jwt" | "oauth" {
|
|
return this.credential.delegatedToId ? "jwt" : "oauth";
|
|
}
|
|
|
|
private async getOAuthClientSingleton() {
|
|
if (this.oAuthClient) {
|
|
log.debug("Reusing existing oAuthClient");
|
|
return this.oAuthClient;
|
|
}
|
|
log.debug("Creating new oAuthClient");
|
|
const { client_id, client_secret, redirect_uris } = await getGoogleAppKeys();
|
|
const googleCredentials = OAuth2UniversalSchema.parse(this.credential.key);
|
|
this.oAuthClient = new MyGoogleOAuth2Client(client_id, client_secret, redirect_uris[0]);
|
|
this.oAuthClient.setCredentials(googleCredentials);
|
|
return this.oAuthClient;
|
|
}
|
|
|
|
private async getJwtClientSingleton({
|
|
emailToImpersonate,
|
|
delegatedTo,
|
|
}: {
|
|
emailToImpersonate: string | null;
|
|
delegatedTo: DelegatedTo;
|
|
}) {
|
|
if (!emailToImpersonate) {
|
|
log.error("DelegatedTo: No email to impersonate found for delegation credential");
|
|
return null;
|
|
}
|
|
const oauthClientIdAliasRegex = /\+[a-zA-Z0-9]{25}/;
|
|
if (!this.jwtAuthClient) {
|
|
log.debug("Creating new delegation credential authClient");
|
|
const authClient = new JWT({
|
|
email: delegatedTo.serviceAccountKey.client_email,
|
|
key: delegatedTo.serviceAccountKey.private_key,
|
|
scopes: ["https://www.googleapis.com/auth/calendar"],
|
|
subject: emailToImpersonate.replace(oauthClientIdAliasRegex, ""),
|
|
});
|
|
this.jwtAuthClient = authClient;
|
|
} else {
|
|
log.debug("Reusing existing delegation credential authClient");
|
|
}
|
|
return this.jwtAuthClient;
|
|
}
|
|
|
|
private async refreshOAuthToken({ refreshToken }: { refreshToken: string | null }) {
|
|
const oAuthClient = await this.getOAuthClientSingleton();
|
|
return oAuthClient.refreshToken(refreshToken);
|
|
}
|
|
|
|
private refreshJwtToken = async ({ delegatedTo }: { delegatedTo: DelegatedTo }) => {
|
|
log.debug("Attempting to authorize using JWT auth");
|
|
const { user } = this.credential;
|
|
const emailToImpersonate = user?.email ?? null;
|
|
const authClient = await this.getJwtClientSingleton({ delegatedTo, emailToImpersonate });
|
|
if (!authClient) {
|
|
log.error("JWT auth: No auth client found");
|
|
return null;
|
|
}
|
|
try {
|
|
log.debug("Authorizing using JWT auth");
|
|
return await authClient.authorize();
|
|
} catch (error) {
|
|
log.error("DelegatedTo: Error authorizing using JWT auth", JSON.stringify(error));
|
|
|
|
if ((error as any).response?.data?.error === "unauthorized_client") {
|
|
throw new CalendarAppDelegationCredentialClientIdNotAuthorizedError(
|
|
"Make sure that the Client ID for the delegation credential is added to the Google Workspace Admin Console"
|
|
);
|
|
}
|
|
|
|
if ((error as any).response?.data?.error === "invalid_grant") {
|
|
throw new CalendarAppDelegationCredentialInvalidGrantError(
|
|
`User ${emailToImpersonate} might not exist in Google Workspace`
|
|
);
|
|
}
|
|
|
|
// Catch all error
|
|
throw new CalendarAppDelegationCredentialError("Error authorizing delegation credential");
|
|
}
|
|
};
|
|
|
|
private initAuthMechanism(credential: CredentialForCalendarServiceWithEmail) {
|
|
const authStrategy = this.getAuthStrategy();
|
|
const authManager = new OAuthManager({
|
|
// Keep it false for oauth because Google's OAuth2Client library that we use supports token expiry check, itself when we use the client to make any request
|
|
// We keep it true for jwt because JWT Client doesn't support token expiry check and we do it ourselves
|
|
autoCheckTokenExpiryOnRequest: authStrategy !== "oauth",
|
|
...(authStrategy === "oauth"
|
|
? {
|
|
// Use Google's OAuth2Client library itself to check if the token is expiring
|
|
// For JWT, OAuthManager will do it itself
|
|
isTokenExpiring: async () => {
|
|
const oAuthClient = await this.getOAuthClientSingleton();
|
|
return oAuthClient.isTokenExpiring();
|
|
},
|
|
}
|
|
: {}),
|
|
credentialSyncVariables: {
|
|
APP_CREDENTIAL_SHARING_ENABLED: APP_CREDENTIAL_SHARING_ENABLED,
|
|
CREDENTIAL_SYNC_ENDPOINT: CREDENTIAL_SYNC_ENDPOINT,
|
|
CREDENTIAL_SYNC_SECRET: CREDENTIAL_SYNC_SECRET,
|
|
CREDENTIAL_SYNC_SECRET_HEADER_NAME: CREDENTIAL_SYNC_SECRET_HEADER_NAME,
|
|
},
|
|
resourceOwner: {
|
|
type: "user",
|
|
id: credential.userId,
|
|
},
|
|
appSlug: metadata.slug,
|
|
getCurrentTokenObject: async () => {
|
|
return oAuthManagerHelper.getCurrentTokenObject(this.credential);
|
|
},
|
|
fetchNewTokenObject: async ({ refreshToken }: { refreshToken: string | null }) => {
|
|
let result;
|
|
if (authStrategy === "jwt" && this.credential.delegatedTo) {
|
|
log.debug("Fetching new token object for JWT auth");
|
|
result = {
|
|
// In case of JWT Token flow, there is no refresh token, so we need to refresh the token using Service Account
|
|
tokenObject: await this.refreshJwtToken({ delegatedTo: this.credential.delegatedTo }),
|
|
status: 200,
|
|
statusText: "OK",
|
|
};
|
|
}
|
|
|
|
if (!result || !result.tokenObject) {
|
|
log.debug("Fetching new token object for my Google Auth");
|
|
const tokenFetchedResult = await this.refreshOAuthToken({ refreshToken });
|
|
result = {
|
|
tokenObject: tokenFetchedResult.res?.data ?? null,
|
|
status: tokenFetchedResult.res?.status,
|
|
statusText: tokenFetchedResult.res?.statusText,
|
|
};
|
|
}
|
|
return new Response(JSON.stringify(result.tokenObject), {
|
|
status: result.status,
|
|
statusText: result.statusText,
|
|
});
|
|
},
|
|
isTokenObjectUnusable: async function (response) {
|
|
// TODO: Confirm that if this logic should go to isAccessTokenUnusable
|
|
if (!response.ok || (response.status < 200 && response.status >= 300)) {
|
|
const responseBody = await response.json();
|
|
if (responseBody.error === "invalid_grant") {
|
|
return {
|
|
reason: "invalid_grant",
|
|
};
|
|
}
|
|
}
|
|
return null;
|
|
},
|
|
isAccessTokenUnusable: async () => {
|
|
// As long as refresh_token is valid, access_token is regenerated and fixed automatically by Google Calendar when a problem with it is detected
|
|
// So, a situation where access_token is invalid but refresh_token is valid should not happen
|
|
return null;
|
|
},
|
|
invalidateTokenObject: () => invalidateCredential(this.credential.id),
|
|
expireAccessToken: async () => {
|
|
await oAuthManagerHelper.markTokenAsExpired(this.credential);
|
|
},
|
|
updateTokenObject: async (token) => {
|
|
await oAuthManagerHelper.updateTokenObjectInDb({
|
|
tokenObject: token,
|
|
authStrategy: this.getAuthStrategy(),
|
|
credentialId: this.credential.id,
|
|
userId: this.credential.userId ?? null,
|
|
delegatedToId: this.credential.delegatedToId ?? null,
|
|
credentialType: this.credential.type,
|
|
appId: metadata.slug,
|
|
});
|
|
if (this.oAuthClient) {
|
|
this.oAuthClient.setCredentials(token);
|
|
}
|
|
|
|
// Update cached credential as well
|
|
this.credential.key = token as Prisma.JsonValue;
|
|
},
|
|
});
|
|
this.authManager = authManager;
|
|
|
|
return {
|
|
getOAuthClientWithRefreshedToken: async () => {
|
|
const { token } = await authManager.getTokenObjectOrFetch();
|
|
if (!token) {
|
|
throw new Error("Invalid grant for Google Calendar app");
|
|
}
|
|
const oAuthClient = await this.getOAuthClientSingleton();
|
|
return oAuthClient;
|
|
},
|
|
getJwtClientWithRefreshedToken: async ({ delegatedTo }: { delegatedTo: DelegatedTo }) => {
|
|
log.debug("Getting JWT client with refreshed token");
|
|
await authManager.getTokenObjectOrFetch();
|
|
return this.getJwtClientSingleton({
|
|
emailToImpersonate: this.credential.user?.email ?? null,
|
|
delegatedTo,
|
|
});
|
|
},
|
|
};
|
|
}
|
|
|
|
/**
|
|
* Returns a Google Calendar client that is authenticated with the user's credentials.
|
|
* If the user is delegated, it will use the delegation credential.
|
|
* If the user is not delegated, it will use the user's OAuth credentials.
|
|
*/
|
|
public async getClient(): Promise<calendar_v3.Calendar> {
|
|
log.debug("Getting authed calendar client");
|
|
let googleAuthClient;
|
|
const authStrategy = this.getAuthStrategy();
|
|
|
|
if (authStrategy === "jwt" && this.credential.delegatedTo) {
|
|
googleAuthClient = await this.authMechanism.getJwtClientWithRefreshedToken({
|
|
delegatedTo: this.credential.delegatedTo,
|
|
});
|
|
}
|
|
|
|
if (!googleAuthClient) {
|
|
googleAuthClient = await this.authMechanism.getOAuthClientWithRefreshedToken();
|
|
}
|
|
|
|
if (!googleAuthClient) {
|
|
throw new Error("Failed to initialize Google Auth client");
|
|
}
|
|
|
|
return new calendar_v3.Calendar({
|
|
auth: googleAuthClient,
|
|
});
|
|
}
|
|
}
|