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,40 @@
1
+ import type { GuardConfig } from "../types.js";
2
+ export type IngressMode = "block" | "redact";
3
+ export type ProtectionAction = "allow" | "block" | "redact";
4
+ export interface ProtectedText {
5
+ action: ProtectionAction;
6
+ text: string;
7
+ totalFindings: number;
8
+ }
9
+ export interface ProtectionOptions {
10
+ mode: IngressMode;
11
+ context: string;
12
+ }
13
+ export type TextProtector = (text: string, config: GuardConfig, options: ProtectionOptions) => ProtectedText;
14
+ export declare function blockedText(context: string, totalFindings: number): string;
15
+ /**
16
+ * Returns text that is safe to place in an LLM context. Content that exceeds
17
+ * the scanner limit is blocked rather than forwarding an unscanned suffix.
18
+ */
19
+ export declare function protectText(text: string, config: GuardConfig, options: ProtectionOptions): ProtectedText;
20
+ /**
21
+ * Bounded LRU cache for history replay. Entries store only a content hash and
22
+ * an allow/block decision; original text and redacted text are never retained.
23
+ */
24
+ export declare class ContentHashCache {
25
+ private readonly maxEntries;
26
+ private readonly entries;
27
+ private hits;
28
+ private misses;
29
+ constructor(maxEntries?: number);
30
+ get size(): number;
31
+ get stats(): {
32
+ hits: number;
33
+ misses: number;
34
+ };
35
+ protect(text: string, config: GuardConfig, options: ProtectionOptions): ProtectedText;
36
+ private keyFor;
37
+ private set;
38
+ }
39
+ /** Recursively protects strings embedded in JSON-like tool metadata. */
40
+ export declare function protectUnknownStrings(value: unknown, config: GuardConfig, options: ProtectionOptions, protector?: TextProtector, seen?: WeakMap<object, unknown>): unknown;
@@ -0,0 +1,91 @@
1
+ /**
2
+ * W2 (B2) mapping-key providers — key custody for the encrypted mapping
3
+ * store (decision `docs/plans/2026-10-07-persistence-decision-db-over-t2.md`
4
+ * §10: keychain is the local-first equivalent of mainstream key custody;
5
+ * none of the four reference integrations ship one).
6
+ *
7
+ * Resolution ladder (decision §4.6/§8 — degrade, never fail-closed):
8
+ * 1. OS keychain — macOS Keychain (`security`), Linux libsecret
9
+ * (`secret-tool`), Windows DPAPI (ProtectedData, CurrentUser scope).
10
+ * 2. 0600 keyfile — ONLY when explicitly opted in; documented weaker
11
+ * (a stolen directory/backup carries both secrets).
12
+ * 3. null — the caller degrades that process to memory-only operation;
13
+ * conversations are never blocked.
14
+ *
15
+ * Threat-model boundary (documented in the decision and README): the
16
+ * keychain defends OFFLINE file theft (disk, backups, a stolen SGP.db); it
17
+ * does not defend malware already running inside the user's login session
18
+ * (macOS authorization prompts can be social-engineered; DPAPI/libsecret
19
+ * decrypt for the same user). This is the common OS-protection boundary,
20
+ * not unique to this design.
21
+ */
22
+ import type { MappingKey, MappingKeyProvider } from "./mapping-store.js";
23
+ /** Platform keychain access. `read` returns null when the item is absent;
24
+ * any other failure throws (= keychain unavailable, ladder steps down). */
25
+ export interface KeyStoreProbe {
26
+ read(): string | null;
27
+ write(hexKey: string): void;
28
+ }
29
+ /** macOS Keychain generic-password probe. Exit 44 = item not found (null). */
30
+ export declare function createMacKeychainProbe(): KeyStoreProbe | null;
31
+ /**
32
+ * Linux libsecret probe via secret-tool.
33
+ *
34
+ * Exit-code semantics (R2-4): `secret-tool lookup` exits 1 BOTH when no item
35
+ * matches (silent, empty stdout AND stderr) and on real errors (message on
36
+ * stderr). Only the silent variant is "absent"; a read failure must never be
37
+ * mistaken for absence, or the ladder would create/overwrite a key over an
38
+ * unreadable keychain. ENOENT means secret-tool is not installed.
39
+ */
40
+ export declare function interpretSecretToolLookup(result: {
41
+ status: number | null;
42
+ stdout: string;
43
+ stderr?: string;
44
+ error?: {
45
+ code?: string;
46
+ };
47
+ }): string | null;
48
+ export declare function createLinuxSecretProbe(): KeyStoreProbe | null;
49
+ /**
50
+ * Windows DPAPI probe. DPAPI protects data, not storage, so the encrypted
51
+ * key blob lives in a 0600 file under the user's profile; it is decryptable
52
+ * only by the same user on the same machine (offline theft fails).
53
+ */
54
+ export declare function createWindowsDpapiProbe(): KeyStoreProbe | null;
55
+ /** The platform's keychain probe, or null when unsupported. */
56
+ export declare function createPlatformKeychainProbe(): KeyStoreProbe | null;
57
+ /**
58
+ * 0600 keyfile provider — the documented-weaker ladder step. The key sits
59
+ * next to the data's directory tree, so directory/backup theft carries both
60
+ * secrets; it still enforces the two-file bar and never prompts.
61
+ *
62
+ * R-round guarantees:
63
+ * - Creation uses exclusive (`wx`) semantics: two processes racing the first
64
+ * create converge on ONE key (the loser adopts the winner's file) instead
65
+ * of silently forking keys.
66
+ * - An existing file with group/other permission bits is tightened to 0600;
67
+ * if tightening fails the provider refuses (ladder degrades, memory-only)
68
+ * rather than silently accepting a world-readable key.
69
+ */
70
+ export declare class KeyfileMappingKeyProvider implements MappingKeyProvider {
71
+ private readonly path;
72
+ readonly source: "keyfile";
73
+ private key;
74
+ constructor(path: string);
75
+ getOrCreateKey(): MappingKey;
76
+ }
77
+ export interface ResolveMappingKeyOptions {
78
+ /** Explicit opt-in for the weaker keyfile ladder step. */
79
+ keyFile: boolean;
80
+ /** Overrides the default keyfile location. */
81
+ keyfilePath?: string;
82
+ /** Content-free degradation notice (the guard's WARN line). */
83
+ warn: (message: string) => void;
84
+ }
85
+ /** Overridable for tests. */
86
+ export declare function resolveMappingKeyWithProbe(probe: KeyStoreProbe | null, options: ResolveMappingKeyOptions): MappingKeyProvider | null;
87
+ /** Ladder entry point for production callers. */
88
+ export declare function resolveMappingKey(options: ResolveMappingKeyOptions): MappingKeyProvider | null;
89
+ export declare function defaultKeyfilePath(): string;
90
+ /** Decision §8: global store location, owner-specified file name. */
91
+ export declare function defaultStorePath(): string;
@@ -0,0 +1,166 @@
1
+ /**
2
+ * W2 (B1, R2 2026-10-07) encrypted SQLite mapping store — the persistence
3
+ * adapter for the transparent pseudonymization core (decision
4
+ * `docs/plans/2026-10-07-persistence-decision-db-over-t2.md`).
5
+ *
6
+ * Design constraints (decision §4 + external-review R1/R2 rounds):
7
+ * - Per-entry AES-256-GCM; AAD binds `sessionId || token` so a row moved
8
+ * between sessions/tokens fails authentication instead of decrypting.
9
+ * - Originals NEVER appear in plaintext anywhere in the file (tokens do —
10
+ * they are non-sensitive by design: they ride transcripts already).
11
+ * - Dual-secret custody: this module needs BOTH the DB file and the key
12
+ * provider's key; either alone exposes nothing.
13
+ * - Degrade, never fail-closed: unreadable DB → the caller falls back to
14
+ * memory-only; undecryptable rows are skipped (treated as absent).
15
+ * - WAL journal; writes are single transactions; lazy TTL sweep on open
16
+ * (writer handles only — readOnly handles never write).
17
+ * - Pure storage: no OpenCode imports, no config coupling. The core stays
18
+ * fs/db-free; this adapter feeds it via seedSession (B3).
19
+ *
20
+ * Concurrency & lifecycle invariants (R1+R2):
21
+ * - Lazy `node:sqlite` load: a runtime without the driver must not break
22
+ * plugin load when persistence is OFF (zero-diff default path).
23
+ * - Initialization (DDL, version upgrade, meta bootstrap, key pinning) runs
24
+ * in ONE BEGIN IMMEDIATE transaction with ON CONFLICT DO NOTHING inserts:
25
+ * two first-openers can never clobber each other's key identity (R2-3).
26
+ * - Key identity pinning: sha256(key) prefix recorded in meta. Opening with
27
+ * a DIFFERENT key throws MappingKeyMismatchError (memory-only degrade),
28
+ * never silently re-keys. `forgetAll` clears the pin so a mismatched store
29
+ * can be deliberately reset with `forget --all` (R2-13). readOnly handles
30
+ * never pin anything (R2-12).
31
+ * - Optimistic concurrency with absent-sentinel and tombstones:
32
+ * - expectedVersion === 0 means "the row was ABSENT when this handle last
33
+ * looked" — writing then requires the row to still be absent (R2-1).
34
+ * - every delete (forget / TTL sweep / LRU eviction) records the row's
35
+ * version in session_tombstones; re-creation CONTINUES the numbering, so
36
+ * a stale writer's remembered version can never match a re-created row
37
+ * (no ABA resurrection, R2-2).
38
+ * - Bounded retention: a single snapshot larger than maxEntries is refused
39
+ * outright (R2-10); beyond that, maxSessions / maxEntries evict
40
+ * least-recently-used sessions inside the write transaction.
41
+ * - Erasure honesty: `PRAGMA secure_delete = ON` zeroes deleted pages,
42
+ * forgetAll additionally VACUUMs and truncates the WAL. Logical +
43
+ * best-effort in-file erasure — physical media residue is out of scope.
44
+ */
45
+ /** 32-byte AES-256 key material. Never persisted by this module. */
46
+ export type MappingKey = Buffer;
47
+ /** Supplies the encryption key. Implementations: in-memory (tests), keychain (B2). */
48
+ export interface MappingKeyProvider {
49
+ /** Runtime provenance only; never key material. Omitted by custom providers. */
50
+ readonly source?: "os-keychain" | "keyfile";
51
+ /** Returns the 32-byte key, creating it on first use when supported. */
52
+ getOrCreateKey(): MappingKey;
53
+ }
54
+ /** In-memory key provider for tests and throwaway stores. */
55
+ export declare class InMemoryMappingKeyProvider implements MappingKeyProvider {
56
+ private key;
57
+ constructor(seed?: Buffer);
58
+ getOrCreateKey(): MappingKey;
59
+ }
60
+ export interface MappingEntry {
61
+ token: string;
62
+ original: string;
63
+ }
64
+ export interface SeededSession {
65
+ sessionId: string;
66
+ epoch: string;
67
+ entries: MappingEntry[];
68
+ }
69
+ /** What loadSession returns: the seed plus the row's optimistic-concurrency
70
+ * version, captured at read time so a stale handle cannot overwrite a newer
71
+ * snapshot written by another process in between (R1 F3.2). */
72
+ export interface LoadedSession extends SeededSession {
73
+ version: number;
74
+ }
75
+ export interface OpenMappingStoreOptions {
76
+ /** Absolute or relative DB file path. Parent directories are created 0700. */
77
+ path: string;
78
+ keyProvider: MappingKeyProvider;
79
+ /**
80
+ * TTL in whole days; 0 disables expiry (manual forget only). Sessions whose
81
+ * `expires_at` passed are dropped by the sweep on open (writer handles
82
+ * only). Default 7 (decision §8, owner 2026-10-07).
83
+ */
84
+ ttlDays?: number;
85
+ /** Max persisted sessions before LRU eviction (default 256, owner R-round). */
86
+ maxSessions?: number;
87
+ /** Max total persisted mapping rows before LRU eviction (default 50,000).
88
+ * A single snapshot larger than this is refused (R2-10). */
89
+ maxEntries?: number;
90
+ /**
91
+ * Probe/erase handle for doctor and `forget`: never initializes or pins —
92
+ * no DDL, no meta bootstrap or key pinning, no TTL sweep, no last_used
93
+ * touches — and putSession refuses. Counting and deleting never decrypt,
94
+ * so a throwaway key suffices. forgetSession/forgetAll still perform the
95
+ * explicit erasure writes (tombstone + delete + epoch bump + key-pin
96
+ * clear). An uninitialized file yields an empty stub (R2-12).
97
+ */
98
+ readOnly?: boolean;
99
+ /** Injection point for deterministic tests. */
100
+ now?: () => number;
101
+ }
102
+ /** CAS failure: another process holds a newer (or simply different-lineage)
103
+ * snapshot for this session; the stale writer is refused. */
104
+ export declare class MappingStoreConflictError extends Error {
105
+ constructor(sessionId: string);
106
+ }
107
+ /** A forget ran under this handle; persisting now would resurrect erased data. */
108
+ export declare class MappingForgottenError extends Error {
109
+ constructor();
110
+ }
111
+ /** The resolved key does not match the key identity pinned in this store. */
112
+ export declare class MappingKeyMismatchError extends Error {
113
+ constructor();
114
+ }
115
+ /** The single snapshot exceeds the store-wide entry cap; refused outright. */
116
+ export declare class MappingSnapshotTooLargeError extends Error {
117
+ constructor(sessionId: string, entries: number, cap: number);
118
+ }
119
+ /**
120
+ * Stable identity for a key: sha256 prefix. The key is 256-bit random, so
121
+ * publishing this digest inside the (plaintext) meta row leaks nothing about
122
+ * the key material; it exists to detect key-source drift before any write.
123
+ */
124
+ export declare function deriveKeyId(key: MappingKey): string;
125
+ export interface MappingStore {
126
+ /** The persisted session, or null when absent. Undecryptable rows are skipped. */
127
+ loadSession(sessionId: string): LoadedSession | null;
128
+ /**
129
+ * Tombstone generation for an ABSENT session (0 = never deleted). The guard
130
+ * pairs this with loadSession's null to build the absent-CAS token
131
+ * (-(generation+1)); an absent writer whose remembered generation no longer
132
+ * matches is refused (R3-F2: no resurrection across a delete boundary).
133
+ */
134
+ absentGeneration(sessionId: string): number;
135
+ /**
136
+ * Atomically persists a session's full mapping set (replace semantics)
137
+ * guarded by compare-and-swap on the version observed at LOAD time.
138
+ * expectedVersion > 0: the remembered row version. expectedVersion <= 0
139
+ * encodes an ABSENT look with its generation: -g-1 (0 ≡ generation 0, a
140
+ * never-deleted look). Returns the
141
+ * stored version. Throws MappingStoreConflictError on any lineage
142
+ * mismatch, MappingForgottenError when a store-wide forget raced this
143
+ * handle, MappingSnapshotTooLargeError when the snapshot itself exceeds
144
+ * maxEntries, Error on I/O.
145
+ */
146
+ putSession(seed: SeededSession, expectedVersion: number): number;
147
+ /** Drops one session (idempotent, tombstoning its version). Returns true
148
+ * when a row was removed. */
149
+ forgetSession(sessionId: string): boolean;
150
+ /**
151
+ * Drops every session AND clears the pinned key identity (deliberate reset
152
+ * path — the next writer open re-pins). secure_delete zeroes freed pages,
153
+ * then VACUUM + WAL truncate. Returns the number of sessions removed.
154
+ */
155
+ forgetAll(): number;
156
+ /** Persisted session count. */
157
+ sessionCount(): number;
158
+ close(): void;
159
+ }
160
+ /**
161
+ * Opens (creating when needed) the encrypted mapping store. Throws only on
162
+ * unreadable/uncreatable files or key-identity mismatch — callers translate
163
+ * that into a memory-only degradation, never a conversation failure
164
+ * (decision §4.6).
165
+ */
166
+ export declare function openMappingStore(options: OpenMappingStoreOptions): MappingStore;
@@ -0,0 +1,41 @@
1
+ /**
2
+ * Decision model — translates a ScanResult into a GuardDecisionResult
3
+ * that the reminder / confirmation UI layer can consume.
4
+ */
5
+ import type { ScanResult, Finding, GuardConfig } from "../types.js";
6
+ /** Overall decision the guardrail returns. */
7
+ export type GuardDecision = "ALLOW" | "WARN" | "CONFIRM";
8
+ /** Computed risk level. */
9
+ export type GuardRiskLevel = "LOW" | "MEDIUM" | "HIGH" | "CRITICAL";
10
+ /** Recommended action when decision is CONFIRM. */
11
+ export type GuardRecommendedAction = "REVIEW" | "BLOCK";
12
+ /** A single finding as seen by the decision layer. */
13
+ export interface GuardDecisionFinding {
14
+ type: Finding["type"];
15
+ severity: Finding["severity"];
16
+ description: string;
17
+ preview: string;
18
+ line?: number;
19
+ }
20
+ /** The full decision result consumed by the UI layer. */
21
+ export interface GuardDecisionResult {
22
+ decision: GuardDecision;
23
+ riskLevel: GuardRiskLevel;
24
+ summary: string;
25
+ findings: readonly GuardDecisionFinding[];
26
+ recommendedAction?: GuardRecommendedAction;
27
+ safePreview?: string;
28
+ redactedContent?: string;
29
+ originalContent: string;
30
+ }
31
+ /**
32
+ * Translate a ScanResult into a GuardDecisionResult.
33
+ *
34
+ * | Findings | decision | riskLevel | recommendedAction |
35
+ * |-------------------|----------|-----------|-------------------|
36
+ * | none | ALLOW | LOW | — |
37
+ * | LOW only | WARN | MEDIUM | — |
38
+ * | MEDIUM (no HIGH) | CONFIRM | HIGH | REVIEW |
39
+ * | any HIGH | CONFIRM | CRITICAL | BLOCK |
40
+ */
41
+ export declare function toDecisionResult(scan: ScanResult, originalContent: string, config?: GuardConfig): GuardDecisionResult;
@@ -0,0 +1,176 @@
1
+ /**
2
+ * Session-scoped reversible pseudonymization core (issue #22, offline core).
3
+ *
4
+ * This module is a PURE IN-MEMORY DATA SUBSTITUTION engine over strings and
5
+ * strict-JSON values. It performs exact, reversible replacement of scanner
6
+ * findings with opaque session-scoped tokens. It does NOT provide, and must
7
+ * not be described as providing: shell escaping, tool permission decisions,
8
+ * model dispatch, provider/streaming/WebSocket rewriting, UI restoration, or
9
+ * persistence. Runtime adapters are not wired in this module; integrating it
10
+ * into OpenCode hooks remains gated on runtime evidence.
11
+ *
12
+ * Guarantees implemented here:
13
+ * - Bidirectional exact-string mapping per session identity (never normalized,
14
+ * never shared across sessions, never persisted; no TTL, no eviction, no fs).
15
+ * - Reserved token namespace, two versions (W1, 2026-10-07): new mints are
16
+ * category-labelled `[SGP2:<FINDING_TYPE>-<4 letters>×3]` with a random
17
+ * letter-only payload (digit-free so digit-based detector families cannot
18
+ * match it); the legacy `[SGP1:<epoch32hex>-<counter>]` shape stays
19
+ * recognized so mappings issued before the switch keep restoring. Strict
20
+ * protection and restoration entrypoints reject foreign, expired, or
21
+ * malformed markers of either version. Explicit model-text entrypoints
22
+ * preserve unknown markers as literal text, scan them normally, and never
23
+ * grant them mapping ownership.
24
+ * - Every protect/restore operation is an atomic transaction: the live
25
+ * registry is mutated only after the whole operation (including rescans,
26
+ * token-neighbor scans, capacity checks and independent absence checks)
27
+ * succeeds. Failed restores never mutate anything; inputs are never mutated.
28
+ * - Issued tokens are validated FIRST, as a unit: their spans are exempt
29
+ * (interior findings included, before overlap checks) on input and output,
30
+ * crossing matches still fail, and token epochs are never decoded as user
31
+ * content — decoding runs only over separate non-token segments, while
32
+ * the decoder's URL-context windows crossing a token retain that token's
33
+ * fragment verbatim and decode only the surrounding pieces.
34
+ * - Failures carry ONLY a static reason string: no originals, findings,
35
+ * previews, exception messages, partial output, or blocked-content notices.
36
+ *
37
+ * Non-goals documented up front: this is not universal detection. The engine's
38
+ * own finding collapse can hide values; the rescan plus independent absence
39
+ * check below is defense in depth over WHAT the scanner reports, not a claim
40
+ * that every sensitive value is detected.
41
+ */
42
+ import type { GuardConfig } from "../types.js";
43
+ /** Static failure codes. Every failure result contains only `reason`. */
44
+ export type PseudonymFailureReason = "invalid_session" | "invalid_input" | "session_limit" | "entry_limit" | "session_capacity" | "aggregate_capacity" | "operation_limit" | "truncated_content" | "encoded_content"
45
+ /** Zero-width characters hide a value the scanner would otherwise detect. */
46
+ | "unicode_evasion" | "invalid_finding_span" | "token_overlap" | "malformed_token" | "unknown_token" | "residual_sensitive_content" | "unsafe_structure" | "key_collision" | "epoch_collision" | "token_collision" | "scanner_failure" | "internal_failure";
47
+ export interface PseudonymFailure {
48
+ ok: false;
49
+ reason: PseudonymFailureReason;
50
+ }
51
+ export type PseudonymTextResult = {
52
+ ok: true;
53
+ text: string;
54
+ } | PseudonymFailure;
55
+ export type PseudonymJsonResult = {
56
+ ok: true;
57
+ value: unknown;
58
+ } | PseudonymFailure;
59
+ /** Documented conservative budgets. All values are positive safe integers. */
60
+ export interface PseudonymLimits {
61
+ /** Live sessions with at least one committed mapping. Default 128. */
62
+ maxSessions: number;
63
+ /** Mapping entries (original+token pairs) per session. Default 4096. */
64
+ maxEntriesPerSession: number;
65
+ /**
66
+ * Per-session charge in UTF-16 code units: originals + tokens + the session
67
+ * identity + ENTRY_OVERHEAD_UNITS per entry. 2 bytes/unit ⇒ 2,097,152 units
68
+ * ≈ 4 MiB. A conservative accounting bound, not an actual-JS-RSS guarantee.
69
+ */
70
+ maxSessionUnits: number;
71
+ /** Aggregate mapping entries across all sessions of THIS service instance. Default 65536. */
72
+ maxEntriesTotal: number;
73
+ /**
74
+ * Aggregate UTF-16-unit charge across all sessions (16,777,216 ≈ 32 MiB at
75
+ * 2 bytes/unit). Per service instance only — not a claim about every
76
+ * possible instance or process RSS.
77
+ */
78
+ maxUnitsTotal: number;
79
+ /** Maximum strict-JSON nesting depth per operation. Default 32. */
80
+ maxDepth: number;
81
+ /** Maximum visited value nodes per JSON operation. Default 10000. */
82
+ maxNodes: number;
83
+ /**
84
+ * Combined input+output UTF-16-unit budget per operation (text and JSON),
85
+ * bounding traversal and restored/output growth. Default 1 Mi units.
86
+ */
87
+ maxUnitsPerOperation: number;
88
+ }
89
+ /** Persisted-mapping seed for `seedSession` (W2/B3). */
90
+ export interface SessionSeed {
91
+ /** The session's original 32-hex epoch (v1-era sessions keep theirs). */
92
+ epoch: string;
93
+ entries: ReadonlyArray<{
94
+ token: string;
95
+ original: string;
96
+ }>;
97
+ }
98
+ export interface PseudonymizerService {
99
+ isTextSafe(text: string): boolean;
100
+ /**
101
+ * Session-aware safety check for structural positions (identifiers,
102
+ * transport metadata). Marker-shaped content is never unsafe per se:
103
+ * registered markers are exempt from interior scanning; unregistered
104
+ * payloads scan as ordinary text. Unsafe only on a scanner finding (the
105
+ * position cannot be masked or renamed) or a scanning failure.
106
+ */
107
+ isStructuralIdentifierSafe(sessionId: string, text: string): boolean;
108
+ /**
109
+ * Rebuilds a session from persisted mappings (W2/B3, decision
110
+ * 2026-10-07-db-over-t2). All-or-nothing: on any failure the registry is
111
+ * untouched. Tokens must match a reserved shape exactly (either version —
112
+ * v1 seeds keep restoring pre-upgrade mappings); originals are exact
113
+ * strings. Budgets mirror live staging. Seeding an existing session or a
114
+ * duplicate epoch fails; callers clear first when they mean replace.
115
+ */
116
+ seedSession(sessionId: string, seed: SessionSeed): {
117
+ ok: true;
118
+ } | PseudonymFailure;
119
+ protectText(sessionId: string, text: string): PseudonymTextResult;
120
+ protectTextForModel(sessionId: string, text: string): PseudonymTextResult;
121
+ restoreText(sessionId: string, text: string): PseudonymTextResult;
122
+ restoreTextForDisplay(sessionId: string, text: string): PseudonymTextResult;
123
+ protectJson(sessionId: string, value: unknown): PseudonymJsonResult;
124
+ protectJsonForModel(sessionId: string, value: unknown): PseudonymJsonResult;
125
+ restoreJson(sessionId: string, value: unknown): PseudonymJsonResult;
126
+ /** Drops one session's mappings and releases its budgets. Safe if absent. */
127
+ clearSession(sessionId: string): void;
128
+ /** Read-only: whether this session currently holds committed mappings. */
129
+ hasSession(sessionId: string): boolean;
130
+ /**
131
+ * Read-only committed-mapping snapshot for persistence (W2/B4). Null when
132
+ * the session is absent. The epoch is included so a hydrated process can
133
+ * re-register it with identical uniqueness semantics.
134
+ */
135
+ exportSession(sessionId: string): SessionSeed | null;
136
+ }
137
+ export type CreatePseudonymizerResult = ({
138
+ ok: true;
139
+ } & PseudonymizerService) | {
140
+ ok: false;
141
+ reason: "STATIC_CODE";
142
+ };
143
+ /**
144
+ * Reserved, recognizable token namespace — two versions.
145
+ *
146
+ * v1 (legacy, still recognized for restoration of pre-upgrade mappings):
147
+ * `[SGP1:<32 lowercase hex epoch>-<zero-padded counter>]`, e.g.
148
+ * `[SGP1:0f1e...-00000001]`.
149
+ *
150
+ * v2 (minted since W1, 2026-10-07): `[SGP2:<CATEGORY>-<seg>-<seg>-<seg>]`,
151
+ * e.g. `[SGP2:PII_EMAIL-wxyz-abcd-efgh]`. CATEGORY is the scanner
152
+ * FindingType label (closed enum, `[A-Z][A-Z_]*`); each segment is 4
153
+ * lowercase letters. Design constraints (decision doc W1 / T3):
154
+ * - letter-only payload ⇒ zero digit runs (phone/card/IBAN/TW-ID families
155
+ * cannot match), ≤4-char hex-like runs (hex detector needs far longer);
156
+ * - `-` after the category (not `:`) so the generic-secret keyword shape
157
+ * `secret\s*[:=]\s*value` cannot self-collide with `SECRET-…` labels;
158
+ * - payload alphabet shares no shell metacharacter, like v1.
159
+ * Any occurrence of either prefix in any scanned or restored string is
160
+ * validated strictly against its version's shape; unknown shapes fail the
161
+ * operation.
162
+ */
163
+ export declare const PSEUDONYM_TOKEN_PREFIX = "[SGP1:";
164
+ export declare const PSEUDONYM_TOKEN_PREFIX_V2 = "[SGP2:";
165
+ /** All reserved token prefixes, both versions. */
166
+ export declare const PSEUDONYM_TOKEN_PREFIXES: readonly string[];
167
+ /** True when `text` contains any reserved token prefix (either version). */
168
+ export declare function containsTokenPrefix(text: string): boolean;
169
+ /**
170
+ * Creates a synchronous, in-memory pseudonymizer service. The factory itself
171
+ * only fails on statically invalid arguments (malformed config or limits) with
172
+ * the single static reason "STATIC_CODE"; per-operation failures use their own
173
+ * static reasons. The result spreads the service methods, so no `this` binding
174
+ * is required.
175
+ */
176
+ export declare function createPseudonymizer(config: GuardConfig, limits?: Partial<PseudonymLimits>): CreatePseudonymizerResult;
@@ -0,0 +1,56 @@
1
+ /**
2
+ * Redaction helpers — deterministic replacement of sensitive spans
3
+ * and safe preview generation.
4
+ *
5
+ * Internal match metadata (match_start, match_end, match_text) is used
6
+ * for replacement but MUST NOT be exposed via transport-facing outputs.
7
+ */
8
+ import type { Finding, GuardConfig, ScanResult, RedactResult } from "../types.js";
9
+ /** Keys that are internal-only and must never appear in transport-facing outputs. */
10
+ declare const INTERNAL_FINDING_KEYS: readonly ["match_start", "match_end", "match_text"];
11
+ type InternalFindingKey = (typeof INTERNAL_FINDING_KEYS)[number];
12
+ /** A finding with internal metadata stripped — safe for transport serialization. */
13
+ export type TransportSafeFinding = Omit<Finding, InternalFindingKey>;
14
+ /** A ScanResult with transport-safe findings. */
15
+ export interface TransportSafeScanResult extends Omit<ScanResult, "findings"> {
16
+ findings: TransportSafeFinding[];
17
+ }
18
+ /** A RedactResult with transport-safe findings. */
19
+ export interface TransportSafeRedactResult extends Omit<RedactResult, "findings"> {
20
+ findings: TransportSafeFinding[];
21
+ }
22
+ /**
23
+ * Strip internal match metadata from a single finding.
24
+ * The returned object is safe to serialize to transport consumers.
25
+ */
26
+ export declare function sanitizeFindingForExport(f: Finding): TransportSafeFinding;
27
+ /**
28
+ * Strip internal match metadata from an array of findings.
29
+ */
30
+ export declare function sanitizeFindingsForExport(findings: readonly Finding[]): TransportSafeFinding[];
31
+ /**
32
+ * Produce a transport-safe copy of a ScanResult by stripping internal
33
+ * match metadata from every finding.
34
+ */
35
+ export declare function sanitizeScanResultForExport(result: ScanResult): TransportSafeScanResult;
36
+ /**
37
+ * Produce a transport-safe copy of a RedactResult by stripping internal
38
+ * match metadata from every finding.
39
+ */
40
+ export declare function sanitizeRedactResultForExport(result: RedactResult): TransportSafeRedactResult;
41
+ /**
42
+ * Build a safe preview of the original content.
43
+ *
44
+ * Returns a masked excerpt centered around the first finding,
45
+ * respecting `preview_length` from config (default 60).
46
+ * Returns undefined when no findings or no match metadata is available.
47
+ */
48
+ export declare function buildSafePreview(originalContent: string, findings: readonly Finding[], config?: GuardConfig): string | undefined;
49
+ /**
50
+ * Build a fully redacted version of the original content.
51
+ *
52
+ * Replaces all sensitive spans with semantic placeholders.
53
+ * Returns undefined when no findings or match metadata is missing.
54
+ */
55
+ export declare function buildRedactedContent(originalContent: string, findings: readonly Finding[], _config?: GuardConfig): string | undefined;
56
+ export {};
@@ -0,0 +1,23 @@
1
+ /**
2
+ * Structural-string collection for JSON Schema subtrees, shared by the
3
+ * session-layer request guard (src/core/session-guard.ts) and the wire-layer
4
+ * remaskers (src/core/wire.ts) so the pre-mask safety check
5
+ * and the post-mask identity comparison can never drift apart.
6
+ *
7
+ * Structural identifiers (tool names, property keys, enum/const values, regex
8
+ * patterns) must survive masking verbatim: a sensitive or token-bearing one
9
+ * refuses the whole request rather than being silently renamed. Schema
10
+ * ANNOTATION values (`description`, `title` — human prose a provider never
11
+ * dispatches on) are deliberately NOT structural: they are protected as
12
+ * ordinary content leaves, so a scanner hit inside a tool-schema description
13
+ * masks to a pseudonym token instead of failing the request. Fail-closed is
14
+ * unchanged for every identifier position.
15
+ */
16
+ /** JSON Schema annotation keywords whose VALUES are prose, not identifiers. */
17
+ export declare const SCHEMA_ANNOTATION_KEYS: ReadonlySet<string>;
18
+ /**
19
+ * Keys and identifier values of a schema/metadata subtree, in stable walk
20
+ * order. Annotation-key VALUES are skipped (the key itself is still pushed so
21
+ * both sides of the before/after comparison see the same collection).
22
+ */
23
+ export declare function walkSchemaStrings(out: string[], value: unknown): void;
@@ -1,7 +1,7 @@
1
1
  /**
2
2
  * Structural-string collection for JSON Schema subtrees, shared by the
3
- * session-layer request guard (src/opencode-transparent.ts) and the wire-layer
4
- * remaskers (src/opencode-transparent-http.ts) so the pre-mask safety check
3
+ * session-layer request guard (src/core/session-guard.ts) and the wire-layer
4
+ * remaskers (src/core/wire.ts) so the pre-mask safety check
5
5
  * and the post-mask identity comparison can never drift apart.
6
6
  *
7
7
  * Structural identifiers (tool names, property keys, enum/const values, regex
@@ -0,0 +1,39 @@
1
+ /**
2
+ * Exact-value search for the masking path: every occurrence of a set of
3
+ * detected values in one string, overlapping occurrences included.
4
+ *
5
+ * Searching each value with indexOf costs (values × text length), which is
6
+ * what limited how large a string the model path could afford. An Aho-Corasick
7
+ * automaton over UTF-16 code units costs (total value length + text length),
8
+ * plus the occurrences visited, but building one costs far more than a few
9
+ * indexOf calls and the value set can grow with every string of a request. So
10
+ * indexOf stays for small searches and the automaton takes over when the
11
+ * estimate favours it. Both strategies yield the same occurrences in the same
12
+ * order; tests/value-search.test.ts holds them to that.
13
+ */
14
+ export type ValueSearchStrategy = "auto" | "indexOf" | "automaton";
15
+ /**
16
+ * Called for an occurrence of `value` at [start, end). Return true when the
17
+ * occurrence was taken. That promises every occurrence overlapping it would be
18
+ * rejected, so the search may skip those.
19
+ */
20
+ export type OccurrenceVisitor = (start: number, end: number, value: string) => boolean;
21
+ export interface ValueSearch {
22
+ /** Number of distinct values the caller supplied, for detecting staleness. */
23
+ readonly sourceSize: number;
24
+ /**
25
+ * Visits occurrences longest value first, ties in input order, and each
26
+ * value's occurrences in ascending position.
27
+ */
28
+ visitOccurrences(text: string, visit: OccurrenceVisitor): void;
29
+ /**
30
+ * True when every occurrence of every value lies inside one of `spans`, which
31
+ * must be ascending and disjoint. Spans out of order can only make this return
32
+ * false, never true.
33
+ */
34
+ everyOccurrenceCovered(text: string, spans: readonly {
35
+ start: number;
36
+ end: number;
37
+ }[]): boolean;
38
+ }
39
+ export declare function createValueSearch(source: Iterable<string>, sourceSize: number, strategy?: ValueSearchStrategy): ValueSearch;