Skip to content

Open source alternative to Semrush and Ahrefs

Bind MCP credentials to one organization and add a Connected agents revoke flow (#1019)

Ben Senescu07e0ef449721
diff --git a/.agents/PAPERCUTS.md b/.agents/PAPERCUTS.md
index a73006fc..33fd050e 100644
--- a/.agents/PAPERCUTS.md
+++ b/.agents/PAPERCUTS.md
@@ -31,6 +31,7 @@ data, or sensitive paths.
- `2026-09-05T23:52:53Z` — `codex` — After `pnpm build` ran alongside an active Vite dev server, browser navigation failed and server functions returned undefined. The server logged `Cannot read properties of undefined (reading 'map')` in `runInRunnerObject` / `loadEntries`. Restarting Vite restored the same dashboard without code changes. Stop and restart the dev server around production builds before browser QA; consider documenting or isolating the shared build/runtime state.
- [ ] `2026-09-27T22:06:28Z` — `claude` — Hosted auth mode can't run behind `pnpm dev:agents`: `hostedBaseUrlSchema` in `src/lib/auth.ts` accepts only https or the exact host `localhost`, so a portless `*.localhost` `BETTER_AUTH_URL` returns 500, and setting `TURNSTILE_SITE_KEY` without `TURNSTILE_SECRET_KEY` turns every `/api/auth` call into a bare "Missing Better Auth hosted configuration" 500. Workaround: run `vite dev --port <n> --strictPort` with `BETTER_AUTH_URL=http://localhost:<n>`; fix: accept `*.localhost` over http and name the missing variable in the error.
+- `2026-10-20T01:12:41Z` — `claude` — Process environment variables passed to `vite dev` (for example `AUTH_MODE=hosted PORT=3108`) do not reach the Worker's `env`: @cloudflare/vite-plugin builds Worker vars from `.env`/`.env.local` only, so overrides silently lose to the file. Set `CLOUDFLARE_INCLUDE_PROCESS_ENV=true` (as `tests/playwright.mcp-isolation.config.ts` and `compose.yaml` do) when a script needs a second dev server in a different auth mode.
## Deferred
diff --git a/docs/maintainers/specs/0011-multi-user-organizations.md b/docs/maintainers/specs/0011-multi-user-organizations.md
index 7920db1a..565d5ce2 100644
--- a/docs/maintainers/specs/0011-multi-user-organizations.md
+++ b/docs/maintainers/specs/0011-multi-user-organizations.md
@@ -44,16 +44,14 @@ sessions or tokens.
## Authorization
- Every request re-validates the member row; removing a member revokes access
- on their next request, including MCP OAuth tokens (per-request membership
- 401 in the transport, role stamped per request).
-- **MCP API keys are user-scoped credentials** (`orgScope: "user"`), not
- key→org bindings: project-scoped tools derive the org from the project row
- and authorize via the caller's membership in that org, then bill that org.
- One key works across all the user's organizations. `list_projects` spans
- memberships; `create_project` requires an explicit `organizationId` when the
- user belongs to more than one (the error lists the options and instructs
- the agent to confirm with the user). OAuth tokens stay pinned to the org
- stamped at consent until re-auth.
+ on their next request, including MCP credentials (per-request membership
+ check in the transport, role stamped per request).
+- **MCP credentials are bound to one organization.** An OAuth grant is bound
+ to the org active at consent and an API key to the org active when it was
+ created; project-scoped tools authorize the project against that org and
+ bill it. Losing that membership kills the credential; it is never rebound
+ to another org the user belongs to. See
+ [0017 — MCP credential scope](./0017-mcp-credential-scope.md).
- Chat (SAM) re-checks membership every turn and fails closed in hosted mode
when the member row is gone — WebSockets authorize at connect time only,
so the per-turn check is what revokes a removed member's open socket.
diff --git a/docs/maintainers/specs/0017-mcp-credential-scope.md b/docs/maintainers/specs/0017-mcp-credential-scope.md
new file mode 100644
index 00000000..2bec445d
--- /dev/null
+++ b/docs/maintainers/specs/0017-mcp-credential-scope.md
@@ -0,0 +1,55 @@
+# 0017 — MCP credential scope
+
+Every hosted MCP credential is bound to exactly one organization: the one the
+user was working in when the credential was created. Self-host deployments and
+the in-app agent already worked this way; this record makes the hosted OAuth
+and API-key paths match.
+
+## What a credential is bound to
+
+A credential carries the user and one organization id. On every `/mcp` request
+the server requires a live membership for that user in that organization and
+stamps the member row's role into the request; roles are never stored on a
+token or key. Tools that take a `projectId` authorize the project against the
+bound organization, and billing goes to that organization.
+
+## How credentials bind
+
+- **OAuth grants.** Accepting the consent page binds the grant to the active
+ organization. For people who belong to more than one, the page names it and
+ offers a switcher; switching there is the same as switching in the app, so
+ the app follows. Everyone else has only one and sees no label. The same id
+ is kept in the grant metadata so Settings can show which workspace each
+ connected agent reaches.
+- **API keys.** Creating a key binds it, server-side, to the session's active
+ organization after confirming the user is a member there. The key's
+ organization is stored with the key; the client cannot choose it.
+
+Keys that predate this binding were assigned the organization the runtime
+would have resolved for them at the time (the user's last-active organization
+if still a member, otherwise the one joined most recently). A key with no
+organization is refused.
+
+## Membership removal and revocation
+
+- Removing a user from an organization kills every credential bound to it on
+ the next request: OAuth grants answer 401 with a Bearer challenge so a
+ compliant client re-authorizes, and the new grant binds to whichever
+ organization is active at that consent; API keys answer 403.
+- Settings lists the user's connected agents (one entry per OAuth grant) with
+ a Disconnect action. Disconnecting deletes the grant and every access token
+ issued under it, so the client's next call fails and it must authorize
+ again. API keys are revoked from the same Settings page as before.
+
+## Alternatives considered
+
+- **User-scoped credentials** (the model this replaces): one credential worked
+ across every organization the user belongs to, including ones joined later,
+ with the organization derived per call from the project. Rejected because the
+ consent page reads as access to one workspace, and a later invitation to
+ another organization silently widened what an already-connected agent could
+ reach.
+- **A per-key organization picker.** Rejected: multi-organization membership
+ is rare (invitations are the only way in), and the picker adds UI for a case
+ the active organization already answers. Switching organizations and
+ creating a key there covers it.
diff --git a/drizzle/pg/0040_bind_api_keys_to_organization.sql b/drizzle/pg/0040_bind_api_keys_to_organization.sql
new file mode 100644
index 00000000..cd65709d
--- /dev/null
+++ b/drizzle/pg/0040_bind_api_keys_to_organization.sql
@@ -0,0 +1,23 @@
+-- Bind existing MCP API keys to one organization. Keys created from now on
+-- get {"organizationId": ...} stamped into metadata at creation; older keys
+-- resolved the org per request. Backfill with the same rule that runtime
+-- used: the user's last-active organization if still a member, else the
+-- organization they joined most recently. Keys whose user belongs to no
+-- organization stay unbound and are rejected by /mcp. The plugin writes
+-- metadata through JSON.stringify, so an unset value is the text 'null', not
+-- SQL NULL.
+UPDATE "apikey"
+SET "metadata" = (
+ SELECT json_build_object('organizationId', "member"."organization_id")::text
+ FROM "member"
+ JOIN "user" ON "user"."id" = "member"."user_id"
+ WHERE "member"."user_id" = "apikey"."reference_id"
+ ORDER BY
+ CASE WHEN "member"."organization_id" = "user"."last_active_organization_id" THEN 0 ELSE 1 END,
+ "member"."created_at" DESC
+ LIMIT 1
+)
+WHERE ("metadata" IS NULL OR "metadata" = 'null')
+ AND EXISTS (
+ SELECT 1 FROM "member" WHERE "member"."user_id" = "apikey"."reference_id"
+ );
diff --git a/drizzle/pg/meta/0040_snapshot.json b/drizzle/pg/meta/0040_snapshot.json
new file mode 100644
index 00000000..a4d6bda8
--- /dev/null
+++ b/drizzle/pg/meta/0040_snapshot.json
@@ -0,0 +1,6255 @@
+{
+ "id": "e55a0fe9-3358-4a35-8d3b-4d0a289d78f0",
+ "prevId": "9e6c46c6-b97f-47ec-9a1e-1aaa4de4bdcf",
+ "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,
+ "with": {},
+ "method": "btree",
+ "concurrently": false
+ }
+ },
+ "foreignKeys": {
+ "backlink_snapshots_project_id_projects_id_fk": {
+ "name": "backlink_snapshots_project_id_projects_id_fk",
+ "tableFrom": "backlink_snapshots",
+ "columnsFrom": [
+ "project_id"
+ ],
+ "tableTo": "projects",
+ "columnsTo": [
+ "id"
+ ],
+ "onUpdate": "no action",
+ "onDelete": "cascade"
+ }
+ },
+ "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,
+ "with": {},
+ "method": "btree",
+ "concurrently": false
+ }
+ },
+ "foreignKeys": {
+ "crawler_credentials_project_id_projects_id_fk": {
+ "name": "crawler_credentials_project_id_projects_id_fk",
+ "tableFrom": "crawler_credentials",
+ "columnsFrom": [
+ "project_id"
+ ],
+ "tableTo": "projects",
+ "columnsTo": [
+ "id"
+ ],
+ "onUpdate": "no action",
+ "onDelete": "cascade"
+ }
+ },
+ "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,
+ "with": {},
+ "method": "btree",
+ "concurrently": false
+ }
+ },
+ "foreignKeys": {
+ "dashboard_step_dismissals_user_id_user_id_fk": {
+ "name": "dashboard_step_dismissals_user_id_user_id_fk",
+ "tableFrom": "dashboard_step_dismissals",
+ "columnsFrom": [
+ "user_id"
+ ],
+ "tableTo": "user",
+ "columnsTo": [
+ "id"
+ ],
+ "onUpdate": "no action",
+ "onDelete": "cascade"
+ },
+ "dashboard_step_dismissals_project_id_projects_id_fk": {
+ "name": "dashboard_step_dismissals_project_id_projects_id_fk",
+ "tableFrom": "dashboard_step_dismissals",
+ "columnsFrom": [
+ "project_id"
+ ],
+ "tableTo": "projects",
+ "columnsTo": [
+ "id"
+ ],
+ "onUpdate": "no action",
+ "onDelete": "cascade"
+ }
+ },
+ "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.data_refresh_claims": {
+ "name": "data_refresh_claims",
+ "schema": "",
+ "columns": {
+ "key": {
+ "name": "key",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "organization_id": {
+ "name": "organization_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "token": {
+ "name": "token",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "next_attempt_at": {
+ "name": "next_attempt_at",
+ "type": "bigint",
+ "primaryKey": false,
+ "notNull": true
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {
+ "data_refresh_claims_organization_id_organization_id_fk": {
+ "name": "data_refresh_claims_organization_id_organization_id_fk",
+ "tableFrom": "data_refresh_claims",
+ "columnsFrom": [
+ "organization_id"
+ ],
+ "tableTo": "organization",
+ "columnsTo": [
+ "id"
+ ],
+ "onUpdate": "no action",
+ "onDelete": "cascade"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "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,
+ "with": {},
+ "method": "btree",
+ "concurrently": false
+ },
+ "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,
+ "with": {},
+ "method": "btree",
+ "concurrently": false
+ }
+ },
+ "foreignKeys": {
+ "keyword_metrics_project_id_projects_id_fk": {
+ "name": "keyword_metrics_project_id_projects_id_fk",
+ "tableFrom": "keyword_metrics",
+ "columnsFrom": [
+ "project_id"
+ ],
+ "tableTo": "projects",
+ "columnsTo": [
+ "id"
+ ],
+ "onUpdate": "no action",
+ "onDelete": "cascade"
+ }
+ },
+ "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",
+ "columnsFrom": [
+ "organization_id"
+ ],
+ "tableTo": "organization",
+ "columnsTo": [
+ "id"
+ ],
+ "onUpdate": "no action",
+ "onDelete": "cascade"
+ }
+ },
+ "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",
+ "columnsFrom": [
+ "project_id"
+ ],
+ "tableTo": "projects",
+ "columnsTo": [
+ "id"
+ ],
+ "onUpdate": "no action",
+ "onDelete": "cascade"
+ }
+ },
+ "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
+ },
+ "ai_research_keywords": {
+ "name": "ai_research_keywords",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "indexnow_key": {
+ "name": "indexnow_key",
+ "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,
+ "with": {},
+ "method": "btree",
+ "where": "\"projects\".\"name\" = 'Default' AND \"projects\".\"domain\" IS NULL AND \"projects\".\"archived_at\" IS NULL",
+ "concurrently": false
+ },
+ "projects_organization_id_idx": {
+ "name": "projects_organization_id_idx",
+ "columns": [
+ {
+ "expression": "organization_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "with": {},
+ "method": "btree",
+ "concurrently": false
+ }
+ },
+ "foreignKeys": {
+ "projects_organization_id_organization_id_fk": {
+ "name": "projects_organization_id_organization_id_fk",
+ "tableFrom": "projects",
+ "columnsFrom": [
+ "organization_id"
+ ],
+ "tableTo": "organization",
+ "columnsTo": [
+ "id"
+ ],
+ "onUpdate": "no action",
+ "onDelete": "cascade"
+ }
+ },
+ "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,
+ "with": {},
+ "method": "btree",
+ "concurrently": false
+ },
+ "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,
+ "with": {},
+ "method": "btree",
+ "concurrently": false
+ },
+ "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,
+ "with": {},
+ "method": "btree",
+ "where": "\"rank_check_runs\".\"status\" IN ('pending', 'running')",
+ "concurrently": false
+ }
+ },
+ "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",
+ "columnsFrom": [
+ "config_id"
+ ],
+ "tableTo": "rank_tracking_configs",
+ "columnsTo": [
+ "id"
+ ],
+ "onUpdate": "no action",
+ "onDelete": "cascade"
+ },
+ "rank_check_runs_project_id_projects_id_fk": {
+ "name": "rank_check_runs_project_id_projects_id_fk",
+ "tableFrom": "rank_check_runs",
+ "columnsFrom": [
+ "project_id"
+ ],
+ "tableTo": "projects",
+ "columnsTo": [
+ "id"
+ ],
+ "onUpdate": "no action",
+ "onDelete": "cascade"
+ }
+ },
+ "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,
+ "with": {},
+ "method": "btree",
+ "concurrently": false
+ },
+ "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,
+ "with": {},
+ "method": "btree",
+ "concurrently": false
+ }
+ },
+ "foreignKeys": {
+ "rank_snapshots_run_id_rank_check_runs_id_fk": {
+ "name": "rank_snapshots_run_id_rank_check_runs_id_fk",
+ "tableFrom": "rank_snapshots",
+ "columnsFrom": [
+ "run_id"
+ ],
+ "tableTo": "rank_check_runs",
+ "columnsTo": [
+ "id"
+ ],
+ "onUpdate": "no action",
+ "onDelete": "cascade"
+ }
+ },
+ "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,
+ "with": {},
+ "method": "btree",
+ "concurrently": false
+ },
+ "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"
+ },
+ {
+ "expression": "language_code",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": true,
+ "with": {},
+ "method": "btree",
+ "where": "\"rank_tracking_configs\".\"location_name\" IS NULL",
+ "concurrently": false
+ },
+ "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": "language_code",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "location_name",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": true,
+ "with": {},
+ "method": "btree",
+ "where": "\"rank_tracking_configs\".\"location_name\" IS NOT NULL",
+ "concurrently": false
+ }
+ },
+ "foreignKeys": {
+ "rank_tracking_configs_project_id_projects_id_fk": {
+ "name": "rank_tracking_configs_project_id_projects_id_fk",
+ "tableFrom": "rank_tracking_configs",
+ "columnsFrom": [
+ "project_id"
+ ],
+ "tableTo": "projects",
+ "columnsTo": [
+ "id"
+ ],
+ "onUpdate": "no action",
+ "onDelete": "cascade"
+ }
+ },
+ "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
+ },
+ "pinned_at": {
+ "name": "pinned_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,
+ "with": {},
+ "method": "btree",
+ "concurrently": false
+ }
+ },
+ "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",
+ "columnsFrom": [
+ "config_id"
+ ],
+ "tableTo": "rank_tracking_configs",
+ "columnsTo": [
+ "id"
+ ],
+ "onUpdate": "no action",
+ "onDelete": "cascade"
+ }
+ },
+ "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,
+ "with": {},
+ "method": "btree",
+ "concurrently": false
+ },
+ "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,
+ "with": {},
+ "method": "btree",
+ "concurrently": 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",
+ "columnsFrom": [
+ "saved_keyword_id"
+ ],
+ "tableTo": "saved_keywords",
+ "columnsTo": [
+ "id"
+ ],
+ "onUpdate": "no action",
+ "onDelete": "cascade"
+ },
+ "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",
+ "columnsFrom": [
+ "tag_id"
+ ],
+ "tableTo": "saved_keyword_tags",
+ "columnsTo": [
+ "id"
+ ],
+ "onUpdate": "no action",
+ "onDelete": "cascade"
+ }
+ },
+ "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,
+ "with": {},
+ "method": "btree",
+ "concurrently": false
+ },
+ "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,
+ "with": {},
+ "method": "btree",
+ "concurrently": false
+ }
+ },
+ "foreignKeys": {
+ "saved_keyword_tags_project_id_projects_id_fk": {
+ "name": "saved_keyword_tags_project_id_projects_id_fk",
+ "tableFrom": "saved_keyword_tags",
+ "columnsFrom": [
+ "project_id"
+ ],
+ "tableTo": "projects",
+ "columnsTo": [
+ "id"
+ ],
+ "onUpdate": "no action",
+ "onDelete": "cascade"
+ }
+ },
+ "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,
+ "with": {},
+ "method": "btree",
+ "concurrently": false
+ },
+ "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,
+ "with": {},
+ "method": "btree",
+ "concurrently": false
+ }
+ },
+ "foreignKeys": {
+ "saved_keywords_project_id_projects_id_fk": {
+ "name": "saved_keywords_project_id_projects_id_fk",
+ "tableFrom": "saved_keywords",
+ "columnsFrom": [
+ "project_id"
+ ],
+ "tableTo": "projects",
+ "columnsTo": [
+ "id"
+ ],
+ "onUpdate": "no action",
+ "onDelete": "cascade"
+ }
+ },
+ "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,
+ "with": {},
+ "method": "btree",
+ "concurrently": false
+ }
+ },
+ "foreignKeys": {
+ "user_onboarding_answers_user_id_user_id_fk": {
+ "name": "user_onboarding_answers_user_id_user_id_fk",
+ "tableFrom": "user_onboarding_answers",
+ "columnsFrom": [
+ "user_id"
+ ],
+ "tableTo": "user",
+ "columnsTo": [
+ "id"
+ ],
+ "onUpdate": "no action",
+ "onDelete": "cascade"
+ },
+ "user_onboarding_answers_organization_id_organization_id_fk": {
+ "name": "user_onboarding_answers_organization_id_organization_id_fk",
+ "tableFrom": "user_onboarding_answers",
+ "columnsFrom": [
+ "organization_id"
+ ],
+ "tableTo": "organization",
+ "columnsTo": [
+ "id"
+ ],
+ "onUpdate": "no action",
+ "onDelete": "cascade"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.user_signup_campaigns": {
+ "name": "user_signup_campaigns",
+ "schema": "",
+ "columns": {
+ "user_id": {
+ "name": "user_id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "utm_source": {
+ "name": "utm_source",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "utm_campaign": {
+ "name": "utm_campaign",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "utm_content": {
+ "name": "utm_content",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {
+ "user_signup_campaigns_user_id_user_id_fk": {
+ "name": "user_signup_campaigns_user_id_user_id_fk",
+ "tableFrom": "user_signup_campaigns",
+ "columnsFrom": [
+ "user_id"
+ ],
+ "tableTo": "user",
+ "columnsTo": [
+ "id"
+ ],
+ "onUpdate": "no action",
+ "onDelete": "cascade"
+ }
+ },
+ "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,
+ "with": {},
+ "method": "btree",
+ "concurrently": false
+ }
+ },
+ "foreignKeys": {
+ "project_competitors_project_id_projects_id_fk": {
+ "name": "project_competitors_project_id_projects_id_fk",
+ "tableFrom": "project_competitors",
+ "columnsFrom": [
+ "project_id"
+ ],
+ "tableTo": "projects",
+ "columnsTo": [
+ "id"
+ ],
+ "onUpdate": "no action",
+ "onDelete": "cascade"
+ }
+ },
+ "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",
+ "columnsFrom": [
+ "project_id"
+ ],
+ "tableTo": "projects",
+ "columnsTo": [
+ "id"
+ ],
+ "onUpdate": "no action",
+ "onDelete": "cascade"
+ }
+ },
+ "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,
+ "with": {},
+ "method": "btree",
+ "concurrently": false
+ }
+ },
+ "foreignKeys": {
+ "project_key_pages_project_id_projects_id_fk": {
+ "name": "project_key_pages_project_id_projects_id_fk",
+ "tableFrom": "project_key_pages",
+ "columnsFrom": [
+ "project_id"
+ ],
+ "tableTo": "projects",
+ "columnsTo": [
+ "id"
+ ],
+ "onUpdate": "no action",
+ "onDelete": "cascade"
+ }
+ },
+ "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,
+ "with": {},
+ "method": "btree",
+ "concurrently": false
+ }
+ },
+ "foreignKeys": {
+ "project_research_log_project_id_projects_id_fk": {
+ "name": "project_research_log_project_id_projects_id_fk",
+ "tableFrom": "project_research_log",
+ "columnsFrom": [
+ "project_id"
+ ],
+ "tableTo": "projects",
+ "columnsTo": [
+ "id"
+ ],
+ "onUpdate": "no action",
+ "onDelete": "cascade"
+ }
+ },
+ "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,
+ "with": {},
+ "method": "btree",
+ "concurrently": false
+ },
+ "reports_share_token_idx": {
+ "name": "reports_share_token_idx",
+ "columns": [
+ {
+ "expression": "share_token",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": true,
+ "with": {},
+ "method": "btree",
+ "concurrently": false
+ }
+ },
+ "foreignKeys": {
+ "reports_project_id_projects_id_fk": {
+ "name": "reports_project_id_projects_id_fk",
+ "tableFrom": "reports",
+ "columnsFrom": [
+ "project_id"
+ ],
+ "tableTo": "projects",
+ "columnsTo": [
+ "id"
+ ],
+ "onUpdate": "no action",
+ "onDelete": "cascade"
+ }
+ },
+ "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,
+ "with": {},
+ "method": "btree",
+ "concurrently": false
+ }
+ },
+ "foreignKeys": {
+ "report_templates_project_id_projects_id_fk": {
+ "name": "report_templates_project_id_projects_id_fk",
+ "tableFrom": "report_templates",
+ "columnsFrom": [
+ "project_id"
+ ],
+ "tableTo": "projects",
+ "columnsTo": [
+ "id"
+ ],
+ "onUpdate": "no action",
+ "onDelete": "cascade"
+ }
+ },
+ "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,
+ "with": {},
+ "method": "btree",
+ "concurrently": false
+ },
+ "audit_issues_page_id_idx": {
+ "name": "audit_issues_page_id_idx",
+ "columns": [
+ {
+ "expression": "page_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "with": {},
+ "method": "btree",
+ "concurrently": false
+ }
+ },
+ "foreignKeys": {
+ "audit_issues_audit_id_audits_id_fk": {
+ "name": "audit_issues_audit_id_audits_id_fk",
+ "tableFrom": "audit_issues",
+ "columnsFrom": [
+ "audit_id"
+ ],
+ "tableTo": "audits",
+ "columnsTo": [
+ "id"
+ ],
+ "onUpdate": "no action",
+ "onDelete": "cascade"
+ },
+ "audit_issues_page_id_audit_pages_id_fk": {
+ "name": "audit_issues_page_id_audit_pages_id_fk",
+ "tableFrom": "audit_issues",
+ "columnsFrom": [
+ "page_id"
+ ],
+ "tableTo": "audit_pages",
+ "columnsTo": [
+ "id"
+ ],
+ "onUpdate": "no action",
+ "onDelete": "cascade"
+ }
+ },
+ "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,
+ "with": {},
+ "method": "btree",
+ "concurrently": false
+ },
+ "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,
+ "with": {},
+ "method": "btree",
+ "concurrently": false
+ }
+ },
+ "foreignKeys": {
+ "audit_lighthouse_results_audit_id_audits_id_fk": {
+ "name": "audit_lighthouse_results_audit_id_audits_id_fk",
+ "tableFrom": "audit_lighthouse_results",
+ "columnsFrom": [
+ "audit_id"
+ ],
+ "tableTo": "audits",
+ "columnsTo": [
+ "id"
+ ],
+ "onUpdate": "no action",
+ "onDelete": "cascade"
+ },
+ "audit_lighthouse_results_page_id_audit_pages_id_fk": {
+ "name": "audit_lighthouse_results_page_id_audit_pages_id_fk",
+ "tableFrom": "audit_lighthouse_results",
+ "columnsFrom": [
+ "page_id"
+ ],
+ "tableTo": "audit_pages",
+ "columnsTo": [
+ "id"
+ ],
+ "onUpdate": "no action",
+ "onDelete": "cascade"
+ }
+ },
+ "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
+ },
+ "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
+ },
+ "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
+ },
+ "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,
+ "with": {},
+ "method": "btree",
+ "concurrently": false
+ }
+ },
+ "foreignKeys": {
+ "audit_pages_audit_id_audits_id_fk": {
+ "name": "audit_pages_audit_id_audits_id_fk",
+ "tableFrom": "audit_pages",
+ "columnsFrom": [
+ "audit_id"
+ ],
+ "tableTo": "audits",
+ "columnsTo": [
+ "id"
+ ],
+ "onUpdate": "no action",
+ "onDelete": "cascade"
+ }
+ },
+ "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,
+ "with": {},
+ "method": "btree",
+ "concurrently": false
+ },
+ "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,
+ "with": {},
+ "method": "btree",
+ "concurrently": false
+ }
+ },
+ "foreignKeys": {
+ "audits_project_id_projects_id_fk": {
+ "name": "audits_project_id_projects_id_fk",
+ "tableFrom": "audits",
+ "columnsFrom": [
+ "project_id"
+ ],
+ "tableTo": "projects",
+ "columnsTo": [
+ "id"
+ ],
+ "onUpdate": "no action",
+ "onDelete": "cascade"
+ }
+ },
+ "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,
+ "with": {},
+ "method": "btree",
+ "concurrently": false
+ }
+ },
+ "foreignKeys": {
+ "sam_sessions_project_id_projects_id_fk": {
+ "name": "sam_sessions_project_id_projects_id_fk",
+ "tableFrom": "sam_sessions",
+ "columnsFrom": [
+ "project_id"
+ ],
+ "tableTo": "projects",
+ "columnsTo": [
+ "id"
+ ],
+ "onUpdate": "no action",
+ "onDelete": "cascade"
+ },
+ "sam_sessions_user_id_user_id_fk": {
+ "name": "sam_sessions_user_id_user_id_fk",
+ "tableFrom": "sam_sessions",
+ "columnsFrom": [
+ "user_id"
+ ],
+ "tableTo": "user",
+ "columnsTo": [
+ "id"
+ ],
+ "onUpdate": "no action",
+ "onDelete": "cascade"
+ }
+ },
+ "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,
+ "with": {},
+ "method": "btree",
+ "concurrently": false
+ },
+ "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,
+ "with": {},
+ "method": "btree",
+ "concurrently": false
+ },
+ "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,
+ "with": {},
+ "method": "btree",
+ "where": "\"account\".\"provider_id\" in ('google-search-console', 'google-analytics')",
+ "concurrently": false
+ }
+ },
+ "foreignKeys": {
+ "account_user_id_user_id_fk": {
+ "name": "account_user_id_user_id_fk",
+ "tableFrom": "account",
+ "columnsFrom": [
+ "user_id"
+ ],
+ "tableTo": "user",
+ "columnsTo": [
+ "id"
+ ],
+ "onUpdate": "no action",
+ "onDelete": "cascade"
+ }
+ },
+ "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,
+ "with": {},
+ "method": "btree",
+ "concurrently": false
+ },
+ "apikey_referenceId_idx": {
+ "name": "apikey_referenceId_idx",
+ "columns": [
+ {
+ "expression": "reference_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "with": {},
+ "method": "btree",
+ "concurrently": false
+ },
+ "apikey_key_idx": {
+ "name": "apikey_key_idx",
+ "columns": [
+ {
+ "expression": "key",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "with": {},
+ "method": "btree",
+ "concurrently": false
+ }
+ },
+ "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,
+ "with": {},
+ "method": "btree",
+ "concurrently": false
+ },
+ "invitation_email_idx": {
+ "name": "invitation_email_idx",
+ "columns": [
+ {
+ "expression": "email",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "with": {},
+ "method": "btree",
+ "concurrently": false
+ }
+ },
+ "foreignKeys": {
+ "invitation_organization_id_organization_id_fk": {
+ "name": "invitation_organization_id_organization_id_fk",
+ "tableFrom": "invitation",
+ "columnsFrom": [
+ "organization_id"
+ ],
+ "tableTo": "organization",
+ "columnsTo": [
+ "id"
+ ],
+ "onUpdate": "no action",
+ "onDelete": "cascade"
+ },
+ "invitation_inviter_id_user_id_fk": {
+ "name": "invitation_inviter_id_user_id_fk",
+ "tableFrom": "invitation",
+ "columnsFrom": [
+ "inviter_id"
+ ],
+ "tableTo": "user",
+ "columnsTo": [
+ "id"
+ ],
+ "onUpdate": "no action",
+ "onDelete": "cascade"
+ }
+ },
+ "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,
+ "with": {},
+ "method": "btree",
+ "concurrently": false
+ },
+ "member_userId_idx": {
+ "name": "member_userId_idx",
+ "columns": [
+ {
+ "expression": "user_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "with": {},
+ "method": "btree",
+ "concurrently": false
+ },
+ "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,
+ "with": {},
+ "method": "btree",
+ "concurrently": false
+ }
+ },
+ "foreignKeys": {
+ "member_organization_id_organization_id_fk": {
+ "name": "member_organization_id_organization_id_fk",
+ "tableFrom": "member",
+ "columnsFrom": [
+ "organization_id"
+ ],
+ "tableTo": "organization",
+ "columnsTo": [
+ "id"
+ ],
+ "onUpdate": "no action",
+ "onDelete": "cascade"
+ },
+ "member_user_id_user_id_fk": {
+ "name": "member_user_id_user_id_fk",
+ "tableFrom": "member",
+ "columnsFrom": [
+ "user_id"
+ ],
+ "tableTo": "user",
+ "columnsTo": [
+ "id"
+ ],
+ "onUpdate": "no action",
+ "onDelete": "cascade"
+ }
+ },
+ "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,
+ "with": {},
+ "method": "btree",
+ "concurrently": false
+ }
+ },
+ "foreignKeys": {},
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {
+ "organization_slug_unique": {
+ "name": "organization_slug_unique",
+ "columns": [
+ "slug"
+ ],
+ "nullsNotDistinct": false
+ }
+ },
+ "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,
+ "with": {},
+ "method": "btree",
+ "concurrently": false
+ }
+ },
+ "foreignKeys": {
+ "session_user_id_user_id_fk": {
+ "name": "session_user_id_user_id_fk",
+ "tableFrom": "session",
+ "columnsFrom": [
+ "user_id"
+ ],
+ "tableTo": "user",
+ "columnsTo": [
+ "id"
+ ],
+ "onUpdate": "no action",
+ "onDelete": "cascade"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {
+ "session_token_unique": {
+ "name": "session_token_unique",
+ "columns": [
+ "token"
+ ],
+ "nullsNotDistinct": false
+ }
+ },
+ "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
+ },
+ "terms_accepted_version": {
+ "name": "terms_accepted_version",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "terms_accepted_at": {
+ "name": "terms_accepted_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "product_updates_opt_in": {
+ "name": "product_updates_opt_in",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "product_updates_changed_at": {
+ "name": "product_updates_changed_at",
+ "type": "timestamp with time zone",
+ "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",
+ "columns": [
+ "email"
+ ],
+ "nullsNotDistinct": false
+ }
+ },
+ "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,
+ "with": {},
+ "method": "btree",
+ "concurrently": false
+ },
+ "verification_expiresAt_idx": {
+ "name": "verification_expiresAt_idx",
+ "columns": [
+ {
+ "expression": "expires_at",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "with": {},
+ "method": "btree",
+ "concurrently": false
+ }
+ },
+ "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",
+ "columnsFrom": [
+ "organization_id"
+ ],
+ "tableTo": "organization",
+ "columnsTo": [
+ "id"
+ ],
+ "onUpdate": "no action",
+ "onDelete": "cascade"
+ }
+ },
+ "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,
+ "with": {},
+ "method": "btree",
+ "concurrently": false
+ },
+ "ga4_connections_organization_idx": {
+ "name": "ga4_connections_organization_idx",
+ "columns": [
+ {
+ "expression": "organization_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "with": {},
+ "method": "btree",
+ "concurrently": false
+ },
+ "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,
+ "with": {},
+ "method": "btree",
+ "concurrently": false
+ }
+ },
+ "foreignKeys": {
+ "ga4_connections_project_id_projects_id_fk": {
+ "name": "ga4_connections_project_id_projects_id_fk",
+ "tableFrom": "ga4_connections",
+ "columnsFrom": [
+ "project_id"
+ ],
+ "tableTo": "projects",
+ "columnsTo": [
+ "id"
+ ],
+ "onUpdate": "no action",
+ "onDelete": "cascade"
+ },
+ "ga4_connections_organization_id_organization_id_fk": {
+ "name": "ga4_connections_organization_id_organization_id_fk",
+ "tableFrom": "ga4_connections",
+ "columnsFrom": [
+ "organization_id"
+ ],
+ "tableTo": "organization",
+ "columnsTo": [
+ "id"
+ ],
+ "onUpdate": "no action",
+ "onDelete": "cascade"
+ }
+ },
+ "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,
+ "with": {},
+ "method": "btree",
+ "concurrently": false
+ },
+ "gsc_connections_organization_idx": {
+ "name": "gsc_connections_organization_idx",
+ "columns": [
+ {
+ "expression": "organization_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "with": {},
+ "method": "btree",
+ "concurrently": false
+ }
+ },
+ "foreignKeys": {
+ "gsc_connections_project_id_projects_id_fk": {
+ "name": "gsc_connections_project_id_projects_id_fk",
+ "tableFrom": "gsc_connections",
+ "columnsFrom": [
+ "project_id"
+ ],
+ "tableTo": "projects",
+ "columnsTo": [
+ "id"
+ ],
+ "onUpdate": "no action",
+ "onDelete": "cascade"
+ },
+ "gsc_connections_organization_id_organization_id_fk": {
+ "name": "gsc_connections_organization_id_organization_id_fk",
+ "tableFrom": "gsc_connections",
+ "columnsFrom": [
+ "organization_id"
+ ],
+ "tableTo": "organization",
+ "columnsTo": [
+ "id"
+ ],
+ "onUpdate": "no action",
+ "onDelete": "cascade"
+ }
+ },
+ "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
+ },
+ "public.ai_matches": {
+ "name": "ai_matches",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "observation_id": {
+ "name": "observation_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "name": {
+ "name": "name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "domain": {
+ "name": "domain",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "own": {
+ "name": "own",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "mentioned": {
+ "name": "mentioned",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "cited": {
+ "name": "cited",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "first_mention": {
+ "name": "first_mention",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false
+ }
+ },
+ "indexes": {
+ "ai_matches_observation_domain_idx": {
+ "name": "ai_matches_observation_domain_idx",
+ "columns": [
+ {
+ "expression": "observation_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "domain",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": true,
+ "with": {},
+ "method": "btree",
+ "concurrently": false
+ }
+ },
+ "foreignKeys": {
+ "ai_matches_observation_id_ai_observations_id_fk": {
+ "name": "ai_matches_observation_id_ai_observations_id_fk",
+ "tableFrom": "ai_matches",
+ "columnsFrom": [
+ "observation_id"
+ ],
+ "tableTo": "ai_observations",
+ "columnsTo": [
+ "id"
+ ],
+ "onUpdate": "no action",
+ "onDelete": "cascade"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.ai_observations": {
+ "name": "ai_observations",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "run_id": {
+ "name": "run_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "prompt_id": {
+ "name": "prompt_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "engine": {
+ "name": "engine",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "branded": {
+ "name": "branded",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "status": {
+ "name": "status",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'pending'"
+ },
+ "collected_at": {
+ "name": "collected_at",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "answer_markdown": {
+ "name": "answer_markdown",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "error": {
+ "name": "error",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ }
+ },
+ "indexes": {
+ "ai_observations_run_prompt_engine_idx": {
+ "name": "ai_observations_run_prompt_engine_idx",
+ "columns": [
+ {
+ "expression": "run_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "prompt_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "engine",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": true,
+ "with": {},
+ "method": "btree",
+ "concurrently": false
+ },
+ "ai_observations_prompt_idx": {
+ "name": "ai_observations_prompt_idx",
+ "columns": [
+ {
+ "expression": "prompt_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "with": {},
+ "method": "btree",
+ "concurrently": false
+ }
+ },
+ "foreignKeys": {
+ "ai_observations_run_id_ai_runs_id_fk": {
+ "name": "ai_observations_run_id_ai_runs_id_fk",
+ "tableFrom": "ai_observations",
+ "columnsFrom": [
+ "run_id"
+ ],
+ "tableTo": "ai_runs",
+ "columnsTo": [
+ "id"
+ ],
+ "onUpdate": "no action",
+ "onDelete": "cascade"
+ },
+ "ai_observations_prompt_id_ai_prompts_id_fk": {
+ "name": "ai_observations_prompt_id_ai_prompts_id_fk",
+ "tableFrom": "ai_observations",
+ "columnsFrom": [
+ "prompt_id"
+ ],
+ "tableTo": "ai_prompts",
+ "columnsTo": [
+ "id"
+ ],
+ "onUpdate": "no action",
+ "onDelete": "cascade"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.ai_prompts": {
+ "name": "ai_prompts",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "tracker_id": {
+ "name": "tracker_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "topic": {
+ "name": "topic",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "text": {
+ "name": "text",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "paused": {
+ "name": "paused",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": true,
+ "default": false
+ },
+ "archived": {
+ "name": "archived",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": true,
+ "default": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ }
+ },
+ "indexes": {
+ "ai_prompts_tracker_idx": {
+ "name": "ai_prompts_tracker_idx",
+ "columns": [
+ {
+ "expression": "tracker_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "with": {},
+ "method": "btree",
+ "concurrently": false
+ }
+ },
+ "foreignKeys": {
+ "ai_prompts_tracker_id_ai_trackers_id_fk": {
+ "name": "ai_prompts_tracker_id_ai_trackers_id_fk",
+ "tableFrom": "ai_prompts",
+ "columnsFrom": [
+ "tracker_id"
+ ],
+ "tableTo": "ai_trackers",
+ "columnsTo": [
+ "id"
+ ],
+ "onUpdate": "no action",
+ "onDelete": "cascade"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.ai_runs": {
+ "name": "ai_runs",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "tracker_id": {
+ "name": "tracker_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "project_id": {
+ "name": "project_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "trigger": {
+ "name": "trigger",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "status": {
+ "name": "status",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'queued'"
+ },
+ "location_code": {
+ "name": "location_code",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "language_code": {
+ "name": "language_code",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "completed_at": {
+ "name": "completed_at",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ }
+ },
+ "indexes": {
+ "ai_runs_project_created_idx": {
+ "name": "ai_runs_project_created_idx",
+ "columns": [
+ {
+ "expression": "project_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "created_at",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "with": {},
+ "method": "btree",
+ "concurrently": false
+ },
+ "ai_runs_one_active_idx": {
+ "name": "ai_runs_one_active_idx",
+ "columns": [
+ {
+ "expression": "tracker_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": true,
+ "with": {},
+ "method": "btree",
+ "where": "\"ai_runs\".\"status\" IN ('queued', 'running')",
+ "concurrently": false
+ }
+ },
+ "foreignKeys": {
+ "ai_runs_tracker_id_ai_trackers_id_fk": {
+ "name": "ai_runs_tracker_id_ai_trackers_id_fk",
+ "tableFrom": "ai_runs",
+ "columnsFrom": [
+ "tracker_id"
+ ],
+ "tableTo": "ai_trackers",
+ "columnsTo": [
+ "id"
+ ],
+ "onUpdate": "no action",
+ "onDelete": "cascade"
+ },
+ "ai_runs_project_id_projects_id_fk": {
+ "name": "ai_runs_project_id_projects_id_fk",
+ "tableFrom": "ai_runs",
+ "columnsFrom": [
+ "project_id"
+ ],
+ "tableTo": "projects",
+ "columnsTo": [
+ "id"
+ ],
+ "onUpdate": "no action",
+ "onDelete": "cascade"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.ai_sources": {
+ "name": "ai_sources",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "observation_id": {
+ "name": "observation_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "url": {
+ "name": "url",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "domain": {
+ "name": "domain",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "title": {
+ "name": "title",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "position": {
+ "name": "position",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true
+ }
+ },
+ "indexes": {
+ "ai_sources_observation_idx": {
+ "name": "ai_sources_observation_idx",
+ "columns": [
+ {
+ "expression": "observation_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "with": {},
+ "method": "btree",
+ "concurrently": false
+ }
+ },
+ "foreignKeys": {
+ "ai_sources_observation_id_ai_observations_id_fk": {
+ "name": "ai_sources_observation_id_ai_observations_id_fk",
+ "tableFrom": "ai_sources",
+ "columnsFrom": [
+ "observation_id"
+ ],
+ "tableTo": "ai_observations",
+ "columnsTo": [
+ "id"
+ ],
+ "onUpdate": "no action",
+ "onDelete": "cascade"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.ai_trackers": {
+ "name": "ai_trackers",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "project_id": {
+ "name": "project_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "enabled": {
+ "name": "enabled",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": true,
+ "default": false
+ },
+ "chatgpt": {
+ "name": "chatgpt",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": true,
+ "default": true
+ },
+ "gemini": {
+ "name": "gemini",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": true,
+ "default": false
+ },
+ "claude": {
+ "name": "claude",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": true,
+ "default": false
+ },
+ "perplexity": {
+ "name": "perplexity",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": true,
+ "default": false
+ },
+ "google_ai_overview": {
+ "name": "google_ai_overview",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": true,
+ "default": 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'"
+ },
+ "schedule_interval": {
+ "name": "schedule_interval",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'weekly'"
+ },
+ "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
+ }
+ },
+ "indexes": {
+ "ai_trackers_project_idx": {
+ "name": "ai_trackers_project_idx",
+ "columns": [
+ {
+ "expression": "project_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": true,
+ "with": {},
+ "method": "btree",
+ "concurrently": false
+ },
+ "ai_trackers_due_idx": {
+ "name": "ai_trackers_due_idx",
+ "columns": [
+ {
+ "expression": "enabled",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "next_check_at",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "with": {},
+ "method": "btree",
+ "concurrently": false
+ }
+ },
+ "foreignKeys": {
+ "ai_trackers_project_id_projects_id_fk": {
+ "name": "ai_trackers_project_id_projects_id_fk",
+ "tableFrom": "ai_trackers",
+ "columnsFrom": [
+ "project_id"
+ ],
+ "tableTo": "projects",
+ "columnsTo": [
+ "id"
+ ],
+ "onUpdate": "no action",
+ "onDelete": "cascade"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.local_rank_businesses": {
+ "name": "local_rank_businesses",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "scan_id": {
+ "name": "scan_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "identity": {
+ "name": "identity",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "title": {
+ "name": "title",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "cid": {
+ "name": "cid",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "place_id": {
+ "name": "place_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "address": {
+ "name": "address",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "rating": {
+ "name": "rating",
+ "type": "double precision",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "reviews": {
+ "name": "reviews",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false
+ }
+ },
+ "indexes": {
+ "local_rank_businesses_scan_identity_idx": {
+ "name": "local_rank_businesses_scan_identity_idx",
+ "columns": [
+ {
+ "expression": "scan_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "identity",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": true,
+ "with": {},
+ "method": "btree",
+ "concurrently": false
+ }
+ },
+ "foreignKeys": {
+ "local_rank_businesses_scan_id_local_rank_scans_id_fk": {
+ "name": "local_rank_businesses_scan_id_local_rank_scans_id_fk",
+ "tableFrom": "local_rank_businesses",
+ "columnsFrom": [
+ "scan_id"
+ ],
+ "tableTo": "local_rank_scans",
+ "columnsTo": [
+ "id"
+ ],
+ "onUpdate": "no action",
+ "onDelete": "cascade"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.local_rank_checks": {
+ "name": "local_rank_checks",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "project_id": {
+ "name": "project_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "tracker_id": {
+ "name": "tracker_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "status": {
+ "name": "status",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "error": {
+ "name": "error",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "completed_at": {
+ "name": "completed_at",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ }
+ },
+ "indexes": {
+ "local_rank_checks_tracker_created_idx": {
+ "name": "local_rank_checks_tracker_created_idx",
+ "columns": [
+ {
+ "expression": "tracker_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "created_at",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "with": {},
+ "method": "btree",
+ "concurrently": false
+ },
+ "local_rank_checks_one_active_idx": {
+ "name": "local_rank_checks_one_active_idx",
+ "columns": [
+ {
+ "expression": "tracker_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": true,
+ "with": {},
+ "method": "btree",
+ "where": "\"local_rank_checks\".\"status\" IN ('queued', 'running')",
+ "concurrently": false
+ }
+ },
+ "foreignKeys": {
+ "local_rank_checks_project_id_projects_id_fk": {
+ "name": "local_rank_checks_project_id_projects_id_fk",
+ "tableFrom": "local_rank_checks",
+ "columnsFrom": [
+ "project_id"
+ ],
+ "tableTo": "projects",
+ "columnsTo": [
+ "id"
+ ],
+ "onUpdate": "no action",
+ "onDelete": "cascade"
+ },
+ "local_rank_checks_tracker_id_local_rank_trackers_id_fk": {
+ "name": "local_rank_checks_tracker_id_local_rank_trackers_id_fk",
+ "tableFrom": "local_rank_checks",
+ "columnsFrom": [
+ "tracker_id"
+ ],
+ "tableTo": "local_rank_trackers",
+ "columnsTo": [
+ "id"
+ ],
+ "onUpdate": "no action",
+ "onDelete": "cascade"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.local_rank_keywords": {
+ "name": "local_rank_keywords",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "tracker_id": {
+ "name": "tracker_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "keyword": {
+ "name": "keyword",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "archived_at": {
+ "name": "archived_at",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ }
+ },
+ "indexes": {
+ "local_rank_keywords_tracker_keyword_idx": {
+ "name": "local_rank_keywords_tracker_keyword_idx",
+ "columns": [
+ {
+ "expression": "tracker_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "keyword",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": true,
+ "with": {},
+ "method": "btree",
+ "concurrently": false
+ }
+ },
+ "foreignKeys": {
+ "local_rank_keywords_tracker_id_local_rank_trackers_id_fk": {
+ "name": "local_rank_keywords_tracker_id_local_rank_trackers_id_fk",
+ "tableFrom": "local_rank_keywords",
+ "columnsFrom": [
+ "tracker_id"
+ ],
+ "tableTo": "local_rank_trackers",
+ "columnsTo": [
+ "id"
+ ],
+ "onUpdate": "no action",
+ "onDelete": "cascade"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.local_rank_points": {
+ "name": "local_rank_points",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "scan_id": {
+ "name": "scan_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "row": {
+ "name": "row",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "col": {
+ "name": "col",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "latitude": {
+ "name": "latitude",
+ "type": "double precision",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "longitude": {
+ "name": "longitude",
+ "type": "double precision",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "status": {
+ "name": "status",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "rank": {
+ "name": "rank",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "results_count": {
+ "name": "results_count",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "error": {
+ "name": "error",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "collected_at": {
+ "name": "collected_at",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ }
+ },
+ "indexes": {
+ "local_rank_points_scan_position_idx": {
+ "name": "local_rank_points_scan_position_idx",
+ "columns": [
+ {
+ "expression": "scan_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "row",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "col",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": true,
+ "with": {},
+ "method": "btree",
+ "concurrently": false
+ }
+ },
+ "foreignKeys": {
+ "local_rank_points_scan_id_local_rank_scans_id_fk": {
+ "name": "local_rank_points_scan_id_local_rank_scans_id_fk",
+ "tableFrom": "local_rank_points",
+ "columnsFrom": [
+ "scan_id"
+ ],
+ "tableTo": "local_rank_scans",
+ "columnsTo": [
+ "id"
+ ],
+ "onUpdate": "no action",
+ "onDelete": "cascade"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.local_rank_results": {
+ "name": "local_rank_results",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "point_id": {
+ "name": "point_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "business_id": {
+ "name": "business_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "rank": {
+ "name": "rank",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true
+ }
+ },
+ "indexes": {
+ "local_rank_results_point_business_idx": {
+ "name": "local_rank_results_point_business_idx",
+ "columns": [
+ {
+ "expression": "point_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "business_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": true,
+ "with": {},
+ "method": "btree",
+ "concurrently": false
+ },
+ "local_rank_results_business_idx": {
+ "name": "local_rank_results_business_idx",
+ "columns": [
+ {
+ "expression": "business_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "with": {},
+ "method": "btree",
+ "concurrently": false
+ }
+ },
+ "foreignKeys": {
+ "local_rank_results_point_id_local_rank_points_id_fk": {
+ "name": "local_rank_results_point_id_local_rank_points_id_fk",
+ "tableFrom": "local_rank_results",
+ "columnsFrom": [
+ "point_id"
+ ],
+ "tableTo": "local_rank_points",
+ "columnsTo": [
+ "id"
+ ],
+ "onUpdate": "no action",
+ "onDelete": "cascade"
+ },
+ "local_rank_results_business_id_local_rank_businesses_id_fk": {
+ "name": "local_rank_results_business_id_local_rank_businesses_id_fk",
+ "tableFrom": "local_rank_results",
+ "columnsFrom": [
+ "business_id"
+ ],
+ "tableTo": "local_rank_businesses",
+ "columnsTo": [
+ "id"
+ ],
+ "onUpdate": "no action",
+ "onDelete": "cascade"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.local_rank_scans": {
+ "name": "local_rank_scans",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "check_id": {
+ "name": "check_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "project_id": {
+ "name": "project_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "tracker_id": {
+ "name": "tracker_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "keyword_id": {
+ "name": "keyword_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "status": {
+ "name": "status",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "error": {
+ "name": "error",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "completed_at": {
+ "name": "completed_at",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ }
+ },
+ "indexes": {
+ "local_rank_scans_tracker_created_idx": {
+ "name": "local_rank_scans_tracker_created_idx",
+ "columns": [
+ {
+ "expression": "tracker_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "created_at",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "with": {},
+ "method": "btree",
+ "concurrently": false
+ },
+ "local_rank_scans_project_idx": {
+ "name": "local_rank_scans_project_idx",
+ "columns": [
+ {
+ "expression": "project_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "with": {},
+ "method": "btree",
+ "concurrently": false
+ },
+ "local_rank_scans_check_keyword_idx": {
+ "name": "local_rank_scans_check_keyword_idx",
+ "columns": [
+ {
+ "expression": "check_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "keyword_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": true,
+ "with": {},
+ "method": "btree",
+ "concurrently": false
+ }
+ },
+ "foreignKeys": {
+ "local_rank_scans_check_id_local_rank_checks_id_fk": {
+ "name": "local_rank_scans_check_id_local_rank_checks_id_fk",
+ "tableFrom": "local_rank_scans",
+ "columnsFrom": [
+ "check_id"
+ ],
+ "tableTo": "local_rank_checks",
+ "columnsTo": [
+ "id"
+ ],
+ "onUpdate": "no action",
+ "onDelete": "cascade"
+ },
+ "local_rank_scans_project_id_projects_id_fk": {
+ "name": "local_rank_scans_project_id_projects_id_fk",
+ "tableFrom": "local_rank_scans",
+ "columnsFrom": [
+ "project_id"
+ ],
+ "tableTo": "projects",
+ "columnsTo": [
+ "id"
+ ],
+ "onUpdate": "no action",
+ "onDelete": "cascade"
+ },
+ "local_rank_scans_tracker_id_local_rank_trackers_id_fk": {
+ "name": "local_rank_scans_tracker_id_local_rank_trackers_id_fk",
+ "tableFrom": "local_rank_scans",
+ "columnsFrom": [
+ "tracker_id"
+ ],
+ "tableTo": "local_rank_trackers",
+ "columnsTo": [
+ "id"
+ ],
+ "onUpdate": "no action",
+ "onDelete": "cascade"
+ },
+ "local_rank_scans_keyword_id_local_rank_keywords_id_fk": {
+ "name": "local_rank_scans_keyword_id_local_rank_keywords_id_fk",
+ "tableFrom": "local_rank_scans",
+ "columnsFrom": [
+ "keyword_id"
+ ],
+ "tableTo": "local_rank_keywords",
+ "columnsTo": [
+ "id"
+ ],
+ "onUpdate": "no action",
+ "onDelete": "cascade"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.local_rank_trackers": {
+ "name": "local_rank_trackers",
+ "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
+ },
+ "address": {
+ "name": "address",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "cid": {
+ "name": "cid",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "place_id": {
+ "name": "place_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "latitude": {
+ "name": "latitude",
+ "type": "double precision",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "longitude": {
+ "name": "longitude",
+ "type": "double precision",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "grid_size": {
+ "name": "grid_size",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "spacing_km": {
+ "name": "spacing_km",
+ "type": "double precision",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "language_code": {
+ "name": "language_code",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ }
+ },
+ "indexes": {
+ "local_rank_trackers_project_idx": {
+ "name": "local_rank_trackers_project_idx",
+ "columns": [
+ {
+ "expression": "project_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "with": {},
+ "method": "btree",
+ "concurrently": false
+ }
+ },
+ "foreignKeys": {
+ "local_rank_trackers_project_id_projects_id_fk": {
+ "name": "local_rank_trackers_project_id_projects_id_fk",
+ "tableFrom": "local_rank_trackers",
+ "columnsFrom": [
+ "project_id"
+ ],
+ "tableTo": "projects",
+ "columnsTo": [
+ "id"
+ ],
+ "onUpdate": "no action",
+ "onDelete": "cascade"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ }
+ },
+ "enums": {},
+ "schemas": {},
+ "views": {},
+ "sequences": {},
+ "roles": {},
+ "policies": {},
+ "_meta": {
+ "columns": {},
+ "schemas": {},
+ "tables": {}
+ }
+}
\ No newline at end of file
diff --git a/drizzle/pg/meta/_journal.json b/drizzle/pg/meta/_journal.json
index 4d0f13b4..c36c07f7 100644
--- a/drizzle/pg/meta/_journal.json
+++ b/drizzle/pg/meta/_journal.json
@@ -281,6 +281,13 @@
"when": 1792647301349,
"tag": "0039_silly_jocasta",
"breakpoints": true
+ },
+ {
+ "idx": 40,
+ "version": "7",
+ "when": 1792713961615,
+ "tag": "0040_bind_api_keys_to_organization",
+ "breakpoints": true
}
]
}
\ No newline at end of file
diff --git a/drizzle/sqlite/0062_bind_api_keys_to_organization.sql b/drizzle/sqlite/0062_bind_api_keys_to_organization.sql
new file mode 100644
index 00000000..64f652f0
--- /dev/null
+++ b/drizzle/sqlite/0062_bind_api_keys_to_organization.sql
@@ -0,0 +1,23 @@
+-- Bind existing MCP API keys to one organization. Keys created from now on
+-- get {"organizationId": ...} stamped into metadata at creation; older keys
+-- resolved the org per request. Backfill with the same rule that runtime
+-- used: the user's last-active organization if still a member, else the
+-- organization they joined most recently. Keys whose user belongs to no
+-- organization stay unbound and are rejected by /mcp. The plugin writes
+-- metadata through JSON.stringify, so an unset value is the text 'null', not
+-- SQL NULL.
+UPDATE `apikey`
+SET `metadata` = (
+ SELECT json_object('organizationId', `member`.`organization_id`)
+ FROM `member`
+ JOIN `user` ON `user`.`id` = `member`.`user_id`
+ WHERE `member`.`user_id` = `apikey`.`reference_id`
+ ORDER BY
+ CASE WHEN `member`.`organization_id` = `user`.`last_active_organization_id` THEN 0 ELSE 1 END,
+ `member`.`created_at` DESC
+ LIMIT 1
+)
+WHERE (`metadata` IS NULL OR `metadata` = 'null')
+ AND EXISTS (
+ SELECT 1 FROM `member` WHERE `member`.`user_id` = `apikey`.`reference_id`
+ );
diff --git a/drizzle/sqlite/meta/0062_snapshot.json b/drizzle/sqlite/meta/0062_snapshot.json
new file mode 100644
index 00000000..4bd386e9
--- /dev/null
+++ b/drizzle/sqlite/meta/0062_snapshot.json
@@ -0,0 +1,5665 @@
+{
+ "id": "633a88f7-a404-403e-9507-e5c69314be6c",
+ "prevId": "7e47683d-84bc-4146-851a-8f4a7e410b90",
+ "version": "6",
+ "dialect": "sqlite",
+ "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",
+ "columnsFrom": [
+ "project_id"
+ ],
+ "tableTo": "projects",
+ "columnsTo": [
+ "id"
+ ],
+ "onUpdate": "no action",
+ "onDelete": "cascade"
+ }
+ },
+ "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",
+ "columnsFrom": [
+ "project_id"
+ ],
+ "tableTo": "projects",
+ "columnsTo": [
+ "id"
+ ],
+ "onUpdate": "no action",
+ "onDelete": "cascade"
+ }
+ },
+ "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",
+ "columnsFrom": [
+ "user_id"
+ ],
+ "tableTo": "user",
+ "columnsTo": [
+ "id"
+ ],
+ "onUpdate": "no action",
+ "onDelete": "cascade"
+ },
+ "dashboard_step_dismissals_project_id_projects_id_fk": {
+ "name": "dashboard_step_dismissals_project_id_projects_id_fk",
+ "tableFrom": "dashboard_step_dismissals",
+ "columnsFrom": [
+ "project_id"
+ ],
+ "tableTo": "projects",
+ "columnsTo": [
+ "id"
+ ],
+ "onUpdate": "no action",
+ "onDelete": "cascade"
+ }
+ },
+ "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": {}
+ },
+ "data_refresh_claims": {
+ "name": "data_refresh_claims",
+ "columns": {
+ "key": {
+ "name": "key",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "organization_id": {
+ "name": "organization_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "token": {
+ "name": "token",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "next_attempt_at": {
+ "name": "next_attempt_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {
+ "data_refresh_claims_organization_id_organization_id_fk": {
+ "name": "data_refresh_claims_organization_id_organization_id_fk",
+ "tableFrom": "data_refresh_claims",
+ "columnsFrom": [
+ "organization_id"
+ ],
+ "tableTo": "organization",
+ "columnsTo": [
+ "id"
+ ],
+ "onUpdate": "no action",
+ "onDelete": "cascade"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "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",
+ "columnsFrom": [
+ "project_id"
+ ],
+ "tableTo": "projects",
+ "columnsTo": [
+ "id"
+ ],
+ "onUpdate": "no action",
+ "onDelete": "cascade"
+ }
+ },
+ "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",
+ "columnsFrom": [
+ "organization_id"
+ ],
+ "tableTo": "organization",
+ "columnsTo": [
+ "id"
+ ],
+ "onUpdate": "no action",
+ "onDelete": "cascade"
+ }
+ },
+ "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",
+ "columnsFrom": [
+ "project_id"
+ ],
+ "tableTo": "projects",
+ "columnsTo": [
+ "id"
+ ],
+ "onUpdate": "no action",
+ "onDelete": "cascade"
+ }
+ },
+ "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
+ },
+ "ai_research_keywords": {
+ "name": "ai_research_keywords",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "indexnow_key": {
+ "name": "indexnow_key",
+ "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"
+ ],
+ "where": "\"projects\".\"name\" = 'Default' AND \"projects\".\"domain\" IS NULL AND \"projects\".\"archived_at\" IS NULL",
+ "isUnique": true
+ },
+ "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",
+ "columnsFrom": [
+ "organization_id"
+ ],
+ "tableTo": "organization",
+ "columnsTo": [
+ "id"
+ ],
+ "onUpdate": "no action",
+ "onDelete": "cascade"
+ }
+ },
+ "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"
+ ],
+ "where": "\"rank_check_runs\".\"status\" IN ('pending', 'running')",
+ "isUnique": true
+ }
+ },
+ "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",
+ "columnsFrom": [
+ "config_id"
+ ],
+ "tableTo": "rank_tracking_configs",
+ "columnsTo": [
+ "id"
+ ],
+ "onUpdate": "no action",
+ "onDelete": "cascade"
+ },
+ "rank_check_runs_project_id_projects_id_fk": {
+ "name": "rank_check_runs_project_id_projects_id_fk",
+ "tableFrom": "rank_check_runs",
+ "columnsFrom": [
+ "project_id"
+ ],
+ "tableTo": "projects",
+ "columnsTo": [
+ "id"
+ ],
+ "onUpdate": "no action",
+ "onDelete": "cascade"
+ }
+ },
+ "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",
+ "columnsFrom": [
+ "run_id"
+ ],
+ "tableTo": "rank_check_runs",
+ "columnsTo": [
+ "id"
+ ],
+ "onUpdate": "no action",
+ "onDelete": "cascade"
+ }
+ },
+ "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",
+ "language_code"
+ ],
+ "where": "\"rank_tracking_configs\".\"location_name\" IS NULL",
+ "isUnique": true
+ },
+ "rank_tracking_configs_local_idx": {
+ "name": "rank_tracking_configs_local_idx",
+ "columns": [
+ "project_id",
+ "domain",
+ "location_code",
+ "language_code",
+ "location_name"
+ ],
+ "where": "\"rank_tracking_configs\".\"location_name\" IS NOT NULL",
+ "isUnique": true
+ }
+ },
+ "foreignKeys": {
+ "rank_tracking_configs_project_id_projects_id_fk": {
+ "name": "rank_tracking_configs_project_id_projects_id_fk",
+ "tableFrom": "rank_tracking_configs",
+ "columnsFrom": [
+ "project_id"
+ ],
+ "tableTo": "projects",
+ "columnsTo": [
+ "id"
+ ],
+ "onUpdate": "no action",
+ "onDelete": "cascade"
+ }
+ },
+ "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
+ },
+ "pinned_at": {
+ "name": "pinned_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",
+ "columnsFrom": [
+ "config_id"
+ ],
+ "tableTo": "rank_tracking_configs",
+ "columnsTo": [
+ "id"
+ ],
+ "onUpdate": "no action",
+ "onDelete": "cascade"
+ }
+ },
+ "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",
+ "columnsFrom": [
+ "saved_keyword_id"
+ ],
+ "tableTo": "saved_keywords",
+ "columnsTo": [
+ "id"
+ ],
+ "onUpdate": "no action",
+ "onDelete": "cascade"
+ },
+ "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",
+ "columnsFrom": [
+ "tag_id"
+ ],
+ "tableTo": "saved_keyword_tags",
+ "columnsTo": [
+ "id"
+ ],
+ "onUpdate": "no action",
+ "onDelete": "cascade"
+ }
+ },
+ "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",
+ "columnsFrom": [
+ "project_id"
+ ],
+ "tableTo": "projects",
+ "columnsTo": [
+ "id"
+ ],
+ "onUpdate": "no action",
+ "onDelete": "cascade"
+ }
+ },
+ "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",
+ "columnsFrom": [
+ "project_id"
+ ],
+ "tableTo": "projects",
+ "columnsTo": [
+ "id"
+ ],
+ "onUpdate": "no action",
+ "onDelete": "cascade"
+ }
+ },
+ "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",
+ "columnsFrom": [
+ "user_id"
+ ],
+ "tableTo": "user",
+ "columnsTo": [
+ "id"
+ ],
+ "onUpdate": "no action",
+ "onDelete": "cascade"
+ },
+ "user_onboarding_answers_organization_id_organization_id_fk": {
+ "name": "user_onboarding_answers_organization_id_organization_id_fk",
+ "tableFrom": "user_onboarding_answers",
+ "columnsFrom": [
+ "organization_id"
+ ],
+ "tableTo": "organization",
+ "columnsTo": [
+ "id"
+ ],
+ "onUpdate": "no action",
+ "onDelete": "cascade"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "user_signup_campaigns": {
+ "name": "user_signup_campaigns",
+ "columns": {
+ "user_id": {
+ "name": "user_id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "utm_source": {
+ "name": "utm_source",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "utm_campaign": {
+ "name": "utm_campaign",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "utm_content": {
+ "name": "utm_content",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {
+ "user_signup_campaigns_user_id_user_id_fk": {
+ "name": "user_signup_campaigns_user_id_user_id_fk",
+ "tableFrom": "user_signup_campaigns",
+ "columnsFrom": [
+ "user_id"
+ ],
+ "tableTo": "user",
+ "columnsTo": [
+ "id"
+ ],
+ "onUpdate": "no action",
+ "onDelete": "cascade"
+ }
+ },
+ "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",
+ "columnsFrom": [
+ "project_id"
+ ],
+ "tableTo": "projects",
+ "columnsTo": [
+ "id"
+ ],
+ "onUpdate": "no action",
+ "onDelete": "cascade"
+ }
+ },
+ "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",
+ "columnsFrom": [
+ "project_id"
+ ],
+ "tableTo": "projects",
+ "columnsTo": [
+ "id"
+ ],
+ "onUpdate": "no action",
+ "onDelete": "cascade"
+ }
+ },
+ "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",
+ "columnsFrom": [
+ "project_id"
+ ],
+ "tableTo": "projects",
+ "columnsTo": [
+ "id"
+ ],
+ "onUpdate": "no action",
+ "onDelete": "cascade"
+ }
+ },
+ "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",
+ "columnsFrom": [
+ "project_id"
+ ],
+ "tableTo": "projects",
+ "columnsTo": [
+ "id"
+ ],
+ "onUpdate": "no action",
+ "onDelete": "cascade"
+ }
+ },
+ "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",
+ "columnsFrom": [
+ "project_id"
+ ],
+ "tableTo": "projects",
+ "columnsTo": [
+ "id"
+ ],
+ "onUpdate": "no action",
+ "onDelete": "cascade"
+ }
+ },
+ "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",
+ "columnsFrom": [
+ "project_id"
+ ],
+ "tableTo": "projects",
+ "columnsTo": [
+ "id"
+ ],
+ "onUpdate": "no action",
+ "onDelete": "cascade"
+ }
+ },
+ "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",
+ "columnsFrom": [
+ "audit_id"
+ ],
+ "tableTo": "audits",
+ "columnsTo": [
+ "id"
+ ],
+ "onUpdate": "no action",
+ "onDelete": "cascade"
+ },
+ "audit_issues_page_id_audit_pages_id_fk": {
+ "name": "audit_issues_page_id_audit_pages_id_fk",
+ "tableFrom": "audit_issues",
+ "columnsFrom": [
+ "page_id"
+ ],
+ "tableTo": "audit_pages",
+ "columnsTo": [
+ "id"
+ ],
+ "onUpdate": "no action",
+ "onDelete": "cascade"
+ }
+ },
+ "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",
+ "columnsFrom": [
+ "audit_id"
+ ],
+ "tableTo": "audits",
+ "columnsTo": [
+ "id"
+ ],
+ "onUpdate": "no action",
+ "onDelete": "cascade"
+ },
+ "audit_lighthouse_results_page_id_audit_pages_id_fk": {
+ "name": "audit_lighthouse_results_page_id_audit_pages_id_fk",
+ "tableFrom": "audit_lighthouse_results",
+ "columnsFrom": [
+ "page_id"
+ ],
+ "tableTo": "audit_pages",
+ "columnsTo": [
+ "id"
+ ],
+ "onUpdate": "no action",
+ "onDelete": "cascade"
+ }
+ },
+ "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
+ },
+ "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
+ },
+ "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
+ },
+ "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",
+ "columnsFrom": [
+ "audit_id"
+ ],
+ "tableTo": "audits",
+ "columnsTo": [
+ "id"
+ ],
+ "onUpdate": "no action",
+ "onDelete": "cascade"
+ }
+ },
+ "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",
+ "columnsFrom": [
+ "project_id"
+ ],
+ "tableTo": "projects",
+ "columnsTo": [
+ "id"
+ ],
+ "onUpdate": "no action",
+ "onDelete": "cascade"
+ }
+ },
+ "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",
+ "columnsFrom": [
+ "project_id"
+ ],
+ "tableTo": "projects",
+ "columnsTo": [
+ "id"
+ ],
+ "onUpdate": "no action",
+ "onDelete": "cascade"
+ },
+ "sam_sessions_user_id_user_id_fk": {
+ "name": "sam_sessions_user_id_user_id_fk",
+ "tableFrom": "sam_sessions",
+ "columnsFrom": [
+ "user_id"
+ ],
+ "tableTo": "user",
+ "columnsTo": [
+ "id"
+ ],
+ "onUpdate": "no action",
+ "onDelete": "cascade"
+ }
+ },
+ "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"
+ ],
+ "where": "\"account\".\"provider_id\" in ('google-search-console', 'google-analytics')",
+ "isUnique": true
+ }
+ },
+ "foreignKeys": {
+ "account_user_id_user_id_fk": {
+ "name": "account_user_id_user_id_fk",
+ "tableFrom": "account",
+ "columnsFrom": [
+ "user_id"
+ ],
+ "tableTo": "user",
+ "columnsTo": [
+ "id"
+ ],
+ "onUpdate": "no action",
+ "onDelete": "cascade"
+ }
+ },
+ "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",
+ "columnsFrom": [
+ "organization_id"
+ ],
+ "tableTo": "organization",
+ "columnsTo": [
+ "id"
+ ],
+ "onUpdate": "no action",
+ "onDelete": "cascade"
+ },
+ "invitation_inviter_id_user_id_fk": {
+ "name": "invitation_inviter_id_user_id_fk",
+ "tableFrom": "invitation",
+ "columnsFrom": [
+ "inviter_id"
+ ],
+ "tableTo": "user",
+ "columnsTo": [
+ "id"
+ ],
+ "onUpdate": "no action",
+ "onDelete": "cascade"
+ }
+ },
+ "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",
+ "columnsFrom": [
+ "organization_id"
+ ],
+ "tableTo": "organization",
+ "columnsTo": [
+ "id"
+ ],
+ "onUpdate": "no action",
+ "onDelete": "cascade"
+ },
+ "member_user_id_user_id_fk": {
+ "name": "member_user_id_user_id_fk",
+ "tableFrom": "member",
+ "columnsFrom": [
+ "user_id"
+ ],
+ "tableTo": "user",
+ "columnsTo": [
+ "id"
+ ],
+ "onUpdate": "no action",
+ "onDelete": "cascade"
+ }
+ },
+ "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",
+ "columnsFrom": [
+ "user_id"
+ ],
+ "tableTo": "user",
+ "columnsTo": [
+ "id"
+ ],
+ "onUpdate": "no action",
+ "onDelete": "cascade"
+ }
+ },
+ "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
+ },
+ "terms_accepted_version": {
+ "name": "terms_accepted_version",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "terms_accepted_at": {
+ "name": "terms_accepted_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "product_updates_opt_in": {
+ "name": "product_updates_opt_in",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "product_updates_changed_at": {
+ "name": "product_updates_changed_at",
+ "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",
+ "columnsFrom": [
+ "organization_id"
+ ],
+ "tableTo": "organization",
+ "columnsTo": [
+ "id"
+ ],
+ "onUpdate": "no action",
+ "onDelete": "cascade"
+ }
+ },
+ "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",
+ "columnsFrom": [
+ "project_id"
+ ],
+ "tableTo": "projects",
+ "columnsTo": [
+ "id"
+ ],
+ "onUpdate": "no action",
+ "onDelete": "cascade"
+ },
+ "ga4_connections_organization_id_organization_id_fk": {
+ "name": "ga4_connections_organization_id_organization_id_fk",
+ "tableFrom": "ga4_connections",
+ "columnsFrom": [
+ "organization_id"
+ ],
+ "tableTo": "organization",
+ "columnsTo": [
+ "id"
+ ],
+ "onUpdate": "no action",
+ "onDelete": "cascade"
+ }
+ },
+ "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",
+ "columnsFrom": [
+ "project_id"
+ ],
+ "tableTo": "projects",
+ "columnsTo": [
+ "id"
+ ],
+ "onUpdate": "no action",
+ "onDelete": "cascade"
+ },
+ "gsc_connections_organization_id_organization_id_fk": {
+ "name": "gsc_connections_organization_id_organization_id_fk",
+ "tableFrom": "gsc_connections",
+ "columnsFrom": [
+ "organization_id"
+ ],
+ "tableTo": "organization",
+ "columnsTo": [
+ "id"
+ ],
+ "onUpdate": "no action",
+ "onDelete": "cascade"
+ }
+ },
+ "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": {}
+ },
+ "ai_matches": {
+ "name": "ai_matches",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "observation_id": {
+ "name": "observation_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": true,
+ "autoincrement": false
+ },
+ "own": {
+ "name": "own",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "mentioned": {
+ "name": "mentioned",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "cited": {
+ "name": "cited",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "first_mention": {
+ "name": "first_mention",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "ai_matches_observation_domain_idx": {
+ "name": "ai_matches_observation_domain_idx",
+ "columns": [
+ "observation_id",
+ "domain"
+ ],
+ "isUnique": true
+ }
+ },
+ "foreignKeys": {
+ "ai_matches_observation_id_ai_observations_id_fk": {
+ "name": "ai_matches_observation_id_ai_observations_id_fk",
+ "tableFrom": "ai_matches",
+ "columnsFrom": [
+ "observation_id"
+ ],
+ "tableTo": "ai_observations",
+ "columnsTo": [
+ "id"
+ ],
+ "onUpdate": "no action",
+ "onDelete": "cascade"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "ai_observations": {
+ "name": "ai_observations",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "run_id": {
+ "name": "run_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "prompt_id": {
+ "name": "prompt_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "engine": {
+ "name": "engine",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "branded": {
+ "name": "branded",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "status": {
+ "name": "status",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'pending'"
+ },
+ "collected_at": {
+ "name": "collected_at",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "answer_markdown": {
+ "name": "answer_markdown",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "error": {
+ "name": "error",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "ai_observations_run_prompt_engine_idx": {
+ "name": "ai_observations_run_prompt_engine_idx",
+ "columns": [
+ "run_id",
+ "prompt_id",
+ "engine"
+ ],
+ "isUnique": true
+ },
+ "ai_observations_prompt_idx": {
+ "name": "ai_observations_prompt_idx",
+ "columns": [
+ "prompt_id"
+ ],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {
+ "ai_observations_run_id_ai_runs_id_fk": {
+ "name": "ai_observations_run_id_ai_runs_id_fk",
+ "tableFrom": "ai_observations",
+ "columnsFrom": [
+ "run_id"
+ ],
+ "tableTo": "ai_runs",
+ "columnsTo": [
+ "id"
+ ],
+ "onUpdate": "no action",
+ "onDelete": "cascade"
+ },
+ "ai_observations_prompt_id_ai_prompts_id_fk": {
+ "name": "ai_observations_prompt_id_ai_prompts_id_fk",
+ "tableFrom": "ai_observations",
+ "columnsFrom": [
+ "prompt_id"
+ ],
+ "tableTo": "ai_prompts",
+ "columnsTo": [
+ "id"
+ ],
+ "onUpdate": "no action",
+ "onDelete": "cascade"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "ai_prompts": {
+ "name": "ai_prompts",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "tracker_id": {
+ "name": "tracker_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "topic": {
+ "name": "topic",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "text": {
+ "name": "text",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "paused": {
+ "name": "paused",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": false
+ },
+ "archived": {
+ "name": "archived",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "ai_prompts_tracker_idx": {
+ "name": "ai_prompts_tracker_idx",
+ "columns": [
+ "tracker_id"
+ ],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {
+ "ai_prompts_tracker_id_ai_trackers_id_fk": {
+ "name": "ai_prompts_tracker_id_ai_trackers_id_fk",
+ "tableFrom": "ai_prompts",
+ "columnsFrom": [
+ "tracker_id"
+ ],
+ "tableTo": "ai_trackers",
+ "columnsTo": [
+ "id"
+ ],
+ "onUpdate": "no action",
+ "onDelete": "cascade"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "ai_runs": {
+ "name": "ai_runs",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "tracker_id": {
+ "name": "tracker_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "project_id": {
+ "name": "project_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "trigger": {
+ "name": "trigger",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "status": {
+ "name": "status",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'queued'"
+ },
+ "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
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "completed_at": {
+ "name": "completed_at",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "ai_runs_project_created_idx": {
+ "name": "ai_runs_project_created_idx",
+ "columns": [
+ "project_id",
+ "created_at"
+ ],
+ "isUnique": false
+ },
+ "ai_runs_one_active_idx": {
+ "name": "ai_runs_one_active_idx",
+ "columns": [
+ "tracker_id"
+ ],
+ "where": "\"ai_runs\".\"status\" IN ('queued', 'running')",
+ "isUnique": true
+ }
+ },
+ "foreignKeys": {
+ "ai_runs_tracker_id_ai_trackers_id_fk": {
+ "name": "ai_runs_tracker_id_ai_trackers_id_fk",
+ "tableFrom": "ai_runs",
+ "columnsFrom": [
+ "tracker_id"
+ ],
+ "tableTo": "ai_trackers",
+ "columnsTo": [
+ "id"
+ ],
+ "onUpdate": "no action",
+ "onDelete": "cascade"
+ },
+ "ai_runs_project_id_projects_id_fk": {
+ "name": "ai_runs_project_id_projects_id_fk",
+ "tableFrom": "ai_runs",
+ "columnsFrom": [
+ "project_id"
+ ],
+ "tableTo": "projects",
+ "columnsTo": [
+ "id"
+ ],
+ "onUpdate": "no action",
+ "onDelete": "cascade"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "ai_sources": {
+ "name": "ai_sources",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "observation_id": {
+ "name": "observation_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "url": {
+ "name": "url",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "domain": {
+ "name": "domain",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "title": {
+ "name": "title",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "position": {
+ "name": "position",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "ai_sources_observation_idx": {
+ "name": "ai_sources_observation_idx",
+ "columns": [
+ "observation_id"
+ ],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {
+ "ai_sources_observation_id_ai_observations_id_fk": {
+ "name": "ai_sources_observation_id_ai_observations_id_fk",
+ "tableFrom": "ai_sources",
+ "columnsFrom": [
+ "observation_id"
+ ],
+ "tableTo": "ai_observations",
+ "columnsTo": [
+ "id"
+ ],
+ "onUpdate": "no action",
+ "onDelete": "cascade"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "ai_trackers": {
+ "name": "ai_trackers",
+ "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
+ },
+ "enabled": {
+ "name": "enabled",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": false
+ },
+ "chatgpt": {
+ "name": "chatgpt",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": true
+ },
+ "gemini": {
+ "name": "gemini",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": false
+ },
+ "claude": {
+ "name": "claude",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": false
+ },
+ "perplexity": {
+ "name": "perplexity",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": false
+ },
+ "google_ai_overview": {
+ "name": "google_ai_overview",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 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'"
+ },
+ "schedule_interval": {
+ "name": "schedule_interval",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'weekly'"
+ },
+ "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
+ }
+ },
+ "indexes": {
+ "ai_trackers_project_idx": {
+ "name": "ai_trackers_project_idx",
+ "columns": [
+ "project_id"
+ ],
+ "isUnique": true
+ },
+ "ai_trackers_due_idx": {
+ "name": "ai_trackers_due_idx",
+ "columns": [
+ "enabled",
+ "next_check_at"
+ ],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {
+ "ai_trackers_project_id_projects_id_fk": {
+ "name": "ai_trackers_project_id_projects_id_fk",
+ "tableFrom": "ai_trackers",
+ "columnsFrom": [
+ "project_id"
+ ],
+ "tableTo": "projects",
+ "columnsTo": [
+ "id"
+ ],
+ "onUpdate": "no action",
+ "onDelete": "cascade"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "local_rank_businesses": {
+ "name": "local_rank_businesses",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "scan_id": {
+ "name": "scan_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "identity": {
+ "name": "identity",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "title": {
+ "name": "title",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "cid": {
+ "name": "cid",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "place_id": {
+ "name": "place_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "address": {
+ "name": "address",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "rating": {
+ "name": "rating",
+ "type": "real",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "reviews": {
+ "name": "reviews",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "local_rank_businesses_scan_identity_idx": {
+ "name": "local_rank_businesses_scan_identity_idx",
+ "columns": [
+ "scan_id",
+ "identity"
+ ],
+ "isUnique": true
+ }
+ },
+ "foreignKeys": {
+ "local_rank_businesses_scan_id_local_rank_scans_id_fk": {
+ "name": "local_rank_businesses_scan_id_local_rank_scans_id_fk",
+ "tableFrom": "local_rank_businesses",
+ "columnsFrom": [
+ "scan_id"
+ ],
+ "tableTo": "local_rank_scans",
+ "columnsTo": [
+ "id"
+ ],
+ "onUpdate": "no action",
+ "onDelete": "cascade"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "local_rank_checks": {
+ "name": "local_rank_checks",
+ "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
+ },
+ "tracker_id": {
+ "name": "tracker_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "status": {
+ "name": "status",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "error": {
+ "name": "error",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "completed_at": {
+ "name": "completed_at",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "local_rank_checks_tracker_created_idx": {
+ "name": "local_rank_checks_tracker_created_idx",
+ "columns": [
+ "tracker_id",
+ "created_at"
+ ],
+ "isUnique": false
+ },
+ "local_rank_checks_one_active_idx": {
+ "name": "local_rank_checks_one_active_idx",
+ "columns": [
+ "tracker_id"
+ ],
+ "where": "\"local_rank_checks\".\"status\" IN ('queued', 'running')",
+ "isUnique": true
+ }
+ },
+ "foreignKeys": {
+ "local_rank_checks_project_id_projects_id_fk": {
+ "name": "local_rank_checks_project_id_projects_id_fk",
+ "tableFrom": "local_rank_checks",
+ "columnsFrom": [
+ "project_id"
+ ],
+ "tableTo": "projects",
+ "columnsTo": [
+ "id"
+ ],
+ "onUpdate": "no action",
+ "onDelete": "cascade"
+ },
+ "local_rank_checks_tracker_id_local_rank_trackers_id_fk": {
+ "name": "local_rank_checks_tracker_id_local_rank_trackers_id_fk",
+ "tableFrom": "local_rank_checks",
+ "columnsFrom": [
+ "tracker_id"
+ ],
+ "tableTo": "local_rank_trackers",
+ "columnsTo": [
+ "id"
+ ],
+ "onUpdate": "no action",
+ "onDelete": "cascade"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "local_rank_keywords": {
+ "name": "local_rank_keywords",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "tracker_id": {
+ "name": "tracker_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "keyword": {
+ "name": "keyword",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "archived_at": {
+ "name": "archived_at",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "local_rank_keywords_tracker_keyword_idx": {
+ "name": "local_rank_keywords_tracker_keyword_idx",
+ "columns": [
+ "tracker_id",
+ "keyword"
+ ],
+ "isUnique": true
+ }
+ },
+ "foreignKeys": {
+ "local_rank_keywords_tracker_id_local_rank_trackers_id_fk": {
+ "name": "local_rank_keywords_tracker_id_local_rank_trackers_id_fk",
+ "tableFrom": "local_rank_keywords",
+ "columnsFrom": [
+ "tracker_id"
+ ],
+ "tableTo": "local_rank_trackers",
+ "columnsTo": [
+ "id"
+ ],
+ "onUpdate": "no action",
+ "onDelete": "cascade"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "local_rank_points": {
+ "name": "local_rank_points",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "scan_id": {
+ "name": "scan_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "row": {
+ "name": "row",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "col": {
+ "name": "col",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "latitude": {
+ "name": "latitude",
+ "type": "real",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "longitude": {
+ "name": "longitude",
+ "type": "real",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "status": {
+ "name": "status",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "rank": {
+ "name": "rank",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "results_count": {
+ "name": "results_count",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "error": {
+ "name": "error",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "collected_at": {
+ "name": "collected_at",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "local_rank_points_scan_position_idx": {
+ "name": "local_rank_points_scan_position_idx",
+ "columns": [
+ "scan_id",
+ "row",
+ "col"
+ ],
+ "isUnique": true
+ }
+ },
+ "foreignKeys": {
+ "local_rank_points_scan_id_local_rank_scans_id_fk": {
+ "name": "local_rank_points_scan_id_local_rank_scans_id_fk",
+ "tableFrom": "local_rank_points",
+ "columnsFrom": [
+ "scan_id"
+ ],
+ "tableTo": "local_rank_scans",
+ "columnsTo": [
+ "id"
+ ],
+ "onUpdate": "no action",
+ "onDelete": "cascade"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "local_rank_results": {
+ "name": "local_rank_results",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "point_id": {
+ "name": "point_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "business_id": {
+ "name": "business_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "rank": {
+ "name": "rank",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "local_rank_results_point_business_idx": {
+ "name": "local_rank_results_point_business_idx",
+ "columns": [
+ "point_id",
+ "business_id"
+ ],
+ "isUnique": true
+ },
+ "local_rank_results_business_idx": {
+ "name": "local_rank_results_business_idx",
+ "columns": [
+ "business_id"
+ ],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {
+ "local_rank_results_point_id_local_rank_points_id_fk": {
+ "name": "local_rank_results_point_id_local_rank_points_id_fk",
+ "tableFrom": "local_rank_results",
+ "columnsFrom": [
+ "point_id"
+ ],
+ "tableTo": "local_rank_points",
+ "columnsTo": [
+ "id"
+ ],
+ "onUpdate": "no action",
+ "onDelete": "cascade"
+ },
+ "local_rank_results_business_id_local_rank_businesses_id_fk": {
+ "name": "local_rank_results_business_id_local_rank_businesses_id_fk",
+ "tableFrom": "local_rank_results",
+ "columnsFrom": [
+ "business_id"
+ ],
+ "tableTo": "local_rank_businesses",
+ "columnsTo": [
+ "id"
+ ],
+ "onUpdate": "no action",
+ "onDelete": "cascade"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "local_rank_scans": {
+ "name": "local_rank_scans",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "check_id": {
+ "name": "check_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "project_id": {
+ "name": "project_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "tracker_id": {
+ "name": "tracker_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "keyword_id": {
+ "name": "keyword_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "status": {
+ "name": "status",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "error": {
+ "name": "error",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "completed_at": {
+ "name": "completed_at",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "local_rank_scans_tracker_created_idx": {
+ "name": "local_rank_scans_tracker_created_idx",
+ "columns": [
+ "tracker_id",
+ "created_at"
+ ],
+ "isUnique": false
+ },
+ "local_rank_scans_project_idx": {
+ "name": "local_rank_scans_project_idx",
+ "columns": [
+ "project_id"
+ ],
+ "isUnique": false
+ },
+ "local_rank_scans_check_keyword_idx": {
+ "name": "local_rank_scans_check_keyword_idx",
+ "columns": [
+ "check_id",
+ "keyword_id"
+ ],
+ "isUnique": true
+ }
+ },
+ "foreignKeys": {
+ "local_rank_scans_check_id_local_rank_checks_id_fk": {
+ "name": "local_rank_scans_check_id_local_rank_checks_id_fk",
+ "tableFrom": "local_rank_scans",
+ "columnsFrom": [
+ "check_id"
+ ],
+ "tableTo": "local_rank_checks",
+ "columnsTo": [
+ "id"
+ ],
+ "onUpdate": "no action",
+ "onDelete": "cascade"
+ },
+ "local_rank_scans_project_id_projects_id_fk": {
+ "name": "local_rank_scans_project_id_projects_id_fk",
+ "tableFrom": "local_rank_scans",
+ "columnsFrom": [
+ "project_id"
+ ],
+ "tableTo": "projects",
+ "columnsTo": [
+ "id"
+ ],
+ "onUpdate": "no action",
+ "onDelete": "cascade"
+ },
+ "local_rank_scans_tracker_id_local_rank_trackers_id_fk": {
+ "name": "local_rank_scans_tracker_id_local_rank_trackers_id_fk",
+ "tableFrom": "local_rank_scans",
+ "columnsFrom": [
+ "tracker_id"
+ ],
+ "tableTo": "local_rank_trackers",
+ "columnsTo": [
+ "id"
+ ],
+ "onUpdate": "no action",
+ "onDelete": "cascade"
+ },
+ "local_rank_scans_keyword_id_local_rank_keywords_id_fk": {
+ "name": "local_rank_scans_keyword_id_local_rank_keywords_id_fk",
+ "tableFrom": "local_rank_scans",
+ "columnsFrom": [
+ "keyword_id"
+ ],
+ "tableTo": "local_rank_keywords",
+ "columnsTo": [
+ "id"
+ ],
+ "onUpdate": "no action",
+ "onDelete": "cascade"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "local_rank_trackers": {
+ "name": "local_rank_trackers",
+ "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
+ },
+ "address": {
+ "name": "address",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "cid": {
+ "name": "cid",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "place_id": {
+ "name": "place_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "latitude": {
+ "name": "latitude",
+ "type": "real",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "longitude": {
+ "name": "longitude",
+ "type": "real",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "grid_size": {
+ "name": "grid_size",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "spacing_km": {
+ "name": "spacing_km",
+ "type": "real",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "language_code": {
+ "name": "language_code",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "local_rank_trackers_project_idx": {
+ "name": "local_rank_trackers_project_idx",
+ "columns": [
+ "project_id"
+ ],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {
+ "local_rank_trackers_project_id_projects_id_fk": {
+ "name": "local_rank_trackers_project_id_projects_id_fk",
+ "tableFrom": "local_rank_trackers",
+ "columnsFrom": [
+ "project_id"
+ ],
+ "tableTo": "projects",
+ "columnsTo": [
+ "id"
+ ],
+ "onUpdate": "no action",
+ "onDelete": "cascade"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ }
+ },
+ "views": {},
+ "enums": {},
+ "_meta": {
+ "columns": {},
+ "schemas": {},
+ "tables": {}
+ },
+ "internal": {
+ "indexes": {}
+ }
+}
\ No newline at end of file
diff --git a/drizzle/sqlite/meta/_journal.json b/drizzle/sqlite/meta/_journal.json
index 98c4b44c..1e85a73b 100644
--- a/drizzle/sqlite/meta/_journal.json
+++ b/drizzle/sqlite/meta/_journal.json
@@ -435,6 +435,13 @@
"when": 1792647300707,
"tag": "0061_bumpy_fat_cobra",
"breakpoints": true
+ },
+ {
+ "idx": 62,
+ "version": "6",
+ "when": 1792713962596,
+ "tag": "0062_bind_api_keys_to_organization",
+ "breakpoints": true
}
]
}
\ No newline at end of file
diff --git a/package.json b/package.json
index de7e2272..83d2b040 100644
--- a/package.json
+++ b/package.json
@@ -47,6 +47,7 @@
"test:ci": "vitest run --reporter=dot",
"test:e2e": "playwright test -c tests/playwright.config.ts",
"test:e2e:free-tools": "playwright test -c tests/playwright.free-tools.config.ts",
+ "test:e2e:mcp-isolation": "playwright test -c tests/playwright.mcp-isolation.config.ts",
"test:e2e:domain": "playwright test -c tests/playwright.config.ts tests/domain-overview-filters.spec.ts",
"test:e2e:domain:perf": "playwright test -c tests/playwright.config.ts tests/domain-overview-filters.perf.spec.ts",
"test:e2e:keywords": "playwright test -c tests/playwright.config.ts tests/keyword-research-navigation.spec.ts",
diff --git a/src/client/features/settings/ApiKeySettings.tsx b/src/client/features/settings/ApiKeySettings.tsx
index 6550d994..68675128 100644
--- a/src/client/features/settings/ApiKeySettings.tsx
+++ b/src/client/features/settings/ApiKeySettings.tsx
@@ -29,6 +29,7 @@ import {
TableRow,
} from "@/client/components/ui/table";
import { CopyButton } from "@/client/components/CopyButton";
+import { useOrganizations } from "@/client/features/settings/useOrganizations";
import { captureClientEvent } from "@/client/lib/posthog";
import { authClient } from "@/lib/auth-client";
@@ -39,6 +40,13 @@ const createKeySchema = z.object({
name: z.string().trim().min(1, "Name is required"),
});
+// Stamped server-side when the key is created (see the /api-key/create hook
+// in lib/auth.ts). Older keys were backfilled; only keys whose user had no
+// organization at the time have none.
+const apiKeyMetadataSchema = z.looseObject({
+ organizationId: z.string().optional(),
+});
+
export function ApiKeySettings() {
const queryClient = useQueryClient();
const [isCreateOpen, setIsCreateOpen] = useState(false);
@@ -46,6 +54,11 @@ export function ApiKeySettings() {
const [revoking, setRevoking] = useState<{ id: string; name: string } | null>(
null,
);
+ const {
+ hasMultiple: showOrganization,
+ activeOrganizationName,
+ organizationName,
+ } = useOrganizations();
const mcpUrl =
typeof window === "undefined"
@@ -65,6 +78,9 @@ export function ApiKeySettings() {
start: key.start,
createdAt: new Date(key.createdAt),
lastRequest: key.lastRequest ? new Date(key.lastRequest) : null,
+ organizationId:
+ apiKeyMetadataSchema.safeParse(key.metadata).data?.organizationId ??
+ null,
}));
},
});
@@ -156,6 +172,9 @@ export function ApiKeySettings() {
<TableRow>
<TableHead>Name</TableHead>
<TableHead>Key</TableHead>
+ {showOrganization ? (
+ <TableHead>Organization</TableHead>
+ ) : null}
<TableHead>Created</TableHead>
<TableHead>Last used</TableHead>
<TableHead className="w-10" />
@@ -173,6 +192,11 @@ export function ApiKeySettings() {
>
{key.start || "oseo_"}…
</TableCell>
+ {showOrganization ? (
+ <TableCell className="text-xs text-muted-foreground">
+ {organizationName(key.organizationId) ?? "—"}
+ </TableCell>
+ ) : null}
<TableCell className="text-xs text-muted-foreground">
{key.createdAt.toLocaleDateString()}
</TableCell>
@@ -284,6 +308,11 @@ export function ApiKeySettings() {
/>
)}
</form.AppField>
+ {showOrganization ? (
+ <p className="text-sm text-muted-foreground">
+ This key works in {activeOrganizationName}.
+ </p>
+ ) : null}
<DialogFooter>
<Button variant="ghost" onClick={closeCreateModal}>
Cancel
diff --git a/src/client/features/settings/McpConnectionsSettings.tsx b/src/client/features/settings/McpConnectionsSettings.tsx
new file mode 100644
index 00000000..87fb1ee8
--- /dev/null
+++ b/src/client/features/settings/McpConnectionsSettings.tsx
@@ -0,0 +1,132 @@
+import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
+import { Unplug } from "lucide-react";
+import { useState } from "react";
+import { toast } from "sonner";
+import { ConfirmDialog } from "@/client/components/ConfirmDialog";
+import { SectionHeader } from "@/client/components/PageHeader";
+import { QueryState } from "@/client/components/QueryState";
+import { RowActionsMenu } from "@/client/components/RowActionsMenu";
+import { DropdownMenuItem } from "@/client/components/ui/dropdown-menu";
+import {
+ Table,
+ TableBody,
+ TableCard,
+ TableCell,
+ TableHead,
+ TableHeader,
+ TableRow,
+} from "@/client/components/ui/table";
+import { useOrganizations } from "@/client/features/settings/useOrganizations";
+import { captureClientEvent } from "@/client/lib/posthog";
+import {
+ listMcpConnections,
+ revokeMcpConnection,
+} from "@/serverFunctions/mcp-connections";
+
+export function McpConnectionsSettings() {
+ const queryClient = useQueryClient();
+ const [disconnecting, setDisconnecting] = useState<{
+ id: string;
+ clientName: string;
+ } | null>(null);
+ const { hasMultiple: showOrganization, organizationName } =
+ useOrganizations();
+
+ const connectionsQuery = useQuery({
+ queryKey: ["mcpConnections"],
+ queryFn: () => listMcpConnections(),
+ });
+
+ const disconnectMutation = useMutation({
+ mutationFn: (grantId: string) => revokeMcpConnection({ data: { grantId } }),
+ onSuccess: () => {
+ captureClientEvent("mcp:connection_revoked");
+ toast.success("Agent disconnected");
+ setDisconnecting(null);
+ void queryClient.invalidateQueries({ queryKey: ["mcpConnections"] });
+ },
+ });
+
+ return (
+ <section className="space-y-3">
+ <SectionHeader title="Connected agents" />
+ <p className="text-sm">AI clients signed in to OpenSEO with OAuth.</p>
+
+ <QueryState
+ query={connectionsQuery}
+ errorFallback="We couldn't load your connected agents."
+ >
+ {(connections) =>
+ connections.length === 0 ? (
+ <p className="text-sm text-muted-foreground">
+ No agents connected yet.
+ </p>
+ ) : (
+ <TableCard>
+ <Table>
+ <TableHeader>
+ <TableRow>
+ <TableHead>Client</TableHead>
+ {showOrganization ? (
+ <TableHead>Organization</TableHead>
+ ) : null}
+ <TableHead>Connected</TableHead>
+ <TableHead className="w-10" />
+ </TableRow>
+ </TableHeader>
+ <TableBody>
+ {connections.map((connection) => (
+ <TableRow key={connection.id}>
+ <TableCell className="max-w-[220px] truncate font-medium">
+ {connection.clientName}
+ </TableCell>
+ {showOrganization ? (
+ <TableCell className="text-xs text-muted-foreground">
+ {organizationName(connection.organizationId) ?? "—"}
+ </TableCell>
+ ) : null}
+ <TableCell className="text-xs text-muted-foreground">
+ {new Date(connection.createdAt).toLocaleDateString()}
+ </TableCell>
+ <TableCell>
+ <RowActionsMenu
+ label={`Actions for ${connection.clientName}`}
+ >
+ <DropdownMenuItem
+ variant="destructive"
+ onClick={() =>
+ setDisconnecting({
+ id: connection.id,
+ clientName: connection.clientName,
+ })
+ }
+ >
+ <Unplug />
+ Disconnect
+ </DropdownMenuItem>
+ </RowActionsMenu>
+ </TableCell>
+ </TableRow>
+ ))}
+ </TableBody>
+ </Table>
+ </TableCard>
+ )
+ }
+ </QueryState>
+
+ {disconnecting ? (
+ <ConfirmDialog
+ title={`Disconnect “${disconnecting.clientName}”?`}
+ confirmLabel="Disconnect"
+ destructive
+ pending={disconnectMutation.isPending}
+ onClose={() => setDisconnecting(null)}
+ onConfirm={() => disconnectMutation.mutate(disconnecting.id)}
+ >
+ It will have to sign in to OpenSEO again.
+ </ConfirmDialog>
+ ) : null}
+ </section>
+ );
+}
diff --git a/src/client/features/settings/useOrganizations.ts b/src/client/features/settings/useOrganizations.ts
new file mode 100644
index 00000000..e9b3c024
--- /dev/null
+++ b/src/client/features/settings/useOrganizations.ts
@@ -0,0 +1,17 @@
+import { useQuery } from "@tanstack/react-query";
+import { organizationContextQueryOptions } from "@/client/features/team/organizationQueries";
+
+// Which organization an agent or key is bound to only matters to people in
+// more than one; everyone else sees no organization labels at all, the same
+// rule as the sidebar switcher.
+export function useOrganizations() {
+ const { data } = useQuery(organizationContextQueryOptions());
+ const organizations = data?.organizations ?? [];
+ return {
+ activeOrganizationName: data?.organizationName ?? null,
+ hasMultiple: organizations.length > 1,
+ organizationName: (organizationId: string | null) =>
+ organizations.find((o) => o.organizationId === organizationId)
+ ?.organizationName ?? null,
+ };
+}
diff --git a/src/lib/auth-api-key.ts b/src/lib/auth-api-key.ts
index 8154e5fe..f95cf354 100644
--- a/src/lib/auth-api-key.ts
+++ b/src/lib/auth-api-key.ts
@@ -7,6 +7,10 @@ export const API_KEY_PREFIX = "oseo_";
export function createApiKeyPlugin() {
return apiKey({
defaultPrefix: API_KEY_PREFIX,
+ // metadata is where the server stamps the key's organization
+ // ({ organizationId }) in the /api-key/create before hook in lib/auth.ts;
+ // the plugin rejects any metadata unless this is on.
+ enableMetadata: true,
// Stored display prefix ("oseo_" + 4 key chars) shown in Settings so keys
// are tellable apart; the plugin default of 6 barely clears the prefix.
startingCharactersConfig: { shouldStore: true, charactersLength: 9 },
diff --git a/src/lib/auth.ts b/src/lib/auth.ts
index 7585eb20..48f365e9 100644
--- a/src/lib/auth.ts
+++ b/src/lib/auth.ts
@@ -1,6 +1,10 @@
import { env } from "cloudflare:workers";
import { betterAuth } from "better-auth";
-import { APIError, createAuthMiddleware } from "better-auth/api";
+import {
+ APIError,
+ createAuthMiddleware,
+ getSessionFromCtx,
+} from "better-auth/api";
import { captcha } from "better-auth/plugins";
import { drizzleAdapter } from "better-auth/adapters/drizzle";
import { tanstackStartCookies } from "better-auth/tanstack-start";
@@ -14,6 +18,7 @@ import { z } from "zod";
import { CURRENT_TERMS_VERSION } from "@/shared/terms";
import { isHostedAuthMode } from "@/lib/auth-mode";
import { createApiKeyPlugin } from "@/lib/auth-api-key";
+import { getActiveOrganizationId } from "@/lib/auth-session";
import { createBaseAuthConfig } from "@/lib/auth-config";
import {
getHostedTurnstileSecretKey,
@@ -221,6 +226,37 @@ function createAuth() {
tanstackStartCookies(),
],
hooks: {
+ // Binds a new MCP API key to the organization the session is working
+ // in, server-side: the /mcp handler reads metadata.organizationId and
+ // bills/authorizes that org for the key's lifetime. The session's
+ // active org is only a hint; the member row is the authorization fact.
+ // Throwing here means an unbound key can never be minted through the
+ // HTTP endpoint. Better Auth merges the returned body over the
+ // request's, so an organizationId the client sends loses to this one.
+ // The owner can still rewrite metadata through /api-key/update, which
+ // gains nothing: a key pointed at an org they are not in fails the
+ // membership check on its next /mcp call, and one pointed at an org
+ // they are in is no different from a key created there.
+ before: createAuthMiddleware(async (ctx) => {
+ if (ctx.path !== "/api-key/create") return;
+ // Minting a credential must see the stored session, not the cookie
+ // cache: a cookie from a session revoked minutes ago must not mint a
+ // key that outlives the revocation. The plugin reuses this lookup.
+ const session = await getSessionFromCtx(ctx, {
+ disableCookieCache: true,
+ });
+ if (!session) throw new APIError("UNAUTHORIZED");
+ const organizationId = getActiveOrganizationId(session);
+ const membership = organizationId
+ ? await AuthRepository.getMembership(session.user.id, organizationId)
+ : null;
+ if (!organizationId || !membership) {
+ throw new APIError("FORBIDDEN", {
+ message: "Select an organization before creating an API key.",
+ });
+ }
+ return { context: { body: { metadata: { organizationId } } } };
+ }),
// Marked when the user creates an MCP API key, the API-key counterpart
// of OAuth's authorize step. Not on each /mcp request: isolates share no
// memory, so every one would re-send it and hit Loops' team-wide rate
diff --git a/src/routes/_app/settings/index.tsx b/src/routes/_app/settings/index.tsx
index 5826f06e..b84b8cff 100644
--- a/src/routes/_app/settings/index.tsx
+++ b/src/routes/_app/settings/index.tsx
@@ -2,6 +2,7 @@ import { createFileRoute } from "@tanstack/react-router";
import { ApiKeySettings } from "@/client/features/settings/ApiKeySettings";
import { SectionHeader } from "@/client/components/PageHeader";
import { ThemePreferenceRadio } from "@/client/components/ThemePreferenceMenuItems";
+import { McpConnectionsSettings } from "@/client/features/settings/McpConnectionsSettings";
import { PrivacySettings } from "@/client/features/settings/PrivacySettings";
import { isHostedClientAuthMode } from "@/lib/auth-mode";
import { version } from "../../../../package.json";
@@ -24,6 +25,8 @@ function PersonalSettings() {
{isHosted ? (
<>
+ <McpConnectionsSettings />
+
<ApiKeySettings />
<PrivacySettings />
diff --git a/src/routes/_authenticated.oauth-consent.tsx b/src/routes/_authenticated.oauth-consent.tsx
index 3b8fb640..25e160b1 100644
--- a/src/routes/_authenticated.oauth-consent.tsx
+++ b/src/routes/_authenticated.oauth-consent.tsx
@@ -1,7 +1,10 @@
+import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { createFileRoute } from "@tanstack/react-router";
-import { Check, Database, KeyRound, User } from "lucide-react";
+import { Building2, Check, Database, KeyRound, User } from "lucide-react";
import { useEffect, useState } from "react";
import { useSession } from "@/lib/auth-client";
+import { clearLastProjectId } from "@/client/lib/active-project";
+import { getStandardErrorMessage } from "@/client/lib/error-messages";
import { captureClientEvent } from "@/client/lib/posthog";
import { Alert, AlertDescription } from "@/client/components/ui/alert";
import { Button } from "@/client/components/ui/button";
@@ -11,6 +14,15 @@ import {
CardHeader,
CardTitle,
} from "@/client/components/ui/card";
+import {
+ Select,
+ SelectContent,
+ SelectItem,
+ SelectTrigger,
+ SelectValue,
+} from "@/client/components/ui/select";
+import { organizationContextQueryOptions } from "@/client/features/team/organizationQueries";
+import { switchOrganization } from "@/serverFunctions/organization";
export const Route = createFileRoute("/_authenticated/oauth-consent")({
component: OAuthConsentPage,
@@ -25,12 +37,17 @@ const SCOPES = [
{
icon: KeyRound,
label: "Act on your behalf via MCP",
- description: "Run tools and write results back to your organization.",
+ description: "Run tools and save results in this workspace.",
},
];
function OAuthConsentPage() {
const { data: session } = useSession();
+ const queryClient = useQueryClient();
+ const { data: organizationContext } = useQuery(
+ organizationContextQueryOptions(),
+ );
+ const organizations = organizationContext?.organizations ?? [];
const [pendingAction, setPendingAction] = useState<
"authorize" | "cancel" | null
>(null);
@@ -40,6 +57,21 @@ function OAuthConsentPage() {
captureClientEvent("mcp:consent_viewed");
}, []);
+ // The grant binds to the session's active workspace when Authorize is
+ // clicked, so switching here is the same switch as the account menu's and
+ // carries over to the app.
+ const switchWorkspace = useMutation({
+ mutationFn: (organizationId: string) =>
+ switchOrganization({ data: { organizationId } }),
+ onMutate: () => setError(null),
+ onSuccess: async () => {
+ // The remembered project belongs to the old workspace.
+ clearLastProjectId();
+ await queryClient.invalidateQueries(organizationContextQueryOptions());
+ },
+ onError: (switchError) => setError(getStandardErrorMessage(switchError)),
+ });
+
async function respond(accept: boolean) {
setError(null);
setPendingAction(accept ? "authorize" : "cancel");
@@ -103,6 +135,53 @@ function OAuthConsentPage() {
<div className="font-medium">{session?.user.email}</div>
</div>
</div>
+ {/* The grant is bound to the active workspace. Which one only
+ matters to people in more than one, the same rule as the account
+ menu switcher and the Settings organization columns. */}
+ {organizations.length > 1 ? (
+ <div className="mt-2 flex items-center gap-3 rounded-lg border border-border bg-muted/50 px-3 py-2 text-sm">
+ <div className="flex size-7 items-center justify-center rounded-full bg-muted">
+ <Building2 className="size-4" />
+ </div>
+ <div className="min-w-0 flex-1">
+ <div className="text-xs text-muted-foreground">Workspace</div>
+ <Select
+ items={organizations.map((organization) => ({
+ value: organization.organizationId,
+ label: organization.organizationName,
+ }))}
+ value={organizationContext?.organizationId ?? null}
+ disabled={switchWorkspace.isPending || pendingAction !== null}
+ onValueChange={(organizationId) => {
+ if (
+ organizationId &&
+ organizationId !== organizationContext?.organizationId
+ ) {
+ switchWorkspace.mutate(organizationId);
+ }
+ }}
+ >
+ <SelectTrigger
+ size="sm"
+ aria-label="Workspace"
+ className="mt-0.5 w-full font-medium"
+ >
+ <SelectValue />
+ </SelectTrigger>
+ <SelectContent>
+ {organizations.map((organization) => (
+ <SelectItem
+ key={organization.organizationId}
+ value={organization.organizationId}
+ >
+ {organization.organizationName}
+ </SelectItem>
+ ))}
+ </SelectContent>
+ </Select>
+ </div>
+ </div>
+ ) : null}
<div className="mt-6">
<div className="text-xs font-medium uppercase tracking-wide text-muted-foreground">
@@ -144,7 +223,7 @@ function OAuthConsentPage() {
type="button"
className="flex-1"
pending={pendingAction === "authorize"}
- disabled={pendingAction !== null}
+ disabled={pendingAction !== null || switchWorkspace.isPending}
onClick={() => void respond(true)}
>
{pendingAction === "authorize" ? "Authorizing..." : "Authorize"}
@@ -152,7 +231,7 @@ function OAuthConsentPage() {
</div>
<p className="mt-6 text-center text-xs text-muted-foreground">
- You can revoke access at any time in Settings.
+ You can disconnect it anytime in Settings under Connected agents.
</p>
</CardContent>
</Card>
diff --git a/src/server/auth/default-hosted-organization.ts b/src/server/auth/default-hosted-organization.ts
index c24e794d..39bd79aa 100644
--- a/src/server/auth/default-hosted-organization.ts
+++ b/src/server/auth/default-hosted-organization.ts
@@ -151,21 +151,6 @@ export async function resolveActiveHostedOrganization(
return created;
}
-// Same as resolveActiveHostedOrganization, but never mints a default
-// organization. Used by API-key authentication: a user with no memberships has
-// no org to bill or authorize, so credentials should be rejected instead of
-// silently spinning up a new workspace.
-export async function resolveExistingActiveHostedOrganization(
- userId: string,
-): Promise<ActiveHostedOrganization | null> {
- const existing = await findExistingActiveOrganization(userId);
- if (!existing) {
- return null;
- }
- await repairDubReferralPin(userId);
- return existing;
-}
-
// Sign-in (session-create hook) variant: same resolution, except a user with
// no memberships and a pending invitation gets NO auto-minted personal
// organization — someone who signs up from an invite link should end up in
diff --git a/src/server/features/projects/services/ProjectService.ts b/src/server/features/projects/services/ProjectService.ts
index f3c228d6..5cbe48a5 100644
--- a/src/server/features/projects/services/ProjectService.ts
+++ b/src/server/features/projects/services/ProjectService.ts
@@ -2,7 +2,6 @@ import {
archiveProject,
createProject,
getProjectForOrganization,
- getProjectWithOrganization,
listArchivedProjects,
listProjects,
listProjectsEnsuringOne,
@@ -21,5 +20,4 @@ export const ProjectService = {
restoreProject,
listArchivedProjects,
getProjectForOrganization,
- getProjectWithOrganization,
} as const;
diff --git a/src/server/features/projects/services/projects.ts b/src/server/features/projects/services/projects.ts
index 86bbc2d1..2a486deb 100644
--- a/src/server/features/projects/services/projects.ts
+++ b/src/server/features/projects/services/projects.ts
@@ -206,18 +206,6 @@ export async function getProjectForOrganization(
return mapProject(project);
}
-// Project lookup that reveals which org owns it, for user-scoped credentials
-// (MCP API keys): the caller derives the org FROM the project and must then
-// authorize the user's membership in that org before acting on the result.
-export async function getProjectWithOrganization(projectId: string) {
- const project = await ProjectRepository.getProjectById(projectId);
- if (!project) return null;
- return {
- organizationId: project.organizationId,
- project: mapProject(project),
- };
-}
-
export async function setProjectWebsite(
organizationId: string,
input: SetProjectWebsiteInput,
diff --git a/src/server/features/sam/SamChatAgent.ts b/src/server/features/sam/SamChatAgent.ts
index d2faca34..438b50cf 100644
--- a/src/server/features/sam/SamChatAgent.ts
+++ b/src/server/features/sam/SamChatAgent.ts
@@ -370,9 +370,6 @@ export class SamChatAgent extends Think {
userEmail: ctx.userEmail,
organizationId,
role: membership?.role ?? "owner",
- // SAM sessions belong to one project's workspace; org context is
- // fixed for the session, like an OAuth token's.
- orgScope: "pinned",
baseUrl,
clientId: null,
scopes: [MCP_SCOPE],
diff --git a/src/server/mcp/api-key-auth.test.ts b/src/server/mcp/api-key-auth.test.ts
index beb8ba7f..99589a96 100644
--- a/src/server/mcp/api-key-auth.test.ts
+++ b/src/server/mcp/api-key-auth.test.ts
@@ -6,7 +6,7 @@ import type { handleAuthenticatedOpenSeoMcpRequest } from "@/server/mcp/transpor
const mocks = vi.hoisted(() => ({
verifyApiKey: vi.fn(),
getHostedUser: vi.fn(),
- resolveExistingActiveHostedOrganization: vi.fn(),
+ getMembership: vi.fn(),
recordMcpAuthorized: vi.fn(),
handleAuthenticatedOpenSeoMcpRequest:
vi.fn<typeof handleAuthenticatedOpenSeoMcpRequest>(),
@@ -25,14 +25,10 @@ vi.mock("@/lib/auth", () => ({
vi.mock("@/server/auth/repositories/AuthRepository", () => ({
AuthRepository: {
getHostedUser: mocks.getHostedUser,
+ getMembership: mocks.getMembership,
},
}));
-vi.mock("@/server/auth/default-hosted-organization", () => ({
- resolveExistingActiveHostedOrganization:
- mocks.resolveExistingActiveHostedOrganization,
-}));
-
vi.mock("@/server/features/activation/mcpActivation", () => ({
recordMcpAuthorized: mocks.recordMcpAuthorized,
}));
@@ -55,16 +51,20 @@ function request(headers?: HeadersInit, method = "POST") {
return new Request("https://app.openseo.so/mcp", { method, headers });
}
+// What verifyApiKey returns for a key bound to org-1 at creation.
+const boundKey = {
+ valid: true,
+ error: null,
+ key: { referenceId: "user-1", metadata: { organizationId: "org-1" } },
+};
+
describe("handleMcpApiKeyRequest", () => {
beforeEach(() => {
mocks.getHostedUser.mockResolvedValue({
id: "user-1",
});
- mocks.resolveExistingActiveHostedOrganization.mockResolvedValue({
- organizationId: "org-1",
- role: "owner",
- });
+ mocks.getMembership.mockResolvedValue({ role: "owner" });
mocks.recordMcpAuthorized.mockResolvedValue(undefined);
mocks.handleAuthenticatedOpenSeoMcpRequest.mockResolvedValue(
new Response("mcp response"),
@@ -76,13 +76,9 @@ describe("handleMcpApiKeyRequest", () => {
["case-insensitive bearer", { Authorization: "bearer oseo_secret" }],
["x-api-key", { "x-api-key": "oseo_secret" }],
])(
- "handles a valid key sent as %s with the hosted user, organization, and MCP scopes",
+ "handles a valid key sent as %s with the hosted user, its bound organization, and MCP scopes",
async (_label, headers) => {
- mocks.verifyApiKey.mockResolvedValue({
- valid: true,
- error: null,
- key: { referenceId: "user-1" },
- });
+ mocks.verifyApiKey.mockResolvedValue(boundKey);
const mcpRequest = request(headers);
const response = await handleMcpApiKeyRequest(mcpRequest, env, ctx);
@@ -91,9 +87,9 @@ describe("handleMcpApiKeyRequest", () => {
expect(mocks.verifyApiKey).toHaveBeenCalledWith({
body: { key: "oseo_secret" },
});
- expect(
- mocks.resolveExistingActiveHostedOrganization,
- ).toHaveBeenCalledWith("user-1");
+ // The org comes from the key's metadata; the role from the live member
+ // row in that org.
+ expect(mocks.getMembership).toHaveBeenCalledWith("user-1", "org-1");
expect(mocks.recordMcpAuthorized).toHaveBeenCalledWith("org-1");
expect(mocks.handleAuthenticatedOpenSeoMcpRequest).toHaveBeenCalledTimes(
1,
@@ -117,13 +113,32 @@ describe("handleMcpApiKeyRequest", () => {
},
);
- it("returns 403 when the user has no organization membership", async () => {
+ // A key that predates the org binding and was not backfilled is dead, not
+ // rebound to whatever org the user is in now.
+ it("returns 403 for a key with no organization in its metadata", async () => {
mocks.verifyApiKey.mockResolvedValue({
valid: true,
error: null,
- key: { referenceId: "user-1" },
+ key: { referenceId: "user-1", metadata: null },
+ });
+
+ const response = await handleMcpApiKeyRequest(
+ request({ Authorization: "Bearer oseo_secret" }),
+ env,
+ ctx,
+ );
+
+ expect(response?.status).toBe(403);
+ await expect(response?.json()).resolves.toMatchObject({
+ error: "account_access_revoked",
});
- mocks.resolveExistingActiveHostedOrganization.mockResolvedValue(null);
+ expect(mocks.getMembership).not.toHaveBeenCalled();
+ expect(mocks.handleAuthenticatedOpenSeoMcpRequest).not.toHaveBeenCalled();
+ });
+
+ it("returns 403 when the user was removed from the key's organization", async () => {
+ mocks.verifyApiKey.mockResolvedValue(boundKey);
+ mocks.getMembership.mockResolvedValue(null);
const response = await handleMcpApiKeyRequest(
request({ Authorization: "Bearer oseo_secret" }),
@@ -160,11 +175,7 @@ describe("handleMcpApiKeyRequest", () => {
});
it("returns 429 with Retry-After when the MCP_RATE_LIMIT binding denies", async () => {
- mocks.verifyApiKey.mockResolvedValue({
- valid: true,
- error: null,
- key: { referenceId: "user-1" },
- });
+ mocks.verifyApiKey.mockResolvedValue(boundKey);
const limit = vi.fn().mockResolvedValue({ success: false });
const response = await handleMcpApiKeyRequest(
diff --git a/src/server/mcp/api-key-auth.ts b/src/server/mcp/api-key-auth.ts
index 001b24a1..46d559c7 100644
--- a/src/server/mcp/api-key-auth.ts
+++ b/src/server/mcp/api-key-auth.ts
@@ -1,11 +1,18 @@
+import { z } from "zod";
import { getAuth, getHostedBaseUrl } from "@/lib/auth";
import { API_KEY_PREFIX } from "@/lib/auth-api-key";
import { MCP_OAUTH_SCOPES } from "@/lib/oauth-resource";
-import { resolveExistingActiveHostedOrganization } from "@/server/auth/default-hosted-organization";
import { AuthRepository } from "@/server/auth/repositories/AuthRepository";
import { recordMcpAuthorized } from "@/server/features/activation/mcpActivation";
import { createWorkersOAuthMcpProps, MCP_ROUTE } from "@/server/mcp/context";
+// Stamped server-side at creation by the /api-key/create before hook in
+// lib/auth.ts (and backfilled for older keys by migration), never by the
+// client. The plugin stores it as JSON text and parses it on read.
+const apiKeyMetadataSchema = z.looseObject({
+ organizationId: z.string().min(1),
+});
+
function getApiKey(request: Request) {
// Both branches require the oseo_ prefix: anything else (a Cloudflare OAuth
// access token, a stray foreign x-api-key header) falls through to the
@@ -125,29 +132,32 @@ export async function handleMcpApiKeyRequest(
const user = await AuthRepository.getHostedUser(userId);
if (!user?.email) return apiKeyErrorResponse(null);
- // API keys bill the user's active organization. Keys are user-scoped and
- // the org derives from the project each tool call names (project-level
- // authz) — not key→org binding. Fail closed if the user has no existing
- // memberships; we never mint a default organization for an API key.
- const resolved = await resolveExistingActiveHostedOrganization(userId);
- if (!resolved) {
+ // A key is bound to the organization that was active when it was created
+ // and bills that org. The member row is the authorization fact, re-read
+ // per request so removing a member kills their keys immediately; the role
+ // is never stored on the key. A key with no organization predates the
+ // binding and was not backfilled, so it fails the same way rather than
+ // being rebound to some other org.
+ const organizationId = apiKeyMetadataSchema.safeParse(result.key.metadata)
+ .data?.organizationId;
+ const membership = organizationId
+ ? await AuthRepository.getMembership(userId, organizationId)
+ : null;
+ if (!organizationId || !membership) {
return apiKeyErrorResponse({
code: "FORBIDDEN",
- message: "API key is not associated with an organization",
+ message:
+ "This API key's organization access was revoked. Create a new key in Settings.",
});
}
- const { organizationId, role } = resolved;
// clientId "api_key" satisfies the hosted transport's fail-closed props
// schema and counts these calls as external MCP clients in telemetry.
- // The key is the credential, not a key→org binding: the hosted transport
- // stamps orgScope "user", and organizationId above is only the fallback
- // for tools with no project argument.
const props = createWorkersOAuthMcpProps({
userId,
userEmail: user.email,
organizationId,
- role,
+ role: membership.role,
baseUrl: getHostedBaseUrl(),
scopes: [...MCP_OAUTH_SCOPES],
clientId: "api_key",
diff --git a/src/server/mcp/connections.test.ts b/src/server/mcp/connections.test.ts
new file mode 100644
index 00000000..51a984b2
--- /dev/null
+++ b/src/server/mcp/connections.test.ts
@@ -0,0 +1,51 @@
+import { expect, it, vi } from "vitest";
+import { McpConnectionsService } from "./connections";
+
+const helpers = vi.hoisted(() => ({
+ listUserGrants: vi.fn(),
+ lookupClient: vi.fn(),
+ revokeGrant: vi.fn(),
+}));
+
+vi.mock("@/server/mcp/oauth-provider", () => ({
+ getCapturedOAuthHelpers: () => helpers,
+}));
+
+it("lists grants newest first with the client name and bound organization", async () => {
+ helpers.listUserGrants.mockResolvedValue({
+ items: [
+ {
+ id: "grant-old",
+ clientId: "codex",
+ metadata: { organizationId: "org-1" },
+ createdAt: 1_700_000_000,
+ },
+ {
+ id: "grant-new",
+ clientId: "deleted-client",
+ metadata: null,
+ createdAt: 1_700_000_100,
+ },
+ ],
+ });
+ helpers.lookupClient.mockImplementation((clientId: string) =>
+ Promise.resolve(clientId === "codex" ? { clientName: "Codex" } : null),
+ );
+
+ await expect(
+ McpConnectionsService.listMcpConnections("user-1"),
+ ).resolves.toEqual([
+ {
+ id: "grant-new",
+ clientName: "MCP client",
+ createdAt: 1_700_000_100_000,
+ organizationId: null,
+ },
+ {
+ id: "grant-old",
+ clientName: "Codex",
+ createdAt: 1_700_000_000_000,
+ organizationId: "org-1",
+ },
+ ]);
+});
diff --git a/src/server/mcp/connections.ts b/src/server/mcp/connections.ts
new file mode 100644
index 00000000..621111ed
--- /dev/null
+++ b/src/server/mcp/connections.ts
@@ -0,0 +1,47 @@
+import { sortBy } from "remeda";
+import { z } from "zod";
+import { getCapturedOAuthHelpers } from "@/server/mcp/oauth-provider";
+
+// The OAuth grants behind "Connected agents" in Settings. Grants live under
+// the KV key grant:{userId}:{grantId}, so listUserGrants and revokeGrant can
+// only ever reach the caller's own grants.
+
+const grantMetadataSchema = z.looseObject({
+ organizationId: z.string().optional(),
+});
+
+async function listMcpConnections(userId: string) {
+ const oauth = getCapturedOAuthHelpers();
+ // One page: a person has a handful of agents, and a page holds a thousand.
+ const { items: grants } = await oauth.listUserGrants(userId);
+
+ const connections = await Promise.all(
+ grants.map(async (grant) => {
+ const client = await oauth.lookupClient(grant.clientId);
+ return {
+ id: grant.id,
+ clientName: client?.clientName ?? "MCP client",
+ // The provider stores Unix seconds.
+ createdAt: grant.createdAt * 1000,
+ // Named on the client from the organizations the user belongs to,
+ // the same way the API keys table does it.
+ organizationId:
+ grantMetadataSchema.safeParse(grant.metadata).data?.organizationId ??
+ null,
+ };
+ }),
+ );
+
+ return sortBy(connections, [(connection) => connection.createdAt, "desc"]);
+}
+
+// Deletes the grant and every access token under it; the client's next call
+// gets 401 and it has to authorize again.
+async function revokeMcpConnection(userId: string, grantId: string) {
+ await getCapturedOAuthHelpers().revokeGrant(grantId, userId);
+}
+
+export const McpConnectionsService = {
+ listMcpConnections,
+ revokeMcpConnection,
+};
diff --git a/src/server/mcp/context.test.ts b/src/server/mcp/context.test.ts
index 75986f7e..89387bea 100644
--- a/src/server/mcp/context.test.ts
+++ b/src/server/mcp/context.test.ts
@@ -16,6 +16,7 @@ describe("OpenSEO tool auth context", () => {
it("prefers standard OAuth client metadata over the props fallback", () => {
const props = createWorkersOAuthMcpProps({
...applicationContext,
+ role: "admin",
clientId: "stale-client",
scopes: ["offline_access"],
});
@@ -35,6 +36,7 @@ describe("OpenSEO tool auth context", () => {
).auth,
).toMatchObject({
...applicationContext,
+ role: "admin",
clientId: "client-1",
scopes: ["mcp"],
});
@@ -43,6 +45,7 @@ describe("OpenSEO tool auth context", () => {
it("reads clientId and scopes from props when authInfo is absent", () => {
const props = createWorkersOAuthMcpProps({
...applicationContext,
+ role: "owner",
clientId: "legacy-client",
scopes: ["mcp"],
});
@@ -53,4 +56,25 @@ describe("OpenSEO tool auth context", () => {
scopes: ["mcp"],
});
});
+
+ // The hosted transport stamps the role from the member row on every
+ // request; hosted props without one skipped that check.
+ it("fails closed when hosted props carry no role", () => {
+ const props = createWorkersOAuthMcpProps({
+ ...applicationContext,
+ clientId: "api_key",
+ scopes: ["mcp"],
+ });
+
+ expect(() => createMcpToolContext({}, props)).toThrow("missing a role");
+ });
+
+ it("defaults self-host props (no client identity) to the implicit owner", () => {
+ const props = createWorkersOAuthMcpProps(applicationContext);
+
+ expect(createMcpToolContext({}, props).auth).toMatchObject({
+ role: "owner",
+ clientId: null,
+ });
+ });
});
diff --git a/src/server/mcp/context.ts b/src/server/mcp/context.ts
index 019b8887..1ec52e77 100644
--- a/src/server/mcp/context.ts
+++ b/src/server/mcp/context.ts
@@ -7,21 +7,18 @@ import { buildDashboardUrl } from "@/server/mcp/urls";
export type ToolAuthContext = {
userId: string;
userEmail: string;
+ // The one organization every tool call is bound to. Hosted credentials
+ // (OAuth grants, API keys) are pinned at creation to the org that was active
+ // then and re-checked against a live membership on every request; self-host
+ // and SAM are bound to their single org / the chat's project org.
organizationId: string;
// Org role for permission gates (owner/admin/member, comma-joined when
// multiple). Hosted: stamped per request from the member row in
// transport.ts. Self-host/delegated: one implicit user per org → "owner".
role: string;
- // How tool calls bind to an organization. "pinned": the request's
- // organizationId is the authorization boundary — self-host and SAM, which
- // have no member rows or are already bound to one project. "user": every
- // hosted credential (OAuth tokens, API keys; stamped by the hosted
- // transport) — project-scoped tools derive the org from the project row and
- // authorize via the caller's membership in THAT org, so one credential works
- // across every organization the user belongs to; organizationId is only the
- // fallback context for the few tools with no project argument.
- orgScope: "pinned" | "user";
scopes: string[];
+ // OAuth client id, the literal "api_key", or null for first-party callers
+ // (self-host transports, SAM). See isHostedMcpClient.
clientId: string | null;
baseUrl: string;
// Which client made the call ("Claude Code", "Codex", "API key", …), for
@@ -50,9 +47,6 @@ const applicationAuthContextSchema = z.object({
// transport, never baked into tokens) and from delegated modes (implicit
// owner).
role: z.string().min(1).optional(),
- // Stamped per request by the hosted transport, never baked into tokens;
- // absent (self-host, SAM) means "pinned".
- orgScope: z.enum(["pinned", "user"]).optional(),
baseUrl: z.string().url(),
// Compatibility fallback until workers-oauth-provider supplies the verified
// context marker consumed by Agents SDK 0.20.x (the
@@ -120,6 +114,13 @@ function readClientTitle(context: ToolCallContext): string | undefined {
return parsed.success ? parsed.data[CLIENT_INFO_META_KEY]?.title : undefined;
}
+// Hosted credentials always carry a client identity: an OAuth client id or
+// "api_key". First-party callers (self-host transports, SAM) have none. Gates
+// hosted-only side effects such as finishing the onboarding wizard.
+export function isHostedMcpClient(auth: Pick<ToolAuthContext, "clientId">) {
+ return auth.clientId !== null;
+}
+
export function createMcpToolContext(
context: ToolCallContext,
props: McpProps,
@@ -135,23 +136,19 @@ export function createMcpToolContext(
const authInfo = context.http?.authInfo;
const clientId = authInfo?.clientId ?? applicationAuth.clientId ?? null;
const scopes = authInfo?.scopes ?? applicationAuth.scopes ?? [];
- const orgScope = applicationAuth.orgScope ?? "pinned";
- // Delegated/self-hosted modes have no member rows and a single implicit owner
- // per org; "pinned" without a role means owner. Hosted ("user" scope)
- // stamps the role from the member row per request in transport.ts.
- const role =
- applicationAuth.role ?? (orgScope === "pinned" ? "owner" : undefined);
- if (!role) {
- throw new Error(
- "MCP auth context is missing a role for a user-scoped credential",
- );
+ // Hosted credentials get their role stamped per request by transport.ts
+ // from the member row; one arriving without it bypassed that check, so fail
+ // closed. Delegated/self-hosted modes have no member rows and a single
+ // implicit owner per org.
+ if (isHostedMcpClient({ clientId }) && !applicationAuth.role) {
+ throw new Error("MCP auth context is missing a role for a hosted client");
}
+ const role = applicationAuth.role ?? "owner";
return {
auth: {
...applicationAuth,
role,
- orgScope,
clientId,
scopes,
clientLabel: resolveClientLabel({
diff --git a/src/server/mcp/instrumentation.test.ts b/src/server/mcp/instrumentation.test.ts
index 3464f8bf..7623a8a8 100644
--- a/src/server/mcp/instrumentation.test.ts
+++ b/src/server/mcp/instrumentation.test.ts
@@ -45,7 +45,6 @@ const authContext: ToolAuthContext = {
userEmail: "[email protected]",
organizationId: "org-1",
role: "owner",
- orgScope: "pinned",
clientId: "client-1",
scopes: ["mcp"],
baseUrl: "https://app.openseo.so",
diff --git a/src/server/mcp/oauth-provider.ts b/src/server/mcp/oauth-provider.ts
index d20076a1..91a704f8 100644
--- a/src/server/mcp/oauth-provider.ts
+++ b/src/server/mcp/oauth-provider.ts
@@ -305,9 +305,10 @@ async function handleOAuthConsentResponse(
);
}
- // organizationId is only the fallback context for tools with no project
- // argument; the hosted transport re-resolves it and stamps orgScope per
- // request, so one authorization follows the user across every organization.
+ // The grant is bound to the organization active at consent: every /mcp
+ // request re-checks the user's membership in exactly this org and 401s once
+ // it is gone (transport.ts). The same id goes into the grant metadata below,
+ // which the Settings "Connected agents" list reads to name the workspace.
const props = createWorkersOAuthMcpProps({
userId: context.userId,
userEmail: context.userEmail,
@@ -350,11 +351,26 @@ async function handleOAuthConsentResponse(
return jsonResponse({ redirectTo });
}
+// The provider sets OAUTH_PROVIDER on the env it hands the default handler,
+// but `import { env } from "cloudflare:workers"` is a different object, so
+// server functions (which run inside appFetch) cannot read it there. The
+// helpers are stateless wrappers over the OAUTH_KV binding, so one module-level
+// reference serves every request.
+let oauthHelpers: OAuthHelpers | undefined;
+
+export function getCapturedOAuthHelpers() {
+ if (!oauthHelpers) {
+ throw new Error("OAuth provider helpers are unavailable");
+ }
+ return oauthHelpers;
+}
+
function createDefaultHandler(
appFetch: AppFetch,
): ExportedHandlerWithFetch<OpenSeoOAuthEnv> {
return {
async fetch(request, env) {
+ oauthHelpers = env.OAUTH_PROVIDER;
const url = new URL(request.url);
if (url.pathname === OAUTH_AUTHORIZE_PATH) {
diff --git a/src/server/mcp/project-auth.test.ts b/src/server/mcp/project-auth.test.ts
index bf0b376a..8dd606a6 100644
--- a/src/server/mcp/project-auth.test.ts
+++ b/src/server/mcp/project-auth.test.ts
@@ -4,20 +4,11 @@ import { makeToolContext } from "@/server/mcp/tools/tool-test-support";
const mocks = vi.hoisted(() => ({
getProjectForOrganization: vi.fn(),
- getProjectWithOrganization: vi.fn(),
- getMembership: vi.fn(),
}));
vi.mock("@/server/features/projects/services/ProjectService", () => ({
ProjectService: {
getProjectForOrganization: mocks.getProjectForOrganization,
- getProjectWithOrganization: mocks.getProjectWithOrganization,
- },
-}));
-
-vi.mock("@/server/auth/repositories/AuthRepository", () => ({
- AuthRepository: {
- getMembership: mocks.getMembership,
},
}));
@@ -34,7 +25,7 @@ describe("withMcpProjectAuth", () => {
});
});
- it("checks project access for the authenticated organization and passes auth, billing, and project context to the handler", async () => {
+ it("checks project access for the credential's organization and passes auth, billing, and project context to the handler", async () => {
const handler = vi.fn().mockReturnValue("ok");
const wrapped = withMcpProjectAuth(handler);
@@ -52,7 +43,6 @@ describe("withMcpProjectAuth", () => {
userEmail: "[email protected]",
organizationId: "org_123",
role: "owner",
- orgScope: "pinned",
clientId: "client_123",
scopes: ["mcp"],
},
@@ -88,77 +78,3 @@ describe("withMcpProjectAuth", () => {
expect(handler).not.toHaveBeenCalled();
});
});
-
-// User-scoped credentials (API keys): the org derives from the project and
-// access is the caller's membership in that org — never the request's
-// organizationId.
-describe("withMcpProjectAuth with a user-scoped credential", () => {
- const userScopedContext = makeToolContext({ orgScope: "user" });
-
- beforeEach(() => {
- mocks.getProjectWithOrganization.mockResolvedValue({
- organizationId: "org_other",
- project: {
- id: "project_123",
- name: "Test",
- locationCode: 2840,
- languageCode: "en",
- },
- });
- mocks.getMembership.mockResolvedValue({ role: "admin" });
- });
-
- it("rebinds auth and billing to the project's org and the member's role there", async () => {
- const userContext = makeToolContext({ orgScope: "user" });
- const handler = vi.fn<
- (
- args: { projectId: string },
- context: {
- auth: { organizationId: string; role: string };
- billing: { organizationId: string };
- },
- ) => string
- >(() => "ok");
-
- await withMcpProjectAuth(handler)(
- { projectId: "project_123" },
- userContext,
- );
-
- expect(mocks.getMembership).toHaveBeenCalledWith("user_123", "org_other");
- expect(mocks.getProjectForOrganization).not.toHaveBeenCalled();
- const [, context] = handler.mock.calls[0];
- expect(context.auth.organizationId).toBe("org_other");
- expect(context.auth.role).toBe("admin");
- expect(context.billing.organizationId).toBe("org_other");
- // Written back so instrumentation credits the project's org.
- expect(userContext.auth.organizationId).toBe("org_other");
- expect(userContext.auth.role).toBe("admin");
- });
-
- it("rejects when the caller has no membership in the project's org", async () => {
- mocks.getMembership.mockResolvedValue(null);
- const handler = vi.fn();
-
- await expect(
- withMcpProjectAuth(handler)(
- { projectId: "project_123" },
- userScopedContext,
- ),
- ).rejects.toThrow("FORBIDDEN");
-
- expect(handler).not.toHaveBeenCalled();
- });
-
- it("rejects an unknown project without leaking whether it exists", async () => {
- mocks.getProjectWithOrganization.mockResolvedValue(null);
- const handler = vi.fn();
-
- await expect(
- withMcpProjectAuth(handler)({ projectId: "missing" }, userScopedContext),
- ).rejects.toThrow("FORBIDDEN");
-
- expect(mocks.getMembership).not.toHaveBeenCalled();
- expect(handler).not.toHaveBeenCalled();
- });
-});
diff --git a/src/server/mcp/project-auth.ts b/src/server/mcp/project-auth.ts
index 4416876f..daa67002 100644
--- a/src/server/mcp/project-auth.ts
+++ b/src/server/mcp/project-auth.ts
@@ -1,4 +1,3 @@
-import { AuthRepository } from "@/server/auth/repositories/AuthRepository";
import { ProjectService } from "@/server/features/projects/services/ProjectService";
import { AppError } from "@/server/lib/errors";
import { buildBillingCustomer, type ToolContext } from "@/server/mcp/context";
@@ -13,41 +12,10 @@ async function requireProjectAccess(
) {
const { baseUrl, ...auth } = toolContext.auth;
- // User-scoped credentials have no org binding: derive the org from the
- // project row, then authorize via the caller's membership in that org. The
- // returned auth is rebound to the project's org + the member's role there,
- // so billing and every downstream org read follow the project.
- if (auth.orgScope === "user") {
- const resolved = await ProjectService.getProjectWithOrganization(projectId);
- const membership = resolved
- ? await AuthRepository.getMembership(auth.userId, resolved.organizationId)
- : null;
- // One FORBIDDEN for both unknown project and non-membership, so probing
- // with foreign project ids can't distinguish "exists" from "no access".
- if (!resolved || !membership) {
- throw new AppError("FORBIDDEN");
- }
-
- const projectAuth = {
- ...auth,
- organizationId: resolved.organizationId,
- role: membership.role,
- };
- // instrumentMcpToolHandler wraps outside this gate and reads
- // toolContext.auth after the handler returns, so the usage event and the
- // activation milestone credit the project's org, not the fallback one.
- toolContext.auth = { ...projectAuth, baseUrl };
- return {
- auth: projectAuth,
- baseUrl,
- billing: buildBillingCustomer(projectAuth, projectId),
- project: resolved.project,
- };
- }
-
- // Authorize the caller-supplied projectId against the token's organization.
- // Assert on the result instead of relying on the lookup throwing, so this
- // stays a hard gate even if the service's error behavior ever changes.
+ // Authorize the caller-supplied projectId against the credential's bound
+ // organization. Assert on the result instead of relying on the lookup
+ // throwing, so this stays a hard gate even if the service's error behavior
+ // ever changes.
const project = await ProjectService.getProjectForOrganization(
auth.organizationId,
projectId,
diff --git a/src/server/mcp/tools/create-project.test.ts b/src/server/mcp/tools/create-project.test.ts
index 4597ff60..094fb9a1 100644
--- a/src/server/mcp/tools/create-project.test.ts
+++ b/src/server/mcp/tools/create-project.test.ts
@@ -4,7 +4,6 @@ import { makeToolContext } from "./tool-test-support";
const mocks = vi.hoisted(() => ({
createProject: vi.fn(),
- listMembershipsForUser: vi.fn(),
markOnboardingCompleted: vi.fn(),
captureServerEvent: vi.fn(),
}));
@@ -32,16 +31,12 @@ vi.mock("@/server/lib/posthog", () => ({
captureServerEvent: mocks.captureServerEvent,
}));
-vi.mock("@/server/auth/repositories/AuthRepository", () => ({
- AuthRepository: {
- listMembershipsForUser: mocks.listMembershipsForUser,
- },
-}));
-
+// makeToolContext's default clientId makes this a hosted (OAuth / API key)
+// caller; clientId null is self-host or SAM.
const toolContext = makeToolContext();
describe("create_project MCP tool", () => {
- it("creates a project scoped to the caller's organization and returns it", async () => {
+ beforeEach(() => {
mocks.createProject.mockResolvedValue({
id: "project_new",
name: "Acme",
@@ -49,7 +44,10 @@ describe("create_project MCP tool", () => {
locationCode: 2840,
languageCode: "en",
});
+ mocks.markOnboardingCompleted.mockResolvedValue(false);
+ });
+ it("creates a project in the credential's organization and returns it", async () => {
const result = await createProjectTool.handler(
{ name: "Acme", domain: "acme.com", locationCode: 2840 },
toolContext,
@@ -70,8 +68,11 @@ describe("create_project MCP tool", () => {
languageCode: "en",
url: "https://open-seo.test/p/project_new",
});
- // Self-host and SAM connections have no onboarding wizard to finish.
- expect(mocks.markOnboardingCompleted).not.toHaveBeenCalled();
+ // The agent did the wizard's main job, so the app skips onboarding.
+ expect(mocks.markOnboardingCompleted).toHaveBeenCalledWith(
+ "user_123",
+ "org_123",
+ );
const first = result.content?.[0];
expect(first?.type).toBe("text");
if (first?.type === "text") {
@@ -95,16 +96,6 @@ describe("create_project MCP tool", () => {
expect(mocks.createProject).not.toHaveBeenCalled();
});
- it("rejects a foreign organizationId on a organization-bound (pinned) connection", async () => {
- await expect(
- createProjectTool.handler(
- { name: "Acme", organizationId: "org_other" },
- toolContext,
- ),
- ).rejects.toThrow("bound to a single organization");
- expect(mocks.createProject).not.toHaveBeenCalled();
- });
-
it("rejects a member role from creating projects", async () => {
const memberContext = makeToolContext({ role: "member" });
@@ -113,62 +104,26 @@ describe("create_project MCP tool", () => {
).rejects.toMatchObject({ code: "FORBIDDEN" });
expect(mocks.createProject).not.toHaveBeenCalled();
});
-});
-// User-scoped credentials (API keys): the target organization must be
-// unambiguous — a single membership resolves implicitly, multiple require an
-// explicit, membership-checked organizationId confirmed with the user.
-describe("create_project with a user-scoped credential", () => {
- const userScopedContext = makeToolContext({ orgScope: "user" });
- const memberships = [
- { organizationId: "org_a", organizationName: "Alpha", role: "owner" },
- { organizationId: "org_b", organizationName: "Beta", role: "admin" },
- ];
-
- beforeEach(() => {
- mocks.createProject.mockResolvedValue({
- id: "project_new",
- name: "Acme",
- domain: null,
- locationCode: 2840,
- languageCode: "en",
- });
- mocks.listMembershipsForUser.mockResolvedValue(memberships);
- mocks.markOnboardingCompleted.mockResolvedValue(false);
- });
-
- it("errors with the organization list when no organizationId is given and the user has several", async () => {
- await expect(
- createProjectTool.handler({ name: "Acme" }, userScopedContext),
- ).rejects.toThrow(/org_a {2}Alpha[\s\S]*org_b {2}Beta/);
- expect(mocks.createProject).not.toHaveBeenCalled();
- });
-
- it("creates in the named organization when the user is a member of it", async () => {
- const userContext = makeToolContext({ orgScope: "user" });
+ it("skips onboarding completion for self-host and SAM callers", async () => {
await createProjectTool.handler(
- { name: "Acme", organizationId: "org_b" },
- userContext,
+ { name: "Acme" },
+ makeToolContext({ clientId: null }),
);
- expect(mocks.createProject).toHaveBeenCalledWith("org_b", {
+ expect(mocks.createProject).toHaveBeenCalledWith("org_123", {
name: "Acme",
});
- // Written back so instrumentation credits the target org.
- expect(userContext.auth).toMatchObject({
- organizationId: "org_b",
- role: "admin",
- });
+ expect(mocks.markOnboardingCompleted).not.toHaveBeenCalled();
});
it("still returns the project when marking onboarding complete fails", async () => {
- mocks.listMembershipsForUser.mockResolvedValue([memberships[0]]);
mocks.markOnboardingCompleted.mockRejectedValue(new Error("db down"));
vi.spyOn(console, "error").mockImplementation(() => {});
const result = await createProjectTool.handler(
{ name: "Acme" },
- userScopedContext,
+ toolContext,
);
// A failed tool call would make the agent retry and duplicate the project.
@@ -177,43 +132,17 @@ describe("create_project with a user-scoped credential", () => {
});
});
- it("rejects a organizationId the user is not a member of", async () => {
- await expect(
- createProjectTool.handler(
- { name: "Acme", organizationId: "org_stranger" },
- userScopedContext,
- ),
- ).rejects.toThrow("not a member");
- expect(mocks.createProject).not.toHaveBeenCalled();
- });
-
- it("resolves implicitly when the user belongs to exactly one organization", async () => {
- mocks.listMembershipsForUser.mockResolvedValue([memberships[0]]);
-
- await createProjectTool.handler({ name: "Acme" }, userScopedContext);
-
- expect(mocks.createProject).toHaveBeenCalledWith("org_a", {
- name: "Acme",
- });
- // The agent did the wizard's main job, so the app skips onboarding.
- expect(mocks.markOnboardingCompleted).toHaveBeenCalledWith(
- "user_123",
- "org_a",
- );
- });
-
it("reports onboarding completion only from the call that completed it", async () => {
- mocks.listMembershipsForUser.mockResolvedValue([memberships[0]]);
mocks.markOnboardingCompleted.mockResolvedValueOnce(true);
- await createProjectTool.handler({ name: "Acme" }, userScopedContext);
- await createProjectTool.handler({ name: "Acme" }, userScopedContext);
+ await createProjectTool.handler({ name: "Acme" }, toolContext);
+ await createProjectTool.handler({ name: "Acme" }, toolContext);
expect(mocks.captureServerEvent).toHaveBeenCalledTimes(1);
expect(mocks.captureServerEvent).toHaveBeenCalledWith({
distinctId: "user_123",
event: "onboarding:completed",
- organizationId: "org_a",
+ organizationId: "org_123",
properties: { via: "agent_project" },
});
});
diff --git a/src/server/mcp/tools/create-project.ts b/src/server/mcp/tools/create-project.ts
index 917012b7..2dbfb0df 100644
--- a/src/server/mcp/tools/create-project.ts
+++ b/src/server/mcp/tools/create-project.ts
@@ -1,10 +1,9 @@
import { requireOrgPermission } from "@/server/auth/org-gate";
-import { AuthRepository } from "@/server/auth/repositories/AuthRepository";
import { completeOnboardingFromAgent } from "@/server/features/activation/mcpActivation";
import { ProjectService } from "@/server/features/projects/services/ProjectService";
import { AppError } from "@/server/lib/errors";
import { mcpResponse } from "@/server/mcp/formatters";
-import { type ToolContext } from "@/server/mcp/context";
+import { isHostedMcpClient, type ToolContext } from "@/server/mcp/context";
import { optionalMetaOutputSchema } from "@/server/mcp/output-schemas";
import { buildDashboardUrl } from "@/server/mcp/urls";
import { languageCodeSchema, locationCodeSchema } from "@/server/mcp/schemas";
@@ -36,69 +35,10 @@ const inputSchema = {
.describe(
'Optional language code (e.g. "en", "fr"). Requires locationCode; derived from the location when omitted.',
),
- organizationId: z
- .string()
- .trim()
- .min(1)
- .optional()
- .describe(
- "Organization id to create the project in. Required when the user belongs to more than one organization — omitting it returns the list; confirm the choice with the user before retrying.",
- ),
} as const;
type Args = z.infer<z.ZodObject<typeof inputSchema>>;
-// Which organization gets the project. Pinned credentials (self-host, SAM)
-// are bound to one org. User-scoped credentials (hosted OAuth tokens and API
-// keys) span organizations, so an ambiguous target is an error listing the
-// options — the agent must confirm the choice with the user rather than
-// guessing.
-async function resolveTargetOrganization(
- auth: Omit<ToolContext["auth"], "baseUrl">,
- organizationId: string | undefined,
-) {
- if (auth.orgScope !== "user") {
- if (organizationId && organizationId !== auth.organizationId) {
- throw new AppError(
- "FORBIDDEN",
- "This connection is bound to a single organization — omit organizationId.",
- );
- }
- return { organizationId: auth.organizationId, role: auth.role };
- }
-
- const memberships = await AuthRepository.listMembershipsForUser(auth.userId);
- if (organizationId) {
- const membership = memberships.find(
- (candidate) => candidate.organizationId === organizationId,
- );
- if (!membership) {
- throw new AppError(
- "FORBIDDEN",
- "The user is not a member of that organization.",
- );
- }
- return { organizationId, role: membership.role };
- }
- if (memberships.length === 1) {
- const only = memberships[0];
- return { organizationId: only.organizationId, role: only.role };
- }
- if (memberships.length === 0) {
- throw new AppError("FORBIDDEN");
- }
- const organizationList = memberships
- .map(
- (membership) =>
- `- ${membership.organizationId} ${membership.organizationName}`,
- )
- .join("\n");
- throw new AppError(
- "VALIDATION_ERROR",
- `The user belongs to ${memberships.length} organizations. Ask the user which organization this project should be created in, then retry with organizationId set:\n${organizationList}`,
- );
-}
-
export const createProjectTool = {
name: "create_project",
config: {
@@ -127,19 +67,13 @@ export const createProjectTool = {
},
handler: async (args: Args, context: ToolContext) => {
const { baseUrl, ...auth } = context.auth;
- const target = await resolveTargetOrganization(auth, args.organizationId);
- // Same as withMcpProjectAuth: instrumentation reads context.auth after
- // the handler, so telemetry credits the target org.
- context.auth = { ...context.auth, ...target };
// Same gate as the createProject server function — MCP and the dashboard
- // must agree on who can create projects. The role is the caller's role
- // in the TARGET organization, not the request-level one.
- requireOrgPermission(target, { project: ["create"] });
+ // must agree on who can create projects.
+ requireOrgPermission(auth, { project: ["create"] });
// Reuse the app's create schema so the market pair rule (a languageCode
// requires a locationCode) and domain normalization match the dashboard.
// A rejection is bad caller input, not a fault: VALIDATION_ERROR keeps it
- // out of error reporting while still naming the bad field. organizationId
- // is stripped here — it was consumed above.
+ // out of error reporting while still naming the bad field.
const parsedInput = createProjectSchema.safeParse(args);
if (!parsedInput.success) {
throw new AppError(
@@ -149,17 +83,14 @@ export const createProjectTool = {
}
const input = parsedInput.data;
const project = await ProjectService.createProject(
- target.organizationId,
+ auth.organizationId,
input,
);
// Hosted users only: self-host and SAM never run the onboarding wizard.
// Best-effort: the project already exists, and an error here would make
// the agent retry and create a duplicate.
- if (auth.orgScope === "user") {
- await completeOnboardingFromAgent(
- { userId: auth.userId, organizationId: target.organizationId },
- "agent_project",
- );
+ if (isHostedMcpClient(auth)) {
+ await completeOnboardingFromAgent(auth, "agent_project");
}
return mcpResponse({
text: `Created project ${project.id} ${project.name}${
diff --git a/src/server/mcp/tools/list-projects.ts b/src/server/mcp/tools/list-projects.ts
index 82d4cf65..f590812c 100644
--- a/src/server/mcp/tools/list-projects.ts
+++ b/src/server/mcp/tools/list-projects.ts
@@ -1,4 +1,3 @@
-import { AuthRepository } from "@/server/auth/repositories/AuthRepository";
import { ProjectService } from "@/server/features/projects/services/ProjectService";
import { mcpResponse } from "@/server/mcp/formatters";
import { type ToolContext } from "@/server/mcp/context";
@@ -6,42 +5,12 @@ import { optionalMetaOutputSchema } from "@/server/mcp/output-schemas";
import { buildDashboardUrl } from "@/server/mcp/urls";
import { z } from "zod";
-// The org(s) whose projects the caller can see. Pinned credentials (self-host,
-// SAM) see the bound org; user-scoped credentials (hosted OAuth tokens and API
-// keys) see every organization the user belongs to, labeled so the agent can
-// tell same-named projects apart.
-async function listVisibleProjects(auth: Omit<ToolContext["auth"], "baseUrl">) {
- if (auth.orgScope !== "user") {
- const projects = await ProjectService.listProjects(auth.organizationId);
- return projects.map((project) => ({
- ...project,
- organization: undefined,
- organizationId: undefined,
- }));
- }
-
- const memberships = await AuthRepository.listMembershipsForUser(auth.userId);
- const byOrg = await Promise.all(
- memberships.map(async (membership) => {
- const projects = await ProjectService.listProjects(
- membership.organizationId,
- );
- return projects.map((project) => ({
- ...project,
- organization: membership.organizationName,
- organizationId: membership.organizationId,
- }));
- }),
- );
- return byOrg.flat();
-}
-
export const listProjectsTool = {
name: "list_projects",
config: {
title: "List projects",
description:
- "Lists the user's projects. Uses no credits — does not call DataForSEO. Use this whenever you need a `projectId` for another OpenSEO tool. Returns an array of {id, name, domain, locationCode, languageCode}; pass the `id` value as `projectId`. locationCode/languageCode are the project's default market — tools fall back to them when a call omits location/language args. When the user belongs to several organizations, each project is labeled with its organization and organizationId (pass that to create_project).",
+ "Lists the user's projects. Uses no credits — does not call DataForSEO. Use this whenever you need a `projectId` for another OpenSEO tool. Returns an array of {id, name, domain, locationCode, languageCode}; pass the `id` value as `projectId`. locationCode/languageCode are the project's default market — tools fall back to them when a call omits location/language args.",
inputSchema: {} as Record<string, never>,
outputSchema: z.looseObject({
projects: z.array(
@@ -53,8 +22,6 @@ export const listProjectsTool = {
locationCode: z.number(),
languageCode: z.string(),
url: z.string(),
- organization: z.string().optional(),
- organizationId: z.string().optional(),
})
.passthrough(),
),
@@ -67,8 +34,8 @@ export const listProjectsTool = {
},
},
handler: async (_args: Record<string, never>, context: ToolContext) => {
- const { baseUrl, ...auth } = context.auth;
- const projects = await listVisibleProjects(auth);
+ const { baseUrl, organizationId } = context.auth;
+ const projects = await ProjectService.listProjects(organizationId);
const lines =
projects.length === 0
? [
@@ -76,7 +43,7 @@ export const listProjectsTool = {
]
: projects.map(
(p) =>
- `- ${p.id} ${p.name}${p.domain ? ` (${p.domain})` : ""}${p.organization ? ` organization:${p.organization} [${p.organizationId}]` : ""} market:${p.locationCode}/${p.languageCode}`,
+ `- ${p.id} ${p.name}${p.domain ? ` (${p.domain})` : ""} market:${p.locationCode}/${p.languageCode}`,
);
return mcpResponse({
text: `Projects (${projects.length}):\n${lines.join("\n")}`,
@@ -91,8 +58,6 @@ export const listProjectsTool = {
locationCode: p.locationCode,
languageCode: p.languageCode,
url: buildDashboardUrl(baseUrl, `/p/${p.id}`),
- ...(p.organization ? { organization: p.organization } : {}),
- ...(p.organizationId ? { organizationId: p.organizationId } : {}),
})),
},
});
diff --git a/src/server/mcp/tools/saved-keywords-tools.test.ts b/src/server/mcp/tools/saved-keywords-tools.test.ts
index 9e90af1a..67c5d530 100644
--- a/src/server/mcp/tools/saved-keywords-tools.test.ts
+++ b/src/server/mcp/tools/saved-keywords-tools.test.ts
@@ -15,12 +15,6 @@ vi.mock("@/server/features/projects/services/ProjectService", () => ({
},
}));
-// project-auth imports the repository for user-scoped (API key) credentials;
-// unused here (pinned context) but keeps the db out of the module graph.
-vi.mock("@/server/auth/repositories/AuthRepository", () => ({
- AuthRepository: { getMembership: vi.fn() },
-}));
-
vi.mock("@/server/features/keywords/services/KeywordResearchService", () => ({
KeywordResearchService: {
getSavedKeywords: mocks.getSavedKeywords,
diff --git a/src/server/mcp/tools/tool-test-support.ts b/src/server/mcp/tools/tool-test-support.ts
index 8431655d..45ef7cd2 100644
--- a/src/server/mcp/tools/tool-test-support.ts
+++ b/src/server/mcp/tools/tool-test-support.ts
@@ -9,7 +9,6 @@ export function makeToolContext(
userEmail: "[email protected]",
organizationId: "org_123",
role: "owner",
- orgScope: "pinned",
clientId: "client_123",
scopes: ["mcp"],
baseUrl: "https://open-seo.test",
diff --git a/src/server/mcp/tools/whoami.test.ts b/src/server/mcp/tools/whoami.test.ts
index c938a9cb..5565b5f6 100644
--- a/src/server/mcp/tools/whoami.test.ts
+++ b/src/server/mcp/tools/whoami.test.ts
@@ -28,7 +28,7 @@ vi.mock("@/server/lib/runtime-env", () => ({
}));
vi.mock("@/server/lib/posthog", () => ({ captureServerEvent: vi.fn() }));
-const context = makeToolContext({ orgScope: "user" });
+const context = makeToolContext();
beforeEach(() => {
mocks.isHosted.mockResolvedValue(true);
diff --git a/src/server/mcp/transport-v2.test.ts b/src/server/mcp/transport-v2.test.ts
index f1e370af..7492a0d5 100644
--- a/src/server/mcp/transport-v2.test.ts
+++ b/src/server/mcp/transport-v2.test.ts
@@ -17,10 +17,6 @@ vi.mock("@/server/auth/repositories/AuthRepository", () => ({
},
}));
-vi.mock("@/server/auth/default-hosted-organization", () => ({
- resolveExistingActiveHostedOrganization: vi.fn(),
-}));
-
vi.mock("@/middleware/ensure-user/cloudflareAccess", () => ({
resolveCloudflareAccessContext: vi.fn(),
}));
diff --git a/src/server/mcp/transport.test.ts b/src/server/mcp/transport.test.ts
index 8c6365ce..f0ac6f92 100644
--- a/src/server/mcp/transport.test.ts
+++ b/src/server/mcp/transport.test.ts
@@ -21,19 +21,10 @@ const authRepositoryMocks = vi.hoisted(() => ({
getMembership: vi.fn(),
}));
-const hostedOrganizationMocks = vi.hoisted(() => ({
- resolveExistingActiveHostedOrganization: vi.fn(),
-}));
-
vi.mock("@/server/auth/repositories/AuthRepository", () => ({
AuthRepository: authRepositoryMocks,
}));
-vi.mock("@/server/auth/default-hosted-organization", () => ({
- resolveExistingActiveHostedOrganization:
- hostedOrganizationMocks.resolveExistingActiveHostedOrganization,
-}));
-
vi.mock("@/middleware/ensure-user/cloudflareAccess", () => ({
resolveCloudflareAccessContext:
selfHostedAuthMocks.resolveCloudflareAccessContext,
@@ -244,13 +235,17 @@ describe("handleAuthenticatedOpenSeoMcpRequest", () => {
legacy: "reject",
}),
);
- // The transport stamps the per-request role and user scope into the props
- // it hands the server; neither is baked into tokens.
+ // The transport checks membership in the token's org and stamps the
+ // member row's role into the props it hands the server; roles are never
+ // baked into tokens.
+ expect(authRepositoryMocks.getMembership).toHaveBeenCalledWith(
+ "user-1",
+ "org-1",
+ );
expect(selfHostedAuthMocks.createOpenSeoMcpServer).toHaveBeenCalledWith({
[MCP_AUTH_CONTEXT_PROP]: {
...props[MCP_AUTH_CONTEXT_PROP],
role: "owner",
- orgScope: "user",
},
});
});
@@ -289,7 +284,6 @@ describe("handleAuthenticatedOpenSeoMcpRequest", () => {
[MCP_AUTH_CONTEXT_PROP]: {
...props[MCP_AUTH_CONTEXT_PROP],
role: "owner",
- orgScope: "user",
},
});
});
@@ -314,52 +308,12 @@ describe("handleAuthenticatedOpenSeoMcpRequest", () => {
expect(response.status).toBe(403);
});
- it("rebinds a token to the user's active org when the consent-time membership is gone", async () => {
+ // The grant is bound to its consent-time org for life: once the member row
+ // is gone the token is dead, never rebound to another org the user is in.
+ // The Bearer challenge sends compliant clients back through OAuth.
+ it("rejects a token whose consent-time membership is gone", async () => {
authRepositoryMocks.getMembership.mockResolvedValue(null);
- hostedOrganizationMocks.resolveExistingActiveHostedOrganization.mockResolvedValue(
- { organizationId: "org-2", role: "member" },
- );
- // No orgScope: a grant minted before the flag existed heals the same way.
- const props = createWorkersOAuthMcpProps({
- userId: "user-1",
- userEmail: "[email protected]",
- organizationId: "org-1",
- baseUrl: "https://open-seo.test",
- clientId: "client-1",
- scopes: ["mcp"],
- });
-
- const response = await handleAuthenticatedOpenSeoMcpRequest(
- createMcpRequest(),
- props,
- {},
- { ...ctx, props },
- );
-
- expect(response.status).toBe(200);
- expect(selfHostedAuthMocks.createOpenSeoMcpServer).toHaveBeenCalledWith({
- [MCP_AUTH_CONTEXT_PROP]: {
- ...props[MCP_AUTH_CONTEXT_PROP],
- organizationId: "org-2",
- role: "member",
- orgScope: "user",
- },
- });
- });
-
- it("rejects a token whose user belongs to no organization", async () => {
- authRepositoryMocks.getMembership.mockResolvedValue(null);
- hostedOrganizationMocks.resolveExistingActiveHostedOrganization.mockResolvedValue(
- null,
- );
- const props = createWorkersOAuthMcpProps({
- userId: "user-1",
- userEmail: "[email protected]",
- organizationId: "org-1",
- baseUrl: "https://open-seo.test",
- clientId: "client-1",
- scopes: ["mcp"],
- });
+ const props = hostedProps();
const response = await handleAuthenticatedOpenSeoMcpRequest(
createMcpRequest(),
@@ -369,6 +323,10 @@ describe("handleAuthenticatedOpenSeoMcpRequest", () => {
);
expect(response.status).toBe(401);
+ expect(response.headers.get("WWW-Authenticate")).toBe(
+ 'Bearer error="invalid_token"',
+ );
+ expect(selfHostedAuthMocks.createOpenSeoMcpServer).not.toHaveBeenCalled();
});
it("rejects an OAuth client without the MCP scope", async () => {
diff --git a/src/server/mcp/transport.ts b/src/server/mcp/transport.ts
index 277d9388..6841dc2a 100644
--- a/src/server/mcp/transport.ts
+++ b/src/server/mcp/transport.ts
@@ -22,7 +22,6 @@ import { getPublicOrigin } from "@/server/mcp/public-origin";
import { createOpenSeoMcpServer } from "@/server/mcp/server";
import { supportsMcpApps } from "@/server/mcp/ui-capabilities";
import { AuthRepository } from "@/server/auth/repositories/AuthRepository";
-import { resolveExistingActiveHostedOrganization } from "@/server/auth/default-hosted-organization";
// Mirrors the agents SDK's DEFAULT_CORS_OPTIONS so legacy responses carry the
// same CORS surface as the modern handler's.
@@ -163,19 +162,6 @@ function createRequestHandler(
};
}
-// Hosted credentials (OAuth grants and API keys) are user-scoped: the
-// organizationId they carry is only the fallback context for tools with no
-// project argument, so keep it while the membership holds, else rebind to the
-// user's current active org. Null only when they belong to no org at all.
-async function resolveRequestOrganization(
- userId: string,
- organizationId: string,
-) {
- const membership = await AuthRepository.getMembership(userId, organizationId);
- if (membership) return { organizationId, role: membership.role };
- return resolveExistingActiveHostedOrganization(userId);
-}
-
export async function handleAuthenticatedOpenSeoMcpRequest(
request: Request,
props: unknown,
@@ -200,16 +186,19 @@ export async function handleAuthenticatedOpenSeoMcpRequest(
return withMcpCors(new Response("Invalid Origin", { status: 403 }));
}
- // Tokens snapshot organizationId at consent and refresh copies it verbatim,
- // so the grant can outlive the membership (member removed, org changed).
- // Re-resolve per request; 401 invalid_token only once the user belongs to
- // no organization, pushing compliant clients back through OAuth.
+ // A hosted credential is bound to the organization that was active when it
+ // was created (OAuth: at consent; API key: at creation) and stays bound for
+ // its lifetime. The grant can outlive the membership (member removed), so
+ // require a live member row in exactly that org on every request: once it
+ // is gone the credential is dead, with no fallback to another org. The 401
+ // pushes compliant clients back through OAuth, and the new grant binds to
+ // whichever org is active at that consent.
const authContext = result.data[MCP_AUTH_CONTEXT_PROP];
- const organization = await resolveRequestOrganization(
+ const membership = await AuthRepository.getMembership(
authContext.userId,
authContext.organizationId,
);
- if (!organization) {
+ if (!membership) {
return new Response("Organization access revoked", {
status: 401,
headers: { "WWW-Authenticate": 'Bearer error="invalid_token"' },
@@ -220,15 +209,10 @@ export async function handleAuthenticatedOpenSeoMcpRequest(
// own; passing authContext explicitly hands it the schema-validated copy
// (with the per-request role stamped in — roles are never baked into
// tokens) and keeps this path symmetrical with self-hosted, which has no
- // ctx.props. orgScope is stamped here rather than read from the token so
- // grants minted before it existed are user-scoped too: project-scoped tools
- // authorize per call via membership in the project's org, so one
- // authorization follows the user across every organization they belong to.
+ // ctx.props.
const requestProps = createWorkersOAuthMcpProps({
...authContext,
- organizationId: organization.organizationId,
- role: organization.role,
- orgScope: "user",
+ role: membership.role,
// The only per-request client signal that reaches a tools/call: initialize's
// clientInfo is long gone by then and this transport never populates
// ServerContext.http.req. Display only (report attribution).
diff --git a/src/serverFunctions/mcp-connections.ts b/src/serverFunctions/mcp-connections.ts
new file mode 100644
index 00000000..ecc2f74c
--- /dev/null
+++ b/src/serverFunctions/mcp-connections.ts
@@ -0,0 +1,17 @@
+import { createServerFn } from "@tanstack/react-start";
+import { z } from "zod";
+import { McpConnectionsService } from "@/server/mcp/connections";
+import { requireAuthenticatedContext } from "@/serverFunctions/middleware";
+
+export const listMcpConnections = createServerFn({ method: "GET" })
+ .middleware(requireAuthenticatedContext)
+ .handler(({ context }) =>
+ McpConnectionsService.listMcpConnections(context.userId),
+ );
+
+export const revokeMcpConnection = createServerFn({ method: "POST" })
+ .middleware(requireAuthenticatedContext)
+ .validator(z.object({ grantId: z.string().min(1) }))
+ .handler(({ data, context }) =>
+ McpConnectionsService.revokeMcpConnection(context.userId, data.grantId),
+ );
diff --git a/tests/mcp-isolation/auth.ts b/tests/mcp-isolation/auth.ts
new file mode 100644
index 00000000..096ce068
--- /dev/null
+++ b/tests/mcp-isolation/auth.ts
@@ -0,0 +1,291 @@
+import { createHash, randomBytes } from "node:crypto";
+import {
+ expect,
+ type APIRequest,
+ type APIRequestContext,
+ type APIResponse,
+ type Browser,
+} from "@playwright/test";
+import { z } from "zod";
+import type { Credential } from "./mcp";
+
+// What a real MCP client (Codex, Claude Code) registers as its callback.
+const REDIRECT_URI = "http://localhost:1455/auth/callback";
+
+/** A signed-up hosted user with its own cookie jar. */
+export type Account = {
+ label: string;
+ name: string;
+ email: string;
+ password: string;
+ baseURL: string;
+ api: APIRequestContext;
+};
+
+async function readJson(response: APIResponse, what: string): Promise<unknown> {
+ const text = await response.text();
+ expect(
+ response.ok(),
+ `${what}: HTTP ${response.status()} ${text.slice(0, 300)}`,
+ ).toBe(true);
+ const parsed: unknown = JSON.parse(text);
+ return parsed;
+}
+
+/**
+ * Email + password sign-up through Better Auth. BYPASS_EMAIL_VERIFICATION=true
+ * makes the response set the session cookie right away, and the session-create
+ * hook mints the user's default organization. The context sends Origin on
+ * every request because Better Auth checks it on POST.
+ */
+export async function signUp(
+ request: APIRequest,
+ baseURL: string,
+ account: Pick<Account, "label" | "name" | "email" | "password">,
+): Promise<Account> {
+ const api = await request.newContext({
+ baseURL,
+ extraHTTPHeaders: { Origin: baseURL },
+ });
+ await readJson(
+ await api.post("/api/auth/sign-up/email", {
+ data: {
+ name: account.name,
+ email: account.email,
+ password: account.password,
+ },
+ }),
+ `sign up ${account.label}`,
+ );
+ return { ...account, baseURL, api };
+}
+
+const organizationListSchema = z.array(
+ z.looseObject({ id: z.string(), name: z.string() }),
+);
+
+export async function listOrganizations(account: Account) {
+ return organizationListSchema.parse(
+ await readJson(
+ await account.api.get("/api/auth/organization/list"),
+ `list organizations for ${account.label}`,
+ ),
+ );
+}
+
+export async function setActiveOrganization(
+ account: Account,
+ organizationId: string,
+) {
+ await readJson(
+ await account.api.post("/api/auth/organization/set-active", {
+ data: { organizationId },
+ }),
+ `set active organization for ${account.label}`,
+ );
+}
+
+const invitationSchema = z.looseObject({ id: z.string() });
+
+/**
+ * The raw invite endpoint creates the pending invitation and emails nobody
+ * (the app's sendTeamInvitation server function is what sends mail), which is
+ * exactly what the membership chapter needs. The response carries the
+ * invitation id; `list-user-invitations` is avoided because it requires a
+ * verified email, which BYPASS_EMAIL_VERIFICATION accounts never get.
+ */
+export async function inviteMember(
+ inviter: Account,
+ input: { email: string; organizationId: string },
+) {
+ const invitation = invitationSchema.parse(
+ await readJson(
+ await inviter.api.post("/api/auth/organization/invite-member", {
+ // The app only ever mints "admin" (enforced in lib/auth.ts).
+ data: { ...input, role: "admin" },
+ }),
+ `${inviter.label} invites ${input.email}`,
+ ),
+ );
+ return invitation.id;
+}
+
+/** Also switches the accepting session's active organization to the new one. */
+export async function acceptInvitation(account: Account, invitationId: string) {
+ await readJson(
+ await account.api.post("/api/auth/organization/accept-invitation", {
+ data: { invitationId },
+ }),
+ `${account.label} accepts invitation`,
+ );
+}
+
+export async function removeMember(
+ owner: Account,
+ input: { email: string; organizationId: string },
+) {
+ await readJson(
+ await owner.api.post("/api/auth/organization/remove-member", {
+ data: {
+ memberIdOrEmail: input.email,
+ organizationId: input.organizationId,
+ },
+ }),
+ `${owner.label} removes ${input.email}`,
+ );
+}
+
+const createdApiKeySchema = z.looseObject({ key: z.string() });
+
+/**
+ * The key is returned once. It is bound server-side to the session's active
+ * organization (the /api-key/create before-hook in lib/auth.ts stamps
+ * metadata.organizationId); the client never sends metadata.
+ */
+export async function createApiKey(
+ account: Account,
+ name: string,
+): Promise<Credential> {
+ const created = createdApiKeySchema.parse(
+ await readJson(
+ await account.api.post("/api/auth/api-key/create", { data: { name } }),
+ `create API key "${name}" for ${account.label}`,
+ ),
+ );
+ return { label: `${account.label} api-key (${name})`, secret: created.key };
+}
+
+const registrationSchema = z.looseObject({ client_id: z.string() });
+const tokenResponseSchema = z.looseObject({ access_token: z.string() });
+
+// Codex-style dynamic client registration: no token_endpoint_auth_method, so
+// the server registers a public client.
+async function registerOAuthClient(
+ anon: APIRequestContext,
+ clientName: string,
+) {
+ const registration = registrationSchema.parse(
+ await readJson(
+ await anon.post("/api/auth/oauth2/register", {
+ data: {
+ client_name: clientName,
+ redirect_uris: [REDIRECT_URI],
+ grant_types: ["authorization_code", "refresh_token"],
+ response_types: ["code"],
+ },
+ }),
+ `register OAuth client "${clientName}"`,
+ ),
+ );
+ return registration.client_id;
+}
+
+/**
+ * The full authorization-code + PKCE flow, driven the way a real client drives
+ * it: /api/auth/oauth2/authorize in the user's browser, the consent page, the
+ * redirect back to the client's callback (intercepted here), then the code
+ * exchange at the token endpoint. Along the way it asserts that the consent
+ * page names the signed-in user and the workspace the grant will be bound to.
+ */
+export async function authorizeOAuth(
+ browser: Browser,
+ anon: APIRequestContext,
+ account: Account,
+ options: {
+ clientName: string;
+ // The Workspace row only renders for people in more than one
+ // organization; null asserts it is absent.
+ expectedWorkspace: string | null;
+ // Pick this workspace in the consent page's switcher before authorizing.
+ switchToWorkspace?: string;
+ },
+): Promise<Credential> {
+ const label = `${account.label} oauth (${options.clientName})`;
+ const clientId = await registerOAuthClient(anon, options.clientName);
+ const codeVerifier = randomBytes(32).toString("base64url");
+ const codeChallenge = createHash("sha256")
+ .update(codeVerifier)
+ .digest("base64url");
+ const resource = `${account.baseURL}/mcp`;
+ const authorizeQuery = new URLSearchParams({
+ response_type: "code",
+ client_id: clientId,
+ redirect_uri: REDIRECT_URI,
+ scope: "offline_access mcp",
+ state: randomBytes(8).toString("hex"),
+ code_challenge: codeChallenge,
+ code_challenge_method: "S256",
+ resource,
+ });
+
+ // A browser signed in as this user: copy the cookie jar from its API context.
+ const context = await browser.newContext({
+ baseURL: account.baseURL,
+ storageState: await account.api.storageState(),
+ });
+ let code: string | null;
+ try {
+ const page = await context.newPage();
+ // Nothing listens on :1455; answer the callback navigation ourselves and
+ // read the code off the request URL.
+ await page.route(`${REDIRECT_URI}**`, (route) =>
+ route.fulfill({ status: 200, body: "ok" }),
+ );
+ await page.goto(`/api/auth/oauth2/authorize?${authorizeQuery.toString()}`);
+ await expect(page).toHaveURL(/\/oauth-consent\?/);
+ const authorize = page.getByRole("button", {
+ name: "Authorize",
+ exact: true,
+ });
+ await expect(authorize).toBeVisible();
+ // The "Signed in as" and "Workspace" rows of the consent card
+ // (src/routes/_authenticated.oauth-consent.tsx).
+ await expect(page.getByText(account.email).first()).toBeVisible();
+ const workspaceRow = page.getByText("Workspace", { exact: true });
+ if (options.expectedWorkspace) {
+ await expect(workspaceRow).toBeVisible();
+ await expect(
+ page.getByText(options.expectedWorkspace, { exact: true }).first(),
+ ).toBeVisible();
+ } else {
+ await expect(workspaceRow).toBeHidden();
+ }
+ if (options.switchToWorkspace) {
+ const switcher = page.getByRole("combobox", { name: "Workspace" });
+ await switcher.click();
+ await page
+ .getByRole("option", { name: options.switchToWorkspace, exact: true })
+ .click();
+ // The trigger shows the new name once the switch has landed and the
+ // organization context refetched.
+ await expect(switcher).toContainText(options.switchToWorkspace);
+ await expect(authorize).toBeEnabled();
+ }
+
+ const callback = page.waitForRequest((request) =>
+ request.url().startsWith(REDIRECT_URI),
+ );
+ await authorize.click();
+ code = new URL((await callback).url()).searchParams.get("code");
+ } finally {
+ await context.close();
+ }
+ expect(code, "authorization code in the callback redirect").toBeTruthy();
+
+ const tokens = tokenResponseSchema.parse(
+ await readJson(
+ await anon.post("/api/auth/oauth2/token", {
+ form: {
+ grant_type: "authorization_code",
+ code: code ?? "",
+ redirect_uri: REDIRECT_URI,
+ client_id: clientId,
+ code_verifier: codeVerifier,
+ resource,
+ },
+ }),
+ `exchange code for ${account.label}`,
+ ),
+ );
+ return { label, secret: tokens.access_token };
+}
diff --git a/tests/mcp-isolation/checks.ts b/tests/mcp-isolation/checks.ts
new file mode 100644
index 00000000..4245a7cc
--- /dev/null
+++ b/tests/mcp-isolation/checks.ts
@@ -0,0 +1,60 @@
+import { mkdir, writeFile } from "node:fs/promises";
+import path from "node:path";
+import { expect } from "@playwright/test";
+
+type Check = {
+ chapter: string;
+ credential: string;
+ tool: string;
+ expectation: string;
+ outcome: "pass" | "fail";
+ detail: string;
+};
+
+const checks: Check[] = [];
+
+/**
+ * Records one verdict for the report and asserts it softly, so a failing cell
+ * of the cross-tenant matrix still lets the rest of the matrix run and show up
+ * in the table.
+ */
+export function check(input: Omit<Check, "outcome"> & { ok: boolean }) {
+ const { ok, ...rest } = input;
+ const entry: Check = { ...rest, outcome: ok ? "pass" : "fail" };
+ checks.push(entry);
+ expect
+ .soft(
+ ok,
+ `[${entry.chapter}] ${entry.credential} / ${entry.tool}: ${entry.expectation} (${entry.detail})`,
+ )
+ .toBe(true);
+}
+
+function cell(value: string) {
+ const flat = value.replace(/\s+/g, " ").replace(/\|/g, "\\|").trim();
+ return flat.length > 160 ? `${flat.slice(0, 157)}...` : flat;
+}
+
+/** Writes every recorded check as a markdown table (creates the directory). */
+export async function writeReport(
+ filePath: string,
+ header: Record<string, string>,
+) {
+ const failed = checks.filter((entry) => entry.outcome === "fail").length;
+ const lines = [
+ "# MCP tenant isolation report",
+ "",
+ ...Object.entries(header).map(([key, value]) => `- ${key}: ${value}`),
+ `- Checks: ${checks.length} (${checks.length - failed} pass, ${failed} fail)`,
+ "",
+ "| Chapter | Credential | Tool | Expectation | Outcome | Detail |",
+ "| --- | --- | --- | --- | --- | --- |",
+ ...checks.map(
+ (entry) =>
+ `| ${cell(entry.chapter)} | ${cell(entry.credential)} | ${cell(entry.tool)} | ${cell(entry.expectation)} | ${entry.outcome} | ${cell(entry.detail)} |`,
+ ),
+ "",
+ ];
+ await mkdir(path.dirname(filePath), { recursive: true });
+ await writeFile(filePath, lines.join("\n"), "utf8");
+}
diff --git a/tests/mcp-isolation/matrix.ts b/tests/mcp-isolation/matrix.ts
new file mode 100644
index 00000000..458d8bf6
--- /dev/null
+++ b/tests/mcp-isolation/matrix.ts
@@ -0,0 +1,234 @@
+import type { APIRequestContext } from "@playwright/test";
+import { check } from "./checks";
+import {
+ callTool,
+ describeResult,
+ structured,
+ type McpCallResult,
+ type ToolCall,
+} from "./mcp";
+import {
+ reportSchema,
+ reportsSchema,
+ savedKeywordsSchema,
+ templatesSchema,
+} from "./schemas";
+import { INTRUDER, reportHtml, type SeededData, type Tenant } from "./tenants";
+
+/**
+ * The read/change/delete/export surface, all pointed at B's project. The
+ * project gate answers a project outside the bound organization with
+ * NOT_FOUND (ProjectService.getProjectForOrganization treats it as
+ * nonexistent), so the error text is not asserted: isError plus the leak scan
+ * is the invariant.
+ */
+export function foreignProjectCalls(b: Tenant, seeded: SeededData): ToolCall[] {
+ const projectId = b.projectId;
+ return [
+ { name: "get_project_context", arguments: { projectId } },
+ {
+ name: "update_project_context",
+ arguments: {
+ projectId,
+ updates: [{ section: "current_goal", content: INTRUDER }],
+ },
+ },
+ { name: "list_saved_keywords", arguments: { projectId } },
+ { name: "save_keywords", arguments: { projectId, keywords: [INTRUDER] } },
+ {
+ name: "remove_saved_keywords",
+ arguments: { projectId, savedKeywordIds: seeded.keywordIds },
+ },
+ { name: "list_reports", arguments: { projectId } },
+ { name: "get_report", arguments: { projectId, reportId: seeded.reportId } },
+ {
+ name: "save_report",
+ arguments: {
+ projectId,
+ title: INTRUDER,
+ summary: INTRUDER,
+ html: reportHtml(INTRUDER, INTRUDER),
+ },
+ },
+ {
+ name: "set_report_sharing",
+ arguments: { projectId, reportId: seeded.reportId, public: true },
+ },
+ {
+ name: "delete_report",
+ arguments: { projectId, reportId: seeded.reportId },
+ },
+ { name: "list_report_templates", arguments: { projectId } },
+ {
+ name: "save_report_template",
+ arguments: {
+ projectId,
+ name: INTRUDER,
+ description: INTRUDER,
+ instructions: INTRUDER,
+ },
+ },
+ {
+ name: "delete_report_template",
+ arguments: { projectId, templateId: seeded.templateId },
+ },
+ { name: "export_ai_visibility_data", arguments: { projectId } },
+ { name: "get_audit_status", arguments: { projectId } },
+ ];
+}
+
+/**
+ * A's own project with B's resource ids: every lookup must stay inside A's
+ * project. remove_saved_keywords is not here because it ignores foreign ids by
+ * contract (no error); the spec asserts "deleted nothing" for it separately.
+ */
+export function foreignResourceCalls(
+ a: Tenant,
+ seeded: SeededData,
+): ToolCall[] {
+ const projectId = a.projectId;
+ const { reportId, templateId } = seeded;
+ return [
+ { name: "get_report", arguments: { projectId, reportId } },
+ {
+ name: "set_report_sharing",
+ arguments: { projectId, reportId, public: true },
+ },
+ { name: "delete_report", arguments: { projectId, reportId } },
+ {
+ name: "save_report",
+ arguments: {
+ projectId,
+ reportId,
+ title: INTRUDER,
+ summary: INTRUDER,
+ html: reportHtml(INTRUDER, INTRUDER),
+ },
+ },
+ { name: "delete_report_template", arguments: { projectId, templateId } },
+ {
+ name: "save_report_template",
+ arguments: {
+ projectId,
+ templateId,
+ name: INTRUDER,
+ description: INTRUDER,
+ instructions: INTRUDER,
+ },
+ },
+ { name: "get_audit_status", arguments: { projectId, auditId: reportId } },
+ ];
+}
+
+/**
+ * B's identifiers that appear in a response although the caller never sent
+ * them. An echo of a caller-supplied id (NOT_FOUND messages repeat the id they
+ * were given) tells the caller nothing it did not already know, so supplied
+ * values are excluded.
+ */
+export function leaked(
+ result: McpCallResult,
+ call: ToolCall,
+ seeded: SeededData,
+) {
+ const supplied = JSON.stringify(call.arguments ?? {}).toLowerCase();
+ const body = result.body.toLowerCase();
+ return seeded.secrets.filter(
+ (secret) =>
+ !supplied.includes(secret.toLowerCase()) &&
+ body.includes(secret.toLowerCase()),
+ );
+}
+
+/** As B, after A's attempts: the seeded data is intact and nothing was added. */
+export async function checkTenantBUnchanged(
+ anon: APIRequestContext,
+ b: Tenant,
+ seeded: SeededData,
+ chapter: string,
+) {
+ const projectId = b.projectId;
+ const credential = b.oauth.label;
+ const read = (call: ToolCall) => callTool(anon, b.oauth, call);
+
+ const context = await read({
+ name: "get_project_context",
+ arguments: { projectId },
+ });
+ check({
+ chapter,
+ credential,
+ tool: "get_project_context",
+ expectation: "marker intact, no intruder text",
+ ok:
+ context.isError === false &&
+ context.text.includes(seeded.marker) &&
+ !context.text.includes(INTRUDER),
+ detail: describeResult(context),
+ });
+
+ const keywords = structured(
+ await read({ name: "list_saved_keywords", arguments: { projectId } }),
+ savedKeywordsSchema,
+ "B lists saved keywords",
+ );
+ check({
+ chapter,
+ credential,
+ tool: "list_saved_keywords",
+ expectation: "seeded keyword kept, no intruder keyword",
+ ok:
+ seeded.keywordIds.every((id) =>
+ keywords.rows.some((row) => row.id === id),
+ ) && keywords.rows.every((row) => row.keyword !== INTRUDER),
+ detail: keywords.rows.map((row) => row.keyword).join(","),
+ });
+
+ const reports = structured(
+ await read({ name: "list_reports", arguments: { projectId } }),
+ reportsSchema,
+ "B lists reports",
+ );
+ check({
+ chapter,
+ credential,
+ tool: "list_reports",
+ expectation: "only the seeded report exists",
+ ok:
+ reports.reports.length === 1 && reports.reports[0].id === seeded.reportId,
+ detail: reports.reports.map((report) => report.id).join(","),
+ });
+
+ const report = structured(
+ await read({
+ name: "get_report",
+ arguments: { projectId, reportId: seeded.reportId },
+ }),
+ reportSchema,
+ "B reads its report",
+ );
+ check({
+ chapter,
+ credential,
+ tool: "get_report",
+ expectation: "report still private",
+ ok: report.report.shareUrl === null,
+ detail: `shareUrl=${String(report.report.shareUrl)}`,
+ });
+
+ const templates = structured(
+ await read({ name: "list_report_templates", arguments: { projectId } }),
+ templatesSchema,
+ "B lists templates",
+ );
+ check({
+ chapter,
+ credential,
+ tool: "list_report_templates",
+ expectation: "only the seeded template exists",
+ ok:
+ templates.templates.length === 1 &&
+ templates.templates[0].id === seeded.templateId,
+ detail: templates.templates.map((template) => template.id).join(","),
+ });
+}
diff --git a/tests/mcp-isolation/mcp.ts b/tests/mcp-isolation/mcp.ts
new file mode 100644
index 00000000..fc745915
--- /dev/null
+++ b/tests/mcp-isolation/mcp.ts
@@ -0,0 +1,143 @@
+import type { APIRequestContext } from "@playwright/test";
+import { z } from "zod";
+
+/**
+ * A hosted credential exactly as an MCP client presents it: an OAuth access
+ * token or an `oseo_` API key, both sent as `Authorization: Bearer`.
+ */
+export type Credential = { label: string; secret: string };
+
+export type ToolCall = { name: string; arguments?: Record<string, unknown> };
+
+export type McpCallResult = {
+ status: number;
+ /** Lower-cased header names, as Playwright returns them. */
+ headers: Record<string, string>;
+ /** The raw response body; the leak checks scan all of it. */
+ body: string;
+ /**
+ * Set when the server answered JSON-RPC, i.e. the credential was accepted
+ * and the call reached a tool. Undefined for HTTP-level rejections (401/403).
+ */
+ isError: boolean | undefined;
+ /**
+ * The tool's text content, the JSON-RPC error message, or the raw body for
+ * HTTP-level rejections.
+ */
+ text: string;
+ structuredContent: unknown;
+ /**
+ * `error` from a non-JSON-RPC JSON body, e.g. the API-key path's
+ * `{ error: "invalid_api_key" }` / `{ error: "account_access_revoked" }`.
+ */
+ errorCode: string | undefined;
+};
+
+const rpcResponseSchema = z.object({
+ result: z
+ .looseObject({
+ isError: z.boolean().optional(),
+ content: z
+ .array(z.looseObject({ type: z.string(), text: z.string().optional() }))
+ .optional(),
+ structuredContent: z.unknown().optional(),
+ })
+ .optional(),
+ error: z.looseObject({ code: z.number(), message: z.string() }).optional(),
+});
+
+const httpErrorSchema = z.looseObject({ error: z.string() });
+
+function parseJson(body: string): unknown {
+ try {
+ const parsed: unknown = JSON.parse(body);
+ return parsed;
+ } catch {
+ return undefined;
+ }
+}
+
+/**
+ * One `tools/call` against the real `/mcp` route. The request carries no
+ * `_meta` protocol-version envelope, so the server classifies it as legacy
+ * traffic and answers plain JSON from its stateless path; a tool failure comes
+ * back as `result.isError: true` with the message in `content[0].text`.
+ */
+export async function callTool(
+ api: APIRequestContext,
+ credential: Credential,
+ call: ToolCall,
+): Promise<McpCallResult> {
+ const response = await api.post("/mcp", {
+ headers: {
+ Authorization: `Bearer ${credential.secret}`,
+ Accept: "application/json, text/event-stream",
+ "Content-Type": "application/json",
+ },
+ data: {
+ jsonrpc: "2.0",
+ id: 1,
+ method: "tools/call",
+ params: { name: call.name, arguments: call.arguments ?? {} },
+ },
+ });
+ const body = await response.text();
+ const base = { status: response.status(), headers: response.headers(), body };
+ const json = parseJson(body);
+
+ const rpc = rpcResponseSchema.safeParse(json);
+ if (rpc.success && rpc.data.result) {
+ const { result } = rpc.data;
+ return {
+ ...base,
+ isError: result.isError ?? false,
+ text: (result.content ?? []).map((block) => block.text ?? "").join("\n"),
+ structuredContent: result.structuredContent,
+ errorCode: undefined,
+ };
+ }
+ if (rpc.success && rpc.data.error) {
+ return {
+ ...base,
+ isError: true,
+ text: rpc.data.error.message,
+ structuredContent: undefined,
+ errorCode: undefined,
+ };
+ }
+
+ const httpError = httpErrorSchema.safeParse(json);
+ return {
+ ...base,
+ isError: undefined,
+ text: body,
+ structuredContent: undefined,
+ errorCode: httpError.success ? httpError.data.error : undefined,
+ };
+}
+
+/** A successful call's structuredContent, parsed; throws on any failure. */
+export function structured<T>(
+ result: McpCallResult,
+ schema: z.ZodType<T>,
+ what: string,
+): T {
+ if (result.isError !== false) {
+ throw new Error(`${what} failed: HTTP ${result.status} ${result.text}`);
+ }
+ return schema.parse(result.structuredContent);
+}
+
+/** A one-line summary of a result for the report table. */
+export function describeResult(result: McpCallResult): string {
+ const auth = result.headers["www-authenticate"];
+ return [
+ `HTTP ${result.status}`,
+ result.isError === undefined ? "" : `isError=${String(result.isError)}`,
+ result.errorCode ? `error=${result.errorCode}` : "",
+ auth ? `WWW-Authenticate: ${auth}` : "",
+ result.text.slice(0, 120).replace(/\s+/g, " "),
+ ]
+ .filter(Boolean)
+ .join(" | ");
+}
diff --git a/tests/mcp-isolation/schemas.ts b/tests/mcp-isolation/schemas.ts
new file mode 100644
index 00000000..4c17d530
--- /dev/null
+++ b/tests/mcp-isolation/schemas.ts
@@ -0,0 +1,20 @@
+import { z } from "zod";
+
+// Only the fields the suite asserts on; every tool returns more.
+
+const idSchema = z.looseObject({ id: z.string() });
+
+export const projectsSchema = z.looseObject({ projects: z.array(idSchema) });
+export const createdProjectSchema = z.looseObject({ project: idSchema });
+export const whoamiSchema = z.looseObject({ userEmail: z.string() });
+export const savedKeywordsSchema = z.looseObject({
+ rows: z.array(z.looseObject({ id: z.string(), keyword: z.string() })),
+});
+export const reportsSchema = z.looseObject({ reports: z.array(idSchema) });
+export const reportSchema = z.looseObject({
+ report: z.looseObject({ shareUrl: z.string().nullable() }),
+});
+export const savedReportSchema = z.looseObject({ reportId: z.string() });
+export const templatesSchema = z.looseObject({ templates: z.array(idSchema) });
+export const savedTemplateSchema = z.looseObject({ templateId: z.string() });
+export const deletedCountSchema = z.looseObject({ deletedCount: z.number() });
diff --git a/tests/mcp-isolation/tenants.ts b/tests/mcp-isolation/tenants.ts
new file mode 100644
index 00000000..facd8929
--- /dev/null
+++ b/tests/mcp-isolation/tenants.ts
@@ -0,0 +1,209 @@
+import { randomBytes } from "node:crypto";
+import {
+ expect,
+ type APIRequest,
+ type APIRequestContext,
+ type Browser,
+} from "@playwright/test";
+import { z } from "zod";
+import {
+ authorizeOAuth,
+ createApiKey,
+ listOrganizations,
+ signUp,
+ type Account,
+} from "./auth";
+import { check } from "./checks";
+import {
+ callTool,
+ describeResult,
+ structured,
+ type Credential,
+ type ToolCall,
+} from "./mcp";
+import {
+ createdProjectSchema,
+ savedKeywordsSchema,
+ savedReportSchema,
+ savedTemplateSchema,
+} from "./schemas";
+
+// Run-unique suffix: emails, the marker and the intruder strings all carry it.
+export const RUN = randomBytes(4).toString("hex");
+// OAuth client names: A's two grants must be tellable apart in Settings.
+export const CLIENT_A = "Isolation Test";
+export const CLIENT_A_IN_B = "Isolation Test (B workspace)";
+export const KEY_A = "Isolation key A";
+export const KEY_A_IN_B = "Isolation key A in B";
+// What A tries to write into B's workspace; must never land anywhere.
+export const INTRUDER = `intruder-a-${RUN}`;
+
+export type Tenant = Account & {
+ orgId: string;
+ orgName: string;
+ projectId: string;
+ oauth: Credential;
+ apiKey: Credential;
+};
+
+export type SeededData = {
+ marker: string;
+ reportId: string;
+ templateId: string;
+ keywordIds: string[];
+ /** Every B identifier that must never show up in A's responses. */
+ secrets: string[];
+};
+
+export function reportHtml(title: string, body: string) {
+ return `<!doctype html><html lang="en"><head><meta charset="utf-8"><title>${title}</title></head><body><h1>${title}</h1><p>${body}</p></body></html>`;
+}
+
+/**
+ * Signs a user up, authorizes an OAuth grant (asserting the consent page
+ * names the user and the workspace), creates an API key and a project.
+ */
+export async function setupTenant(
+ label: "A" | "B",
+ deps: {
+ request: APIRequest;
+ browser: Browser;
+ anon: APIRequestContext;
+ baseURL: string;
+ },
+): Promise<Tenant> {
+ const account = await signUp(deps.request, deps.baseURL, {
+ label,
+ name: `${label === "A" ? "Alice" : "Bob"} Isolation ${RUN}`,
+ email: `isolation-${label.toLowerCase()}-${RUN}@example.com`,
+ password: `Isolation-${RUN}-pass`,
+ });
+ const chapter = "1 setup";
+ const organizations = await listOrganizations(account);
+ check({
+ chapter,
+ credential: `${label} session`,
+ tool: "sign-up",
+ expectation: "exactly one organization to bind credentials to",
+ ok: organizations.length === 1,
+ detail: organizations.map((org) => `${org.name} (${org.id})`).join(", "),
+ });
+ expect(organizations, `${label} has exactly one organization`).toHaveLength(
+ 1,
+ );
+ const org = organizations[0];
+ // A fresh account belongs to one organization, so the consent page names
+ // no workspace; chapter 4 checks the row once A belongs to two.
+ const oauth = await authorizeOAuth(deps.browser, deps.anon, account, {
+ clientName: CLIENT_A,
+ expectedWorkspace: null,
+ });
+ const apiKey = await createApiKey(account, `Isolation key ${label}`);
+ // No organizationId argument: the credential is bound to one workspace.
+ const createCall = await callTool(deps.anon, oauth, {
+ name: "create_project",
+ arguments: { name: `Isolation ${label} ${RUN}` },
+ });
+ check({
+ chapter,
+ credential: oauth.label,
+ tool: "create_project",
+ expectation: "accepted without an organizationId argument",
+ ok: createCall.isError === false,
+ detail: describeResult(createCall),
+ });
+ const created = structured(
+ createCall,
+ createdProjectSchema,
+ `create_project for ${label}`,
+ );
+ return {
+ ...account,
+ orgId: org.id,
+ orgName: org.name,
+ projectId: created.project.id,
+ oauth,
+ apiKey,
+ };
+}
+
+/** B writes its marker into context, a saved keyword, a report and a template. */
+export async function seedTenantB(
+ anon: APIRequestContext,
+ b: Tenant,
+): Promise<SeededData> {
+ const marker = `secret-b-${RUN}`;
+ const projectId = b.projectId;
+ const seed = (call: ToolCall) => callTool(anon, b.oauth, call);
+
+ structured(
+ await seed({
+ name: "update_project_context",
+ arguments: {
+ projectId,
+ updates: [
+ { section: "business_overview", content: `Confidential ${marker}` },
+ ],
+ },
+ }),
+ z.unknown(),
+ "seed project context",
+ );
+ structured(
+ await seed({
+ name: "save_keywords",
+ arguments: { projectId, keywords: [marker] },
+ }),
+ z.unknown(),
+ "seed saved keyword",
+ );
+ const keywords = structured(
+ await seed({ name: "list_saved_keywords", arguments: { projectId } }),
+ savedKeywordsSchema,
+ "list seeded keywords",
+ );
+ const keywordIds = keywords.rows.map((row) => row.id);
+ expect(keywordIds.length, "B has a saved keyword").toBeGreaterThan(0);
+ const report = structured(
+ await seed({
+ name: "save_report",
+ arguments: {
+ projectId,
+ title: `Isolation report ${marker}`,
+ summary: `Summary with ${marker}`,
+ html: reportHtml(`Isolation report ${marker}`, `Body with ${marker}`),
+ skill: "isolation-test",
+ },
+ }),
+ savedReportSchema,
+ "seed report",
+ );
+ const template = structured(
+ await seed({
+ name: "save_report_template",
+ arguments: {
+ projectId,
+ name: `Isolation template ${marker}`,
+ description: `Template carrying ${marker}`,
+ instructions: `Always mention ${marker}.`,
+ },
+ }),
+ savedTemplateSchema,
+ "seed report template",
+ );
+ return {
+ marker,
+ reportId: report.reportId,
+ templateId: template.templateId,
+ keywordIds,
+ secrets: [
+ marker,
+ b.projectId,
+ report.reportId,
+ template.templateId,
+ ...keywordIds,
+ b.orgId,
+ b.email,
+ ],
+ };
+}
diff --git a/tests/mcp-tenant-isolation.spec.ts b/tests/mcp-tenant-isolation.spec.ts
new file mode 100644
index 00000000..707364ba
--- /dev/null
+++ b/tests/mcp-tenant-isolation.spec.ts
@@ -0,0 +1,416 @@
+import { fileURLToPath } from "node:url";
+import { expect, test, type APIRequestContext } from "@playwright/test";
+import {
+ acceptInvitation,
+ authorizeOAuth,
+ createApiKey,
+ inviteMember,
+ removeMember,
+ setActiveOrganization,
+} from "./mcp-isolation/auth";
+import { check, writeReport } from "./mcp-isolation/checks";
+import {
+ checkTenantBUnchanged,
+ foreignProjectCalls,
+ foreignResourceCalls,
+ leaked,
+} from "./mcp-isolation/matrix";
+import {
+ callTool,
+ describeResult,
+ type Credential,
+ type ToolCall,
+} from "./mcp-isolation/mcp";
+import {
+ deletedCountSchema,
+ projectsSchema,
+ whoamiSchema,
+} from "./mcp-isolation/schemas";
+import {
+ CLIENT_A,
+ CLIENT_A_IN_B,
+ KEY_A,
+ KEY_A_IN_B,
+ RUN,
+ seedTenantB,
+ setupTenant,
+ type SeededData,
+ type Tenant,
+} from "./mcp-isolation/tenants";
+
+/**
+ * Two-account tenant isolation through the real hosted /mcp endpoint.
+ *
+ * Run: pnpm test:e2e:mcp-isolation
+ *
+ * Prerequisites
+ * - .env.local in hosted mode with real BETTER_AUTH_SECRET, GOOGLE_CLIENT_ID,
+ * GOOGLE_CLIENT_SECRET (any non-empty values work for email/password
+ * sign-up) and no TURNSTILE_SITE_KEY. The config overrides AUTH_MODE, PORT,
+ * BYPASS_EMAIL_VERIFICATION and BETTER_AUTH_URL for the server it boots on
+ * :3108 (see tests/playwright.mcp-isolation.config.ts for how).
+ * - The local D1 database is migrated (pnpm db:migrate:local). The suite
+ * shares .wrangler/state with `pnpm dev`; stop the :3107 server first or
+ * expect sporadic "database is locked" errors.
+ * - Chrome (PLAYWRIGHT_CHANNEL=chrome by default) for the consent page and
+ * the Settings revocation steps.
+ *
+ * Side effects: two throwaway accounts and organizations per run (emails end
+ * in @example.com). `whoami` initializes billing for both organizations, so
+ * AUTUMN_SECRET_KEY should point at a sandbox. Only free tools are called; no
+ * DataForSEO spend.
+ *
+ * Every verdict lands in .logs/mcp-isolation/report.md.
+ */
+
+const REPORT_PATH = fileURLToPath(
+ new URL("../.logs/mcp-isolation/report.md", import.meta.url),
+);
+
+// Shared across the serial chapters below (one worker, one module instance).
+let anon: APIRequestContext;
+let a: Tenant;
+let b: Tenant;
+let seeded: SeededData;
+
+const readProject = (projectId: string): ToolCall => ({
+ name: "get_project_context",
+ arguments: { projectId },
+});
+
+test.describe.configure({ mode: "serial" });
+
+test.afterAll(async () => {
+ await writeReport(REPORT_PATH, {
+ Run: RUN,
+ Date: new Date().toISOString(),
+ "Account A": a?.email ?? "(setup failed)",
+ "Account B": b?.email ?? "(setup failed)",
+ });
+ await Promise.all(
+ [anon, a?.api, b?.api].map((context) => context?.dispose()),
+ );
+});
+
+test("1. setup: two accounts, OAuth grant + API key each, B seeds marked data", async ({
+ playwright,
+ browser,
+ baseURL,
+}) => {
+ if (!baseURL) throw new Error("baseURL is required");
+ anon = await playwright.request.newContext({ baseURL });
+ const deps = { request: playwright.request, browser, anon, baseURL };
+ await test.step("sign up A with an OAuth grant, an API key and a project", async () => {
+ a = await setupTenant("A", deps);
+ });
+ await test.step("sign up B with an OAuth grant, an API key and a project", async () => {
+ b = await setupTenant("B", deps);
+ });
+ expect(a.orgId).not.toBe(b.orgId);
+ await test.step("B seeds context, a keyword, a report and a template carrying its marker", async () => {
+ seeded = await seedTenantB(anon, b);
+ });
+});
+
+test("2. baseline: each account reads its own data; list_projects stays inside the workspace", async () => {
+ const chapter = "2 baseline";
+ for (const [tenant, other] of [
+ [a, b],
+ [b, a],
+ ] as const) {
+ for (const credential of [tenant.oauth, tenant.apiKey]) {
+ await test.step(`${credential.label} reads its own project`, async () => {
+ const context = await callTool(
+ anon,
+ credential,
+ readProject(tenant.projectId),
+ );
+ check({
+ chapter,
+ credential: credential.label,
+ tool: "get_project_context",
+ expectation: "own project readable",
+ ok:
+ context.isError === false &&
+ (tenant !== b || context.text.includes(seeded.marker)),
+ detail: describeResult(context),
+ });
+
+ const whoami = await callTool(anon, credential, { name: "whoami" });
+ const identity = whoamiSchema.safeParse(whoami.structuredContent);
+ check({
+ chapter,
+ credential: credential.label,
+ tool: "whoami",
+ expectation: `reports ${tenant.email}`,
+ ok:
+ whoami.isError === false &&
+ identity.success &&
+ identity.data.userEmail === tenant.email,
+ detail: describeResult(whoami),
+ });
+
+ const projects = await callTool(anon, credential, {
+ name: "list_projects",
+ });
+ const listed = projectsSchema.safeParse(projects.structuredContent);
+ const ids = listed.success
+ ? listed.data.projects.map((project) => project.id)
+ : [];
+ check({
+ chapter,
+ credential: credential.label,
+ tool: "list_projects",
+ expectation: "lists only the bound workspace's project",
+ ok:
+ projects.isError === false &&
+ ids.length === 1 &&
+ ids[0] === tenant.projectId &&
+ !ids.includes(other.projectId),
+ detail: `${describeResult(projects)} | ids=${ids.join(",")}`,
+ });
+ });
+ }
+ }
+});
+
+test("3. cross-tenant matrix: A cannot read, change, delete or export B's data", async () => {
+ const chapter = "3 cross-tenant";
+ const matrix = [
+ { suffix: "B project", calls: foreignProjectCalls(b, seeded) },
+ { suffix: "A project, B id", calls: foreignResourceCalls(a, seeded) },
+ ];
+ for (const credential of [a.oauth, a.apiKey]) {
+ for (const { suffix, calls } of matrix) {
+ await test.step(`${credential.label}: ${suffix}`, async () => {
+ for (const call of calls) {
+ const result = await callTool(anon, credential, call);
+ const leaks = leaked(result, call, seeded);
+ check({
+ chapter,
+ credential: credential.label,
+ tool: `${call.name} (${suffix})`,
+ expectation: "tool error, nothing of B's in the response",
+ ok:
+ result.status === 200 &&
+ result.isError === true &&
+ leaks.length === 0,
+ detail: `${describeResult(result)}${leaks.length > 0 ? ` | LEAKED ${leaks.join(",")}` : ""}`,
+ });
+ }
+ });
+ }
+
+ await test.step(`${credential.label}: remove_saved_keywords with B's ids deletes nothing`, async () => {
+ // remove_saved_keywords ignores foreign ids by contract (no error), so
+ // the invariant is "deleted nothing" rather than isError.
+ const call: ToolCall = {
+ name: "remove_saved_keywords",
+ arguments: {
+ projectId: a.projectId,
+ savedKeywordIds: seeded.keywordIds,
+ },
+ };
+ const result = await callTool(anon, credential, call);
+ const count = deletedCountSchema.safeParse(result.structuredContent);
+ check({
+ chapter,
+ credential: credential.label,
+ tool: "remove_saved_keywords (A project, B ids)",
+ expectation: "deletes nothing",
+ ok:
+ result.isError === false &&
+ count.success &&
+ count.data.deletedCount === 0 &&
+ leaked(result, call, seeded).length === 0,
+ detail: describeResult(result),
+ });
+ });
+ }
+
+ await test.step("as B: nothing changed", () =>
+ checkTenantBUnchanged(anon, b, seeded, chapter));
+});
+
+test("4. membership: credentials are bound to the workspace they were created in", async ({
+ browser,
+}) => {
+ const chapter = "4 membership";
+ const readB = readProject(b.projectId);
+
+ await test.step("B invites A as admin and A accepts", async () => {
+ const invitationId = await inviteMember(b, {
+ email: a.email,
+ organizationId: b.orgId,
+ });
+ await acceptInvitation(a, invitationId);
+ });
+
+ await test.step("A's original credentials still cannot read B's project", async () => {
+ for (const credential of [a.oauth, a.apiKey]) {
+ const result = await callTool(anon, credential, readB);
+ check({
+ chapter,
+ credential: credential.label,
+ tool: "get_project_context (B project, A is now a member)",
+ expectation: "still a tool error: bound to A's workspace",
+ ok:
+ result.status === 200 &&
+ result.isError === true &&
+ leaked(result, readB, seeded).length === 0,
+ detail: describeResult(result),
+ });
+ }
+ });
+
+ let oauthInB: Credential;
+ let apiKeyInB: Credential;
+ await test.step("A switches to B's workspace on the consent page, then creates a key there", async () => {
+ // Start from A's own workspace so the grant can only land in B's through
+ // the consent page's switcher.
+ await setActiveOrganization(a, a.orgId);
+ oauthInB = await authorizeOAuth(browser, anon, a, {
+ clientName: CLIENT_A_IN_B,
+ expectedWorkspace: a.orgName,
+ switchToWorkspace: b.orgName,
+ });
+ // Same switch as the account menu: it carries over to A's session.
+ apiKeyInB = await createApiKey(a, KEY_A_IN_B);
+ for (const credential of [oauthInB, apiKeyInB]) {
+ const result = await callTool(anon, credential, readB);
+ check({
+ chapter,
+ credential: credential.label,
+ tool: "get_project_context (B project)",
+ expectation: "readable: the marker appears",
+ ok: result.isError === false && result.text.includes(seeded.marker),
+ detail: describeResult(result),
+ });
+ }
+ });
+
+ await test.step("B removes A: the B-bound credentials stop working", async () => {
+ await removeMember(b, { email: a.email, organizationId: b.orgId });
+
+ const oauthResult = await callTool(anon, oauthInB, readB);
+ // The transport answers a dead membership with 401 + WWW-Authenticate:
+ // Bearer error="invalid_token" (src/server/mcp/transport.ts).
+ check({
+ chapter,
+ credential: oauthInB.label,
+ tool: "get_project_context (after removal)",
+ expectation: "HTTP 401 with invalid_token challenge",
+ ok:
+ oauthResult.status === 401 &&
+ /invalid_token/.test(oauthResult.headers["www-authenticate"] ?? "") &&
+ leaked(oauthResult, readB, seeded).length === 0,
+ detail: describeResult(oauthResult),
+ });
+
+ const keyResult = await callTool(anon, apiKeyInB, readB);
+ // The API-key path answers a dead membership with 403 +
+ // { error: "account_access_revoked" } (src/server/mcp/api-key-auth.ts).
+ check({
+ chapter,
+ credential: apiKeyInB.label,
+ tool: "get_project_context (after removal)",
+ expectation: "HTTP 403 account_access_revoked",
+ ok:
+ keyResult.status === 403 &&
+ keyResult.errorCode === "account_access_revoked" &&
+ leaked(keyResult, readB, seeded).length === 0,
+ detail: describeResult(keyResult),
+ });
+ });
+
+ await test.step("A's own-workspace credentials still work", async () => {
+ await setActiveOrganization(a, a.orgId);
+ for (const credential of [a.oauth, a.apiKey]) {
+ const result = await callTool(anon, credential, readProject(a.projectId));
+ check({
+ chapter,
+ credential: credential.label,
+ tool: "get_project_context (A project)",
+ expectation: "still readable",
+ ok: result.isError === false,
+ detail: describeResult(result),
+ });
+ }
+ });
+});
+
+test("5. revocation in Settings: disconnecting the agent and revoking the key block further calls", async ({
+ browser,
+}) => {
+ const chapter = "5 revocation";
+ const readA = readProject(a.projectId);
+ const context = await browser.newContext({
+ baseURL: a.baseURL,
+ storageState: await a.api.storageState(),
+ });
+ const page = await context.newPage();
+ try {
+ // No onboarding redirect: A's OAuth consent and create_project call have
+ // already completed onboarding (completeOnboardingFromAgent).
+ await page.goto("/settings");
+
+ await test.step("Settings -> Connected agents -> Disconnect", async () => {
+ await expect(page.getByText("Connected agents").first()).toBeVisible();
+ // RowActionsMenu aria-label is `Actions for ${clientName}`
+ // (src/client/features/settings/McpConnectionsSettings.tsx); A has two
+ // grants (CLIENT_A and CLIENT_A_IN_B), hence exact matching.
+ const actions = page.getByRole("button", {
+ name: `Actions for ${CLIENT_A}`,
+ exact: true,
+ });
+ await actions.click();
+ await page.getByRole("menuitem", { name: "Disconnect" }).click();
+ await page
+ .getByRole("alertdialog")
+ .getByRole("button", { name: "Disconnect", exact: true })
+ .click();
+ await expect(actions).toHaveCount(0);
+
+ const result = await callTool(anon, a.oauth, readA);
+ check({
+ chapter,
+ credential: a.oauth.label,
+ tool: "get_project_context (after Disconnect)",
+ expectation: "HTTP 401 with invalid_token challenge",
+ ok:
+ result.status === 401 &&
+ /invalid_token/.test(result.headers["www-authenticate"] ?? ""),
+ detail: describeResult(result),
+ });
+ });
+
+ await test.step("Settings -> API keys -> Revoke key", async () => {
+ await expect(page.getByText("API keys").first()).toBeVisible();
+ // aria-label `Actions for ${key.name}` and the "Revoke key" item/confirm
+ // label come from ApiKeySettings.tsx.
+ const actions = page.getByRole("button", {
+ name: `Actions for ${KEY_A}`,
+ exact: true,
+ });
+ await actions.click();
+ await page.getByRole("menuitem", { name: "Revoke key" }).click();
+ await page
+ .getByRole("alertdialog")
+ .getByRole("button", { name: "Revoke key", exact: true })
+ .click();
+ await expect(actions).toHaveCount(0);
+
+ const result = await callTool(anon, a.apiKey, readA);
+ check({
+ chapter,
+ credential: a.apiKey.label,
+ tool: "get_project_context (after Revoke key)",
+ expectation: "HTTP 401 invalid_api_key",
+ ok: result.status === 401 && result.errorCode === "invalid_api_key",
+ detail: describeResult(result),
+ });
+ });
+ } finally {
+ await context.close();
+ }
+});
diff --git a/tests/playwright.mcp-isolation.config.ts b/tests/playwright.mcp-isolation.config.ts
new file mode 100644
index 00000000..aa287292
--- /dev/null
+++ b/tests/playwright.mcp-isolation.config.ts
@@ -0,0 +1,60 @@
+import { fileURLToPath } from "node:url";
+import { defineConfig } from "@playwright/test";
+
+const repoRoot = fileURLToPath(new URL("..", import.meta.url));
+const PORT = 3108;
+const BASE_URL = `http://localhost:${PORT}`;
+
+// Two-account tenant-isolation suite against the real hosted /mcp endpoint.
+// It boots its own hosted-mode dev server on :3108 so it never shares a port
+// with `pnpm dev` (:3107). Prerequisites are listed at the top of
+// tests/mcp-tenant-isolation.spec.ts.
+//
+// How the overrides reach the Worker: @cloudflare/vite-plugin builds the
+// Worker env with wrangler's getVarsForDev, which reads .env and .env.local
+// from the repo root and ignores process.env by default. With
+// CLOUDFLARE_INCLUDE_PROCESS_ENV=true wrangler merges process.env in, and a
+// process value wins over the file value for the same key (dotenv-expand's
+// precedence), so AUTH_MODE / PORT / BETTER_AUTH_URL below override .env.local
+// for this server only, while BETTER_AUTH_SECRET, GOOGLE_*, AUTUMN_* and the
+// rest still come from .env.local. Side effect: every variable of the shell
+// that launches Playwright becomes a secret binding of this dev Worker, which
+// is harmless locally. vite.config.ts reads PORT from process.env first, so
+// the Vite server itself moves to :3108 as well.
+export default defineConfig({
+ // Keep test-results/ at the repo root (see .gitignore).
+ outputDir: "../test-results",
+ testDir: ".",
+ testMatch: "mcp-tenant-isolation.spec.ts",
+ // The cross-tenant matrix alone is ~60 MCP calls against a cold dev server.
+ timeout: 240_000,
+ expect: {
+ timeout: 10_000,
+ },
+ fullyParallel: false,
+ workers: 1,
+ reporter: [["list"]],
+ use: {
+ baseURL: BASE_URL,
+ actionTimeout: 10_000,
+ navigationTimeout: 30_000,
+ channel: process.env.PLAYWRIGHT_CHANNEL ?? "chrome",
+ screenshot: "only-on-failure",
+ trace: "retain-on-failure",
+ },
+ webServer: {
+ cwd: repoRoot,
+ command: "pnpm exec vite dev --host 127.0.0.1 --strictPort",
+ env: {
+ NODE_OPTIONS: "",
+ CLOUDFLARE_INCLUDE_PROCESS_ENV: "true",
+ AUTH_MODE: "hosted",
+ BYPASS_EMAIL_VERIFICATION: "true",
+ PORT: String(PORT),
+ BETTER_AUTH_URL: BASE_URL,
+ },
+ url: BASE_URL,
+ reuseExistingServer: false,
+ timeout: 180_000,
+ },
+});
diff --git a/web/content/docs/mcp.md b/web/content/docs/mcp.md
index 16fd5b35..8b717dd8 100644
--- a/web/content/docs/mcp.md
+++ b/web/content/docs/mcp.md
@@ -90,7 +90,7 @@ This local connection is separate from ChatGPT web. See [OpenAI's MCP documentat
## Connect with an API key
-Use an API key in headless environments, CI, or clients where OAuth is inconvenient. API keys are personal: anything an agent does with your key acts as you in your workspace.
+Use an API key in headless environments, CI, or clients where OAuth is inconvenient. API keys are personal: anything an agent does with your key acts as you in the workspace that was active when you created it.
In the [OpenSEO app](https://app.openseo.so/settings), open **Settings -> API keys**, create a key, and copy it when it appears. It won't be shown again.
@@ -124,6 +124,10 @@ codex mcp add openseo --url https://app.openseo.so/mcp --bearer-token-env-var OP
Any other client that supports custom HTTP headers can send `Authorization: Bearer oseo_YOUR_KEY` or `x-api-key: oseo_YOUR_KEY`.
+## Workspaces and revoking access
+
+An OAuth connection or API key is tied to the workspace that was active when you authorized or created it. To use OpenSEO in another workspace, connect again and pick that workspace on the authorization page, or switch to it in the app before creating a key. To disconnect an agent, open [Settings](https://app.openseo.so/settings) and choose **Disconnect** under **Connected agents**. To revoke a key, choose **Revoke key** under **API keys**. A disconnected agent has to sign in again before it can call OpenSEO.
+
## Available tools
OpenSEO MCP exposes tools for SEO research workflows: