rattlecheck 0.0.0-stage → 0.1.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +201 -0
- package/NOTICE +4 -0
- package/README.md +173 -2
- package/bin/rattlecheck.js +12 -0
- package/docs/rules/RC001.md +40 -0
- package/docs/rules/RC002.md +35 -0
- package/docs/rules/RC003.md +25 -0
- package/docs/rules/RC004.md +23 -0
- package/docs/rules/RC005.md +32 -0
- package/docs/rules/RC101.md +31 -0
- package/integrations/AGENTS.md +11 -0
- package/integrations/claude-code/rattlecheck/SKILL.md +42 -0
- package/integrations/cursor/rattlecheck.mdc +13 -0
- package/package.json +45 -4
- package/src/cli.js +158 -0
- package/src/config.js +62 -0
- package/src/live/catalog.js +43 -0
- package/src/live/env.js +102 -0
- package/src/live/ownership.js +72 -0
- package/src/live/probe.js +80 -0
- package/src/live/rc101-anon-readable.js +38 -0
- package/src/mcp/server.js +163 -0
- package/src/model.js +724 -0
- package/src/report/badge-svg.js +26 -0
- package/src/report/card-svg.js +55 -0
- package/src/report/grade.js +27 -0
- package/src/report/sarif.js +44 -0
- package/src/report/terminal.js +105 -0
- package/src/rules/index.js +14 -0
- package/src/rules/supabase/rc001-table-without-rls.js +54 -0
- package/src/rules/supabase/rc002-definer-callable-by-anon.js +37 -0
- package/src/rules/supabase/rc003-definer-search-path.js +33 -0
- package/src/rules/supabase/rc004-invoker-trigger-locked-table.js +49 -0
- package/src/rules/supabase/rc005-permissive-true-policy.js +81 -0
- package/src/scan.js +167 -0
- package/src/sql/ident.js +25 -0
- package/src/sql/signature.js +143 -0
- package/src/sql/statements.js +267 -0
- package/src/version.js +6 -0
package/src/scan.js
ADDED
|
@@ -0,0 +1,167 @@
|
|
|
1
|
+
// The single entry point every surface uses: CLI, MCP server, tests.
|
|
2
|
+
import path from 'node:path';
|
|
3
|
+
import { buildModel, findMigrationsDir, loadMigrations, readExposedSchemas } from './model.js';
|
|
4
|
+
import { loadConfig } from './config.js';
|
|
5
|
+
import { STATIC_RULES, LIVE_RULES } from './rules/index.js';
|
|
6
|
+
import { countBySeverity, gradeFor, GRADES, OPEN_SEVERITIES } from './report/grade.js';
|
|
7
|
+
import { readProjectEnv, looksSecret } from './live/env.js';
|
|
8
|
+
import { proveOwnership } from './live/ownership.js';
|
|
9
|
+
import { probeTables } from './live/probe.js';
|
|
10
|
+
import { listExposedObjects } from './live/catalog.js';
|
|
11
|
+
import { tableExposure } from './model.js';
|
|
12
|
+
import { VERSION, USER_AGENT } from './version.js';
|
|
13
|
+
|
|
14
|
+
export const REPORT_SCHEMA = 'rattlecheck.report/v1';
|
|
15
|
+
|
|
16
|
+
export class ScanError extends Error {
|
|
17
|
+
constructor(message, code = 2) {
|
|
18
|
+
super(message);
|
|
19
|
+
this.code = code;
|
|
20
|
+
}
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
function decorate(rule, f, root, migrationsDir) {
|
|
24
|
+
return {
|
|
25
|
+
rule: rule.id,
|
|
26
|
+
title: rule.title,
|
|
27
|
+
target: rule.target,
|
|
28
|
+
...f,
|
|
29
|
+
file: f.file && migrationsDir ? path.relative(root, path.join(migrationsDir, f.file)) : f.file,
|
|
30
|
+
standards: rule.standards,
|
|
31
|
+
};
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
/**
|
|
35
|
+
* @param {object} opts
|
|
36
|
+
* @param {string} [opts.root]
|
|
37
|
+
* @param {boolean} [opts.live]
|
|
38
|
+
* @param {string} [opts.configPath]
|
|
39
|
+
* @param {object} [opts.env] process environment (tokens are read from here)
|
|
40
|
+
* @param {Function} [opts.fetchImpl]
|
|
41
|
+
*/
|
|
42
|
+
export async function scan({ root = '.', live = false, configPath, env = process.env, fetchImpl = globalThis.fetch } = {}) {
|
|
43
|
+
root = path.resolve(root);
|
|
44
|
+
const config = loadConfig(root, configPath);
|
|
45
|
+
const migrationsDir = findMigrationsDir(root);
|
|
46
|
+
if (!migrationsDir) {
|
|
47
|
+
throw new ScanError(`No Supabase migrations found under ${root}. Run rattlecheck from your project folder (the one that contains supabase/migrations), or pass that folder as an argument.`);
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
const migrations = loadMigrations(migrationsDir);
|
|
51
|
+
const exposedSchemas = config.exposedSchemas ?? readExposedSchemas(root);
|
|
52
|
+
const model = buildModel(migrations, { defaults: config.defaults, exposedSchemas, migrationRoles: config.migrationRoles });
|
|
53
|
+
|
|
54
|
+
const raw = [];
|
|
55
|
+
const checked = new Set();
|
|
56
|
+
for (const rule of STATIC_RULES) {
|
|
57
|
+
const r = rule.check(model);
|
|
58
|
+
r.checked.forEach((c) => checked.add(c));
|
|
59
|
+
for (const f of r.findings) raw.push(decorate(rule, f, root, migrationsDir));
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
let liveReport = { ran: false };
|
|
63
|
+
if (live) {
|
|
64
|
+
const projectEnv = readProjectEnv(root, env);
|
|
65
|
+
if (!projectEnv.url || !projectEnv.anonKey) {
|
|
66
|
+
throw new ScanError(
|
|
67
|
+
`Live check needs your project URL and public (anon or publishable) key together, either both in the environment or both in .env / .env.local (looked in: ${projectEnv.source}).`,
|
|
68
|
+
);
|
|
69
|
+
}
|
|
70
|
+
if (looksSecret(projectEnv.anonKey) || projectEnv.anonKey === projectEnv.serviceKey) {
|
|
71
|
+
throw new ScanError('The key in your public (anon or publishable) slot is a secret key. A live check with it would mean nothing, and that key should never ship in your website. Use the anon or publishable key.');
|
|
72
|
+
}
|
|
73
|
+
const own = await proveOwnership({ url: projectEnv.url, accessToken: projectEnv.accessToken, serviceKey: projectEnv.serviceKey, fetchImpl, userAgent: USER_AGENT });
|
|
74
|
+
if (!own.ok) {
|
|
75
|
+
throw new ScanError(
|
|
76
|
+
`Live check refused: rattlecheck only checks projects you can prove are yours (${own.reason}). ` +
|
|
77
|
+
'Run `supabase login` and set SUPABASE_ACCESS_TOKEN, or put the project\'s service key in your local .env.',
|
|
78
|
+
4,
|
|
79
|
+
);
|
|
80
|
+
}
|
|
81
|
+
const fromMigrations = [...model.tables.values()].filter((t) => tableExposure(model, t).exposed).map((t) => t.key);
|
|
82
|
+
// The live check has to ask about everything the project serves, not just
|
|
83
|
+
// what the migrations know about. See src/live/catalog.js.
|
|
84
|
+
const catalog = own.method === 'access-token'
|
|
85
|
+
? await listExposedObjects({ ref: own.ref, accessToken: projectEnv.accessToken, schemas: exposedSchemas, fetchImpl, userAgent: USER_AGENT })
|
|
86
|
+
: { ok: false, names: [], reason: 'proved ownership with a service key; the full table list needs SUPABASE_ACCESS_TOKEN' };
|
|
87
|
+
const candidates = [...new Set([...fromMigrations, ...catalog.names])];
|
|
88
|
+
const probe = await probeTables({ url: own.base, anonKey: projectEnv.anonKey, tables: candidates, fetchImpl, userAgent: USER_AGENT });
|
|
89
|
+
for (const rule of LIVE_RULES) {
|
|
90
|
+
const r = rule.check(probe, model);
|
|
91
|
+
r.checked.forEach((c) => checked.add(c));
|
|
92
|
+
for (const f of r.findings) raw.push(decorate(rule, f, root, migrationsDir));
|
|
93
|
+
}
|
|
94
|
+
const by = (s) => probe.results.filter((x) => x.state === s).length;
|
|
95
|
+
const known = new Set(fromMigrations);
|
|
96
|
+
const complete = catalog.ok || probe.apiList.ok;
|
|
97
|
+
liveReport = {
|
|
98
|
+
ran: true,
|
|
99
|
+
ownership: own.method,
|
|
100
|
+
// How the list of things to ask about was built. complete=false means
|
|
101
|
+
// objects created outside migrations may exist and were NOT checked.
|
|
102
|
+
coverage: {
|
|
103
|
+
complete,
|
|
104
|
+
source: catalog.ok ? 'project catalog (read-only)' : probe.apiList.ok ? 'API table list' : 'migrations only',
|
|
105
|
+
fromMigrations: fromMigrations.length,
|
|
106
|
+
outsideMigrations: probe.results.filter((x) => !known.has(x.table)).length,
|
|
107
|
+
...(complete ? {} : { reason: catalog.reason }),
|
|
108
|
+
},
|
|
109
|
+
probed: probe.results.length,
|
|
110
|
+
open: by('open'),
|
|
111
|
+
lockedOrEmpty: by('locked-or-empty'),
|
|
112
|
+
locked: by('locked'),
|
|
113
|
+
notExposed: by('not-exposed'),
|
|
114
|
+
errors: by('error'),
|
|
115
|
+
};
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
// Allowlist: exact rule + object name.
|
|
119
|
+
const findings = [];
|
|
120
|
+
const allowed = [];
|
|
121
|
+
const used = new Set();
|
|
122
|
+
for (const f of raw) {
|
|
123
|
+
const idx = config.allow.findIndex((a) => a.rule.toUpperCase() === f.rule && a.object === f.name);
|
|
124
|
+
if (idx === -1) findings.push(f);
|
|
125
|
+
else {
|
|
126
|
+
used.add(idx);
|
|
127
|
+
allowed.push({ ...f, reason: config.allow[idx].reason });
|
|
128
|
+
}
|
|
129
|
+
}
|
|
130
|
+
const configWarnings = config.allow
|
|
131
|
+
.map((a, i) => ({ a, i }))
|
|
132
|
+
.filter(({ a, i }) => !used.has(i) && !(a.rule.toUpperCase() === 'RC101' && !live))
|
|
133
|
+
.map(({ a }) => `allow entry ${a.rule} ${a.object} matches nothing. Remove it, so it can't quietly cover something new later.`);
|
|
134
|
+
|
|
135
|
+
const order = { critical: 0, high: 1, warning: 2 };
|
|
136
|
+
findings.sort((a, b) => order[a.severity] - order[b.severity] || a.rule.localeCompare(b.rule) || a.name.localeCompare(b.name));
|
|
137
|
+
|
|
138
|
+
const counts = countBySeverity(findings);
|
|
139
|
+
const letter = checked.size === 0 ? 'N/A' : gradeFor(counts);
|
|
140
|
+
const open = new Set(findings.filter((f) => OPEN_SEVERITIES.has(f.severity)).map((f) => f.object));
|
|
141
|
+
|
|
142
|
+
const coverageOk = !(migrations.length > 0 && model.coverage.statements === 0);
|
|
143
|
+
|
|
144
|
+
return {
|
|
145
|
+
schema: REPORT_SCHEMA,
|
|
146
|
+
tool: { name: 'rattlecheck', version: VERSION },
|
|
147
|
+
target: 'supabase',
|
|
148
|
+
generatedAt: new Date().toISOString(),
|
|
149
|
+
root,
|
|
150
|
+
migrationsDir: path.relative(root, migrationsDir) || '.',
|
|
151
|
+
grade: { letter, ...GRADES[letter] },
|
|
152
|
+
doors: { checked: checked.size, open: open.size },
|
|
153
|
+
counts,
|
|
154
|
+
findings,
|
|
155
|
+
allowed,
|
|
156
|
+
configWarnings,
|
|
157
|
+
coverage: {
|
|
158
|
+
ok: coverageOk,
|
|
159
|
+
...model.coverage,
|
|
160
|
+
tables: model.tables.size,
|
|
161
|
+
functions: model.functions.size,
|
|
162
|
+
exposedSchemas,
|
|
163
|
+
defaults: model.defaults,
|
|
164
|
+
},
|
|
165
|
+
live: liveReport,
|
|
166
|
+
};
|
|
167
|
+
}
|
package/src/sql/ident.js
ADDED
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
// Quote SQL identifiers for generated fix statements.
|
|
2
|
+
const RESERVED = new Set([
|
|
3
|
+
'all', 'analyse', 'analyze', 'and', 'any', 'array', 'as', 'asc', 'asymmetric', 'both', 'case', 'cast',
|
|
4
|
+
'check', 'collate', 'column', 'constraint', 'create', 'current_catalog', 'current_date', 'current_role',
|
|
5
|
+
'current_time', 'current_timestamp', 'current_user', 'default', 'deferrable', 'desc', 'distinct', 'do',
|
|
6
|
+
'else', 'end', 'except', 'false', 'fetch', 'for', 'foreign', 'from', 'grant', 'group', 'having', 'in',
|
|
7
|
+
'initially', 'intersect', 'into', 'lateral', 'leading', 'limit', 'localtime', 'localtimestamp', 'not',
|
|
8
|
+
'null', 'offset', 'on', 'only', 'or', 'order', 'placing', 'primary', 'references', 'returning', 'select',
|
|
9
|
+
'session_user', 'some', 'symmetric', 'table', 'then', 'to', 'trailing', 'true', 'union', 'unique', 'user',
|
|
10
|
+
'using', 'variadic', 'when', 'where', 'window', 'with',
|
|
11
|
+
]);
|
|
12
|
+
|
|
13
|
+
export function quoteIdent(name) {
|
|
14
|
+
if (/^[a-z_][a-z0-9_$]*$/.test(name) && !RESERVED.has(name)) return name;
|
|
15
|
+
return `"${name.replace(/"/g, '""')}"`;
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
export function qualified(schema, name) {
|
|
19
|
+
return `${quoteIdent(schema)}.${quoteIdent(name)}`;
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
// public.f(uuid, text) as SQL: schema-qualified name plus the identity argument types.
|
|
23
|
+
export function functionRef(f) {
|
|
24
|
+
return `${qualified(f.schema, f.name)}(${f.argsig ?? ''})`;
|
|
25
|
+
}
|
|
@@ -0,0 +1,143 @@
|
|
|
1
|
+
// Canonicalises a SQL function argument list into the type-only form Postgres
|
|
2
|
+
// uses for function identity (`format_type` over `proargtypes`), so overloads of
|
|
3
|
+
// the same name stay distinct. `foo(uuid)` and `foo(uuid, text)` are different
|
|
4
|
+
// functions with different grants, and merging them hides real holes.
|
|
5
|
+
|
|
6
|
+
// Words that can legitimately START a type, so `timestamp with time zone` as an
|
|
7
|
+
// unnamed argument is not mistaken for an argument named "timestamp".
|
|
8
|
+
const TYPE_INITIAL_WORDS = new Set([
|
|
9
|
+
'bigint', 'int8', 'bit', 'boolean', 'bool', 'box', 'bytea', 'character', 'char',
|
|
10
|
+
'varchar', 'cidr', 'circle', 'citext', 'date', 'daterange', 'decimal', 'double',
|
|
11
|
+
'float4', 'float8', 'hstore', 'inet', 'int', 'int2', 'int4', 'int4range',
|
|
12
|
+
'int8range', 'integer', 'interval', 'json', 'jsonb', 'jsonpath', 'line', 'lseg',
|
|
13
|
+
'ltree', 'macaddr', 'macaddr8', 'money', 'name', 'numeric', 'numrange', 'oid',
|
|
14
|
+
'path', 'pg_lsn', 'point', 'polygon', 'real', 'record', 'regclass', 'regproc',
|
|
15
|
+
'regrole', 'smallint', 'text', 'time', 'timestamp', 'timestamptz', 'timetz',
|
|
16
|
+
'tsquery', 'tsrange', 'tstzrange', 'tsvector', 'uuid', 'vector', 'xml',
|
|
17
|
+
'anyarray', 'anyelement', 'anyenum', 'anynonarray', 'jsonb_path', 'void',
|
|
18
|
+
]);
|
|
19
|
+
|
|
20
|
+
// The multi-word types that can appear without an argument name in front.
|
|
21
|
+
const MULTIWORD_TYPE_RE = /^(?:double\s+precision|(?:character|char|bit)\s+varying|(?:timestamp|time)\s*(?:\(\s*\d+\s*\))?\s+with(?:out)?\s+time\s+zone)(?:\s*\(\s*\d+\s*\))?(?:\s*\[\s*\d*\s*\])*\s*$/i;
|
|
22
|
+
|
|
23
|
+
const TYPE_ALIASES = new Map([
|
|
24
|
+
['int', 'integer'], ['int4', 'integer'],
|
|
25
|
+
['int8', 'bigint'],
|
|
26
|
+
['int2', 'smallint'],
|
|
27
|
+
['bool', 'boolean'],
|
|
28
|
+
['varchar', 'character varying'],
|
|
29
|
+
['char', 'character'],
|
|
30
|
+
['float8', 'double precision'],
|
|
31
|
+
['float4', 'real'],
|
|
32
|
+
['decimal', 'numeric'],
|
|
33
|
+
['timestamptz', 'timestamp with time zone'],
|
|
34
|
+
['timetz', 'time with time zone'],
|
|
35
|
+
// Bare `timestamp` / `time` mean the WITHOUT TIME ZONE variants.
|
|
36
|
+
['timestamp', 'timestamp without time zone'],
|
|
37
|
+
['time', 'time without time zone'],
|
|
38
|
+
]);
|
|
39
|
+
|
|
40
|
+
function splitTopLevel(argList) {
|
|
41
|
+
const parts = [];
|
|
42
|
+
let depth = 0;
|
|
43
|
+
let cur = '';
|
|
44
|
+
for (let i = 0; i < argList.length; i++) {
|
|
45
|
+
const ch = argList[i];
|
|
46
|
+
if (ch === "'" || ch === '"') {
|
|
47
|
+
const q = ch;
|
|
48
|
+
cur += ch;
|
|
49
|
+
i++;
|
|
50
|
+
while (i < argList.length) {
|
|
51
|
+
cur += argList[i];
|
|
52
|
+
if (argList[i] === q) {
|
|
53
|
+
if (argList[i + 1] === q) { cur += argList[i + 1]; i += 2; continue; }
|
|
54
|
+
break;
|
|
55
|
+
}
|
|
56
|
+
i++;
|
|
57
|
+
}
|
|
58
|
+
continue;
|
|
59
|
+
}
|
|
60
|
+
if (ch === '(' || ch === '[') depth++;
|
|
61
|
+
else if (ch === ')' || ch === ']') depth--;
|
|
62
|
+
if (ch === ',' && depth === 0) { parts.push(cur); cur = ''; continue; }
|
|
63
|
+
cur += ch;
|
|
64
|
+
}
|
|
65
|
+
if (cur.trim()) parts.push(cur);
|
|
66
|
+
return parts.map((p) => p.trim()).filter(Boolean);
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
function canonicaliseType(raw) {
|
|
70
|
+
let t = raw.trim().replace(/\s+/g, ' ');
|
|
71
|
+
|
|
72
|
+
// Array suffix travels with the type: `uuid []` -> `uuid[]`.
|
|
73
|
+
let arraySuffix = '';
|
|
74
|
+
const arr = /((\s*\[\s*\d*\s*\])+)$/.exec(t);
|
|
75
|
+
if (arr) {
|
|
76
|
+
arraySuffix = '[]'.repeat((arr[1].match(/\[/g) || []).length);
|
|
77
|
+
t = t.slice(0, arr.index).trim();
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
// Length/precision modifiers are not part of function identity, wherever
|
|
81
|
+
// they sit: `timestamp(3) with time zone` must keep `with time zone`.
|
|
82
|
+
t = t.replace(/\([^)]*\)/g, ' ').replace(/\s+/g, ' ').trim();
|
|
83
|
+
|
|
84
|
+
// `public.thing` and `thing` are the same type here: format_type renders
|
|
85
|
+
// public types unqualified when public is on the search_path.
|
|
86
|
+
t = t.replace(/^"?public"?\./i, '');
|
|
87
|
+
t = t.replace(/"/g, '');
|
|
88
|
+
|
|
89
|
+
const lower = t.toLowerCase();
|
|
90
|
+
if (TYPE_ALIASES.has(lower)) return TYPE_ALIASES.get(lower) + arraySuffix;
|
|
91
|
+
|
|
92
|
+
// `character varying` / `bit varying` keep their two-word form.
|
|
93
|
+
return lower + arraySuffix;
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
// Turns the raw text between the parentheses of a CREATE/REVOKE/GRANT/DROP
|
|
97
|
+
// FUNCTION statement into `type, type, type` matching the catalog.
|
|
98
|
+
export function normaliseArgs(rawArgs) {
|
|
99
|
+
if (rawArgs == null) return null; // caller must fall back to name matching
|
|
100
|
+
if (!rawArgs.trim()) return '';
|
|
101
|
+
|
|
102
|
+
const out = [];
|
|
103
|
+
for (const part of splitTopLevel(rawArgs)) {
|
|
104
|
+
let arg = part;
|
|
105
|
+
|
|
106
|
+
// Strip DEFAULT ... / `= ...`; not part of identity.
|
|
107
|
+
arg = arg.replace(/\s+default\s+[\s\S]*$/i, '');
|
|
108
|
+
const eq = arg.search(/(?<![:<>!])=(?!=)/);
|
|
109
|
+
if (eq !== -1) arg = arg.slice(0, eq);
|
|
110
|
+
arg = arg.trim();
|
|
111
|
+
|
|
112
|
+
// Argument mode. OUT args do not participate in identity at all.
|
|
113
|
+
let mode = null;
|
|
114
|
+
const modeMatch = /^(in|out|inout|variadic)\s+/i.exec(arg);
|
|
115
|
+
if (modeMatch) {
|
|
116
|
+
mode = modeMatch[1].toLowerCase();
|
|
117
|
+
arg = arg.slice(modeMatch[0].length).trim();
|
|
118
|
+
}
|
|
119
|
+
if (mode === 'out') continue;
|
|
120
|
+
|
|
121
|
+
const tokens = arg.split(/\s+/);
|
|
122
|
+
let typeText;
|
|
123
|
+
if (tokens.length === 1) {
|
|
124
|
+
typeText = tokens[0];
|
|
125
|
+
} else if (MULTIWORD_TYPE_RE.test(arg)) {
|
|
126
|
+
// Unnamed multi-word type: `timestamp with time zone`, `double precision`.
|
|
127
|
+
// Matching the whole type keeps `name text`, `date date` and
|
|
128
|
+
// `time time with time zone` (arguments named after a type) apart.
|
|
129
|
+
typeText = arg;
|
|
130
|
+
} else {
|
|
131
|
+
typeText = tokens.slice(1).join(' '); // first token was the argument name
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
out.push(canonicaliseType(typeText));
|
|
135
|
+
}
|
|
136
|
+
return out.join(', ');
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
// `public.foo(uuid, text)`: the identity key used throughout rattlecheck.
|
|
140
|
+
export function signatureKey(schema, name, normalisedArgs) {
|
|
141
|
+
const s = (schema || 'public').toLowerCase();
|
|
142
|
+
return normalisedArgs === null ? `${s}.${name}` : `${s}.${name}(${normalisedArgs})`;
|
|
143
|
+
}
|
|
@@ -0,0 +1,267 @@
|
|
|
1
|
+
// Minimal SQL lexer: splits a migration file into statements while respecting
|
|
2
|
+
// the four things a naive `split(';')` gets wrong. Getting any of them wrong
|
|
3
|
+
// makes a checker silently skip statements and report a false all-clear.
|
|
4
|
+
//
|
|
5
|
+
// 1. dollar-quoted bodies $$ ... ; ... $$ (every PL/pgSQL function)
|
|
6
|
+
// 2. single-quoted literals 'a;b' 'it''s' and E'it\\'s'
|
|
7
|
+
// 3. double-quoted identifiers "weird;name"
|
|
8
|
+
// 4. comments -- to EOL and /* nested */
|
|
9
|
+
//
|
|
10
|
+
// Returns [{ sql, index }] in source order. `index` is the offset of the first
|
|
11
|
+
// non-whitespace character of the statement, so callers can report positions.
|
|
12
|
+
// Use lineIndex(source) to turn an index into a 1-based line number.
|
|
13
|
+
|
|
14
|
+
const IDENT_CHAR = /[A-Za-z0-9_$]/;
|
|
15
|
+
|
|
16
|
+
// Index just past the closing quote of the literal or identifier opening at
|
|
17
|
+
// `i`. Handles '' / "" doubling and, for E'...' strings, backslash escapes.
|
|
18
|
+
// Getting E-strings wrong is not cosmetic: one E'don\'t' would otherwise
|
|
19
|
+
// swallow the rest of the file and every statement after it would vanish.
|
|
20
|
+
export function quotedEnd(sql, i) {
|
|
21
|
+
const q = sql[i];
|
|
22
|
+
const isE = q === "'" && (sql[i - 1] === 'E' || sql[i - 1] === 'e') && !(i >= 2 && IDENT_CHAR.test(sql[i - 2]));
|
|
23
|
+
const n = sql.length;
|
|
24
|
+
let j = i + 1;
|
|
25
|
+
while (j < n) {
|
|
26
|
+
if (isE && sql[j] === '\\') {
|
|
27
|
+
j += 2;
|
|
28
|
+
continue;
|
|
29
|
+
}
|
|
30
|
+
if (sql[j] === q) {
|
|
31
|
+
if (sql[j + 1] === q) {
|
|
32
|
+
j += 2;
|
|
33
|
+
continue;
|
|
34
|
+
}
|
|
35
|
+
return j + 1;
|
|
36
|
+
}
|
|
37
|
+
j++;
|
|
38
|
+
}
|
|
39
|
+
return n;
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
// If a dollar-quote opens at `i`, returns its tag ($$ or $name$), else null.
|
|
43
|
+
// A `$` inside an identifier (foo$bar) or a parameter ($1) is not a quote.
|
|
44
|
+
export function dollarTagAt(sql, i) {
|
|
45
|
+
if (sql[i] !== '$') return null;
|
|
46
|
+
if (i > 0 && IDENT_CHAR.test(sql[i - 1])) return null;
|
|
47
|
+
const m = /^\$([A-Za-z_][A-Za-z0-9_]*)?\$/.exec(sql.slice(i, i + 256));
|
|
48
|
+
return m ? m[0] : null;
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
function blockCommentEnd(sql, i) {
|
|
52
|
+
let depth = 1;
|
|
53
|
+
let j = i + 2;
|
|
54
|
+
while (j < sql.length && depth > 0) {
|
|
55
|
+
if (sql[j] === '/' && sql[j + 1] === '*') {
|
|
56
|
+
depth++;
|
|
57
|
+
j += 2;
|
|
58
|
+
} else if (sql[j] === '*' && sql[j + 1] === '/') {
|
|
59
|
+
depth--;
|
|
60
|
+
j += 2;
|
|
61
|
+
} else j++;
|
|
62
|
+
}
|
|
63
|
+
return j;
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
export function splitStatements(sql) {
|
|
67
|
+
const statements = [];
|
|
68
|
+
let start = 0;
|
|
69
|
+
let i = 0;
|
|
70
|
+
const n = sql.length;
|
|
71
|
+
|
|
72
|
+
while (i < n) {
|
|
73
|
+
const ch = sql[i];
|
|
74
|
+
if (ch === '-' && sql[i + 1] === '-') {
|
|
75
|
+
const nl = sql.indexOf('\n', i);
|
|
76
|
+
i = nl === -1 ? n : nl + 1;
|
|
77
|
+
continue;
|
|
78
|
+
}
|
|
79
|
+
if (ch === '/' && sql[i + 1] === '*') {
|
|
80
|
+
i = blockCommentEnd(sql, i);
|
|
81
|
+
continue;
|
|
82
|
+
}
|
|
83
|
+
if (ch === "'" || ch === '"') {
|
|
84
|
+
i = quotedEnd(sql, i);
|
|
85
|
+
continue;
|
|
86
|
+
}
|
|
87
|
+
const tag = dollarTagAt(sql, i);
|
|
88
|
+
if (tag) {
|
|
89
|
+
const end = sql.indexOf(tag, i + tag.length);
|
|
90
|
+
i = end === -1 ? n : end + tag.length;
|
|
91
|
+
continue;
|
|
92
|
+
}
|
|
93
|
+
if (ch === ';') {
|
|
94
|
+
const raw = sql.slice(start, i);
|
|
95
|
+
if (raw.trim()) statements.push({ sql: raw.trim(), index: start + (raw.length - raw.trimStart().length) });
|
|
96
|
+
i++;
|
|
97
|
+
start = i;
|
|
98
|
+
continue;
|
|
99
|
+
}
|
|
100
|
+
i++;
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
const tail = sql.slice(start);
|
|
104
|
+
if (tail.trim()) statements.push({ sql: tail.trim(), index: start + (tail.length - tail.trimStart().length) });
|
|
105
|
+
return statements;
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
// Strips comments so keyword matching can't be fooled by a commented-out
|
|
109
|
+
// `CREATE FUNCTION` or by a `-- SECURITY DEFINER` note. Strings and
|
|
110
|
+
// dollar-quoted bodies are kept verbatim.
|
|
111
|
+
export function stripComments(sql) {
|
|
112
|
+
let out = '';
|
|
113
|
+
let i = 0;
|
|
114
|
+
const n = sql.length;
|
|
115
|
+
while (i < n) {
|
|
116
|
+
const ch = sql[i];
|
|
117
|
+
if (ch === '-' && sql[i + 1] === '-') {
|
|
118
|
+
const nl = sql.indexOf('\n', i);
|
|
119
|
+
i = nl === -1 ? n : nl;
|
|
120
|
+
continue;
|
|
121
|
+
}
|
|
122
|
+
if (ch === '/' && sql[i + 1] === '*') {
|
|
123
|
+
i = blockCommentEnd(sql, i);
|
|
124
|
+
out += ' ';
|
|
125
|
+
continue;
|
|
126
|
+
}
|
|
127
|
+
if (ch === "'" || ch === '"') {
|
|
128
|
+
const end = quotedEnd(sql, i);
|
|
129
|
+
out += sql.slice(i, end);
|
|
130
|
+
i = end;
|
|
131
|
+
continue;
|
|
132
|
+
}
|
|
133
|
+
const tag = dollarTagAt(sql, i);
|
|
134
|
+
if (tag) {
|
|
135
|
+
const end = sql.indexOf(tag, i + tag.length);
|
|
136
|
+
const stop = end === -1 ? n : end + tag.length;
|
|
137
|
+
out += sql.slice(i, stop);
|
|
138
|
+
i = stop;
|
|
139
|
+
continue;
|
|
140
|
+
}
|
|
141
|
+
out += ch;
|
|
142
|
+
i++;
|
|
143
|
+
}
|
|
144
|
+
return out;
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
// Replaces the inside of every single-quoted literal and dollar-quoted string
|
|
148
|
+
// with spaces (same length), so a keyword search can't match text like
|
|
149
|
+
// DEFAULT 'enable row level security'. Identifiers are left alone.
|
|
150
|
+
export function blankLiterals(sql) {
|
|
151
|
+
let out = '';
|
|
152
|
+
let i = 0;
|
|
153
|
+
const n = sql.length;
|
|
154
|
+
while (i < n) {
|
|
155
|
+
const ch = sql[i];
|
|
156
|
+
if (ch === "'") {
|
|
157
|
+
const end = quotedEnd(sql, i);
|
|
158
|
+
out += `'${' '.repeat(Math.max(0, end - i - 2))}'`.slice(0, end - i);
|
|
159
|
+
i = end;
|
|
160
|
+
continue;
|
|
161
|
+
}
|
|
162
|
+
if (ch === '"') {
|
|
163
|
+
const end = quotedEnd(sql, i);
|
|
164
|
+
out += sql.slice(i, end);
|
|
165
|
+
i = end;
|
|
166
|
+
continue;
|
|
167
|
+
}
|
|
168
|
+
const tag = dollarTagAt(sql, i);
|
|
169
|
+
if (tag) {
|
|
170
|
+
const end = sql.indexOf(tag, i + tag.length);
|
|
171
|
+
const stop = end === -1 ? n : end + tag.length;
|
|
172
|
+
out += ' '.repeat(stop - i);
|
|
173
|
+
i = stop;
|
|
174
|
+
continue;
|
|
175
|
+
}
|
|
176
|
+
out += ch;
|
|
177
|
+
i++;
|
|
178
|
+
}
|
|
179
|
+
return out;
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
// Reads a possibly-quoted, possibly-schema-qualified identifier starting at
|
|
183
|
+
// `pos`. Handles `public.foo`, `"public"."foo"`, `foo`, `"foo"`.
|
|
184
|
+
// Returns { schema, name, end } with identifiers already case-folded the way
|
|
185
|
+
// Postgres folds them (unquoted -> lower, quoted -> verbatim).
|
|
186
|
+
export function readQualifiedName(sql, pos) {
|
|
187
|
+
const parts = [];
|
|
188
|
+
let i = pos;
|
|
189
|
+
for (;;) {
|
|
190
|
+
while (i < sql.length && /\s/.test(sql[i])) i++;
|
|
191
|
+
if (sql[i] === '"') {
|
|
192
|
+
let j = i + 1;
|
|
193
|
+
let val = '';
|
|
194
|
+
while (j < sql.length) {
|
|
195
|
+
if (sql[j] === '"') {
|
|
196
|
+
if (sql[j + 1] === '"') { val += '"'; j += 2; continue; }
|
|
197
|
+
j++;
|
|
198
|
+
break;
|
|
199
|
+
}
|
|
200
|
+
val += sql[j];
|
|
201
|
+
j++;
|
|
202
|
+
}
|
|
203
|
+
parts.push(val);
|
|
204
|
+
i = j;
|
|
205
|
+
} else {
|
|
206
|
+
const m = /^[A-Za-z_][A-Za-z0-9_$]*/.exec(sql.slice(i));
|
|
207
|
+
if (!m) break;
|
|
208
|
+
parts.push(m[0].toLowerCase());
|
|
209
|
+
i += m[0].length;
|
|
210
|
+
}
|
|
211
|
+
while (i < sql.length && /\s/.test(sql[i])) i++;
|
|
212
|
+
if (sql[i] === '.') { i++; continue; }
|
|
213
|
+
break;
|
|
214
|
+
}
|
|
215
|
+
if (parts.length === 0) return null;
|
|
216
|
+
const name = parts[parts.length - 1];
|
|
217
|
+
const schema = parts.length > 1 ? parts[parts.length - 2] : null;
|
|
218
|
+
return { schema, name, end: i };
|
|
219
|
+
}
|
|
220
|
+
|
|
221
|
+
// Reads the balanced parenthesised argument list starting at the '(' at `pos`.
|
|
222
|
+
// Returns { raw, end } or null when there is no '(' there.
|
|
223
|
+
export function readParenGroup(sql, pos) {
|
|
224
|
+
let i = pos;
|
|
225
|
+
while (i < sql.length && /\s/.test(sql[i])) i++;
|
|
226
|
+
if (sql[i] !== '(') return null;
|
|
227
|
+
const open = i;
|
|
228
|
+
let depth = 0;
|
|
229
|
+
while (i < sql.length) {
|
|
230
|
+
const ch = sql[i];
|
|
231
|
+
if (ch === "'" || ch === '"') {
|
|
232
|
+
i = quotedEnd(sql, i);
|
|
233
|
+
continue;
|
|
234
|
+
}
|
|
235
|
+
const tag = dollarTagAt(sql, i);
|
|
236
|
+
if (tag) {
|
|
237
|
+
const end = sql.indexOf(tag, i + tag.length);
|
|
238
|
+
i = end === -1 ? sql.length : end + tag.length;
|
|
239
|
+
continue;
|
|
240
|
+
}
|
|
241
|
+
if (ch === '(') depth++;
|
|
242
|
+
else if (ch === ')') {
|
|
243
|
+
depth--;
|
|
244
|
+
if (depth === 0) return { raw: sql.slice(open + 1, i), end: i + 1 };
|
|
245
|
+
}
|
|
246
|
+
i++;
|
|
247
|
+
}
|
|
248
|
+
return null;
|
|
249
|
+
}
|
|
250
|
+
|
|
251
|
+
// Returns a function mapping a character offset in `source` to a 1-based line
|
|
252
|
+
// number. Built once per file: rescanning from the start for every statement
|
|
253
|
+
// is quadratic and took 50 seconds on a large baseline.
|
|
254
|
+
export function lineIndex(source) {
|
|
255
|
+
const starts = [0];
|
|
256
|
+
for (let i = 0; i < source.length; i++) if (source.charCodeAt(i) === 10) starts.push(i + 1);
|
|
257
|
+
return (index) => {
|
|
258
|
+
let lo = 0;
|
|
259
|
+
let hi = starts.length - 1;
|
|
260
|
+
while (lo < hi) {
|
|
261
|
+
const mid = (lo + hi + 1) >> 1;
|
|
262
|
+
if (starts[mid] <= index) lo = mid;
|
|
263
|
+
else hi = mid - 1;
|
|
264
|
+
}
|
|
265
|
+
return lo + 1;
|
|
266
|
+
};
|
|
267
|
+
}
|