Skip to content

Open source alternative to Semrush and Ahrefs

Simplify Google integrations and support full account removal (#598)

Ben Senescu1940928e3235
diff --git a/src/client/features/ga4/Ga4PropertyPicker.tsx b/src/client/features/ga4/Ga4PropertyPicker.tsx
index e873c445..630a3c63 100644
--- a/src/client/features/ga4/Ga4PropertyPicker.tsx
+++ b/src/client/features/ga4/Ga4PropertyPicker.tsx
@@ -1,6 +1,4 @@
-import { GoogleGlyph } from "@/client/features/gsc/GoogleGlyph";
-import { startGoogleLink } from "@/client/features/integrations/startGoogleLink";
-
+import { GooglePropertyPicker } from "@/client/features/integrations/GooglePropertyPicker";
type PropertyOption = {
propertyId: string;
displayName: string;
@@ -21,214 +19,34 @@ export type Ga4PropertySelection = {
propertyId: string;
};
-type SecondaryAction = {
- label: string;
- onClick: () => void;
- destructive?: boolean;
- disabled?: boolean;
-};
-
-export function Ga4PropertyPicker({
- loading,
- error,
- accounts,
- selection,
- onSelect,
- onSave,
- saving,
- onRetry,
- secondaryAction,
-}: {
+export function Ga4PropertyPicker(props: {
+ readOnly?: boolean;
loading: boolean;
+ linking?: boolean;
error: boolean;
accounts: AccountOption[];
selection: Ga4PropertySelection | null;
- onSelect: (selection: Ga4PropertySelection) => void;
+ onSelect: (selection: Ga4PropertySelection | null) => void;
onSave: () => void;
saving: boolean;
onRetry: () => void;
- secondaryAction?: SecondaryAction;
-}) {
- if (loading) {
- return (
- <div className="flex items-center gap-2 text-sm text-base-content/50">
- <span className="loading loading-spinner loading-sm" />
- Loading properties…
- </div>
- );
- }
- if (error) {
- return (
- <div className="space-y-3">
- <p className="text-sm text-error">
- Couldn&rsquo;t load your Google Analytics properties.
- </p>
- <div className="flex flex-wrap items-center gap-1">
- <button
- type="button"
- className="btn btn-ghost btn-sm"
- onClick={onRetry}
- >
- Try again
- </button>
- {secondaryAction ? (
- <SecondaryActionButton action={secondaryAction} />
- ) : null}
- </div>
- </div>
- );
- }
-
- const allAccountsRequireReconnect =
- accounts.length > 0 &&
- accounts.every((account) => account.requiresReconnect);
- if (allAccountsRequireReconnect) {
- return (
- <div className="space-y-3">
- <p className="text-sm text-error">
- Connection expired. Reconnect to continue.
- </p>
- <div className="flex flex-wrap items-center gap-1">
- <GoogleConnectButton
- label="Reconnect with Google"
- onClick={() => void startGoogleLink("ga4", window.location.href)}
- />
- {secondaryAction ? (
- <SecondaryActionButton action={secondaryAction} />
- ) : null}
- </div>
- </div>
- );
- }
-
- const usableAccounts = accounts.filter(
- (account) => !account.requiresReconnect && !account.propertiesUnavailable,
- );
- const options = usableAccounts.flatMap((account) =>
- account.properties.map((property) => ({
- accountId: account.accountId,
- propertyId: property.propertyId,
- })),
- );
- const selectedIndex = selection
- ? options.findIndex(
- (option) =>
- option.accountId === selection.accountId &&
- option.propertyId === selection.propertyId,
- )
- : -1;
- const hasUnavailableAccounts = accounts.some(
- (account) => account.propertiesUnavailable,
- );
-
- return (
- <div className="space-y-4">
- {hasUnavailableAccounts ? (
- <p className="text-sm text-warning">
- Some properties couldn&rsquo;t be loaded. Check that the Analytics
- Admin API is enabled and that this Google account has property access.
- </p>
- ) : null}
- <label className="block">
- <span className="mb-1.5 block text-sm font-medium text-base-content/80">
- Property
- </span>
- <select
- className="select select-bordered w-full max-w-md"
- value={selectedIndex >= 0 ? String(selectedIndex) : ""}
- onChange={(event) => {
- const option = options[Number(event.target.value)];
- if (option) onSelect(option);
- }}
- >
- <option value="" disabled>
- Select a property…
- </option>
- {usableAccounts.map((account) => (
- <optgroup
- key={account.accountId}
- label={account.email ?? "Google account"}
- >
- {account.properties.length === 0 ? (
- <option disabled>No properties</option>
- ) : (
- account.properties.map((property) => {
- const index = options.findIndex(
- (option) =>
- option.accountId === account.accountId &&
- option.propertyId === property.propertyId,
- );
- return (
- <option key={property.propertyId} value={index}>
- {property.accountDisplayName} · {property.displayName}
- </option>
- );
- })
- )}
- </optgroup>
- ))}
- </select>
- </label>
- {options.length === 0 && !hasUnavailableAccounts ? (
- <p className="text-sm text-base-content/60">
- No Google Analytics properties are available for this account.
- </p>
- ) : null}
- <div className="flex flex-wrap items-center gap-1">
- <button
- type="button"
- className="btn btn-primary btn-sm"
- onClick={onSave}
- disabled={selectedIndex < 0 || saving}
- >
- {saving ? "Saving…" : "Save property"}
- </button>
- <button
- type="button"
- className="btn btn-ghost btn-sm"
- onClick={() => void startGoogleLink("ga4", window.location.href)}
- >
- Connect another Google account
- </button>
- {secondaryAction ? (
- <SecondaryActionButton action={secondaryAction} />
- ) : null}
- </div>
- </div>
- );
-}
-
-function SecondaryActionButton({ action }: { action: SecondaryAction }) {
- return (
- <button
- type="button"
- className={[
- "btn btn-ghost btn-sm",
- action.destructive ? "text-error hover:bg-error/10" : "",
- ].join(" ")}
- onClick={action.onClick}
- disabled={action.disabled}
- >
- {action.label}
- </button>
- );
-}
-
-function GoogleConnectButton({
- label,
- onClick,
-}: {
- label: string;
- onClick: () => void;
+ onReconnect: () => void;
+ secondaryAction?: { label: string; onClick: () => void; disabled?: boolean };
}) {
return (
- <button
- type="button"
- onClick={onClick}
- className="inline-flex items-center gap-2.5 rounded-lg border border-base-300 bg-base-100 px-4 py-2.5 text-sm font-semibold shadow-sm transition hover:bg-base-200"
- >
- <GoogleGlyph className="size-[18px]" />
- {label}
- </button>
+ <GooglePropertyPicker
+ {...props}
+ provider="ga4"
+ accounts={props.accounts.map((account) => ({
+ ...account,
+ unavailable: account.propertiesUnavailable,
+ properties: account.properties.map((property) => ({
+ id: property.propertyId,
+ name: property.displayName,
+ detail: `${property.accountDisplayName} · ${property.propertyId.replace(/^properties\//, "")}`,
+ selectable: true,
+ })),
+ }))}
+ />
);
}
diff --git a/src/client/features/ga4/GoogleAnalyticsConnectionCard.tsx b/src/client/features/ga4/GoogleAnalyticsConnectionCard.tsx
index d57b378b..833f21cd 100644
--- a/src/client/features/ga4/GoogleAnalyticsConnectionCard.tsx
+++ b/src/client/features/ga4/GoogleAnalyticsConnectionCard.tsx
@@ -1,22 +1,23 @@
+import { ga4ConnectionOptions } from "@/client/features/integrations/googleConnectionQueries";
import * as React from "react";
+import { GoogleConnectedState } from "@/client/features/integrations/GoogleConnectedState";
+import { useGooglePickerResume } from "@/client/features/integrations/useGooglePickerResume";
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { toast } from "sonner";
import {
Ga4PropertyPicker,
type Ga4PropertySelection,
} from "@/client/features/ga4/Ga4PropertyPicker";
-import { GoogleGlyph } from "@/client/features/gsc/GoogleGlyph";
+import { GoogleProjectEmptyState } from "@/client/features/integrations/GoogleProjectEmptyState";
import { GoogleLinkErrorAlert } from "@/client/features/integrations/GoogleLinkErrorAlert";
import { GoogleOAuthSetupWarning } from "@/client/features/integrations/GoogleOAuthSetupWarning";
import { IntegrationConnectionCard } from "@/client/features/integrations/IntegrationConnectionCard";
import { GoogleAnalyticsLogo } from "@/client/features/integrations/GoogleProductLogos";
-import { startGoogleLink } from "@/client/features/integrations/startGoogleLink";
import { getStandardErrorMessage } from "@/client/lib/error-messages";
import { captureClientEvent } from "@/client/lib/posthog";
import { isHostedClientAuthMode } from "@/lib/auth-mode";
import {
disconnectGa4,
- getGa4Connection,
listGa4Properties,
setGa4Property,
} from "@/serverFunctions/ga4";
@@ -35,20 +36,24 @@ export function GoogleAnalyticsConnectionCard({
}) {
const hosted = isHostedClientAuthMode();
const queryClient = useQueryClient();
- const [picking, setPicking] = React.useState(false);
+ const { picking, setPicking, linkAccount, linking } = useGooglePickerResume(
+ "ga4",
+ projectId,
+ );
const [selection, setSelection] = React.useState<Ga4PropertySelection | null>(
null,
);
- const connectionKey = ["ga4Connection", projectId];
- const connectionQuery = useQuery({
- queryKey: connectionKey,
- queryFn: () => getGa4Connection({ data: { projectId } }),
- });
+ const connectionOptions = ga4ConnectionOptions(projectId);
+ const connectionKey = connectionOptions.queryKey;
+ const connectionQuery = useQuery(connectionOptions);
const connection = connectionQuery.data;
+ const connectionUnavailable = connectionQuery.isError && !connection;
const connected = Boolean(connection?.connected);
+ const hasGrant = Boolean(connection?.currentUserHasGrant);
+ const canManage = connection?.canManage === true;
const selfHostedNeedsSetup =
!hosted && connectionQuery.isSuccess && !connection?.googleOAuthConfigured;
- const showPicker = picking || (connection?.currentUserHasGrant && !connected);
+ const showPicker = picking ?? (!connected && hasGrant && canManage);
const propertiesQuery = useQuery({
queryKey: ["ga4Properties", projectId],
queryFn: () => listGa4Properties({ data: { projectId } }),
@@ -60,7 +65,7 @@ export function GoogleAnalyticsConnectionCard({
);
React.useEffect(() => {
- if (selection) return;
+ if (!picking || !connected || selection) return;
for (const account of accounts) {
const selectedProperty = account.properties.find(
(property) => property.isSelected,
@@ -73,10 +78,9 @@ export function GoogleAnalyticsConnectionCard({
return;
}
}
- }, [accounts, selection]);
+ }, [accounts, selection, picking, connected]);
- const invalidateConnectionState = () => {
- void queryClient.invalidateQueries({ queryKey: connectionKey });
+ const invalidateReports = () => {
void queryClient.invalidateQueries({
queryKey: ["dashboardActivation", projectId],
});
@@ -87,25 +91,36 @@ export function GoogleAnalyticsConnectionCard({
const setPropertyMutation = useMutation({
mutationFn: (selected: Ga4PropertySelection) =>
setGa4Property({ data: { projectId, ...selected } }),
- onSuccess: () => {
+ onSuccess: (saved) => {
+ queryClient.setQueryData(connectionKey, (current: typeof connection) =>
+ current ? { ...current, ...saved } : current,
+ );
captureClientEvent("ga4:property_select");
toast.success("Google Analytics connected");
+ queryClient.removeQueries({ queryKey: ["ga4Properties", projectId] });
+ void queryClient.invalidateQueries({ queryKey: connectionKey });
setPicking(false);
- invalidateConnectionState();
+ invalidateReports();
},
- onError: (error) => toast.error(getStandardErrorMessage(error)),
});
const disconnectMutation = useMutation({
mutationFn: () => disconnectGa4({ data: { projectId } }),
onSuccess: () => {
- toast.success("Google Analytics disconnected");
+ toast.success("Google Analytics disconnected from this project");
+ queryClient.setQueryData(connectionKey, (current: typeof connection) =>
+ current ? { ...current, connected: false } : current,
+ );
+ queryClient.removeQueries({ queryKey: ["ga4Properties", projectId] });
setPicking(false);
setSelection(null);
- invalidateConnectionState();
+ void queryClient.invalidateQueries({ queryKey: connectionKey });
+ invalidateReports();
},
- onError: (error) => toast.error(getStandardErrorMessage(error)),
});
- const handleConnect = () => void startGoogleLink("ga4", window.location.href);
+ const changingConnection =
+ setPropertyMutation.isPending || disconnectMutation.isPending || linking;
+ const dismissDisabled = dismissing || changingConnection;
+ const handleConnect = () => void linkAccount(window.location.href);
return (
<>
@@ -114,7 +129,7 @@ export function GoogleAnalyticsConnectionCard({
title="Google Analytics"
icon={<GoogleAnalyticsLogo className="size-5" />}
status={
- connectionQuery.isLoading
+ connectionQuery.isPending || connectionUnavailable
? undefined
: selfHostedNeedsSetup
? "setup_required"
@@ -124,10 +139,27 @@ export function GoogleAnalyticsConnectionCard({
}
>
<GoogleLinkErrorAlert provider="ga4" className="mb-4" />
- {connectionQuery.isLoading ? (
- <div className="flex items-center gap-2 text-sm text-base-content/50">
- <span className="loading loading-spinner loading-sm" />
- Checking…
+ {connectionQuery.isPending ? (
+ <div
+ role="status"
+ aria-label="Loading connection"
+ className="space-y-3 animate-pulse"
+ >
+ <div className="h-4 w-2/3 rounded bg-base-200" />
+ <div className="h-9 w-24 rounded bg-base-200" />
+ </div>
+ ) : connectionUnavailable ? (
+ <div role="alert" className="space-y-3 text-sm">
+ <p className="text-error">
+ Couldn't check this project's connection.
+ </p>
+ <button
+ type="button"
+ className="btn btn-ghost btn-sm"
+ onClick={() => void connectionQuery.refetch()}
+ >
+ Try again
+ </button>
</div>
) : selfHostedNeedsSetup ? (
<div className="space-y-3">
@@ -135,72 +167,86 @@ export function GoogleAnalyticsConnectionCard({
integrationName="Google Analytics"
docsUrl={GA4_SELF_HOSTED_SETUP_DOCS_URL}
/>
- {onDismiss ? (
- <DismissButton onClick={onDismiss} disabled={dismissing} />
- ) : null}
+ <DismissButton onClick={onDismiss} disabled={dismissDisabled} />
</div>
) : connected && !picking ? (
- <ConnectedState
- displayName={connection?.propertyDisplayName ?? ""}
- propertyId={connection?.propertyId ?? ""}
- timeZone={connection?.propertyTimeZone ?? ""}
- currencyCode={connection?.propertyCurrencyCode ?? ""}
- connectedByEmail={connection?.connectedByEmail ?? null}
+ <GoogleConnectedState
+ property={connection?.propertyDisplayName ?? ""}
+ detail={connection?.propertyId}
+ canManageAccounts={hasGrant}
+ email={connection?.connectedByEmail}
onChange={() => {
+ setPropertyMutation.reset();
+ disconnectMutation.reset();
setSelection(null);
setPicking(true);
}}
- onDisconnect={() => disconnectMutation.mutate()}
+ onDisconnect={() => {
+ setPropertyMutation.reset();
+ disconnectMutation.mutate();
+ }}
disconnecting={disconnectMutation.isPending}
+ disabled={linking}
+ canManage={canManage}
/>
) : showPicker ? (
- <Ga4PropertyPicker
- loading={propertiesQuery.isLoading}
- error={propertiesQuery.isError}
- accounts={accounts}
- selection={selection}
- onSelect={setSelection}
- onSave={() => selection && setPropertyMutation.mutate(selection)}
- saving={setPropertyMutation.isPending}
- onRetry={() => void propertiesQuery.refetch()}
- secondaryAction={
- connected
- ? { label: "Cancel", onClick: () => setPicking(false) }
- : onDismiss
- ? {
- label: "Dismiss",
- disabled: dismissing,
- onClick: onDismiss,
- }
- : {
- label: "Disconnect",
- destructive: true,
- disabled: disconnectMutation.isPending,
- onClick: () => disconnectMutation.mutate(),
- }
- }
- />
+ <fieldset disabled={changingConnection}>
+ <Ga4PropertyPicker
+ readOnly={!canManage}
+ linking={linking}
+ loading={propertiesQuery.isLoading}
+ error={propertiesQuery.isError}
+ accounts={accounts}
+ selection={selection}
+ onSelect={setSelection}
+ onSave={() => selection && setPropertyMutation.mutate(selection)}
+ saving={setPropertyMutation.isPending}
+ secondaryAction={{
+ label: "Cancel",
+ disabled: setPropertyMutation.isPending,
+ onClick: () => {
+ setPicking(false);
+ setSelection(null);
+ setPropertyMutation.reset();
+ },
+ }}
+ onRetry={() => void propertiesQuery.refetch()}
+ onReconnect={handleConnect}
+ />
+ </fieldset>
) : (
- <div className="space-y-4">
- <p className="text-sm text-base-content/70">
- Connect GA4 to understand what organic visitors do after they land
- on your site.
- </p>
- <div className="flex flex-wrap items-center gap-1">
- <button
- type="button"
- onClick={handleConnect}
- className="inline-flex items-center gap-2.5 rounded-lg border border-base-300 bg-base-100 px-4 py-2.5 text-sm font-semibold text-base-content shadow-sm transition hover:bg-base-200 hover:shadow focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-primary"
- >
- <GoogleGlyph className="size-[18px]" />
- Connect with Google
- </button>
- {onDismiss ? (
- <DismissButton onClick={onDismiss} disabled={dismissing} />
- ) : null}
- </div>
- </div>
+ <GoogleProjectEmptyState
+ name="Google Analytics"
+ hasGrant={hasGrant}
+ canManage={canManage}
+ disabled={linking}
+ onLink={handleConnect}
+ onChoose={() => {
+ setPropertyMutation.reset();
+ disconnectMutation.reset();
+ setSelection(null);
+ setPicking(true);
+ }}
+ >
+ <DismissButton onClick={onDismiss} disabled={dismissDisabled} />
+ </GoogleProjectEmptyState>
)}
+ {showPicker && onDismiss && !connected ? (
+ <DismissButton onClick={onDismiss} disabled={dismissDisabled} />
+ ) : null}
+ {setPropertyMutation.isError || disconnectMutation.isError ? (
+ <p role="alert" className="mt-3 text-sm text-error">
+ {getStandardErrorMessage(
+ setPropertyMutation.error ?? disconnectMutation.error,
+ )}
+ </p>
+ ) : null}
+ {connectionQuery.isSuccess && !selfHostedNeedsSetup && !canManage ? (
+ <p className="mt-3 text-sm text-base-content/60">
+ Ask an organization owner or admin to change this project's
+ connection.
+ </p>
+ ) : null}
</IntegrationConnectionCard>
</>
);
@@ -210,9 +256,10 @@ function DismissButton({
onClick,
disabled,
}: {
- onClick: () => void;
+ onClick?: () => void;
disabled: boolean;
}) {
+ if (!onClick) return null;
return (
<button
type="button"
@@ -224,85 +271,3 @@ function DismissButton({
</button>
);
}
-
-function ConnectedState({
- displayName,
- propertyId,
- timeZone,
- currencyCode,
- connectedByEmail,
- onChange,
- onDisconnect,
- disconnecting,
-}: {
- displayName: string;
- propertyId: string;
- timeZone: string;
- currencyCode: string;
- connectedByEmail: string | null;
- onChange: () => void;
- onDisconnect: () => void;
- disconnecting: boolean;
-}) {
- const numericPropertyId = propertyId.replace(/^properties\//, "");
-
- return (
- <div className="space-y-3">
- <div className="rounded-lg border border-base-300 bg-base-200/30 px-4 py-3.5">
- <div className="flex flex-wrap items-start justify-between gap-x-4 gap-y-2">
- <div className="min-w-0">
- <p className="text-[11px] font-medium uppercase tracking-wide text-base-content/45">
- Selected property
- </p>
- <p className="mt-0.5 truncate text-sm font-semibold">
- {displayName}
- </p>
- </div>
- <span className="rounded-md border border-base-300 bg-base-100 px-2 py-1 font-mono text-[11px] text-base-content/60">
- ID {numericPropertyId}
- </span>
- </div>
-
- <dl className="mt-3 grid gap-x-6 gap-y-2 border-t border-base-300/70 pt-3 text-xs sm:grid-cols-3">
- <div className="min-w-0">
- <dt className="text-base-content/45">Time zone</dt>
- <dd className="mt-0.5 truncate font-medium text-base-content/75">
- {timeZone}
- </dd>
- </div>
- <div>
- <dt className="text-base-content/45">Currency</dt>
- <dd className="mt-0.5 font-medium text-base-content/75">
- {currencyCode}
- </dd>
- </div>
- {connectedByEmail ? (
- <div className="min-w-0">
- <dt className="text-base-content/45">Connected account</dt>
- <dd className="mt-0.5 truncate font-medium text-base-content/75">
- {connectedByEmail}
- </dd>
- </div>
- ) : null}
- </dl>
- </div>
- <div className="flex flex-wrap items-center gap-2">
- <button
- type="button"
- className="btn btn-outline btn-sm border-base-300 font-medium"
- onClick={onChange}
- >
- Change property
- </button>
- <button
- type="button"
- className="btn btn-ghost btn-sm font-medium text-error hover:bg-error/10"
- onClick={onDisconnect}
- disabled={disconnecting}
- >
- {disconnecting ? "Disconnecting…" : "Disconnect"}
- </button>
- </div>
- </div>
- );
-}
diff --git a/src/client/features/gsc/SearchConsoleConnectionCard.tsx b/src/client/features/gsc/SearchConsoleConnectionCard.tsx
index 57709a21..256c0acc 100644
--- a/src/client/features/gsc/SearchConsoleConnectionCard.tsx
+++ b/src/client/features/gsc/SearchConsoleConnectionCard.tsx
@@ -1,10 +1,13 @@
+import { gscConnectionOptions } from "@/client/features/integrations/googleConnectionQueries";
import * as React from "react";
+import { GoogleConnectedState } from "@/client/features/integrations/GoogleConnectedState";
+import { useGooglePickerResume } from "@/client/features/integrations/useGooglePickerResume";
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { toast } from "sonner";
import { isHostedClientAuthMode } from "@/lib/auth-mode";
import { getStandardErrorMessage } from "@/client/lib/error-messages";
import { captureClientEvent } from "@/client/lib/posthog";
-import { GoogleGlyph } from "@/client/features/gsc/GoogleGlyph";
+import { GoogleProjectEmptyState } from "@/client/features/integrations/GoogleProjectEmptyState";
import { GoogleLinkErrorAlert } from "@/client/features/integrations/GoogleLinkErrorAlert";
import { IntegrationConnectionCard } from "@/client/features/integrations/IntegrationConnectionCard";
import { GoogleSearchConsoleLogo } from "@/client/features/integrations/GoogleProductLogos";
@@ -13,13 +16,7 @@ import {
SitePicker,
type GscSiteSelection,
} from "@/client/features/gsc/SitePicker";
-import { startGoogleLink } from "@/client/features/integrations/startGoogleLink";
-import {
- disconnectGsc,
- getGscConnection,
- listGscSites,
- setGscSite,
-} from "@/serverFunctions/gsc";
+import { disconnectGsc, listGscSites, setGscSite } from "@/serverFunctions/gsc";
const GRANT_STATUS_KEY = ["gscGrantStatus"];
@@ -32,22 +29,25 @@ export function SearchConsoleConnectionCard({
}) {
const hosted = isHostedClientAuthMode();
const queryClient = useQueryClient();
- const [picking, setPicking] = React.useState(false);
+ const { picking, setPicking, linkAccount, linking } = useGooglePickerResume(
+ "gsc",
+ projectId,
+ );
const [selection, setSelection] = React.useState<GscSiteSelection | null>(
null,
);
- const connectionKey = ["gscConnection", projectId];
- const connectionQuery = useQuery({
- queryKey: connectionKey,
- queryFn: () => getGscConnection({ data: { projectId } }),
- });
+ const connectionOptions = gscConnectionOptions(projectId);
+ const connectionKey = connectionOptions.queryKey;
+ const connectionQuery = useQuery(connectionOptions);
const connection = connectionQuery.data;
const connected = Boolean(connection?.connected);
+ const hasGrant = Boolean(connection?.currentUserHasGrant);
+ const canManage = connection?.canManage === true;
const selfHostedNeedsSetup =
!hosted && connectionQuery.isSuccess && !connection?.googleOAuthConfigured;
- const showPicker = picking || (connection?.currentUserHasGrant && !connected);
+ const showPicker = picking ?? (!connected && hasGrant && canManage);
const sitesQuery = useQuery({
queryKey: ["gscSites", projectId],
queryFn: () => listGscSites({ data: { projectId } }),
@@ -71,7 +71,7 @@ export function SearchConsoleConnectionCard({
}, [requiresReconnect, queryClient, projectId]);
React.useEffect(() => {
- if (selection) return;
+ if (!picking || !connected || selection) return;
for (const account of accounts) {
const selectedSite = account.sites.find((site) => site.isSelected);
if (selectedSite) {
@@ -82,16 +82,20 @@ export function SearchConsoleConnectionCard({
return;
}
}
- }, [accounts, selection]);
+ }, [accounts, selection, picking, connected]);
const setSiteMutation = useMutation({
mutationFn: (selected: GscSiteSelection) =>
setGscSite({ data: { projectId, ...selected } }),
- onSuccess: () => {
+ onSuccess: (saved) => {
+ queryClient.setQueryData(connectionKey, (current: typeof connection) =>
+ current ? { ...current, ...saved } : current,
+ );
captureClientEvent("gsc:property_select");
toast.success("Search Console connected");
- setPicking(false);
+ queryClient.removeQueries({ queryKey: ["gscSites", projectId] });
void queryClient.invalidateQueries({ queryKey: connectionKey });
+ setPicking(false);
void queryClient.invalidateQueries({ queryKey: GRANT_STATUS_KEY });
// The Search Performance report caches {connected:false}; refresh it so
// the page shows data right after connecting instead of the stale card.
@@ -110,18 +114,19 @@ export function SearchConsoleConnectionCard({
queryKey: ["dashboardGscReport", projectId],
});
},
- onError: (error) => toast.error(getStandardErrorMessage(error)),
});
const disconnectMutation = useMutation({
mutationFn: () => disconnectGsc({ data: { projectId } }),
onSuccess: () => {
- toast.success("Search Console disconnected");
+ toast.success("Search Console disconnected from this project");
+ queryClient.setQueryData(connectionKey, (current: typeof connection) =>
+ current ? { ...current, connected: false } : current,
+ );
+ queryClient.removeQueries({ queryKey: ["gscSites", projectId] });
setPicking(false);
setSelection(null);
void queryClient.invalidateQueries({ queryKey: connectionKey });
- // Disconnect can drop the account-level grant server-side; keep the
- // shared grant-status cache (onboarding step + re-engagement nudge) honest.
void queryClient.invalidateQueries({ queryKey: GRANT_STATUS_KEY });
void queryClient.invalidateQueries({
queryKey: ["searchPerformance", projectId],
@@ -136,18 +141,17 @@ export function SearchConsoleConnectionCard({
queryKey: ["dashboardGscReport", projectId],
});
},
- onError: (error) => toast.error(getStandardErrorMessage(error)),
});
const handleConnect = () =>
- void startGoogleLink("gsc", returnTo ?? window.location.href);
+ void linkAccount(returnTo ?? window.location.href);
return (
<IntegrationConnectionCard
title="Google Search Console"
icon={<GoogleSearchConsoleLogo className="size-5" />}
status={
- connectionQuery.isLoading
+ connectionQuery.isPending || (connectionQuery.isError && !connection)
? undefined
: selfHostedNeedsSetup
? "setup_required"
@@ -157,115 +161,102 @@ export function SearchConsoleConnectionCard({
}
>
<GoogleLinkErrorAlert provider="gsc" className="mb-4" />
- {connectionQuery.isLoading ? (
- <div className="flex items-center gap-2 text-sm text-base-content/50">
- <span className="loading loading-spinner loading-sm" />
- Checking…
+ {connectionQuery.isPending ? (
+ <div
+ role="status"
+ aria-label="Loading connection"
+ className="space-y-3 animate-pulse"
+ >
+ <div className="h-4 w-2/3 rounded bg-base-200" />
+ <div className="h-9 w-24 rounded bg-base-200" />
+ </div>
+ ) : connectionQuery.isError && !connection ? (
+ <div role="alert" className="space-y-3 text-sm">
+ <p className="text-error">
+ Couldn't check this project's connection.
+ </p>
+ <button
+ type="button"
+ className="btn btn-ghost btn-sm"
+ onClick={() => void connectionQuery.refetch()}
+ >
+ Try again
+ </button>
</div>
) : selfHostedNeedsSetup ? (
<SelfHostedSetupWarning />
) : connected && !picking ? (
- <ConnectedState
- siteUrl={connection?.siteUrl ?? ""}
- connectedByEmail={connection?.connectedByEmail ?? null}
+ <GoogleConnectedState
+ property={connection?.siteUrl ?? ""}
+ canManageAccounts={hasGrant}
+ email={connection?.connectedByEmail}
onChange={() => {
+ setSiteMutation.reset();
+ disconnectMutation.reset();
setSelection(null);
setPicking(true);
}}
- onDisconnect={() => disconnectMutation.mutate()}
+ onDisconnect={() => {
+ setSiteMutation.reset();
+ disconnectMutation.mutate();
+ }}
disconnecting={disconnectMutation.isPending}
+ disabled={linking}
+ canManage={canManage}
/>
) : showPicker ? (
- <SitePicker
- loading={sitesQuery.isLoading}
- error={sitesQuery.isError}
- accounts={accounts}
- selection={selection}
- onSelect={setSelection}
- onSave={() => selection && setSiteMutation.mutate(selection)}
- saving={setSiteMutation.isPending}
- onRetry={() => void sitesQuery.refetch()}
- onReconnect={handleConnect}
- secondaryAction={
- connected
- ? { label: "Cancel", onClick: () => setPicking(false) }
- : {
- label: "Disconnect",
- destructive: true,
- disabled: disconnectMutation.isPending,
- onClick: () => disconnectMutation.mutate(),
- }
- }
- />
+ <fieldset disabled={linking || setSiteMutation.isPending}>
+ <SitePicker
+ readOnly={!canManage}
+ linking={linking}
+ loading={sitesQuery.isLoading}
+ error={sitesQuery.isError}
+ accounts={accounts}
+ selection={selection}
+ onSelect={setSelection}
+ onSave={() => selection && setSiteMutation.mutate(selection)}
+ saving={setSiteMutation.isPending}
+ secondaryAction={{
+ label: "Cancel",
+ disabled: setSiteMutation.isPending,
+ onClick: () => {
+ setPicking(false);
+ setSelection(null);
+ setSiteMutation.reset();
+ },
+ }}
+ onRetry={() => void sitesQuery.refetch()}
+ onReconnect={handleConnect}
+ />
+ </fieldset>
) : (
- <div className="space-y-4">
- <p className="text-sm text-base-content/70">
- Connect GSC to see how your website is actually performing in Google
- Search.
- </p>
- <button
- type="button"
- onClick={handleConnect}
- className="inline-flex items-center gap-2.5 rounded-lg border border-base-300 bg-base-100 px-4 py-2.5 text-sm font-semibold text-base-content shadow-sm transition hover:bg-base-200 hover:shadow focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-primary"
- >
- <GoogleGlyph className="size-[18px]" />
- Connect with Google
- </button>
- </div>
+ <GoogleProjectEmptyState
+ name="Search Console"
+ hasGrant={hasGrant}
+ canManage={canManage}
+ disabled={linking}
+ onLink={handleConnect}
+ onChoose={() => {
+ setSiteMutation.reset();
+ disconnectMutation.reset();
+ setSelection(null);
+ setPicking(true);
+ }}
+ ></GoogleProjectEmptyState>
)}
+ {setSiteMutation.isError || disconnectMutation.isError ? (
+ <p role="alert" className="mt-3 text-sm text-error">
+ {getStandardErrorMessage(
+ setSiteMutation.error ?? disconnectMutation.error,
+ )}
+ </p>
+ ) : null}
+ {connectionQuery.isSuccess && !selfHostedNeedsSetup && !canManage ? (
+ <p className="mt-3 text-sm text-base-content/60">
+ Ask an organization owner or admin to change this project's
+ connection.
+ </p>
+ ) : null}
</IntegrationConnectionCard>
);
}
-
-// ---------------------------------------------------------------------------
-// Connected state
-// ---------------------------------------------------------------------------
-
-function ConnectedState({
- siteUrl,
- connectedByEmail,
- onChange,
- onDisconnect,
- disconnecting,
-}: {
- siteUrl: string;
- connectedByEmail: string | null;
- onChange: () => void;
- onDisconnect: () => void;
- disconnecting: boolean;
-}) {
- return (
- <div className="space-y-4">
- <div className="flex items-center gap-3 rounded-lg border border-base-300 bg-base-200/40 p-3.5">
- <div className="grid size-9 shrink-0 place-items-center rounded-md border border-base-300 bg-base-100">
- <GoogleSearchConsoleLogo className="size-5" />
- </div>
- <div className="min-w-0">
- <p className="truncate font-mono text-sm">{siteUrl}</p>
- {connectedByEmail ? (
- <p className="truncate text-xs text-base-content/55">
- Connected by {connectedByEmail}
- </p>
- ) : null}
- </div>
- </div>
- <div className="flex items-center gap-1">
- <button
- type="button"
- className="btn btn-ghost btn-sm"
- onClick={onChange}
- >
- Change property
- </button>
- <button
- type="button"
- className="btn btn-ghost btn-sm text-error hover:bg-error/10"
- onClick={onDisconnect}
- disabled={disconnecting}
- >
- Disconnect
- </button>
- </div>
- </div>
- );
-}
diff --git a/src/client/features/gsc/SitePicker.tsx b/src/client/features/gsc/SitePicker.tsx
index 066aed52..234272d1 100644
--- a/src/client/features/gsc/SitePicker.tsx
+++ b/src/client/features/gsc/SitePicker.tsx
@@ -1,6 +1,4 @@
-import { GoogleGlyph } from "@/client/features/gsc/GoogleGlyph";
-import { startGoogleLink } from "@/client/features/integrations/startGoogleLink";
-
+import { GooglePropertyPicker } from "@/client/features/integrations/GooglePropertyPicker";
type SiteOption = {
siteUrl: string;
permissionLevel: string;
@@ -12,6 +10,7 @@ type AccountOption = {
accountId: string;
email: string | null;
requiresReconnect: boolean;
+ propertiesUnavailable: boolean;
sites: SiteOption[];
};
@@ -20,181 +19,51 @@ export type GscSiteSelection = {
siteUrl: string;
};
-type SecondaryAction = {
- label: string;
- onClick: () => void;
- destructive?: boolean;
- disabled?: boolean;
-};
-
-/**
- * Verified-property selector for connected Google accounts. Shared by the
- * Integrations card and the onboarding step. `secondaryAction` is optional —
- * omit it where there's nothing to cancel/disconnect (e.g. onboarding).
- */
-export function SitePicker({
- loading,
- error,
- accounts,
- selection,
- onSelect,
- onSave,
- saving,
- onRetry,
- onReconnect,
- secondaryAction,
-}: {
+export function SitePicker(props: {
+ readOnly?: boolean;
loading: boolean;
+ linking?: boolean;
error: boolean;
accounts: AccountOption[];
selection: GscSiteSelection | null;
- onSelect: (selection: GscSiteSelection) => void;
+ onSelect: (selection: GscSiteSelection | null) => void;
onSave: () => void;
saving: boolean;
onRetry: () => void;
onReconnect: () => void;
- secondaryAction?: SecondaryAction;
+ secondaryAction?: { label: string; onClick: () => void; disabled?: boolean };
}) {
- if (loading) {
- return (
- <div className="flex items-center gap-2 text-sm text-base-content/50">
- <span className="loading loading-spinner loading-sm" />
- Loading properties…
- </div>
- );
- }
- if (error) {
- return (
- <div className="space-y-3">
- <p className="text-sm text-error">
- Couldn't load your Search Console properties.
- </p>
- <button
- type="button"
- className="btn btn-ghost btn-sm"
- onClick={onRetry}
- >
- Try again
- </button>
- </div>
- );
- }
-
- const allAccountsRequireReconnect =
- accounts.length > 0 &&
- accounts.every((account) => account.requiresReconnect);
- if (allAccountsRequireReconnect) {
- return (
- <div className="space-y-3">
- <p className="text-sm text-error">
- Connection expired. Reconnect to continue.
- </p>
- <button
- type="button"
- onClick={onReconnect}
- className="inline-flex items-center gap-2.5 rounded-lg border border-base-300 bg-base-100 px-4 py-2.5 text-sm font-semibold shadow-sm transition hover:bg-base-200"
- >
- <GoogleGlyph className="size-[18px]" />
- Reconnect with Google
- </button>
- </div>
- );
- }
-
- const healthyAccounts = accounts.filter(
- (account) => !account.requiresReconnect,
- );
- const options = healthyAccounts.flatMap((account) =>
- account.sites.map((site) => ({
- accountId: account.accountId,
- siteUrl: site.siteUrl,
- })),
- );
- const selectedIndex = selection
- ? options.findIndex(
- (option) =>
- option.accountId === selection.accountId &&
- option.siteUrl === selection.siteUrl,
- )
- : -1;
-
return (
- <div className="space-y-4">
- <label className="block">
- <span className="mb-1.5 block text-sm font-medium text-base-content/80">
- Property
- </span>
- <select
- className="select select-bordered w-full max-w-md"
- value={selectedIndex >= 0 ? String(selectedIndex) : ""}
- onChange={(event) => {
- const option = options[Number(event.target.value)];
- if (option) onSelect(option);
- }}
- >
- <option value="" disabled>
- Select a property…
- </option>
- {healthyAccounts.map((account) => (
- <optgroup
- key={account.accountId}
- label={account.email ?? "Google account"}
- >
- {account.sites.length === 0 ? (
- <option disabled>No properties</option>
- ) : (
- account.sites.map((site) => {
- const index = options.findIndex(
- (option) =>
- option.accountId === account.accountId &&
- option.siteUrl === site.siteUrl,
- );
- return (
- <option
- key={site.siteUrl}
- value={index}
- disabled={!site.selectable}
- >
- {site.siteUrl}
- {site.selectable ? "" : " (no access)"}
- </option>
- );
- })
- )}
- </optgroup>
- ))}
- </select>
- </label>
- <div className="flex flex-wrap items-center gap-1">
- <button
- type="button"
- className="btn btn-primary btn-sm"
- onClick={onSave}
- disabled={selectedIndex < 0 || saving}
- >
- {saving ? "Saving…" : "Save property"}
- </button>
- <button
- type="button"
- className="btn btn-ghost btn-sm"
- onClick={() => void startGoogleLink("gsc", window.location.href)}
- >
- Connect another Google account
- </button>
- {secondaryAction ? (
- <button
- type="button"
- className={[
- "btn btn-ghost btn-sm",
- secondaryAction.destructive ? "text-error hover:bg-error/10" : "",
- ].join(" ")}
- onClick={secondaryAction.onClick}
- disabled={secondaryAction.disabled}
- >
- {secondaryAction.label}
- </button>
- ) : null}
- </div>
- </div>
+ <GooglePropertyPicker
+ {...props}
+ provider="gsc"
+ accounts={props.accounts.map((account) => ({
+ ...account,
+ unavailable: account.propertiesUnavailable,
+ properties: account.sites.map((site) => ({
+ id: site.siteUrl,
+ name: site.siteUrl,
+ selectable: site.selectable,
+ })),
+ }))}
+ selection={
+ props.selection
+ ? {
+ accountId: props.selection.accountId,
+ propertyId: props.selection.siteUrl,
+ }
+ : null
+ }
+ onSelect={(selection) =>
+ props.onSelect(
+ selection
+ ? {
+ accountId: selection.accountId,
+ siteUrl: selection.propertyId,
+ }
+ : null,
+ )
+ }
+ />
);
}
diff --git a/src/client/features/integrations/GoogleAccountRemovalDialog.tsx b/src/client/features/integrations/GoogleAccountRemovalDialog.tsx
new file mode 100644
index 00000000..21ca7f79
--- /dev/null
+++ b/src/client/features/integrations/GoogleAccountRemovalDialog.tsx
@@ -0,0 +1,137 @@
+import { useEffect, useId, useRef } from "react";
+import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
+import { getStandardErrorMessage } from "@/client/lib/error-messages";
+import {
+ getGoogleAccountRemovalImpact,
+ removeGoogleAccount,
+} from "@/serverFunctions/googleAccounts";
+
+export function GoogleAccountRemovalDialog({
+ provider,
+ accountId,
+ label,
+ onClose,
+ onRemoved,
+}: {
+ provider: "gsc" | "ga4";
+ accountId: string;
+ label: string;
+ onClose: () => void;
+ onRemoved: () => void;
+}) {
+ const dialog = useRef<HTMLDialogElement>(null);
+ const titleId = useId();
+ const queryClient = useQueryClient();
+ const impact = useQuery({
+ queryKey: ["googleAccountRemovalImpact", provider, accountId],
+ queryFn: () =>
+ getGoogleAccountRemovalImpact({ data: { provider, accountId } }),
+ staleTime: 0,
+ gcTime: 0,
+ });
+ const removal = useMutation({
+ mutationFn: () =>
+ removeGoogleAccount({ data: { provider, accountId, confirmed: true } }),
+ onSuccess: async () => {
+ const keys =
+ provider === "gsc"
+ ? [
+ "gscConnection",
+ "gscSites",
+ "gscGrantStatus",
+ "searchPerformance",
+ "searchPerformanceTable",
+ "dashboardGscReport",
+ "dashboardActivation",
+ ]
+ : [
+ "ga4Connection",
+ "ga4Properties",
+ "dashboardGa4Report",
+ "dashboardActivation",
+ ];
+ await Promise.all(
+ keys.map((key) => queryClient.invalidateQueries({ queryKey: [key] })),
+ );
+ onRemoved();
+ },
+ });
+ useEffect(() => {
+ const element = dialog.current;
+ element?.showModal();
+ return () => element?.close();
+ }, []);
+ const name = provider === "gsc" ? "Search Console" : "Google Analytics";
+ return (
+ <dialog
+ ref={dialog}
+ aria-labelledby={titleId}
+ className="modal"
+ onCancel={(event) => {
+ event.preventDefault();
+ if (!removal.isPending) onClose();
+ }}
+ >
+ <div className="modal-box max-w-md space-y-4">
+ <h3 id={titleId} className="text-lg font-semibold">
+ Remove Google account?
+ </h3>
+ <p className="break-all text-sm font-medium">{label}</p>
+ <p className="text-sm text-base-content/70">
+ This removes the account’s {name} connection from OpenSEO. You can
+ reconnect it anytime.
+ </p>
+ {impact.isPending ? (
+ <p role="status" className="text-sm text-base-content/60">
+ Checking connected projects…
+ </p>
+ ) : impact.isError ? (
+ <div role="alert" className="text-sm">
+ <p className="text-error">Couldn't check connected projects.</p>
+ <button
+ type="button"
+ className="btn btn-ghost btn-sm"
+ onClick={() => void impact.refetch()}
+ >
+ Try again
+ </button>
+ </div>
+ ) : impact.data.projectCount > 0 ? (
+ <p className="text-sm font-medium">
+ This will also disconnect {name} from {impact.data.projectCount}{" "}
+ project{impact.data.projectCount === 1 ? "" : "s"}.
+ </p>
+ ) : (
+ <p className="text-sm text-base-content/60">
+ No projects will be affected.
+ </p>
+ )}
+ {removal.isError ? (
+ <p role="alert" className="text-sm text-error">
+ {getStandardErrorMessage(removal.error)}
+ </p>
+ ) : null}
+ <div className="flex flex-wrap justify-end gap-2">
+ <button
+ type="button"
+ className="btn btn-ghost btn-sm"
+ disabled={removal.isPending}
+ onClick={onClose}
+ >
+ Cancel
+ </button>
+ <button
+ type="button"
+ className="btn btn-error btn-sm"
+ disabled={
+ !impact.isSuccess || impact.isFetching || removal.isPending
+ }
+ onClick={() => removal.mutate()}
+ >
+ {removal.isPending ? "Removing…" : "Remove account"}
+ </button>
+ </div>
+ </div>
+ </dialog>
+ );
+}
diff --git a/src/client/features/integrations/GoogleConnectedState.tsx b/src/client/features/integrations/GoogleConnectedState.tsx
new file mode 100644
index 00000000..e17b09a6
--- /dev/null
+++ b/src/client/features/integrations/GoogleConnectedState.tsx
@@ -0,0 +1,64 @@
+export function GoogleConnectedState({
+ property,
+ detail,
+ email,
+ onChange,
+ onDisconnect,
+ disconnecting,
+ canManage,
+ canManageAccounts,
+ disabled,
+}: {
+ property: string;
+ detail?: string | null;
+ email?: string | null;
+ onChange: () => void;
+ onDisconnect: () => void;
+ disconnecting: boolean;
+ canManage: boolean;
+ canManageAccounts: boolean;
+ disabled: boolean;
+}) {
+ return (
+ <div className="space-y-4">
+ <div className="min-w-0">
+ <p className="break-words text-sm font-semibold">
+ {property || detail}
+ </p>
+ {detail ? (
+ <p className="mt-1 text-xs text-base-content/50">
+ ID {detail.replace(/^properties\//, "")}
+ </p>
+ ) : null}
+ {email ? (
+ <p className="mt-1 break-all text-sm text-base-content/60">{email}</p>
+ ) : null}
+ </div>
+ {canManage || canManageAccounts ? (
+ <fieldset
+ disabled={disconnecting || disabled}
+ className="flex flex-wrap items-center gap-1"
+ >
+ <button
+ type="button"
+ className="btn btn-outline btn-sm border-base-300"
+ onClick={onChange}
+ >
+ {canManage
+ ? "Change property or account"
+ : "Manage Google accounts"}
+ </button>
+ {canManage ? (
+ <button
+ type="button"
+ className="btn btn-ghost btn-sm text-error hover:bg-error/10"
+ onClick={onDisconnect}
+ >
+ {disconnecting ? "Disconnecting…" : "Disconnect project"}
+ </button>
+ ) : null}
+ </fieldset>
+ ) : null}
+ </div>
+ );
+}
diff --git a/src/client/features/integrations/GoogleProjectEmptyState.tsx b/src/client/features/integrations/GoogleProjectEmptyState.tsx
new file mode 100644
index 00000000..ceb1cf7b
--- /dev/null
+++ b/src/client/features/integrations/GoogleProjectEmptyState.tsx
@@ -0,0 +1,55 @@
+import type { ReactNode } from "react";
+import { GoogleGlyph } from "@/client/features/gsc/GoogleGlyph";
+
+export function GoogleProjectEmptyState({
+ name,
+ hasGrant,
+ disabled,
+ canManage,
+ onChoose,
+ onLink,
+ children,
+}: {
+ name: string;
+ hasGrant: boolean;
+ disabled: boolean;
+ canManage: boolean;
+ onChoose: () => void;
+ onLink: () => void;
+ children?: ReactNode;
+}) {
+ return (
+ <div className="space-y-4">
+ <p className="text-sm text-base-content/70">
+ {hasGrant
+ ? `Choose a ${name} property to finish connecting this project.`
+ : `Connect ${name} to see this project’s data.`}
+ </p>
+ <div className="flex flex-wrap items-center gap-1">
+ {canManage || hasGrant ? (
+ <button
+ type="button"
+ onClick={hasGrant ? onChoose : onLink}
+ disabled={disabled}
+ aria-busy={disabled}
+ className="inline-flex items-center gap-2.5 rounded-lg border border-base-300 bg-base-100 px-4 py-2.5 text-sm font-semibold shadow-sm transition hover:bg-base-200 disabled:opacity-50"
+ >
+ {disabled ? (
+ <span className="loading loading-spinner loading-xs" />
+ ) : (
+ !hasGrant && <GoogleGlyph className="size-[18px]" />
+ )}
+ {disabled
+ ? "Opening Google…"
+ : canManage
+ ? hasGrant
+ ? "Choose property"
+ : "Connect"
+ : "Manage Google accounts"}
+ </button>
+ ) : null}
+ {children}
+ </div>
+ </div>
+ );
+}
diff --git a/src/client/features/integrations/GooglePropertyPicker.tsx b/src/client/features/integrations/GooglePropertyPicker.tsx
new file mode 100644
index 00000000..d65c4a58
--- /dev/null
+++ b/src/client/features/integrations/GooglePropertyPicker.tsx
@@ -0,0 +1,362 @@
+import { GoogleAccountRemovalDialog } from "@/client/features/integrations/GoogleAccountRemovalDialog";
+import { useId, useRef, useState, type KeyboardEvent } from "react";
+import { Check, ChevronDown, Plus, Search } from "lucide-react";
+
+type Selection = { accountId: string; propertyId: string };
+type Property = {
+ id: string;
+ name: string;
+ detail?: string;
+ selectable: boolean;
+};
+type Account = {
+ accountId: string;
+ email: string | null;
+ requiresReconnect: boolean;
+ unavailable?: boolean;
+ properties: Property[];
+};
+type SecondaryAction = {
+ label: string;
+ onClick: () => void;
+ disabled?: boolean;
+};
+
+function accountLabel(account: Account) {
+ return account.email ?? `Google account · ${account.accountId.slice(-6)}`;
+}
+
+export function GooglePropertyPicker({
+ provider,
+ readOnly = false,
+ loading,
+ linking = false,
+ error,
+ accounts,
+ selection,
+ onSelect,
+ onSave,
+ saving,
+ onRetry,
+ onReconnect,
+ secondaryAction,
+}: {
+ provider: "gsc" | "ga4";
+ readOnly?: boolean;
+ loading: boolean;
+ linking?: boolean;
+ error: boolean;
+ accounts: Account[];
+ selection: Selection | null;
+ onSelect: (selection: Selection | null) => void;
+ onSave: () => void;
+ saving: boolean;
+ onRetry: () => void;
+ onReconnect: () => void;
+ secondaryAction?: SecondaryAction;
+}) {
+ const [open, setOpen] = useState(false);
+ const [removing, setRemoving] = useState<Account | null>(null);
+ const [search, setSearch] = useState("");
+ const panelId = useId();
+ const trigger = useRef<HTMLButtonElement>(null);
+ const selectedAccount = accounts.find(
+ (a) => a.accountId === selection?.accountId,
+ );
+ const selected = selectedAccount?.properties.find(
+ (p) => p.id === selection?.propertyId,
+ );
+ const canSave =
+ selected?.selectable &&
+ !selectedAccount?.requiresReconnect &&
+ !selectedAccount?.unavailable &&
+ !loading &&
+ !error;
+ const query = search.trim().toLowerCase();
+ const filtered = accounts
+ .map((account) => ({
+ ...account,
+ properties: account.properties.filter((property) =>
+ `${account.email ?? ""} ${property.name} ${property.detail ?? ""} ${property.id}`
+ .toLowerCase()
+ .includes(query),
+ ),
+ }))
+ .filter(
+ (account) =>
+ !query ||
+ account.properties.length > 0 ||
+ accountLabel(account).toLowerCase().includes(query),
+ );
+ const close = () => {
+ setOpen(false);
+ setSearch("");
+ trigger.current?.focus();
+ };
+ return (
+ <div className="space-y-4">
+ {removing ? (
+ <GoogleAccountRemovalDialog
+ provider={provider}
+ accountId={removing.accountId}
+ label={accountLabel(removing)}
+ onClose={() => setRemoving(null)}
+ onRemoved={() => {
+ if (selection?.accountId === removing.accountId) onSelect(null);
+ setRemoving(null);
+ }}
+ />
+ ) : null}
+ <div>
+ <p className="mb-2 text-sm font-medium">
+ {readOnly ? "Manage Google accounts" : "Choose property"}
+ </p>
+ <button
+ ref={trigger}
+ type="button"
+ aria-expanded={open}
+ aria-controls={panelId}
+ disabled={saving}
+ className="flex w-full items-center justify-between gap-3 rounded-lg border border-base-300 px-3.5 py-3 text-left text-sm hover:bg-base-200/40 disabled:opacity-50"
+ onClick={() => {
+ setOpen(!open);
+ setSearch("");
+ }}
+ >
+ <span className="min-w-0">
+ <span className="block truncate">
+ {selected?.name ?? "Select a property…"}
+ </span>
+ {selectedAccount ? (
+ <span className="mt-0.5 block truncate text-xs text-base-content/50">
+ {accountLabel(selectedAccount)}
+ </span>
+ ) : null}
+ </span>
+ <ChevronDown className="size-4 shrink-0 text-base-content/50" />
+ </button>
+ {open ? (
+ <div
+ id={panelId}
+ role="region"
+ aria-label="Google properties"
+ className="mt-2 overflow-hidden rounded-lg border border-base-300 bg-base-100 shadow-sm"
+ onKeyDown={(event) => handlePropertyKeyDown(event, close)}
+ >
+ <label className="flex items-center gap-2 border-b border-base-300 px-3.5 py-3">
+ <Search className="size-4 shrink-0 text-base-content/40" />
+ <input
+ autoFocus
+ type="search"
+ aria-label="Search properties or accounts"
+ placeholder="Search properties or accounts…"
+ value={search}
+ onChange={(event) => setSearch(event.target.value)}
+ className="min-w-0 w-full bg-transparent text-sm outline-none"
+ />
+ </label>
+ <div className="max-h-72 overflow-y-auto overscroll-contain p-1.5">
+ {loading ? (
+ <p
+ role="status"
+ className="flex items-center gap-2 p-3 text-sm text-base-content/60"
+ >
+ <span className="loading loading-spinner loading-xs" />
+ Loading properties…
+ </p>
+ ) : error ? (
+ <div role="alert" className="p-3 text-sm">
+ <p className="text-error">Couldn't load properties.</p>
+ <button
+ type="button"
+ className="btn btn-ghost btn-sm mt-1"
+ onClick={onRetry}
+ >
+ Try again
+ </button>
+ </div>
+ ) : (
+ <>
+ {filtered.map((account) => (
+ <div
+ key={account.accountId}
+ className="py-1"
+ role="group"
+ aria-label={accountLabel(account)}
+ >
+ <div className="flex items-center justify-between gap-2 px-2 py-2 text-xs font-medium text-base-content/55">
+ <span className="min-w-0 break-all">
+ {accountLabel(account)}
+ </span>
+ <button
+ type="button"
+ className="btn btn-ghost btn-xs shrink-0 text-error"
+ disabled={saving}
+ onClick={() => setRemoving(account)}
+ aria-label={`Remove ${accountLabel(account)}`}
+ >
+ Remove account
+ </button>
+ </div>
+ {account.requiresReconnect ? (
+ <div className="flex flex-wrap items-center justify-between gap-2 px-2 pb-2 text-sm">
+ <span className="text-base-content/60">
+ Connection expired
+ </span>
+ <button
+ type="button"
+ className="btn btn-ghost btn-xs"
+ onClick={onReconnect}
+ aria-label={`Reconnect ${accountLabel(account)}`}
+ disabled={linking}
+ aria-busy={linking}
+ >
+ {linking ? "Opening Google…" : "Reconnect"}
+ </button>
+ </div>
+ ) : account.unavailable ? (
+ <div className="flex flex-wrap items-center justify-between gap-2 px-2 pb-2 text-sm">
+ <span className="text-base-content/60">
+ Couldn't load properties
+ </span>
+ <button
+ type="button"
+ className="btn btn-ghost btn-xs"
+ onClick={onRetry}
+ >
+ Try again
+ </button>
+ </div>
+ ) : account.properties.length === 0 ? (
+ <p className="px-2 pb-3 text-sm text-base-content/50">
+ No properties available
+ </p>
+ ) : (
+ account.properties.map((property) => {
+ const chosen =
+ selection?.accountId === account.accountId &&
+ selection?.propertyId === property.id;
+ return (
+ <button
+ key={property.id}
+ data-property
+ type="button"
+ aria-pressed={chosen}
+ disabled={
+ readOnly || !property.selectable || saving
+ }
+ className={`flex w-full items-center justify-between gap-3 rounded-md px-2 py-2.5 text-left text-sm hover:bg-base-200 focus-visible:outline-2 focus-visible:outline-primary disabled:opacity-40 ${chosen ? "bg-base-200" : ""}`}
+ onClick={() => {
+ onSelect({
+ accountId: account.accountId,
+ propertyId: property.id,
+ });
+ close();
+ }}
+ >
+ <span className="min-w-0">
+ <span className="block break-words">
+ {property.name}
+ </span>
+ {property.detail ? (
+ <span className="mt-0.5 block text-xs text-base-content/50">
+ {property.detail}
+ </span>
+ ) : null}
+ {!property.selectable ? (
+ <span className="block text-xs">
+ No verified access
+ </span>
+ ) : null}
+ </span>
+ {chosen ? (
+ <Check className="size-4 shrink-0" />
+ ) : null}
+ </button>
+ );
+ })
+ )}
+ </div>
+ ))}
+ {filtered.length === 0 ? (
+ <p className="p-3 text-sm text-base-content/50">
+ {query
+ ? "No matching properties or accounts"
+ : "Add a Google account to find properties."}
+ </p>
+ ) : null}
+ </>
+ )}
+ </div>
+ <div className="border-t border-base-300 p-1.5">
+ <button
+ type="button"
+ className="flex w-full items-center gap-2 rounded-md px-2 py-2.5 text-left text-sm font-medium hover:bg-base-200"
+ onClick={onReconnect}
+ disabled={saving || linking}
+ aria-busy={linking}
+ >
+ {linking ? (
+ <span className="loading loading-spinner loading-xs" />
+ ) : (
+ <Plus className="size-4" />
+ )}
+ {linking ? "Opening Google…" : "Add Google account"}
+ </button>
+ </div>
+ </div>
+ ) : null}
+ </div>
+ <div className="flex flex-wrap items-center gap-1">
+ <button
+ hidden={readOnly}
+ type="button"
+ className="btn btn-primary btn-sm"
+ onClick={onSave}
+ disabled={!canSave || saving}
+ >
+ {saving ? "Saving…" : "Save property"}
+ </button>
+ {secondaryAction ? (
+ <button
+ type="button"
+ className="btn btn-ghost btn-sm"
+ disabled={saving || secondaryAction.disabled}
+ onClick={secondaryAction.onClick}
+ >
+ {secondaryAction.label}
+ </button>
+ ) : null}
+ </div>
+ </div>
+ );
+}
+
+function handlePropertyKeyDown(
+ event: KeyboardEvent<HTMLDivElement>,
+ close: () => void,
+) {
+ if (event.key === "Escape") {
+ event.preventDefault();
+ close();
+ }
+ if (event.key !== "ArrowDown" && event.key !== "ArrowUp") return;
+ const buttons = Array.from(
+ event.currentTarget.querySelectorAll<HTMLButtonElement>(
+ "button[data-property]:not(:disabled)",
+ ),
+ );
+ if (!buttons.length) return;
+ event.preventDefault();
+ const index = buttons.findIndex(
+ (button) => button === document.activeElement,
+ );
+ const nextIndex =
+ index < 0
+ ? event.key === "ArrowDown"
+ ? 0
+ : buttons.length - 1
+ : (index + (event.key === "ArrowDown" ? 1 : buttons.length - 1)) %
+ buttons.length;
+ buttons[nextIndex]?.focus();
+}
diff --git a/src/client/features/integrations/IntegrationConnectionCard.tsx b/src/client/features/integrations/IntegrationConnectionCard.tsx
index 2d71179b..0d674616 100644
--- a/src/client/features/integrations/IntegrationConnectionCard.tsx
+++ b/src/client/features/integrations/IntegrationConnectionCard.tsx
@@ -19,16 +19,14 @@ export function IntegrationConnectionCard({
}) {
return (
<div className="overflow-hidden rounded-xl border border-base-300 bg-base-100 shadow-sm">
- <div className="flex items-start justify-between gap-4 p-5 sm:p-6">
+ <div className="flex flex-col items-start justify-between gap-3 p-5 sm:flex-row sm:gap-4 sm:p-6">
<div className="flex min-w-0 items-center gap-2.5">
{icon ? (
<span className="grid size-8 shrink-0 place-items-center rounded-lg border border-base-300 bg-base-100 shadow-sm">
{icon}
</span>
) : null}
- <h2 className="truncate text-base font-semibold leading-tight">
- {title}
- </h2>
+ <h2 className="text-base font-semibold leading-tight">{title}</h2>
</div>
{status ? <ConnectionStatusPill status={status} /> : null}
</div>
diff --git a/src/client/features/integrations/googleAuthErrorCopy.ts b/src/client/features/integrations/googleAuthErrorCopy.ts
index d7043b53..de4554f4 100644
--- a/src/client/features/integrations/googleAuthErrorCopy.ts
+++ b/src/client/features/integrations/googleAuthErrorCopy.ts
@@ -30,8 +30,9 @@ export function googleAuthErrorCopy(
case "account_already_linked_to_different_user":
return {
title: "Google account already connected",
- description:
- "That Google account is already linked to a different OpenSEO account. Disconnect it there first, or contact support and we'll move it over.",
+ description: providerLabel
+ ? `Sign in to the OpenSEO user that linked it, open the ${providerLabel} property picker, and choose Remove account beside the Google account. Then link it here.`
+ : "That Google account is already linked to a different OpenSEO user. Sign in with that user, or contact support for help.",
};
default:
return {
diff --git a/src/client/features/integrations/googleConnectionQueries.ts b/src/client/features/integrations/googleConnectionQueries.ts
new file mode 100644
index 00000000..f5fca95f
--- /dev/null
+++ b/src/client/features/integrations/googleConnectionQueries.ts
@@ -0,0 +1,15 @@
+import { queryOptions } from "@tanstack/react-query";
+import { getGscConnection } from "@/serverFunctions/gsc";
+import { getGa4Connection } from "@/serverFunctions/ga4";
+
+export const gscConnectionOptions = (projectId: string) =>
+ queryOptions({
+ queryKey: ["gscConnection", projectId],
+ queryFn: () => getGscConnection({ data: { projectId } }),
+ });
+
+export const ga4ConnectionOptions = (projectId: string) =>
+ queryOptions({
+ queryKey: ["ga4Connection", projectId],
+ queryFn: () => getGa4Connection({ data: { projectId } }),
+ });
diff --git a/src/client/features/integrations/googleSetupState.test.ts b/src/client/features/integrations/googleSetupState.test.ts
new file mode 100644
index 00000000..46812e4c
--- /dev/null
+++ b/src/client/features/integrations/googleSetupState.test.ts
@@ -0,0 +1,107 @@
+import { createElement } from "react";
+import { renderToStaticMarkup } from "react-dom/server";
+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
+import { describe, expect, it, vi } from "vitest";
+import { SearchConsoleConnectionCard } from "@/client/features/gsc/SearchConsoleConnectionCard";
+import { GoogleAnalyticsConnectionCard } from "@/client/features/ga4/GoogleAnalyticsConnectionCard";
+import { SearchConsoleOnboardingStep } from "@/client/features/onboarding/SearchConsoleOnboardingStep";
+
+vi.mock("@/serverFunctions/gsc", () => ({
+ getGscConnection: vi.fn(),
+ listGscSites: vi.fn(),
+ setGscSite: vi.fn(),
+ disconnectGsc: vi.fn(),
+}));
+vi.mock("@/serverFunctions/ga4", () => ({
+ getGa4Connection: vi.fn(),
+ listGa4Properties: vi.fn(),
+ setGa4Property: vi.fn(),
+ disconnectGa4: vi.fn(),
+}));
+vi.mock("@/serverFunctions/projects", () => ({ getProjects: vi.fn() }));
+vi.mock("@/serverFunctions/googleAccounts", () => ({
+ getGoogleAccountRemovalImpact: vi.fn(),
+ removeGoogleAccount: vi.fn(),
+}));
+vi.mock("@/client/features/integrations/startGoogleLink", () => ({
+ startGoogleLink: vi.fn(),
+ useGoogleLinkPending: () => false,
+}));
+vi.mock("@/client/features/integrations/googleLinkError", () => ({
+ getGoogleLinkError: () => null,
+ clearGoogleLinkError: vi.fn(),
+ reportGoogleLinkErrorOnce: vi.fn(),
+}));
+vi.mock("@/lib/auth-mode", () => ({ isHostedClientAuthMode: () => true }));
+vi.mock("@/client/lib/posthog", () => ({ captureClientEvent: vi.fn() }));
+
+function renderSetup(
+ surface: "gsc" | "ga4" | "onboarding",
+ hasGrant: boolean,
+ connected = false,
+ canManage = true,
+) {
+ const client = new QueryClient({
+ defaultOptions: { queries: { retry: false } },
+ });
+ client.setQueryData(["projects"], [{ id: "project-a" }]);
+ const provider = surface === "ga4" ? "ga4" : "gsc";
+ client.setQueryData([`${provider}Connection`, "project-a"], {
+ connected,
+ currentUserHasGrant: hasGrant,
+ canManage,
+ googleOAuthConfigured: true,
+ siteUrl: "https://example.com/",
+ propertyId: "properties/123",
+ propertyDisplayName: "Example",
+ });
+ const component =
+ surface === "onboarding"
+ ? createElement(SearchConsoleOnboardingStep)
+ : createElement(
+ surface === "gsc"
+ ? SearchConsoleConnectionCard
+ : GoogleAnalyticsConnectionCard,
+ { projectId: "project-a" },
+ );
+ const html = renderToStaticMarkup(
+ createElement(QueryClientProvider, { client }, component),
+ );
+ client.clear();
+ return html;
+}
+
+describe.each(["gsc", "ga4", "onboarding"] as const)(
+ "%s setup from persisted authorization",
+ (surface) => {
+ it("opens property selection without a browser resume flag after authorization", () => {
+ const html = renderSetup(surface, true);
+ expect(html).toContain("Choose property");
+ expect(html).toContain("Select a property");
+ expect(html).not.toContain("Connect with Google");
+ });
+ it("offers authorization when no account has been linked", () => {
+ const html = renderSetup(surface, false);
+ expect(html).not.toContain("Select a property");
+ expect(html).toContain(
+ surface === "onboarding" ? "Connect with Google" : "Connect",
+ );
+ });
+ it("shows the saved connection rather than reopening setup", () => {
+ const html = renderSetup(surface, true, true);
+ expect(html).not.toContain("Select a property");
+ expect(html).toContain(
+ surface === "ga4" ? "Example" : "https://example.com/",
+ );
+ });
+ },
+);
+
+it.each(["gsc", "ga4"] as const)(
+ "does not automatically open property editing for a %s viewer",
+ (surface) => {
+ const html = renderSetup(surface, true, false, false);
+ expect(html).not.toContain("Select a property");
+ expect(html).toContain("Manage Google accounts");
+ },
+);
diff --git a/src/client/features/integrations/startGoogleLink.test.ts b/src/client/features/integrations/startGoogleLink.test.ts
new file mode 100644
index 00000000..66a8c715
--- /dev/null
+++ b/src/client/features/integrations/startGoogleLink.test.ts
@@ -0,0 +1,103 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+
+const { link, hosted, selfHosted } = vi.hoisted(() => ({
+ link: vi.fn(),
+ hosted: vi.fn(() => true),
+ selfHosted: vi.fn(),
+}));
+vi.mock("@/lib/auth-client", () => ({ authClient: { oauth2: { link } } }));
+vi.mock("@/lib/auth-mode", () => ({ isHostedClientAuthMode: hosted }));
+vi.mock("@/serverFunctions/gsc", () => ({
+ startSelfHostedGscLink: selfHosted,
+}));
+vi.mock("@/serverFunctions/ga4", () => ({
+ startSelfHostedGa4Link: selfHosted,
+}));
+vi.mock("sonner", () => ({ toast: { error: vi.fn() } }));
+// Browser checks exercise React subscriptions; here read the real pending snapshot
+// to test network and navigation timing without a DOM.
+vi.mock("react", () => ({
+ useSyncExternalStore: (_subscribe: unknown, snapshot: () => boolean) =>
+ snapshot(),
+}));
+import { startGoogleLink, useGoogleLinkPending } from "./startGoogleLink";
+
+beforeEach(() => {
+ vi.useFakeTimers();
+ hosted.mockReturnValue(true);
+ vi.stubGlobal("window", {
+ location: {
+ origin: "https://app.example.com",
+ href: "https://app.example.com/p/1",
+ },
+ });
+});
+afterEach(() => {
+ vi.runAllTimers();
+ vi.useRealTimers();
+ vi.unstubAllGlobals();
+});
+
+describe("Google authorization loading", () => {
+ it("stays pending during a slow request and after the redirect URL is assigned", async () => {
+ let finish!: (value: { data: { url: string } }) => void;
+ link.mockImplementationOnce(
+ () =>
+ new Promise((resolve) => {
+ finish = resolve;
+ }),
+ );
+ const request = startGoogleLink("gsc", "/p/1");
+ expect(useGoogleLinkPending()).toBe(true);
+ await vi.advanceTimersByTimeAsync(30_000);
+ expect(useGoogleLinkPending()).toBe(true);
+ expect(await startGoogleLink("ga4", "/p/1")).toBe(false);
+ expect(link).toHaveBeenCalledTimes(1);
+ finish({ data: { url: "https://accounts.google.com/authorize" } });
+ expect(await request).toBe(true);
+ expect(window.location.href).toBe("https://accounts.google.com/authorize");
+ expect(useGoogleLinkPending()).toBe(true);
+ await vi.advanceTimersByTimeAsync(5_000);
+ expect(useGoogleLinkPending()).toBe(true);
+ // Preserve recovery when the user cancels a browser navigation.
+ await vi.advanceTimersByTimeAsync(10_000);
+ expect(useGoogleLinkPending()).toBe(false);
+ });
+
+ it.each(["rejected", "missing-url", "network-error"])(
+ "clears loading after %s and allows retry",
+ async (failure) => {
+ if (failure === "network-error")
+ link.mockRejectedValueOnce(new Error("Network unavailable"));
+ else
+ link.mockResolvedValueOnce(
+ failure === "rejected"
+ ? { error: { message: "Request failed" } }
+ : { data: {} },
+ );
+ expect(await startGoogleLink("gsc", "/p/1")).toBe(false);
+ expect(useGoogleLinkPending()).toBe(false);
+ link.mockResolvedValueOnce({
+ data: { url: "https://accounts.google.com/authorize" },
+ });
+ expect(await startGoogleLink("gsc", "/p/1")).toBe(true);
+ expect(useGoogleLinkPending()).toBe(true);
+ },
+ );
+
+ it("uses the same pending state for self-hosted authorization", async () => {
+ hosted.mockReturnValue(false);
+ let finish!: (value: { url: string }) => void;
+ selfHosted.mockImplementationOnce(
+ () =>
+ new Promise((resolve) => {
+ finish = resolve;
+ }),
+ );
+ const request = startGoogleLink("ga4", "/p/1");
+ expect(useGoogleLinkPending()).toBe(true);
+ finish({ url: "https://accounts.google.com/authorize" });
+ expect(await request).toBe(true);
+ expect(useGoogleLinkPending()).toBe(true);
+ });
+});
diff --git a/src/client/features/integrations/startGoogleLink.ts b/src/client/features/integrations/startGoogleLink.ts
index 407e8647..c1990cf9 100644
--- a/src/client/features/integrations/startGoogleLink.ts
+++ b/src/client/features/integrations/startGoogleLink.ts
@@ -1,4 +1,5 @@
import { toast } from "sonner";
+import { useSyncExternalStore } from "react";
import { getStandardErrorMessage } from "@/client/lib/error-messages";
import { GOOGLE_LINK_ERROR_PARAM } from "@/client/features/integrations/googleLinkError";
import { authClient } from "@/lib/auth-client";
@@ -32,6 +33,26 @@ function withGoogleLinkErrorParam(
// redirect to Google is pending, would overwrite the single Better Auth state
// cookie and guarantee a state_mismatch for whichever consent screen finishes.
let linkRedirectPending = false;
+const listeners = new Set<() => void>();
+
+function setLinkPending(pending: boolean) {
+ linkRedirectPending = pending;
+ for (const listener of listeners) listener();
+}
+
+function subscribe(listener: () => void) {
+ listeners.add(listener);
+ return () => listeners.delete(listener);
+}
+
+/** All Google entry points share the same request and navigation state. */
+export function useGoogleLinkPending() {
+ return useSyncExternalStore(
+ subscribe,
+ () => linkRedirectPending,
+ () => false,
+ );
+}
/**
* Kick off an incremental Google OAuth grant. On success this redirects the
@@ -45,9 +66,9 @@ let linkRedirectPending = false;
export async function startGoogleLink(
provider: "gsc" | "ga4",
callbackURL: string,
-): Promise<void> {
- if (linkRedirectPending) return;
- linkRedirectPending = true;
+): Promise<boolean> {
+ if (linkRedirectPending) return false;
+ setLinkPending(true);
let redirecting = false;
try {
const config = googleProviders[provider];
@@ -63,11 +84,11 @@ export async function startGoogleLink(
});
if (res.error) {
toast.error(res.error.message ?? "Could not start Google sign-in");
- return;
+ return false;
}
url = res.data?.url;
}
- if (!url) return;
+ if (!url) return false;
redirecting = true;
window.location.href = url;
@@ -76,13 +97,15 @@ export async function startGoogleLink(
// beforeunload prompt). Revive the buttons instead of leaving the page
// dead until reload.
setTimeout(() => {
- linkRedirectPending = false;
+ setLinkPending(false);
}, 15_000);
+ return true;
} catch (error) {
toast.error(getStandardErrorMessage(error));
+ return false;
} finally {
// Single release point: any exit that didn't hand off to the browser
// (error, missing URL, thrown) re-arms the button immediately.
- if (!redirecting) linkRedirectPending = false;
+ if (!redirecting) setLinkPending(false);
}
}
diff --git a/src/client/features/integrations/useGooglePickerResume.ts b/src/client/features/integrations/useGooglePickerResume.ts
new file mode 100644
index 00000000..ef8c258c
--- /dev/null
+++ b/src/client/features/integrations/useGooglePickerResume.ts
@@ -0,0 +1,45 @@
+import { useEffect, useState } from "react";
+import {
+ startGoogleLink,
+ useGoogleLinkPending,
+} from "@/client/features/integrations/startGoogleLink";
+
+/** Restore the picker after Google's full-page redirect, scoped to this project. */
+export function useGooglePickerResume(
+ provider: "gsc" | "ga4",
+ projectId: string,
+) {
+ // null lets the card derive unfinished setup from the saved authorization.
+ // false means the user explicitly closed the picker during this visit.
+ const [picking, setPicking] = useState<boolean | null>(null);
+ const linking = useGoogleLinkPending();
+ const key = `google-property-picker:${provider}:${projectId}`;
+ useEffect(() => {
+ setPicking(null);
+ try {
+ if (sessionStorage.getItem(key)) {
+ sessionStorage.removeItem(key);
+ setPicking(true);
+ }
+ } catch {
+ /* Storage can be disabled; Connect still opens the picker. */
+ }
+ }, [key]);
+
+ const linkAccount = async (callbackURL: string) => {
+ try {
+ sessionStorage.setItem(key, "open");
+ } catch {
+ /* Google authorization does not require browser storage. */
+ }
+ const redirecting = await startGoogleLink(provider, callbackURL);
+ if (!redirecting) {
+ try {
+ sessionStorage.removeItem(key);
+ } catch {
+ /* Storage is optional. */
+ }
+ }
+ };
+ return { picking, setPicking, linkAccount, linking };
+}
diff --git a/src/client/features/onboarding/SearchConsoleOnboardingStep.tsx b/src/client/features/onboarding/SearchConsoleOnboardingStep.tsx
index 8772217f..a7f77901 100644
--- a/src/client/features/onboarding/SearchConsoleOnboardingStep.tsx
+++ b/src/client/features/onboarding/SearchConsoleOnboardingStep.tsx
@@ -9,7 +9,10 @@ import {
SitePicker,
type GscSiteSelection,
} from "@/client/features/gsc/SitePicker";
-import { startGoogleLink } from "@/client/features/integrations/startGoogleLink";
+import {
+ startGoogleLink,
+ useGoogleLinkPending,
+} from "@/client/features/integrations/startGoogleLink";
import { getStandardErrorMessage } from "@/client/lib/error-messages";
import { captureClientEvent } from "@/client/lib/posthog";
import {
@@ -54,6 +57,7 @@ export function SearchConsoleOnboardingStep() {
/** Connect + pick-a-property flow, scoped to a known project. */
function GscConnect({ projectId }: { projectId: string }) {
const queryClient = useQueryClient();
+ const linking = useGoogleLinkPending();
const [selection, setSelection] = React.useState<GscSiteSelection | null>(
null,
);
@@ -133,17 +137,20 @@ function GscConnect({ projectId }: { projectId: string }) {
return (
<div className="space-y-4">
<GoogleLinkErrorAlert provider="gsc" />
- <SitePicker
- loading={sitesQuery.isLoading}
- error={sitesQuery.isError}
- accounts={accounts}
- selection={selection}
- onSelect={setSelection}
- onSave={() => selection && setSiteMutation.mutate(selection)}
- saving={setSiteMutation.isPending}
- onRetry={() => void sitesQuery.refetch()}
- onReconnect={handleConnect}
- />
+ <fieldset disabled={linking}>
+ <SitePicker
+ linking={linking}
+ loading={sitesQuery.isLoading}
+ error={sitesQuery.isError}
+ accounts={accounts}
+ selection={selection}
+ onSelect={setSelection}
+ onSave={() => selection && setSiteMutation.mutate(selection)}
+ saving={setSiteMutation.isPending}
+ onRetry={() => void sitesQuery.refetch()}
+ onReconnect={handleConnect}
+ />
+ </fieldset>
</div>
);
}
@@ -154,10 +161,16 @@ function GscConnect({ projectId }: { projectId: string }) {
<button
type="button"
onClick={handleConnect}
+ disabled={linking}
+ aria-busy={linking}
className="inline-flex items-center gap-2.5 rounded-lg border border-base-300 bg-base-100 px-4 py-2.5 text-sm font-semibold text-base-content shadow-sm transition hover:bg-base-200 hover:shadow focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-primary"
>
- <GoogleGlyph className="size-[18px]" />
- Connect with Google
+ {linking ? (
+ <span className="loading loading-spinner loading-xs" />
+ ) : (
+ <GoogleGlyph className="size-[18px]" />
+ )}
+ {linking ? "Opening Google…" : "Connect with Google"}
</button>
</div>
);
diff --git a/src/routes/_project/p/$projectId/settings/integrations.tsx b/src/routes/_project/p/$projectId/settings/integrations.tsx
index fd4703ef..b2e15310 100644
--- a/src/routes/_project/p/$projectId/settings/integrations.tsx
+++ b/src/routes/_project/p/$projectId/settings/integrations.tsx
@@ -1,3 +1,8 @@
+import { queryClient } from "@/client/tanstack-db/queryClient";
+import {
+ gscConnectionOptions,
+ ga4ConnectionOptions,
+} from "@/client/features/integrations/googleConnectionQueries";
import { createFileRoute } from "@tanstack/react-router";
import { SearchConsoleConnectionCard } from "@/client/features/gsc/SearchConsoleConnectionCard";
import { GoogleAnalyticsConnectionCard } from "@/client/features/ga4/GoogleAnalyticsConnectionCard";
@@ -5,6 +10,11 @@ import { GoogleAnalyticsConnectionCard } from "@/client/features/ga4/GoogleAnaly
export const Route = createFileRoute(
"/_project/p/$projectId/settings/integrations",
)({
+ loader: ({ params }) => {
+ // Start both database checks on link intent without holding up navigation.
+ void queryClient.prefetchQuery(gscConnectionOptions(params.projectId));
+ void queryClient.prefetchQuery(ga4ConnectionOptions(params.projectId));
+ },
component: ProjectIntegrationsRoute,
});
diff --git a/src/server/features/ga4/repositories/Ga4ConnectionRepository.ts b/src/server/features/ga4/repositories/Ga4ConnectionRepository.ts
index 097a24fc..421c13cf 100644
--- a/src/server/features/ga4/repositories/Ga4ConnectionRepository.ts
+++ b/src/server/features/ga4/repositories/Ga4ConnectionRepository.ts
@@ -1,4 +1,4 @@
-import { and, eq, sql } from "drizzle-orm";
+import { eq, sql } from "drizzle-orm";
import { db } from "@/db";
import { ga4Connections } from "@/db/schema";
@@ -59,26 +59,8 @@ async function deleteByProjectId(projectId: string): Promise<void> {
.where(eq(ga4Connections.projectId, projectId));
}
-async function existsForConnectorAccount(
- userId: string,
- ga4AccountId: string,
-): Promise<boolean> {
- const rows = await db
- .select({ id: ga4Connections.id })
- .from(ga4Connections)
- .where(
- and(
- eq(ga4Connections.connectedByUserId, userId),
- eq(ga4Connections.ga4AccountId, ga4AccountId),
- ),
- )
- .limit(1);
- return rows.length > 0;
-}
-
export const Ga4ConnectionRepository = {
getByProjectId,
upsert,
deleteByProjectId,
- existsForConnectorAccount,
};
diff --git a/src/server/features/ga4/services/Ga4Service.test.ts b/src/server/features/ga4/services/Ga4Service.test.ts
index bbfe48b0..756179b8 100644
--- a/src/server/features/ga4/services/Ga4Service.test.ts
+++ b/src/server/features/ga4/services/Ga4Service.test.ts
@@ -38,7 +38,6 @@ const mocks = vi.hoisted(() => {
upsert: vi.fn(),
getByProjectId: vi.fn(),
deleteByProjectId: vi.fn(),
- existsForConnectorAccount: vi.fn(),
};
});
@@ -54,17 +53,9 @@ vi.mock("@/server/features/ga4/repositories/Ga4ConnectionRepository", () => ({
upsert: mocks.upsert,
getByProjectId: mocks.getByProjectId,
deleteByProjectId: mocks.deleteByProjectId,
- existsForConnectorAccount: mocks.existsForConnectorAccount,
},
}));
-function collectSqlParams(value: unknown): unknown[] {
- if (!value || typeof value !== "object") return [];
- if ("value" in value && "encoder" in value) return [value.value];
- if (!("queryChunks" in value) || !Array.isArray(value.queryChunks)) return [];
- return value.queryChunks.flatMap(collectSqlParams);
-}
-
describe("Ga4Service", () => {
beforeEach(() => {
mocks.state.grants = [{ id: "grant-a", accountId: "sub-a" }];
@@ -208,37 +199,10 @@ describe("Ga4Service", () => {
consoleError.mockRestore();
});
- it("removes the caller's unused Analytics grant on disconnect", async () => {
- mocks.getByProjectId.mockResolvedValue({
- connectedByUserId: "u1",
- ga4AccountId: "sub-a",
- });
- mocks.existsForConnectorAccount.mockResolvedValue(false);
-
- await Ga4Service.disconnect({ projectId: "p1", userId: "u1" });
-
+ it("disconnects only this project and leaves linked Google accounts intact", async () => {
+ mocks.dbDelete.mockClear();
+ await Ga4Service.disconnect({ projectId: "p1" });
expect(mocks.deleteByProjectId).toHaveBeenCalledWith("p1");
- const whereCondition = mocks.deleteWhere.mock.calls[0]?.[0];
- expect(collectSqlParams(whereCondition)).toEqual(
- expect.arrayContaining(["u1", "google-analytics", "sub-a"]),
- );
- });
-
- it("keeps a shared grant and never unlinks another member's grant", async () => {
- mocks.getByProjectId.mockResolvedValue({
- connectedByUserId: "u1",
- ga4AccountId: "sub-a",
- });
- mocks.existsForConnectorAccount.mockResolvedValue(true);
- await Ga4Service.disconnect({ projectId: "p1", userId: "u1" });
- expect(mocks.dbDelete).not.toHaveBeenCalled();
-
- mocks.getByProjectId.mockResolvedValue({
- connectedByUserId: "owner",
- ga4AccountId: "sub-a",
- });
- await Ga4Service.disconnect({ projectId: "p2", userId: "other-member" });
- expect(mocks.existsForConnectorAccount).toHaveBeenCalledTimes(1);
expect(mocks.dbDelete).not.toHaveBeenCalled();
});
});
diff --git a/src/server/features/ga4/services/Ga4Service.ts b/src/server/features/ga4/services/Ga4Service.ts
index 190325d4..3af8415a 100644
--- a/src/server/features/ga4/services/Ga4Service.ts
+++ b/src/server/features/ga4/services/Ga4Service.ts
@@ -133,41 +133,8 @@ async function setProperty(input: {
});
}
-async function unlinkUserGrant(
- userId: string,
- ga4AccountId: string,
-): Promise<void> {
- await db
- .delete(account)
- .where(
- and(
- eq(account.userId, userId),
- eq(account.providerId, GA4_OAUTH_PROVIDER_ID),
- eq(account.accountId, ga4AccountId),
- ),
- );
-}
-
-async function disconnect(input: {
- projectId: string;
- userId: string;
-}): Promise<void> {
- const connection = await Ga4ConnectionRepository.getByProjectId(
- input.projectId,
- );
+async function disconnect(input: { projectId: string }): Promise<void> {
await Ga4ConnectionRepository.deleteByProjectId(input.projectId);
- if (
- connection?.ga4AccountId &&
- connection.connectedByUserId === input.userId
- ) {
- const stillUsed = await Ga4ConnectionRepository.existsForConnectorAccount(
- input.userId,
- connection.ga4AccountId,
- );
- if (!stillUsed) {
- await unlinkUserGrant(input.userId, connection.ga4AccountId);
- }
- }
}
export const Ga4Service = {
diff --git a/src/server/features/google/GoogleAccountRepository.ts b/src/server/features/google/GoogleAccountRepository.ts
new file mode 100644
index 00000000..694b0d44
--- /dev/null
+++ b/src/server/features/google/GoogleAccountRepository.ts
@@ -0,0 +1,60 @@
+import { and, count, eq, isNull, or } from "drizzle-orm";
+import { db } from "@/db";
+import { runBatch } from "@/db/runBatch";
+import { account, ga4Connections, gscConnections } from "@/db/schema";
+import { GA4_OAUTH_PROVIDER_ID } from "@/shared/ga4";
+import { GSC_OAUTH_PROVIDER_ID } from "@/shared/gsc";
+
+type AccountInput = {
+ userId: string;
+ provider: "gsc" | "ga4";
+ accountId: string;
+};
+
+function scope(input: AccountInput) {
+ const gsc = input.provider === "gsc";
+ const connections = gsc ? gscConnections : ga4Connections;
+ return {
+ connections,
+ grant: and(
+ eq(account.userId, input.userId),
+ eq(
+ account.providerId,
+ gsc ? GSC_OAUTH_PROVIDER_ID : GA4_OAUTH_PROVIDER_ID,
+ ),
+ eq(account.accountId, input.accountId),
+ ),
+ usage: and(
+ eq(connections.connectedByUserId, input.userId),
+ gsc
+ ? // Legacy GSC mappings can use any of this user's grants.
+ or(
+ eq(gscConnections.gscAccountId, input.accountId),
+ isNull(gscConnections.gscAccountId),
+ )
+ : eq(ga4Connections.ga4AccountId, input.accountId),
+ ),
+ };
+}
+
+async function getRemovalImpact(input: AccountInput) {
+ const { connections, usage } = scope(input);
+ const [result] = await db
+ .select({ projectCount: count() })
+ .from(connections)
+ .where(usage);
+ return { projectCount: result?.projectCount ?? 0 };
+}
+
+async function remove(input: AccountInput) {
+ const { connections, grant, usage } = scope(input);
+ // Atomic on D1 and Postgres: never leave a partial account removal.
+ // Both deletes are scoped to the authenticated owner, including on retries
+ // after this Google identity has been linked to a different OpenSEO user.
+ await runBatch((tx) => [
+ tx.delete(connections).where(usage),
+ tx.delete(account).where(grant),
+ ]);
+}
+
+export const GoogleAccountRepository = { getRemovalImpact, remove };
diff --git a/src/server/features/google/GoogleAccountService.test.ts b/src/server/features/google/GoogleAccountService.test.ts
new file mode 100644
index 00000000..94b56ed0
--- /dev/null
+++ b/src/server/features/google/GoogleAccountService.test.ts
@@ -0,0 +1,252 @@
+import { mkdtempSync, readFileSync, rmSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+import { createClient, type Client } from "@libsql/client";
+import { drizzle } from "drizzle-orm/libsql";
+import {
+ afterAll,
+ beforeAll,
+ beforeEach,
+ describe,
+ expect,
+ it,
+ vi,
+} from "vitest";
+import type { runBatch } from "@/db/runBatch";
+import type * as ServiceModule from "./GoogleAccountService";
+
+vi.mock("cloudflare:workers", () => ({ env: {} }));
+let client: Client;
+const directory = mkdtempSync(join(tmpdir(), "google-account-removal-"));
+let service: typeof ServiceModule.GoogleAccountService;
+type Build = Parameters<typeof runBatch>[0];
+
+beforeAll(async () => {
+ client = createClient({ url: `file:${join(directory, "test.db")}` });
+ const testDb = drizzle(client);
+ vi.doMock("@/db", () => ({ db: testDb }));
+ vi.doMock("@/db/runBatch", () => ({
+ runBatch: async (build: Build) => {
+ await testDb.transaction(async (tx) => {
+ // oxlint-disable-next-line typescript/no-unsafe-type-assertion -- real SQLite Drizzle executor has the same query-builder surface
+ for (const statement of build(tx as unknown as Parameters<Build>[0]))
+ await statement;
+ });
+ },
+ }));
+ await client.executeMultiple(`
+ CREATE TABLE user (id text PRIMARY KEY);
+ CREATE TABLE organization (id text PRIMARY KEY);
+ CREATE TABLE projects (id text PRIMARY KEY, archived integer DEFAULT 0);
+ INSERT INTO user VALUES ('u1'), ('u2');
+ INSERT INTO organization VALUES ('org1'), ('org2');
+ INSERT INTO projects (id, archived) VALUES ('p1',0), ('p2',1), ('p3',0), ('p4',0);
+ `);
+ const authMigration = readFileSync(
+ "drizzle/0003_light_sage.sql",
+ "utf8",
+ ).split("--> statement-breakpoint");
+ await client.executeMultiple(
+ authMigration
+ .filter(
+ (sql) =>
+ sql.includes("CREATE TABLE `account`") ||
+ sql.includes("CREATE INDEX `account_userId_idx`"),
+ )
+ .join("\n"),
+ );
+ for (const file of [
+ "drizzle/0019_true_absorbing_man.sql",
+ "drizzle/0039_ga4_connections.sql",
+ ]) {
+ await client.executeMultiple(
+ readFileSync(file, "utf8")
+ .split("--> statement-breakpoint")
+ .filter((sql) => !sql.includes("ALTER TABLE"))
+ .join("\n"),
+ );
+ }
+ await client.execute("ALTER TABLE gsc_connections ADD gsc_account_id text");
+ ({ GoogleAccountService: service } = await import("./GoogleAccountService"));
+});
+
+afterAll(() => {
+ client.close();
+ rmSync(directory, { recursive: true });
+});
+beforeEach(async () => {
+ await client.executeMultiple(
+ "DROP TRIGGER IF EXISTS fail_remove; DELETE FROM gsc_connections; DELETE FROM ga4_connections; DELETE FROM account;",
+ );
+});
+
+async function grant(provider: string, accountId = "google-a", userId = "u1") {
+ await client.execute({
+ sql: "INSERT INTO account (id, account_id, provider_id, user_id, updated_at, access_token, refresh_token) VALUES (?, ?, ?, ?, 1, 'access', 'refresh')",
+ args: [`${provider}-${userId}-${accountId}`, accountId, provider, userId],
+ });
+}
+async function mapping(
+ provider: "gsc" | "ga4",
+ projectId: string,
+ accountId: string | null = "google-a",
+ userId = "u1",
+) {
+ if (provider === "gsc")
+ await client.execute({
+ sql: "INSERT INTO gsc_connections (id, project_id, organization_id, site_url, connected_by_user_id, gsc_account_id) VALUES (?, ?, ?, 'https://example.com/', ?, ?)",
+ args: [
+ projectId,
+ projectId,
+ projectId === "p2" ? "org2" : "org1",
+ userId,
+ accountId,
+ ],
+ });
+ else
+ await client.execute({
+ sql: "INSERT INTO ga4_connections (id, project_id, organization_id, property_id, property_display_name, property_time_zone, property_currency_code, connected_by_user_id, ga4_account_id) VALUES (?, ?, ?, 'properties/123', 'Example', 'UTC', 'USD', ?, ?)",
+ args: [
+ projectId,
+ projectId,
+ projectId === "p2" ? "org2" : "org1",
+ userId,
+ accountId,
+ ],
+ });
+}
+async function rows(table: "account" | "gsc_connections" | "ga4_connections") {
+ return (await client.execute(`SELECT * FROM ${table} ORDER BY id`)).rows;
+}
+
+for (const provider of ["gsc", "ga4"] as const) {
+ describe(`${provider} Google account removal`, () => {
+ const providerId =
+ provider === "gsc" ? "google-search-console" : "google-analytics";
+ const otherId =
+ provider === "gsc" ? "google-analytics" : "google-search-console";
+ const table = provider === "gsc" ? "gsc_connections" : "ga4_connections";
+ const input = { provider, accountId: "google-a", userId: "u1" };
+
+ it("deletes the authorization row so another OpenSEO user can claim the identity", async () => {
+ await grant(providerId);
+ await mapping(provider, "p1");
+ expect((await rows("account"))[0]?.user_id).toBe("u1");
+ await service.remove(input);
+ expect(await rows("account")).toEqual([]);
+ expect(await rows(table)).toEqual([]);
+ // Better Auth's link callback looks up this pair across all users.
+ const existing = await client.execute({
+ sql: "SELECT user_id FROM account WHERE provider_id = ? AND account_id = ?",
+ args: [providerId, "google-a"],
+ });
+ expect(existing.rows).toEqual([]);
+ await grant(providerId, "google-a", "u2");
+ expect((await rows("account"))[0]?.user_id).toBe("u2");
+ });
+
+ it("removes all dependent mappings including archived and other-workspace projects", async () => {
+ await grant(providerId);
+ await mapping(provider, "p1");
+ await mapping(provider, "p2");
+ expect(await service.getRemovalImpact(input)).toEqual({
+ projectCount: 2,
+ });
+ await service.remove(input);
+ expect(await rows(table)).toEqual([]);
+ expect(await rows("account")).toEqual([]);
+ });
+
+ it("preserves other accounts, the other integration, and Google sign-in", async () => {
+ await grant(providerId);
+ await grant(providerId, "google-b");
+ await grant(otherId);
+ await grant("google");
+ await mapping(provider, "p1");
+ await mapping(provider, "p3", "google-b");
+ await mapping(provider === "gsc" ? "ga4" : "gsc", "p4");
+ await service.remove(input);
+ expect(await rows("account")).toHaveLength(3);
+ expect((await rows(table)).map((row) => row.project_id)).toEqual(["p3"]);
+ expect(
+ await rows(provider === "gsc" ? "ga4_connections" : "gsc_connections"),
+ ).toHaveLength(1);
+ });
+
+ it("cannot remove another user's grant or project mappings", async () => {
+ await grant(providerId);
+ await mapping(provider, "p1");
+ expect(
+ await service.getRemovalImpact({ ...input, userId: "u2" }),
+ ).toEqual({ projectCount: 0 });
+ await service.remove({ ...input, userId: "u2" });
+ expect(await rows("account")).toHaveLength(1);
+ expect(await rows(table)).toHaveLength(1);
+ });
+
+ it("a repeated old-user removal does not delete the new owner's grant", async () => {
+ await grant(providerId);
+ await service.remove(input);
+ await grant(providerId, "google-a", "u2");
+ await mapping(provider, "p1", "google-a", "u2");
+ await service.remove(input);
+ expect((await rows("account"))[0]?.user_id).toBe("u2");
+ expect(await rows(table)).toHaveLength(1);
+ });
+
+ it("rolls project deletion back if deleting the authorization fails", async () => {
+ await grant(providerId);
+ await mapping(provider, "p1");
+ await client.execute(
+ "CREATE TRIGGER fail_remove BEFORE DELETE ON account BEGIN SELECT RAISE(ABORT, 'test failure'); END",
+ );
+ await expect(service.remove(input)).rejects.toThrow();
+ expect(await rows(table)).toHaveLength(1);
+ expect(await rows("account")).toHaveLength(1);
+ });
+ });
+}
+
+it("includes legacy GSC mappings in removal without touching another user's legacy mappings", async () => {
+ await grant("google-search-console");
+ await mapping("gsc", "p1", null);
+ await mapping("gsc", "p2", null, "u2");
+ const input = {
+ provider: "gsc" as const,
+ accountId: "google-a",
+ userId: "u1",
+ };
+ expect((await service.getRemovalImpact(input)).projectCount).toBe(1);
+ await service.remove(input);
+ expect((await rows("gsc_connections")).map((row) => row.project_id)).toEqual([
+ "p2",
+ ]);
+});
+
+it.each(["same-account", "other-account", "other-user"] as const)(
+ "GSC preserves a missing email only for the same connection identity: %s",
+ async (change) => {
+ const { GscConnectionRepository } =
+ await import("@/server/features/gsc/repositories/GscConnectionRepository");
+ const base = {
+ projectId: "p1",
+ organizationId: "org1",
+ siteUrl: "https://example.com/",
+ connectedByUserId: "u1",
+ gscAccountId: "google-a",
+ connectedAccountEmail: "[email protected]",
+ };
+ await GscConnectionRepository.upsert(base);
+ const connectedByUserId = change === "other-user" ? "u2" : "u1";
+ const gscAccountId = change === "other-account" ? "google-b" : "google-a";
+ const saved = await GscConnectionRepository.upsert({
+ ...base,
+ connectedByUserId,
+ gscAccountId,
+ connectedAccountEmail: null,
+ });
+ expect(saved.connectedAccountEmail).toBe(
+ change === "same-account" ? "[email protected]" : null,
+ );
+ },
+);
diff --git a/src/server/features/google/GoogleAccountService.ts b/src/server/features/google/GoogleAccountService.ts
new file mode 100644
index 00000000..1e3a5520
--- /dev/null
+++ b/src/server/features/google/GoogleAccountService.ts
@@ -0,0 +1,21 @@
+import { GoogleAccountRepository } from "./GoogleAccountRepository";
+
+type AccountInput = {
+ userId: string;
+ provider: "gsc" | "ga4";
+ accountId: string;
+};
+
+async function getRemovalImpact(input: AccountInput) {
+ return GoogleAccountRepository.getRemovalImpact(input);
+}
+
+async function remove(input: AccountInput) {
+ // A user owns their personal Google authorization even when its projects
+ // belong to other organizations. Removing it releases the provider identity
+ // for another OpenSEO user; it does not delete Google sign-in or other scopes.
+ await GoogleAccountRepository.remove(input);
+ return { removed: true as const };
+}
+
+export const GoogleAccountService = { getRemovalImpact, remove };
diff --git a/src/server/features/gsc/repositories/GscConnectionRepository.ts b/src/server/features/gsc/repositories/GscConnectionRepository.ts
index ca42d21b..bb2efe0a 100644
--- a/src/server/features/gsc/repositories/GscConnectionRepository.ts
+++ b/src/server/features/gsc/repositories/GscConnectionRepository.ts
@@ -1,4 +1,4 @@
-import { and, eq, sql } from "drizzle-orm";
+import { eq, sql } from "drizzle-orm";
import { db } from "@/db";
import { gscConnections } from "@/db/schema";
@@ -33,7 +33,12 @@ async function upsert(input: {
organizationId: input.organizationId,
connectedByUserId: input.connectedByUserId,
gscAccountId: input.gscAccountId,
- connectedAccountEmail: sql`coalesce(${input.connectedAccountEmail}, ${gscConnections.connectedAccountEmail})`,
+ connectedAccountEmail: sql`case
+ when ${gscConnections.connectedByUserId} = ${input.connectedByUserId}
+ and ${gscConnections.gscAccountId} = ${input.gscAccountId}
+ then coalesce(${input.connectedAccountEmail}, ${gscConnections.connectedAccountEmail})
+ else ${input.connectedAccountEmail}
+ end`,
updatedAt: sql`(current_timestamp)`,
},
})
@@ -50,26 +55,8 @@ async function deleteByProjectId(projectId: string): Promise<void> {
.where(eq(gscConnections.projectId, projectId));
}
-async function existsForConnectorAccount(
- userId: string,
- gscAccountId: string,
-): Promise<boolean> {
- const rows = await db
- .select({ id: gscConnections.id })
- .from(gscConnections)
- .where(
- and(
- eq(gscConnections.connectedByUserId, userId),
- eq(gscConnections.gscAccountId, gscAccountId),
- ),
- )
- .limit(1);
- return rows.length > 0;
-}
-
export const GscConnectionRepository = {
getByProjectId,
upsert,
deleteByProjectId,
- existsForConnectorAccount,
};
diff --git a/src/server/features/gsc/services/GscService.test.ts b/src/server/features/gsc/services/GscService.test.ts
index 52436203..603e3897 100644
--- a/src/server/features/gsc/services/GscService.test.ts
+++ b/src/server/features/gsc/services/GscService.test.ts
@@ -45,7 +45,6 @@ const mocks = vi.hoisted(() => {
upsert: vi.fn(),
getByProjectId: vi.fn(),
deleteByProjectId: vi.fn(),
- existsForConnectorAccount: vi.fn(),
};
});
@@ -61,7 +60,6 @@ vi.mock("@/server/features/gsc/repositories/GscConnectionRepository", () => ({
upsert: mocks.upsert,
getByProjectId: mocks.getByProjectId,
deleteByProjectId: mocks.deleteByProjectId,
- existsForConnectorAccount: mocks.existsForConnectorAccount,
},
}));
@@ -72,15 +70,6 @@ const baseInput = {
userId: "u1",
};
-function collectSqlParams(value: unknown): unknown[] {
- if (!value || typeof value !== "object") return [];
- if ("value" in value && "encoder" in value) {
- return [value.value];
- }
- if (!("queryChunks" in value) || !Array.isArray(value.queryChunks)) return [];
- return value.queryChunks.flatMap(collectSqlParams);
-}
-
describe("GscService.setSite", () => {
beforeEach(() => {
mocks.state.selectRows = [{ id: "grant-a", accountId: "sub-a" }];
@@ -204,12 +193,14 @@ describe("GscService.listSitesForUserWithGrantStatus", () => {
accountId: "sub-a",
requiresReconnect: false,
+ propertiesUnavailable: false,
sites: [{ siteUrl: "https://x/", permissionLevel: "siteOwner" }],
},
{
accountId: "sub-b",
email: null,
requiresReconnect: true,
+ propertiesUnavailable: false,
sites: [],
},
],
@@ -221,6 +212,27 @@ describe("GscService.listSitesForUserWithGrantStatus", () => {
expect(mocks.dbDelete).not.toHaveBeenCalled();
});
+ it("keeps healthy accounts usable when another account hits a temporary API error", async () => {
+ mocks.getUserInfoEmail.mockResolvedValue("[email protected]");
+ mocks.listSites.mockImplementation(async ({ gscAccountId }) => {
+ if (gscAccountId === "sub-b")
+ throw new GscApiError(503, "Temporarily unavailable");
+ return [{ siteUrl: "https://x/", permissionLevel: "siteOwner" }];
+ });
+ const result = await GscService.listSitesForUserWithGrantStatus("u1");
+ expect(result.accounts[0]).toMatchObject({
+ requiresReconnect: false,
+ propertiesUnavailable: false,
+ sites: [{ siteUrl: "https://x/" }],
+ });
+ expect(result.accounts[1]).toMatchObject({
+ requiresReconnect: false,
+ propertiesUnavailable: true,
+ sites: [],
+ });
+ expect(mocks.dbDelete).not.toHaveBeenCalled();
+ });
+
it("keeps userinfo failures non-fatal", async () => {
mocks.state.selectRows = [{ id: "grant-a", accountId: "sub-a" }];
mocks.getUserInfoEmail.mockRejectedValue(new Error("userinfo unavailable"));
@@ -236,6 +248,7 @@ describe("GscService.listSitesForUserWithGrantStatus", () => {
accountId: "sub-a",
email: null,
requiresReconnect: false,
+ propertiesUnavailable: false,
sites: [{ siteUrl: "https://x/", permissionLevel: "siteOwner" }],
},
],
@@ -257,6 +270,7 @@ describe("GscService.listSitesForUserWithGrantStatus", () => {
accountId: "sub-a",
email: null,
requiresReconnect: true,
+ propertiesUnavailable: false,
sites: [],
},
],
@@ -289,12 +303,14 @@ describe("GscService.listSitesForUserWithGrantStatus", () => {
accountId: "sub-a",
requiresReconnect: false,
+ propertiesUnavailable: false,
sites: [{ siteUrl: "https://x/", permissionLevel: "siteOwner" }],
},
{
accountId: "sub-b",
email: null,
- requiresReconnect: true,
+ requiresReconnect: false,
+ propertiesUnavailable: true,
sites: [],
},
],
@@ -358,75 +374,10 @@ describe("GscService.getPerformance", () => {
});
describe("GscService.disconnect", () => {
- beforeEach(() => {
- mocks.getByProjectId.mockReset();
- mocks.deleteByProjectId.mockReset().mockResolvedValue(undefined);
- mocks.existsForConnectorAccount.mockReset();
+ it("disconnects only this project and leaves linked Google accounts intact", async () => {
mocks.dbDelete.mockClear();
- mocks.deleteWhere.mockClear();
- });
-
- it("unlinks only the disconnected account when it is no longer used", async () => {
- mocks.getByProjectId.mockResolvedValue({
- connectedByUserId: "u1",
- gscAccountId: "sub-b",
- });
- mocks.existsForConnectorAccount.mockResolvedValue(false);
-
- await GscService.disconnect({ projectId: "p1", userId: "u1" });
-
+ await GscService.disconnect({ projectId: "p1" });
expect(mocks.deleteByProjectId).toHaveBeenCalledWith("p1");
- expect(mocks.existsForConnectorAccount).toHaveBeenCalledWith("u1", "sub-b");
- expect(mocks.dbDelete).toHaveBeenCalledTimes(1);
- const whereCondition = mocks.deleteWhere.mock.calls[0]?.[0];
- expect(collectSqlParams(whereCondition)).toEqual(
- expect.arrayContaining(["u1", "google-search-console", "sub-b"]),
- );
- });
-
- it("keeps the grant when the same account powers another project", async () => {
- mocks.getByProjectId.mockResolvedValue({
- connectedByUserId: "u1",
- gscAccountId: "sub-b",
- });
- mocks.existsForConnectorAccount.mockResolvedValue(true);
-
- await GscService.disconnect({ projectId: "p1", userId: "u1" });
-
- expect(mocks.dbDelete).not.toHaveBeenCalled();
- });
-
- it("never revokes a grant when another member disconnects", async () => {
- mocks.getByProjectId.mockResolvedValue({
- connectedByUserId: "owner",
- gscAccountId: "sub-b",
- });
-
- await GscService.disconnect({ projectId: "p1", userId: "other-member" });
-
- expect(mocks.existsForConnectorAccount).not.toHaveBeenCalled();
- expect(mocks.dbDelete).not.toHaveBeenCalled();
- });
-
- it("deletes no grants for a legacy null-account connection", async () => {
- mocks.getByProjectId.mockResolvedValue({
- connectedByUserId: "u1",
- gscAccountId: null,
- });
-
- await GscService.disconnect({ projectId: "p1", userId: "u1" });
-
- expect(mocks.deleteByProjectId).toHaveBeenCalledWith("p1");
- expect(mocks.existsForConnectorAccount).not.toHaveBeenCalled();
- expect(mocks.dbDelete).not.toHaveBeenCalled();
- });
-
- it("deletes no grants when no property was bound", async () => {
- mocks.getByProjectId.mockResolvedValue(null);
-
- await GscService.disconnect({ projectId: "p1", userId: "u1" });
-
- expect(mocks.existsForConnectorAccount).not.toHaveBeenCalled();
expect(mocks.dbDelete).not.toHaveBeenCalled();
});
});
diff --git a/src/server/features/gsc/services/GscService.ts b/src/server/features/gsc/services/GscService.ts
index 29e4c8c5..b3bb47fe 100644
--- a/src/server/features/gsc/services/GscService.ts
+++ b/src/server/features/gsc/services/GscService.ts
@@ -41,6 +41,7 @@ type GscSiteListResult = {
accountId: string;
email: string | null;
requiresReconnect: boolean;
+ propertiesUnavailable: boolean;
sites: GscSite[];
}>;
};
@@ -112,6 +113,7 @@ async function listSitesForUserWithGrantStatus(
accountId: grant.accountId,
email,
requiresReconnect: false,
+ propertiesUnavailable: false,
sites,
};
} catch (error) {
@@ -125,7 +127,8 @@ async function listSitesForUserWithGrantStatus(
return {
accountId: grant.accountId,
email: null,
- requiresReconnect: true,
+ requiresReconnect: isExpectedGrantFailure(error),
+ propertiesUnavailable: !isExpectedGrantFailure(error),
sites: [],
};
}
@@ -185,41 +188,8 @@ async function setSite(input: {
});
}
-async function unlinkUserGrant(
- userId: string,
- gscAccountId: string,
-): Promise<void> {
- await db
- .delete(account)
- .where(
- and(
- eq(account.userId, userId),
- eq(account.providerId, GSC_OAUTH_PROVIDER_ID),
- eq(account.accountId, gscAccountId),
- ),
- );
-}
-
-async function disconnect(input: {
- projectId: string;
- userId: string;
-}): Promise<void> {
- const connection = await GscConnectionRepository.getByProjectId(
- input.projectId,
- );
+async function disconnect(input: { projectId: string }): Promise<void> {
await GscConnectionRepository.deleteByProjectId(input.projectId);
- if (
- connection?.gscAccountId &&
- connection.connectedByUserId === input.userId
- ) {
- const stillUsed = await GscConnectionRepository.existsForConnectorAccount(
- input.userId,
- connection.gscAccountId,
- );
- if (!stillUsed) {
- await unlinkUserGrant(input.userId, connection.gscAccountId);
- }
- }
}
/** Pass-through of GSC `searchAnalytics.query` for a project's connected property. */
diff --git a/src/serverFunctions/ga4.ts b/src/serverFunctions/ga4.ts
index 95f14f90..a98a0ef7 100644
--- a/src/serverFunctions/ga4.ts
+++ b/src/serverFunctions/ga4.ts
@@ -12,6 +12,7 @@ import {
createSelfHostedGoogleAuthorizationUrl,
GA4_INTEGRATION,
} from "@/server/features/google/selfHostedOAuth";
+import { hasOrgPermission } from "@/lib/org-permissions";
import { requireOrgPermission } from "@/server/auth/org-gate";
import { isHostedServerAuthMode } from "@/server/lib/runtime-env";
import { captureServerEvent } from "@/server/lib/posthog";
@@ -43,6 +44,7 @@ export const getGa4Connection = createServerFn({ method: "POST" })
]);
return {
connected: Boolean(connection),
+ canManage: hasOrgPermission(context.role, { integration: ["manage"] }),
currentUserHasGrant,
googleOAuthConfigured: hosted || ga4Configured,
propertyId: connection?.propertyId ?? null,
@@ -183,6 +185,10 @@ export const setGa4Property = createServerFn({ method: "POST" })
connected: true as const,
propertyId: connection.propertyId,
propertyDisplayName: connection.propertyDisplayName,
+ propertyTimeZone: connection.propertyTimeZone,
+ propertyCurrencyCode: connection.propertyCurrencyCode,
+ connectedByEmail: connection.connectedAccountEmail,
+ connectedAt: connection.createdAt,
};
});
@@ -191,10 +197,7 @@ export const disconnectGa4 = createServerFn({ method: "POST" })
.validator(projectScopedSchema)
.handler(async ({ context }) => {
requireOrgPermission(context, { integration: ["manage"] });
- await Ga4Service.disconnect({
- projectId: context.projectId,
- userId: context.userId,
- });
+ await Ga4Service.disconnect({ projectId: context.projectId });
waitUntil(
captureServerEvent({
distinctId: context.userId,
diff --git a/src/serverFunctions/googleAccounts.ts b/src/serverFunctions/googleAccounts.ts
new file mode 100644
index 00000000..484e9458
--- /dev/null
+++ b/src/serverFunctions/googleAccounts.ts
@@ -0,0 +1,23 @@
+import { createServerFn } from "@tanstack/react-start";
+import { z } from "zod";
+import { GoogleAccountService } from "@/server/features/google/GoogleAccountService";
+import { requireAuthenticatedContext } from "@/serverFunctions/middleware";
+
+const accountSchema = z.object({
+ provider: z.enum(["gsc", "ga4"]),
+ accountId: z.string().min(1),
+});
+
+export const getGoogleAccountRemovalImpact = createServerFn({ method: "POST" })
+ .middleware(requireAuthenticatedContext)
+ .validator(accountSchema)
+ .handler(({ data, context }) =>
+ GoogleAccountService.getRemovalImpact({ ...data, userId: context.userId }),
+ );
+
+export const removeGoogleAccount = createServerFn({ method: "POST" })
+ .middleware(requireAuthenticatedContext)
+ .validator(accountSchema.extend({ confirmed: z.literal(true) }))
+ .handler(({ data, context }) =>
+ GoogleAccountService.remove({ ...data, userId: context.userId }),
+ );
diff --git a/src/serverFunctions/gsc.ts b/src/serverFunctions/gsc.ts
index 8ee1a1a7..5aac49d0 100644
--- a/src/serverFunctions/gsc.ts
+++ b/src/serverFunctions/gsc.ts
@@ -8,6 +8,7 @@ import {
createSelfHostedGoogleAuthorizationUrl,
GSC_INTEGRATION,
} from "@/server/features/google/selfHostedOAuth";
+import { hasOrgPermission } from "@/lib/org-permissions";
import { requireOrgPermission } from "@/server/auth/org-gate";
import { captureServerEvent } from "@/server/lib/posthog";
import { getPublicOrigin } from "@/server/mcp/public-origin";
@@ -48,6 +49,7 @@ export const getGscConnection = createServerFn({ method: "POST" })
]);
return {
connected: Boolean(connection),
+ canManage: hasOrgPermission(context.role, { integration: ["manage"] }),
currentUserHasGrant,
googleOAuthConfigured: hosted || gscConfigured,
siteUrl: connection?.siteUrl ?? null,
@@ -64,20 +66,25 @@ export const listGscSites = createServerFn({ method: "POST" })
GscService.listSitesForUserWithGrantStatus(context.userId),
GscService.getConnection(context.projectId),
]);
- let legacySelectionMatched = false;
+ const legacyAccounts = !connection?.gscAccountId
+ ? siteList.accounts.filter((grant) =>
+ grant.sites.some((site) => site.siteUrl === connection?.siteUrl),
+ )
+ : [];
+ const unambiguousLegacyAccountId =
+ legacyAccounts.length === 1 ? legacyAccounts[0]?.accountId : undefined;
return {
accounts: siteList.accounts.map((grant) => ({
accountId: grant.accountId,
email: grant.email,
requiresReconnect: grant.requiresReconnect,
+ propertiesUnavailable: grant.propertiesUnavailable,
sites: grant.sites.map((site) => {
const isSelected = connection?.gscAccountId
? connection.gscAccountId === grant.accountId &&
connection.siteUrl === site.siteUrl
- : !legacySelectionMatched && connection?.siteUrl === site.siteUrl;
- if (!connection?.gscAccountId && isSelected) {
- legacySelectionMatched = true;
- }
+ : unambiguousLegacyAccountId === grant.accountId &&
+ connection?.siteUrl === site.siteUrl;
return {
siteUrl: site.siteUrl,
permissionLevel: site.permissionLevel,
@@ -109,7 +116,12 @@ export const setGscSite = createServerFn({ method: "POST" })
properties: { project_id: context.projectId, site_url: data.siteUrl },
}),
);
- return { connected: true as const, siteUrl: connection.siteUrl };
+ return {
+ connected: true as const,
+ siteUrl: connection.siteUrl,
+ connectedByEmail: connection.connectedAccountEmail,
+ connectedAt: connection.createdAt,
+ };
});
export const disconnectGsc = createServerFn({ method: "POST" })
@@ -117,10 +129,7 @@ export const disconnectGsc = createServerFn({ method: "POST" })
.validator(projectScopedSchema)
.handler(async ({ context }) => {
requireOrgPermission(context, { integration: ["manage"] });
- await GscService.disconnect({
- projectId: context.projectId,
- userId: context.userId,
- });
+ await GscService.disconnect({ projectId: context.projectId });
waitUntil(
captureServerEvent({
distinctId: context.userId,