Open source alternative to Semrush and Ahrefs
TypeScript backlink-analysisgoogle-search-console-mcpkeyword-researchmcpseoseo-agentseo-auditseo-automationseo-skillsseo-toolssite-audit
Let two OpenSEO logins connect the same Google account (EVE-160) (#674)
Carter Smith2abb569a281e
diff --git a/drizzle-pg/0028_modern_nekra.sql b/drizzle-pg/0028_modern_nekra.sqlnew file mode 100644index 00000000..8ccf4a92--- /dev/null+++ b/drizzle-pg/0028_modern_nekra.sql@@ -0,0 +1,13 @@+DELETE FROM "account" WHERE "id" IN (+ SELECT "id" FROM (+ SELECT "id", ROW_NUMBER() OVER (+ PARTITION BY "user_id", "provider_id", "account_id"+ ORDER BY ("refresh_token" IS NOT NULL) DESC, "updated_at" DESC, "id" DESC+ ) AS "row_number"+ FROM "account"+ WHERE "provider_id" IN ('google-search-console', 'google-analytics')+ ) AS "duplicate_grants"+ WHERE "row_number" > 1+);+--> statement-breakpoint+CREATE UNIQUE INDEX IF NOT EXISTS "account_google_grant_owner_idx" ON "account" USING btree ("user_id","provider_id","account_id") WHERE "account"."provider_id" in ('google-search-console', 'google-analytics');diff --git a/drizzle-pg/meta/0028_snapshot.json b/drizzle-pg/meta/0028_snapshot.jsonnew file mode 100644index 00000000..aaf6d553--- /dev/null+++ b/drizzle-pg/meta/0028_snapshot.json@@ -0,0 +1,4615 @@+{+ "id": "a3eb3dfd-37d1-440d-9215-2ac472cf5186",+ "prevId": "31da0d5e-cca2-4fda-a54b-e65ac6a62ff9",+ "version": "7",+ "dialect": "postgresql",+ "tables": {+ "public.backlink_snapshots": {+ "name": "backlink_snapshots",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "serial",+ "primaryKey": true,+ "notNull": true+ },+ "project_id": {+ "name": "project_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "domain": {+ "name": "domain",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "rank": {+ "name": "rank",+ "type": "integer",+ "primaryKey": false,+ "notNull": false+ },+ "backlinks": {+ "name": "backlinks",+ "type": "bigint",+ "primaryKey": false,+ "notNull": false+ },+ "referring_domains": {+ "name": "referring_domains",+ "type": "bigint",+ "primaryKey": false,+ "notNull": false+ },+ "broken_backlinks": {+ "name": "broken_backlinks",+ "type": "bigint",+ "primaryKey": false,+ "notNull": false+ },+ "new_backlinks": {+ "name": "new_backlinks",+ "type": "bigint",+ "primaryKey": false,+ "notNull": false+ },+ "lost_backlinks": {+ "name": "lost_backlinks",+ "type": "bigint",+ "primaryKey": false,+ "notNull": false+ },+ "new_referring_domains": {+ "name": "new_referring_domains",+ "type": "bigint",+ "primaryKey": false,+ "notNull": false+ },+ "lost_referring_domains": {+ "name": "lost_referring_domains",+ "type": "bigint",+ "primaryKey": false,+ "notNull": false+ },+ "captured_at": {+ "name": "captured_at",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "to_char(now() AT TIME ZONE 'utc', 'YYYY-MM-DD\"T\"HH24:MI:SS.MS\"Z\"')"+ }+ },+ "indexes": {+ "backlink_snapshots_project_captured_idx": {+ "name": "backlink_snapshots_project_captured_idx",+ "columns": [+ {+ "expression": "project_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "captured_at",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "backlink_snapshots_project_id_projects_id_fk": {+ "name": "backlink_snapshots_project_id_projects_id_fk",+ "tableFrom": "backlink_snapshots",+ "tableTo": "projects",+ "columnsFrom": [+ "project_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.crawler_credentials": {+ "name": "crawler_credentials",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "project_id": {+ "name": "project_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "host": {+ "name": "host",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "provider": {+ "name": "provider",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "signature_input": {+ "name": "signature_input",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "signature": {+ "name": "signature",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "expires_at": {+ "name": "expires_at",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "created_by_user_id": {+ "name": "created_by_user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "created_at": {+ "name": "created_at",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "to_char(now() AT TIME ZONE 'utc', 'YYYY-MM-DD\"T\"HH24:MI:SS.MS\"Z\"')"+ }+ },+ "indexes": {+ "crawler_credentials_project_host_idx": {+ "name": "crawler_credentials_project_host_idx",+ "columns": [+ {+ "expression": "project_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "host",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": true,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "crawler_credentials_project_id_projects_id_fk": {+ "name": "crawler_credentials_project_id_projects_id_fk",+ "tableFrom": "crawler_credentials",+ "tableTo": "projects",+ "columnsFrom": [+ "project_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.dashboard_step_dismissals": {+ "name": "dashboard_step_dismissals",+ "schema": "",+ "columns": {+ "user_id": {+ "name": "user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "project_id": {+ "name": "project_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "step": {+ "name": "step",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ }+ },+ "indexes": {+ "dashboard_step_dismissals_project_idx": {+ "name": "dashboard_step_dismissals_project_idx",+ "columns": [+ {+ "expression": "project_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "dashboard_step_dismissals_user_id_user_id_fk": {+ "name": "dashboard_step_dismissals_user_id_user_id_fk",+ "tableFrom": "dashboard_step_dismissals",+ "tableTo": "user",+ "columnsFrom": [+ "user_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "dashboard_step_dismissals_project_id_projects_id_fk": {+ "name": "dashboard_step_dismissals_project_id_projects_id_fk",+ "tableFrom": "dashboard_step_dismissals",+ "tableTo": "projects",+ "columnsFrom": [+ "project_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {+ "dashboard_step_dismissals_user_id_project_id_step_pk": {+ "name": "dashboard_step_dismissals_user_id_project_id_step_pk",+ "columns": [+ "user_id",+ "project_id",+ "step"+ ]+ }+ },+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.keyword_metrics": {+ "name": "keyword_metrics",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "serial",+ "primaryKey": true,+ "notNull": true+ },+ "project_id": {+ "name": "project_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "keyword": {+ "name": "keyword",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "location_code": {+ "name": "location_code",+ "type": "integer",+ "primaryKey": false,+ "notNull": true+ },+ "language_code": {+ "name": "language_code",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'en'"+ },+ "search_volume": {+ "name": "search_volume",+ "type": "integer",+ "primaryKey": false,+ "notNull": false+ },+ "cpc": {+ "name": "cpc",+ "type": "real",+ "primaryKey": false,+ "notNull": false+ },+ "competition": {+ "name": "competition",+ "type": "real",+ "primaryKey": false,+ "notNull": false+ },+ "keyword_difficulty": {+ "name": "keyword_difficulty",+ "type": "integer",+ "primaryKey": false,+ "notNull": false+ },+ "intent": {+ "name": "intent",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "monthly_searches": {+ "name": "monthly_searches",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "fetched_at": {+ "name": "fetched_at",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "to_char(now() AT TIME ZONE 'utc', 'YYYY-MM-DD\"T\"HH24:MI:SS.MS\"Z\"')"+ }+ },+ "indexes": {+ "keyword_metrics_unique_project_keyword_location_language": {+ "name": "keyword_metrics_unique_project_keyword_location_language",+ "columns": [+ {+ "expression": "project_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "keyword",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "location_code",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "language_code",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": true,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "keyword_metrics_lookup_idx": {+ "name": "keyword_metrics_lookup_idx",+ "columns": [+ {+ "expression": "project_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "keyword",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "location_code",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "language_code",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "fetched_at",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "keyword_metrics_project_id_projects_id_fk": {+ "name": "keyword_metrics_project_id_projects_id_fk",+ "tableFrom": "keyword_metrics",+ "tableTo": "projects",+ "columnsFrom": [+ "project_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.organization_activation_state": {+ "name": "organization_activation_state",+ "schema": "",+ "columns": {+ "organization_id": {+ "name": "organization_id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "first_mcp_authorized_at": {+ "name": "first_mcp_authorized_at",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "first_mcp_tool_call_at": {+ "name": "first_mcp_tool_call_at",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "updated_at": {+ "name": "updated_at",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "to_char(now() AT TIME ZONE 'utc', 'YYYY-MM-DD\"T\"HH24:MI:SS.MS\"Z\"')"+ }+ },+ "indexes": {},+ "foreignKeys": {+ "organization_activation_state_organization_id_organization_id_fk": {+ "name": "organization_activation_state_organization_id_organization_id_fk",+ "tableFrom": "organization_activation_state",+ "tableTo": "organization",+ "columnsFrom": [+ "organization_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.project_activation_state": {+ "name": "project_activation_state",+ "schema": "",+ "columns": {+ "project_id": {+ "name": "project_id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "competitor_step_clicked_at": {+ "name": "competitor_step_clicked_at",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "keyword_step_clicked_at": {+ "name": "keyword_step_clicked_at",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "mcp_card_dismissed_at": {+ "name": "mcp_card_dismissed_at",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "ga4_card_dismissed_at": {+ "name": "ga4_card_dismissed_at",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "updated_at": {+ "name": "updated_at",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "to_char(now() AT TIME ZONE 'utc', 'YYYY-MM-DD\"T\"HH24:MI:SS.MS\"Z\"')"+ }+ },+ "indexes": {},+ "foreignKeys": {+ "project_activation_state_project_id_projects_id_fk": {+ "name": "project_activation_state_project_id_projects_id_fk",+ "tableFrom": "project_activation_state",+ "tableTo": "projects",+ "columnsFrom": [+ "project_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.projects": {+ "name": "projects",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "organization_id": {+ "name": "organization_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "name": {+ "name": "name",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "domain": {+ "name": "domain",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "location_code": {+ "name": "location_code",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "default": 2840+ },+ "language_code": {+ "name": "language_code",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'en'"+ },+ "created_at": {+ "name": "created_at",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "to_char(now() AT TIME ZONE 'utc', 'YYYY-MM-DD\"T\"HH24:MI:SS.MS\"Z\"')"+ },+ "archived_at": {+ "name": "archived_at",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ }+ },+ "indexes": {+ "projects_one_default_per_organization_idx": {+ "name": "projects_one_default_per_organization_idx",+ "columns": [+ {+ "expression": "organization_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": true,+ "where": "\"projects\".\"name\" = 'Default' AND \"projects\".\"domain\" IS NULL AND \"projects\".\"archived_at\" IS NULL",+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "projects_organization_id_idx": {+ "name": "projects_organization_id_idx",+ "columns": [+ {+ "expression": "organization_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "projects_organization_id_organization_id_fk": {+ "name": "projects_organization_id_organization_id_fk",+ "tableFrom": "projects",+ "tableTo": "organization",+ "columnsFrom": [+ "organization_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.rank_check_runs": {+ "name": "rank_check_runs",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "config_id": {+ "name": "config_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "project_id": {+ "name": "project_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "status": {+ "name": "status",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'pending'"+ },+ "keywords_total": {+ "name": "keywords_total",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "default": 0+ },+ "keywords_checked": {+ "name": "keywords_checked",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "default": 0+ },+ "is_subset_run": {+ "name": "is_subset_run",+ "type": "boolean",+ "primaryKey": false,+ "notNull": true,+ "default": false+ },+ "error_message": {+ "name": "error_message",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "started_at": {+ "name": "started_at",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "to_char(now() AT TIME ZONE 'utc', 'YYYY-MM-DD\"T\"HH24:MI:SS.MS\"Z\"')"+ },+ "completed_at": {+ "name": "completed_at",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ }+ },+ "indexes": {+ "rank_check_runs_config_idx": {+ "name": "rank_check_runs_config_idx",+ "columns": [+ {+ "expression": "config_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "started_at",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "rank_check_runs_project_idx": {+ "name": "rank_check_runs_project_idx",+ "columns": [+ {+ "expression": "project_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "started_at",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "rank_check_runs_one_active_per_config_idx": {+ "name": "rank_check_runs_one_active_per_config_idx",+ "columns": [+ {+ "expression": "config_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": true,+ "where": "\"rank_check_runs\".\"status\" IN ('pending', 'running')",+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "rank_check_runs_config_id_rank_tracking_configs_id_fk": {+ "name": "rank_check_runs_config_id_rank_tracking_configs_id_fk",+ "tableFrom": "rank_check_runs",+ "tableTo": "rank_tracking_configs",+ "columnsFrom": [+ "config_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "rank_check_runs_project_id_projects_id_fk": {+ "name": "rank_check_runs_project_id_projects_id_fk",+ "tableFrom": "rank_check_runs",+ "tableTo": "projects",+ "columnsFrom": [+ "project_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.rank_snapshots": {+ "name": "rank_snapshots",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "serial",+ "primaryKey": true,+ "notNull": true+ },+ "run_id": {+ "name": "run_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "tracking_keyword_id": {+ "name": "tracking_keyword_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "keyword": {+ "name": "keyword",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "device": {+ "name": "device",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "position": {+ "name": "position",+ "type": "integer",+ "primaryKey": false,+ "notNull": false+ },+ "url": {+ "name": "url",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "serp_features": {+ "name": "serp_features",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "checked_at": {+ "name": "checked_at",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "to_char(now() AT TIME ZONE 'utc', 'YYYY-MM-DD\"T\"HH24:MI:SS.MS\"Z\"')"+ }+ },+ "indexes": {+ "rank_snapshots_keyword_device_idx": {+ "name": "rank_snapshots_keyword_device_idx",+ "columns": [+ {+ "expression": "tracking_keyword_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "device",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "checked_at",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "rank_snapshots_run_keyword_device_idx": {+ "name": "rank_snapshots_run_keyword_device_idx",+ "columns": [+ {+ "expression": "run_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "tracking_keyword_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "device",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": true,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "rank_snapshots_run_id_rank_check_runs_id_fk": {+ "name": "rank_snapshots_run_id_rank_check_runs_id_fk",+ "tableFrom": "rank_snapshots",+ "tableTo": "rank_check_runs",+ "columnsFrom": [+ "run_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.rank_tracking_configs": {+ "name": "rank_tracking_configs",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "project_id": {+ "name": "project_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "domain": {+ "name": "domain",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "location_code": {+ "name": "location_code",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "default": 2840+ },+ "language_code": {+ "name": "language_code",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'en'"+ },+ "devices": {+ "name": "devices",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'both'"+ },+ "serp_depth": {+ "name": "serp_depth",+ "type": "integer",+ "primaryKey": false,+ "notNull": true+ },+ "schedule_interval": {+ "name": "schedule_interval",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'weekly'"+ },+ "location_name": {+ "name": "location_name",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "is_active": {+ "name": "is_active",+ "type": "boolean",+ "primaryKey": false,+ "notNull": true,+ "default": true+ },+ "last_checked_at": {+ "name": "last_checked_at",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "next_check_at": {+ "name": "next_check_at",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "last_skip_reason": {+ "name": "last_skip_reason",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "created_at": {+ "name": "created_at",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "to_char(now() AT TIME ZONE 'utc', 'YYYY-MM-DD\"T\"HH24:MI:SS.MS\"Z\"')"+ }+ },+ "indexes": {+ "rank_tracking_configs_project_active_created_idx": {+ "name": "rank_tracking_configs_project_active_created_idx",+ "columns": [+ {+ "expression": "project_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "is_active",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "created_at",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "rank_tracking_configs_national_idx": {+ "name": "rank_tracking_configs_national_idx",+ "columns": [+ {+ "expression": "project_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "domain",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "location_code",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": true,+ "where": "\"rank_tracking_configs\".\"location_name\" IS NULL",+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "rank_tracking_configs_local_idx": {+ "name": "rank_tracking_configs_local_idx",+ "columns": [+ {+ "expression": "project_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "domain",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "location_code",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "location_name",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": true,+ "where": "\"rank_tracking_configs\".\"location_name\" IS NOT NULL",+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "rank_tracking_configs_project_id_projects_id_fk": {+ "name": "rank_tracking_configs_project_id_projects_id_fk",+ "tableFrom": "rank_tracking_configs",+ "tableTo": "projects",+ "columnsFrom": [+ "project_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.rank_tracking_keywords": {+ "name": "rank_tracking_keywords",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "config_id": {+ "name": "config_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "keyword": {+ "name": "keyword",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "match_case": {+ "name": "match_case",+ "type": "boolean",+ "primaryKey": false,+ "notNull": true,+ "default": false+ },+ "search_volume": {+ "name": "search_volume",+ "type": "integer",+ "primaryKey": false,+ "notNull": false+ },+ "keyword_difficulty": {+ "name": "keyword_difficulty",+ "type": "integer",+ "primaryKey": false,+ "notNull": false+ },+ "cpc": {+ "name": "cpc",+ "type": "real",+ "primaryKey": false,+ "notNull": false+ },+ "metrics_fetched_at": {+ "name": "metrics_fetched_at",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "created_at": {+ "name": "created_at",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "to_char(now() AT TIME ZONE 'utc', 'YYYY-MM-DD\"T\"HH24:MI:SS.MS\"Z\"')"+ }+ },+ "indexes": {+ "rank_tracking_keywords_config_keyword_idx": {+ "name": "rank_tracking_keywords_config_keyword_idx",+ "columns": [+ {+ "expression": "config_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "keyword",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": true,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "rank_tracking_keywords_config_id_rank_tracking_configs_id_fk": {+ "name": "rank_tracking_keywords_config_id_rank_tracking_configs_id_fk",+ "tableFrom": "rank_tracking_keywords",+ "tableTo": "rank_tracking_configs",+ "columnsFrom": [+ "config_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.saved_keyword_tag_assignments": {+ "name": "saved_keyword_tag_assignments",+ "schema": "",+ "columns": {+ "saved_keyword_id": {+ "name": "saved_keyword_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "tag_id": {+ "name": "tag_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "created_at": {+ "name": "created_at",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "to_char(now() AT TIME ZONE 'utc', 'YYYY-MM-DD\"T\"HH24:MI:SS.MS\"Z\"')"+ }+ },+ "indexes": {+ "saved_keyword_tag_assignments_unique_idx": {+ "name": "saved_keyword_tag_assignments_unique_idx",+ "columns": [+ {+ "expression": "saved_keyword_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "tag_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": true,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "saved_keyword_tag_assignments_tag_idx": {+ "name": "saved_keyword_tag_assignments_tag_idx",+ "columns": [+ {+ "expression": "tag_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "saved_keyword_tag_assignments_saved_keyword_id_saved_keywords_id_fk": {+ "name": "saved_keyword_tag_assignments_saved_keyword_id_saved_keywords_id_fk",+ "tableFrom": "saved_keyword_tag_assignments",+ "tableTo": "saved_keywords",+ "columnsFrom": [+ "saved_keyword_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "saved_keyword_tag_assignments_tag_id_saved_keyword_tags_id_fk": {+ "name": "saved_keyword_tag_assignments_tag_id_saved_keyword_tags_id_fk",+ "tableFrom": "saved_keyword_tag_assignments",+ "tableTo": "saved_keyword_tags",+ "columnsFrom": [+ "tag_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.saved_keyword_tags": {+ "name": "saved_keyword_tags",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "project_id": {+ "name": "project_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "name": {+ "name": "name",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "normalized_name": {+ "name": "normalized_name",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "color": {+ "name": "color",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "created_at": {+ "name": "created_at",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "to_char(now() AT TIME ZONE 'utc', 'YYYY-MM-DD\"T\"HH24:MI:SS.MS\"Z\"')"+ }+ },+ "indexes": {+ "saved_keyword_tags_project_normalized_name_idx": {+ "name": "saved_keyword_tags_project_normalized_name_idx",+ "columns": [+ {+ "expression": "project_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "normalized_name",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": true,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "saved_keyword_tags_project_name_idx": {+ "name": "saved_keyword_tags_project_name_idx",+ "columns": [+ {+ "expression": "project_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "name",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "saved_keyword_tags_project_id_projects_id_fk": {+ "name": "saved_keyword_tags_project_id_projects_id_fk",+ "tableFrom": "saved_keyword_tags",+ "tableTo": "projects",+ "columnsFrom": [+ "project_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.saved_keywords": {+ "name": "saved_keywords",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "project_id": {+ "name": "project_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "keyword": {+ "name": "keyword",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "location_code": {+ "name": "location_code",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "default": 2840+ },+ "language_code": {+ "name": "language_code",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'en'"+ },+ "created_at": {+ "name": "created_at",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "to_char(now() AT TIME ZONE 'utc', 'YYYY-MM-DD\"T\"HH24:MI:SS.MS\"Z\"')"+ }+ },+ "indexes": {+ "saved_keywords_unique_project_keyword_location_language": {+ "name": "saved_keywords_unique_project_keyword_location_language",+ "columns": [+ {+ "expression": "project_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "keyword",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "location_code",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "language_code",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": true,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "saved_keywords_project_created_idx": {+ "name": "saved_keywords_project_created_idx",+ "columns": [+ {+ "expression": "project_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "created_at",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "saved_keywords_project_id_projects_id_fk": {+ "name": "saved_keywords_project_id_projects_id_fk",+ "tableFrom": "saved_keywords",+ "tableTo": "projects",+ "columnsFrom": [+ "project_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.user_onboarding_answers": {+ "name": "user_onboarding_answers",+ "schema": "",+ "columns": {+ "user_id": {+ "name": "user_id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "organization_id": {+ "name": "organization_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "interested_features": {+ "name": "interested_features",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'[]'"+ },+ "work_for": {+ "name": "work_for",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "client_website_count": {+ "name": "client_website_count",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "found_via": {+ "name": "found_via",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "mcp_setup_intent": {+ "name": "mcp_setup_intent",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "completed_at": {+ "name": "completed_at",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "gsc_nudge_dismissed_at": {+ "name": "gsc_nudge_dismissed_at",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "created_at": {+ "name": "created_at",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "to_char(now() AT TIME ZONE 'utc', 'YYYY-MM-DD\"T\"HH24:MI:SS.MS\"Z\"')"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "to_char(now() AT TIME ZONE 'utc', 'YYYY-MM-DD\"T\"HH24:MI:SS.MS\"Z\"')"+ }+ },+ "indexes": {+ "user_onboarding_answers_organization_idx": {+ "name": "user_onboarding_answers_organization_idx",+ "columns": [+ {+ "expression": "organization_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "user_onboarding_answers_user_id_user_id_fk": {+ "name": "user_onboarding_answers_user_id_user_id_fk",+ "tableFrom": "user_onboarding_answers",+ "tableTo": "user",+ "columnsFrom": [+ "user_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "user_onboarding_answers_organization_id_organization_id_fk": {+ "name": "user_onboarding_answers_organization_id_organization_id_fk",+ "tableFrom": "user_onboarding_answers",+ "tableTo": "organization",+ "columnsFrom": [+ "organization_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.project_competitors": {+ "name": "project_competitors",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "project_id": {+ "name": "project_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "domain": {+ "name": "domain",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "name": {+ "name": "name",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "notes": {+ "name": "notes",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "updated_at": {+ "name": "updated_at",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "to_char(now() AT TIME ZONE 'utc', 'YYYY-MM-DD\"T\"HH24:MI:SS.MS\"Z\"')"+ },+ "updated_by": {+ "name": "updated_by",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ }+ },+ "indexes": {+ "project_competitors_project_domain_idx": {+ "name": "project_competitors_project_domain_idx",+ "columns": [+ {+ "expression": "project_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "domain",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": true,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "project_competitors_project_id_projects_id_fk": {+ "name": "project_competitors_project_id_projects_id_fk",+ "tableFrom": "project_competitors",+ "tableTo": "projects",+ "columnsFrom": [+ "project_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.project_context_sections": {+ "name": "project_context_sections",+ "schema": "",+ "columns": {+ "project_id": {+ "name": "project_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "key": {+ "name": "key",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "title": {+ "name": "title",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "content": {+ "name": "content",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "updated_at": {+ "name": "updated_at",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "to_char(now() AT TIME ZONE 'utc', 'YYYY-MM-DD\"T\"HH24:MI:SS.MS\"Z\"')"+ },+ "updated_by": {+ "name": "updated_by",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ }+ },+ "indexes": {},+ "foreignKeys": {+ "project_context_sections_project_id_projects_id_fk": {+ "name": "project_context_sections_project_id_projects_id_fk",+ "tableFrom": "project_context_sections",+ "tableTo": "projects",+ "columnsFrom": [+ "project_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {+ "project_context_sections_project_id_key_pk": {+ "name": "project_context_sections_project_id_key_pk",+ "columns": [+ "project_id",+ "key"+ ]+ }+ },+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.project_key_pages": {+ "name": "project_key_pages",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "project_id": {+ "name": "project_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "url": {+ "name": "url",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "role": {+ "name": "role",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "topic": {+ "name": "topic",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "notes": {+ "name": "notes",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "updated_at": {+ "name": "updated_at",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "to_char(now() AT TIME ZONE 'utc', 'YYYY-MM-DD\"T\"HH24:MI:SS.MS\"Z\"')"+ },+ "updated_by": {+ "name": "updated_by",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ }+ },+ "indexes": {+ "project_key_pages_project_url_idx": {+ "name": "project_key_pages_project_url_idx",+ "columns": [+ {+ "expression": "project_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "url",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": true,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "project_key_pages_project_id_projects_id_fk": {+ "name": "project_key_pages_project_id_projects_id_fk",+ "tableFrom": "project_key_pages",+ "tableTo": "projects",+ "columnsFrom": [+ "project_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.project_research_log": {+ "name": "project_research_log",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "project_id": {+ "name": "project_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "entry_date": {+ "name": "entry_date",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "summary": {+ "name": "summary",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "created_by": {+ "name": "created_by",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "created_at": {+ "name": "created_at",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "to_char(now() AT TIME ZONE 'utc', 'YYYY-MM-DD\"T\"HH24:MI:SS.MS\"Z\"')"+ }+ },+ "indexes": {+ "project_research_log_project_date_idx": {+ "name": "project_research_log_project_date_idx",+ "columns": [+ {+ "expression": "project_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "entry_date",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "project_research_log_project_id_projects_id_fk": {+ "name": "project_research_log_project_id_projects_id_fk",+ "tableFrom": "project_research_log",+ "tableTo": "projects",+ "columnsFrom": [+ "project_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.reports": {+ "name": "reports",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "project_id": {+ "name": "project_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "title": {+ "name": "title",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "summary": {+ "name": "summary",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "html": {+ "name": "html",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "skill": {+ "name": "skill",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "template_id": {+ "name": "template_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "created_by": {+ "name": "created_by",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "created_by_user_id": {+ "name": "created_by_user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "size_bytes": {+ "name": "size_bytes",+ "type": "integer",+ "primaryKey": false,+ "notNull": true+ },+ "share_token": {+ "name": "share_token",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "shared_at": {+ "name": "shared_at",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "created_at": {+ "name": "created_at",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "to_char(now() AT TIME ZONE 'utc', 'YYYY-MM-DD\"T\"HH24:MI:SS.MS\"Z\"')"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "to_char(now() AT TIME ZONE 'utc', 'YYYY-MM-DD\"T\"HH24:MI:SS.MS\"Z\"')"+ }+ },+ "indexes": {+ "reports_project_updated_idx": {+ "name": "reports_project_updated_idx",+ "columns": [+ {+ "expression": "project_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "updated_at",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "size_bytes",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "reports_share_token_idx": {+ "name": "reports_share_token_idx",+ "columns": [+ {+ "expression": "share_token",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": true,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "reports_project_id_projects_id_fk": {+ "name": "reports_project_id_projects_id_fk",+ "tableFrom": "reports",+ "tableTo": "projects",+ "columnsFrom": [+ "project_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.report_templates": {+ "name": "report_templates",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "project_id": {+ "name": "project_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "name": {+ "name": "name",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "description": {+ "name": "description",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "instructions": {+ "name": "instructions",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "created_by": {+ "name": "created_by",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "created_by_user_id": {+ "name": "created_by_user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "created_at": {+ "name": "created_at",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "to_char(now() AT TIME ZONE 'utc', 'YYYY-MM-DD\"T\"HH24:MI:SS.MS\"Z\"')"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "to_char(now() AT TIME ZONE 'utc', 'YYYY-MM-DD\"T\"HH24:MI:SS.MS\"Z\"')"+ }+ },+ "indexes": {+ "report_templates_project_name_idx": {+ "name": "report_templates_project_name_idx",+ "columns": [+ {+ "expression": "project_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "name",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": true,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "report_templates_project_id_projects_id_fk": {+ "name": "report_templates_project_id_projects_id_fk",+ "tableFrom": "report_templates",+ "tableTo": "projects",+ "columnsFrom": [+ "project_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.audit_issues": {+ "name": "audit_issues",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "audit_id": {+ "name": "audit_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "page_id": {+ "name": "page_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "page_url": {+ "name": "page_url",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "issue_type": {+ "name": "issue_type",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "severity": {+ "name": "severity",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'info'"+ },+ "details_json": {+ "name": "details_json",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ }+ },+ "indexes": {+ "audit_issues_audit_type_idx": {+ "name": "audit_issues_audit_type_idx",+ "columns": [+ {+ "expression": "audit_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "issue_type",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "audit_issues_page_id_idx": {+ "name": "audit_issues_page_id_idx",+ "columns": [+ {+ "expression": "page_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "audit_issues_audit_id_audits_id_fk": {+ "name": "audit_issues_audit_id_audits_id_fk",+ "tableFrom": "audit_issues",+ "tableTo": "audits",+ "columnsFrom": [+ "audit_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "audit_issues_page_id_audit_pages_id_fk": {+ "name": "audit_issues_page_id_audit_pages_id_fk",+ "tableFrom": "audit_issues",+ "tableTo": "audit_pages",+ "columnsFrom": [+ "page_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.audit_lighthouse_results": {+ "name": "audit_lighthouse_results",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "audit_id": {+ "name": "audit_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "page_id": {+ "name": "page_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "strategy": {+ "name": "strategy",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "performance_score": {+ "name": "performance_score",+ "type": "integer",+ "primaryKey": false,+ "notNull": false+ },+ "accessibility_score": {+ "name": "accessibility_score",+ "type": "integer",+ "primaryKey": false,+ "notNull": false+ },+ "best_practices_score": {+ "name": "best_practices_score",+ "type": "integer",+ "primaryKey": false,+ "notNull": false+ },+ "seo_score": {+ "name": "seo_score",+ "type": "integer",+ "primaryKey": false,+ "notNull": false+ },+ "lcp_ms": {+ "name": "lcp_ms",+ "type": "real",+ "primaryKey": false,+ "notNull": false+ },+ "cls": {+ "name": "cls",+ "type": "real",+ "primaryKey": false,+ "notNull": false+ },+ "inp_ms": {+ "name": "inp_ms",+ "type": "real",+ "primaryKey": false,+ "notNull": false+ },+ "ttfb_ms": {+ "name": "ttfb_ms",+ "type": "real",+ "primaryKey": false,+ "notNull": false+ },+ "error_message": {+ "name": "error_message",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "r2_key": {+ "name": "r2_key",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "payload_size_bytes": {+ "name": "payload_size_bytes",+ "type": "integer",+ "primaryKey": false,+ "notNull": false+ }+ },+ "indexes": {+ "audit_lighthouse_results_audit_id_idx": {+ "name": "audit_lighthouse_results_audit_id_idx",+ "columns": [+ {+ "expression": "audit_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "audit_lighthouse_results_page_id_idx": {+ "name": "audit_lighthouse_results_page_id_idx",+ "columns": [+ {+ "expression": "page_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "audit_lighthouse_results_audit_id_audits_id_fk": {+ "name": "audit_lighthouse_results_audit_id_audits_id_fk",+ "tableFrom": "audit_lighthouse_results",+ "tableTo": "audits",+ "columnsFrom": [+ "audit_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "audit_lighthouse_results_page_id_audit_pages_id_fk": {+ "name": "audit_lighthouse_results_page_id_audit_pages_id_fk",+ "tableFrom": "audit_lighthouse_results",+ "tableTo": "audit_pages",+ "columnsFrom": [+ "page_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.audit_pages": {+ "name": "audit_pages",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "audit_id": {+ "name": "audit_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "url": {+ "name": "url",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "status_code": {+ "name": "status_code",+ "type": "integer",+ "primaryKey": false,+ "notNull": false+ },+ "redirect_url": {+ "name": "redirect_url",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "title": {+ "name": "title",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "meta_description": {+ "name": "meta_description",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "canonical_url": {+ "name": "canonical_url",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "robots_meta": {+ "name": "robots_meta",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "og_title": {+ "name": "og_title",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "og_description": {+ "name": "og_description",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "og_image": {+ "name": "og_image",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "h1_count": {+ "name": "h1_count",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "default": 0+ },+ "h2_count": {+ "name": "h2_count",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "default": 0+ },+ "h3_count": {+ "name": "h3_count",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "default": 0+ },+ "h4_count": {+ "name": "h4_count",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "default": 0+ },+ "h5_count": {+ "name": "h5_count",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "default": 0+ },+ "h6_count": {+ "name": "h6_count",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "default": 0+ },+ "heading_order_json": {+ "name": "heading_order_json",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "word_count": {+ "name": "word_count",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "default": 0+ },+ "images_total": {+ "name": "images_total",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "default": 0+ },+ "images_missing_alt": {+ "name": "images_missing_alt",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "default": 0+ },+ "images_json": {+ "name": "images_json",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "internal_link_count": {+ "name": "internal_link_count",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "default": 0+ },+ "external_link_count": {+ "name": "external_link_count",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "default": 0+ },+ "has_structured_data": {+ "name": "has_structured_data",+ "type": "boolean",+ "primaryKey": false,+ "notNull": true,+ "default": false+ },+ "hreflang_tags_json": {+ "name": "hreflang_tags_json",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "is_indexable": {+ "name": "is_indexable",+ "type": "boolean",+ "primaryKey": false,+ "notNull": true,+ "default": true+ },+ "x_robots_tag": {+ "name": "x_robots_tag",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "header_canonical_url": {+ "name": "header_canonical_url",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "crawl_depth": {+ "name": "crawl_depth",+ "type": "integer",+ "primaryKey": false,+ "notNull": false+ },+ "in_sitemap": {+ "name": "in_sitemap",+ "type": "boolean",+ "primaryKey": false,+ "notNull": true,+ "default": false+ },+ "content_hash": {+ "name": "content_hash",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "fetch_class": {+ "name": "fetch_class",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'ok'"+ },+ "response_time_ms": {+ "name": "response_time_ms",+ "type": "integer",+ "primaryKey": false,+ "notNull": false+ }+ },+ "indexes": {+ "audit_pages_audit_url_idx": {+ "name": "audit_pages_audit_url_idx",+ "columns": [+ {+ "expression": "audit_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "url",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "audit_pages_audit_id_audits_id_fk": {+ "name": "audit_pages_audit_id_audits_id_fk",+ "tableFrom": "audit_pages",+ "tableTo": "audits",+ "columnsFrom": [+ "audit_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.audits": {+ "name": "audits",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "project_id": {+ "name": "project_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "started_by_user_id": {+ "name": "started_by_user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "start_url": {+ "name": "start_url",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "status": {+ "name": "status",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'running'"+ },+ "workflow_instance_id": {+ "name": "workflow_instance_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "config": {+ "name": "config",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'{}'"+ },+ "pages_crawled": {+ "name": "pages_crawled",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "default": 0+ },+ "pages_total": {+ "name": "pages_total",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "default": 0+ },+ "lighthouse_total": {+ "name": "lighthouse_total",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "default": 0+ },+ "lighthouse_completed": {+ "name": "lighthouse_completed",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "default": 0+ },+ "lighthouse_failed": {+ "name": "lighthouse_failed",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "default": 0+ },+ "current_phase": {+ "name": "current_phase",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "default": "'discovery'"+ },+ "error_code": {+ "name": "error_code",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "error_detail": {+ "name": "error_detail",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "failed_phase": {+ "name": "failed_phase",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "started_at": {+ "name": "started_at",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "to_char(now() AT TIME ZONE 'utc', 'YYYY-MM-DD\"T\"HH24:MI:SS.MS\"Z\"')"+ },+ "completed_at": {+ "name": "completed_at",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ }+ },+ "indexes": {+ "audits_project_id_idx": {+ "name": "audits_project_id_idx",+ "columns": [+ {+ "expression": "project_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "audits_started_by_user_id_idx": {+ "name": "audits_started_by_user_id_idx",+ "columns": [+ {+ "expression": "started_by_user_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "audits_project_id_projects_id_fk": {+ "name": "audits_project_id_projects_id_fk",+ "tableFrom": "audits",+ "tableTo": "projects",+ "columnsFrom": [+ "project_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.sam_sessions": {+ "name": "sam_sessions",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "project_id": {+ "name": "project_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "user_id": {+ "name": "user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "title": {+ "name": "title",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'New chat'"+ },+ "created_at": {+ "name": "created_at",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "to_char(now() AT TIME ZONE 'utc', 'YYYY-MM-DD\"T\"HH24:MI:SS.MS\"Z\"')"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "to_char(now() AT TIME ZONE 'utc', 'YYYY-MM-DD\"T\"HH24:MI:SS.MS\"Z\"')"+ },+ "archived_at": {+ "name": "archived_at",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ }+ },+ "indexes": {+ "sam_sessions_project_updated_idx": {+ "name": "sam_sessions_project_updated_idx",+ "columns": [+ {+ "expression": "project_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "updated_at",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "sam_sessions_project_id_projects_id_fk": {+ "name": "sam_sessions_project_id_projects_id_fk",+ "tableFrom": "sam_sessions",+ "tableTo": "projects",+ "columnsFrom": [+ "project_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "sam_sessions_user_id_user_id_fk": {+ "name": "sam_sessions_user_id_user_id_fk",+ "tableFrom": "sam_sessions",+ "tableTo": "user",+ "columnsFrom": [+ "user_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.account": {+ "name": "account",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "account_id": {+ "name": "account_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "provider_id": {+ "name": "provider_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "user_id": {+ "name": "user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "access_token": {+ "name": "access_token",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "refresh_token": {+ "name": "refresh_token",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "id_token": {+ "name": "id_token",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "access_token_expires_at": {+ "name": "access_token_expires_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": false+ },+ "refresh_token_expires_at": {+ "name": "refresh_token_expires_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": false+ },+ "scope": {+ "name": "scope",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "password": {+ "name": "password",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true+ }+ },+ "indexes": {+ "account_userId_idx": {+ "name": "account_userId_idx",+ "columns": [+ {+ "expression": "user_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "account_accountId_providerId_idx": {+ "name": "account_accountId_providerId_idx",+ "columns": [+ {+ "expression": "account_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "provider_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "account_google_grant_owner_idx": {+ "name": "account_google_grant_owner_idx",+ "columns": [+ {+ "expression": "user_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "provider_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "account_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": true,+ "where": "\"account\".\"provider_id\" in ('google-search-console', 'google-analytics')",+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "account_user_id_user_id_fk": {+ "name": "account_user_id_user_id_fk",+ "tableFrom": "account",+ "tableTo": "user",+ "columnsFrom": [+ "user_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.apikey": {+ "name": "apikey",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "config_id": {+ "name": "config_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'default'"+ },+ "name": {+ "name": "name",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "start": {+ "name": "start",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "prefix": {+ "name": "prefix",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "key": {+ "name": "key",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "reference_id": {+ "name": "reference_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "refill_interval": {+ "name": "refill_interval",+ "type": "integer",+ "primaryKey": false,+ "notNull": false+ },+ "refill_amount": {+ "name": "refill_amount",+ "type": "integer",+ "primaryKey": false,+ "notNull": false+ },+ "last_refill_at": {+ "name": "last_refill_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": false+ },+ "enabled": {+ "name": "enabled",+ "type": "boolean",+ "primaryKey": false,+ "notNull": false,+ "default": true+ },+ "rate_limit_enabled": {+ "name": "rate_limit_enabled",+ "type": "boolean",+ "primaryKey": false,+ "notNull": false,+ "default": true+ },+ "rate_limit_time_window": {+ "name": "rate_limit_time_window",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "default": 60000+ },+ "rate_limit_max": {+ "name": "rate_limit_max",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "default": 120+ },+ "request_count": {+ "name": "request_count",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "default": 0+ },+ "remaining": {+ "name": "remaining",+ "type": "integer",+ "primaryKey": false,+ "notNull": false+ },+ "last_request": {+ "name": "last_request",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": false+ },+ "expires_at": {+ "name": "expires_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": false+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true+ },+ "permissions": {+ "name": "permissions",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "metadata": {+ "name": "metadata",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ }+ },+ "indexes": {+ "apikey_configId_idx": {+ "name": "apikey_configId_idx",+ "columns": [+ {+ "expression": "config_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "apikey_referenceId_idx": {+ "name": "apikey_referenceId_idx",+ "columns": [+ {+ "expression": "reference_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "apikey_key_idx": {+ "name": "apikey_key_idx",+ "columns": [+ {+ "expression": "key",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {},+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.invitation": {+ "name": "invitation",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "organization_id": {+ "name": "organization_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "email": {+ "name": "email",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "role": {+ "name": "role",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "status": {+ "name": "status",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'pending'"+ },+ "expires_at": {+ "name": "expires_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "inviter_id": {+ "name": "inviter_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ }+ },+ "indexes": {+ "invitation_organizationId_idx": {+ "name": "invitation_organizationId_idx",+ "columns": [+ {+ "expression": "organization_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "invitation_email_idx": {+ "name": "invitation_email_idx",+ "columns": [+ {+ "expression": "email",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "invitation_organization_id_organization_id_fk": {+ "name": "invitation_organization_id_organization_id_fk",+ "tableFrom": "invitation",+ "tableTo": "organization",+ "columnsFrom": [+ "organization_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "invitation_inviter_id_user_id_fk": {+ "name": "invitation_inviter_id_user_id_fk",+ "tableFrom": "invitation",+ "tableTo": "user",+ "columnsFrom": [+ "inviter_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.member": {+ "name": "member",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "organization_id": {+ "name": "organization_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "user_id": {+ "name": "user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "role": {+ "name": "role",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'member'"+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true+ }+ },+ "indexes": {+ "member_organizationId_idx": {+ "name": "member_organizationId_idx",+ "columns": [+ {+ "expression": "organization_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "member_userId_idx": {+ "name": "member_userId_idx",+ "columns": [+ {+ "expression": "user_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "member_organizationId_userId_uidx": {+ "name": "member_organizationId_userId_uidx",+ "columns": [+ {+ "expression": "organization_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "user_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": true,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "member_organization_id_organization_id_fk": {+ "name": "member_organization_id_organization_id_fk",+ "tableFrom": "member",+ "tableTo": "organization",+ "columnsFrom": [+ "organization_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "member_user_id_user_id_fk": {+ "name": "member_user_id_user_id_fk",+ "tableFrom": "member",+ "tableTo": "user",+ "columnsFrom": [+ "user_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.organization": {+ "name": "organization",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "name": {+ "name": "name",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "slug": {+ "name": "slug",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "logo": {+ "name": "logo",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true+ },+ "metadata": {+ "name": "metadata",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ }+ },+ "indexes": {+ "organization_slug_uidx": {+ "name": "organization_slug_uidx",+ "columns": [+ {+ "expression": "slug",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": true,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {},+ "compositePrimaryKeys": {},+ "uniqueConstraints": {+ "organization_slug_unique": {+ "name": "organization_slug_unique",+ "nullsNotDistinct": false,+ "columns": [+ "slug"+ ]+ }+ },+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.session": {+ "name": "session",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "expires_at": {+ "name": "expires_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true+ },+ "token": {+ "name": "token",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true+ },+ "ip_address": {+ "name": "ip_address",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "user_agent": {+ "name": "user_agent",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "user_id": {+ "name": "user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "active_organization_id": {+ "name": "active_organization_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ }+ },+ "indexes": {+ "session_userId_idx": {+ "name": "session_userId_idx",+ "columns": [+ {+ "expression": "user_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "session_user_id_user_id_fk": {+ "name": "session_user_id_user_id_fk",+ "tableFrom": "session",+ "tableTo": "user",+ "columnsFrom": [+ "user_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {+ "session_token_unique": {+ "name": "session_token_unique",+ "nullsNotDistinct": false,+ "columns": [+ "token"+ ]+ }+ },+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.user": {+ "name": "user",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "name": {+ "name": "name",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "email": {+ "name": "email",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "email_verified": {+ "name": "email_verified",+ "type": "boolean",+ "primaryKey": false,+ "notNull": true,+ "default": false+ },+ "image": {+ "name": "image",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "analytics_opted_out": {+ "name": "analytics_opted_out",+ "type": "boolean",+ "primaryKey": false,+ "notNull": false+ },+ "last_active_organization_id": {+ "name": "last_active_organization_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ }+ },+ "indexes": {},+ "foreignKeys": {},+ "compositePrimaryKeys": {},+ "uniqueConstraints": {+ "user_email_unique": {+ "name": "user_email_unique",+ "nullsNotDistinct": false,+ "columns": [+ "email"+ ]+ }+ },+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.verification": {+ "name": "verification",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "identifier": {+ "name": "identifier",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "value": {+ "name": "value",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "expires_at": {+ "name": "expires_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "verification_identifier_idx": {+ "name": "verification_identifier_idx",+ "columns": [+ {+ "expression": "identifier",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "verification_expiresAt_idx": {+ "name": "verification_expiresAt_idx",+ "columns": [+ {+ "expression": "expires_at",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {},+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.billing_customer_status": {+ "name": "billing_customer_status",+ "schema": "",+ "columns": {+ "organization_id": {+ "name": "organization_id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "is_paying": {+ "name": "is_paying",+ "type": "boolean",+ "primaryKey": false,+ "notNull": true,+ "default": false+ },+ "paid_plan_id": {+ "name": "paid_plan_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "paid_plan_status": {+ "name": "paid_plan_status",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "customer_json": {+ "name": "customer_json",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "synced_at": {+ "name": "synced_at",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "created_at": {+ "name": "created_at",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "to_char(now() AT TIME ZONE 'utc', 'YYYY-MM-DD\"T\"HH24:MI:SS.MS\"Z\"')"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "to_char(now() AT TIME ZONE 'utc', 'YYYY-MM-DD\"T\"HH24:MI:SS.MS\"Z\"')"+ }+ },+ "indexes": {},+ "foreignKeys": {+ "billing_customer_status_organization_id_organization_id_fk": {+ "name": "billing_customer_status_organization_id_organization_id_fk",+ "tableFrom": "billing_customer_status",+ "tableTo": "organization",+ "columnsFrom": [+ "organization_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.ga4_connections": {+ "name": "ga4_connections",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "project_id": {+ "name": "project_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "organization_id": {+ "name": "organization_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "property_id": {+ "name": "property_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "property_display_name": {+ "name": "property_display_name",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "property_time_zone": {+ "name": "property_time_zone",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "property_currency_code": {+ "name": "property_currency_code",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "connected_by_user_id": {+ "name": "connected_by_user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "ga4_account_id": {+ "name": "ga4_account_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "connected_account_email": {+ "name": "connected_account_email",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "created_at": {+ "name": "created_at",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "to_char(now() AT TIME ZONE 'utc', 'YYYY-MM-DD\"T\"HH24:MI:SS.MS\"Z\"')"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "to_char(now() AT TIME ZONE 'utc', 'YYYY-MM-DD\"T\"HH24:MI:SS.MS\"Z\"')"+ }+ },+ "indexes": {+ "ga4_connections_project_idx": {+ "name": "ga4_connections_project_idx",+ "columns": [+ {+ "expression": "project_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": true,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "ga4_connections_organization_idx": {+ "name": "ga4_connections_organization_idx",+ "columns": [+ {+ "expression": "organization_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "ga4_connections_connector_idx": {+ "name": "ga4_connections_connector_idx",+ "columns": [+ {+ "expression": "connected_by_user_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "ga4_account_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "ga4_connections_project_id_projects_id_fk": {+ "name": "ga4_connections_project_id_projects_id_fk",+ "tableFrom": "ga4_connections",+ "tableTo": "projects",+ "columnsFrom": [+ "project_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "ga4_connections_organization_id_organization_id_fk": {+ "name": "ga4_connections_organization_id_organization_id_fk",+ "tableFrom": "ga4_connections",+ "tableTo": "organization",+ "columnsFrom": [+ "organization_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.gsc_connections": {+ "name": "gsc_connections",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "project_id": {+ "name": "project_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "organization_id": {+ "name": "organization_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "site_url": {+ "name": "site_url",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "connected_by_user_id": {+ "name": "connected_by_user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "gsc_account_id": {+ "name": "gsc_account_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "connected_account_email": {+ "name": "connected_account_email",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "created_at": {+ "name": "created_at",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "to_char(now() AT TIME ZONE 'utc', 'YYYY-MM-DD\"T\"HH24:MI:SS.MS\"Z\"')"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "to_char(now() AT TIME ZONE 'utc', 'YYYY-MM-DD\"T\"HH24:MI:SS.MS\"Z\"')"+ }+ },+ "indexes": {+ "gsc_connections_project_idx": {+ "name": "gsc_connections_project_idx",+ "columns": [+ {+ "expression": "project_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": true,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "gsc_connections_organization_idx": {+ "name": "gsc_connections_organization_idx",+ "columns": [+ {+ "expression": "organization_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "gsc_connections_project_id_projects_id_fk": {+ "name": "gsc_connections_project_id_projects_id_fk",+ "tableFrom": "gsc_connections",+ "tableTo": "projects",+ "columnsFrom": [+ "project_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "gsc_connections_organization_id_organization_id_fk": {+ "name": "gsc_connections_organization_id_organization_id_fk",+ "tableFrom": "gsc_connections",+ "tableTo": "organization",+ "columnsFrom": [+ "organization_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.telemetry_state": {+ "name": "telemetry_state",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "integer",+ "primaryKey": true,+ "notNull": true,+ "default": 1+ },+ "install_id": {+ "name": "install_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "installed_at": {+ "name": "installed_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": false+ },+ "last_heartbeat_at": {+ "name": "last_heartbeat_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": false+ },+ "last_version": {+ "name": "last_version",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "mcp_tool_call_count": {+ "name": "mcp_tool_call_count",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "default": 0+ }+ },+ "indexes": {},+ "foreignKeys": {},+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ }+ },+ "enums": {},+ "schemas": {},+ "sequences": {},+ "roles": {},+ "policies": {},+ "views": {},+ "_meta": {+ "columns": {},+ "schemas": {},+ "tables": {}+ }+}\ No newline at end of filediff --git a/drizzle-pg/meta/_journal.json b/drizzle-pg/meta/_journal.jsonindex f74df84c..f7c806b5 100644--- a/drizzle-pg/meta/_journal.json+++ b/drizzle-pg/meta/_journal.json@@ -197,6 +197,13 @@"when": 1790212958262,"tag": "0027_keyword_step","breakpoints": true+ },+ {+ "idx": 28,+ "version": "7",+ "when": 1790316400631,+ "tag": "0028_modern_nekra",+ "breakpoints": true}]}\ No newline at end of filediff --git a/drizzle/0050_famous_crystal.sql b/drizzle/0050_famous_crystal.sqlnew file mode 100644index 00000000..c5a980be--- /dev/null+++ b/drizzle/0050_famous_crystal.sql@@ -0,0 +1,13 @@+DELETE FROM `account` WHERE `id` IN (+ SELECT `id` FROM (+ SELECT `id`, ROW_NUMBER() OVER (+ PARTITION BY `user_id`, `provider_id`, `account_id`+ ORDER BY (`refresh_token` IS NOT NULL) DESC, `updated_at` DESC, `id` DESC+ ) AS `row_number`+ FROM `account`+ WHERE `provider_id` IN ('google-search-console', 'google-analytics')+ ) AS `duplicate_grants`+ WHERE `row_number` > 1+);+--> statement-breakpoint+CREATE UNIQUE INDEX IF NOT EXISTS `account_google_grant_owner_idx` ON `account` (`user_id`,`provider_id`,`account_id`) WHERE "account"."provider_id" in ('google-search-console', 'google-analytics');diff --git a/drizzle/meta/0050_snapshot.json b/drizzle/meta/0050_snapshot.jsonnew file mode 100644index 00000000..3781ed80--- /dev/null+++ b/drizzle/meta/0050_snapshot.json@@ -0,0 +1,4184 @@+{+ "version": "6",+ "dialect": "sqlite",+ "id": "7cf6af9c-60b6-4eaa-9b61-535e0b684e33",+ "prevId": "fae28927-4696-4704-accf-12a4793fbda8",+ "tables": {+ "backlink_snapshots": {+ "name": "backlink_snapshots",+ "columns": {+ "id": {+ "name": "id",+ "type": "integer",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": true+ },+ "project_id": {+ "name": "project_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "domain": {+ "name": "domain",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "rank": {+ "name": "rank",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "backlinks": {+ "name": "backlinks",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "referring_domains": {+ "name": "referring_domains",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "broken_backlinks": {+ "name": "broken_backlinks",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "new_backlinks": {+ "name": "new_backlinks",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "lost_backlinks": {+ "name": "lost_backlinks",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "new_referring_domains": {+ "name": "new_referring_domains",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "lost_referring_domains": {+ "name": "lost_referring_domains",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "captured_at": {+ "name": "captured_at",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "(current_timestamp)"+ }+ },+ "indexes": {+ "backlink_snapshots_project_captured_idx": {+ "name": "backlink_snapshots_project_captured_idx",+ "columns": [+ "project_id",+ "captured_at"+ ],+ "isUnique": false+ }+ },+ "foreignKeys": {+ "backlink_snapshots_project_id_projects_id_fk": {+ "name": "backlink_snapshots_project_id_projects_id_fk",+ "tableFrom": "backlink_snapshots",+ "tableTo": "projects",+ "columnsFrom": [+ "project_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "crawler_credentials": {+ "name": "crawler_credentials",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "project_id": {+ "name": "project_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "host": {+ "name": "host",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "provider": {+ "name": "provider",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "signature_input": {+ "name": "signature_input",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "signature": {+ "name": "signature",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "expires_at": {+ "name": "expires_at",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "created_by_user_id": {+ "name": "created_by_user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "created_at": {+ "name": "created_at",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "(current_timestamp)"+ }+ },+ "indexes": {+ "crawler_credentials_project_host_idx": {+ "name": "crawler_credentials_project_host_idx",+ "columns": [+ "project_id",+ "host"+ ],+ "isUnique": true+ }+ },+ "foreignKeys": {+ "crawler_credentials_project_id_projects_id_fk": {+ "name": "crawler_credentials_project_id_projects_id_fk",+ "tableFrom": "crawler_credentials",+ "tableTo": "projects",+ "columnsFrom": [+ "project_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "dashboard_step_dismissals": {+ "name": "dashboard_step_dismissals",+ "columns": {+ "user_id": {+ "name": "user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "project_id": {+ "name": "project_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "step": {+ "name": "step",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ }+ },+ "indexes": {+ "dashboard_step_dismissals_project_idx": {+ "name": "dashboard_step_dismissals_project_idx",+ "columns": [+ "project_id"+ ],+ "isUnique": false+ }+ },+ "foreignKeys": {+ "dashboard_step_dismissals_user_id_user_id_fk": {+ "name": "dashboard_step_dismissals_user_id_user_id_fk",+ "tableFrom": "dashboard_step_dismissals",+ "tableTo": "user",+ "columnsFrom": [+ "user_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "dashboard_step_dismissals_project_id_projects_id_fk": {+ "name": "dashboard_step_dismissals_project_id_projects_id_fk",+ "tableFrom": "dashboard_step_dismissals",+ "tableTo": "projects",+ "columnsFrom": [+ "project_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {+ "dashboard_step_dismissals_user_id_project_id_step_pk": {+ "columns": [+ "user_id",+ "project_id",+ "step"+ ],+ "name": "dashboard_step_dismissals_user_id_project_id_step_pk"+ }+ },+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "keyword_metrics": {+ "name": "keyword_metrics",+ "columns": {+ "id": {+ "name": "id",+ "type": "integer",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": true+ },+ "project_id": {+ "name": "project_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "keyword": {+ "name": "keyword",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "location_code": {+ "name": "location_code",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "language_code": {+ "name": "language_code",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "'en'"+ },+ "search_volume": {+ "name": "search_volume",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "cpc": {+ "name": "cpc",+ "type": "real",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "competition": {+ "name": "competition",+ "type": "real",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "keyword_difficulty": {+ "name": "keyword_difficulty",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "intent": {+ "name": "intent",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "monthly_searches": {+ "name": "monthly_searches",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "fetched_at": {+ "name": "fetched_at",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "(current_timestamp)"+ }+ },+ "indexes": {+ "keyword_metrics_unique_project_keyword_location_language": {+ "name": "keyword_metrics_unique_project_keyword_location_language",+ "columns": [+ "project_id",+ "keyword",+ "location_code",+ "language_code"+ ],+ "isUnique": true+ },+ "keyword_metrics_lookup_idx": {+ "name": "keyword_metrics_lookup_idx",+ "columns": [+ "project_id",+ "keyword",+ "location_code",+ "language_code",+ "fetched_at"+ ],+ "isUnique": false+ }+ },+ "foreignKeys": {+ "keyword_metrics_project_id_projects_id_fk": {+ "name": "keyword_metrics_project_id_projects_id_fk",+ "tableFrom": "keyword_metrics",+ "tableTo": "projects",+ "columnsFrom": [+ "project_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "organization_activation_state": {+ "name": "organization_activation_state",+ "columns": {+ "organization_id": {+ "name": "organization_id",+ "type": "text",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "first_mcp_authorized_at": {+ "name": "first_mcp_authorized_at",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "first_mcp_tool_call_at": {+ "name": "first_mcp_tool_call_at",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "updated_at": {+ "name": "updated_at",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "(current_timestamp)"+ }+ },+ "indexes": {},+ "foreignKeys": {+ "organization_activation_state_organization_id_organization_id_fk": {+ "name": "organization_activation_state_organization_id_organization_id_fk",+ "tableFrom": "organization_activation_state",+ "tableTo": "organization",+ "columnsFrom": [+ "organization_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "project_activation_state": {+ "name": "project_activation_state",+ "columns": {+ "project_id": {+ "name": "project_id",+ "type": "text",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "competitor_step_clicked_at": {+ "name": "competitor_step_clicked_at",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "keyword_step_clicked_at": {+ "name": "keyword_step_clicked_at",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "mcp_card_dismissed_at": {+ "name": "mcp_card_dismissed_at",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "ga4_card_dismissed_at": {+ "name": "ga4_card_dismissed_at",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "updated_at": {+ "name": "updated_at",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "(current_timestamp)"+ }+ },+ "indexes": {},+ "foreignKeys": {+ "project_activation_state_project_id_projects_id_fk": {+ "name": "project_activation_state_project_id_projects_id_fk",+ "tableFrom": "project_activation_state",+ "tableTo": "projects",+ "columnsFrom": [+ "project_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "projects": {+ "name": "projects",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "organization_id": {+ "name": "organization_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "name": {+ "name": "name",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "domain": {+ "name": "domain",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "location_code": {+ "name": "location_code",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": 2840+ },+ "language_code": {+ "name": "language_code",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "'en'"+ },+ "created_at": {+ "name": "created_at",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "(current_timestamp)"+ },+ "archived_at": {+ "name": "archived_at",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ }+ },+ "indexes": {+ "projects_one_default_per_organization_idx": {+ "name": "projects_one_default_per_organization_idx",+ "columns": [+ "organization_id"+ ],+ "isUnique": true,+ "where": "\"projects\".\"name\" = 'Default' AND \"projects\".\"domain\" IS NULL AND \"projects\".\"archived_at\" IS NULL"+ },+ "projects_organization_id_idx": {+ "name": "projects_organization_id_idx",+ "columns": [+ "organization_id"+ ],+ "isUnique": false+ }+ },+ "foreignKeys": {+ "projects_organization_id_organization_id_fk": {+ "name": "projects_organization_id_organization_id_fk",+ "tableFrom": "projects",+ "tableTo": "organization",+ "columnsFrom": [+ "organization_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "rank_check_runs": {+ "name": "rank_check_runs",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "config_id": {+ "name": "config_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "project_id": {+ "name": "project_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "status": {+ "name": "status",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "'pending'"+ },+ "keywords_total": {+ "name": "keywords_total",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": 0+ },+ "keywords_checked": {+ "name": "keywords_checked",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": 0+ },+ "is_subset_run": {+ "name": "is_subset_run",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": false+ },+ "error_message": {+ "name": "error_message",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "started_at": {+ "name": "started_at",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "(current_timestamp)"+ },+ "completed_at": {+ "name": "completed_at",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ }+ },+ "indexes": {+ "rank_check_runs_config_idx": {+ "name": "rank_check_runs_config_idx",+ "columns": [+ "config_id",+ "started_at"+ ],+ "isUnique": false+ },+ "rank_check_runs_project_idx": {+ "name": "rank_check_runs_project_idx",+ "columns": [+ "project_id",+ "started_at"+ ],+ "isUnique": false+ },+ "rank_check_runs_one_active_per_config_idx": {+ "name": "rank_check_runs_one_active_per_config_idx",+ "columns": [+ "config_id"+ ],+ "isUnique": true,+ "where": "\"rank_check_runs\".\"status\" IN ('pending', 'running')"+ }+ },+ "foreignKeys": {+ "rank_check_runs_config_id_rank_tracking_configs_id_fk": {+ "name": "rank_check_runs_config_id_rank_tracking_configs_id_fk",+ "tableFrom": "rank_check_runs",+ "tableTo": "rank_tracking_configs",+ "columnsFrom": [+ "config_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "rank_check_runs_project_id_projects_id_fk": {+ "name": "rank_check_runs_project_id_projects_id_fk",+ "tableFrom": "rank_check_runs",+ "tableTo": "projects",+ "columnsFrom": [+ "project_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "rank_snapshots": {+ "name": "rank_snapshots",+ "columns": {+ "id": {+ "name": "id",+ "type": "integer",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": true+ },+ "run_id": {+ "name": "run_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "tracking_keyword_id": {+ "name": "tracking_keyword_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "keyword": {+ "name": "keyword",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "device": {+ "name": "device",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "position": {+ "name": "position",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "url": {+ "name": "url",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "serp_features": {+ "name": "serp_features",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "checked_at": {+ "name": "checked_at",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "(current_timestamp)"+ }+ },+ "indexes": {+ "rank_snapshots_keyword_device_idx": {+ "name": "rank_snapshots_keyword_device_idx",+ "columns": [+ "tracking_keyword_id",+ "device",+ "checked_at"+ ],+ "isUnique": false+ },+ "rank_snapshots_run_keyword_device_idx": {+ "name": "rank_snapshots_run_keyword_device_idx",+ "columns": [+ "run_id",+ "tracking_keyword_id",+ "device"+ ],+ "isUnique": true+ }+ },+ "foreignKeys": {+ "rank_snapshots_run_id_rank_check_runs_id_fk": {+ "name": "rank_snapshots_run_id_rank_check_runs_id_fk",+ "tableFrom": "rank_snapshots",+ "tableTo": "rank_check_runs",+ "columnsFrom": [+ "run_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "rank_tracking_configs": {+ "name": "rank_tracking_configs",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "project_id": {+ "name": "project_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "domain": {+ "name": "domain",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "location_code": {+ "name": "location_code",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": 2840+ },+ "language_code": {+ "name": "language_code",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "'en'"+ },+ "devices": {+ "name": "devices",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "'both'"+ },+ "serp_depth": {+ "name": "serp_depth",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "schedule_interval": {+ "name": "schedule_interval",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "'weekly'"+ },+ "location_name": {+ "name": "location_name",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "is_active": {+ "name": "is_active",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": true+ },+ "last_checked_at": {+ "name": "last_checked_at",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "next_check_at": {+ "name": "next_check_at",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "last_skip_reason": {+ "name": "last_skip_reason",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "created_at": {+ "name": "created_at",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "(current_timestamp)"+ }+ },+ "indexes": {+ "rank_tracking_configs_project_active_created_idx": {+ "name": "rank_tracking_configs_project_active_created_idx",+ "columns": [+ "project_id",+ "is_active",+ "created_at"+ ],+ "isUnique": false+ },+ "rank_tracking_configs_national_idx": {+ "name": "rank_tracking_configs_national_idx",+ "columns": [+ "project_id",+ "domain",+ "location_code"+ ],+ "isUnique": true,+ "where": "\"rank_tracking_configs\".\"location_name\" IS NULL"+ },+ "rank_tracking_configs_local_idx": {+ "name": "rank_tracking_configs_local_idx",+ "columns": [+ "project_id",+ "domain",+ "location_code",+ "location_name"+ ],+ "isUnique": true,+ "where": "\"rank_tracking_configs\".\"location_name\" IS NOT NULL"+ }+ },+ "foreignKeys": {+ "rank_tracking_configs_project_id_projects_id_fk": {+ "name": "rank_tracking_configs_project_id_projects_id_fk",+ "tableFrom": "rank_tracking_configs",+ "tableTo": "projects",+ "columnsFrom": [+ "project_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "rank_tracking_keywords": {+ "name": "rank_tracking_keywords",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "config_id": {+ "name": "config_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "keyword": {+ "name": "keyword",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "match_case": {+ "name": "match_case",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": false+ },+ "search_volume": {+ "name": "search_volume",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "keyword_difficulty": {+ "name": "keyword_difficulty",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "cpc": {+ "name": "cpc",+ "type": "real",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "metrics_fetched_at": {+ "name": "metrics_fetched_at",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "created_at": {+ "name": "created_at",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "(current_timestamp)"+ }+ },+ "indexes": {+ "rank_tracking_keywords_config_keyword_idx": {+ "name": "rank_tracking_keywords_config_keyword_idx",+ "columns": [+ "config_id",+ "keyword"+ ],+ "isUnique": true+ }+ },+ "foreignKeys": {+ "rank_tracking_keywords_config_id_rank_tracking_configs_id_fk": {+ "name": "rank_tracking_keywords_config_id_rank_tracking_configs_id_fk",+ "tableFrom": "rank_tracking_keywords",+ "tableTo": "rank_tracking_configs",+ "columnsFrom": [+ "config_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "saved_keyword_tag_assignments": {+ "name": "saved_keyword_tag_assignments",+ "columns": {+ "saved_keyword_id": {+ "name": "saved_keyword_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "tag_id": {+ "name": "tag_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "created_at": {+ "name": "created_at",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "(current_timestamp)"+ }+ },+ "indexes": {+ "saved_keyword_tag_assignments_unique_idx": {+ "name": "saved_keyword_tag_assignments_unique_idx",+ "columns": [+ "saved_keyword_id",+ "tag_id"+ ],+ "isUnique": true+ },+ "saved_keyword_tag_assignments_tag_idx": {+ "name": "saved_keyword_tag_assignments_tag_idx",+ "columns": [+ "tag_id"+ ],+ "isUnique": false+ }+ },+ "foreignKeys": {+ "saved_keyword_tag_assignments_saved_keyword_id_saved_keywords_id_fk": {+ "name": "saved_keyword_tag_assignments_saved_keyword_id_saved_keywords_id_fk",+ "tableFrom": "saved_keyword_tag_assignments",+ "tableTo": "saved_keywords",+ "columnsFrom": [+ "saved_keyword_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "saved_keyword_tag_assignments_tag_id_saved_keyword_tags_id_fk": {+ "name": "saved_keyword_tag_assignments_tag_id_saved_keyword_tags_id_fk",+ "tableFrom": "saved_keyword_tag_assignments",+ "tableTo": "saved_keyword_tags",+ "columnsFrom": [+ "tag_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "saved_keyword_tags": {+ "name": "saved_keyword_tags",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "project_id": {+ "name": "project_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "name": {+ "name": "name",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "normalized_name": {+ "name": "normalized_name",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "color": {+ "name": "color",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "created_at": {+ "name": "created_at",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "(current_timestamp)"+ }+ },+ "indexes": {+ "saved_keyword_tags_project_normalized_name_idx": {+ "name": "saved_keyword_tags_project_normalized_name_idx",+ "columns": [+ "project_id",+ "normalized_name"+ ],+ "isUnique": true+ },+ "saved_keyword_tags_project_name_idx": {+ "name": "saved_keyword_tags_project_name_idx",+ "columns": [+ "project_id",+ "name"+ ],+ "isUnique": false+ }+ },+ "foreignKeys": {+ "saved_keyword_tags_project_id_projects_id_fk": {+ "name": "saved_keyword_tags_project_id_projects_id_fk",+ "tableFrom": "saved_keyword_tags",+ "tableTo": "projects",+ "columnsFrom": [+ "project_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "saved_keywords": {+ "name": "saved_keywords",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "project_id": {+ "name": "project_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "keyword": {+ "name": "keyword",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "location_code": {+ "name": "location_code",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": 2840+ },+ "language_code": {+ "name": "language_code",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "'en'"+ },+ "created_at": {+ "name": "created_at",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "(current_timestamp)"+ }+ },+ "indexes": {+ "saved_keywords_unique_project_keyword_location_language": {+ "name": "saved_keywords_unique_project_keyword_location_language",+ "columns": [+ "project_id",+ "keyword",+ "location_code",+ "language_code"+ ],+ "isUnique": true+ },+ "saved_keywords_project_created_idx": {+ "name": "saved_keywords_project_created_idx",+ "columns": [+ "project_id",+ "created_at"+ ],+ "isUnique": false+ }+ },+ "foreignKeys": {+ "saved_keywords_project_id_projects_id_fk": {+ "name": "saved_keywords_project_id_projects_id_fk",+ "tableFrom": "saved_keywords",+ "tableTo": "projects",+ "columnsFrom": [+ "project_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "user_onboarding_answers": {+ "name": "user_onboarding_answers",+ "columns": {+ "user_id": {+ "name": "user_id",+ "type": "text",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "organization_id": {+ "name": "organization_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "interested_features": {+ "name": "interested_features",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "'[]'"+ },+ "work_for": {+ "name": "work_for",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "client_website_count": {+ "name": "client_website_count",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "found_via": {+ "name": "found_via",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "mcp_setup_intent": {+ "name": "mcp_setup_intent",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "completed_at": {+ "name": "completed_at",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "gsc_nudge_dismissed_at": {+ "name": "gsc_nudge_dismissed_at",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "created_at": {+ "name": "created_at",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "(current_timestamp)"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "(current_timestamp)"+ }+ },+ "indexes": {+ "user_onboarding_answers_organization_idx": {+ "name": "user_onboarding_answers_organization_idx",+ "columns": [+ "organization_id"+ ],+ "isUnique": false+ }+ },+ "foreignKeys": {+ "user_onboarding_answers_user_id_user_id_fk": {+ "name": "user_onboarding_answers_user_id_user_id_fk",+ "tableFrom": "user_onboarding_answers",+ "tableTo": "user",+ "columnsFrom": [+ "user_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "user_onboarding_answers_organization_id_organization_id_fk": {+ "name": "user_onboarding_answers_organization_id_organization_id_fk",+ "tableFrom": "user_onboarding_answers",+ "tableTo": "organization",+ "columnsFrom": [+ "organization_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "project_competitors": {+ "name": "project_competitors",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "project_id": {+ "name": "project_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "domain": {+ "name": "domain",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "name": {+ "name": "name",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "notes": {+ "name": "notes",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "updated_at": {+ "name": "updated_at",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "(current_timestamp)"+ },+ "updated_by": {+ "name": "updated_by",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ }+ },+ "indexes": {+ "project_competitors_project_domain_idx": {+ "name": "project_competitors_project_domain_idx",+ "columns": [+ "project_id",+ "domain"+ ],+ "isUnique": true+ }+ },+ "foreignKeys": {+ "project_competitors_project_id_projects_id_fk": {+ "name": "project_competitors_project_id_projects_id_fk",+ "tableFrom": "project_competitors",+ "tableTo": "projects",+ "columnsFrom": [+ "project_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "project_context_sections": {+ "name": "project_context_sections",+ "columns": {+ "project_id": {+ "name": "project_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "key": {+ "name": "key",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "title": {+ "name": "title",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "content": {+ "name": "content",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "updated_at": {+ "name": "updated_at",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "(current_timestamp)"+ },+ "updated_by": {+ "name": "updated_by",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ }+ },+ "indexes": {},+ "foreignKeys": {+ "project_context_sections_project_id_projects_id_fk": {+ "name": "project_context_sections_project_id_projects_id_fk",+ "tableFrom": "project_context_sections",+ "tableTo": "projects",+ "columnsFrom": [+ "project_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {+ "project_context_sections_project_id_key_pk": {+ "columns": [+ "project_id",+ "key"+ ],+ "name": "project_context_sections_project_id_key_pk"+ }+ },+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "project_key_pages": {+ "name": "project_key_pages",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "project_id": {+ "name": "project_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "url": {+ "name": "url",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "role": {+ "name": "role",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "topic": {+ "name": "topic",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "notes": {+ "name": "notes",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "updated_at": {+ "name": "updated_at",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "(current_timestamp)"+ },+ "updated_by": {+ "name": "updated_by",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ }+ },+ "indexes": {+ "project_key_pages_project_url_idx": {+ "name": "project_key_pages_project_url_idx",+ "columns": [+ "project_id",+ "url"+ ],+ "isUnique": true+ }+ },+ "foreignKeys": {+ "project_key_pages_project_id_projects_id_fk": {+ "name": "project_key_pages_project_id_projects_id_fk",+ "tableFrom": "project_key_pages",+ "tableTo": "projects",+ "columnsFrom": [+ "project_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "project_research_log": {+ "name": "project_research_log",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "project_id": {+ "name": "project_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "entry_date": {+ "name": "entry_date",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "summary": {+ "name": "summary",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "created_by": {+ "name": "created_by",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "created_at": {+ "name": "created_at",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "(strftime('%Y-%m-%dT%H:%M:%fZ','now'))"+ }+ },+ "indexes": {+ "project_research_log_project_date_idx": {+ "name": "project_research_log_project_date_idx",+ "columns": [+ "project_id",+ "entry_date"+ ],+ "isUnique": false+ }+ },+ "foreignKeys": {+ "project_research_log_project_id_projects_id_fk": {+ "name": "project_research_log_project_id_projects_id_fk",+ "tableFrom": "project_research_log",+ "tableTo": "projects",+ "columnsFrom": [+ "project_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "reports": {+ "name": "reports",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "project_id": {+ "name": "project_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "title": {+ "name": "title",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "summary": {+ "name": "summary",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "html": {+ "name": "html",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "skill": {+ "name": "skill",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "template_id": {+ "name": "template_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "created_by": {+ "name": "created_by",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "created_by_user_id": {+ "name": "created_by_user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "size_bytes": {+ "name": "size_bytes",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "share_token": {+ "name": "share_token",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "shared_at": {+ "name": "shared_at",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "created_at": {+ "name": "created_at",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "(strftime('%Y-%m-%dT%H:%M:%fZ','now'))"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "(strftime('%Y-%m-%dT%H:%M:%fZ','now'))"+ }+ },+ "indexes": {+ "reports_project_updated_idx": {+ "name": "reports_project_updated_idx",+ "columns": [+ "project_id",+ "updated_at",+ "id",+ "size_bytes"+ ],+ "isUnique": false+ },+ "reports_share_token_idx": {+ "name": "reports_share_token_idx",+ "columns": [+ "share_token"+ ],+ "isUnique": true+ }+ },+ "foreignKeys": {+ "reports_project_id_projects_id_fk": {+ "name": "reports_project_id_projects_id_fk",+ "tableFrom": "reports",+ "tableTo": "projects",+ "columnsFrom": [+ "project_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "report_templates": {+ "name": "report_templates",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "project_id": {+ "name": "project_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "name": {+ "name": "name",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "description": {+ "name": "description",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "instructions": {+ "name": "instructions",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "created_by": {+ "name": "created_by",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "created_by_user_id": {+ "name": "created_by_user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "created_at": {+ "name": "created_at",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "(strftime('%Y-%m-%dT%H:%M:%fZ','now'))"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "(strftime('%Y-%m-%dT%H:%M:%fZ','now'))"+ }+ },+ "indexes": {+ "report_templates_project_name_idx": {+ "name": "report_templates_project_name_idx",+ "columns": [+ "project_id",+ "name"+ ],+ "isUnique": true+ }+ },+ "foreignKeys": {+ "report_templates_project_id_projects_id_fk": {+ "name": "report_templates_project_id_projects_id_fk",+ "tableFrom": "report_templates",+ "tableTo": "projects",+ "columnsFrom": [+ "project_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "audit_issues": {+ "name": "audit_issues",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "audit_id": {+ "name": "audit_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "page_id": {+ "name": "page_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "page_url": {+ "name": "page_url",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "issue_type": {+ "name": "issue_type",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "severity": {+ "name": "severity",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "'info'"+ },+ "details_json": {+ "name": "details_json",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ }+ },+ "indexes": {+ "audit_issues_audit_type_idx": {+ "name": "audit_issues_audit_type_idx",+ "columns": [+ "audit_id",+ "issue_type"+ ],+ "isUnique": false+ },+ "audit_issues_page_id_idx": {+ "name": "audit_issues_page_id_idx",+ "columns": [+ "page_id"+ ],+ "isUnique": false+ }+ },+ "foreignKeys": {+ "audit_issues_audit_id_audits_id_fk": {+ "name": "audit_issues_audit_id_audits_id_fk",+ "tableFrom": "audit_issues",+ "tableTo": "audits",+ "columnsFrom": [+ "audit_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "audit_issues_page_id_audit_pages_id_fk": {+ "name": "audit_issues_page_id_audit_pages_id_fk",+ "tableFrom": "audit_issues",+ "tableTo": "audit_pages",+ "columnsFrom": [+ "page_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "audit_lighthouse_results": {+ "name": "audit_lighthouse_results",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "audit_id": {+ "name": "audit_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "page_id": {+ "name": "page_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "strategy": {+ "name": "strategy",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "performance_score": {+ "name": "performance_score",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "accessibility_score": {+ "name": "accessibility_score",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "best_practices_score": {+ "name": "best_practices_score",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "seo_score": {+ "name": "seo_score",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "lcp_ms": {+ "name": "lcp_ms",+ "type": "real",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "cls": {+ "name": "cls",+ "type": "real",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "inp_ms": {+ "name": "inp_ms",+ "type": "real",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "ttfb_ms": {+ "name": "ttfb_ms",+ "type": "real",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "error_message": {+ "name": "error_message",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "r2_key": {+ "name": "r2_key",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "payload_size_bytes": {+ "name": "payload_size_bytes",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ }+ },+ "indexes": {+ "audit_lighthouse_results_audit_id_idx": {+ "name": "audit_lighthouse_results_audit_id_idx",+ "columns": [+ "audit_id"+ ],+ "isUnique": false+ },+ "audit_lighthouse_results_page_id_idx": {+ "name": "audit_lighthouse_results_page_id_idx",+ "columns": [+ "page_id"+ ],+ "isUnique": false+ }+ },+ "foreignKeys": {+ "audit_lighthouse_results_audit_id_audits_id_fk": {+ "name": "audit_lighthouse_results_audit_id_audits_id_fk",+ "tableFrom": "audit_lighthouse_results",+ "tableTo": "audits",+ "columnsFrom": [+ "audit_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "audit_lighthouse_results_page_id_audit_pages_id_fk": {+ "name": "audit_lighthouse_results_page_id_audit_pages_id_fk",+ "tableFrom": "audit_lighthouse_results",+ "tableTo": "audit_pages",+ "columnsFrom": [+ "page_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "audit_pages": {+ "name": "audit_pages",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "audit_id": {+ "name": "audit_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "url": {+ "name": "url",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "status_code": {+ "name": "status_code",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "redirect_url": {+ "name": "redirect_url",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "title": {+ "name": "title",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "meta_description": {+ "name": "meta_description",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "canonical_url": {+ "name": "canonical_url",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "robots_meta": {+ "name": "robots_meta",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "og_title": {+ "name": "og_title",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "og_description": {+ "name": "og_description",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "og_image": {+ "name": "og_image",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "h1_count": {+ "name": "h1_count",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": 0+ },+ "h2_count": {+ "name": "h2_count",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": 0+ },+ "h3_count": {+ "name": "h3_count",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": 0+ },+ "h4_count": {+ "name": "h4_count",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": 0+ },+ "h5_count": {+ "name": "h5_count",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": 0+ },+ "h6_count": {+ "name": "h6_count",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": 0+ },+ "heading_order_json": {+ "name": "heading_order_json",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "word_count": {+ "name": "word_count",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": 0+ },+ "images_total": {+ "name": "images_total",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": 0+ },+ "images_missing_alt": {+ "name": "images_missing_alt",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": 0+ },+ "images_json": {+ "name": "images_json",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "internal_link_count": {+ "name": "internal_link_count",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": 0+ },+ "external_link_count": {+ "name": "external_link_count",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": 0+ },+ "has_structured_data": {+ "name": "has_structured_data",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": false+ },+ "hreflang_tags_json": {+ "name": "hreflang_tags_json",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "is_indexable": {+ "name": "is_indexable",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": true+ },+ "x_robots_tag": {+ "name": "x_robots_tag",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "header_canonical_url": {+ "name": "header_canonical_url",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "crawl_depth": {+ "name": "crawl_depth",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "in_sitemap": {+ "name": "in_sitemap",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": false+ },+ "content_hash": {+ "name": "content_hash",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "fetch_class": {+ "name": "fetch_class",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "'ok'"+ },+ "response_time_ms": {+ "name": "response_time_ms",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ }+ },+ "indexes": {+ "audit_pages_audit_url_idx": {+ "name": "audit_pages_audit_url_idx",+ "columns": [+ "audit_id",+ "url"+ ],+ "isUnique": false+ }+ },+ "foreignKeys": {+ "audit_pages_audit_id_audits_id_fk": {+ "name": "audit_pages_audit_id_audits_id_fk",+ "tableFrom": "audit_pages",+ "tableTo": "audits",+ "columnsFrom": [+ "audit_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "audits": {+ "name": "audits",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "project_id": {+ "name": "project_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "started_by_user_id": {+ "name": "started_by_user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "start_url": {+ "name": "start_url",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "status": {+ "name": "status",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "'running'"+ },+ "workflow_instance_id": {+ "name": "workflow_instance_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "config": {+ "name": "config",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "'{}'"+ },+ "pages_crawled": {+ "name": "pages_crawled",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": 0+ },+ "pages_total": {+ "name": "pages_total",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": 0+ },+ "lighthouse_total": {+ "name": "lighthouse_total",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": 0+ },+ "lighthouse_completed": {+ "name": "lighthouse_completed",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": 0+ },+ "lighthouse_failed": {+ "name": "lighthouse_failed",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": 0+ },+ "current_phase": {+ "name": "current_phase",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false,+ "default": "'discovery'"+ },+ "error_code": {+ "name": "error_code",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "error_detail": {+ "name": "error_detail",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "failed_phase": {+ "name": "failed_phase",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "started_at": {+ "name": "started_at",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "(current_timestamp)"+ },+ "completed_at": {+ "name": "completed_at",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ }+ },+ "indexes": {+ "audits_project_id_idx": {+ "name": "audits_project_id_idx",+ "columns": [+ "project_id"+ ],+ "isUnique": false+ },+ "audits_started_by_user_id_idx": {+ "name": "audits_started_by_user_id_idx",+ "columns": [+ "started_by_user_id"+ ],+ "isUnique": false+ }+ },+ "foreignKeys": {+ "audits_project_id_projects_id_fk": {+ "name": "audits_project_id_projects_id_fk",+ "tableFrom": "audits",+ "tableTo": "projects",+ "columnsFrom": [+ "project_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "sam_sessions": {+ "name": "sam_sessions",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "project_id": {+ "name": "project_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "user_id": {+ "name": "user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "title": {+ "name": "title",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "'New chat'"+ },+ "created_at": {+ "name": "created_at",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "(current_timestamp)"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "(current_timestamp)"+ },+ "archived_at": {+ "name": "archived_at",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ }+ },+ "indexes": {+ "sam_sessions_project_updated_idx": {+ "name": "sam_sessions_project_updated_idx",+ "columns": [+ "project_id",+ "updated_at"+ ],+ "isUnique": false+ }+ },+ "foreignKeys": {+ "sam_sessions_project_id_projects_id_fk": {+ "name": "sam_sessions_project_id_projects_id_fk",+ "tableFrom": "sam_sessions",+ "tableTo": "projects",+ "columnsFrom": [+ "project_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "sam_sessions_user_id_user_id_fk": {+ "name": "sam_sessions_user_id_user_id_fk",+ "tableFrom": "sam_sessions",+ "tableTo": "user",+ "columnsFrom": [+ "user_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "account": {+ "name": "account",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "account_id": {+ "name": "account_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "provider_id": {+ "name": "provider_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "user_id": {+ "name": "user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "access_token": {+ "name": "access_token",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "refresh_token": {+ "name": "refresh_token",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "id_token": {+ "name": "id_token",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "access_token_expires_at": {+ "name": "access_token_expires_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "refresh_token_expires_at": {+ "name": "refresh_token_expires_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "scope": {+ "name": "scope",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "password": {+ "name": "password",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "created_at": {+ "name": "created_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "(cast(unixepoch('subsecond') * 1000 as integer))"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ }+ },+ "indexes": {+ "account_userId_idx": {+ "name": "account_userId_idx",+ "columns": [+ "user_id"+ ],+ "isUnique": false+ },+ "account_accountId_providerId_idx": {+ "name": "account_accountId_providerId_idx",+ "columns": [+ "account_id",+ "provider_id"+ ],+ "isUnique": false+ },+ "account_google_grant_owner_idx": {+ "name": "account_google_grant_owner_idx",+ "columns": [+ "user_id",+ "provider_id",+ "account_id"+ ],+ "isUnique": true,+ "where": "\"account\".\"provider_id\" in ('google-search-console', 'google-analytics')"+ }+ },+ "foreignKeys": {+ "account_user_id_user_id_fk": {+ "name": "account_user_id_user_id_fk",+ "tableFrom": "account",+ "tableTo": "user",+ "columnsFrom": [+ "user_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "apikey": {+ "name": "apikey",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "config_id": {+ "name": "config_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "'default'"+ },+ "name": {+ "name": "name",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "start": {+ "name": "start",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "prefix": {+ "name": "prefix",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "key": {+ "name": "key",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "reference_id": {+ "name": "reference_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "refill_interval": {+ "name": "refill_interval",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "refill_amount": {+ "name": "refill_amount",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "last_refill_at": {+ "name": "last_refill_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "enabled": {+ "name": "enabled",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false,+ "default": true+ },+ "rate_limit_enabled": {+ "name": "rate_limit_enabled",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false,+ "default": true+ },+ "rate_limit_time_window": {+ "name": "rate_limit_time_window",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false,+ "default": 60000+ },+ "rate_limit_max": {+ "name": "rate_limit_max",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false,+ "default": 120+ },+ "request_count": {+ "name": "request_count",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false,+ "default": 0+ },+ "remaining": {+ "name": "remaining",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "last_request": {+ "name": "last_request",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "expires_at": {+ "name": "expires_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "created_at": {+ "name": "created_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "updated_at": {+ "name": "updated_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "permissions": {+ "name": "permissions",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "metadata": {+ "name": "metadata",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ }+ },+ "indexes": {+ "apikey_configId_idx": {+ "name": "apikey_configId_idx",+ "columns": [+ "config_id"+ ],+ "isUnique": false+ },+ "apikey_referenceId_idx": {+ "name": "apikey_referenceId_idx",+ "columns": [+ "reference_id"+ ],+ "isUnique": false+ },+ "apikey_key_idx": {+ "name": "apikey_key_idx",+ "columns": [+ "key"+ ],+ "isUnique": false+ }+ },+ "foreignKeys": {},+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "invitation": {+ "name": "invitation",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "organization_id": {+ "name": "organization_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "email": {+ "name": "email",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "role": {+ "name": "role",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "status": {+ "name": "status",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "'pending'"+ },+ "expires_at": {+ "name": "expires_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "created_at": {+ "name": "created_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "(cast(unixepoch('subsecond') * 1000 as integer))"+ },+ "inviter_id": {+ "name": "inviter_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ }+ },+ "indexes": {+ "invitation_organizationId_idx": {+ "name": "invitation_organizationId_idx",+ "columns": [+ "organization_id"+ ],+ "isUnique": false+ },+ "invitation_email_idx": {+ "name": "invitation_email_idx",+ "columns": [+ "email"+ ],+ "isUnique": false+ }+ },+ "foreignKeys": {+ "invitation_organization_id_organization_id_fk": {+ "name": "invitation_organization_id_organization_id_fk",+ "tableFrom": "invitation",+ "tableTo": "organization",+ "columnsFrom": [+ "organization_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "invitation_inviter_id_user_id_fk": {+ "name": "invitation_inviter_id_user_id_fk",+ "tableFrom": "invitation",+ "tableTo": "user",+ "columnsFrom": [+ "inviter_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "member": {+ "name": "member",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "organization_id": {+ "name": "organization_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "user_id": {+ "name": "user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "role": {+ "name": "role",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "'member'"+ },+ "created_at": {+ "name": "created_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ }+ },+ "indexes": {+ "member_organizationId_idx": {+ "name": "member_organizationId_idx",+ "columns": [+ "organization_id"+ ],+ "isUnique": false+ },+ "member_userId_idx": {+ "name": "member_userId_idx",+ "columns": [+ "user_id"+ ],+ "isUnique": false+ },+ "member_organizationId_userId_uidx": {+ "name": "member_organizationId_userId_uidx",+ "columns": [+ "organization_id",+ "user_id"+ ],+ "isUnique": true+ }+ },+ "foreignKeys": {+ "member_organization_id_organization_id_fk": {+ "name": "member_organization_id_organization_id_fk",+ "tableFrom": "member",+ "tableTo": "organization",+ "columnsFrom": [+ "organization_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "member_user_id_user_id_fk": {+ "name": "member_user_id_user_id_fk",+ "tableFrom": "member",+ "tableTo": "user",+ "columnsFrom": [+ "user_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "organization": {+ "name": "organization",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "name": {+ "name": "name",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "slug": {+ "name": "slug",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "logo": {+ "name": "logo",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "created_at": {+ "name": "created_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "metadata": {+ "name": "metadata",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ }+ },+ "indexes": {+ "organization_slug_unique": {+ "name": "organization_slug_unique",+ "columns": [+ "slug"+ ],+ "isUnique": true+ },+ "organization_slug_uidx": {+ "name": "organization_slug_uidx",+ "columns": [+ "slug"+ ],+ "isUnique": true+ }+ },+ "foreignKeys": {},+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "session": {+ "name": "session",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "expires_at": {+ "name": "expires_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "token": {+ "name": "token",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "created_at": {+ "name": "created_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "(cast(unixepoch('subsecond') * 1000 as integer))"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "ip_address": {+ "name": "ip_address",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "user_agent": {+ "name": "user_agent",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "user_id": {+ "name": "user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "active_organization_id": {+ "name": "active_organization_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ }+ },+ "indexes": {+ "session_token_unique": {+ "name": "session_token_unique",+ "columns": [+ "token"+ ],+ "isUnique": true+ },+ "session_userId_idx": {+ "name": "session_userId_idx",+ "columns": [+ "user_id"+ ],+ "isUnique": false+ }+ },+ "foreignKeys": {+ "session_user_id_user_id_fk": {+ "name": "session_user_id_user_id_fk",+ "tableFrom": "session",+ "tableTo": "user",+ "columnsFrom": [+ "user_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "user": {+ "name": "user",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "name": {+ "name": "name",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "email": {+ "name": "email",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "email_verified": {+ "name": "email_verified",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": false+ },+ "image": {+ "name": "image",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "created_at": {+ "name": "created_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "(cast(unixepoch('subsecond') * 1000 as integer))"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "(cast(unixepoch('subsecond') * 1000 as integer))"+ },+ "analytics_opted_out": {+ "name": "analytics_opted_out",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "last_active_organization_id": {+ "name": "last_active_organization_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ }+ },+ "indexes": {+ "user_email_unique": {+ "name": "user_email_unique",+ "columns": [+ "email"+ ],+ "isUnique": true+ }+ },+ "foreignKeys": {},+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "verification": {+ "name": "verification",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "identifier": {+ "name": "identifier",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "value": {+ "name": "value",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "expires_at": {+ "name": "expires_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "created_at": {+ "name": "created_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "(cast(unixepoch('subsecond') * 1000 as integer))"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "(cast(unixepoch('subsecond') * 1000 as integer))"+ }+ },+ "indexes": {+ "verification_identifier_idx": {+ "name": "verification_identifier_idx",+ "columns": [+ "identifier"+ ],+ "isUnique": false+ },+ "verification_expiresAt_idx": {+ "name": "verification_expiresAt_idx",+ "columns": [+ "expires_at"+ ],+ "isUnique": false+ }+ },+ "foreignKeys": {},+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "billing_customer_status": {+ "name": "billing_customer_status",+ "columns": {+ "organization_id": {+ "name": "organization_id",+ "type": "text",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "is_paying": {+ "name": "is_paying",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": false+ },+ "paid_plan_id": {+ "name": "paid_plan_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "paid_plan_status": {+ "name": "paid_plan_status",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "customer_json": {+ "name": "customer_json",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "synced_at": {+ "name": "synced_at",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "created_at": {+ "name": "created_at",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "(current_timestamp)"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "(current_timestamp)"+ }+ },+ "indexes": {},+ "foreignKeys": {+ "billing_customer_status_organization_id_organization_id_fk": {+ "name": "billing_customer_status_organization_id_organization_id_fk",+ "tableFrom": "billing_customer_status",+ "tableTo": "organization",+ "columnsFrom": [+ "organization_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "ga4_connections": {+ "name": "ga4_connections",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "project_id": {+ "name": "project_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "organization_id": {+ "name": "organization_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "property_id": {+ "name": "property_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "property_display_name": {+ "name": "property_display_name",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "property_time_zone": {+ "name": "property_time_zone",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "property_currency_code": {+ "name": "property_currency_code",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "connected_by_user_id": {+ "name": "connected_by_user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "ga4_account_id": {+ "name": "ga4_account_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "connected_account_email": {+ "name": "connected_account_email",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "created_at": {+ "name": "created_at",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "(current_timestamp)"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "(current_timestamp)"+ }+ },+ "indexes": {+ "ga4_connections_project_idx": {+ "name": "ga4_connections_project_idx",+ "columns": [+ "project_id"+ ],+ "isUnique": true+ },+ "ga4_connections_organization_idx": {+ "name": "ga4_connections_organization_idx",+ "columns": [+ "organization_id"+ ],+ "isUnique": false+ },+ "ga4_connections_connector_idx": {+ "name": "ga4_connections_connector_idx",+ "columns": [+ "connected_by_user_id",+ "ga4_account_id"+ ],+ "isUnique": false+ }+ },+ "foreignKeys": {+ "ga4_connections_project_id_projects_id_fk": {+ "name": "ga4_connections_project_id_projects_id_fk",+ "tableFrom": "ga4_connections",+ "tableTo": "projects",+ "columnsFrom": [+ "project_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "ga4_connections_organization_id_organization_id_fk": {+ "name": "ga4_connections_organization_id_organization_id_fk",+ "tableFrom": "ga4_connections",+ "tableTo": "organization",+ "columnsFrom": [+ "organization_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "gsc_connections": {+ "name": "gsc_connections",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "project_id": {+ "name": "project_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "organization_id": {+ "name": "organization_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "site_url": {+ "name": "site_url",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "connected_by_user_id": {+ "name": "connected_by_user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "gsc_account_id": {+ "name": "gsc_account_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "connected_account_email": {+ "name": "connected_account_email",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "created_at": {+ "name": "created_at",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "(current_timestamp)"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "(current_timestamp)"+ }+ },+ "indexes": {+ "gsc_connections_project_idx": {+ "name": "gsc_connections_project_idx",+ "columns": [+ "project_id"+ ],+ "isUnique": true+ },+ "gsc_connections_organization_idx": {+ "name": "gsc_connections_organization_idx",+ "columns": [+ "organization_id"+ ],+ "isUnique": false+ }+ },+ "foreignKeys": {+ "gsc_connections_project_id_projects_id_fk": {+ "name": "gsc_connections_project_id_projects_id_fk",+ "tableFrom": "gsc_connections",+ "tableTo": "projects",+ "columnsFrom": [+ "project_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "gsc_connections_organization_id_organization_id_fk": {+ "name": "gsc_connections_organization_id_organization_id_fk",+ "tableFrom": "gsc_connections",+ "tableTo": "organization",+ "columnsFrom": [+ "organization_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "telemetry_state": {+ "name": "telemetry_state",+ "columns": {+ "id": {+ "name": "id",+ "type": "integer",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false,+ "default": 1+ },+ "install_id": {+ "name": "install_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "installed_at": {+ "name": "installed_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "last_heartbeat_at": {+ "name": "last_heartbeat_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "last_version": {+ "name": "last_version",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "mcp_tool_call_count": {+ "name": "mcp_tool_call_count",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": 0+ }+ },+ "indexes": {},+ "foreignKeys": {},+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ }+ },+ "views": {},+ "enums": {},+ "_meta": {+ "schemas": {},+ "tables": {},+ "columns": {}+ },+ "internal": {+ "indexes": {}+ }+}\ No newline at end of filediff --git a/drizzle/meta/_journal.json b/drizzle/meta/_journal.jsonindex a56bcb51..f3ea7e83 100644--- a/drizzle/meta/_journal.json+++ b/drizzle/meta/_journal.json@@ -351,6 +351,13 @@"when": 1790212957846,"tag": "0049_keyword_step","breakpoints": true+ },+ {+ "idx": 50,+ "version": "6",+ "when": 1790316400182,+ "tag": "0050_famous_crystal",+ "breakpoints": true}]}\ No newline at end of filediff --git a/plugins/openseo/.claude-plugin/plugin.json b/plugins/openseo/.claude-plugin/plugin.jsonindex 8a92c657..cb50a8da 100644--- a/plugins/openseo/.claude-plugin/plugin.json+++ b/plugins/openseo/.claude-plugin/plugin.json@@ -1,7 +1,7 @@{"name": "openseo","displayName": "OpenSEO",- "version": "1.0.3",+ "version": "1.0.4","description": "Without good data, your agent gives generic advice. Keyword research, competitor research, backlinks, and site audits. All for $10/month.","author": {"name": "OpenSEO",diff --git a/plugins/openseo/.codex-plugin/plugin.json b/plugins/openseo/.codex-plugin/plugin.jsonindex 34e9ae32..90a46665 100644--- a/plugins/openseo/.codex-plugin/plugin.json+++ b/plugins/openseo/.codex-plugin/plugin.json@@ -1,6 +1,6 @@{"name": "openseo",- "version": "1.0.3",+ "version": "1.0.4","description": "Without good data, your agent gives generic advice. Keyword research, competitor research, backlinks, and site audits. All for $10/month.","author": {"name": "OpenSEO",diff --git a/plugins/openseo/.cursor-plugin/plugin.json b/plugins/openseo/.cursor-plugin/plugin.jsonindex d0cebede..19f234f8 100644--- a/plugins/openseo/.cursor-plugin/plugin.json+++ b/plugins/openseo/.cursor-plugin/plugin.json@@ -1,6 +1,6 @@{"name": "openseo",- "version": "1.0.3",+ "version": "1.0.4","description": "SEO made simple. Research keywords and competitors, audit sites, track rankings, and use Search Console data from your agent.","author": {"name": "Every App, Inc",diff --git a/specs/0003-google-search-console-integration.md b/specs/0003-google-search-console-integration.mdindex 96c44f4f..465510b8 100644--- a/specs/0003-google-search-console-integration.md+++ b/specs/0003-google-search-console-integration.md@@ -12,7 +12,9 @@ Users previously got Search Console data into OpenSEO by manually exporting CSVsAdd a native GSC connection plus two read-only MCP tools.-**Auth (incremental OAuth grant).** Connecting requests a read-only Search Console scope through a dedicated Better Auth `genericOAuth` provider (`google-search-console`), separate from logging in with Google. `allowDifferentEmails` lets a user connect a Google account whose email differs from their OpenSEO login (an agency connecting a client). OAuth tokens are encrypted at rest.+**Auth (incremental OAuth grant).** Connecting requests a read-only Search Console scope through the app's own Google OAuth flow (`/api/gsc/oauth/callback`), separate from logging in with Google. Better Auth still handles login only. The grant is stored in the `account` table under the `google-search-console` provider ID, keyed by OpenSEO user and Google account, and its tokens are encrypted at rest. Any Google account can back the grant, including one whose email differs from the OpenSEO login (an agency connecting a client) and one that another OpenSEO user has also connected. The OAuth state is a single-use nonce stored server-side and deleted by the first callback that presents it, so a captured consent URL cannot be replayed. It binds the flow to the user and the provider, and a PKCE verifier derived from that state binds the code to the flow.++The first version used a Better Auth `genericOAuth` provider. Better Auth treats every linked account as a login identity, so it refused to link one Google account to a second OpenSEO user. That blocked people with two OpenSEO logins and members of one organization who share a client Google account, so the flow moved out of Better Auth.**Scoping.** A connection maps one verified property to one project (`gsc_connections`, unique per project). The connection belongs to the project/workspace; any member can query it, and requests run under the connecting member's grant. Property selection lives in the Integrations UI (account dropdown), not an MCP tool.diff --git a/specs/0007-google-analytics-mcp-integration.md b/specs/0007-google-analytics-mcp-integration.mdindex 7e520996..3df585e0 100644--- a/specs/0007-google-analytics-mcp-integration.md+++ b/specs/0007-google-analytics-mcp-integration.md@@ -57,8 +57,11 @@ subsequently approved tools without rewriting the historical contract.### Authentication and grant ownership-Use a dedicated Better Auth `genericOAuth` provider named `google-analytics`.-It requests these scopes:+Use a dedicated Google OAuth grant with the provider ID `google-analytics`.+The app's own Google OAuth flow issues it, the same flow as Search Console+(see spec 0003). It first shipped as a Better Auth `genericOAuth` provider,+which could not link one Google account to two OpenSEO users. It requests+these scopes:- `openid`, `email`, and `profile` identify the connected Google account.- `https://www.googleapis.com/auth/analytics.readonly` discovers properties@@ -69,13 +72,16 @@ keeps GSC access unchanged, allows an agency to use different Google accountsfor GSC and GA4, and gives GA4 its own reconnect and disconnect lifecycle. NoAnalytics write scope is allowed.-The connecting OpenSEO user owns the Better Auth grant. Better Auth stores its-OAuth access and refresh tokens, encrypted at rest, in the `account` table-under the `google-analytics` provider ID. Feature tables must not copy those+The connecting OpenSEO user owns the grant. The app stores its OAuth access+and refresh tokens, encrypted at rest with the Better Auth secret, in the+`account` table under the `google-analytics` provider ID. The row is keyed by+OpenSEO user and Google account, so two OpenSEO users can each connect the+same Google account. Feature tables must not copy thosetokens. Refresh-token rotation preserves the existing encrypted refresh tokenwhen Google omits a new one.-Hosted OpenSEO reuses its Google OAuth client. A self-hosted operator reuses+Hosted OpenSEO reuses its Google OAuth client and registers+`/api/ga4/oauth/callback` on it. A self-hosted operator reuses`GOOGLE_CLIENT_ID`, `GOOGLE_CLIENT_SECRET`, and `BETTER_AUTH_SECRET`, enablesthe Google Analytics Admin API and Google Analytics Data API, and registers`/api/ga4/oauth/callback`. GA4 adds no application secret.@@ -109,7 +115,7 @@ grant and that the exact property appears in a fresh discovery response beforeupserting the mapping. Clients cannot submit `organizationId`,`connectedByUserId`, account email, time zone, currency, or display name.-Disconnecting always deletes the project's mapping. It deletes the Better Auth+Disconnecting always deletes the project's mapping. It deletes thegrant only when the caller owns that grant and no other GA4 connection refersto the same `(connected_by_user_id, ga4_account_id)` pair. A different projectmember may remove the project mapping but cannot unlink another user's grant.diff --git a/src/client/features/ga4/GoogleAnalyticsConnectionCard.tsx b/src/client/features/ga4/GoogleAnalyticsConnectionCard.tsxindex 4198e0ff..e14b9397 100644--- a/src/client/features/ga4/GoogleAnalyticsConnectionCard.tsx+++ b/src/client/features/ga4/GoogleAnalyticsConnectionCard.tsx@@ -49,13 +49,13 @@ export function GoogleAnalyticsConnectionCard({const connected = Boolean(connection?.connected);const hasGrant = Boolean(connection?.currentUserHasGrant);const canManage = connection?.canManage === true;- const selfHostedNeedsSetup =+ const needsGoogleOAuthSetup =!hosted && connectionQuery.isSuccess && !connection?.googleOAuthConfigured;const showPicker = picking ?? (!connected && hasGrant && canManage);const propertiesQuery = useQuery({queryKey: ["ga4Properties", projectId],queryFn: () => listGa4Properties({ data: { projectId } }),- enabled: Boolean(showPicker && !selfHostedNeedsSetup),+ enabled: Boolean(showPicker && !needsGoogleOAuthSetup),});const accounts = React.useMemo(() => propertiesQuery.data?.accounts ?? [],@@ -129,7 +129,7 @@ export function GoogleAnalyticsConnectionCard({status={connectionQuery.isPending || connectionUnavailable? undefined- : selfHostedNeedsSetup+ : needsGoogleOAuthSetup? "setup_required": connected? "connected"@@ -159,7 +159,7 @@ export function GoogleAnalyticsConnectionCard({Try again</button></div>- ) : selfHostedNeedsSetup ? (+ ) : needsGoogleOAuthSetup ? (<div className="space-y-3"><GoogleOAuthSetupWarningintegrationName="Google Analytics"@@ -239,7 +239,7 @@ export function GoogleAnalyticsConnectionCard({)}</p>) : null}- {connectionQuery.isSuccess && !selfHostedNeedsSetup && !canManage ? (+ {connectionQuery.isSuccess && !needsGoogleOAuthSetup && !canManage ? (<p className="mt-3 text-sm text-base-content/60">Ask an organization owner or admin to change this project'sconnection.diff --git a/src/client/features/gsc/SearchConsoleConnectionCard.tsx b/src/client/features/gsc/SearchConsoleConnectionCard.tsxindex 2a0fa8ce..e93b2667 100644--- a/src/client/features/gsc/SearchConsoleConnectionCard.tsx+++ b/src/client/features/gsc/SearchConsoleConnectionCard.tsx@@ -4,7 +4,6 @@ import { GoogleConnectedState } from "@/client/features/integrations/GoogleConneimport { 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 { GoogleProjectEmptyState } from "@/client/features/integrations/GoogleProjectEmptyState";@@ -27,7 +26,6 @@ export function SearchConsoleConnectionCard({projectId: string;returnTo?: string;}) {- const hosted = isHostedClientAuthMode();const queryClient = useQueryClient();const { picking, setPicking, linkAccount, linking } = useGooglePickerResume("gsc",@@ -44,14 +42,14 @@ export function SearchConsoleConnectionCard({const connected = Boolean(connection?.connected);const hasGrant = Boolean(connection?.currentUserHasGrant);const canManage = connection?.canManage === true;- const selfHostedNeedsSetup =- !hosted && connectionQuery.isSuccess && !connection?.googleOAuthConfigured;+ const needsGoogleOAuthSetup =+ connectionQuery.isSuccess && !connection?.googleOAuthConfigured;const showPicker = picking ?? (!connected && hasGrant && canManage);const sitesQuery = useQuery({queryKey: ["gscSites", projectId],queryFn: () => listGscSites({ data: { projectId } }),- enabled: Boolean(showPicker && !selfHostedNeedsSetup),+ enabled: Boolean(showPicker && !needsGoogleOAuthSetup),});const accounts = React.useMemo(() => sitesQuery.data?.accounts ?? [],@@ -155,7 +153,7 @@ export function SearchConsoleConnectionCard({status={connectionQuery.isPending || (connectionQuery.isError && !connection)? undefined- : selfHostedNeedsSetup+ : needsGoogleOAuthSetup? "setup_required": connected? "connected"@@ -185,7 +183,7 @@ export function SearchConsoleConnectionCard({Try again</button></div>- ) : selfHostedNeedsSetup ? (+ ) : needsGoogleOAuthSetup ? (<SelfHostedSetupWarning />) : connected && !picking ? (<GoogleConnectedState@@ -253,7 +251,7 @@ export function SearchConsoleConnectionCard({)}</p>) : null}- {connectionQuery.isSuccess && !selfHostedNeedsSetup && !canManage ? (+ {connectionQuery.isSuccess && !needsGoogleOAuthSetup && !canManage ? (<p className="mt-3 text-sm text-base-content/60">Ask an organization owner or admin to change this project'sconnection.diff --git a/src/client/features/integrations/GoogleLinkErrorAlert.tsx b/src/client/features/integrations/GoogleLinkErrorAlert.tsxindex 1d267228..7bb56941 100644--- a/src/client/features/integrations/GoogleLinkErrorAlert.tsx+++ b/src/client/features/integrations/GoogleLinkErrorAlert.tsx@@ -5,8 +5,8 @@ import {clearGoogleLinkError,getGoogleLinkError,reportGoogleLinkErrorOnce,- type GoogleLinkProvider,} from "./googleLinkError";+import type { GoogleLinkProvider } from "@/shared/google-link";const PROVIDER_LABELS: Record<GoogleLinkProvider, string> = {gsc: "Search Console",@@ -15,11 +15,11 @@ const PROVIDER_LABELS: Record<GoogleLinkProvider, string> = {/*** Inline error shown on a connect surface after a failed Google link flow.- * startGoogleLink sends OAuth failures back to the page that started the- * connect (see its errorCallbackURL); googleLinkError.ts captures the params- * before the router can redirect them away, and this renders the explanation- * next to the Connect button that retries it. Persists until dismissed or the- * user navigates.+ * The OAuth callback sends failures back to the page that started the connect+ * (see googleOAuth.ts); googleLinkError.ts captures the params before the+ * router can redirect them away, and this renders the explanation next to the+ * Connect button that retries it. Persists until dismissed or the user+ * navigates.*/export function GoogleLinkErrorAlert({provider,diff --git a/src/client/features/integrations/googleAuthErrorCopy.ts b/src/client/features/integrations/googleAuthErrorCopy.tsindex de4554f4..6d134ab4 100644--- a/src/client/features/integrations/googleAuthErrorCopy.ts+++ b/src/client/features/integrations/googleAuthErrorCopy.ts@@ -1,8 +1,8 @@/*** Plain-language copy for Google OAuth failures, shared by the connect-surface* inline alert (GoogleLinkErrorAlert) and the /auth-error fallback page.- * `code` is the `error` query param Better Auth appends on its error- * redirects.+ * `code` is the `error` query param on the redirect: Google's own error code+ * (access_denied), or one set by googleOAuth.ts / Better Auth.** `providerLabel` ("Search Console" / "Google Analytics") is set when the* failure came from a connect flow; without it the copy reads as a Google@@ -27,12 +27,11 @@ export function googleAuthErrorCopy(description:"Google's permission screen was closed or declined. Try again whenever you're ready.",};- case "account_already_linked_to_different_user":+ case "connection_save_failed":return {- title: "Google account already connected",- 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.",+ title: `${what} didn't finish`,+ description:+ "We couldn't save the connection. Please try again — if it keeps failing, contact support.",};default:return {diff --git a/src/client/features/integrations/googleLinkError.test.ts b/src/client/features/integrations/googleLinkError.test.tsindex c43448b5..981770a9 100644--- a/src/client/features/integrations/googleLinkError.test.ts+++ b/src/client/features/integrations/googleLinkError.test.ts@@ -4,6 +4,7 @@ import { googleAuthErrorCopy } from "./googleAuthErrorCopy";const captureClientEvent = vi.hoisted(() => vi.fn());vi.mock("@/client/lib/posthog", () => ({ captureClientEvent }));+// Capture runs once per module instance, so each test needs a fresh module.beforeEach(() => vi.resetModules());afterEach(() => vi.unstubAllGlobals());@@ -23,18 +24,15 @@ async function openCallback(path: string) {}describe("Google link callback errors", () => {- it("recovers an account conflict appended after the dashboard anchor", async () => {+ it("recovers the error and keeps the dashboard anchor", async () => {const { errors, location, state, replaceState } = await openCallback(- "/p/project-a?google_link_error=gsc#connect-gsc&error=account_already_linked_to_different_user&error_description=Already%20linked",+ "/p/project-a?google_link_error=gsc&error=access_denied#connect-gsc",);const error = errors.getGoogleLinkError("gsc");- expect(error).toEqual({ code: "account_already_linked_to_different_user" });+ expect(error).toEqual({ code: "access_denied" });const copy = googleAuthErrorCopy(error!.code, "Search Console");- expect(copy.title).toBe("Google account already connected");- expect(copy.description).toContain(- "Sign in to the OpenSEO user that linked it",- );+ expect(copy.title).toBe("Search Console connection was canceled");expect(location.href).toBe("https://app.example.com/p/project-a#connect-gsc",);@@ -44,7 +42,7 @@ describe("Google link callback errors", () => {errors.reportGoogleLinkErrorOnce();expect(captureClientEvent).toHaveBeenCalledExactlyOnceWith("gsc:connect_error",- { error_code: "account_already_linked_to_different_user" },+ { error_code: "access_denied" },);expect(errors.getGoogleLinkError("ga4")).toBeNull();errors.clearGoogleLinkError();@@ -53,39 +51,14 @@ describe("Google link callback errors", () => {it("keeps ordinary query errors and onboarding step parameters", async () => {const { errors, location } = await openCallback(- "/onboarding?step=3&google_link_error=gsc&error=access_denied&error_description=Denied",+ "/onboarding?step=3&google_link_error=gsc&error=access_denied",);expect(errors.getGoogleLinkError("gsc")).toEqual({ code: "access_denied" });expect(location.href).toBe("https://app.example.com/onboarding?step=3");});- it("preserves unrelated query and fragment parameters and supports GA4", async () => {- const { errors, location } = await openCallback(- "/p/project-a?range=28d&google_link_error=ga4#connect-ga4&tab=overview&error=state_mismatch",- );- expect(errors.getGoogleLinkError("ga4")).toEqual({- code: "state_mismatch",- });- expect(location.href).toBe(- "https://app.example.com/p/project-a?range=28d#connect-ga4&tab=overview",- );- errors.reportGoogleLinkErrorOnce();- expect(captureClientEvent).toHaveBeenCalledWith("ga4:connect_error", {- error_code: "state_mismatch",- });- });-- it("prefers a query error when both locations contain one", async () => {- const { errors, location } = await openCallback(- "/p/project-a?google_link_error=gsc&error=access_denied#connect-gsc&error=state_mismatch",- );- expect(errors.getGoogleLinkError("gsc")).toEqual({ code: "access_denied" });- expect(location.hash).toBe("#connect-gsc");- });-it("does not consume errors from unrelated redirects", async () => {- const path =- "/p/project-a?error=access_denied#connect-gsc&error=state_mismatch";+ const path = "/p/project-a?error=access_denied#connect-gsc";const { errors, location, replaceState } = await openCallback(path);expect(errors.getGoogleLinkError("gsc")).toBeNull();expect(replaceState).not.toHaveBeenCalled();diff --git a/src/client/features/integrations/googleLinkError.ts b/src/client/features/integrations/googleLinkError.tsindex 9aa4b866..ea187260 100644--- a/src/client/features/integrations/googleLinkError.ts+++ b/src/client/features/integrations/googleLinkError.ts@@ -1,13 +1,8 @@import { captureClientEvent } from "@/client/lib/posthog";--/**- * Marker appended to the errorCallbackURL so a failed Google link redirect can- * be told apart from any other `error` query param. Its value is the provider- * key ("gsc" | "ga4").- */-export const GOOGLE_LINK_ERROR_PARAM = "google_link_error";--export type GoogleLinkProvider = "gsc" | "ga4";+import {+ GOOGLE_LINK_ERROR_PARAM,+ type GoogleLinkProvider,+} from "@/shared/google-link";type CapturedLinkError = {provider: GoogleLinkProvider;@@ -28,21 +23,9 @@ function captureLinkErrorFromLocation(): CapturedLinkError | null {const url = new URL(window.location.href);const provider = url.searchParams.get(GOOGLE_LINK_ERROR_PARAM);if (provider !== "gsc" && provider !== "ga4") return null;- // OAuth can append &error= after an existing #connect-gsc anchor.- // Retain the anchor so the dashboard can reopen the connection step.- const [anchor, ...fragmentParts] = url.hash.slice(1).split("&");- const fragmentParams = new URLSearchParams(fragmentParts.join("&"));- const code =- url.searchParams.get("error") ?? fragmentParams.get("error") ?? "unknown";- if (fragmentParams.has("error") || fragmentParams.has("error_description")) {- fragmentParams.delete("error");- fragmentParams.delete("error_description");- const remaining = fragmentParams.toString();- url.hash = `${anchor}${remaining ? `&${remaining}` : ""}`;- }+ const code = url.searchParams.get("error") ?? "unknown";url.searchParams.delete(GOOGLE_LINK_ERROR_PARAM);url.searchParams.delete("error");- url.searchParams.delete("error_description");// history.replaceState rather than a router navigate: the params are// one-shot and foreign to every route's search schema, and the router (not// yet started) should never see them. Passing the current history.statediff --git a/src/client/features/integrations/startGoogleLink.test.ts b/src/client/features/integrations/startGoogleLink.test.tsindex 66a8c715..f1e1b141 100644--- a/src/client/features/integrations/startGoogleLink.test.ts+++ b/src/client/features/integrations/startGoogleLink.test.ts@@ -1,18 +1,8 @@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,-}));+const { startLink } = vi.hoisted(() => ({ startLink: vi.fn() }));+vi.mock("@/serverFunctions/gsc", () => ({ startGscLink: startLink }));+vi.mock("@/serverFunctions/ga4", () => ({ startGa4Link: startLink }));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.@@ -24,7 +14,6 @@ import { startGoogleLink, useGoogleLinkPending } from "./startGoogleLink";beforeEach(() => {vi.useFakeTimers();- hosted.mockReturnValue(true);vi.stubGlobal("window", {location: {origin: "https://app.example.com",@@ -40,8 +29,8 @@ afterEach(() => {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(+ let finish!: (value: { url: string }) => void;+ startLink.mockImplementationOnce(() =>new Promise((resolve) => {finish = resolve;@@ -52,8 +41,8 @@ describe("Google authorization loading", () => {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(startLink).toHaveBeenCalledTimes(1);+ finish({ 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);@@ -64,40 +53,14 @@ describe("Google authorization loading", () => {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);+ it("clears loading after a failed request and allows retry", async () => {+ startLink.mockRejectedValueOnce(new Error("Network unavailable"));+ expect(await startGoogleLink("gsc", "/p/1")).toBe(false);+ expect(useGoogleLinkPending()).toBe(false);+ startLink.mockResolvedValueOnce({+ url: "https://accounts.google.com/authorize",+ });+ expect(await startGoogleLink("gsc", "/p/1")).toBe(true);expect(useGoogleLinkPending()).toBe(true);});});diff --git a/src/client/features/integrations/startGoogleLink.ts b/src/client/features/integrations/startGoogleLink.tsindex c1990cf9..1cc18ab0 100644--- a/src/client/features/integrations/startGoogleLink.ts+++ b/src/client/features/integrations/startGoogleLink.ts@@ -1,37 +1,18 @@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";-import { isHostedClientAuthMode } from "@/lib/auth-mode";-import { startSelfHostedGa4Link } from "@/serverFunctions/ga4";-import { startSelfHostedGscLink } from "@/serverFunctions/gsc";-import { GA4_OAUTH_PROVIDER_ID } from "@/shared/ga4";-import { GSC_OAUTH_PROVIDER_ID } from "@/shared/gsc";+import { startGa4Link } from "@/serverFunctions/ga4";+import { startGscLink } from "@/serverFunctions/gsc";+import type { GoogleLinkProvider } from "@/shared/google-link";-const googleProviders = {- gsc: {- providerId: GSC_OAUTH_PROVIDER_ID,- startSelfHosted: startSelfHostedGscLink,- },- ga4: {- providerId: GA4_OAUTH_PROVIDER_ID,- startSelfHosted: startSelfHostedGa4Link,- },-} as const;--function withGoogleLinkErrorParam(- callbackURL: string,- provider: "gsc" | "ga4",-): string {- const url = new URL(callbackURL, window.location.origin);- url.searchParams.set(GOOGLE_LINK_ERROR_PARAM, provider);- return url.toString();-}+const startLink: Record<GoogleLinkProvider, typeof startGscLink> = {+ gsc: startGscLink,+ ga4: startGa4Link,+};// One link flow at a time: a double-click, or a second Connect click while the-// redirect to Google is pending, would overwrite the single Better Auth state-// cookie and guarantee a state_mismatch for whichever consent screen finishes.+// redirect to Google is pending, would start two consent screens for one+// return page.let linkRedirectPending = false;const listeners = new Set<() => void>();@@ -57,39 +38,21 @@ export function useGoogleLinkPending() {/*** Kick off an incremental Google OAuth grant. On success this redirects the* whole page to Google's consent screen; `callbackURL` is where Google returns- * the user afterward. Failures during the Google round-trip redirect to the- * same page with an error marker that GoogleLinkErrorAlert surfaces. Shared by- * the connection cards, onboarding, property pickers, and re-engagement prompt- * so the link/error/redirect flow stays in one place — callers keep their own- * analytics and dismissal behavior.+ * the user afterward. Failures during the Google round-trip redirect back to+ * the same page with an error marker that GoogleLinkErrorAlert surfaces.+ * Shared by the connection cards, onboarding, property pickers, and+ * re-engagement prompt so the link/error/redirect flow stays in one place —+ * callers keep their own analytics and dismissal behavior.*/export async function startGoogleLink(- provider: "gsc" | "ga4",+ provider: GoogleLinkProvider,callbackURL: string,): Promise<boolean> {if (linkRedirectPending) return false;setLinkPending(true);let redirecting = false;try {- const config = googleProviders[provider];- let url: string | undefined;- if (!isHostedClientAuthMode()) {- const res = await config.startSelfHosted({ data: { callbackURL } });- url = res.url;- } else {- const res = await authClient.oauth2.link({- providerId: config.providerId,- callbackURL,- errorCallbackURL: withGoogleLinkErrorParam(callbackURL, provider),- });- if (res.error) {- toast.error(res.error.message ?? "Could not start Google sign-in");- return false;- }- url = res.data?.url;- }- if (!url) return false;-+ const { url } = await startLink[provider]({ data: { callbackURL } });redirecting = true;window.location.href = url;// The page is about to unload, so the guard normally never needs to@@ -105,7 +68,7 @@ export async function startGoogleLink(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.+ // (a thrown request) re-arms the button immediately.if (!redirecting) setLinkPending(false);}}diff --git a/src/db/better-auth-schema.ts b/src/db/better-auth-schema.tsindex 857c42f6..14775768 100644--- a/src/db/better-auth-schema.ts+++ b/src/db/better-auth-schema.ts@@ -86,6 +86,11 @@ export const account = sqliteTable(table.accountId,table.providerId,),+ uniqueIndex("account_google_grant_owner_idx")+ .on(table.userId, table.providerId, table.accountId)+ .where(+ sql`${table.providerId} in ('google-search-console', 'google-analytics')`,+ ),],);diff --git a/src/db/pg/better-auth-schema.ts b/src/db/pg/better-auth-schema.tsindex 2852d6fa..9c89440e 100644--- a/src/db/pg/better-auth-schema.ts+++ b/src/db/pg/better-auth-schema.ts@@ -1,4 +1,4 @@-import { relations } from "drizzle-orm";+import { relations, sql } from "drizzle-orm";import {boolean,index,@@ -79,6 +79,11 @@ export const account = pgTable(table.accountId,table.providerId,),+ uniqueIndex("account_google_grant_owner_idx")+ .on(table.userId, table.providerId, table.accountId)+ .where(+ sql`${table.providerId} in ('google-search-console', 'google-analytics')`,+ ),],);diff --git a/src/lib/auth-client.ts b/src/lib/auth-client.tsindex 5752cc31..7db599fa 100644--- a/src/lib/auth-client.ts+++ b/src/lib/auth-client.ts@@ -1,7 +1,6 @@import { createAuthClient } from "better-auth/react";import { apiKeyClient } from "@better-auth/api-key/client";import {- genericOAuthClient,inferAdditionalFields,organizationClient,} from "better-auth/client/plugins";@@ -18,7 +17,6 @@ export const authClient = createAuthClient({// synchronous checkRolePermission evaluates against the defaults and// disagrees with the server.organizationClient({ ac: orgAccessControl, roles: orgRoles }),- genericOAuthClient(),inferAdditionalFields({ user: userAdditionalFields }),],});diff --git a/src/lib/auth-config.ts b/src/lib/auth-config.tsindex 16c0f5cf..6565c190 100644--- a/src/lib/auth-config.ts+++ b/src/lib/auth-config.ts@@ -1,9 +1,6 @@-import { env } from "cloudflare:workers";-import { genericOAuth, organization } from "better-auth/plugins";+import { organization } from "better-auth/plugins";import { baseAuthOptions } from "@/lib/auth-options";import { orgAccessControl, orgRoles } from "@/lib/org-permissions";-import { GA4_OAUTH_PROVIDER_ID, GA4_OAUTH_SCOPES } from "@/shared/ga4";-import { GSC_OAUTH_PROVIDER_ID, GSC_OAUTH_SCOPES } from "@/shared/gsc";type OrganizationOptions = NonNullable<Parameters<typeof organization>[0]>;@@ -23,23 +20,22 @@ export function createBaseAuthConfig(options?: {ipAddressHeaders: ["cf-connecting-ip"],},// Better Auth writes the OAuth state verification row with a 10-minute- // expiry but sets the matching signed cookie with maxAge 300, and- // parseGenericState checks the cookie before the row's expiresAt — so the- // intended 10-minute window is unreachable. The GSC and GA4 providers- // below force `select_account consent`, a two-screen Google flow, so a- // user who takes more than 5 minutes returns with a live verification row- // and a dead cookie and fails with "State mismatch: State not persisted- // correctly". The row's expiresAt still enforces the real 10-minute- // window and the state stays single-use, so this is not a weakening.+ // expiry but sets the matching signed cookie with maxAge 300, and checks+ // the cookie before the row's expiresAt — so the intended 10-minute+ // window is unreachable. A user who takes more than 5 minutes on+ // Google's sign-in screens returns with a live verification row and a+ // dead cookie and fails with "State mismatch". The row's expiresAt still+ // enforces the real 10-minute window and the state stays single-use.cookies: { state: { attributes: { maxAge: 600 } } },},account: {- // Encrypt OAuth access/refresh tokens at rest in D1. Also covers the- // google social-login tokens; the key derives from BETTER_AUTH_SECRET.+ // Encrypt OAuth access/refresh tokens at rest. Covers the google+ // social-login tokens and the Search Console / Analytics grants written+ // by googleOAuth.ts; the key derives from BETTER_AUTH_SECRET.encryptOAuthTokens: true,accountLinking: {- // Allow connecting a Google account whose email differs from the- // logged-in user's (agency/freelancer managing a client's property).+ // Preserve linking a Google sign-in account whose email differs from+ // the current user's email. Data grants use a separate OAuth flow.allowDifferentEmails: true,},},@@ -67,32 +63,6 @@ export function createBaseAuthConfig(options?: {invitationLimit: 20,...options?.organization,}),- genericOAuth({- config: [- {- providerId: GSC_OAUTH_PROVIDER_ID,- clientId: env.GOOGLE_CLIENT_ID?.trim() ?? "",- clientSecret: env.GOOGLE_CLIENT_SECRET?.trim() ?? "",- discoveryUrl:- "https://accounts.google.com/.well-known/openid-configuration",- scopes: [...GSC_OAUTH_SCOPES],- accessType: "offline", // request a refresh token- prompt: "select_account consent",- pkce: true,- },- {- providerId: GA4_OAUTH_PROVIDER_ID,- clientId: env.GOOGLE_CLIENT_ID?.trim() ?? "",- clientSecret: env.GOOGLE_CLIENT_SECRET?.trim() ?? "",- discoveryUrl:- "https://accounts.google.com/.well-known/openid-configuration",- scopes: [...GA4_OAUTH_SCOPES],- accessType: "offline",- prompt: "select_account consent",- pkce: true,- },- ],- }),],};}diff --git a/src/lib/auth.ts b/src/lib/auth.tsindex aed5db9d..061e6fad 100644--- a/src/lib/auth.ts+++ b/src/lib/auth.ts@@ -185,13 +185,11 @@ function createAuth() {},},socialProviders: getSocialProviders(),- // Where OAuth redirect-flow failures land when Better Auth can't honor a- // per-flow errorCallbackURL (Google-side errors like a canceled consent- // screen, replayed callback URLs, sign-in failures). Without this the- // default /api/auth/error page 302s to `/?error=...` and the dashboard- // silently discards the code. Self-hosted never serves these flows (its- // Google OAuth endpoints are hand-rolled), so the placeholder baseUrl- // there is harmless.+ // Where Google sign-in failures land (canceled consent screen, replayed+ // callback URLs). Without this the default /api/auth/error page 302s to+ // `/?error=...` and the dashboard silently discards the code. Self-hosted+ // never serves social sign-in, so the placeholder baseUrl there is+ // harmless.onAPIError: { errorURL: `${baseUrl}/auth-error` },trustedOrigins: getTrustedOrigins(baseUrl),database,@@ -331,10 +329,10 @@ function getHostedSecret() {function getSocialProviders() {// Google social login is hosted-only. Self-hosted builds the auth instance- // solely for Search Console token ops, which use the genericOAuth provider- // (createBaseAuthConfig) with its own creds — so it must NOT require the+ // for sessions and for the token-encryption secret that Search Console /+ // Analytics grants use (googleOAuth.ts) — so it must NOT require the// social-login config here, otherwise getAuth() construction would be coupled- // to GSC creds rather than just BETTER_AUTH_SECRET.+ // to Google creds rather than just BETTER_AUTH_SECRET.if (!isHostedAuthMode(env.AUTH_MODE)) {return {};}diff --git a/src/routes/api/ga4/oauth/callback.ts b/src/routes/api/ga4/oauth/callback.tsindex 2416c63b..b2e02413 100644--- a/src/routes/api/ga4/oauth/callback.ts+++ b/src/routes/api/ga4/oauth/callback.ts@@ -1,14 +1,14 @@import { createFileRoute } from "@tanstack/react-router";import {GA4_INTEGRATION,- handleSelfHostedGoogleOAuthCallbackRequest,-} from "@/server/features/google/selfHostedOAuth";+ handleGoogleOAuthCallbackRequest,+} from "@/server/features/google/googleOAuth";export const Route = createFileRoute("/api/ga4/oauth/callback")({server: {handlers: {GET: async ({ request }: { request: Request }) =>- handleSelfHostedGoogleOAuthCallbackRequest(request, GA4_INTEGRATION),+ handleGoogleOAuthCallbackRequest(request, GA4_INTEGRATION),},},});diff --git a/src/routes/api/gsc/oauth/callback.ts b/src/routes/api/gsc/oauth/callback.tsindex 542c0695..6dc88e11 100644--- a/src/routes/api/gsc/oauth/callback.ts+++ b/src/routes/api/gsc/oauth/callback.ts@@ -1,18 +1,14 @@import { createFileRoute } from "@tanstack/react-router";import {GSC_INTEGRATION,- handleSelfHostedGoogleOAuthCallbackRequest,-} from "@/server/features/google/selfHostedOAuth";+ handleGoogleOAuthCallbackRequest,+} from "@/server/features/google/googleOAuth";export const Route = createFileRoute("/api/gsc/oauth/callback")({server: {handlers: {- GET: async ({ request }: { request: Request }) => {- return handleSelfHostedGoogleOAuthCallbackRequest(- request,- GSC_INTEGRATION,- );- },+ GET: async ({ request }: { request: Request }) =>+ handleGoogleOAuthCallbackRequest(request, GSC_INTEGRATION),},},});diff --git a/src/routes/auth-error.tsx b/src/routes/auth-error.tsxindex c64c432a..53481114 100644--- a/src/routes/auth-error.tsx+++ b/src/routes/auth-error.tsx@@ -14,12 +14,11 @@ export const Route = createFileRoute("/auth-error")({});/**- * Landing page for Better Auth OAuth failures that can't be routed back to the- * page that started the flow (wired via `onAPIError.errorURL` in auth.ts):- * Google-side errors like a canceled consent screen, replayed callback URLs,- * and sign-in failures. Link failures that Better Auth can attribute to a- * specific flow return to the connect surface instead (see startGoogleLink's- * errorCallbackURL).+ * Landing page for OAuth failures that can't be routed back to the page that+ * started the flow: Better Auth sign-in failures (wired via+ * `onAPIError.errorURL` in auth.ts) and Search Console / Analytics callbacks+ * whose state can't be verified (googleOAuth.ts). Link failures that can be+ * attributed to a specific flow return to the connect surface instead.*/function AuthErrorPage() {const { error } = Route.useSearch();diff --git a/src/server/features/google/googleAccessToken.test.ts b/src/server/features/google/googleAccessToken.test.tsnew file mode 100644index 00000000..1986779c--- /dev/null+++ b/src/server/features/google/googleAccessToken.test.ts@@ -0,0 +1,121 @@+import { beforeEach, describe, expect, it, vi } from "vitest";+import { getGoogleAccessToken } from "./googleOAuth";++const mocks = vi.hoisted(() => ({+ getGoogleOAuthClientConfig: vi.fn(),+ fetch: vi.fn<typeof fetch>(),+ selectLimit: vi.fn(),+ updateSet: vi.fn(),+ getAuth: vi.fn(),+}));++vi.mock("cloudflare:workers", () => ({ env: {} }));+vi.mock("@/db/schema", () => ({+ account: {+ id: "id",+ userId: "userId",+ providerId: "providerId",+ accountId: "accountId",+ },+}));+vi.mock("@/db", () => ({+ db: {+ select: () => ({+ from: () => ({ where: () => ({ limit: mocks.selectLimit }) }),+ }),+ update: () => ({+ set: mocks.updateSet.mockReturnValue({ where: vi.fn() }),+ }),+ },+}));+vi.mock("@/lib/auth", () => ({ getAuth: mocks.getAuth }));+vi.mock("./oauth-config", () => ({+ getGoogleOAuthClientConfig: mocks.getGoogleOAuthClientConfig,+}));++describe("getGoogleAccessToken", () => {+ const userId = "user-1";+ const grant = {+ id: "account-row",+ accessToken: "stored-access",+ refreshToken: "stored-refresh",+ accessTokenExpiresAt: new Date(Date.now() + 60 * 60 * 1_000),+ };++ beforeEach(() => {+ mocks.getGoogleOAuthClientConfig.mockResolvedValue({+ clientId: "google-client-id",+ clientSecret: "google-client-secret",+ });+ mocks.getAuth.mockReturnValue({+ $context: Promise.resolve({+ options: { account: { encryptOAuthTokens: false } },+ secretConfig: "secret",+ }),+ });+ vi.stubGlobal("fetch", mocks.fetch);+ });++ it("returns the stored token while it is fresh", async () => {+ mocks.selectLimit.mockResolvedValue([grant]);++ await expect(+ getGoogleAccessToken({+ userId,+ providerId: "google-search-console",+ accountId: "google-account-1",+ }),+ ).resolves.toBe("stored-access");+ expect(mocks.fetch).not.toHaveBeenCalled();+ });++ it("refreshes an expiring token against Google and persists it", async () => {+ mocks.selectLimit.mockResolvedValue([+ { ...grant, accessTokenExpiresAt: new Date(Date.now() + 1_000) },+ ]);+ mocks.fetch.mockResolvedValue(+ new Response(+ JSON.stringify({ access_token: "new-access", expires_in: 3600 }),+ { status: 200 },+ ),+ );++ await expect(+ getGoogleAccessToken({ userId, providerId: "google-analytics" }),+ ).resolves.toBe("new-access");+ const body = mocks.fetch.mock.calls[0][1]?.body;+ if (!(body instanceof URLSearchParams)) throw new Error("form body");+ expect(body.get("grant_type")).toBe("refresh_token");+ expect(body.get("refresh_token")).toBe("stored-refresh");+ expect(mocks.updateSet).toHaveBeenCalledWith(+ expect.objectContaining({ accessToken: "new-access" }),+ );+ });++ it("rejects an expired grant that has no refresh token", async () => {+ mocks.selectLimit.mockResolvedValue([+ {+ ...grant,+ refreshToken: null,+ accessTokenExpiresAt: new Date(Date.now() - 1_000),+ },+ ]);++ await expect(+ getGoogleAccessToken({ userId, providerId: "google-search-console" }),+ ).rejects.toThrow(/cannot be refreshed/);+ expect(mocks.fetch).not.toHaveBeenCalled();+ });++ it("rejects when Google refuses the refresh", async () => {+ mocks.selectLimit.mockResolvedValue([+ { ...grant, accessTokenExpiresAt: null },+ ]);+ mocks.fetch.mockResolvedValue(new Response("", { status: 400 }));++ await expect(+ getGoogleAccessToken({ userId, providerId: "google-analytics" }),+ ).rejects.toThrow(/refused to refresh/);+ expect(mocks.updateSet).not.toHaveBeenCalled();+ });+});diff --git a/src/server/features/google/googleIdToken.test.ts b/src/server/features/google/googleIdToken.test.tsnew file mode 100644index 00000000..7e292bce--- /dev/null+++ b/src/server/features/google/googleIdToken.test.ts@@ -0,0 +1,67 @@+import { exportJWK, generateKeyPair, SignJWT, type JWTPayload } from "jose";+import { afterEach, expect, it, vi } from "vitest";+import { getGoogleAccountId } from "./googleIdToken";++afterEach(() => vi.unstubAllGlobals());++it("accepts only a Google-signed ID token for this OAuth client", async () => {+ const { publicKey, privateKey } = await generateKeyPair("RS256");+ const publicJwk = await exportJWK(publicKey);+ Object.assign(publicJwk, { kid: "test-key", alg: "RS256", use: "sig" });+ const fetchKeys = vi.fn(async (input: RequestInfo | URL) => {+ const url =+ input instanceof URL+ ? input.href+ : input instanceof Request+ ? input.url+ : input;+ expect(url).toBe("https://www.googleapis.com/oauth2/v3/certs");+ return new Response(JSON.stringify({ keys: [publicJwk] }), {+ status: 200,+ headers: { "Cache-Control": "public, max-age=60" },+ });+ });+ vi.stubGlobal("fetch", fetchKeys);++ const sign = async (+ claims: JWTPayload = {},+ issuer = "https://accounts.google.com",+ ) =>+ new SignJWT({ sub: "google-account-1", ...claims })+ .setProtectedHeader({ alg: "RS256", kid: "test-key" })+ .setIssuer(issuer)+ .setAudience("google-client-id")+ .setIssuedAt()+ .setExpirationTime("1h")+ .sign(privateKey);++ const valid = await sign();+ await expect(getGoogleAccountId(valid, "google-client-id")).resolves.toBe(+ "google-account-1",+ );+ expect(fetchKeys).toHaveBeenCalledTimes(1);+ await expect(getGoogleAccountId(valid, "other-client")).rejects.toThrow();+ await expect(+ getGoogleAccountId(+ await sign({}, "https://other.example"),+ "google-client-id",+ ),+ ).rejects.toThrow();+ const now = Math.floor(Date.now() / 1_000);+ const expired = await new SignJWT({ sub: "google-account-1" })+ .setProtectedHeader({ alg: "RS256", kid: "test-key" })+ .setIssuer("https://accounts.google.com")+ .setAudience("google-client-id")+ .setIssuedAt(now - 3_600)+ .setExpirationTime(now - 1)+ .sign(privateKey);+ await expect(+ getGoogleAccountId(expired, "google-client-id"),+ ).rejects.toThrow();+ const [header, payload, signature] = valid.split(".");+ if (!header || !payload || !signature) throw new Error("Invalid test token");+ const broken = `${header}.${payload}.${signature.startsWith("a") ? "b" : "a"}${signature.slice(1)}`;+ await expect(+ getGoogleAccountId(broken, "google-client-id"),+ ).rejects.toThrow();+});diff --git a/src/server/features/google/googleIdToken.ts b/src/server/features/google/googleIdToken.tsnew file mode 100644index 00000000..9e601fa7--- /dev/null+++ b/src/server/features/google/googleIdToken.ts@@ -0,0 +1,20 @@+import { createRemoteJWKSet, jwtVerify } from "jose";+import { z } from "zod";++const googleKeys = createRemoteJWKSet(+ new URL("https://www.googleapis.com/oauth2/v3/certs"),+);+const googleIdentitySchema = z.object({+ sub: z.string().min(1),+ exp: z.number().int(),+ iat: z.number().int(),+});++export async function getGoogleAccountId(idToken: string, clientId: string) {+ const { payload } = await jwtVerify(idToken, googleKeys, {+ issuer: ["https://accounts.google.com", "accounts.google.com"],+ audience: clientId,+ algorithms: ["RS256"],+ });+ return googleIdentitySchema.parse(payload).sub;+}diff --git a/src/server/features/google/googleOAuth.test.ts b/src/server/features/google/googleOAuth.test.tsnew file mode 100644index 00000000..a8d6a39d--- /dev/null+++ b/src/server/features/google/googleOAuth.test.ts@@ -0,0 +1,392 @@+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,+ afterEach,+ beforeAll,+ beforeEach,+ describe,+ expect,+ it,+ vi,+} from "vitest";+import type * as OAuthModule from "./googleOAuth";++const mocks = vi.hoisted(() => ({+ getGoogleOAuthClientConfig: vi.fn(),+ hasGoogleOAuthConfig: vi.fn(),+ fetch: vi.fn<typeof fetch>(),+ getAuth: vi.fn(),+ getGoogleAccountId:+ vi.fn<(idToken: string, clientId: string) => Promise<string>>(),+ resolveUserContextFromHeaders: vi.fn(),+}));++vi.mock("cloudflare:workers", () => ({ env: {} }));+vi.mock("@/lib/auth", () => ({ getAuth: mocks.getAuth }));+vi.mock("./googleIdToken", () => ({+ getGoogleAccountId: mocks.getGoogleAccountId,+}));+vi.mock("@/middleware/ensure-user/resolve", () => ({+ resolveUserContextFromHeaders: mocks.resolveUserContextFromHeaders,+}));+vi.mock("@/server/features/google/oauth-config", () => ({+ getGoogleOAuthClientConfig: mocks.getGoogleOAuthClientConfig,+ hasGoogleOAuthConfig: mocks.hasGoogleOAuthConfig,+}));++// The state row and the grant upsert both need real SQL (partial unique index,+// delete ... returning), so the module runs against a libsql file.+let client: Client;+let oauth: typeof OAuthModule;+const directory = mkdtempSync(join(tmpdir(), "google-oauth-"));++function migrationStatements(file: string, include: (sql: string) => boolean) {+ return readFileSync(file, "utf8")+ .split("--> statement-breakpoint")+ .filter(include)+ .join("\n");+}++beforeAll(async () => {+ client = createClient({ url: `file:${join(directory, "test.db")}` });+ vi.doMock("@/db", () => ({ db: drizzle(client) }));+ // `account` references `user`; libsql enforces foreign keys by default.+ await client.executeMultiple(+ "CREATE TABLE user (id text PRIMARY KEY); INSERT INTO user VALUES ('user-1'), ('user-2');",+ );+ await client.executeMultiple(+ migrationStatements(+ "drizzle/0003_light_sage.sql",+ (sql) =>+ sql.includes("CREATE TABLE `account`") ||+ sql.includes("CREATE TABLE `verification`"),+ ),+ );+ await client.executeMultiple(+ migrationStatements("drizzle/0050_famous_crystal.sql", (sql) =>+ sql.includes("CREATE UNIQUE INDEX"),+ ),+ );+ oauth = await import("./googleOAuth");+});++afterAll(() => {+ client.close();+ rmSync(directory, { recursive: true });+});++const userId = "user-1";+const publicOrigin = "http://localhost:3001";+const callbackURL = `${publicOrigin}/p/project/settings?tab=integrations`;+const idToken = "google-id-token";++async function authorizationUrl(+ integration: OAuthModule.GoogleOAuthIntegration,+ url = callbackURL,+) {+ return new URL(+ await oauth.createGoogleAuthorizationUrl({+ integration,+ userId,+ callbackURL: url,+ publicOrigin,+ }),+ );+}++async function authorizationState(+ integration: OAuthModule.GoogleOAuthIntegration,+ url = callbackURL,+) {+ return (await authorizationUrl(integration, url)).searchParams.get("state")!;+}++function callbackRequest(+ integration: OAuthModule.GoogleOAuthIntegration,+ state: string,+ params: Record<string, string>,+) {+ const url = new URL(integration.callbackPath, publicOrigin);+ url.searchParams.set("state", state);+ for (const [key, value] of Object.entries(params)) {+ url.searchParams.set(key, value);+ }+ return new Request(url);+}++/** Drive the route handler as the given signed-in user. */+function callback(+ integration: OAuthModule.GoogleOAuthIntegration,+ state: string,+ params: Record<string, string>,+ asUserId = userId,+) {+ mocks.resolveUserContextFromHeaders.mockResolvedValue({ userId: asUserId });+ return oauth.handleGoogleOAuthCallbackRequest(+ callbackRequest(integration, state, params),+ integration,+ );+}++function tokenResponse(body: Record<string, unknown>) {+ return new Response(JSON.stringify(body), { status: 200 });+}++async function grants() {+ const result = await client.execute(+ "SELECT user_id, provider_id, account_id, access_token, refresh_token FROM account ORDER BY user_id",+ );+ return result.rows.map((row) => ({ ...row }));+}++describe("Google OAuth grants", () => {+ beforeEach(async () => {+ await client.executeMultiple(+ "DELETE FROM account; DELETE FROM verification;",+ );+ mocks.getGoogleOAuthClientConfig.mockResolvedValue({+ clientId: "google-client-id",+ clientSecret: "google-client-secret",+ });+ mocks.hasGoogleOAuthConfig.mockResolvedValue(true);+ mocks.getGoogleAccountId.mockResolvedValue("google-account-1");+ mocks.getAuth.mockReturnValue({+ $context: Promise.resolve({+ options: { account: { encryptOAuthTokens: false } },+ secretConfig: "secret",+ }),+ });+ vi.stubGlobal("fetch", mocks.fetch);+ });++ afterEach(() => {+ vi.useRealTimers();+ });++ it.each([+ ["https://evil.example/p", "/"],+ [`${publicOrigin}//evil.example/p`, "/"],+ [`${publicOrigin}/p/1?x=1#h`, "/p/1?x=1#h"],+ ])("reduces callbackURL %s to same-origin path %s", async (input, path) => {+ const state = await authorizationState(oauth.GA4_INTEGRATION, input);+ const response = await callback(oauth.GA4_INTEGRATION, state, {+ error: "access_denied",+ });+ const back = new URL(response.headers.get("Location")!, publicOrigin);+ expect(back.origin).toBe(publicOrigin);+ expect(`${back.pathname}${back.search}${back.hash}`).toBe(+ path === "/"+ ? "/?google_link_error=ga4&error=access_denied"+ : "/p/1?x=1&google_link_error=ga4&error=access_denied#h",+ );+ });++ it("exchanges the code with PKCE and persists the grant", async () => {+ const authorizeUrl = await authorizationUrl(oauth.GA4_INTEGRATION);+ const state = authorizeUrl.searchParams.get("state")!;+ mocks.fetch.mockResolvedValue(+ tokenResponse({+ access_token: "access-token",+ refresh_token: "refresh-token",+ expires_in: 3600,+ id_token: idToken,+ }),+ );++ const response = await callback(oauth.GA4_INTEGRATION, state, {+ code: "code-1",+ });++ expect(response.status).toBe(303);+ expect(response.headers.get("Location")).toBe(+ "/p/project/settings?tab=integrations",+ );+ const body = mocks.fetch.mock.calls[0][1]?.body;+ if (!(body instanceof URLSearchParams)) throw new Error("form body");+ const digest = await crypto.subtle.digest(+ "SHA-256",+ new TextEncoder().encode(body.get("code_verifier")!),+ );+ expect(Buffer.from(digest).toString("base64url")).toBe(+ authorizeUrl.searchParams.get("code_challenge"),+ );+ expect(mocks.getGoogleAccountId).toHaveBeenCalledWith(+ idToken,+ "google-client-id",+ );+ expect(await grants()).toEqual([+ {+ user_id: "user-1",+ provider_id: "google-analytics",+ account_id: "google-account-1",+ access_token: "access-token",+ refresh_token: "refresh-token",+ },+ ]);+ });++ it("stores one grant per user for a Google account and keeps the refresh token on re-consent", async () => {+ mocks.getGoogleAccountId.mockResolvedValue("shared-google-account");+ mocks.fetch.mockResolvedValue(+ tokenResponse({+ access_token: "first",+ refresh_token: "refresh-1",+ id_token: idToken,+ }),+ );+ await callback(+ oauth.GSC_INTEGRATION,+ await authorizationState(oauth.GSC_INTEGRATION),+ { code: "code-1" },+ );++ // Google omits the refresh token when the user already consented once.+ // A Response body reads once, so each exchange gets a fresh one.+ mocks.fetch.mockImplementation(async () =>+ tokenResponse({ access_token: "second", id_token: idToken }),+ );+ await callback(+ oauth.GSC_INTEGRATION,+ await authorizationState(oauth.GSC_INTEGRATION),+ { code: "code-2" },+ );+ const otherUserUrl = new URL(+ await oauth.createGoogleAuthorizationUrl({+ integration: oauth.GSC_INTEGRATION,+ userId: "user-2",+ callbackURL,+ publicOrigin,+ }),+ );+ await callback(+ oauth.GSC_INTEGRATION,+ otherUserUrl.searchParams.get("state")!,+ { code: "code-3" },+ "user-2",+ );++ expect(await grants()).toEqual([+ {+ user_id: "user-1",+ provider_id: "google-search-console",+ account_id: "shared-google-account",+ access_token: "second",+ refresh_token: "refresh-1",+ },+ {+ user_id: "user-2",+ provider_id: "google-search-console",+ account_id: "shared-google-account",+ access_token: "second",+ refresh_token: null,+ },+ ]);+ });++ it.each(["network failure", "invalid token response", "invalid ID token"])(+ "returns %s to the connect page without storing a grant",+ async (failure) => {+ const state = await authorizationState(oauth.GA4_INTEGRATION);+ if (failure === "network failure") {+ mocks.fetch.mockRejectedValue(new Error("Network unavailable"));+ } else {+ mocks.fetch.mockResolvedValue(+ failure === "invalid token response"+ ? new Response("not-json", { status: 200 })+ : tokenResponse({+ access_token: "access-token",+ id_token: idToken,+ }),+ );+ }+ if (failure === "invalid ID token") {+ mocks.getGoogleAccountId.mockRejectedValue(new Error("Bad signature"));+ }++ const response = await callback(oauth.GA4_INTEGRATION, state, {+ code: "code-1",+ });++ expect(response.headers.get("Location")).toBe(+ "/p/project/settings?tab=integrations&google_link_error=ga4&error=oauth_code_verification_failed",+ );+ expect(await grants()).toEqual([]);+ },+ );++ it("returns a grant save failure to the connect page", async () => {+ const state = await authorizationState(oauth.GA4_INTEGRATION);+ mocks.fetch.mockResolvedValue(+ tokenResponse({ access_token: "access-token", id_token: idToken }),+ );+ const log = vi.spyOn(console, "error").mockImplementation(() => {});++ try {+ await client.execute(+ "CREATE TRIGGER fail_insert BEFORE INSERT ON account BEGIN SELECT RAISE(ABORT, 'database unavailable'); END",+ );+ const response = await callback(oauth.GA4_INTEGRATION, state, {+ code: "code-1",+ });++ expect(response.headers.get("Location")).toBe(+ "/p/project/settings?tab=integrations&google_link_error=ga4&error=connection_save_failed",+ );+ expect(log).toHaveBeenCalledWith(+ "google.oauth.grant_save_failed",+ expect.objectContaining({ provider: "ga4" }),+ );+ } finally {+ await client.execute("DROP TRIGGER IF EXISTS fail_insert");+ log.mockRestore();+ }+ });++ it.each(["unknown", "expired", "other user", "already used"])(+ "sends %s state to /auth-error before token exchange",+ async (kind) => {+ vi.useFakeTimers();+ vi.setSystemTime(new Date("2026-08-07T12:00:00Z"));+ let state = await authorizationState(oauth.GA4_INTEGRATION);+ if (kind === "unknown") state = `${state.slice(0, -1)}x`;+ if (kind === "expired")+ vi.setSystemTime(new Date("2026-08-07T12:11:00Z"));+ if (kind === "already used") {+ await callback(oauth.GA4_INTEGRATION, state, {+ error: "access_denied",+ });+ }++ const response = await callback(+ oauth.GA4_INTEGRATION,+ state,+ { code: "code-1" },+ kind === "other user" ? "user-2" : userId,+ );++ expect(response.status).toBe(303);+ expect(response.headers.get("Location")).toBe(+ "/auth-error?error=state_mismatch",+ );+ expect(mocks.fetch).not.toHaveBeenCalled();+ expect(await grants()).toEqual([]);+ },+ );++ it("sweeps expired states when a new flow starts", async () => {+ vi.useFakeTimers();+ vi.setSystemTime(new Date("2026-08-07T12:00:00Z"));+ await authorizationState(oauth.GA4_INTEGRATION);+ vi.setSystemTime(new Date("2026-08-07T12:11:00Z"));+ await authorizationState(oauth.GSC_INTEGRATION);++ const rows = await client.execute(+ "SELECT identifier LIKE 'google-link:gsc:%' AS is_gsc FROM verification",+ );+ expect(rows.rows.map((row) => row.is_gsc)).toEqual([1]);+ });+});diff --git a/src/server/features/google/googleOAuth.ts b/src/server/features/google/googleOAuth.tsnew file mode 100644index 00000000..691227c0--- /dev/null+++ b/src/server/features/google/googleOAuth.ts@@ -0,0 +1,406 @@+import { symmetricDecrypt, symmetricEncrypt } from "better-auth/crypto";+import { and, eq, sql } from "drizzle-orm";+import { z } from "zod";+import { db } from "@/db";+import { account } from "@/db/schema";+import { getAuth } from "@/lib/auth";+import { resolveUserContextFromHeaders } from "@/middleware/ensure-user/resolve";+import { AppError } from "@/server/lib/errors";+import { responseForAppError } from "@/server/lib/http-errors";+import { getPublicOrigin } from "@/server/mcp/public-origin";+import { GA4_OAUTH_PROVIDER_ID, GA4_OAUTH_SCOPES } from "@/shared/ga4";+import {+ GOOGLE_LINK_ERROR_PARAM,+ type GoogleLinkProvider,+} from "@/shared/google-link";+import { GSC_OAUTH_PROVIDER_ID, GSC_OAUTH_SCOPES } from "@/shared/gsc";+import {+ getGoogleOAuthClientConfig,+ hasGoogleOAuthConfig,+} from "./oauth-config";+import { getGoogleAccountId } from "./googleIdToken";+import {+ consumeState,+ createState,+ getCodeChallenge,+ getCodeVerifier,+} from "./googleOAuthState";++/**+ * Google data grants (Search Console, Analytics) are linked here rather than+ * through Better Auth's generic-oauth plugin. Better Auth treats every linked+ * provider account as a login identity and refuses to link one Google account+ * to a second user, which blocked agencies and multi-member orgs from each+ * connecting the same client Google account. Grants live in the Better Auth+ * `account` table, encrypted with its secret, but are keyed per user so the+ * same Google identity may back several users. This module owns the whole+ * lifecycle: consent redirect, callback, and access-token refresh. The state+ * is a single-use nonce bound to the session user and provider, stored in+ * Better Auth's verification table and deleted by the first callback that+ * presents it. The PKCE verifier is an HMAC of that nonce.+ */++const GOOGLE_AUTH_URL = "https://accounts.google.com/o/oauth2/v2/auth";+const GOOGLE_TOKEN_URL = "https://oauth2.googleapis.com/token";+// Refresh when the stored access token is within this many ms of expiry.+const ACCESS_TOKEN_SKEW_MS = 5_000;++export type GoogleOAuthIntegration = {+ provider: GoogleLinkProvider;+ providerId: string;+ displayName: string;+ callbackPath: `/${string}`;+ scopes: readonly string[];+};++export const GSC_INTEGRATION: GoogleOAuthIntegration = {+ provider: "gsc",+ providerId: GSC_OAUTH_PROVIDER_ID,+ displayName: "Search Console",+ callbackPath: "/api/gsc/oauth/callback",+ scopes: GSC_OAUTH_SCOPES,+};++export const GA4_INTEGRATION: GoogleOAuthIntegration = {+ provider: "ga4",+ providerId: GA4_OAUTH_PROVIDER_ID,+ displayName: "Google Analytics",+ callbackPath: "/api/ga4/oauth/callback",+ scopes: GA4_OAUTH_SCOPES,+};++const googleTokenResponseSchema = z.object({+ access_token: z.string().min(1),+ expires_in: z.number().optional(),+ refresh_token: z.string().optional(),+ scope: z.string().optional(),+ id_token: z.string().optional(),+});++type GoogleTokenResponse = z.infer<typeof googleTokenResponseSchema>;++/** Same-origin path to return to after consent. A pathname can start with+ * `//host`, which browsers treat as protocol-relative, so the reduced path is+ * re-parsed to prove it still resolves to our origin. */+function getSafeCallbackPath(callbackURL: string, publicOrigin: string) {+ try {+ const url = new URL(callbackURL, publicOrigin);+ const path = `${url.pathname}${url.search}${url.hash}`;+ if (url.origin !== publicOrigin) return "/";+ if (new URL(path, publicOrigin).origin !== publicOrigin) return "/";+ return path;+ } catch {+ return "/";+ }+}++function getRedirectUri(+ publicOrigin: string,+ integration: GoogleOAuthIntegration,+) {+ return `${publicOrigin}${integration.callbackPath}`;+}++/** Token encryption matches Better Auth's own `account` rows so grants+ * written before this module (and google social-login rows) stay readable. */+async function tokenCrypto() {+ const ctx = await getAuth().$context;+ const enabled = Boolean(ctx.options.account?.encryptOAuthTokens);+ return {+ encrypt: (value: string) =>+ enabled+ ? symmetricEncrypt({ key: ctx.secretConfig, data: value })+ : value,+ decrypt: (value: string) =>+ enabled+ ? symmetricDecrypt({ key: ctx.secretConfig, data: value })+ : value,+ };+}++async function upsertGrant(input: {+ integration: GoogleOAuthIntegration;+ userId: string;+ googleAccountId: string;+ tokens: GoogleTokenResponse;+}) {+ const { encrypt } = await tokenCrypto();+ const accountValues = {+ accountId: input.googleAccountId,+ providerId: input.integration.providerId,+ userId: input.userId,+ accessToken: await encrypt(input.tokens.access_token),+ refreshToken: input.tokens.refresh_token+ ? await encrypt(input.tokens.refresh_token)+ : null,+ accessTokenExpiresAt: new Date(+ Date.now() + (input.tokens.expires_in ?? 3600) * 1_000,+ ),+ refreshTokenExpiresAt: null,+ scope: input.tokens.scope+ ? input.tokens.scope.trim().split(/\s+/).join(",")+ : input.integration.scopes.join(","),+ password: null,+ };+ await db+ .insert(account)+ .values({+ id: crypto.randomUUID(),+ ...accountValues,+ createdAt: new Date(),+ updatedAt: new Date(),+ })+ .onConflictDoUpdate({+ target: [account.userId, account.providerId, account.accountId],+ targetWhere: sql`${account.providerId} in ('google-search-console', 'google-analytics')`,+ set: {+ ...accountValues,+ // Google may omit the refresh token on a later consent. Keep the+ // stored token, including when two callbacks finish together.+ refreshToken: sql`coalesce(excluded.refresh_token, ${account.refreshToken})`,+ updatedAt: new Date(),+ },+ });+}++/** Google's token endpoint; null when it rejects the grant. */+async function fetchTokens(params: Record<string, string>) {+ const response = await fetch(GOOGLE_TOKEN_URL, {+ method: "POST",+ headers: { "Content-Type": "application/x-www-form-urlencoded" },+ body: new URLSearchParams(params),+ });+ if (!response.ok) return null;+ return googleTokenResponseSchema.parse(await response.json());+}++export async function createGoogleAuthorizationUrl(input: {+ integration: GoogleOAuthIntegration;+ userId: string;+ callbackURL: string;+ publicOrigin: string;+}) {+ const config = await getGoogleOAuthClientConfig();+ if (!config || !(await hasGoogleOAuthConfig(config))) {+ throw new AppError(+ "AUTH_CONFIG_MISSING",+ `${input.integration.displayName} is not configured. Set GOOGLE_CLIENT_ID, GOOGLE_CLIENT_SECRET, and BETTER_AUTH_SECRET.`,+ );+ }+ const state = await createState({+ provider: input.integration.provider,+ userId: input.userId,+ callbackPath: getSafeCallbackPath(input.callbackURL, input.publicOrigin),+ });+ const url = new URL(GOOGLE_AUTH_URL);+ url.searchParams.set("client_id", config.clientId);+ url.searchParams.set(+ "redirect_uri",+ getRedirectUri(input.publicOrigin, input.integration),+ );+ url.searchParams.set("response_type", "code");+ url.searchParams.set("scope", input.integration.scopes.join(" "));+ url.searchParams.set("access_type", "offline");+ url.searchParams.set("prompt", "select_account consent");+ url.searchParams.set("state", state);+ url.searchParams.set(+ "code_challenge",+ await getCodeChallenge(+ await getCodeVerifier({+ state,+ clientSecret: config.clientSecret,+ provider: input.integration.provider,+ }),+ ),+ );+ url.searchParams.set("code_challenge_method", "S256");+ return url.toString();+}++function redirect(location: string) {+ return new Response(null, { status: 303, headers: { Location: location } });+}++/**+ * Google returns here after consent. Failures the user can act on go back to+ * the page that started the connect with `error` + the provider marker, which+ * GoogleLinkErrorAlert renders next to the Connect button. An unverifiable+ * state has no page to return to, so it lands on /auth-error.+ */+async function handleGoogleOAuthCallback(input: {+ integration: GoogleOAuthIntegration;+ request: Request;+ userId: string;+ publicOrigin: string;+}) {+ const config = await getGoogleOAuthClientConfig();+ if (!config) {+ throw new AppError(+ "AUTH_CONFIG_MISSING",+ `${input.integration.displayName} OAuth is not configured.`,+ );+ }+ const url = new URL(input.request.url);+ const rawState = url.searchParams.get("state");+ // Consumed before the user check so a state presented by the wrong session+ // is burned rather than left for a second attempt.+ const state = await consumeState({+ state: rawState,+ provider: input.integration.provider,+ });+ if (!rawState || !state || state.userId !== input.userId) {+ return redirect("/auth-error?error=state_mismatch");+ }+ const fail = (code: string) => {+ const back = new URL(state.callbackPath, input.publicOrigin);+ back.searchParams.set(GOOGLE_LINK_ERROR_PARAM, input.integration.provider);+ back.searchParams.set("error", code);+ return redirect(`${back.pathname}${back.search}${back.hash}`);+ };+ const googleError = url.searchParams.get("error");+ if (googleError) return fail(googleError);+ const code = url.searchParams.get("code");+ if (!code) return fail("missing_code");+ let tokens: GoogleTokenResponse | null;+ try {+ tokens = await fetchTokens({+ code,+ client_id: config.clientId,+ client_secret: config.clientSecret,+ redirect_uri: getRedirectUri(input.publicOrigin, input.integration),+ grant_type: "authorization_code",+ code_verifier: await getCodeVerifier({+ state: rawState,+ clientSecret: config.clientSecret,+ provider: input.integration.provider,+ }),+ });+ } catch {+ return fail("oauth_code_verification_failed");+ }+ if (!tokens) return fail("oauth_code_verification_failed");+ let googleAccountId: string;+ try {+ googleAccountId = await getGoogleAccountId(+ tokens.id_token ?? "",+ config.clientId,+ );+ } catch {+ return fail("oauth_code_verification_failed");+ }+ try {+ await upsertGrant({+ integration: input.integration,+ userId: input.userId,+ googleAccountId,+ tokens,+ });+ } catch (error) {+ console.error("google.oauth.grant_save_failed", {+ provider: input.integration.provider,+ error,+ });+ return fail("connection_save_failed");+ }+ return redirect(state.callbackPath);+}++/**+ * A currently valid access token for one of the user's Google grants,+ * refreshed against Google and re-persisted when it is about to expire.+ * `accountId` (the Google sub) picks between several grants for the same+ * provider; legacy connections without one fall back to the first grant.+ */+export async function getGoogleAccessToken(input: {+ userId: string;+ providerId: string;+ accountId?: string;+}): Promise<string> {+ const [grant] = await db+ .select({+ id: account.id,+ accessToken: account.accessToken,+ refreshToken: account.refreshToken,+ accessTokenExpiresAt: account.accessTokenExpiresAt,+ })+ .from(account)+ .where(+ and(+ eq(account.userId, input.userId),+ eq(account.providerId, input.providerId),+ input.accountId ? eq(account.accountId, input.accountId) : undefined,+ ),+ )+ .limit(1);+ if (!grant) throw new Error(`No ${input.providerId} grant for this user.`);+ const { encrypt, decrypt } = await tokenCrypto();+ const expiresAt = grant.accessTokenExpiresAt?.getTime();+ const fresh =+ expiresAt !== undefined && expiresAt - Date.now() > ACCESS_TOKEN_SKEW_MS;+ if (fresh && grant.accessToken) return decrypt(grant.accessToken);+ if (!grant.refreshToken) {+ // Google only issues a refresh token on the first consent, so a grant+ // without one cannot recover once its access token expires. Failing here+ // lets the GSC/GA4 clients ask for a reconnect instead of sending a dead+ // token to Google.+ throw new Error(+ `The ${input.providerId} grant has expired and cannot be refreshed.`,+ );+ }+ const config = await getGoogleOAuthClientConfig();+ if (!config) {+ throw new AppError(+ "AUTH_CONFIG_MISSING",+ "Google OAuth is not configured.",+ );+ }+ const tokens = await fetchTokens({+ client_id: config.clientId,+ client_secret: config.clientSecret,+ refresh_token: await decrypt(grant.refreshToken),+ grant_type: "refresh_token",+ });+ if (!tokens) {+ throw new Error(`Google refused to refresh the ${input.providerId} grant.`);+ }+ await db+ .update(account)+ .set({+ accessToken: await encrypt(tokens.access_token),+ accessTokenExpiresAt: new Date(+ Date.now() + (tokens.expires_in ?? 3600) * 1_000,+ ),+ // Google rarely rotates refresh tokens; keep a new one when it does.+ ...(tokens.refresh_token+ ? { refreshToken: await encrypt(tokens.refresh_token) }+ : {}),+ updatedAt: new Date(),+ })+ .where(eq(account.id, grant.id));+ return tokens.access_token;+}++export async function handleGoogleOAuthCallbackRequest(+ request: Request,+ integration: GoogleOAuthIntegration,+) {+ try {+ const context = await resolveUserContextFromHeaders(request.headers);+ return await handleGoogleOAuthCallback({+ integration,+ request,+ userId: context.userId,+ publicOrigin: getPublicOrigin(request),+ });+ } catch (error) {+ // The browser is mid-redirect from Google, so an expired session or a+ // missing config should land on the error page, not a bare status body.+ if (error instanceof AppError) {+ return redirect(`/auth-error?error=${error.code.toLowerCase()}`);+ }+ return responseForAppError(+ error,+ `${integration.displayName} OAuth failed`,+ );+ }+}diff --git a/src/server/features/google/googleOAuthMigration.test.ts b/src/server/features/google/googleOAuthMigration.test.tsnew file mode 100644index 00000000..25e9234c--- /dev/null+++ b/src/server/features/google/googleOAuthMigration.test.ts@@ -0,0 +1,110 @@+import { mkdtempSync, readFileSync, rmSync } from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";+import { createClient } from "@libsql/client";+import { sql } from "drizzle-orm";+import { drizzle } from "drizzle-orm/libsql";+import { sqliteTable, text, integer } from "drizzle-orm/sqlite-core";+import { expect, it } from "vitest";++const grants = sqliteTable("account", {+ id: text("id").primaryKey(),+ userId: text("user_id").notNull(),+ providerId: text("provider_id").notNull(),+ accountId: text("account_id").notNull(),+ accessToken: text("access_token"),+ refreshToken: text("refresh_token"),+ updatedAt: integer("updated_at").notNull(),+});++it("keeps one refreshable grant per user and Google identity without changing project bindings", async () => {+ const directory = mkdtempSync(join(tmpdir(), "google-grant-migration-"));+ const client = createClient({ url: `file:${join(directory, "test.db")}` });+ try {+ await client.executeMultiple(`+ CREATE TABLE account (+ id text PRIMARY KEY,+ user_id text NOT NULL,+ provider_id text NOT NULL,+ account_id text NOT NULL,+ access_token text,+ refresh_token text,+ updated_at integer NOT NULL+ );+ CREATE TABLE gsc_connections (+ project_id text PRIMARY KEY,+ connected_by_user_id text NOT NULL,+ gsc_account_id text+ );+ INSERT INTO account VALUES+ ('old-refresh', 'user-1', 'google-search-console', 'google-1', 'old-access', 'refresh', 1),+ ('new-no-refresh', 'user-1', 'google-search-console', 'google-1', 'new-access', NULL, 2),+ ('other-user', 'user-2', 'google-search-console', 'google-1', 'access', 'refresh', 1),+ ('analytics', 'user-1', 'google-analytics', 'google-1', 'access', 'refresh', 1),+ ('sign-in-a', 'user-1', 'google', 'google-1', 'access', NULL, 1),+ ('sign-in-b', 'user-1', 'google', 'google-1', 'access', NULL, 2);+ INSERT INTO gsc_connections VALUES ('project-1', 'user-1', 'google-1');+ `);++ const migration = readFileSync(+ "drizzle/0050_famous_crystal.sql",+ "utf8",+ ).replaceAll("--> statement-breakpoint", "");+ await client.executeMultiple(migration);++ const existingGrants = await client.execute(+ "SELECT id FROM account WHERE provider_id = 'google-search-console' ORDER BY id",+ );+ expect(existingGrants.rows.map((row) => row.id)).toEqual([+ "old-refresh",+ "other-user",+ ]);+ const bindings = await client.execute("SELECT * FROM gsc_connections");+ expect(bindings.rows).toHaveLength(1);+ expect(bindings.rows[0]?.gsc_account_id).toBe("google-1");+ const signIns = await client.execute(+ "SELECT id FROM account WHERE provider_id = 'google'",+ );+ expect(signIns.rows).toHaveLength(2);++ await expect(+ client.execute(+ "INSERT INTO account VALUES ('duplicate', 'user-1', 'google-search-console', 'google-1', 'access', NULL, 3)",+ ),+ ).rejects.toThrow();++ const db = drizzle(client);+ await Promise.all(+ [null, "new-refresh"].map((refreshToken, index) =>+ db+ .insert(grants)+ .values({+ id: `callback-${index}`,+ userId: "user-3",+ providerId: "google-analytics",+ accountId: "google-2",+ accessToken: `access-${index}`,+ refreshToken,+ updatedAt: index,+ })+ .onConflictDoUpdate({+ target: [grants.userId, grants.providerId, grants.accountId],+ targetWhere: sql`${grants.providerId} in ('google-search-console', 'google-analytics')`,+ set: {+ accessToken: `access-${index}`,+ refreshToken: sql`coalesce(excluded.refresh_token, ${grants.refreshToken})`,+ updatedAt: index,+ },+ }),+ ),+ );+ const concurrent = await client.execute(+ "SELECT refresh_token FROM account WHERE user_id = 'user-3'",+ );+ expect(concurrent.rows).toHaveLength(1);+ expect(concurrent.rows[0]?.refresh_token).toBe("new-refresh");+ } finally {+ client.close();+ rmSync(directory, { recursive: true });+ }+});diff --git a/src/server/features/google/googleOAuthState.ts b/src/server/features/google/googleOAuthState.tsnew file mode 100644index 00000000..ae9116de--- /dev/null+++ b/src/server/features/google/googleOAuthState.ts@@ -0,0 +1,124 @@+import { and, eq, gt, like, lt } from "drizzle-orm";+import { z } from "zod";+import { db } from "@/db";+import { verification } from "@/db/schema";+import type { GoogleLinkProvider } from "@/shared/google-link";++/**+ * Single-use OAuth state and PKCE for the Google data-grant flow+ * (googleOAuth.ts). The state is a random nonce whose payload lives in Better+ * Auth's `verification` table and is deleted the moment a callback presents+ * it, so a captured consent URL cannot be replayed. The PKCE verifier is an+ * HMAC of that nonce.+ */++const STATE_TTL_MS = 10 * 60 * 1_000;+const STATE_IDENTIFIER_PREFIX = "google-link:";++const oauthStateSchema = z.object({+ userId: z.string().min(1),+ callbackPath: z.string().min(1),+});++function bytesToBase64Url(bytes: Uint8Array) {+ let binary = "";+ for (const byte of bytes) binary += String.fromCharCode(byte);+ return btoa(binary)+ .replaceAll("+", "-")+ .replaceAll("/", "_")+ .replaceAll("=", "");+}++function stateIdentifier(provider: GoogleLinkProvider, state: string) {+ return `${STATE_IDENTIFIER_PREFIX}${provider}:${state}`;+}++export async function getCodeVerifier(input: {+ state: string;+ clientSecret: string;+ provider: GoogleLinkProvider;+}) {+ const key = await crypto.subtle.importKey(+ "raw",+ new TextEncoder().encode(+ `openseo:${input.provider}:pkce:${input.clientSecret}`,+ ),+ { name: "HMAC", hash: "SHA-256" },+ false,+ ["sign"],+ );+ const signature = await crypto.subtle.sign(+ "HMAC",+ key,+ new TextEncoder().encode(input.state),+ );+ return bytesToBase64Url(new Uint8Array(signature));+}++export async function getCodeChallenge(verifier: string) {+ const digest = await crypto.subtle.digest(+ "SHA-256",+ new TextEncoder().encode(verifier),+ );+ return bytesToBase64Url(new Uint8Array(digest));+}++/** Persist a fresh state and return the nonce to send to Google. */+export async function createState(input: {+ provider: GoogleLinkProvider;+ userId: string;+ callbackPath: string;+}) {+ const state = bytesToBase64Url(crypto.getRandomValues(new Uint8Array(32)));+ const now = new Date();+ // Abandoned consents never come back to delete their row; sweep them here+ // so the table does not grow without bound.+ await db+ .delete(verification)+ .where(+ and(+ like(verification.identifier, `${STATE_IDENTIFIER_PREFIX}%`),+ lt(verification.expiresAt, now),+ ),+ );+ await db.insert(verification).values({+ id: crypto.randomUUID(),+ identifier: stateIdentifier(input.provider, state),+ value: JSON.stringify({+ userId: input.userId,+ callbackPath: input.callbackPath,+ }),+ expiresAt: new Date(now.getTime() + STATE_TTL_MS),+ });+ return state;+}++/**+ * Atomically delete and return the state's payload, or null when it is+ * unknown, already used, or expired. Two callbacks racing on one state can+ * only have one winner.+ */+export async function consumeState(input: {+ state: string | null;+ provider: GoogleLinkProvider;+}) {+ if (!input.state) return null;+ const [row] = await db+ .delete(verification)+ .where(+ and(+ eq(+ verification.identifier,+ stateIdentifier(input.provider, input.state),+ ),+ gt(verification.expiresAt, new Date()),+ ),+ )+ .returning({ value: verification.value });+ if (!row) return null;+ try {+ return oauthStateSchema.parse(JSON.parse(row.value));+ } catch {+ return null;+ }+}diff --git a/src/server/features/google/oauth-config.ts b/src/server/features/google/oauth-config.tsindex 85fede9d..676b2139 100644--- a/src/server/features/google/oauth-config.ts+++ b/src/server/features/google/oauth-config.ts@@ -14,7 +14,9 @@ export async function getGoogleOAuthClientConfig(): Promise<GoogleOAuthClientConreturn clientId && clientSecret ? { clientId, clientSecret } : null;}-export async function hasSelfHostedGoogleOAuthConfig(+/** Search Console and Analytics need a Google OAuth client plus the secret+ * that encrypts stored tokens. Hosted deployments always have both. */+export async function hasGoogleOAuthConfig(config?: GoogleOAuthClientConfig | null,): Promise<boolean> {const oauthConfig =diff --git a/src/server/features/google/selfHostedOAuth.test.ts b/src/server/features/google/selfHostedOAuth.test.tsdeleted file mode 100644index fe0a1bd3..00000000--- a/src/server/features/google/selfHostedOAuth.test.ts+++ /dev/null@@ -1,231 +0,0 @@-import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";-import {- createSelfHostedGoogleAuthorizationUrl,- GA4_INTEGRATION,- GSC_INTEGRATION,- handleSelfHostedGoogleOAuthCallback,- type SelfHostedGoogleOAuthIntegration,-} from "./selfHostedOAuth";--const mocks = vi.hoisted(() => ({- getGoogleOAuthClientConfig: vi.fn(),- hasSelfHostedGoogleOAuthConfig: vi.fn(),- fetch: vi.fn(),- selectLimit: vi.fn(),- insertValues: vi.fn(),- updateSet: vi.fn(),- getAuth: vi.fn(),-}));--vi.mock("cloudflare:workers", () => ({ env: {} }));-vi.mock("@/db/schema", () => ({- account: {- id: "id",- userId: "userId",- providerId: "providerId",- accountId: "accountId",- },-}));-vi.mock("@/db", () => ({- db: {- select: () => ({- from: () => ({ where: () => ({ limit: mocks.selectLimit }) }),- }),- insert: () => ({ values: mocks.insertValues }),- update: () => ({- set: mocks.updateSet.mockReturnValue({ where: vi.fn() }),- }),- },-}));-vi.mock("@/lib/auth", () => ({ getAuth: mocks.getAuth }));-vi.mock("@/server/features/google/oauth-config", () => ({- getGoogleOAuthClientConfig: mocks.getGoogleOAuthClientConfig,- hasSelfHostedGoogleOAuthConfig: mocks.hasSelfHostedGoogleOAuthConfig,-}));--const user = { userId: "user-1", userEmail: "[email protected]" };-const publicOrigin = "http://localhost:3001";-const callbackURL = `${publicOrigin}/p/project/settings`;--async function authorizationState(- integration: SelfHostedGoogleOAuthIntegration,-) {- const url = new URL(- await createSelfHostedGoogleAuthorizationUrl({- integration,- user,- callbackURL,- publicOrigin,- }),- );- return url.searchParams.get("state")!;-}--function callbackRequest(- integration: SelfHostedGoogleOAuthIntegration,- state: string,- params: Record<string, string>,-) {- const url = new URL(integration.callbackPath, publicOrigin);- url.searchParams.set("state", state);- for (const [key, value] of Object.entries(params)) {- url.searchParams.set(key, value);- }- return new Request(url);-}--describe("self-hosted Google OAuth providers", () => {- beforeEach(() => {- mocks.getGoogleOAuthClientConfig.mockResolvedValue({- clientId: "google-client-id",- clientSecret: "google-client-secret",- });- mocks.hasSelfHostedGoogleOAuthConfig.mockResolvedValue(true);- mocks.selectLimit.mockResolvedValue([]);- mocks.insertValues.mockResolvedValue(undefined);- mocks.getAuth.mockReturnValue({- $context: Promise.resolve({- options: { account: { encryptOAuthTokens: false } },- secretConfig: "secret",- }),- });- vi.stubGlobal("fetch", mocks.fetch);- });-- afterEach(() => {- vi.useRealTimers();- });-- it("keeps GSC and GA4 callback paths and scopes isolated", async () => {- const common = { user, callbackURL, publicOrigin };- const gscUrl = new URL(- await createSelfHostedGoogleAuthorizationUrl({- integration: GSC_INTEGRATION,- ...common,- }),- );- const ga4Url = new URL(- await createSelfHostedGoogleAuthorizationUrl({- integration: GA4_INTEGRATION,- ...common,- }),- );-- expect(gscUrl.searchParams.get("redirect_uri")).toBe(- `${publicOrigin}/api/gsc/oauth/callback`,- );- expect(ga4Url.searchParams.get("redirect_uri")).toBe(- `${publicOrigin}/api/ga4/oauth/callback`,- );- expect(gscUrl.searchParams.get("scope")).toContain("webmasters.readonly");- expect(ga4Url.searchParams.get("scope")).toContain("analytics.readonly");- expect(gscUrl.searchParams.get("state")).not.toBe(- ga4Url.searchParams.get("state"),- );- });-- it("round-trips signed state, exchanges the code, and persists the GA4 grant", async () => {- const state = await authorizationState(GA4_INTEGRATION);- const idToken = `header.${btoa(JSON.stringify({ sub: "google-account-1" }))}.signature`;- mocks.fetch.mockResolvedValue(- new Response(- JSON.stringify({- access_token: "access-token",- refresh_token: "refresh-token",- expires_in: 3600,- scope: "openid analytics.readonly",- id_token: idToken,- }),- { status: 200 },- ),- );-- const response = await handleSelfHostedGoogleOAuthCallback({- integration: GA4_INTEGRATION,- request: callbackRequest(GA4_INTEGRATION, state, { code: "code-1" }),- user,- publicOrigin,- });-- expect(response.status).toBe(303);- expect(response.headers.get("Location")).toBe("/p/project/settings");- expect(mocks.fetch).toHaveBeenCalledWith(- "https://oauth2.googleapis.com/token",- expect.objectContaining({ method: "POST" }),- );- expect(mocks.insertValues).toHaveBeenCalledWith(- expect.objectContaining({- accountId: "google-account-1",- providerId: "google-analytics",- userId: "user-1",- accessToken: "access-token",- refreshToken: "refresh-token",- }),- );- });-- it.each(["tampered", "expired"])(- "rejects %s state before token exchange",- async (kind) => {- vi.useFakeTimers();- vi.setSystemTime(new Date("2026-08-07T12:00:00Z"));- let state = await authorizationState(GA4_INTEGRATION);- if (kind === "tampered") state = `${state.slice(0, -1)}x`;- else vi.setSystemTime(new Date("2026-08-07T12:11:00Z"));-- await expect(- handleSelfHostedGoogleOAuthCallback({- integration: GA4_INTEGRATION,- request: callbackRequest(GA4_INTEGRATION, state, { code: "code-1" }),- user,- publicOrigin,- }),- ).rejects.toMatchObject({ code: "VALIDATION_ERROR" });- expect(mocks.fetch).not.toHaveBeenCalled();- expect(mocks.insertValues).not.toHaveBeenCalled();- },- );-- it("handles a provider denial without exchanging or persisting credentials", async () => {- const state = await authorizationState(GA4_INTEGRATION);- const response = await handleSelfHostedGoogleOAuthCallback({- integration: GA4_INTEGRATION,- request: callbackRequest(GA4_INTEGRATION, state, {- error: "access_denied",- }),- user,- publicOrigin,- });-- expect(response.status).toBe(303);- expect(mocks.fetch).not.toHaveBeenCalled();- expect(mocks.insertValues).not.toHaveBeenCalled();- });-- it("round-trips the GSC integration through the shared callback", async () => {- const state = await authorizationState(GSC_INTEGRATION);- const idToken = `header.${btoa(JSON.stringify({ sub: "gsc-account-1" }))}.signature`;- mocks.fetch.mockResolvedValue(- new Response(- JSON.stringify({ access_token: "gsc-token", id_token: idToken }),- { status: 200 },- ),- );-- const response = await handleSelfHostedGoogleOAuthCallback({- integration: GSC_INTEGRATION,- request: callbackRequest(GSC_INTEGRATION, state, { code: "gsc-code" }),- user,- publicOrigin,- });-- expect(response.status).toBe(303);- expect(mocks.insertValues).toHaveBeenCalledWith(- expect.objectContaining({- providerId: "google-search-console",- accountId: "gsc-account-1",- accessToken: "gsc-token",- }),- );- });-});diff --git a/src/server/features/google/selfHostedOAuth.ts b/src/server/features/google/selfHostedOAuth.tsdeleted file mode 100644index 817e2887..00000000--- a/src/server/features/google/selfHostedOAuth.ts+++ /dev/null@@ -1,409 +0,0 @@-import { symmetricEncrypt } from "better-auth/crypto";-import { env } from "cloudflare:workers";-import { and, eq } from "drizzle-orm";-import { decodeJwt } from "jose";-import { z } from "zod";-import { db } from "@/db";-import { account } from "@/db/schema";-import { getAuth } from "@/lib/auth";-import { getAuthMode, isHostedAuthMode } from "@/lib/auth-mode";-import { resolveCloudflareAccessContext } from "@/middleware/ensure-user/cloudflareAccess";-import { resolveLocalNoAuthContext } from "@/middleware/ensure-user/delegated";-import { AppError } from "@/server/lib/errors";-import { responseForAppError } from "@/server/lib/http-errors";-import { getPublicOrigin } from "@/server/mcp/public-origin";-import { GA4_OAUTH_PROVIDER_ID, GA4_OAUTH_SCOPES } from "@/shared/ga4";-import { GSC_OAUTH_PROVIDER_ID, GSC_OAUTH_SCOPES } from "@/shared/gsc";-import {- getGoogleOAuthClientConfig,- hasSelfHostedGoogleOAuthConfig,-} from "./oauth-config";--const GOOGLE_AUTH_URL = "https://accounts.google.com/o/oauth2/v2/auth";-const GOOGLE_TOKEN_URL = "https://oauth2.googleapis.com/token";--export type SelfHostedGoogleOAuthIntegration = {- providerId: string;- stateNamespace: string;- displayName: string;- callbackPath: `/${string}`;- scopes: readonly string[];-};--type SelfHostedGoogleUser = {- userId: string;- userEmail: string;-};--export const GSC_INTEGRATION: SelfHostedGoogleOAuthIntegration = {- providerId: GSC_OAUTH_PROVIDER_ID,- // Preserve the state-signing namespace used by the original GSC flow so a- // deployment does not invalidate an authorization already in progress.- stateNamespace: "gsc",- displayName: "Search Console",- callbackPath: "/api/gsc/oauth/callback",- scopes: GSC_OAUTH_SCOPES,-};--export const GA4_INTEGRATION: SelfHostedGoogleOAuthIntegration = {- providerId: GA4_OAUTH_PROVIDER_ID,- stateNamespace: "ga4",- displayName: "Google Analytics",- callbackPath: "/api/ga4/oauth/callback",- scopes: GA4_OAUTH_SCOPES,-};--const oauthStateSchema = z.object({- userId: z.string().min(1),- callbackPath: z.string().min(1),- exp: z.number().int(),-});--const googleTokenResponseSchema = z.object({- access_token: z.string().min(1),- expires_in: z.number().optional(),- refresh_token: z.string().optional(),- scope: z.string().optional(),- id_token: z.string().optional(),- token_type: z.string().optional(),-});--const googleIdTokenSchema = z.object({ sub: z.string().min(1) });-type GoogleTokenResponse = z.infer<typeof googleTokenResponseSchema>;--function bytesToBase64Url(bytes: Uint8Array) {- let binary = "";- for (const byte of bytes) binary += String.fromCharCode(byte);- return btoa(binary)- .replaceAll("+", "-")- .replaceAll("/", "_")- .replaceAll("=", "");-}--function base64UrlToBytes(value: string) {- const padded = `${value}${"=".repeat((4 - (value.length % 4)) % 4)}`;- const binary = atob(padded.replaceAll("-", "+").replaceAll("_", "/"));- return Uint8Array.from(binary, (char) => char.charCodeAt(0));-}--async function getStateKey(clientSecret: string, stateNamespace: string) {- return crypto.subtle.importKey(- "raw",- new TextEncoder().encode(`openseo:${stateNamespace}:${clientSecret}`),- { name: "HMAC", hash: "SHA-256" },- false,- ["sign", "verify"],- );-}--async function signState(- payload: string,- clientSecret: string,- stateNamespace: string,-) {- const signature = await crypto.subtle.sign(- "HMAC",- await getStateKey(clientSecret, stateNamespace),- new TextEncoder().encode(payload),- );- return bytesToBase64Url(new Uint8Array(signature));-}--function getSafeCallbackPath(callbackURL: string, publicOrigin: string) {- try {- const url = new URL(callbackURL, publicOrigin);- if (url.origin !== publicOrigin) return "/";- return `${url.pathname}${url.search}${url.hash}`;- } catch {- return "/";- }-}--async function createState(input: {- integration: SelfHostedGoogleOAuthIntegration;- clientSecret: string;- userId: string;- callbackURL: string;- publicOrigin: string;-}) {- const payload = bytesToBase64Url(- new TextEncoder().encode(- JSON.stringify({- userId: input.userId,- callbackPath: getSafeCallbackPath(- input.callbackURL,- input.publicOrigin,- ),- exp: Date.now() + 10 * 60 * 1_000,- }),- ),- );- const signature = await signState(- payload,- input.clientSecret,- input.integration.stateNamespace,- );- return `${payload}.${signature}`;-}--async function verifyState(input: {- state: string;- clientSecret: string;- integration: SelfHostedGoogleOAuthIntegration;-}) {- const [payload, signature] = input.state.split(".");- if (!payload || !signature) {- throw new AppError(- "VALIDATION_ERROR",- `Invalid ${input.integration.displayName} state`,- );- }- const ok = await crypto.subtle.verify(- "HMAC",- await getStateKey(input.clientSecret, input.integration.stateNamespace),- base64UrlToBytes(signature),- new TextEncoder().encode(payload),- );- if (!ok) {- throw new AppError(- "VALIDATION_ERROR",- `Invalid ${input.integration.displayName} state`,- );- }- const parsed = oauthStateSchema.parse(- JSON.parse(new TextDecoder().decode(base64UrlToBytes(payload))),- );- if (parsed.exp < Date.now()) {- throw new AppError(- "VALIDATION_ERROR",- `Expired ${input.integration.displayName} state`,- );- }- return parsed;-}--function getRedirectUri(- publicOrigin: string,- integration: SelfHostedGoogleOAuthIntegration,-) {- return `${publicOrigin}${integration.callbackPath}`;-}--function getGoogleAccountId(tokens: GoogleTokenResponse) {- if (!tokens.id_token) {- throw new AppError(- "VALIDATION_ERROR",- "Google did not return an ID token.",- );- }- return googleIdTokenSchema.parse(decodeJwt(tokens.id_token)).sub;-}--async function upsertGrant(input: {- integration: SelfHostedGoogleOAuthIntegration;- user: SelfHostedGoogleUser;- tokens: GoogleTokenResponse;-}) {- const ctx = await getAuth().$context;- const encrypt = (value: string) =>- ctx.options.account?.encryptOAuthTokens- ? symmetricEncrypt({ key: ctx.secretConfig, data: value })- : value;- const googleAccountId = getGoogleAccountId(input.tokens);- const existing = await db- .select({ id: account.id, refreshToken: account.refreshToken })- .from(account)- .where(- and(- eq(account.userId, input.user.userId),- eq(account.providerId, input.integration.providerId),- eq(account.accountId, googleAccountId),- ),- )- .limit(1);- const accountValues = {- accountId: googleAccountId,- providerId: input.integration.providerId,- userId: input.user.userId,- accessToken: await encrypt(input.tokens.access_token),- refreshToken: input.tokens.refresh_token- ? await encrypt(input.tokens.refresh_token)- : (existing[0]?.refreshToken ?? null),- idToken: input.tokens.id_token- ? await encrypt(input.tokens.id_token)- : null,- accessTokenExpiresAt: new Date(- Date.now() + (input.tokens.expires_in ?? 3600) * 1_000,- ),- refreshTokenExpiresAt: null,- scope: input.tokens.scope- ? input.tokens.scope.trim().split(/\s+/).join(",")- : input.integration.scopes.join(","),- password: null,- };- if (existing[0]) {- await db- .update(account)- .set({ ...accountValues, updatedAt: new Date() })- .where(eq(account.id, existing[0].id));- return;- }- await db.insert(account).values({- id: crypto.randomUUID(),- ...accountValues,- createdAt: new Date(),- updatedAt: new Date(),- });-}--async function exchangeCode(input: {- integration: SelfHostedGoogleOAuthIntegration;- code: string;- clientId: string;- clientSecret: string;- redirectUri: string;-}) {- const response = await fetch(GOOGLE_TOKEN_URL, {- method: "POST",- headers: { "Content-Type": "application/x-www-form-urlencoded" },- body: new URLSearchParams({- code: input.code,- client_id: input.clientId,- client_secret: input.clientSecret,- redirect_uri: input.redirectUri,- grant_type: "authorization_code",- }),- });- if (!response.ok) {- throw new AppError(- "VALIDATION_ERROR",- `Google rejected the ${input.integration.displayName} authorization code.`,- );- }- return googleTokenResponseSchema.parse(await response.json());-}--export async function createSelfHostedGoogleAuthorizationUrl(input: {- integration: SelfHostedGoogleOAuthIntegration;- user: SelfHostedGoogleUser;- callbackURL: string;- publicOrigin: string;-}) {- const config = await getGoogleOAuthClientConfig();- if (!config || !(await hasSelfHostedGoogleOAuthConfig(config))) {- throw new AppError(- "AUTH_CONFIG_MISSING",- `${input.integration.displayName} is not configured. Set GOOGLE_CLIENT_ID, GOOGLE_CLIENT_SECRET, and BETTER_AUTH_SECRET.`,- );- }- const redirectUri = getRedirectUri(input.publicOrigin, input.integration);- const state = await createState({- integration: input.integration,- clientSecret: config.clientSecret,- userId: input.user.userId,- callbackURL: input.callbackURL,- publicOrigin: input.publicOrigin,- });- const url = new URL(GOOGLE_AUTH_URL);- url.searchParams.set("client_id", config.clientId);- url.searchParams.set("redirect_uri", redirectUri);- url.searchParams.set("response_type", "code");- url.searchParams.set("scope", input.integration.scopes.join(" "));- url.searchParams.set("access_type", "offline");- url.searchParams.set("prompt", "select_account consent");- url.searchParams.set("state", state);- return url.toString();-}--export async function handleSelfHostedGoogleOAuthCallback(input: {- integration: SelfHostedGoogleOAuthIntegration;- request: Request;- user: SelfHostedGoogleUser;- publicOrigin: string;-}) {- const config = await getGoogleOAuthClientConfig();- if (!config) {- return new Response(- `Missing ${input.integration.displayName} OAuth configuration`,- { status: 500 },- );- }- const url = new URL(input.request.url);- const stateParam = url.searchParams.get("state");- if (!stateParam) {- return new Response(- `Missing ${input.integration.displayName} OAuth state`,- {- status: 400,- },- );- }- const state = await verifyState({- state: stateParam,- clientSecret: config.clientSecret,- integration: input.integration,- });- if (state.userId !== input.user.userId) {- return new Response(- `${input.integration.displayName} OAuth user mismatch`,- {- status: 403,- },- );- }- const redirectToCallback = () =>- new Response(null, {- status: 303,- headers: { Location: state.callbackPath },- });- if (url.searchParams.get("error")) return redirectToCallback();- const code = url.searchParams.get("code");- if (!code) {- return new Response(`Missing ${input.integration.displayName} OAuth code`, {- status: 400,- });- }- const tokens = await exchangeCode({- integration: input.integration,- code,- clientId: config.clientId,- clientSecret: config.clientSecret,- redirectUri: getRedirectUri(input.publicOrigin, input.integration),- });- await upsertGrant({- integration: input.integration,- user: input.user,- tokens,- });- return redirectToCallback();-}--export async function handleSelfHostedGoogleOAuthCallbackRequest(- request: Request,- integration: SelfHostedGoogleOAuthIntegration,-) {- try {- const authMode = getAuthMode(env.AUTH_MODE);- if (isHostedAuthMode(authMode)) {- return new Response("Not found", { status: 404 });- }- const context =- authMode === "local_noauth"- ? await resolveLocalNoAuthContext()- : await resolveCloudflareAccessContext(request.headers);- return await handleSelfHostedGoogleOAuthCallback({- integration,- request,- user: {- userId: context.userId,- userEmail: context.userEmail,- },- publicOrigin: getPublicOrigin(request),- });- } catch (error) {- return responseForAppError(- error,- `${integration.displayName} OAuth failed`,- );- }-}diff --git a/src/server/gdpr/storage-erasure.ts b/src/server/gdpr/storage-erasure.tsindex 927917f9..17d32ff0 100644--- a/src/server/gdpr/storage-erasure.ts+++ b/src/server/gdpr/storage-erasure.ts@@ -1,4 +1,4 @@-import { getAuth } from "@/lib/auth";+import { getGoogleAccessToken } from "@/server/features/google/googleOAuth";import type { SamChatAgent } from "@/server/features/sam/SamChatAgent";import { captureServerError } from "@/server/lib/posthog";import {@@ -139,22 +139,18 @@ async function revokeGoogleAccount(userId: string,account: GdprStorageErasurePayload["googleAccounts"][number],): Promise<GoogleRevocationResult> {- let accessToken: string | undefined;+ let accessToken: string;try {- const result = await getAuth().api.getAccessToken({- body: {- userId,- providerId: account.providerId,- accountId: account.accountId,- },+ accessToken = await getGoogleAccessToken({+ userId,+ providerId: account.providerId,+ accountId: account.accountId,});- accessToken = result?.accessToken;} catch {- // If Better Auth cannot mint a token, the locally stored grant is no longer- // usable. The Postgres transaction still removes its encrypted token row.+ // If no token can be minted, the locally stored grant is no longer usable.+ // The Postgres transaction still removes its encrypted token row.return { ...account, status: "token_unavailable" };}- if (!accessToken) return { ...account, status: "token_unavailable" };const response = await fetch(GOOGLE_REVOKE_URL, {method: "POST",diff --git a/src/server/lib/ga4Client.test.ts b/src/server/lib/ga4Client.test.tsindex 30b18577..ee1f4e2c 100644--- a/src/server/lib/ga4Client.test.ts+++ b/src/server/lib/ga4Client.test.ts@@ -12,8 +12,8 @@ const mocks = vi.hoisted(() => ({fetch: vi.fn<typeof fetch>(),}));-vi.mock("@/lib/auth", () => ({- getAuth: () => ({ api: { getAccessToken: mocks.getAccessToken } }),+vi.mock("@/server/features/google/googleOAuth", () => ({+ getGoogleAccessToken: mocks.getAccessToken,}));function jsonResponse(body: unknown, status = 200) {@@ -27,7 +27,7 @@ function requestUrl(input: RequestInfo | URL): string {describe("ga4Client admin API", () => {beforeEach(() => {- mocks.getAccessToken.mockResolvedValue({ accessToken: "ga4_tok" });+ mocks.getAccessToken.mockResolvedValue("ga4_tok");vi.stubGlobal("fetch", mocks.fetch);});@@ -81,11 +81,9 @@ describe("ga4Client admin API", () => {},]);expect(mocks.getAccessToken).toHaveBeenCalledWith({- body: {- providerId: "google-analytics",- userId: "u1",- accountId: "google-sub-a",- },+ providerId: "google-analytics",+ userId: "u1",+ accountId: "google-sub-a",});const secondUrl = mocks.fetch.mock.calls[1]?.[0];const secondUrlText =@@ -134,7 +132,7 @@ describe("ga4Client admin API", () => {).rejects.toMatchObject({ status: 401 });});- it("throws a token error when Better Auth cannot mint an access token", async () => {+ it("throws a token error when no access token can be minted", async () => {mocks.getAccessToken.mockRejectedValue(new Error("revoked"));await expect(createGa4AdminClient({@@ -257,7 +255,7 @@ const reportRequest = {describe("ga4Client data API", () => {beforeEach(() => {- mocks.getAccessToken.mockResolvedValue({ accessToken: "token" });+ mocks.getAccessToken.mockResolvedValue("token");vi.stubGlobal("fetch", mocks.fetch);});@@ -285,11 +283,9 @@ describe("ga4Client data API", () => {expect(result.rowCount).toBe(1);expect(mocks.getAccessToken).toHaveBeenCalledWith({- body: {- providerId: "google-analytics",- userId: "user_1",- accountId: "account_1",- },+ providerId: "google-analytics",+ userId: "user_1",+ accountId: "account_1",});expect(mocks.fetch).toHaveBeenCalledWith("https://analyticsdata.googleapis.com/v1beta/properties/123:runReport",diff --git a/src/server/lib/ga4Client.ts b/src/server/lib/ga4Client.tsindex 432d31f0..3b34b40c 100644--- a/src/server/lib/ga4Client.ts+++ b/src/server/lib/ga4Client.ts@@ -1,6 +1,6 @@/* eslint-disable max-lines -- one client module per Google integration (gscClient precedent); GA4 spans the Admin and Data APIs */import { z } from "zod";-import { getAuth } from "@/lib/auth";+import { getGoogleAccessToken } from "@/server/features/google/googleOAuth";import {Ga4AdminApiError,Ga4DataApiError,@@ -128,14 +128,11 @@ async function getGa4AccessToken(opts: {userId: string;ga4AccountId: string;}): Promise<string> {- let result: { accessToken?: string } | undefined;try {- result = await getAuth().api.getAccessToken({- body: {- providerId: GA4_OAUTH_PROVIDER_ID,- userId: opts.userId,- accountId: opts.ga4AccountId,- },+ return await getGoogleAccessToken({+ providerId: GA4_OAUTH_PROVIDER_ID,+ userId: opts.userId,+ accountId: opts.ga4AccountId,});} catch (error) {throw new Ga4TokenError(@@ -143,10 +140,6 @@ async function getGa4AccessToken(opts: {error,);}- if (!result?.accessToken) {- throw new Ga4TokenError("Google Analytics returned no access token.");- }- return result.accessToken;}function adminMessageForStatus(status: number): string {diff --git a/src/server/lib/gscClient.test.ts b/src/server/lib/gscClient.test.tsindex 54e0e1b7..20cefca0 100644--- a/src/server/lib/gscClient.test.ts+++ b/src/server/lib/gscClient.test.ts@@ -5,8 +5,8 @@ const mocks = vi.hoisted(() => ({fetch: vi.fn<typeof fetch>(),}));-vi.mock("@/lib/auth", () => ({- getAuth: () => ({ api: { getAccessToken: mocks.getAccessToken } }),+vi.mock("@/server/features/google/googleOAuth", () => ({+ getGoogleAccessToken: mocks.getAccessToken,}));function jsonResponse(body: unknown, status = 200) {@@ -16,7 +16,7 @@ function jsonResponse(body: unknown, status = 200) {describe("gscClient", () => {beforeEach(() => {mocks.getAccessToken.mockReset();- mocks.getAccessToken.mockResolvedValue({ accessToken: "tok_123" });+ mocks.getAccessToken.mockResolvedValue("tok_123");mocks.fetch.mockReset();vi.stubGlobal("fetch", mocks.fetch);});@@ -49,11 +49,9 @@ describe("gscClient", () => {}).listSites();expect(mocks.getAccessToken).toHaveBeenCalledWith({- body: {- providerId: "google-search-console",- userId: "u1",- accountId: "google-sub-a",- },+ providerId: "google-search-console",+ userId: "u1",+ accountId: "google-sub-a",});});@@ -64,7 +62,9 @@ describe("gscClient", () => {await createGscClient({ userId: "u1" }).listSites();expect(mocks.getAccessToken).toHaveBeenCalledWith({- body: { providerId: "google-search-console", userId: "u1" },+ providerId: "google-search-console",+ userId: "u1",+ accountId: undefined,});});diff --git a/src/server/lib/gscClient.ts b/src/server/lib/gscClient.tsindex 9bbe2732..8ae94df5 100644--- a/src/server/lib/gscClient.ts+++ b/src/server/lib/gscClient.ts@@ -1,4 +1,4 @@-import { getAuth } from "@/lib/auth";+import { getGoogleAccessToken } from "@/server/features/google/googleOAuth";import { GSC_OAUTH_PROVIDER_ID } from "@/shared/gsc";import { GscApiError, GscTokenError } from "./gscErrors";@@ -78,25 +78,18 @@ function messageForStatus(status: number, body: string): string {/** Free Google Search Console client. Unlike the DataForSEO client it does NOT* meter credits — GSC is first-party data with no per-call cost. Access tokens- * are minted (and auto-refreshed) by Better Auth from the connector's stored+ * come from (and are auto-refreshed against) the connector's stored* google-search-console grant. */export function createGscClient(opts: {userId: string;gscAccountId?: string;}) {async function getToken(): Promise<string> {- let result: { accessToken?: string } | undefined;try {- // Headerless call: getAccessToken trusts body.userId when no request- // session is present, and auto-refreshes via the genericOAuth provider.- // Works in every auth mode — self-hosted builds the same Better Auth- // instance once BETTER_AUTH_SECRET is set.- result = await getAuth().api.getAccessToken({- body: {- providerId: GSC_OAUTH_PROVIDER_ID,- userId: opts.userId,- ...(opts.gscAccountId ? { accountId: opts.gscAccountId } : {}),- },+ return await getGoogleAccessToken({+ providerId: GSC_OAUTH_PROVIDER_ID,+ userId: opts.userId,+ accountId: opts.gscAccountId,});} catch (error) {throw new GscTokenError(@@ -104,12 +97,6 @@ export function createGscClient(opts: {error,);}- if (!result?.accessToken) {- throw new GscTokenError(- "Search Console returned no access token (grant revoked or expired).",- );- }- return result.accessToken;}async function request<T>(diff --git a/src/server/mcp/tools/search-console-tools.test.ts b/src/server/mcp/tools/search-console-tools.test.tsindex 62eb326a..8880261d 100644--- a/src/server/mcp/tools/search-console-tools.test.ts+++ b/src/server/mcp/tools/search-console-tools.test.ts@@ -5,8 +5,7 @@ import { makeToolContext } from "./tool-test-support";const mocks = vi.hoisted(() => ({getProjectForOrganization: vi.fn(),- isHostedServerAuthMode: vi.fn(),- hasSelfHostedGoogleOAuthConfig: vi.fn(),+ hasGoogleOAuthConfig: vi.fn(),GscService: {getPerformance: vi.fn(),inspectUrls: vi.fn(),@@ -14,11 +13,8 @@ const mocks = vi.hoisted(() => ({}));vi.mock("cloudflare:workers", () => ({ env: {} }));-vi.mock("@/server/lib/runtime-env", () => ({- isHostedServerAuthMode: mocks.isHostedServerAuthMode,-}));vi.mock("@/server/features/google/oauth-config", () => ({- hasSelfHostedGoogleOAuthConfig: mocks.hasSelfHostedGoogleOAuthConfig,+ hasGoogleOAuthConfig: mocks.hasGoogleOAuthConfig,}));vi.mock("@/server/features/projects/services/ProjectService", () => ({ProjectService: {@@ -45,8 +41,7 @@ describe("search console MCP tools", () => {locationCode: 2840,languageCode: "en",});- mocks.isHostedServerAuthMode.mockResolvedValue(true);- mocks.hasSelfHostedGoogleOAuthConfig.mockResolvedValue(false);+ mocks.hasGoogleOAuthConfig.mockResolvedValue(true);});it("returns performance rows on success and passes filters through", async () => {@@ -235,8 +230,7 @@ describe("search console MCP tools", () => {});it("returns a setup message in self-hosted mode without a Google client", async () => {- mocks.isHostedServerAuthMode.mockResolvedValue(false);- mocks.hasSelfHostedGoogleOAuthConfig.mockResolvedValue(false);+ mocks.hasGoogleOAuthConfig.mockResolvedValue(false);const { getSearchConsolePerformanceTool } = searchConsoleTools;const result = await getSearchConsolePerformanceTool.handler(@@ -251,8 +245,7 @@ describe("search console MCP tools", () => {});it("allows performance queries in self-hosted mode with a Google client", async () => {- mocks.isHostedServerAuthMode.mockResolvedValue(false);- mocks.hasSelfHostedGoogleOAuthConfig.mockResolvedValue(true);+ mocks.hasGoogleOAuthConfig.mockResolvedValue(true);mocks.GscService.getPerformance.mockResolvedValue({siteUrl: "https://example.com/",connectedBy: "[email protected]",@@ -338,8 +331,7 @@ describe("search console MCP tools", () => {});it("returns a setup message for inspect_urls in self-hosted mode without a Google client", async () => {- mocks.isHostedServerAuthMode.mockResolvedValue(false);- mocks.hasSelfHostedGoogleOAuthConfig.mockResolvedValue(false);+ mocks.hasGoogleOAuthConfig.mockResolvedValue(false);const { inspectUrlsTool } = searchConsoleTools;const result = await inspectUrlsTool.handler(diff --git a/src/server/mcp/tools/search-console-tools.ts b/src/server/mcp/tools/search-console-tools.tsindex 8f95dc30..7b766296 100644--- a/src/server/mcp/tools/search-console-tools.ts+++ b/src/server/mcp/tools/search-console-tools.ts@@ -7,8 +7,7 @@ import { withMcpProjectAuth } from "@/server/mcp/project-auth";import { formatMcpTable, type McpTableColumn } from "@/server/mcp/table";import { projectIdSchema } from "@/server/mcp/schemas";import { buildDashboardUrl } from "@/server/mcp/urls";-import { hasSelfHostedGoogleOAuthConfig } from "@/server/features/google/oauth-config";-import { isHostedServerAuthMode } from "@/server/lib/runtime-env";+import { hasGoogleOAuthConfig } from "@/server/features/google/oauth-config";import { GscService } from "@/server/features/gsc/services/GscService";import {GSC_DATE_RANGES,@@ -65,17 +64,13 @@ function connectGscUrl(baseUrl: string, projectId: string): string {}/** Self-hosted GSC requires the operator to provide a Google OAuth client and- * BETTER_AUTH_SECRET. Hosted mode always has both; self-hosted tools return this- * setup nudge before attempting a token lookup when either is missing. */+ * BETTER_AUTH_SECRET. Return this setup nudge before attempting a token lookup+ * when either is missing. */async function missingSelfHostedGoogleClientResponse(context: ProjectAuthContext,projectId: string,) {- const [hosted, configured] = await Promise.all([- isHostedServerAuthMode(),- hasSelfHostedGoogleOAuthConfig(),- ]);- if (hosted || configured) return null;+ if (await hasGoogleOAuthConfig()) return null;return mcpResponse({text: `This self-hosted OpenSEO deployment is not configured for Search Console yet. Set GOOGLE_CLIENT_ID, GOOGLE_CLIENT_SECRET, and BETTER_AUTH_SECRET, then reconnect Search Console from the project's settings page. Setup docs: ${GSC_SELF_HOSTED_SETUP_DOCS_URL}`,diff --git a/src/serverFunctions/ga4.ts b/src/serverFunctions/ga4.tsindex a98a0ef7..298d6cda 100644--- a/src/serverFunctions/ga4.ts+++ b/src/serverFunctions/ga4.ts@@ -7,14 +7,13 @@ import { Ga4OrganicOverviewService } from "@/server/features/ga4/services/Ga4Orgimport { Ga4Service } from "@/server/features/ga4/services/Ga4Service";import { AppError } from "@/server/lib/errors";import { Ga4ReportError } from "@/server/lib/ga4Errors";-import { hasSelfHostedGoogleOAuthConfig } from "@/server/features/google/oauth-config";+import { hasGoogleOAuthConfig } from "@/server/features/google/oauth-config";import {- createSelfHostedGoogleAuthorizationUrl,+ createGoogleAuthorizationUrl,GA4_INTEGRATION,-} from "@/server/features/google/selfHostedOAuth";+} from "@/server/features/google/googleOAuth";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";import { getPublicOrigin } from "@/server/mcp/public-origin";import {@@ -27,7 +26,7 @@ const setPropertySchema = projectScopedSchema.extend({accountId: z.string().min(1),propertyId: z.string().regex(/^properties\/\d+$/),});-const startSelfHostedLinkSchema = z.object({+const startLinkSchema = z.object({callbackURL: z.string().min(1),});@@ -35,18 +34,17 @@ export const getGa4Connection = createServerFn({ method: "POST" }).middleware(requireProjectContext).validator(projectScopedSchema).handler(async ({ context }) => {- const [connection, currentUserHasGrant, hosted, ga4Configured] =+ const [connection, currentUserHasGrant, googleOAuthConfigured] =await Promise.all([Ga4Service.getConnection(context.projectId),Ga4Service.userHasGrant(context.userId),- isHostedServerAuthMode(),- hasSelfHostedGoogleOAuthConfig(),+ hasGoogleOAuthConfig(),]);return {connected: Boolean(connection),canManage: hasOrgPermission(context.role, { integration: ["manage"] }),currentUserHasGrant,- googleOAuthConfigured: hosted || ga4Configured,+ googleOAuthConfigured,propertyId: connection?.propertyId ?? null,propertyDisplayName: connection?.propertyDisplayName ?? null,propertyTimeZone: connection?.propertyTimeZone ?? null,@@ -209,16 +207,13 @@ export const disconnectGa4 = createServerFn({ method: "POST" })return { connected: false as const };});-export const startSelfHostedGa4Link = createServerFn({ method: "POST" })+export const startGa4Link = createServerFn({ method: "POST" }).middleware(requireAuthenticatedContext)- .validator(startSelfHostedLinkSchema)+ .validator(startLinkSchema).handler(async ({ data, context }) => ({- url: await createSelfHostedGoogleAuthorizationUrl({+ url: await createGoogleAuthorizationUrl({integration: GA4_INTEGRATION,- user: {- userId: context.userId,- userEmail: context.userEmail,- },+ userId: context.userId,callbackURL: data.callbackURL,publicOrigin: getPublicOrigin(getRequest()),}),diff --git a/src/serverFunctions/gsc.ts b/src/serverFunctions/gsc.tsindex 5aac49d0..8cbc35a4 100644--- a/src/serverFunctions/gsc.ts+++ b/src/serverFunctions/gsc.ts@@ -3,16 +3,15 @@ import { getRequest } from "@tanstack/react-start/server";import { waitUntil } from "cloudflare:workers";import { z } from "zod";import { GscService } from "@/server/features/gsc/services/GscService";-import { hasSelfHostedGoogleOAuthConfig } from "@/server/features/google/oauth-config";+import { hasGoogleOAuthConfig } from "@/server/features/google/oauth-config";import {- createSelfHostedGoogleAuthorizationUrl,+ createGoogleAuthorizationUrl,GSC_INTEGRATION,-} from "@/server/features/google/selfHostedOAuth";+} from "@/server/features/google/googleOAuth";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";-import { isHostedServerAuthMode } from "@/server/lib/runtime-env";import {requireAuthenticatedContext,requireProjectContext,@@ -23,7 +22,7 @@ const setSiteSchema = projectScopedSchema.extend({accountId: z.string().min(1),siteUrl: z.string().min(1),});-const startSelfHostedLinkSchema = z.object({+const startLinkSchema = z.object({callbackURL: z.string().min(1),});@@ -40,18 +39,17 @@ export const getGscConnection = createServerFn({ method: "POST" }).middleware(requireProjectContext).validator(projectScopedSchema).handler(async ({ context }) => {- const [connection, currentUserHasGrant, hosted, gscConfigured] =+ const [connection, currentUserHasGrant, googleOAuthConfigured] =await Promise.all([GscService.getConnection(context.projectId),GscService.userHasGrant(context.userId),- isHostedServerAuthMode(),- hasSelfHostedGoogleOAuthConfig(),+ hasGoogleOAuthConfig(),]);return {connected: Boolean(connection),canManage: hasOrgPermission(context.role, { integration: ["manage"] }),currentUserHasGrant,- googleOAuthConfigured: hosted || gscConfigured,+ googleOAuthConfigured,siteUrl: connection?.siteUrl ?? null,connectedByEmail: connection?.connectedAccountEmail ?? null,connectedAt: connection?.createdAt ?? null,@@ -141,20 +139,14 @@ export const disconnectGsc = createServerFn({ method: "POST" })return { connected: false as const };});-export const startSelfHostedGscLink = createServerFn({ method: "POST" })+export const startGscLink = createServerFn({ method: "POST" }).middleware(requireAuthenticatedContext)- .validator(startSelfHostedLinkSchema)- .handler(async ({ data, context }) => {- const publicOrigin = getPublicOrigin(getRequest());- const url = await createSelfHostedGoogleAuthorizationUrl({+ .validator(startLinkSchema)+ .handler(async ({ data, context }) => ({+ url: await createGoogleAuthorizationUrl({integration: GSC_INTEGRATION,- user: {- userId: context.userId,- userEmail: context.userEmail,- },+ userId: context.userId,callbackURL: data.callbackURL,- publicOrigin,- });-- return { url };- });+ publicOrigin: getPublicOrigin(getRequest()),+ }),+ }));diff --git a/src/shared/google-link.ts b/src/shared/google-link.tsnew file mode 100644index 00000000..e339ef39--- /dev/null+++ b/src/shared/google-link.ts@@ -0,0 +1,9 @@+/**+ * Query param the Google OAuth callback appends (next to `error`) when it+ * bounces a failed connect back to the page that started it, so the client can+ * tell a Search Console or Analytics link failure apart from any other `error`+ * param. Its value is the provider key.+ */+export const GOOGLE_LINK_ERROR_PARAM = "google_link_error";++export type GoogleLinkProvider = "gsc" | "ga4";