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.
- package/LICENSE +21 -0
- package/README.md +546 -2
- package/README.zh-TW.md +565 -0
- package/dist/cli.js +61 -0
- package/dist/config/loader.js +94 -0
- package/dist/decision/deidentify.js +195 -0
- package/dist/decision/ingress.js +136 -0
- package/dist/decision/mapping-key.js +318 -0
- package/dist/decision/mapping-store.js +555 -0
- package/dist/decision/model.js +76 -0
- package/dist/decision/pseudonymization.js +1230 -0
- package/dist/decision/redaction.js +185 -0
- package/dist/decision/schema-strings.js +42 -0
- package/dist/doctor.js +438 -0
- package/dist/env-queries.js +584 -0
- package/dist/forget.js +56 -0
- package/dist/help.js +37 -0
- package/dist/i18n/en.js +71 -0
- package/dist/i18n/index.js +28 -0
- package/dist/i18n/zh-TW.js +71 -0
- package/dist/index.js +12 -0
- package/dist/opencode-env-tools.js +243 -0
- package/dist/opencode-hooks.js +84 -0
- package/dist/opencode-transparent-aisdk.js +100 -0
- package/dist/opencode-transparent-http.js +2315 -0
- package/dist/opencode-transparent-stream.js +192 -0
- package/dist/opencode-transparent-ws.js +298 -0
- package/dist/opencode-transparent.js +1492 -0
- package/dist/opencode-v2.js +216 -0
- package/dist/opencode.js +175 -0
- package/dist/plugin-options.js +100 -0
- package/dist/rules/builtin.js +283 -0
- package/dist/rules/dynamic.js +68 -0
- package/dist/scanner/encoding.js +274 -0
- package/dist/scanner/engine.js +321 -0
- package/dist/scanner/exact-values.js +99 -0
- package/dist/scanner/redaction-verifier.js +82 -0
- package/dist/scanner/unicode.js +157 -0
- package/dist/scanner/utils.js +60 -0
- package/dist/transports/cli.js +447 -0
- package/dist/transports/web-ui.js +540 -0
- package/dist/transports/web.js +200 -0
- package/dist/types.js +23 -0
- package/dist/utils/files.js +36 -0
- package/dist/utils/path-security.js +30 -0
- package/dist/utils/win-encoding.js +45 -0
- package/package.json +71 -4
|
@@ -0,0 +1,94 @@
|
|
|
1
|
+
import * as fs from "fs";
|
|
2
|
+
import * as path from "path";
|
|
3
|
+
import { createHash } from "crypto";
|
|
4
|
+
import * as yaml from "js-yaml";
|
|
5
|
+
import { fileURLToPath } from "url";
|
|
6
|
+
import { z } from "zod";
|
|
7
|
+
import { loadExactValueDetector } from "../scanner/exact-values.js";
|
|
8
|
+
import { BUILTIN_RULE_IDS } from "../rules/builtin.js";
|
|
9
|
+
const __dirname = path.dirname(fileURLToPath(import.meta.url));
|
|
10
|
+
const MAX_DYNAMIC_RULE_LENGTH = 200;
|
|
11
|
+
const MAX_PRIVATE_DOMAIN_LENGTH = 255;
|
|
12
|
+
const MAX_ENV_FILE_PATH_LENGTH = 4096;
|
|
13
|
+
const CustomRuleSchema = z.object({
|
|
14
|
+
description: z.string().min(1).max(MAX_DYNAMIC_RULE_LENGTH),
|
|
15
|
+
pattern: z.string().min(1).max(MAX_DYNAMIC_RULE_LENGTH),
|
|
16
|
+
severity: z.enum(["HIGH", "MEDIUM", "LOW"]).default("HIGH"),
|
|
17
|
+
});
|
|
18
|
+
export const GuardConfigSchema = z.object({
|
|
19
|
+
nda_keywords: z.array(z.string().min(1).max(MAX_DYNAMIC_RULE_LENGTH)).default(["CONFIDENTIAL", "INTERNAL ONLY", "DO NOT SHARE", "NDA"]),
|
|
20
|
+
private_domains: z.array(z.string().min(1).max(MAX_PRIVATE_DOMAIN_LENGTH)).default([]),
|
|
21
|
+
custom_rules: z.array(CustomRuleSchema).nullable().default([]).transform((v) => v ?? []),
|
|
22
|
+
settings: z.object({
|
|
23
|
+
max_chars: z.number().int().positive().default(200000),
|
|
24
|
+
show_line_numbers: z.boolean().default(true),
|
|
25
|
+
preview_length: z.number().int().positive().default(60),
|
|
26
|
+
encoding_detection: z.boolean().default(false),
|
|
27
|
+
env_files: z.array(z.string().min(1).max(MAX_ENV_FILE_PATH_LENGTH)).max(16).default([]),
|
|
28
|
+
rule_overrides: z.record(z.string().min(1), z.boolean()).default({}),
|
|
29
|
+
}).default({}),
|
|
30
|
+
}).superRefine((config, ctx) => {
|
|
31
|
+
// Unknown rule ids in `rule_overrides` fail the parse (fail-closed): a typo
|
|
32
|
+
// must never silently leave a rule in the wrong state.
|
|
33
|
+
const overrides = config.settings.rule_overrides ?? {};
|
|
34
|
+
for (const id of Object.keys(overrides)) {
|
|
35
|
+
if (!BUILTIN_RULE_IDS.has(id)) {
|
|
36
|
+
ctx.addIssue({
|
|
37
|
+
code: z.ZodIssueCode.custom,
|
|
38
|
+
path: ["settings", "rule_overrides", id],
|
|
39
|
+
message: `unknown builtin rule id "${id}" (see src/rules/builtin.ts BUILTIN_RULE_IDS)`,
|
|
40
|
+
});
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
});
|
|
44
|
+
function finalizeConfig(config, workspaceRoot) {
|
|
45
|
+
return {
|
|
46
|
+
...config,
|
|
47
|
+
exact_value_detector: loadExactValueDetector(config.settings.env_files ?? [], workspaceRoot),
|
|
48
|
+
};
|
|
49
|
+
}
|
|
50
|
+
/**
|
|
51
|
+
* Resolves the guard config path exactly like `loadConfig` does: the override
|
|
52
|
+
* when it exists, otherwise the first default candidate that exists. Returns
|
|
53
|
+
* undefined when no config file is present (defaults apply).
|
|
54
|
+
*/
|
|
55
|
+
export function findConfigPath(overridePath) {
|
|
56
|
+
const configPaths = overridePath
|
|
57
|
+
? [overridePath]
|
|
58
|
+
: [
|
|
59
|
+
path.resolve(process.cwd(), "config/guard.config.yaml"),
|
|
60
|
+
path.resolve(__dirname, "../../config/guard.config.yaml"),
|
|
61
|
+
path.resolve(process.env.HOME ?? "~", ".leakshield/guard.config.yaml"),
|
|
62
|
+
];
|
|
63
|
+
for (const p of configPaths) {
|
|
64
|
+
if (fs.existsSync(p))
|
|
65
|
+
return p;
|
|
66
|
+
}
|
|
67
|
+
return undefined;
|
|
68
|
+
}
|
|
69
|
+
/**
|
|
70
|
+
* Loads the guard config and, from the very same read, the fingerprint of the
|
|
71
|
+
* bytes it was parsed from. The allowlist inside `config` and `fingerprint`
|
|
72
|
+
* are therefore guaranteed to describe one configuration state — an edit
|
|
73
|
+
* between a config load and a separate fingerprint read could otherwise
|
|
74
|
+
* authorize against content that never existed at a single point in time.
|
|
75
|
+
*/
|
|
76
|
+
export function loadConfigWithFingerprint(overridePath, workspaceRoot = process.cwd()) {
|
|
77
|
+
const configPath = findConfigPath(overridePath);
|
|
78
|
+
if (!configPath) {
|
|
79
|
+
return {
|
|
80
|
+
config: finalizeConfig(GuardConfigSchema.parse({}), workspaceRoot),
|
|
81
|
+
fingerprint: "absent",
|
|
82
|
+
configPath,
|
|
83
|
+
};
|
|
84
|
+
}
|
|
85
|
+
const raw = fs.readFileSync(configPath, "utf-8");
|
|
86
|
+
return {
|
|
87
|
+
config: finalizeConfig(GuardConfigSchema.parse(yaml.load(raw)), workspaceRoot),
|
|
88
|
+
fingerprint: createHash("sha256").update(raw).digest("hex"),
|
|
89
|
+
configPath,
|
|
90
|
+
};
|
|
91
|
+
}
|
|
92
|
+
export function loadConfig(overridePath, workspaceRoot = process.cwd()) {
|
|
93
|
+
return loadConfigWithFingerprint(overridePath, workspaceRoot).config;
|
|
94
|
+
}
|
|
@@ -0,0 +1,195 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Per-session email de-identification (issue #20 trial).
|
|
3
|
+
*
|
|
4
|
+
* Opt-in (v2 plugin option `deidentify: true`, requires `mode: "redact"`):
|
|
5
|
+
* repeated MEDIUM `PII_EMAIL` findings are replaced with opaque, stable
|
|
6
|
+
* `[SG-EMAIL-…]` placeholders so an agent can correlate occurrences without
|
|
7
|
+
* seeing the addresses. The mapping key lives in memory for one plugin setup
|
|
8
|
+
* (= one OpenCode session) and is never persisted; there is no reverse
|
|
9
|
+
* mapping. Everything else — HIGH findings, truncation, encoded/overlapping/
|
|
10
|
+
* ambiguous findings, verification failure — keeps the fail-closed default.
|
|
11
|
+
*/
|
|
12
|
+
import { createHmac, randomBytes } from "node:crypto";
|
|
13
|
+
import { scanText } from "../scanner/engine.js";
|
|
14
|
+
import { redactAndVerify } from "../scanner/redaction-verifier.js";
|
|
15
|
+
import { blockedText, protectText, } from "./ingress.js";
|
|
16
|
+
export const DEIDENTIFY_MARKER_PREFIX = "[SG-EMAIL-";
|
|
17
|
+
/** A fully formed issued-placeholder shape. */
|
|
18
|
+
const DEIDENTIFY_MARKER_SHAPE = /\[SG-EMAIL-[0-9a-f]{16}\]/g;
|
|
19
|
+
/** Placeholder body length: 16 hex chars (64 bits). See placeholderFor(). */
|
|
20
|
+
const PLACEHOLDER_HEX_CHARS = 16;
|
|
21
|
+
/**
|
|
22
|
+
* Bound on the placeholders a session retains for replay protection. The
|
|
23
|
+
* registry is bounded so a long session cannot grow it without limit; a unit
|
|
24
|
+
* that would exceed it fails closed (blocks) before issuing anything, and
|
|
25
|
+
* placeholders are retained only after the unit has fully succeeded — so a
|
|
26
|
+
* refused unit consumes no quota.
|
|
27
|
+
*/
|
|
28
|
+
export const ISSUED_PLACEHOLDER_LIMIT = 4096;
|
|
29
|
+
/** One random key per plugin setup (= one OpenCode session); never persisted. */
|
|
30
|
+
export function createSessionKey() {
|
|
31
|
+
return randomBytes(32);
|
|
32
|
+
}
|
|
33
|
+
/**
|
|
34
|
+
* Stable opaque placeholder for one email value within a session. The value is
|
|
35
|
+
* normalized (trim + lowercase) so case variants of one address collide to a
|
|
36
|
+
* single placeholder. 16 hex chars (64 bits) of HMAC-SHA-256 keyed by the
|
|
37
|
+
* session key — non-reversible without the in-memory key, and shaped so no
|
|
38
|
+
* scanner rule or `[REDACTED_*]` marker exemption matches it. Collision
|
|
39
|
+
* bound: at 64 bits, a birthday collision needs ~2^32 distinct values in one
|
|
40
|
+
* session before two different addresses could share a placeholder.
|
|
41
|
+
*/
|
|
42
|
+
export function placeholderFor(value, sessionKey) {
|
|
43
|
+
const digest = createHmac("sha256", sessionKey)
|
|
44
|
+
.update(value.trim().toLowerCase())
|
|
45
|
+
.digest("hex");
|
|
46
|
+
return `${DEIDENTIFY_MARKER_PREFIX}${digest.slice(0, PLACEHOLDER_HEX_CHARS)}]`;
|
|
47
|
+
}
|
|
48
|
+
function isDeidentifiableEmail(finding) {
|
|
49
|
+
return finding.type === "PII_EMAIL" && finding.severity === "MEDIUM";
|
|
50
|
+
}
|
|
51
|
+
/**
|
|
52
|
+
* Substitute email spans in `text` according to `findings`, enforcing the
|
|
53
|
+
* fail-closed gates up front. Returns `{ ok: false }` when:
|
|
54
|
+
* - any finding (email or not) carries `encoding_detected` metadata
|
|
55
|
+
* (its offsets cannot be trusted for substitution),
|
|
56
|
+
* - an email finding lacks usable `match_start`/`match_end`/`match_text`,
|
|
57
|
+
* - email spans overlap, or
|
|
58
|
+
* - a span's `match_text` does not equal the slice it claims to cover.
|
|
59
|
+
*/
|
|
60
|
+
export function applyDeidentify(text, findings, sessionKey) {
|
|
61
|
+
if (findings.some((f) => f.encoding_detected))
|
|
62
|
+
return { ok: false };
|
|
63
|
+
const emails = findings.filter(isDeidentifiableEmail);
|
|
64
|
+
const spans = [];
|
|
65
|
+
for (const f of emails) {
|
|
66
|
+
const { match_start: start, match_end: end, match_text: matched } = f;
|
|
67
|
+
if (typeof start !== "number" ||
|
|
68
|
+
typeof end !== "number" ||
|
|
69
|
+
typeof matched !== "string" ||
|
|
70
|
+
!Number.isInteger(start) ||
|
|
71
|
+
!Number.isInteger(end) ||
|
|
72
|
+
start < 0 ||
|
|
73
|
+
start >= end ||
|
|
74
|
+
end > text.length ||
|
|
75
|
+
text.slice(start, end) !== matched) {
|
|
76
|
+
return { ok: false };
|
|
77
|
+
}
|
|
78
|
+
spans.push({ start, end, placeholder: placeholderFor(matched, sessionKey) });
|
|
79
|
+
}
|
|
80
|
+
spans.sort((a, b) => a.start - b.start);
|
|
81
|
+
for (let i = 1; i < spans.length; i++) {
|
|
82
|
+
if (spans[i].start < spans[i - 1].end)
|
|
83
|
+
return { ok: false };
|
|
84
|
+
}
|
|
85
|
+
// Apply descending by start so earlier offsets stay valid during splicing.
|
|
86
|
+
let substituted = text;
|
|
87
|
+
for (let i = spans.length - 1; i >= 0; i--) {
|
|
88
|
+
const { start, end, placeholder } = spans[i];
|
|
89
|
+
substituted = substituted.slice(0, start) + placeholder + substituted.slice(end);
|
|
90
|
+
}
|
|
91
|
+
return { ok: true, text: substituted };
|
|
92
|
+
}
|
|
93
|
+
/**
|
|
94
|
+
* `protectText` with the de-identification trial applied: emails opted in via
|
|
95
|
+
* the session key are replaced by stable placeholders before the standard
|
|
96
|
+
* redaction/verification pipeline. Any doubt (truncation, encoded findings,
|
|
97
|
+
* bad spans, verification failure, residual originals) blocks the whole unit.
|
|
98
|
+
*
|
|
99
|
+
* `issuedPlaceholders` is the session-owned set of placeholders issued so far.
|
|
100
|
+
* Placeholders already present in `text` are protected exactly like newly
|
|
101
|
+
* issued ones, so a prompt→context replay cannot corrupt a placeholder whose
|
|
102
|
+
* hex body happens to contain a phone-shaped run. Only placeholders actually
|
|
103
|
+
* in this set are exempt — an arbitrary marker-shaped lookalike is not.
|
|
104
|
+
*/
|
|
105
|
+
export function deidentifyText(text, config, sessionKey, options, issuedPlaceholders) {
|
|
106
|
+
if (options.mode !== "redact") {
|
|
107
|
+
// Defense in depth: de-identification is a redact-mode-only trial, so this
|
|
108
|
+
// exported API must never relax block mode even if a future caller
|
|
109
|
+
// bypasses the plugin-option schema refine.
|
|
110
|
+
return protectText(text, config, options);
|
|
111
|
+
}
|
|
112
|
+
const block = (totalFindings) => ({
|
|
113
|
+
action: "block",
|
|
114
|
+
text: blockedText(options.context, totalFindings),
|
|
115
|
+
totalFindings,
|
|
116
|
+
});
|
|
117
|
+
try {
|
|
118
|
+
// The model boundary never honors in-text ignore directives (fail-open
|
|
119
|
+
// bypass otherwise); the same flag covers every scan below.
|
|
120
|
+
const noDirectives = { honorIgnoreDirectives: false };
|
|
121
|
+
const scan = scanText(text, config, noDirectives);
|
|
122
|
+
if (scan.was_truncated)
|
|
123
|
+
return block(scan.total_findings);
|
|
124
|
+
const emails = scan.findings.filter(isDeidentifiableEmail);
|
|
125
|
+
const owned = issuedPlaceholders
|
|
126
|
+
? [...issuedPlaceholders].filter((placeholder) => text.includes(placeholder))
|
|
127
|
+
: [];
|
|
128
|
+
// Any reserved marker this session does not own is refused: it is an
|
|
129
|
+
// evicted/foreign/never-issued marker whose hex body must not be partially
|
|
130
|
+
// rewritten (a phone-shaped run inside it would corrupt the grammar), and a
|
|
131
|
+
// marker-shaped lookalike must never be exempted.
|
|
132
|
+
DEIDENTIFY_MARKER_SHAPE.lastIndex = 0;
|
|
133
|
+
for (let match = DEIDENTIFY_MARKER_SHAPE.exec(text); match !== null; match = DEIDENTIFY_MARKER_SHAPE.exec(text)) {
|
|
134
|
+
if (!issuedPlaceholders?.has(match[0]))
|
|
135
|
+
return block(scan.total_findings);
|
|
136
|
+
}
|
|
137
|
+
// Nothing trial-related in this unit: keep the standard pipeline.
|
|
138
|
+
if (emails.length === 0 && owned.length === 0) {
|
|
139
|
+
return protectText(text, config, options);
|
|
140
|
+
}
|
|
141
|
+
const protectedStrings = [...owned];
|
|
142
|
+
const newPlaceholders = [];
|
|
143
|
+
let subject = text;
|
|
144
|
+
if (emails.length > 0) {
|
|
145
|
+
const applied = applyDeidentify(text, scan.findings, sessionKey);
|
|
146
|
+
if (!applied.ok)
|
|
147
|
+
return block(scan.total_findings);
|
|
148
|
+
subject = applied.text;
|
|
149
|
+
const alreadyQueued = new Set();
|
|
150
|
+
for (const f of emails) {
|
|
151
|
+
const placeholder = placeholderFor(f.match_text, sessionKey);
|
|
152
|
+
protectedStrings.push(placeholder);
|
|
153
|
+
if (!issuedPlaceholders?.has(placeholder) && !alreadyQueued.has(placeholder)) {
|
|
154
|
+
alreadyQueued.add(placeholder);
|
|
155
|
+
newPlaceholders.push(placeholder);
|
|
156
|
+
}
|
|
157
|
+
}
|
|
158
|
+
// Capacity is decided BEFORE anything is issued/retained: a unit that
|
|
159
|
+
// cannot retain ownership of every new marker fails closed and consumes
|
|
160
|
+
// no quota, so a refused unit never leaves a half-registered state.
|
|
161
|
+
if (issuedPlaceholders &&
|
|
162
|
+
issuedPlaceholders.size + newPlaceholders.length > ISSUED_PLACEHOLDER_LIMIT) {
|
|
163
|
+
return block(scan.total_findings);
|
|
164
|
+
}
|
|
165
|
+
}
|
|
166
|
+
const uniqueProtected = [...new Set(protectedStrings)];
|
|
167
|
+
const verified = redactAndVerify(subject, config, noDirectives, uniqueProtected);
|
|
168
|
+
if (!verified.verified)
|
|
169
|
+
return block(scan.total_findings);
|
|
170
|
+
// Independent safety check: every detected email original must be absent
|
|
171
|
+
// from the final output (the placeholders are exempted above, so a leaked
|
|
172
|
+
// original outside a placeholder still fails here).
|
|
173
|
+
const finalText = verified.redacted;
|
|
174
|
+
for (const f of emails) {
|
|
175
|
+
if (f.match_text && finalText.includes(f.match_text)) {
|
|
176
|
+
return block(scan.total_findings);
|
|
177
|
+
}
|
|
178
|
+
}
|
|
179
|
+
// Commit ownership only after the whole unit succeeded, so a blocked unit
|
|
180
|
+
// never consumes registry capacity.
|
|
181
|
+
if (issuedPlaceholders) {
|
|
182
|
+
for (const placeholder of newPlaceholders)
|
|
183
|
+
issuedPlaceholders.add(placeholder);
|
|
184
|
+
}
|
|
185
|
+
// Nothing changed: the unit was already safe once owned placeholders are
|
|
186
|
+
// exempted (e.g. an untouched replay). Otherwise it was redacted.
|
|
187
|
+
if (finalText === text)
|
|
188
|
+
return { action: "allow", text, totalFindings: 0 };
|
|
189
|
+
return { action: "redact", text: finalText, totalFindings: scan.total_findings };
|
|
190
|
+
}
|
|
191
|
+
catch {
|
|
192
|
+
// A scanner failure must never result in the original content reaching a model.
|
|
193
|
+
return block(0);
|
|
194
|
+
}
|
|
195
|
+
}
|
|
@@ -0,0 +1,136 @@
|
|
|
1
|
+
import { createHash } from "node:crypto";
|
|
2
|
+
import { scanText } from "../scanner/engine.js";
|
|
3
|
+
import { redactAndVerify } from "../scanner/redaction-verifier.js";
|
|
4
|
+
const DEFAULT_CACHE_SIZE = 512;
|
|
5
|
+
export function blockedText(context, totalFindings) {
|
|
6
|
+
const count = totalFindings === 0 ? "unscanned" : `${totalFindings} sensitive item(s)`;
|
|
7
|
+
return `[LeakShield blocked ${context}: ${count}. Original content was not sent to the model.]`;
|
|
8
|
+
}
|
|
9
|
+
/**
|
|
10
|
+
* Returns text that is safe to place in an LLM context. Content that exceeds
|
|
11
|
+
* the scanner limit is blocked rather than forwarding an unscanned suffix.
|
|
12
|
+
*/
|
|
13
|
+
export function protectText(text, config, options) {
|
|
14
|
+
try {
|
|
15
|
+
// The model boundary never honors in-text ignore directives: prompt/tool
|
|
16
|
+
// text could carry `// sg-ignore` and sail through raw (fail-open bypass).
|
|
17
|
+
const scan = scanText(text, config, { honorIgnoreDirectives: false });
|
|
18
|
+
if (scan.safe && !scan.was_truncated) {
|
|
19
|
+
return { action: "allow", text, totalFindings: 0 };
|
|
20
|
+
}
|
|
21
|
+
if (options.mode === "redact" && !scan.was_truncated) {
|
|
22
|
+
const verified = redactAndVerify(text, config, { honorIgnoreDirectives: false });
|
|
23
|
+
if (verified.verified && verified.redacted !== text) {
|
|
24
|
+
return {
|
|
25
|
+
action: "redact",
|
|
26
|
+
text: verified.redacted,
|
|
27
|
+
totalFindings: scan.total_findings,
|
|
28
|
+
};
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
return {
|
|
32
|
+
action: "block",
|
|
33
|
+
text: blockedText(options.context, scan.total_findings),
|
|
34
|
+
totalFindings: scan.total_findings,
|
|
35
|
+
};
|
|
36
|
+
}
|
|
37
|
+
catch {
|
|
38
|
+
// A scanner failure must never result in the original content reaching a model.
|
|
39
|
+
return { action: "block", text: blockedText(options.context, 0), totalFindings: 0 };
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
/**
|
|
43
|
+
* Bounded LRU cache for history replay. Entries store only a content hash and
|
|
44
|
+
* an allow/block decision; original text and redacted text are never retained.
|
|
45
|
+
*/
|
|
46
|
+
export class ContentHashCache {
|
|
47
|
+
maxEntries;
|
|
48
|
+
entries = new Map();
|
|
49
|
+
hits = 0;
|
|
50
|
+
misses = 0;
|
|
51
|
+
constructor(maxEntries = DEFAULT_CACHE_SIZE) {
|
|
52
|
+
this.maxEntries = maxEntries;
|
|
53
|
+
}
|
|
54
|
+
get size() {
|
|
55
|
+
return this.entries.size;
|
|
56
|
+
}
|
|
57
|
+
get stats() {
|
|
58
|
+
return { hits: this.hits, misses: this.misses };
|
|
59
|
+
}
|
|
60
|
+
protect(text, config, options) {
|
|
61
|
+
const key = this.keyFor(text, config, options);
|
|
62
|
+
const cached = this.entries.get(key);
|
|
63
|
+
if (cached) {
|
|
64
|
+
this.hits++;
|
|
65
|
+
this.entries.delete(key);
|
|
66
|
+
this.entries.set(key, cached);
|
|
67
|
+
return cached.action === "allow"
|
|
68
|
+
? { action: "allow", text, totalFindings: 0 }
|
|
69
|
+
: { action: "block", text: cached.blockedText, totalFindings: cached.totalFindings };
|
|
70
|
+
}
|
|
71
|
+
this.misses++;
|
|
72
|
+
const result = protectText(text, config, options);
|
|
73
|
+
if (result.action !== "redact") {
|
|
74
|
+
this.set(key, result);
|
|
75
|
+
}
|
|
76
|
+
return result;
|
|
77
|
+
}
|
|
78
|
+
keyFor(text, config, options) {
|
|
79
|
+
const { exact_value_detector, ...serializableConfig } = config;
|
|
80
|
+
return createHash("sha256")
|
|
81
|
+
.update(JSON.stringify({
|
|
82
|
+
text,
|
|
83
|
+
config: serializableConfig,
|
|
84
|
+
exactValueFingerprint: exact_value_detector?.fingerprint,
|
|
85
|
+
mode: options.mode,
|
|
86
|
+
context: options.context,
|
|
87
|
+
}))
|
|
88
|
+
.digest("hex");
|
|
89
|
+
}
|
|
90
|
+
set(key, result) {
|
|
91
|
+
if (this.entries.size >= this.maxEntries) {
|
|
92
|
+
const oldestKey = this.entries.keys().next().value;
|
|
93
|
+
if (oldestKey !== undefined)
|
|
94
|
+
this.entries.delete(oldestKey);
|
|
95
|
+
}
|
|
96
|
+
this.entries.set(key, result.action === "allow"
|
|
97
|
+
? { action: "allow", totalFindings: 0 }
|
|
98
|
+
: { action: "block", totalFindings: result.totalFindings, blockedText: result.text });
|
|
99
|
+
}
|
|
100
|
+
}
|
|
101
|
+
function isPlainRecord(value) {
|
|
102
|
+
if (typeof value !== "object" || value === null)
|
|
103
|
+
return false;
|
|
104
|
+
const prototype = Object.getPrototypeOf(value);
|
|
105
|
+
return prototype === Object.prototype || prototype === null;
|
|
106
|
+
}
|
|
107
|
+
/** Recursively protects strings embedded in JSON-like tool metadata. */
|
|
108
|
+
export function protectUnknownStrings(value, config, options, protector = protectText, seen = new WeakMap()) {
|
|
109
|
+
if (typeof value === "string") {
|
|
110
|
+
return protector(value, config, options).text;
|
|
111
|
+
}
|
|
112
|
+
if (typeof value !== "object" || value === null)
|
|
113
|
+
return value;
|
|
114
|
+
const cached = seen.get(value);
|
|
115
|
+
if (cached !== undefined)
|
|
116
|
+
return cached;
|
|
117
|
+
if (Array.isArray(value)) {
|
|
118
|
+
const copy = [];
|
|
119
|
+
seen.set(value, copy);
|
|
120
|
+
copy.push(...value.map((item) => protectUnknownStrings(item, config, options, protector, seen)));
|
|
121
|
+
return copy;
|
|
122
|
+
}
|
|
123
|
+
if (!isPlainRecord(value)) {
|
|
124
|
+
return "[LeakShield blocked unsupported metadata value.]";
|
|
125
|
+
}
|
|
126
|
+
const copy = {};
|
|
127
|
+
seen.set(value, copy);
|
|
128
|
+
for (const [key, item] of Object.entries(value)) {
|
|
129
|
+
// Protect keys too: an email or secret embedded in an object key must not
|
|
130
|
+
// reach the model raw. NOTE: two distinct keys may redact to the same
|
|
131
|
+
// placeholder and merge into one entry — safety over metadata fidelity.
|
|
132
|
+
const protectedKey = typeof key === "string" ? protector(key, config, options).text : key;
|
|
133
|
+
copy[protectedKey] = protectUnknownStrings(item, config, options, protector, seen);
|
|
134
|
+
}
|
|
135
|
+
return copy;
|
|
136
|
+
}
|