leakshield 0.3.1 → 0.5.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +144 -546
- package/README.zh-TW.md +143 -520
- package/dist/adapters/claude-code/capabilities.d.ts +14 -0
- package/dist/adapters/claude-code/capabilities.js +47 -0
- package/dist/adapters/claude-code/cli.d.ts +10 -0
- package/dist/adapters/claude-code/cli.js +51 -0
- package/dist/adapters/claude-code/doctor.d.ts +19 -0
- package/dist/adapters/claude-code/doctor.js +177 -0
- package/dist/adapters/claude-code/proxy.d.ts +47 -0
- package/dist/adapters/claude-code/proxy.js +348 -0
- package/dist/adapters/opencode/capabilities.d.ts +10 -0
- package/dist/adapters/opencode/capabilities.js +48 -0
- package/dist/adapters/opencode/doctor.d.ts +67 -0
- package/dist/{doctor.js → adapters/opencode/doctor.js} +26 -44
- package/dist/adapters/opencode/env-queries.d.ts +133 -0
- package/dist/adapters/opencode/env-tools.d.ts +20 -0
- package/dist/adapters/opencode/hooks.d.ts +4 -0
- package/dist/adapters/opencode/plugin.d.ts +12 -0
- package/dist/{opencode.js → adapters/opencode/plugin.js} +43 -14
- package/dist/adapters/opencode/tool-policy.d.ts +2 -0
- package/dist/adapters/opencode/tool-policy.js +23 -0
- package/dist/adapters/opencode/transparent-aisdk.d.ts +6 -0
- package/dist/{opencode-transparent-aisdk.js → adapters/opencode/transparent-aisdk.js} +1 -1
- package/dist/adapters/opencode/transparent.d.ts +70 -0
- package/dist/adapters/opencode/transparent.js +242 -0
- package/dist/adapters/opencode/v2.d.ts +23 -0
- package/dist/{opencode-v2.js → adapters/opencode/v2.js} +13 -8
- package/dist/adapters/pi/capabilities.d.ts +10 -0
- package/dist/adapters/pi/capabilities.js +50 -0
- package/dist/adapters/pi/doctor.d.ts +26 -0
- package/dist/adapters/pi/doctor.js +276 -0
- package/dist/adapters/pi/extension.d.ts +28 -0
- package/dist/adapters/pi/extension.js +109 -0
- package/dist/adapters/pi/guard.d.ts +33 -0
- package/dist/adapters/pi/guard.js +154 -0
- package/dist/adapters/pi/persistence.d.ts +9 -0
- package/dist/adapters/pi/persistence.js +69 -0
- package/dist/adapters/pi/settings.d.ts +51 -0
- package/dist/adapters/pi/settings.js +136 -0
- package/dist/adapters/pi/tool-policy.d.ts +11 -0
- package/dist/adapters/pi/tool-policy.js +114 -0
- package/dist/cli.d.ts +18 -0
- package/dist/cli.js +17 -6
- package/dist/config/loader.d.ts +70 -0
- package/dist/config/loader.js +8 -0
- package/dist/config/plain-object.d.ts +2 -0
- package/dist/core/index.d.ts +9 -0
- package/dist/core/index.js +9 -0
- package/dist/core/session-guard.d.ts +62 -0
- package/dist/{opencode-transparent.js → core/session-guard.js} +56 -713
- package/dist/core/sse-recovery.d.ts +6 -0
- package/dist/core/tool-restore-policy.d.ts +153 -0
- package/dist/core/tool-restore-policy.js +453 -0
- package/dist/core/wire.d.ts +213 -0
- package/dist/{opencode-transparent-http.js → core/wire.js} +125 -42
- package/dist/core/ws.d.ts +26 -0
- package/dist/{opencode-transparent-ws.js → core/ws.js} +1 -1
- package/dist/decision/deidentify.d.ts +63 -0
- package/dist/decision/ingress.d.ts +40 -0
- package/dist/decision/mapping-key.d.ts +91 -0
- package/dist/decision/mapping-store.d.ts +166 -0
- package/dist/decision/model.d.ts +41 -0
- package/dist/decision/pseudonymization.d.ts +176 -0
- package/dist/decision/redaction.d.ts +56 -0
- package/dist/decision/redaction.js +3 -0
- package/dist/decision/schema-strings.d.ts +23 -0
- package/dist/decision/schema-strings.js +2 -2
- package/dist/decision/value-search.d.ts +39 -0
- package/dist/doctor-capabilities.d.ts +21 -0
- package/dist/doctor-capabilities.js +58 -0
- package/dist/doctor-hosts.d.ts +18 -0
- package/dist/doctor-hosts.js +144 -0
- package/dist/doctor-report.d.ts +45 -0
- package/dist/doctor-report.js +111 -0
- package/dist/forget.d.ts +18 -0
- package/dist/guard-options.d.ts +45 -0
- package/dist/{plugin-options.js → guard-options.js} +8 -6
- package/dist/help.d.ts +2 -0
- package/dist/help.js +15 -1
- package/dist/i18n/en.d.ts +65 -0
- package/dist/i18n/index.d.ts +15 -0
- package/dist/i18n/zh-TW.d.ts +65 -0
- package/dist/index.d.ts +13 -0
- package/dist/index.js +1 -1
- package/dist/rules/builtin.d.ts +4 -0
- package/dist/rules/builtin.js +75 -2
- package/dist/rules/dynamic.d.ts +33 -0
- package/dist/scanner/allowlist.d.ts +22 -0
- package/dist/scanner/cidr.d.ts +39 -0
- package/dist/scanner/encoding.d.ts +87 -0
- package/dist/scanner/engine.d.ts +43 -0
- package/dist/scanner/exact-values.d.ts +11 -0
- package/dist/scanner/redaction-verifier.d.ts +24 -0
- package/dist/scanner/remotes.d.ts +29 -0
- package/dist/scanner/unicode.d.ts +57 -0
- package/dist/scanner/utils.d.ts +22 -0
- package/dist/transports/cli.d.ts +27 -0
- package/dist/transports/web-ui.d.ts +1 -0
- package/dist/transports/web-ui.js +1 -1
- package/dist/transports/web.d.ts +4 -0
- package/dist/types/capabilities.d.ts +67 -0
- package/dist/types/capabilities.js +133 -0
- package/dist/types.d.ts +149 -0
- package/dist/types.js +3 -0
- package/dist/utils/files.d.ts +3 -0
- package/dist/utils/path-security.d.ts +18 -0
- package/dist/utils/win-encoding.d.ts +16 -0
- package/package.json +15 -3
- /package/dist/{env-queries.js → adapters/opencode/env-queries.js} +0 -0
- /package/dist/{opencode-env-tools.js → adapters/opencode/env-tools.js} +0 -0
- /package/dist/{opencode-hooks.js → adapters/opencode/hooks.js} +0 -0
- /package/dist/{opencode-transparent-stream.js → core/sse-recovery.js} +0 -0
|
@@ -0,0 +1,213 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Transport-boundary helpers for OpenCode v2 transparent pseudonymization
|
|
3
|
+
* (issue #22; protocol selection is not provider-brand selection).
|
|
4
|
+
*
|
|
5
|
+
* Source-verified against the installed @opencode/plugin 2.0.19 declarations:
|
|
6
|
+
* `session:http.request` / `session:http.response` expose native `Request` /
|
|
7
|
+
* `Response` objects whose bodies are one-shot streams (clone before reading).
|
|
8
|
+
* Supported wire protocols are the three custom-provider dialects — OpenAI
|
|
9
|
+
* Chat Completions, Anthropic Messages and OpenAI Responses — selected by URL
|
|
10
|
+
* path shape; each has JSON / event-stream response restore.
|
|
11
|
+
*
|
|
12
|
+
* Outbound enforcement and ingress restoration:
|
|
13
|
+
* - Final-wire masking refuses unsupported routes, mixed dialects and
|
|
14
|
+
* bodyless requests. Explicit false admission may accept an unknown route
|
|
15
|
+
* with scoped host preparation proof; its opaque body is not inspected.
|
|
16
|
+
* A placeholder in transport metadata or the URL is judged
|
|
17
|
+
* session-aware instead: clean markers are preserved verbatim with a
|
|
18
|
+
* content-free WARN; sensitive content still refuses (unmaskable
|
|
19
|
+
* position).
|
|
20
|
+
* - Transport metadata is inspected: decoded non-auth headers and query
|
|
21
|
+
* parameters, and numeric body values, must not scan as sensitive;
|
|
22
|
+
* legitimate authentication headers are preserved.
|
|
23
|
+
* - The whole body is validated BEFORE any token is issued, then protected in
|
|
24
|
+
* ONE atomic transaction, so a rejected request commits no mapping or
|
|
25
|
+
* session capacity.
|
|
26
|
+
* - Protocol metadata (model ids, tools, usage, numeric fields, envelopes) is
|
|
27
|
+
* never rewritten: structural identifiers (message ids, roles, part types,
|
|
28
|
+
* tool names and schema keys/enum constraints) are preserved and a
|
|
29
|
+
* sensitive one refuses the request rather than being silently renamed.
|
|
30
|
+
* - Response restore touches assistant display text only: owned tokens are
|
|
31
|
+
* restored and unknown/malformed marker strings remain literal there. A
|
|
32
|
+
* placeholder in an unplaceable response field is degradation — kept
|
|
33
|
+
* literal with a WARN — never a refusal; actual tool arguments remain
|
|
34
|
+
* tokenized for the typed tool gate.
|
|
35
|
+
* - Streaming is pull-based with bounded original-event transactions and
|
|
36
|
+
* channel state. SG parser/restore failures replay undelivered originals,
|
|
37
|
+
* then bypass rewriting; source errors and cancellation remain failures.
|
|
38
|
+
* Non-stream restoration failures are recovered by the session hook.
|
|
39
|
+
*/
|
|
40
|
+
import { type PseudonymJsonResult, type PseudonymTextResult } from "../decision/pseudonymization.js";
|
|
41
|
+
/** The masking/detection subset of the pseudonymization core this module needs. */
|
|
42
|
+
export interface TransportMaskingService {
|
|
43
|
+
protectJsonForModel(sessionID: string, value: unknown): PseudonymJsonResult;
|
|
44
|
+
restoreText(sessionID: string, text: string): PseudonymTextResult;
|
|
45
|
+
restoreTextForDisplay(sessionID: string, text: string): PseudonymTextResult;
|
|
46
|
+
/** Non-committing sensitivity detection: no mapping, no mutation. */
|
|
47
|
+
detectSensitive(text: string): boolean;
|
|
48
|
+
/**
|
|
49
|
+
* Session-aware judgement for structural positions (identifiers, transport
|
|
50
|
+
* metadata): marker-shaped content is safe when clean (registered-marker
|
|
51
|
+
* interiors exempt, unregistered payloads scanned); unsafe on a finding,
|
|
52
|
+
* because the position cannot be masked without breaking the protocol.
|
|
53
|
+
*/
|
|
54
|
+
isStructuralIdentifierSafe(sessionID: string, text: string): boolean;
|
|
55
|
+
/**
|
|
56
|
+
* Field-aware transport variants: identical to the strict checks except
|
|
57
|
+
* that PII_URL findings are exempt. The request URL, query values, and
|
|
58
|
+
* header values are infrastructure positions — masking or refusing an
|
|
59
|
+
* endpoint URL would break every request once the opt-in URL rule is
|
|
60
|
+
* enabled, so URL findings are ignored there. User-content URLs inside
|
|
61
|
+
* the request body are unaffected (still masked).
|
|
62
|
+
*/
|
|
63
|
+
transportDetectSensitive(text: string): boolean;
|
|
64
|
+
/** Transport variant of {@link isStructuralIdentifierSafe} (PII_URL exempt). */
|
|
65
|
+
isTransportIdentifierSafe(sessionID: string, text: string): boolean;
|
|
66
|
+
/**
|
|
67
|
+
* Attachment policy: "block" (default) refuses media/file parts at the
|
|
68
|
+
* wire; "allow" tolerates them as opaque leaves that are substituted with a
|
|
69
|
+
* sentinel around the masking transaction and restored verbatim after it,
|
|
70
|
+
* so binary payloads are neither scanned nor altered.
|
|
71
|
+
*/
|
|
72
|
+
readonly attachmentsPolicy?: "block" | "allow";
|
|
73
|
+
/**
|
|
74
|
+
* Anthropic extended-thinking history blocks. "refuse" (default) keeps the
|
|
75
|
+
* original contract: any `thinking` / `redacted_thinking` block refuses the
|
|
76
|
+
* request. "mask" accepts them: thinking text is masked like other text,
|
|
77
|
+
* while `signature` and `redacted_thinking.data` cross verbatim as opaque
|
|
78
|
+
* provider state (never scanned, never altered).
|
|
79
|
+
*/
|
|
80
|
+
readonly anthropicThinking?: "refuse" | "mask";
|
|
81
|
+
}
|
|
82
|
+
/** Wire routes this module can protect, detected by URL PATH SHAPE — never by
|
|
83
|
+
* provider or model name, so any endpoint speaking a supported dialect
|
|
84
|
+
* (OpenAI-compatible gateways, Anthropic-native, …) is covered uniformly. */
|
|
85
|
+
export type ModelWireRoute = "chat-completions" | "anthropic-messages" | "openai-responses";
|
|
86
|
+
export declare function classifyModelRoute(url: string): ModelWireRoute | null;
|
|
87
|
+
/**
|
|
88
|
+
* In "allow" mode, temporarily substitutes every media/file record with a
|
|
89
|
+
* unique sentinel string around the masking transaction, then restores the
|
|
90
|
+
* originals into the protected result: binary payloads are neither scanned
|
|
91
|
+
* nor altered, and the structural checks outside this wrapper see identical
|
|
92
|
+
* attachment records before and after. Shared by the wire remaskers and the
|
|
93
|
+
* session-layer request guard so "allow means unscanned" holds at both
|
|
94
|
+
* boundaries.
|
|
95
|
+
*/
|
|
96
|
+
export declare function withOpaqueAttachments<T extends Record<string, unknown>>(policy: "block" | "allow", body: T, fn: (input: T) => T): T;
|
|
97
|
+
/**
|
|
98
|
+
* Remasks an OpenAI-compatible Chat Completions JSON request body.
|
|
99
|
+
*
|
|
100
|
+
* Every check that can reject runs FIRST (route, transport metadata, dialect,
|
|
101
|
+
* message shapes, structural identifiers, numeric values); only then is the
|
|
102
|
+
* whole body protected in a SINGLE transaction, so a rejected request commits
|
|
103
|
+
* no mapping or session capacity. The original request is consumed only through
|
|
104
|
+
* `clone()`; the ORIGINAL request object is returned only when its body already
|
|
105
|
+
* is the canonical serialization of what was scanned. A rebuilt request inherits every transport control (method, url,
|
|
106
|
+
* mode, credentials, cache, redirect, referrer, integrity, keepalive, signal,
|
|
107
|
+
* authentication headers) and recomputes body headers.
|
|
108
|
+
*/
|
|
109
|
+
export declare function remaskChatCompletionsRequest(service: TransportMaskingService, sessionID: string, request: Request): Promise<Request>;
|
|
110
|
+
/**
|
|
111
|
+
* Remasks an Anthropic Messages JSON request body. Same contract as the
|
|
112
|
+
* chat-completions path: every check that can reject runs FIRST, then the
|
|
113
|
+
* whole body is protected in ONE transaction; a rejected request commits no
|
|
114
|
+
* mapping or session capacity. tool_use.input is already a JSON object (no
|
|
115
|
+
* string re-encoding needed) and stays tokenized on the wire; the typed tool
|
|
116
|
+
* gate restores before execution.
|
|
117
|
+
*/
|
|
118
|
+
export declare function remaskAnthropicMessagesRequest(service: TransportMaskingService, sessionID: string, request: Request): Promise<Request>;
|
|
119
|
+
/**
|
|
120
|
+
* Remasks an OpenAI Responses JSON request body. Same contract as the other
|
|
121
|
+
* dialects: reject-first validation, ONE atomic transaction, structural
|
|
122
|
+
* identifiers preserved. function_call.arguments is a JSON-encoded string and
|
|
123
|
+
* is parsed before masking and re-encoded after (same rule as chat
|
|
124
|
+
* completions tool arguments).
|
|
125
|
+
*/
|
|
126
|
+
export declare function remaskResponsesRequest(service: TransportMaskingService, sessionID: string, request: Request): Promise<Request>;
|
|
127
|
+
/** Hook-first admission: check the supported response route and transport
|
|
128
|
+
* metadata without reading, validating, or changing the final request body.
|
|
129
|
+
* Returning the same Request preserves identity for response attribution. */
|
|
130
|
+
export declare function admitModelRequest(service: TransportMaskingService, sessionID: string, request: Request, allowHookOnly?: boolean): Request;
|
|
131
|
+
/** Protocol dispatcher: masks any supported wire route by URL shape. */
|
|
132
|
+
export declare function remaskModelRequest(service: TransportMaskingService, sessionID: string, request: Request): Promise<Request>;
|
|
133
|
+
/**
|
|
134
|
+
* Restores assistant display text in a model response. Error bodies and
|
|
135
|
+
* unsupported content types are passed through only when a bounded clone-read
|
|
136
|
+
* proves they carry no reserved token this module cannot restore; otherwise
|
|
137
|
+
* the response fails closed.
|
|
138
|
+
*/
|
|
139
|
+
export declare function restoreChatCompletionsResponse(service: TransportMaskingService, sessionID: string, response: Response): Promise<Response>;
|
|
140
|
+
export declare function restoreDisplayText(service: TransportMaskingService, sessionID: string, text: string): string;
|
|
141
|
+
/**
|
|
142
|
+
* Splits `buffered` into the portion safe to restore now and any incomplete
|
|
143
|
+
* token candidate that must be held back until more stream data arrives. A
|
|
144
|
+
* held tail is either a partial token from its LAST full prefix (either
|
|
145
|
+
* version), or the longest suffix that is a proper prefix of a reserved
|
|
146
|
+
* namespace prefix (e.g. `[SG`, `[SGP2`): emitting that suffix literally
|
|
147
|
+
* would make the token unrestorable. Complete tokens in the emit portion are
|
|
148
|
+
* restored by the caller through the core; a tail that never completes
|
|
149
|
+
* degrades to a literal emit with a WARN at the terminal boundary
|
|
150
|
+
* (P1, 2026-10-06b).
|
|
151
|
+
*/
|
|
152
|
+
export declare function splitRestorable(buffered: string): {
|
|
153
|
+
emit: string;
|
|
154
|
+
hold: string;
|
|
155
|
+
};
|
|
156
|
+
/**
|
|
157
|
+
* Incremental SSE restore. UTF-8 is decoded streaming (code points may split
|
|
158
|
+
* across chunks), complete events are assembled from their `data:` lines as
|
|
159
|
+
* they terminate (a blank line), and each choice's `delta.content` channel
|
|
160
|
+
* keeps a token-prefix hold buffer so tokens split across chunks AND events
|
|
161
|
+
* are restored exactly once, in order.
|
|
162
|
+
*
|
|
163
|
+
* Bounds are explicit, measured in UTF-8 bytes and fail closed: the pending
|
|
164
|
+
* line buffer, the accumulated (unterminated) event, each choice channel, the
|
|
165
|
+
* aggregate channel state and the channel count are all capped, each charged
|
|
166
|
+
* before the value is accumulated. A choice whose token is still unresolved
|
|
167
|
+
* at a terminal `finish_reason` degrades — the held tail is emitted literally
|
|
168
|
+
* with a WARN — and a choice that keeps producing output after it is terminal
|
|
169
|
+
* refuses. Reading is pull-based: one
|
|
170
|
+
* bounded batch of upstream data is consumed per downstream pull, so an unread
|
|
171
|
+
* consumer never builds an unbounded downstream queue. Errors from the
|
|
172
|
+
* underlying stream propagate and downstream cancellation cancels its reader.
|
|
173
|
+
* SG parse/restore failures instead replay undelivered originals and bypass
|
|
174
|
+
* further rewriting; they never cancel a healthy upstream response.
|
|
175
|
+
*/
|
|
176
|
+
export declare function createSseRestoreStream(service: TransportMaskingService, sessionID: string, body: ReadableStream<Uint8Array>): ReadableStream<Uint8Array>;
|
|
177
|
+
/**
|
|
178
|
+
* Restores an Anthropic Messages SSE stream. Channel hold buffers are keyed by
|
|
179
|
+
* content-block index (tokens may split across content_block_delta events);
|
|
180
|
+
* content_block_stop requires an empty channel and marks the index terminal;
|
|
181
|
+
* message_stop requires every channel drained. input_json_delta is
|
|
182
|
+
* deliberately untouched (tool arguments restore at the typed tool gate). All
|
|
183
|
+
* framing/byte caps mirror the chat-completions stream.
|
|
184
|
+
*/
|
|
185
|
+
export declare function createAnthropicSseRestoreStream(service: TransportMaskingService, sessionID: string, body: ReadableStream<Uint8Array>): ReadableStream<Uint8Array>;
|
|
186
|
+
/**
|
|
187
|
+
* Restores assistant display text in an Anthropic Messages response. Error
|
|
188
|
+
* bodies and unsupported content types pass through only when provably free
|
|
189
|
+
* of reserved tokens; otherwise the response fails closed.
|
|
190
|
+
*/
|
|
191
|
+
export declare function restoreAnthropicMessagesResponse(service: TransportMaskingService, sessionID: string, response: Response): Promise<Response>;
|
|
192
|
+
/** Protocol dispatcher: restores a response using the SAME wire route the
|
|
193
|
+
* masked request used (classified by request URL shape). */
|
|
194
|
+
export declare function restoreModelResponse(service: TransportMaskingService, sessionID: string, request: Request, response: Response): Promise<Response>;
|
|
195
|
+
export declare const RESPONSES_TEXT_DELTA_TYPES: ReadonlySet<string>;
|
|
196
|
+
export declare const RESPONSES_TEXT_DONE_TYPES: ReadonlySet<string>;
|
|
197
|
+
/** Restore complete display fields of one Responses event (HTTP/WS share
|
|
198
|
+
* the same part/item semantics). Delta buffering belongs to the transport;
|
|
199
|
+
* function-call arguments and provider state are never restored here. */
|
|
200
|
+
export declare function restoreResponsesEventDisplay(service: TransportMaskingService, sessionID: string, chunk: Record<string, unknown>): void;
|
|
201
|
+
/**
|
|
202
|
+
* Restores an OpenAI Responses SSE stream. Channels are keyed by item id (or
|
|
203
|
+
* output index) for response.output_text.delta events; function_call_arguments
|
|
204
|
+
* deltas are untouched (tool gate); the terminal response.completed/failed/
|
|
205
|
+
* incomplete event requires drained channels, and no event may follow it.
|
|
206
|
+
*/
|
|
207
|
+
export declare function createResponsesSseRestoreStream(service: TransportMaskingService, sessionID: string, body: ReadableStream<Uint8Array>): ReadableStream<Uint8Array>;
|
|
208
|
+
/**
|
|
209
|
+
* Restores assistant display text in an OpenAI Responses response; error
|
|
210
|
+
* bodies and unsupported content types pass through only when provably free
|
|
211
|
+
* of reserved tokens.
|
|
212
|
+
*/
|
|
213
|
+
export declare function restoreResponsesResponse(service: TransportMaskingService, sessionID: string, response: Response): Promise<Response>;
|
|
@@ -37,9 +37,9 @@
|
|
|
37
37
|
* then bypass rewriting; source errors and cancellation remain failures.
|
|
38
38
|
* Non-stream restoration failures are recovered by the session hook.
|
|
39
39
|
*/
|
|
40
|
-
import { containsTokenPrefix, PSEUDONYM_TOKEN_PREFIXES, } from "
|
|
41
|
-
import { walkSchemaStrings } from "
|
|
42
|
-
import { createRecoveringSseStream } from "./
|
|
40
|
+
import { containsTokenPrefix, PSEUDONYM_TOKEN_PREFIXES, } from "../decision/pseudonymization.js";
|
|
41
|
+
import { walkSchemaStrings } from "../decision/schema-strings.js";
|
|
42
|
+
import { createRecoveringSseStream } from "./sse-recovery.js";
|
|
43
43
|
// ─── Static failure messages (no content ever included) ─────────────────────
|
|
44
44
|
/**
|
|
45
45
|
* Content-free degradation notice for the host log (P1, 2026-10-06b): one
|
|
@@ -605,6 +605,21 @@ function collectWireStructuralStrings(body) {
|
|
|
605
605
|
walkSchemaStrings(out, body.response_format);
|
|
606
606
|
return out;
|
|
607
607
|
}
|
|
608
|
+
/** Forwards exactly the value that was scanned. The original bytes are kept
|
|
609
|
+
* only when they already are that serialization: a body that parses to
|
|
610
|
+
* something else (a duplicate key keeps only its last occurrence, invalid
|
|
611
|
+
* UTF-8 decodes to U+FFFD) would otherwise carry content the scanner never
|
|
612
|
+
* saw. Keeping the original Request otherwise preserves its identity. */
|
|
613
|
+
function forwardSerialized(request, raw, serialized) {
|
|
614
|
+
if (serialized === raw && !raw.includes("\uFFFD"))
|
|
615
|
+
return request;
|
|
616
|
+
const headers = new Headers(request.headers);
|
|
617
|
+
headers.delete("content-encoding");
|
|
618
|
+
// Let fetch frame the replacement body. An explicit length can also be
|
|
619
|
+
// rejected when Node's fetch uses a newer host-installed dispatcher.
|
|
620
|
+
headers.delete("content-length");
|
|
621
|
+
return new Request(request, { body: serialized, headers });
|
|
622
|
+
}
|
|
608
623
|
/**
|
|
609
624
|
* Remasks an OpenAI-compatible Chat Completions JSON request body.
|
|
610
625
|
*
|
|
@@ -612,8 +627,8 @@ function collectWireStructuralStrings(body) {
|
|
|
612
627
|
* message shapes, structural identifiers, numeric values); only then is the
|
|
613
628
|
* whole body protected in a SINGLE transaction, so a rejected request commits
|
|
614
629
|
* no mapping or session capacity. The original request is consumed only through
|
|
615
|
-
* `clone()
|
|
616
|
-
*
|
|
630
|
+
* `clone()`; the ORIGINAL request object is returned only when its body already
|
|
631
|
+
* is the canonical serialization of what was scanned. A rebuilt request inherits every transport control (method, url,
|
|
617
632
|
* mode, credentials, cache, redirect, referrer, integrity, keepalive, signal,
|
|
618
633
|
* authentication headers) and recomputes body headers.
|
|
619
634
|
*/
|
|
@@ -647,9 +662,6 @@ export async function remaskChatCompletionsRequest(service, sessionID, request)
|
|
|
647
662
|
throw new Error(refusal("body-shape"));
|
|
648
663
|
validateDialect(body);
|
|
649
664
|
validateMessages(body, attachmentsAllowed(service));
|
|
650
|
-
// Capture the original wire shape BEFORE transforming tool arguments, so a
|
|
651
|
-
// no-op protection still returns the ORIGINAL request untouched.
|
|
652
|
-
const originalSerialized = JSON.stringify(body);
|
|
653
665
|
// Tool arguments are JSON-encoded strings. Protecting them as PARSED values
|
|
654
666
|
// (a) keeps masking from invalidating the JSON — a numeric pin matched by the
|
|
655
667
|
// phone detector would otherwise be masked mid-token, producing invalid JSON
|
|
@@ -743,19 +755,15 @@ export async function remaskChatCompletionsRequest(service, sessionID, request)
|
|
|
743
755
|
}
|
|
744
756
|
}
|
|
745
757
|
const serialized = JSON.stringify(next);
|
|
746
|
-
|
|
747
|
-
return request;
|
|
748
|
-
const headers = new Headers(request.headers);
|
|
749
|
-
headers.delete("content-encoding");
|
|
750
|
-
headers.set("content-length", String(byteLength(serialized)));
|
|
751
|
-
return new Request(request, { body: serialized, headers });
|
|
758
|
+
return forwardSerialized(request, raw, serialized);
|
|
752
759
|
}
|
|
753
760
|
// ─── Anthropic Messages request (wire dialect) ──────────────────────────────
|
|
754
761
|
/**
|
|
755
762
|
* Validates an Anthropic Messages request body: top-level `system` (string or
|
|
756
763
|
* text blocks), `messages` with content blocks (text | tool_use |
|
|
757
|
-
* tool_result), flat `tools` ({name, description?, input_schema}). Images,
|
|
758
|
-
* documents, thinking blocks
|
|
764
|
+
* tool_result, whose parts are text or a bare tool_reference), flat `tools` ({name, description?, input_schema}). Images,
|
|
765
|
+
* documents, thinking blocks (unless the service sets anthropicThinking
|
|
766
|
+
* "mask"), and any unknown block type refuse — never pass
|
|
759
767
|
* tokenized or unscanned content through the wire boundary.
|
|
760
768
|
*/
|
|
761
769
|
function validateAnthropicSystem(system) {
|
|
@@ -769,7 +777,17 @@ function validateAnthropicSystem(system) {
|
|
|
769
777
|
}
|
|
770
778
|
}
|
|
771
779
|
}
|
|
772
|
-
|
|
780
|
+
/**
|
|
781
|
+
* A `tool_reference` part (Claude Code's ToolSearch result) names a tool and
|
|
782
|
+
* nothing else. Only that exact shape is accepted; its `tool_name` is a
|
|
783
|
+
* structural identifier, so a finding there refuses instead of being renamed.
|
|
784
|
+
*/
|
|
785
|
+
function isToolReferencePart(part) {
|
|
786
|
+
if (!isRecord(part) || part.type !== "tool_reference" || typeof part.tool_name !== "string")
|
|
787
|
+
return false;
|
|
788
|
+
return Object.keys(part).every((key) => key === "type" || key === "tool_name");
|
|
789
|
+
}
|
|
790
|
+
function validateAnthropicContent(content, allowAttachments, allowThinking = false) {
|
|
773
791
|
if (content === undefined || content === null || typeof content === "string")
|
|
774
792
|
return;
|
|
775
793
|
if (!Array.isArray(content))
|
|
@@ -779,6 +797,17 @@ function validateAnthropicContent(content, allowAttachments) {
|
|
|
779
797
|
throw new Error(refusal("anthropic-content-block"));
|
|
780
798
|
if (allowAttachments && isAttachmentRecord(block))
|
|
781
799
|
continue;
|
|
800
|
+
if (allowThinking && block.type === "thinking") {
|
|
801
|
+
if (typeof block.thinking !== "string" || (block.signature !== undefined && typeof block.signature !== "string")) {
|
|
802
|
+
throw new Error(refusal("anthropic-thinking-block"));
|
|
803
|
+
}
|
|
804
|
+
continue;
|
|
805
|
+
}
|
|
806
|
+
if (allowThinking && block.type === "redacted_thinking") {
|
|
807
|
+
if (typeof block.data !== "string")
|
|
808
|
+
throw new Error(refusal("anthropic-thinking-block"));
|
|
809
|
+
continue;
|
|
810
|
+
}
|
|
782
811
|
switch (block.type) {
|
|
783
812
|
case "text":
|
|
784
813
|
if (typeof block.text !== "string")
|
|
@@ -805,6 +834,8 @@ function validateAnthropicContent(content, allowAttachments) {
|
|
|
805
834
|
if (allowAttachments && isAttachmentRecord(part)) {
|
|
806
835
|
continue;
|
|
807
836
|
}
|
|
837
|
+
if (isToolReferencePart(part))
|
|
838
|
+
continue;
|
|
808
839
|
if (!isRecord(part) || part.type !== "text" || typeof part.text !== "string") {
|
|
809
840
|
throw new Error(refusal("anthropic-tool-result-part"));
|
|
810
841
|
}
|
|
@@ -816,7 +847,7 @@ function validateAnthropicContent(content, allowAttachments) {
|
|
|
816
847
|
}
|
|
817
848
|
}
|
|
818
849
|
}
|
|
819
|
-
function validateAnthropicDialect(body, allowAttachments) {
|
|
850
|
+
function validateAnthropicDialect(body, allowAttachments, allowThinking = false) {
|
|
820
851
|
validateAnthropicSystem(body.system);
|
|
821
852
|
if (body.tools !== undefined) {
|
|
822
853
|
if (!Array.isArray(body.tools))
|
|
@@ -835,8 +866,55 @@ function validateAnthropicDialect(body, allowAttachments) {
|
|
|
835
866
|
if (!isRecord(message) || typeof message.role !== "string") {
|
|
836
867
|
throw new Error(refusal("anthropic-message-shape"));
|
|
837
868
|
}
|
|
838
|
-
validateAnthropicContent(message.content, allowAttachments);
|
|
869
|
+
validateAnthropicContent(message.content, allowAttachments, allowThinking);
|
|
870
|
+
}
|
|
871
|
+
}
|
|
872
|
+
const OPAQUE_THINKING_SENTINEL = "__sg_opaque_thinking";
|
|
873
|
+
/**
|
|
874
|
+
* Stashes thinking `signature` and `redacted_thinking.data` strings around the
|
|
875
|
+
* masking transaction. Both are provider-verified blobs over earlier masked
|
|
876
|
+
* traffic: a false-positive detector hit inside the base64 would corrupt them
|
|
877
|
+
* and the provider would reject the whole history. Same sentinel contract as
|
|
878
|
+
* withOpaqueReasoningContent: substitute, protect, restore, verify counts.
|
|
879
|
+
*/
|
|
880
|
+
function withOpaqueThinkingState(body, fn) {
|
|
881
|
+
const opaqueField = (block) => {
|
|
882
|
+
if (block.type === "thinking" && typeof block.signature === "string")
|
|
883
|
+
return "signature";
|
|
884
|
+
if (block.type === "redacted_thinking" && typeof block.data === "string")
|
|
885
|
+
return "data";
|
|
886
|
+
return null;
|
|
887
|
+
};
|
|
888
|
+
const blocksOf = (value) => {
|
|
889
|
+
if (!Array.isArray(value.messages))
|
|
890
|
+
return [];
|
|
891
|
+
return value.messages.flatMap((message) => isRecord(message) && Array.isArray(message.content) ? message.content.filter(isRecord) : []);
|
|
892
|
+
};
|
|
893
|
+
const originals = [];
|
|
894
|
+
for (const block of blocksOf(body)) {
|
|
895
|
+
const field = opaqueField(block);
|
|
896
|
+
if (field === null)
|
|
897
|
+
continue;
|
|
898
|
+
originals.push(block[field]);
|
|
899
|
+
block[field] = `${OPAQUE_THINKING_SENTINEL}_${originals.length - 1}`;
|
|
900
|
+
}
|
|
901
|
+
if (originals.length === 0)
|
|
902
|
+
return fn(body);
|
|
903
|
+
const result = fn(body);
|
|
904
|
+
const sentinelRe = new RegExp(`^${OPAQUE_THINKING_SENTINEL}_(\\d+)$`);
|
|
905
|
+
let restored = 0;
|
|
906
|
+
for (const block of blocksOf(result)) {
|
|
907
|
+
const field = opaqueField(block);
|
|
908
|
+
if (field === null)
|
|
909
|
+
continue;
|
|
910
|
+
const match = sentinelRe.exec(block[field]);
|
|
911
|
+
if (match === null || Number(match[1]) !== restored)
|
|
912
|
+
throw new Error(MASK_FAILURE);
|
|
913
|
+
block[field] = originals[restored++];
|
|
839
914
|
}
|
|
915
|
+
if (restored !== originals.length)
|
|
916
|
+
throw new Error(MASK_FAILURE);
|
|
917
|
+
return result;
|
|
840
918
|
}
|
|
841
919
|
/** Structural identifiers that must survive masking verbatim (Anthropic shape). */
|
|
842
920
|
function collectAnthropicStructuralStrings(body) {
|
|
@@ -856,8 +934,15 @@ function collectAnthropicStructuralStrings(body) {
|
|
|
856
934
|
pushString(out, block.id);
|
|
857
935
|
pushString(out, block.name);
|
|
858
936
|
}
|
|
859
|
-
if (block.type === "tool_result")
|
|
937
|
+
if (block.type === "tool_result") {
|
|
860
938
|
pushString(out, block.tool_use_id);
|
|
939
|
+
if (Array.isArray(block.content)) {
|
|
940
|
+
for (const part of block.content) {
|
|
941
|
+
if (isToolReferencePart(part))
|
|
942
|
+
pushString(out, part.tool_name);
|
|
943
|
+
}
|
|
944
|
+
}
|
|
945
|
+
}
|
|
861
946
|
}
|
|
862
947
|
}
|
|
863
948
|
}
|
|
@@ -908,8 +993,8 @@ export async function remaskAnthropicMessagesRequest(service, sessionID, request
|
|
|
908
993
|
}
|
|
909
994
|
if (!isRecord(body))
|
|
910
995
|
throw new Error(refusal("body-shape"));
|
|
911
|
-
|
|
912
|
-
|
|
996
|
+
const allowThinking = service.anthropicThinking === "mask";
|
|
997
|
+
validateAnthropicDialect(body, attachmentsAllowed(service), allowThinking);
|
|
913
998
|
const structuralBefore = collectAnthropicStructuralStrings(body);
|
|
914
999
|
for (const identifier of structuralBefore) {
|
|
915
1000
|
if (containsTokenPrefix(identifier) || service.detectSensitive(identifier)) {
|
|
@@ -923,7 +1008,7 @@ export async function remaskAnthropicMessagesRequest(service, sessionID, request
|
|
|
923
1008
|
});
|
|
924
1009
|
if (unsafeNumber)
|
|
925
1010
|
throw new Error(refusal("number-sensitive"));
|
|
926
|
-
const
|
|
1011
|
+
const protect = (input) => {
|
|
927
1012
|
const masked = service.protectJsonForModel(sessionID, input);
|
|
928
1013
|
if (!masked.ok)
|
|
929
1014
|
throw new Error(MASK_FAILURE);
|
|
@@ -931,19 +1016,15 @@ export async function remaskAnthropicMessagesRequest(service, sessionID, request
|
|
|
931
1016
|
if (!isRecord(value))
|
|
932
1017
|
throw new Error(MASK_FAILURE);
|
|
933
1018
|
return value;
|
|
934
|
-
}
|
|
1019
|
+
};
|
|
1020
|
+
const next = withOpaqueAttachments(service.attachmentsPolicy ?? "block", body, (input) => allowThinking ? withOpaqueThinkingState(input, protect) : protect(input));
|
|
935
1021
|
const structuralAfter = collectAnthropicStructuralStrings(next);
|
|
936
1022
|
if (structuralAfter.length !== structuralBefore.length ||
|
|
937
1023
|
structuralAfter.some((identifier, index) => identifier !== structuralBefore[index])) {
|
|
938
1024
|
throw new Error(refusal("structural-drift"));
|
|
939
1025
|
}
|
|
940
1026
|
const serialized = JSON.stringify(next);
|
|
941
|
-
|
|
942
|
-
return request;
|
|
943
|
-
const headers = new Headers(request.headers);
|
|
944
|
-
headers.delete("content-encoding");
|
|
945
|
-
headers.set("content-length", String(byteLength(serialized)));
|
|
946
|
-
return new Request(request, { body: serialized, headers });
|
|
1027
|
+
return forwardSerialized(request, raw, serialized);
|
|
947
1028
|
}
|
|
948
1029
|
// ─── OpenAI Responses request (wire dialect) ────────────────────────────────
|
|
949
1030
|
/**
|
|
@@ -1151,7 +1232,6 @@ export async function remaskResponsesRequest(service, sessionID, request) {
|
|
|
1151
1232
|
if (!isRecord(body))
|
|
1152
1233
|
throw new Error(refusal("body-shape"));
|
|
1153
1234
|
validateResponsesDialect(body, attachmentsAllowed(service));
|
|
1154
|
-
const originalSerialized = JSON.stringify(body);
|
|
1155
1235
|
// function_call.arguments strings are parsed so masking cannot invalidate
|
|
1156
1236
|
// the JSON; re-encoded after the atomic protect (chat-completions rule).
|
|
1157
1237
|
const transformedArguments = [];
|
|
@@ -1205,12 +1285,7 @@ export async function remaskResponsesRequest(service, sessionID, request) {
|
|
|
1205
1285
|
}
|
|
1206
1286
|
}
|
|
1207
1287
|
const serialized = JSON.stringify(next);
|
|
1208
|
-
|
|
1209
|
-
return request;
|
|
1210
|
-
const headers = new Headers(request.headers);
|
|
1211
|
-
headers.delete("content-encoding");
|
|
1212
|
-
headers.set("content-length", String(byteLength(serialized)));
|
|
1213
|
-
return new Request(request, { body: serialized, headers });
|
|
1288
|
+
return forwardSerialized(request, raw, serialized);
|
|
1214
1289
|
}
|
|
1215
1290
|
function isRecordArgumentsString(item) {
|
|
1216
1291
|
return typeof item.arguments === "string";
|
|
@@ -1615,14 +1690,14 @@ function allowAnthropicField(fields, record, field) {
|
|
|
1615
1690
|
allowed.add(field);
|
|
1616
1691
|
fields.set(record, allowed);
|
|
1617
1692
|
}
|
|
1618
|
-
function anthropicStrayTokenIn(value, fields) {
|
|
1693
|
+
function anthropicStrayTokenIn(value, fields, tokenizedThinking = false) {
|
|
1619
1694
|
if (typeof value === "string") {
|
|
1620
1695
|
return containsTokenPrefix(value);
|
|
1621
1696
|
}
|
|
1622
1697
|
if (value === null || typeof value !== "object")
|
|
1623
1698
|
return false;
|
|
1624
1699
|
if (Array.isArray(value)) {
|
|
1625
|
-
return value.some((item) => anthropicStrayTokenIn(item, fields));
|
|
1700
|
+
return value.some((item) => anthropicStrayTokenIn(item, fields, tokenizedThinking));
|
|
1626
1701
|
}
|
|
1627
1702
|
const record = value;
|
|
1628
1703
|
for (const key of Object.keys(record)) {
|
|
@@ -1640,14 +1715,22 @@ function anthropicStrayTokenIn(value, fields) {
|
|
|
1640
1715
|
return true;
|
|
1641
1716
|
continue; // input stays tokenized by design
|
|
1642
1717
|
}
|
|
1643
|
-
if (
|
|
1718
|
+
if (tokenizedThinking && block.type === "thinking") {
|
|
1719
|
+
// Thinking text is signed: restoring it would break the signature
|
|
1720
|
+
// when Claude Code resends it, so its placeholders stay as sent.
|
|
1721
|
+
const { thinking: _signed, ...rest } = block;
|
|
1722
|
+
if (anthropicStrayTokenIn(rest, fields, tokenizedThinking))
|
|
1723
|
+
return true;
|
|
1724
|
+
continue;
|
|
1725
|
+
}
|
|
1726
|
+
if (anthropicStrayTokenIn(block, fields, tokenizedThinking))
|
|
1644
1727
|
return true;
|
|
1645
1728
|
}
|
|
1646
1729
|
continue;
|
|
1647
1730
|
}
|
|
1648
1731
|
if (fields?.get(record)?.has(key))
|
|
1649
1732
|
continue;
|
|
1650
|
-
if (anthropicStrayTokenIn(value, fields))
|
|
1733
|
+
if (anthropicStrayTokenIn(value, fields, tokenizedThinking))
|
|
1651
1734
|
return true;
|
|
1652
1735
|
}
|
|
1653
1736
|
return false;
|
|
@@ -1693,7 +1776,7 @@ async function restoreAnthropicJsonResponse(service, sessionID, response) {
|
|
|
1693
1776
|
}
|
|
1694
1777
|
// tool_use / other blocks: input stays tokenized until the typed tool gate.
|
|
1695
1778
|
}
|
|
1696
|
-
if (anthropicStrayTokenIn(body, fields))
|
|
1779
|
+
if (anthropicStrayTokenIn(body, fields, service.anthropicThinking === "mask"))
|
|
1697
1780
|
throw new Error(UNSUPPORTED_RESPONSE);
|
|
1698
1781
|
if (!changed)
|
|
1699
1782
|
return response;
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
/** Native Responses-family WS adapter. Selection is protocol/shape based,
|
|
2
|
+
* never provider-brand based. No network I/O: a synthetic HTTP Request reuses
|
|
3
|
+
* the established metadata admission and atomic Responses body masker.
|
|
4
|
+
* OpenCode exposes no connection ID; attribution uses the hook's session,
|
|
5
|
+
* kind and model lane, then the provider's response ID. */
|
|
6
|
+
import { type TransportMaskingService } from "./wire.js";
|
|
7
|
+
type Event = Record<string, unknown>;
|
|
8
|
+
export declare function createResponsesWebSocketAdapter(service: TransportMaskingService, wireProtection: boolean, hasProtectedContext?: (event: Event) => boolean): {
|
|
9
|
+
handshake(event: Event): void;
|
|
10
|
+
send(event: Event): Promise<string>;
|
|
11
|
+
receive(event: Event): string;
|
|
12
|
+
/** Response-only hook mode. The host event and prepared content scope
|
|
13
|
+
* select the mapping; a provider response.created starts the bounded
|
|
14
|
+
* response/channel state. No handshake, send, or transport gate is used.
|
|
15
|
+
* Errors are caught by the ingress hook and keep frames literal. */
|
|
16
|
+
receiveOnly(event: Event): string;
|
|
17
|
+
/** Keep a validated handshake reusable for the next response, but never
|
|
18
|
+
* restore another frame from a failed response. A held literal prefix can
|
|
19
|
+
* be flushed only into the very same verified text channel/response. */
|
|
20
|
+
abandonResponse(event: Event): string | undefined;
|
|
21
|
+
reset: (event: Event) => void;
|
|
22
|
+
resetRequest: (event: Event) => void;
|
|
23
|
+
clearSession(sessionID: string): void;
|
|
24
|
+
dispose(): void;
|
|
25
|
+
};
|
|
26
|
+
export {};
|
|
@@ -3,7 +3,7 @@
|
|
|
3
3
|
* the established metadata admission and atomic Responses body masker.
|
|
4
4
|
* OpenCode exposes no connection ID; attribution uses the hook's session,
|
|
5
5
|
* kind and model lane, then the provider's response ID. */
|
|
6
|
-
import { admitModelRequest, classifyModelRoute, remaskResponsesRequest, RESPONSES_TEXT_DELTA_TYPES, RESPONSES_TEXT_DONE_TYPES, restoreDisplayText, restoreResponsesEventDisplay, splitRestorable, } from "./
|
|
6
|
+
import { admitModelRequest, classifyModelRoute, remaskResponsesRequest, RESPONSES_TEXT_DELTA_TYPES, RESPONSES_TEXT_DONE_TYPES, restoreDisplayText, restoreResponsesEventDisplay, splitRestorable, } from "./wire.js";
|
|
7
7
|
const ROUTE_ERROR = "LeakShield blocked a request on an unsupported route.";
|
|
8
8
|
const FRAME_ERROR = "LeakShield blocked an unsupported or malformed WebSocket frame.";
|
|
9
9
|
const ATTRIBUTION_ERROR = "LeakShield blocked a WebSocket frame that could not be matched to a request.";
|
|
@@ -0,0 +1,63 @@
|
|
|
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 type { Finding, GuardConfig } from "../types.js";
|
|
13
|
+
import { type ProtectionOptions, type ProtectedText } from "./ingress.js";
|
|
14
|
+
export declare const DEIDENTIFY_MARKER_PREFIX = "[SG-EMAIL-";
|
|
15
|
+
/**
|
|
16
|
+
* Bound on the placeholders a session retains for replay protection. The
|
|
17
|
+
* registry is bounded so a long session cannot grow it without limit; a unit
|
|
18
|
+
* that would exceed it fails closed (blocks) before issuing anything, and
|
|
19
|
+
* placeholders are retained only after the unit has fully succeeded — so a
|
|
20
|
+
* refused unit consumes no quota.
|
|
21
|
+
*/
|
|
22
|
+
export declare const ISSUED_PLACEHOLDER_LIMIT = 4096;
|
|
23
|
+
/** One random key per plugin setup (= one OpenCode session); never persisted. */
|
|
24
|
+
export declare function createSessionKey(): Buffer;
|
|
25
|
+
/**
|
|
26
|
+
* Stable opaque placeholder for one email value within a session. The value is
|
|
27
|
+
* normalized (trim + lowercase) so case variants of one address collide to a
|
|
28
|
+
* single placeholder. 16 hex chars (64 bits) of HMAC-SHA-256 keyed by the
|
|
29
|
+
* session key — non-reversible without the in-memory key, and shaped so no
|
|
30
|
+
* scanner rule or `[REDACTED_*]` marker exemption matches it. Collision
|
|
31
|
+
* bound: at 64 bits, a birthday collision needs ~2^32 distinct values in one
|
|
32
|
+
* session before two different addresses could share a placeholder.
|
|
33
|
+
*/
|
|
34
|
+
export declare function placeholderFor(value: string, sessionKey: Buffer): string;
|
|
35
|
+
export type DeidentifyApplication = {
|
|
36
|
+
ok: true;
|
|
37
|
+
text: string;
|
|
38
|
+
} | {
|
|
39
|
+
ok: false;
|
|
40
|
+
};
|
|
41
|
+
/**
|
|
42
|
+
* Substitute email spans in `text` according to `findings`, enforcing the
|
|
43
|
+
* fail-closed gates up front. Returns `{ ok: false }` when:
|
|
44
|
+
* - any finding (email or not) carries `encoding_detected` metadata
|
|
45
|
+
* (its offsets cannot be trusted for substitution),
|
|
46
|
+
* - an email finding lacks usable `match_start`/`match_end`/`match_text`,
|
|
47
|
+
* - email spans overlap, or
|
|
48
|
+
* - a span's `match_text` does not equal the slice it claims to cover.
|
|
49
|
+
*/
|
|
50
|
+
export declare function applyDeidentify(text: string, findings: readonly Finding[], sessionKey: Buffer): DeidentifyApplication;
|
|
51
|
+
/**
|
|
52
|
+
* `protectText` with the de-identification trial applied: emails opted in via
|
|
53
|
+
* the session key are replaced by stable placeholders before the standard
|
|
54
|
+
* redaction/verification pipeline. Any doubt (truncation, encoded findings,
|
|
55
|
+
* bad spans, verification failure, residual originals) blocks the whole unit.
|
|
56
|
+
*
|
|
57
|
+
* `issuedPlaceholders` is the session-owned set of placeholders issued so far.
|
|
58
|
+
* Placeholders already present in `text` are protected exactly like newly
|
|
59
|
+
* issued ones, so a prompt→context replay cannot corrupt a placeholder whose
|
|
60
|
+
* hex body happens to contain a phone-shaped run. Only placeholders actually
|
|
61
|
+
* in this set are exempt — an arbitrary marker-shaped lookalike is not.
|
|
62
|
+
*/
|
|
63
|
+
export declare function deidentifyText(text: string, config: GuardConfig, sessionKey: Buffer, options: ProtectionOptions, issuedPlaceholders?: Set<string>): ProtectedText;
|