leakshield 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (47) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +546 -2
  3. package/README.zh-TW.md +565 -0
  4. package/dist/cli.js +61 -0
  5. package/dist/config/loader.js +94 -0
  6. package/dist/decision/deidentify.js +195 -0
  7. package/dist/decision/ingress.js +136 -0
  8. package/dist/decision/mapping-key.js +318 -0
  9. package/dist/decision/mapping-store.js +555 -0
  10. package/dist/decision/model.js +76 -0
  11. package/dist/decision/pseudonymization.js +1230 -0
  12. package/dist/decision/redaction.js +185 -0
  13. package/dist/decision/schema-strings.js +42 -0
  14. package/dist/doctor.js +438 -0
  15. package/dist/env-queries.js +584 -0
  16. package/dist/forget.js +56 -0
  17. package/dist/help.js +37 -0
  18. package/dist/i18n/en.js +71 -0
  19. package/dist/i18n/index.js +28 -0
  20. package/dist/i18n/zh-TW.js +71 -0
  21. package/dist/index.js +12 -0
  22. package/dist/opencode-env-tools.js +243 -0
  23. package/dist/opencode-hooks.js +84 -0
  24. package/dist/opencode-transparent-aisdk.js +100 -0
  25. package/dist/opencode-transparent-http.js +2315 -0
  26. package/dist/opencode-transparent-stream.js +192 -0
  27. package/dist/opencode-transparent-ws.js +298 -0
  28. package/dist/opencode-transparent.js +1492 -0
  29. package/dist/opencode-v2.js +216 -0
  30. package/dist/opencode.js +175 -0
  31. package/dist/plugin-options.js +100 -0
  32. package/dist/rules/builtin.js +283 -0
  33. package/dist/rules/dynamic.js +68 -0
  34. package/dist/scanner/encoding.js +274 -0
  35. package/dist/scanner/engine.js +321 -0
  36. package/dist/scanner/exact-values.js +99 -0
  37. package/dist/scanner/redaction-verifier.js +82 -0
  38. package/dist/scanner/unicode.js +157 -0
  39. package/dist/scanner/utils.js +60 -0
  40. package/dist/transports/cli.js +447 -0
  41. package/dist/transports/web-ui.js +540 -0
  42. package/dist/transports/web.js +200 -0
  43. package/dist/types.js +23 -0
  44. package/dist/utils/files.js +36 -0
  45. package/dist/utils/path-security.js +30 -0
  46. package/dist/utils/win-encoding.js +45 -0
  47. package/package.json +71 -4
@@ -0,0 +1,192 @@
1
+ /** Transactional ingress recovery shared by the three SSE protocol adapters.
2
+ * Keep original frames until a token tail is resolved; on an adapter failure
3
+ * release only the not-yet-delivered originals and bypass further rewriting.
4
+ * No tee, rewind, synthetic completion or unbounded shadow stream is needed. */
5
+ const MAX_RETAINED_BYTES = 1_048_576;
6
+ const MAX_RETAINED_PARTS = 4096;
7
+ function concatenate(parts) {
8
+ const size = parts.reduce((sum, part) => sum + part.length, 0);
9
+ const result = new Uint8Array(size);
10
+ let at = 0;
11
+ for (const part of parts) {
12
+ result.set(part, at);
13
+ at += part.length;
14
+ }
15
+ return result;
16
+ }
17
+ export function createRecoveringSseStream(reader, rewrite, abandon) {
18
+ const decoder = new TextDecoder("utf-8", { fatal: true });
19
+ const encoder = new TextEncoder();
20
+ let input;
21
+ let at = 0;
22
+ let lineParts = [], frameParts = [], originals = [];
23
+ let lines = [], outputs = [];
24
+ let lineBytes = 0, frameBytes = 0, originalBytes = 0, outputBytes = 0, retainedParts = 0;
25
+ let bypass = false, finished = false, holding = false;
26
+ const clear = () => {
27
+ lineParts = [];
28
+ frameParts = [];
29
+ originals = [];
30
+ lines = [];
31
+ outputs = [];
32
+ lineBytes = 0;
33
+ frameBytes = 0;
34
+ originalBytes = 0;
35
+ outputBytes = 0;
36
+ retainedParts = 0;
37
+ };
38
+ const recover = (controller) => {
39
+ bypass = true;
40
+ // Static, once per stream. Never include an exception or frame contents.
41
+ console.warn("[leakshield] degraded: SSE restoration stopped; undelivered original frames kept literal");
42
+ abandon();
43
+ for (const part of [...originals, ...frameParts, ...lineParts])
44
+ controller.enqueue(part);
45
+ clear();
46
+ if (input !== undefined && at < input.length)
47
+ controller.enqueue(input.subarray(at));
48
+ input = undefined;
49
+ at = 0;
50
+ };
51
+ const commit = (controller) => {
52
+ const text = outputs.join("");
53
+ originals = [];
54
+ outputs = [];
55
+ originalBytes = 0;
56
+ outputBytes = 0;
57
+ retainedParts = frameParts.length + lineParts.length;
58
+ if (text)
59
+ controller.enqueue(encoder.encode(text));
60
+ };
61
+ const event = (controller, terminated) => {
62
+ const raw = concatenate(frameParts);
63
+ originals.push(raw);
64
+ originalBytes += raw.length;
65
+ retainedParts += 1 - frameParts.length;
66
+ const eventLines = lines;
67
+ frameParts = [];
68
+ lines = [];
69
+ frameBytes = 0;
70
+ try {
71
+ const rewritten = rewrite(eventLines, terminated);
72
+ outputBytes += encoder.encode(rewritten.output).length;
73
+ if (outputBytes > MAX_RETAINED_BYTES)
74
+ throw new Error("SSE rewrite budget");
75
+ outputs.push(rewritten.output);
76
+ holding = rewritten.holding;
77
+ if (!holding) {
78
+ commit(controller);
79
+ return true;
80
+ }
81
+ return false;
82
+ }
83
+ catch {
84
+ recover(controller);
85
+ return true;
86
+ }
87
+ };
88
+ return new ReadableStream({
89
+ async pull(controller) {
90
+ if (finished)
91
+ return;
92
+ try {
93
+ for (;;) {
94
+ if (input === undefined || at === input.length) {
95
+ input = undefined;
96
+ at = 0;
97
+ // Source errors deliberately remain errors, not a recoverable
98
+ // parser verdict. This read is outside the rewrite catch above.
99
+ const next = await reader.read();
100
+ if (finished)
101
+ return;
102
+ if (next.done) {
103
+ if (!bypass) {
104
+ if (holding)
105
+ recover(controller);
106
+ else if (lineParts.length || frameParts.length) {
107
+ try {
108
+ if (lineParts.length) {
109
+ lines.push(decoder.decode(concatenate(lineParts)));
110
+ frameParts.push(...lineParts);
111
+ frameBytes += lineBytes;
112
+ lineParts = [];
113
+ lineBytes = 0;
114
+ }
115
+ event(controller, false);
116
+ if (holding && !bypass)
117
+ recover(controller);
118
+ }
119
+ catch {
120
+ recover(controller);
121
+ }
122
+ }
123
+ }
124
+ finished = true;
125
+ abandon();
126
+ controller.close();
127
+ return;
128
+ }
129
+ input = next.value;
130
+ }
131
+ if (bypass) {
132
+ if (input.length)
133
+ controller.enqueue(input.subarray(at));
134
+ input = undefined;
135
+ at = 0;
136
+ return;
137
+ }
138
+ const newline = input.indexOf(10, at);
139
+ const end = newline === -1 ? input.length : newline + 1;
140
+ const fragment = input.subarray(at, end);
141
+ if (originalBytes + frameBytes + lineBytes + fragment.length > MAX_RETAINED_BYTES || retainedParts >= MAX_RETAINED_PARTS) {
142
+ recover(controller);
143
+ return;
144
+ }
145
+ // Copy bounded slices so a tiny retained tail cannot pin a huge
146
+ // backing ArrayBuffer supplied in a single upstream chunk.
147
+ lineParts.push(fragment.slice());
148
+ lineBytes += fragment.length;
149
+ retainedParts += 1;
150
+ at = end;
151
+ if (newline === -1)
152
+ continue;
153
+ const rawLine = concatenate(lineParts);
154
+ frameParts.push(...lineParts);
155
+ frameBytes += lineBytes;
156
+ lineParts = [];
157
+ lineBytes = 0;
158
+ let line;
159
+ try {
160
+ line = decoder.decode(rawLine.subarray(0, rawLine.length - 1));
161
+ }
162
+ catch {
163
+ recover(controller);
164
+ return;
165
+ }
166
+ if (line === "" || line === "\r") {
167
+ if (event(controller, true))
168
+ return;
169
+ }
170
+ else
171
+ lines.push(line);
172
+ }
173
+ }
174
+ catch (error) {
175
+ if (finished)
176
+ return;
177
+ finished = true;
178
+ clear();
179
+ abandon();
180
+ controller.error(error);
181
+ void reader.cancel(error).catch(() => { });
182
+ }
183
+ },
184
+ cancel(reason) {
185
+ finished = true;
186
+ input = undefined;
187
+ clear();
188
+ abandon();
189
+ return reader.cancel(reason);
190
+ },
191
+ }, { highWaterMark: 0 });
192
+ }
@@ -0,0 +1,298 @@
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 { admitModelRequest, classifyModelRoute, remaskResponsesRequest, RESPONSES_TEXT_DELTA_TYPES, RESPONSES_TEXT_DONE_TYPES, restoreDisplayText, restoreResponsesEventDisplay, splitRestorable, } from "./opencode-transparent-http.js";
7
+ const ROUTE_ERROR = "LeakShield transparent mode blocked an unsupported model transport route.";
8
+ const FRAME_ERROR = "LeakShield transparent mode blocked an unsupported or malformed WebSocket frame.";
9
+ const ATTRIBUTION_ERROR = "LeakShield transparent mode blocked a WebSocket frame without matching request attribution.";
10
+ const LIMIT_ERROR = "LeakShield transparent mode blocked an oversized WebSocket buffer.";
11
+ const MAX_FRAME_BYTES = 4 * 1024 * 1024;
12
+ const MAX_LANES = 1024;
13
+ const MAX_CHANNELS = 256;
14
+ const MAX_CHANNEL_BYTES = 65_536;
15
+ const MAX_TOTAL_BYTES = 1_048_576;
16
+ const TERMINAL_TYPES = new Set(["response.completed", "response.failed", "response.incomplete", "error"]);
17
+ const bytes = (text) => Buffer.byteLength(text, "utf8");
18
+ const record = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
19
+ function laneKey(event) {
20
+ const model = event.model;
21
+ if (typeof event.sessionID !== "string" || !event.sessionID ||
22
+ !["primary", "title", "compaction", "generate"].includes(String(event.kind)) ||
23
+ !record(model) || typeof model.providerID !== "string" || typeof model.id !== "string")
24
+ throw new Error(ROUTE_ERROR);
25
+ const key = JSON.stringify([event.sessionID, event.kind, model.providerID, model.id]);
26
+ if (bytes(key) > 4096)
27
+ throw new Error(LIMIT_ERROR);
28
+ return key;
29
+ }
30
+ function parseFrame(frame) {
31
+ if (typeof frame !== "string")
32
+ throw new Error(FRAME_ERROR);
33
+ if (bytes(frame) > MAX_FRAME_BYTES)
34
+ throw new Error(LIMIT_ERROR);
35
+ let value;
36
+ try {
37
+ value = JSON.parse(frame);
38
+ }
39
+ catch {
40
+ throw new Error(FRAME_ERROR);
41
+ }
42
+ if (!record(value) || typeof value.type !== "string")
43
+ throw new Error(FRAME_ERROR);
44
+ return value;
45
+ }
46
+ export function createResponsesWebSocketAdapter(service, wireProtection, hasProtectedContext = () => false) {
47
+ const lanes = new Map();
48
+ let hookOnlyNoticed = false;
49
+ let totalBytes = 0;
50
+ const clearBuffers = (lane) => {
51
+ for (const hold of lane.holds.values())
52
+ totalBytes -= bytes(hold);
53
+ for (const key of lane.counts.keys())
54
+ totalBytes -= bytes(key);
55
+ lane.holds.clear();
56
+ lane.counts.clear();
57
+ };
58
+ const reset = (event) => {
59
+ const key = laneKey(event);
60
+ const lane = lanes.get(key);
61
+ if (lane)
62
+ clearBuffers(lane);
63
+ lanes.delete(key);
64
+ };
65
+ const resetRequest = (event) => {
66
+ laneKey(event); // Validate attribution before invalidating any lane.
67
+ const prefix = `${JSON.stringify([event.sessionID, event.kind]).slice(0, -1)},`;
68
+ for (const [key, lane] of lanes) {
69
+ if (!key.startsWith(prefix))
70
+ continue;
71
+ clearBuffers(lane);
72
+ lanes.delete(key);
73
+ }
74
+ };
75
+ const getLane = (event) => {
76
+ const lane = lanes.get(laneKey(event));
77
+ if (!lane)
78
+ throw new Error(ATTRIBUTION_ERROR);
79
+ return lane;
80
+ };
81
+ return {
82
+ handshake(event) {
83
+ const key = laneKey(event);
84
+ // Invalidate earlier attribution even if the replacement handshake fails.
85
+ resetRequest(event);
86
+ if (typeof event.url !== "string" || !record(event.headers))
87
+ throw new Error(ROUTE_ERROR);
88
+ let url;
89
+ try {
90
+ url = new URL(event.url);
91
+ }
92
+ catch {
93
+ throw new Error(ROUTE_ERROR);
94
+ }
95
+ if (!["ws:", "wss:"].includes(url.protocol))
96
+ throw new Error(ROUTE_ERROR);
97
+ const restorable = classifyModelRoute(url.href) === "openai-responses";
98
+ if (!restorable && (wireProtection || !hasProtectedContext(event)))
99
+ throw new Error(ROUTE_ERROR);
100
+ url.protocol = url.protocol === "wss:" ? "https:" : "http:";
101
+ const headers = new Headers();
102
+ for (const [name, value] of Object.entries(event.headers)) {
103
+ if (typeof value !== "string")
104
+ throw new Error(ROUTE_ERROR);
105
+ headers.set(name, value);
106
+ }
107
+ const request = admitModelRequest(service, String(event.sessionID), new Request(url, { method: "POST", headers }), !restorable);
108
+ if (lanes.size >= MAX_LANES) {
109
+ const inactive = [...lanes].find(([, lane]) => !lane.sent || lane.terminal);
110
+ if (!inactive)
111
+ throw new Error(LIMIT_ERROR);
112
+ lanes.delete(inactive[0]);
113
+ }
114
+ lanes.set(key, { request, restorable, sent: false, terminal: false, holds: new Map(), counts: new Map() });
115
+ if (!restorable && !hookOnlyNoticed) {
116
+ hookOnlyNoticed = true;
117
+ console.warn("[leakshield] degraded: unknown WS route admitted with scoped context hooks only; frames are not inspected or restored");
118
+ }
119
+ },
120
+ async send(event) {
121
+ const lane = getLane(event);
122
+ // A rejected retry cannot leave the previous request eligible to receive.
123
+ lane.sent = false;
124
+ clearBuffers(lane);
125
+ if (!lane.restorable) {
126
+ if (!hasProtectedContext(event))
127
+ throw new Error(ROUTE_ERROR);
128
+ if (typeof event.frame !== "string")
129
+ throw new Error(FRAME_ERROR);
130
+ lane.sent = true;
131
+ return event.frame;
132
+ }
133
+ const body = parseFrame(event.frame);
134
+ if (body.type !== "response.create")
135
+ throw new Error(FRAME_ERROR);
136
+ let frame = String(event.frame);
137
+ if (wireProtection) {
138
+ // Provider continuation IDs are identifiers, not display text. Never
139
+ // remask them into new values, even when they look sensitive.
140
+ const identifiers = {};
141
+ for (const name of ["type", "event_id", "previous_response_id", "conversation"]) {
142
+ if (!(name in body))
143
+ continue;
144
+ const value = body[name];
145
+ if (value !== null && (typeof value !== "string" || !service.isStructuralIdentifierSafe(String(event.sessionID), value))) {
146
+ throw new Error(FRAME_ERROR);
147
+ }
148
+ identifiers[name] = value;
149
+ delete body[name];
150
+ }
151
+ const request = new Request(lane.request, { body: JSON.stringify(body) });
152
+ const masked = await remaskResponsesRequest(service, String(event.sessionID), request);
153
+ frame = JSON.stringify({ ...JSON.parse(await masked.text()), ...identifiers });
154
+ }
155
+ if (lanes.get(laneKey(event)) !== lane)
156
+ throw new Error(ATTRIBUTION_ERROR);
157
+ lane.sent = true;
158
+ lane.terminal = false;
159
+ lane.responseID = undefined;
160
+ return frame;
161
+ },
162
+ receive(event) {
163
+ const lane = getLane(event);
164
+ if (!lane.restorable) {
165
+ if (typeof event.frame !== "string")
166
+ throw new Error(FRAME_ERROR);
167
+ return event.frame;
168
+ }
169
+ if (!lane.sent || lane.terminal)
170
+ throw new Error(ATTRIBUTION_ERROR);
171
+ const chunk = parseFrame(event.frame);
172
+ const type = String(chunk.type);
173
+ const response = record(chunk.response) ? chunk.response : undefined;
174
+ if (type === "response.created") {
175
+ if (lane.responseID !== undefined || typeof response?.id !== "string")
176
+ throw new Error(ATTRIBUTION_ERROR);
177
+ if (bytes(response.id) > 4096)
178
+ throw new Error(LIMIT_ERROR);
179
+ lane.responseID = response.id;
180
+ }
181
+ if (type !== "error" && lane.responseID === undefined)
182
+ throw new Error(ATTRIBUTION_ERROR);
183
+ for (const id of [chunk.response_id, response?.id]) {
184
+ if (id !== undefined && id !== lane.responseID)
185
+ throw new Error(ATTRIBUTION_ERROR);
186
+ }
187
+ const channel = JSON.stringify([type.replace(/\.(delta|done)$/, ""), chunk.item_id ?? chunk.output_index ?? "0", chunk.content_index ?? chunk.summary_index ?? 0]);
188
+ if (bytes(channel) > 4096)
189
+ throw new Error(LIMIT_ERROR);
190
+ if (RESPONSES_TEXT_DELTA_TYPES.has(type)) {
191
+ if (typeof chunk.delta !== "string")
192
+ throw new Error(FRAME_ERROR);
193
+ if (!lane.counts.has(channel) && lane.counts.size >= MAX_CHANNELS)
194
+ throw new Error(LIMIT_ERROR);
195
+ const previous = lane.holds.get(channel) ?? "";
196
+ if (bytes(previous) + bytes(chunk.delta) > MAX_CHANNEL_BYTES)
197
+ throw new Error(LIMIT_ERROR);
198
+ const { emit, hold } = splitRestorable(previous + chunk.delta);
199
+ const nextTotal = totalBytes - bytes(previous) + bytes(hold) + (lane.counts.has(channel) ? 0 : bytes(channel));
200
+ if (nextTotal > MAX_TOTAL_BYTES)
201
+ throw new Error(LIMIT_ERROR);
202
+ chunk.delta = restoreDisplayText(service, String(event.sessionID), emit);
203
+ totalBytes = nextTotal;
204
+ if (hold)
205
+ lane.holds.set(channel, hold);
206
+ else
207
+ lane.holds.delete(channel);
208
+ lane.counts.set(channel, (lane.counts.get(channel) ?? 0) + emit.length);
209
+ }
210
+ else if (RESPONSES_TEXT_DONE_TYPES.has(type)) {
211
+ const held = lane.holds.get(channel);
212
+ // A WS hook replaces ONE frame, unlike SSE's ability to insert an
213
+ // extra delta. Keep done semantics and its complete restored field;
214
+ // malformed providers that omit the final delta get a static notice.
215
+ if (held) {
216
+ console.warn("[leakshield] degraded: WS text ended with an incomplete delta tail; complete done field retained");
217
+ totalBytes -= bytes(held);
218
+ lane.holds.delete(channel);
219
+ }
220
+ if (lane.counts.delete(channel))
221
+ totalBytes -= bytes(channel);
222
+ }
223
+ restoreResponsesEventDisplay(service, String(event.sessionID), chunk);
224
+ if (TERMINAL_TYPES.has(type)) {
225
+ if (lane.holds.size)
226
+ console.warn("[leakshield] degraded: WS terminal frame dropped incomplete placeholder tails");
227
+ clearBuffers(lane);
228
+ lane.terminal = true;
229
+ }
230
+ return JSON.stringify(chunk);
231
+ },
232
+ /** Response-only hook mode. The host event and prepared content scope
233
+ * select the mapping; a provider response.created starts the bounded
234
+ * response/channel state. No handshake, send, or transport gate is used.
235
+ * Errors are caught by the ingress hook and keep frames literal. */
236
+ receiveOnly(event) {
237
+ if (wireProtection || !hasProtectedContext(event))
238
+ throw new Error(ATTRIBUTION_ERROR);
239
+ const key = laneKey(event);
240
+ const chunk = parseFrame(event.frame);
241
+ if (chunk.type === "response.created") {
242
+ const previous = lanes.get(key);
243
+ if (!previous || !previous.sent || previous.terminal) {
244
+ resetRequest(event);
245
+ if (lanes.size >= MAX_LANES)
246
+ throw new Error(LIMIT_ERROR);
247
+ lanes.set(key, {
248
+ request: new Request("https://hook-only.invalid/v1/responses"),
249
+ restorable: true, sent: true, terminal: false, holds: new Map(), counts: new Map(),
250
+ });
251
+ }
252
+ }
253
+ return this.receive(event);
254
+ },
255
+ /** Keep a validated handshake reusable for the next response, but never
256
+ * restore another frame from a failed response. A held literal prefix can
257
+ * be flushed only into the very same verified text channel/response. */
258
+ abandonResponse(event) {
259
+ const lane = lanes.get(laneKey(event));
260
+ if (!lane)
261
+ return undefined;
262
+ let frame;
263
+ try {
264
+ const chunk = parseFrame(event.frame);
265
+ const id = record(chunk.response) ? chunk.response.id : chunk.response_id;
266
+ if (lane.sent && !lane.terminal && lane.responseID !== undefined && (id === undefined || id === lane.responseID) &&
267
+ RESPONSES_TEXT_DELTA_TYPES.has(String(chunk.type)) && typeof chunk.delta === "string") {
268
+ const channel = JSON.stringify([String(chunk.type).replace(/\.(delta|done)$/, ""), chunk.item_id ?? chunk.output_index ?? "0", chunk.content_index ?? chunk.summary_index ?? 0]);
269
+ const held = lane.holds.get(channel);
270
+ if (held)
271
+ frame = JSON.stringify({ ...chunk, delta: held + chunk.delta });
272
+ }
273
+ }
274
+ catch { /* Unparseable/unattributed frames stay byte-for-byte original. */ }
275
+ clearBuffers(lane);
276
+ lane.sent = false;
277
+ lane.terminal = true;
278
+ lane.responseID = undefined;
279
+ return frame;
280
+ },
281
+ reset,
282
+ resetRequest,
283
+ clearSession(sessionID) {
284
+ const prefix = `${JSON.stringify([sessionID]).slice(0, -1)},`;
285
+ for (const [key, lane] of lanes) {
286
+ if (!key.startsWith(prefix))
287
+ continue;
288
+ clearBuffers(lane);
289
+ lanes.delete(key);
290
+ }
291
+ },
292
+ dispose() {
293
+ lanes.clear();
294
+ totalBytes = 0;
295
+ hookOnlyNoticed = false;
296
+ },
297
+ };
298
+ }