|
| 1 | +import crypto from 'crypto'; |
| 2 | +import fs from 'fs'; |
| 3 | +import type { |
| 4 | + BaselineEntry, |
| 5 | + BaselineFile, |
| 6 | + ScanResult, |
| 7 | +} from '../config/types.js'; |
| 8 | +import { resolveFromCwd } from '../core/helpers/resolveFromCwd.js'; |
| 9 | + |
| 10 | +export const BASELINE_FILE = 'dotenv-diff.baseline.json'; |
| 11 | +const BASELINE_VERSION = 1; |
| 12 | + |
| 13 | +/** |
| 14 | + * Loads the baseline file from disk. Returns null if the file does not exist |
| 15 | + * or cannot be parsed into a valid shape. |
| 16 | + * @param cwd - Current working directory to resolve the baseline file from |
| 17 | + * @returns The parsed baseline file or null if not found/invalid |
| 18 | + */ |
| 19 | +export function loadBaselineFile(cwd: string): BaselineFile | null { |
| 20 | + const filePath = resolveFromCwd(cwd, BASELINE_FILE); |
| 21 | + if (!fs.existsSync(filePath)) return null; |
| 22 | + try { |
| 23 | + const raw = fs.readFileSync(filePath, 'utf8'); |
| 24 | + const parsed = JSON.parse(raw) as unknown; |
| 25 | + if ( |
| 26 | + typeof parsed === 'object' && |
| 27 | + parsed !== null && |
| 28 | + 'version' in parsed && |
| 29 | + Array.isArray((parsed as { entries?: unknown }).entries) |
| 30 | + ) { |
| 31 | + return parsed as BaselineFile; |
| 32 | + } |
| 33 | + return null; |
| 34 | + } catch { |
| 35 | + return null; |
| 36 | + } |
| 37 | +} |
| 38 | + |
| 39 | +/** |
| 40 | + * Writes a baseline file to disk and returns the absolute path it was written to. |
| 41 | + * @param cwd - Current working directory to resolve the baseline file from |
| 42 | + * @param entries - List of baseline entries to write |
| 43 | + * @returns Absolute file path of the written baseline file |
| 44 | + * @throws If writing the file fails (e.g. due to permissions or disk issues) |
| 45 | + */ |
| 46 | +export async function writeBaselineFile( |
| 47 | + cwd: string, |
| 48 | + entries: BaselineEntry[], |
| 49 | +): Promise<string> { |
| 50 | + const filePath = resolveFromCwd(cwd, BASELINE_FILE); |
| 51 | + const payload: BaselineFile = { |
| 52 | + version: BASELINE_VERSION, |
| 53 | + createdAt: new Date().toISOString(), |
| 54 | + entries, |
| 55 | + }; |
| 56 | + await fs.promises.writeFile( |
| 57 | + filePath, |
| 58 | + `${JSON.stringify(payload, null, 2)}\n`, |
| 59 | + 'utf8', |
| 60 | + ); |
| 61 | + return filePath; |
| 62 | +} |
| 63 | + |
| 64 | +/** |
| 65 | + * Converts a ScanResult into a deterministic list of baseline entries. |
| 66 | + * |
| 67 | + * Identifiers are chosen to be stable across runs — volatile fields like line |
| 68 | + * numbers and snippet text are excluded. Secrets are stored as a fingerprint |
| 69 | + * (SHA-256 truncated to 12 hex chars) of `file:snippet` so no secret value is |
| 70 | + * ever written to the baseline file. |
| 71 | + * @param scanResult The full scan result to convert into baseline entries |
| 72 | + * @returns A sorted list of baseline entries representing the scan result |
| 73 | + */ |
| 74 | +export function collectBaselineEntries( |
| 75 | + scanResult: ScanResult, |
| 76 | +): BaselineEntry[] { |
| 77 | + const entries: BaselineEntry[] = []; |
| 78 | + |
| 79 | + for (const key of scanResult.missing) { |
| 80 | + entries.push({ rule: 'missing', key }); |
| 81 | + } |
| 82 | + |
| 83 | + for (const key of scanResult.unused) { |
| 84 | + entries.push({ rule: 'unused', key }); |
| 85 | + } |
| 86 | + |
| 87 | + for (const usage of scanResult.logged) { |
| 88 | + entries.push({ |
| 89 | + rule: 'logged', |
| 90 | + key: usage.variable, |
| 91 | + file: usage.file, |
| 92 | + }); |
| 93 | + } |
| 94 | + |
| 95 | + for (const secret of scanResult.secrets) { |
| 96 | + entries.push({ |
| 97 | + rule: 'secret', |
| 98 | + key: fingerprint(`${secret.file}:${secret.snippet}`), |
| 99 | + file: secret.file, |
| 100 | + }); |
| 101 | + } |
| 102 | + |
| 103 | + for (const warning of scanResult.exampleWarnings ?? []) { |
| 104 | + entries.push({ rule: 'example-secret', key: warning.key }); |
| 105 | + } |
| 106 | + |
| 107 | + for (const dup of scanResult.duplicates.env ?? []) { |
| 108 | + entries.push({ rule: 'duplicate-env', key: dup.key }); |
| 109 | + } |
| 110 | + |
| 111 | + for (const dup of scanResult.duplicates.example ?? []) { |
| 112 | + entries.push({ rule: 'duplicate-example', key: dup.key }); |
| 113 | + } |
| 114 | + |
| 115 | + // variable + file uniquely identifies a framework warning without line numbers |
| 116 | + for (const warning of scanResult.frameworkWarnings ?? []) { |
| 117 | + entries.push({ |
| 118 | + rule: 'framework', |
| 119 | + key: warning.variable, |
| 120 | + file: warning.file, |
| 121 | + }); |
| 122 | + } |
| 123 | + |
| 124 | + for (const warning of scanResult.uppercaseWarnings ?? []) { |
| 125 | + entries.push({ rule: 'uppercase', key: warning.key }); |
| 126 | + } |
| 127 | + |
| 128 | + for (const warning of scanResult.expireWarnings ?? []) { |
| 129 | + entries.push({ rule: 'expire', key: warning.key }); |
| 130 | + } |
| 131 | + |
| 132 | + // Sort the key pair so the entry is identical regardless of scanner order |
| 133 | + for (const warning of scanResult.inconsistentNamingWarnings ?? []) { |
| 134 | + const pair = [warning.key1, warning.key2].sort().join('|'); |
| 135 | + entries.push({ rule: 'inconsistent-naming', key: pair }); |
| 136 | + } |
| 137 | + |
| 138 | + return sortEntries(entries); |
| 139 | +} |
| 140 | + |
| 141 | +/** |
| 142 | + * Returns a new ScanResult with every warning that is covered by a baseline |
| 143 | + * entry removed. The matching logic is the mirror image of |
| 144 | + * {@link collectBaselineEntries} so every entry written suppresses the |
| 145 | + * correct warning. |
| 146 | + * @param scanResult The full scan result to apply baseline filtering to |
| 147 | + * @param entries The list of baseline entries to apply |
| 148 | + * @returns A new ScanResult with baseline-covered warnings removed |
| 149 | + */ |
| 150 | +export function applyBaselineEntries( |
| 151 | + scanResult: ScanResult, |
| 152 | + entries: BaselineEntry[], |
| 153 | +): ScanResult { |
| 154 | + const has = (rule: string, key: string, file?: string): boolean => |
| 155 | + entries.some( |
| 156 | + (e) => |
| 157 | + e.rule === rule && e.key === key && (file == null || e.file === file), |
| 158 | + ); |
| 159 | + |
| 160 | + return { |
| 161 | + ...scanResult, |
| 162 | + missing: scanResult.missing.filter((k) => !has('missing', k)), |
| 163 | + unused: scanResult.unused.filter((k) => !has('unused', k)), |
| 164 | + logged: scanResult.logged.filter((u) => !has('logged', u.variable, u.file)), |
| 165 | + secrets: scanResult.secrets.filter( |
| 166 | + (s) => !has('secret', fingerprint(`${s.file}:${s.snippet}`)), |
| 167 | + ), |
| 168 | + duplicates: { |
| 169 | + ...(scanResult.duplicates.env != null && { |
| 170 | + env: scanResult.duplicates.env.filter( |
| 171 | + (d) => !has('duplicate-env', d.key), |
| 172 | + ), |
| 173 | + }), |
| 174 | + ...(scanResult.duplicates.example != null && { |
| 175 | + example: scanResult.duplicates.example.filter( |
| 176 | + (d) => !has('duplicate-example', d.key), |
| 177 | + ), |
| 178 | + }), |
| 179 | + }, |
| 180 | + ...(scanResult.exampleWarnings != null && { |
| 181 | + exampleWarnings: scanResult.exampleWarnings.filter( |
| 182 | + (w) => !has('example-secret', w.key), |
| 183 | + ), |
| 184 | + }), |
| 185 | + ...(scanResult.frameworkWarnings != null && { |
| 186 | + frameworkWarnings: scanResult.frameworkWarnings.filter( |
| 187 | + (w) => !has('framework', w.variable, w.file), |
| 188 | + ), |
| 189 | + }), |
| 190 | + ...(scanResult.uppercaseWarnings != null && { |
| 191 | + uppercaseWarnings: scanResult.uppercaseWarnings.filter( |
| 192 | + (w) => !has('uppercase', w.key), |
| 193 | + ), |
| 194 | + }), |
| 195 | + ...(scanResult.expireWarnings != null && { |
| 196 | + expireWarnings: scanResult.expireWarnings.filter( |
| 197 | + (w) => !has('expire', w.key), |
| 198 | + ), |
| 199 | + }), |
| 200 | + ...(scanResult.inconsistentNamingWarnings != null && { |
| 201 | + inconsistentNamingWarnings: scanResult.inconsistentNamingWarnings.filter( |
| 202 | + (w) => { |
| 203 | + const pair = [w.key1, w.key2].sort().join('|'); |
| 204 | + return !has('inconsistent-naming', pair); |
| 205 | + }, |
| 206 | + ), |
| 207 | + }), |
| 208 | + }; |
| 209 | +} |
| 210 | + |
| 211 | +/** |
| 212 | + * SHA-256 fingerprint truncated to 12 hex chars. Stable across runs; used for |
| 213 | + * secrets so no secret value is ever committed to the baseline file. |
| 214 | + * @param input The string to fingerprint (e.g. `file:snippet` for a secret) |
| 215 | + * @returns A 12-character hex string representing the fingerprint |
| 216 | + */ |
| 217 | +function fingerprint(input: string): string { |
| 218 | + return crypto.createHash('sha256').update(input).digest('hex').slice(0, 12); |
| 219 | +} |
| 220 | + |
| 221 | +function sortEntries(entries: BaselineEntry[]): BaselineEntry[] { |
| 222 | + return [...entries].sort((a, b) => { |
| 223 | + if (a.rule !== b.rule) return a.rule.localeCompare(b.rule); |
| 224 | + const fileA = a.file ?? ''; |
| 225 | + const fileB = b.file ?? ''; |
| 226 | + if (fileA !== fileB) return fileA.localeCompare(fileB); |
| 227 | + return a.key.localeCompare(b.key); |
| 228 | + }); |
| 229 | +} |
0 commit comments