A full-featured CRM built with React, shadcn/ui, and Supabase.
Make SQL filtering more robust
fzaninotto1f0747a69ddf
diff --git a/package-lock.json b/package-lock.jsonindex eb2bacf9..a4e4674c 100644--- a/package-lock.json+++ b/package-lock.json@@ -102,6 +102,7 @@"glob": "^11.1.0","globals": "^16.3.0","husky": "^9.1.7",+ "pgsql-ast-parser": "^12.0.2","playwright": "^1.58.2","prettier": "^3.6.2","shadcn": "^3.5.0",@@ -10950,6 +10951,13 @@"node": ">=8"}},+ "node_modules/discontinuous-range": {+ "version": "1.0.0",+ "resolved": "https://registry.npmjs.org/discontinuous-range/-/discontinuous-range-1.0.0.tgz",+ "integrity": "sha512-c68LpLbO+7kP/b1Hr1qs8/BJ09F5khZGTxqxZuhzxpmwJKOgRFHJWIb9/KmqnqHhLdO55aOxFH/EGBvUQbL/RQ==",+ "dev": true,+ "license": "MIT"+ },"node_modules/doctrine": {"version": "3.0.0","resolved": "https://registry.npmjs.org/doctrine/-/doctrine-3.0.0.tgz",@@ -14198,6 +14206,13 @@"node": ">=16 || 14 >=14.17"}},+ "node_modules/moo": {+ "version": "0.5.3",+ "resolved": "https://registry.npmjs.org/moo/-/moo-0.5.3.tgz",+ "integrity": "sha512-m2fmM2dDm7GZQsY7KK2cme8agi+AAljILjQnof7p1ZMDe6dQ4bdnSMx0cPppudoeNv5hEFQirN6u+O4fDE0IWA==",+ "dev": true,+ "license": "BSD-3-Clause"+ },"node_modules/mrmime": {"version": "2.0.1","resolved": "https://registry.npmjs.org/mrmime/-/mrmime-2.0.1.tgz",@@ -14294,6 +14309,36 @@"dev": true,"license": "MIT"},+ "node_modules/nearley": {+ "version": "2.20.1",+ "resolved": "https://registry.npmjs.org/nearley/-/nearley-2.20.1.tgz",+ "integrity": "sha512-+Mc8UaAebFzgV+KpI5n7DasuuQCHA89dmwm7JXw3TV43ukfNQ9DnBH3Mdb2g/I4Fdxc26pwimBWvjIw0UAILSQ==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "commander": "^2.19.0",+ "moo": "^0.5.0",+ "railroad-diagrams": "^1.0.0",+ "randexp": "0.4.6"+ },+ "bin": {+ "nearley-railroad": "bin/nearley-railroad.js",+ "nearley-test": "bin/nearley-test.js",+ "nearley-unparse": "bin/nearley-unparse.js",+ "nearleyc": "bin/nearleyc.js"+ },+ "funding": {+ "type": "individual",+ "url": "https://nearley.js.org/#give-to-nearley"+ }+ },+ "node_modules/nearley/node_modules/commander": {+ "version": "2.20.3",+ "resolved": "https://registry.npmjs.org/commander/-/commander-2.20.3.tgz",+ "integrity": "sha512-GpVkmM8vF2vQUkj2LvZmD35JxeJOLCwJ9cUkugyk2nuhbv3+mJvpLYYt+0+USMxE+oj+ey/lJEnhZw75x/OMcQ==",+ "dev": true,+ "license": "MIT"+ },"node_modules/negotiator": {"version": "1.0.0","resolved": "https://registry.npmjs.org/negotiator/-/negotiator-1.0.0.tgz",@@ -14900,6 +14945,17 @@"node": ">= 14.16"}},+ "node_modules/pgsql-ast-parser": {+ "version": "12.0.2",+ "resolved": "https://registry.npmjs.org/pgsql-ast-parser/-/pgsql-ast-parser-12.0.2.tgz",+ "integrity": "sha512-1WWa96Sw6h4uv9GLw98EzH/+xoBTC8j2TwV/AMW3E+Ir/fHOu/jLLbj6kPiz3y2bGISTKNYvKWwHoqvQ5FLuAw==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "moo": "^0.5.1",+ "nearley": "^2.19.5"+ }+ },"node_modules/picocolors": {"version": "1.1.1","resolved": "https://registry.npmjs.org/picocolors/-/picocolors-1.1.1.tgz",@@ -15591,6 +15647,27 @@"integrity": "sha512-tQkJl2GRWh83ui2DiPTJz9wEiMN20syf+5oKfB03yYP7ioZcJwsIK8FjrtLwH1m7C7e+Tt2yYBlrOpdT+dyeIQ==","license": "MIT"},+ "node_modules/railroad-diagrams": {+ "version": "1.0.0",+ "resolved": "https://registry.npmjs.org/railroad-diagrams/-/railroad-diagrams-1.0.0.tgz",+ "integrity": "sha512-cz93DjNeLY0idrCNOH6PviZGRN9GJhsdm9hpn1YCS879fj4W+x5IFJhhkRZcwVgMmFF7R82UA/7Oh+R8lLZg6A==",+ "dev": true,+ "license": "CC0-1.0"+ },+ "node_modules/randexp": {+ "version": "0.4.6",+ "resolved": "https://registry.npmjs.org/randexp/-/randexp-0.4.6.tgz",+ "integrity": "sha512-80WNmd9DA0tmZrw9qQa62GPPWfuXJknrmVmLcxvq4uZBdYqb1wYoKTmnlGUchvVWe0XiLupYkBoXVOxz3C8DYQ==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "discontinuous-range": "1.0.0",+ "ret": "~0.1.10"+ },+ "engines": {+ "node": ">=0.12"+ }+ },"node_modules/randombytes": {"version": "2.1.0","resolved": "https://registry.npmjs.org/randombytes/-/randombytes-2.1.0.tgz",@@ -16110,6 +16187,16 @@"url": "https://github.com/sponsors/sindresorhus"}},+ "node_modules/ret": {+ "version": "0.1.15",+ "resolved": "https://registry.npmjs.org/ret/-/ret-0.1.15.tgz",+ "integrity": "sha512-TTlYpa+OL+vMMNG24xSlQGEJ3B/RzEfUlLct7b5G/ytav+wPrplCpVMFuwzXbkecJrb6IYo1iFb0S9v37754mg==",+ "dev": true,+ "license": "MIT",+ "engines": {+ "node": ">=0.12"+ }+ },"node_modules/rettime": {"version": "0.7.0","resolved": "https://registry.npmjs.org/rettime/-/rettime-0.7.0.tgz",diff --git a/package.json b/package.jsonindex 3b59c469..f4674044 100644--- a/package.json+++ b/package.json@@ -120,6 +120,7 @@"glob": "^11.1.0","globals": "^16.3.0","husky": "^9.1.7",+ "pgsql-ast-parser": "^12.0.2","playwright": "^1.58.2","prettier": "^3.6.2","shadcn": "^3.5.0",diff --git a/supabase/functions/mcp/index.ts b/supabase/functions/mcp/index.tsindex a169ef17..9fcc513b 100644--- a/supabase/functions/mcp/index.ts+++ b/supabase/functions/mcp/index.ts@@ -4,6 +4,7 @@ import { WebStandardStreamableHTTPServerTransport } from "npm:@modelcontextprotoimport { createRemoteJWKSet, jwtVerify, decodeJwt } from "npm:jose@5";import { Pool } from "https://deno.land/x/[email protected]/mod.ts";import { z } from "npm:zod@^3.25";+import { validateReadOnly, validateWrite } from "./validateSql.ts";import { corsHeaders } from "../_shared/cors.ts";// --- Environment & Config ---@@ -200,50 +201,6 @@ async function getSchemaData(): Promise<string> {}}-// --- SQL Validation -----const ALLOWED_READ_STATEMENTS = /^\s*(SELECT|WITH)\b/i;-const ALLOWED_WRITE_STATEMENTS = /^\s*(INSERT|UPDATE|DELETE|WITH)\b/i;-// Keywords blocked in all queries (DDL, admin commands, etc.)-const BLOCKED_KEYWORDS =- /\b(DROP|ALTER|CREATE|TRUNCATE|GRANT|REVOKE|COPY|VACUUM|REINDEX|CLUSTER|COMMENT|SECURITY\s+LABEL|DO\s*\$|CALL|RESET|LOAD|LISTEN|NOTIFY|UNLISTEN|DISCARD|PREPARE|EXECUTE|DEALLOCATE)\b/i;-// DML keywords that must not appear inside read-only queries-// (e.g. writable CTEs: WITH d AS (DELETE FROM t RETURNING *) SELECT ...)-const WRITE_KEYWORDS = /\b(INSERT|UPDATE|DELETE)\b/i;-// SET is valid inside UPDATE (e.g. "UPDATE t SET col = val") but not as a-// standalone statement (e.g. "SET search_path = ..."). Block it only when it-// appears at the statement level.-const BLOCKED_STATEMENT_SET = /^\s*SET\b/i;--function validateReadOnly(sql: string): string | null {- if (!ALLOWED_READ_STATEMENTS.test(sql)) {- return "Only SELECT and WITH statements are allowed. Use the mutate tool for INSERT, UPDATE, or DELETE.";- }- const writeMatch = sql.match(WRITE_KEYWORDS);- if (writeMatch) {- return `Write operation ${writeMatch[0].toUpperCase()} is not allowed in read-only queries. Use the mutate tool instead.`;- }- const match = sql.match(BLOCKED_KEYWORDS);- if (match) {- return `Disallowed keyword: ${match[0].toUpperCase()}`;- }- return null;-}--function validateWrite(sql: string): string | null {- if (!ALLOWED_WRITE_STATEMENTS.test(sql)) {- return "Only INSERT, UPDATE, DELETE, and WITH statements are allowed. Use the query tool for SELECT.";- }- if (BLOCKED_STATEMENT_SET.test(sql)) {- return "Disallowed keyword: SET";- }- const match = sql.match(BLOCKED_KEYWORDS);- if (match) {- return `Disallowed keyword: ${match[0].toUpperCase()}`;- }- return null;-}-// --- Database: query with RLS ---async function executeQueryWithRLS(diff --git a/supabase/functions/mcp/validateSql.test.ts b/supabase/functions/mcp/validateSql.test.tsnew file mode 100644index 00000000..eaba3ee5--- /dev/null+++ b/supabase/functions/mcp/validateSql.test.ts@@ -0,0 +1,122 @@+// @vitest-environment node+import { describe, it, expect } from "vitest";+import { validateReadOnly, validateWrite } from "./validateSql";++describe("validateReadOnly", () => {+ it.each([+ ["simple SELECT", "SELECT * FROM contacts"],+ [+ "SELECT with WHERE",+ "SELECT id, name FROM contacts WHERE created_at > NOW() - INTERVAL '30 days'",+ ],+ [+ "SELECT with JOIN",+ "SELECT c.name, co.name FROM contacts c JOIN companies co ON c.company_id = co.id",+ ],+ [+ "SELECT with subquery",+ "SELECT * FROM contacts WHERE company_id IN (SELECT id FROM companies WHERE sector = 'Tech')",+ ],+ [+ "read-only CTE",+ "WITH recent AS (SELECT * FROM contacts WHERE created_at > NOW() - INTERVAL '7 days') SELECT * FROM recent",+ ],+ [+ "aggregate query",+ "SELECT COUNT(*) as total, type FROM tasks GROUP BY type",+ ],+ [+ "DELETE in string literal",+ "SELECT * FROM contacts WHERE status = 'DELETE'",+ ],+ [+ "DROP in string literal",+ "SELECT * FROM logs WHERE message = 'DROP TABLE failed'",+ ],+ [+ "UPDATE in string literal",+ "SELECT * FROM contacts WHERE note = 'Please UPDATE your info'",+ ],+ [+ "DROP in block comment",+ "SELECT /* DROP TABLE contacts */ * FROM contacts",+ ],+ ["DROP in line comment", "SELECT * FROM contacts -- DROP TABLE contacts"],+ ])("allows %s", (_label, sql) => {+ expect(validateReadOnly(sql)).toBeNull();+ });++ it.each([+ ["INSERT", "INSERT INTO contacts (name) VALUES ('test')"],+ ["UPDATE", "UPDATE contacts SET name = 'test'"],+ ["DELETE", "DELETE FROM contacts WHERE id = 1"],+ [+ "writable CTE (DELETE)",+ "WITH d AS (DELETE FROM contacts RETURNING *) SELECT * FROM d",+ ],+ [+ "writable CTE (UPDATE)",+ "WITH u AS (UPDATE contacts SET name = 'x' RETURNING *) SELECT * FROM u",+ ],+ [+ "writable CTE (INSERT)",+ "WITH i AS (INSERT INTO contacts (name) VALUES ('x') RETURNING *) SELECT * FROM i",+ ],+ ["DROP TABLE", "DROP TABLE contacts"],+ ["CREATE TABLE", "CREATE TABLE evil (id int)"],+ ["ALTER TABLE", "ALTER TABLE contacts ADD COLUMN x int"],+ ["TRUNCATE", "TRUNCATE contacts"],+ ["SET", "SET LOCAL role = 'postgres'"],+ ["DO block", "DO $$ BEGIN END $$"],+ ["multi-statement (SELECT; DROP)", "SELECT 1; DROP TABLE contacts"],+ ["multi-statement (SELECT; SET)", "SELECT 1; SET LOCAL role = 'postgres'"],+ ["multi-statement (two SELECTs)", "SELECT 1; SELECT 2"],+ ["unparseable SQL", "NOT VALID SQL %%%"],+ ])("rejects %s", (_label, sql) => {+ expect(validateReadOnly(sql)).not.toBeNull();+ });+});++describe("validateWrite", () => {+ it.each([+ [+ "INSERT",+ "INSERT INTO contacts (first_name, last_name) VALUES ('John', 'Doe')",+ ],+ ["UPDATE", "UPDATE contacts SET name = 'test' WHERE id = 1"],+ ["DELETE", "DELETE FROM contacts WHERE id = 1"],+ [+ "INSERT with RETURNING",+ "INSERT INTO contacts (name) VALUES ('test') RETURNING id",+ ],+ [+ "UPDATE with subquery",+ "UPDATE contacts SET company_id = (SELECT id FROM companies WHERE name = 'Acme') WHERE id = 1",+ ],+ [+ "writable CTE with INSERT",+ "WITH d AS (DELETE FROM old_contacts RETURNING *) INSERT INTO archive SELECT * FROM d",+ ],+ ])("allows %s", (_label, sql) => {+ expect(validateWrite(sql)).toBeNull();+ });++ it.each([+ ["standalone SELECT", "SELECT * FROM contacts"],+ ["DROP TABLE", "DROP TABLE contacts"],+ ["CREATE TABLE", "CREATE TABLE evil (id int)"],+ ["TRUNCATE", "TRUNCATE contacts"],+ ["SET", "SET LOCAL role = 'postgres'"],+ [+ "multi-statement (DELETE; DROP)",+ "DELETE FROM contacts; DROP TABLE contacts",+ ],+ [+ "multi-statement (DELETE; SET)",+ "DELETE FROM contacts; SET LOCAL role = 'postgres'",+ ],+ ["unparseable SQL", "NOT VALID SQL %%%"],+ ])("rejects %s", (_label, sql) => {+ expect(validateWrite(sql)).not.toBeNull();+ });+});diff --git a/supabase/functions/mcp/validateSql.ts b/supabase/functions/mcp/validateSql.tsnew file mode 100644index 00000000..930381b5--- /dev/null+++ b/supabase/functions/mcp/validateSql.ts@@ -0,0 +1,65 @@+import { parse, type Statement } from "npm:pgsql-ast-parser@^12";++const ALLOWED_READ_TYPES = new Set(["select", "with"]);+const ALLOWED_WRITE_TYPES = new Set(["insert", "update", "delete", "with"]);++// Collect all statement types found in a parsed AST, including inner+// statements in WITH (CTE) bindings which can contain writable DML.+function collectStatementTypes(stmts: Statement[]): Set<string> {+ const types = new Set<string>();+ for (const stmt of stmts) {+ types.add(stmt.type);+ if (stmt.type === "with" && "bind" in stmt && Array.isArray(stmt.bind)) {+ for (const cte of stmt.bind) {+ if (cte.statement?.type) {+ types.add(cte.statement.type);+ }+ }+ }+ }+ return types;+}++export function validateReadOnly(sql: string): string | null {+ let stmts: Statement[];+ try {+ stmts = parse(sql);+ } catch {+ return "Failed to parse SQL. Please check your query syntax.";+ }+ if (stmts.length === 0) {+ return "Empty query.";+ }+ if (stmts.length > 1) {+ return "Only a single statement is allowed.";+ }+ const types = collectStatementTypes(stmts);+ for (const type of types) {+ if (!ALLOWED_READ_TYPES.has(type)) {+ return `Statement type "${type}" is not allowed in read-only queries. Use the mutate tool for data modifications.`;+ }+ }+ return null;+}++export function validateWrite(sql: string): string | null {+ let stmts: Statement[];+ try {+ stmts = parse(sql);+ } catch {+ return "Failed to parse SQL. Please check your query syntax.";+ }+ if (stmts.length === 0) {+ return "Empty query.";+ }+ if (stmts.length > 1) {+ return "Only a single statement is allowed.";+ }+ const types = collectStatementTypes(stmts);+ for (const type of types) {+ if (!ALLOWED_WRITE_TYPES.has(type)) {+ return `Statement type "${type}" is not allowed. Only INSERT, UPDATE, and DELETE statements are supported.`;+ }+ }+ return null;+}diff --git a/vitest.functions.config.ts b/vitest.functions.config.tsindex 283d90b5..8f579517 100644--- a/vitest.functions.config.ts+++ b/vitest.functions.config.ts@@ -14,11 +14,12 @@ export default defineConfig({},resolve: {alias: {- // Map the Deno JSR import to the installed npm package+ // Map Deno-style imports to installed npm packages"jsr:@supabase/supabase-js@2": path.resolve(__dirname,"node_modules/@supabase/supabase-js",),+ "npm:pgsql-ast-parser@^12": "pgsql-ast-parser",},},});