diff --git a/apps/web/app/settings/(admin-layout)/admin/workspace-platforms/page.tsx b/apps/web/app/settings/(admin-layout)/admin/workspace-platforms/page.tsx new file mode 100644 index 0000000000..ccf5f7cc14 --- /dev/null +++ b/apps/web/app/settings/(admin-layout)/admin/workspace-platforms/page.tsx @@ -0,0 +1,28 @@ +import { _generateMetadata } from "app/_utils"; +import { getFixedT } from "app/_utils"; + +import { getServerSessionForAppDir } from "@calcom/feature-auth/lib/get-server-session-for-app-dir"; +import LicenseRequired from "@calcom/features/ee/common/components/LicenseRequired"; +import WorkspacePlatformsPage from "@calcom/features/ee/organizations/pages/settings/admin/WorkspacePlatformPage"; +import SettingsHeader from "@calcom/features/settings/appDir/SettingsHeader"; + +export const generateMetadata = async () => + await _generateMetadata( + (t) => t("workspace_platforms"), + (t) => t("workspace_platforms_description") + ); + +const Page = async () => { + const session = await getServerSessionForAppDir(); + + const t = await getFixedT(session?.user.locale || "en"); + return ( + + + + + + ); +}; + +export default Page; diff --git a/apps/web/app/settings/(settings-layout)/organizations/domain-wide-delegation/page.tsx b/apps/web/app/settings/(settings-layout)/organizations/domain-wide-delegation/page.tsx new file mode 100644 index 0000000000..70bdaece4b --- /dev/null +++ b/apps/web/app/settings/(settings-layout)/organizations/domain-wide-delegation/page.tsx @@ -0,0 +1,27 @@ +import { _generateMetadata, getFixedT } from "app/_utils"; + +import { getServerSessionForAppDir } from "@calcom/features/auth/lib/get-server-session-for-app-dir"; +import DomainWideDelegationList from "@calcom/features/ee/organizations/pages/settings/domainWideDelegation"; +import SettingsHeader from "@calcom/features/settings/appDir/SettingsHeader"; + +export const generateMetadata = async () => + await _generateMetadata( + (t) => t("domain_wide_delegation"), + (t) => t("domain_wide_delegation_description") + ); + +const Page = async () => { + const session = await getServerSessionForAppDir(); + const t = await getFixedT(session?.user.locale || "en"); + + return ( + + + + ); +}; + +export default Page; diff --git a/apps/web/pages/api/trpc/domainWideDelegation/[trpc].ts b/apps/web/pages/api/trpc/domainWideDelegation/[trpc].ts new file mode 100644 index 0000000000..e3d6a0fd1b --- /dev/null +++ b/apps/web/pages/api/trpc/domainWideDelegation/[trpc].ts @@ -0,0 +1,4 @@ +import { createNextApiHandler } from "@calcom/trpc/server/createNextApiHandler"; +import { domainWideDelegationRouter } from "@calcom/trpc/server/routers/viewer/domainWideDelegation/_router"; + +export default createNextApiHandler(domainWideDelegationRouter); diff --git a/apps/web/public/static/locales/en/common.json b/apps/web/public/static/locales/en/common.json index 8999016efd..fe250db493 100644 --- a/apps/web/public/static/locales/en/common.json +++ b/apps/web/public/static/locales/en/common.json @@ -2240,6 +2240,26 @@ "what_is_this_meeting_about": "What is this meeting about?", "add_to_team": "Add to team", "remove_users_from_org": "Remove users from organization", + "domain_wide_delegation": "Domain-wide delegation", + "domain_wide_delegation_description": "Domain-wide delegation allows you to manage access to Google Workspace calendars for your organization.", + "add_client_id_in_google_workspace_with_below_scope": "Add this Client Id in Google Workspace with the scope below", + "domain_wide_delegation_enabled": "Domain-wide delegation enabled", + "domain_wide_delegation_disabled": "Domain-wide delegation disabled", + "add_domain_wide_delegation": "Add domain-wide delegation", + "edit_domain_wide_delegation": "Edit domain-wide delegation", + "domain": "Domain", + "no_workspace_platforms": "No workspace platforms", + "workspace_platform": "Workspace platform", + "workspace_platforms": "Workspace platforms", + "workspace_platforms_description": "Manage workspace platforms that can be used for domain-wide delegation", + "edit_workspace_platform": "Edit workspace platform", + "edit_service_account": "Edit service account", + "add_workspace_platform": "Add workspace platform", + "slug": "Slug", + "service_account_key": "Service account key JSON", + "edit_service_account_key": "Edit service account key JSON", + "domain_wide_delegation_restricts_adding_more_than_one_installation": "Domain-wide delegation restricts adding more than one installation", + "app_successfully_installed_and_is_using_delegated_credentials": "App successfully installed and is using delegated credentials", "remove_users_from_org_confirm": "Are you sure you want to remove {{userCount}} users from this organization?", "remove_users_from_team": "Remove users from team", "remove_users_from_team_confirm": "Are you sure you want to remove {{userCount}} users from this team?", diff --git a/apps/web/tsconfig.json b/apps/web/tsconfig.json index fd7ed7332a..5fe50438a9 100644 --- a/apps/web/tsconfig.json +++ b/apps/web/tsconfig.json @@ -9,6 +9,7 @@ "@lib/*": ["lib/*"], "@server/*": ["server/*"], "@prisma/client/*": ["@calcom/prisma/client/*"], + "@calcom/repository/*": ["@calcom/lib/server/repository/*"], "@calcom/ui/*": ["../../packages/ui/components/*"] }, "plugins": [ diff --git a/packages/app-store/googlecalendar/lib/CalendarService.test.ts b/packages/app-store/googlecalendar/lib/CalendarService.test.ts index 72d9b95a29..87aab1cc2c 100644 --- a/packages/app-store/googlecalendar/lib/CalendarService.test.ts +++ b/packages/app-store/googlecalendar/lib/CalendarService.test.ts @@ -141,6 +141,7 @@ test("Calendar can be watched and unwatched", async () => { integration: "google_calendar", externalId: "example@cal.com", credentialId: 1, + domainWideDelegationCredentialId: null, googleChannelId: "mock-channel-id", googleChannelKind: "api#channel", googleChannelResourceId: "mock-resource-id", @@ -162,6 +163,7 @@ test("Calendar can be watched and unwatched", async () => { integration: "google_calendar", externalId: "example@cal.com", credentialId: 1, + domainWideDelegationCredentialId: null, googleChannelId: null, googleChannelKind: null, googleChannelResourceId: null, diff --git a/packages/features/domain-wide-delegation/domain-wide-delegation-repository.interface.ts b/packages/features/domain-wide-delegation/domain-wide-delegation-repository.interface.ts new file mode 100644 index 0000000000..9c77dacc9f --- /dev/null +++ b/packages/features/domain-wide-delegation/domain-wide-delegation-repository.interface.ts @@ -0,0 +1,59 @@ +import type { Prisma } from "@prisma/client"; + +type DomainWideDelegationSafeSelect = { + id: string; + enabled: boolean; + domain: string; + createdAt: Date; + updatedAt: Date; + organizationId: number; + workspacePlatform: { + name: string; + slug: string; + }; +}; + +export interface IDomainWideDelegationRepository { + create(args: { + domain: string; + enabled: boolean; + organizationId: number; + workspacePlatformId: number; + serviceAccountKey: Exclude; + }): Promise; + + findById(args: { id: string }): Promise; + + findByIdIncludeSensitiveServiceAccountKey(args: { + id: string; + }): Promise<(DomainWideDelegationSafeSelect & { serviceAccountKey: any }) | null>; + + findUniqueByOrganizationMemberEmail(args: { + email: string; + }): Promise; + + findByUser(args: { user: { email: string } }): Promise; + + updateById(args: { + id: string; + data: Partial<{ + workspacePlatformId: number; + domain: string; + enabled: boolean; + organizationId: number; + }>; + }): Promise; + + deleteById(args: { id: string }): Promise; + + findDelegationsWithServiceAccount(args: { organizationId: number }): Promise< + (DomainWideDelegationSafeSelect & { + workspacePlatform: { + id: number; + name: string; + slug: string; + }; + serviceAccountKey: any; + })[] + >; +} diff --git a/packages/features/domain-wide-delegation/domain-wide-delegation.ts b/packages/features/domain-wide-delegation/domain-wide-delegation.ts new file mode 100644 index 0000000000..dfdf7a63dc --- /dev/null +++ b/packages/features/domain-wide-delegation/domain-wide-delegation.ts @@ -0,0 +1,38 @@ +import { DomainWideDelegationRepository } from "@calcom/lib/server/repository/domainWideDelegation"; +import prisma from "@calcom/prisma"; + +import { MockDomainWideDelegationRepository } from "./mock-domain-wide-delegation.repository"; + +export class DomainWideDelegation { + static async checkIfDwDIsEnabled(userId: number, teamId: number | null) { + if (!teamId) { + return false; + } + const teamFeature = await prisma.teamFeatures.findFirst({ + where: { + teamId: teamId, + featureId: "domain-wide-delegation", + }, + }); + + const membership = await prisma.membership.findFirst({ + where: { + userId: userId, + teamId: teamId, + accepted: true, + }, + }); + + return !!(teamFeature && membership); + } + + static async init(userId: number, teamId: number | null) { + const domainWideDelegationEnabled = await this.checkIfDwDIsEnabled(userId, teamId); + + if (!domainWideDelegationEnabled) { + return new MockDomainWideDelegationRepository(); + } + + return new DomainWideDelegationRepository(); + } +} diff --git a/packages/features/domain-wide-delegation/mock-domain-wide-delegation.repository.ts b/packages/features/domain-wide-delegation/mock-domain-wide-delegation.repository.ts new file mode 100644 index 0000000000..a900466bad --- /dev/null +++ b/packages/features/domain-wide-delegation/mock-domain-wide-delegation.repository.ts @@ -0,0 +1,59 @@ +import type { Prisma } from "@prisma/client"; + +import type { IDomainWideDelegationRepository } from "./domain-wide-delegation-repository.interface"; + +export class MockDomainWideDelegationRepository implements IDomainWideDelegationRepository { + async create(_data: { + domain: string; + enabled: boolean; + organizationId: number; + workspacePlatformId: number; + serviceAccountKey: Exclude; + }) { + return null; + } + + async findById(_args: { id: string }) { + return null; + } + + async findByIdIncludeSensitiveServiceAccountKey(_args: { id: string }) { + return null; + } + + async findUniqueByOrganizationMemberEmail(_args: { email: string }) { + return null; + } + + async findByUser(_args: { user: { email: string } }) { + return null; + } + + static async findAllByDomain(_args: { domain: string }) { + return []; + } + + static async findFirstByOrganizationId(_args: { organizationId: number }) { + return null; + } + + async updateById(_args: { + id: string; + data: Partial<{ + workspacePlatformId: number; + domain: string; + enabled: boolean; + organizationId: number; + }>; + }) { + return null; + } + + async deleteById(_args: { id: string }) { + return null; + } + + async findDelegationsWithServiceAccount(_args: { organizationId: number }) { + return []; + } +} diff --git a/packages/features/ee/organizations/pages/settings/admin/WorkspacePlatformPage.tsx b/packages/features/ee/organizations/pages/settings/admin/WorkspacePlatformPage.tsx new file mode 100644 index 0000000000..9d2a42a5f6 --- /dev/null +++ b/packages/features/ee/organizations/pages/settings/admin/WorkspacePlatformPage.tsx @@ -0,0 +1,440 @@ +"use client"; + +import { zodResolver } from "@hookform/resolvers/zod"; +import { useState } from "react"; +import type { SubmitHandler } from "react-hook-form"; +import { useForm, useFormContext } from "react-hook-form"; +import { z } from "zod"; + +import { useLocale } from "@calcom/lib/hooks/useLocale"; +import { serviceAccountKeySchema } from "@calcom/prisma/zod-utils"; +import { trpc, type RouterOutputs } from "@calcom/trpc"; +import { + Button, + Form, + Switch, + showToast, + Dialog, + DialogContent, + DialogFooter, + DialogClose, + TextField, + TextAreaField, + Table, + DropdownActions, +} from "@calcom/ui"; + +const { Body, Cell, ColumnTitle, Header, Row } = Table; + +type WorkspacePlatform = RouterOutputs["viewer"]["admin"]["workspacePlatform"]["list"][number]; +type EditType = "meta" | "serviceAccount"; + +type Props = { + workspacePlatforms: WorkspacePlatform[]; + onAdd: () => void; + onEdit: (platform: WorkspacePlatform, editType: EditType) => void; + onToggle: (platform: WorkspacePlatform, checked: boolean) => void; + isOpen: boolean; + onOpenChange: (open: boolean) => void; + editingPlatform: WorkspacePlatform; + isCreate: boolean; + platform: WorkspacePlatform; + platformId?: number; + platforms: WorkspacePlatform[]; +}; + +const WorkspacePlatformsPage = () => { + const { t } = useLocale(); + const [isDialogOpen, setIsDialogOpen] = useState(false); + + const [editing, setEditing] = useState< + { platform: WorkspacePlatform; editType: EditType } | { platform: null; editType: EditType } + >({ platform: null, editType: "meta" }); + + const utils = trpc.useUtils(); + const { data: workspacePlatforms, isPending, error } = trpc.viewer.admin.workspacePlatform.list.useQuery(); + const toggleEnabledMutation = trpc.viewer.admin.workspacePlatform.toggleEnabled.useMutation({ + onSuccess: () => { + showToast(t("workspace_platform_updated_successfully"), "success"); + utils.viewer.admin.workspacePlatform.list.invalidate(); + }, + onError: (error) => { + console.error(error); + showToast(t("something_went_wrong"), "error"); + }, + }); + + if (error) { + return ; + } + + if (isPending || !workspacePlatforms) return ; + + return ( + <> + + {editing.editType === "meta" && ( + + )} + {editing.editType === "serviceAccount" && ( + + )} + + ); + + function handleAdd() { + setEditing({ platform: null, editType: "meta" }); + setIsDialogOpen(true); + } + + function handleEdit(platform: Props["platform"], editType: "meta" | "serviceAccount" = "meta") { + setEditing({ platform, editType }); + setIsDialogOpen(true); + } + + function handleToggle(platform: Props["platform"], checked: boolean) { + toggleEnabledMutation.mutate({ ...platform, enabled: checked }); + } +}; + +function LoadingState() { + const { t } = useLocale(); + return
{t("loading")}...
; +} + +function ErrorState() { + const { t } = useLocale(); + return
{t("something_went_wrong")}
; +} + +function PageContent({ + workspacePlatforms, + onAdd, + onEdit, + onToggle, +}: Pick) { + return ( +
+ {workspacePlatforms.length === 0 ? ( + + ) : ( + + )} +
+ ); +} + +function EmptyState({ onAdd }: Pick) { + const { t } = useLocale(); + + return ( +
+

{t("no_workspace_platforms")}

+ +
+ ); +} + +function PlatformList({ + platforms, + onEdit, + onToggle, + onAdd, +}: Pick) { + const { t } = useLocale(); + + return ( + <> + +
+ {t("platform")} + {t("slug")} + {t("status")} + + {t("actions")} + +
+ + {platforms.map((platform) => ( + + ))} + +
+
+ +
+ + ); +} + +function ServiceAccountFields() { + const { t } = useLocale(); + const form = useFormContext(); + + return ( +
+ +
+ ); +} + +function UpdateServiceAccountFieldsDialog({ + isOpen, + onOpenChange, + platformId, +}: Pick) { + const { t } = useLocale(); + const utils = trpc.useUtils(); + type FormValues = { defaultServiceAccountKey: string }; + const form = useForm({ + defaultValues: { + defaultServiceAccountKey: "", + }, + resolver: zodResolver(z.object({ defaultServiceAccountKey: z.string() })), + }); + + const updateServiceAccountMutation = trpc.viewer.admin.workspacePlatform.updateServiceAccount.useMutation({ + onSuccess: () => { + showToast(t("service_account_updated_successfully"), "success"); + utils.viewer.admin.workspacePlatform.list.invalidate(); + onOpenChange(false); + }, + onError: (error) => { + showToast(error.message || t("something_went_wrong"), "error"); + }, + }); + + const onSubmit: SubmitHandler = (values) => { + if (!platformId) return; + + const parsedKey = JSON.parse(values.defaultServiceAccountKey); + const validatedKey = serviceAccountKeySchema.safeParse(parsedKey); + if (!validatedKey.success) { + form.setError("defaultServiceAccountKey", { message: t("invalid_service_account_key") }); + return; + } + updateServiceAccountMutation.mutate({ + id: platformId, + ...values, + defaultServiceAccountKey: validatedKey.data, + }); + }; + + return ( + + +
+ + + + + + +
+
+ ); +} + +function PlatformListItem({ platform, onEdit, onToggle }: Pick) { + const { t } = useLocale(); + + return ( + + +
+ {platform.name} +
+
+ +
+ {platform.slug} +
+
+ + onToggle(platform, checked)} /> + + +
+ onEdit(platform, "meta"), + icon: "pencil", + }, + { + id: "edit-service-account", + label: t("edit_service_account"), + onClick: () => onEdit(platform, "serviceAccount"), + icon: "pencil", + }, + ]} + /> +
+
+
+ ); +} + +function CreatePlatformDialog({ isOpen, onOpenChange }: Pick) { + const { t } = useLocale(); + type FormValues = { name: string; description: string; slug: string; defaultServiceAccountKey: string }; + const form = useForm({ + defaultValues: { + name: "", + description: "", + slug: "", + defaultServiceAccountKey: "", + }, + resolver: zodResolver( + z.object({ + name: z.string(), + description: z.string(), + slug: z.string(), + defaultServiceAccountKey: z.string(), + }) + ), + }); + + const utils = trpc.useUtils(); + + const addMutation = trpc.viewer.admin.workspacePlatform.add.useMutation({ + onSuccess: async () => { + showToast(t("workspace_platform_added_successfully"), "success"); + onOpenChange(false); + await utils.viewer.admin.workspacePlatform.list.invalidate(); + }, + onError: (error) => { + showToast(error.message, "error"); + }, + }); + + const onSubmit: SubmitHandler = (values) => { + const parsedKey = JSON.parse(values.defaultServiceAccountKey); + const validatedKey = serviceAccountKeySchema.safeParse(parsedKey); + if (!validatedKey.success) { + form.setError("defaultServiceAccountKey", { message: t("invalid_service_account_key") }); + return; + } + addMutation.mutate({ + ...values, + defaultServiceAccountKey: validatedKey.data, + }); + }; + + return ( + + +
+ + + + + + +
+
+ ); +} + +function UpdatePlatformDialog({ + isOpen, + onOpenChange, + editingPlatform, +}: Pick) { + const { t } = useLocale(); + type FormValues = { name: string; description: string }; + const form = useForm({ + defaultValues: { + name: editingPlatform.name, + description: editingPlatform.description, + }, + }); + + const utils = trpc.useUtils(); + + const updateMutation = trpc.viewer.admin.workspacePlatform.update.useMutation({ + onSuccess: async () => { + showToast(t("workspace_platform_updated_successfully"), "success"); + onOpenChange(false); + await utils.viewer.admin.workspacePlatform.list.invalidate(); + }, + onError: function (error) { + showToast(error.message, "error"); + }, + }); + + const onSubmit: SubmitHandler = (values) => { + updateMutation.mutate({ ...values, id: editingPlatform.id }); + }; + + return ( + + +
+ + + + + + +
+
+ ); +} + +function PlatformFormFields({ isCreate }: Pick) { + const { t } = useLocale(); + const form = useFormContext(); + + return ( +
+ + + {isCreate && } + {isCreate && } +
+ ); +} + +function CreateUpdatePlatformDialog({ + isOpen, + onOpenChange, + editingPlatform, +}: Pick & { editingPlatform?: Props["editingPlatform"] }) { + if (editingPlatform) { + return ( + + ); + } + return ; +} + +export default WorkspacePlatformsPage; diff --git a/packages/features/ee/organizations/pages/settings/domainWideDelegation.tsx b/packages/features/ee/organizations/pages/settings/domainWideDelegation.tsx new file mode 100644 index 0000000000..500ee066be --- /dev/null +++ b/packages/features/ee/organizations/pages/settings/domainWideDelegation.tsx @@ -0,0 +1,414 @@ +"use client"; + +import { useState } from "react"; +import { useForm, Controller, useFormContext } from "react-hook-form"; + +import { useLocale } from "@calcom/lib/hooks/useLocale"; +import { trpc } from "@calcom/trpc/react"; +import { + DropdownActions, + Button, + Dialog, + DialogContent, + DialogFooter, + Form, + TextField, + SelectField, + showToast, + Badge, + Switch, + InfoBadge, + EmptyScreen, + SkeletonContainer, + SkeletonText, +} from "@calcom/ui"; + +interface DelegationItemProps { + delegation: { + id: string; + domain: string; + enabled: boolean; + serviceAccountClientId: string | null; + workspacePlatform: { + name: string; + slug: string; + }; + }; + toggleDelegation: (delegation: DelegationItemProps["delegation"]) => void; + onEdit: (delegation: DelegationItemProps["delegation"]) => void; + onDelete: (id: string) => void; +} + +type WorkspacePlatform = { + id: number; + name: string; + slug: string; +}; + +function getWorkspacePlatformOptions(workspacePlatforms: WorkspacePlatform[]) { + return workspacePlatforms.map((platform) => ({ + value: platform.slug, + label: platform.name, + })); +} + +const SkeletonLoader = () => { + return ( + +
+ + +
+
+ ); +}; + +function DelegationListItemActions({ + delegation, + toggleDelegation, + onEdit, + onDelete, +}: { + delegation: DelegationItemProps["delegation"]; + toggleDelegation: DelegationItemProps["toggleDelegation"]; + onEdit: (delegation: DelegationItemProps["delegation"]) => void; + onDelete: (id: string) => void; +}) { + const { t } = useLocale(); + + return ( +
+ toggleDelegation(delegation)} /> + onEdit(delegation), + icon: "pencil", + }, + { + id: "delete", + label: t("delete"), + onClick: () => onDelete(delegation.id), + icon: "trash", + }, + ]} + /> +
+ ); +} + +function DelegationListItem({ delegation, toggleDelegation, onEdit, onDelete }: DelegationItemProps) { + const { t } = useLocale(); + return ( +
  • +
    +
    +
    + {delegation.serviceAccountClientId} + +
    + https://www.googleapis.com/auth/calendar +
    + {delegation.workspacePlatform.name} + {delegation.domain} +
    +
    + +
    +
  • + ); +} + +function CreateDelegationDialog({ + isOpen, + onClose, + onSubmit, + workspacePlatforms, +}: { + isOpen: boolean; + onClose: () => void; + onSubmit: (data: { domain: string; workspacePlatformSlug: string; enabled: boolean }) => void; + workspacePlatforms: WorkspacePlatform[]; +}) { + const { t } = useLocale(); + + const form = useForm<{ domain: string; workspacePlatformSlug: string; enabled: boolean }>({ + defaultValues: { + domain: "", + workspacePlatformSlug: "", + }, + }); + + return ( + + +
    + + + + + + +
    +
    + ); +} + +function EditDelegationDialog({ + isOpen, + onClose, + delegation, + onSubmit, + workspacePlatforms, +}: { + isOpen: boolean; + onClose: () => void; + delegation: DelegationItemProps["delegation"]; + onSubmit: (data: { domain: string; workspacePlatformSlug: string; enabled: boolean }) => void; + workspacePlatforms: WorkspacePlatform[]; +}) { + const { t } = useLocale(); + + const form = useForm<{ domain: string; workspacePlatformSlug: string; enabled: boolean }>({ + defaultValues: { + domain: delegation.domain, + workspacePlatformSlug: delegation.workspacePlatform.slug, + }, + }); + + return ( + + +
    + + + + + + +
    +
    + ); +} + +function DelegationFormFields({ workspacePlatforms }: { workspacePlatforms: WorkspacePlatform[] }) { + const { t } = useLocale(); + const form = useFormContext(); + return ( +
    + + { + const platformOptions = getWorkspacePlatformOptions(workspacePlatforms); + const selectedPlatform = platformOptions.find((opt) => opt.value === value); + return ( + onChange(option?.value)} + value={selectedPlatform} + options={platformOptions} + /> + ); + }} + /> +
    + ); +} + +function CreateEditDelegationDialog({ + isOpen, + onClose, + delegation, + onSubmit, + workspacePlatforms, +}: { + isOpen: boolean; + onClose: () => void; + delegation: DelegationItemProps["delegation"] | null; + onSubmit: (data: { domain: string; workspacePlatformSlug: string; enabled: boolean }) => void; + workspacePlatforms: WorkspacePlatform[]; +}) { + if (delegation) { + return ( + + ); + } + return ( + + ); +} + +function DomainWideDelegationList() { + const { t } = useLocale(); + const utils = trpc.useContext(); + const { data: delegations, isLoading, error } = trpc.viewer.domainWideDelegation.list.useQuery(); + + const updateMutation = trpc.viewer.domainWideDelegation.update.useMutation({ + onSuccess: () => utils.viewer.domainWideDelegation.list.invalidate(), + onError: (error) => { + showToast(error.message, "error"); + }, + }); + + const toggleEnabledMutation = trpc.viewer.domainWideDelegation.toggleEnabled.useMutation({ + onSuccess: (data) => { + if (data) { + showToast( + data.enabled ? t("domain_wide_delegation_enabled") : t("domain_wide_delegation_disabled"), + "success" + ); + utils.viewer.domainWideDelegation.list.invalidate(); + } + }, + onError: (error) => { + showToast(error.message, "error"); + }, + }); + + const createMutation = trpc.viewer.domainWideDelegation.add.useMutation({ + onSuccess: () => utils.viewer.domainWideDelegation.list.invalidate(), + onError: (error) => { + showToast(error.message, "error"); + }, + }); + + const deleteMutation = trpc.viewer.domainWideDelegation.delete.useMutation({ + onSuccess: () => utils.viewer.domainWideDelegation.list.invalidate(), + onError: (error) => { + showToast(error.message, "error"); + }, + }); + + const onDelete = (id: string) => { + deleteMutation.mutate({ id }); + }; + + const toggleDelegation = (delegation: DelegationItemProps["delegation"]) => { + if (delegation) { + toggleEnabledMutation.mutate({ + id: delegation.id, + enabled: !delegation.enabled, + }); + } + }; + + const [createEditDialog, setCreateEditDialog] = useState<{ + isOpen: boolean; + delegation: DelegationItemProps["delegation"] | null; + }>({ + isOpen: false, + delegation: null, + }); + + const { data: workspacePlatforms, isLoading: isLoadingWorkspacePlatforms } = + trpc.viewer.domainWideDelegation.listWorkspacePlatforms.useQuery(); + + const enabledWorkspacePlatforms = workspacePlatforms?.filter((platform) => platform.enabled) || []; + + const onEditClick = (delegation: DelegationItemProps["delegation"]) => { + setCreateEditDialog({ isOpen: true, delegation }); + }; + + const onCreateClick = () => setCreateEditDialog({ isOpen: true, delegation: null }); + + const handleSubmit = (data: { domain: string; workspacePlatformSlug: string; enabled: boolean }) => { + if (createEditDialog.delegation) { + updateMutation.mutate({ + id: createEditDialog.delegation.id, + ...data, + }); + } else { + createMutation.mutate(data); + } + setCreateEditDialog({ isOpen: false, delegation: null }); + }; + + const AddDwDButton = () => { + return ( + + ); + }; + + if (isLoading || isLoadingWorkspacePlatforms) { + return ; + } + + if (error) { + return
    {t(error.message)}
    ; + } + + if (!delegations || !workspacePlatforms) { + return
    {t("something_went_wrong")}
    ; + } + + return ( +
    + {!!delegations?.length ? ( + <> +
      + {delegations.map( + (delegation) => + delegation && ( + + ) + )} +
    + + + ) : ( + } + /> + )} + + setCreateEditDialog({ isOpen: false, delegation: null })} + delegation={createEditDialog.delegation} + onSubmit={handleSubmit} + workspacePlatforms={enabledWorkspacePlatforms} + /> +
    + ); +} + +export default function DomainWideDelegationListPage() { + return ; +} diff --git a/packages/features/flags/config.ts b/packages/features/flags/config.ts index 4530f87703..e271a6ea5a 100644 --- a/packages/features/flags/config.ts +++ b/packages/features/flags/config.ts @@ -15,4 +15,5 @@ export type AppFlags = { "disable-signup": boolean; attributes: boolean; "organizer-request-email-v2": boolean; + "domain-wide-delegation": boolean; }; diff --git a/packages/features/flags/hooks/index.ts b/packages/features/flags/hooks/index.ts index 582fb0e012..c32e6b682a 100644 --- a/packages/features/flags/hooks/index.ts +++ b/packages/features/flags/hooks/index.ts @@ -14,6 +14,7 @@ const initialData: AppFlags = { "disable-signup": false, attributes: false, "organizer-request-email-v2": false, + "domain-wide-delegation": false, }; if (process.env.NEXT_PUBLIC_IS_E2E) { diff --git a/packages/features/settings/appDir/SettingsLayoutAppDirClient.tsx b/packages/features/settings/appDir/SettingsLayoutAppDirClient.tsx index a97aab7d99..dcc3a8135b 100644 --- a/packages/features/settings/appDir/SettingsLayoutAppDirClient.tsx +++ b/packages/features/settings/appDir/SettingsLayoutAppDirClient.tsx @@ -99,6 +99,10 @@ const tabs: VerticalTabItemProps[] = [ name: "admin_api", href: "https://cal.com/docs/enterprise-features/api/api-reference/bookings#admin-access", }, + // { + // name: "domain_wide_delegation", + // href: "/settings/organizations/domain-wide-delegation", + // }, ], }, { @@ -127,6 +131,7 @@ const tabs: VerticalTabItemProps[] = [ { name: "organizations", href: "/settings/admin/organizations" }, { name: "lockedSMS", href: "/settings/admin/lockedSMS" }, { name: "oAuth", href: "/settings/admin/oAuth" }, + { name: "Workspace Platforms", href: "/settings/admin/workspace-platforms" }, ], }, ]; diff --git a/packages/features/settings/layouts/SettingsLayout.tsx b/packages/features/settings/layouts/SettingsLayout.tsx index be6323aadd..757f543f08 100644 --- a/packages/features/settings/layouts/SettingsLayout.tsx +++ b/packages/features/settings/layouts/SettingsLayout.tsx @@ -98,6 +98,10 @@ const tabs: VerticalTabItemProps[] = [ name: "admin_api", href: "https://cal.com/docs/enterprise-features/api/api-reference/bookings#admin-access", }, + // { + // name: "domain_wide_delegation", + // href: "/settings/organizations/domain-wide-delegation", + // }, ], }, { @@ -126,6 +130,7 @@ const tabs: VerticalTabItemProps[] = [ { name: "organizations", href: "/settings/admin/organizations" }, { name: "lockedSMS", href: "/settings/admin/lockedSMS" }, { name: "oAuth", href: "/settings/admin/oAuth" }, + { name: "Workspace Platforms", href: "/settings/admin/workspace-platforms" }, ], }, ]; @@ -156,6 +161,8 @@ const useTabs = () => { const isAdmin = session.data?.user.role === UserPermissionRole.ADMIN; const isOrgAdminOrOwner = orgBranding?.role === MembershipRole.ADMIN || orgBranding?.role === MembershipRole.OWNER; + // const flags = useFlags(); + // console.log("flags", flags); const processTabsMemod = useMemo(() => { const processedTabs = tabs.map((tab) => { diff --git a/packages/lib/buildCalEventFromBooking.ts b/packages/lib/buildCalEventFromBooking.ts index ede1d436f1..247fd6594e 100644 --- a/packages/lib/buildCalEventFromBooking.ts +++ b/packages/lib/buildCalEventFromBooking.ts @@ -13,6 +13,7 @@ type DestinationCalendar = { userId: number | null; eventTypeId: number | null; credentialId: number | null; + domainWideDelegationCredentialId: string | null; } | null; type Attendee = { diff --git a/packages/lib/server/repository/domainWideDelegation.ts b/packages/lib/server/repository/domainWideDelegation.ts new file mode 100644 index 0000000000..47f530a35f --- /dev/null +++ b/packages/lib/server/repository/domainWideDelegation.ts @@ -0,0 +1,203 @@ +import type { Prisma } from "@prisma/client"; +import z from "zod"; + +import type { IDomainWideDelegationRepository } from "@calcom/features/domain-wide-delegation/domain-wide-delegation-repository.interface"; +import { getFeatureFlag } from "@calcom/features/flags/server/utils"; +import logger from "@calcom/lib/logger"; +import { prisma } from "@calcom/prisma"; + +import { OrganizationRepository } from "./organization"; + +const serviceAccountKeySchema = z + .object({ + client_email: z.string(), + private_key: z.string(), + client_id: z.string(), + }) + .passthrough(); + +export type ServiceAccountKey = z.infer; + +const repositoryLogger = logger.getSubLogger({ prefix: ["DomainWideDelegationRepository"] }); +const domainWideDelegationSafeSelect = { + id: true, + enabled: true, + domain: true, + createdAt: true, + updatedAt: true, + organizationId: true, + workspacePlatform: { + select: { + name: true, + slug: true, + }, + }, +}; + +const domainWideDelegationSelectIncludesServiceAccountKey = { + ...domainWideDelegationSafeSelect, + serviceAccountKey: true, +}; + +export class DomainWideDelegationRepository implements IDomainWideDelegationRepository { + private static withParsedServiceAccountKey( + domainWideDelegation: T + ) { + if (!domainWideDelegation) { + return null; + } + const parsedServiceAccountKey = serviceAccountKeySchema.safeParse(domainWideDelegation.serviceAccountKey); + + return { + ...domainWideDelegation, + serviceAccountKey: parsedServiceAccountKey.success ? parsedServiceAccountKey.data : null, + }; + } + + async create(data: { + domain: string; + enabled: boolean; + organizationId: number; + workspacePlatformId: number; + serviceAccountKey: Exclude; + }) { + return await prisma.domainWideDelegation.create({ + data: { + workspacePlatform: { + connect: { + id: data.workspacePlatformId, + }, + }, + domain: data.domain, + enabled: data.enabled, + organization: { + connect: { + id: data.organizationId, + }, + }, + serviceAccountKey: data.serviceAccountKey, + }, + select: domainWideDelegationSafeSelect, + }); + } + + async findById({ id }: { id: string }) { + return await prisma.domainWideDelegation.findUnique({ + where: { id }, + select: domainWideDelegationSafeSelect, + }); + } + + async findByIdIncludeSensitiveServiceAccountKey({ id }: { id: string }) { + const domainWideDelegation = await prisma.domainWideDelegation.findUnique({ + where: { id }, + select: domainWideDelegationSelectIncludesServiceAccountKey, + }); + if (!domainWideDelegation) return null; + return DomainWideDelegationRepository.withParsedServiceAccountKey(domainWideDelegation); + } + + async findUniqueByOrganizationMemberEmail({ email }: { email: string }) { + const log = repositoryLogger.getSubLogger({ prefix: ["findUniqueByOrganizationMemberEmail"] }); + log.debug("called with", { email }); + const organization = await OrganizationRepository.findByMemberEmail({ email }); + if (!organization) { + log.debug("Email not found in any organization:", email); + return null; + } + + const emailDomain = email.split("@")[1]; + const domainWideDelegation = await prisma.domainWideDelegation.findUnique({ + where: { + organizationId_domain: { + organizationId: organization.id, + domain: emailDomain, + }, + }, + select: domainWideDelegationSafeSelect, + }); + + return domainWideDelegation; + } + + async findByUser({ user }: { user: { email: string } }) { + return await this.findUniqueByOrganizationMemberEmail({ email: user.email }); + } + + static async findAllByDomain({ domain }: { domain: string }) { + return await prisma.domainWideDelegation.findMany({ + where: { domain }, + select: domainWideDelegationSafeSelect, + }); + } + + static async findFirstByOrganizationId({ organizationId }: { organizationId: number }) { + const domainWideDelegationEnabled = await getFeatureFlag(prisma, "domain-wide-delegation"); + if (!domainWideDelegationEnabled) { + return null; + } + + return await prisma.domainWideDelegation.findFirst({ + where: { organizationId }, + select: domainWideDelegationSafeSelect, + }); + } + + async updateById({ + id, + data, + }: { + id: string; + data: Partial<{ + workspacePlatformId: number; + domain: string; + enabled: boolean; + organizationId: number; + }>; + }) { + const { workspacePlatformId, organizationId, ...rest } = data; + return await prisma.domainWideDelegation.update({ + where: { id }, + data: { + ...(workspacePlatformId && { + workspacePlatform: { + connect: { + id: workspacePlatformId, + }, + }, + }), + ...(organizationId && { + organization: { + connect: { + id: organizationId, + }, + }, + }), + ...rest, + }, + select: domainWideDelegationSafeSelect, + }); + } + + async deleteById({ id }: { id: string }) { + return await prisma.domainWideDelegation.delete({ + where: { id }, + }); + } + + async findDelegationsWithServiceAccount({ organizationId }: { organizationId: number }) { + return await prisma.domainWideDelegation.findMany({ + where: { organizationId }, + select: { + ...domainWideDelegationSelectIncludesServiceAccountKey, + workspacePlatform: { + select: { + id: true, + name: true, + slug: true, + }, + }, + }, + }); + } +} diff --git a/packages/lib/server/repository/organization.ts b/packages/lib/server/repository/organization.ts index 333b921a07..dabe5d49ee 100644 --- a/packages/lib/server/repository/organization.ts +++ b/packages/lib/server/repository/organization.ts @@ -311,6 +311,39 @@ export class OrganizationRepository { return { ...org, metadata: parsedMetadata }; } + static async findByMemberEmail({ email }: { email: string }) { + const organization = await prisma.team.findFirst({ + where: { + isOrganization: true, + members: { + some: { + user: { email }, + }, + }, + }, + }); + return organization ?? null; + } + + static async findByMemberEmailId({ email }: { email: string }) { + const log = logger.getSubLogger({ prefix: ["findByMemberEmailId"] }); + log.debug("called with", { email }); + const organization = await prisma.team.findFirst({ + where: { + isOrganization: true, + members: { + some: { + user: { + email, + }, + }, + }, + }, + }); + + return organization; + } + static async findCalVideoLogoByOrgId({ id }: { id: number }) { const org = await prisma.team.findUnique({ where: { diff --git a/packages/lib/server/repository/workspacePlatform.ts b/packages/lib/server/repository/workspacePlatform.ts new file mode 100644 index 0000000000..1f6c6f9f80 --- /dev/null +++ b/packages/lib/server/repository/workspacePlatform.ts @@ -0,0 +1,93 @@ +import type { Prisma } from "@prisma/client"; + +import { prisma } from "@calcom/prisma"; +import type { TServiceAccountKeySchema } from "@calcom/prisma/zod-utils"; +import { serviceAccountKeySchema } from "@calcom/prisma/zod-utils"; + +const safeWorkspacePlatformSelect = { + id: true, + name: true, + enabled: true, + slug: true, + description: true, +}; + +const workspacePlatformSelectWithServiceAccountKey = { + ...safeWorkspacePlatformSelect, + defaultServiceAccountKey: true, +}; + +export class WorkspacePlatformRepository { + private static withParsedServiceAccountKey( + data: T + ) { + return { + ...data, + defaultServiceAccountKey: serviceAccountKeySchema.parse(data.defaultServiceAccountKey), + }; + } + + static async create(data: { + slug: string; + name: string; + description: string; + defaultServiceAccountKey: TServiceAccountKeySchema; + enabled: boolean; + }) { + return await prisma.workspacePlatform.create({ + data, + select: safeWorkspacePlatformSelect, + }); + } + + static async findAll() { + return await prisma.workspacePlatform.findMany({ + select: safeWorkspacePlatformSelect, + }); + } + + static async findAllBySlug({ slug }: { slug: string }) { + return await prisma.workspacePlatform.findMany({ + where: { slug }, + select: safeWorkspacePlatformSelect, + }); + } + + static async findBySlug({ slug }: { slug: string }) { + return await prisma.workspacePlatform.findUnique({ + where: { slug }, + select: safeWorkspacePlatformSelect, + }); + } + + static async findBySlugIncludeSensitiveServiceAccountKey({ slug }: { slug: string }) { + const workspacePlatform = await prisma.workspacePlatform.findUnique({ + where: { slug }, + select: workspacePlatformSelectWithServiceAccountKey, + }); + if (!workspacePlatform) { + return null; + } + return this.withParsedServiceAccountKey(workspacePlatform); + } + + static async updateById({ + id, + data, + }: { + id: number; + data: Partial<{ + slug: string; + name: string; + description: string; + defaultServiceAccountKey: TServiceAccountKeySchema; + enabled: boolean; + }>; + }) { + return await prisma.workspacePlatform.update({ + where: { id }, + data, + select: safeWorkspacePlatformSelect, + }); + } +} diff --git a/packages/prisma/migrations/20241205095738_add_feature_flag_domain_wide_delegation/migration.sql b/packages/prisma/migrations/20241205095738_add_feature_flag_domain_wide_delegation/migration.sql new file mode 100644 index 0000000000..62b4877041 --- /dev/null +++ b/packages/prisma/migrations/20241205095738_add_feature_flag_domain_wide_delegation/migration.sql @@ -0,0 +1,9 @@ +INSERT INTO + "Feature" (slug, enabled, description, "type") +VALUES + ( + 'domain-wide-delegation', + false, + 'Enable Google Workspace Domain-Wide Delegation - Allows system to act on behalf of Google Workspace users.', + 'OPERATIONAL' + ) ON CONFLICT (slug) DO NOTHING; diff --git a/packages/prisma/migrations/20241206131352_add_dwd/migration.sql b/packages/prisma/migrations/20241206131352_add_dwd/migration.sql new file mode 100644 index 0000000000..0c13e42166 --- /dev/null +++ b/packages/prisma/migrations/20241206131352_add_dwd/migration.sql @@ -0,0 +1,57 @@ +-- AlterTable +ALTER TABLE "BookingReference" ADD COLUMN "domainWideDelegationCredentialId" TEXT; + +-- AlterTable +ALTER TABLE "DestinationCalendar" ADD COLUMN "domainWideDelegationCredentialId" TEXT; + +-- AlterTable +ALTER TABLE "SelectedCalendar" ADD COLUMN "domainWideDelegationCredentialId" TEXT; + +-- CreateTable +CREATE TABLE "DomainWideDelegation" ( + "id" TEXT NOT NULL, + "workspacePlatformId" INTEGER NOT NULL, + "serviceAccountKey" JSONB NOT NULL, + "enabled" BOOLEAN NOT NULL DEFAULT false, + "organizationId" INTEGER NOT NULL, + "domain" TEXT NOT NULL, + "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP, + "updatedAt" TIMESTAMP(3) NOT NULL, + + CONSTRAINT "DomainWideDelegation_pkey" PRIMARY KEY ("id") +); + +-- CreateTable +CREATE TABLE "WorkspacePlatform" ( + "id" SERIAL NOT NULL, + "slug" TEXT NOT NULL, + "name" TEXT NOT NULL, + "description" TEXT NOT NULL, + "defaultServiceAccountKey" JSONB NOT NULL, + "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP, + "updatedAt" TIMESTAMP(3) NOT NULL, + "enabled" BOOLEAN NOT NULL DEFAULT false, + + CONSTRAINT "WorkspacePlatform_pkey" PRIMARY KEY ("id") +); + +-- CreateIndex +CREATE UNIQUE INDEX "DomainWideDelegation_organizationId_domain_key" ON "DomainWideDelegation"("organizationId", "domain"); + +-- CreateIndex +CREATE UNIQUE INDEX "WorkspacePlatform_slug_key" ON "WorkspacePlatform"("slug"); + +-- AddForeignKey +ALTER TABLE "DestinationCalendar" ADD CONSTRAINT "DestinationCalendar_domainWideDelegationCredentialId_fkey" FOREIGN KEY ("domainWideDelegationCredentialId") REFERENCES "DomainWideDelegation"("id") ON DELETE CASCADE ON UPDATE CASCADE; + +-- AddForeignKey +ALTER TABLE "BookingReference" ADD CONSTRAINT "BookingReference_domainWideDelegationCredentialId_fkey" FOREIGN KEY ("domainWideDelegationCredentialId") REFERENCES "DomainWideDelegation"("id") ON DELETE SET NULL ON UPDATE CASCADE; + +-- AddForeignKey +ALTER TABLE "SelectedCalendar" ADD CONSTRAINT "SelectedCalendar_domainWideDelegationCredentialId_fkey" FOREIGN KEY ("domainWideDelegationCredentialId") REFERENCES "DomainWideDelegation"("id") ON DELETE CASCADE ON UPDATE CASCADE; + +-- AddForeignKey +ALTER TABLE "DomainWideDelegation" ADD CONSTRAINT "DomainWideDelegation_workspacePlatformId_fkey" FOREIGN KEY ("workspacePlatformId") REFERENCES "WorkspacePlatform"("id") ON DELETE CASCADE ON UPDATE CASCADE; + +-- AddForeignKey +ALTER TABLE "DomainWideDelegation" ADD CONSTRAINT "DomainWideDelegation_organizationId_fkey" FOREIGN KEY ("organizationId") REFERENCES "Team"("id") ON DELETE CASCADE ON UPDATE CASCADE; diff --git a/packages/prisma/schema.prisma b/packages/prisma/schema.prisma index e72c7250e4..51cfd9f7f2 100644 --- a/packages/prisma/schema.prisma +++ b/packages/prisma/schema.prisma @@ -213,18 +213,20 @@ enum IdentityProvider { } model DestinationCalendar { - id Int @id @default(autoincrement()) - integration String - externalId String + id Int @id @default(autoincrement()) + integration String + externalId String /// @zod.custom(imports.emailSchema) - primaryEmail String? - user User? @relation(fields: [userId], references: [id], onDelete: Cascade) - userId Int? @unique - booking Booking[] - eventType EventType? @relation(fields: [eventTypeId], references: [id], onDelete: Cascade) - eventTypeId Int? @unique - credentialId Int? - credential Credential? @relation(fields: [credentialId], references: [id], onDelete: Cascade) + primaryEmail String? + user User? @relation(fields: [userId], references: [id], onDelete: Cascade) + userId Int? @unique + booking Booking[] + eventType EventType? @relation(fields: [eventTypeId], references: [id], onDelete: Cascade) + eventTypeId Int? @unique + credentialId Int? + credential Credential? @relation(fields: [credentialId], references: [id], onDelete: Cascade) + domainWideDelegation DomainWideDelegation? @relation(fields: [domainWideDelegationCredentialId], references: [id], onDelete: Cascade) + domainWideDelegationCredentialId String? @@index([userId]) @@index([eventTypeId]) @@ -463,6 +465,8 @@ model Team { activeOrgWorkflows WorkflowsOnTeams[] attributes Attribute[] smsLockReviewedByAdmin Boolean @default(false) + // Available for Organization only + domainWideDelegations DomainWideDelegation[] features TeamFeatures[] /// @zod.custom(imports.intervalLimitsType) @@ -567,8 +571,10 @@ model BookingReference { externalCalendarId String? deleted Boolean? - credential Credential? @relation(fields: [credentialId], references: [id], onDelete: SetNull) - credentialId Int? + credential Credential? @relation(fields: [credentialId], references: [id], onDelete: SetNull) + credentialId Int? + domainWideDelegation DomainWideDelegation? @relation(fields: [domainWideDelegationCredentialId], references: [id], onDelete: SetNull) + domainWideDelegationCredentialId String? @@index([bookingId]) @@index([type]) @@ -703,18 +709,20 @@ model Availability { } model SelectedCalendar { - user User @relation(fields: [userId], references: [id], onDelete: Cascade) - userId Int - integration String - externalId String - credential Credential? @relation(fields: [credentialId], references: [id], onDelete: Cascade) - credentialId Int? + user User @relation(fields: [userId], references: [id], onDelete: Cascade) + userId Int + integration String + externalId String + credential Credential? @relation(fields: [credentialId], references: [id], onDelete: Cascade) + credentialId Int? // Used to identify a watched calendar channel in Google Calendar - googleChannelId String? @unique - googleChannelKind String? - googleChannelResourceId String? - googleChannelResourceUri String? - googleChannelExpiration String? + googleChannelId String? @unique + googleChannelKind String? + googleChannelResourceId String? + googleChannelResourceUri String? + googleChannelExpiration String? + domainWideDelegationCredential DomainWideDelegation? @relation(fields: [domainWideDelegationCredentialId], references: [id], onDelete: Cascade) + domainWideDelegationCredentialId String? @@id([userId, integration, externalId]) @@index([userId]) @@ -1665,6 +1673,46 @@ enum EventTypeAutoTranslatedField { DESCRIPTION // Currently the only field we translate } +model DomainWideDelegation { + id String @id @default(uuid()) + workspacePlatform WorkspacePlatform @relation(fields: [workspacePlatformId], references: [id], onDelete: Cascade) + workspacePlatformId Int + // Provides possibility to have different service accounts for different organizations if the need arises, but normally they should be the same + /// @zod.custom(imports.serviceAccountKeySchema) + serviceAccountKey Json + enabled Boolean @default(false) + organizationId Int + organization Team @relation(fields: [organizationId], references: [id], onDelete: Cascade) + domain String + selectedCalendars SelectedCalendar[] + destinationCalendar DestinationCalendar[] + bookingReferences BookingReference[] + createdAt DateTime @default(now()) + updatedAt DateTime @updatedAt + + // Should be fair to assume that one domain can be only on one workspace platform at a time. So, one can't have two different workspace platforms for the same domain + // Because we don't know which domain the organization might have, we couldn't make "domain" unique here as that would prevent an actual owner of the domain to be unable to use that domain if it is used by someone else. + @@unique([organizationId, domain]) +} + +// It is for domain-wide delegation +model WorkspacePlatform { + id Int @id @default(autoincrement()) + /// @zod.min(1) + slug String + /// @zod.min(1) + name String + description String + /// @zod.custom(imports.serviceAccountKeySchema) + defaultServiceAccountKey Json + createdAt DateTime @default(now()) + updatedAt DateTime @updatedAt + enabled Boolean @default(false) + domainWideDelegations DomainWideDelegation[] + + @@unique([slug]) +} + model EventTypeTranslation { uid String @id @default(cuid()) eventType EventType @relation(fields: [eventTypeId], references: [id], onDelete: Cascade) diff --git a/packages/prisma/zod-utils.ts b/packages/prisma/zod-utils.ts index d0279e3480..f5268dca8c 100644 --- a/packages/prisma/zod-utils.ts +++ b/packages/prisma/zod-utils.ts @@ -777,4 +777,16 @@ export const bookingSeatDataSchema = z.object({ responses: bookingResponses, }); +export const serviceAccountKeySchema = z + .object({ + type: z.string(), + client_id: z.string(), + client_email: z.string(), + private_key: z.string(), + }) + // There could be more properties available here by the Workspace platform(e.g. Google), we don't want to loose them but don't need them also at the moment + .passthrough(); + +export type TServiceAccountKeySchema = z.infer; + export const rrSegmentQueryValueSchema = zodAttributesQueryValue.nullish(); diff --git a/packages/trpc/react/shared.ts b/packages/trpc/react/shared.ts index 7577b47e1e..5eb0a52e3f 100644 --- a/packages/trpc/react/shared.ts +++ b/packages/trpc/react/shared.ts @@ -31,4 +31,5 @@ export const ENDPOINTS = [ "oAuth", "attributes", "routingForms", + "domainWideDelegation", ] as const; diff --git a/packages/trpc/server/routers/viewer/_router.tsx b/packages/trpc/server/routers/viewer/_router.tsx index fb9ea91662..f0eaaee1cd 100644 --- a/packages/trpc/server/routers/viewer/_router.tsx +++ b/packages/trpc/server/routers/viewer/_router.tsx @@ -16,6 +16,7 @@ import { authRouter } from "./auth/_router"; import { availabilityRouter } from "./availability/_router"; import { bookingsRouter } from "./bookings/_router"; import { deploymentSetupRouter } from "./deploymentSetup/_router"; +import { domainWideDelegationRouter } from "./domainWideDelegation/_router"; import { dsyncRouter } from "./dsync/_router"; import { eventTypesRouter } from "./eventTypes/_router"; import { googleWorkspaceRouter } from "./googleWorkspace/_router"; @@ -44,6 +45,7 @@ export const viewerRouter = mergeRouters( teams: viewerTeamsRouter, timezones: timezonesRouter, organizations: viewerOrganizationsRouter, + domainWideDelegation: domainWideDelegationRouter, webhook: webhookRouter, apiKeys: apiKeysRouter, slots: slotsRouter, diff --git a/packages/trpc/server/routers/viewer/admin/_router.ts b/packages/trpc/server/routers/viewer/admin/_router.ts index d208a16b33..19113a00be 100644 --- a/packages/trpc/server/routers/viewer/admin/_router.ts +++ b/packages/trpc/server/routers/viewer/admin/_router.ts @@ -7,6 +7,12 @@ import { ZAdminRemoveTwoFactor } from "./removeTwoFactor.schema"; import { ZAdminPasswordResetSchema } from "./sendPasswordReset.schema"; import { ZSetSMSLockState } from "./setSMSLockState.schema"; import { toggleFeatureFlag } from "./toggleFeatureFlag.procedure"; +import { + workspacePlatformCreateSchema, + workspacePlatformUpdateSchema, + workspacePlatformUpdateServiceAccountSchema, + workspacePlatformToggleEnabledSchema, +} from "./workspacePlatform/schema"; const NAMESPACE = "admin"; @@ -62,4 +68,43 @@ export const adminRouter = router({ ); return handler(opts); }), + workspacePlatform: router({ + list: authedAdminProcedure.query(async () => { + const handler = await importHandler( + namespaced("workspacePlatforms.list"), + () => import("./workspacePlatform/list.handler") + ); + return handler(); + }), + add: authedAdminProcedure.input(workspacePlatformCreateSchema).mutation(async (opts) => { + const handler = await importHandler( + namespaced("workspacePlatforms.add"), + () => import("./workspacePlatform/add.handler") + ); + return handler(opts); + }), + update: authedAdminProcedure.input(workspacePlatformUpdateSchema).mutation(async (opts) => { + const handler = await importHandler( + namespaced("workspacePlatforms.update"), + () => import("./workspacePlatform/update.handler") + ); + return handler(opts); + }), + updateServiceAccount: authedAdminProcedure + .input(workspacePlatformUpdateServiceAccountSchema) + .mutation(async (opts) => { + const handler = await importHandler( + namespaced("workspacePlatforms.updateServiceAccount"), + () => import("./workspacePlatform/updateServiceAccount.handler") + ); + return handler(opts); + }), + toggleEnabled: authedAdminProcedure.input(workspacePlatformToggleEnabledSchema).mutation(async (opts) => { + const handler = await importHandler( + namespaced("workspacePlatforms.toggleEnabled"), + () => import("./workspacePlatform/toggleEnabled.handler") + ); + return handler(opts); + }), + }), }); diff --git a/packages/trpc/server/routers/viewer/admin/workspacePlatform/add.handler.ts b/packages/trpc/server/routers/viewer/admin/workspacePlatform/add.handler.ts new file mode 100644 index 0000000000..07fe5ee263 --- /dev/null +++ b/packages/trpc/server/routers/viewer/admin/workspacePlatform/add.handler.ts @@ -0,0 +1,23 @@ +import type { z } from "zod"; + +import logger from "@calcom/lib/logger"; +import { WorkspacePlatformRepository } from "@calcom/lib/server/repository/workspacePlatform"; + +import { TRPCError } from "@trpc/server"; + +import type { workspacePlatformCreateSchema } from "./schema"; +import { ensureNoServiceAccountKey } from "./utils"; + +export default async function addHandler({ + input, +}: { + input: z.infer; +}) { + try { + const workspacePlatform = await WorkspacePlatformRepository.create(input); + return ensureNoServiceAccountKey(workspacePlatform); + } catch (error) { + logger.error(error); + throw new TRPCError({ code: "INTERNAL_SERVER_ERROR", message: "Failed to add workspace platform" }); + } +} diff --git a/packages/trpc/server/routers/viewer/admin/workspacePlatform/list.handler.ts b/packages/trpc/server/routers/viewer/admin/workspacePlatform/list.handler.ts new file mode 100644 index 0000000000..4071f6dddf --- /dev/null +++ b/packages/trpc/server/routers/viewer/admin/workspacePlatform/list.handler.ts @@ -0,0 +1,15 @@ +import { WorkspacePlatformRepository } from "@calcom/lib/server/repository/workspacePlatform"; + +import { TRPCError } from "@trpc/server"; + +import { ensureNoServiceAccountKey } from "./utils"; + +export default async function listHandler() { + try { + const workspacePlatforms = await WorkspacePlatformRepository.findAll(); + return workspacePlatforms.map(ensureNoServiceAccountKey); + } catch (error) { + console.error(error); + throw new TRPCError({ code: "INTERNAL_SERVER_ERROR", message: "Failed to fetch workspace platforms" }); + } +} diff --git a/packages/trpc/server/routers/viewer/admin/workspacePlatform/schema.ts b/packages/trpc/server/routers/viewer/admin/workspacePlatform/schema.ts new file mode 100644 index 0000000000..bed4ef7649 --- /dev/null +++ b/packages/trpc/server/routers/viewer/admin/workspacePlatform/schema.ts @@ -0,0 +1,27 @@ +import { z } from "zod"; + +import { serviceAccountKeySchema } from "@calcom/prisma/zod-utils"; + +export const workspacePlatformCreateSchema = z.object({ + slug: z.string().min(1), + name: z.string().min(1), + description: z.string().min(1), + defaultServiceAccountKey: serviceAccountKeySchema, + enabled: z.boolean().optional().default(true), +}); + +export const workspacePlatformUpdateSchema = z.object({ + id: z.number(), + name: z.string().min(1), + description: z.string().min(1), +}); + +export const workspacePlatformUpdateServiceAccountSchema = z.object({ + id: z.number(), + defaultServiceAccountKey: serviceAccountKeySchema, +}); + +export const workspacePlatformToggleEnabledSchema = z.object({ + id: z.number(), + enabled: z.boolean(), +}); diff --git a/packages/trpc/server/routers/viewer/admin/workspacePlatform/toggleEnabled.handler.ts b/packages/trpc/server/routers/viewer/admin/workspacePlatform/toggleEnabled.handler.ts new file mode 100644 index 0000000000..23d7a89f18 --- /dev/null +++ b/packages/trpc/server/routers/viewer/admin/workspacePlatform/toggleEnabled.handler.ts @@ -0,0 +1,21 @@ +import type { z } from "zod"; + +import { WorkspacePlatformRepository } from "@calcom/lib/server/repository/workspacePlatform"; + +import type { workspacePlatformToggleEnabledSchema } from "./schema"; +import { ensureNoServiceAccountKey } from "./utils"; + +export default async function toggleEnabledHandler({ + input, +}: { + input: z.infer; +}) { + const updatedWorkspacePlatform = await WorkspacePlatformRepository.updateById({ + id: input.id, + data: { + enabled: input.enabled, + }, + }); + + return ensureNoServiceAccountKey(updatedWorkspacePlatform); +} diff --git a/packages/trpc/server/routers/viewer/admin/workspacePlatform/update.handler.ts b/packages/trpc/server/routers/viewer/admin/workspacePlatform/update.handler.ts new file mode 100644 index 0000000000..daffe8b120 --- /dev/null +++ b/packages/trpc/server/routers/viewer/admin/workspacePlatform/update.handler.ts @@ -0,0 +1,29 @@ +import type { z } from "zod"; + +import { WorkspacePlatformRepository } from "@calcom/lib/server/repository/workspacePlatform"; + +import { TRPCError } from "@trpc/server"; + +import type { workspacePlatformUpdateSchema } from "./schema"; +import { ensureNoServiceAccountKey } from "./utils"; + +export default async function updateHandler({ + input, +}: { + input: z.infer; +}) { + try { + const updatedWorkspacePlatform = await WorkspacePlatformRepository.updateById({ + id: input.id, + data: { + name: input.name, + description: input.description, + }, + }); + + return ensureNoServiceAccountKey(updatedWorkspacePlatform); + } catch (error) { + console.error(error); + throw new TRPCError({ code: "INTERNAL_SERVER_ERROR", message: "Failed to update workspace platform" }); + } +} diff --git a/packages/trpc/server/routers/viewer/admin/workspacePlatform/updateServiceAccount.handler.ts b/packages/trpc/server/routers/viewer/admin/workspacePlatform/updateServiceAccount.handler.ts new file mode 100644 index 0000000000..bc6948b0d9 --- /dev/null +++ b/packages/trpc/server/routers/viewer/admin/workspacePlatform/updateServiceAccount.handler.ts @@ -0,0 +1,27 @@ +import type { z } from "zod"; + +import { WorkspacePlatformRepository } from "@calcom/lib/server/repository/workspacePlatform"; + +import { TRPCError } from "@trpc/server"; + +import type { workspacePlatformUpdateServiceAccountSchema } from "./schema"; +import { ensureNoServiceAccountKey } from "./utils"; + +export default async function updateServiceAccountHandler({ + input, +}: { + input: z.infer; +}) { + try { + const updatedWorkspacePlatform = await WorkspacePlatformRepository.updateById({ + id: input.id, + data: { + defaultServiceAccountKey: input.defaultServiceAccountKey, + }, + }); + return ensureNoServiceAccountKey(updatedWorkspacePlatform); + } catch (error) { + console.error(error); + throw new TRPCError({ code: "INTERNAL_SERVER_ERROR", message: "Failed to update service account" }); + } +} diff --git a/packages/trpc/server/routers/viewer/admin/workspacePlatform/utils.ts b/packages/trpc/server/routers/viewer/admin/workspacePlatform/utils.ts new file mode 100644 index 0000000000..5679025bc4 --- /dev/null +++ b/packages/trpc/server/routers/viewer/admin/workspacePlatform/utils.ts @@ -0,0 +1,9 @@ +export function ensureNoServiceAccountKey( + workspacePlatform: T +) { + const { defaultServiceAccountKey: _1, ...rest } = workspacePlatform; + return { + ...rest, + defaultServiceAccountKey: undefined, + }; +} diff --git a/packages/trpc/server/routers/viewer/domainWideDelegation/_router.ts b/packages/trpc/server/routers/viewer/domainWideDelegation/_router.ts new file mode 100644 index 0000000000..7c0002580f --- /dev/null +++ b/packages/trpc/server/routers/viewer/domainWideDelegation/_router.ts @@ -0,0 +1,46 @@ +import authedProcedure, { authedOrgAdminProcedure } from "../../../procedures/authedProcedure"; +import { router, importHandler } from "../../../trpc"; +import { + DomainWideDelegationCreateSchema, + DomainWideDelegationUpdateSchema, + DomainWideDelegationDeleteSchema, + DomainWideDelegationToggleEnabledSchema, +} from "./schema"; + +const NAMESPACE = "domainWideDelegation"; +const namespaced = (s: string) => `${NAMESPACE}.${s}`; + +export const domainWideDelegationRouter = router({ + list: authedOrgAdminProcedure.query(async (opts) => { + const handler = await importHandler(namespaced("list"), () => import("./list.handler")); + return handler(opts); + }), + update: authedOrgAdminProcedure.input(DomainWideDelegationUpdateSchema).mutation(async (opts) => { + const handler = await importHandler(namespaced("update"), () => import("./update.handler")); + return handler(opts); + }), + add: authedOrgAdminProcedure.input(DomainWideDelegationCreateSchema).mutation(async (opts) => { + const handler = await importHandler(namespaced("add"), () => import("./add.handler")); + return handler(opts); + }), + toggleEnabled: authedOrgAdminProcedure + .input(DomainWideDelegationToggleEnabledSchema) + .mutation(async (opts) => { + const handler = await importHandler( + namespaced("toggleEnabled"), + () => import("./toggleEnabled.handler") + ); + return handler(opts); + }), + delete: authedOrgAdminProcedure.input(DomainWideDelegationDeleteSchema).mutation(async (opts) => { + const handler = await importHandler(namespaced("delete"), () => import("./delete.handler")); + return handler(opts); + }), + listWorkspacePlatforms: authedProcedure.query(async () => { + const handler = await importHandler( + namespaced("listWorkspacePlatforms"), + () => import("./listWorkspacePlatforms.handler") + ); + return handler(); + }), +}); diff --git a/packages/trpc/server/routers/viewer/domainWideDelegation/add.handler.ts b/packages/trpc/server/routers/viewer/domainWideDelegation/add.handler.ts new file mode 100644 index 0000000000..f1812d9c87 --- /dev/null +++ b/packages/trpc/server/routers/viewer/domainWideDelegation/add.handler.ts @@ -0,0 +1,66 @@ +import type { z } from "zod"; + +import { DomainWideDelegation } from "@calcom/features/domain-wide-delegation/domain-wide-delegation"; +import { WorkspacePlatformRepository } from "@calcom/lib/server/repository/workspacePlatform"; + +import { TRPCError } from "@trpc/server"; + +import type { DomainWideDelegationCreateSchema } from "./schema"; +import { + ensureDomainWideDelegationNotAlreadyConfigured, + ensureNoServiceAccountKey, + handleDomainWideDelegationError, +} from "./utils"; + +export default async function handler({ + input, + ctx, +}: { + input: z.infer; + ctx: { user: { id: number; organizationId: number | null } }; +}) { + const { workspacePlatformSlug, domain } = input; + const { user } = ctx; + const { organizationId } = user; + + if (!organizationId) { + throw new TRPCError({ + code: "UNAUTHORIZED", + message: "You must be part of an organization to add a domain-wide delegation", + }); + } + + try { + const workspacePlatform = await WorkspacePlatformRepository.findBySlugIncludeSensitiveServiceAccountKey({ + slug: workspacePlatformSlug, + }); + + if (!workspacePlatform) { + throw new TRPCError({ + code: "NOT_FOUND", + message: `Workspace platform ${workspacePlatformSlug} not found`, + }); + } + + await ensureDomainWideDelegationNotAlreadyConfigured({ + domain, + currentOrganizationId: organizationId, + dwdBeingUpdatedId: null, + }); + + const domainWideDelegationRepository = await DomainWideDelegation.init(user.id, organizationId); + + const createdDelegation = await domainWideDelegationRepository.create({ + workspacePlatformId: workspacePlatform.id, + domain, + // We don't want to enable by default because enabling requires some checks to be completed and it has a separate flow. + enabled: false, + organizationId, + serviceAccountKey: workspacePlatform.defaultServiceAccountKey, + }); + + return ensureNoServiceAccountKey(createdDelegation); + } catch (error) { + handleDomainWideDelegationError(error); + } +} diff --git a/packages/trpc/server/routers/viewer/domainWideDelegation/delete.handler.ts b/packages/trpc/server/routers/viewer/domainWideDelegation/delete.handler.ts new file mode 100644 index 0000000000..85b5c9d6f8 --- /dev/null +++ b/packages/trpc/server/routers/viewer/domainWideDelegation/delete.handler.ts @@ -0,0 +1,23 @@ +import type z from "zod"; + +import { DomainWideDelegation } from "@calcom/features/domain-wide-delegation/domain-wide-delegation"; + +import type { DomainWideDelegationDeleteSchema } from "./schema"; + +export default async function handler({ + ctx, + input, +}: { + input: z.infer; + ctx: { user: { id: number; organizationId: number | null } }; +}) { + const { id } = input; + + const domainWideDelegationRepository = await DomainWideDelegation.init( + ctx.user.id, + ctx.user.organizationId + ); + await domainWideDelegationRepository.deleteById({ id }); + + return { id }; +} diff --git a/packages/trpc/server/routers/viewer/domainWideDelegation/list.handler.ts b/packages/trpc/server/routers/viewer/domainWideDelegation/list.handler.ts new file mode 100644 index 0000000000..ae1371084a --- /dev/null +++ b/packages/trpc/server/routers/viewer/domainWideDelegation/list.handler.ts @@ -0,0 +1,34 @@ +import { DomainWideDelegation } from "@calcom/features/domain-wide-delegation/domain-wide-delegation"; +import type { PrismaClient } from "@calcom/prisma"; +import { serviceAccountKeySchema } from "@calcom/prisma/zod-utils"; + +import { ensureNoServiceAccountKey } from "./utils"; + +export default async function handler({ + ctx, +}: { + ctx: { prisma: PrismaClient; user: { id: number; organization: { id: number | null } } }; +}) { + const { user } = ctx; + + const organizationId = user.organization?.id; + + if (!organizationId) { + throw new Error("You must be in an organization to list domain wide delegations"); + } + const domainWideDelegationRepository = await DomainWideDelegation.init(user.id, organizationId); + + const domainWideDelegations = await domainWideDelegationRepository.findDelegationsWithServiceAccount({ + organizationId, + }); + + return domainWideDelegations.map((delegation) => { + // Let's not parse the service account key here, we should be able to fix the item with the problem, so we always try to return the complete list + const serviceAccountKey = serviceAccountKeySchema.safeParse(delegation.serviceAccountKey); + + return ensureNoServiceAccountKey({ + ...delegation, + serviceAccountClientId: serviceAccountKey.success ? serviceAccountKey.data?.client_id ?? null : null, + }); + }); +} diff --git a/packages/trpc/server/routers/viewer/domainWideDelegation/listWorkspacePlatforms.handler.ts b/packages/trpc/server/routers/viewer/domainWideDelegation/listWorkspacePlatforms.handler.ts new file mode 100644 index 0000000000..712661dfee --- /dev/null +++ b/packages/trpc/server/routers/viewer/domainWideDelegation/listWorkspacePlatforms.handler.ts @@ -0,0 +1,7 @@ +import { WorkspacePlatformRepository } from "@calcom/lib/server/repository/workspacePlatform"; + +export default async function handler() { + const workspacePlatforms = await WorkspacePlatformRepository.findAll(); + + return workspacePlatforms; +} diff --git a/packages/trpc/server/routers/viewer/domainWideDelegation/schema.ts b/packages/trpc/server/routers/viewer/domainWideDelegation/schema.ts new file mode 100644 index 0000000000..29fda5aa31 --- /dev/null +++ b/packages/trpc/server/routers/viewer/domainWideDelegation/schema.ts @@ -0,0 +1,21 @@ +import { z } from "zod"; + +export const DomainWideDelegationCreateSchema = z.object({ + workspacePlatformSlug: z.string(), + domain: z.string(), +}); + +export const DomainWideDelegationUpdateSchema = z.object({ + id: z.string(), + workspacePlatformSlug: z.string(), + domain: z.string(), +}); + +export const DomainWideDelegationToggleEnabledSchema = z.object({ + id: z.string(), + enabled: z.boolean(), +}); + +export const DomainWideDelegationDeleteSchema = z.object({ + id: z.string(), +}); diff --git a/packages/trpc/server/routers/viewer/domainWideDelegation/toggleEnabled.handler.ts b/packages/trpc/server/routers/viewer/domainWideDelegation/toggleEnabled.handler.ts new file mode 100644 index 0000000000..a21cfafdb9 --- /dev/null +++ b/packages/trpc/server/routers/viewer/domainWideDelegation/toggleEnabled.handler.ts @@ -0,0 +1,59 @@ +import type { z } from "zod"; + +import { DomainWideDelegation } from "@calcom/features/domain-wide-delegation/domain-wide-delegation"; + +// import { checkIfSuccessfullyConfiguredInWorkspace } from "@calcom/lib/domainWideDelegation/server"; +import type { DomainWideDelegationToggleEnabledSchema } from "./schema"; +import { ensureNoServiceAccountKey } from "./utils"; + +const assertWorkspaceConfigured = async ({ + domainWideDelegationId, + user, +}: { + domainWideDelegationId: string; + user: { id: number; email: string; organizationId: number | null }; +}) => { + const domainWideDelegationRepository = await DomainWideDelegation.init(user.id, user.organizationId); + const domainWideDelegation = await domainWideDelegationRepository.findById({ id: domainWideDelegationId }); + if (!domainWideDelegation) { + throw new Error("Domain wide delegation not found"); + } + + // TODO: Uncomment later + // const isSuccessfullyConfigured = await checkIfSuccessfullyConfiguredInWorkspace({ + // domainWideDelegation, + // user, + // }); + + // if (!isSuccessfullyConfigured) { + // throw new Error("Workspace not successfully configured"); + // } +}; + +export default async function toggleEnabledHandler({ + ctx, + input, +}: { + ctx: { user: { id: number; email: string; organizationId: number | null } }; + input: z.infer; +}) { + const { user: loggedInUser } = ctx; + + if (input.enabled) { + await assertWorkspaceConfigured({ domainWideDelegationId: input.id, user: loggedInUser }); + } + + const domainWideDelegationRepository = await DomainWideDelegation.init( + loggedInUser.id, + loggedInUser.organizationId + ); + + const updatedDomainWideDelegation = await domainWideDelegationRepository.updateById({ + id: input.id, + data: { + enabled: input.enabled, + }, + }); + + return ensureNoServiceAccountKey(updatedDomainWideDelegation); +} diff --git a/packages/trpc/server/routers/viewer/domainWideDelegation/update.handler.ts b/packages/trpc/server/routers/viewer/domainWideDelegation/update.handler.ts new file mode 100644 index 0000000000..e8cab41fc5 --- /dev/null +++ b/packages/trpc/server/routers/viewer/domainWideDelegation/update.handler.ts @@ -0,0 +1,65 @@ +import type { z } from "zod"; + +import { DomainWideDelegation } from "@calcom/features/domain-wide-delegation/domain-wide-delegation"; +import { WorkspacePlatformRepository } from "@calcom/lib/server/repository/workspacePlatform"; +import { TRPCError } from "@calcom/trpc/server"; + +import type { DomainWideDelegationUpdateSchema } from "./schema"; +import { + ensureDomainWideDelegationNotAlreadyConfigured, + ensureNoServiceAccountKey, + handleDomainWideDelegationError, +} from "./utils"; + +export default async function handler({ + input, + ctx, +}: { + input: z.infer; + ctx: { user: { id: number; organizationId: number | null } }; +}) { + const { id, workspacePlatformSlug, domain } = input; + const { user } = ctx; + const { organizationId } = user; + + if (!organizationId) { + throw new TRPCError({ + code: "UNAUTHORIZED", + message: "You must be part of an organization to update a domain wide delegation", + }); + } + + await ensureDomainWideDelegationNotAlreadyConfigured({ + domain, + currentOrganizationId: organizationId, + dwdBeingUpdatedId: id, + }); + + try { + const workspacePlatform = await WorkspacePlatformRepository.findBySlugIncludeSensitiveServiceAccountKey({ + slug: workspacePlatformSlug, + }); + + if (!workspacePlatform) { + throw new TRPCError({ + code: "NOT_FOUND", + message: `Workspace platform ${workspacePlatformSlug} not found`, + }); + } + + const domainWideDelegationRepository = await DomainWideDelegation.init(user.id, organizationId); + + const updatedDelegation = await domainWideDelegationRepository.updateById({ + id, + data: { + workspacePlatformId: workspacePlatform.id, + domain, + organizationId, + }, + }); + + return ensureNoServiceAccountKey(updatedDelegation); + } catch (error) { + handleDomainWideDelegationError(error); + } +} diff --git a/packages/trpc/server/routers/viewer/domainWideDelegation/utils.ts b/packages/trpc/server/routers/viewer/domainWideDelegation/utils.ts new file mode 100644 index 0000000000..f0677b59d2 --- /dev/null +++ b/packages/trpc/server/routers/viewer/domainWideDelegation/utils.ts @@ -0,0 +1,106 @@ +import { z } from "zod"; + +import logger from "@calcom/lib/logger"; +import { safeStringify } from "@calcom/lib/safeStringify"; +import { DomainWideDelegationRepository } from "@calcom/lib/server/repository/domainWideDelegation"; +import type { Prisma } from "@calcom/prisma/client"; + +import { TRPCError } from "@trpc/server"; + +const log = logger.getSubLogger({ prefix: ["domainWideDelegation/utils"] }); +export class InvalidServiceAccountKeyError extends Error { + constructor(message: string) { + super(message); + this.name = "InvalidServiceAccountKeyError"; + } +} + +export async function ensureDomainWideDelegationNotAlreadyConfigured({ + domain, + currentOrganizationId, + dwdBeingUpdatedId, +}: { + domain: string; + currentOrganizationId: number; + dwdBeingUpdatedId: string | null; +}) { + const allDelegationsForDomain = await DomainWideDelegationRepository.findAllByDomain({ + domain, + }); + + const conflictingDelegationInCurrentOrg = allDelegationsForDomain.find( + (delegation) => delegation.organizationId === currentOrganizationId && delegation.id !== dwdBeingUpdatedId + ); + + if (conflictingDelegationInCurrentOrg) { + throw new TRPCError({ + code: "BAD_REQUEST", + message: `Your organization already has domain-wide delegation for ${conflictingDelegationInCurrentOrg.domain}`, + }); + } + + const differentOrgEnabledDelegations = allDelegationsForDomain.filter( + (delegation) => delegation.organizationId !== currentOrganizationId && delegation.enabled + ); + + if (differentOrgEnabledDelegations.length > 0) { + throw new TRPCError({ + code: "BAD_REQUEST", + message: `Domain ${domain} already has domain-wide delegation enabled in another organization`, + }); + } +} + +export function parseServiceAccountKey(serviceAccountKey: Prisma.JsonValue) { + if (!serviceAccountKey) { + return null; + } + const schema = z.object({ + client_id: z.string(), + private_key: z.string(), + client_email: z.string(), + }); + + const parsedServiceAccountKey = schema.safeParse(serviceAccountKey); + + if (!parsedServiceAccountKey.success) { + console.error("Invalid service account key", parsedServiceAccountKey.error); + throw new InvalidServiceAccountKeyError( + "Service account key must contain private_key, client_email and client_id" + ); + } + + return parsedServiceAccountKey.data; +} + +export const handleDomainWideDelegationError = (error: unknown) => { + if (error instanceof InvalidServiceAccountKeyError) { + throw new TRPCError({ + code: "BAD_REQUEST", + message: error.message, + }); + } + + if (error instanceof TRPCError) { + throw error; + } + + log.error("Error handling domain-wide delegation:", safeStringify(error)); + throw new TRPCError({ + code: "INTERNAL_SERVER_ERROR", + message: "An error occurred while handling domain-wide delegation settings.", + }); +}; + +export const ensureNoServiceAccountKey = ( + domainWideDelegation: T +) => { + if (!domainWideDelegation) { + return null; + } + const { serviceAccountKey: _1, ...rest } = domainWideDelegation; + return { + ...rest, + serviceAccountKey: undefined, + }; +}; diff --git a/packages/types/Calendar.d.ts b/packages/types/Calendar.d.ts index ea6af7dcf1..8e26fa20f9 100644 --- a/packages/types/Calendar.d.ts +++ b/packages/types/Calendar.d.ts @@ -217,6 +217,7 @@ export interface CalendarEvent { platformCancelUrl?: string | null; platformBookingUrl?: string | null; oneTimePassword?: string | null; + domainWideDelegationCredentialId?: string | null; } export interface EntryPoint {