leakshield 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (47) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +546 -2
  3. package/README.zh-TW.md +565 -0
  4. package/dist/cli.js +61 -0
  5. package/dist/config/loader.js +94 -0
  6. package/dist/decision/deidentify.js +195 -0
  7. package/dist/decision/ingress.js +136 -0
  8. package/dist/decision/mapping-key.js +318 -0
  9. package/dist/decision/mapping-store.js +555 -0
  10. package/dist/decision/model.js +76 -0
  11. package/dist/decision/pseudonymization.js +1230 -0
  12. package/dist/decision/redaction.js +185 -0
  13. package/dist/decision/schema-strings.js +42 -0
  14. package/dist/doctor.js +438 -0
  15. package/dist/env-queries.js +584 -0
  16. package/dist/forget.js +56 -0
  17. package/dist/help.js +37 -0
  18. package/dist/i18n/en.js +71 -0
  19. package/dist/i18n/index.js +28 -0
  20. package/dist/i18n/zh-TW.js +71 -0
  21. package/dist/index.js +12 -0
  22. package/dist/opencode-env-tools.js +243 -0
  23. package/dist/opencode-hooks.js +84 -0
  24. package/dist/opencode-transparent-aisdk.js +100 -0
  25. package/dist/opencode-transparent-http.js +2315 -0
  26. package/dist/opencode-transparent-stream.js +192 -0
  27. package/dist/opencode-transparent-ws.js +298 -0
  28. package/dist/opencode-transparent.js +1492 -0
  29. package/dist/opencode-v2.js +216 -0
  30. package/dist/opencode.js +175 -0
  31. package/dist/plugin-options.js +100 -0
  32. package/dist/rules/builtin.js +283 -0
  33. package/dist/rules/dynamic.js +68 -0
  34. package/dist/scanner/encoding.js +274 -0
  35. package/dist/scanner/engine.js +321 -0
  36. package/dist/scanner/exact-values.js +99 -0
  37. package/dist/scanner/redaction-verifier.js +82 -0
  38. package/dist/scanner/unicode.js +157 -0
  39. package/dist/scanner/utils.js +60 -0
  40. package/dist/transports/cli.js +447 -0
  41. package/dist/transports/web-ui.js +540 -0
  42. package/dist/transports/web.js +200 -0
  43. package/dist/types.js +23 -0
  44. package/dist/utils/files.js +36 -0
  45. package/dist/utils/path-security.js +30 -0
  46. package/dist/utils/win-encoding.js +45 -0
  47. package/package.json +71 -4
@@ -0,0 +1,283 @@
1
+ /** Luhn checksum(ISO/IEC 7812-1);信用卡號形狀相符後必須通過才命中。 */
2
+ function luhnValid(raw) {
3
+ const digits = raw.replace(/[^0-9]/g, "");
4
+ if (digits.length < 13 || digits.length > 19)
5
+ return false;
6
+ let sum = 0;
7
+ let double = false;
8
+ for (let i = digits.length - 1; i >= 0; i--) {
9
+ let d = digits.charCodeAt(i) - 48;
10
+ if (double) {
11
+ d *= 2;
12
+ if (d > 9)
13
+ d -= 9;
14
+ }
15
+ sum += d;
16
+ double = !double;
17
+ }
18
+ return sum % 10 === 0;
19
+ }
20
+ /** IBAN mod-97(ISO 13616):前四碼移到尾端、字母轉數字後取模必須為 1。 */
21
+ function ibanValid(raw) {
22
+ const s = raw.replace(/\s+/g, "").toUpperCase();
23
+ if (s.length < 15 || s.length > 34)
24
+ return false;
25
+ if (!/^[A-Z]{2}[0-9]{2}[A-Z0-9]{11,30}$/.test(s))
26
+ return false;
27
+ const rearranged = s.slice(4) + s.slice(0, 4);
28
+ let remainder = 0;
29
+ for (const ch of rearranged) {
30
+ const code = ch.charCodeAt(0);
31
+ const v = code >= 48 && code <= 57 ? code - 48 : code - 55; // 0-9 或 A=10…Z=35
32
+ remainder = (remainder * (v < 10 ? 10 : 100) + v) % 97;
33
+ }
34
+ return remainder === 1;
35
+ }
36
+ /** 僅公共可路由 IPv4 視為敏感;私有/回環/鏈路本地/CGNAT/保留段不命中(config 常見值)。 */
37
+ function publicIPv4(raw) {
38
+ const octets = raw.split(".").map(Number);
39
+ if (octets.length !== 4 || octets.some((n) => !Number.isInteger(n) || n < 0 || n > 255))
40
+ return false;
41
+ const [a, b] = octets;
42
+ if (a === 0 || a === 10 || a === 127)
43
+ return false;
44
+ if (a === 169 && b === 254)
45
+ return false; // link-local
46
+ if (a === 172 && b >= 16 && b <= 31)
47
+ return false; // private
48
+ if (a === 192 && b === 168)
49
+ return false; // private
50
+ if (a === 100 && b >= 64 && b <= 127)
51
+ return false; // CGNAT
52
+ if (a >= 224)
53
+ return false; // multicast / reserved
54
+ return true;
55
+ }
56
+ export const BUILTIN_RULES = [
57
+ // ── API Keys / Secrets / Tokens ──────────────────────────────────────────
58
+ {
59
+ id: "openai-key",
60
+ type: "API_KEY",
61
+ severity: "HIGH",
62
+ description: "OpenAI API Key",
63
+ // 涵蓋舊格式 sk-xxx 與新格式 sk-proj-xxx / sk-svcacct-xxx(上限放寬至 120)
64
+ pattern: /sk-[A-Za-z0-9\-_]{20,120}/g,
65
+ },
66
+ {
67
+ id: "anthropic-key",
68
+ type: "API_KEY",
69
+ severity: "HIGH",
70
+ description: "Anthropic API Key",
71
+ pattern: /sk-ant-[A-Za-z0-9\-_]{20,80}/g,
72
+ },
73
+ {
74
+ id: "google-key",
75
+ type: "API_KEY",
76
+ severity: "HIGH",
77
+ description: "Google API Key",
78
+ pattern: /AIza[0-9A-Za-z\-_]{35}/g,
79
+ },
80
+ {
81
+ id: "aws-access-key",
82
+ type: "API_KEY",
83
+ severity: "HIGH",
84
+ description: "AWS Access Key ID",
85
+ // AWS key 固定以 AKIA / ASIA / ABIA / ACCA 開頭,後接 16 個大寫英數字
86
+ // 加上 word boundary 避免命中嵌入較長字串中的片段(如 base64)
87
+ pattern: /\b(?:AKIA|ASIA|ABIA|ACCA)[0-9A-Z]{16}\b/g,
88
+ },
89
+ {
90
+ id: "aws-secret",
91
+ type: "SECRET",
92
+ severity: "HIGH",
93
+ description: "AWS Secret Access Key",
94
+ // 改進規則:要求明確的 AWS secret 關鍵字前綴
95
+ // 匹配格式:aws_secret_access_key, aws_secret_key, secretAccessKey, etc.
96
+ // 避免誤報 Git commit hash 或一般 Base64 字串
97
+ pattern: /(?:aws_secret_access_key|aws_secret_key|aws.?secret|secretAccessKey|aws.?access)\s*[:=]\s*['"]?([A-Za-z0-9\/+]{40})['"]?/gi,
98
+ },
99
+ {
100
+ id: "github-pat",
101
+ type: "TOKEN",
102
+ severity: "HIGH",
103
+ description: "GitHub Personal Access Token",
104
+ pattern: /ghp_[A-Za-z0-9]{36}/g,
105
+ },
106
+ {
107
+ id: "github-fine-grained-pat",
108
+ type: "TOKEN",
109
+ severity: "HIGH",
110
+ description: "GitHub Fine-Grained Personal Access Token",
111
+ // 2022 年起新格式
112
+ pattern: /github_pat_[A-Za-z0-9_]{82}/g,
113
+ },
114
+ {
115
+ id: "github-oauth-app",
116
+ type: "TOKEN",
117
+ severity: "HIGH",
118
+ description: "GitHub OAuth / App Token",
119
+ pattern: /gho_[A-Za-z0-9]{36}|ghs_[A-Za-z0-9]{36}/g,
120
+ },
121
+ {
122
+ id: "generic-bearer",
123
+ type: "TOKEN",
124
+ severity: "HIGH",
125
+ description: "Generic Bearer Token(長度 ≥ 32 的字串)",
126
+ pattern: /bearer\s+[A-Za-z0-9\-_\.]{32,}/gi,
127
+ },
128
+ {
129
+ id: "generic-secret",
130
+ type: "SECRET",
131
+ severity: "HIGH",
132
+ description: "Generic Secret / Password 賦值",
133
+ // 同時涵蓋有引號(YAML/JSON)與無引號(.env)寫法
134
+ // (?!\$\{) 排除環境變數參照 ${VAR};(?!\*) 排除遮罩值 ********
135
+ pattern: /(?:password|passwd|secret|private_key|client_secret)\s*[:=]\s*(?:['"](?!\$\{)[^'"]{8,}['"]|(?!['"\$\*])\S{8,})/gi,
136
+ },
137
+ {
138
+ id: "jwt",
139
+ type: "TOKEN",
140
+ severity: "HIGH",
141
+ description: "JWT Token",
142
+ // 移除最後一段 character class 中的 . 以減少誤匹配
143
+ pattern: /eyJ[A-Za-z0-9\-_]+\.eyJ[A-Za-z0-9\-_]+\.[A-Za-z0-9\-_+/=]+/g,
144
+ },
145
+ {
146
+ id: "stripe-live-secret",
147
+ type: "API_KEY",
148
+ severity: "HIGH",
149
+ description: "Stripe Live Secret Key",
150
+ pattern: /sk_live_[A-Za-z0-9]{24,}/g,
151
+ },
152
+ {
153
+ id: "stripe-live-publishable",
154
+ type: "API_KEY",
155
+ severity: "HIGH",
156
+ description: "Stripe Live Publishable Key",
157
+ pattern: /pk_live_[A-Za-z0-9]{24,}/g,
158
+ },
159
+ {
160
+ id: "slack-bot",
161
+ type: "TOKEN",
162
+ severity: "HIGH",
163
+ description: "Slack Bot Token",
164
+ pattern: /xoxb-[0-9A-Za-z\-]{40,}/g,
165
+ },
166
+ {
167
+ id: "slack-user-app",
168
+ type: "TOKEN",
169
+ severity: "HIGH",
170
+ description: "Slack User / App Token",
171
+ pattern: /xoxp-[0-9A-Za-z\-]{40,}|xoxa-[0-9A-Za-z\-]{40,}/g,
172
+ },
173
+ {
174
+ id: "huggingface-token",
175
+ type: "API_KEY",
176
+ severity: "HIGH",
177
+ description: "Hugging Face API Token",
178
+ pattern: /hf_[A-Za-z0-9]{34,}/g,
179
+ },
180
+ {
181
+ id: "pem-private-key",
182
+ type: "SECRET",
183
+ severity: "HIGH",
184
+ description: "PEM Private Key",
185
+ // Full PEM block first (header + body + END) so the base64 body cannot
186
+ // survive a redaction/pseudonymization that only renamed the header; a
187
+ // truncated block (no END line) falls back to the header-only match.
188
+ pattern: /-----BEGIN (?:RSA |EC |DSA |OPENSSH )?PRIVATE KEY-----[\s\S]*?-----END (?:RSA |EC |DSA |OPENSSH )?PRIVATE KEY-----|-----BEGIN (?:RSA |EC |DSA |OPENSSH )?PRIVATE KEY-----/g,
189
+ },
190
+ // ── PII ──────────────────────────────────────────────────────────────────
191
+ {
192
+ id: "email",
193
+ type: "PII_EMAIL",
194
+ severity: "MEDIUM",
195
+ description: "Email 地址",
196
+ pattern: /[a-zA-Z0-9._%+\-]+@[a-zA-Z0-9.\-]+\.[a-zA-Z]{2,}/g,
197
+ },
198
+ {
199
+ id: "phone-tw",
200
+ type: "PII_PHONE_TW",
201
+ severity: "MEDIUM",
202
+ description: "台灣手機號碼",
203
+ // Opt-in(P2, 2026-10-06 owner 拍板;2026-10-07 實作):數字段對 SGP1
204
+ // token 類字串的誤報是量測到的主要 FP 源(0.294%)。要開啟:
205
+ // settings.rule_overrides["phone-tw"]: true。漏真電話風險見 README。
206
+ optIn: true,
207
+ pattern: /(?:(?:\+886)|0)9\d{2}[-\s]?\d{3}[-\s]?\d{3}/g,
208
+ },
209
+ {
210
+ id: "phone-intl",
211
+ type: "PII_PHONE_INTL",
212
+ severity: "LOW",
213
+ description: "國際電話號碼",
214
+ // Opt-in,同 phone-tw(P2)。要開啟:settings.rule_overrides["phone-intl"]: true
215
+ optIn: true,
216
+ pattern: /\+[1-9]\d{6,14}\b/g,
217
+ },
218
+ {
219
+ id: "id-tw",
220
+ type: "PII_ID_TW",
221
+ severity: "HIGH",
222
+ description: "台灣身份證字號",
223
+ // 加上 word boundary 避免擷取較長字串的片段
224
+ pattern: /\b[A-Z][12]\d{8}\b/g,
225
+ },
226
+ // ── 資料庫連線字串 ────────────────────────────────────────────────────────
227
+ {
228
+ id: "db-connection",
229
+ type: "DB_CONNECTION",
230
+ severity: "HIGH",
231
+ description: "資料庫連線字串(含密碼)",
232
+ pattern: /(?:mongodb(?:\+srv)?|postgresql|postgres|mysql|redis|mssql):\/\/[^:\s]+:[^@\s]+@[^\s"']+/gi,
233
+ },
234
+ {
235
+ id: "db-connection-ado",
236
+ type: "DB_CONNECTION",
237
+ severity: "HIGH",
238
+ description: "DB Connection String(ADO 格式)",
239
+ // (?:[^;]+;)* 允許 Server 與 Password 之間存在任意數量的中間欄位
240
+ pattern: /(?:Data Source|Server|Host)\s*=\s*[^;]+;(?:[^;]+;)*\s*(?:Password|Pwd)\s*=\s*[^;]+/gi,
241
+ },
242
+ // ── 金融/網路 PII(regex 框形狀,validate 再驗校驗碼/可路由性)────────
243
+ {
244
+ id: "credit-card",
245
+ type: "PII_CREDIT_CARD",
246
+ severity: "HIGH",
247
+ description: "信用卡號(Luhn 驗證)",
248
+ // 13–19 位數字,允許空格或連字號分隔;Luhn 不過由 validate 排除
249
+ pattern: /\b(?:[0-9][ -]?){12,18}[0-9]\b/g,
250
+ validate: luhnValid,
251
+ },
252
+ {
253
+ id: "iban",
254
+ type: "PII_IBAN",
255
+ severity: "HIGH",
256
+ description: "IBAN 國際銀行帳號(mod-97 驗證)",
257
+ // 緊湊或四字一空格兩種形狀(檢查碼後可有一空格);mod-97 不過由 validate 排除
258
+ pattern: /\b[A-Z]{2}[0-9]{2} ?(?:[A-Z0-9]{11,30}|(?:[A-Z0-9]{4} ){2,7}[A-Z0-9]{1,4})\b/g,
259
+ validate: ibanValid,
260
+ },
261
+ {
262
+ id: "public-ipv4",
263
+ type: "PII_IP",
264
+ severity: "MEDIUM",
265
+ description: "公共 IPv4 位址",
266
+ // 私有/回環/CGNAT/保留段由 validate 排除,避免 config 常數誤報
267
+ pattern: /\b(?:[0-9]{1,3}\.){3}[0-9]{1,3}\b/g,
268
+ validate: publicIPv4,
269
+ },
270
+ {
271
+ id: "url",
272
+ type: "PII_URL",
273
+ severity: "LOW",
274
+ description: "HTTP(S) URL",
275
+ // Opt-in:always-on 會把 wire 請求的 endpoint 當 PII 導致 fail-closed 拒絕
276
+ // (tests/opencode-transparent.test.ts 曾回歸)。要開啟:settings.rule_overrides.url: true
277
+ // 結尾不吃句讀(.,;:!?),避免把句子標點吞進遮罩範圍
278
+ optIn: true,
279
+ pattern: /\bhttps?:\/\/[^\s<>"'`\\)\]]*[^\s<>"'`\\)\][.,;:!?]/g,
280
+ },
281
+ ];
282
+ /** 所有 builtin 規則的 stable id(供 config rule_overrides 驗證;tests 保證每條規則都有 id)。 */
283
+ export const BUILTIN_RULE_IDS = new Set(BUILTIN_RULES.map((rule) => rule.id).filter((id) => id !== undefined));
@@ -0,0 +1,68 @@
1
+ // ReDoS protection: test the compiled regex against a fixed input with a
2
+ // synchronous timeout. Node.js is single-threaded so we approximate a timeout
3
+ // by measuring wall-clock time after exec() returns. Patterns that complete
4
+ // under REDOS_TIMEOUT_MS are accepted; those that hang are caught by the
5
+ // outer try/catch if they throw, or rejected if they exceed the limit.
6
+ const REDOS_TIMEOUT_MS = 200;
7
+ const REDOS_TEST_INPUT = "a".repeat(50) + "!";
8
+ function isSafePattern(pattern) {
9
+ let compiled;
10
+ try {
11
+ compiled = new RegExp(pattern, "gi");
12
+ }
13
+ catch {
14
+ return false; // invalid regex syntax
15
+ }
16
+ const start = Date.now();
17
+ try {
18
+ compiled.exec(REDOS_TEST_INPUT);
19
+ }
20
+ catch {
21
+ return false;
22
+ }
23
+ return Date.now() - start < REDOS_TIMEOUT_MS;
24
+ }
25
+ export function buildDynamicRules(config) {
26
+ const rules = [];
27
+ // Word boundaries make keyword rules match the standalone WORD, not words
28
+ // that merely contain it ("Foundation" must not trip「NDA」, "confidentiality"
29
+ // must not trip「CONFIDENTIAL」). Boundaries are added only where the
30
+ // keyword's edge is an ASCII word character: `\b` never holds between two
31
+ // non-word characters, so CJK keywords (「機密」inside Chinese text) would
32
+ // silently stop matching if we wrapped them unconditionally.
33
+ const keywordPattern = (keyword) => {
34
+ const escaped = keyword.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
35
+ const lead = /^[A-Za-z0-9_]/.test(keyword) ? "\\b" : "";
36
+ const trail = /[A-Za-z0-9_]$/.test(keyword) ? "\\b" : "";
37
+ return new RegExp(lead + escaped + trail, "gi");
38
+ };
39
+ for (const kw of config.nda_keywords) {
40
+ rules.push({
41
+ type: "NDA_KEYWORD",
42
+ severity: "HIGH",
43
+ description: `NDA 關鍵字「${kw}」`,
44
+ pattern: keywordPattern(kw),
45
+ });
46
+ }
47
+ for (const domain of config.private_domains) {
48
+ rules.push({
49
+ type: "PRIVATE_DOMAIN",
50
+ severity: "MEDIUM",
51
+ description: `私有域名「${domain}」`,
52
+ pattern: new RegExp(domain.replace(/\./g, "\\."), "gi"),
53
+ });
54
+ }
55
+ for (const rule of config.custom_rules) {
56
+ if (!isSafePattern(rule.pattern)) {
57
+ console.warn(`[leakshield] custom_rules: 略過不安全或無效的 pattern —「${rule.description}」`);
58
+ continue;
59
+ }
60
+ rules.push({
61
+ type: "CUSTOM",
62
+ severity: rule.severity,
63
+ description: rule.description,
64
+ pattern: new RegExp(rule.pattern, "gi"),
65
+ });
66
+ }
67
+ return rules;
68
+ }
@@ -0,0 +1,274 @@
1
+ /**
2
+ * Encoding detection and decoding utilities
3
+ * Prevents attackers from bypassing detection using Base64, URL encoding, etc.
4
+ */
5
+ import { ZERO_WIDTH_CHARS, scanTextInternal } from "./engine.js";
6
+ // ─── Base64 Detection & Decoding ─────────────────────────────────────────────────
7
+ /**
8
+ * Detects potential Base64 encoded strings.
9
+ * Looks for:
10
+ * - Length >= 32 characters
11
+ * - Only contains Base64 alphabet (A-Za-z0-9+/=)
12
+ * - Proper padding (0-2 '=' chars at end)
13
+ * - Even length when padded
14
+ */
15
+ function detectBase64(text) {
16
+ const candidates = [];
17
+ // Pattern for Base64 strings (16+ chars, lowered threshold for security)
18
+ const base64Pattern = /[A-Za-z0-9+/]{16,}={0,2}/g;
19
+ const matches = text.matchAll(base64Pattern);
20
+ for (const match of matches) {
21
+ const candidate = match[0];
22
+ // Skip if it's clearly not Base64
23
+ if (candidate.length % 4 !== 0 && !candidate.endsWith('=')) {
24
+ continue;
25
+ }
26
+ // Check padding validity
27
+ const padCount = (candidate.match(/=/g) || []).length;
28
+ if (padCount > 2)
29
+ continue;
30
+ // Check if it's likely Base64 (has reasonable entropy)
31
+ const uniqueChars = new Set(candidate).size;
32
+ const entropy = uniqueChars / candidate.length;
33
+ // Low entropy suggests it's not Base64 (e.g., "AAAAAAAAAA...")
34
+ if (entropy < 0.3)
35
+ continue;
36
+ candidates.push(candidate);
37
+ }
38
+ return candidates;
39
+ }
40
+ /**
41
+ * Attempts to decode a Base64 string and validate the result.
42
+ * Returns null if decoding fails or result doesn't look like text.
43
+ */
44
+ function tryDecodeBase64(encoded) {
45
+ try {
46
+ // Add padding if missing
47
+ const padded = encoded.padEnd(Math.ceil(encoded.length / 4) * 4, '=');
48
+ const decoded = Buffer.from(padded, 'base64').toString('utf-8');
49
+ // Validate the decoded result
50
+ if (decoded.length < 10)
51
+ return null; // Too short
52
+ // Check if it looks like text (contains letters)
53
+ if (!/[a-zA-Z]{2,}/.test(decoded))
54
+ return null;
55
+ // Check for common sensitive patterns in decoded text
56
+ const hasSensitivePattern = /(?:api|key|secret|token|password|sk-|ghp_|gho_)/i.test(decoded);
57
+ return {
58
+ decoded,
59
+ encoding_type: 'Base64',
60
+ confidence: hasSensitivePattern ? 0.9 : 0.6,
61
+ };
62
+ }
63
+ catch {
64
+ return null;
65
+ }
66
+ }
67
+ // ─── URL Encoding Detection & Decoding ───────────────────────────────────────────
68
+ /**
69
+ * Detects potential URL-encoded strings.
70
+ * Looks for percent-encoded characters like %20, %2F, etc.
71
+ */
72
+ function detectUrlEncoding(text) {
73
+ const candidates = [];
74
+ // Look for strings with percent-encoded characters (lowered threshold)
75
+ const urlEncodedPattern = /(?:%[0-9A-Fa-f]{2}){1,}/g;
76
+ const matches = text.matchAll(urlEncodedPattern);
77
+ for (const match of matches) {
78
+ const candidate = match[0];
79
+ // Extract a larger context (up to 200 chars around the encoded part)
80
+ const start = Math.max(0, match.index - 50);
81
+ const end = Math.min(text.length, match.index + candidate.length + 50);
82
+ const context = text.slice(start, end);
83
+ candidates.push(context);
84
+ }
85
+ return candidates;
86
+ }
87
+ /**
88
+ * Attempts to decode URL-encoded text.
89
+ */
90
+ function tryDecodeUrl(encoded) {
91
+ try {
92
+ const decoded = decodeURIComponent(encoded.replace(/\+/g, ' '));
93
+ if (decoded === encoded)
94
+ return null; // Nothing was decoded
95
+ const hasSensitivePattern = /(?:api|key|secret|token|password|sk-|ghp_|gho_)/i.test(decoded);
96
+ return {
97
+ decoded,
98
+ encoding_type: 'URL',
99
+ confidence: hasSensitivePattern ? 0.85 : 0.5,
100
+ };
101
+ }
102
+ catch {
103
+ return null;
104
+ }
105
+ }
106
+ // ─── Hex Encoding Detection ──────────────────────────────────────────────────────
107
+ /**
108
+ * Detects potential hex-encoded strings.
109
+ */
110
+ function detectHexEncoding(text) {
111
+ const candidates = [];
112
+ // Look for sequences of hex pairs
113
+ const hexPattern = /(?:\\x[0-9a-fA-F]{2}|[0-9a-fA-F]{32,})/g;
114
+ const matches = text.matchAll(hexPattern);
115
+ for (const match of matches) {
116
+ candidates.push(match[0]);
117
+ }
118
+ return candidates;
119
+ }
120
+ /**
121
+ * Attempts to decode hex-encoded text.
122
+ */
123
+ function tryDecodeHex(encoded) {
124
+ try {
125
+ let decoded = encoded;
126
+ // Handle \xHH format
127
+ if (decoded.includes('\\x')) {
128
+ decoded = decoded.replace(/\\x([0-9a-fA-F]{2})/g, (_, p1) => String.fromCharCode(parseInt(p1, 16)));
129
+ }
130
+ else {
131
+ // Handle raw hex format
132
+ if (decoded.length % 2 !== 0)
133
+ return null;
134
+ decoded = Buffer.from(decoded, 'hex').toString('utf-8');
135
+ }
136
+ if (decoded.length < 10)
137
+ return null;
138
+ const hasSensitivePattern = /(?:api|key|secret|token|password|sk-|ghp_|gho_)/i.test(decoded);
139
+ return {
140
+ decoded,
141
+ encoding_type: 'Hex',
142
+ confidence: hasSensitivePattern ? 0.8 : 0.5,
143
+ };
144
+ }
145
+ catch {
146
+ return null;
147
+ }
148
+ }
149
+ /**
150
+ * Scans text with automatic decoding of common encodings.
151
+ * This prevents attackers from bypassing detection using Base64, URL encoding, etc.
152
+ */
153
+ export function scanTextWithDecoding(text, config, opts) {
154
+ const results = [];
155
+ const encodingTypesFound = new Set();
156
+ // 1. Scan the original text
157
+ const originalResult = scanTextInternal(text, config, opts);
158
+ results.push(originalResult);
159
+ // A zero-width character inside an encoded run breaks candidate detection
160
+ // (a ZWSP in Base64 or hex), so decode the stripped form as well. Each
161
+ // candidate is decoded once even when both forms contain it.
162
+ const stripped = text.replace(ZERO_WIDTH_CHARS, "");
163
+ const sources = stripped === text ? [text] : [text, stripped];
164
+ const decodedCandidates = new Set();
165
+ const firstSighting = (kind, candidate) => {
166
+ const id = `${kind}\0${candidate}`;
167
+ if (decodedCandidates.has(id))
168
+ return false;
169
+ decodedCandidates.add(id);
170
+ return true;
171
+ };
172
+ for (const source of sources) {
173
+ // 2. Try Base64 decoding
174
+ const base64Candidates = detectBase64(source);
175
+ for (const candidate of base64Candidates) {
176
+ if (!firstSighting("base64", candidate))
177
+ continue;
178
+ const decoded = tryDecodeBase64(candidate);
179
+ if (decoded && decoded.confidence >= 0.6) {
180
+ const decodedResult = scanTextInternal(decoded.decoded, config, opts);
181
+ if (!decodedResult.safe) {
182
+ results.push(decodedResult);
183
+ encodingTypesFound.add('Base64');
184
+ // Add metadata about the encoding
185
+ decodedResult.findings.forEach(f => {
186
+ f.encoding_detected = {
187
+ type: 'Base64',
188
+ confidence: decoded.confidence,
189
+ encoded_length: candidate.length,
190
+ decoded_length: decoded.decoded.length,
191
+ };
192
+ });
193
+ }
194
+ }
195
+ }
196
+ // 3. Try URL decoding
197
+ const urlCandidates = detectUrlEncoding(source);
198
+ for (const candidate of urlCandidates) {
199
+ if (!firstSighting("url", candidate))
200
+ continue;
201
+ const decoded = tryDecodeUrl(candidate);
202
+ if (decoded && decoded.confidence >= 0.5) {
203
+ const decodedResult = scanTextInternal(decoded.decoded, config, opts);
204
+ if (!decodedResult.safe) {
205
+ results.push(decodedResult);
206
+ encodingTypesFound.add('URL');
207
+ decodedResult.findings.forEach(f => {
208
+ f.encoding_detected = {
209
+ type: 'URL',
210
+ confidence: decoded.confidence,
211
+ };
212
+ });
213
+ }
214
+ }
215
+ }
216
+ // 4. Try Hex decoding
217
+ const hexCandidates = detectHexEncoding(source);
218
+ for (const candidate of hexCandidates) {
219
+ if (!firstSighting("hex", candidate))
220
+ continue;
221
+ const decoded = tryDecodeHex(candidate);
222
+ if (decoded && decoded.confidence >= 0.5) {
223
+ const decodedResult = scanTextInternal(decoded.decoded, config, opts);
224
+ if (!decodedResult.safe) {
225
+ results.push(decodedResult);
226
+ encodingTypesFound.add('Hex');
227
+ decodedResult.findings.forEach(f => {
228
+ f.encoding_detected = {
229
+ type: 'Hex',
230
+ confidence: decoded.confidence,
231
+ };
232
+ });
233
+ }
234
+ }
235
+ }
236
+ }
237
+ // Merge results
238
+ const encodingTypesFoundArray = Array.from(encodingTypesFound);
239
+ const mergedResult = mergeScanResults(results, config, encodingTypesFoundArray);
240
+ return {
241
+ original: originalResult,
242
+ decoded: results.slice(1), // Exclude original
243
+ was_decoded: encodingTypesFound.size > 0,
244
+ encoding_types_found: Array.from(encodingTypesFound),
245
+ ...mergedResult,
246
+ };
247
+ }
248
+ /**
249
+ * Merges multiple scan results into a single result.
250
+ * Deduplicates findings by position and type.
251
+ */
252
+ function mergeScanResults(results, config, encodingTypesFound) {
253
+ const allFindings = results.flatMap(r => r.findings);
254
+ // Deduplicate by type and position
255
+ const seen = new Set();
256
+ const deduplicated = [];
257
+ for (const finding of allFindings) {
258
+ const key = `${finding.type}:${finding.match_start}:${finding.match_end}`;
259
+ if (!seen.has(key)) {
260
+ seen.add(key);
261
+ deduplicated.push(finding);
262
+ }
263
+ }
264
+ const safe = deduplicated.length === 0;
265
+ const highCount = deduplicated.filter(f => f.severity === "HIGH").length;
266
+ const medCount = deduplicated.filter(f => f.severity === "MEDIUM").length;
267
+ const lowCount = deduplicated.length - highCount - medCount;
268
+ const hasEncodedFindings = encodingTypesFound.length > 0;
269
+ return {
270
+ safe,
271
+ total_findings: deduplicated.length,
272
+ findings: deduplicated,
273
+ };
274
+ }