Scheduling infrastructure for absolutely everyone.
feat: domain wide delegation UI (#18013)
Udit Takkarbe3e5801077f
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.tsxnew file mode 100644index 00000000000..ccf5f7cc140--- /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 (+ <SettingsHeader title={t("workspace_platforms")} description={t("workspace_platforms_description")}>+ <LicenseRequired>+ <WorkspacePlatformsPage />+ </LicenseRequired>+ </SettingsHeader>+ );+};++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.tsxnew file mode 100644index 00000000000..70bdaece4b2--- /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 (+ <SettingsHeader+ borderInShellHeader+ title={t("domain_wide_delegation")}+ description={t("domain_wide_delegation_description")}>+ <DomainWideDelegationList />+ </SettingsHeader>+ );+};++export default Page;diff --git a/apps/web/pages/api/trpc/domainWideDelegation/[trpc].ts b/apps/web/pages/api/trpc/domainWideDelegation/[trpc].tsnew file mode 100644index 00000000000..e3d6a0fd1b5--- /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.jsonindex 8999016efd7..fe250db4932 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.jsonindex fd7ed7332aa..5fe50438a9b 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.tsindex 72d9b95a291..87aab1cc2c1 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: "[email protected]",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: "[email protected]",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.tsnew file mode 100644index 00000000000..9c77dacc9f2--- /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<Prisma.JsonValue, null>;+ }): Promise<DomainWideDelegationSafeSelect | null>;++ findById(args: { id: string }): Promise<DomainWideDelegationSafeSelect | null>;++ findByIdIncludeSensitiveServiceAccountKey(args: {+ id: string;+ }): Promise<(DomainWideDelegationSafeSelect & { serviceAccountKey: any }) | null>;++ findUniqueByOrganizationMemberEmail(args: {+ email: string;+ }): Promise<DomainWideDelegationSafeSelect | null>;++ findByUser(args: { user: { email: string } }): Promise<DomainWideDelegationSafeSelect | null>;++ updateById(args: {+ id: string;+ data: Partial<{+ workspacePlatformId: number;+ domain: string;+ enabled: boolean;+ organizationId: number;+ }>;+ }): Promise<DomainWideDelegationSafeSelect | null>;++ deleteById(args: { id: string }): Promise<any>;++ 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.tsnew file mode 100644index 00000000000..dfdf7a63dc6--- /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.tsnew file mode 100644index 00000000000..a900466bad6--- /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<Prisma.JsonValue, null>;+ }) {+ 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.tsxnew file mode 100644index 00000000000..9d2a42a5f62--- /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 <ErrorState />;+ }++ if (isPending || !workspacePlatforms) return <LoadingState />;++ return (+ <>+ <PageContent+ workspacePlatforms={workspacePlatforms}+ onAdd={handleAdd}+ onEdit={handleEdit}+ onToggle={handleToggle}+ />+ {editing.editType === "meta" && (+ <CreateUpdatePlatformDialog+ isOpen={isDialogOpen}+ onOpenChange={setIsDialogOpen}+ editingPlatform={editing.platform || undefined}+ key={editing.platform?.id}+ />+ )}+ {editing.editType === "serviceAccount" && (+ <UpdateServiceAccountFieldsDialog+ isOpen={isDialogOpen}+ onOpenChange={setIsDialogOpen}+ platformId={editing.platform?.id}+ />+ )}+ </>+ );++ 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 <div>{t("loading")}...</div>;+}++function ErrorState() {+ const { t } = useLocale();+ return <div>{t("something_went_wrong")}</div>;+}++function PageContent({+ workspacePlatforms,+ onAdd,+ onEdit,+ onToggle,+}: Pick<Props, "workspacePlatforms" | "onAdd" | "onEdit" | "onToggle">) {+ return (+ <div>+ {workspacePlatforms.length === 0 ? (+ <EmptyState onAdd={onAdd} />+ ) : (+ <PlatformList platforms={workspacePlatforms} onEdit={onEdit} onToggle={onToggle} onAdd={onAdd} />+ )}+ </div>+ );+}++function EmptyState({ onAdd }: Pick<Props, "onAdd">) {+ const { t } = useLocale();++ return (+ <div className="flex flex-col items-center justify-center space-y-4 py-10">+ <p className="text-gray-500">{t("no_workspace_platforms")}</p>+ <Button color="secondary" onClick={onAdd}>+ {t("add")}+ </Button>+ </div>+ );+}++function PlatformList({+ platforms,+ onEdit,+ onToggle,+ onAdd,+}: Pick<Props, "platforms" | "onEdit" | "onToggle" | "onAdd">) {+ const { t } = useLocale();++ return (+ <>+ <Table>+ <Header>+ <ColumnTitle widthClassNames="w-1/4">{t("platform")}</ColumnTitle>+ <ColumnTitle widthClassNames="w-1/4">{t("slug")}</ColumnTitle>+ <ColumnTitle widthClassNames="w-1/4">{t("status")}</ColumnTitle>+ <ColumnTitle widthClassNames="w-1/4">+ <span className="sr-only">{t("actions")}</span>+ </ColumnTitle>+ </Header>+ <Body>+ {platforms.map((platform) => (+ <PlatformListItem key={platform.id} platform={platform} onEdit={onEdit} onToggle={onToggle} />+ ))}+ </Body>+ </Table>+ <div className="mt-4 flex justify-end">+ <Button color="secondary" onClick={onAdd}>+ {t("add")}+ </Button>+ </div>+ </>+ );+}++function ServiceAccountFields() {+ const { t } = useLocale();+ const form = useFormContext();++ return (+ <div className="space-y-4">+ <TextAreaField+ required+ label={t("service_account_key")}+ {...form.register("defaultServiceAccountKey")}+ />+ </div>+ );+}++function UpdateServiceAccountFieldsDialog({+ isOpen,+ onOpenChange,+ platformId,+}: Pick<Props, "isOpen" | "onOpenChange" | "platformId">) {+ const { t } = useLocale();+ const utils = trpc.useUtils();+ type FormValues = { defaultServiceAccountKey: string };+ const form = useForm<FormValues>({+ 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<FormValues> = (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 (+ <Dialog open={isOpen} onOpenChange={onOpenChange}>+ <DialogContent title={t("edit_service_account_key")}>+ <Form form={form} handleSubmit={onSubmit}>+ <ServiceAccountFields />+ <DialogFooter>+ <Button type="button" color="minimal" onClick={() => onOpenChange(false)}>+ {t("cancel")}+ </Button>+ <Button type="submit" loading={updateServiceAccountMutation.isPending}>+ {t("update")}+ </Button>+ </DialogFooter>+ </Form>+ </DialogContent>+ </Dialog>+ );+}++function PlatformListItem({ platform, onEdit, onToggle }: Pick<Props, "platform" | "onEdit" | "onToggle">) {+ const { t } = useLocale();++ return (+ <Row>+ <Cell>+ <div className="text-subtle font-medium">+ <span className="text-default">{platform.name}</span>+ </div>+ </Cell>+ <Cell>+ <div className="text-subtle font-medium">+ <span className="text-muted">{platform.slug}</span>+ </div>+ </Cell>+ <Cell>+ <Switch checked={platform.enabled} onCheckedChange={(checked) => onToggle(platform, checked)} />+ </Cell>+ <Cell>+ <div className="flex justify-end">+ <DropdownActions+ actions={[+ {+ id: "edit",+ label: t("edit"),+ onClick: () => onEdit(platform, "meta"),+ icon: "pencil",+ },+ {+ id: "edit-service-account",+ label: t("edit_service_account"),+ onClick: () => onEdit(platform, "serviceAccount"),+ icon: "pencil",+ },+ ]}+ />+ </div>+ </Cell>+ </Row>+ );+}++function CreatePlatformDialog({ isOpen, onOpenChange }: Pick<Props, "isOpen" | "onOpenChange">) {+ const { t } = useLocale();+ type FormValues = { name: string; description: string; slug: string; defaultServiceAccountKey: string };+ const form = useForm<FormValues>({+ 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<FormValues> = (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 (+ <Dialog open={isOpen} onOpenChange={onOpenChange}>+ <DialogContent enableOverflow title={t("add_workspace_platform")}>+ <Form form={form} handleSubmit={onSubmit}>+ <PlatformFormFields isCreate={true} />+ <DialogFooter>+ <DialogClose />+ <Button type="submit">{t("create")}</Button>+ </DialogFooter>+ </Form>+ </DialogContent>+ </Dialog>+ );+}++function UpdatePlatformDialog({+ isOpen,+ onOpenChange,+ editingPlatform,+}: Pick<Props, "isOpen" | "onOpenChange" | "editingPlatform">) {+ const { t } = useLocale();+ type FormValues = { name: string; description: string };+ const form = useForm<FormValues>({+ 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<FormValues> = (values) => {+ updateMutation.mutate({ ...values, id: editingPlatform.id });+ };++ return (+ <Dialog open={isOpen} onOpenChange={onOpenChange}>+ <DialogContent title={t("edit_workspace_platform")}>+ <Form form={form} handleSubmit={onSubmit}>+ <PlatformFormFields isCreate={false} />+ <DialogFooter>+ <DialogClose />+ <Button type="submit">{t("save")}</Button>+ </DialogFooter>+ </Form>+ </DialogContent>+ </Dialog>+ );+}++function PlatformFormFields({ isCreate }: Pick<Props, "isCreate">) {+ const { t } = useLocale();+ const form = useFormContext();++ return (+ <div className="space-y-4">+ <TextField required label={t("name")} {...form.register("name")} />+ <TextAreaField required label={t("description")} {...form.register("description")} />+ {isCreate && <TextField required label={t("slug")} {...form.register("slug")} />}+ {isCreate && <ServiceAccountFields />}+ </div>+ );+}++function CreateUpdatePlatformDialog({+ isOpen,+ onOpenChange,+ editingPlatform,+}: Pick<Props, "isOpen" | "onOpenChange"> & { editingPlatform?: Props["editingPlatform"] }) {+ if (editingPlatform) {+ return (+ <UpdatePlatformDialog isOpen={isOpen} onOpenChange={onOpenChange} editingPlatform={editingPlatform} />+ );+ }+ return <CreatePlatformDialog isOpen={isOpen} onOpenChange={onOpenChange} />;+}++export default WorkspacePlatformsPage;diff --git a/packages/features/ee/organizations/pages/settings/domainWideDelegation.tsx b/packages/features/ee/organizations/pages/settings/domainWideDelegation.tsxnew file mode 100644index 00000000000..500ee066be9--- /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 (+ <SkeletonContainer>+ <div className="divide-subtle border-subtle space-y-6 rounded-b-lg border border-t-0 px-6 py-4">+ <SkeletonText className="h-8 w-full" />+ <SkeletonText className="h-8 w-full" />+ </div>+ </SkeletonContainer>+ );+};++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 (+ <div className="flex items-center space-x-2">+ <Switch checked={delegation.enabled} onCheckedChange={() => toggleDelegation(delegation)} />+ <DropdownActions+ actions={[+ {+ id: "edit",+ label: t("edit"),+ onClick: () => onEdit(delegation),+ icon: "pencil",+ },+ {+ id: "delete",+ label: t("delete"),+ onClick: () => onDelete(delegation.id),+ icon: "trash",+ },+ ]}+ />+ </div>+ );+}++function DelegationListItem({ delegation, toggleDelegation, onEdit, onDelete }: DelegationItemProps) {+ const { t } = useLocale();+ return (+ <li className="border-subtle bg-default divide-subtle flex flex-col divide-y border">+ <div className="flex items-center justify-between space-x-2 p-4">+ <div className="flex flex-col items-start">+ <div className="flex items-center space-x-2">+ <span>{delegation.serviceAccountClientId}</span>+ <InfoBadge content={t("add_client_id_in_google_workspace_with_below_scope")} />+ </div>+ <span className="text-muted mt-2">https://www.googleapis.com/auth/calendar</span>+ <div className="mt-2 flex items-center space-x-2">+ <Badge variant="default">{delegation.workspacePlatform.name}</Badge>+ <Badge variant="gray">{delegation.domain}</Badge>+ </div>+ </div>+ <DelegationListItemActions+ delegation={delegation}+ toggleDelegation={toggleDelegation}+ onEdit={onEdit}+ onDelete={onDelete}+ />+ </div>+ </li>+ );+}++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 (+ <Dialog open={isOpen} onOpenChange={onClose}>+ <DialogContent enableOverflow title={t("add_domain_wide_delegation")}>+ <Form form={form} handleSubmit={onSubmit}>+ <DelegationFormFields workspacePlatforms={workspacePlatforms} />+ <DialogFooter>+ <Button type="button" color="secondary" onClick={onClose}>+ {t("cancel")}+ </Button>+ <Button type="submit">{t("create")}</Button>+ </DialogFooter>+ </Form>+ </DialogContent>+ </Dialog>+ );+}++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 (+ <Dialog open={isOpen} onOpenChange={onClose}>+ <DialogContent title={t("edit_domain_wide_delegation")}>+ <Form form={form} handleSubmit={onSubmit}>+ <DelegationFormFields workspacePlatforms={workspacePlatforms} />+ <DialogFooter>+ <Button type="button" color="secondary" onClick={onClose}>+ {t("cancel")}+ </Button>+ <Button type="submit">{t("update")}</Button>+ </DialogFooter>+ </Form>+ </DialogContent>+ </Dialog>+ );+}++function DelegationFormFields({ workspacePlatforms }: { workspacePlatforms: WorkspacePlatform[] }) {+ const { t } = useLocale();+ const form = useFormContext();+ return (+ <div className="space-y-4">+ <TextField label={t("domain")} {...form.register("domain")} />+ <Controller+ name="workspacePlatformSlug"+ control={form.control}+ render={({ field: { value, onChange } }) => {+ const platformOptions = getWorkspacePlatformOptions(workspacePlatforms);+ const selectedPlatform = platformOptions.find((opt) => opt.value === value);+ return (+ <SelectField+ required+ label={t("workspace_platform")}+ onChange={(option) => onChange(option?.value)}+ value={selectedPlatform}+ options={platformOptions}+ />+ );+ }}+ />+ </div>+ );+}++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 (+ <EditDelegationDialog+ isOpen={isOpen}+ onClose={onClose}+ delegation={delegation}+ onSubmit={onSubmit}+ workspacePlatforms={workspacePlatforms}+ />+ );+ }+ return (+ <CreateDelegationDialog+ isOpen={isOpen}+ onClose={onClose}+ onSubmit={onSubmit}+ workspacePlatforms={workspacePlatforms}+ />+ );+}++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 (+ <Button type="button" color="secondary" StartIcon="plus" className="mt-6" onClick={onCreateClick}>+ {t("add_domain_wide_delegation")}+ </Button>+ );+ };++ if (isLoading || isLoadingWorkspacePlatforms) {+ return <SkeletonLoader />;+ }++ if (error) {+ return <div>{t(error.message)}</div>;+ }++ if (!delegations || !workspacePlatforms) {+ return <div>{t("something_went_wrong")}</div>;+ }++ return (+ <div>+ {!!delegations?.length ? (+ <>+ <ul className="space-y-2 [&>*:last-child]:rounded-b-xl">+ {delegations.map(+ (delegation) =>+ delegation && (+ <DelegationListItem+ key={delegation.id}+ delegation={delegation}+ toggleDelegation={toggleDelegation}+ onEdit={onEditClick}+ onDelete={onDelete}+ />+ )+ )}+ </ul>+ <AddDwDButton />+ </>+ ) : (+ <EmptyScreen+ Icon="link"+ headline={t("add_domain_wide_delegation")}+ description={t("domain_wide_delegation_description")}+ className="rounded-b-lg rounded-t-none border-t-0"+ buttonRaw={<AddDwDButton />}+ />+ )}++ <CreateEditDelegationDialog+ isOpen={createEditDialog.isOpen}+ onClose={() => setCreateEditDialog({ isOpen: false, delegation: null })}+ delegation={createEditDialog.delegation}+ onSubmit={handleSubmit}+ workspacePlatforms={enabledWorkspacePlatforms}+ />+ </div>+ );+}++export default function DomainWideDelegationListPage() {+ return <DomainWideDelegationList />;+}diff --git a/packages/features/flags/config.ts b/packages/features/flags/config.tsindex 4530f87703c..e271a6ea5a6 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.tsindex 582fb0e012d..c32e6b682a2 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.tsxindex a97aab7d99c..dcc3a8135b5 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.tsxindex be6323aadd1..757f543f08b 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.tsindex ede1d436f18..247fd6594ee 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.tsnew file mode 100644index 00000000000..47f530a35fe--- /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<typeof serviceAccountKeySchema>;++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<T extends { serviceAccountKey: Prisma.JsonValue } | null>(+ 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<Prisma.JsonValue, null>;+ }) {+ 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.tsindex 333b921a074..dabe5d49ee5 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.tsnew file mode 100644index 00000000000..1f6c6f9f80a--- /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<T extends { defaultServiceAccountKey: Prisma.JsonValue }>(+ 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.sqlnew file mode 100644index 00000000000..62b48770415--- /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.sqlnew file mode 100644index 00000000000..0c13e42166c--- /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.prismaindex e72c7250e40..51cfd9f7f2a 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.tsindex d0279e34805..f5268dca8cb 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<typeof serviceAccountKeySchema>;+export const rrSegmentQueryValueSchema = zodAttributesQueryValue.nullish();diff --git a/packages/trpc/react/shared.ts b/packages/trpc/react/shared.tsindex 7577b47e1ec..5eb0a52e3fd 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.tsxindex fb9ea916624..f0eaaee1cd1 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.tsindex d208a16b339..19113a00bea 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.tsnew file mode 100644index 00000000000..07fe5ee2635--- /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<typeof workspacePlatformCreateSchema>;+}) {+ 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.tsnew file mode 100644index 00000000000..4071f6dddfb--- /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.tsnew file mode 100644index 00000000000..bed4ef7649c--- /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.tsnew file mode 100644index 00000000000..23d7a89f181--- /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<typeof workspacePlatformToggleEnabledSchema>;+}) {+ 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.tsnew file mode 100644index 00000000000..daffe8b1204--- /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<typeof workspacePlatformUpdateSchema>;+}) {+ 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.tsnew file mode 100644index 00000000000..bc6948b0d95--- /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<typeof workspacePlatformUpdateServiceAccountSchema>;+}) {+ 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.tsnew file mode 100644index 00000000000..5679025bc4c--- /dev/null+++ b/packages/trpc/server/routers/viewer/admin/workspacePlatform/utils.ts@@ -0,0 +1,9 @@+export function ensureNoServiceAccountKey<T extends { id: number; defaultServiceAccountKey?: unknown }>(+ 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.tsnew file mode 100644index 00000000000..7c0002580fd--- /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.tsnew file mode 100644index 00000000000..f1812d9c871--- /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<typeof DomainWideDelegationCreateSchema>;+ 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.tsnew file mode 100644index 00000000000..85b5c9d6f8d--- /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<typeof DomainWideDelegationDeleteSchema>;+ 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.tsnew file mode 100644index 00000000000..ae1371084a1--- /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.tsnew file mode 100644index 00000000000..712661dfeec--- /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.tsnew file mode 100644index 00000000000..29fda5aa31f--- /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.tsnew file mode 100644index 00000000000..a21cfafdb9a--- /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<typeof DomainWideDelegationToggleEnabledSchema>;+}) {+ 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.tsnew file mode 100644index 00000000000..e8cab41fc5f--- /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<typeof DomainWideDelegationUpdateSchema>;+ 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.tsnew file mode 100644index 00000000000..f0677b59d24--- /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 = <T extends { id: string; serviceAccountKey?: unknown } | null>(+ 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.tsindex ea6af7dcf14..8e26fa20f92 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 {