feat: add OAuth client developer settings page with approval workflow (#25556)
* feat: add OAuth client developer settings page with approval workflow - Add new developer OAuth page at /settings/developer/oAuth for users to submit OAuth client requests - Transform admin OAuth page into management dashboard for reviewing/approving submissions - Add OAuthClientApprovalStatus enum (PENDING, APPROVED, REJECTED) to track submission status - Add userId and createdAt fields to OAuthClient model for tracking submissions - Create email notifications for admin (new submission) and user (approval) - Add sidebar navigation link in developer section below API keys - Add comprehensive translations for new UI strings - Create OAuthClientRepository for data access following repository pattern Co-Authored-By: [email protected] <[email protected]> * fix: re-export generateSecret for backward compatibility Co-Authored-By: [email protected] <[email protected]> * feat: make logo mandatory and list items clickable for OAuth clients Co-Authored-By: [email protected] <[email protected]> * fix: add missing translation keys and remove client secret from details dialog Co-Authored-By: [email protected] <[email protected]> * fix: address cubic AI reviewer comments - Remove duplicate 'there' JSON key in common.json - Add select clause to findByUserId to avoid exposing clientSecret - Add @@index([userId]) to OAuthClient model for query performance - Update migration to include the index Co-Authored-By: [email protected] <[email protected]> * fix: address PR review comments - fix indentation and use useCopy hook Co-Authored-By: [email protected] <[email protected]> * fix: change react-dom/server import to fix Turbopack compatibility Co-Authored-By: [email protected] <[email protected]> * Revert "fix: change react-dom/server import to fix Turbopack compatibility" This reverts commit c3e0b709c2d88fd221143cb4ce9cd25bb8c94277. * fix: use email service pattern for OAuth client notifications Co-Authored-By: [email protected] <[email protected]> * fix: add try-catch around email sending to handle Turbopack react-dom/server issue Co-Authored-By: [email protected] <[email protected]> * Revert "fix: add try-catch around email sending to handle Turbopack react-dom/server issue" This reverts commit fc9d47cd773505ebc5ee2696718aad4a8a98be77. * fix: improve OAuth client UI with skeleton loaders and smaller dialog styling - Replace 'Loading...' text with proper skeleton loaders in both developer and admin OAuth client views - Make client_id and copy button smaller in dialogs using size='sm' and text-sm styling - Add 'client_id' translation key to common.json for proper i18n Co-Authored-By: [email protected] <[email protected]> * fix: improve skeleton loader to match actual OAuth client list structure - Remove divide-y from container and use conditional border-b on rows - Match the exact structure from oauth-clients-view.tsx L126-160 - Use proper spacing for text elements (mt-1 instead of space-y-2) Co-Authored-By: [email protected] <[email protected]> * fix skeleton * rename the selected oauth client dialog * fix: address PR feedback - admin auth, dropdown styling, sidebar label - Add defense-in-depth admin authorization check in updateClientStatus handler - Fix broken dropdown menu by using DropdownItem with StartIcon prop - Fix sidebar menu label from 'oAuth' to 'oauth_clients' to match developer view Co-Authored-By: [email protected] <[email protected]> * update common.json * feat: show client secret in approval email for confidential OAuth clients - Add regenerateSecret method to OAuthClientRepository - Regenerate secret when admin approves a PENDING confidential client - Include client secret in approval notification email - Add one-time warning message about storing the secret securely - Only regenerate on first approval (not re-approvals) Co-Authored-By: [email protected] <[email protected]> * feat: add Website URL field, fix logo styling, show client secret after approval - Add Website URL field to OAuth client forms (admin and developer views) - Fix Upload Logo section styling by wrapping in Label div with proper gap - Display client secret in dialog after admin approves a confidential OAuth client - Add websiteUrl field to Prisma schema with migration - Update tRPC handlers and repository to support websiteUrl - Add translation keys for new UI elements Co-Authored-By: [email protected] <[email protected]> * fix: move clientSecret variable declaration outside if block for proper scoping Co-Authored-By: [email protected] <[email protected]> * refactor: dont expose client secret in emails * refactor: dont regenerate secret upon status change * refactor: reuse existing hash function * refactor: rename admin/oAuth to admin/oauth page * refactor: deduplicate oauth repositories * refactor: remove withGlobalPrisma from oauth repository * refactor: developer oauth page * refactor: oauth status by default accepted * refactor: request oauth status when creating * refactor ux * fix: address Cubic AI code review feedback - Add purpose field to plain text email body for accessibility - Convert NewOAuthClientButton to inline JSX to avoid React anti-pattern - Trigger re-approval when redirectUri changes for security - Add e.preventDefault() for Space key to prevent page scroll - Change default approvalStatus to PENDING for defense-in-depth - Use oauth_clients translation key for consistency - Add meaningful alt text to Avatar for accessibility - Remove onClick from DialogClose to prevent double-run close effects - Return NOT_FOUND for non-owner delete to prevent resource enumeration Co-Authored-By: unknown <> * common.json file * refactor: delete all prisma migrations * refactor: have just 1 prisma migration * revert: some devin changes * fix: typecheck * test: owner OAuth crud * test: admin OAuth approval / rejection * fix: address Cubic AI review feedback (confidence 9/10 issues) - schema.prisma: Remove @default("") from purpose field to make it required - schema.prisma: Use UTC-aware timezone expression for createdAt default - OAuthClientFormFields.tsx: Localize redirect URI placeholder using t() - common.json: Add redirect_uri_placeholder translation key Co-Authored-By: unknown <> * cubic changes * refactor: dont log sensitive info and rethrow error * cubic feedback * refactor: make oauth client purpose optional * refactor: admin/oauth not allowed if not logged in * refactor: admin view skeleton * refactor: rename state * refactor: get rid of redundant mapping * refactor: remove redundant handler * refactor: remove redundant handler * refactor: re-usable new oauth client button * refactor: dialogs * refactor: modals * refactor: handler names, dialog, skeleton * fix: purpose being null * refactor: rename handler and delete old oauth admin page * fix: purpose in submission * refactor: handler names * refactor: rename * refactor: update handler * refactor: rename approvalStatus -> status * refactor: simplify modal * refactor: name * dont require repproval if redirectUri changes * fix: remove integration sync index creation * refactor: require re-approval if redirectUri updated * fix: flaky e2e test * fix: flaky e2e test * fix: flaky e2e test * fix: remove duplicate common.json keys * refactor: replace [email protected] with SUPPORT_MAIL_ADDRESS * refactor: generate client secret on handler level * fix: authorization code only available to approved clients * refactor: cubic review dont display exclamation * refactor: cubic review website_url in common json * fix: dont default in ui to approved status * refactor: optiona logo in schema create handler * fix: tests * fix: tests * fix: /authorize redirect if client not approved or show error * test: authorize page with invalid client id * refactor: dont allow refreshing tokens unless approved client * fix: flaky e2e test * fix: flaky e2e test * fix: flaky e2e test * fix: flaky e2e test * fix: flaky e2e test * fix: flaky e2e test * chore: warn that pending client is not usable * fix: approve and reject buttons * fix: /authorize show error if client not approved * refactor: info message about editing oauth client and status * change info alert to warning * try to fix ci test * debug: failing e2e test * fix: improve session propagation in oauth-client-admin E2E test - Add navigateToAdminOAuthPage helper that waits for listClients API call - If the API call doesn't arrive (session issue), reload page to force session refresh - This fixes the CI flakiness where admin page wasn't loading due to session not having ADMIN role Co-Authored-By: [email protected] <[email protected]> * fix: register waitForResponse before navigating in E2E test - Register the listClients waitForResponse promise BEFORE page.goto() - This ensures the response isn't missed during page load - Also register the promise before reload in the catch block Co-Authored-By: [email protected] <[email protected]> * fix: rename oAuth folder to oauth for case-sensitive filesystems The admin OAuth page route was at /settings/admin/oAuth (capital A) but the code references /settings/admin/oauth (lowercase). This caused 404 errors on case-sensitive filesystems (Linux). Also improved the E2E test navigation helper to retry with delays if the admin page doesn't load immediately, handling session propagation timing. Co-Authored-By: [email protected] <[email protected]> * test style --------- Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> Co-authored-by: [email protected] <[email protected]> Co-authored-by: Lauris Skraucis <[email protected]> Co-authored-by: supalarry <[email protected]> Co-authored-by: cubic-dev-ai[bot] <1082092+cubic-dev-ai[bot]@users.noreply.github.com> Co-authored-by: CarinaWolli <[email protected]> Co-authored-by: [email protected] <[email protected]> Co-authored-by: Morgan <[email protected]>
This commit is contained in:
60 files changed
+5231
-368
No files matched your search
@@ -0,0 +1,33 @@
|
||||
import type BaseEmail from "@calcom/emails/templates/_base-email";
|
||||
|
||||
import type { OAuthClientNotification } from "./templates/admin-oauth-client-notification";
|
||||
import AdminOAuthClientNotification from "./templates/admin-oauth-client-notification";
|
||||
import type { OAuthClientApprovedNotification } from "./templates/oauth-client-approved-notification";
|
||||
import OAuthClientApprovedEmail from "./templates/oauth-client-approved-notification";
|
||||
import type { OAuthClientRejectedNotification } from "./templates/oauth-client-rejected-notification";
|
||||
import OAuthClientRejectedEmail from "./templates/oauth-client-rejected-notification";
|
||||
|
||||
const sendEmail = async (prepare: () => BaseEmail) => {
|
||||
let email: BaseEmail | undefined;
|
||||
|
||||
try {
|
||||
email = prepare();
|
||||
return await email.sendEmail();
|
||||
} catch (e) {
|
||||
const errorName = e instanceof Error ? e.name : "UnknownError";
|
||||
console.error(`${email?.constructor?.name ?? "Email"}.sendEmail oauth-email-service failed (${errorName})`, e);
|
||||
throw e;
|
||||
}
|
||||
};
|
||||
|
||||
export const sendAdminOAuthClientNotification = async (input: OAuthClientNotification) => {
|
||||
await sendEmail(() => new AdminOAuthClientNotification(input));
|
||||
};
|
||||
|
||||
export const sendOAuthClientApprovedNotification = async (input: OAuthClientApprovedNotification) => {
|
||||
await sendEmail(() => new OAuthClientApprovedEmail(input));
|
||||
};
|
||||
|
||||
export const sendOAuthClientRejectedNotification = async (input: OAuthClientRejectedNotification) => {
|
||||
await sendEmail(() => new OAuthClientRejectedEmail(input));
|
||||
};
|
||||
@@ -0,0 +1,124 @@
|
||||
import type { TFunction } from "i18next";
|
||||
|
||||
import { APP_NAME, WEBAPP_URL } from "@calcom/lib/constants";
|
||||
|
||||
import { BaseEmailHtml, CallToAction } from "../components";
|
||||
|
||||
type AdminOAuthClientNotification = {
|
||||
language: TFunction;
|
||||
clientName: string;
|
||||
purpose: string | null;
|
||||
clientId: string;
|
||||
redirectUri: string;
|
||||
submitterEmail: string;
|
||||
submitterName: string | null;
|
||||
};
|
||||
|
||||
export const AdminOAuthClientNotificationEmail = ({
|
||||
clientName,
|
||||
purpose,
|
||||
clientId,
|
||||
redirectUri,
|
||||
submitterEmail,
|
||||
submitterName,
|
||||
language,
|
||||
}: AdminOAuthClientNotification) => {
|
||||
return (
|
||||
<BaseEmailHtml
|
||||
subject={language("admin_oauth_notification_email_subject", { clientName, appName: APP_NAME })}
|
||||
callToAction={
|
||||
<CallToAction
|
||||
label={language("admin_oauth_notification_email_cta")}
|
||||
href={`${WEBAPP_URL}/settings/admin/oauth`}
|
||||
endIconName="white-arrow-right"
|
||||
/>
|
||||
}>
|
||||
<p
|
||||
style={{
|
||||
fontWeight: 600,
|
||||
fontSize: "24px",
|
||||
lineHeight: "38px",
|
||||
}}>
|
||||
<>{language("admin_oauth_notification_email_title", { clientName })}</>
|
||||
</p>
|
||||
<p style={{ fontWeight: 400 }}>
|
||||
<>{language("hi_admin")}</>
|
||||
</p>
|
||||
<p style={{ fontWeight: 400, lineHeight: "24px" }}>
|
||||
{language("admin_oauth_notification_email_body", { submitterEmail })}
|
||||
</p>
|
||||
<table
|
||||
role="presentation"
|
||||
border={0}
|
||||
cellSpacing="0"
|
||||
cellPadding="0"
|
||||
style={{
|
||||
verticalAlign: "top",
|
||||
marginTop: "10px",
|
||||
borderRadius: "6px",
|
||||
borderCollapse: "separate",
|
||||
border: "solid #e5e7eb 1px",
|
||||
}}
|
||||
width="100%">
|
||||
<tbody>
|
||||
<tr style={{ lineHeight: "24px" }}>
|
||||
<td
|
||||
style={{
|
||||
padding: "12px",
|
||||
borderBottom: "1px solid #e5e7eb",
|
||||
fontWeight: 600,
|
||||
width: "30%",
|
||||
}}>
|
||||
{language("client_name")}
|
||||
</td>
|
||||
<td style={{ padding: "12px", borderBottom: "1px solid #e5e7eb" }}>{clientName}</td>
|
||||
</tr>
|
||||
<tr style={{ lineHeight: "24px" }}>
|
||||
<td
|
||||
style={{
|
||||
padding: "12px",
|
||||
borderBottom: "1px solid #e5e7eb",
|
||||
fontWeight: 600,
|
||||
}}>
|
||||
{language("purpose")}
|
||||
</td>
|
||||
<td style={{ padding: "12px", borderBottom: "1px solid #e5e7eb" }}>{purpose ?? ""}</td>
|
||||
</tr>
|
||||
<tr style={{ lineHeight: "24px" }}>
|
||||
<td
|
||||
style={{
|
||||
padding: "12px",
|
||||
borderBottom: "1px solid #e5e7eb",
|
||||
fontWeight: 600,
|
||||
}}>
|
||||
{language("client_id")}
|
||||
</td>
|
||||
<td style={{ padding: "12px", borderBottom: "1px solid #e5e7eb" }}>
|
||||
<code style={{ fontSize: "12px" }}>{clientId}</code>
|
||||
</td>
|
||||
</tr>
|
||||
<tr style={{ lineHeight: "24px" }}>
|
||||
<td
|
||||
style={{
|
||||
padding: "12px",
|
||||
borderBottom: "1px solid #e5e7eb",
|
||||
fontWeight: 600,
|
||||
}}>
|
||||
{language("redirect_uri")}
|
||||
</td>
|
||||
<td style={{ padding: "12px", borderBottom: "1px solid #e5e7eb" }}>{redirectUri}</td>
|
||||
</tr>
|
||||
<tr style={{ lineHeight: "24px" }}>
|
||||
<td style={{ padding: "12px", fontWeight: 600 }}>{language("submitted_by")}</td>
|
||||
<td style={{ padding: "12px" }}>
|
||||
{submitterName ? `${submitterName} (${submitterEmail})` : submitterEmail}
|
||||
</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
<p style={{ fontWeight: 400, lineHeight: "24px", marginTop: "20px" }}>
|
||||
{language("admin_oauth_notification_email_footer")}
|
||||
</p>
|
||||
</BaseEmailHtml>
|
||||
);
|
||||
};
|
||||
@@ -0,0 +1,87 @@
|
||||
import type { TFunction } from "i18next";
|
||||
|
||||
import { APP_NAME, WEBAPP_URL } from "@calcom/lib/constants";
|
||||
|
||||
import { BaseEmailHtml, CallToAction } from "../components";
|
||||
|
||||
type OAuthClientApprovedNotification = {
|
||||
language: TFunction;
|
||||
userName: string | null;
|
||||
clientName: string;
|
||||
clientId: string;
|
||||
};
|
||||
|
||||
export const OAuthClientApprovedNotificationEmail = ({
|
||||
userName,
|
||||
clientName,
|
||||
clientId,
|
||||
language,
|
||||
}: OAuthClientApprovedNotification) => {
|
||||
return (
|
||||
<BaseEmailHtml
|
||||
subject={language("oauth_client_approved_email_subject", { clientName, appName: APP_NAME })}
|
||||
callToAction={
|
||||
<CallToAction
|
||||
label={language("oauth_client_approved_email_cta")}
|
||||
href={`${WEBAPP_URL}/settings/developer/oauth`}
|
||||
endIconName="white-arrow-right"
|
||||
/>
|
||||
}>
|
||||
<p
|
||||
style={{
|
||||
fontWeight: 600,
|
||||
fontSize: "24px",
|
||||
lineHeight: "38px",
|
||||
}}>
|
||||
{language("oauth_client_approved_email_title", { clientName })}
|
||||
</p>
|
||||
<p style={{ fontWeight: 400 }}>
|
||||
{language("hi_user", { name: userName || language("there") })}!
|
||||
</p>
|
||||
<p style={{ fontWeight: 400, lineHeight: "24px" }}>{language("oauth_client_approved_email_body")}</p>
|
||||
<table
|
||||
role="presentation"
|
||||
border={0}
|
||||
cellSpacing="0"
|
||||
cellPadding="0"
|
||||
style={{
|
||||
verticalAlign: "top",
|
||||
marginTop: "10px",
|
||||
borderRadius: "6px",
|
||||
borderCollapse: "separate",
|
||||
border: "solid #e5e7eb 1px",
|
||||
}}
|
||||
width="100%">
|
||||
<tbody>
|
||||
<tr style={{ lineHeight: "24px" }}>
|
||||
<td
|
||||
style={{
|
||||
padding: "12px",
|
||||
borderBottom: "1px solid #e5e7eb",
|
||||
fontWeight: 600,
|
||||
width: "30%",
|
||||
}}>
|
||||
{language("client_name")}
|
||||
</td>
|
||||
<td style={{ padding: "12px", borderBottom: "1px solid #e5e7eb" }}>{clientName}</td>
|
||||
</tr>
|
||||
<tr style={{ lineHeight: "24px" }}>
|
||||
<td
|
||||
style={{
|
||||
padding: "12px",
|
||||
fontWeight: 600,
|
||||
}}>
|
||||
{language("client_id")}
|
||||
</td>
|
||||
<td style={{ padding: "12px" }}>
|
||||
<code style={{ fontSize: "12px" }}>{clientId}</code>
|
||||
</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
<p style={{ fontWeight: 400, lineHeight: "24px", marginTop: "20px" }}>
|
||||
{language("oauth_client_approved_email_footer")}
|
||||
</p>
|
||||
</BaseEmailHtml>
|
||||
);
|
||||
};
|
||||
@@ -0,0 +1,101 @@
|
||||
import type { TFunction } from "i18next";
|
||||
|
||||
import { APP_NAME, WEBAPP_URL } from "@calcom/lib/constants";
|
||||
|
||||
import { BaseEmailHtml, CallToAction } from "../components";
|
||||
|
||||
type OAuthClientRejectedNotification = {
|
||||
language: TFunction;
|
||||
userName: string | null;
|
||||
clientName: string;
|
||||
clientId: string;
|
||||
rejectionReason: string;
|
||||
};
|
||||
|
||||
export const OAuthClientRejectedNotificationEmail = ({
|
||||
userName,
|
||||
clientName,
|
||||
clientId,
|
||||
rejectionReason,
|
||||
language,
|
||||
}: OAuthClientRejectedNotification) => {
|
||||
return (
|
||||
<BaseEmailHtml
|
||||
subject={language("oauth_client_rejected_email_subject", { clientName, appName: APP_NAME })}
|
||||
callToAction={
|
||||
<CallToAction
|
||||
label={language("oauth_client_rejected_email_cta")}
|
||||
href={`${WEBAPP_URL}/settings/developer/oauth`}
|
||||
endIconName="white-arrow-right"
|
||||
/>
|
||||
}>
|
||||
<p
|
||||
style={{
|
||||
fontWeight: 600,
|
||||
fontSize: "24px",
|
||||
lineHeight: "38px",
|
||||
}}>
|
||||
{language("oauth_client_rejected_email_title", { clientName })}
|
||||
</p>
|
||||
<p style={{ fontWeight: 400 }}>{language("hi_user", { name: userName || language("there") })}!</p>
|
||||
<p style={{ fontWeight: 400, lineHeight: "24px" }}>{language("oauth_client_rejected_email_body")}</p>
|
||||
<table
|
||||
role="presentation"
|
||||
border={0}
|
||||
cellSpacing="0"
|
||||
cellPadding="0"
|
||||
style={{
|
||||
verticalAlign: "top",
|
||||
marginTop: "10px",
|
||||
borderRadius: "6px",
|
||||
borderCollapse: "separate",
|
||||
border: "solid #e5e7eb 1px",
|
||||
}}
|
||||
width="100%">
|
||||
<tbody>
|
||||
<tr style={{ lineHeight: "24px" }}>
|
||||
<td
|
||||
style={{
|
||||
padding: "12px",
|
||||
borderBottom: "1px solid #e5e7eb",
|
||||
fontWeight: 600,
|
||||
width: "30%",
|
||||
}}>
|
||||
{language("client_name")}
|
||||
</td>
|
||||
<td style={{ padding: "12px", borderBottom: "1px solid #e5e7eb" }}>{clientName}</td>
|
||||
</tr>
|
||||
<tr style={{ lineHeight: "24px" }}>
|
||||
<td
|
||||
style={{
|
||||
padding: "12px",
|
||||
borderBottom: "1px solid #e5e7eb",
|
||||
fontWeight: 600,
|
||||
width: "30%",
|
||||
}}>
|
||||
{language("client_id")}
|
||||
</td>
|
||||
<td style={{ padding: "12px", borderBottom: "1px solid #e5e7eb" }}>
|
||||
<code style={{ fontSize: "12px" }}>{clientId}</code>
|
||||
</td>
|
||||
</tr>
|
||||
<tr style={{ lineHeight: "24px" }}>
|
||||
<td
|
||||
style={{
|
||||
padding: "12px",
|
||||
fontWeight: 600,
|
||||
}}>
|
||||
{language("oauth_client_rejected_email_reason_label")}
|
||||
</td>
|
||||
<td style={{ padding: "12px" }}>
|
||||
<span style={{ whiteSpace: "pre-wrap" }}>{rejectionReason}</span>
|
||||
</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
<p style={{ fontWeight: 400, lineHeight: "24px", marginTop: "20px" }}>
|
||||
{language("oauth_client_rejected_email_footer")}
|
||||
</p>
|
||||
</BaseEmailHtml>
|
||||
);
|
||||
};
|
||||
@@ -37,6 +37,9 @@ export { OrganisationAccountVerifyEmail } from "./OrganizationAccountVerifyEmail
|
||||
export { OrgAutoInviteEmail } from "./OrgAutoInviteEmail";
|
||||
export { MonthlyDigestEmail } from "./MonthlyDigestEmail";
|
||||
export { AdminOrganizationNotificationEmail } from "./AdminOrganizationNotificationEmail";
|
||||
export { AdminOAuthClientNotificationEmail } from "./AdminOAuthClientNotificationEmail";
|
||||
export { OAuthClientApprovedNotificationEmail } from "./OAuthClientApprovedNotificationEmail";
|
||||
export { OAuthClientRejectedNotificationEmail } from "./OAuthClientRejectedNotificationEmail";
|
||||
export { BookingRedirectEmailNotification } from "./BookingRedirectEmailNotification";
|
||||
export { VerifyEmailChangeEmail } from "./VerifyEmailChangeEmail";
|
||||
export { OrganizationCreationEmail } from "./OrganizationCreationEmail";
|
||||
|
||||
@@ -0,0 +1,89 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import type { TFunction } from "i18next";
|
||||
import { SUPPORT_MAIL_ADDRESS } from "@calcom/lib/constants";
|
||||
|
||||
import AdminOAuthClientNotification from "./admin-oauth-client-notification";
|
||||
|
||||
class TestAdminOAuthClientNotification extends AdminOAuthClientNotification {
|
||||
public async getPayload() {
|
||||
return await this.getNodeMailerPayload();
|
||||
}
|
||||
}
|
||||
|
||||
describe("AdminOAuthClientNotification", () => {
|
||||
it("renders a node mailer payload containing the submitted client information", async () => {
|
||||
const t = ((key: string, vars?: Record<string, unknown>) => {
|
||||
if (key === "admin_oauth_notification_email_subject") {
|
||||
return `New OAuth Client: ${String(vars?.clientName ?? "")}`;
|
||||
}
|
||||
|
||||
if (key === "admin_oauth_notification_email_title") {
|
||||
return `New OAuth Client: ${String(vars?.clientName ?? "")}`;
|
||||
}
|
||||
|
||||
if (key === "hi_admin") return "Hi Administrator";
|
||||
|
||||
if (key === "admin_oauth_notification_email_body") {
|
||||
return `A new OAuth client has been submitted by ${String(vars?.submitterEmail ?? "")} and is awaiting your review.`;
|
||||
}
|
||||
|
||||
if (key === "admin_oauth_notification_email_cta") return "Review OAuth Clients";
|
||||
if (key === "admin_oauth_notification_email_footer") {
|
||||
return "Please review this submission and approve or reject it in the admin dashboard.";
|
||||
}
|
||||
|
||||
if (key === "client_name") return "Name";
|
||||
if (key === "purpose") return "Purpose";
|
||||
if (key === "client_id") return "Client ID";
|
||||
if (key === "redirect_uri") return "Redirect URI";
|
||||
if (key === "submitted_by") return "Submitted By";
|
||||
|
||||
return key;
|
||||
}) as unknown as TFunction;
|
||||
|
||||
const input = {
|
||||
t,
|
||||
clientName: "My Client",
|
||||
purpose: "My Purpose",
|
||||
clientId: "client_123",
|
||||
redirectUri: "https://example.com/callback",
|
||||
submitterEmail: "[email protected]",
|
||||
submitterName: "Submitter Name",
|
||||
};
|
||||
|
||||
const email = new TestAdminOAuthClientNotification(input);
|
||||
const payload = await email.getPayload();
|
||||
|
||||
expect(payload).toEqual(
|
||||
expect.objectContaining({
|
||||
to: SUPPORT_MAIL_ADDRESS,
|
||||
subject: `New OAuth Client: ${input.clientName}`,
|
||||
})
|
||||
);
|
||||
|
||||
const html = "html" in payload ? (payload.html as string) : "";
|
||||
expect(html).toContain(`New OAuth Client: ${input.clientName}`);
|
||||
expect(html).toContain("Hi Administrator");
|
||||
expect(html).toContain(
|
||||
`A new OAuth client has been submitted by ${input.submitterEmail} and is awaiting your review.`
|
||||
);
|
||||
expect(html).toContain("Review OAuth Clients");
|
||||
expect(html).toContain("Please review this submission and approve or reject it in the admin dashboard.");
|
||||
|
||||
expect(html).toContain(">Name<");
|
||||
expect(html).toContain(input.clientName);
|
||||
|
||||
expect(html).toContain(">Purpose<");
|
||||
expect(html).toContain(input.purpose);
|
||||
|
||||
expect(html).toContain(">Client ID<");
|
||||
expect(html).toContain(input.clientId);
|
||||
|
||||
expect(html).toContain(">Redirect URI<");
|
||||
expect(html).toContain(input.redirectUri);
|
||||
|
||||
expect(html).toContain(">Submitted By<");
|
||||
expect(html).toContain(`${input.submitterName} (${input.submitterEmail})`);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,50 @@
|
||||
import type { TFunction } from "i18next";
|
||||
|
||||
import { EMAIL_FROM_NAME, SUPPORT_MAIL_ADDRESS } from "@calcom/lib/constants";
|
||||
|
||||
import renderEmail from "../src/renderEmail";
|
||||
import BaseEmail from "./_base-email";
|
||||
|
||||
export type OAuthClientNotification = {
|
||||
t: TFunction;
|
||||
clientName: string;
|
||||
purpose: string | null;
|
||||
clientId: string;
|
||||
redirectUri: string;
|
||||
submitterEmail: string;
|
||||
submitterName: string | null;
|
||||
};
|
||||
|
||||
export default class AdminOAuthClientNotification extends BaseEmail {
|
||||
input: OAuthClientNotification;
|
||||
|
||||
constructor(input: OAuthClientNotification) {
|
||||
super();
|
||||
this.name = "SEND_ADMIN_OAUTH_CLIENT_NOTIFICATION";
|
||||
this.input = input;
|
||||
}
|
||||
|
||||
protected async getNodeMailerPayload(): Promise<Record<string, unknown>> {
|
||||
return {
|
||||
from: `${EMAIL_FROM_NAME} <${this.getMailerOptions().from}>`,
|
||||
to: SUPPORT_MAIL_ADDRESS,
|
||||
subject: `${this.input.t("admin_oauth_notification_email_subject", { clientName: this.input.clientName })}`,
|
||||
html: await renderEmail("AdminOAuthClientNotificationEmail", {
|
||||
clientName: this.input.clientName,
|
||||
purpose: this.input.purpose,
|
||||
clientId: this.input.clientId,
|
||||
redirectUri: this.input.redirectUri,
|
||||
submitterEmail: this.input.submitterEmail,
|
||||
submitterName: this.input.submitterName,
|
||||
language: this.input.t,
|
||||
}),
|
||||
text: this.getTextBody(),
|
||||
};
|
||||
}
|
||||
|
||||
protected getTextBody(): string {
|
||||
return `${this.input.t("hi_admin")}, ${this.input.t("admin_oauth_notification_email_title", { clientName: this.input.clientName })}
|
||||
${this.input.t("admin_oauth_notification_email_body", { submitterEmail: this.input.submitterEmail })}
|
||||
${this.input.t("purpose")}: ${this.input.purpose ?? ""}`.trim();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,78 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import type { TFunction } from "i18next";
|
||||
|
||||
import OAuthClientApprovedEmail from "./oauth-client-approved-notification";
|
||||
|
||||
class TestOAuthClientApprovedEmail extends OAuthClientApprovedEmail {
|
||||
public async getPayload() {
|
||||
return await this.getNodeMailerPayload();
|
||||
}
|
||||
}
|
||||
|
||||
describe("OAuthClientApprovedEmail", () => {
|
||||
it("renders a node mailer payload containing the approved client information", async () => {
|
||||
const t = ((key: string, vars?: Record<string, unknown>) => {
|
||||
if (key === "oauth_client_approved_email_subject") {
|
||||
return `OAuth Client Approved: ${String(vars?.clientName ?? "")}`;
|
||||
}
|
||||
|
||||
if (key === "oauth_client_approved_email_title") {
|
||||
return `OAuth Client Approved: ${String(vars?.clientName ?? "")}`;
|
||||
}
|
||||
|
||||
if (key === "hi_user") return `Hi ${String(vars?.name ?? "")}`;
|
||||
if (key === "there") return "there";
|
||||
|
||||
if (key === "oauth_client_approved_email_body") {
|
||||
return "Great news! Your OAuth client has been approved and is now ready to use.";
|
||||
}
|
||||
|
||||
if (key === "oauth_client_approved_email_footer") {
|
||||
return "You can now use your client ID and secret to integrate with Cal.com.";
|
||||
}
|
||||
|
||||
if (key === "oauth_client_approved_email_cta") return "View Your OAuth Clients";
|
||||
|
||||
if (key === "client_name") return "Name";
|
||||
if (key === "client_id") return "Client ID";
|
||||
|
||||
return key;
|
||||
}) as unknown as TFunction;
|
||||
|
||||
const input = {
|
||||
t,
|
||||
userEmail: "[email protected]",
|
||||
userName: "Admin Example",
|
||||
clientName: "pkce",
|
||||
clientId: "client_123",
|
||||
};
|
||||
|
||||
const email = new TestOAuthClientApprovedEmail(input);
|
||||
const payload = await email.getPayload();
|
||||
|
||||
expect(payload).toEqual(
|
||||
expect.objectContaining({
|
||||
to: input.userEmail,
|
||||
subject: `OAuth Client Approved: ${input.clientName}`,
|
||||
})
|
||||
);
|
||||
|
||||
const html = "html" in payload ? (payload.html as string) : "";
|
||||
|
||||
expect(html).toContain(`OAuth Client Approved: ${input.clientName}`);
|
||||
expect(html).toContain("Hi Admin Example!");
|
||||
expect(html).toContain("Great news! Your OAuth client has been approved and is now ready to use.");
|
||||
|
||||
expect(html).toContain(">Name<");
|
||||
expect(html).toContain(input.clientName);
|
||||
|
||||
expect(html).toContain(">Client ID<");
|
||||
expect(html).toContain(input.clientId);
|
||||
|
||||
expect(html).toContain("View Your OAuth Clients");
|
||||
expect(html).toContain("/settings/developer/oauth");
|
||||
|
||||
expect(html).toContain("You can now use your client ID and secret to integrate with Cal.com.");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,44 @@
|
||||
import type { TFunction } from "i18next";
|
||||
|
||||
import { EMAIL_FROM_NAME } from "@calcom/lib/constants";
|
||||
|
||||
import renderEmail from "../src/renderEmail";
|
||||
import BaseEmail from "./_base-email";
|
||||
|
||||
export type OAuthClientApprovedNotification = {
|
||||
t: TFunction;
|
||||
userEmail: string;
|
||||
userName: string | null;
|
||||
clientName: string;
|
||||
clientId: string;
|
||||
};
|
||||
|
||||
export default class OAuthClientApprovedEmail extends BaseEmail {
|
||||
input: OAuthClientApprovedNotification;
|
||||
|
||||
constructor(input: OAuthClientApprovedNotification) {
|
||||
super();
|
||||
this.name = "SEND_OAUTH_CLIENT_APPROVED_NOTIFICATION";
|
||||
this.input = input;
|
||||
}
|
||||
|
||||
protected async getNodeMailerPayload(): Promise<Record<string, unknown>> {
|
||||
return {
|
||||
from: `${EMAIL_FROM_NAME} <${this.getMailerOptions().from}>`,
|
||||
to: this.input.userEmail,
|
||||
subject: `${this.input.t("oauth_client_approved_email_subject", { clientName: this.input.clientName })}`,
|
||||
html: await renderEmail("OAuthClientApprovedNotificationEmail", {
|
||||
userName: this.input.userName,
|
||||
clientName: this.input.clientName,
|
||||
clientId: this.input.clientId,
|
||||
language: this.input.t,
|
||||
}),
|
||||
text: this.getTextBody(),
|
||||
};
|
||||
}
|
||||
|
||||
protected getTextBody(): string {
|
||||
return `${this.input.t("oauth_client_approved_email_title", { clientName: this.input.clientName })}
|
||||
${this.input.t("oauth_client_approved_email_body")}`.trim();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,84 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import type { TFunction } from "i18next";
|
||||
|
||||
import OAuthClientRejectedEmail from "./oauth-client-rejected-notification";
|
||||
|
||||
class TestOAuthClientRejectedEmail extends OAuthClientRejectedEmail {
|
||||
public async getPayload() {
|
||||
return await this.getNodeMailerPayload();
|
||||
}
|
||||
}
|
||||
|
||||
describe("OAuthClientRejectedEmail", () => {
|
||||
it("renders a node mailer payload containing the rejected client information and rejection reason", async () => {
|
||||
const t = ((key: string, vars?: Record<string, unknown>) => {
|
||||
if (key === "oauth_client_rejected_email_subject") {
|
||||
return `OAuth Client Rejected: ${String(vars?.clientName ?? "")}`;
|
||||
}
|
||||
|
||||
if (key === "oauth_client_rejected_email_title") {
|
||||
return `OAuth Client Rejected: ${String(vars?.clientName ?? "")}`;
|
||||
}
|
||||
|
||||
if (key === "hi_user") return `Hi ${String(vars?.name ?? "")}`;
|
||||
if (key === "there") return "there";
|
||||
|
||||
if (key === "oauth_client_rejected_email_body") {
|
||||
return "Unfortunately, your OAuth client submission was rejected.";
|
||||
}
|
||||
|
||||
if (key === "oauth_client_rejected_email_reason_label") return "Reason for rejection";
|
||||
|
||||
if (key === "oauth_client_rejected_email_footer") {
|
||||
return "You can update your OAuth client submission and resubmit it for review.";
|
||||
}
|
||||
|
||||
if (key === "oauth_client_rejected_email_cta") return "View Your OAuth Clients";
|
||||
|
||||
if (key === "client_name") return "Name";
|
||||
if (key === "client_id") return "Client ID";
|
||||
|
||||
return key;
|
||||
}) as unknown as TFunction;
|
||||
|
||||
const input = {
|
||||
t,
|
||||
userEmail: "[email protected]",
|
||||
userName: "Admin Example",
|
||||
clientName: "pkce",
|
||||
clientId: "client_123",
|
||||
rejectionReason: "we dont support your usecase",
|
||||
};
|
||||
|
||||
const email = new TestOAuthClientRejectedEmail(input);
|
||||
const payload = await email.getPayload();
|
||||
|
||||
expect(payload).toEqual(
|
||||
expect.objectContaining({
|
||||
to: input.userEmail,
|
||||
subject: `OAuth Client Rejected: ${input.clientName}`,
|
||||
})
|
||||
);
|
||||
|
||||
const html = "html" in payload ? (payload.html as string) : "";
|
||||
|
||||
expect(html).toContain(`OAuth Client Rejected: ${input.clientName}`);
|
||||
expect(html).toContain("Hi Admin Example!");
|
||||
expect(html).toContain("Unfortunately, your OAuth client submission was rejected.");
|
||||
|
||||
expect(html).toContain(">Name<");
|
||||
expect(html).toContain(input.clientName);
|
||||
|
||||
expect(html).toContain(">Client ID<");
|
||||
expect(html).toContain(input.clientId);
|
||||
|
||||
expect(html).toContain("Reason for rejection");
|
||||
expect(html).toContain(input.rejectionReason);
|
||||
|
||||
expect(html).toContain("View Your OAuth Clients");
|
||||
expect(html).toContain("/settings/developer/oauth");
|
||||
|
||||
expect(html).toContain("You can update your OAuth client submission and resubmit it for review.");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,49 @@
|
||||
import type { TFunction } from "i18next";
|
||||
|
||||
import { EMAIL_FROM_NAME } from "@calcom/lib/constants";
|
||||
|
||||
import renderEmail from "../src/renderEmail";
|
||||
import BaseEmail from "./_base-email";
|
||||
|
||||
export type OAuthClientRejectedNotification = {
|
||||
t: TFunction;
|
||||
userEmail: string;
|
||||
userName: string | null;
|
||||
clientName: string;
|
||||
clientId: string;
|
||||
rejectionReason: string;
|
||||
};
|
||||
|
||||
export default class OAuthClientRejectedEmail extends BaseEmail {
|
||||
input: OAuthClientRejectedNotification;
|
||||
|
||||
constructor(input: OAuthClientRejectedNotification) {
|
||||
super();
|
||||
this.name = "SEND_OAUTH_CLIENT_REJECTED_NOTIFICATION";
|
||||
this.input = input;
|
||||
}
|
||||
|
||||
protected async getNodeMailerPayload(): Promise<Record<string, unknown>> {
|
||||
return {
|
||||
from: `${EMAIL_FROM_NAME} <${this.getMailerOptions().from}>`,
|
||||
to: this.input.userEmail,
|
||||
subject: `${this.input.t("oauth_client_rejected_email_subject", { clientName: this.input.clientName })}`,
|
||||
html: await renderEmail("OAuthClientRejectedNotificationEmail", {
|
||||
userName: this.input.userName,
|
||||
clientName: this.input.clientName,
|
||||
clientId: this.input.clientId,
|
||||
rejectionReason: this.input.rejectionReason,
|
||||
language: this.input.t,
|
||||
}),
|
||||
text: this.getTextBody(),
|
||||
};
|
||||
}
|
||||
|
||||
protected getTextBody(): string {
|
||||
return `${this.input.t("oauth_client_rejected_email_title", { clientName: this.input.clientName })}
|
||||
${this.input.t("oauth_client_rejected_email_body")}
|
||||
|
||||
${this.input.t("oauth_client_rejected_email_reason_label")}
|
||||
${this.input.rejectionReason}`.trim();
|
||||
}
|
||||
}
|
||||
@@ -1,4 +1,8 @@
|
||||
import { randomBytes } from "node:crypto";
|
||||
|
||||
|
||||
import type { PrismaClient } from "@calcom/prisma";
|
||||
import type { OAuthClientStatus } from "@calcom/prisma/enums";
|
||||
|
||||
export class OAuthClientRepository {
|
||||
constructor(private readonly prisma: PrismaClient) {}
|
||||
@@ -12,9 +16,15 @@ export class OAuthClientRepository {
|
||||
redirectUri: true,
|
||||
clientType: true,
|
||||
name: true,
|
||||
purpose: true,
|
||||
logo: true,
|
||||
clientId: true,
|
||||
isTrusted: true,
|
||||
websiteUrl: true,
|
||||
rejectionReason: true,
|
||||
status: true,
|
||||
userId: true,
|
||||
createdAt: true,
|
||||
},
|
||||
});
|
||||
}
|
||||
@@ -27,7 +37,191 @@ export class OAuthClientRepository {
|
||||
redirectUri: true,
|
||||
clientSecret: true,
|
||||
clientType: true,
|
||||
status: true,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
async findByClientIdIncludeUser(clientId: string) {
|
||||
return this.prisma.oAuthClient.findUnique({
|
||||
where: { clientId },
|
||||
select: {
|
||||
clientId: true,
|
||||
redirectUri: true,
|
||||
clientType: true,
|
||||
name: true,
|
||||
purpose: true,
|
||||
logo: true,
|
||||
websiteUrl: true,
|
||||
rejectionReason: true,
|
||||
isTrusted: true,
|
||||
status: true,
|
||||
userId: true,
|
||||
createdAt: true,
|
||||
user: {
|
||||
select: {
|
||||
id: true,
|
||||
email: true,
|
||||
name: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
async findByUserId(userId: number) {
|
||||
return this.prisma.oAuthClient.findMany({
|
||||
where: { userId },
|
||||
select: {
|
||||
clientId: true,
|
||||
redirectUri: true,
|
||||
name: true,
|
||||
purpose: true,
|
||||
logo: true,
|
||||
websiteUrl: true,
|
||||
rejectionReason: true,
|
||||
clientType: true,
|
||||
status: true,
|
||||
userId: true,
|
||||
createdAt: true,
|
||||
},
|
||||
orderBy: { createdAt: "desc" },
|
||||
});
|
||||
}
|
||||
|
||||
async findByUserIdAndStatus(userId: number, status: OAuthClientStatus) {
|
||||
return this.prisma.oAuthClient.findMany({
|
||||
where: { userId, status },
|
||||
orderBy: { createdAt: "desc" },
|
||||
});
|
||||
}
|
||||
|
||||
async findAll() {
|
||||
return this.prisma.oAuthClient.findMany({
|
||||
select: {
|
||||
clientId: true,
|
||||
redirectUri: true,
|
||||
name: true,
|
||||
purpose: true,
|
||||
logo: true,
|
||||
websiteUrl: true,
|
||||
rejectionReason: true,
|
||||
clientType: true,
|
||||
status: true,
|
||||
userId: true,
|
||||
createdAt: true,
|
||||
user: {
|
||||
select: {
|
||||
id: true,
|
||||
email: true,
|
||||
name: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
orderBy: { createdAt: "desc" },
|
||||
});
|
||||
}
|
||||
|
||||
async findByStatus(status: OAuthClientStatus) {
|
||||
return this.prisma.oAuthClient.findMany({
|
||||
where: { status },
|
||||
select: {
|
||||
clientId: true,
|
||||
redirectUri: true,
|
||||
name: true,
|
||||
purpose: true,
|
||||
logo: true,
|
||||
websiteUrl: true,
|
||||
rejectionReason: true,
|
||||
clientType: true,
|
||||
status: true,
|
||||
userId: true,
|
||||
createdAt: true,
|
||||
user: {
|
||||
select: {
|
||||
id: true,
|
||||
email: true,
|
||||
name: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
orderBy: { createdAt: "desc" },
|
||||
});
|
||||
}
|
||||
|
||||
async create(data: {
|
||||
name: string;
|
||||
purpose: string;
|
||||
redirectUri: string;
|
||||
clientSecret?: string;
|
||||
logo?: string;
|
||||
websiteUrl?: string;
|
||||
enablePkce?: boolean;
|
||||
userId?: number;
|
||||
status: OAuthClientStatus;
|
||||
}) {
|
||||
const { name, purpose, redirectUri, clientSecret, logo, websiteUrl, enablePkce, userId, status } = data;
|
||||
|
||||
const clientId = randomBytes(32).toString("hex");
|
||||
|
||||
const client = await this.prisma.oAuthClient.create({
|
||||
data: {
|
||||
name,
|
||||
purpose,
|
||||
redirectUri,
|
||||
clientId,
|
||||
clientType: enablePkce ? "PUBLIC" : "CONFIDENTIAL",
|
||||
logo,
|
||||
websiteUrl,
|
||||
status,
|
||||
clientSecret,
|
||||
...(userId && {
|
||||
user: {
|
||||
connect: { id: userId },
|
||||
},
|
||||
}),
|
||||
},
|
||||
});
|
||||
|
||||
return {
|
||||
clientId: client.clientId,
|
||||
name: client.name,
|
||||
purpose: client.purpose,
|
||||
redirectUri: client.redirectUri,
|
||||
logo: client.logo,
|
||||
clientType: client.clientType,
|
||||
clientSecret: client.clientSecret,
|
||||
isPkceEnabled: enablePkce,
|
||||
status: client.status,
|
||||
};
|
||||
}
|
||||
|
||||
async updateStatus(clientId: string, status: OAuthClientStatus) {
|
||||
return this.prisma.oAuthClient.update({
|
||||
where: { clientId },
|
||||
data: { status },
|
||||
});
|
||||
}
|
||||
|
||||
async update(
|
||||
clientId: string,
|
||||
data: {
|
||||
name?: string;
|
||||
purpose?: string;
|
||||
redirectUri?: string;
|
||||
logo?: string;
|
||||
websiteUrl?: string;
|
||||
}
|
||||
) {
|
||||
return this.prisma.oAuthClient.update({
|
||||
where: { clientId },
|
||||
data,
|
||||
});
|
||||
}
|
||||
|
||||
async delete(clientId: string) {
|
||||
return this.prisma.oAuthClient.delete({
|
||||
where: { clientId },
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
import { randomBytes } from "crypto";
|
||||
import { randomBytes } from "node:crypto";
|
||||
import jwt from "jsonwebtoken";
|
||||
|
||||
import { TeamRepository } from "@calcom/features/ee/teams/repositories/TeamRepository";
|
||||
@@ -8,6 +8,7 @@ import { generateSecret } from "@calcom/features/oauth/utils/generateSecret";
|
||||
import { ErrorCode } from "@calcom/lib/errorCodes";
|
||||
import { ErrorWithCode } from "@calcom/lib/errors";
|
||||
import { verifyCodeChallenge } from "@calcom/lib/pkce";
|
||||
import { OAuthClientStatus } from "@calcom/prisma/enums";
|
||||
import type { AccessScope, OAuthClientType } from "@calcom/prisma/enums";
|
||||
|
||||
export interface OAuth2Client {
|
||||
@@ -51,6 +52,7 @@ export class OAuthService {
|
||||
private readonly accessCodeRepository: AccessCodeRepository;
|
||||
private readonly teamsRepository: TeamRepository;
|
||||
private readonly oAuthClientRepository: OAuthClientRepository;
|
||||
|
||||
constructor(
|
||||
private readonly deps: {
|
||||
oAuthClientRepository: OAuthClientRepository;
|
||||
@@ -67,7 +69,7 @@ export class OAuthService {
|
||||
const client = await this.oAuthClientRepository.findByClientId(clientId);
|
||||
|
||||
if (!client) {
|
||||
throw new ErrorWithCode(ErrorCode.NotFound, "unauthorized_client");
|
||||
throw new ErrorWithCode(ErrorCode.NotFound, "unauthorized_client", { reason: "client_not_found" });
|
||||
}
|
||||
|
||||
return {
|
||||
@@ -80,6 +82,27 @@ export class OAuthService {
|
||||
};
|
||||
}
|
||||
|
||||
async getClientForAuthorization(clientId: string, redirectUri: string): Promise<OAuth2Client> {
|
||||
const client = await this.oAuthClientRepository.findByClientId(clientId);
|
||||
|
||||
if (!client) {
|
||||
throw new ErrorWithCode(ErrorCode.NotFound, "unauthorized_client", { reason: "client_not_found" });
|
||||
}
|
||||
|
||||
this.validateRedirectUri(client.redirectUri, redirectUri);
|
||||
|
||||
this.ensureClientIsApproved(client);
|
||||
|
||||
return {
|
||||
clientId: client.clientId,
|
||||
redirectUri: client.redirectUri,
|
||||
name: client.name,
|
||||
logo: client.logo,
|
||||
isTrusted: client.isTrusted,
|
||||
clientType: client.clientType,
|
||||
};
|
||||
}
|
||||
|
||||
async generateAuthorizationCode(
|
||||
clientId: string,
|
||||
userId: number,
|
||||
@@ -96,6 +119,8 @@ export class OAuthService {
|
||||
throw new ErrorWithCode(ErrorCode.Unauthorized, "unauthorized_client", { reason: "client_not_found" });
|
||||
}
|
||||
|
||||
this.ensureClientIsApproved(client);
|
||||
|
||||
// RFC 6749 4.1.2.1: Redirect URI mismatch on Auth step is 'invalid_request'
|
||||
this.validateRedirectUri(client.redirectUri, redirectUri);
|
||||
|
||||
@@ -148,6 +173,12 @@ export class OAuthService {
|
||||
return { redirectUrl, authorizationCode, client };
|
||||
}
|
||||
|
||||
private ensureClientIsApproved(client: { status: OAuthClientStatus }): void {
|
||||
if (client.status !== OAuthClientStatus.APPROVED) {
|
||||
throw new ErrorWithCode(ErrorCode.Unauthorized, "unauthorized_client", { reason: "client_not_approved" });
|
||||
}
|
||||
}
|
||||
|
||||
private validateRedirectUri(registeredUri: string, providedUri: string): void {
|
||||
if (providedUri !== registeredUri) {
|
||||
throw new ErrorWithCode(ErrorCode.BadRequest, "invalid_request", { reason: "redirect_uri_mismatch" });
|
||||
@@ -285,6 +316,8 @@ export class OAuthService {
|
||||
});
|
||||
}
|
||||
|
||||
this.ensureClientIsApproved(client);
|
||||
|
||||
const decodedToken = this.verifyRefreshToken(refreshToken);
|
||||
|
||||
if (!decodedToken || decodedToken.token_type !== "Refresh Token") {
|
||||
@@ -423,6 +456,7 @@ export class OAuthService {
|
||||
|
||||
export type OAuthErrorReason =
|
||||
| "client_not_found"
|
||||
| "client_not_approved"
|
||||
| "redirect_uri_mismatch"
|
||||
| "pkce_required"
|
||||
| "invalid_code_challenge_method"
|
||||
@@ -439,7 +473,8 @@ export type OAuthErrorReason =
|
||||
// Mapping of OAuth error reasons to descriptive messages, keeping previous messages for compatibility
|
||||
export const OAUTH_ERROR_REASONS: Record<OAuthErrorReason, string> = {
|
||||
client_not_found: "OAuth client with ID not found",
|
||||
redirect_uri_mismatch: "redirect_uri does not match registered redirect URI",
|
||||
client_not_approved: "OAuth client is not approved",
|
||||
redirect_uri_mismatch: "redirect_uri does not match OAuth client's redirect URI",
|
||||
pkce_required: "code_challenge required for public clients",
|
||||
invalid_code_challenge_method: "code_challenge_method must be S256",
|
||||
team_not_found_or_no_access: "Team not found or user is not an admin/owner",
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
import { randomBytes, createHash } from "crypto";
|
||||
import { randomBytes, createHash } from "node:crypto";
|
||||
|
||||
const hashSecretKey = (apiKey: string): string => createHash("sha256").update(apiKey).digest("hex");
|
||||
export const hashSecretKey = (apiKey: string): string => createHash("sha256").update(apiKey).digest("hex");
|
||||
|
||||
// Generate a random secret
|
||||
export const generateSecret = (secret = randomBytes(32).toString("hex")) => [hashSecretKey(secret), secret];
|
||||
@@ -0,0 +1,16 @@
|
||||
-- CreateEnum
|
||||
CREATE TYPE "public"."OAuthClientStatus" AS ENUM ('pending', 'approved', 'rejected');
|
||||
|
||||
-- AlterTable
|
||||
ALTER TABLE "public"."OAuthClient" ADD COLUMN "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
ADD COLUMN "purpose" TEXT,
|
||||
ADD COLUMN "rejectionReason" TEXT,
|
||||
ADD COLUMN "status" "public"."OAuthClientStatus" NOT NULL DEFAULT 'approved',
|
||||
ADD COLUMN "userId" INTEGER,
|
||||
ADD COLUMN "websiteUrl" TEXT;
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "OAuthClient_userId_idx" ON "public"."OAuthClient"("userId");
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "public"."OAuthClient" ADD CONSTRAINT "OAuthClient_userId_fkey" FOREIGN KEY ("userId") REFERENCES "public"."users"("id") ON DELETE SET NULL ON UPDATE CASCADE;
|
||||
@@ -484,6 +484,7 @@ model User {
|
||||
whitelistWorkflows Boolean @default(false)
|
||||
calAiPhoneNumbers CalAiPhoneNumber[]
|
||||
agents Agent[]
|
||||
oAuthClients OAuthClient[]
|
||||
holidaySettings UserHolidaySettings?
|
||||
|
||||
autoOptInFeatures Boolean @default(false)
|
||||
@@ -1774,15 +1775,30 @@ enum OAuthClientType {
|
||||
PUBLIC @map("public")
|
||||
}
|
||||
|
||||
enum OAuthClientStatus {
|
||||
PENDING @map("pending")
|
||||
APPROVED @map("approved")
|
||||
REJECTED @map("rejected")
|
||||
}
|
||||
|
||||
model OAuthClient {
|
||||
clientId String @id @unique
|
||||
redirectUri String
|
||||
clientSecret String?
|
||||
clientType OAuthClientType @default(CONFIDENTIAL)
|
||||
name String
|
||||
logo String?
|
||||
isTrusted Boolean @default(false)
|
||||
accessCodes AccessCode[]
|
||||
clientId String @id @unique
|
||||
redirectUri String
|
||||
clientSecret String?
|
||||
clientType OAuthClientType @default(CONFIDENTIAL)
|
||||
name String
|
||||
purpose String?
|
||||
logo String?
|
||||
websiteUrl String?
|
||||
rejectionReason String?
|
||||
isTrusted Boolean @default(false)
|
||||
accessCodes AccessCode[]
|
||||
status OAuthClientStatus @default(APPROVED)
|
||||
userId Int?
|
||||
user User? @relation(fields: [userId], references: [id], onDelete: SetNull)
|
||||
createdAt DateTime @default(now())
|
||||
|
||||
@@index([userId])
|
||||
}
|
||||
|
||||
model AccessCode {
|
||||
|
||||
@@ -1,29 +1,30 @@
|
||||
import authedProcedure, { authedAdminProcedure } from "@calcom/trpc/server/procedures/authedProcedure";
|
||||
|
||||
import { router } from "../../../trpc";
|
||||
import { ZAddClientInputSchema } from "./addClient.schema";
|
||||
import { ZCreateClientInputSchema } from "./createClient.schema";
|
||||
import { ZGenerateAuthCodeInputSchema } from "./generateAuthCode.schema";
|
||||
import { ZGetClientInputSchema } from "./getClient.schema";
|
||||
|
||||
type OAuthRouterHandlerCache = {
|
||||
getClient?: typeof import("./getClient.handler").getClientHandler;
|
||||
addClient?: typeof import("./addClient.handler").addClientHandler;
|
||||
generateAuthCode?: typeof import("./generateAuthCode.handler").generateAuthCodeHandler;
|
||||
};
|
||||
import { ZGetClientForAuthorizationInputSchema } from "./getClientForAuthorization.schema";
|
||||
import { ZListClientsInputSchema } from "./listClients.schema";
|
||||
import { ZSubmitClientInputSchema, ZSubmitClientOutputSchema } from "./submitClientForReview.schema";
|
||||
import { ZUpdateClientInputSchema } from "./updateClient.schema";
|
||||
import { ZDeleteClientInputSchema } from "./deleteClient.schema";
|
||||
|
||||
export const oAuthRouter = router({
|
||||
getClient: authedProcedure.input(ZGetClientInputSchema).query(async ({ input }) => {
|
||||
const { getClientHandler } = await import("./getClient.handler");
|
||||
getClientForAuthorization: authedProcedure
|
||||
.input(ZGetClientForAuthorizationInputSchema)
|
||||
.query(async ({ input }) => {
|
||||
const { getClientForAuthorizationHandler } = await import("./getClientForAuthorization.handler");
|
||||
|
||||
return getClientHandler({
|
||||
input,
|
||||
});
|
||||
}),
|
||||
return getClientForAuthorizationHandler({
|
||||
input,
|
||||
});
|
||||
}),
|
||||
|
||||
addClient: authedAdminProcedure.input(ZAddClientInputSchema).mutation(async ({ input }) => {
|
||||
const { addClientHandler } = await import("./addClient.handler");
|
||||
createClient: authedAdminProcedure.input(ZCreateClientInputSchema).mutation(async ({ ctx, input }) => {
|
||||
const { createClientHandler } = await import("./createClient.handler");
|
||||
|
||||
return addClientHandler({
|
||||
return createClientHandler({
|
||||
ctx,
|
||||
input,
|
||||
});
|
||||
}),
|
||||
@@ -36,4 +37,51 @@ export const oAuthRouter = router({
|
||||
input,
|
||||
});
|
||||
}),
|
||||
|
||||
submitClientForReview: authedProcedure
|
||||
.input(ZSubmitClientInputSchema)
|
||||
.output(ZSubmitClientOutputSchema)
|
||||
.mutation(async ({ ctx, input }) => {
|
||||
const { submitClientForReviewHandler } = await import("./submitClientForReview.handler");
|
||||
|
||||
return submitClientForReviewHandler({
|
||||
ctx,
|
||||
input,
|
||||
});
|
||||
}),
|
||||
|
||||
listClients: authedAdminProcedure.input(ZListClientsInputSchema).query(async ({ ctx, input }) => {
|
||||
const { listClientsHandler } = await import("./listClients.handler");
|
||||
|
||||
return listClientsHandler({
|
||||
ctx,
|
||||
input,
|
||||
});
|
||||
}),
|
||||
|
||||
listUserClients: authedProcedure.query(async ({ ctx }) => {
|
||||
const { listUserClientsHandler } = await import("./listUserClients.handler");
|
||||
|
||||
return listUserClientsHandler({
|
||||
ctx,
|
||||
});
|
||||
}),
|
||||
|
||||
updateClient: authedProcedure.input(ZUpdateClientInputSchema).mutation(async ({ ctx, input }) => {
|
||||
const { updateClientHandler } = await import("./updateClient.handler");
|
||||
|
||||
return updateClientHandler({
|
||||
ctx,
|
||||
input,
|
||||
});
|
||||
}),
|
||||
|
||||
deleteClient: authedProcedure.input(ZDeleteClientInputSchema).mutation(async ({ ctx, input }) => {
|
||||
const { deleteClientHandler } = await import("./deleteClient.handler");
|
||||
|
||||
return deleteClientHandler({
|
||||
ctx,
|
||||
input,
|
||||
});
|
||||
}),
|
||||
});
|
||||
@@ -1,47 +0,0 @@
|
||||
import { randomBytes } from "node:crypto";
|
||||
|
||||
import { generateSecret } from "@calcom/features/oauth/utils/generateSecret";
|
||||
import { prisma } from "@calcom/prisma";
|
||||
import { Prisma } from "@calcom/prisma/client";
|
||||
|
||||
import type { TAddClientInputSchema } from "./addClient.schema";
|
||||
|
||||
type AddClientOptions = {
|
||||
input: TAddClientInputSchema;
|
||||
};
|
||||
|
||||
export const addClientHandler = async ({ input }: AddClientOptions) => {
|
||||
const { name, redirectUri, logo, enablePkce } = input;
|
||||
|
||||
const clientId = randomBytes(32).toString("hex");
|
||||
const clientType = enablePkce ? "PUBLIC" : "CONFIDENTIAL";
|
||||
|
||||
// Only generate client secret for confidential clients
|
||||
const clientData: Prisma.OAuthClientCreateInput = {
|
||||
name,
|
||||
redirectUri,
|
||||
clientId,
|
||||
clientType,
|
||||
logo,
|
||||
};
|
||||
|
||||
let secret: string | undefined;
|
||||
if (!enablePkce) {
|
||||
const [hashedSecret, plainSecret] = generateSecret();
|
||||
clientData.clientSecret = hashedSecret;
|
||||
secret = plainSecret;
|
||||
}
|
||||
const client = await prisma.oAuthClient.create({
|
||||
data: clientData,
|
||||
});
|
||||
|
||||
return {
|
||||
clientId: client.clientId,
|
||||
name: client.name,
|
||||
redirectUri: client.redirectUri,
|
||||
logo: client.logo,
|
||||
clientType: client.clientType,
|
||||
clientSecret: secret, // Only return plain secret for confidential clients
|
||||
isPkceEnabled: enablePkce,
|
||||
};
|
||||
};
|
||||
@@ -1,22 +0,0 @@
|
||||
import { z } from "zod";
|
||||
|
||||
export type TAddClientInputSchemaInput = {
|
||||
name: string;
|
||||
redirectUri: string;
|
||||
logo: string;
|
||||
enablePkce?: boolean;
|
||||
};
|
||||
|
||||
export type TAddClientInputSchema = {
|
||||
name: string;
|
||||
redirectUri: string;
|
||||
logo: string;
|
||||
enablePkce: boolean;
|
||||
};
|
||||
|
||||
export const ZAddClientInputSchema: z.ZodType<TAddClientInputSchema, z.ZodTypeDef, TAddClientInputSchemaInput> = z.object({
|
||||
name: z.string(),
|
||||
redirectUri: z.string(),
|
||||
logo: z.string(),
|
||||
enablePkce: z.boolean().optional().default(false),
|
||||
});
|
||||
@@ -0,0 +1,48 @@
|
||||
import { OAuthClientRepository } from "@calcom/features/oauth/repositories/OAuthClientRepository";
|
||||
import type { PrismaClient } from "@calcom/prisma";
|
||||
import { generateSecret } from "@calcom/features/oauth/utils/generateSecret";
|
||||
import type { TCreateClientInputSchema } from "./createClient.schema";
|
||||
|
||||
type AddClientOptions = {
|
||||
ctx: {
|
||||
prisma: PrismaClient;
|
||||
};
|
||||
input: TCreateClientInputSchema;
|
||||
};
|
||||
|
||||
export const createClientHandler = async ({ ctx, input }: AddClientOptions) => {
|
||||
const { name, purpose, redirectUri, logo, websiteUrl, enablePkce } = input;
|
||||
|
||||
const oAuthClientRepository = new OAuthClientRepository(ctx.prisma);
|
||||
|
||||
let plainSecret: string | undefined;
|
||||
let hashedSecret: string | undefined;
|
||||
if (!enablePkce) {
|
||||
const [hashed, plain] = generateSecret();
|
||||
hashedSecret = hashed;
|
||||
plainSecret = plain;
|
||||
}
|
||||
|
||||
const client = await oAuthClientRepository.create({
|
||||
name,
|
||||
purpose,
|
||||
redirectUri,
|
||||
clientSecret: hashedSecret,
|
||||
logo,
|
||||
websiteUrl,
|
||||
enablePkce,
|
||||
status: "APPROVED",
|
||||
});
|
||||
|
||||
return {
|
||||
clientId: client.clientId,
|
||||
name: client.name,
|
||||
purpose: client.purpose,
|
||||
redirectUri: client.redirectUri,
|
||||
logo: client.logo,
|
||||
clientType: client.clientType,
|
||||
clientSecret: plainSecret,
|
||||
isPkceEnabled: enablePkce,
|
||||
status: client.status,
|
||||
};
|
||||
};
|
||||
@@ -0,0 +1,34 @@
|
||||
import { z } from "zod";
|
||||
|
||||
export type TCreateClientInputSchemaInput = {
|
||||
name: string;
|
||||
purpose: string;
|
||||
redirectUri: string;
|
||||
logo?: string;
|
||||
websiteUrl?: string;
|
||||
enablePkce?: boolean;
|
||||
};
|
||||
|
||||
export type TCreateClientInputSchema = {
|
||||
name: string;
|
||||
purpose: string;
|
||||
redirectUri: string;
|
||||
logo?: string;
|
||||
websiteUrl?: string;
|
||||
enablePkce: boolean;
|
||||
};
|
||||
|
||||
export const ZCreateClientInputSchema: z.ZodType<TCreateClientInputSchema, z.ZodTypeDef, TCreateClientInputSchemaInput> = z.object({
|
||||
name: z.string(),
|
||||
purpose: z.string().min(1),
|
||||
redirectUri: z.string(),
|
||||
logo: z
|
||||
.string()
|
||||
.optional()
|
||||
.transform((value) => (typeof value === "string" && value.trim() === "" ? undefined : value)),
|
||||
websiteUrl: z
|
||||
.union([z.literal(""), z.string().url("Must be a valid URL")])
|
||||
.optional()
|
||||
.transform((value) => (value === "" ? undefined : value)),
|
||||
enablePkce: z.boolean().optional().default(false),
|
||||
});
|
||||
@@ -0,0 +1,37 @@
|
||||
import { TRPCError } from "@trpc/server";
|
||||
|
||||
import { OAuthClientRepository } from "@calcom/features/oauth/repositories/OAuthClientRepository";
|
||||
import type { PrismaClient } from "@calcom/prisma";
|
||||
|
||||
import type { TDeleteClientInputSchema } from "./deleteClient.schema";
|
||||
|
||||
type DeleteClientOptions = {
|
||||
ctx: {
|
||||
user: {
|
||||
id: number;
|
||||
};
|
||||
prisma: PrismaClient;
|
||||
};
|
||||
input: TDeleteClientInputSchema;
|
||||
};
|
||||
|
||||
export const deleteClientHandler = async ({ ctx, input }: DeleteClientOptions) => {
|
||||
const { clientId } = input;
|
||||
|
||||
const oAuthClientRepository = new OAuthClientRepository(ctx.prisma);
|
||||
|
||||
const existingClient = await oAuthClientRepository.findByClientId(clientId);
|
||||
if (!existingClient) {
|
||||
throw new TRPCError({ code: "NOT_FOUND", message: "OAuth Client not found" });
|
||||
}
|
||||
|
||||
const isOwner = existingClient.userId != null && existingClient.userId === ctx.user.id;
|
||||
|
||||
if (!isOwner) {
|
||||
throw new TRPCError({ code: "NOT_FOUND", message: "OAuth Client not found" });
|
||||
}
|
||||
|
||||
await oAuthClientRepository.delete(clientId);
|
||||
|
||||
return { clientId };
|
||||
};
|
||||
@@ -0,0 +1,7 @@
|
||||
import { z } from "zod";
|
||||
|
||||
export const ZDeleteClientInputSchema = z.object({
|
||||
clientId: z.string().min(1),
|
||||
});
|
||||
|
||||
export type TDeleteClientInputSchema = z.infer<typeof ZDeleteClientInputSchema>;
|
||||
@@ -4,17 +4,15 @@ import { describe, expect, it, vi, beforeEach } from "vitest";
|
||||
|
||||
import { OAUTH_ERROR_REASONS } from "@calcom/features/oauth/services/OAuthService";
|
||||
|
||||
import type { TrpcSessionUser } from "@calcom/trpc/server/types";
|
||||
|
||||
import { TRPCError } from "@trpc/server";
|
||||
|
||||
import { generateAuthCodeHandler } from "./generateAuthCode.handler";
|
||||
|
||||
const mockUser = {
|
||||
id: 1,
|
||||
email: "[email protected]",
|
||||
name: "Test User",
|
||||
};
|
||||
const mockUser = { id: 1 } as unknown as NonNullable<TrpcSessionUser>;
|
||||
|
||||
const mockCtx = {
|
||||
const mockCtx: { user: NonNullable<TrpcSessionUser> } = {
|
||||
user: mockUser,
|
||||
};
|
||||
|
||||
@@ -29,6 +27,7 @@ describe("generateAuthCodeHandler", () => {
|
||||
redirectUri: "https://app.example.com/callback",
|
||||
name: "Test Public Client",
|
||||
clientType: "PUBLIC" as const,
|
||||
status: "APPROVED" as const,
|
||||
};
|
||||
|
||||
it("should generate authorization code for PUBLIC client with valid PKCE", async () => {
|
||||
@@ -164,6 +163,7 @@ describe("generateAuthCodeHandler", () => {
|
||||
clientType: "CONFIDENTIAL" as const,
|
||||
isTrusted: undefined,
|
||||
logo: undefined,
|
||||
status: "APPROVED" as const,
|
||||
};
|
||||
|
||||
it("should generate authorization code for CONFIDENTIAL client without PKCE", async () => {
|
||||
@@ -303,6 +303,7 @@ describe("generateAuthCodeHandler", () => {
|
||||
redirectUri: "https://app.example.com/callback",
|
||||
name: "Test Public Client",
|
||||
clientType: "PUBLIC" as const,
|
||||
status: "APPROVED" as const,
|
||||
};
|
||||
|
||||
prismaMock.oAuthClient.findFirst.mockResolvedValue(mockPublicClient);
|
||||
@@ -370,5 +371,65 @@ describe("generateAuthCodeHandler", () => {
|
||||
})
|
||||
);
|
||||
});
|
||||
|
||||
it("should reject PENDING client", async () => {
|
||||
const mockPendingClient = {
|
||||
clientId: "pending_client_123",
|
||||
redirectUri: "https://app.example.com/callback",
|
||||
name: "Test Pending Client",
|
||||
clientType: "CONFIDENTIAL" as const,
|
||||
status: "PENDING" as const,
|
||||
};
|
||||
|
||||
prismaMock.oAuthClient.findFirst.mockResolvedValue(mockPendingClient);
|
||||
|
||||
const input = {
|
||||
clientId: "pending_client_123",
|
||||
scopes: [],
|
||||
teamSlug: undefined,
|
||||
codeChallenge: undefined,
|
||||
codeChallengeMethod: undefined,
|
||||
redirectUri: "https://app.example.com/callback",
|
||||
};
|
||||
|
||||
await expect(generateAuthCodeHandler({ ctx: mockCtx, input })).rejects.toThrow(
|
||||
new TRPCError({
|
||||
code: "UNAUTHORIZED",
|
||||
message: OAUTH_ERROR_REASONS.client_not_approved,
|
||||
})
|
||||
);
|
||||
|
||||
expect(prismaMock.accessCode.create).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("should reject REJECTED client", async () => {
|
||||
const mockRejectedClient = {
|
||||
clientId: "rejected_client_123",
|
||||
redirectUri: "https://app.example.com/callback",
|
||||
name: "Test Rejected Client",
|
||||
clientType: "CONFIDENTIAL" as const,
|
||||
status: "REJECTED" as const,
|
||||
};
|
||||
|
||||
prismaMock.oAuthClient.findFirst.mockResolvedValue(mockRejectedClient);
|
||||
|
||||
const input = {
|
||||
clientId: "rejected_client_123",
|
||||
scopes: [],
|
||||
teamSlug: undefined,
|
||||
codeChallenge: undefined,
|
||||
codeChallengeMethod: undefined,
|
||||
redirectUri: "https://app.example.com/callback",
|
||||
};
|
||||
|
||||
await expect(generateAuthCodeHandler({ ctx: mockCtx, input })).rejects.toThrow(
|
||||
new TRPCError({
|
||||
code: "UNAUTHORIZED",
|
||||
message: OAUTH_ERROR_REASONS.client_not_approved,
|
||||
})
|
||||
);
|
||||
|
||||
expect(prismaMock.accessCode.create).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -1,7 +0,0 @@
|
||||
import { z } from "zod";
|
||||
|
||||
export const ZGetClientInputSchema = z.object({
|
||||
clientId: z.string(),
|
||||
});
|
||||
|
||||
export type TGetClientInputSchema = z.infer<typeof ZGetClientInputSchema>;
|
||||
+6
-6
@@ -6,19 +6,19 @@ import { httpStatusToTrpcCode } from "@calcom/trpc/server/lib/toTRPCError";
|
||||
|
||||
import { TRPCError } from "@trpc/server";
|
||||
|
||||
import type { TGetClientInputSchema } from "./getClient.schema";
|
||||
import type { TGetClientForAuthorizationInputSchema } from "./getClientForAuthorization.schema";
|
||||
|
||||
type GetClientOptions = {
|
||||
input: TGetClientInputSchema;
|
||||
type GetClientForAuthorizationOptions = {
|
||||
input: TGetClientForAuthorizationInputSchema;
|
||||
};
|
||||
|
||||
export const getClientHandler = async ({ input }: GetClientOptions) => {
|
||||
export const getClientForAuthorizationHandler = async ({ input }: GetClientForAuthorizationOptions) => {
|
||||
try {
|
||||
const { clientId } = input;
|
||||
const { clientId, redirectUri } = input;
|
||||
|
||||
const oAuthService = getOAuthService();
|
||||
|
||||
const oAuthClient = await oAuthService.getClient(clientId);
|
||||
const oAuthClient = await oAuthService.getClientForAuthorization(clientId, redirectUri);
|
||||
|
||||
return {
|
||||
clientId: oAuthClient.clientId,
|
||||
@@ -0,0 +1,8 @@
|
||||
import { z } from "zod";
|
||||
|
||||
export const ZGetClientForAuthorizationInputSchema = z.object({
|
||||
clientId: z.string(),
|
||||
redirectUri: z.string().url("Must be a valid URL"),
|
||||
});
|
||||
|
||||
export type TGetClientForAuthorizationInputSchema = z.infer<typeof ZGetClientForAuthorizationInputSchema>;
|
||||
@@ -0,0 +1,23 @@
|
||||
import { OAuthClientRepository } from "@calcom/features/oauth/repositories/OAuthClientRepository";
|
||||
import type { PrismaClient } from "@calcom/prisma";
|
||||
|
||||
import type { TListClientsInputSchema } from "./listClients.schema";
|
||||
|
||||
type ListClientsOptions = {
|
||||
ctx: {
|
||||
prisma: PrismaClient;
|
||||
};
|
||||
input: TListClientsInputSchema;
|
||||
};
|
||||
|
||||
export const listClientsHandler = async ({ ctx, input }: ListClientsOptions) => {
|
||||
const { status } = input;
|
||||
|
||||
const oAuthClientRepository = new OAuthClientRepository(ctx.prisma);
|
||||
|
||||
if (status) {
|
||||
return oAuthClientRepository.findByStatus(status);
|
||||
}
|
||||
|
||||
return oAuthClientRepository.findAll();
|
||||
};
|
||||
@@ -0,0 +1,9 @@
|
||||
import { z } from "zod";
|
||||
|
||||
import { OAuthClientStatus } from "@calcom/prisma/enums";
|
||||
|
||||
export const ZListClientsInputSchema = z.object({
|
||||
status: z.nativeEnum(OAuthClientStatus).optional(),
|
||||
});
|
||||
|
||||
export type TListClientsInputSchema = z.infer<typeof ZListClientsInputSchema>;
|
||||
@@ -0,0 +1,19 @@
|
||||
import { OAuthClientRepository } from "@calcom/features/oauth/repositories/OAuthClientRepository";
|
||||
import type { PrismaClient } from "@calcom/prisma";
|
||||
|
||||
type ListUserClientsOptions = {
|
||||
ctx: {
|
||||
user: {
|
||||
id: number;
|
||||
};
|
||||
prisma: PrismaClient;
|
||||
};
|
||||
};
|
||||
|
||||
export const listUserClientsHandler = async ({ ctx }: ListUserClientsOptions) => {
|
||||
const userId = ctx.user.id;
|
||||
|
||||
const oAuthClientRepository = new OAuthClientRepository(ctx.prisma);
|
||||
|
||||
return oAuthClientRepository.findByUserId(userId);
|
||||
};
|
||||
@@ -0,0 +1,122 @@
|
||||
import { describe, expect, it, vi, beforeEach } from "vitest";
|
||||
|
||||
import type { TFunction } from "i18next";
|
||||
|
||||
import type { PrismaClient } from "@calcom/prisma";
|
||||
|
||||
import { submitClientForReviewHandler } from "./submitClientForReview.handler";
|
||||
|
||||
const mocks = vi.hoisted(() => {
|
||||
return {
|
||||
createOAuthClient: vi.fn(),
|
||||
sendAdminOAuthClientNotification: vi.fn(),
|
||||
getTranslation: vi.fn(),
|
||||
generateSecret: vi.fn(),
|
||||
};
|
||||
});
|
||||
|
||||
vi.mock("@calcom/features/oauth/repositories/OAuthClientRepository", () => ({
|
||||
OAuthClientRepository: class {
|
||||
constructor() {}
|
||||
create = mocks.createOAuthClient;
|
||||
},
|
||||
}));
|
||||
|
||||
vi.mock("@calcom/emails/oauth-email-service", () => ({
|
||||
sendAdminOAuthClientNotification: mocks.sendAdminOAuthClientNotification,
|
||||
}));
|
||||
|
||||
vi.mock("@calcom/lib/server/i18n", () => ({
|
||||
getTranslation: mocks.getTranslation,
|
||||
}));
|
||||
|
||||
vi.mock("@calcom/features/oauth/utils/generateSecret", () => ({
|
||||
generateSecret: mocks.generateSecret,
|
||||
}));
|
||||
|
||||
describe("submitClientHandler", () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
});
|
||||
|
||||
it("creates an OAuth client and sends the admin notification email with expected parameters", async () => {
|
||||
const t = ((key: string, vars?: Record<string, unknown>) => {
|
||||
if (key === "admin_oauth_notification_email_subject") {
|
||||
return `admin_oauth_notification_email_subject:${String(vars?.clientName ?? "")}`;
|
||||
}
|
||||
return key;
|
||||
}) as unknown as TFunction;
|
||||
|
||||
mocks.getTranslation.mockResolvedValue(t);
|
||||
mocks.generateSecret.mockReturnValue(["hashed-secret", "plain-secret"]);
|
||||
|
||||
const createdClient = {
|
||||
clientId: "client_123",
|
||||
name: "My Test Client",
|
||||
purpose: "My test purpose",
|
||||
redirectUri: "https://example.com/callback",
|
||||
logo: "https://example.com/logo.png",
|
||||
clientType: "CONFIDENTIAL",
|
||||
clientSecret: "hashed-secret",
|
||||
isPkceEnabled: false,
|
||||
status: "PENDING",
|
||||
};
|
||||
|
||||
mocks.createOAuthClient.mockResolvedValue(createdClient);
|
||||
mocks.sendAdminOAuthClientNotification.mockResolvedValue({});
|
||||
|
||||
const ctx = {
|
||||
user: {
|
||||
id: 42,
|
||||
email: "[email protected]",
|
||||
name: "Submitter Name",
|
||||
},
|
||||
prisma: {} as unknown as PrismaClient,
|
||||
};
|
||||
|
||||
const input = {
|
||||
name: createdClient.name,
|
||||
purpose: createdClient.purpose,
|
||||
redirectUri: createdClient.redirectUri,
|
||||
logo: createdClient.logo,
|
||||
websiteUrl: "https://example.com",
|
||||
enablePkce: false,
|
||||
};
|
||||
|
||||
const result = await submitClientForReviewHandler({ ctx, input });
|
||||
|
||||
expect(mocks.createOAuthClient).toHaveBeenCalledWith({
|
||||
name: input.name,
|
||||
purpose: input.purpose,
|
||||
redirectUri: input.redirectUri,
|
||||
clientSecret: "hashed-secret",
|
||||
logo: input.logo,
|
||||
websiteUrl: input.websiteUrl,
|
||||
enablePkce: input.enablePkce,
|
||||
userId: ctx.user.id,
|
||||
status: "PENDING",
|
||||
});
|
||||
|
||||
expect(mocks.sendAdminOAuthClientNotification).toHaveBeenCalledWith({
|
||||
t,
|
||||
clientName: createdClient.name,
|
||||
purpose: createdClient.purpose,
|
||||
clientId: createdClient.clientId,
|
||||
redirectUri: createdClient.redirectUri,
|
||||
submitterEmail: ctx.user.email,
|
||||
submitterName: ctx.user.name,
|
||||
});
|
||||
|
||||
expect(result).toEqual({
|
||||
clientId: createdClient.clientId,
|
||||
name: createdClient.name,
|
||||
purpose: createdClient.purpose,
|
||||
clientSecret: "plain-secret",
|
||||
redirectUri: createdClient.redirectUri,
|
||||
logo: createdClient.logo,
|
||||
clientType: createdClient.clientType,
|
||||
status: createdClient.status,
|
||||
isPkceEnabled: input.enablePkce,
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,69 @@
|
||||
import { sendAdminOAuthClientNotification } from "@calcom/emails/oauth-email-service";
|
||||
import { getTranslation } from "@calcom/lib/server/i18n";
|
||||
import { OAuthClientRepository } from "@calcom/features/oauth/repositories/OAuthClientRepository";
|
||||
import { generateSecret } from "@calcom/features/oauth/utils/generateSecret";
|
||||
import type { PrismaClient } from "@calcom/prisma";
|
||||
|
||||
import type { TSubmitClientInputSchema } from "./submitClientForReview.schema";
|
||||
|
||||
type SubmitClientOptions = {
|
||||
ctx: {
|
||||
user: {
|
||||
id: number;
|
||||
email: string;
|
||||
name: string | null;
|
||||
};
|
||||
prisma: PrismaClient;
|
||||
};
|
||||
input: TSubmitClientInputSchema;
|
||||
};
|
||||
|
||||
export const submitClientForReviewHandler = async ({ ctx, input }: SubmitClientOptions) => {
|
||||
const { name, purpose, redirectUri, logo, websiteUrl, enablePkce } = input;
|
||||
const userId = ctx.user.id;
|
||||
|
||||
const oAuthClientRepository = new OAuthClientRepository(ctx.prisma);
|
||||
|
||||
let plainSecret: string | undefined;
|
||||
let hashedSecret: string | undefined;
|
||||
if (!enablePkce) {
|
||||
const [hashed, plain] = generateSecret();
|
||||
hashedSecret = hashed;
|
||||
plainSecret = plain;
|
||||
}
|
||||
|
||||
const client = await oAuthClientRepository.create({
|
||||
name,
|
||||
purpose,
|
||||
redirectUri,
|
||||
clientSecret: hashedSecret,
|
||||
logo,
|
||||
websiteUrl,
|
||||
enablePkce,
|
||||
userId,
|
||||
status: "PENDING",
|
||||
});
|
||||
|
||||
const t = await getTranslation("en", "common");
|
||||
await sendAdminOAuthClientNotification({
|
||||
t,
|
||||
clientName: client.name,
|
||||
purpose: client.purpose,
|
||||
clientId: client.clientId,
|
||||
redirectUri: client.redirectUri,
|
||||
submitterEmail: ctx.user.email,
|
||||
submitterName: ctx.user.name,
|
||||
});
|
||||
|
||||
return {
|
||||
clientId: client.clientId,
|
||||
name: client.name,
|
||||
purpose: client.purpose,
|
||||
clientSecret: plainSecret,
|
||||
redirectUri: client.redirectUri,
|
||||
logo: client.logo,
|
||||
clientType: client.clientType,
|
||||
status: client.status,
|
||||
isPkceEnabled: enablePkce,
|
||||
};
|
||||
};
|
||||
@@ -0,0 +1,32 @@
|
||||
import { z } from "zod";
|
||||
|
||||
export const ZSubmitClientInputSchema = z.object({
|
||||
name: z.string().min(1, "Client name is required"),
|
||||
purpose: z.string().min(1, "Purpose is required"),
|
||||
redirectUri: z.string().url("Must be a valid URL"),
|
||||
logo: z
|
||||
.string()
|
||||
.optional()
|
||||
.transform((value) => (typeof value === "string" && value.trim() === "" ? undefined : value)),
|
||||
websiteUrl: z
|
||||
.union([z.literal(""), z.string().url("Must be a valid URL")])
|
||||
.optional()
|
||||
.transform((value) => (value === "" ? undefined : value)),
|
||||
enablePkce: z.boolean().optional().default(false),
|
||||
});
|
||||
|
||||
export const ZSubmitClientOutputSchema = z.object({
|
||||
clientId: z.string(),
|
||||
name: z.string(),
|
||||
purpose: z.string().nullable(),
|
||||
clientSecret: z.string().optional(),
|
||||
redirectUri: z.string(),
|
||||
logo: z.string().nullable(),
|
||||
clientType: z.string(),
|
||||
status: z.string(),
|
||||
isPkceEnabled: z.boolean().optional(),
|
||||
});
|
||||
|
||||
export type TSubmitClientInputSchema = z.infer<typeof ZSubmitClientInputSchema>;
|
||||
|
||||
export type TSubmitClientOutputSchema = z.infer<typeof ZSubmitClientOutputSchema>;
|
||||
@@ -0,0 +1,490 @@
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
import type { TFunction } from "i18next";
|
||||
|
||||
import type { PrismaClient } from "@calcom/prisma";
|
||||
import { OAuthClientStatus, UserPermissionRole } from "@calcom/prisma/enums";
|
||||
|
||||
import { updateClientHandler } from "./updateClient.handler";
|
||||
|
||||
const mocks = vi.hoisted(() => {
|
||||
return {
|
||||
findByClientId: vi.fn(),
|
||||
findByClientIdIncludeUser: vi.fn(),
|
||||
sendOAuthClientApprovedNotification: vi.fn(),
|
||||
sendOAuthClientRejectedNotification: vi.fn(),
|
||||
getTranslation: vi.fn(),
|
||||
};
|
||||
});
|
||||
|
||||
const CLIENT_ID = "client_123";
|
||||
const OWNER_USER_ID = 42;
|
||||
|
||||
const USER_EMAIL = "[email protected]";
|
||||
const USER_NAME = "Admin Example";
|
||||
|
||||
const CLIENT_NAME = "My Client";
|
||||
const CLIENT_PURPOSE = "My purpose";
|
||||
const REDIRECT_URI = "https://example.com/callback";
|
||||
|
||||
const REJECTION_REASON_TRIMMED = "we dont support your usecase";
|
||||
const REJECTION_REASON_RAW = " we dont support your usecase ";
|
||||
|
||||
vi.mock("@calcom/features/oauth/repositories/OAuthClientRepository", () => ({
|
||||
OAuthClientRepository: class {
|
||||
constructor() {}
|
||||
findByClientId = mocks.findByClientId;
|
||||
findByClientIdIncludeUser = mocks.findByClientIdIncludeUser;
|
||||
},
|
||||
}));
|
||||
|
||||
vi.mock("@calcom/emails/oauth-email-service", () => ({
|
||||
sendOAuthClientApprovedNotification: mocks.sendOAuthClientApprovedNotification,
|
||||
sendOAuthClientRejectedNotification: mocks.sendOAuthClientRejectedNotification,
|
||||
}));
|
||||
|
||||
vi.mock("@calcom/lib/server/i18n", () => ({
|
||||
getTranslation: mocks.getTranslation,
|
||||
}));
|
||||
|
||||
describe("updateClientHandler", () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
});
|
||||
|
||||
it("updates status to APPROVED (admin) and sends approved notification email with expected parameters", async () => {
|
||||
const t = ((key: string, vars?: Record<string, unknown>) => {
|
||||
if (key === "oauth_client_approved_email_subject") {
|
||||
return `OAuth Client Approved: ${String(vars?.clientName ?? "")}`;
|
||||
}
|
||||
return key;
|
||||
}) as unknown as TFunction;
|
||||
|
||||
mocks.getTranslation.mockResolvedValue(t);
|
||||
|
||||
mocks.findByClientIdIncludeUser.mockResolvedValue({
|
||||
clientId: CLIENT_ID,
|
||||
userId: OWNER_USER_ID,
|
||||
name: CLIENT_NAME,
|
||||
purpose: CLIENT_PURPOSE,
|
||||
redirectUri: REDIRECT_URI,
|
||||
websiteUrl: null,
|
||||
logo: null,
|
||||
status: "PENDING",
|
||||
user: {
|
||||
email: USER_EMAIL,
|
||||
name: USER_NAME,
|
||||
},
|
||||
});
|
||||
|
||||
const prismaUpdate = vi.fn().mockResolvedValue({
|
||||
clientId: CLIENT_ID,
|
||||
name: CLIENT_NAME,
|
||||
purpose: CLIENT_PURPOSE,
|
||||
status: "APPROVED",
|
||||
redirectUri: REDIRECT_URI,
|
||||
websiteUrl: null,
|
||||
logo: null,
|
||||
rejectionReason: null,
|
||||
});
|
||||
|
||||
const ctx = {
|
||||
user: {
|
||||
id: 1,
|
||||
role: UserPermissionRole.ADMIN,
|
||||
},
|
||||
prisma: {
|
||||
oAuthClient: {
|
||||
update: prismaUpdate,
|
||||
},
|
||||
} as unknown as PrismaClient,
|
||||
};
|
||||
|
||||
const input = {
|
||||
clientId: CLIENT_ID,
|
||||
status: OAuthClientStatus.APPROVED,
|
||||
};
|
||||
|
||||
const result = await updateClientHandler({ ctx, input });
|
||||
|
||||
expect(prismaUpdate).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
where: { clientId: input.clientId },
|
||||
data: {
|
||||
status: "APPROVED",
|
||||
rejectionReason: null,
|
||||
},
|
||||
})
|
||||
);
|
||||
|
||||
expect(mocks.getTranslation).toHaveBeenCalledWith("en", "common");
|
||||
|
||||
expect(mocks.sendOAuthClientApprovedNotification).toHaveBeenCalledWith({
|
||||
t,
|
||||
userEmail: USER_EMAIL,
|
||||
userName: USER_NAME,
|
||||
clientName: CLIENT_NAME,
|
||||
clientId: CLIENT_ID,
|
||||
});
|
||||
|
||||
expect(result).toEqual({
|
||||
clientId: CLIENT_ID,
|
||||
name: CLIENT_NAME,
|
||||
purpose: CLIENT_PURPOSE,
|
||||
status: "APPROVED",
|
||||
redirectUri: REDIRECT_URI,
|
||||
websiteUrl: null,
|
||||
logo: null,
|
||||
rejectionReason: null,
|
||||
});
|
||||
});
|
||||
|
||||
it("updates status to REJECTED (admin) and sends rejected notification email with trimmed rejection reason", async () => {
|
||||
const t = ((key: string, vars?: Record<string, unknown>) => {
|
||||
if (key === "oauth_client_rejected_email_subject") {
|
||||
return `OAuth Client Rejected: ${String(vars?.clientName ?? "")}`;
|
||||
}
|
||||
return key;
|
||||
}) as unknown as TFunction;
|
||||
|
||||
mocks.getTranslation.mockResolvedValue(t);
|
||||
|
||||
mocks.findByClientIdIncludeUser.mockResolvedValue({
|
||||
clientId: CLIENT_ID,
|
||||
userId: OWNER_USER_ID,
|
||||
name: CLIENT_NAME,
|
||||
purpose: CLIENT_PURPOSE,
|
||||
redirectUri: REDIRECT_URI,
|
||||
websiteUrl: null,
|
||||
logo: null,
|
||||
status: "PENDING",
|
||||
user: {
|
||||
email: USER_EMAIL,
|
||||
name: USER_NAME,
|
||||
},
|
||||
});
|
||||
|
||||
const prismaUpdate = vi.fn().mockResolvedValue({
|
||||
clientId: CLIENT_ID,
|
||||
name: CLIENT_NAME,
|
||||
purpose: CLIENT_PURPOSE,
|
||||
status: "REJECTED",
|
||||
redirectUri: REDIRECT_URI,
|
||||
websiteUrl: null,
|
||||
logo: null,
|
||||
rejectionReason: REJECTION_REASON_TRIMMED,
|
||||
});
|
||||
|
||||
const ctx = {
|
||||
user: {
|
||||
id: 1,
|
||||
role: UserPermissionRole.ADMIN,
|
||||
},
|
||||
prisma: {
|
||||
oAuthClient: {
|
||||
update: prismaUpdate,
|
||||
},
|
||||
} as unknown as PrismaClient,
|
||||
};
|
||||
|
||||
const input = {
|
||||
clientId: CLIENT_ID,
|
||||
status: OAuthClientStatus.REJECTED,
|
||||
rejectionReason: REJECTION_REASON_RAW,
|
||||
};
|
||||
|
||||
await updateClientHandler({ ctx, input });
|
||||
|
||||
expect(prismaUpdate).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
where: { clientId: input.clientId },
|
||||
data: {
|
||||
status: "REJECTED",
|
||||
rejectionReason: REJECTION_REASON_TRIMMED,
|
||||
},
|
||||
})
|
||||
);
|
||||
|
||||
expect(mocks.getTranslation).toHaveBeenCalledWith("en", "common");
|
||||
|
||||
expect(mocks.sendOAuthClientRejectedNotification).toHaveBeenCalledWith({
|
||||
t,
|
||||
userEmail: USER_EMAIL,
|
||||
userName: USER_NAME,
|
||||
clientName: CLIENT_NAME,
|
||||
clientId: CLIENT_ID,
|
||||
rejectionReason: REJECTION_REASON_TRIMMED,
|
||||
});
|
||||
});
|
||||
|
||||
it("throws FORBIDDEN when a non-admin attempts to set rejectionReason", async () => {
|
||||
mocks.findByClientIdIncludeUser.mockResolvedValue({
|
||||
clientId: CLIENT_ID,
|
||||
userId: OWNER_USER_ID,
|
||||
name: CLIENT_NAME,
|
||||
purpose: CLIENT_PURPOSE,
|
||||
redirectUri: REDIRECT_URI,
|
||||
websiteUrl: null,
|
||||
logo: null,
|
||||
status: "PENDING",
|
||||
user: null,
|
||||
});
|
||||
|
||||
const ctx = {
|
||||
user: {
|
||||
id: 2,
|
||||
role: UserPermissionRole.USER,
|
||||
},
|
||||
prisma: {
|
||||
oAuthClient: {
|
||||
update: vi.fn(),
|
||||
},
|
||||
} as unknown as PrismaClient,
|
||||
};
|
||||
|
||||
const input = {
|
||||
clientId: CLIENT_ID,
|
||||
rejectionReason: "nope",
|
||||
};
|
||||
|
||||
await expect(updateClientHandler({ ctx, input })).rejects.toMatchObject({
|
||||
code: "FORBIDDEN",
|
||||
message: "Only admins can set a rejection reason",
|
||||
});
|
||||
});
|
||||
|
||||
it("throws BAD_REQUEST when rejecting without a non-empty rejectionReason", async () => {
|
||||
mocks.findByClientIdIncludeUser.mockResolvedValue({
|
||||
clientId: CLIENT_ID,
|
||||
userId: OWNER_USER_ID,
|
||||
name: CLIENT_NAME,
|
||||
purpose: CLIENT_PURPOSE,
|
||||
redirectUri: REDIRECT_URI,
|
||||
websiteUrl: null,
|
||||
logo: null,
|
||||
status: "PENDING",
|
||||
user: null,
|
||||
});
|
||||
|
||||
const ctx = {
|
||||
user: {
|
||||
id: 1,
|
||||
role: UserPermissionRole.ADMIN,
|
||||
},
|
||||
prisma: {
|
||||
oAuthClient: {
|
||||
update: vi.fn(),
|
||||
},
|
||||
} as unknown as PrismaClient,
|
||||
};
|
||||
|
||||
await expect(
|
||||
updateClientHandler({
|
||||
ctx,
|
||||
input: {
|
||||
clientId: CLIENT_ID,
|
||||
status: OAuthClientStatus.REJECTED,
|
||||
rejectionReason: " ",
|
||||
},
|
||||
})
|
||||
).rejects.toMatchObject({
|
||||
code: "BAD_REQUEST",
|
||||
message: "Rejection reason is required",
|
||||
});
|
||||
});
|
||||
|
||||
it("throws FORBIDDEN when a non-admin attempts to update status", async () => {
|
||||
mocks.findByClientIdIncludeUser.mockResolvedValue({
|
||||
clientId: CLIENT_ID,
|
||||
userId: OWNER_USER_ID,
|
||||
name: CLIENT_NAME,
|
||||
purpose: CLIENT_PURPOSE,
|
||||
redirectUri: REDIRECT_URI,
|
||||
websiteUrl: null,
|
||||
logo: null,
|
||||
status: "PENDING",
|
||||
user: null,
|
||||
});
|
||||
|
||||
const ctx = {
|
||||
user: {
|
||||
id: 2,
|
||||
role: UserPermissionRole.USER,
|
||||
},
|
||||
prisma: {
|
||||
oAuthClient: {
|
||||
update: vi.fn(),
|
||||
},
|
||||
} as unknown as PrismaClient,
|
||||
};
|
||||
|
||||
await expect(
|
||||
updateClientHandler({
|
||||
ctx,
|
||||
input: {
|
||||
clientId: CLIENT_ID,
|
||||
status: OAuthClientStatus.APPROVED,
|
||||
},
|
||||
})
|
||||
).rejects.toMatchObject({
|
||||
code: "FORBIDDEN",
|
||||
message: "Only admins can update OAuth client status",
|
||||
});
|
||||
});
|
||||
|
||||
it("throws FORBIDDEN when a non-owner, non-admin attempts to update client fields", async () => {
|
||||
mocks.findByClientIdIncludeUser.mockResolvedValue({
|
||||
clientId: CLIENT_ID,
|
||||
userId: OWNER_USER_ID,
|
||||
name: CLIENT_NAME,
|
||||
purpose: CLIENT_PURPOSE,
|
||||
redirectUri: REDIRECT_URI,
|
||||
websiteUrl: null,
|
||||
logo: null,
|
||||
status: "PENDING",
|
||||
user: null,
|
||||
});
|
||||
|
||||
const ctx = {
|
||||
user: {
|
||||
id: 999,
|
||||
role: UserPermissionRole.USER,
|
||||
},
|
||||
prisma: {
|
||||
oAuthClient: {
|
||||
update: vi.fn(),
|
||||
},
|
||||
} as unknown as PrismaClient,
|
||||
};
|
||||
|
||||
await expect(
|
||||
updateClientHandler({
|
||||
ctx,
|
||||
input: {
|
||||
clientId: CLIENT_ID,
|
||||
name: "New Name",
|
||||
},
|
||||
})
|
||||
).rejects.toMatchObject({
|
||||
code: "FORBIDDEN",
|
||||
message: "You do not have permission to update this OAuth client",
|
||||
});
|
||||
});
|
||||
|
||||
it("sets status to PENDING when an owner edits a previously approved client (reapproval flow)", async () => {
|
||||
mocks.findByClientIdIncludeUser.mockResolvedValue({
|
||||
clientId: CLIENT_ID,
|
||||
userId: OWNER_USER_ID,
|
||||
name: CLIENT_NAME,
|
||||
purpose: CLIENT_PURPOSE,
|
||||
redirectUri: REDIRECT_URI,
|
||||
websiteUrl: null,
|
||||
logo: null,
|
||||
status: "APPROVED",
|
||||
user: null,
|
||||
});
|
||||
|
||||
const prismaUpdate = vi.fn().mockResolvedValue({
|
||||
clientId: CLIENT_ID,
|
||||
name: "My Client v2",
|
||||
purpose: CLIENT_PURPOSE,
|
||||
status: "PENDING",
|
||||
redirectUri: REDIRECT_URI,
|
||||
websiteUrl: null,
|
||||
logo: null,
|
||||
rejectionReason: null,
|
||||
});
|
||||
|
||||
const ctx = {
|
||||
user: {
|
||||
id: 42,
|
||||
role: UserPermissionRole.USER,
|
||||
},
|
||||
prisma: {
|
||||
oAuthClient: {
|
||||
update: prismaUpdate,
|
||||
},
|
||||
} as unknown as PrismaClient,
|
||||
};
|
||||
|
||||
await updateClientHandler({
|
||||
ctx,
|
||||
input: {
|
||||
clientId: CLIENT_ID,
|
||||
name: "My Client v2",
|
||||
},
|
||||
});
|
||||
|
||||
expect(prismaUpdate).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
where: { clientId: CLIENT_ID },
|
||||
data: {
|
||||
name: "My Client v2",
|
||||
status: "PENDING",
|
||||
rejectionReason: null,
|
||||
},
|
||||
})
|
||||
);
|
||||
|
||||
expect(mocks.sendOAuthClientApprovedNotification).not.toHaveBeenCalled();
|
||||
expect(mocks.sendOAuthClientRejectedNotification).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("sets status to PENDING when an owner updates redirectUri (reapproval flow)", async () => {
|
||||
mocks.findByClientIdIncludeUser.mockResolvedValue({
|
||||
clientId: CLIENT_ID,
|
||||
userId: OWNER_USER_ID,
|
||||
name: CLIENT_NAME,
|
||||
purpose: CLIENT_PURPOSE,
|
||||
redirectUri: REDIRECT_URI,
|
||||
websiteUrl: null,
|
||||
logo: null,
|
||||
status: "APPROVED",
|
||||
user: null,
|
||||
});
|
||||
|
||||
const updatedRedirectUri = "https://example.com/new-callback";
|
||||
|
||||
const prismaUpdate = vi.fn().mockResolvedValue({
|
||||
clientId: CLIENT_ID,
|
||||
name: CLIENT_NAME,
|
||||
purpose: CLIENT_PURPOSE,
|
||||
status: "PENDING",
|
||||
redirectUri: updatedRedirectUri,
|
||||
websiteUrl: null,
|
||||
logo: null,
|
||||
rejectionReason: null,
|
||||
});
|
||||
|
||||
const ctx = {
|
||||
user: {
|
||||
id: OWNER_USER_ID,
|
||||
role: UserPermissionRole.USER,
|
||||
},
|
||||
prisma: {
|
||||
oAuthClient: {
|
||||
update: prismaUpdate,
|
||||
},
|
||||
} as unknown as PrismaClient,
|
||||
};
|
||||
|
||||
await updateClientHandler({
|
||||
ctx,
|
||||
input: {
|
||||
clientId: CLIENT_ID,
|
||||
redirectUri: updatedRedirectUri,
|
||||
},
|
||||
});
|
||||
|
||||
expect(prismaUpdate).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
where: { clientId: CLIENT_ID },
|
||||
data: {
|
||||
redirectUri: updatedRedirectUri,
|
||||
status: "PENDING",
|
||||
rejectionReason: null,
|
||||
},
|
||||
})
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,310 @@
|
||||
import { TRPCError } from "@trpc/server";
|
||||
|
||||
import { sendOAuthClientApprovedNotification, sendOAuthClientRejectedNotification } from "@calcom/emails/oauth-email-service";
|
||||
import { getTranslation } from "@calcom/lib/server/i18n";
|
||||
import { OAuthClientRepository } from "@calcom/features/oauth/repositories/OAuthClientRepository";
|
||||
import type { PrismaClient } from "@calcom/prisma";
|
||||
import { UserPermissionRole } from "@calcom/prisma/enums";
|
||||
import type { OAuthClientStatus } from "@calcom/prisma/enums";
|
||||
|
||||
import type { TUpdateClientInputSchema } from "./updateClient.schema";
|
||||
|
||||
type UpdateClientOptions = {
|
||||
ctx: {
|
||||
user: {
|
||||
id: number;
|
||||
role: UserPermissionRole;
|
||||
};
|
||||
prisma: PrismaClient;
|
||||
};
|
||||
input: TUpdateClientInputSchema;
|
||||
};
|
||||
|
||||
type UpdateClientOutput = {
|
||||
clientId: string;
|
||||
name: string;
|
||||
purpose: string | null;
|
||||
status: OAuthClientStatus;
|
||||
redirectUri: string;
|
||||
websiteUrl: string | null;
|
||||
logo: string | null;
|
||||
rejectionReason: string | null;
|
||||
};
|
||||
|
||||
const updateClientHandler = async ({
|
||||
ctx,
|
||||
input,
|
||||
}: UpdateClientOptions): Promise<UpdateClientOutput> => {
|
||||
const {
|
||||
clientId,
|
||||
status: requestedStatus,
|
||||
rejectionReason,
|
||||
name,
|
||||
purpose,
|
||||
redirectUri,
|
||||
websiteUrl,
|
||||
logo,
|
||||
} = input;
|
||||
|
||||
const oAuthClientRepository = new OAuthClientRepository(ctx.prisma);
|
||||
|
||||
const isAdmin = ctx.user.role === UserPermissionRole.ADMIN;
|
||||
|
||||
const clientWithUser = await oAuthClientRepository.findByClientIdIncludeUser(clientId);
|
||||
if (!clientWithUser) {
|
||||
throw new TRPCError({ code: "NOT_FOUND", message: "OAuth Client not found" });
|
||||
}
|
||||
const isOwner = clientWithUser.userId != null && clientWithUser.userId === ctx.user.id;
|
||||
|
||||
if (rejectionReason !== undefined && !isAdmin) {
|
||||
throw new TRPCError({ code: "FORBIDDEN", message: "Only admins can set a rejection reason" });
|
||||
}
|
||||
|
||||
if (requestedStatus === "REJECTED" && (!rejectionReason || rejectionReason.trim().length === 0)) {
|
||||
throw new TRPCError({ code: "BAD_REQUEST", message: "Rejection reason is required" });
|
||||
}
|
||||
|
||||
const isUpdatingFields = hasAnyFieldsChanged({ name, purpose, redirectUri, websiteUrl, logo });
|
||||
const isUpdatingStatus = requestedStatus !== undefined;
|
||||
|
||||
if (isUpdatingStatus && !isAdmin) {
|
||||
throw new TRPCError({ code: "FORBIDDEN", message: "Only admins can update OAuth client status" });
|
||||
}
|
||||
|
||||
if (isUpdatingFields && !isAdmin && !isOwner) {
|
||||
throw new TRPCError({ code: "FORBIDDEN", message: "You do not have permission to update this OAuth client" });
|
||||
}
|
||||
|
||||
const shouldTriggerReapprovalForOwnerEdit = triggersReapprovalForOwnerEdit({
|
||||
isAdmin,
|
||||
isOwner,
|
||||
currentClient: {
|
||||
name: clientWithUser.name,
|
||||
logo: clientWithUser.logo,
|
||||
websiteUrl: clientWithUser.websiteUrl,
|
||||
redirectUri: clientWithUser.redirectUri,
|
||||
},
|
||||
proposedUpdates: {
|
||||
name,
|
||||
logo,
|
||||
websiteUrl,
|
||||
redirectUri,
|
||||
},
|
||||
});
|
||||
|
||||
const nextStatus = computeNextStatus({
|
||||
requestedStatus,
|
||||
triggersReapprovalForOwnerEdit: shouldTriggerReapprovalForOwnerEdit,
|
||||
currentStatus: clientWithUser.status,
|
||||
});
|
||||
|
||||
const updateData = buildUpdateClientUpdateData({
|
||||
name,
|
||||
purpose,
|
||||
redirectUri,
|
||||
logo,
|
||||
websiteUrl,
|
||||
requestedStatus,
|
||||
rejectionReason,
|
||||
nextStatus,
|
||||
currentStatus: clientWithUser.status,
|
||||
});
|
||||
|
||||
const updatedClient = await ctx.prisma.oAuthClient.update({
|
||||
where: { clientId },
|
||||
data: updateData,
|
||||
select: {
|
||||
clientId: true,
|
||||
name: true,
|
||||
purpose: true,
|
||||
status: true,
|
||||
redirectUri: true,
|
||||
websiteUrl: true,
|
||||
logo: true,
|
||||
rejectionReason: true,
|
||||
},
|
||||
});
|
||||
|
||||
await notifyOwnerAboutAdminReview({
|
||||
isAdmin,
|
||||
requestedStatus,
|
||||
clientWithUser,
|
||||
updatedClient: {
|
||||
clientId: updatedClient.clientId,
|
||||
name: updatedClient.name,
|
||||
},
|
||||
rejectionReason,
|
||||
});
|
||||
|
||||
return {
|
||||
clientId: updatedClient.clientId,
|
||||
name: updatedClient.name,
|
||||
purpose: updatedClient.purpose,
|
||||
status: updatedClient.status,
|
||||
redirectUri: updatedClient.redirectUri,
|
||||
websiteUrl: updatedClient.websiteUrl,
|
||||
logo: updatedClient.logo,
|
||||
rejectionReason: updatedClient.rejectionReason,
|
||||
};
|
||||
};
|
||||
|
||||
function toNullableString(value: string | null | undefined) {
|
||||
return value ?? null;
|
||||
}
|
||||
|
||||
function hasAnyFieldsChanged(fields: Record<string, unknown>) {
|
||||
return Object.values(fields).some((value) => value !== undefined);
|
||||
}
|
||||
|
||||
type ClientFieldsForReapprovalCheck = {
|
||||
name: string;
|
||||
logo: string | null;
|
||||
websiteUrl: string | null;
|
||||
redirectUri: string;
|
||||
};
|
||||
|
||||
function triggersReapprovalForOwnerEdit(params: {
|
||||
isAdmin: boolean;
|
||||
isOwner: boolean;
|
||||
currentClient: ClientFieldsForReapprovalCheck;
|
||||
proposedUpdates: Partial<{
|
||||
name: string;
|
||||
logo: string | null;
|
||||
websiteUrl: string | null;
|
||||
redirectUri: string;
|
||||
}>;
|
||||
}) {
|
||||
const { isAdmin, isOwner, currentClient, proposedUpdates } = params;
|
||||
if (isAdmin) return false;
|
||||
if (!isOwner) return false;
|
||||
|
||||
if (proposedUpdates.name !== undefined && proposedUpdates.name !== currentClient.name) {
|
||||
return true;
|
||||
}
|
||||
|
||||
if (
|
||||
proposedUpdates.logo !== undefined &&
|
||||
toNullableString(proposedUpdates.logo) !== toNullableString(currentClient.logo)
|
||||
) {
|
||||
return true;
|
||||
}
|
||||
|
||||
if (
|
||||
proposedUpdates.websiteUrl !== undefined &&
|
||||
toNullableString(proposedUpdates.websiteUrl) !== toNullableString(currentClient.websiteUrl)
|
||||
) {
|
||||
return true;
|
||||
}
|
||||
|
||||
if (proposedUpdates.redirectUri !== undefined && proposedUpdates.redirectUri !== currentClient.redirectUri) {
|
||||
return true;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
function computeNextStatus(params: {
|
||||
requestedStatus: OAuthClientStatus | undefined;
|
||||
triggersReapprovalForOwnerEdit: boolean;
|
||||
currentStatus: OAuthClientStatus;
|
||||
}): OAuthClientStatus {
|
||||
const { requestedStatus, triggersReapprovalForOwnerEdit, currentStatus } = params;
|
||||
if (requestedStatus !== undefined) return requestedStatus;
|
||||
if (triggersReapprovalForOwnerEdit) return "PENDING";
|
||||
return currentStatus;
|
||||
}
|
||||
|
||||
type NotifyOwnerAboutAdminReviewParams = {
|
||||
isAdmin: boolean;
|
||||
requestedStatus: OAuthClientStatus | undefined;
|
||||
clientWithUser: Awaited<ReturnType<OAuthClientRepository["findByClientIdIncludeUser"]>> | null;
|
||||
updatedClient: {
|
||||
clientId: string;
|
||||
name: string;
|
||||
};
|
||||
rejectionReason: string | undefined;
|
||||
};
|
||||
|
||||
async function notifyOwnerAboutAdminReview(params: NotifyOwnerAboutAdminReviewParams) {
|
||||
const { isAdmin, requestedStatus, clientWithUser, updatedClient, rejectionReason } = params;
|
||||
if (!isAdmin) return;
|
||||
if (requestedStatus !== "APPROVED" && requestedStatus !== "REJECTED") return;
|
||||
if (!clientWithUser?.user) return;
|
||||
|
||||
const t = await getTranslation("en", "common");
|
||||
|
||||
if (requestedStatus === "APPROVED") {
|
||||
await sendOAuthClientApprovedNotification({
|
||||
t,
|
||||
userEmail: clientWithUser.user.email,
|
||||
userName: clientWithUser.user.name,
|
||||
clientName: updatedClient.name,
|
||||
clientId: updatedClient.clientId,
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
await sendOAuthClientRejectedNotification({
|
||||
t,
|
||||
userEmail: clientWithUser.user.email,
|
||||
userName: clientWithUser.user.name,
|
||||
clientName: updatedClient.name,
|
||||
clientId: updatedClient.clientId,
|
||||
rejectionReason: rejectionReason?.trim() ?? "",
|
||||
});
|
||||
}
|
||||
|
||||
type UpdateOAuthClientData = {
|
||||
name?: string;
|
||||
purpose?: string;
|
||||
redirectUri?: string;
|
||||
logo?: string | null;
|
||||
websiteUrl?: string | null;
|
||||
status?: OAuthClientStatus;
|
||||
rejectionReason?: string | null;
|
||||
};
|
||||
|
||||
function buildUpdateClientUpdateData(params: {
|
||||
name: string | undefined;
|
||||
purpose: string | undefined;
|
||||
redirectUri: string | undefined;
|
||||
logo: string | null | undefined;
|
||||
websiteUrl: string | null | undefined;
|
||||
requestedStatus: OAuthClientStatus | undefined;
|
||||
rejectionReason: string | undefined;
|
||||
nextStatus: OAuthClientStatus;
|
||||
currentStatus: OAuthClientStatus;
|
||||
}): UpdateOAuthClientData {
|
||||
const {
|
||||
name,
|
||||
purpose,
|
||||
redirectUri,
|
||||
logo,
|
||||
websiteUrl,
|
||||
requestedStatus,
|
||||
rejectionReason,
|
||||
nextStatus,
|
||||
currentStatus,
|
||||
} = params;
|
||||
|
||||
const updateData: UpdateOAuthClientData = {};
|
||||
|
||||
if (name !== undefined) updateData.name = name;
|
||||
if (purpose !== undefined) updateData.purpose = purpose;
|
||||
if (redirectUri !== undefined) updateData.redirectUri = redirectUri;
|
||||
if (logo !== undefined) updateData.logo = logo;
|
||||
if (websiteUrl !== undefined) updateData.websiteUrl = websiteUrl;
|
||||
if (nextStatus !== currentStatus) updateData.status = nextStatus;
|
||||
|
||||
if (requestedStatus === "REJECTED") {
|
||||
updateData.rejectionReason = rejectionReason?.trim() ?? null;
|
||||
} else if (requestedStatus !== undefined) {
|
||||
updateData.rejectionReason = null;
|
||||
} else if (nextStatus !== currentStatus && nextStatus !== "REJECTED") {
|
||||
updateData.rejectionReason = null;
|
||||
}
|
||||
|
||||
return updateData;
|
||||
}
|
||||
|
||||
export { updateClientHandler };
|
||||
@@ -0,0 +1,30 @@
|
||||
import { z } from "zod";
|
||||
|
||||
import { OAuthClientStatus } from "@calcom/prisma/enums";
|
||||
|
||||
export const ZUpdateClientInputSchema = z.object({
|
||||
clientId: z.string(),
|
||||
status: z.nativeEnum(OAuthClientStatus).optional(),
|
||||
rejectionReason: z.string().min(1).optional(),
|
||||
name: z.string().min(1).optional(),
|
||||
purpose: z.string().min(1).optional(),
|
||||
redirectUri: z.string().url().optional(),
|
||||
logo: z.preprocess(
|
||||
(value) => (typeof value === "string" && value.trim() === "" ? null : value),
|
||||
z.string().nullable().optional()
|
||||
),
|
||||
websiteUrl: z.preprocess(
|
||||
(value) => (typeof value === "string" && value.trim() === "" ? null : value),
|
||||
z.string().url().nullable().optional()
|
||||
),
|
||||
}).superRefine((val, ctx) => {
|
||||
if (val.status === OAuthClientStatus.REJECTED && !val.rejectionReason) {
|
||||
ctx.addIssue({
|
||||
code: z.ZodIssueCode.custom,
|
||||
path: ["rejectionReason"],
|
||||
message: "Rejection reason is required",
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
export type TUpdateClientInputSchema = z.infer<typeof ZUpdateClientInputSchema>;
|
||||
Reference in new issue
Block a user