| 1 | #!/usr/bin/env node |
| 2 | // Path sweep for the level 2 vendor bundle: no file that leaves this machine |
| 3 | // may carry a path of the machine that built it. |
| 4 | // |
| 5 | // node sweep.mjs sweep web/vendor/x2/<buildId>/ named by the manifest |
| 6 | // node sweep.mjs <dir> sweep every file in <dir> (.gz files are inflated first) |
| 7 | // node sweep.mjs --list [<dir>] print every hit with its context, to review an allowlist change |
| 8 | // |
| 9 | // Always fatal, wherever they appear: the user name, the home folder and the |
| 10 | // absolute build folder. Generic patterns (home prefixes of macOS, Linux and |
| 11 | // Windows, file:// and sourceMappingURL) are fatal unless the exact hit is in |
| 12 | // sweep-allowlist.json, which stores the sha256 of each hit's context (the |
| 13 | // literal around it) and how many times it appears: a new hit or a changed |
| 14 | // count fails the sweep. Base64 |
| 15 | // data: URLs are decoded and their printable strings swept too, the way |
| 16 | // `strings` would see them. |
| 17 | // |
| 18 | // The patterns are assembled at run time, so this file (like every committed |
| 19 | // file) contains none of them literally. |
| 20 | import fs from 'node:fs'; |
| 21 | import os from 'node:os'; |
| 22 | import path from 'node:path'; |
| 23 | import zlib from 'node:zlib'; |
| 24 | import crypto from 'node:crypto'; |
| 25 | import { fileURLToPath } from 'node:url'; |
| 26 | |
| 27 | const HERE = path.dirname(fileURLToPath(import.meta.url)); |
| 28 | const S = '/'; |
| 29 | const B = '\\'; |
| 30 | |
| 31 | export function patterns() { |
| 32 | return [ |
| 33 | { id: 'mac-home', re: new RegExp(S + 'Users' + S, 'g') }, |
| 34 | { id: 'linux-home', re: new RegExp(S + 'home' + S, 'g') }, |
| 35 | { id: 'windows-home', re: new RegExp('[A-Za-z]:' + B + B + '+Users' + B + B, 'g') }, |
| 36 | { id: 'file-url', re: new RegExp('file:' + S + S, 'g') }, |
| 37 | { id: 'source-map', re: new RegExp('source' + 'MappingURL', 'g') }, |
| 38 | ]; |
| 39 | } |
| 40 | |
| 41 | function fatalNeedles(buildRoot) { |
| 42 | const out = []; |
| 43 | const add = (label, v) => { if (typeof v === 'string' && v.length >= 3) out.push({ label, needle: v }); }; |
| 44 | let user = ''; |
| 45 | try { user = os.userInfo().username; } catch { /* no user database */ } |
| 46 | add('user name', user); |
| 47 | add('home folder', os.homedir()); |
| 48 | add('build folder', buildRoot && path.resolve(buildRoot)); |
| 49 | add('repository folder', buildRoot && path.resolve(buildRoot, '../..')); |
| 50 | return out; |
| 51 | } |
| 52 | |
| 53 | // printable runs of 4+ bytes, as `strings` prints them |
| 54 | function printable(bytes) { |
| 55 | let s = '', run = ''; |
| 56 | for (const b of bytes) { |
| 57 | if (b >= 0x20 && b < 0x7f) run += String.fromCharCode(b); |
| 58 | else { if (run.length >= 4) s += run + '\n'; run = ''; } |
| 59 | } |
| 60 | if (run.length >= 4) s += run + '\n'; |
| 61 | return s; |
| 62 | } |
| 63 | |
| 64 | // The text views of one file: itself, plus the printable strings of every |
| 65 | // base64 data: URL inside it. |
| 66 | function views(name, bytes) { |
| 67 | const text = Buffer.from(bytes).toString('latin1'); |
| 68 | const out = [{ where: name, text }]; |
| 69 | const re = /data:[\w.+-]+\/[\w.+-]+(?:;[\w.+-]+=[\w.+-]+)*;base64,([A-Za-z0-9+/=]+)/g; |
| 70 | let m, k = 0; |
| 71 | while ((m = re.exec(text))) { |
| 72 | const decoded = Buffer.from(m[1], 'base64'); |
| 73 | out.push({ where: `${name}#data${k++}`, text: printable(decoded) }); |
| 74 | } |
| 75 | return out; |
| 76 | } |
| 77 | |
| 78 | // The context of a hit: up to 40 characters either side, cut at the nearest |
| 79 | // quote, backtick or line break, so it is the literal the hit lives in and |
| 80 | // does not change when the minifier renames the code around it. |
| 81 | const CONTEXT = 40; |
| 82 | const STOP = new Set(['"', "'", '`', '\n']); |
| 83 | function contextOf(text, i, len) { |
| 84 | let a = i, b = i + len; |
| 85 | while (a > 0 && i - a < CONTEXT && !STOP.has(text[a - 1])) a--; |
| 86 | while (b < text.length && b - (i + len) < CONTEXT && !STOP.has(text[b])) b++; |
| 87 | return text.slice(a, b); |
| 88 | } |
| 89 | const contextHash = (where, id, text, i, len) => |
| 90 | crypto.createHash('sha256').update(`${where}\0${id}\0${contextOf(text, i, len)}`).digest('hex'); |
| 91 | |
| 92 | export function collectHits(files) { |
| 93 | const hits = new Map(); // key → { file, pattern, context, count, sample } |
| 94 | for (const { name, bytes } of files) { |
| 95 | for (const v of views(name, bytes)) { |
| 96 | for (const { id, re } of patterns()) { |
| 97 | re.lastIndex = 0; |
| 98 | let m; |
| 99 | while ((m = re.exec(v.text))) { |
| 100 | const context = contextHash(v.where.replace(/#data\d+$/, '#data'), id, v.text, m.index, m[0].length); |
| 101 | const key = `${name}|${id}|${context}`; |
| 102 | const h = hits.get(key) || { file: name, pattern: id, context, count: 0, sample: contextOf(v.text, m.index, m[0].length) }; |
| 103 | h.count++; |
| 104 | hits.set(key, h); |
| 105 | } |
| 106 | } |
| 107 | } |
| 108 | } |
| 109 | return [...hits.values()]; |
| 110 | } |
| 111 | |
| 112 | export function sweepBuffers(files, allowlist, { buildRoot = HERE } = {}) { |
| 113 | const problems = []; |
| 114 | for (const { name, bytes } of files) { |
| 115 | for (const v of views(name, bytes)) { |
| 116 | for (const { label, needle } of fatalNeedles(buildRoot)) { |
| 117 | if (v.text.includes(needle)) problems.push(`${v.where}: contains the ${label}`); |
| 118 | } |
| 119 | } |
| 120 | } |
| 121 | const allowed = new Map((allowlist?.hits || []).map(h => [`${h.file}|${h.pattern}|${h.context}`, h])); |
| 122 | const seen = new Set(); |
| 123 | const hits = collectHits(files); |
| 124 | for (const h of hits) { |
| 125 | const key = `${h.file}|${h.pattern}|${h.context}`; |
| 126 | const a = allowed.get(key); |
| 127 | seen.add(key); |
| 128 | if (!a) problems.push(`${h.file}: new ${h.pattern} hit (${h.count}×), not in sweep-allowlist.json`); |
| 129 | else if (a.count !== h.count) problems.push(`${h.file}: ${h.pattern} hit "${a.why}" appears ${h.count}×, the allowlist says ${a.count}×`); |
| 130 | } |
| 131 | const names = new Set(files.map(f => f.name)); |
| 132 | for (const [key, a] of allowed) { |
| 133 | if (!seen.has(key) && names.has(a.file)) problems.push(`${a.file}: allowed ${a.pattern} hit "${a.why}" is gone; update sweep-allowlist.json`); |
| 134 | } |
| 135 | return { ok: problems.length === 0, problems, hits }; |
| 136 | } |
| 137 | |
| 138 | // files of a folder; .gz inflated and named without the suffix |
| 139 | export function readDir(dir) { |
| 140 | return fs.readdirSync(dir).sort().filter(n => fs.statSync(path.join(dir, n)).isFile()).map(n => { |
| 141 | const bytes = fs.readFileSync(path.join(dir, n)); |
| 142 | return n.endsWith('.gz') ? { name: n.slice(0, -3), bytes: zlib.gunzipSync(bytes) } : { name: n, bytes }; |
| 143 | }); |
| 144 | } |
| 145 | |
| 146 | function defaultDir() { |
| 147 | const manifest = JSON.parse(fs.readFileSync(path.join(HERE, '../../web/js/ext2/vendor-manifest.json'), 'utf8')); |
| 148 | return path.join(HERE, '../../web/vendor/x2', manifest.buildId); |
| 149 | } |
| 150 | |
| 151 | if (process.argv[1] && path.resolve(process.argv[1]) === fileURLToPath(import.meta.url)) { |
| 152 | const args = process.argv.slice(2); |
| 153 | const list = args.includes('--list'); |
| 154 | const dir = args.find(a => !a.startsWith('--')) || defaultDir(); |
| 155 | const files = readDir(dir); |
| 156 | const allow = JSON.parse(fs.readFileSync(path.join(HERE, 'sweep-allowlist.json'), 'utf8')); |
| 157 | const report = sweepBuffers(files, allow, { buildRoot: HERE }); |
| 158 | if (list) for (const h of report.hits) console.log(JSON.stringify({ file: h.file, pattern: h.pattern, context: h.context, count: h.count }), '\n ', JSON.stringify(h.sample)); |
| 159 | console.log(`swept ${files.length} files in ${path.basename(dir)}: ${report.hits.length} distinct generic hits, ${report.problems.length} problems`); |
| 160 | for (const p of report.problems) console.log(' ✗ ' + p); |
| 161 | process.exit(report.ok ? 0 : 1); |
| 162 | } |