leakshield 0.3.1 → 0.4.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 (108) hide show
  1. package/README.md +35 -5
  2. package/README.zh-TW.md +34 -5
  3. package/dist/adapters/claude-code/capabilities.d.ts +14 -0
  4. package/dist/adapters/claude-code/capabilities.js +47 -0
  5. package/dist/adapters/claude-code/cli.d.ts +10 -0
  6. package/dist/adapters/claude-code/cli.js +51 -0
  7. package/dist/adapters/claude-code/doctor.d.ts +19 -0
  8. package/dist/adapters/claude-code/doctor.js +177 -0
  9. package/dist/adapters/claude-code/proxy.d.ts +47 -0
  10. package/dist/adapters/claude-code/proxy.js +348 -0
  11. package/dist/adapters/opencode/capabilities.d.ts +10 -0
  12. package/dist/adapters/opencode/capabilities.js +48 -0
  13. package/dist/adapters/opencode/doctor.d.ts +67 -0
  14. package/dist/{doctor.js → adapters/opencode/doctor.js} +16 -42
  15. package/dist/adapters/opencode/env-queries.d.ts +133 -0
  16. package/dist/adapters/opencode/env-tools.d.ts +20 -0
  17. package/dist/adapters/opencode/hooks.d.ts +4 -0
  18. package/dist/adapters/opencode/plugin.d.ts +12 -0
  19. package/dist/{opencode.js → adapters/opencode/plugin.js} +7 -7
  20. package/dist/adapters/opencode/tool-policy.d.ts +2 -0
  21. package/dist/adapters/opencode/tool-policy.js +23 -0
  22. package/dist/adapters/opencode/transparent-aisdk.d.ts +6 -0
  23. package/dist/{opencode-transparent-aisdk.js → adapters/opencode/transparent-aisdk.js} +1 -1
  24. package/dist/adapters/opencode/transparent.d.ts +66 -0
  25. package/dist/adapters/opencode/transparent.js +237 -0
  26. package/dist/adapters/opencode/v2.d.ts +20 -0
  27. package/dist/{opencode-v2.js → adapters/opencode/v2.js} +3 -3
  28. package/dist/adapters/pi/capabilities.d.ts +10 -0
  29. package/dist/adapters/pi/capabilities.js +50 -0
  30. package/dist/adapters/pi/doctor.d.ts +26 -0
  31. package/dist/adapters/pi/doctor.js +276 -0
  32. package/dist/adapters/pi/extension.d.ts +28 -0
  33. package/dist/adapters/pi/extension.js +109 -0
  34. package/dist/adapters/pi/guard.d.ts +33 -0
  35. package/dist/adapters/pi/guard.js +154 -0
  36. package/dist/adapters/pi/persistence.d.ts +9 -0
  37. package/dist/adapters/pi/persistence.js +69 -0
  38. package/dist/adapters/pi/settings.d.ts +51 -0
  39. package/dist/adapters/pi/settings.js +136 -0
  40. package/dist/adapters/pi/tool-policy.d.ts +11 -0
  41. package/dist/adapters/pi/tool-policy.js +114 -0
  42. package/dist/cli.d.ts +18 -0
  43. package/dist/cli.js +17 -6
  44. package/dist/config/loader.d.ts +70 -0
  45. package/dist/config/plain-object.d.ts +2 -0
  46. package/dist/core/index.d.ts +9 -0
  47. package/dist/core/index.js +9 -0
  48. package/dist/core/session-guard.d.ts +61 -0
  49. package/dist/{opencode-transparent.js → core/session-guard.js} +55 -713
  50. package/dist/core/sse-recovery.d.ts +6 -0
  51. package/dist/core/tool-restore-policy.d.ts +153 -0
  52. package/dist/core/tool-restore-policy.js +453 -0
  53. package/dist/core/wire.d.ts +213 -0
  54. package/dist/{opencode-transparent-http.js → core/wire.js} +125 -42
  55. package/dist/core/ws.d.ts +26 -0
  56. package/dist/{opencode-transparent-ws.js → core/ws.js} +1 -1
  57. package/dist/decision/deidentify.d.ts +63 -0
  58. package/dist/decision/ingress.d.ts +40 -0
  59. package/dist/decision/mapping-key.d.ts +91 -0
  60. package/dist/decision/mapping-store.d.ts +166 -0
  61. package/dist/decision/model.d.ts +41 -0
  62. package/dist/decision/pseudonymization.d.ts +176 -0
  63. package/dist/decision/redaction.d.ts +56 -0
  64. package/dist/decision/schema-strings.d.ts +23 -0
  65. package/dist/decision/schema-strings.js +2 -2
  66. package/dist/decision/value-search.d.ts +39 -0
  67. package/dist/doctor-capabilities.d.ts +21 -0
  68. package/dist/doctor-capabilities.js +58 -0
  69. package/dist/doctor-hosts.d.ts +18 -0
  70. package/dist/doctor-hosts.js +144 -0
  71. package/dist/doctor-report.d.ts +45 -0
  72. package/dist/doctor-report.js +111 -0
  73. package/dist/forget.d.ts +18 -0
  74. package/dist/guard-options.d.ts +45 -0
  75. package/dist/{plugin-options.js → guard-options.js} +4 -1
  76. package/dist/help.d.ts +2 -0
  77. package/dist/help.js +15 -1
  78. package/dist/i18n/en.d.ts +65 -0
  79. package/dist/i18n/index.d.ts +15 -0
  80. package/dist/i18n/zh-TW.d.ts +65 -0
  81. package/dist/index.d.ts +13 -0
  82. package/dist/index.js +1 -1
  83. package/dist/rules/builtin.d.ts +4 -0
  84. package/dist/rules/dynamic.d.ts +33 -0
  85. package/dist/scanner/allowlist.d.ts +22 -0
  86. package/dist/scanner/cidr.d.ts +39 -0
  87. package/dist/scanner/encoding.d.ts +87 -0
  88. package/dist/scanner/engine.d.ts +43 -0
  89. package/dist/scanner/exact-values.d.ts +11 -0
  90. package/dist/scanner/redaction-verifier.d.ts +24 -0
  91. package/dist/scanner/remotes.d.ts +29 -0
  92. package/dist/scanner/unicode.d.ts +57 -0
  93. package/dist/scanner/utils.d.ts +22 -0
  94. package/dist/transports/cli.d.ts +27 -0
  95. package/dist/transports/web-ui.d.ts +1 -0
  96. package/dist/transports/web-ui.js +1 -1
  97. package/dist/transports/web.d.ts +4 -0
  98. package/dist/types/capabilities.d.ts +67 -0
  99. package/dist/types/capabilities.js +133 -0
  100. package/dist/types.d.ts +149 -0
  101. package/dist/utils/files.d.ts +3 -0
  102. package/dist/utils/path-security.d.ts +18 -0
  103. package/dist/utils/win-encoding.d.ts +16 -0
  104. package/package.json +11 -3
  105. /package/dist/{env-queries.js → adapters/opencode/env-queries.js} +0 -0
  106. /package/dist/{opencode-env-tools.js → adapters/opencode/env-tools.js} +0 -0
  107. /package/dist/{opencode-hooks.js → adapters/opencode/hooks.js} +0 -0
  108. /package/dist/{opencode-transparent-stream.js → core/sse-recovery.js} +0 -0
@@ -0,0 +1,65 @@
1
+ export declare const zhTW: {
2
+ "scan.safe_summary": string;
3
+ "scan.unsafe_summary": string;
4
+ "scan.safe_recommendation": string;
5
+ "scan.unsafe_recommendation": string;
6
+ "scan.warning_encoded": string;
7
+ "scan.warning_truncated": string;
8
+ "scan.warning_zero_width": string;
9
+ "scan.warning_suspicious_unicode": string;
10
+ "redact.safe_summary": string;
11
+ "redact.unsafe_summary": string;
12
+ "cli.scan_target": string;
13
+ "cli.hits": string;
14
+ "cli.location": string;
15
+ "cli.preview": string;
16
+ "cli.more_of_type": string;
17
+ "cli.error_file_not_found": string;
18
+ "cli.error_dir_not_found": string;
19
+ "cli.error_redact_no_input": string;
20
+ "cli.error_path": string;
21
+ "cli.dryrun_header": string;
22
+ "cli.dryrun_safe": string;
23
+ "cli.dryrun_location": string;
24
+ "cli.dryrun_preview": string;
25
+ "cli.redact_written": string;
26
+ "cli.redact_footer": string;
27
+ "cli.redact_incomplete": string;
28
+ "cli.redact_verified": string;
29
+ "cli.scan_dir": string;
30
+ "cli.ext_filter": string;
31
+ "cli.found_files": string;
32
+ "cli.skipped_files": string;
33
+ "cli.dir_complete": string;
34
+ "cli.inline_label": string;
35
+ "cli.decision_warn_header": string;
36
+ "cli.decision_confirm_header": string;
37
+ "cli.confirm_next_step": string;
38
+ "cli.usage_title": string;
39
+ "cli.usage_heading": string;
40
+ "cli.usage_text": string;
41
+ "cli.usage_file": string;
42
+ "cli.usage_dir": string;
43
+ "cli.usage_dir_ext": string;
44
+ "cli.usage_stdin": string;
45
+ "cli.usage_web": string;
46
+ "cli.usage_redact_heading": string;
47
+ "cli.usage_redact_text": string;
48
+ "cli.usage_redact_file": string;
49
+ "cli.usage_redact_out": string;
50
+ "cli.usage_redact_stdin": string;
51
+ "cli.usage_redact_dryrun": string;
52
+ "cli.usage_options_heading": string;
53
+ "cli.usage_opt_format": string;
54
+ "cli.usage_opt_severity": string;
55
+ "cli.usage_opt_redact": string;
56
+ "cli.usage_opt_dryrun": string;
57
+ "cli.usage_opt_out": string;
58
+ "cli.usage_opt_outside": string;
59
+ "cli.usage_opt_web": string;
60
+ "cli.usage_opt_port": string;
61
+ "cli.usage_opt_encoding": string;
62
+ "web.server_title": string;
63
+ "web.server_url": string;
64
+ "web.server_stop": string;
65
+ };
@@ -0,0 +1,13 @@
1
+ /**
2
+ * Package entrypoint for the OpenCode plugin loaders.
3
+ *
4
+ * - OpenCode v2 resolves the package `main` (or `<dir>/index.js` when the dist
5
+ * directory is configured directly) to this file.
6
+ * - The default export is the OpenCode v2 plugin definition (`id` +
7
+ * `setup(ctx)`). Its `server` export is a fail-closed stub for v1 hosts,
8
+ * which are no longer supported.
9
+ *
10
+ * The CLI/web entrypoint lives in `./cli.js` (published as the `leakshield`
11
+ * bin) so importing this module never starts an interactive process.
12
+ */
13
+ export { default } from "./adapters/opencode/plugin.js";
package/dist/index.js CHANGED
@@ -10,4 +10,4 @@
10
10
  * The CLI/web entrypoint lives in `./cli.js` (published as the `leakshield`
11
11
  * bin) so importing this module never starts an interactive process.
12
12
  */
13
- export { default } from "./opencode.js";
13
+ export { default } from "./adapters/opencode/plugin.js";
@@ -0,0 +1,4 @@
1
+ import type { Rule } from "../types.js";
2
+ export declare const BUILTIN_RULES: Rule[];
3
+ /** 所有 builtin 規則的 stable id(供 config rule_overrides 驗證;tests 保證每條規則都有 id)。 */
4
+ export declare const BUILTIN_RULE_IDS: ReadonlySet<string>;
@@ -0,0 +1,33 @@
1
+ import type { CustomRuleConfig, GuardConfig, Rule } from "../types.js";
2
+ export type CustomPatternVerdict = "ok" | "invalid" | "redos-suspect";
3
+ /**
4
+ * Which edges of a rule can actually take a boundary. `word_boundary` can only
5
+ * add `\b` where the edge is a literal ASCII word character; an edge that is a
6
+ * group, class, quantifier or escape is reported as hidden rather than guessed
7
+ * at, and `--doctor` warns so the rule does not look stricter than it is.
8
+ */
9
+ export declare function customRuleBoundaries(rule: Pick<CustomRuleConfig, "pattern" | "word_boundary">): {
10
+ lead: "added" | "hidden" | "none";
11
+ trail: "added" | "hidden" | "none";
12
+ };
13
+ /**
14
+ * Pattern source with `word_boundary` applied. A `\b` is added only where the
15
+ * edge is a literal ASCII word character; an already-written `\b`/`^`/`$` is
16
+ * respected. A top-level alternation is refused because `\bfoo|bar\b` would
17
+ * silently mean `(\bfoo)|(bar\b)`; group it as `(?:foo|bar)`.
18
+ */
19
+ export declare function customRuleSource(rule: Pick<CustomRuleConfig, "pattern" | "word_boundary" | "description">): string;
20
+ /** Final flags: `g` is always present; `i` stays the default so existing rules
21
+ * keep matching as they did before `flags` existed. */
22
+ export declare function customRuleFlags(rule: Pick<CustomRuleConfig, "flags">): string;
23
+ /** The exact RegExp the scanner uses for a custom rule. */
24
+ export declare function customRulePattern(rule: CustomRuleConfig): RegExp;
25
+ export declare function checkCustomPattern(pattern: string, flags?: string): CustomPatternVerdict;
26
+ /** Probe the rule's final pattern (flags and boundaries included). */
27
+ export declare function checkCustomRule(rule: CustomRuleConfig): CustomPatternVerdict;
28
+ /** Descriptions of the custom rules `buildDynamicRules` skips, in config order. */
29
+ export declare function skippedCustomRules(config: GuardConfig): {
30
+ description: string;
31
+ reason: Exclude<CustomPatternVerdict, "ok">;
32
+ }[];
33
+ export declare function buildDynamicRules(config: GuardConfig): Rule[];
@@ -0,0 +1,22 @@
1
+ /**
2
+ * Exact-match allowlists (issue #32).
3
+ *
4
+ * An allowlist entry suppresses a finding only when the matched text is exactly
5
+ * that string. It is not a pattern, it is not a substring test, and it does not
6
+ * rewrite anything: the content still leaves the machine as-is. That makes it a
7
+ * real bypass, which is why every suppression is counted here and surfaced by
8
+ * `--doctor`, and why the entry lists are capped at config load.
9
+ *
10
+ * The counter is process-wide and monotonic. It is diagnostic evidence ("how
11
+ * often did the allowlist actually fire?"), not a metric to optimize.
12
+ */
13
+ /** Values that never produce a finding, for one rule or for every rule. */
14
+ export declare function allowSet(values: readonly string[] | undefined): ReadonlySet<string>;
15
+ /** True when `matchedText` is exactly an allowlisted value. */
16
+ export declare function isAllowlisted(matchedText: string, globalAllow: ReadonlySet<string>, ruleAllow: ReadonlySet<string> | undefined): boolean;
17
+ /** Record one suppressed finding. Bounded so a long-lived process cannot wrap. */
18
+ export declare function noteAllowlistSuppression(): void;
19
+ /** Findings suppressed by an allowlist since this module was loaded. */
20
+ export declare function allowlistSuppressions(): number;
21
+ /** Test seam only: reset the counter between cases. */
22
+ export declare function resetAllowlistSuppressionsForTests(): void;
@@ -0,0 +1,39 @@
1
+ /**
2
+ * IPv4 CIDR helpers for the private-range rule.
3
+ *
4
+ * Password-strength regex cannot express "address inside 172.16.0.0/12": a
5
+ * pattern that covers the range also covers version strings, and one that is
6
+ * narrow enough to avoid them misses octets. Membership is therefore a
7
+ * numeric comparison, and the network list is validated when the config
8
+ * loads so a typo cannot silently weaken the rule.
9
+ */
10
+ /** Ranges the rule covers when `settings.private_cidrs` is empty. */
11
+ export declare const DEFAULT_PRIVATE_CIDRS: readonly string[];
12
+ export interface Cidr {
13
+ /** Network address, already masked. */
14
+ base: number;
15
+ /** Bit mask for the prefix length. */
16
+ mask: number;
17
+ }
18
+ /** Dotted-quad to a 32-bit unsigned integer, or null when it is not an address. */
19
+ export declare function ipv4ToInt(raw: string): number | null;
20
+ /** Parse `a.b.c.d/prefix`; returns null for anything else. */
21
+ export declare function parseCidr(text: string): Cidr | null;
22
+ /** Parse a configured list, falling back to the documented defaults. */
23
+ export declare function parseCidrList(entries: readonly string[] | undefined): Cidr[];
24
+ /** True when the dotted-quad address falls inside one of the networks. */
25
+ export declare function containsAddress(cidrs: readonly Cidr[], raw: string): boolean;
26
+ /**
27
+ * Every four-octet window in a dotted run, in order.
28
+ *
29
+ * `10.1.2.3.4` is not an address, but it contains `1.2.3.4`. A regex finds
30
+ * only the first four groups, so the runner is what keeps detection
31
+ * consistent for the addresses hiding behind that prefix.
32
+ */
33
+ export declare function ipv4Windows(raw: string): string[];
34
+ /**
35
+ * True when `raw` is inside one of the networks, including when it is a
36
+ * dotted run longer than four octets: the run is reported whole if any of
37
+ * its four-octet windows matches.
38
+ */
39
+ export declare function containsAddressInRun(cidrs: readonly Cidr[], raw: string): boolean;
@@ -0,0 +1,87 @@
1
+ /**
2
+ * Encoding detection and decoding utilities
3
+ * Prevents attackers from bypassing detection using Base64, URL encoding, etc.
4
+ */
5
+ import type { Finding, GuardConfig, ScanResult } from "../types.js";
6
+ import { type ScanOptions } from "./engine.js";
7
+ export interface DecodingResult {
8
+ decoded: string;
9
+ encoding_type: string;
10
+ confidence: number;
11
+ }
12
+ export interface ScanWithDecodingResult {
13
+ original: ScanResult;
14
+ decoded: ScanResult[];
15
+ was_decoded: boolean;
16
+ encoding_types_found: string[];
17
+ safe: boolean;
18
+ total_findings: number;
19
+ findings: import("../types.js").Finding[];
20
+ }
21
+ /**
22
+ * Scans text with automatic decoding of common encodings.
23
+ * This prevents attackers from bypassing detection using Base64, URL encoding, etc.
24
+ */
25
+ export declare function scanTextWithDecoding(text: string, config: GuardConfig, opts?: ScanOptions): ScanWithDecodingResult;
26
+ /** Half-open UTF-16 source span of an encoded run whose decoded form has a finding. */
27
+ export interface EncodedRun {
28
+ start: number;
29
+ end: number;
30
+ severity: Finding["severity"];
31
+ /** match_text of the decoded findings behind this run. */
32
+ decodedMatches: string[];
33
+ /** The decoded findings behind this run, tagged with `encoding_detected`. */
34
+ findings: Finding[];
35
+ }
36
+ /**
37
+ * True when masking the runs located in `text` accounts for EVERY decoded
38
+ * finding in `decodedMatches` (the match_text values the whole-segment
39
+ * decoding scan reported). Three checks:
40
+ * - Normalization: any zero-width or look-alike character in `text` returns
41
+ * false, wherever it sits. The generic decoder also decodes the stripped and
42
+ * folded sources, whose runs the locator cannot map back, so partial
43
+ * masking of the raw source could erase the evidence that a hidden part
44
+ * remains.
45
+ * - Evasion: a located decoded form that reports a Unicode evasion returns
46
+ * false. The same character can be percent-encoded, which the normalization
47
+ * check cannot see, and the finding it hides has no source span.
48
+ * - Coverage: each decoded match must equal, or be a substring of, a decoded
49
+ * match of a located run or a direct match (substring because the generic
50
+ * decoder's +/-50 windows can clip a value the locator sees in full). Direct
51
+ * matches count because those windows also re-report plain findings near any
52
+ * percent run, and the direct findings are masked anyway.
53
+ */
54
+ export declare function decodedFindingsAttributable(text: string, config: GuardConfig, opts: ScanOptions | undefined, decodedMatches: readonly string[], directMatches: readonly string[]): boolean;
55
+ /**
56
+ * Re-expresses the encoded findings of a decoding scan as spans of `text`.
57
+ * scanTextWithDecoding reports decoded findings at offsets of the DECODED
58
+ * string, which redaction would apply to the source. Here each located run
59
+ * contributes its decoded findings at the run's exact source span, so a
60
+ * placeholder replaces the whole run.
61
+ *
62
+ * When the decoded findings cannot all be attributed to located runs (a
63
+ * hidden run, a Unicode evasion, a finding without text), it fails closed:
64
+ * every encoded finding loses its offsets, so no redacted content or safe
65
+ * preview is built for the result. `encoding_detected` is kept either way,
66
+ * which the redaction verifier and deidentify rely on to stay fail-closed.
67
+ */
68
+ export declare function anchorDecodedFindings(text: string, scan: ScanWithDecodingResult, config: GuardConfig, opts?: ScanOptions): Finding[];
69
+ /**
70
+ * Locates the encoded runs of `text` whose decoded form holds a finding, as
71
+ * exact spans of `text` itself. This is the ONLY place decoded offsets are
72
+ * mapped back to the source, and it works on `text` alone: the zero-width
73
+ * stripped and confusable-folded sources that scanTextWithDecoding also
74
+ * decodes have offsets that do not map back, so runs hidden that way are not
75
+ * located (the caller's strict rescan keeps refusing them).
76
+ *
77
+ * - Base64 and hex: the span is the whole candidate match, decoded with the
78
+ * same functions and confidence thresholds as scanTextWithDecoding.
79
+ * - URL: the generic decoder's +/-50 window is NOT used, because a clipped
80
+ * window would mask part of a value and leak the rest. The text is split
81
+ * into percent runs and literal pieces and decoded into one string with a
82
+ * decoded-unit to source-range map: literal units map one to one, every
83
+ * unit of a decoded run maps to the WHOLE run. A finding becomes a span
84
+ * only if it covers a decoded-run unit or a "+" turned into a space (the
85
+ * direct scan already handles the rest) and its offsets are exact.
86
+ */
87
+ export declare function locateEncodedRuns(text: string, config: GuardConfig, opts?: ScanOptions): EncodedRun[];
@@ -0,0 +1,43 @@
1
+ import type { GuardConfig, ScanResult, RedactResult } from "../types.js";
2
+ /**
3
+ * Options shared by the scanning entry points.
4
+ */
5
+ export interface ScanOptions {
6
+ /**
7
+ * When false, in-text ignore directives (`// sg-ignore` and friends) are NOT
8
+ * honored and every line is scanned. The model boundary (protectText /
9
+ * deidentifyText) must always pass false — prompt or tool text could
10
+ * otherwise carry a directive and sail through raw (fail-open bypass).
11
+ * The CLI/Web transports keep the default (true), which is their contract.
12
+ */
13
+ honorIgnoreDirectives?: boolean;
14
+ }
15
+ /** Invisible format characters that can splice a value so the rules miss it. */
16
+ export declare const ZERO_WIDTH_CHARS: RegExp;
17
+ /** Appends the ` [WARNING: a, b]` suffix to a summary; no suffix when there is none. */
18
+ export declare function appendWarnings(summary: string, warnings: readonly string[] | undefined): string;
19
+ /**
20
+ * Internal scan function without encoding detection.
21
+ * Used by scanTextWithDecoding to avoid infinite recursion.
22
+ */
23
+ declare function scanTextInternal(text: string, config: GuardConfig, opts?: ScanOptions): ScanResult;
24
+ export declare function scanText(text: string, config: GuardConfig, opts?: ScanOptions): ScanResult;
25
+ export { scanTextInternal };
26
+ /** A UTF-16 code-unit span, half-open [start, end). */
27
+ export interface Utf16Span {
28
+ start: number;
29
+ end: number;
30
+ }
31
+ export declare function redactText(text: string, config: GuardConfig, opts?: ScanOptions,
32
+ /**
33
+ * Spans that must never be rewritten by redaction (validated issued
34
+ * placeholders). A match that merely OVERLAPS one of these spans is
35
+ * skipped, not redacted: redacting it would corrupt the protected value,
36
+ * and leaving it unredacted lets the verification pass report it as a
37
+ * crossing residual and fail closed. Only fully contained matches are
38
+ * exempt from residual reporting (see filterResidualFindings).
39
+ */
40
+ protectedSpans?: readonly Utf16Span[]): RedactResult;
41
+ export { scanTextWithDecoding } from "./encoding.js";
42
+ export type { ScanWithDecodingResult } from "./encoding.js";
43
+ export { sanitizeForScanning, isLikelyHomographAttack, detectSuspiciousUnicode, } from "./unicode.js";
@@ -0,0 +1,11 @@
1
+ export interface ExactValueMatch {
2
+ index: number;
3
+ length: number;
4
+ }
5
+ export declare class ExactValueDetector {
6
+ #private;
7
+ readonly fingerprint: string;
8
+ constructor(values: readonly string[]);
9
+ findAll(text: string): ExactValueMatch[];
10
+ }
11
+ export declare function loadExactValueDetector(envFiles: readonly string[], workspaceRoot: string): ExactValueDetector | undefined;
@@ -0,0 +1,24 @@
1
+ import { type ScanOptions, type Utf16Span } from "./engine.js";
2
+ import type { GuardConfig } from "../types.js";
3
+ export interface RedactVerifiedResult {
4
+ redacted: string;
5
+ verified: boolean;
6
+ totalFindings: number;
7
+ residualFindings: number;
8
+ wasTruncated: boolean;
9
+ summary: string;
10
+ }
11
+ /**
12
+ * Every occurrence of each `protected` string in `text`, as UTF-16 spans.
13
+ * Callers pass the exact values they issued, never a marker-shaped pattern, so
14
+ * a lookalike string that was not issued is never exempted.
15
+ */
16
+ export declare function spansForProtectedStrings(text: string, protectedStrings: readonly string[]): Utf16Span[];
17
+ export declare function redactAndVerify(text: string, config: GuardConfig, opts?: ScanOptions,
18
+ /**
19
+ * Exact values issued by this operation (e.g. `[SG-EMAIL-…]` placeholders)
20
+ * that redaction must not rewrite and verification must exempt exactly when
21
+ * contained. Neighbouring and crossing findings stay reportable so they
22
+ * still fail closed.
23
+ */
24
+ protectedStrings?: readonly string[]): RedactVerifiedResult;
@@ -0,0 +1,29 @@
1
+ /**
2
+ * Transport-aware classification for email-shaped spans.
3
+ *
4
+ * A Git remote written the way SSH expects it (`user@host:path`) and the
5
+ * userinfo of an authenticated URL (`scheme://user:password@host`) both
6
+ * contain a `user@host` run that the email rule would happily report as PII.
7
+ * Reporting it is wrong twice over: a public host gets pseudonymized for no
8
+ * privacy gain, and the password half of a credential is labelled as personal
9
+ * data instead of a secret.
10
+ *
11
+ * The classifier reads the first scheme of the whitespace-delimited run and
12
+ * parses that URL's authority once. The scheme does not have to start the run,
13
+ * so a wrapped URL (`{"url": "https://…"}`, `url=https://…`) is recognised.
14
+ *
15
+ * Every expansion is bounded. When a boundary cannot be proven within the
16
+ * window the span is reported: an unproven exemption must never hide an
17
+ * address. The scp fallback is not attempted in that case, because it would
18
+ * turn a truncated run into an exemption.
19
+ *
20
+ * What it does NOT do: whitelist hosts, paths, files or commands. It only
21
+ * tells the email rule that this span belongs to a different construct. Every
22
+ * other rule still scans the same bytes.
23
+ */
24
+ export type TransportSpan = "ssh-authority" | "url-credential";
25
+ /**
26
+ * Classify the span `text.slice(index, index + length)`, or return null when it
27
+ * is an ordinary address that the email rule should keep reporting.
28
+ */
29
+ export declare function classifyTransportSpan(text: string, index: number, length: number): TransportSpan | null;
@@ -0,0 +1,57 @@
1
+ /**
2
+ * Unicode security utilities
3
+ * Prevents homograph attacks and zero-width character bypasses
4
+ */
5
+ /**
6
+ * Normalizes Unicode text to prevent homograph attacks.
7
+ *
8
+ * Uses NFC (Canonical Composition) to:
9
+ * - Convert composed characters to canonical form
10
+ * - Remove variation selectors
11
+ * - Normalize different representations of the same character
12
+ *
13
+ * Example:
14
+ * - "pa‌ssword" (with zero-width) → "password"
15
+ * - "pᴀssword" (Cyrillic 'a') → "password" (detected as different)
16
+ */
17
+ export declare function normalizeUnicode(text: string): {
18
+ normalized: string;
19
+ hadZeroWidth: boolean;
20
+ hadVariants: boolean;
21
+ removedChars: number;
22
+ };
23
+ /**
24
+ * Detects if text contains suspicious Unicode patterns.
25
+ * Returns details about what was found.
26
+ * Only flags patterns that are likely used for bypassing detection.
27
+ */
28
+ export declare function detectSuspiciousUnicode(text: string): {
29
+ hasZeroWidth: boolean;
30
+ hasVariationSelectors: boolean;
31
+ hasMixedScripts: boolean;
32
+ hasHomographs: boolean;
33
+ details: string[];
34
+ };
35
+ /**
36
+ * Checks if a string likely contains a homograph attack.
37
+ * This is a heuristic check - not 100% accurate but catches common patterns.
38
+ */
39
+ export declare function isLikelyHomographAttack(text: string): boolean;
40
+ /**
41
+ * Sanitizes text for scanning by applying Unicode normalization.
42
+ * Returns both the normalized text and metadata about what was changed.
43
+ */
44
+ export declare function sanitizeForScanning(text: string): {
45
+ sanitized: string;
46
+ metadata: {
47
+ hadZeroWidth: boolean;
48
+ hadVariants: boolean;
49
+ removedChars: number;
50
+ homographSuspected: boolean;
51
+ };
52
+ };
53
+ /**
54
+ * Replaces Cyrillic/Greek look-alike letters with their Latin counterparts.
55
+ * Length-preserving; returns the input unchanged when it has none.
56
+ */
57
+ export declare function foldConfusables(text: string): string;
@@ -0,0 +1,22 @@
1
+ export declare function redact(_value: string, _previewLen: number): string;
2
+ export declare function getLineCol(text: string, index: number): {
3
+ line: number;
4
+ col: number;
5
+ };
6
+ /** Start offset of every line in a text; a line break is `\r?\n`, so only `\n` ends a line. */
7
+ export declare function createLineIndex(text: string): number[];
8
+ /** Line (1-based) and column (1-based) of `index`, given the starts from createLineIndex of the same text. */
9
+ export declare function lineColAt(lineStarts: readonly number[], index: number): {
10
+ line: number;
11
+ col: number;
12
+ };
13
+ /**
14
+ * Extracts line numbers that should be ignored during scanning.
15
+ *
16
+ * Lines containing any of the supported ignore patterns will be skipped.
17
+ * This prevents attackers from using variants to bypass detection.
18
+ *
19
+ * @param text - The full text content to scan
20
+ * @returns Set of line numbers (1-indexed) to ignore
21
+ */
22
+ export declare function getIgnoredLines(text: string): Set<number>;
@@ -0,0 +1,27 @@
1
+ import type { ScanResult } from "../types.js";
2
+ import type { GuardDecisionResult } from "../decision/model.js";
3
+ import { validateCliScanPath } from "../utils/path-security.js";
4
+ export { validateCliScanPath };
5
+ type MinSeverity = "high" | "medium" | "low";
6
+ export declare function filterBySeverity(result: ScanResult, min: MinSeverity): ScanResult;
7
+ /**
8
+ * Pure function that formats a GuardDecisionResult into CLI output lines.
9
+ *
10
+ * Does NOT write to console — returns an array of strings so callers can
11
+ * test formatting without capturing stdout.
12
+ *
13
+ * | decision | Behaviour |
14
+ * |----------|---------------------------------------------|
15
+ * | ALLOW | Clean summary, continue normally |
16
+ * | WARN | Reminder with findings, then continue |
17
+ * | CONFIRM | Warning card with actions (non-interactive) |
18
+ */
19
+ export declare function formatCliDecision(decision: GuardDecisionResult, label: string): string[];
20
+ /**
21
+ * Build a decision-oriented JSON object safe for CLI/CI export.
22
+ *
23
+ * Strips `originalContent` and ensures findings carry only transport-safe fields.
24
+ */
25
+ export declare function buildDecisionJsonOutput(decision: GuardDecisionResult, label: string): Record<string, unknown>;
26
+ export declare function printCliResult(result: ScanResult, label: string): void;
27
+ export declare function runCli(): Promise<void>;
@@ -0,0 +1 @@
1
+ export declare const WEB_UI_HTML: string;
@@ -236,7 +236,7 @@ export const WEB_UI_HTML = String.raw `<!DOCTYPE html>
236
236
  <main class="shell">
237
237
  <header class="topbar">
238
238
  <div class="brand">
239
- <div class="mark" aria-hidden="true">SG</div>
239
+ <div class="mark" aria-hidden="true">LS</div>
240
240
  <div>
241
241
  <h1>LeakShield</h1>
242
242
  <p class="tagline"><span class="tagline-part">本機敏感內容檢查台</span> <span class="tagline-part" lang="en">/ Local redaction workbench</span></p>
@@ -0,0 +1,4 @@
1
+ import * as http from "node:http";
2
+ import type { GuardConfig } from "../types.js";
3
+ export declare function createWebServer(config?: GuardConfig): http.Server;
4
+ export declare function runWeb(port: number): Promise<void>;
@@ -0,0 +1,67 @@
1
+ export type CapabilityState = "protected" | "refused" | "not-present" | "outside" | "unknown";
2
+ export interface Capability {
3
+ state: CapabilityState;
4
+ /** The core handler this egress reaches, or where the request is refused. */
5
+ mechanism: string;
6
+ /** Required for protected and not-present; expected for refused. A repo-relative path. */
7
+ evidence?: string;
8
+ /** Residual risk or coverage limit; only what is true. */
9
+ note?: string;
10
+ }
11
+ export interface HostCapabilities {
12
+ /** "opencode" | "claude-code" | "pi" */
13
+ host: string;
14
+ /** The host version the rows were verified against. */
15
+ verifiedVersion: string;
16
+ interception: "in-process-fetch" | "in-process-host-hook" | "loopback-proxy" | "preload";
17
+ transports: {
18
+ /** Model HTTP: the three wire families, or the proxy's route. */
19
+ http: Capability;
20
+ websocket: Capability;
21
+ /** smithy / gRPC / node:http / an SDK's built-in transport. */
22
+ nonFetch: Capability;
23
+ };
24
+ surfaces: {
25
+ /** The local tool execution boundary. */
26
+ toolArgs: Capability;
27
+ /** Assistant text restoration. */
28
+ replyDisplay: Capability;
29
+ /** Compaction / branch summary / title. */
30
+ background: Capability;
31
+ };
32
+ credentials: "in-process" | "separated";
33
+ persistence: "opt-in" | "none";
34
+ /**
35
+ * Load order, a disabled extension, an unsupported provider, …
36
+ * Each entry starts with the row it qualifies, `<section>.<field>: `, so an
37
+ * `outside` row can be traced to its residual by invariant 4.
38
+ */
39
+ residuals: string[];
40
+ }
41
+ export declare const CAPABILITY_ROWS: readonly ["transports.http", "transports.websocket", "transports.nonFetch", "surfaces.toolArgs", "surfaces.replyDisplay", "surfaces.background"];
42
+ export type CapabilityRow = (typeof CAPABILITY_ROWS)[number];
43
+ export declare const CAPABILITY_ROW_TITLES: Readonly<Record<CapabilityRow, string>>;
44
+ export declare function capabilityAt(capabilities: HostCapabilities, row: CapabilityRow): Capability;
45
+ export interface CapabilityVerdict {
46
+ verdict: "PROTECTED" | "PARTIAL";
47
+ unknown: CapabilityRow[];
48
+ outside: CapabilityRow[];
49
+ }
50
+ /**
51
+ * `unknown` and `outside` rows cap the host at PARTIAL. A host can still be
52
+ * PARTIAL for install-level reasons (hook-first mode, load order); this only
53
+ * answers what the declaration itself allows.
54
+ */
55
+ export declare function capabilityVerdict(capabilities: HostCapabilities): CapabilityVerdict;
56
+ export declare class CapabilityInvariantError extends Error {
57
+ constructor(host: string, message: string);
58
+ }
59
+ export interface CapabilityAudit {
60
+ /** Repository root that evidence paths are resolved against. */
61
+ root?: string;
62
+ /** Injectable for tests that declare synthetic evidence. */
63
+ fileExists?(filePath: string): boolean;
64
+ /** Injectable alongside `fileExists`; a directory is not evidence. */
65
+ isFile?(filePath: string): boolean;
66
+ }
67
+ export declare function assertCapabilities(capabilities: HostCapabilities, audit?: CapabilityAudit): void;