Open source alternative to Semrush and Ahrefs
TypeScript backlink-analysisgoogle-search-console-mcpkeyword-researchmcpseoseo-agentseo-auditseo-automationseo-skillsseo-toolssite-audit
Revert "Search the Google Analytics / Search Console pickers, and clear them …" (#597)
Ben Senescu22ef28f81780
diff --git a/src/client/components/SearchableSelect.test.ts b/src/client/components/SearchableSelect.test.tsdeleted file mode 100644index c136bc3d..00000000--- a/src/client/components/SearchableSelect.test.ts+++ /dev/null@@ -1,32 +0,0 @@-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.tsxdeleted file mode 100644index f822d6ce..00000000--- a/src/client/components/SearchableSelect.tsx+++ /dev/null@@ -1,109 +0,0 @@-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 091cc464..e873c445 100644--- a/src/client/features/ga4/Ga4PropertyPicker.tsx+++ b/src/client/features/ga4/Ga4PropertyPicker.tsx@@ -1,4 +1,3 @@-import { SearchableSelect } from "@/client/components/SearchableSelect";import { GoogleGlyph } from "@/client/features/gsc/GoogleGlyph";import { startGoogleLink } from "@/client/features/integrations/startGoogleLink";@@ -105,24 +104,19 @@ 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) => ({- 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,- },+ accountId: account.accountId,+ propertyId: property.propertyId,})),);- const selectedValue = selection- ? `${selection.accountId}:${selection.propertyId}`- : null;- const hasSelection = options.some((option) => option.value === selectedValue);+ const selectedIndex = selection+ ? options.findIndex(+ (option) =>+ option.accountId === selection.accountId &&+ option.propertyId === selection.propertyId,+ )+ : -1;const hasUnavailableAccounts = accounts.some((account) => account.propertiesUnavailable,);@@ -135,26 +129,46 @@ export function Ga4PropertyPicker({Admin API is enabled and that this Google account has property access.</p>) : null}- {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}+ <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.@@ -165,7 +179,7 @@ export function Ga4PropertyPicker({type="button"className="btn btn-primary btn-sm"onClick={onSave}- disabled={!hasSelection || saving}+ disabled={selectedIndex < 0 || saving}>{saving ? "Saving…" : "Save property"}</button>diff --git a/src/client/features/ga4/GoogleAnalyticsConnectionCard.tsx b/src/client/features/ga4/GoogleAnalyticsConnectionCard.tsxindex dc27a52e..d57b378b 100644--- a/src/client/features/ga4/GoogleAnalyticsConnectionCard.tsx+++ b/src/client/features/ga4/GoogleAnalyticsConnectionCard.tsx@@ -16,7 +16,6 @@ import { captureClientEvent } from "@/client/lib/posthog";import { isHostedClientAuthMode } from "@/lib/auth-mode";import {disconnectGa4,- unlinkGa4Account,getGa4Connection,listGa4Properties,setGa4Property,@@ -102,25 +101,6 @@ 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)),@@ -174,46 +154,32 @@ 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 || 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>- </>+ <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(),+ }+ }+ />) : (<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 997831c6..57709a21 100644--- a/src/client/features/gsc/SearchConsoleConnectionCard.tsx+++ b/src/client/features/gsc/SearchConsoleConnectionCard.tsx@@ -16,7 +16,6 @@ import {import { startGoogleLink } from "@/client/features/integrations/startGoogleLink";import {disconnectGsc,- unlinkGscAccount,getGscConnection,listGscSites,setGscSite,@@ -120,8 +119,9 @@ 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,25 +139,6 @@ 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);@@ -195,41 +176,27 @@ 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 || 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+ <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(),}- 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 39f0f78b..066aed52 100644--- a/src/client/features/gsc/SitePicker.tsx+++ b/src/client/features/gsc/SitePicker.tsx@@ -1,4 +1,3 @@-import { SearchableSelect } from "@/client/components/SearchableSelect";import { GoogleGlyph } from "@/client/features/gsc/GoogleGlyph";import { startGoogleLink } from "@/client/features/integrations/startGoogleLink";@@ -105,55 +104,73 @@ 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) => ({- 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 },+ accountId: account.accountId,+ siteUrl: site.siteUrl,})),);- const selectedValue = selection- ? `${selection.accountId}:${selection.siteUrl}`- : null;- const hasSelection = options.some((option) => option.value === selectedValue);+ const selectedIndex = selection+ ? options.findIndex(+ (option) =>+ option.accountId === selection.accountId &&+ option.siteUrl === selection.siteUrl,+ )+ : -1;return (<div className="space-y-4">- {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>- )}+ <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"><buttontype="button"className="btn btn-primary btn-sm"onClick={onSave}- disabled={!hasSelection || saving}+ disabled={selectedIndex < 0 || 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.tsdeleted file mode 100644index 45b0393e..00000000--- a/src/server/features/ga4/repositories/Ga4ConnectionRepository.query.test.ts+++ /dev/null@@ -1,75 +0,0 @@-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 e930c01e..097a24fc 100644--- a/src/server/features/ga4/repositories/Ga4ConnectionRepository.ts+++ b/src/server/features/ga4/repositories/Ga4ConnectionRepository.ts@@ -1,7 +1,6 @@-import { and, eq, notExists, sql } from "drizzle-orm";+import { and, eq, sql } from "drizzle-orm";import { db } from "@/db";-import { account, ga4Connections } from "@/db/schema";-import { GA4_OAUTH_PROVIDER_ID } from "@/shared/ga4";+import { ga4Connections } from "@/db/schema";export type Ga4Connection = typeof ga4Connections.$inferSelect;@@ -60,37 +59,26 @@ async function deleteByProjectId(projectId: string): Promise<void> {.where(eq(ga4Connections.projectId, projectId));}-async function deleteUnusedGrant(+async function existsForConnectorAccount(userId: string,- accountId: string,+ ga4AccountId: string,): Promise<boolean> {- const deleted = await db- .delete(account)+ const rows = await db+ .select({ id: ga4Connections.id })+ .from(ga4Connections).where(and(- 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),- ),- ),- ),+ eq(ga4Connections.connectedByUserId, userId),+ eq(ga4Connections.ga4AccountId, ga4AccountId),),)- .returning({ id: account.id });- return deleted.length > 0;+ .limit(1);+ return rows.length > 0;}export const Ga4ConnectionRepository = {getByProjectId,upsert,deleteByProjectId,- deleteUnusedGrant,+ existsForConnectorAccount,};diff --git a/src/server/features/ga4/services/Ga4Service.test.ts b/src/server/features/ga4/services/Ga4Service.test.tsindex 231ca53b..bbfe48b0 100644--- a/src/server/features/ga4/services/Ga4Service.test.ts+++ b/src/server/features/ga4/services/Ga4Service.test.ts@@ -1,3 +1,4 @@+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";@@ -9,6 +10,9 @@ 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,@@ -29,16 +33,18 @@ const mocks = vi.hoisted(() => {}),})),})),+ dbDelete: vi.fn(() => ({ where: deleteWhere })),+ deleteWhere,upsert: vi.fn(),getByProjectId: vi.fn(),deleteByProjectId: vi.fn(),- deleteUnusedGrant: vi.fn(),+ existsForConnectorAccount: vi.fn(),};});vi.mock("cloudflare:workers", () => ({ env: {} }));vi.mock("@/db", () => ({- db: { select: mocks.dbSelect },+ db: { select: mocks.dbSelect, delete: mocks.dbDelete },}));vi.mock("@/server/lib/ga4Client", () => ({createGa4AdminClient: mocks.createGa4AdminClient,@@ -48,10 +54,17 @@ vi.mock("@/server/features/ga4/repositories/Ga4ConnectionRepository", () => ({upsert: mocks.upsert,getByProjectId: mocks.getByProjectId,deleteByProjectId: mocks.deleteByProjectId,- deleteUnusedGrant: mocks.deleteUnusedGrant,+ 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" }];@@ -195,21 +208,37 @@ describe("Ga4Service", () => {consoleError.mockRestore();});- it("disconnects only the project and leaves Google accounts linked", async () => {+ 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" });+expect(mocks.deleteByProjectId).toHaveBeenCalledWith("p1");- expect(mocks.deleteUnusedGrant).not.toHaveBeenCalled();+ const whereCondition = mocks.deleteWhere.mock.calls[0]?.[0];+ expect(collectSqlParams(whereCondition)).toEqual(+ expect.arrayContaining(["u1", "google-analytics", "sub-a"]),+ );});- 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();+ 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.tsindex 3df01897..190325d4 100644--- a/src/server/features/ga4/services/Ga4Service.ts+++ b/src/server/features/ga4/services/Ga4Service.ts@@ -133,21 +133,41 @@ 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> {- await Ga4ConnectionRepository.deleteByProjectId(input.projectId);-}--async function unlinkAccount(input: {- userId: string;- accountId: string;-}): Promise<boolean> {- return Ga4ConnectionRepository.deleteUnusedGrant(- input.userId,- input.accountId,+ 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);+ }+ }}export const Ga4Service = {@@ -156,5 +176,4 @@ 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.tsdeleted file mode 100644index 5fd56c3c..00000000--- a/src/server/features/gsc/repositories/GscConnectionRepository.query.test.ts+++ /dev/null@@ -1,99 +0,0 @@-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 60243c0c..ca42d21b 100644--- a/src/server/features/gsc/repositories/GscConnectionRepository.ts+++ b/src/server/features/gsc/repositories/GscConnectionRepository.ts@@ -1,7 +1,6 @@-import { and, eq, isNull, notExists, or, sql } from "drizzle-orm";+import { and, eq, sql } from "drizzle-orm";import { db } from "@/db";-import { account, gscConnections } from "@/db/schema";-import { GSC_OAUTH_PROVIDER_ID } from "@/shared/gsc";+import { gscConnections } from "@/db/schema";export type GscConnection = typeof gscConnections.$inferSelect;@@ -51,40 +50,26 @@ async function deleteByProjectId(projectId: string): Promise<void> {.where(eq(gscConnections.projectId, projectId));}-async function deleteUnusedGrant(+async function existsForConnectorAccount(userId: string,- accountId: string,+ gscAccountId: string,): Promise<boolean> {- const deleted = await db- .delete(account)+ const rows = await db+ .select({ id: gscConnections.id })+ .from(gscConnections).where(and(- 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),- ),- ),- ),- ),+ eq(gscConnections.connectedByUserId, userId),+ eq(gscConnections.gscAccountId, gscAccountId),),)- .returning({ id: account.id });- return deleted.length > 0;+ .limit(1);+ return rows.length > 0;}export const GscConnectionRepository = {getByProjectId,upsert,deleteByProjectId,- deleteUnusedGrant,+ existsForConnectorAccount,};diff --git a/src/server/features/gsc/services/GscService.test.ts b/src/server/features/gsc/services/GscService.test.tsindex b8f70a94..52436203 100644--- a/src/server/features/gsc/services/GscService.test.ts+++ b/src/server/features/gsc/services/GscService.test.ts@@ -1,3 +1,5 @@+/* 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";@@ -13,6 +15,9 @@ 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(() => {@@ -27,6 +32,8 @@ const mocks = vi.hoisted(() => {return {state,dbSelect,+ deleteWhere,+ dbDelete: vi.fn(() => ({ where: deleteWhere })),listSites,getUserInfoEmail,querySearchAnalytics,@@ -38,13 +45,13 @@ const mocks = vi.hoisted(() => {upsert: vi.fn(),getByProjectId: vi.fn(),deleteByProjectId: vi.fn(),- deleteUnusedGrant: vi.fn(),+ existsForConnectorAccount: vi.fn(),};});vi.mock("cloudflare:workers", () => ({ env: {} }));vi.mock("@/db", () => ({- db: { select: mocks.dbSelect },+ db: { select: mocks.dbSelect, delete: mocks.dbDelete },}));vi.mock("@/server/lib/gscClient", () => ({createGscClient: mocks.createGscClient,@@ -54,7 +61,7 @@ vi.mock("@/server/features/gsc/repositories/GscConnectionRepository", () => ({upsert: mocks.upsert,getByProjectId: mocks.getByProjectId,deleteByProjectId: mocks.deleteByProjectId,- deleteUnusedGrant: mocks.deleteUnusedGrant,+ existsForConnectorAccount: mocks.existsForConnectorAccount,},}));@@ -65,6 +72,15 @@ 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" }];@@ -165,6 +181,7 @@ 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 () => {@@ -201,7 +218,7 @@ describe("GscService.listSitesForUserWithGrantStatus", () => {expect(mocks.getUserInfoEmail).not.toHaveBeenCalledWith(expect.objectContaining({ gscAccountId: "sub-b" }),);- expect(mocks.deleteUnusedGrant).not.toHaveBeenCalled();+ expect(mocks.dbDelete).not.toHaveBeenCalled();});it("keeps userinfo failures non-fatal", async () => {@@ -245,7 +262,7 @@ describe("GscService.listSitesForUserWithGrantStatus", () => {],});expect(mocks.getUserInfoEmail).not.toHaveBeenCalled();- expect(mocks.deleteUnusedGrant).not.toHaveBeenCalled();+ expect(mocks.dbDelete).not.toHaveBeenCalled();});it("keeps non-auth GSC API errors reportable", async () => {@@ -287,7 +304,7 @@ describe("GscService.listSitesForUserWithGrantStatus", () => {"sub-b",rateLimit,);- expect(mocks.deleteUnusedGrant).not.toHaveBeenCalled();+ expect(mocks.dbDelete).not.toHaveBeenCalled();consoleError.mockRestore();});});@@ -342,24 +359,74 @@ describe("GscService.getPerformance", () => {describe("GscService.disconnect", () => {beforeEach(() => {- mocks.deleteByProjectId.mockResolvedValue(undefined);+ mocks.getByProjectId.mockReset();+ mocks.deleteByProjectId.mockReset().mockResolvedValue(undefined);+ mocks.existsForConnectorAccount.mockReset();+ mocks.dbDelete.mockClear();+ mocks.deleteWhere.mockClear();});- it("disconnects only the project and leaves Google accounts linked", async () => {+ 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.deleteUnusedGrant).not.toHaveBeenCalled();+ 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("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();+ 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.tsindex ff82188d..29e4c8c5 100644--- a/src/server/features/gsc/services/GscService.ts+++ b/src/server/features/gsc/services/GscService.ts@@ -185,11 +185,41 @@ 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. */@@ -272,23 +302,12 @@ 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 e2e874c2..95f14f90 100644--- a/src/serverFunctions/ga4.ts+++ b/src/serverFunctions/ga4.ts@@ -220,13 +220,3 @@ 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 508b72b3..8ee1a1a7 100644--- a/src/serverFunctions/gsc.ts+++ b/src/serverFunctions/gsc.ts@@ -149,13 +149,3 @@ 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,- }),- }));