@eyeoverthink/sva-gate 2.1.0 → 2.1.2

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.
@@ -1,228 +1,228 @@
1
- // Zero-dependency Streaming Token Guard for LLM NDJSON / text streams.
2
- // Prevents credentials and PII split across arbitrary token boundaries (e.g. "sk-" + "ant-..." or "123-" + "45-6789")
3
- // from leaking mid-stream before sealing/redaction triggers.
4
- // Ported from StreamCanaryInterceptor's cross-token tail-prefix buffering design.
5
- // 1.4.0: the whole trailing token is always held (not only known prefixes), cuts never fall inside a detected
6
- // value, PEM bodies and multi-word values (titled names, addresses, IBANs, "password is ...") are held, and
7
- // already-emitted context feeds look-behind detectors.
8
- import { detect, SealSession } from './membrane-core.js';
9
-
10
- export const SECRET_PREFIXES = [
11
- 'sk-ant-',
12
- 'sk-proj-',
13
- 'sk-',
14
- 'AIza',
15
- 'ghp_',
16
- 'gho_',
17
- 'github_pat_',
18
- 'AKIA',
19
- 'xoxb-',
20
- 'xoxp-',
21
- 'Bearer ',
22
- '-----BEGIN ',
23
- ];
24
-
25
- const MAX_PREFIX_LEN = Math.max(...SECRET_PREFIXES.map((p) => p.length));
26
-
27
- // Already-emitted raw text kept so that look-behind detectors ("password is <value>", "account no 12345",
28
- // "Bearer <token>") still see their keyword when the value arrives in a later chunk. It is never emitted again.
29
- const CONTEXT_CHARS = 64;
30
-
31
- // Tail patterns for detectors whose matches contain whitespace, so a "hold the last word" rule is not enough.
32
- const MULTIWORD_TAILS = [
33
- // A titled name in progress: "Dr", "Dr.", "Dr. Elena", "Dr. Elena Ruiz" (PERSON allows up to three names).
34
- /\b(?:Dr|Mr|Mrs|Ms|Mx|Prof|Sr|Sra|Herr|Frau)\.?(?:\s{1,4}[A-Z][a-z'’-]*){0,3}\s{0,4}$/,
35
- // A street address in progress: "12", "12 Main", "12 Main Street".
36
- /\b\d{1,6}(?:\s{1,4}[A-Z][a-z]*){0,5}\s{0,4}$/,
37
- // An IBAN written in groups of four.
38
- /\b[A-Z]{2}\d{2}(?:\s?[A-Z0-9]{1,4}){0,8}\s?$/,
39
- // A keyword whose value is detected by look-behind, still waiting for the value.
40
- /\b(?:password|passwd|passcode|pin|secret|api[_-]?key|token|account|acct|patient|customer|member|policy|case|invoice|Bearer)\b[^\n]{0,24}$/i,
41
- ];
42
-
43
- // Returns how many trailing characters of `text` must be held back because they could still become (part of)
44
- // a secret or PII value once more text arrives.
45
- export function tailHoldLength(text) {
46
- if (!text) return 0;
47
- let hold = 0;
48
-
49
- // 1. Partial match against any known secret prefix (e.g. trailing "sk-" or "ghp")
50
- const maxCheck = Math.min(text.length, MAX_PREFIX_LEN);
51
- for (const pfx of SECRET_PREFIXES) {
52
- for (let len = 1; len <= Math.min(pfx.length, maxCheck); len++) {
53
- if (text.endsWith(pfx.slice(0, len))) hold = Math.max(hold, len);
54
- }
55
- }
56
-
57
- // 2. Active secret prefix still accumulating token chars right up to the end of the chunk
58
- for (const pfx of SECRET_PREFIXES) {
59
- const idx = text.lastIndexOf(pfx);
60
- if (idx !== -1) {
61
- const tail = text.slice(idx);
62
- if (/^[A-Za-z0-9_\-./+=: ]+$/.test(tail) && tail.length < 256) {
63
- hold = Math.max(hold, tail.length);
64
- }
65
- }
66
- }
67
-
68
- // 3. Partial trailing digit/separator run (could become SSN 123-45-6789, phone, or card number)
69
- const digitTail = text.match(/[+\d][\d\s.\-()]{0,22}$/);
70
- if (digitTail) hold = Math.max(hold, digitTail[0].length);
71
-
72
- // 4. The whole trailing run of non-whitespace characters, however long and even when it is the whole text.
73
- // Every single-token detector (email, JWT, API key, URL with a token, card, SSN) can only match a run that
74
- // has ended, so the run in progress is always held. (1.3.0 capped this at 32 characters and skipped it when
75
- // the run was the whole buffer, so a fragment that arrived as its own chunk was emitted at once.)
76
- const wordTail = text.match(/\S+$/);
77
- if (wordTail) hold = Math.max(hold, wordTail[0].length);
78
-
79
- // 5. A PEM block that has begun but not ended (its body contains newlines, so rule 4 cannot cover it).
80
- const begin = text.lastIndexOf('-----BEGIN ');
81
- if (begin !== -1 && !/-----END [A-Z0-9 ]+-----/.test(text.slice(begin))) hold = Math.max(hold, text.length - begin);
82
-
83
- // 6. Detectors whose matches span whitespace.
84
- for (const re of MULTIWORD_TAILS) {
85
- const m = text.match(re);
86
- if (m) hold = Math.max(hold, m[0].length);
87
- }
88
-
89
- return Math.min(hold, text.length);
90
- }
91
-
92
- export class StreamSealGuard {
93
- constructor({ session = null, mode = 'seal', maxBuffer = 4096 } = {}) {
94
- this.session = session || new SealSession();
95
- this.mode = mode; // 'seal' (typed placeholders) | 'redact' ([REDACTED:<TYPE>])
96
- this.maxBuffer = maxBuffer;
97
- this.buffer = '';
98
- this.context = '';
99
- this.chunksProcessed = 0;
100
- this.sealsApplied = 0;
101
- this.alerts = [];
102
- }
103
-
104
- // Spans of `text`, detected with the already-emitted context in front so look-behind detectors work.
105
- // Coordinates are relative to `text`; a span that began in the context is clipped to start at 0.
106
- _spans(text) {
107
- const ctx = this.context;
108
- const spans = [];
109
- for (const sp of detect(ctx + text)) {
110
- const end = sp.end - ctx.length;
111
- if (end <= 0) continue;
112
- const start = Math.max(0, sp.start - ctx.length);
113
- spans.push({ start, end, type: sp.type, value: text.slice(start, end) });
114
- }
115
- return spans;
116
- }
117
-
118
- _seal(text, spans) {
119
- if (!text) return '';
120
- const inside = spans.filter((sp) => sp.end <= text.length);
121
- if (inside.length === 0) return text;
122
- this.sealsApplied += inside.length;
123
- this.alerts.push({
124
- chunkIndex: this.chunksProcessed,
125
- types: [...new Set(inside.map((s) => s.type))],
126
- count: inside.length,
127
- });
128
- if (this.mode === 'redact') {
129
- let out = '';
130
- let pos = 0;
131
- for (const sp of inside) {
132
- out += text.slice(pos, sp.start) + `[REDACTED:${sp.type}]`;
133
- pos = sp.end;
134
- }
135
- return out + text.slice(pos);
136
- }
137
- return this.session.apply(text, inside);
138
- }
139
-
140
- _emit(raw, spans) {
141
- const out = this._seal(raw, spans);
142
- this.context = (this.context + raw).slice(-CONTEXT_CHARS);
143
- return out;
144
- }
145
-
146
- // Kept for callers that used it in 1.3.0: seal a self-contained piece of text.
147
- _sealWindow(text) { return this._seal(text, text ? this._spans(text) : []); }
148
-
149
- // Feed one streaming token/chunk; returns the safe-to-emit prefix while holding any boundary-split candidate.
150
- push(chunk) {
151
- this.chunksProcessed++;
152
- const combined = this.buffer + String(chunk ?? '');
153
- if (!combined) return '';
154
-
155
- const spans = this._spans(combined);
156
- let cut = combined.length - tailHoldLength(combined);
157
-
158
- // Never cut inside a detected value, and never emit a value that ends in the trailing whitespace: it may
159
- // still grow ("Dr. Elena " + "Ruiz", "415 555 " + "0100"). Repeat until the cut is stable.
160
- for (let moved = true; moved;) {
161
- moved = false;
162
- for (const sp of spans) {
163
- const straddles = sp.start < cut && sp.end > cut;
164
- const growing = sp.start < cut && combined.slice(sp.end).trim() === '';
165
- if (straddles || growing) { cut = sp.start; moved = true; }
166
- }
167
- }
168
-
169
- // Bounded memory: never hold more than maxBuffer characters; the oldest part is sealed and emitted.
170
- if (combined.length - cut > this.maxBuffer) cut = combined.length - this.maxBuffer;
171
-
172
- this.buffer = combined.slice(cut);
173
- return this._emit(combined.slice(0, cut), spans);
174
- }
175
-
176
- // Flush remaining buffered tail at end-of-stream.
177
- flush() {
178
- const rest = this.buffer;
179
- this.buffer = '';
180
- if (!rest) return '';
181
- return this._emit(rest, this._spans(rest));
182
- }
183
-
184
- // Process one Ollama-style NDJSON line (supports both /api/generate `.response` and /api/chat `.message.content`).
185
- processNdjsonLine(line) {
186
- const parsed = JSON.parse(line);
187
- if (parsed.response !== undefined) {
188
- parsed.response = this.push(parsed.response);
189
- if (parsed.done === true) parsed.response += this.flush();
190
- return parsed;
191
- }
192
- if (parsed.message?.content !== undefined) {
193
- parsed.message.content = this.push(parsed.message.content);
194
- if (parsed.done === true) parsed.message.content += this.flush();
195
- return parsed;
196
- }
197
- if (parsed.done === true && this.buffer) {
198
- parsed.flushedTail = this.flush();
199
- }
200
- return parsed;
201
- }
202
-
203
- // Async generator wrapper for any chunked UTF-8 / string NDJSON stream.
204
- async *interceptNdjson(readableStream) {
205
- let lineBuf = '';
206
- const dec = new TextDecoder();
207
- for await (const chunk of readableStream) {
208
- lineBuf += typeof chunk === 'string' ? chunk : dec.decode(chunk, { stream: true });
209
- const lines = lineBuf.split('\n');
210
- lineBuf = lines.pop() || '';
211
- for (const line of lines) {
212
- if (line.trim()) yield this.processNdjsonLine(line);
213
- }
214
- }
215
- if (lineBuf.trim()) yield this.processNdjsonLine(lineBuf);
216
- const tail = this.flush();
217
- if (tail) yield { response: tail, done: true };
218
- }
219
-
220
- getStats() {
221
- return {
222
- chunksProcessed: this.chunksProcessed,
223
- sealsApplied: this.sealsApplied,
224
- withheld: { ...this.session.counts },
225
- alerts: this.alerts.slice(),
226
- };
227
- }
228
- }
1
+ // Zero-dependency Streaming Token Guard for LLM NDJSON / text streams.
2
+ // Prevents credentials and PII split across arbitrary token boundaries (e.g. "sk-" + "ant-..." or "123-" + "45-6789")
3
+ // from leaking mid-stream before sealing/redaction triggers.
4
+ // Ported from StreamCanaryInterceptor's cross-token tail-prefix buffering design.
5
+ // 1.4.0: the whole trailing token is always held (not only known prefixes), cuts never fall inside a detected
6
+ // value, PEM bodies and multi-word values (titled names, addresses, IBANs, "password is ...") are held, and
7
+ // already-emitted context feeds look-behind detectors.
8
+ import { detect, SealSession } from './membrane-core.js';
9
+
10
+ export const SECRET_PREFIXES = [
11
+ 'sk-ant-',
12
+ 'sk-proj-',
13
+ 'sk-',
14
+ 'AIza',
15
+ 'ghp_',
16
+ 'gho_',
17
+ 'github_pat_',
18
+ 'AKIA',
19
+ 'xoxb-',
20
+ 'xoxp-',
21
+ 'Bearer ',
22
+ '-----BEGIN ',
23
+ ];
24
+
25
+ const MAX_PREFIX_LEN = Math.max(...SECRET_PREFIXES.map((p) => p.length));
26
+
27
+ // Already-emitted raw text kept so that look-behind detectors ("password is <value>", "account no 12345",
28
+ // "Bearer <token>") still see their keyword when the value arrives in a later chunk. It is never emitted again.
29
+ const CONTEXT_CHARS = 64;
30
+
31
+ // Tail patterns for detectors whose matches contain whitespace, so a "hold the last word" rule is not enough.
32
+ const MULTIWORD_TAILS = [
33
+ // A titled name in progress: "Dr", "Dr.", "Dr. Elena", "Dr. Elena Ruiz" (PERSON allows up to three names).
34
+ /\b(?:Dr|Mr|Mrs|Ms|Mx|Prof|Sr|Sra|Herr|Frau)\.?(?:\s{1,4}[A-Z][a-z'’-]*){0,3}\s{0,4}$/,
35
+ // A street address in progress: "12", "12 Main", "12 Main Street".
36
+ /\b\d{1,6}(?:\s{1,4}[A-Z][a-z]*){0,5}\s{0,4}$/,
37
+ // An IBAN written in groups of four.
38
+ /\b[A-Z]{2}\d{2}(?:\s?[A-Z0-9]{1,4}){0,8}\s?$/,
39
+ // A keyword whose value is detected by look-behind, still waiting for the value.
40
+ /\b(?:password|passwd|passcode|pin|secret|api[_-]?key|token|account|acct|patient|customer|member|policy|case|invoice|Bearer)\b[^\n]{0,24}$/i,
41
+ ];
42
+
43
+ // Returns how many trailing characters of `text` must be held back because they could still become (part of)
44
+ // a secret or PII value once more text arrives.
45
+ export function tailHoldLength(text) {
46
+ if (!text) return 0;
47
+ let hold = 0;
48
+
49
+ // 1. Partial match against any known secret prefix (e.g. trailing "sk-" or "ghp")
50
+ const maxCheck = Math.min(text.length, MAX_PREFIX_LEN);
51
+ for (const pfx of SECRET_PREFIXES) {
52
+ for (let len = 1; len <= Math.min(pfx.length, maxCheck); len++) {
53
+ if (text.endsWith(pfx.slice(0, len))) hold = Math.max(hold, len);
54
+ }
55
+ }
56
+
57
+ // 2. Active secret prefix still accumulating token chars right up to the end of the chunk
58
+ for (const pfx of SECRET_PREFIXES) {
59
+ const idx = text.lastIndexOf(pfx);
60
+ if (idx !== -1) {
61
+ const tail = text.slice(idx);
62
+ if (/^[A-Za-z0-9_\-./+=: ]+$/.test(tail) && tail.length < 256) {
63
+ hold = Math.max(hold, tail.length);
64
+ }
65
+ }
66
+ }
67
+
68
+ // 3. Partial trailing digit/separator run (could become SSN 123-45-6789, phone, or card number)
69
+ const digitTail = text.match(/[+\d][\d\s.\-()]{0,22}$/);
70
+ if (digitTail) hold = Math.max(hold, digitTail[0].length);
71
+
72
+ // 4. The whole trailing run of non-whitespace characters, however long and even when it is the whole text.
73
+ // Every single-token detector (email, JWT, API key, URL with a token, card, SSN) can only match a run that
74
+ // has ended, so the run in progress is always held. (1.3.0 capped this at 32 characters and skipped it when
75
+ // the run was the whole buffer, so a fragment that arrived as its own chunk was emitted at once.)
76
+ const wordTail = text.match(/\S+$/);
77
+ if (wordTail) hold = Math.max(hold, wordTail[0].length);
78
+
79
+ // 5. A PEM block that has begun but not ended (its body contains newlines, so rule 4 cannot cover it).
80
+ const begin = text.lastIndexOf('-----BEGIN ');
81
+ if (begin !== -1 && !/-----END [A-Z0-9 ]+-----/.test(text.slice(begin))) hold = Math.max(hold, text.length - begin);
82
+
83
+ // 6. Detectors whose matches span whitespace.
84
+ for (const re of MULTIWORD_TAILS) {
85
+ const m = text.match(re);
86
+ if (m) hold = Math.max(hold, m[0].length);
87
+ }
88
+
89
+ return Math.min(hold, text.length);
90
+ }
91
+
92
+ export class StreamSealGuard {
93
+ constructor({ session = null, mode = 'seal', maxBuffer = 4096 } = {}) {
94
+ this.session = session || new SealSession();
95
+ this.mode = mode; // 'seal' (typed placeholders) | 'redact' ([REDACTED:<TYPE>])
96
+ this.maxBuffer = maxBuffer;
97
+ this.buffer = '';
98
+ this.context = '';
99
+ this.chunksProcessed = 0;
100
+ this.sealsApplied = 0;
101
+ this.alerts = [];
102
+ }
103
+
104
+ // Spans of `text`, detected with the already-emitted context in front so look-behind detectors work.
105
+ // Coordinates are relative to `text`; a span that began in the context is clipped to start at 0.
106
+ _spans(text) {
107
+ const ctx = this.context;
108
+ const spans = [];
109
+ for (const sp of detect(ctx + text)) {
110
+ const end = sp.end - ctx.length;
111
+ if (end <= 0) continue;
112
+ const start = Math.max(0, sp.start - ctx.length);
113
+ spans.push({ start, end, type: sp.type, value: text.slice(start, end) });
114
+ }
115
+ return spans;
116
+ }
117
+
118
+ _seal(text, spans) {
119
+ if (!text) return '';
120
+ const inside = spans.filter((sp) => sp.end <= text.length);
121
+ if (inside.length === 0) return text;
122
+ this.sealsApplied += inside.length;
123
+ this.alerts.push({
124
+ chunkIndex: this.chunksProcessed,
125
+ types: [...new Set(inside.map((s) => s.type))],
126
+ count: inside.length,
127
+ });
128
+ if (this.mode === 'redact') {
129
+ let out = '';
130
+ let pos = 0;
131
+ for (const sp of inside) {
132
+ out += text.slice(pos, sp.start) + `[REDACTED:${sp.type}]`;
133
+ pos = sp.end;
134
+ }
135
+ return out + text.slice(pos);
136
+ }
137
+ return this.session.apply(text, inside);
138
+ }
139
+
140
+ _emit(raw, spans) {
141
+ const out = this._seal(raw, spans);
142
+ this.context = (this.context + raw).slice(-CONTEXT_CHARS);
143
+ return out;
144
+ }
145
+
146
+ // Kept for callers that used it in 1.3.0: seal a self-contained piece of text.
147
+ _sealWindow(text) { return this._seal(text, text ? this._spans(text) : []); }
148
+
149
+ // Feed one streaming token/chunk; returns the safe-to-emit prefix while holding any boundary-split candidate.
150
+ push(chunk) {
151
+ this.chunksProcessed++;
152
+ const combined = this.buffer + String(chunk ?? '');
153
+ if (!combined) return '';
154
+
155
+ const spans = this._spans(combined);
156
+ let cut = combined.length - tailHoldLength(combined);
157
+
158
+ // Never cut inside a detected value, and never emit a value that ends in the trailing whitespace: it may
159
+ // still grow ("Dr. Elena " + "Ruiz", "415 555 " + "0100"). Repeat until the cut is stable.
160
+ for (let moved = true; moved;) {
161
+ moved = false;
162
+ for (const sp of spans) {
163
+ const straddles = sp.start < cut && sp.end > cut;
164
+ const growing = sp.start < cut && combined.slice(sp.end).trim() === '';
165
+ if (straddles || growing) { cut = sp.start; moved = true; }
166
+ }
167
+ }
168
+
169
+ // Bounded memory: never hold more than maxBuffer characters; the oldest part is sealed and emitted.
170
+ if (combined.length - cut > this.maxBuffer) cut = combined.length - this.maxBuffer;
171
+
172
+ this.buffer = combined.slice(cut);
173
+ return this._emit(combined.slice(0, cut), spans);
174
+ }
175
+
176
+ // Flush remaining buffered tail at end-of-stream.
177
+ flush() {
178
+ const rest = this.buffer;
179
+ this.buffer = '';
180
+ if (!rest) return '';
181
+ return this._emit(rest, this._spans(rest));
182
+ }
183
+
184
+ // Process one Ollama-style NDJSON line (supports both /api/generate `.response` and /api/chat `.message.content`).
185
+ processNdjsonLine(line) {
186
+ const parsed = JSON.parse(line);
187
+ if (parsed.response !== undefined) {
188
+ parsed.response = this.push(parsed.response);
189
+ if (parsed.done === true) parsed.response += this.flush();
190
+ return parsed;
191
+ }
192
+ if (parsed.message?.content !== undefined) {
193
+ parsed.message.content = this.push(parsed.message.content);
194
+ if (parsed.done === true) parsed.message.content += this.flush();
195
+ return parsed;
196
+ }
197
+ if (parsed.done === true && this.buffer) {
198
+ parsed.flushedTail = this.flush();
199
+ }
200
+ return parsed;
201
+ }
202
+
203
+ // Async generator wrapper for any chunked UTF-8 / string NDJSON stream.
204
+ async *interceptNdjson(readableStream) {
205
+ let lineBuf = '';
206
+ const dec = new TextDecoder();
207
+ for await (const chunk of readableStream) {
208
+ lineBuf += typeof chunk === 'string' ? chunk : dec.decode(chunk, { stream: true });
209
+ const lines = lineBuf.split('\n');
210
+ lineBuf = lines.pop() || '';
211
+ for (const line of lines) {
212
+ if (line.trim()) yield this.processNdjsonLine(line);
213
+ }
214
+ }
215
+ if (lineBuf.trim()) yield this.processNdjsonLine(lineBuf);
216
+ const tail = this.flush();
217
+ if (tail) yield { response: tail, done: true };
218
+ }
219
+
220
+ getStats() {
221
+ return {
222
+ chunksProcessed: this.chunksProcessed,
223
+ sealsApplied: this.sealsApplied,
224
+ withheld: { ...this.session.counts },
225
+ alerts: this.alerts.slice(),
226
+ };
227
+ }
228
+ }