@chatpanel/bridge 0.11.24 → 0.11.25

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 (62) hide show
  1. package/README.md +7 -7
  2. package/package.json +1 -13
  3. package/scripts/sync-channels.mjs +8 -90
  4. package/scripts/sync-events.mjs +7 -78
  5. package/scripts/sync-pii.mjs +7 -68
  6. package/src/api-compat.js +5 -294
  7. package/src/channels/adapters/telegram.js +3 -298
  8. package/src/channels/bridge.js +1 -59
  9. package/src/channels/eventlog.js +3 -57
  10. package/src/channels/gateway.js +1 -114
  11. package/src/channels/invoke.js +1 -172
  12. package/src/channels/normalize.js +1 -58
  13. package/src/channels/pairing.js +1 -95
  14. package/src/channels/service.js +1 -329
  15. package/src/channels/stream.js +5 -104
  16. package/src/cli-errors.js +3 -136
  17. package/src/connections.js +1 -160
  18. package/src/connectors.js +1 -100
  19. package/src/engines/antigravity.js +5 -235
  20. package/src/engines/args.js +1 -47
  21. package/src/engines/claude.js +6 -586
  22. package/src/engines/cli-agents.js +7 -312
  23. package/src/engines/codex.js +6 -481
  24. package/src/engines/custom.js +17 -577
  25. package/src/engines/prompt.js +6 -32
  26. package/src/engines/stream-formats.js +2 -222
  27. package/src/entitlement.js +1 -77
  28. package/src/env.js +3 -628
  29. package/src/events/capability.js +1 -134
  30. package/src/events/event.js +1 -183
  31. package/src/events/reach.js +1 -31
  32. package/src/events/ref.js +1 -63
  33. package/src/events/scm-connection.js +1 -188
  34. package/src/events/scopes.js +1 -20
  35. package/src/events/skill-manifest.js +1 -338
  36. package/src/events/skill-scan.js +3 -217
  37. package/src/events/view.js +1 -96
  38. package/src/mcp-capabilities.js +2 -139
  39. package/src/mcp-local.js +0 -0
  40. package/src/mcp-quarantine.js +1 -110
  41. package/src/net.js +1 -107
  42. package/src/pii/index.js +1 -29
  43. package/src/pii/net.js +1 -111
  44. package/src/pii/pii-detect.js +2 -296
  45. package/src/pii/pii-redact.js +1 -470
  46. package/src/pii/pipeline.js +1 -137
  47. package/src/pii/sanitize.js +2 -179
  48. package/src/pii/tool-harness.js +1 -184
  49. package/src/pii/tool-rank.js +1 -110
  50. package/src/proc.js +2 -91
  51. package/src/relay-timeout.js +1 -21
  52. package/src/runs.js +1 -49
  53. package/src/sanitize.js +1 -7
  54. package/src/scm.js +1 -76
  55. package/src/server.js +10 -1492
  56. package/src/service.js +11 -176
  57. package/src/sign-in.js +1 -91
  58. package/src/skills.js +1 -399
  59. package/src/ssrf.js +1 -70
  60. package/src/update.js +1 -216
  61. package/src/workdir.js +1 -108
  62. package/src/worktree.js +3 -125
@@ -1,470 +1 @@
1
- // GENERATED — do not edit.
2
- // Source of truth: chatpanel-pii/pii-redact.js (npm @chatpanel/pii).
3
- // Edit there, then run: npm run sync:pii
4
- //
5
- // Vendored rather than depended on: the bridge ships zero runtime dependencies so a
6
- // curl one-liner install cannot fail on someone's registry, and so the compiled
7
- // single-file binary has nothing to resolve.
8
-
9
- // Reversible PII redaction.
10
- //
11
- // Strips sensitive values out of everything that leaves the device for a model
12
- // (chat text, attached page/meeting context, and tool results we feed back), then
13
- // reconstructs the originals when the reply is rendered to the user. The model
14
- // only ever sees opaque, stable placeholders like [[EMAIL_1]] / [[PERSON_2]] — so
15
- // it can still reason about "who said what" without seeing the real values.
16
- //
17
- // Pure + dependency-free so it is unit-testable and runs identically for API and
18
- // CLI/bridge agents (both assemble their outbound payload through providers.js).
19
- //
20
- // Tiers:
21
- // 'basic' — deterministic regex: emails, phones, IPs, cards (Luhn), SSNs, keys.
22
- // 'full' — basic + entity-aware: known people/orgs (meeting roster, contacts,
23
- // the user's own identity) and a user-editable custom dictionary.
24
- //
25
- // Reversibility caveat: if the model paraphrases instead of echoing a token, that
26
- // one reference won't restore (it shows the token) — but the privacy guarantee
27
- // (the real value never left the device) always holds.
28
-
29
- import { stripHidden, confusablesSkeleton } from './sanitize.js';
30
-
31
- const TOKEN_RE = /\[\[([A-Z][A-Z0-9]*)_(\d+)\]\]/g;
32
-
33
- /**
34
- * THE TOKEN FORMAT, PUBLISHED — because `[[TYPE_n]]` collides with `[[wikilink]]`.
35
- *
36
- * The placeholder grammar was chosen to be visually obvious in a prompt, and it is
37
- * character-for-character the wikilink syntax notes and briefs use. So `[[PERSON_1]]` in a
38
- * stored message reads as a link to a page called "PERSON_1", and downstream that became a
39
- * backlink, a graph node, and a subject with its own page. The name of a person we
40
- * deliberately did not learn was being filed as a thing we know about.
41
- *
42
- * A placeholder is the ABSENCE of an identity. It must never become a link, a subject, a tag
43
- * or a topic — and it must never be restored into anything derived and persisted, because
44
- * that would put the PII back on disk in a second place.
45
- *
46
- * Exported rather than left private so consumers ASK instead of re-deriving the pattern:
47
- * this package owns the format, and `CLAUDE.md` lists it as a wire contract that only
48
- * changes additively.
49
- */
50
- export const REDACTION_TOKEN_TYPES = Object.freeze([
51
- 'PERSON', 'ORG', 'LOCATION', 'ADDRESS', 'EMAIL', 'PHONE', 'ID', 'SSN', 'IBAN',
52
- 'CREDITCARD', 'CARD', 'POST', 'FAC', 'GROUP', 'NRP', 'ENTITY', 'KEY', 'SECRET',
53
- 'TERM', 'PII', 'OTHER',
54
- ]);
55
-
56
- /**
57
- * Is this bare string one of OUR placeholders?
58
- *
59
- * Matched against the known type vocabulary rather than the bare `[A-Z]+_\d+` shape, and
60
- * that holds even inside brackets: `[[Q3_2026]]` and `[[PHASE_2]]` are links people
61
- * genuinely write, so a shape test would trade one invisible bug for another. A custom
62
- * dictionary type is the accepted gap — it is user-chosen, so a downstream consumer filing
63
- * it is a name the user picked, not a stranger's identity.
64
- *
65
- * Bracket-tolerant: callers ask both before and after a wikilink parser has stripped them.
66
- */
67
- export function isRedactionToken(value) {
68
- const bare = String(value ?? '').trim().replace(/^\[{1,2}|\]{1,2}$/g, '');
69
- const m = /^([A-Z][A-Z0-9]*)_\d+$/.exec(bare);
70
- return !!m && REDACTION_TOKEN_TYPES.includes(m[1]);
71
- }
72
-
73
- // Bracket-TOLERANT match of the same token. Smaller models routinely drop or mangle
74
- // the [[ ]] when echoing a placeholder into tool-call JSON — e.g. they emit "ORG_1"
75
- // or "[ORG_1]" instead of "[[ORG_1]]" — which the strict TOKEN_RE misses, leaving
76
- // the tool to search the literal "ORG_1" (and get nothing). We match 0–2 brackets
77
- // on each side and reconstruct the canonical token to look up; only ACTUAL vault
78
- // tokens are swapped, so a coincidental "ABC_1" that isn't ours is left untouched.
79
- const TOLERANT_TOKEN_RE = /\[{0,2}([A-Z][A-Z0-9]*_\d+)\]{0,2}/g;
80
-
81
- // A vault is the per-conversation mapping between placeholders and originals. Keep
82
- // one per conversation so PERSON_1 means the same entity across turns.
83
- export function createVault() {
84
- // `aliases` maps a pseudonym (e.g. "Robin") back to the real value (e.g. "Alex Rivera")
85
- // so LOCAL tool calls (history/meeting search) can run on real data. The reply
86
- // restorer ignores it — pseudonyms stay permanent in the user's view.
87
- return { byToken: new Map(), byValue: new Map(), counts: new Map(), aliases: new Map() };
88
- }
89
-
90
- export function vaultToJSON(vault) {
91
- return {
92
- entries: [...(vault?.byToken || new Map())].map(([token, value]) => ({ token, value })),
93
- aliases: [...(vault?.aliases || new Map())].map(([alias, value]) => ({ alias, value })),
94
- };
95
- }
96
-
97
- export function vaultFromJSON(data) {
98
- const vault = createVault();
99
- for (const { token, value } of data?.entries || []) {
100
- const m = /^\[\[([A-Z][A-Z0-9]*)_(\d+)\]\]$/.exec(token);
101
- vault.byToken.set(token, value);
102
- vault.byValue.set(value, token);
103
- if (m) vault.counts.set(m[1], Math.max(vault.counts.get(m[1]) || 0, Number(m[2])));
104
- }
105
- for (const { alias, value } of data?.aliases || []) vault.aliases.set(alias, value);
106
- return vault;
107
- }
108
-
109
- function tokenFor(vault, type, value) {
110
- const existing = vault.byValue.get(value);
111
- if (existing) return existing;
112
- const t = String(type || 'PII').toUpperCase().replace(/[^A-Z0-9]/g, '') || 'PII';
113
- const n = (vault.counts.get(t) || 0) + 1;
114
- vault.counts.set(t, n);
115
- const token = `[[${t}_${n}]]`;
116
- vault.byToken.set(token, value);
117
- vault.byValue.set(value, token);
118
- return token;
119
- }
120
-
121
- function escapeRegex(s) {
122
- return String(s).replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
123
- }
124
-
125
- // Reject a user-supplied dictionary regex that is a likely ReDoS (catastrophic
126
- // backtracking) BEFORE compiling + running it on untrusted-length input. Heuristic,
127
- // not exhaustive: cap length, and reject the classic nested-quantifier families —
128
- // a quantified group whose body also has a quantifier ((a+)+ / (a*)* / (.*)+) and
129
- // back-to-back unbounded quantifiers (a**, .*+). A rejected pattern is skipped like a
130
- // syntactically-invalid one, so redaction never breaks or hangs.
131
- function isSafeUserPattern(p) {
132
- if (typeof p !== 'string' || p.length === 0 || p.length > 200) return false;
133
- if (/\([^)]*[+*}][^)]*\)\s*[+*{]/.test(p)) return false; // (…quantifier…)quantifier
134
- if (/[+*]\s*[+*]/.test(p)) return false; // a**, a+*, .*+
135
- return true;
136
- }
137
-
138
- // Apply many find/replace rules in a SINGLE left-to-right pass over the source.
139
- // Each rule is { re: <global RegExp>, repl: (match) => string }. Unlike running
140
- // rule[0].replace then rule[1].replace then …, text emitted by one rule is NEVER
141
- // re-scanned by a later rule — so substitutions can't cascade (e.g. a pseudonym
142
- // that happens to equal another entry's input). On a tie at the same position the
143
- // earlier rule wins (rules carry priority by their order in the array).
144
- function applyRulesOnce(text, rules) {
145
- if (!rules || rules.length === 0) return text;
146
- let out = '';
147
- let pos = 0;
148
- const n = text.length;
149
- while (pos <= n) {
150
- let best = null;
151
- let bestRule = null;
152
- for (const rule of rules) {
153
- rule.re.lastIndex = pos;
154
- const m = rule.re.exec(text);
155
- if (m && (best === null || m.index < best.index)) {
156
- best = m;
157
- bestRule = rule;
158
- if (m.index === pos) break; // nothing can start earlier than the cursor
159
- }
160
- }
161
- if (!best) { out += text.slice(pos); break; }
162
- out += text.slice(pos, best.index);
163
- if (best[0].length === 0) { // pathological empty match — emit a char, advance
164
- out += text[best.index] ?? '';
165
- pos = best.index + 1;
166
- } else {
167
- out += bestRule.repl(best);
168
- pos = best.index + best[0].length;
169
- }
170
- }
171
- return out;
172
- }
173
-
174
- function luhnValid(digits) {
175
- let sum = 0;
176
- let alt = false;
177
- for (let i = digits.length - 1; i >= 0; i--) {
178
- let d = digits.charCodeAt(i) - 48;
179
- if (alt) { d *= 2; if (d > 9) d -= 9; }
180
- sum += d;
181
- alt = !alt;
182
- }
183
- return sum % 10 === 0;
184
- }
185
-
186
- // Plausible IPv6? Controls false positives from the broad IPV6 regex: accept only a
187
- // `::`-compressed form (≥1 hextet) or a full 8-hextet address, hextets ≤4 hex digits.
188
- function isLikelyIpv6(s) {
189
- if (!/^[0-9A-Fa-f:]+$/.test(s) || (s.match(/:/g) || []).length < 2) return false;
190
- const parts = s.split(':');
191
- if (parts.some((p) => p.length > 4)) return false;
192
- if (s.includes('::')) return parts.filter(Boolean).length >= 1 && parts.filter(Boolean).length <= 7;
193
- return parts.length === 8 && parts.every((p) => p.length >= 1);
194
- }
195
-
196
- // Deterministic detectors. Each: { type, re, valid? }. Order = priority; more
197
- // specific patterns run first so they win the bytes before greedier ones.
198
- const DETECTORS = [
199
- // PEM private-key block (multi-line) — highest priority, most specific.
200
- { type: 'SECRET', re: /-----BEGIN (?:[A-Z0-9]+ )*PRIVATE KEY-----[\s\S]*?-----END (?:[A-Z0-9]+ )*PRIVATE KEY-----/g },
201
- { type: 'EMAIL', re: /\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}\b/g },
202
- // SSN: dash- OR space-separated (bare 9-digit is left alone — too false-positive-prone).
203
- { type: 'SSN', re: /\b\d{3}[-\s]\d{2}[-\s]\d{4}\b/g },
204
- {
205
- // Vendor API keys / tokens. sk-… also covers OpenAI sk-proj-/sk-ant-. Adds Google
206
- // (AIza…), Stripe (sk_live_/rk_test_…), GitHub fine-grained PATs, Slack xapp-.
207
- type: 'KEY',
208
- re: /\b(?:sk-[A-Za-z0-9_-]{16,}|AKIA[0-9A-Z]{16}|gh[pousr]_[A-Za-z0-9]{20,}|github_pat_[0-9A-Za-z_]{22,}|xox[baprs]-[A-Za-z0-9-]{10,}|xapp-[0-9]-[A-Za-z0-9-]{10,}|AIza[0-9A-Za-z_-]{35}|[rs]k_(?:live|test)_[0-9A-Za-z]{16,})\b/g,
209
- },
210
- // JWT — three base64url segments; `eyJ` is base64 of `{"…`, so this is specific.
211
- { type: 'KEY', re: /\beyJ[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{6,}\.[A-Za-z0-9_-]{6,}\b/g },
212
- {
213
- type: 'IP',
214
- re: /\b(?:(?:25[0-5]|2[0-4]\d|1?\d?\d)\.){3}(?:25[0-5]|2[0-4]\d|1?\d?\d)\b/g,
215
- },
216
- {
217
- // IPv6 (incl. :: compression). Broad match narrowed by isLikelyIpv6 to curb FPs.
218
- type: 'IP',
219
- re: /(?<![:\w])(?:[0-9A-Fa-f]{0,4}:){2,7}[0-9A-Fa-f]{0,4}(?![:\w])/g,
220
- valid: (m) => isLikelyIpv6(m),
221
- },
222
- {
223
- // Phone: only count it if it has a separator or a leading + and 7–15 digits —
224
- // so long bare ids (a 11-digit page id, an order number) are NOT redacted.
225
- type: 'PHONE',
226
- re: /(?<![\w.])\+?\d[\d ().-]{6,}\d(?![\w])/g,
227
- valid: (m) => {
228
- const digits = m.replace(/\D/g, '');
229
- // Needs a separator / leading + OR be a bare 10-digit run (a typed phone like
230
- // 9320434444). 11+ bare digits still require formatting so long ids aren't hit.
231
- return digits.length >= 7 && digits.length <= 15
232
- && (/[ ().-]/.test(m) || m.trimStart().startsWith('+') || digits.length === 10);
233
- },
234
- },
235
- {
236
- type: 'CARD',
237
- re: /\b(?:\d[ -]?){13,19}\b/g,
238
- valid: (m) => { const d = m.replace(/\D/g, ''); return d.length >= 13 && d.length <= 19 && luhnValid(d); },
239
- },
240
- ];
241
-
242
- // Redact `text`, recording placeholders in `vault`. `entities` (full tier) is a
243
- // list of { value, type } known names/orgs; `dictionary` is the user's custom
244
- // list of { value, type } (exact strings) or { pattern, flags, type } (regex).
245
- export function redactText(text, vault, {
246
- tier = 'basic',
247
- entities = [],
248
- dictionary = [],
249
- sanitize = true,
250
- sanitizeOpts = undefined,
251
- } = {}) {
252
- if (text == null || text === '') return text;
253
- // De-steganography BEFORE detection, in-band: an obfuscated value
254
- // (j<ZWSP>o<ZWSP>hn@x.com, homoglyphs, ASCII-smuggled Tag chars) must become
255
- // matchable so the regex/NER can't be trivially bypassed. Callers used to have to
256
- // remember to stripHidden() first; folding it in here makes the engine safe on its
257
- // own — the sanitize:false escape hatch is only for a caller that already did it.
258
- let out = sanitize ? stripHidden(String(text), sanitizeOpts) : String(text);
259
- const v = vault || createVault();
260
-
261
- const entityTier = tier === 'full' || tier === 'entities';
262
-
263
- // 1) User dictionary first — highest authority, user explicitly chose these.
264
- // An entry with `alias` PSEUDONYMIZES: permanent substitution (the model and
265
- // the user's transcript both see the alias, never reversed). Otherwise it
266
- // REDACTS to a reversible [[TYPE_n]] placeholder restored in the user's view.
267
- // All entries are applied in ONE pass (applyRulesOnce): an alias produced by
268
- // one entry must not be re-matched by a later entry, or substitutions cascade
269
- // (e.g. value 'Arnav'→alias 'John' then 'John' caught by a later 'John' rule).
270
- const dictRules = [];
271
- for (const d of dictionary || []) {
272
- if (!d) continue;
273
- let re;
274
- try {
275
- re = d.pattern
276
- ? (isSafeUserPattern(d.pattern) ? new RegExp(d.pattern, d.flags && /g/.test(d.flags) ? d.flags : `${d.flags || ''}g`) : null)
277
- : (d.value ? new RegExp(`(?<![\\w])${escapeRegex(d.value)}(?![\\w])`, 'gi') : null);
278
- } catch {
279
- re = null; // a bad user regex must never break redaction
280
- }
281
- if (!re) continue;
282
- if (d.alias != null && d.alias !== '') {
283
- // pseudonymize: model + reply see the alias…
284
- // …but record alias→original so LOCAL tool args (history/meeting search) map
285
- // back to the real value. Local lookups must hit real data; only the model is blinded.
286
- if (d.value) v.aliases.set(d.alias, d.value);
287
- dictRules.push({ re, repl: () => d.alias });
288
- } else {
289
- const type = d.type || (d.pattern ? 'PII' : 'TERM');
290
- dictRules.push({ re, repl: (m) => tokenFor(v, type, d.pattern ? m[0] : d.value) });
291
- }
292
- }
293
- out = applyRulesOnce(out, dictRules);
294
-
295
- // 2) Known entities (full tier) — longest value first so "Alex Rivera" wins
296
- // before a bare "Alex". Restores to the canonical entity value.
297
- if (entityTier) {
298
- const ents = [...(entities || [])].filter((e) => e && e.value)
299
- .sort((a, b) => String(b.value).length - String(a.value).length);
300
- for (const e of ents) {
301
- const re = new RegExp(`(?<![\\w])${escapeRegex(e.value)}(?![\\w])`, 'gi');
302
- out = out.replace(re, () => tokenFor(v, e.type || 'PERSON', e.value));
303
- }
304
- }
305
-
306
- // 3) Deterministic detectors (all tiers). Detect against a CONFUSABLES SKELETON so
307
- // homoglyph-obfuscated values (Cyrillic/Greek/fullwidth Latin look-alikes) match
308
- // the ASCII regexes — but REDACT the ORIGINAL span. The fold is 1:1 per code point,
309
- // so a skeleton match's indices line up with `out`, and legitimate non-Latin text
310
- // (which won't match a detector) is never rewritten. Higher-priority detectors
311
- // (earlier in DETECTORS) claim overlapping spans first, matching the old order.
312
- const skel = confusablesSkeleton(out);
313
- const taken = []; // non-overlapping [start,end) spans, in priority order
314
- const overlaps = (s, e) => taken.some((t) => s < t.end && e > t.start);
315
- for (const det of DETECTORS) {
316
- det.re.lastIndex = 0;
317
- let m;
318
- while ((m = det.re.exec(skel)) !== null) {
319
- if (m[0].length === 0) { det.re.lastIndex++; continue; }
320
- const start = m.index, end = start + m[0].length;
321
- if ((det.valid && !det.valid(m[0])) || overlaps(start, end)) continue;
322
- taken.push({ start, end, type: det.type });
323
- }
324
- }
325
- if (taken.length) {
326
- taken.sort((a, b) => a.start - b.start);
327
- let rebuilt = '';
328
- let pos = 0;
329
- for (const t of taken) {
330
- rebuilt += out.slice(pos, t.start) + tokenFor(v, t.type, out.slice(t.start, t.end));
331
- pos = t.end;
332
- }
333
- out = rebuilt + out.slice(pos);
334
- }
335
- return out;
336
- }
337
-
338
- // Re-redact a tool RESULT before the model sees it, walking the shapes tools
339
- // actually return: a bare string, a { text } object, an array, and the
340
- // MCP-standard { content: [{ type:'text', text }] } (incl. an embedded
341
- // { resource: { text } }). Only text-bearing fields are redacted — arbitrary
342
- // fields (ids, urls, mime types) are left intact so tool results stay valid.
343
- // Restore is the inverse concern; this only runs on the model-facing direction.
344
- export function redactResultShape(raw, vault, opts) {
345
- if (raw == null || typeof raw === 'string') {
346
- return raw == null ? raw : redactText(raw, vault, opts);
347
- }
348
- if (Array.isArray(raw)) return raw.map((r) => redactResultShape(r, vault, opts));
349
- if (typeof raw === 'object') {
350
- let out = raw;
351
- if (typeof raw.text === 'string') out = { ...out, text: redactText(raw.text, vault, opts) };
352
- if (Array.isArray(raw.content)) out = { ...out, content: raw.content.map((c) => redactResultShape(c, vault, opts)) };
353
- if (raw.resource && typeof raw.resource === 'object' && typeof raw.resource.text === 'string') {
354
- out = { ...out, resource: { ...raw.resource, text: redactText(raw.resource.text, vault, opts) } };
355
- }
356
- return out;
357
- }
358
- return raw;
359
- }
360
-
361
- // Swap placeholders back to their originals. Unknown tokens are left untouched.
362
- export function restoreText(text, vault) {
363
- if (text == null || !vault) return text;
364
- return String(text).replace(TOLERANT_TOKEN_RE, (m, inner) => {
365
- const canonical = `[[${inner}]]`;
366
- return vault.byToken.has(canonical) ? vault.byToken.get(canonical) : m;
367
- });
368
- }
369
-
370
- // Restore for LOCAL use only — e.g. tool-call args that hit on-device history /
371
- // meeting search. Undoes reversible tokens AND pseudonyms, so local lookups run on
372
- // the real values. NOT used for the user-facing reply (pseudonyms stay there).
373
- export function restoreWithAliases(text, vault) {
374
- let out = restoreText(text, vault);
375
- if (vault?.aliases?.size) {
376
- // ONE pass over every alias at once. Looping `replace` per alias re-scans the
377
- // output and cascades when one alias's real value equals another alias (e.g.
378
- // 'Twinkle'→'John' then 'John'→'Arnav'): the model's "Twinkle" would walk the
379
- // chain to "Arnav". A single alternation replaces each span exactly once.
380
- // Longest alias first so a multi-word pseudonym wins over its prefix.
381
- const aliases = [...vault.aliases.keys()].filter(Boolean).sort((a, b) => b.length - a.length);
382
- if (aliases.length) {
383
- const re = new RegExp(`(?<![\\w])(?:${aliases.map(escapeRegex).join('|')})(?![\\w])`, 'g');
384
- out = out.replace(re, (m) => (vault.aliases.has(m) ? vault.aliases.get(m) : m));
385
- }
386
- }
387
- return out;
388
- }
389
-
390
- /**
391
- * THE LAST LINE BEFORE A HUMAN READS IT.
392
- *
393
- * `restoreText` undoes what a given vault minted. This asks the harder question a UI has to
394
- * answer: is there ANY placeholder left in what I am about to show? A reply is redacted for
395
- * the model's benefit, never the reader's — so a token reaching the screen is always a bug,
396
- * and one that is invisible to the code that caused it, because by then the turn is over.
397
- *
398
- * It exists because a turn can mint tokens in one vault and be restored against another (or
399
- * against none): a local agent under "redact for remote only" gets no vault at all, while
400
- * tool results reaching it may already carry placeholders from somewhere else. Every one of
401
- * those paths ends at the same render call, so the check belongs there.
402
- *
403
- * Returns `{ text, unresolved }` — restored where the vault knows the token, and the list of
404
- * the ones it could not, so the caller can decide (mask, warn, log) rather than silently
405
- * shipping `[[PERSON_5]]` to a person reading about their own colleagues.
406
- */
407
- export function scrubPlaceholders(text, vault) {
408
- const src = String(text ?? '');
409
- if (!src) return { text: src, unresolved: [] };
410
- const unresolved = [];
411
- const out = src.replace(TOKEN_RE, (match) => {
412
- const value = vault?.byToken?.get(match);
413
- if (value != null) return value;
414
- unresolved.push(match);
415
- return match;
416
- });
417
- TOKEN_RE.lastIndex = 0;
418
- return { text: out, unresolved };
419
- }
420
-
421
- // True if the text still contains any redaction placeholder (useful for streaming
422
- // restore — buffer a tail when a token may be split across chunks).
423
- export function hasToken(text) {
424
- TOKEN_RE.lastIndex = 0;
425
- return TOKEN_RE.test(String(text || ''));
426
- }
427
-
428
- // ── What was redacted, for the user's own eyes ──────────────────────────────────────────
429
- //
430
- // The privacy promise is invisible unless you can SEE it: which entity types were caught,
431
- // how many of each, and (on request) the actual before → after pairs. All of that already
432
- // exists in the vault — this just summarises it, so every client renders the same shape
433
- // instead of each one re-deriving it.
434
- //
435
- // PRIVACY OF THE SUMMARY ITSELF: `types` carries counts only, never values, so it is safe
436
- // to render, log or persist. Real values live behind `pairs`, which a caller must ask for
437
- // explicitly (`includeValues: true`) — they are the user's own data, shown on their own
438
- // device, and must never be written anywhere durable.
439
-
440
- /** Entity type + count for everything this vault redacted, most-frequent first. */
441
- export function redactionSummary(vault, { includeValues = false, maxPairs = 200 } = {}) {
442
- const byType = new Map();
443
- const pairs = [];
444
- for (const [token, value] of vault?.byToken || new Map()) {
445
- const m = /^\[\[([A-Z][A-Z0-9]*)_(\d+)\]\]$/.exec(token);
446
- const type = m ? m[1] : 'OTHER';
447
- byType.set(type, (byType.get(type) || 0) + 1);
448
- if (includeValues && pairs.length < maxPairs) pairs.push({ token, value, type });
449
- }
450
- const types = [...byType.entries()]
451
- .map(([type, count]) => ({ type, count }))
452
- .sort((a, b) => b.count - a.count || a.type.localeCompare(b.type));
453
- return {
454
- total: types.reduce((n, t) => n + t.count, 0),
455
- types,
456
- ...(includeValues ? { pairs } : {}),
457
- };
458
- }
459
-
460
- /** Merge several vault summaries (e.g. every conversation) into one. Counts only. */
461
- export function mergeRedactionSummaries(summaries) {
462
- const byType = new Map();
463
- for (const s of summaries || []) {
464
- for (const t of s?.types || []) byType.set(t.type, (byType.get(t.type) || 0) + t.count);
465
- }
466
- const types = [...byType.entries()]
467
- .map(([type, count]) => ({ type, count }))
468
- .sort((a, b) => b.count - a.count || a.type.localeCompare(b.type));
469
- return { total: types.reduce((n, t) => n + t.count, 0), types };
470
- }
1
+ import{stripHidden as I,confusablesSkeleton as Z}from"./sanitize.js";const y=/\[\[([A-Z][A-Z0-9]*)_(\d+)\]\]/g,m=Object.freeze(["PERSON","ORG","LOCATION","ADDRESS","EMAIL","PHONE","ID","SSN","IBAN","CREDITCARD","CARD","POST","FAC","GROUP","NRP","ENTITY","KEY","SECRET","TERM","PII","OTHER"]);function $(e){const t=String(e??"").trim().replace(/^\[{1,2}|\]{1,2}$/g,""),n=/^([A-Z][A-Z0-9]*)_\d+$/.exec(t);return!!n&&m.includes(n[1])}const k=/\[{0,2}([A-Z][A-Z0-9]*_\d+)\]{0,2}/g;function b(){return{byToken:new Map,byValue:new Map,counts:new Map,aliases:new Map}}function v(e){return{entries:[...e?.byToken||new Map].map(([t,n])=>({token:t,value:n})),aliases:[...e?.aliases||new Map].map(([t,n])=>({alias:t,value:n}))}}function D(e){const t=b();for(const{token:n,value:r}of e?.entries||[]){const s=/^\[\[([A-Z][A-Z0-9]*)_(\d+)\]\]$/.exec(n);t.byToken.set(n,r),t.byValue.set(r,n),s&&t.counts.set(s[1],Math.max(t.counts.get(s[1])||0,Number(s[2])))}for(const{alias:n,value:r}of e?.aliases||[])t.aliases.set(n,r);return t}function h(e,t,n){const r=e.byValue.get(n);if(r)return r;const s=String(t||"PII").toUpperCase().replace(/[^A-Z0-9]/g,"")||"PII",l=(e.counts.get(s)||0)+1;e.counts.set(s,l);const c=`[[${s}_${l}]]`;return e.byToken.set(c,n),e.byValue.set(n,c),c}function x(e){return String(e).replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function _(e){return!(typeof e!="string"||e.length===0||e.length>200||/\([^)]*[+*}][^)]*\)\s*[+*{]/.test(e)||/[+*]\s*[+*]/.test(e))}function O(e,t){if(!t||t.length===0)return e;let n="",r=0;const s=e.length;for(;r<=s;){let l=null,c=null;for(const a of t){a.re.lastIndex=r;const f=a.re.exec(e);if(f&&(l===null||f.index<l.index)&&(l=f,c=a,f.index===r))break}if(!l){n+=e.slice(r);break}n+=e.slice(r,l.index),l[0].length===0?(n+=e[l.index]??"",r=l.index+1):(n+=c.repl(l),r=l.index+l[0].length)}return n}function N(e){let t=0,n=!1;for(let r=e.length-1;r>=0;r--){let s=e.charCodeAt(r)-48;n&&(s*=2,s>9&&(s-=9)),t+=s,n=!n}return t%10===0}function P(e){if(!/^[0-9A-Fa-f:]+$/.test(e)||(e.match(/:/g)||[]).length<2)return!1;const t=e.split(":");return t.some(n=>n.length>4)?!1:e.includes("::")?t.filter(Boolean).length>=1&&t.filter(Boolean).length<=7:t.length===8&&t.every(n=>n.length>=1)}const z=[{type:"SECRET",re:/-----BEGIN (?:[A-Z0-9]+ )*PRIVATE KEY-----[\s\S]*?-----END (?:[A-Z0-9]+ )*PRIVATE KEY-----/g},{type:"EMAIL",re:/\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}\b/g},{type:"SSN",re:/\b\d{3}[-\s]\d{2}[-\s]\d{4}\b/g},{type:"KEY",re:/\b(?:sk-[A-Za-z0-9_-]{16,}|AKIA[0-9A-Z]{16}|gh[pousr]_[A-Za-z0-9]{20,}|github_pat_[0-9A-Za-z_]{22,}|xox[baprs]-[A-Za-z0-9-]{10,}|xapp-[0-9]-[A-Za-z0-9-]{10,}|AIza[0-9A-Za-z_-]{35}|[rs]k_(?:live|test)_[0-9A-Za-z]{16,})\b/g},{type:"KEY",re:/\beyJ[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{6,}\.[A-Za-z0-9_-]{6,}\b/g},{type:"IP",re:/\b(?:(?:25[0-5]|2[0-4]\d|1?\d?\d)\.){3}(?:25[0-5]|2[0-4]\d|1?\d?\d)\b/g},{type:"IP",re:/(?<![:\w])(?:[0-9A-Fa-f]{0,4}:){2,7}[0-9A-Fa-f]{0,4}(?![:\w])/g,valid:e=>P(e)},{type:"PHONE",re:/(?<![\w.])\+?\d[\d ().-]{6,}\d(?![\w])/g,valid:e=>{const t=e.replace(/\D/g,"");return t.length>=7&&t.length<=15&&(/[ ().-]/.test(e)||e.trimStart().startsWith("+")||t.length===10)}},{type:"CARD",re:/\b(?:\d[ -]?){13,19}\b/g,valid:e=>{const t=e.replace(/\D/g,"");return t.length>=13&&t.length<=19&&N(t)}}];function E(e,t,{tier:n="basic",entities:r=[],dictionary:s=[],sanitize:l=!0,sanitizeOpts:c=void 0}={}){if(e==null||e==="")return e;let a=l?I(String(e),c):String(e);const f=t||b(),g=n==="full"||n==="entities",A=[];for(const o of s||[]){if(!o)continue;let i;try{i=o.pattern?_(o.pattern)?new RegExp(o.pattern,o.flags&&/g/.test(o.flags)?o.flags:`${o.flags||""}g`):null:o.value?new RegExp(`(?<![\\w])${x(o.value)}(?![\\w])`,"gi"):null}catch{i=null}if(i)if(o.alias!=null&&o.alias!=="")o.value&&f.aliases.set(o.alias,o.value),A.push({re:i,repl:()=>o.alias});else{const u=o.type||(o.pattern?"PII":"TERM");A.push({re:i,repl:p=>h(f,u,o.pattern?p[0]:o.value)})}}if(a=O(a,A),g){const o=[...r||[]].filter(i=>i&&i.value).sort((i,u)=>String(u.value).length-String(i.value).length);for(const i of o){const u=new RegExp(`(?<![\\w])${x(i.value)}(?![\\w])`,"gi");a=a.replace(u,()=>h(f,i.type||"PERSON",i.value))}}const R=Z(a),d=[],S=(o,i)=>d.some(u=>o<u.end&&i>u.start);for(const o of z){o.re.lastIndex=0;let i;for(;(i=o.re.exec(R))!==null;){if(i[0].length===0){o.re.lastIndex++;continue}const u=i.index,p=u+i[0].length;o.valid&&!o.valid(i[0])||S(u,p)||d.push({start:u,end:p,type:o.type})}}if(d.length){d.sort((u,p)=>u.start-p.start);let o="",i=0;for(const u of d)o+=a.slice(i,u.start)+h(f,u.type,a.slice(u.start,u.end)),i=u.end;a=o+a.slice(i)}return a}function T(e,t,n){if(e==null||typeof e=="string")return e==null?e:E(e,t,n);if(Array.isArray(e))return e.map(r=>T(r,t,n));if(typeof e=="object"){let r=e;return typeof e.text=="string"&&(r={...r,text:E(e.text,t,n)}),Array.isArray(e.content)&&(r={...r,content:e.content.map(s=>T(s,t,n))}),e.resource&&typeof e.resource=="object"&&typeof e.resource.text=="string"&&(r={...r,resource:{...e.resource,text:E(e.resource.text,t,n)}}),r}return e}function C(e,t){return e==null||!t?e:String(e).replace(k,(n,r)=>{const s=`[[${r}]]`;return t.byToken.has(s)?t.byToken.get(s):n})}function K(e,t){let n=C(e,t);if(t?.aliases?.size){const r=[...t.aliases.keys()].filter(Boolean).sort((s,l)=>l.length-s.length);if(r.length){const s=new RegExp(`(?<![\\w])(?:${r.map(x).join("|")})(?![\\w])`,"g");n=n.replace(s,l=>t.aliases.has(l)?t.aliases.get(l):l)}}return n}function w(e,t){const n=String(e??"");if(!n)return{text:n,unresolved:[]};const r=[],s=n.replace(y,l=>{const c=t?.byToken?.get(l);return c??(r.push(l),l)});return y.lastIndex=0,{text:s,unresolved:r}}function V(e){return y.lastIndex=0,y.test(String(e||""))}function Y(e,{includeValues:t=!1,maxPairs:n=200}={}){const r=new Map,s=[];for(const[c,a]of e?.byToken||new Map){const f=/^\[\[([A-Z][A-Z0-9]*)_(\d+)\]\]$/.exec(c),g=f?f[1]:"OTHER";r.set(g,(r.get(g)||0)+1),t&&s.length<n&&s.push({token:c,value:a,type:g})}const l=[...r.entries()].map(([c,a])=>({type:c,count:a})).sort((c,a)=>a.count-c.count||c.type.localeCompare(a.type));return{total:l.reduce((c,a)=>c+a.count,0),types:l,...t?{pairs:s}:{}}}function F(e){const t=new Map;for(const r of e||[])for(const s of r?.types||[])t.set(s.type,(t.get(s.type)||0)+s.count);const n=[...t.entries()].map(([r,s])=>({type:r,count:s})).sort((r,s)=>s.count-r.count||r.type.localeCompare(s.type));return{total:n.reduce((r,s)=>r+s.count,0),types:n}}export{m as REDACTION_TOKEN_TYPES,b as createVault,V as hasToken,$ as isRedactionToken,F as mergeRedactionSummaries,T as redactResultShape,E as redactText,Y as redactionSummary,C as restoreText,K as restoreWithAliases,w as scrubPlaceholders,D as vaultFromJSON,v as vaultToJSON};
@@ -1,137 +1 @@
1
- // GENERATED — do not edit.
2
- // Source of truth: chatpanel-pii/pipeline.js (npm @chatpanel/pii).
3
- // Edit there, then run: npm run sync:pii
4
- //
5
- // Vendored rather than depended on: the bridge ships zero runtime dependencies so a
6
- // curl one-liner install cannot fail on someone's registry, and so the compiled
7
- // single-file binary has nothing to resolve.
8
-
9
- // Pure turn-level orchestration shared by every ChatPanel surface (extension,
10
- // gateway, bridge). It composes the deterministic engine (pii-redact.js) into the
11
- // message pipeline and applies the tier / scope / dictionary gating.
12
- //
13
- // What lives HERE (portable): redactOutbound, redactToolResult/redactResult,
14
- // makeStreamRestorer, restore/restoreDeep, effectiveTier + gating.
15
- //
16
- // Host glue kept in the EXTENSION (NOT here): reading settings.ui.piiRedaction,
17
- // the entitlement flag, and chrome storage — those wrap these pure functions with
18
- // host-specific config.
19
-
20
- import { redactText, restoreText, restoreWithAliases, redactResultShape } from './pii-redact.js';
21
-
22
- export function redactionEnabled(cfg) {
23
- return !!(cfg && cfg.mode && cfg.mode !== 'off');
24
- }
25
-
26
- // The entity (name/org) tier is Pro; Free falls back to the deterministic regex tier.
27
- export function effectiveTier(cfg, isPro) {
28
- const t = cfg?.tier === 'full' ? 'full' : 'basic';
29
- return t === 'full' && !isPro ? 'basic' : t;
30
- }
31
-
32
- // On Free the first FREE_DICT_LIMIT custom-dictionary entries apply; the full
33
- // dictionary is Pro. Enforced here as well as in the UI.
34
- export const FREE_DICT_LIMIT = 5;
35
-
36
- export function gatedDictionary(cfg, isPro) {
37
- const d = Array.isArray(cfg?.dictionary) ? cfg.dictionary : [];
38
- return isPro ? d : d.slice(0, FREE_DICT_LIMIT);
39
- }
40
-
41
- export function gatedScope(cfg, isPro) {
42
- const s = cfg?.scope || {};
43
- if (isPro) return s;
44
- return { chat: s.chat !== false, context: false, history: false, toolResults: false };
45
- }
46
-
47
- export function redactOpts(cfg, isPro, entities) {
48
- return {
49
- tier: effectiveTier(cfg, isPro),
50
- entities: entities || [],
51
- dictionary: gatedDictionary(cfg, isPro),
52
- };
53
- }
54
-
55
- // Returns redacted COPIES — never mutates the stored conversation.
56
- export function redactOutbound({ messages, system, vault, cfg, isPro = false, entities = [] }) {
57
- if (!redactionEnabled(cfg) || !vault) return { messages, system };
58
- const opts = redactOpts(cfg, isPro, entities);
59
- const scope = gatedScope(cfg, isPro);
60
- const redactMsg = (m) => {
61
- const copy = { ...m };
62
- if (scope.chat !== false && m.content) copy.content = redactText(m.content, vault, opts);
63
- if (Array.isArray(m.attachments)) {
64
- copy.attachments = m.attachments.map((a) => {
65
- if (a.kind === 'image' || !a.text) return a;
66
- const isHistory = a.kind === 'history-rag';
67
- if (isHistory ? scope.history === false : scope.context === false) return a;
68
- return { ...a, text: redactText(a.text, vault, opts) };
69
- });
70
- }
71
- return copy;
72
- };
73
- return {
74
- messages: (messages || []).map(redactMsg),
75
- system: system ? redactText(system, vault, opts) : system,
76
- };
77
- }
78
-
79
- export function redactToolResult(text, { vault, cfg, isPro = false, entities = [] } = {}) {
80
- if (!redactionEnabled(cfg) || !vault || !gatedScope(cfg, isPro).toolResults) return text;
81
- if (typeof text !== 'string') return text;
82
- return redactText(text, vault, redactOpts(cfg, isPro, entities));
83
- }
84
-
85
- // Streaming-safe restorer. push() returns text safe to display now; flush() the rest.
86
- export function makeStreamRestorer(vault) {
87
- let buf = '';
88
- return {
89
- push(chunk) {
90
- if (!vault) return chunk || '';
91
- buf += chunk || '';
92
- const open = buf.lastIndexOf('[[');
93
- let safe;
94
- if (open !== -1 && !buf.slice(open).includes(']]')) {
95
- safe = buf.slice(0, open);
96
- buf = buf.slice(open);
97
- } else {
98
- safe = buf;
99
- buf = '';
100
- }
101
- return restoreText(safe, vault);
102
- },
103
- flush() {
104
- const out = vault ? restoreText(buf, vault) : buf;
105
- buf = '';
106
- return out;
107
- },
108
- };
109
- }
110
-
111
- export function restore(text, vault) {
112
- return vault ? restoreText(text, vault) : text;
113
- }
114
-
115
- // Deep-restore a value (tool-call args contain tokens; local tools must run on the
116
- // REAL values). restoreWithAliases undoes pseudonyms too — local lookups hit real
117
- // data; only the model stays blinded.
118
- export function restoreDeep(value, vault) {
119
- if (!vault) return value;
120
- if (typeof value === 'string') return restoreWithAliases(value, vault);
121
- if (Array.isArray(value)) return value.map((v) => restoreDeep(v, vault));
122
- if (value && typeof value === 'object') {
123
- const out = {};
124
- for (const k of Object.keys(value)) out[k] = restoreDeep(value[k], vault);
125
- return out;
126
- }
127
- return value;
128
- }
129
-
130
- // Re-redact a tool result of any shape (string / { text } / array / MCP
131
- // { content:[{text}] }), gated once by the toolResults scope. The old path only
132
- // covered string + { text }, so PII in a content[] item reached the model.
133
- export function redactResult(result, ctx) {
134
- const { vault, cfg, isPro = false, entities = [] } = ctx || {};
135
- if (!redactionEnabled(cfg) || !vault || !gatedScope(cfg, isPro).toolResults) return result;
136
- return redactResultShape(result, vault, redactOpts(cfg, isPro, entities));
137
- }
1
+ import{redactText as c,restoreText as d,restoreWithAliases as b,redactResultShape as m}from"./pii-redact.js";function l(t){return!!(t&&t.mode&&t.mode!=="off")}function A(t,e){const r=t?.tier==="full"?"full":"basic";return r==="full"&&!e?"basic":r}const T=5;function k(t,e){const r=Array.isArray(t?.dictionary)?t.dictionary:[];return e?r:r.slice(0,T)}function y(t,e){const r=t?.scope||{};return e?r:{chat:r.chat!==!1,context:!1,history:!1,toolResults:!1}}function x(t,e,r){return{tier:A(t,e),entities:r||[],dictionary:k(t,e)}}function D({messages:t,system:e,vault:r,cfg:n,isPro:o=!1,entities:f=[]}){if(!l(n)||!r)return{messages:t,system:e};const u=x(n,o,f),p=y(n,o),R=i=>{const a={...i};return p.chat!==!1&&i.content&&(a.content=c(i.content,r,u)),Array.isArray(i.attachments)&&(a.attachments=i.attachments.map(s=>s.kind==="image"||!s.text||(s.kind==="history-rag"?p.history===!1:p.context===!1)?s:{...s,text:c(s.text,r,u)})),a};return{messages:(t||[]).map(R),system:e&&c(e,r,u)}}function E(t,{vault:e,cfg:r,isPro:n=!1,entities:o=[]}={}){return!l(r)||!e||!y(r,n).toolResults||typeof t!="string"?t:c(t,e,x(r,n,o))}function S(t){let e="";return{push(r){if(!t)return r||"";e+=r||"";const n=e.lastIndexOf("[[");let o;return n!==-1&&!e.slice(n).includes("]]")?(o=e.slice(0,n),e=e.slice(n)):(o=e,e=""),d(o,t)},flush(){const r=t?d(e,t):e;return e="",r}}}function j(t,e){return e?d(t,e):t}function h(t,e){if(!e)return t;if(typeof t=="string")return b(t,e);if(Array.isArray(t))return t.map(r=>h(r,e));if(t&&typeof t=="object"){const r={};for(const n of Object.keys(t))r[n]=h(t[n],e);return r}return t}function H(t,e){const{vault:r,cfg:n,isPro:o=!1,entities:f=[]}=e||{};return!l(n)||!r||!y(n,o).toolResults?t:m(t,r,x(n,o,f))}export{T as FREE_DICT_LIMIT,A as effectiveTier,k as gatedDictionary,y as gatedScope,S as makeStreamRestorer,x as redactOpts,D as redactOutbound,H as redactResult,E as redactToolResult,l as redactionEnabled,j as restore,h as restoreDeep};