1const strLitRe = /'([^'\\]*(?:\\.[^'\\]*)*)'|"([^"\\]*(?:\\.[^"\\]*)*)"|`([^`\\]*(?:\\.[^`\\]*)*)`/g 2const b64Re = /^[A-Za-z0-9+/]+={0,2}$/ 3const hexRe = /^[0-9a-fA-F]+$/ 5const isMostlyPrintable = (str: string): boolean => { 6 if (str.length < 4) return false 8 for (const ch of str) { 9 const code = ch.charCodeAt(0) 10 if ((code >= 32 && code <= 126) || code === 10 || code === 13 || code === 9) printable++ 12 return printable / str.length >= 0.85 15// Extract base64/hex-encoded string literals from source, decode them, return concatenated decoded text. 16// Used to catch encoding workarounds for forbidden-string guards (e.g. Buffer.from('Y2FsbWlu...', 'base64')). 17// The returned text is meant to be fed to perFileGuardNeedle alongside the original contents. 18export const decodeStrLiterals = (contents: string): string => { 19 const decodedParts: string[] = [] 20 strLitRe.lastIndex = 0 22 while ((m = strLitRe.exec(contents)) !== null) { 23 const lit = m[1] ?? m[2] ?? m[3] 24 if (!lit || lit.length < 8) continue 25 for (const encoding of ['base64', 'hex'] as const) { 26 const valid = encoding === 'base64' ? b64Re.test(lit) : (hexRe.test(lit) && lit.length % 2 === 0) 29 const decoded = Buffer.from(lit, encoding).toString('utf-8') 30 if (isMostlyPrintable(decoded)) decodedParts.push(decoded) 31 } catch { /* skip undecodable */ } // catch:userapproved 34 return decodedParts.join('\n')