Open source alternative to Semrush and Ahrefs
TypeScript backlink-analysisgoogle-search-console-mcpkeyword-researchmcpseoseo-agentseo-auditseo-automationseo-skillsseo-toolssite-audit
Search the Google Analytics / Search Console pickers, and clear them on disconnect (#566)
Ben Senescu1a470f0da2d3
diff --git a/src/client/components/SearchableSelect.test.ts b/src/client/components/SearchableSelect.test.tsnew file mode 100644index 00000000..c136bc3d--- /dev/null+++ b/src/client/components/SearchableSelect.test.ts@@ -0,0 +1,32 @@+import { describe, expect, it } from "vitest";+import { filterSearchableOptions } from "./SearchableSelect";++const options = [+ {+ value: "sub-a:properties/111",+ label: "Acme Inc · Acme Marketing",+ hint: "properties/111",+ group: "[email protected]",+ keywords: ["sub-a"],+ },+ {+ value: "sub-b:https://beta.io/",+ label: "https://beta.io/",+ group: "[email protected]",+ keywords: ["sub-b"],+ },+];++describe("filterSearchableOptions", () => {+ it("returns every option for a blank query", () => {+ expect(filterSearchableOptions(options, " ")).toEqual(options);+ });++ it("matches label, hint, group and keywords case-insensitively", () => {+ expect(filterSearchableOptions(options, "MARKET")).toEqual([options[0]]);+ expect(filterSearchableOptions(options, "111")).toEqual([options[0]]);+ expect(filterSearchableOptions(options, "ops@beta")).toEqual([options[1]]);+ expect(filterSearchableOptions(options, "sub-b")).toEqual([options[1]]);+ expect(filterSearchableOptions(options, "nothing")).toEqual([]);+ });+});diff --git a/src/client/components/SearchableSelect.tsx b/src/client/components/SearchableSelect.tsxnew file mode 100644index 00000000..f822d6ce--- /dev/null+++ b/src/client/components/SearchableSelect.tsx@@ -0,0 +1,109 @@+import { useId, useState } from "react";++type SearchableOption = {+ value: string;+ label: string;+ hint?: string;+ group?: string;+ keywords?: string[];+ disabled?: boolean;+};++export function filterSearchableOptions(+ options: readonly SearchableOption[],+ query: string,+): SearchableOption[] {+ const needle = query.trim().toLowerCase();+ return options.filter((option) =>+ [option.label, option.hint, option.group, ...(option.keywords ?? [])].some(+ (field) => field?.toLowerCase().includes(needle),+ ),+ );+}++function renderOption(option: SearchableOption) {+ return (+ <option key={option.value} value={option.value} disabled={option.disabled}>+ {option.label}+ {option.hint ? ` · ${option.hint}` : ""}+ </option>+ );+}++/** Search filters options; the browser owns selection and keyboard access. */+export function SearchableSelect({+ value,+ onChange,+ options,+ placeholder = "Select…",+ searchPlaceholder = "Search",+ emptyLabel = "No matches",+ className = "w-full",+ "aria-label": ariaLabel = "Property",+}: {+ value: string | null;+ onChange: (value: string) => void;+ options: readonly SearchableOption[];+ placeholder?: string;+ searchPlaceholder?: string;+ emptyLabel?: string;+ className?: string;+ "aria-label"?: string;+}) {+ const [query, setQuery] = useState("");+ const id = useId();+ const filtered = filterSearchableOptions(options, query);+ const selected = options.find((option) => option.value === value);+ const groups = new Map<string, SearchableOption[]>();+ for (const option of filtered) {+ const group = option.group ?? "";+ const entries = groups.get(group) ?? [];+ entries.push(option);+ groups.set(group, entries);+ }++ return (+ <div className={`space-y-2 ${className}`}>+ <input+ type="search"+ className="input input-bordered w-full"+ aria-label={`Search ${ariaLabel}`}+ aria-controls={id}+ placeholder={searchPlaceholder}+ value={query}+ onChange={(event) => setQuery(event.target.value)}+ />+ <select+ id={id}+ className="select select-bordered w-full"+ aria-label={ariaLabel}+ value={selected?.value ?? ""}+ onChange={(event) => onChange(event.target.value)}+ >+ <option value="" disabled>+ {placeholder}+ </option>+ {/* Filtering must not silently replace a choice already made. */}+ {selected && !filtered.includes(selected) ? (+ <option value={selected.value} hidden>+ {selected.label}+ </option>+ ) : null}+ {[...groups].map(([group, entries]) =>+ group ? (+ <optgroup key={group} label={group}>+ {entries.map(renderOption)}+ </optgroup>+ ) : (+ entries.map(renderOption)+ ),+ )}+ </select>+ {filtered.length === 0 ? (+ <p role="status" className="text-sm text-base-content/60">+ {emptyLabel}+ </p>+ ) : null}+ </div>+ );+}diff --git a/src/client/features/ga4/Ga4PropertyPicker.tsx b/src/client/features/ga4/Ga4PropertyPicker.tsxindex e873c445..091cc464 100644--- a/src/client/features/ga4/Ga4PropertyPicker.tsx+++ b/src/client/features/ga4/Ga4PropertyPicker.tsx@@ -1,3 +1,4 @@+import { SearchableSelect } from "@/client/components/SearchableSelect";import { GoogleGlyph } from "@/client/features/gsc/GoogleGlyph";import { startGoogleLink } from "@/client/features/integrations/startGoogleLink";@@ -104,19 +105,24 @@ export function Ga4PropertyPicker({const usableAccounts = accounts.filter((account) => !account.requiresReconnect && !account.propertiesUnavailable,);+ // The selection rides along on the option so picking one is a lookup rather+ // than parsing the composite value back apart.const options = usableAccounts.flatMap((account) =>account.properties.map((property) => ({- accountId: account.accountId,- propertyId: property.propertyId,+ value: `${account.accountId}:${property.propertyId}`,+ label: `${property.accountDisplayName} · ${property.displayName}`,+ hint: property.propertyId,+ group: account.email ?? "Google account",+ selection: {+ accountId: account.accountId,+ propertyId: property.propertyId,+ },})),);- const selectedIndex = selection- ? options.findIndex(- (option) =>- option.accountId === selection.accountId &&- option.propertyId === selection.propertyId,- )- : -1;+ const selectedValue = selection+ ? `${selection.accountId}:${selection.propertyId}`+ : null;+ const hasSelection = options.some((option) => option.value === selectedValue);const hasUnavailableAccounts = accounts.some((account) => account.propertiesUnavailable,);@@ -129,46 +135,26 @@ export function Ga4PropertyPicker({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 ? (+ <div>+ <span className="mb-1.5 block text-sm font-medium text-base-content/80">+ Property+ </span>+ <SearchableSelect+ className="w-full max-w-md"+ aria-label="Google Analytics property"+ value={selectedValue}+ onChange={(value) => {+ const option = options.find((entry) => entry.value === value);+ if (option) onSelect(option.selection);+ }}+ options={options}+ placeholder="Select a property…"+ searchPlaceholder="Search by name, account, or ID"+ emptyLabel="No properties match"+ />+ </div>+ ) : null}{options.length === 0 && !hasUnavailableAccounts ? (<p className="text-sm text-base-content/60">No Google Analytics properties are available for this account.@@ -179,7 +165,7 @@ export function Ga4PropertyPicker({type="button"className="btn btn-primary btn-sm"onClick={onSave}- disabled={selectedIndex < 0 || saving}+ disabled={!hasSelection || saving}>{saving ? "Saving…" : "Save property"}</button>diff --git a/src/client/features/ga4/GoogleAnalyticsConnectionCard.tsx b/src/client/features/ga4/GoogleAnalyticsConnectionCard.tsxindex d57b378b..dc27a52e 100644--- a/src/client/features/ga4/GoogleAnalyticsConnectionCard.tsx+++ b/src/client/features/ga4/GoogleAnalyticsConnectionCard.tsx@@ -16,6 +16,7 @@ import { captureClientEvent } from "@/client/lib/posthog";import { isHostedClientAuthMode } from "@/lib/auth-mode";import {disconnectGa4,+ unlinkGa4Account,getGa4Connection,listGa4Properties,setGa4Property,@@ -101,6 +102,25 @@ export function GoogleAnalyticsConnectionCard({toast.success("Google Analytics disconnected");setPicking(false);setSelection(null);+ queryClient.removeQueries({ queryKey: ["ga4Properties"] });+ invalidateConnectionState();+ },+ onError: (error) => toast.error(getStandardErrorMessage(error)),+ });+ const unlinkMutation = useMutation({+ mutationFn: (accountId: string) =>+ unlinkGa4Account({ data: { accountId } }),+ onSuccess: ({ removed }) => {+ if (!removed) {+ toast.error(+ "Disconnect projects using this Google account before removing it.",+ );+ return;+ }+ toast.success("Google account removed");+ setSelection(null);+ setPicking(false);+ queryClient.removeQueries({ queryKey: ["ga4Properties"] });invalidateConnectionState();},onError: (error) => toast.error(getStandardErrorMessage(error)),@@ -154,32 +174,46 @@ export function GoogleAnalyticsConnectionCard({disconnecting={disconnectMutation.isPending}/>) : 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(),- }- }- />+ <>+ <Ga4PropertyPicker+ loading={propertiesQuery.isLoading}+ error={propertiesQuery.isError}+ accounts={accounts}+ selection={selection}+ onSelect={setSelection}+ onSave={() => selection && setPropertyMutation.mutate(selection)}+ saving={setPropertyMutation.isPending || unlinkMutation.isPending}+ onRetry={() => void propertiesQuery.refetch()}+ secondaryAction={+ connected+ ? { label: "Cancel", onClick: () => setPicking(false) }+ : onDismiss+ ? {+ label: "Dismiss",+ disabled: dismissing,+ onClick: onDismiss,+ }+ : undefined+ }+ />+ <div className="mt-3 flex flex-wrap gap-2">+ {accounts.map((account, index) => (+ <button+ key={account.accountId}+ type="button"+ className="btn btn-ghost btn-sm text-error"+ disabled={+ unlinkMutation.isPending ||+ setPropertyMutation.isPending ||+ disconnectMutation.isPending+ }+ onClick={() => unlinkMutation.mutate(account.accountId)}+ >+ Remove {account.email ?? `Google account ${index + 1}`}+ </button>+ ))}+ </div>+ </>) : (<div className="space-y-4"><p className="text-sm text-base-content/70">diff --git a/src/client/features/gsc/SearchConsoleConnectionCard.tsx b/src/client/features/gsc/SearchConsoleConnectionCard.tsxindex 57709a21..997831c6 100644--- a/src/client/features/gsc/SearchConsoleConnectionCard.tsx+++ b/src/client/features/gsc/SearchConsoleConnectionCard.tsx@@ -16,6 +16,7 @@ import {import { startGoogleLink } from "@/client/features/integrations/startGoogleLink";import {disconnectGsc,+ unlinkGscAccount,getGscConnection,listGscSites,setGscSite,@@ -119,9 +120,8 @@ export function SearchConsoleConnectionCard({toast.success("Search Console disconnected");setPicking(false);setSelection(null);+ queryClient.removeQueries({ queryKey: ["gscSites"] });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],@@ -139,6 +139,25 @@ export function SearchConsoleConnectionCard({onError: (error) => toast.error(getStandardErrorMessage(error)),});+ const unlinkMutation = useMutation({+ mutationFn: (accountId: string) =>+ unlinkGscAccount({ data: { accountId } }),+ onSuccess: ({ removed }) => {+ if (!removed) {+ toast.error(+ "Disconnect projects using this Google account before removing it.",+ );+ return;+ }+ toast.success("Google account removed");+ setSelection(null);+ setPicking(false);+ queryClient.removeQueries({ queryKey: ["gscSites"] });+ void queryClient.invalidateQueries({ queryKey: connectionKey });+ void queryClient.invalidateQueries({ queryKey: GRANT_STATUS_KEY });+ },+ onError: (error) => toast.error(getStandardErrorMessage(error)),+ });const handleConnect = () =>void startGoogleLink("gsc", returnTo ?? window.location.href);@@ -176,27 +195,41 @@ export function SearchConsoleConnectionCard({disconnecting={disconnectMutation.isPending}/>) : 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(),+ <>+ <SitePicker+ loading={sitesQuery.isLoading}+ error={sitesQuery.isError}+ accounts={accounts}+ selection={selection}+ onSelect={setSelection}+ onSave={() => selection && setSiteMutation.mutate(selection)}+ saving={setSiteMutation.isPending || unlinkMutation.isPending}+ onRetry={() => void sitesQuery.refetch()}+ onReconnect={handleConnect}+ secondaryAction={+ connected+ ? { label: "Cancel", onClick: () => setPicking(false) }+ : undefined+ }+ />+ <div className="mt-3 flex flex-wrap gap-2">+ {accounts.map((account, index) => (+ <button+ key={account.accountId}+ type="button"+ className="btn btn-ghost btn-sm text-error"+ disabled={+ unlinkMutation.isPending ||+ setSiteMutation.isPending ||+ disconnectMutation.isPending}- }- />+ onClick={() => unlinkMutation.mutate(account.accountId)}+ >+ Remove {account.email ?? `Google account ${index + 1}`}+ </button>+ ))}+ </div>+ </>) : (<div className="space-y-4"><p className="text-sm text-base-content/70">diff --git a/src/client/features/gsc/SitePicker.tsx b/src/client/features/gsc/SitePicker.tsxindex 066aed52..39f0f78b 100644--- a/src/client/features/gsc/SitePicker.tsx+++ b/src/client/features/gsc/SitePicker.tsx@@ -1,3 +1,4 @@+import { SearchableSelect } from "@/client/components/SearchableSelect";import { GoogleGlyph } from "@/client/features/gsc/GoogleGlyph";import { startGoogleLink } from "@/client/features/integrations/startGoogleLink";@@ -104,73 +105,55 @@ export function SitePicker({const healthyAccounts = accounts.filter((account) => !account.requiresReconnect,);+ // The selection rides along on the option so picking one is a lookup rather+ // than parsing the composite value back apart.const options = healthyAccounts.flatMap((account) =>account.sites.map((site) => ({- accountId: account.accountId,- siteUrl: site.siteUrl,+ value: `${account.accountId}:${site.siteUrl}`,+ label: site.siteUrl,+ hint: site.selectable ? undefined : "No access",+ group: account.email ?? "Google account",+ disabled: !site.selectable,+ selection: { accountId: account.accountId, siteUrl: site.siteUrl },})),);- const selectedIndex = selection- ? options.findIndex(- (option) =>- option.accountId === selection.accountId &&- option.siteUrl === selection.siteUrl,- )- : -1;+ const selectedValue = selection+ ? `${selection.accountId}:${selection.siteUrl}`+ : null;+ const hasSelection = options.some((option) => option.value === selectedValue);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>+ {options.length > 0 ? (+ <div>+ <span className="mb-1.5 block text-sm font-medium text-base-content/80">+ Property+ </span>+ <SearchableSelect+ className="w-full max-w-md"+ aria-label="Search Console property"+ value={selectedValue}+ onChange={(value) => {+ const option = options.find((entry) => entry.value === value);+ if (option) onSelect(option.selection);+ }}+ options={options}+ placeholder="Select a property…"+ searchPlaceholder="Search by URL or account"+ emptyLabel="No properties match"+ />+ </div>+ ) : (+ <p className="text-sm text-base-content/60">+ No Search Console properties are available for this account.+ </p>+ )}<div className="flex flex-wrap items-center gap-1"><buttontype="button"className="btn btn-primary btn-sm"onClick={onSave}- disabled={selectedIndex < 0 || saving}+ disabled={!hasSelection || saving}>{saving ? "Saving…" : "Save property"}</button>diff --git a/src/server/features/ga4/repositories/Ga4ConnectionRepository.query.test.ts b/src/server/features/ga4/repositories/Ga4ConnectionRepository.query.test.tsnew file mode 100644index 00000000..45b0393e--- /dev/null+++ b/src/server/features/ga4/repositories/Ga4ConnectionRepository.query.test.ts@@ -0,0 +1,75 @@+import { createClient, type Client } from "@libsql/client";+import { drizzle } from "drizzle-orm/libsql";+import { afterAll, beforeAll, expect, it, vi } from "vitest";+import type * as Ga4ConnectionRepositoryModule from "./Ga4ConnectionRepository";++// Real in-memory SQLite: which grants the correlated DELETE keeps is the whole+// contract here and a mocked builder chain can't see it. The dynamic import is+// needed so the repository binds to the test db instead of the real one.++vi.mock("cloudflare:workers", () => ({+ env: { DATABASE_PROVIDER: "d1" },+}));++let client: Client;+let Ga4ConnectionRepository: typeof Ga4ConnectionRepositoryModule.Ga4ConnectionRepository;++beforeAll(async () => {+ client = createClient({ url: "file::memory:" });+ vi.doMock("@/db", () => ({ db: drizzle(client) }));+ await client.executeMultiple(`+ CREATE TABLE ga4_connections (+ id text PRIMARY KEY NOT NULL,+ project_id text NOT NULL,+ connected_by_user_id text NOT NULL,+ ga4_account_id text NOT NULL+ );+ CREATE TABLE account (+ id text PRIMARY KEY NOT NULL,+ account_id text NOT NULL,+ provider_id text NOT NULL,+ user_id text NOT NULL+ );+ -- bystander: their own project uses the same Google sub as u1's unused+ -- grant. stranger: a grant no project uses, which only the user filter protects.+ INSERT INTO ga4_connections (id, project_id, connected_by_user_id, ga4_account_id)+ VALUES ('c1', 'p1', 'u1', 'sub-used'),+ ('c2', 'p2', 'bystander', 'sub-unused');+ INSERT INTO account (id, user_id, provider_id, account_id) VALUES+ ('g1', 'u1', 'google-analytics', 'sub-used'),+ ('g2', 'u1', 'google-analytics', 'sub-unused'),+ ('g3', 'u1', 'google-search-console', 'sub-unused'),+ ('g4', 'bystander', 'google-analytics', 'sub-unused'),+ ('g5', 'stranger', 'google-analytics', 'sub-idle');+ INSERT INTO account (id, user_id, provider_id, account_id)+ VALUES ('pending', 'u1', 'google-analytics', 'sub-other-pending');+ `);+ ({ Ga4ConnectionRepository } = await import("./Ga4ConnectionRepository"));+});++afterAll(() => {+ client.close();+});++it("deletes only the caller's Analytics grants that no project of theirs uses", async () => {+ await Ga4ConnectionRepository.deleteUnusedGrant("u1", "sub-unused");++ const { rows } = await client.execute(+ "SELECT user_id, provider_id, account_id FROM account ORDER BY user_id, provider_id, account_id",+ );+ expect(+ rows.map((row) => [row.user_id, row.provider_id, row.account_id]),+ ).toEqual([+ ["bystander", "google-analytics", "sub-unused"],+ ["stranger", "google-analytics", "sub-idle"],+ ["u1", "google-analytics", "sub-other-pending"],+ ["u1", "google-analytics", "sub-used"],+ ["u1", "google-search-console", "sub-unused"],+ ]);+});++it("does not remove an account a saved project still uses", async () => {+ await expect(+ Ga4ConnectionRepository.deleteUnusedGrant("u1", "sub-used"),+ ).resolves.toBe(false);+});diff --git a/src/server/features/ga4/repositories/Ga4ConnectionRepository.ts b/src/server/features/ga4/repositories/Ga4ConnectionRepository.tsindex 097a24fc..e930c01e 100644--- a/src/server/features/ga4/repositories/Ga4ConnectionRepository.ts+++ b/src/server/features/ga4/repositories/Ga4ConnectionRepository.ts@@ -1,6 +1,7 @@-import { and, eq, sql } from "drizzle-orm";+import { and, eq, notExists, sql } from "drizzle-orm";import { db } from "@/db";-import { ga4Connections } from "@/db/schema";+import { account, ga4Connections } from "@/db/schema";+import { GA4_OAUTH_PROVIDER_ID } from "@/shared/ga4";export type Ga4Connection = typeof ga4Connections.$inferSelect;@@ -59,26 +60,37 @@ async function deleteByProjectId(projectId: string): Promise<void> {.where(eq(ga4Connections.projectId, projectId));}-async function existsForConnectorAccount(+async function deleteUnusedGrant(userId: string,- ga4AccountId: string,+ accountId: string,): Promise<boolean> {- const rows = await db- .select({ id: ga4Connections.id })- .from(ga4Connections)+ const deleted = await db+ .delete(account).where(and(- eq(ga4Connections.connectedByUserId, userId),- eq(ga4Connections.ga4AccountId, ga4AccountId),+ eq(account.userId, userId),+ eq(account.accountId, accountId),+ eq(account.providerId, GA4_OAUTH_PROVIDER_ID),+ notExists(+ db+ .select({ id: ga4Connections.id })+ .from(ga4Connections)+ .where(+ and(+ eq(ga4Connections.connectedByUserId, account.userId),+ eq(ga4Connections.ga4AccountId, account.accountId),+ ),+ ),+ ),),)- .limit(1);- return rows.length > 0;+ .returning({ id: account.id });+ return deleted.length > 0;}export const Ga4ConnectionRepository = {getByProjectId,upsert,deleteByProjectId,- existsForConnectorAccount,+ deleteUnusedGrant,};diff --git a/src/server/features/ga4/services/Ga4Service.test.ts b/src/server/features/ga4/services/Ga4Service.test.tsindex bbfe48b0..231ca53b 100644--- a/src/server/features/ga4/services/Ga4Service.test.ts+++ b/src/server/features/ga4/services/Ga4Service.test.ts@@ -1,4 +1,3 @@-import type { SQL } from "drizzle-orm";import { beforeEach, describe, expect, it, vi } from "vitest";import { Ga4AdminApiError, Ga4TokenError } from "@/server/lib/ga4Errors";import { Ga4Service } from "./Ga4Service";@@ -10,9 +9,6 @@ const mocks = vi.hoisted(() => {const listProperties = vi.fn();const getProperty = vi.fn();const getUserInfoEmail = vi.fn();- const deleteWhere = vi- .fn<(condition: SQL) => Promise<void>>()- .mockResolvedValue(undefined);return {state,listProperties,@@ -33,18 +29,16 @@ const mocks = vi.hoisted(() => {}),})),})),- dbDelete: vi.fn(() => ({ where: deleteWhere })),- deleteWhere,upsert: vi.fn(),getByProjectId: vi.fn(),deleteByProjectId: vi.fn(),- existsForConnectorAccount: vi.fn(),+ deleteUnusedGrant: vi.fn(),};});vi.mock("cloudflare:workers", () => ({ env: {} }));vi.mock("@/db", () => ({- db: { select: mocks.dbSelect, delete: mocks.dbDelete },+ db: { select: mocks.dbSelect },}));vi.mock("@/server/lib/ga4Client", () => ({createGa4AdminClient: mocks.createGa4AdminClient,@@ -54,17 +48,10 @@ vi.mock("@/server/features/ga4/repositories/Ga4ConnectionRepository", () => ({upsert: mocks.upsert,getByProjectId: mocks.getByProjectId,deleteByProjectId: mocks.deleteByProjectId,- existsForConnectorAccount: mocks.existsForConnectorAccount,+ deleteUnusedGrant: mocks.deleteUnusedGrant,},}));-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 +195,21 @@ 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);-+ it("disconnects only the project and leaves Google accounts linked", async () => {await Ga4Service.disconnect({ projectId: "p1", userId: "u1" });-expect(mocks.deleteByProjectId).toHaveBeenCalledWith("p1");- const whereCondition = mocks.deleteWhere.mock.calls[0]?.[0];- expect(collectSqlParams(whereCondition)).toEqual(- expect.arrayContaining(["u1", "google-analytics", "sub-a"]),- );+ expect(mocks.deleteUnusedGrant).not.toHaveBeenCalled();});- 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();+ it("removes only the explicitly selected account, refusing one still in use", async () => {+ mocks.deleteUnusedGrant+ .mockResolvedValueOnce(true)+ .mockResolvedValueOnce(false);+ await Ga4Service.unlinkAccount({ userId: "u1", accountId: "sub-unused" });+ expect(mocks.deleteUnusedGrant).toHaveBeenCalledWith("u1", "sub-unused");+ await expect(+ Ga4Service.unlinkAccount({ userId: "u1", accountId: "sub-used" }),+ ).resolves.toBe(false);+ expect(mocks.deleteByProjectId).not.toHaveBeenCalled();});});diff --git a/src/server/features/ga4/services/Ga4Service.ts b/src/server/features/ga4/services/Ga4Service.tsindex 190325d4..3df01897 100644--- a/src/server/features/ga4/services/Ga4Service.ts+++ b/src/server/features/ga4/services/Ga4Service.ts@@ -133,41 +133,21 @@ 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,- );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);- }- }+}++async function unlinkAccount(input: {+ userId: string;+ accountId: string;+}): Promise<boolean> {+ return Ga4ConnectionRepository.deleteUnusedGrant(+ input.userId,+ input.accountId,+ );}export const Ga4Service = {@@ -176,4 +156,5 @@ export const Ga4Service = {listPropertiesForUserWithGrantStatus,setProperty,disconnect,+ unlinkAccount,};diff --git a/src/server/features/gsc/repositories/GscConnectionRepository.query.test.ts b/src/server/features/gsc/repositories/GscConnectionRepository.query.test.tsnew file mode 100644index 00000000..5fd56c3c--- /dev/null+++ b/src/server/features/gsc/repositories/GscConnectionRepository.query.test.ts@@ -0,0 +1,99 @@+import { createClient, type Client } from "@libsql/client";+import { drizzle } from "drizzle-orm/libsql";+import { afterAll, beforeAll, expect, it, vi } from "vitest";+import type * as GscConnectionRepositoryModule from "./GscConnectionRepository";++// Real in-memory SQLite: which grants the correlated DELETE keeps is the whole+// contract here and a mocked builder chain can't see it. The dynamic import is+// needed so the repository binds to the test db instead of the real one.++vi.mock("cloudflare:workers", () => ({+ env: { DATABASE_PROVIDER: "d1" },+}));++let client: Client;+let GscConnectionRepository: typeof GscConnectionRepositoryModule.GscConnectionRepository;++async function grants() {+ const { rows } = await client.execute(+ "SELECT user_id, provider_id, account_id FROM account ORDER BY user_id, provider_id, account_id",+ );+ return rows.map((row) => [row.user_id, row.provider_id, row.account_id]);+}++beforeAll(async () => {+ client = createClient({ url: "file::memory:" });+ vi.doMock("@/db", () => ({ db: drizzle(client) }));+ await client.executeMultiple(`+ CREATE TABLE gsc_connections (+ id text PRIMARY KEY NOT NULL,+ project_id text NOT NULL,+ organization_id text NOT NULL,+ site_url text NOT NULL,+ connected_by_user_id text NOT NULL,+ connected_account_email text,+ gsc_account_id text,+ created_at text DEFAULT (current_timestamp) NOT NULL,+ updated_at text DEFAULT (current_timestamp) NOT NULL+ );+ CREATE TABLE account (+ id text PRIMARY KEY NOT NULL,+ account_id text NOT NULL,+ provider_id text NOT NULL,+ user_id text NOT NULL+ );+ -- legacy: connected before gsc_account_id existed. bystander: their own+ -- project uses the same Google sub as u1's unused grant. stranger: a grant+ -- no project uses, which only the user filter protects.+ INSERT INTO gsc_connections (id, project_id, organization_id, site_url, connected_by_user_id, gsc_account_id)+ VALUES ('c1', 'p1', 'o1', 'https://a.example/', 'legacy', NULL),+ ('c2', 'p2', 'o1', 'https://b.example/', 'u1', 'sub-used'),+ ('c3', 'p3', 'o2', 'https://c.example/', 'bystander', 'sub-unused');+ INSERT INTO account (id, user_id, provider_id, account_id) VALUES+ ('g1', 'legacy', 'google-search-console', 'sub-a'),+ ('g2', 'legacy', 'google-search-console', 'sub-b'),+ ('g3', 'u1', 'google-search-console', 'sub-used'),+ ('g4', 'u1', 'google-search-console', 'sub-unused'),+ ('g5', 'u1', 'google-analytics', 'sub-unused'),+ ('g6', 'bystander', 'google-search-console', 'sub-unused'),+ ('g7', 'stranger', 'google-search-console', 'sub-idle');+ INSERT INTO account (id, user_id, provider_id, account_id)+ VALUES ('pending', 'u1', 'google-search-console', 'sub-other-pending');+ `);+ ({ GscConnectionRepository } = await import("./GscConnectionRepository"));+});++afterAll(() => {+ client.close();+});++it("deletes only the caller's Search Console grants that no project of theirs uses", async () => {+ await GscConnectionRepository.deleteUnusedGrant("u1", "sub-unused");++ await expect(grants()).resolves.toEqual([+ ["bystander", "google-search-console", "sub-unused"],+ ["legacy", "google-search-console", "sub-a"],+ ["legacy", "google-search-console", "sub-b"],+ ["stranger", "google-search-console", "sub-idle"],+ ["u1", "google-analytics", "sub-unused"],+ ["u1", "google-search-console", "sub-other-pending"],+ ["u1", "google-search-console", "sub-used"],+ ]);+});++it("treats a legacy connection with no bound account as using every grant", async () => {+ await GscConnectionRepository.deleteUnusedGrant("legacy", "sub-a");++ await expect(grants()).resolves.toEqual(+ expect.arrayContaining([+ ["legacy", "google-search-console", "sub-a"],+ ["legacy", "google-search-console", "sub-b"],+ ]),+ );+});++it("does not remove an account a saved project still uses", async () => {+ await expect(+ GscConnectionRepository.deleteUnusedGrant("u1", "sub-used"),+ ).resolves.toBe(false);+});diff --git a/src/server/features/gsc/repositories/GscConnectionRepository.ts b/src/server/features/gsc/repositories/GscConnectionRepository.tsindex ca42d21b..60243c0c 100644--- a/src/server/features/gsc/repositories/GscConnectionRepository.ts+++ b/src/server/features/gsc/repositories/GscConnectionRepository.ts@@ -1,6 +1,7 @@-import { and, eq, sql } from "drizzle-orm";+import { and, eq, isNull, notExists, or, sql } from "drizzle-orm";import { db } from "@/db";-import { gscConnections } from "@/db/schema";+import { account, gscConnections } from "@/db/schema";+import { GSC_OAUTH_PROVIDER_ID } from "@/shared/gsc";export type GscConnection = typeof gscConnections.$inferSelect;@@ -50,26 +51,40 @@ async function deleteByProjectId(projectId: string): Promise<void> {.where(eq(gscConnections.projectId, projectId));}-async function existsForConnectorAccount(+async function deleteUnusedGrant(userId: string,- gscAccountId: string,+ accountId: string,): Promise<boolean> {- const rows = await db- .select({ id: gscConnections.id })- .from(gscConnections)+ const deleted = await db+ .delete(account).where(and(- eq(gscConnections.connectedByUserId, userId),- eq(gscConnections.gscAccountId, gscAccountId),+ eq(account.userId, userId),+ eq(account.accountId, accountId),+ eq(account.providerId, GSC_OAUTH_PROVIDER_ID),+ notExists(+ db+ .select({ id: gscConnections.id })+ .from(gscConnections)+ .where(+ and(+ eq(gscConnections.connectedByUserId, account.userId),+ or(+ eq(gscConnections.gscAccountId, account.accountId),+ isNull(gscConnections.gscAccountId),+ ),+ ),+ ),+ ),),)- .limit(1);- return rows.length > 0;+ .returning({ id: account.id });+ return deleted.length > 0;}export const GscConnectionRepository = {getByProjectId,upsert,deleteByProjectId,- existsForConnectorAccount,+ deleteUnusedGrant,};diff --git a/src/server/features/gsc/services/GscService.test.ts b/src/server/features/gsc/services/GscService.test.tsindex 52436203..b8f70a94 100644--- a/src/server/features/gsc/services/GscService.test.ts+++ b/src/server/features/gsc/services/GscService.test.ts@@ -1,5 +1,3 @@-/* eslint-disable max-lines */-import type { SQL } from "drizzle-orm";import { beforeEach, describe, expect, it, vi } from "vitest";import { GscApiError, GscTokenError } from "@/server/lib/gscErrors";import { GscService } from "./GscService";@@ -15,9 +13,6 @@ const mocks = vi.hoisted(() => {vi.fn<(opts: GscClientOptions) => Promise<string | null>>();const querySearchAnalytics =vi.fn<(opts: GscClientOptions) => Promise<never[]>>();- const deleteWhere = vi- .fn<(condition: SQL) => Promise<void>>()- .mockResolvedValue(undefined);const dbSelect = vi.fn(() => ({from: vi.fn(() => ({where: vi.fn(() => {@@ -32,8 +27,6 @@ const mocks = vi.hoisted(() => {return {state,dbSelect,- deleteWhere,- dbDelete: vi.fn(() => ({ where: deleteWhere })),listSites,getUserInfoEmail,querySearchAnalytics,@@ -45,13 +38,13 @@ const mocks = vi.hoisted(() => {upsert: vi.fn(),getByProjectId: vi.fn(),deleteByProjectId: vi.fn(),- existsForConnectorAccount: vi.fn(),+ deleteUnusedGrant: vi.fn(),};});vi.mock("cloudflare:workers", () => ({ env: {} }));vi.mock("@/db", () => ({- db: { select: mocks.dbSelect, delete: mocks.dbDelete },+ db: { select: mocks.dbSelect },}));vi.mock("@/server/lib/gscClient", () => ({createGscClient: mocks.createGscClient,@@ -61,7 +54,7 @@ vi.mock("@/server/features/gsc/repositories/GscConnectionRepository", () => ({upsert: mocks.upsert,getByProjectId: mocks.getByProjectId,deleteByProjectId: mocks.deleteByProjectId,- existsForConnectorAccount: mocks.existsForConnectorAccount,+ deleteUnusedGrant: mocks.deleteUnusedGrant,},}));@@ -72,15 +65,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" }];@@ -181,7 +165,6 @@ describe("GscService.listSitesForUserWithGrantStatus", () => {mocks.listSites.mockReset();mocks.getUserInfoEmail.mockReset();mocks.createGscClient.mockClear();- mocks.dbDelete.mockClear();});it("lists grants independently and never deletes a dead grant", async () => {@@ -218,7 +201,7 @@ describe("GscService.listSitesForUserWithGrantStatus", () => {expect(mocks.getUserInfoEmail).not.toHaveBeenCalledWith(expect.objectContaining({ gscAccountId: "sub-b" }),);- expect(mocks.dbDelete).not.toHaveBeenCalled();+ expect(mocks.deleteUnusedGrant).not.toHaveBeenCalled();});it("keeps userinfo failures non-fatal", async () => {@@ -262,7 +245,7 @@ describe("GscService.listSitesForUserWithGrantStatus", () => {],});expect(mocks.getUserInfoEmail).not.toHaveBeenCalled();- expect(mocks.dbDelete).not.toHaveBeenCalled();+ expect(mocks.deleteUnusedGrant).not.toHaveBeenCalled();});it("keeps non-auth GSC API errors reportable", async () => {@@ -304,7 +287,7 @@ describe("GscService.listSitesForUserWithGrantStatus", () => {"sub-b",rateLimit,);- expect(mocks.dbDelete).not.toHaveBeenCalled();+ expect(mocks.deleteUnusedGrant).not.toHaveBeenCalled();consoleError.mockRestore();});});@@ -359,74 +342,24 @@ describe("GscService.getPerformance", () => {describe("GscService.disconnect", () => {beforeEach(() => {- mocks.getByProjectId.mockReset();- mocks.deleteByProjectId.mockReset().mockResolvedValue(undefined);- mocks.existsForConnectorAccount.mockReset();- 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" });-- 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();+ mocks.deleteByProjectId.mockResolvedValue(undefined);});- 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,- });-+ it("disconnects only the project and leaves Google accounts linked", async () => {await GscService.disconnect({ projectId: "p1", userId: "u1" });-expect(mocks.deleteByProjectId).toHaveBeenCalledWith("p1");- expect(mocks.existsForConnectorAccount).not.toHaveBeenCalled();- expect(mocks.dbDelete).not.toHaveBeenCalled();+ expect(mocks.deleteUnusedGrant).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();+ it("removes only the explicitly selected account, refusing one still in use", async () => {+ mocks.deleteUnusedGrant+ .mockResolvedValueOnce(true)+ .mockResolvedValueOnce(false);+ await GscService.unlinkAccount({ userId: "u1", accountId: "sub-unused" });+ expect(mocks.deleteUnusedGrant).toHaveBeenCalledWith("u1", "sub-unused");+ await expect(+ GscService.unlinkAccount({ userId: "u1", accountId: "sub-used" }),+ ).resolves.toBe(false);+ expect(mocks.deleteByProjectId).not.toHaveBeenCalled();});});diff --git a/src/server/features/gsc/services/GscService.ts b/src/server/features/gsc/services/GscService.tsindex 29e4c8c5..ff82188d 100644--- a/src/server/features/gsc/services/GscService.ts+++ b/src/server/features/gsc/services/GscService.ts@@ -185,41 +185,11 @@ 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,- );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. */@@ -302,12 +272,23 @@ async function inspectUrls(input: {};}+async function unlinkAccount(input: {+ userId: string;+ accountId: string;+}): Promise<boolean> {+ return GscConnectionRepository.deleteUnusedGrant(+ input.userId,+ input.accountId,+ );+}+export const GscService = {getConnection,userHasGrant,listSitesForUserWithGrantStatus,setSite,disconnect,+ unlinkAccount,getPerformance,inspectUrls,};diff --git a/src/serverFunctions/ga4.ts b/src/serverFunctions/ga4.tsindex 95f14f90..e2e874c2 100644--- a/src/serverFunctions/ga4.ts+++ b/src/serverFunctions/ga4.ts@@ -220,3 +220,13 @@ export const startSelfHostedGa4Link = createServerFn({ method: "POST" })publicOrigin: getPublicOrigin(getRequest()),}),}));++export const unlinkGa4Account = createServerFn({ method: "POST" })+ .middleware(requireAuthenticatedContext)+ .validator(z.object({ accountId: z.string().min(1) }))+ .handler(async ({ data, context }) => ({+ removed: await Ga4Service.unlinkAccount({+ userId: context.userId,+ accountId: data.accountId,+ }),+ }));diff --git a/src/serverFunctions/gsc.ts b/src/serverFunctions/gsc.tsindex 8ee1a1a7..508b72b3 100644--- a/src/serverFunctions/gsc.ts+++ b/src/serverFunctions/gsc.ts@@ -149,3 +149,13 @@ export const startSelfHostedGscLink = createServerFn({ method: "POST" })return { url };});++export const unlinkGscAccount = createServerFn({ method: "POST" })+ .middleware(requireAuthenticatedContext)+ .validator(z.object({ accountId: z.string().min(1) }))+ .handler(async ({ data, context }) => ({+ removed: await GscService.unlinkAccount({+ userId: context.userId,+ accountId: data.accountId,+ }),+ }));