Rallly is an open-source scheduling and collaboration tool designed to make organizing events and meetings easier.
TypeScript i18nextnext-authnextjspostgresqlprismareact-emailt3-stacktailwindcsstrpcturborepotypescriptzod
🐛 Delete Zoom tokens when a conferencing connection is disconnected (#3372)
Luke Vella9dd865015f18
diff --git a/apps/docs/integrations/zoom.mdx b/apps/docs/integrations/zoom.mdxindex 670118ac0..35c116a0d 100644--- a/apps/docs/integrations/zoom.mdx+++ b/apps/docs/integrations/zoom.mdx@@ -121,7 +121,7 @@ Rallly does not store the content of any meeting.<img src="/images/integrations/zoom/disconnect-menu.png" alt="The connected Zoom account with its menu open, showing Disconnect" /></Frame>-The connection is removed immediately. Polls that already chose Zoom keep that choice but can no longer be finalized with a Zoom link until an account is connected again. Meetings Rallly already created stay in your Zoom account; delete them from Zoom if you no longer need them.+The connection is removed immediately: Rallly deletes the account details and tokens it stored, then asks Zoom to revoke its access. To confirm the access is gone, remove the app from Zoom as described below. Polls that already chose Zoom keep that choice but can no longer be finalized with a Zoom link until an account is connected again. Meetings Rallly already created stay in your Zoom account; delete them from Zoom if you no longer need them.### From Zoomdiff --git a/apps/web/src/features/conferencing/mutations.ts b/apps/web/src/features/conferencing/mutations.tsindex 5fa9be369..ff6eefa83 100644--- a/apps/web/src/features/conferencing/mutations.ts+++ b/apps/web/src/features/conferencing/mutations.ts@@ -1,7 +1,13 @@import "server-only";import { prisma } from "@rallly/database";+import { createLogger } from "@rallly/logger";+import { after } from "next/server";+import { loadCredential } from "@/features/credentials/data";import type { UserInfo } from "@/lib/oauth/types";+import { revokeZoomToken } from "./service";++const logger = createLogger("conferencing/mutations");export const createConferencingConnection = async ({userId,@@ -44,8 +50,6 @@ export const createConferencingConnection = async ({});};-// Only the connection goes; the credential row may still back a calendar-// connection on the same Google account.export const disconnectConferencingConnection = async ({userId,id,@@ -55,14 +59,55 @@ export const disconnectConferencingConnection = async ({}) => {const connection = await prisma.conferencingConnection.findFirst({where: { id, userId },- select: { id: true },+ select: { id: true, provider: true, credentialId: true },});if (!connection) {return { ok: false as const, reason: "not_found" as const };}- await prisma.conferencingConnection.delete({ where: { id } });+ await removeConferencingConnection(connection);return { ok: true as const };};++const removeConferencingConnection = async ({+ id,+ provider,+ credentialId,+}: {+ id: string;+ provider: string;+ credentialId: string;+}) => {+ // Read before the delete, which takes the tokens needed to revoke the grant.+ // A credential that cannot be read must not block the disconnect.+ const credential =+ provider === "zoom"+ ? await loadCredential(credentialId).catch((error) => {+ logger.warn(+ { err: error, credentialId },+ "Failed to read credential",+ );+ return null;+ })+ : null;++ // A Google credential can also back a calendar connection on the same+ // account, so the credential goes only once nothing references it.+ const [, { count }] = await prisma.$transaction([+ prisma.conferencingConnection.delete({ where: { id } }),+ prisma.credential.deleteMany({+ where: {+ id: credentialId,+ calendarConnections: { none: {} },+ conferencingConnections: { none: {} },+ },+ }),+ ]);++ if (count > 0 && credential) {+ // The disconnect is done once the rows are gone; Zoom need not answer first.+ after(() => revokeZoomToken({ credential }));+ }+};diff --git a/apps/web/src/features/conferencing/service.ts b/apps/web/src/features/conferencing/service.tsindex 55436f911..4c910dfe8 100644--- a/apps/web/src/features/conferencing/service.ts+++ b/apps/web/src/features/conferencing/service.ts@@ -122,6 +122,42 @@ async function refreshZoomTokenIfExpired({scopes: tokens.scopes,};}+// Best effort: the tokens are already deleted locally, and a grant Zoom still+// holds is one the user can remove from their own Zoom app list.+export async function revokeZoomToken({+ credential,+}: {+ credential: NonNullable<Awaited<ReturnType<typeof loadCredential>>>;+}) {+ const { secret } = credential;+ if (!env.ZOOM_CLIENT_ID || !env.ZOOM_CLIENT_SECRET) {+ return;+ }++ const client = new ZoomOAuthClient({+ clientId: env.ZOOM_CLIENT_ID,+ clientSecret: env.ZOOM_CLIENT_SECRET,+ scopes: secret.scopes,+ });++ try {+ // Zoom rejects an expired access token, and they only live an hour, so+ // one that is stale, close to expiry or of unknown age is exchanged in+ // memory first, with the same margin refreshZoomTokenIfExpired uses.+ const expiresAt = secret.expiresAt+ ? new Date(secret.expiresAt)+ : credential.expiresAt;+ const isFresh = expiresAt && expiresAt.getTime() - 60_000 > Date.now();+ const accessToken =+ !isFresh && secret.refreshToken+ ? (await client.refreshAccessToken(secret.refreshToken)).accessToken+ : secret.accessToken;+ await client.revokeToken(accessToken);+ } catch (error) {+ logger.warn({ err: error }, "Failed to revoke Zoom token");+ }+}+async function createZoomMeeting({accessToken,title,diff --git a/apps/web/src/lib/oauth/providers/zoom.ts b/apps/web/src/lib/oauth/providers/zoom.tsindex 7451b260c..7cd1f29d8 100644--- a/apps/web/src/lib/oauth/providers/zoom.ts+++ b/apps/web/src/lib/oauth/providers/zoom.ts@@ -99,4 +99,12 @@ export class ZoomOAuthClient implements OAuthClient {handleOAuthError(error);}}++ async revokeToken(accessToken: string): Promise<void> {+ try {+ await this.client.revokeToken(accessToken);+ } catch (error) {+ handleOAuthError(error);+ }+ }}diff --git a/apps/web/tests/conferencing.spec.ts b/apps/web/tests/conferencing.spec.tsindex 01755aeb5..6af95d9c1 100644--- a/apps/web/tests/conferencing.spec.ts+++ b/apps/web/tests/conferencing.spec.ts@@ -7,29 +7,45 @@ import { createUserInDb, loginWithEmail } from "./test-utils";const runId = Date.now().toString(36);-// Seeds what the OAuth callback would have written, so the UI can be-// exercised without driving Zoom's consent screen.-async function seedZoomConnection(userId: string) {+async function seedCredential({+ userId,+ provider,+ providerAccountId,+ scopes,+}: {+ userId: string;+ provider: string;+ providerAccountId: string;+ scopes: string[];+}) {const secretPassword = process.env.SECRET_PASSWORD;if (!secretPassword) {throw new Error("SECRET_PASSWORD is required to seed a credential");}- const credential = await prisma.credential.create({+ return prisma.credential.create({data: {userId,- provider: "zoom",- providerAccountId: `zoom-${runId}`,+ provider,+ providerAccountId,type: "OAUTH",secret: encrypt(- JSON.stringify({- accessToken: "test-token",- scopes: ["meeting:write:meeting"],- }),+ JSON.stringify({ accessToken: "test-token", scopes }),secretPassword,),- scopes: ["meeting:write:meeting"],+ scopes,},});+}++// Seeds what the OAuth callback would have written, so the UI can be+// exercised without driving Zoom's consent screen.+async function seedZoomConnection(userId: string) {+ const credential = await seedCredential({+ userId,+ provider: "zoom",+ providerAccountId: `zoom-${runId}`,+ scopes: ["meeting:write:meeting"],+ });return prisma.conferencingConnection.create({data: {userId,@@ -191,5 +207,48 @@ test.describeexpect(await prisma.conferencingConnection.count({ where: { userId } }),).toBe(0);+ expect(+ await prisma.credential.count({ where: { userId, provider: "zoom" } }),+ ).toBe(0);+ });++ test("disconnecting Google Meet keeps a credential the calendar still uses", async () => {+ const providerAccountId = `google-${runId}`;+ const email = `organizer-${runId}@gmail.example`;+ const credential = await seedCredential({+ userId,+ provider: "google",+ providerAccountId,+ scopes: ["https://www.googleapis.com/auth/meetings.space.created"],+ });+ await prisma.calendarConnection.create({+ data: {+ userId,+ provider: "google",+ integrationId: "google-calendar",+ providerAccountId,+ email,+ credentialId: credential.id,+ },+ });+ await prisma.conferencingConnection.create({+ data: {+ userId,+ provider: "google",+ integrationId: "google-meet",+ providerAccountId,+ email,+ displayName: "Google Meet",+ credentialId: credential.id,+ },+ });++ await page.goto("/settings/conferencing");+ await page.getByRole("button", { name: "More options" }).click();+ await page.getByRole("menuitem", { name: "Disconnect" }).click();+ await expect(page.getByText("No accounts connected")).toBeVisible();+ expect(+ await prisma.credential.count({ where: { id: credential.id } }),+ ).toBe(1);});});