@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.
package/README.md CHANGED
@@ -1,4 +1,12 @@
1
- # `@eyeoverthink/sva-gate` (`v1.0.0`)
1
+ # `@eyeoverthink/sva-gate` (`v2.1.0`)
2
+
3
+ > **2.1.0 — privacy membrane and skill crystallizer fixes** (synced with `@eyeoverthink/privacy-membrane` 1.4.0 and
4
+ > `@eyeoverthink/skill-crystallizer` 1.3.0). `StreamSealGuard` no longer leaks a JWT, PEM key, email, password or
5
+ > titled name whose fragment arrives as its own chunk; `SealSession.unseal(text, { strict: true })` restores only the
6
+ > exact `⟦TYPE_n⟧` placeholders the session issued; detection is linear on adversarial input. The skill binder now
7
+ > refuses quantity and negation words its examples never used ("Two $240 coats…", "…is not 25% off…") and tasks on
8
+ > which two rules that both fit the examples disagree; `explainApply` says why. MCP `serverInfo.version` now reports
9
+ > the package version.
2
10
 
3
11
  > **2.0.0 — breaking: verification now asks whose signature counts.** A receipt is `ok` only when it is intact
4
12
  > **and** signed by a key you name in `expectedPublicKeys` (CLI: `--key <hex>`). Without it an intact receipt is
@@ -34,12 +42,12 @@ Gives any agent **6 deterministic verification tools** over stdio JSON-RPC 2.0:
34
42
 
35
43
  | MCP Tool | Layer | What It Enforces |
36
44
  | --- | --- | --- |
37
- | `sva_seal_text` | Layer 2 (`EMA/1`) | Seals PII/secrets (emails, SSNs, API keys, phones) into typed placeholders + `StreamSealGuard` cross-token split-secret sealing + zero-width prompt-injection scan |
45
+ | `sva_seal_text` | Layer 2 (`EMA/1`) | Seals PII/secrets (emails, SSNs, API keys, phones) into typed placeholders + `StreamSealGuard` cross-token split-secret sealing + keyword/zero-width prompt-injection scan |
38
46
  | `sva_mint_receipt` | Layer 1 (`SVA-ER/1`) | Mints an Ed25519-signed, RFC 6962 `0x00`/`0x01` Merkle-proven receipt + matching `OPEG/1` `S4_COMMIT` envelope |
39
- | `sva_verify_receipt` | Layer 1 (`SVA-ER/1` + `AER-1`) | Verifies **`SVA-ER/1`** receipts AND **IETF `draft-zambo-aer1-26` (`AER-1` v0.4)** receipts offline |
47
+ | `sva_verify_receipt` | Layer 1 (`SVA-ER/1` + `AER-1`) | Verifies **`SVA-ER/1`** receipts against a key you pin, and checks **`AER-1` v0.4** receipts (an individual Internet-Draft, `draft-zambo-aer1-26`, not an IETF standard) offline. AER-1 receipts carry no issuer signature, so they are reported as `integrity_only` |
40
48
  | `sva_opeg_check` | Layer 2 (`OPEG/1`) | Fail-closed pre-commit gate: blocks `DIRECT_INFERENCE`, tampered `R_san` digests, and invalid receipts (`sva-er/1` or `aer-1`) |
41
- | `sva_judge_audit` | Layer 3 (`SVA-JEV/1`) | Calibrated epistemic judge gates: Wilson 95% CI > 2/3, author self-vote exclusion, mandatory verbatim `>= 12`-char quotes, hidden planted-fake traps, and zero-LLM `new_terms` invention scanner |
42
- | `sva_crystallize_skill` | Layer 1 (`VSC/1`) | Zero-LLM deterministic parameter binder induction with leave-one-out verification and novel-wording near-miss rejection |
49
+ | `sva_judge_audit` | Layer 3 (`SVA-JEV/1`) | Rule checks over judge results you supply (no model call): Wilson 95% CI > 2/3 on your counts, author self-vote exclusion, mandatory verbatim `>= 12`-char quotes, hidden planted-fake traps, and zero-LLM `new_terms` invention scanner |
50
+ | `sva_crystallize_skill` | Layer 1 (`VSC/1`) | Zero-LLM deterministic parameter binder induction with leave-one-out verification; refuses novel wording, unseen quantity/negation words and ambiguous rules (`testResult.refused` says why) |
43
51
 
44
52
  ---
45
53
 
@@ -91,6 +99,8 @@ console.log(verifyAnyReceipt(receipt, { deliverable })); // { ok: false,
91
99
  // 2. Seal split-token API keys across streaming chunks
92
100
  const sg = new StreamSealGuard();
93
101
  const safe = ['Key sk-', 'ant-api03-abcdefghijklmnop1234567890 ok'].map((c) => sg.push(c)).join('') + sg.flush();
102
+ // -> 'Key ⟦SECRET_1⟧ ok'. Put values back only in text a person you trust will read; strict ignores bare EMAIL_1 etc.
103
+ const restored = sg.session.unseal(modelReply, { strict: true });
94
104
 
95
105
  // 3. Enforce SVA-JEV/1 epistemic judge gates
96
106
  const verdict = evaluateSvaJev1({
@@ -129,6 +139,10 @@ res = evaluate_sva_jev1({
129
139
 
130
140
  ## Honest Limits
131
141
 
142
+ - **The privacy membrane is regex-based.** It misses IPv6 addresses, SSNs written without dashes and names without a title. Default (lenient) `unseal` also restores `[EMAIL_1]`, `<EMAIL_1>` and the bare word `EMAIL_1`, so any text that names a placeholder receives the real value; use `{ strict: true }` for text shown to others. The streaming guard emits each word when the next whitespace arrives, and only holds what a detector could recognise.
143
+ - **The skill binder gates a fixed list of quantity and negation words before numbers**, not every meaning-changing phrase; treat a routed answer as a draft for templated tasks only.
144
+ - **The prompt-injection scan is a keyword list.** Paraphrases, other languages and homoglyphs score 0.
145
+
132
146
  - **Signatures prove post-signing integrity and key possession**, not that a compromised host didn't fabricate data prior to signing. Local unsynced clocks are explicitly labeled `unattested`.
133
147
  - **`SVA-JEV/1` verdicts are stamped `stability-signal-not-correctness`** — multi-model consensus is never proof of truth.
134
148
  - **Deterministic `new_terms` catches invented numbers and code identifiers**, not subtle semantic paraphrasing.
package/bin/sva-gate.js CHANGED
@@ -26,7 +26,7 @@ Commands:
26
26
  sva-gate seal <text> Seal PII/secrets & scan for prompt injection
27
27
  sva-gate stream-demo Demonstrate StreamSealGuard cross-token sealing
28
28
  sva-gate mint <json-file | inline-json> Mint SVA-ER/1 receipt + OPEG/1 S4_COMMIT envelope
29
- sva-gate verify <receipt.json> [deliverable] --key <hex> Verify SVA-ER/1 or IETF AER-1 v0.4 receipt offline
29
+ sva-gate verify <receipt.json> [deliverable] --key <hex> Verify SVA-ER/1 or AER-1 v0.4 receipt offline
30
30
  sva-gate gate <opeg-envelope.json> --key <hex> Evaluate OPEG/1 S4_COMMIT gate fail-closed
31
31
 
32
32
  --key <hex> Ed25519 public key allowed to have signed (repeatable). Without it an intact
package/package.json CHANGED
@@ -1,8 +1,8 @@
1
1
  {
2
2
  "name": "@eyeoverthink/sva-gate",
3
- "version": "2.0.1",
3
+ "version": "2.1.0",
4
4
  "type": "module",
5
- "description": "Zero-dependency 3-layer verification SDK, CLI, and stdio MCP server for AI agents: SVA-ER/1 & IETF AER-1 receipts, OPEG/1 execution gates, StreamSealGuard split-token privacy membrane, SVA-JEV/1 calibrated epistemic judge, and zero-LLM skill crystallization.",
5
+ "description": "Zero-dependency 3-layer verification SDK, CLI, and stdio MCP server for AI agents: SVA-ER/1 & AER-1 (draft-zambo-aer1) receipts, OPEG/1 execution gates, StreamSealGuard split-token privacy membrane, SVA-JEV/1 rule-based judge checks, and zero-LLM skill crystallization.",
6
6
  "license": "Apache-2.0",
7
7
  "main": "./src/index.js",
8
8
  "types": "./src/index.d.ts",
@@ -38,6 +38,7 @@
38
38
  "files": [
39
39
  "bin/",
40
40
  "src/",
41
+ "test/",
41
42
  "README.md",
42
43
  "LICENSE"
43
44
  ],
package/src/index.d.ts CHANGED
@@ -87,7 +87,8 @@ export class SealSession {
87
87
  placeholder(type: string, value: string): string;
88
88
  apply(text: string, findings: unknown[]): string;
89
89
  values(): Array<{ type: string; value: string }>;
90
- unseal(text: string, opts?: { json?: boolean }): string;
90
+ /** Lenient by default (also restores [EMAIL_1], <EMAIL_1>, bare EMAIL_1); strict restores only exact ⟦TYPE_n⟧ tokens issued by this session. */
91
+ unseal(text: string, opts?: { json?: boolean; strict?: boolean }): string;
91
92
  audit(outbound: string): { clean: boolean; leaks: string[] };
92
93
  }
93
94
  export class MembraneLeak extends Error {
@@ -130,6 +131,11 @@ export function leaveOneOut(
130
131
  ): Array<{ ok: boolean; [k: string]: unknown }>;
131
132
  export function applySpec(spec: Record<string, unknown>, task: string): Record<string, unknown> | null;
132
133
  export function novelWording(pos: Array<{ task: string }>, task: string): string[];
134
+ export function explainApply(
135
+ spec: Record<string, unknown>,
136
+ task: string,
137
+ ): { input: Record<string, unknown> | null; refused: null | 'shape' | 'block-word' | 'context-block' | 'modifier' | 'ambiguous' | 'missing'; detail: unknown };
138
+ export function modifierWords(task: string): string[];
133
139
 
134
140
  export const MCP_TOOLS: Array<{ name: string; description: string; inputSchema: Record<string, unknown> }>;
135
141
  export function createMcpHandler(): (req: Record<string, unknown>) => Record<string, unknown> | null;
package/src/index.js CHANGED
@@ -41,6 +41,8 @@ export {
41
41
  induce,
42
42
  leaveOneOut,
43
43
  applySpec,
44
+ explainApply,
45
+ modifierWords,
44
46
  novelWording,
45
47
  } from './lib/binder-induction.js';
46
48
 
@@ -1,14 +1,17 @@
1
- export {
2
- induce,
3
- leaveOneOut,
4
- applySpec,
5
- novelWording,
6
- } from '../index.js';
7
-
8
- export function numberTokens(task: string): Array<Record<string, unknown>>;
9
- export const shapeOf: (toks: Array<{ kind: string }>) => string;
10
- export function questionWords(task: string): string[];
11
- export function learnBlocks(pos: Array<{ task: string }>, neg: Array<{ task: string }>): unknown[];
12
- export function contested(pos: Array<{ task: string }>, task: string): boolean;
13
- export function wordingOf(task: string, kinds: string[]): string;
14
- export function compileSpec(spec: Record<string, unknown>): (task: string) => Record<string, unknown> | null;
1
+ export {
2
+ induce,
3
+ leaveOneOut,
4
+ applySpec,
5
+ novelWording,
6
+ explainApply,
7
+ modifierWords,
8
+ } from '../index.js';
9
+
10
+ export function numberTokens(task: string): Array<Record<string, unknown>>;
11
+ export const shapeOf: (toks: Array<{ kind: string }>) => string;
12
+ export function questionWords(task: string): string[];
13
+ export function learnBlocks(pos: Array<{ task: string }>, neg: Array<{ task: string }>): { blockWords: string[]; contextBlock: { kinds: string[]; words: string[] } };
14
+ export function contested(pos: Array<{ task: string }>, task: string): { words: string[]; examples: Array<{ task: string }>; tooMany?: number };
15
+ export function wordingOf(task: string, kinds: string[]): string[];
16
+ /** Source text of a self-contained `function bind(task)`. */
17
+ export function compileSpec(spec: Record<string, unknown>): string;
@@ -18,19 +18,41 @@ const round = (x) => Math.round(x * 1e9) / 1e9;
18
18
  export function numberTokens(task) {
19
19
  const s = String(task), out = [];
20
20
  const STOPC = ['and', 'then', 'the', 'that', 'this', 'for', 'with', 'from', 'are', 'was', 'its', 'your'];
21
- const re = /(\$\s?)?(?<![\w.])(-?\d+(?:\.\d+)?)(\s*%|\s?percent\b)?(?:\s?([a-z]+(?:\/[a-z]+)?))?/gi;
21
+ // 1.3.0: "$1,200" is one number (thousands separators), and EUR/GBP/JPY signs mark currency like "$".
22
+ const re = /([$\u20ac\u00a3\u00a5]\s?)?(?<![\w.])(-?(?:\d{1,3}(?:,\d{3})+|\d+)(?:\.\d+)?)(\s*%|\s?percent\b)?(?:\s?([a-z]+(?:\/[a-z]+)?))?/gi;
22
23
  let m;
23
24
  while ((m = re.exec(s))) {
24
25
  const end = m.index + (m[1] || '').length + m[2].length + (m[3] || '').length;
25
26
  const rest = s.slice(end).split(/[,;:?!]|\.(?!\d)|\d/)[0].toLowerCase();
26
27
  const ctx = (rest.match(/[a-z]{3,}/g) || []).filter((w) => !STOPC.includes(w)).slice(0, 3);
27
- out.push({ v: Number(m[2]), kind: m[1] ? 'currency' : m[3] ? 'percent' : 'plain', unit: !m[1] && !m[3] && m[4] ? m[4].toLowerCase() : null, ctx });
28
+ out.push({ v: Number(m[2].replace(/,/g, '')), kind: m[1] ? 'currency' : m[3] ? 'percent' : 'plain', unit: !m[1] && !m[3] && m[4] ? m[4].toLowerCase() : null, ctx });
28
29
  }
29
30
  return out;
30
31
  }
31
32
 
32
33
  export const shapeOf = (toks) => KINDS.map((k) => toks.filter((t) => t.kind === k).length).join(',');
33
34
 
35
+ /**
36
+ * Words that change what the numbers mean without being numbers: quantities written as words ("Two $240 coats"),
37
+ * distributive words ("each", "per"), and negations ("is not 25% off"). 1.2.0 never gated words BEFORE a number, so
38
+ * "Two $240 coats are each 25% off..." routed and answered 162 (correct: 324). A task that uses a modifier no positive
39
+ * example used is refused. Self-contained so compileSpec can inline it.
40
+ */
41
+ export function modifierWords(task) {
42
+ const MOD = ['zero', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine', 'ten', 'eleven', 'twelve',
43
+ 'thirteen', 'fourteen', 'fifteen', 'sixteen', 'seventeen', 'eighteen', 'nineteen', 'twenty', 'thirty', 'forty',
44
+ 'fifty', 'sixty', 'seventy', 'eighty', 'ninety', 'hundred', 'thousand', 'million', 'dozen', 'dozens', 'half',
45
+ 'halves', 'quarter', 'double', 'doubled', 'twice', 'triple', 'tripled', 'thrice', 'couple', 'several', 'both', 'each', 'every', 'per', 'apiece',
46
+ 'not', 'no', 'never', 'none', 'nor', 'neither', 'without', 'except', 'instead', 'excluding'];
47
+ const words = String(task).toLowerCase().replace(/[\u2019']/g, "'").match(/[a-z]+(?:'[a-z]+)?/g) || [];
48
+ const out = new Set();
49
+ for (const w of words) {
50
+ if (MOD.includes(w)) out.add(w);
51
+ else if (/n't$/.test(w)) out.add("n't");
52
+ }
53
+ return [...out].sort();
54
+ }
55
+
34
56
  /** Content words of the question sentence (the last sentence with a "?", else the last sentence). Self-contained. */
35
57
  export function questionWords(task) {
36
58
  const STOPW = ['the', 'and', 'for', 'with', 'that', 'this', 'what', 'how', 'much', 'many', 'does', 'did', 'was', 'are', 'its', 'their', 'your', 'you', 'now', 'then', 'after', 'from', 'into', 'over', 'whole', 'all'];
@@ -61,6 +83,7 @@ export function induce(pos, neg, skill) {
61
83
  if (shapes.length > 2) return { error: `examples have ${shapes.length} different number shapes` };
62
84
  const maxN = Math.max(...toks.map((t) => t.length));
63
85
  const params = {};
86
+ const alternatives = {};
64
87
  for (const key of keys) {
65
88
  const p = props[key] || {};
66
89
  const scales = declaresDecimal(p) ? [0.01, 1] : [1];
@@ -69,17 +92,29 @@ export function induce(pos, neg, skill) {
69
92
  if (p.type === 'array' || Array.isArray(pos[0].input[key])) cands.push({ kind, all: true, scale });
70
93
  else for (let k = 0; k < maxN; k++) cands.push({ kind, k, scale }, { kind, k: -(k + 1), scale });
71
94
  }
72
- const hit = cands.find((s) => pos.every((e, i) => eq(pick(toks[i], s), e.input[key])));
73
- if (!hit) return { error: `no single rule finds ${key} in every example` };
95
+ const fits = cands.filter((s) => pos.every((e, i) => eq(pick(toks[i], s), e.input[key])));
96
+ if (!fits.length) return { error: `no single rule finds ${key} in every example` };
74
97
  // Plain numbers carry their units: measured, positions alone could not tell "40 mph ... 60 mph" from
75
98
  // "120 miles in 2 hours", so the speed binder was (correctly) refused until units were learned.
76
- if (hit.kind === 'plain' || hit.kind === 'any') {
99
+ for (const hit of fits) {
100
+ if (hit.all || (hit.kind !== 'plain' && hit.kind !== 'any')) continue;
77
101
  const units = toks.map((t) => { const l = t.filter((x) => hit.kind === 'any' || x.kind === hit.kind); return (hit.k >= 0 ? l[hit.k] : l[l.length + hit.k])?.unit; });
78
102
  if (units.every(Boolean)) hit.units = [...new Set(units)].sort();
79
103
  }
104
+ // 1.3.0 ambiguity check. 1.2.0 kept the first rule that fit, silently: with examples where d1 = d2, "first %"
105
+ // and "second %" both fit, and "40% off, then 10% off" was bound as {d1: 0.4, d2: 0.4}. A rule that picks a
106
+ // DIFFERENT number in some example (equal values by coincidence) is kept as an alternative; applySpec refuses a
107
+ // task on which the alternatives disagree. Rules that pick the same number in every example are the same rule.
108
+ const which = (t, s) => { const l = t.filter((x) => s.kind === 'any' || x.kind === s.kind); return s.all ? l : (s.k >= 0 ? l[s.k] : l[l.length + s.k]); };
109
+ const same = (a, b) => toks.every((t) => { const x = which(t, a), y = which(t, b); return Array.isArray(x) ? Array.isArray(y) && x.length === y.length && x.every((v, j) => v === y[j]) : x === y; });
110
+ const [hit, ...rest] = fits;
111
+ const alts = [];
112
+ for (const c of rest) if (!same(c, hit) && !alts.some((a) => same(a, c))) alts.push(c);
80
113
  params[key] = hit;
114
+ if (alts.length) alternatives[key] = alts;
81
115
  }
82
- return { spec: { shapes, params, ...learnBlocks(pos, neg) } };
116
+ const modifiers = [...new Set(pos.flatMap((e) => modifierWords(e.task)))].sort();
117
+ return { spec: { shapes, params, alternatives, modifiers, ...learnBlocks(pos, neg) } };
83
118
  }
84
119
 
85
120
  /**
@@ -152,20 +187,45 @@ export function wordingOf(task, kinds) {
152
187
  export function novelWording(pos, task) {
153
188
  const { kinds } = learnBlocks(pos, []).contextBlock;
154
189
  const known = new Set(pos.flatMap((e) => wordingOf(e.task, kinds)));
155
- return wordingOf(task, kinds).filter((w) => !known.has(w));
190
+ const knownMods = new Set(pos.flatMap((e) => modifierWords(e.task)));
191
+ return [
192
+ ...wordingOf(task, kinds).filter((w) => !known.has(w)),
193
+ ...modifierWords(task).filter((w) => !knownMods.has(w)).map((w) => `${w} (quantity or negation)`),
194
+ ];
156
195
  }
157
196
 
158
- /** Apply a spec to a task (the same logic the compiled binder runs). */
159
- export function applySpec(spec, task) {
197
+ /**
198
+ * Apply a spec and say why when it refuses: `{ input, refused }`, where `refused` is null when the task binds, else one
199
+ * of 'shape', 'block-word', 'context-block', 'modifier', 'ambiguous', 'missing'. Same logic the compiled binder runs.
200
+ */
201
+ export function explainApply(spec, task) {
202
+ const no = (refused, detail) => ({ input: null, refused, detail });
160
203
  const toks = numberTokens(task);
161
- if (!spec.shapes.includes(shapeOf(toks))) return null;
204
+ if (!spec.shapes.includes(shapeOf(toks))) return no('shape', shapeOf(toks));
162
205
  const q = questionWords(task);
163
- if (spec.blockWords.some((w) => q.includes(w))) return null;
206
+ const bw = spec.blockWords.filter((w) => q.includes(w));
207
+ if (bw.length) return no('block-word', bw);
164
208
  const cb = spec.contextBlock;
165
- if (cb && toks.some((t) => cb.kinds.includes(t.kind) && t.ctx.some((w) => cb.words.includes(w)))) return null;
209
+ if (cb && toks.some((t) => cb.kinds.includes(t.kind) && t.ctx.some((w) => cb.words.includes(w)))) return no('context-block', cb.words);
210
+ // Specs induced before 1.3.0 carry no `modifiers`; they are treated as having seen none, which is the safe side.
211
+ const mods = modifierWords(task).filter((w) => !(spec.modifiers || []).includes(w));
212
+ if (mods.length) return no('modifier', mods);
166
213
  const out = {};
167
- for (const [k, s] of Object.entries(spec.params)) { const v = pick(toks, s); if (v === undefined) return null; out[k] = v; }
168
- return out;
214
+ for (const [k, s] of Object.entries(spec.params)) {
215
+ const v = pick(toks, s);
216
+ if (v === undefined) return no('missing', k);
217
+ for (const a of (spec.alternatives || {})[k] || []) {
218
+ const w = pick(toks, a);
219
+ if (w === undefined || JSON.stringify(w) !== JSON.stringify(v)) return no('ambiguous', k);
220
+ }
221
+ out[k] = v;
222
+ }
223
+ return { input: out, refused: null, detail: null };
224
+ }
225
+
226
+ /** Apply a spec to a task; null when it refuses (see explainApply for the reason). */
227
+ export function applySpec(spec, task) {
228
+ return explainApply(spec, task).input;
169
229
  }
170
230
 
171
231
  /** Leave-one-out: every example must be predicted by the spec induced from all the others. */
@@ -178,7 +238,8 @@ export function leaveOneOut(pos, neg, skill) {
178
238
  // A miss only because the held-out example has a unit no other example has ("knots") is novelty, not contradiction.
179
239
  let novel = false;
180
240
  if (!ok && r.spec) {
181
- const loose = { ...r.spec, params: Object.fromEntries(Object.entries(r.spec.params).map(([k, p]) => [k, { ...p, units: undefined }])) };
241
+ // A modifier word ("each") only the held-out example uses is novelty too.
242
+ const loose = { ...r.spec, modifiers: [...(r.spec.modifiers || []), ...modifierWords(e.task)], params: Object.fromEntries(Object.entries(r.spec.params).map(([k, p]) => [k, { ...p, units: undefined }])) };
182
243
  const g2 = applySpec(loose, e.task);
183
244
  novel = Boolean(g2) && Object.keys(e.input).every((k) => eq(g2[k], e.input[k]));
184
245
  }
@@ -196,7 +257,9 @@ export function compileSpec(spec) {
196
257
  ` ${numberTokens.toString()}`,
197
258
  ` ${questionWords.toString()}`,
198
259
  ` const shapeOf = ${shapeOf.toString()};`,
260
+ ` ${modifierWords.toString()}`,
199
261
  ` ${pick.toString()}`,
262
+ ` ${explainApply.toString()}`,
200
263
  ` ${applySpec.toString()}`,
201
264
  ' return applySpec(SPEC, task);',
202
265
  '}',
@@ -1,130 +1,156 @@
1
- // Browser-pure Privacy Membrane core extracted directly from src/guard/membrane.js (zero Node imports).
2
- // Runs identically in Node.js and modern browsers with zero dependencies.
3
-
4
- const OPEN = '⟦', CLOSE = '⟧';
5
-
6
- function luhn(digits) {
7
- let sum = 0, alt = false;
8
- for (let i = digits.length - 1; i >= 0; i--) {
9
- let n = digits.charCodeAt(i) - 48;
10
- if (alt) { n *= 2; if (n > 9) n -= 9; }
11
- sum += n;
12
- alt = !alt;
13
- }
14
- return sum % 10 === 0;
15
- }
16
-
17
- const DETECTORS = [
18
- ['SECRET', /-----BEGIN [A-Z ]*PRIVATE KEY-----[\s\S]*?-----END [A-Z ]*PRIVATE KEY-----/g],
19
- ['SECRET', /\b(?:sk|pk|rk)-[A-Za-z0-9_-]{20,}\b|\bgh[pousr]_[A-Za-z0-9]{30,}\b|\bAIza[0-9A-Za-z_-]{30,}\b|\bxox[abpr]-[A-Za-z0-9-]{10,}\b|\bAKIA[0-9A-Z]{16}\b/g],
20
- ['SECRET', /\beyJ[A-Za-z0-9_-]{8,}\.eyJ[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}\b/g],
21
- ['SECRET', /(?<=\b(?:password|passwd|passcode|pin|secret|api[_-]?key|token)\s*(?:is|[:=])\s*["']?)[^\s"',;]{4,}/gi],
22
- ['URL', /\bhttps?:\/\/[^\s<>"')]+[?&](?:token|key|sig|signature|auth|access_token|password)=[^\s<>"')]+/gi],
23
- ['EMAIL', /\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}\b/g],
24
- ['IBAN', /\b[A-Z]{2}\d{2}(?:\s?[A-Z0-9]{4}){2,7}(?:\s?[A-Z0-9]{1,4})?\b/g],
25
- ['CARD', /\b(?:\d[ -]?){12,18}\d\b/g],
26
- ['SSN', /\b\d{3}-\d{2}-\d{4}\b/g],
27
- ['PHONE', /(?:\+\d{1,3}[\s.-]?)?(?:\(\d{2,4}\)[\s.-]?|\b\d{2,4}[\s.-])\d{3,4}[\s.-]\d{3,4}\b/g],
28
- ['IP', /\b(?:(?:25[0-5]|2[0-4]\d|1?\d?\d)\.){3}(?:25[0-5]|2[0-4]\d|1?\d?\d)\b/g],
29
- ['PERSON', /\b(?:Dr|Mr|Mrs|Ms|Mx|Prof|Sr|Sra|Herr|Frau)\.?\s+[A-Z][a-z'’-]+(?:\s+[A-Z][a-z'’-]+){0,2}/g],
30
- ['ADDRESS', /\b\d{1,6}\s+(?:[A-Z][a-z]+\s+){1,4}(?:Street|St|Avenue|Ave|Road|Rd|Boulevard|Blvd|Lane|Ln|Drive|Way|Court|Ct|Place|Pl|Terrace|Parkway|Pkwy|Highway|Hwy)\b\.?(?:,\s*[A-Z][a-z]+(?:\s+[A-Z][a-z]+)*)?/g],
31
- ['ID', /\b[A-Z]{2,5}-\d{5,}\b/g],
32
- ['ID', /(?<=\b(?:account|acct|patient|customer|member|policy|case|invoice)\s*(?:no\.?|number|#|id)?\s*[:#]?\s*)\d{5,}\b/gi],
33
- ];
34
-
35
- const VALIDATE = {
36
- CARD: (v) => { const d = v.replace(/\D/g, ''); return d.length >= 13 && d.length <= 19 && luhn(d); },
37
- PHONE: (v) => { const d = v.replace(/\D/g, ''); return d.length >= 10 && d.length <= 15; },
38
- IBAN: (v) => v.replace(/\s/g, '').length >= 15,
39
- };
40
-
41
- export function detect(text, { terms = [] } = {}) {
42
- const s = String(text ?? '');
43
- const spans = [];
44
- for (const [type, re] of DETECTORS) {
45
- re.lastIndex = 0;
46
- for (const m of s.matchAll(re)) {
47
- let value = m[0].trim();
48
- if (type === 'SECRET' || type === 'URL' || type === 'EMAIL') value = value.replace(/[.,;:!?)]+$/, '');
49
- if (!value || (VALIDATE[type] && !VALIDATE[type](value))) continue;
50
- const start = m.index + m[0].indexOf(value);
51
- spans.push({ start, end: start + value.length, type, value });
52
- }
53
- }
54
- for (const term of terms) {
55
- const t = String(term || '').trim();
56
- if (t.length < 2) continue;
57
- const re = new RegExp(`(?<![\\p{L}\\p{N}])${t.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}(?![\\p{L}\\p{N}])`, 'giu');
58
- for (const m of s.matchAll(re)) spans.push({ start: m.index, end: m.index + m[0].length, type: 'TERM', value: m[0] });
59
- }
60
- spans.sort((a, b) => a.start - b.start || (b.end - b.start) - (a.end - a.start));
61
- const out = [];
62
- for (const sp of spans) {
63
- const last = out.at(-1);
64
- if (last && sp.start < last.end) {
65
- if (sp.end - sp.start > last.end - last.start) out[out.length - 1] = sp;
66
- continue;
67
- }
68
- out.push(sp);
69
- }
70
- return out;
71
- }
72
-
73
- const digitsOnly = (v) => v.replace(/\D/g, '');
74
- const squeezeDigits = (s) => s.replace(/(?<=\d)[\s.\-()]+(?=\d)/g, '');
75
-
76
- export class SealSession {
77
- constructor() { this.byValue = new Map(); this.byPlaceholder = new Map(); this.counts = {}; }
78
-
79
- placeholder(type, value) {
80
- const key = value.toLowerCase();
81
- if (this.byValue.has(key)) return this.byValue.get(key);
82
- this.counts[type] = (this.counts[type] || 0) + 1;
83
- const ph = `${OPEN}${type}_${this.counts[type]}${CLOSE}`;
84
- this.byValue.set(key, ph);
85
- this.byPlaceholder.set(ph, { type, value });
86
- return ph;
87
- }
88
-
89
- apply(text, spans) {
90
- let out = '', i = 0;
91
- for (const sp of spans) { out += text.slice(i, sp.start) + this.placeholder(sp.type, sp.value); i = sp.end; }
92
- return out + text.slice(i);
93
- }
94
-
95
- get size() { return this.byPlaceholder.size; }
96
- values() { return [...this.byPlaceholder.values()]; }
97
-
98
- unseal(text, { json = false } = {}) {
99
- let s = String(text ?? '');
100
- for (const [ph, { type, value }] of this.byPlaceholder) {
101
- const n = ph.slice(OPEN.length + type.length + 1, -CLOSE.length);
102
- const re = new RegExp(`(?:${OPEN}|\\[\\[?|«|<)?\\b${type}_${n}\\b(?:${CLOSE}|\\]\\]?|»|>)?`, 'g');
103
- const rep = json ? JSON.stringify(value).slice(1, -1) : value;
104
- s = s.replace(re, () => rep);
105
- }
106
- return s;
107
- }
108
-
109
- audit(payload) {
110
- const p = String(payload ?? '');
111
- const lower = p.toLowerCase();
112
- const squeezed = squeezeDigits(p);
113
- const leaks = [];
114
- for (const { type, value } of this.values()) {
115
- if (lower.includes(value.toLowerCase())) { leaks.push(type); continue; }
116
- const d = digitsOnly(value);
117
- if (d.length >= 7 && (squeezed.includes(d) || (d.length > 10 && squeezed.includes(d.slice(-10))))) leaks.push(type);
118
- }
119
- return { clean: leaks.length === 0, leaks };
120
- }
121
- }
122
-
123
- export class MembraneLeak extends Error {
124
- constructor(leaks, message = null) {
125
- super(message || `membrane blocked egress: ${leaks.length} sensitive value(s) would have left the machine (${[...new Set(leaks)].join(', ')})`);
126
- this.leaks = leaks;
127
- }
128
- }
129
-
130
- export const MEMBRANE_NOTE = `Some values in this conversation were replaced by placeholders such as ${OPEN}EMAIL_1${CLOSE} or ${OPEN}PERSON_2${CLOSE} to protect privacy. Treat each placeholder as the real value it stands for, keep placeholders EXACTLY as written (same brackets, type and number) wherever the value belongs in your answer, and never try to guess what they hide.`;
1
+ // Browser-pure Privacy Membrane core extracted directly from src/guard/membrane.js (zero Node imports).
2
+ // Runs identically in Node.js and modern browsers with zero dependencies.
3
+
4
+ const OPEN = '⟦', CLOSE = '⟧';
5
+
6
+ function luhn(digits) {
7
+ let sum = 0, alt = false;
8
+ for (let i = digits.length - 1; i >= 0; i--) {
9
+ let n = digits.charCodeAt(i) - 48;
10
+ if (alt) { n *= 2; if (n > 9) n -= 9; }
11
+ sum += n;
12
+ alt = !alt;
13
+ }
14
+ return sum % 10 === 0;
15
+ }
16
+
17
+ const DETECTORS = [
18
+ ['SECRET', /-----BEGIN [A-Z ]*PRIVATE KEY-----[\s\S]*?-----END [A-Z ]*PRIVATE KEY-----/g],
19
+ ['SECRET', /\b(?:sk|pk|rk)-[A-Za-z0-9_-]{20,}\b|\b(?:sk|pk|rk)_(?:live|test)_[A-Za-z0-9]{16,}\b|\bgh[pousr]_[A-Za-z0-9]{30,}\b|\bgithub_pat_[A-Za-z0-9_]{30,}\b|\bhf_[A-Za-z0-9]{30,}\b|\bAIza[0-9A-Za-z_-]{30,}\b|\bxox[abpr]-[A-Za-z0-9-]{10,}\b|\bAKIA[0-9A-Z]{16}\b/g],
20
+ // Bearer credentials: only the token after the scheme is sealed. Bounded whitespace keeps it linear.
21
+ ['SECRET', /(?<=\bBearer[ \t]{1,4})[A-Za-z0-9._~+/=-]{16,}/g],
22
+ ['SECRET', /\beyJ[A-Za-z0-9_-]{8,}\.eyJ[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}\b/g],
23
+ // Bounded look-behind whitespace ({0,8}) keeps this linear on long whitespace runs; the value may contain quotes
24
+ // (ab"cd1234) and ends before an optional closing quote.
25
+ ['SECRET', /(?<=\b(?:password|passwd|passcode|pin|secret|api[_-]?key|token)\s{0,8}(?:is|[:=])\s{0,8}["']?)(?!["'])[^\s,;]{4,}?(?=["']?(?:[\s,;]|$))/gi],
26
+ ['URL', /\bhttps?:\/\/[^\s<>"')]+[?&](?:token|key|sig|signature|auth|access_token|password)=[^\s<>"')]+/gi],
27
+ // RFC 5321 length limits (64 local, 253 domain) bound each attempt, so "a." x 50k is linear, not quadratic.
28
+ ['EMAIL', /\b[A-Za-z0-9_.%+-]{1,64}@[A-Za-z0-9.-]{1,253}\.[A-Za-z]{2,24}\b/g],
29
+ ['IBAN', /\b[A-Z]{2}\d{2}(?:\s?[A-Z0-9]{4}){2,7}(?:\s?[A-Z0-9]{1,4})?\b/g],
30
+ ['CARD', /\b(?:\d[ -]?){12,18}\d\b/g],
31
+ ['SSN', /\b\d{3}-\d{2}-\d{4}\b/g],
32
+ ['PHONE', /(?:\+\d{1,3}[\s.-]?)?(?:\(\d{2,4}\)[\s.-]?|\b\d{2,4}[\s.-])\d{3,4}[\s.-]\d{3,4}\b/g],
33
+ ['IP', /\b(?:(?:25[0-5]|2[0-4]\d|1?\d?\d)\.){3}(?:25[0-5]|2[0-4]\d|1?\d?\d)\b/g],
34
+ ['PERSON', /\b(?:Dr|Mr|Mrs|Ms|Mx|Prof|Sr|Sra|Herr|Frau)\.?\s+[A-Z][a-z'’-]+(?:\s+[A-Z][a-z'’-]+){0,2}/g],
35
+ ['ADDRESS', /\b\d{1,6}\s+(?:[A-Z][a-z]+\s+){1,4}(?:Street|St|Avenue|Ave|Road|Rd|Boulevard|Blvd|Lane|Ln|Drive|Way|Court|Ct|Place|Pl|Terrace|Parkway|Pkwy|Highway|Hwy)\b\.?(?:,\s*[A-Z][a-z]+(?:\s+[A-Z][a-z]+)*)?/g],
36
+ ['ID', /\b[A-Z]{2,5}-\d{5,}\b/g],
37
+ ['ID', /(?<=\b(?:account|acct|patient|customer|member|policy|case|invoice)\s{0,8}(?:no\.?|number|#|id)?\s{0,8}[:#]?\s{0,8})\d{5,}\b/gi],
38
+ ];
39
+
40
+ const VALIDATE = {
41
+ CARD: (v) => { const d = v.replace(/\D/g, ''); return d.length >= 13 && d.length <= 19 && luhn(d); },
42
+ PHONE: (v) => { const d = v.replace(/\D/g, ''); return d.length >= 10 && d.length <= 15; },
43
+ IBAN: (v) => v.replace(/\s/g, '').length >= 15,
44
+ };
45
+
46
+ export function detect(text, { terms = [] } = {}) {
47
+ const s = String(text ?? '');
48
+ const spans = [];
49
+ for (const [type, re] of DETECTORS) {
50
+ re.lastIndex = 0;
51
+ for (const m of s.matchAll(re)) {
52
+ let value = m[0].trim();
53
+ if (type === 'SECRET' || type === 'URL' || type === 'EMAIL') value = value.replace(/[.,;:!?)]+$/, '');
54
+ if (!value || (VALIDATE[type] && !VALIDATE[type](value))) continue;
55
+ const start = m.index + m[0].indexOf(value);
56
+ spans.push({ start, end: start + value.length, type, value });
57
+ }
58
+ }
59
+ for (const term of terms) {
60
+ const t = String(term || '').trim();
61
+ if (t.length < 2) continue;
62
+ const re = new RegExp(`(?<![\\p{L}\\p{N}])${t.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}(?![\\p{L}\\p{N}])`, 'giu');
63
+ for (const m of s.matchAll(re)) spans.push({ start: m.index, end: m.index + m[0].length, type: 'TERM', value: m[0] });
64
+ }
65
+ spans.sort((a, b) => a.start - b.start || (b.end - b.start) - (a.end - a.start));
66
+ const out = [];
67
+ for (const sp of spans) {
68
+ const last = out.at(-1);
69
+ if (last && sp.start < last.end) {
70
+ if (sp.end - sp.start > last.end - last.start) out[out.length - 1] = sp;
71
+ continue;
72
+ }
73
+ out.push(sp);
74
+ }
75
+ return out;
76
+ }
77
+
78
+ const digitsOnly = (v) => v.replace(/\D/g, '');
79
+ const squeezeDigits = (s) => s.replace(/(?<=\d)[\s.\-()]+(?=\d)/g, '');
80
+
81
+ export class SealSession {
82
+ constructor() { this.byValue = new Map(); this.byPlaceholder = new Map(); this.counts = {}; }
83
+
84
+ placeholder(type, value) {
85
+ // Only e-mail addresses are case-insensitive. Secrets, IDs and names that differ in case are different
86
+ // values and must get different placeholders (sk-ABCD... and sk-abcd... used to share one).
87
+ const key = type === 'EMAIL' ? `${type}:${value.toLowerCase()}` : `${type}:${value}`;
88
+ if (this.byValue.has(key)) return this.byValue.get(key);
89
+ this.counts[type] = (this.counts[type] || 0) + 1;
90
+ const ph = `${OPEN}${type}_${this.counts[type]}${CLOSE}`;
91
+ this.byValue.set(key, ph);
92
+ this.byPlaceholder.set(ph, { type, value });
93
+ return ph;
94
+ }
95
+
96
+ apply(text, spans) {
97
+ let out = '', i = 0;
98
+ for (const sp of spans) { out += text.slice(i, sp.start) + this.placeholder(sp.type, sp.value); i = sp.end; }
99
+ return out + text.slice(i);
100
+ }
101
+
102
+ get size() { return this.byPlaceholder.size; }
103
+ values() { return [...this.byPlaceholder.values()]; }
104
+
105
+ /**
106
+ * Put the real values back.
107
+ *
108
+ * Default (lenient) mode restores every form that names a placeholder issued by THIS session:
109
+ * the exact ⟦EMAIL_1⟧, mangled forms such as [EMAIL_1], [[EMAIL_1]], «EMAIL_1», <EMAIL_1>, and the bare word
110
+ * EMAIL_1. That is what makes a model's slightly-mangled reply round-trip, and it is also a risk: a model (or
111
+ * text it copied from an attacker) that writes "EMAIL_1" anywhere receives the real address. Placeholders that
112
+ * were never issued in this session (EMAIL_9) are never touched in either mode.
113
+ *
114
+ * `strict: true` restores only the exact ⟦TYPE_n⟧ tokens this session issued. Use it for any text a model wrote
115
+ * that will be shown to someone other than the person whose data was sealed.
116
+ *
117
+ * Replacement is a single pass: a restored value is never rewritten again, even if it contains text that looks
118
+ * like another placeholder (PHONE_1@corp.example).
119
+ */
120
+ unseal(text, { json = false, strict = false } = {}) {
121
+ const s = String(text ?? '');
122
+ if (this.byPlaceholder.size === 0) return s;
123
+ const ids = new Map();
124
+ for (const [ph, entry] of this.byPlaceholder) ids.set(ph.slice(OPEN.length, -CLOSE.length), entry);
125
+ const alt = [...ids.keys()].sort((a, b) => b.length - a.length).join('|');
126
+ const re = strict
127
+ ? new RegExp(`${OPEN}(${alt})${CLOSE}`, 'g')
128
+ : new RegExp(`(?:${OPEN}|\\[\\[?|«|<)?\\b(${alt})\\b(?:${CLOSE}|\\]\\]?|»|>)?`, 'g');
129
+ return s.replace(re, (_m, id) => {
130
+ const { value } = ids.get(id);
131
+ return json ? JSON.stringify(value).slice(1, -1) : value;
132
+ });
133
+ }
134
+
135
+ audit(payload) {
136
+ const p = String(payload ?? '');
137
+ const lower = p.toLowerCase();
138
+ const squeezed = squeezeDigits(p);
139
+ const leaks = [];
140
+ for (const { type, value } of this.values()) {
141
+ if (lower.includes(value.toLowerCase())) { leaks.push(type); continue; }
142
+ const d = digitsOnly(value);
143
+ if (d.length >= 7 && (squeezed.includes(d) || (d.length > 10 && squeezed.includes(d.slice(-10))))) leaks.push(type);
144
+ }
145
+ return { clean: leaks.length === 0, leaks };
146
+ }
147
+ }
148
+
149
+ export class MembraneLeak extends Error {
150
+ constructor(leaks, message = null) {
151
+ super(message || `membrane blocked egress: ${leaks.length} sensitive value(s) would have left the machine (${[...new Set(leaks)].join(', ')})`);
152
+ this.leaks = leaks;
153
+ }
154
+ }
155
+
156
+ export const MEMBRANE_NOTE = `Some values in this conversation were replaced by placeholders such as ${OPEN}EMAIL_1${CLOSE} or ${OPEN}PERSON_2${CLOSE} to protect privacy. Treat each placeholder as the real value it stands for, keep placeholders EXACTLY as written (same brackets, type and number) wherever the value belongs in your answer, and never try to guess what they hide.`;