Comp AI CRM is an open source, CRM designed for AI agents. Agentic-first CRM.
TypeScript
feat(google-connection): enhance Google connection handling and error messaging
Lewis Carhart501b007b845f
diff --git a/apps/api/src/google/google-connection.service.ts b/apps/api/src/google/google-connection.service.tsindex 13fe8f7d..839bb938 100644--- a/apps/api/src/google/google-connection.service.ts+++ b/apps/api/src/google/google-connection.service.ts@@ -1,10 +1,11 @@-import { isGoogleConfigured } from "@crm/auth";+import { isGoogleConfigured, signsInWithGoogle } from "@crm/auth";import { type Db, GoogleSyncStatus } from "@crm/db";import { Injectable, Logger, NotFoundException } from "@nestjs/common";import { normalizeDomain } from "../companies/domain";import { ActivityStampService } from "../crm/activity-stamp.service";import { InjectDatabase } from "../database/database.constants";import {+ GOOGLE_PROVIDER_ID,SCOPE_FOR_SOURCE,SYNC_SOURCES,type SyncSource,@@ -25,6 +26,7 @@ export type SourceStatus = {export type ConnectionStatus = {configured: boolean;linked: boolean;+ required: boolean;hasRefreshToken: boolean;sources: SourceStatus[];};@@ -44,11 +46,11 @@ export class GoogleConnectionService {async status(userId: string): Promise<ConnectionStatus> {await this.onConnected(userId);- const [granted, rows, hasRefreshToken, linked] = await Promise.all([+ const [granted, rows, hasRefreshToken, accounts] = await Promise.all([this.tokens.grantedScopes(userId),this.state.listForUser(userId),this.tokens.hasRefreshToken(userId),- this.tokens.isLinked(userId),+ this.tokens.signInAccounts(userId),]);const bySource = new Map(rows.map((row) => [row.source, row]));@@ -69,7 +71,10 @@ export class GoogleConnectionService {return {configured: isGoogleConfigured(),- linked,+ linked: accounts.some(+ (account) => account.providerId === GOOGLE_PROVIDER_ID,+ ),+ required: signsInWithGoogle(accounts),hasRefreshToken,sources,};diff --git a/apps/api/src/google/google-token.service.ts b/apps/api/src/google/google-token.service.tsindex c2cebc59..41586fd2 100644--- a/apps/api/src/google/google-token.service.ts+++ b/apps/api/src/google/google-token.service.ts@@ -1,4 +1,4 @@-import { auth } from "@crm/auth";+import { auth, type SignInAccount } from "@crm/auth";import { type Db } from "@crm/db";import { Injectable, Logger } from "@nestjs/common";import { InjectDatabase } from "../database/database.constants";@@ -39,13 +39,11 @@ export class GoogleTokenService {return scopes.includes(SCOPE_FOR_SOURCE[source]);}- async isLinked(userId: string): Promise<boolean> {- const account = await this.db.account.findFirst({- where: { userId, providerId: GOOGLE_PROVIDER_ID },- select: { id: true },+ async signInAccounts(userId: string): Promise<SignInAccount[]> {+ return this.db.account.findMany({+ where: { userId },+ select: { providerId: true, scope: true },});-- return account !== null;}async hasRefreshToken(userId: string): Promise<boolean> {diff --git a/apps/app/app/(app)/settings/connections/google-connection.tsx b/apps/app/app/(app)/settings/connections/google-connection.tsxindex ac114290..c346fd6b 100644--- a/apps/app/app/(app)/settings/connections/google-connection.tsx+++ b/apps/app/app/(app)/settings/connections/google-connection.tsx@@ -121,7 +121,12 @@ function GoogleUnavailable() {);}-function ConnectGoogle() {+const CONNECT_ERRORS: Record<string, string> = {+ "email_doesn't_match":+ "That Google account has a different email address to the one you sign in with, so it cannot be attached to your account. Connect the Google account that matches your sign-in address.",+};++function ConnectGoogle({ connectError }: { connectError?: string }) {const [pending, setPending] = useState(false);async function handleConnect() {@@ -158,6 +163,17 @@ function ConnectGoogle() {</CardHeader><CardContent>+ {connectError ? (+ <Alert variant="destructive">+ <Icon icon={Warning} />+ <AlertTitle>Google did not finish connecting</AlertTitle>+ <AlertDescription>+ {CONNECT_ERRORS[connectError] ??+ "Google returned an error before the connection was made. Try again."}+ </AlertDescription>+ </Alert>+ ) : null}+<Button disabled={pending} onClick={handleConnect} type="button">{pending ? (<Spinner data-icon="inline-start" />@@ -176,7 +192,7 @@ function ConnectGoogle() {);}-export function GoogleConnection() {+export function GoogleConnection({ connectError }: { connectError?: string }) {const trpc = useTRPC();const cache = useCrmCache();const queryClient = useQueryClient();@@ -201,7 +217,10 @@ export function GoogleConnection() {const revoke = useMutation(trpc.google.revokeAccess.mutationOptions({- onSuccess: () => window.location.assign("/"),+ onSuccess: () =>+ window.location.assign(+ status.data?.required ? "/" : "/settings/connections",+ ),onError: (error) => toast.error(error.message),}),);@@ -234,10 +253,11 @@ export function GoogleConnection() {if (!status.data) return null;- const { sources, hasRefreshToken, configured, linked } = status.data;+ const { sources, hasRefreshToken, configured, linked, required } =+ status.data;if (!configured) return <GoogleUnavailable />;- if (!linked) return <ConnectGoogle />;+ if (!linked) return <ConnectGoogle connectError={connectError} />;const failing = sources.filter((source) => source.status === "NEEDS_RECONNECT" || source.lastError,@@ -395,8 +415,9 @@ export function GoogleConnection() {<AlertDialogHeader><AlertDialogTitle>Revoke Google access?</AlertDialogTitle><AlertDialogDescription>- You will be signed out, and you cannot use the CRM again- until you grant access.+ {required+ ? "You will be signed out, and you cannot use the CRM again until you grant access."+ : "New email and meetings stop arriving. Everything already synced stays, and you can connect Google again from this page."}</AlertDialogDescription></AlertDialogHeader>diff --git a/apps/app/app/(app)/settings/connections/page.tsx b/apps/app/app/(app)/settings/connections/page.tsxindex 7614c5dd..e8d7d646 100644--- a/apps/app/app/(app)/settings/connections/page.tsx+++ b/apps/app/app/(app)/settings/connections/page.tsx@@ -16,13 +16,20 @@ export const metadata: Metadata = {title: "Connections",};-export default async function ConnectionsSettingsPage() {+export default async function ConnectionsSettingsPage({+ searchParams,+}: {+ searchParams: Promise<{ error?: string | string[] }>;+}) {await requireSession();const trpc = getServerTrpc();const queryClient = getServerQueryClient();- await queryClient.prefetchQuery(trpc.google.status.queryOptions());+ const [{ error }] = await Promise.all([+ searchParams,+ queryClient.prefetchQuery(trpc.google.status.queryOptions()),+ ]);return (<PageShell>@@ -38,7 +45,9 @@ export default async function ConnectionsSettingsPage() {<PageShellContent><HydrateClient><div className="flex max-w-3xl flex-col gap-6">- <GoogleConnection />+ <GoogleConnection+ connectError={Array.isArray(error) ? error[0] : error}+ /></div></HydrateClient></PageShellContent>diff --git a/packages/auth/src/index.ts b/packages/auth/src/index.tsindex 50f830e5..57ae55b8 100644--- a/packages/auth/src/index.ts+++ b/packages/auth/src/index.ts@@ -22,6 +22,7 @@ export {REQUIRED_SCOPES,type SignInAccount,SYNC_SCOPES,+ signsInWithGoogle,} from "./scopes";export { onSignedIn, type SignedInHandler } from "./signed-in";export {diff --git a/packages/auth/src/scopes.ts b/packages/auth/src/scopes.tsindex 8f667489..ce3ca7ff 100644--- a/packages/auth/src/scopes.ts+++ b/packages/auth/src/scopes.ts@@ -20,20 +20,17 @@ export type SignInAccount = {scope?: string | null;};-export function needsGoogleGrant(accounts: readonly SignInAccount[]): boolean {- const google = accounts.find(- (account) => account.providerId === GOOGLE_PROVIDER_ID,- );-- if (!google) return false;-- const viaSso = accounts.some(- (account) => account.providerId !== GOOGLE_PROVIDER_ID,+export function signsInWithGoogle(accounts: readonly SignInAccount[]): boolean {+ return (+ accounts.length > 0 &&+ accounts.every((account) => account.providerId === GOOGLE_PROVIDER_ID));+}- if (viaSso) return false;+export function needsGoogleGrant(accounts: readonly SignInAccount[]): boolean {+ if (!signsInWithGoogle(accounts)) return false;- return !hasSyncScopes(google.scope);+ return !accounts.some((account) => hasSyncScopes(account.scope));}export function parseScopes(scope: string | null | undefined): Set<string> {diff --git a/packages/auth/test/google-grant.spec.ts b/packages/auth/test/google-grant.spec.tsindex 149c08db..76cad1a8 100644--- a/packages/auth/test/google-grant.spec.ts+++ b/packages/auth/test/google-grant.spec.ts@@ -1,5 +1,9 @@import { describe, expect, it } from "bun:test";-import { needsGoogleGrant, SYNC_SCOPES } from "../src/scopes";+import {+ needsGoogleGrant,+ SYNC_SCOPES,+ signsInWithGoogle,+} from "../src/scopes";const GRANTED = SYNC_SCOPES.join(",");@@ -50,3 +54,24 @@ describe("who has to grant Gmail and Calendar", () => {expect(needsGoogleGrant([])).toBe(false);});});++describe("whether revoking Google costs someone the CRM", () => {+ it("is true when Google is the only way in", () => {+ expect(signsInWithGoogle([{ providerId: "google", scope: GRANTED }])).toBe(+ true,+ );+ });++ it("is false once an IdP is also on the account", () => {+ expect(+ signsInWithGoogle([+ { providerId: "okta", scope: null },+ { providerId: "google", scope: GRANTED },+ ]),+ ).toBe(false);+ });++ it("is false for an account with nothing linked", () => {+ expect(signsInWithGoogle([])).toBe(false);+ });+});