@eyeoverthink/sva-gate 2.0.1 → 2.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.
@@ -49,6 +49,9 @@ export function stripHidden(text) { return String(text ?? '').replace(HIDDEN, ''
49
49
  const SECRET_PATTERNS = [
50
50
  [/\bsk-[A-Za-z0-9_-]{20,}\b/g, '[REDACTED:api-key]'],
51
51
  [/\bgh[pousr]_[A-Za-z0-9]{30,}\b/g, '[REDACTED:github-token]'],
52
+ [/\bgithub_pat_[A-Za-z0-9_]{30,}\b/g, '[REDACTED:github-token]'],
53
+ [/\b(?:sk|rk)_live_[A-Za-z0-9]{16,}\b/g, '[REDACTED:api-key]'],
54
+ [/\bhf_[A-Za-z0-9]{30,}\b/g, '[REDACTED:api-key]'],
52
55
  [/\bAIza[0-9A-Za-z_-]{30,}\b/g, '[REDACTED:google-key]'],
53
56
  [/\bxox[abpr]-[A-Za-z0-9-]{10,}\b/g, '[REDACTED:slack-token]'],
54
57
  [/-----BEGIN [A-Z ]*PRIVATE KEY-----[\s\S]*?-----END [A-Z ]*PRIVATE KEY-----/g, '[REDACTED:private-key]'],
@@ -76,12 +79,24 @@ export function wrapUntrusted(source, content, evidence = null) {
76
79
  return { text: `<untrusted source="${String(source).replace(/"/g, "'")}"${ev}>\n${clean}\n</untrusted>${warn}`, scan };
77
80
  }
78
81
 
82
+ // Recursive deletes of a root, a home directory or a whole drive, and disk-wiping commands. A heuristic list, not a
83
+ // shell parser: it catches the common spellings (flags in any order, PowerShell and cmd), not every possible one.
84
+ const DESTRUCTIVE = [
85
+ /\brm\s+(?:-{1,2}[\w-]+\s+)*-(?:[a-zA-Z]*[rR][a-zA-Z]*|-recursive)\s+(?:-{1,2}[\w-]+\s+)*(?:\/|~\/?|\$HOME\/?|\/\*|\*)(?=\s|$|;|&|\|)/,
86
+ /\brm\b[^\n;&|]*--no-preserve-root/,
87
+ /\bRemove-Item\b(?=[^\n;]*-Recurse)[^\n;]*?(?:\s|['"])(?:[A-Za-z]:[\\/]?|[\\/]|~[\\/]?|\$HOME|\$env:USERPROFILE)(?:\*)?['"]?(?=\s|$|;)/i,
88
+ /\b(?:del|erase|rd|rmdir)\b(?=[^\n;&|]*\/s)[^\n;&|]*\s[A-Za-z]:[\\/]?\*?(?=\s|$|;|&|\|)/i,
89
+ /\bformat\s+[a-z]:/i,
90
+ /\bmkfs\b/i,
91
+ /\bdd\s+if=.*of=\/dev\//i,
92
+ ];
93
+
79
94
  /** Screen a mission goal from the operator. Only blocks clearly destructive intent; everything else passes with notes. */
80
95
  export function screenGoal(goal) {
81
96
  const s = String(goal ?? '');
82
97
  const notes = [];
83
98
  if (s.length > 20000) return { ok: false, reason: 'goal too long (20k char limit)' };
84
- if (/\b(rm\s+-rf\s+\/|format\s+[a-z]:|mkfs|dd\s+if=.*of=\/dev\/)/i.test(s)) return { ok: false, reason: 'goal requests destructive system commands' };
99
+ if (DESTRUCTIVE.some((re) => re.test(s))) return { ok: false, reason: 'goal requests destructive system commands' };
85
100
  const scan = scanInjection(s);
86
101
  if (scan.flags.length) notes.push(`instruction-like patterns: ${scan.flags.join(', ')}`);
87
102
  return { ok: true, notes, scan };
@@ -1,166 +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
- import { detect, SealSession } from './membrane-core.js';
6
-
7
- export const SECRET_PREFIXES = [
8
- 'sk-ant-',
9
- 'sk-proj-',
10
- 'sk-',
11
- 'AIza',
12
- 'ghp_',
13
- 'gho_',
14
- 'github_pat_',
15
- 'AKIA',
16
- 'xoxb-',
17
- 'xoxp-',
18
- 'Bearer ',
19
- '-----BEGIN ',
20
- ];
21
-
22
- const MAX_PREFIX_LEN = Math.max(...SECRET_PREFIXES.map((p) => p.length));
23
- const CRED_CHAR = /[A-Za-z0-9_\-./+=:]/;
24
-
25
- // Returns how many trailing characters of `text` could be the start of a split secret prefix,
26
- // an in-progress token/key, an email local-part, or a partial SSN/phone/card digit run.
27
- export function tailHoldLength(text) {
28
- if (!text) return 0;
29
- let hold = 0;
30
-
31
- // 1. Partial match against any known secret prefix (e.g. trailing "sk-" or "ghp")
32
- const maxCheck = Math.min(text.length, MAX_PREFIX_LEN);
33
- for (const pfx of SECRET_PREFIXES) {
34
- for (let len = 1; len <= Math.min(pfx.length, maxCheck); len++) {
35
- if (text.endsWith(pfx.slice(0, len))) hold = Math.max(hold, len);
36
- }
37
- }
38
-
39
- // 2. Active secret prefix still accumulating token chars right up to the end of the chunk
40
- for (const pfx of SECRET_PREFIXES) {
41
- const idx = text.lastIndexOf(pfx);
42
- if (idx !== -1) {
43
- const tail = text.slice(idx);
44
- if (/^[A-Za-z0-9_\-./+=: ]+$/.test(tail) && tail.length < 256) {
45
- hold = Math.max(hold, tail.length);
46
- }
47
- }
48
- }
49
-
50
- // 3. Partial trailing digit/separator run (could become SSN 123-45-6789, phone, or card number)
51
- const digitTail = text.match(/[+\d][\d\s.\-()]{0,22}$/);
52
- if (digitTail) hold = Math.max(hold, digitTail[0].length);
53
-
54
- // 4. Partial trailing email-like token containing '@' or identifier before '@'
55
- const emailTail = text.match(/[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]*$/);
56
- if (emailTail) hold = Math.max(hold, emailTail[0].length);
57
-
58
- return Math.min(hold, text.length);
59
- }
60
-
61
- export class StreamSealGuard {
62
- constructor({ session = null, mode = 'seal', maxBuffer = 4096 } = {}) {
63
- this.session = session || new SealSession();
64
- this.mode = mode; // 'seal' (typed placeholders) | 'redact' ([REDACTED:<TYPE>])
65
- this.maxBuffer = maxBuffer;
66
- this.buffer = '';
67
- this.chunksProcessed = 0;
68
- this.sealsApplied = 0;
69
- this.alerts = [];
70
- }
71
-
72
- _sealWindow(text) {
73
- if (!text) return '';
74
- const spans = detect(text);
75
- if (spans.length === 0) return text;
76
- this.sealsApplied += spans.length;
77
- this.alerts.push({
78
- chunkIndex: this.chunksProcessed,
79
- types: [...new Set(spans.map((s) => s.type))],
80
- count: spans.length,
81
- });
82
- if (this.mode === 'redact') {
83
- let out = '';
84
- let pos = 0;
85
- for (const sp of spans) {
86
- out += text.slice(pos, sp.start) + `[REDACTED:${sp.type}]`;
87
- pos = sp.end;
88
- }
89
- return out + text.slice(pos);
90
- }
91
- return this.session.apply(text, spans);
92
- }
93
-
94
- // Feed one streaming token/chunk; returns the safe-to-emit prefix while holding any boundary-split candidate.
95
- push(chunk) {
96
- this.chunksProcessed++;
97
- const combined = this.buffer + String(chunk ?? '');
98
- if (!combined) return '';
99
-
100
- // Never hold unbounded memory on adversarial non-whitespace streams
101
- let hold = tailHoldLength(combined);
102
- if (hold > this.maxBuffer) hold = 0;
103
-
104
- // Also hold the trailing identifier if we are mid-word next to a potential '@' or secret
105
- if (hold === 0 && CRED_CHAR.test(combined[combined.length - 1])) {
106
- const wordTail = combined.match(/[A-Za-z0-9._%+-]{1,32}$/);
107
- if (wordTail && wordTail[0].length < combined.length) hold = wordTail[0].length;
108
- }
109
-
110
- const emitRaw = hold > 0 ? combined.slice(0, combined.length - hold) : combined;
111
- this.buffer = hold > 0 ? combined.slice(combined.length - hold) : '';
112
- return this._sealWindow(emitRaw);
113
- }
114
-
115
- // Flush remaining buffered tail at end-of-stream.
116
- flush() {
117
- const rest = this.buffer;
118
- this.buffer = '';
119
- return this._sealWindow(rest);
120
- }
121
-
122
- // Process one Ollama-style NDJSON line (supports both /api/generate `.response` and /api/chat `.message.content`).
123
- processNdjsonLine(line) {
124
- const parsed = JSON.parse(line);
125
- if (parsed.response !== undefined) {
126
- parsed.response = this.push(parsed.response);
127
- if (parsed.done === true) parsed.response += this.flush();
128
- return parsed;
129
- }
130
- if (parsed.message?.content !== undefined) {
131
- parsed.message.content = this.push(parsed.message.content);
132
- if (parsed.done === true) parsed.message.content += this.flush();
133
- return parsed;
134
- }
135
- if (parsed.done === true && this.buffer) {
136
- parsed.flushedTail = this.flush();
137
- }
138
- return parsed;
139
- }
140
-
141
- // Async generator wrapper for any chunked UTF-8 / string NDJSON stream.
142
- async *interceptNdjson(readableStream) {
143
- let lineBuf = '';
144
- const dec = new TextDecoder();
145
- for await (const chunk of readableStream) {
146
- lineBuf += typeof chunk === 'string' ? chunk : dec.decode(chunk, { stream: true });
147
- const lines = lineBuf.split('\n');
148
- lineBuf = lines.pop() || '';
149
- for (const line of lines) {
150
- if (line.trim()) yield this.processNdjsonLine(line);
151
- }
152
- }
153
- if (lineBuf.trim()) yield this.processNdjsonLine(lineBuf);
154
- const tail = this.flush();
155
- if (tail) yield { response: tail, done: true };
156
- }
157
-
158
- getStats() {
159
- return {
160
- chunksProcessed: this.chunksProcessed,
161
- sealsApplied: this.sealsApplied,
162
- withheld: { ...this.session.counts },
163
- alerts: this.alerts.slice(),
164
- };
165
- }
166
- }
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
+ }
package/src/mcp-server.js CHANGED
@@ -2,20 +2,24 @@
2
2
  // Exposes 6 deterministic verification tools spanning all 3 SVA layers:
3
3
  // 1. sva_seal_text (EMA/1 privacy membrane + StreamSealGuard + injection scan)
4
4
  // 2. sva_mint_receipt (SVA-ER/1 Ed25519 + RFC 6962 Merkle receipt & OPEG/1 envelope)
5
- // 3. sva_verify_receipt (SVA-ER/1 & IETF draft-zambo-aer1-26 AER-1 v0.4 verifier)
5
+ // 3. sva_verify_receipt (SVA-ER/1 & AER-1 v0.4 verifier; AER-1 = individual Internet-Draft draft-zambo-aer1-26)
6
6
  // 4. sva_opeg_check (OPEG/1 S4_COMMIT fail-closed execution gate)
7
7
  // 5. sva_judge_audit (SVA-JEV/1 calibrated epistemic judge & planted-fake gate)
8
8
  // 6. sva_crystallize_skill (VSC/1 zero-LLM binder induction + leave-one-out check)
9
9
 
10
10
  import readline from 'node:readline';
11
+ import fs from 'node:fs';
11
12
  import { mintSvaEr1, verifyAnyReceipt, evaluateOpeg1 } from './receipt.js';
12
13
  import { detect, SealSession, StreamSealGuard, scanInjection } from './membrane.js';
13
14
  import { evaluateSvaJev1 } from './lib/judge-verify.js';
14
- import { induce, leaveOneOut, applySpec, novelWording } from './lib/binder-induction.js';
15
+ import { induce, leaveOneOut, explainApply, novelWording } from './lib/binder-induction.js';
16
+
17
+ // Read from package.json so serverInfo never drifts from the published version (it said 2.0.0 in 2.0.2).
18
+ const PKG_VERSION = JSON.parse(fs.readFileSync(new URL('../package.json', import.meta.url), 'utf8')).version;
15
19
 
16
20
  export const SERVER_INFO = {
17
21
  name: '@eyeoverthink/sva-gate',
18
- version: '2.0.0',
22
+ version: PKG_VERSION,
19
23
  };
20
24
 
21
25
  export const MCP_TOOLS = [
@@ -48,7 +52,7 @@ export const MCP_TOOLS = [
48
52
  },
49
53
  {
50
54
  name: 'sva_verify_receipt',
51
- description: 'Verify an SVA-ER/1 receipt (Ed25519 + RFC 6962 Merkle + deliverable digest + RFC 3339 clock) OR an IETF draft-zambo-aer1-26 AER-1 v0.4 receipt offline.',
55
+ description: 'Verify an SVA-ER/1 receipt (Ed25519 + RFC 6962 Merkle + deliverable digest + RFC 3339 clock) OR an AER-1 v0.4 receipt (individual Internet-Draft draft-zambo-aer1-26) offline. AER-1 receipts carry no issuer signature and are reported as integrity_only.',
52
56
  inputSchema: {
53
57
  type: 'object',
54
58
  required: ['receipt'],
@@ -174,12 +178,13 @@ function runTool(name, args = {}) {
174
178
  const loo = { passed: looPassed, total: looRows.length, ok: looRows.length > 0 && looPassed === looRows.length };
175
179
  const out = { induced: Boolean(spec), error: induced?.error ?? null, leaveOneOut: loo, spec };
176
180
  if (spec && typeof args.testTask === 'string') {
177
- const bound = applySpec(spec, args.testTask);
181
+ const { input: bound, refused, detail } = explainApply(spec, args.testTask);
178
182
  const novel = novelWording(pos, args.testTask);
179
183
  out.testResult = {
180
184
  routed: Boolean(bound && novel.length === 0),
181
185
  novelWordingRejected: novel.length > 0 || !bound,
182
186
  novelWords: novel,
187
+ refused: refused ? { reason: refused, detail } : null,
183
188
  bound,
184
189
  };
185
190
  }
package/src/receipt.js CHANGED
@@ -1,4 +1,4 @@
1
- // Zero-dependency SVA-ER/1, IETF AER-1 v0.4, and OPEG/1 minting & verification engine (Node 22+ node:crypto).
1
+ // Zero-dependency SVA-ER/1, AER-1 v0.4 (draft-zambo-aer1-26), and OPEG/1 minting & verification engine (Node 22+ node:crypto).
2
2
  // Follows specs/SVA-ER-1.md, specs/OPEG-1.md, and draft-zambo-aer1-26 (kit 1.6.1) strictly fail-closed.
3
3
 
4
4
  import crypto from 'node:crypto';
@@ -0,0 +1,84 @@
1
+ // Regression tests for the 2026-12-04 review: the bundled privacy membrane (stream guard leak, strict unseal,
2
+ // regex cost), the bundled skill crystallizer (quantity/negation/ambiguity refusals), and README/serverInfo versions.
3
+ import test from 'node:test';
4
+ import assert from 'node:assert/strict';
5
+ import fs from 'node:fs';
6
+ import path from 'node:path';
7
+ import { fileURLToPath } from 'node:url';
8
+ import {
9
+ detect, SealSession, StreamSealGuard, induce, applySpec, explainApply, novelWording, createMcpHandler,
10
+ } from '../src/index.js';
11
+ import { SERVER_INFO } from '../src/mcp-server.js';
12
+
13
+ const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
14
+ const PKG = JSON.parse(fs.readFileSync(path.join(ROOT, 'package.json'), 'utf8'));
15
+ // A public example token, assembled at run time so secret scanners do not flag the test file.
16
+ const JWT = ['eyJhbGciOiJIUzI1NiJ9', 'eyJzdWIiOiIxMjM0NTY3ODkwIn0', 'SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c'].join('.');
17
+ const PEM = '-----BEGIN PRIVATE KEY-----\nMIIEvQIBADANBgkqhkiG9w0BAQEFAASC\n-----END PRIVATE KEY-----';
18
+
19
+ const stream = (chunks) => { const g = new StreamSealGuard(); return { out: chunks.map((c) => g.push(c)).join('') + g.flush(), g }; };
20
+
21
+ test('bundled StreamSealGuard: fragments that arrive as their own chunk do not leak (2.0.x leaked these)', () => {
22
+ const cases = [
23
+ [['Contact', ' el', 'ena', '@', 'north', 'star', '.org', ' today'], 'elena', 'northstar'],
24
+ [['the password is', ' hunter22', ' ok'], 'hunter22'],
25
+ [['auth ', JWT.slice(0, 10), JWT.slice(10), ' end'], 'eyJhbGciOi', 'SflKxw'],
26
+ [['key: ', PEM.slice(0, 40), PEM.slice(40), ' done'], 'MIIEvQ'],
27
+ [['Patient ', 'Dr', '. Elena', ' Ruiz', ' was seen'], 'Elena', 'Ruiz'],
28
+ [['key sk-' + 'A'.repeat(40), 'B'.repeat(20) + ' done'], 'AAAA', 'BBBB'],
29
+ ];
30
+ for (const [chunks, ...secrets] of cases) {
31
+ const { out, g } = stream(chunks);
32
+ for (const s of secrets) assert.ok(!out.includes(s), `${JSON.stringify(chunks)} leaked ${s}: ${out}`);
33
+ assert.equal(g.session.audit(out).clean, true);
34
+ }
35
+ });
36
+
37
+ test('bundled membrane: strict unseal, single-pass unseal, linear detection', () => {
38
+ const s = new SealSession();
39
+ s.apply('mail elena@northstar.org', detect('mail elena@northstar.org'));
40
+ assert.equal(s.unseal('EMAIL_1 and ⟦EMAIL_1⟧', { strict: true }), 'EMAIL_1 and elena@northstar.org');
41
+ const t = performance.now();
42
+ detect('a.'.repeat(50000));
43
+ detect('token' + ' '.repeat(100000));
44
+ assert.ok(performance.now() - t < 3000);
45
+ });
46
+
47
+ test('bundled crystallizer refuses quantity words, negations and ambiguous rules', () => {
48
+ const skill = { params: { properties: {
49
+ price: { type: 'number' }, d1: { type: 'number', description: 'decimal fraction' }, d2: { type: 'number', description: 'decimal fraction' } } } };
50
+ const pos = [
51
+ { task: 'A $100 jacket is 20% off, then an extra 10% off. What is the final price?', input: { price: 100, d1: 0.2, d2: 0.1 } },
52
+ { task: 'A $80 pair of shoes is 15% off, then an extra 20% off. What is the final price?', input: { price: 80, d1: 0.15, d2: 0.2 } },
53
+ { task: 'A $150 backpack is 30% off, then an extra 5% off. What is the final price?', input: { price: 150, d1: 0.3, d2: 0.05 } },
54
+ ];
55
+ const { spec } = induce(pos, [], skill);
56
+ assert.equal(applySpec(spec, 'Two $240 coats are each 25% off, then an extra 10% off. What is the final price?'), null);
57
+ assert.equal(explainApply(spec, 'A $240 coat is not 25% off, then an extra 10% off. What is the final price?').refused, 'modifier');
58
+ assert.ok(novelWording(pos, 'A $240 coat is not 25% off, then an extra 10% off. What is the final price?').length > 0);
59
+ const posEq = pos.map((e) => ({ task: e.task.replace(/extra \d+%/, `extra ${e.input.d1 * 100}%`), input: { ...e.input, d2: e.input.d1 } }));
60
+ const eq = induce(posEq, [], skill).spec;
61
+ assert.equal(explainApply(eq, 'A $240 coat is 40% off, then an extra 10% off. What is the final price?').refused, 'ambiguous');
62
+ });
63
+
64
+ test('MCP sva_crystallize_skill reports the refusal reason', () => {
65
+ const handle = createMcpHandler();
66
+ const res = handle({ jsonrpc: '2.0', id: 1, method: 'tools/call', params: { name: 'sva_crystallize_skill', arguments: {
67
+ skill: { params: { properties: { price: { type: 'number' }, d1: { type: 'number', description: 'decimal fraction' }, d2: { type: 'number', description: 'decimal fraction' } } } },
68
+ examples: [
69
+ { task: 'A $100 jacket is 20% off, then an extra 10% off. What is the final price?', input: { price: 100, d1: 0.2, d2: 0.1 } },
70
+ { task: 'A $150 backpack is 30% off, then an extra 5% off. What is the final price?', input: { price: 150, d1: 0.3, d2: 0.05 } },
71
+ ],
72
+ testTask: 'Two $240 coats are each 25% off, then an extra 10% off. What is the final price?',
73
+ } } });
74
+ const out = JSON.parse(res.result.content[0].text);
75
+ assert.equal(out.testResult.routed, false);
76
+ assert.equal(out.testResult.refused.reason, 'modifier');
77
+ });
78
+
79
+ test('README heading and MCP serverInfo match package.json version', () => {
80
+ const readme = fs.readFileSync(path.join(ROOT, 'README.md'), 'utf8');
81
+ assert.equal(readme.split(/\r?\n/)[0], `# \`@eyeoverthink/sva-gate\` (\`v${PKG.version}\`)`);
82
+ assert.equal(SERVER_INFO.version, PKG.version);
83
+ assert.ok(!/IETF `?draft-zambo/.test(readme), 'AER-1 is an individual draft, not an IETF document');
84
+ });