rlsproof 0.0.0-stage → 1.0.0

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.
@@ -0,0 +1,486 @@
1
+ import fs from "node:fs";
2
+ import path from "node:path";
3
+ import * as libpg from "libpg-query";
4
+ import { redactSecret, sanitizeSnippet, toPosixRelPath } from "../core/findings.js";
5
+
6
+ let moduleReadyPromise = null;
7
+
8
+ export async function ensureSqlParserReady() {
9
+ if (!moduleReadyPromise) {
10
+ moduleReadyPromise = libpg.loadModule();
11
+ }
12
+ await moduleReadyPromise;
13
+ }
14
+
15
+ /**
16
+ * Discovers ordered SQL migration files for a file or repository directory.
17
+ * @param {string} targetPath
18
+ * @returns {{ mode: string, rootDir: string, files: string[] }}
19
+ */
20
+ export function discoverSqlFiles(targetPath) {
21
+ const abs = path.resolve(targetPath);
22
+ const stat = fs.statSync(abs);
23
+
24
+ if (stat.isFile()) {
25
+ return {
26
+ mode: abs.toLowerCase().endsWith(".sql") ? "single-file" : "none",
27
+ rootDir: path.dirname(abs),
28
+ files: abs.toLowerCase().endsWith(".sql") ? [abs] : [],
29
+ };
30
+ }
31
+
32
+ const collectSortedSql = (dir) => {
33
+ if (!fs.existsSync(dir)) return [];
34
+ const entries = fs.readdirSync(dir, { withFileTypes: true });
35
+ const out = [];
36
+ for (const entry of entries) {
37
+ const full = path.join(dir, entry.name);
38
+ if (entry.isDirectory()) {
39
+ // Recurse into subdirectories if migrations are organized in nested folders
40
+ out.push(...collectSortedSql(full));
41
+ } else if (entry.isFile() && entry.name.toLowerCase().endsWith(".sql")) {
42
+ out.push(full);
43
+ }
44
+ }
45
+ return out.sort((a, b) =>
46
+ a.replace(/\\/g, "/").localeCompare(b.replace(/\\/g, "/"))
47
+ );
48
+ };
49
+
50
+ const supabaseMigrations = path.join(abs, "supabase", "migrations");
51
+ if (fs.existsSync(supabaseMigrations) && fs.statSync(supabaseMigrations).isDirectory()) {
52
+ const files = collectSortedSql(supabaseMigrations);
53
+ if (files.length > 0) {
54
+ return { mode: "supabase/migrations", rootDir: abs, files };
55
+ }
56
+ }
57
+
58
+ const supabaseSchemas = path.join(abs, "supabase", "schemas");
59
+ if (fs.existsSync(supabaseSchemas) && fs.statSync(supabaseSchemas).isDirectory()) {
60
+ const files = collectSortedSql(supabaseSchemas);
61
+ if (files.length > 0) {
62
+ return { mode: "supabase/schemas", rootDir: abs, files };
63
+ }
64
+ }
65
+
66
+ // Fallback for standalone SQL fixture folders or custom directories containing direct .sql files
67
+ const directSql = fs
68
+ .readdirSync(abs, { withFileTypes: true })
69
+ .filter((e) => e.isFile() && e.name.toLowerCase().endsWith(".sql"))
70
+ .map((e) => path.join(abs, e.name))
71
+ .sort((a, b) => a.localeCompare(b));
72
+
73
+ if (directSql.length > 0) {
74
+ return { mode: "directory-sql", rootDir: abs, files: directSql };
75
+ }
76
+
77
+ // Also check top-level migrations/ directory if neither supabase/* nor direct .sql exists
78
+ const plainMigrations = path.join(abs, "migrations");
79
+ if (fs.existsSync(plainMigrations) && fs.statSync(plainMigrations).isDirectory()) {
80
+ const files = collectSortedSql(plainMigrations);
81
+ if (files.length > 0) {
82
+ return { mode: "migrations", rootDir: abs, files };
83
+ }
84
+ }
85
+
86
+ return { mode: "none", rootDir: abs, files: [] };
87
+ }
88
+
89
+ /**
90
+ * Builds an index of UTF-8 byte offsets where each line starts, allowing exact
91
+ * O(log N) mapping from PostgreSQL byte offsets to 1-based line numbers.
92
+ */
93
+ function buildLineByteOffsets(buf) {
94
+ const starts = [0];
95
+ for (let i = 0; i < buf.length; i++) {
96
+ if (buf[i] === 0x0a) {
97
+ starts.push(i + 1);
98
+ }
99
+ }
100
+ return starts;
101
+ }
102
+
103
+ export function byteOffsetToLine(lineStarts, byteOffset) {
104
+ const offset = Math.max(0, byteOffset || 0);
105
+ let lo = 0;
106
+ let hi = lineStarts.length - 1;
107
+ while (lo <= hi) {
108
+ const mid = (lo + hi) >> 1;
109
+ if (lineStarts[mid] <= offset) {
110
+ lo = mid + 1;
111
+ } else {
112
+ hi = mid - 1;
113
+ }
114
+ }
115
+ return Math.max(1, hi + 1);
116
+ }
117
+
118
+ /**
119
+ * Strips psql backslash meta-commands outside quotes/comments, preserving line numbers
120
+ * and recording each stripped command as an explicit UNSUPPORTED notice.
121
+ */
122
+ function stripPsqlMetaCommands(sqlText, relFile) {
123
+ const lines = sqlText.split(/\r?\n/);
124
+ const unsupported = [];
125
+ const cleanedLines = [];
126
+ let inDollarTag = null;
127
+ let inBlockComment = 0;
128
+
129
+ for (let idx = 0; idx < lines.length; idx++) {
130
+ const line = lines[idx];
131
+ const trimmed = line.trimStart();
132
+
133
+ if (!inDollarTag && inBlockComment === 0 && /^\\/.test(trimmed)) {
134
+ unsupported.push({
135
+ type: "PSQL_META_COMMAND",
136
+ file: relFile,
137
+ line: idx + 1,
138
+ reason: redactSecret("psql meta-command is outside PostgreSQL SQL grammar and was skipped"),
139
+ snippet: sanitizeSnippet(trimmed, 120),
140
+ });
141
+ cleanedLines.push("");
142
+ continue;
143
+ }
144
+
145
+ // Track multiline block comments and dollar-quoted blocks conservatively
146
+ let i = 0;
147
+ while (i < line.length) {
148
+ const ch = line[i];
149
+ const next = line[i + 1] || "";
150
+
151
+ if (inBlockComment > 0) {
152
+ if (ch === "/" && next === "*") {
153
+ inBlockComment += 1;
154
+ i += 2;
155
+ } else if (ch === "*" && next === "/") {
156
+ inBlockComment -= 1;
157
+ i += 2;
158
+ } else {
159
+ i += 1;
160
+ }
161
+ continue;
162
+ }
163
+
164
+ if (inDollarTag) {
165
+ if (line.startsWith(inDollarTag, i)) {
166
+ i += inDollarTag.length;
167
+ inDollarTag = null;
168
+ } else {
169
+ i += 1;
170
+ }
171
+ continue;
172
+ }
173
+
174
+ if (ch === "-" && next === "-") {
175
+ break;
176
+ }
177
+ if (ch === "/" && next === "*") {
178
+ inBlockComment += 1;
179
+ i += 2;
180
+ continue;
181
+ }
182
+ if (ch === "'") {
183
+ i += 1;
184
+ while (i < line.length) {
185
+ if (line[i] === "'" && line[i + 1] === "'") {
186
+ i += 2;
187
+ } else if (line[i] === "'") {
188
+ i += 1;
189
+ break;
190
+ } else {
191
+ i += 1;
192
+ }
193
+ }
194
+ continue;
195
+ }
196
+ if (ch === '"') {
197
+ i += 1;
198
+ while (i < line.length) {
199
+ if (line[i] === '"' && line[i + 1] === '"') {
200
+ i += 2;
201
+ } else if (line[i] === '"') {
202
+ i += 1;
203
+ break;
204
+ } else {
205
+ i += 1;
206
+ }
207
+ }
208
+ continue;
209
+ }
210
+ if (ch === "$") {
211
+ const tagMatch = line.slice(i).match(/^\$([A-Za-z_][A-Za-z0-9_]*)?\$/);
212
+ if (tagMatch) {
213
+ inDollarTag = tagMatch[0];
214
+ i += inDollarTag.length;
215
+ continue;
216
+ }
217
+ }
218
+ i += 1;
219
+ }
220
+
221
+ cleanedLines.push(line);
222
+ }
223
+
224
+ return {
225
+ cleanedSql: cleanedLines.join("\n"),
226
+ unsupported,
227
+ };
228
+ }
229
+
230
+ /**
231
+ * Splits SQL text into individual statements while respecting quotes, comments,
232
+ * and dollar-quoted function bodies. Used as fallback when a whole migration fails
233
+ * to parse so valid statements in the same file are still recovered.
234
+ */
235
+ export function splitSqlStatementsWithLines(sqlText) {
236
+ const statements = [];
237
+ const n = sqlText.length;
238
+ let start = 0;
239
+ let i = 0;
240
+ let line = 1;
241
+ let stmtLine = 1;
242
+
243
+ function pushSlice(endIdx) {
244
+ const rawSlice = sqlText.slice(start, endIdx);
245
+ const trimmed = rawSlice.trim();
246
+ if (trimmed) {
247
+ const firstNonWs = rawSlice.search(/\S/);
248
+ const leading = firstNonWs > 0 ? rawSlice.slice(0, firstNonWs) : "";
249
+ const leadingLines = (leading.match(/\n/g) || []).length;
250
+ statements.push({
251
+ text: trimmed,
252
+ line: stmtLine + leadingLines,
253
+ });
254
+ }
255
+ start = endIdx + 1;
256
+ stmtLine = line;
257
+ }
258
+
259
+ while (i < n) {
260
+ const ch = sqlText[i];
261
+ const next = sqlText[i + 1] || "";
262
+
263
+ if (ch === "\n") {
264
+ line += 1;
265
+ i += 1;
266
+ continue;
267
+ }
268
+
269
+ if (ch === "-" && next === "-") {
270
+ while (i < n && sqlText[i] !== "\n") i += 1;
271
+ continue;
272
+ }
273
+
274
+ if (ch === "/" && next === "*") {
275
+ let depth = 1;
276
+ i += 2;
277
+ while (i < n && depth > 0) {
278
+ if (sqlText[i] === "\n") line += 1;
279
+ if (sqlText[i] === "/" && sqlText[i + 1] === "*") {
280
+ depth += 1;
281
+ i += 2;
282
+ } else if (sqlText[i] === "*" && sqlText[i + 1] === "/") {
283
+ depth -= 1;
284
+ i += 2;
285
+ } else {
286
+ i += 1;
287
+ }
288
+ }
289
+ continue;
290
+ }
291
+
292
+ if (ch === "'") {
293
+ i += 1;
294
+ while (i < n) {
295
+ if (sqlText[i] === "\n") line += 1;
296
+ if (sqlText[i] === "'" && sqlText[i + 1] === "'") {
297
+ i += 2;
298
+ } else if (sqlText[i] === "'") {
299
+ i += 1;
300
+ break;
301
+ } else {
302
+ i += 1;
303
+ }
304
+ }
305
+ continue;
306
+ }
307
+
308
+ if (ch === '"') {
309
+ i += 1;
310
+ while (i < n) {
311
+ if (sqlText[i] === "\n") line += 1;
312
+ if (sqlText[i] === '"' && sqlText[i + 1] === '"') {
313
+ i += 2;
314
+ } else if (sqlText[i] === '"') {
315
+ i += 1;
316
+ break;
317
+ } else {
318
+ i += 1;
319
+ }
320
+ }
321
+ continue;
322
+ }
323
+
324
+ if (ch === "$") {
325
+ const tagMatch = sqlText.slice(i).match(/^\$([A-Za-z_][A-Za-z0-9_]*)?\$/);
326
+ if (tagMatch) {
327
+ const tag = tagMatch[0];
328
+ const endIdx = sqlText.indexOf(tag, i + tag.length);
329
+ if (endIdx !== -1) {
330
+ const inner = sqlText.slice(i, endIdx + tag.length);
331
+ line += (inner.match(/\n/g) || []).length;
332
+ i = endIdx + tag.length;
333
+ continue;
334
+ }
335
+ }
336
+ }
337
+
338
+ if (ch === ";") {
339
+ pushSlice(i);
340
+ i += 1;
341
+ continue;
342
+ }
343
+
344
+ i += 1;
345
+ }
346
+
347
+ if (start < n) {
348
+ pushSlice(n);
349
+ }
350
+
351
+ return statements;
352
+ }
353
+
354
+ function isCommentOnlySql(text) {
355
+ const withoutLineComments = text.replace(/--[^\r\n]*/g, "");
356
+ const withoutBlockComments = withoutLineComments.replace(/\/\*[\s\S]*?\*\//g, "");
357
+ return withoutBlockComments.trim().length === 0;
358
+ }
359
+
360
+ function extractRawSlice(buf, stmtLocation, stmtLen, nextStmtLocation) {
361
+ const start = Math.max(0, stmtLocation || 0);
362
+ if (typeof stmtLen === "number" && stmtLen > 0) {
363
+ return buf.subarray(start, Math.min(buf.length, start + stmtLen)).toString("utf8").trim();
364
+ }
365
+ const end =
366
+ typeof nextStmtLocation === "number" && nextStmtLocation > start
367
+ ? Math.min(buf.length, nextStmtLocation)
368
+ : buf.length;
369
+ return buf.subarray(start, end).toString("utf8").trim();
370
+ }
371
+
372
+ /**
373
+ * Parses an ordered list of SQL files using libpg-query@18.3.0 with resilient
374
+ * per-statement fallback and explicit UNSUPPORTED tracking.
375
+ */
376
+ export async function parseMigrationFiles(files, rootDir) {
377
+ await ensureSqlParserReady();
378
+
379
+ const parsedStatements = [];
380
+ const unsupported = [];
381
+ const fileTexts = new Map();
382
+ const parseStats = {
383
+ filesTotal: files.length,
384
+ filesParsedCleanly: 0,
385
+ statementsTotal: 0,
386
+ statementsParsed: 0,
387
+ statementsFailed: 0,
388
+ };
389
+
390
+ for (const filePath of files) {
391
+ const relFile = toPosixRelPath(rootDir, filePath);
392
+ let rawText = fs.readFileSync(filePath, "utf8");
393
+ if (rawText.charCodeAt(0) === 0xfeff) {
394
+ rawText = rawText.slice(1);
395
+ }
396
+ fileTexts.set(relFile, rawText);
397
+
398
+ if (!rawText.trim() || isCommentOnlySql(rawText)) {
399
+ parseStats.filesParsedCleanly += 1;
400
+ continue;
401
+ }
402
+
403
+ const { cleanedSql, unsupported: psqlUnsupported } = stripPsqlMetaCommands(rawText, relFile);
404
+ unsupported.push(...psqlUnsupported);
405
+
406
+ if (!cleanedSql.trim() || isCommentOnlySql(cleanedSql)) {
407
+ parseStats.filesParsedCleanly += psqlUnsupported.length === 0 ? 1 : 0;
408
+ continue;
409
+ }
410
+
411
+ try {
412
+ const tree = libpg.parseSync(cleanedSql);
413
+ const stmts = tree?.stmts || [];
414
+ const buf = Buffer.from(cleanedSql, "utf8");
415
+ const lineStarts = buildLineByteOffsets(buf);
416
+
417
+ for (let i = 0; i < stmts.length; i++) {
418
+ const rawStmt = stmts[i];
419
+ if (!rawStmt?.stmt) continue;
420
+ const stmtLoc = rawStmt.stmt_location || 0;
421
+ const nextLoc = i + 1 < stmts.length ? stmts[i + 1].stmt_location : undefined;
422
+ const line = byteOffsetToLine(lineStarts, stmtLoc);
423
+ const text = extractRawSlice(buf, stmtLoc, rawStmt.stmt_len, nextLoc);
424
+ const stmtType = Object.keys(rawStmt.stmt)[0];
425
+
426
+ parseStats.statementsTotal += 1;
427
+ parseStats.statementsParsed += 1;
428
+ parsedStatements.push({
429
+ file: relFile,
430
+ line,
431
+ stmtType,
432
+ node: rawStmt.stmt[stmtType],
433
+ text,
434
+ });
435
+ }
436
+ if (psqlUnsupported.length === 0) {
437
+ parseStats.filesParsedCleanly += 1;
438
+ }
439
+ } catch {
440
+ // Fallback: split statements and parse individually so one bad statement doesn't drop the file.
441
+ const slices = splitSqlStatementsWithLines(cleanedSql);
442
+ let fileFailures = psqlUnsupported.length;
443
+
444
+ for (const slice of slices) {
445
+ if (!slice.text || isCommentOnlySql(slice.text)) continue;
446
+ parseStats.statementsTotal += 1;
447
+ try {
448
+ const singleTree = libpg.parseSync(slice.text);
449
+ const singleStmts = singleTree?.stmts || [];
450
+ for (const s of singleStmts) {
451
+ if (!s?.stmt) continue;
452
+ const stmtType = Object.keys(s.stmt)[0];
453
+ parseStats.statementsParsed += 1;
454
+ parsedStatements.push({
455
+ file: relFile,
456
+ line: slice.line,
457
+ stmtType,
458
+ node: s.stmt[stmtType],
459
+ text: slice.text,
460
+ });
461
+ }
462
+ } catch (stmtErr) {
463
+ parseStats.statementsFailed += 1;
464
+ fileFailures += 1;
465
+ unsupported.push({
466
+ type: "PARSE_ERROR",
467
+ file: relFile,
468
+ line: slice.line,
469
+ reason: redactSecret(stmtErr?.message || "libpg-query failed to parse statement"),
470
+ snippet: sanitizeSnippet(slice.text, 120),
471
+ });
472
+ }
473
+ }
474
+ if (fileFailures === 0) {
475
+ parseStats.filesParsedCleanly += 1;
476
+ }
477
+ }
478
+ }
479
+
480
+ return {
481
+ parsedStatements,
482
+ unsupported,
483
+ parseStats,
484
+ fileTexts,
485
+ };
486
+ }