import { createHash } from "node:crypto"; import { readFileSync, statSync, writeFileSync } from "node:fs"; import { basename, extname, join } from "node:path"; import { defineTool, FilePath, Type } from "@toolpal/tool"; import { escapeXml, unescapeXml, unzip, zip } from "./zip.js"; const MAX_BYTES = 25 * 1024 * 1024; const TEXT_EXTS = new Set([ ".txt", ".md", ".markdown", ".csv", ".tsv", ".json", ".jsonl", ".log", ".env", ".xml", ".html", ".htm", ".yaml", ".yml", ".ini", ".cfg", ".conf", ".sql", ]); const CATEGORIES = [ "private_key", "connection_string", "jwt", "api_key", "secret_assignment", "email", "credit_card", "iban", "ssn", "phone", "ip", ] as const; type Category = (typeof CATEGORIES)[number]; type FindingType = Category | "custom"; type Style = "placeholder" | "mask" | "hash"; interface MatchSpan { start: number; end: number; type: FindingType; value: string; } function luhnValid(raw: string): boolean { const digits = raw.replace(/\D/g, ""); if (digits.length < 13 || digits.length > 19) return false; if (/^(\d)\1+$/.test(digits)) return false; let sum = 0; let alt = false; for (let i = digits.length - 1; i >= 0; i--) { let n = digits.charCodeAt(i) - 48; if (alt) { n *= 2; if (n > 9) n -= 9; } sum += n; alt = !alt; } return sum % 10 === 0; } function ibanValid(raw: string): boolean { const clean = raw.replace(/\s+/g, "").toUpperCase(); if (clean.length < 15 || clean.length > 34) return false; if (!/^[A-Z]{2}\d{2}[A-Z0-9]{11,30}$/.test(clean)) return false; const rearranged = clean.slice(4) + clean.slice(0, 4); let rem = 0; for (const ch of rearranged) { const code = ch.charCodeAt(0); const expanded = code >= 65 && code <= 90 ? String(code - 55) : ch; for (const d of expanded) rem = (rem * 10 + (d.charCodeAt(0) - 48)) % 97; } return rem === 1; } function validIpv4(ip: string): boolean { const parts = ip.split("."); if (parts.length !== 4) return false; return parts.every((p) => { if (p.length > 1 && p.startsWith("0")) return false; const n = Number(p); return n >= 0 && n <= 255; }); } function validSsn(raw: string): boolean { const m = raw.match(/^(\d{3})[-\s](\d{2})[-\s](\d{4})$/); if (!m) return false; const area = Number(m[1]); const group = Number(m[2]); const serial = Number(m[3]); return area !== 0 && area !== 666 && area < 900 && group !== 0 && serial !== 0; } function validPhone(raw: string): boolean { const digits = raw.replace(/\D/g, ""); if (digits.length < 10 || digits.length > 15) return false; // Avoid YYYY-MM-DD or YYYY.MM.DD false positives if (/^\d{4}[-./]\d{2}[-./]\d{2}$/.test(raw.trim())) return false; return true; } interface Detector { type: Category; regex: () => RegExp; group?: number; validate?: (value: string, full: string, index: number, source: string) => boolean; } const DETECTORS: Detector[] = [ { type: "private_key", regex: () => /-----BEGIN [A-Z0-9 ]*PRIVATE KEY-----[\s\S]*?-----END [A-Z0-9 ]*PRIVATE KEY-----/g, }, { type: "connection_string", regex: () => /\b(?:postgres(?:ql)?|mysql|mariadb|mongodb(?:\+srv)?|redis|rediss|amqps?|smtps?):\/\/[^\s"'<>:@]+:[^\s"'<>@]+@[^\s"'<>]+/gi, }, { type: "jwt", regex: () => /\beyJ[A-Za-z0-9_-]{8,}\.eyJ[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{16,}\b/g, }, { type: "api_key", regex: () => new RegExp( [ "\\b(?:AKIA|ASIA|AIDA|AROA)[0-9A-Z]{16}\\b", "\\b(?:ghp|gho|ghu|ghs|ghr)_[A-Za-z0-9]{30,}\\b", "\\bgithub_pat_[A-Za-z0-9_]{30,}\\b", "\\bsk-(?:proj-|ant-|or-v1-|live-|test-)?[A-Za-z0-9_-]{20,}\\b", "\\b(?:pk|rk)_(?:live|test)_[A-Za-z0-9]{20,}\\b", "\\bxox[baprs]-[0-9A-Za-z-]{16,}\\b", "\\bAIza[0-9A-Za-z_-]{35}\\b", "\\bSG\\.[A-Za-z0-9_-]{16,}\\.[A-Za-z0-9_-]{16,}\\b", "\\b(?:re|npm)_[A-Za-z0-9]{24,}\\b", "\\bpypi-[A-Za-z0-9_-]{32,}\\b", "https://hooks\\.slack\\.com/services/T[A-Z0-9]+/B[A-Z0-9]+/[A-Za-z0-9]+", "https://(?:discord|discordapp)\\.com/api/webhooks/\\d+/[A-Za-z0-9_-]+", ].join("|"), "g", ), }, { type: "secret_assignment", regex: () => /\b(?:(?:api[_-]?key|api[_-]?secret|access[_-]?token|auth[_-]?token|secret[_-]?key|client[_-]?secret|private[_-]?key|password|passwd|webhook[_-]?secret|signing[_-]?key)\s*[:=]\s*["']?([A-Za-z0-9+/_.-]{12,})["']?|Bearer\s+([A-Za-z0-9+/_.-]{20,}))/gi, validate: (val) => !/^(?:true|false|null|undefined|example|changeme|your[_-])/i.test(val), }, { type: "email", regex: () => /\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,24}\b/g, }, { type: "iban", regex: () => /\b[A-Z]{2}\d{2}(?:[ ]?[A-Z0-9]{4}){3,7}(?:[ ]?[A-Z0-9]{1,4})?\b/g, validate: (v) => ibanValid(v), }, { type: "credit_card", regex: () => /(? luhnValid(v), }, { type: "ssn", regex: () => /(? validSsn(v), }, { type: "phone", regex: () => /(? validPhone(v), }, { type: "ip", regex: () => /(? { if (v.includes(":")) return true; if (idx > 0 && (src[idx - 1] === "v" || src[idx - 1] === "V")) return false; return validIpv4(v); }, }, ]; function escapeRegex(s: string): string { return s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); } function maskValue(value: string, type: FindingType): string { if (type === "private_key") return "-----BEGIN PRIVATE KEY----- [REDACTED] -----END PRIVATE KEY-----"; if (type === "email") { const [local, domain] = value.split("@"); const keep = local.length > 2 ? local.slice(0, 2) : local.slice(0, 1); return `${keep}***@${domain}`; } if (type === "credit_card" || type === "iban" || type === "ssn" || type === "phone") { const clean = value.replace(/\s+/g, ""); return clean.length > 4 ? `${"*".repeat(Math.min(clean.length - 4, 12))}${clean.slice(-4)}` : "****"; } if (type === "connection_string") { return value.replace(/:\/\/([^:]+):([^@]+)@/, "://$1:***@"); } if (value.length <= 6) return "*".repeat(value.length); return `${value.slice(0, 3)}***${value.slice(-2)}`; } function lineNumberAt(text: string, offset: number): number { let line = 1; for (let i = 0; i < offset; i++) { if (text.charCodeAt(i) === 10) line++; } return line; } class Redactor { private readonly counters = new Map(); private readonly valueToToken = new Map(); private readonly enabled: Set; private readonly allowlist: Set; private readonly customTerms: string[]; readonly findings: Array<{ type: FindingType; line: number; preview: string; replacement: string }> = []; readonly byType: Record = {}; constructor( private readonly style: Style, categories: Category[], customTerms: string[], allowlist: string[], ) { this.enabled = new Set(categories); this.allowlist = new Set(allowlist.map((s) => s.trim().toLowerCase()).filter(Boolean)); this.customTerms = customTerms.map((s) => s.trim()).filter((s) => s.length >= 2); } private tokenFor(type: FindingType, value: string): string { const key = `${type}\0${value}`; const existing = this.valueToToken.get(key); if (existing) return existing; let token: string; if (this.style === "mask") { token = maskValue(value, type); } else if (this.style === "hash") { const digest = createHash("sha256").update(value).digest("hex").slice(0, 8); token = `[${type.toUpperCase()}:${digest}]`; } else { const n = (this.counters.get(type) ?? 0) + 1; this.counters.set(type, n); token = `[${type.toUpperCase()}_${n}]`; } this.valueToToken.set(key, token); return token; } process(text: string, mode: "redact" | "scan"): string { const spans: MatchSpan[] = []; for (const det of DETECTORS) { if (!this.enabled.has(det.type)) continue; const re = det.regex(); for (const m of text.matchAll(re)) { if (m.index === undefined) continue; let value = m[0]; let start = m.index; if (det.type === "secret_assignment") { const captured = m[1] ?? m[2]; if (!captured) continue; const offsetInMatch = m[0].lastIndexOf(captured); start = m.index + offsetInMatch; value = captured; } if (this.allowlist.has(value.trim().toLowerCase())) continue; if (det.validate && !det.validate(value, m[0], start, text)) continue; spans.push({ start, end: start + value.length, type: det.type, value }); } } for (const term of this.customTerms) { const re = new RegExp(`(? a.start - b.start || b.end - a.end); const chosen: MatchSpan[] = []; let lastEnd = -1; for (const s of spans) { if (s.start < lastEnd) continue; chosen.push(s); lastEnd = s.end; } if (chosen.length === 0) return text; let out = ""; let cursor = 0; for (const s of chosen) { const replacement = this.tokenFor(s.type, s.value); this.byType[s.type] = (this.byType[s.type] ?? 0) + 1; if (this.findings.length < 200) { this.findings.push({ type: s.type, line: lineNumberAt(text, s.start), preview: maskValue(s.value, s.type), replacement, }); } if (mode === "redact") { out += text.slice(cursor, s.start) + replacement; cursor = s.end; } } if (mode === "redact") out += text.slice(cursor); return mode === "redact" ? out : text; } } function processDocx(buf: Buffer, redactor: Redactor, mode: "redact" | "scan"): Buffer { const entries = unzip(buf); const xmlBuf = entries.get("word/document.xml"); if (!xmlBuf) throw new Error("Not a valid .docx file (missing word/document.xml)."); const xml = xmlBuf.toString("utf8"); // Process paragraph by paragraph so tokens split across Word runs are still detected. const updated = xml.replace(/]*)?>[\s\S]*?<\/w:p>/g, (para) => { const runs = [...para.matchAll(/]*)?>([\s\S]*?)<\/w:t>/g)]; if (runs.length === 0) return para; const joined = runs.map((r) => unescapeXml(r[1] ?? "")).join(""); const redacted = redactor.process(joined, mode); if (mode === "scan" || redacted === joined) return para; let first = true; return para.replace(/]*)?>[\s\S]*?<\/w:t>/g, () => { if (first) { first = false; return `${escapeXml(redacted)}`; } return ''; }); }); if (mode === "scan") return buf; entries.set("word/document.xml", Buffer.from(updated, "utf8")); return zip([...entries.entries()].map(([name, data]) => ({ name, data }))); } export default defineTool({ description: "Scans and redacts personal information (emails, phone numbers, SSNs, Luhn-verified credit cards, IBANs, IP addresses) and credentials/secrets (API keys, JWTs, private keys, database URLs, Bearer tokens) locally from text or files (TXT, MD, CSV, JSON, LOG, ENV, DOCX). Runs 100% offline with zero network access and no API keys.", input: Type.Object({ text: Type.Optional( Type.String({ maxLength: 500_000, description: "Text to scan or redact inline" }), ), file: Type.Optional( FilePath({ description: "File to scan or redact (TXT, MD, CSV, JSON, LOG, ENV, YAML, DOCX)" }), ), mode: Type.Optional( Type.Union([Type.Literal("redact"), Type.Literal("scan")], { description: "redact (default) outputs sanitized text/file; scan only audits findings", }), ), style: Type.Optional( Type.Union([Type.Literal("placeholder"), Type.Literal("mask"), Type.Literal("hash")], { description: "How to replace matches: placeholder ([EMAIL_1], default), mask (j***@acme.com), or hash ([EMAIL:a1b2c3d4])", }), ), categories: Type.Optional( Type.Array(Type.Union(CATEGORIES.map((c) => Type.Literal(c))), { minItems: 1, uniqueItems: true, description: "Limit detection to specific categories; all categories enabled by default", }), ), customTerms: Type.Optional( Type.Array(Type.String({ minLength: 2, maxLength: 120 }), { maxItems: 100, description: "Extra names, companies or codenames to redact (case-insensitive)", }), ), allowlist: Type.Optional( Type.Array(Type.String({ minLength: 1, maxLength: 200 }), { maxItems: 100, description: "Exact values to leave untouched, e.g. support@company.com", }), ), }), output: Type.Object({ mode: Type.String(), findingsCount: Type.Integer(), byType: Type.Record(Type.String(), Type.Integer()), findings: Type.Array( Type.Object({ type: Type.String(), line: Type.Integer(), preview: Type.String({ description: "Masked preview — raw secret is never returned" }), replacement: Type.String(), }), ), text: Type.Optional(Type.String({ description: "Redacted text (for inline text input)" })), file: Type.Optional(FilePath({ description: "Redacted output file (for file input)" })), }), handler: async (input, ctx) => { if (input.text === undefined && !input.file) { throw new Error("Provide either text or file."); } const mode = input.mode ?? "redact"; const style = input.style ?? "placeholder"; const categories = (input.categories ?? [...CATEGORIES]) as Category[]; const redactor = new Redactor( style, categories, input.customTerms ?? [], input.allowlist ?? [], ); let outText: string | undefined; let outFile: string | undefined; if (input.file) { const { size } = statSync(input.file); if (size > MAX_BYTES) { throw new Error(`The file is ${(size / 1048576).toFixed(1)} MB; the limit is 25 MB.`); } const ext = extname(input.file).toLowerCase(); const stem = basename(input.file, ext); if (ext === ".docx") { const resultBuf = processDocx(readFileSync(input.file), redactor, mode); if (mode === "redact") { outFile = join(ctx.outputDir, `${stem}.redacted.docx`); writeFileSync(outFile, resultBuf); } } else if (TEXT_EXTS.has(ext) || ext === "") { const content = readFileSync(input.file, "utf8"); const redacted = redactor.process(content, mode); if (mode === "redact") { outFile = join(ctx.outputDir, `${stem}.redacted${ext || ".txt"}`); writeFileSync(outFile, redacted, "utf8"); } } else { throw new Error( `Unsupported file type "${ext}". Supported: DOCX or plain-text formats (TXT, MD, CSV, JSON, LOG, ENV, YAML, XML, HTML).`, ); } } if (input.text !== undefined) { const redacted = redactor.process(input.text, mode); if (mode === "redact") outText = redacted; } const total = Object.values(redactor.byType).reduce((a, b) => a + b, 0); ctx.log("info", `${mode === "redact" ? "Redacted" : "Found"} ${total} item(s)`, redactor.byType); return { mode, findingsCount: total, byType: redactor.byType, findings: redactor.findings, ...(outText !== undefined ? { text: outText } : {}), ...(outFile !== undefined ? { file: outFile } : {}), }; }, });