// secret-scanner core engine. // // Scans an arbitrary blob of code / text / unified diff for LEAKED SECRETS: // provider API keys (AWS, GitHub, OpenAI, Stripe, Google, Slack, ...), generic // tokens, private keys (RSA/EC/SSH/PGP), database connection strings, .env // dumps, JWTs, and high-entropy strings that look like credentials. // // The moat is a curated, per-provider catalogue of patterns + a Shannon-entropy // pass (to catch unknown secrets) + (in deep mode) a structural validity hint // for formats whose checksum/shape we can verify offline (no network calls — // we never exfiltrate the secret being scanned). export type Severity = "low" | "medium" | "high" | "critical"; export type Verdict = "CLEAN" | "REVIEW" | "LEAK"; export interface Finding { /** Stable rule id, e.g. "aws-access-key-id". */ rule: string; /** Human label, e.g. "AWS Access Key ID". */ title: string; /** Provider/category, e.g. "AWS", "GitHub", "Generic". */ provider: string; severity: Severity; /** 1-based line number in the input. */ line: number; /** Column (1-based) where the match starts. */ column: number; /** Masked excerpt of the secret (never the full value). */ match: string; /** Shannon entropy (bits/char) of the matched token, when relevant. */ entropy?: number; /** Deep-mode structural validity hint (format-level only, no network). */ validity?: "valid_format" | "invalid_format" | "unknown"; /** Short remediation note. */ remediation: string; } export interface ScanResult { verdict: Verdict; /** 0-100 risk score (max finding severity drives it). */ score: number; summary: string; /** Total lines scanned. */ lines: number; /** Findings, ordered by severity then line. */ findings: Finding[]; meta: { deep: boolean; bytes: number; truncated: boolean; rulesEvaluated: number; entropyFindings: number; }; } interface RuleDef { rule: string; title: string; provider: string; severity: Severity; regex: RegExp; /** Index of the capture group that holds the secret token (default whole match). */ group?: number; remediation: string; /** Optional offline structural validator for deep mode. */ validate?: (token: string) => "valid_format" | "invalid_format" | "unknown"; } const SEV_SCORE: Record = { low: 25, medium: 55, high: 80, critical: 100 }; // ---- Provider rule catalogue (the moat) --------------------------------- // Patterns are intentionally specific (low false-positive) and anchored on the // provider's documented key prefixes/shapes where possible. const RULES: RuleDef[] = [ // ---------- AWS ---------- { rule: "aws-access-key-id", title: "AWS Access Key ID", provider: "AWS", severity: "high", regex: /\b((?:AKIA|ASIA|AROA|AIDA|AGPA|ANPA|ANVA|A3T[A-Z0-9])[A-Z0-9]{16})\b/g, remediation: "Rotate the IAM key immediately in the AWS console and remove it from history.", validate: (t) => (/^(AKIA|ASIA|AROA|AIDA|AGPA|ANPA|ANVA|A3T)[A-Z0-9]{16}$/.test(t) ? "valid_format" : "invalid_format"), }, { rule: "aws-secret-access-key", title: "AWS Secret Access Key", provider: "AWS", severity: "critical", regex: /\b(?:aws_secret_access_key|aws_secret|AWS_SECRET_ACCESS_KEY)\b\s*[:=]\s*["']?([A-Za-z0-9/+=]{40})["']?/g, group: 1, remediation: "This is a full AWS secret. Rotate the key pair now; assume compromise.", }, // ---------- GitHub ---------- { rule: "github-pat", title: "GitHub Personal Access Token", provider: "GitHub", severity: "critical", regex: /\b(ghp_[A-Za-z0-9]{36})\b/g, remediation: "Revoke the token at github.com/settings/tokens and issue a new one.", }, { rule: "github-oauth", title: "GitHub OAuth Access Token", provider: "GitHub", severity: "critical", regex: /\b(gho_[A-Za-z0-9]{36})\b/g, remediation: "Revoke the OAuth token; rotate the OAuth app secret if shared.", }, { rule: "github-app", title: "GitHub App / Refresh / Server Token", provider: "GitHub", severity: "high", regex: /\b((?:ghu|ghs|ghr)_[A-Za-z0-9]{36})\b/g, remediation: "Revoke the GitHub App installation token / refresh token.", }, { rule: "github-fine-grained", title: "GitHub Fine-grained PAT", provider: "GitHub", severity: "critical", regex: /\b(github_pat_[A-Za-z0-9_]{82})\b/g, remediation: "Revoke the fine-grained PAT at github.com/settings/tokens.", }, // ---------- OpenAI ---------- { rule: "openai-key", title: "OpenAI API Key", provider: "OpenAI", severity: "critical", regex: /\b(sk-(?:proj-|svcacct-|admin-)?[A-Za-z0-9_-]{20,})\b/g, remediation: "Revoke the key at platform.openai.com/api-keys.", validate: (t) => (t.startsWith("sk-") && t.length >= 40 ? "valid_format" : "unknown"), }, // ---------- Anthropic ---------- { rule: "anthropic-key", title: "Anthropic API Key", provider: "Anthropic", severity: "critical", regex: /\b(sk-ant-[A-Za-z0-9_-]{30,})\b/g, remediation: "Revoke the key in the Anthropic Console and rotate.", }, // ---------- Stripe ---------- { rule: "stripe-secret", title: "Stripe Secret Key", provider: "Stripe", severity: "critical", regex: /\b((?:sk|rk)_live_[A-Za-z0-9]{24,})\b/g, remediation: "Roll the key in the Stripe dashboard immediately — live secret keys move money.", }, { rule: "stripe-test", title: "Stripe Test Secret Key", provider: "Stripe", severity: "medium", regex: /\b((?:sk|rk)_test_[A-Za-z0-9]{24,})\b/g, remediation: "Roll the test key; avoid committing even test keys.", }, // ---------- Google ---------- { rule: "google-api-key", title: "Google API Key", provider: "Google", severity: "high", regex: /\b(AIza[0-9A-Za-z_-]{35})\b/g, remediation: "Restrict/regenerate the key in Google Cloud Console > Credentials.", }, { rule: "gcp-oauth-secret", title: "Google OAuth Client Secret", provider: "Google", severity: "high", regex: /\b(GOCSPX-[A-Za-z0-9_-]{28})\b/g, remediation: "Reset the OAuth client secret in Google Cloud Console.", }, { rule: "gcp-service-account", title: "Google Service Account Private Key (JSON)", provider: "Google", severity: "critical", regex: /"private_key"\s*:\s*"-----BEGIN PRIVATE KEY-----/g, remediation: "Delete and regenerate the service-account key in IAM.", }, // ---------- Slack ---------- { rule: "slack-token", title: "Slack Token", provider: "Slack", severity: "high", regex: /\b(xox[baprs]-[0-9A-Za-z-]{10,})\b/g, remediation: "Revoke the token in the Slack app settings; rotate the app.", }, { rule: "slack-webhook", title: "Slack Incoming Webhook", provider: "Slack", severity: "medium", regex: /(https:\/\/hooks\.slack\.com\/services\/T[A-Za-z0-9_]+\/B[A-Za-z0-9_]+\/[A-Za-z0-9_]+)/g, remediation: "Disable the webhook URL in Slack; treat as public if leaked.", }, // ---------- Other common SaaS ---------- { rule: "twilio-key", title: "Twilio API Key / Account SID", provider: "Twilio", severity: "high", regex: /\b(SK[0-9a-fA-F]{32}|AC[0-9a-fA-F]{32})\b/g, remediation: "Rotate the Twilio key/auth token in the console.", }, { rule: "sendgrid-key", title: "SendGrid API Key", provider: "SendGrid", severity: "high", regex: /\b(SG\.[A-Za-z0-9_-]{22}\.[A-Za-z0-9_-]{43})\b/g, remediation: "Delete the API key in SendGrid settings and create a new one.", }, { rule: "mailgun-key", title: "Mailgun API Key", provider: "Mailgun", severity: "high", regex: /\b(key-[0-9a-zA-Z]{32})\b/g, remediation: "Rotate the Mailgun key in the dashboard.", }, { rule: "npm-token", title: "npm Access Token", provider: "npm", severity: "critical", regex: /\b(npm_[A-Za-z0-9]{36})\b/g, remediation: "Revoke the token at npmjs.com/settings//tokens.", }, { rule: "pypi-token", title: "PyPI Upload Token", provider: "PyPI", severity: "high", regex: /\b(pypi-AgEIcHlwaS5vcmc[A-Za-z0-9_-]{50,})\b/g, remediation: "Revoke the token at pypi.org/manage/account/token.", }, { rule: "telegram-bot", title: "Telegram Bot Token", provider: "Telegram", severity: "high", regex: /\b([0-9]{8,10}:AA[A-Za-z0-9_-]{33})\b/g, remediation: "Use /revoke with @BotFather to invalidate the token.", }, { rule: "discord-token", title: "Discord Bot Token", provider: "Discord", severity: "high", regex: /\b([MN][A-Za-z0-9_-]{23}\.[A-Za-z0-9_-]{6}\.[A-Za-z0-9_-]{27,})\b/g, remediation: "Reset the bot token in the Discord developer portal.", }, { rule: "shopify-token", title: "Shopify Access Token", provider: "Shopify", severity: "high", regex: /\b(shp(?:at|ca|pa|ss)_[a-fA-F0-9]{32})\b/g, remediation: "Rotate the Shopify access token / app credential.", }, { rule: "square-token", title: "Square Access Token", provider: "Square", severity: "high", regex: /\b((?:sq0atp|sq0csp|EAAA)[A-Za-z0-9_-]{22,})\b/g, remediation: "Rotate the Square access token in the developer dashboard.", }, { rule: "digitalocean-token", title: "DigitalOcean Personal Access Token", provider: "DigitalOcean", severity: "high", regex: /\b(dop_v1_[a-f0-9]{64})\b/g, remediation: "Regenerate the DO token in the API settings.", }, { rule: "doppler-token", title: "Doppler Service Token", provider: "Doppler", severity: "high", regex: /\b(dp\.(?:pt|st|ct|sa)\.[A-Za-z0-9]{40,})\b/g, remediation: "Revoke the Doppler token in the dashboard.", }, { rule: "hashicorp-vault", title: "HashiCorp Vault Token", provider: "Vault", severity: "high", regex: /\b(hvs\.[A-Za-z0-9_-]{24,})\b/g, remediation: "Revoke the Vault token (`vault token revoke`).", }, { rule: "cloudflare-token", title: "Cloudflare API Token", provider: "Cloudflare", severity: "high", regex: /\b(?:cloudflare|cf)[_-]?(?:api[_-]?)?token\b\s*[:=]\s*["']?([A-Za-z0-9_-]{40})["']?/gi, group: 1, remediation: "Roll the Cloudflare API token in the dashboard.", }, // ---------- Private keys ---------- { rule: "private-key-block", title: "Private Key Block (RSA/EC/DSA/OpenSSH/PGP)", provider: "PrivateKey", severity: "critical", regex: /-----BEGIN (?:RSA |EC |DSA |OPENSSH |PGP |ENCRYPTED )?PRIVATE KEY(?: BLOCK)?-----/g, remediation: "Treat the private key as compromised: rotate the key pair and revoke any cert it signed.", }, { rule: "ssh-private-key-marker", title: "SSH Private Key Marker", provider: "PrivateKey", severity: "critical", regex: /-----BEGIN OPENSSH PRIVATE KEY-----/g, remediation: "Replace the SSH key pair; remove the public key from authorized_keys everywhere.", }, // ---------- JWT ---------- { rule: "jwt", title: "JSON Web Token (JWT)", provider: "JWT", severity: "medium", regex: /\b(eyJ[A-Za-z0-9_-]{10,}\.eyJ[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,})\b/g, remediation: "If it carries credentials/long expiry, invalidate the session and rotate the signing secret.", }, // ---------- Connection strings ---------- { rule: "db-connection-string", title: "Database Connection String with Password", provider: "Database", severity: "high", regex: /\b((?:postgres(?:ql)?|mysql|mongodb(?:\+srv)?|redis|amqp|mssql|mariadb):\/\/[^\s:@/]+:[^\s:@/]+@[^\s/]+)/gi, remediation: "Rotate the DB password and move the URI to a secret manager.", }, { rule: "jdbc-password", title: "JDBC / URL Embedded Password", provider: "Database", severity: "high", regex: /[?&](?:password|pwd)=([^\s&"']{6,})/gi, group: 1, remediation: "Remove the inline password; rotate it.", }, // ---------- Generic assignment + Basic auth ---------- { rule: "basic-auth-url", title: "Basic-Auth Credentials in URL", provider: "Generic", severity: "medium", regex: /\bhttps?:\/\/[^\s:@/]+:([^\s:@/]{4,})@[^\s/]+/gi, group: 1, remediation: "Strip credentials from the URL; use a header or secret store.", }, { rule: "generic-secret-assignment", title: "Hardcoded Secret Assignment", provider: "Generic", severity: "low", regex: /\b(?:api[_-]?key|secret|token|passwd|password|access[_-]?token|auth[_-]?token|client[_-]?secret|private[_-]?key)\b\s*[:=]\s*["']([^"'\s]{8,})["']/gi, group: 1, remediation: "Move the value to an environment variable / secret manager and rotate it.", }, ]; // Common placeholder / example values that should NOT be flagged as generic // hardcoded secrets (reduce false positives). const PLACEHOLDER = /^(?:x{3,}|\*{3,}|\.{3,}|<[^>]+>|\$\{[^}]+\}|%[A-Z_]+%|your[_-]?|changeme|example|placeholder|dummy|test|todo|none|null|undefined|redacted|secret|password|token|api[_-]?key|xxxxxxxx)/i; // ---- Shannon entropy ---------------------------------------------------- export function shannonEntropy(s: string): number { if (!s.length) return 0; const freq: Record = {}; for (const ch of s) freq[ch] = (freq[ch] ?? 0) + 1; let H = 0; const n = s.length; for (const k in freq) { const p = freq[k] / n; H -= p * Math.log2(p); } return H; } // Candidate tokens for the entropy pass: long base64/hex-ish blobs. const ENTROPY_CANDIDATE = /[A-Za-z0-9+/=_-]{24,}/g; const HEX_ONLY = /^[a-fA-F0-9]+$/; function maskToken(t: string): string { if (t.length <= 8) return t[0] + "***"; return `${t.slice(0, 4)}…${t.slice(-4)} (${t.length} chars)`; } function looksLikeWord(t: string): boolean { // long natural-language-ish tokens (e.g. minified var names, base64 of text) // tend to have low entropy; we already gate on entropy, this is a 2nd filter. return /^[a-z]+$/.test(t) || /^[A-Z][a-z]+$/.test(t); } const MAX_BYTES = 256 * 1024; // 256 KB scan cap export interface ScanOpts { deep?: boolean; /** Minimum entropy (bits/char) for the entropy pass. Default 3.7 for b64, 3.0 hex. */ entropyThreshold?: number; } export function scan(input: string, opts: ScanOpts = {}): ScanResult { const deep = Boolean(opts.deep); const bytes = Buffer.byteLength(input, "utf8"); const truncated = bytes > MAX_BYTES; const text = truncated ? input.slice(0, MAX_BYTES) : input; const lines = text.split(/\r?\n/); const findings: Finding[] = []; const seen = new Set(); // dedupe identical (rule+token+line) // Build a line-offset index so a global regex match offset -> (line, col). const lineStart: number[] = []; { let off = 0; for (const ln of lines) { lineStart.push(off); off += ln.length + 1; // +1 for the newline } } function locate(absIndex: number): { line: number; column: number } { // binary search the line containing absIndex let lo = 0, hi = lineStart.length - 1, ans = 0; while (lo <= hi) { const mid = (lo + hi) >> 1; if (lineStart[mid] <= absIndex) { ans = mid; lo = mid + 1; } else hi = mid - 1; } return { line: ans + 1, column: absIndex - lineStart[ans] + 1 }; } // ---- Provider rules ---- for (const def of RULES) { def.regex.lastIndex = 0; let m: RegExpExecArray | null; while ((m = def.regex.exec(text)) !== null) { const g = def.group ?? 0; const token = m[g] ?? m[0]; if (m.index === def.regex.lastIndex) def.regex.lastIndex++; // avoid zero-width loop if (!token) continue; // Skip obvious placeholders for the low-severity generic rule. if (def.rule === "generic-secret-assignment" && PLACEHOLDER.test(token)) continue; const tokenAbs = m.index + (m[0].indexOf(token) >= 0 ? m[0].indexOf(token) : 0); const { line, column } = locate(tokenAbs); const key = `${def.rule}:${token}:${line}`; if (seen.has(key)) continue; seen.add(key); const f: Finding = { rule: def.rule, title: def.title, provider: def.provider, severity: def.severity, line, column, match: maskToken(token), remediation: def.remediation, }; if (deep && def.validate) f.validity = def.validate(token); findings.push(f); } } // ---- Entropy pass (catches unknown / custom secrets) ---- let entropyFindings = 0; const b64Threshold = opts.entropyThreshold ?? 3.7; const hexThreshold = 3.0; // Avoid double-flagging tokens already caught by a provider rule. const caught = new Set(findings.map((f) => f.match)); ENTROPY_CANDIDATE.lastIndex = 0; let em: RegExpExecArray | null; while ((em = ENTROPY_CANDIDATE.exec(text)) !== null) { const tok = em[0]; if (looksLikeWord(tok)) continue; const isHex = HEX_ONLY.test(tok); const H = shannonEntropy(tok); const thresh = isHex ? hexThreshold : b64Threshold; if (H < thresh) continue; // hex must be long enough to be a real secret (>= 32 hex = 128 bit) if (isHex && tok.length < 32) continue; const masked = maskToken(tok); if (caught.has(masked)) continue; const { line, column } = locate(em.index); const key = `entropy:${tok}:${line}`; if (seen.has(key)) continue; seen.add(key); entropyFindings++; findings.push({ rule: "high-entropy-string", title: "High-Entropy String (possible secret)", provider: "Generic", severity: "medium", line, column, match: masked, entropy: Math.round(H * 100) / 100, remediation: "Looks like a key/token by randomness. Confirm it is not a credential; if so, rotate and remove.", }); if (entropyFindings >= 200) break; // safety cap } // ---- Score + verdict ---- const sevRank: Record = { low: 1, medium: 2, high: 3, critical: 4 }; findings.sort((a, b) => sevRank[b.severity] - sevRank[a.severity] || a.line - b.line); let score = 0; for (const f of findings) score = Math.max(score, SEV_SCORE[f.severity]); let verdict: Verdict = "CLEAN"; const hasHard = findings.some((f) => f.severity === "high" || f.severity === "critical"); if (hasHard) verdict = "LEAK"; else if (findings.length > 0) verdict = "REVIEW"; const provCount: Record = {}; for (const f of findings) provCount[f.provider] = (provCount[f.provider] ?? 0) + 1; const summary = findings.length === 0 ? `No secrets detected across ${lines.length} line(s).` : `${findings.length} potential secret(s) across ${lines.length} line(s): ${Object.entries(provCount) .map(([p, c]) => `${p}×${c}`) .join(", ")}. Verdict ${verdict}.`; return { verdict, score, summary, lines: lines.length, findings, meta: { deep, bytes, truncated, rulesEvaluated: RULES.length, entropyFindings, }, }; }