@subodh001/pg-safe-migrate 2.5.0 → 2.7.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,19 @@
1
+ export function suppressionReport(records) {
2
+ const summary = { suppressed: 0, rejected: 0, unused: 0, scanErrors: 0 };
3
+ for (const r of records) {
4
+ const key = r.status === 'scan-error' ? 'scanErrors' : r.status;
5
+ if (!Object.hasOwn(summary, key)) throw new Error('Unknown suppression audit status');
6
+ summary[key]++;
7
+ }
8
+ return { summary, records };
9
+ }
10
+ const safe = value => String(value ?? '').replace(/[\u0000-\u001f\u007f-\u009f\u2028\u2029\u202a-\u202e\u2066-\u2069]/g, ' ');
11
+ const cell = value => safe(value).replace(/[&<>\\|`*_~\[\]#!]/g, c => `&#${c.charCodeAt(0)};`);
12
+ export function suppressionText(audit) {
13
+ const s = audit.summary;
14
+ return [`Suppression audit: ${s.suppressed} suppressed, ${s.rejected} rejected, ${s.unused} unused, ${s.scanErrors} scan errors.`, ...audit.records.map(r => ` ${safe(r.status)} ${safe(r.finding?.ruleId ?? r.ruleId ?? r.ruleIds?.join(', '))} ${safe(r.file)}:${r.directiveLine ?? r.line ?? '?'} — ${safe(r.reason)} ${safe(r.message)}`), 'Suppression is not evidence of migration safety.'].join('\n');
15
+ }
16
+ export function suppressionMarkdown(audit) {
17
+ const s = audit.summary;
18
+ return ['','## Suppression audit','',`${s.suppressed} suppressed, ${s.rejected} rejected, ${s.unused} unused, ${s.scanErrors} scan errors.`, '', '| Status | Rule | File | Directive line | Reason | Detail |','|---|---|---|---:|---|---|', ...audit.records.map(r => `| ${cell(r.status)} | ${cell(r.finding?.ruleId ?? r.ruleId ?? r.ruleIds?.join(', '))} | ${cell(r.file)} | ${cell(r.directiveLine ?? r.line)} | ${cell(r.reason)} | ${cell(r.message ?? r.finding?.message)} |`), '', 'Suppression is not evidence of migration safety.', ''].join('\n');
19
+ }
@@ -0,0 +1,78 @@
1
+ // Detection only. Never use these candidates to suppress findings without AST binding.
2
+ const directive = /^\s*pg-safe-migrate-disable-next-line\b(.*)$/i;
3
+ const syntax = /^\s+(PG\d{3}(?:[ \t]*,[ \t]*PG\d{3})*)[ \t]*(?:--[ \t]*reason:[ \t]*(.*))?$/i;
4
+ const identifier = /[a-zA-Z_\u0080-\uffff]/;
5
+ const continuation = /[a-zA-Z_0-9$\u0080-\uffff]/;
6
+
7
+ export function scanSuppressions(sql) {
8
+ if (typeof sql !== 'string') throw new TypeError('SQL must be a string');
9
+ const directives = [], invalid = [];
10
+ let i = 0, line = 1, lineStart = 0;
11
+ function advance(end) {
12
+ while (i < end) {
13
+ if (sql[i] === '\r' || (sql[i] === '\n' && sql[i-1] !== '\r')) line++;
14
+ if (sql[i] === '\r' || sql[i] === '\n') lineStart = i + 1;
15
+ i++;
16
+ }
17
+ }
18
+ function fail(message) { return { directives: [], invalid: [], scanError: { line, offset: i, message } }; }
19
+ while (i < sql.length) {
20
+ const c = sql[i];
21
+ if (sql.startsWith('--', i)) {
22
+ const start = i, startLine = line;
23
+ let end = i + 2;
24
+ while (end < sql.length && !/[\r\n]/.test(sql[end])) end++;
25
+ const match = directive.exec(sql.slice(i+2,end));
26
+ if (match && /^[ \t]*$/.test(sql.slice(lineStart,i))) {
27
+ const parsed = syntax.exec(match[1]);
28
+ const location = { line: startLine, offset: start, endOffset: end };
29
+ if (!parsed) invalid.push({ ...location, message: 'Malformed suppression directive' });
30
+ else directives.push({ ...location, ruleIds: [...new Set(parsed[1].toUpperCase().split(',').map(s=>s.trim()))], reason: (parsed[2] || '').trim() });
31
+ }
32
+ advance(end); continue;
33
+ }
34
+ if (sql.startsWith('/*', i)) {
35
+ let depth = 1; advance(i+2);
36
+ while (i < sql.length && depth) {
37
+ if (sql.startsWith('/*',i)) { depth++; advance(i+2); }
38
+ else if (sql.startsWith('*/',i)) { depth--; advance(i+2); }
39
+ else advance(i+1);
40
+ }
41
+ if (depth) return fail('Unterminated block comment');
42
+ continue;
43
+ }
44
+ const escape = /[eE]/.test(c) && sql[i+1] === "'";
45
+ if (escape || c === "'" || c === '"') {
46
+ const quote = escape ? "'" : c;
47
+ advance(i+(escape?2:1)); let closed = false;
48
+ while (i < sql.length) {
49
+ if (sql[i] === '\\' && quote === "'") {
50
+ if (!escape) return fail('Ambiguous backslash in ordinary string; suppression scan disabled');
51
+ advance(Math.min(i+2,sql.length)); continue;
52
+ }
53
+ if (sql[i] === quote) {
54
+ if (sql[i+1] === quote) { advance(i+2); continue; }
55
+ advance(i+1); closed = true; break;
56
+ }
57
+ advance(i+1);
58
+ }
59
+ if (!closed) return fail('Unterminated quoted token');
60
+ continue;
61
+ }
62
+ if (c === '$') {
63
+ const tag = /^\$(?:[a-zA-Z_\u0080-\uffff][a-zA-Z_0-9\u0080-\uffff]*)?\$/.exec(sql.slice(i));
64
+ if (tag) {
65
+ const end = sql.indexOf(tag[0], i+tag[0].length);
66
+ if (end < 0) return fail('Unterminated dollar quote');
67
+ advance(end+tag[0].length); continue;
68
+ }
69
+ }
70
+ if (identifier.test(c)) {
71
+ let end = i+1;
72
+ while (end < sql.length && continuation.test(sql[end])) end++;
73
+ advance(end); continue;
74
+ }
75
+ advance(i+1);
76
+ }
77
+ return { directives, invalid, scanError: null };
78
+ }
@@ -4,14 +4,22 @@ import { getRule } from './rules/ruleCatalog.js';
4
4
  export function loadTeamPolicy(file) {
5
5
  const policy = JSON.parse(fs.readFileSync(file, 'utf8'));
6
6
  if (!policy || typeof policy !== 'object' || Array.isArray(policy)) throw new Error('Team policy must be a JSON object');
7
- const allowed = ['name', 'maxRiskScore', 'maxWarnings', 'blockedRules', 'requireSimulation'];
7
+ const allowed = ['name', 'maxRiskScore', 'maxWarnings', 'blockedRules', 'requireSimulation', 'suppression'];
8
8
  for (const key of Object.keys(policy)) if (!allowed.includes(key)) throw new Error(`Unknown team policy key: ${key}`);
9
9
  if (policy.name !== undefined && (typeof policy.name !== 'string' || !policy.name.trim() || policy.name.length > 100)) throw new Error('name must be a nonempty string of at most 100 characters');
10
10
  if (policy.maxRiskScore !== undefined && (!Number.isInteger(policy.maxRiskScore) || policy.maxRiskScore < 0 || policy.maxRiskScore > 100)) throw new Error('maxRiskScore must be 0-100');
11
11
  if (policy.maxWarnings !== undefined && (!Number.isInteger(policy.maxWarnings) || policy.maxWarnings < 0)) throw new Error('maxWarnings must be >= 0');
12
- if (policy.blockedRules !== undefined && (!Array.isArray(policy.blockedRules) || policy.blockedRules.some(x => typeof x !== 'string' || !getRule(x)))) throw new Error('blockedRules must be an array of PG rule IDs');
12
+ if (policy.blockedRules !== undefined && (!Array.isArray(policy.blockedRules) || policy.blockedRules.some(x => typeof x !== 'string' || !/^PG\d{3}$/.test(x) || !getRule(x)))) throw new Error('blockedRules must be an array of PG rule IDs');
13
13
  if (policy.blockedRules && new Set(policy.blockedRules).size !== policy.blockedRules.length) throw new Error('blockedRules must not contain duplicates');
14
14
  if (policy.requireSimulation !== undefined && typeof policy.requireSimulation !== 'boolean') throw new Error('requireSimulation must be boolean');
15
+ if (policy.suppression !== undefined) {
16
+ const s = policy.suppression;
17
+ if (!s || typeof s !== 'object' || Array.isArray(s)) throw new Error('policy.suppression must be an object');
18
+ for (const key of Object.keys(s)) if (!['protectedRules','maxSuppressedFindings','failOnRejected','failOnUnused'].includes(key)) throw new Error(`Unknown policy suppression key: ${key}`);
19
+ if (s.protectedRules !== undefined && (!Array.isArray(s.protectedRules) || s.protectedRules.some(id => typeof id !== 'string' || !/^PG\d{3}$/.test(id) || !getRule(id)))) throw new Error('Invalid policy protectedRules');
20
+ if (s.maxSuppressedFindings !== undefined && (!Number.isSafeInteger(s.maxSuppressedFindings) || s.maxSuppressedFindings < 0)) throw new Error('Invalid maxSuppressedFindings');
21
+ for (const key of ['failOnRejected','failOnUnused']) if (s[key] !== undefined && typeof s[key] !== 'boolean') throw new Error(`Invalid ${key}`);
22
+ }
15
23
  return policy;
16
24
  }
17
25
 
@@ -46,3 +54,31 @@ export function assessLintPolicy(findings, policy, risk = {}) {
46
54
  for (const f of findings) if (policy.blockedRules?.includes(f.ruleId)) reasons.push(`Blocked rule ${f.ruleId}: ${f.file}`);
47
55
  return { name: policy.name ?? 'local-team', passed: reasons.length === 0, reasons: [...new Set(reasons)], note: 'Passing a static gate is not a safety guarantee; unknown locks and production workloads still require review.' };
48
56
  }
57
+
58
+ // A static gate always evaluates all configured risks, including suppressed ones.
59
+ export function applySuppressionPolicy(config, policy) {
60
+ if (!config.suppression?.enabled || !policy) return config;
61
+ const protectedRules = [...new Set([...config.suppression.protectedRules, ...['PG011','PG023'], ...(policy.blockedRules ?? []), ...(policy.suppression?.protectedRules ?? [])])];
62
+ return { ...config, suppression: { ...config.suppression, protectedRules } };
63
+ }
64
+ export function enforceSuppressionAudit(gate, policy, audit) {
65
+ if (!audit) return gate;
66
+ const s = audit.summary;
67
+ const limits = policy.suppression ?? {};
68
+ const reasons = [...gate.reasons];
69
+ if (s.suppressed > (limits.maxSuppressedFindings ?? 0)) reasons.push('Suppression limit exceeded');
70
+ if (s.rejected && limits.failOnRejected !== false) reasons.push('Rejected suppression directives');
71
+ if (s.unused && limits.failOnUnused !== false) reasons.push('Unused suppression directives');
72
+ if (s.scanErrors) reasons.push('Suppression scan failed');
73
+ return { ...gate, reasons, passed: reasons.length === 0 };
74
+ }
75
+
76
+ // CI must supply trusted configuration, policy, target and PostgreSQL version.
77
+ export function validateGateConfig(config, policy) {
78
+ if (!policy) return;
79
+ if (config.exclude?.length) throw new Error('Enterprise policy does not allow project exclusions');
80
+ if (config.severity !== 'error') throw new Error('Enterprise policy requires default error severity');
81
+ for (const [id, severity] of Object.entries(config.rules ?? {})) {
82
+ if (severity === 'off' || severity === 'warning') throw new Error(`Enterprise policy does not allow weakening rule ${id}`);
83
+ }
84
+ }