leakshield 0.1.3 → 0.3.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.
- package/README.md +294 -173
- package/README.zh-TW.md +290 -164
- package/dist/config/loader.js +14 -10
- package/dist/config/plain-object.js +14 -0
- package/dist/decision/pseudonymization.js +133 -82
- package/dist/decision/redaction.js +2 -0
- package/dist/decision/value-search.js +250 -0
- package/dist/doctor.js +429 -138
- package/dist/i18n/en.js +4 -0
- package/dist/i18n/zh-TW.js +4 -0
- package/dist/index.js +3 -2
- package/dist/opencode-env-tools.js +0 -75
- package/dist/opencode-hooks.js +4 -73
- package/dist/opencode-transparent.js +582 -89
- package/dist/opencode.js +12 -54
- package/dist/plugin-options.js +15 -21
- package/dist/scanner/encoding.js +291 -7
- package/dist/scanner/engine.js +68 -40
- package/dist/scanner/utils.js +26 -2
- package/dist/transports/cli.js +2 -2
- package/dist/transports/web.js +3 -3
- package/dist/types.js +1 -0
- package/package.json +3 -3
package/dist/opencode.js
CHANGED
|
@@ -2,8 +2,7 @@ import { findConfigPath, loadConfigWithFingerprint } from "./config/loader.js";
|
|
|
2
2
|
import { createSessionKey } from "./decision/deidentify.js";
|
|
3
3
|
import { defaultStorePath } from "./decision/mapping-key.js";
|
|
4
4
|
import { EnvQueryService } from "./env-queries.js";
|
|
5
|
-
import { createFailClosedHooks
|
|
6
|
-
import { createV1EnvTools } from "./opencode-env-tools.js";
|
|
5
|
+
import { createFailClosedHooks } from "./opencode-hooks.js";
|
|
7
6
|
import { createFailClosedV2Setup, createV2Setup } from "./opencode-v2.js";
|
|
8
7
|
import { createFailClosedTransparentGuard, createTransparentSessionGuard } from "./opencode-transparent.js";
|
|
9
8
|
import { PluginOptionsSchema, withDefaultMode } from "./plugin-options.js";
|
|
@@ -34,27 +33,17 @@ function createEnvQueryService(options, workspaceRoot, loaded) {
|
|
|
34
33
|
configFingerprint: loaded.fingerprint,
|
|
35
34
|
});
|
|
36
35
|
}
|
|
37
|
-
function getWorkspaceRoot(input) {
|
|
38
|
-
if (typeof input !== "object" || input === null)
|
|
39
|
-
return process.cwd();
|
|
40
|
-
const context = input;
|
|
41
|
-
if (typeof context.worktree === "string")
|
|
42
|
-
return context.worktree;
|
|
43
|
-
if (typeof context.directory === "string")
|
|
44
|
-
return context.directory;
|
|
45
|
-
return process.cwd();
|
|
46
|
-
}
|
|
47
36
|
/** Whether the raw v2 plugin options select transparent mode, explicitly or
|
|
48
37
|
* by omitting `mode` (the v2 default), even if the options are invalid. */
|
|
49
38
|
function rawModeIsTransparent(options) {
|
|
50
|
-
const resolved = withDefaultMode(options
|
|
39
|
+
const resolved = withDefaultMode(options);
|
|
51
40
|
return (typeof resolved === "object" &&
|
|
52
41
|
resolved !== null &&
|
|
53
42
|
resolved.mode === "transparent");
|
|
54
43
|
}
|
|
55
44
|
const v2Setup = async (ctx) => {
|
|
56
45
|
try {
|
|
57
|
-
const options = PluginOptionsSchema.parse(withDefaultMode(ctx.options
|
|
46
|
+
const options = PluginOptionsSchema.parse(withDefaultMode(ctx.options));
|
|
58
47
|
const loaded = loadConfigWithFingerprint(options.configPath, ctx.location.directory);
|
|
59
48
|
const config = withEncodingDetection(loaded.config);
|
|
60
49
|
if (options.mode === "transparent") {
|
|
@@ -125,47 +114,16 @@ const v2Setup = async (ctx) => {
|
|
|
125
114
|
await createFailClosedV2Setup()(ctx);
|
|
126
115
|
}
|
|
127
116
|
};
|
|
128
|
-
const
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
throw new Error("deidentify is only supported on OpenCode v2");
|
|
136
|
-
}
|
|
137
|
-
if (options.mode === "transparent") {
|
|
138
|
-
// v1 has no native transport hooks to remask the final wire or restore
|
|
139
|
-
// responses, so transparent mode cannot honor its contract there. The
|
|
140
|
-
// throw lands in the catch below → fail-closed hooks.
|
|
141
|
-
throw new Error("transparent mode is only supported on OpenCode v2");
|
|
142
|
-
}
|
|
143
|
-
const workspaceRoot = getWorkspaceRoot(input);
|
|
144
|
-
const loaded = loadConfigWithFingerprint(options.configPath, workspaceRoot);
|
|
145
|
-
const config = withEncodingDetection(loaded.config);
|
|
146
|
-
const hooks = createHooks(config, options.mode);
|
|
147
|
-
const envQueries = createEnvQueryService(options, workspaceRoot, loaded);
|
|
148
|
-
if (!envQueries)
|
|
149
|
-
return hooks;
|
|
150
|
-
try {
|
|
151
|
-
return { ...hooks, tool: await createV1EnvTools(envQueries) };
|
|
152
|
-
}
|
|
153
|
-
catch {
|
|
154
|
-
// The opt-in env query tools failed to load on their own (e.g. a
|
|
155
|
-
// missing v1 SDK module on an incomplete install). Only the feature
|
|
156
|
-
// fails: the full protection hooks above stay exactly as armed as
|
|
157
|
-
// they would be with envQueries off — no fail-closed downgrade, no
|
|
158
|
-
// protection gap, no env tools.
|
|
159
|
-
return hooks;
|
|
160
|
-
}
|
|
161
|
-
}
|
|
162
|
-
catch {
|
|
163
|
-
return createFailClosedHooks();
|
|
164
|
-
}
|
|
165
|
-
};
|
|
117
|
+
const V1_UNSUPPORTED = "LeakShield no longer supports OpenCode v1, so the request was blocked before anything was sent. Upgrade to OpenCode v2.";
|
|
118
|
+
/**
|
|
119
|
+
* OpenCode v1 is not supported. This stub exists only so a v1 host that still
|
|
120
|
+
* loads the package aborts every model request instead of running unprotected.
|
|
121
|
+
* It must not throw: a host could swallow the error and carry on with no guard.
|
|
122
|
+
*/
|
|
123
|
+
const v1Server = async () => createFailClosedHooks(V1_UNSUPPORTED);
|
|
166
124
|
/**
|
|
167
|
-
*
|
|
168
|
-
*
|
|
125
|
+
* OpenCode plugin entry. OpenCode v2 reads `id` and `setup(ctx)`. `server` is
|
|
126
|
+
* the fail-closed stub for v1 hosts (1.18.29+), which call `server(input, options)`.
|
|
169
127
|
*/
|
|
170
128
|
const leakshieldPlugin = {
|
|
171
129
|
id: "leakshield",
|
package/dist/plugin-options.js
CHANGED
|
@@ -4,17 +4,18 @@
|
|
|
4
4
|
* host loaders) and the install doctor (src/doctor.ts).
|
|
5
5
|
*/
|
|
6
6
|
import { z } from "zod";
|
|
7
|
-
|
|
7
|
+
import { plainObject } from "./config/plain-object.js";
|
|
8
|
+
// deidentify is valid only in redact mode; an invalid combination
|
|
8
9
|
// makes the parse throw, and every entry path already fails closed on that.
|
|
9
|
-
// transparent is the
|
|
10
|
+
// transparent is the reversible pseudonymization mode (issue #22):
|
|
10
11
|
// it owns its own bounded session service and transport hooks, so combining
|
|
11
|
-
// it with the second (deidentify) protection pipeline or the
|
|
12
|
+
// it with the second (deidentify) protection pipeline or the env query
|
|
12
13
|
// tools is rejected here — every entry path fails closed on the parse error.
|
|
13
14
|
export const PluginOptionsSchema = z
|
|
14
15
|
.object({
|
|
15
|
-
// No schema default:
|
|
16
|
-
//
|
|
17
|
-
//
|
|
16
|
+
// No schema default: callers fill it in with withDefaultMode() before
|
|
17
|
+
// parsing. A caller that forgets fails the parse, and every entry path
|
|
18
|
+
// fails closed.
|
|
18
19
|
mode: z.enum(["block", "redact", "transparent"]),
|
|
19
20
|
configPath: z.string().min(1).optional(),
|
|
20
21
|
deidentify: z.boolean().default(false),
|
|
@@ -44,8 +45,7 @@ export const PluginOptionsSchema = z
|
|
|
44
45
|
* the ladder OS keychain → explicit keyfile → memory-only degrade;
|
|
45
46
|
* conversations are never blocked by a missing key.
|
|
46
47
|
*/
|
|
47
|
-
persistence: z
|
|
48
|
-
.object({
|
|
48
|
+
persistence: plainObject(z.object({
|
|
49
49
|
enabled: z.boolean().default(false),
|
|
50
50
|
/** Session TTL in days; 0 = never expire (manual forget only). */
|
|
51
51
|
ttlDays: z.number().int().min(0).max(3650).default(7),
|
|
@@ -55,8 +55,7 @@ export const PluginOptionsSchema = z
|
|
|
55
55
|
keyFile: z.boolean().default(false),
|
|
56
56
|
/** Overrides the default keyfile location. */
|
|
57
57
|
keyfilePath: z.string().min(1).optional(),
|
|
58
|
-
})
|
|
59
|
-
.default({}),
|
|
58
|
+
})).prefault({}),
|
|
60
59
|
})
|
|
61
60
|
.refine((options) => !options.deidentify || options.mode === "redact", {
|
|
62
61
|
message: "deidentify requires mode 'redact'",
|
|
@@ -73,24 +72,19 @@ export const PluginOptionsSchema = z
|
|
|
73
72
|
.refine((options) => !options.persistence.enabled || options.mode === "transparent", {
|
|
74
73
|
message: 'persistence requires mode "transparent"',
|
|
75
74
|
});
|
|
76
|
-
/**
|
|
77
|
-
* (transparent is v2-only). */
|
|
78
|
-
export function defaultMode(generation) {
|
|
79
|
-
return generation === "v2" ? "transparent" : "block";
|
|
80
|
-
}
|
|
81
|
-
/** Fills in the generation's default mode when the options omit it. Any
|
|
75
|
+
/** Fills in the default mode (transparent) when the options omit `mode`. Any
|
|
82
76
|
* other non-object input is returned unchanged so the schema rejects it. */
|
|
83
|
-
export function withDefaultMode(input
|
|
77
|
+
export function withDefaultMode(input) {
|
|
84
78
|
if (input === undefined || input === null)
|
|
85
|
-
return { mode:
|
|
79
|
+
return { mode: "transparent" };
|
|
86
80
|
if (typeof input !== "object" || Array.isArray(input))
|
|
87
81
|
return input;
|
|
88
82
|
if (input.mode !== undefined)
|
|
89
83
|
return input;
|
|
90
|
-
return { ...input, mode:
|
|
84
|
+
return { ...input, mode: "transparent" };
|
|
91
85
|
}
|
|
92
|
-
export function validatePluginOptions(input
|
|
93
|
-
const parsed = PluginOptionsSchema.safeParse(withDefaultMode(input
|
|
86
|
+
export function validatePluginOptions(input) {
|
|
87
|
+
const parsed = PluginOptionsSchema.safeParse(withDefaultMode(input));
|
|
94
88
|
if (parsed.success)
|
|
95
89
|
return { ok: true, options: parsed.data };
|
|
96
90
|
return {
|
package/dist/scanner/encoding.js
CHANGED
|
@@ -4,6 +4,9 @@
|
|
|
4
4
|
*/
|
|
5
5
|
import { ZERO_WIDTH_CHARS, scanTextInternal } from "./engine.js";
|
|
6
6
|
import { foldConfusables } from "./unicode.js";
|
|
7
|
+
import { getLineCol } from "./utils.js";
|
|
8
|
+
/** Decoded text that hints at a credential; raises the decoder's confidence. */
|
|
9
|
+
const SENSITIVE_HINT = /(?:api|key|secret|token|password|sk-|ghp_|gho_)/i;
|
|
7
10
|
// ─── Base64 Detection & Decoding ─────────────────────────────────────────────────
|
|
8
11
|
/**
|
|
9
12
|
* Detects potential Base64 encoded strings.
|
|
@@ -13,7 +16,7 @@ import { foldConfusables } from "./unicode.js";
|
|
|
13
16
|
* - Proper padding (0-2 '=' chars at end)
|
|
14
17
|
* - Even length when padded
|
|
15
18
|
*/
|
|
16
|
-
function
|
|
19
|
+
function detectBase64Matches(text) {
|
|
17
20
|
const candidates = [];
|
|
18
21
|
// Pattern for Base64 strings (16+ chars, lowered threshold for security)
|
|
19
22
|
const base64Pattern = /[A-Za-z0-9+/]{16,}={0,2}/g;
|
|
@@ -34,10 +37,13 @@ function detectBase64(text) {
|
|
|
34
37
|
// Low entropy suggests it's not Base64 (e.g., "AAAAAAAAAA...")
|
|
35
38
|
if (entropy < 0.3)
|
|
36
39
|
continue;
|
|
37
|
-
candidates.push(candidate);
|
|
40
|
+
candidates.push({ text: candidate, index: match.index });
|
|
38
41
|
}
|
|
39
42
|
return candidates;
|
|
40
43
|
}
|
|
44
|
+
function detectBase64(text) {
|
|
45
|
+
return detectBase64Matches(text).map((c) => c.text);
|
|
46
|
+
}
|
|
41
47
|
/**
|
|
42
48
|
* Attempts to decode a Base64 string and validate the result.
|
|
43
49
|
* Returns null if decoding fails or result doesn't look like text.
|
|
@@ -54,7 +60,7 @@ function tryDecodeBase64(encoded) {
|
|
|
54
60
|
if (!/[a-zA-Z]{2,}/.test(decoded))
|
|
55
61
|
return null;
|
|
56
62
|
// Check for common sensitive patterns in decoded text
|
|
57
|
-
const hasSensitivePattern =
|
|
63
|
+
const hasSensitivePattern = SENSITIVE_HINT.test(decoded);
|
|
58
64
|
return {
|
|
59
65
|
decoded,
|
|
60
66
|
encoding_type: 'Base64',
|
|
@@ -93,7 +99,7 @@ function tryDecodeUrl(encoded) {
|
|
|
93
99
|
const decoded = decodeURIComponent(encoded.replace(/\+/g, ' '));
|
|
94
100
|
if (decoded === encoded)
|
|
95
101
|
return null; // Nothing was decoded
|
|
96
|
-
const hasSensitivePattern =
|
|
102
|
+
const hasSensitivePattern = SENSITIVE_HINT.test(decoded);
|
|
97
103
|
return {
|
|
98
104
|
decoded,
|
|
99
105
|
encoding_type: 'URL',
|
|
@@ -108,16 +114,19 @@ function tryDecodeUrl(encoded) {
|
|
|
108
114
|
/**
|
|
109
115
|
* Detects potential hex-encoded strings.
|
|
110
116
|
*/
|
|
111
|
-
function
|
|
117
|
+
function detectHexMatches(text) {
|
|
112
118
|
const candidates = [];
|
|
113
119
|
// Look for sequences of hex pairs
|
|
114
120
|
const hexPattern = /(?:\\x[0-9a-fA-F]{2}|[0-9a-fA-F]{32,})/g;
|
|
115
121
|
const matches = text.matchAll(hexPattern);
|
|
116
122
|
for (const match of matches) {
|
|
117
|
-
candidates.push(match[0]);
|
|
123
|
+
candidates.push({ text: match[0], index: match.index });
|
|
118
124
|
}
|
|
119
125
|
return candidates;
|
|
120
126
|
}
|
|
127
|
+
function detectHexEncoding(text) {
|
|
128
|
+
return detectHexMatches(text).map((c) => c.text);
|
|
129
|
+
}
|
|
121
130
|
/**
|
|
122
131
|
* Attempts to decode hex-encoded text.
|
|
123
132
|
*/
|
|
@@ -136,7 +145,7 @@ function tryDecodeHex(encoded) {
|
|
|
136
145
|
}
|
|
137
146
|
if (decoded.length < 10)
|
|
138
147
|
return null;
|
|
139
|
-
const hasSensitivePattern =
|
|
148
|
+
const hasSensitivePattern = SENSITIVE_HINT.test(decoded);
|
|
140
149
|
return {
|
|
141
150
|
decoded,
|
|
142
151
|
encoding_type: 'Hex',
|
|
@@ -276,3 +285,278 @@ function mergeScanResults(results, config, encodingTypesFound) {
|
|
|
276
285
|
findings: deduplicated,
|
|
277
286
|
};
|
|
278
287
|
}
|
|
288
|
+
/**
|
|
289
|
+
* True when masking the runs located in `text` accounts for EVERY decoded
|
|
290
|
+
* finding in `decodedMatches` (the match_text values the whole-segment
|
|
291
|
+
* decoding scan reported). Three checks:
|
|
292
|
+
* - Normalization: any zero-width or look-alike character in `text` returns
|
|
293
|
+
* false, wherever it sits. The generic decoder also decodes the stripped and
|
|
294
|
+
* folded sources, whose runs the locator cannot map back, so partial
|
|
295
|
+
* masking of the raw source could erase the evidence that a hidden part
|
|
296
|
+
* remains.
|
|
297
|
+
* - Evasion: a located decoded form that reports a Unicode evasion returns
|
|
298
|
+
* false. The same character can be percent-encoded, which the normalization
|
|
299
|
+
* check cannot see, and the finding it hides has no source span.
|
|
300
|
+
* - Coverage: each decoded match must equal, or be a substring of, a decoded
|
|
301
|
+
* match of a located run or a direct match (substring because the generic
|
|
302
|
+
* decoder's +/-50 windows can clip a value the locator sees in full). Direct
|
|
303
|
+
* matches count because those windows also re-report plain findings near any
|
|
304
|
+
* percent run, and the direct findings are masked anyway.
|
|
305
|
+
*/
|
|
306
|
+
export function decodedFindingsAttributable(text, config, opts, decodedMatches, directMatches) {
|
|
307
|
+
if (foldConfusables(text.replace(ZERO_WIDTH_CHARS, "")) !== text)
|
|
308
|
+
return false;
|
|
309
|
+
const { runs, evasion } = locateEncoded(text, config, opts);
|
|
310
|
+
if (evasion)
|
|
311
|
+
return false;
|
|
312
|
+
const located = new Set(directMatches);
|
|
313
|
+
for (const run of runs) {
|
|
314
|
+
for (const match of run.decodedMatches)
|
|
315
|
+
located.add(match);
|
|
316
|
+
}
|
|
317
|
+
for (const wanted of new Set(decodedMatches)) {
|
|
318
|
+
if (located.has(wanted))
|
|
319
|
+
continue;
|
|
320
|
+
let covered = false;
|
|
321
|
+
for (const match of located) {
|
|
322
|
+
if (match.includes(wanted)) {
|
|
323
|
+
covered = true;
|
|
324
|
+
break;
|
|
325
|
+
}
|
|
326
|
+
}
|
|
327
|
+
if (!covered)
|
|
328
|
+
return false;
|
|
329
|
+
}
|
|
330
|
+
return true;
|
|
331
|
+
}
|
|
332
|
+
/** What makes two findings distinct: dropping one must never lose a severity. */
|
|
333
|
+
function findingIdentity(finding) {
|
|
334
|
+
return JSON.stringify([finding.type, finding.severity, finding.description, finding.match_text]);
|
|
335
|
+
}
|
|
336
|
+
/**
|
|
337
|
+
* Re-expresses the encoded findings of a decoding scan as spans of `text`.
|
|
338
|
+
* scanTextWithDecoding reports decoded findings at offsets of the DECODED
|
|
339
|
+
* string, which redaction would apply to the source. Here each located run
|
|
340
|
+
* contributes its decoded findings at the run's exact source span, so a
|
|
341
|
+
* placeholder replaces the whole run.
|
|
342
|
+
*
|
|
343
|
+
* When the decoded findings cannot all be attributed to located runs (a
|
|
344
|
+
* hidden run, a Unicode evasion, a finding without text), it fails closed:
|
|
345
|
+
* every encoded finding loses its offsets, so no redacted content or safe
|
|
346
|
+
* preview is built for the result. `encoding_detected` is kept either way,
|
|
347
|
+
* which the redaction verifier and deidentify rely on to stay fail-closed.
|
|
348
|
+
*/
|
|
349
|
+
export function anchorDecodedFindings(text, scan, config, opts) {
|
|
350
|
+
if (scan.decoded.length === 0)
|
|
351
|
+
return scan.findings;
|
|
352
|
+
const decodedFindings = scan.decoded.flatMap((r) => r.findings);
|
|
353
|
+
const decodedMatches = [];
|
|
354
|
+
let attributable = true;
|
|
355
|
+
for (const finding of decodedFindings) {
|
|
356
|
+
if (typeof finding.match_text !== "string" || finding.unicode_detected !== undefined) {
|
|
357
|
+
attributable = false;
|
|
358
|
+
break;
|
|
359
|
+
}
|
|
360
|
+
decodedMatches.push(finding.match_text);
|
|
361
|
+
}
|
|
362
|
+
if (attributable) {
|
|
363
|
+
const directMatches = scan.original.findings.flatMap((f) => (typeof f.match_text === "string" ? [f.match_text] : []));
|
|
364
|
+
attributable = decodedFindingsAttributable(text, config, opts, decodedMatches, directMatches);
|
|
365
|
+
}
|
|
366
|
+
if (!attributable) {
|
|
367
|
+
// Read scan.decoded, not the merged findings: the merge drops a decoded
|
|
368
|
+
// finding whose decoded offsets equal a direct finding's, and the direct
|
|
369
|
+
// finding alone would still produce a redaction that misses the run.
|
|
370
|
+
const seen = new Set();
|
|
371
|
+
const stripped = [];
|
|
372
|
+
for (const finding of decodedFindings) {
|
|
373
|
+
const key = findingIdentity(finding);
|
|
374
|
+
if (seen.has(key))
|
|
375
|
+
continue;
|
|
376
|
+
seen.add(key);
|
|
377
|
+
const { match_start: _start, match_end: _end, ...rest } = finding;
|
|
378
|
+
stripped.push(rest);
|
|
379
|
+
}
|
|
380
|
+
return [...scan.original.findings, ...stripped];
|
|
381
|
+
}
|
|
382
|
+
const anchored = [];
|
|
383
|
+
const seen = new Set();
|
|
384
|
+
// Every finding of a run shares the run's span, so the span alone cannot
|
|
385
|
+
// tell them apart: identity comes from the decoded match, taken before
|
|
386
|
+
// match_text is rewritten to the source slice.
|
|
387
|
+
const add = (finding, identity) => {
|
|
388
|
+
const key = `${finding.match_start}:${finding.match_end}:${identity}`;
|
|
389
|
+
if (seen.has(key))
|
|
390
|
+
return;
|
|
391
|
+
seen.add(key);
|
|
392
|
+
anchored.push(finding);
|
|
393
|
+
};
|
|
394
|
+
for (const finding of scan.original.findings)
|
|
395
|
+
add(finding, findingIdentity(finding));
|
|
396
|
+
for (const run of locateEncodedRuns(text, config, opts)) {
|
|
397
|
+
const { line, col } = getLineCol(text, run.start);
|
|
398
|
+
for (const finding of run.findings) {
|
|
399
|
+
add({
|
|
400
|
+
...finding,
|
|
401
|
+
line,
|
|
402
|
+
column: col,
|
|
403
|
+
match_start: run.start,
|
|
404
|
+
match_end: run.end,
|
|
405
|
+
match_text: text.slice(run.start, run.end),
|
|
406
|
+
}, findingIdentity(finding));
|
|
407
|
+
}
|
|
408
|
+
}
|
|
409
|
+
return anchored;
|
|
410
|
+
}
|
|
411
|
+
const SEVERITY_ORDER = { HIGH: 3, MEDIUM: 2, LOW: 1 };
|
|
412
|
+
function highestSeverity(findings) {
|
|
413
|
+
let best = "LOW";
|
|
414
|
+
for (const finding of findings) {
|
|
415
|
+
if (SEVERITY_ORDER[finding.severity] > SEVERITY_ORDER[best])
|
|
416
|
+
best = finding.severity;
|
|
417
|
+
}
|
|
418
|
+
return best;
|
|
419
|
+
}
|
|
420
|
+
const PERCENT_RUNS = /(?:%[0-9A-Fa-f]{2})+/g;
|
|
421
|
+
/**
|
|
422
|
+
* Locates the encoded runs of `text` whose decoded form holds a finding, as
|
|
423
|
+
* exact spans of `text` itself. This is the ONLY place decoded offsets are
|
|
424
|
+
* mapped back to the source, and it works on `text` alone: the zero-width
|
|
425
|
+
* stripped and confusable-folded sources that scanTextWithDecoding also
|
|
426
|
+
* decodes have offsets that do not map back, so runs hidden that way are not
|
|
427
|
+
* located (the caller's strict rescan keeps refusing them).
|
|
428
|
+
*
|
|
429
|
+
* - Base64 and hex: the span is the whole candidate match, decoded with the
|
|
430
|
+
* same functions and confidence thresholds as scanTextWithDecoding.
|
|
431
|
+
* - URL: the generic decoder's +/-50 window is NOT used, because a clipped
|
|
432
|
+
* window would mask part of a value and leak the rest. The text is split
|
|
433
|
+
* into percent runs and literal pieces and decoded into one string with a
|
|
434
|
+
* decoded-unit to source-range map: literal units map one to one, every
|
|
435
|
+
* unit of a decoded run maps to the WHOLE run. A finding becomes a span
|
|
436
|
+
* only if it covers a decoded-run unit or a "+" turned into a space (the
|
|
437
|
+
* direct scan already handles the rest) and its offsets are exact.
|
|
438
|
+
*/
|
|
439
|
+
export function locateEncodedRuns(text, config, opts) {
|
|
440
|
+
return locateEncoded(text, config, opts).runs;
|
|
441
|
+
}
|
|
442
|
+
function hasUnicodeEvasion(findings) {
|
|
443
|
+
return findings.some((f) => f.unicode_detected !== undefined);
|
|
444
|
+
}
|
|
445
|
+
function locateEncoded(text, config, opts) {
|
|
446
|
+
const runs = [];
|
|
447
|
+
let evasion = false;
|
|
448
|
+
const locate = (candidates, decode, minConfidence) => {
|
|
449
|
+
for (const candidate of candidates) {
|
|
450
|
+
const decoded = decode(candidate.text);
|
|
451
|
+
if (!decoded || decoded.confidence < minConfidence)
|
|
452
|
+
continue;
|
|
453
|
+
const result = scanTextInternal(decoded.decoded, config, opts);
|
|
454
|
+
if (!result.safe) {
|
|
455
|
+
if (hasUnicodeEvasion(result.findings))
|
|
456
|
+
evasion = true;
|
|
457
|
+
const type = decoded.encoding_type;
|
|
458
|
+
const encoding_detected = type === "Base64"
|
|
459
|
+
? { type, confidence: decoded.confidence, encoded_length: candidate.text.length, decoded_length: decoded.decoded.length }
|
|
460
|
+
: { type, confidence: decoded.confidence };
|
|
461
|
+
runs.push({
|
|
462
|
+
start: candidate.index,
|
|
463
|
+
end: candidate.index + candidate.text.length,
|
|
464
|
+
severity: highestSeverity(result.findings),
|
|
465
|
+
decodedMatches: result.findings.flatMap((f) => (typeof f.match_text === "string" ? [f.match_text] : [])),
|
|
466
|
+
findings: result.findings.map((f) => ({ ...f, encoding_detected: { ...encoding_detected } })),
|
|
467
|
+
});
|
|
468
|
+
}
|
|
469
|
+
}
|
|
470
|
+
};
|
|
471
|
+
locate(detectBase64Matches(text), tryDecodeBase64, 0.6);
|
|
472
|
+
locate(detectHexMatches(text), tryDecodeHex, 0.5);
|
|
473
|
+
const locateUrl = (plusAsSpace) => {
|
|
474
|
+
const url = locateUrlRuns(text, config, plusAsSpace, opts);
|
|
475
|
+
runs.push(...url.runs);
|
|
476
|
+
if (url.evasion)
|
|
477
|
+
evasion = true;
|
|
478
|
+
};
|
|
479
|
+
locateUrl(true);
|
|
480
|
+
// "+" is ambiguous: as a space it splits "a+b%40example.com" and would leave
|
|
481
|
+
// "a+" unmasked, so also locate with "+" kept literal. Callers merge overlaps.
|
|
482
|
+
if (text.includes("+"))
|
|
483
|
+
locateUrl(false);
|
|
484
|
+
return { runs, evasion };
|
|
485
|
+
}
|
|
486
|
+
function locateUrlRuns(text, config, plusAsSpace, opts) {
|
|
487
|
+
const pieces = [];
|
|
488
|
+
// Per decoded UTF-16 unit: the source range it maps to, and whether it came
|
|
489
|
+
// from a decoded run or a "+" (only those can hide a finding from the scan).
|
|
490
|
+
const unitStart = [];
|
|
491
|
+
const unitEnd = [];
|
|
492
|
+
const unitHot = [];
|
|
493
|
+
let anyHot = false;
|
|
494
|
+
const addLiteral = (from, to) => {
|
|
495
|
+
for (let i = from; i < to; i += 1) {
|
|
496
|
+
const plus = plusAsSpace && text[i] === "+";
|
|
497
|
+
pieces.push(plus ? " " : text[i]);
|
|
498
|
+
unitStart.push(i);
|
|
499
|
+
unitEnd.push(i + 1);
|
|
500
|
+
unitHot.push(plus);
|
|
501
|
+
if (plus)
|
|
502
|
+
anyHot = true;
|
|
503
|
+
}
|
|
504
|
+
};
|
|
505
|
+
let cursor = 0;
|
|
506
|
+
for (const match of text.matchAll(PERCENT_RUNS)) {
|
|
507
|
+
const start = match.index;
|
|
508
|
+
const end = start + match[0].length;
|
|
509
|
+
addLiteral(cursor, start);
|
|
510
|
+
cursor = end;
|
|
511
|
+
let decoded;
|
|
512
|
+
try {
|
|
513
|
+
decoded = decodeURIComponent(match[0]);
|
|
514
|
+
}
|
|
515
|
+
catch (error) {
|
|
516
|
+
if (!(error instanceof URIError))
|
|
517
|
+
throw error;
|
|
518
|
+
addLiteral(start, end); // malformed run stays literal
|
|
519
|
+
continue;
|
|
520
|
+
}
|
|
521
|
+
pieces.push(decoded);
|
|
522
|
+
for (let i = 0; i < decoded.length; i += 1) {
|
|
523
|
+
unitStart.push(start);
|
|
524
|
+
unitEnd.push(end);
|
|
525
|
+
unitHot.push(true);
|
|
526
|
+
}
|
|
527
|
+
anyHot = true;
|
|
528
|
+
}
|
|
529
|
+
addLiteral(cursor, text.length);
|
|
530
|
+
if (!anyHot)
|
|
531
|
+
return { runs: [], evasion: false };
|
|
532
|
+
const decodedText = pieces.join("");
|
|
533
|
+
const result = scanTextInternal(decodedText, config, opts);
|
|
534
|
+
if (result.safe || result.was_truncated)
|
|
535
|
+
return { runs: [], evasion: false };
|
|
536
|
+
const runs = [];
|
|
537
|
+
for (const finding of result.findings) {
|
|
538
|
+
const start = finding.match_start;
|
|
539
|
+
const end = finding.match_end;
|
|
540
|
+
const matched = finding.match_text;
|
|
541
|
+
if (typeof start !== "number" || typeof end !== "number" || typeof matched !== "string" ||
|
|
542
|
+
!Number.isInteger(start) || !Number.isInteger(end) ||
|
|
543
|
+
start < 0 || start >= end || end > decodedText.length ||
|
|
544
|
+
decodedText.slice(start, end) !== matched) {
|
|
545
|
+
continue; // synthetic or clipped finding: not attributable
|
|
546
|
+
}
|
|
547
|
+
let hot = false;
|
|
548
|
+
for (let i = start; i < end && !hot; i += 1)
|
|
549
|
+
hot = unitHot[i];
|
|
550
|
+
if (!hot)
|
|
551
|
+
continue;
|
|
552
|
+
const encoding_detected = { type: "URL", confidence: SENSITIVE_HINT.test(decodedText) ? 0.85 : 0.5 };
|
|
553
|
+
runs.push({
|
|
554
|
+
start: unitStart[start],
|
|
555
|
+
end: unitEnd[end - 1],
|
|
556
|
+
severity: finding.severity,
|
|
557
|
+
decodedMatches: [matched],
|
|
558
|
+
findings: [{ ...finding, encoding_detected }],
|
|
559
|
+
});
|
|
560
|
+
}
|
|
561
|
+
return { runs, evasion: hasUnicodeEvasion(result.findings) };
|
|
562
|
+
}
|