The most complete open-source travel planner: real-time collaboration, bookings, budgets, packing lists, journals, offline PWA, SSO and an AI-ready MCP server, with planet-wide place search and routing built in.
TypeScript budget-trackercollaborativedockeritinerarymcp-serveroffline-firstopen-sourceopenstreetmappacking-listpwareal-timeself-hostedselfhostedtraveltravel-apptravel-journaltravel-plannertripitwanderlog
fix(db): read plugin SQL the way the Postgres lexer does and refuse INTO and TEMP anywhere
Mauricee6a0a39a51a4
diff --git a/server/src/db/engine/postgres/plugin-sql-guard.ts b/server/src/db/engine/postgres/plugin-sql-guard.tsindex 3077f368a..c78cccdfa 100644--- a/server/src/db/engine/postgres/plugin-sql-guard.ts+++ b/server/src/db/engine/postgres/plugin-sql-guard.ts@@ -7,12 +7,26 @@ import { PLUGIN_SCHEMA_PREFIX } from './plugin-schema';* TREK's tables at all. On Postgres its schema sits in TREK's database and* its statements run as TREK's role, which may read every table TREK has: a* role per plugin would need CREATEROLE, which TREK's role is not given. So- * the statement itself is held to what cannot leave the schema, before it- * runs, and the transaction it runs in names only that schema on its- * `search_path`, so an unqualified name finds nothing else.+ * three layers keep it in, each enough on its own for what it covers:+ *+ * 1. This guard holds the statement to what cannot leave the schema, before+ * it runs.+ * 2. The store sends every statement on its own over the extended query+ * protocol (`extended-query.ts`), which runs exactly one statement, so a+ * second statement the guard missed is an error, never run.+ * 3. The transaction puts the plugin's schema on the `search_path` with+ * `pg_temp` explicitly last, and TREK's own pool connections put `pg_temp`+ * last too (`session-search-path.ts`), so a temporary table never stands+ * in for a table of TREK's or of the plugin's.** The SQL is split into tokens the way Postgres's own lexer splits it (string- * and identifier quoting, comments, dollar signs), and refused when it holds:+ * and identifier quoting, comments, dollar signs). Where JavaScript and the+ * Postgres lexer would read a character differently, the guard refuses it+ * instead of guessing: whitespace is exactly what Postgres skips (space, tab,+ * CR, LF, form feed), a `--` comment ends at CR or LF as it does there, and+ * any other control character, or whitespace past ASCII (U+00A0, U+FEFF,+ * U+2028, ...), outside a string, a quoted name or a comment is refused. The+ * SQL is refused when it holds:** - a statement other than SELECT, INSERT, UPDATE, DELETE, MERGE, WITH,* VALUES, TABLE, TRUNCATE, REFRESH, or a CREATE, ALTER or DROP of a table,@@ -28,13 +42,16 @@ import { PLUGIN_SCHEMA_PREFIX } from './plugin-schema';* `ts_rewrite`), reads or changes settings (`set_config`,* `current_setting`), reaches objects by a name in a string (`nextval`,* `setval`, the `reg*` casts), large objects (`lo_*`) or `dblink`;- * - a temporary table (`CREATE TEMP`, `SELECT ... INTO`), which would outlive- * the call on a pooled connection another plugin uses next, and- * `WITH RECURSIVE`, refused on SQLite too;+ * - the words TEMP and TEMPORARY anywhere outside a string or a quoted name,+ * and INTO anywhere but right after INSERT or MERGE, at any depth of+ * parentheses: a temporary table outlives the call on a pooled connection,+ * and `SELECT ... INTO` creates a table outside what CREATE is held to;+ * - `WITH RECURSIVE`, refused on SQLite too;* - in an ALTER, a change of a table's schema, owner or tablespace;* - escape strings (`E'...'`), Unicode escapes (`U&'...'`), dollar-quoted- * strings and a number running straight into a name, whose reading- * differs between Postgres versions and settings.+ * strings, hexadecimal, octal and binary numbers, digit separators (`1_000`)+ * and a number running straight into a name, whose reading differs between+ * Postgres versions and settings (before 16, Postgres reads `0x1F` as `0 AS x1F`).** An alias that happens to share a schema's name (`auth.id` on a database* that has an `auth` schema) is refused too; the plugin renames the alias.@@ -142,6 +159,34 @@ const NAME_START = /[A-Za-z_\u0080-const NAME_PART = /[A-Za-z0-9_$\u0080-]/;/** The single-character punctuation and operator characters. */const PUNCT = new Set([...'.,()[];+-*/<>=~!@#%^&|?']);+/**+ * What the Postgres lexer skips as whitespace (`space` in scan.l). Vertical+ * tab is whitespace only from Postgres 16 on, so it is refused instead.+ */+const WHITESPACE = new Set([' ', '\t', '\n', '\r', '\f']);+/** The keywords INTO may follow. Anywhere else it makes a table (`SELECT ... INTO`). */+const INTO_AFTER = new Set(['insert', 'merge']);++/**+ * Whether JavaScript and the Postgres lexer read `ch` differently: a control+ * character Postgres does not skip, or whitespace past ASCII, which+ * JavaScript's `\s` skips and Postgres reads as part of a name.+ */+function divergent(ch: string): boolean {+ if (WHITESPACE.has(ch)) return false;+ const code = ch.charCodeAt(0);+ return code < 0x20 || code === 0x7f || /\s/.test(ch);+}++/** Refuses `ch` when {@link divergent}. */+function refuseDivergent(ch: string): void {+ if (divergent(ch)) {+ const code = ch.charCodeAt(0).toString(16).toUpperCase().padStart(4, '0');+ throw new PluginSqlRefused(+ `the character U+${code} is read differently by Postgres; outside a string use plain spaces, tabs and newlines`,+ );+ }+}/** `name` lower-cased the way Postgres folds an unquoted name: ASCII letters only. */function fold(name: string): string {@@ -168,10 +213,12 @@ export function tokenize(sql: string): Token[] {const at = i;const c = sql[i];const next = sql[i + 1];- if (/\s/.test(c)) {+ refuseDivergent(c);+ if (WHITESPACE.has(c)) {i++;} else if (c === '-' && next === '-') {- while (i < n && sql[i] !== '\n') i++;+ // Postgres ends a line comment at either newline character (`non_newline` in scan.l).+ while (i < n && sql[i] !== '\n' && sql[i] !== '\r') i++;} else if (c === '/' && next === '*') {i = skipBlockComment(sql, i);} else if (c === "'") {@@ -191,7 +238,16 @@ export function tokenize(sql: string): Token[] {while (i < n && /[0-9]/.test(sql[i])) i++;tokens.push({ kind: 'param', at });} else if (/[0-9]/.test(c) || (c === '.' && /[0-9]/.test(next ?? ''))) {+ if (c === '0' && /[xXoObB]/.test(next ?? '')) {+ throw new PluginSqlRefused(+ 'hexadecimal, octal and binary numbers are not accepted: Postgres before 16 reads 0x1F as 0 AS x1F; write it in decimal',+ );+ }i = skipNumber(sql, i);+ if (sql[i] === '_') {+ throw new PluginSqlRefused('digit separators (1_000) are not accepted: Postgres before 16 does not read them');+ }+ if (i < n) refuseDivergent(sql[i]);if (i < n && NAME_PART.test(sql[i])) {throw new PluginSqlRefused('a number may not run straight into a name; put a space between them');}@@ -203,7 +259,10 @@ export function tokenize(sql: string): Token[] {if ((c === 'u' || c === 'U') && next === '&' && (sql[i + 2] === "'" || sql[i + 2] === '"')) {throw new PluginSqlRefused('Unicode escapes (U&) are not accepted');}- while (i < n && NAME_PART.test(sql[i])) i++;+ while (i < n && NAME_PART.test(sql[i])) {+ refuseDivergent(sql[i]);+ i++;+ }tokens.push({ kind: 'word', value: truncateName(fold(sql.slice(at, i))), quoted: false, at });} else if (c === ':' && next === ':') {tokens.push({ kind: 'punct', value: '::', at });@@ -253,13 +312,9 @@ function skipQuoted(sql: string, start: number, quote: string, what: string): nuthrow new PluginSqlRefused(`${what} is not closed`);}-/** The index past a numeric constant starting at `start`: decimal, with a fraction and an exponent, or 0x/0o/0b. */+/** The index past a decimal numeric constant starting at `start`, with a fraction and an exponent. */function skipNumber(sql: string, start: number): number {- const rest = sql.slice(start);- const match =- /^0[xX][0-9a-fA-F_]+|^0[oO][0-7_]+|^0[bB][01_]+|^(?:[0-9][0-9_]*(?:\.[0-9_]*)?|\.[0-9][0-9_]*)(?:[eE][+-]?[0-9]+)?/.exec(- rest,- );+ const match = /^(?:[0-9]+(?:\.[0-9]*)?|\.[0-9]+)(?:[eE][+-]?[0-9]+)?/.exec(sql.slice(start));return start + (match ? match[0].length : 1);}@@ -302,7 +357,6 @@ function describe(text: string, tokens: Token[]): PluginStatement {let depth = 0;let main: string | null = verb === 'with' ? null : verb;let returning = false;- let selectInto = false;let params = 0;let qualifies = false;for (const [index, token] of tokens.entries()) {@@ -314,17 +368,14 @@ function describe(text: string, tokens: Token[]): PluginStatement {const after = tokens[index + 1];if (after?.kind === 'punct' && after.value === '.') qualifies = true;if (token.quoted) continue;- if (token.value === 'recursive') throw new PluginSqlRefused('WITH RECURSIVE is not allowed');- if (token.value === 'tablespace') throw new PluginSqlRefused('a tablespace may not be named');+ checkKeyword(token.value, keyword(tokens[index - 1]));if (verb === 'alter' && (token.value === 'schema' || token.value === 'owner')) {throw new PluginSqlRefused(`an ALTER may not change the ${token.value}`);}if (depth !== 0) continue;if (main === null && VERBS.has(token.value)) main = token.value;if (token.value === 'returning') returning = true;- if (token.value === 'into' && main === 'select') selectInto = true;}- if (selectInto) throw new PluginSqlRefused('SELECT ... INTO is not allowed; use CREATE TABLE ... AS');const reads = main !== null && READ_VERBS.has(main);const writesInside = tokens.some((t) => {@@ -355,6 +406,27 @@ function checkObject(verb: string, tokens: readonly Token[]): void {}}+/**+ * Refuses an unquoted keyword that is never safe, at whatever depth of+ * parentheses it sits: `previous` is the unquoted keyword before it, if any.+ * TEMP and TEMPORARY make an object that outlives the call on a pooled+ * connection. INTO anywhere but after INSERT or MERGE is `SELECT ... INTO`,+ * which makes a table (a temporary one with TEMP) past what CREATE is held to;+ * `(SELECT ... INTO t)` and `WITH x AS (...) SELECT ... INTO t` included.+ */+function checkKeyword(word: string, previous: string | null): void {+ if (word === 'recursive') throw new PluginSqlRefused('WITH RECURSIVE is not allowed');+ if (word === 'tablespace') throw new PluginSqlRefused('a tablespace may not be named');+ if (word === 'temp' || word === 'temporary') {+ throw new PluginSqlRefused(+ `temporary objects are not allowed (${word.toUpperCase()}); quote a name spelled "${word}"`,+ );+ }+ if (word === 'into' && (previous === null || !INTO_AFTER.has(previous))) {+ throw new PluginSqlRefused('SELECT ... INTO is not allowed; use CREATE TABLE ... AS');+ }+}+/** Refuses a name that reaches past the plugin's schema whatever qualifies it. */function checkName(name: string): void {if (REFUSED_NAMES.has(name) || REFUSED_PREFIXES.some((p) => name.startsWith(p)) || XML_EXPORT.test(name)) {diff --git a/server/tests/postgres/plugin-data.test.ts b/server/tests/postgres/plugin-data.test.tsindex 608b36eb1..8d70d35fb 100644--- a/server/tests/postgres/plugin-data.test.ts+++ b/server/tests/postgres/plugin-data.test.ts@@ -1,5 +1,5 @@/**- * PGPLUG-001..008 — a plugin's own data (`db:own`) on Postgres, against the+ * PGPLUG-001..011 — a plugin's own data (`db:own`) on Postgres, against the* real app on the lane's database: each plugin gets a schema of its own and no* SQLite file, its SQL keeps the SQLite store's semantics (migrate once per* id, a script's statements committed one by one, an atomic tx, the row cap,@@ -8,6 +8,7 @@* schema and nothing else.*/import { buildApp } from '../../src/bootstrap';+import { extendedQuery } from '../../src/db/engine/postgres/extended-query';import { PluginDataSlots, PostgresPluginDataStore } from '../../src/db/engine/postgres/plugin-data-store';import { withRequestContext } from '../../src/nest/database/request-context';import { PLUGIN_DATA, type PluginDataBackend } from '../../src/nest/plugins/host/plugin-data.backend';@@ -17,6 +18,7 @@ import { MikroORM } from '@mikro-orm/core';import type { AbstractSqlConnection } from '@mikro-orm/sql';import type { INestApplication } from '@nestjs/common';+import { CompiledQuery } from 'kysely';import fs from 'node:fs';import os from 'node:os';import path from 'node:path';@@ -231,4 +233,106 @@ describe('plugin data on Postgres', () => {expect(await pluginSchemas()).toContain('trek_plugin_pg_rpc');closePluginDataDb('pg-rpc');});++ it("PGPLUG-009: the review's bypasses are refused before they run: SQL hidden behind a CR, and SELECT ... INTO TEMP", async () => {+ const store = data.open('pg-bypass');+ await store.migrate('001', 'CREATE TABLE notes (id bigserial PRIMARY KEY, body text NOT NULL)');+ const reads = [+ 'select 1 --\rfrom public.users',+ 'select 1 --x\rfrom public.users',+ 'select 1 --\r, email, password_hash from public.users',+ "(select 1 as id, 'admin' as role into temp users)",+ "(select 99 as id, 'forged'::text as name into temp users)",+ '((select 1 into t))',+ '(select 1) into t',+ 'select * from (select 1 into t) s',+ 'select 1 from public.users',+ ];+ await Promise.all(reads.map((sql) => expect(store.query(sql), sql).rejects.toThrow(/not allowed for plugin/)));+ const scripts = [+ "select 1 --\r; reset search_path; update users set role = 'admin' where id = 1",+ "insert into notes (body) values ('x') --x\r; update public.users set role = 1",+ "select 1 --x\r; create function f() returns int language sql as 'select 1'",+ "select 1 --\r; copy notes to program 'id'",+ '(select 1 into temp t)',+ 'select 1 into temporary t',+ ];+ await Promise.all(scripts.map((sql) => expect(store.exec(sql), sql).rejects.toThrow(/not allowed for plugin/)));++ // Nothing hidden ran: no temporary table anywhere in the database, no function. The insert in front of the+ // CR is a statement of its own, which a script commits before the next one is refused, as on SQLite.+ const [{ temps, functions }] = await withRequestContext(orm, () =>+ orm.em+ .getConnection()+ .execute<Array<{ temps: number; functions: number }>>(+ "select (select count(*) from pg_class where relpersistence = 't') as temps, " ++ "(select count(*) from pg_proc where proname = 'f') as functions",+ [],+ 'all',+ ),+ );+ expect({ temps, functions }).toEqual({ temps: 0, functions: 0 });+ expect(await store.query('SELECT body FROM notes')).toEqual([{ body: 'x' }]);+ });++ it('PGPLUG-010: a statement extendedQuery builds runs alone: a second one in its text is refused by Postgres, not run', async () => {+ const store = data.open('pg-proto');+ await store.migrate('001', 'CREATE TABLE t (x int)');+ const client = (orm.em.getConnection() as AbstractSqlConnection).getClient<object>();+ const two = 'insert into trek_plugin_pg_proto.t values (1); insert into trek_plugin_pg_proto.t values (2)';++ // What a guard that let a second statement through would hand the pool: Postgres parses one statement only.+ await expect(client.executeQuery(extendedQuery(two, []))).rejects.toThrow(+ /cannot insert multiple commands into a prepared statement/,+ );+ expect(await store.query('SELECT count(*) AS n FROM t')).toEqual([{ n: 0 }]);+ // The same text without the marker goes over the simple protocol and runs both, which is what the marker prevents.+ await client.executeQuery(CompiledQuery.raw(two, []));+ expect(await store.query('SELECT count(*) AS n FROM t')).toEqual([{ n: 2 }]);++ // A single statement runs and reports its rows, with or without args.+ const one = await client.executeQuery(extendedQuery('delete from trek_plugin_pg_proto.t where x = $1', [1]));+ expect(one.numAffectedRows).toBe(1n);+ expect(await store.exec('DELETE FROM t')).toEqual({ changes: 0 });+ expect(await store.exec('INSERT INTO t VALUES (5)', [])).toEqual({ changes: 0 });+ expect(await store.tx([{ sql: 'INSERT INTO t VALUES (6)' }, { sql: 'DELETE FROM t' }])).toEqual({+ results: [{ changes: 1 }, { changes: 2 }],+ });+ });++ it("PGPLUG-011: pg_temp is searched last, so a temporary table never stands in for TREK's tables or a plugin's", async () => {+ const [{ path, schema }] = await withRequestContext(orm, () =>+ orm.em+ .getConnection()+ .execute<Array<{ path: string; schema: string }>>(+ "select current_setting('search_path') as path, current_schema() as schema",+ [],+ 'all',+ ),+ );+ expect(path).toMatch(/, pg_temp$/);+ expect(schema).toBe('public');++ const store = data.open('pg-shadow');+ await store.migrate('001', 'CREATE TABLE notes (body text)');+ await store.exec('INSERT INTO notes VALUES ($1)', ['real']);+ const client = (orm.em.getConnection() as AbstractSqlConnection).getClient<object>();+ // One pool connection holding temporary tables named like TREK's and the plugin's, as one left behind would.+ await client.connection().execute(async (conn) => {+ try {+ await conn.executeQuery(CompiledQuery.raw("create temp table users as select 'forged'::text as email"));+ await conn.executeQuery(CompiledQuery.raw("create temp table notes as select 'forged'::text as body"));+ const resolved = await conn.executeQuery<{ ns: string }>(+ CompiledQuery.raw(+ "select relnamespace::regnamespace::text as ns from pg_class where oid = 'users'::regclass",+ ),+ );+ expect(resolved.rows).toEqual([{ ns: 'public' }]);+ const onConnection = new PostgresPluginDataStore('pg-shadow', conn, new PluginDataSlots(1));+ expect(await onConnection.query('SELECT body FROM notes')).toEqual([{ body: 'real' }]);+ } finally {+ await conn.executeQuery(CompiledQuery.raw('drop table if exists pg_temp.users, pg_temp.notes'));+ }+ });+ });});diff --git a/server/tests/unit/db/engine/postgres/plugin-sql-guard.test.ts b/server/tests/unit/db/engine/postgres/plugin-sql-guard.test.tsindex 80950aaa4..14826b68e 100644--- a/server/tests/unit/db/engine/postgres/plugin-sql-guard.test.ts+++ b/server/tests/unit/db/engine/postgres/plugin-sql-guard.test.ts@@ -34,7 +34,7 @@ describe('plugin SQL guard', () => {'VALUES (1), (2)','TABLE notes','(SELECT 1) UNION (SELECT 2)',- 'CREATE TABLE notes (id bigserial PRIMARY KEY, body text, temp real, schema text)',+ 'CREATE TABLE notes (id bigserial PRIMARY KEY, body text, "temp" real, schema text)','CREATE UNIQUE INDEX notes_body ON notes (body)','CREATE UNLOGGED TABLE cache (k text)','CREATE OR REPLACE VIEW v AS SELECT body FROM notes',@@ -50,8 +50,19 @@ describe('plugin SQL guard', () => {"SELECT 'public.users -- not code' AS text",'SELECT 1 -- public.users\n','SELECT /* public.users */ 1',- 'SELECT 1.5e3, .5, 0x1F',+ 'SELECT 1.5e3, .5, 1e-3, 10','INSERT INTO kv VALUES ($1, $2) ON CONFLICT (k) DO NOTHING',+ // A line comment ends at CR as well as LF, as in Postgres; what follows is read as SQL.+ 'SELECT 1 -- public.users\r',+ 'SELECT 1 -- public.users\r\nFROM notes',+ 'SELECT\t1\f',+ // Characters JavaScript reads differently are fine inside strings, quoted names and comments.+ "SELECT 'a b c\u000bd'",+ 'SELECT 1 AS "a b"',+ 'SELECT 1 /* */',+ 'WITH gone AS (DELETE FROM notes RETURNING id) INSERT INTO trash SELECT id FROM gone',+ 'MERGE INTO notes n USING incoming i ON n.id = i.id WHEN NOT MATCHED THEN INSERT (body) VALUES (i.body)',+ 'SELECT body AS "into", "temporary" FROM notes',])('lets through %s', (sql) => {expect(() => check(sql)).not.toThrow();});@@ -114,11 +125,75 @@ describe('plugin SQL guard', () => {['SELECT ""', /a quoted name may not be empty/],['SELECT `x`', /unexpected character/],['SELECT 1; SELECT * FROM public.users', /another schema/],+ ['SELECT 1 FROM notes INTO TEMP copy', /SELECT \.\.\. INTO/],+ ['SELECT * FROM notes WHERE temp > 1', /TEMP/],+ ['SELECT 0x1F', /hexadecimal/],+ ['SELECT 0o17, 0b1', /hexadecimal/],+ ['SELECT 1_000', /digit separators/],])('refuses %s', (sql, reason) => {expect(() => check(sql)).toThrow(PluginSqlRefused);expect(() => check(sql)).toThrow(reason);});+ // The two bypasses of the final review, with their variants: each was let through, and Postgres ran it.+ it.each([+ // A `--` comment ended by a bare CR hid the rest from the guard, which Postgres then ran.+ ['select 1 --\rfrom public.users', /another schema/],+ ['select 1 --x\rfrom public.users', /another schema/],+ ['select 1 --\r, email, password_hash from public.users', /another schema/],+ ["select 1 --\r; reset search_path; update users set role='admin'", /may not start with RESET/],+ ['select 1 --\r; create function f() returns int', /CREATE FUNCTION is not allowed/],+ ['insert into notes (body) values (1) --x\r; update public.users set role = 1', /another schema/],+ ['select 1 -- x\r\u000b; select 1', /U\+000B/],+ // A parenthesized SELECT ... INTO, at any depth, made a temporary table that shadowed TREK's own.+ ["(select 1 as id, 'admin' as role into temp users)", /TEMP|SELECT \.\.\. INTO/],+ ["(select 99 as id, 'forged'::text as name into temp users)", /TEMP|SELECT \.\.\. INTO/],+ ['(select 1 into temp t)', /TEMP|SELECT \.\.\. INTO/],+ ['((select 1 into t))', /SELECT \.\.\. INTO/],+ ['(select 1) into t', /SELECT \.\.\. INTO/],+ ['(select 1 into trek_r_tmp_x)', /SELECT \.\.\. INTO/],+ ['select * from (select 1 into t) s', /SELECT \.\.\. INTO/],+ ['WITH x AS (SELECT 1) SELECT * INTO t FROM x', /SELECT \.\.\. INTO/],+ ['WITH x AS (SELECT 1 INTO t) SELECT 1', /SELECT \.\.\. INTO/],+ ['VALUES (1) INTO t', /SELECT \.\.\. INTO/],+ ['TABLE notes INTO t', /SELECT \.\.\. INTO/],+ ['select 1 into temporary t', /TEMPORARY|SELECT \.\.\. INTO/],+ ['select 1 into unlogged t', /SELECT \.\.\. INTO/],+ ['CREATE TABLE t AS SELECT 1 INTO u', /SELECT \.\.\. INTO/],+ ['CREATE GLOBAL TEMP TABLE t (x int)', /CREATE GLOBAL is not allowed|TEMP/],+ ['CREATE LOCAL TEMPORARY TABLE t (x int)', /CREATE LOCAL is not allowed|TEMPORARY/],+ ['CREATE TEMP VIEW v AS SELECT 1', /CREATE TEMP is not allowed/],+ ['CREATE OR REPLACE TEMP VIEW v AS SELECT 1', /CREATE TEMP is not allowed/],+ ['CREATE TEMPORARY SEQUENCE s', /CREATE TEMPORARY is not allowed/],+ ['select temp from notes', /TEMP/],+ ['select 1 from notes as temporary', /TEMPORARY/],+ ])('refuses the bypass %j', (sql, reason) => {+ expect(() => check(sql)).toThrow(PluginSqlRefused);+ expect(() => check(sql)).toThrow(reason);+ });++ it.each([+ ['NO-BREAK SPACE', ' ', 'U+00A0'],+ ['BYTE ORDER MARK', '', 'U+FEFF'],+ ['LINE SEPARATOR', ' ', 'U+2028'],+ ['PARAGRAPH SEPARATOR', ' ', 'U+2029'],+ ['IDEOGRAPHIC SPACE', ' ', 'U+3000'],+ ['vertical tab', '\u000b', 'U+000B'],+ ['NUL', '\u0000', 'U+0000'],+ ['escape', '\u001b', 'U+001B'],+ ['DEL', '\u007f', 'U+007F'],+ ])('refuses a %s outside a string, which JavaScript and Postgres read differently', (_name, ch, code) => {+ for (const sql of [+ `SELECT 1${ch}FROM public.users`,+ `SELECT x${ch}FROM notes`,+ `${ch}SELECT 1`,+ `SELECT public${ch}.users`,+ ]) {+ expect(() => check(sql), JSON.stringify(sql)).toThrow(PluginSqlRefused);+ expect(() => check(sql), JSON.stringify(sql)).toThrow(code);+ }+ });+it('reads nested block comments as Postgres does, so code after the inner close is still a comment', () => {expect(() => check('SELECT 1 /* outer /* inner */ public.users */')).not.toThrow();expect(() => check('SELECT 1 /* one */ FROM public.users')).toThrow(/another schema/);@@ -140,6 +215,8 @@ describe('plugin SQL guard', () => {const statements = parsePluginSql("CREATE TABLE a (x text);;\n-- note\nINSERT INTO a VALUES ('a;b');");expect(statements.map((s) => s.text)).toEqual(['CREATE TABLE a (x text)', "INSERT INTO a VALUES ('a;b')"]);expect(parsePluginSql('-- nothing\n;')).toEqual([]);+ // What follows a CR is a statement of its own, as Postgres reads it, and is checked like any other.+ expect(parsePluginSql('select 1 --x\r; select 42').map((s) => s.text)).toEqual(['select 1 --x', 'select 42']);});it('says whether a statement returns rows, may write, qualifies a name and how many placeholders it has', () => {