leakshield 0.0.0-stage → 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (47) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +546 -2
  3. package/README.zh-TW.md +565 -0
  4. package/dist/cli.js +61 -0
  5. package/dist/config/loader.js +94 -0
  6. package/dist/decision/deidentify.js +195 -0
  7. package/dist/decision/ingress.js +136 -0
  8. package/dist/decision/mapping-key.js +318 -0
  9. package/dist/decision/mapping-store.js +555 -0
  10. package/dist/decision/model.js +76 -0
  11. package/dist/decision/pseudonymization.js +1230 -0
  12. package/dist/decision/redaction.js +185 -0
  13. package/dist/decision/schema-strings.js +42 -0
  14. package/dist/doctor.js +438 -0
  15. package/dist/env-queries.js +584 -0
  16. package/dist/forget.js +56 -0
  17. package/dist/help.js +37 -0
  18. package/dist/i18n/en.js +71 -0
  19. package/dist/i18n/index.js +28 -0
  20. package/dist/i18n/zh-TW.js +71 -0
  21. package/dist/index.js +12 -0
  22. package/dist/opencode-env-tools.js +243 -0
  23. package/dist/opencode-hooks.js +84 -0
  24. package/dist/opencode-transparent-aisdk.js +100 -0
  25. package/dist/opencode-transparent-http.js +2315 -0
  26. package/dist/opencode-transparent-stream.js +192 -0
  27. package/dist/opencode-transparent-ws.js +298 -0
  28. package/dist/opencode-transparent.js +1492 -0
  29. package/dist/opencode-v2.js +216 -0
  30. package/dist/opencode.js +175 -0
  31. package/dist/plugin-options.js +100 -0
  32. package/dist/rules/builtin.js +283 -0
  33. package/dist/rules/dynamic.js +68 -0
  34. package/dist/scanner/encoding.js +274 -0
  35. package/dist/scanner/engine.js +321 -0
  36. package/dist/scanner/exact-values.js +99 -0
  37. package/dist/scanner/redaction-verifier.js +82 -0
  38. package/dist/scanner/unicode.js +157 -0
  39. package/dist/scanner/utils.js +60 -0
  40. package/dist/transports/cli.js +447 -0
  41. package/dist/transports/web-ui.js +540 -0
  42. package/dist/transports/web.js +200 -0
  43. package/dist/types.js +23 -0
  44. package/dist/utils/files.js +36 -0
  45. package/dist/utils/path-security.js +30 -0
  46. package/dist/utils/win-encoding.js +45 -0
  47. package/package.json +71 -4
@@ -0,0 +1,1230 @@
1
+ /**
2
+ * Session-scoped reversible pseudonymization core (issue #22, offline core).
3
+ *
4
+ * This module is a PURE IN-MEMORY DATA SUBSTITUTION engine over strings and
5
+ * strict-JSON values. It performs exact, reversible replacement of scanner
6
+ * findings with opaque session-scoped tokens. It does NOT provide, and must
7
+ * not be described as providing: shell escaping, tool permission decisions,
8
+ * model dispatch, provider/streaming/WebSocket rewriting, UI restoration, or
9
+ * persistence. Runtime adapters are not wired in this module; integrating it
10
+ * into OpenCode hooks remains gated on runtime evidence.
11
+ *
12
+ * Guarantees implemented here:
13
+ * - Bidirectional exact-string mapping per session identity (never normalized,
14
+ * never shared across sessions, never persisted; no TTL, no eviction, no fs).
15
+ * - Reserved token namespace, two versions (W1, 2026-10-07): new mints are
16
+ * category-labelled `[SGP2:<FINDING_TYPE>-<4 letters>×3]` with a random
17
+ * letter-only payload (digit-free so digit-based detector families cannot
18
+ * match it); the legacy `[SGP1:<epoch32hex>-<counter>]` shape stays
19
+ * recognized so mappings issued before the switch keep restoring. Strict
20
+ * protection and restoration entrypoints reject foreign, expired, or
21
+ * malformed markers of either version. Explicit model-text entrypoints
22
+ * preserve unknown markers as literal text, scan them normally, and never
23
+ * grant them mapping ownership.
24
+ * - Every protect/restore operation is an atomic transaction: the live
25
+ * registry is mutated only after the whole operation (including rescans,
26
+ * token-neighbor scans, capacity checks and independent absence checks)
27
+ * succeeds. Failed restores never mutate anything; inputs are never mutated.
28
+ * - Issued tokens are validated FIRST, as a unit: their spans are exempt
29
+ * (interior findings included, before overlap checks) on input and output,
30
+ * crossing matches still fail, and token epochs are never decoded as user
31
+ * content — decoding runs only over separate non-token segments, while
32
+ * the decoder's URL-context windows crossing a token retain that token's
33
+ * fragment verbatim and decode only the surrounding pieces.
34
+ * - Failures carry ONLY a static reason string: no originals, findings,
35
+ * previews, exception messages, partial output, or blocked-content notices.
36
+ *
37
+ * Non-goals documented up front: this is not universal detection. The engine's
38
+ * own finding collapse can hide values; the rescan plus independent absence
39
+ * check below is defense in depth over WHAT the scanner reports, not a claim
40
+ * that every sensitive value is detected.
41
+ */
42
+ import { randomBytes } from "node:crypto";
43
+ import { types } from "node:util";
44
+ import { scanTextWithDecoding } from "../scanner/encoding.js";
45
+ import { scanTextInternal } from "../scanner/engine.js";
46
+ import { FINDING_TYPES } from "../types.js";
47
+ // ─── Constants ───────────────────────────────────────────────────────────────
48
+ /**
49
+ * Reserved, recognizable token namespace — two versions.
50
+ *
51
+ * v1 (legacy, still recognized for restoration of pre-upgrade mappings):
52
+ * `[SGP1:<32 lowercase hex epoch>-<zero-padded counter>]`, e.g.
53
+ * `[SGP1:0f1e...-00000001]`.
54
+ *
55
+ * v2 (minted since W1, 2026-10-07): `[SGP2:<CATEGORY>-<seg>-<seg>-<seg>]`,
56
+ * e.g. `[SGP2:PII_EMAIL-wxyz-abcd-efgh]`. CATEGORY is the scanner
57
+ * FindingType label (closed enum, `[A-Z][A-Z_]*`); each segment is 4
58
+ * lowercase letters. Design constraints (decision doc W1 / T3):
59
+ * - letter-only payload ⇒ zero digit runs (phone/card/IBAN/TW-ID families
60
+ * cannot match), ≤4-char hex-like runs (hex detector needs far longer);
61
+ * - `-` after the category (not `:`) so the generic-secret keyword shape
62
+ * `secret\s*[:=]\s*value` cannot self-collide with `SECRET-…` labels;
63
+ * - payload alphabet shares no shell metacharacter, like v1.
64
+ * Any occurrence of either prefix in any scanned or restored string is
65
+ * validated strictly against its version's shape; unknown shapes fail the
66
+ * operation.
67
+ */
68
+ export const PSEUDONYM_TOKEN_PREFIX = "[SGP1:";
69
+ export const PSEUDONYM_TOKEN_PREFIX_V2 = "[SGP2:";
70
+ /** All reserved token prefixes, both versions. */
71
+ export const PSEUDONYM_TOKEN_PREFIXES = [
72
+ PSEUDONYM_TOKEN_PREFIX,
73
+ PSEUDONYM_TOKEN_PREFIX_V2,
74
+ ];
75
+ /** True when `text` contains any reserved token prefix (either version). */
76
+ export function containsTokenPrefix(text) {
77
+ return PSEUDONYM_TOKEN_PREFIXES.some((prefix) => text.includes(prefix));
78
+ }
79
+ const TOKEN_SHAPE = /\[SGP1:[0-9a-f]{32}-\d{8,12}\]/y;
80
+ const TOKEN_SHAPE_V2 = /\[SGP2:[A-Z][A-Z_]{0,31}-[a-z]{4}-[a-z]{4}-[a-z]{4}\]/y;
81
+ /** R-round (F1.2): seed intake accepts only real FindingType categories — a
82
+ * tampered store must not hydrate arbitrary-category tokens into the
83
+ * registry. Mint paths derive the label from live findings and cannot lie. */
84
+ const KNOWN_SGP2_CATEGORIES = new Set(FINDING_TYPES);
85
+ const EPOCH_HEX_CHARS = 32; // 128-bit random session epoch
86
+ const PAYLOAD_SEGMENT_CHARS = 4;
87
+ const PAYLOAD_SEGMENTS = 3;
88
+ const PAYLOAD_ALPHABET = "abcdefghijklmnopqrstuvwxyz";
89
+ // 26 * 9 = 234: bytes below this threshold are uniform modulo 26.
90
+ const PAYLOAD_BYTE_CEILING = 234;
91
+ /** Conservative per-entry accounting overhead in UTF-16 units. */
92
+ const ENTRY_OVERHEAD_UNITS = 64;
93
+ /** Conservative per-JSON-node accounting overhead in UTF-16 units. */
94
+ const NODE_OVERHEAD_UNITS = 8;
95
+ const SESSION_ID_MAX_UNITS = 256;
96
+ const DEFAULT_LIMITS = {
97
+ maxSessions: 128,
98
+ maxEntriesPerSession: 4096,
99
+ maxSessionUnits: 2 * 1024 * 1024, // ≈ 4 MiB at 2 bytes per UTF-16 unit
100
+ maxEntriesTotal: 65536,
101
+ maxUnitsTotal: 16 * 1024 * 1024, // ≈ 32 MiB at 2 bytes per UTF-16 unit
102
+ maxDepth: 32,
103
+ maxNodes: 10000,
104
+ maxUnitsPerOperation: 1024 * 1024,
105
+ };
106
+ // ─── Small helpers ───────────────────────────────────────────────────────────
107
+ function fail(reason) {
108
+ return { ok: false, reason };
109
+ }
110
+ function isValidSessionId(value) {
111
+ // Exact identity: no trimming, no normalization, no shared fallback.
112
+ return typeof value === "string" && value.length > 0 && value.length <= SESSION_ID_MAX_UNITS;
113
+ }
114
+ function isPositiveSafeInt(value) {
115
+ return typeof value === "number" && Number.isSafeInteger(value) && value > 0;
116
+ }
117
+ function isValidConfigShape(config) {
118
+ if (typeof config !== "object" || config === null)
119
+ return false;
120
+ const settings = config.settings;
121
+ if (typeof settings !== "object" || settings === null)
122
+ return false;
123
+ return isPositiveSafeInt(settings.max_chars);
124
+ }
125
+ /**
126
+ * Durable snapshot of the validated scanner configuration. The service must
127
+ * never re-read caller-owned objects after the factory returns: post-
128
+ * construction mutations (settings.max_chars = NaN, custom_rules array
129
+ * edits, nested pattern rewrites) must not be able to weaken or enlarge
130
+ * scanning. Plain data (settings, nested rules, keyword/domain arrays,
131
+ * exclusions) is deep-copied. The exact-value detector is snapshotted as a
132
+ * private facade whose scanner-facing callable (findAll — the only method
133
+ * the scanner invokes, plus the public fingerprint) is captured AND bound
134
+ * at factory time, so no later instance or prototype lookup can weaken
135
+ * detection. The facade exposes no detector values and never mutates the
136
+ * caller's detector or class. Returns null when the config cannot be
137
+ * snapshotted without invoking unsupported behavior — the factory then
138
+ * fails statically instead of scanning weakened.
139
+ */
140
+ function snapshotConfig(config) {
141
+ try {
142
+ const { exact_value_detector, ...dataOnly } = config;
143
+ const snapshot = structuredClone(dataOnly);
144
+ if (exact_value_detector !== undefined) {
145
+ const findAll = exact_value_detector.findAll;
146
+ if (typeof findAll !== "function")
147
+ return null;
148
+ snapshot.exact_value_detector = {
149
+ fingerprint: exact_value_detector.fingerprint,
150
+ findAll: findAll.bind(exact_value_detector),
151
+ };
152
+ }
153
+ return snapshot;
154
+ }
155
+ catch {
156
+ return null;
157
+ }
158
+ }
159
+ function resolveLimits(limits) {
160
+ if (limits === undefined)
161
+ return { ...DEFAULT_LIMITS };
162
+ if (typeof limits !== "object" || limits === null)
163
+ return null;
164
+ const resolved = { ...DEFAULT_LIMITS };
165
+ for (const key of Object.keys(DEFAULT_LIMITS)) {
166
+ const provided = limits[key];
167
+ if (provided === undefined)
168
+ continue;
169
+ if (!isPositiveSafeInt(provided))
170
+ return null;
171
+ resolved[key] = provided;
172
+ }
173
+ return resolved;
174
+ }
175
+ function spansOverlap(a, b) {
176
+ return a.start < b.end && b.start < a.end;
177
+ }
178
+ function containedInSpan(inner, outer) {
179
+ return inner.start >= outer.start && inner.end <= outer.end;
180
+ }
181
+ function containedInAnySpan(inner, spans) {
182
+ return spans.some((outer) => containedInSpan(inner, outer));
183
+ }
184
+ // ─── Token occurrence scanning ───────────────────────────────────────────────
185
+ /**
186
+ * Finds registered token spans. Strict callers reject every malformed or
187
+ * unowned marker; model-text callers may leave those occurrences literal —
188
+ * well-shaped unregistered markers are additionally reported in `preserved`
189
+ * so callers can mask a whole marker (one unit, never nested) when a finding
190
+ * touches its payload.
191
+ */
192
+ /** Earliest reserved-token prefix (either version) at/after `from`. */
193
+ function findTokenPrefix(text, from) {
194
+ let best;
195
+ for (const prefix of PSEUDONYM_TOKEN_PREFIXES) {
196
+ const at = text.indexOf(prefix, from);
197
+ if (at !== -1 && (best === undefined || at < best.at))
198
+ best = { at, prefix };
199
+ }
200
+ return best;
201
+ }
202
+ /** Strictly matches the versioned token shape at `at`; undefined otherwise. */
203
+ function matchTokenShape(text, at, prefix) {
204
+ const shape = prefix === PSEUDONYM_TOKEN_PREFIX_V2 ? TOKEN_SHAPE_V2 : TOKEN_SHAPE;
205
+ shape.lastIndex = at;
206
+ const match = shape.exec(text);
207
+ return match === null ? undefined : match[0];
208
+ }
209
+ function scanOwnedTokenSpans(text, isOwned, preserveUnknown = false) {
210
+ const spans = [];
211
+ const preserved = [];
212
+ let cursor = findTokenPrefix(text, 0);
213
+ while (cursor !== undefined) {
214
+ const { at, prefix } = cursor;
215
+ const token = matchTokenShape(text, at, prefix);
216
+ if (token === undefined) {
217
+ if (!preserveUnknown)
218
+ return fail("malformed_token");
219
+ const next = findTokenPrefix(text, at + prefix.length);
220
+ const close = text.indexOf("]", at + prefix.length);
221
+ cursor = next !== undefined && (close === -1 || next.at < close)
222
+ ? next
223
+ : findTokenPrefix(text, close === -1 ? text.length : close + 1);
224
+ continue;
225
+ }
226
+ const end = at + token.length;
227
+ if (!isOwned(token)) {
228
+ if (!preserveUnknown)
229
+ return fail("unknown_token");
230
+ preserved.push({ start: at, end });
231
+ cursor = findTokenPrefix(text, end);
232
+ continue;
233
+ }
234
+ spans.push({ start: at, end });
235
+ cursor = findTokenPrefix(text, end);
236
+ }
237
+ return { ok: true, spans, preserved };
238
+ }
239
+ // ─── Scanner plumbing ────────────────────────────────────────────────────────
240
+ /** The model boundary never honors in-text ignore directives. */
241
+ const MODEL_BOUNDARY_SCAN = { honorIgnoreDirectives: false };
242
+ function rawScan(text, config) {
243
+ try {
244
+ return { ok: true, original: scanTextInternal(text, config, MODEL_BOUNDARY_SCAN) };
245
+ }
246
+ catch {
247
+ return fail("scanner_failure");
248
+ }
249
+ }
250
+ /**
251
+ * Decoding hazards of ONE non-token segment, scanned strictly in isolation.
252
+ * Any truncated scanned representation or any decoded sensitive finding
253
+ * fails closed with a static reason.
254
+ */
255
+ function segmentDecodingHazard(segment, config) {
256
+ if (segment.length === 0)
257
+ return null;
258
+ try {
259
+ const scan = scanTextWithDecoding(segment, config, MODEL_BOUNDARY_SCAN);
260
+ if (scan.original.was_truncated)
261
+ return fail("truncated_content");
262
+ for (const decoded of scan.decoded) {
263
+ if (decoded.was_truncated)
264
+ return fail("truncated_content");
265
+ }
266
+ // `decoded` results only exist when a decoded representation was unsafe,
267
+ // i.e. encoded sensitive content was detected in this segment.
268
+ if (scan.decoded.length > 0)
269
+ return fail("encoded_content");
270
+ return null;
271
+ }
272
+ catch {
273
+ return fail("scanner_failure");
274
+ }
275
+ }
276
+ // Percent-run detector identical to the generic decoder's URL detection
277
+ // (src/scanner/encoding.ts detectUrlEncoding), evaluated over the FULL text
278
+ // so candidate discovery matches exactly; only decoding differs below.
279
+ const URL_PERCENT_RUN = /(?:%[0-9A-Fa-f]{2}){1,}/g;
280
+ const URL_CONTEXT_UNITS = 50;
281
+ /**
282
+ * URL-decoded context hazard across validated owned tokens — the seam
283
+ * per-segment decoding cannot cover. The generic decoder URL-decodes a
284
+ * window of up to 50 units before and after every percent run of the WHOLE
285
+ * text; that is exactly how a percent-encoded marker plus text inside an
286
+ * issued token forms a sensitive match ACROSS the token. This private check
287
+ * re-evaluates those windows without ever decoding token interiors:
288
+ *
289
+ * - Only windows intersecting a validated owned-token span are examined. A
290
+ * window intersecting no token lies wholly inside one non-token segment,
291
+ * where segmentDecodingHazard already decodes it with identical bounds.
292
+ * - The window is split at token boundaries. Owned-token fragments are
293
+ * retained VERBATIM (a clipped fragment's ownership derives from the full
294
+ * validated token in the source, never from a grammar lookalike) and only
295
+ * the separate non-token pieces are decoded with the exact tryDecodeUrl
296
+ * transform, decodeURIComponent(piece.replace(/\+/g, " ")). Token grammar
297
+ * contains no "%" or "+", so no percent run can cross a fragment and the
298
+ * separately decoded pieces equal whole-window decoding of the
299
+ * user-authored parts without decoding the token as content. Token-free
300
+ * gaps are never concatenated with each other.
301
+ * - The reassembled changed representation is scanned ONCE with the raw
302
+ * direct scanner (no recursive decoding) and truncation is enforced.
303
+ * Each retained fragment's decoded-coordinate range is tracked; findings
304
+ * wholly inside a fragment are that token's own interior and are exempt
305
+ * BEFORE any overlap consideration, exactly like the full-text seam.
306
+ * Every other finding — crossing matches and suspicious-Unicode
307
+ * synthetics included — fails encoded_content; malformed ordinary spans
308
+ * fail statically. Decoded offsets are never mapped back to the source.
309
+ * - URIError in any piece skips the whole candidate, matching the existing
310
+ * decoder's null return; unexpected exceptions fail scanner_failure.
311
+ *
312
+ * Bounds: candidates come from the source text itself (URI decoding never
313
+ * expands UTF-16 length beyond its piece), windows are processed
314
+ * sequentially with a monotonically advanced token cursor (window starts
315
+ * never move backwards), and each reassembled scan covers at most the
316
+ * percent run plus 100 units.
317
+ */
318
+ function urlContextHazard(text, config, tokenSpans) {
319
+ if (tokenSpans.length === 0)
320
+ return null;
321
+ URL_PERCENT_RUN.lastIndex = 0;
322
+ let tokenCursor = 0;
323
+ for (let run = URL_PERCENT_RUN.exec(text); run !== null; run = URL_PERCENT_RUN.exec(text)) {
324
+ const winStart = Math.max(0, run.index - URL_CONTEXT_UNITS);
325
+ const winEnd = Math.min(text.length, run.index + run[0].length + URL_CONTEXT_UNITS);
326
+ // Window starts are non-decreasing, so spans ending at or before this
327
+ // window's start can never intersect a later window: advance past them.
328
+ while (tokenCursor < tokenSpans.length && tokenSpans[tokenCursor].end <= winStart) {
329
+ tokenCursor += 1;
330
+ }
331
+ // Fragment of every validated token intersecting the window.
332
+ const fragments = [];
333
+ for (let i = tokenCursor; i < tokenSpans.length && tokenSpans[i].start < winEnd; i += 1) {
334
+ const span = tokenSpans[i];
335
+ if (span.end > winStart) {
336
+ fragments.push({ start: Math.max(span.start, winStart), end: Math.min(span.end, winEnd) });
337
+ }
338
+ }
339
+ if (fragments.length === 0)
340
+ continue; // covered by segment decoding
341
+ const ownedRanges = []; // decoded-coordinate fragment ranges
342
+ let reassembled;
343
+ try {
344
+ const pieces = [];
345
+ let decodedUnits = 0;
346
+ let pos = winStart;
347
+ for (const fragment of fragments) {
348
+ if (fragment.start > pos) {
349
+ const decoded = decodeURIComponent(text.slice(pos, fragment.start).replace(/\+/g, " "));
350
+ pieces.push(decoded);
351
+ decodedUnits += decoded.length;
352
+ }
353
+ pieces.push(text.slice(fragment.start, fragment.end));
354
+ ownedRanges.push({ start: decodedUnits, end: decodedUnits + (fragment.end - fragment.start) });
355
+ decodedUnits += fragment.end - fragment.start;
356
+ pos = fragment.end;
357
+ }
358
+ if (pos < winEnd) {
359
+ const decoded = decodeURIComponent(text.slice(pos, winEnd).replace(/\+/g, " "));
360
+ pieces.push(decoded);
361
+ decodedUnits += decoded.length;
362
+ }
363
+ reassembled = pieces.join("");
364
+ }
365
+ catch (error) {
366
+ if (error instanceof URIError)
367
+ continue; // skip whole candidate, like tryDecodeUrl
368
+ return fail("scanner_failure");
369
+ }
370
+ let scan;
371
+ try {
372
+ scan = scanTextInternal(reassembled, config, MODEL_BOUNDARY_SCAN);
373
+ }
374
+ catch {
375
+ return fail("scanner_failure");
376
+ }
377
+ if (scan.was_truncated)
378
+ return fail("truncated_content");
379
+ for (const finding of scan.findings) {
380
+ if (finding.unicode_detected !== undefined) {
381
+ return fail("unicode_evasion");
382
+ }
383
+ const start = finding.match_start;
384
+ const end = finding.match_end;
385
+ const matched = finding.match_text;
386
+ if (typeof start !== "number" || typeof end !== "number" || typeof matched !== "string" ||
387
+ !Number.isInteger(start) || !Number.isInteger(end) ||
388
+ start < 0 || start >= end || end > reassembled.length ||
389
+ reassembled.slice(start, end) !== matched) {
390
+ return fail("invalid_finding_span");
391
+ }
392
+ // Token interior in the changed representation: exempt before overlap.
393
+ if (containedInAnySpan({ start, end }, ownedRanges))
394
+ continue;
395
+ // Everything else, including matches crossing a retained fragment,
396
+ // is decoded sensitive content.
397
+ return fail("encoded_content");
398
+ }
399
+ }
400
+ return null;
401
+ }
402
+ /**
403
+ * The model-boundary scan seam. The RAW DIRECT scanner runs over the FULL
404
+ * string — including validated token spans — so findings that CROSS a token
405
+ * boundary keep their full-text offsets. The URL-context hazard re-examines
406
+ * the decoder's percent-run windows that cross validated tokens, retaining
407
+ * token fragments verbatim while decoding the surrounding pieces. Decoding
408
+ * then runs over each separate non-token segment: an issued token's epoch
409
+ * hex is never decoded as user-encoded content, and no encoding candidate
410
+ * is ever formed across a token gap (token delimiters break every candidate
411
+ * run anyway, so no genuine user-side candidate is lost by splitting). With
412
+ * no owned tokens this is exactly the historical whole-text scan-then-decode
413
+ * behavior. `tokenSpans` must come from scanOwnedTokenSpans (ascending,
414
+ * disjoint) and must already be strictly validated BEFORE this scan runs.
415
+ * Input scan and output verification rescan share this seam.
416
+ */
417
+ function scanForModelBoundary(text, config, tokenSpans) {
418
+ const direct = rawScan(text, config);
419
+ if (!direct.ok)
420
+ return direct;
421
+ // Full-text truncation is checked on the whole string, independent of any
422
+ // per-segment accounting.
423
+ if (direct.original.was_truncated)
424
+ return fail("truncated_content");
425
+ const urlHazard = urlContextHazard(text, config, tokenSpans);
426
+ if (urlHazard !== null)
427
+ return urlHazard;
428
+ let cursor = 0;
429
+ for (const span of tokenSpans) {
430
+ if (span.start > cursor) {
431
+ const hazard = segmentDecodingHazard(text.slice(cursor, span.start), config);
432
+ if (hazard !== null)
433
+ return hazard;
434
+ }
435
+ cursor = span.end;
436
+ }
437
+ if (cursor < text.length) {
438
+ const hazard = segmentDecodingHazard(text.slice(cursor), config);
439
+ if (hazard !== null)
440
+ return hazard;
441
+ }
442
+ return direct;
443
+ }
444
+ function validateFindingSpans(text, findings) {
445
+ const spans = [];
446
+ for (const finding of findings) {
447
+ if (finding.unicode_detected !== undefined) {
448
+ return fail("unicode_evasion");
449
+ }
450
+ const start = finding.match_start;
451
+ const end = finding.match_end;
452
+ const matched = finding.match_text;
453
+ if (typeof start !== "number" || typeof end !== "number" || typeof matched !== "string" ||
454
+ !Number.isInteger(start) || !Number.isInteger(end) ||
455
+ start < 0 || start >= end || end > text.length ||
456
+ text.slice(start, end) !== matched) {
457
+ return fail("invalid_finding_span");
458
+ }
459
+ spans.push({ start, end, value: matched, type: finding.type, severity: finding.severity });
460
+ }
461
+ spans.sort((a, b) => a.start - b.start || a.end - b.end);
462
+ const deduped = [];
463
+ for (const span of spans) {
464
+ const previous = deduped[deduped.length - 1];
465
+ if (previous && previous.start === span.start && previous.end === span.end) {
466
+ // Identical span from different rules: keep the higher-severity label.
467
+ if (SEVERITY_RANK[span.severity] > SEVERITY_RANK[previous.severity]) {
468
+ previous.type = span.type;
469
+ previous.severity = span.severity;
470
+ }
471
+ continue;
472
+ }
473
+ deduped.push(span);
474
+ }
475
+ return { ok: true, spans: deduped };
476
+ }
477
+ /** Every occurrence of `original` must sit inside a validated token span. */
478
+ function absenceHolds(text, original, tokenSpans) {
479
+ let from = 0;
480
+ for (;;) {
481
+ const at = text.indexOf(original, from);
482
+ if (at === -1)
483
+ return true;
484
+ if (!containedInAnySpan({ start: at, end: at + original.length }, tokenSpans))
485
+ return false;
486
+ from = at + 1;
487
+ }
488
+ }
489
+ // ─── Protect pipeline (per string, inside a transaction) ─────────────────────
490
+ /**
491
+ * Protects one string inside a transaction. `chargedUnits` is the UTF-16-unit
492
+ * amount already charged against limits.maxUnitsPerOperation for this
493
+ * operation INCLUDING this input string (text.length for the text entry
494
+ * point, the walk's aggregate budget for JSON strings/keys), so the combined
495
+ * input+output charge is enforced exactly once and before materialization.
496
+ */
497
+ function protectStringTx(tx, config, limits, text, chargedUnits, preserveUnknownMarkers = false) {
498
+ // Per-string scanner bound: the scanner truncates beyond max_chars, which
499
+ // this core must never accept, so reject before scanning.
500
+ if (text.length > config.settings.max_chars)
501
+ return fail("truncated_content");
502
+ // Registered tokens are identified before scanning. Strict tool-facing
503
+ // callers reject unknown/malformed markers; model-facing callers keep them
504
+ // literal and scan their contents as ordinary text without exempting them.
505
+ const owned = scanOwnedTokenSpans(text, (token) => tx.live?.reverse.get(token) !== undefined || tx.staged?.reverse.get(token) !== undefined, preserveUnknownMarkers);
506
+ if (!owned.ok)
507
+ return owned;
508
+ // Raw direct scan over the FULL string (cross-boundary findings keep
509
+ // full-text offsets); decoding runs only over each separate non-token
510
+ // segment, so issued-token epochs are never decoded as user content,
511
+ // while URL-context windows crossing tokens are checked with the token
512
+ // fragments retained verbatim (see scanForModelBoundary).
513
+ const scanned = scanForModelBoundary(text, config, owned.spans);
514
+ if (!scanned.ok)
515
+ return scanned;
516
+ const collected = validateFindingSpans(text, scanned.original.findings);
517
+ if (!collected.ok)
518
+ return collected;
519
+ // P1 (2026-10-06b): parse uncertainty degrades to best-effort masking.
520
+ // (1) Findings wholly inside a validated owned token are that token's own
521
+ // interior: already pseudonymized, exempt (unchanged).
522
+ // (2) A finding touching a preserved (unregistered) marker extends to the
523
+ // WHOLE marker span — the marker is replaced as one unit, never nested
524
+ // (a prefix is not proof of trust; payloads are scanned as text).
525
+ // (3) Remaining overlaps merge to their union: containment keeps the outer
526
+ // span, identical spans deduplicate, transitive chains merge through
527
+ // sort + iteration. Every actionable finding is fully covered instead
528
+ // of failing the request.
529
+ // (4) A merged span that still crosses a validated owned token cannot be
530
+ // masked without corrupting restoration: safe refusal (token_overlap).
531
+ const candidates = [];
532
+ for (const span of collected.spans) {
533
+ if (containedInAnySpan(span, owned.spans))
534
+ continue;
535
+ candidates.push(span);
536
+ }
537
+ const extended = [];
538
+ for (const span of candidates) {
539
+ let bounds = span;
540
+ for (const marker of owned.preserved) {
541
+ if (spansOverlap(span, marker)) {
542
+ bounds = {
543
+ start: Math.min(bounds.start, marker.start),
544
+ end: Math.max(bounds.end, marker.end),
545
+ value: text.slice(Math.min(span.start, marker.start), Math.max(span.end, marker.end)),
546
+ type: span.type,
547
+ severity: span.severity,
548
+ };
549
+ }
550
+ }
551
+ extended.push(bounds);
552
+ }
553
+ extended.sort((a, b) => a.start - b.start || a.end - b.end);
554
+ const actionable = [];
555
+ for (const bounds of extended) {
556
+ const last = actionable[actionable.length - 1];
557
+ if (last !== undefined && bounds.start < last.end) {
558
+ // R-round (F1.1): every overlap competes on severity, including spans
559
+ // fully contained in the union — a LOW span wrapping an earlier HIGH
560
+ // span must not keep the LOW category.
561
+ const outranks = SEVERITY_RANK[bounds.severity] > SEVERITY_RANK[last.severity];
562
+ if (bounds.end > last.end) {
563
+ // Union merge carries the higher-severity category label forward.
564
+ actionable[actionable.length - 1] = {
565
+ start: last.start,
566
+ end: bounds.end,
567
+ value: text.slice(last.start, bounds.end),
568
+ type: outranks ? bounds.type : last.type,
569
+ severity: outranks ? bounds.severity : last.severity,
570
+ };
571
+ }
572
+ else if (outranks) {
573
+ actionable[actionable.length - 1] = {
574
+ ...last,
575
+ type: bounds.type,
576
+ severity: bounds.severity,
577
+ };
578
+ }
579
+ continue;
580
+ }
581
+ actionable.push({
582
+ start: bounds.start,
583
+ end: bounds.end,
584
+ value: text.slice(bounds.start, bounds.end),
585
+ type: bounds.type,
586
+ severity: bounds.severity,
587
+ });
588
+ }
589
+ for (const span of actionable) {
590
+ if (owned.spans.some((tokenSpan) => spansOverlap(span, tokenSpan))) {
591
+ return fail("token_overlap");
592
+ }
593
+ }
594
+ for (const finding of candidates)
595
+ tx.detectedOriginals.add(finding.value);
596
+ for (const span of actionable)
597
+ tx.detectedOriginals.add(span.value);
598
+ // Stage every mapping first (charging all budgets), then substitute.
599
+ const stagedSpans = [];
600
+ for (const span of actionable) {
601
+ const staged = stageToken(tx, limits, span.value, span.type);
602
+ if (!staged.ok)
603
+ return staged;
604
+ stagedSpans.push({ start: span.start, end: span.end, token: staged.token });
605
+ }
606
+ // Pre-allocation operation guard: the exact prospective substituted
607
+ // output length follows from the validated disjoint spans and the staged
608
+ // fixed tokens (spans never overlap, so each substitution contributes
609
+ // token.length - span length). Refuse BEFORE any substituted string is
610
+ // built or rescanned; a failed transaction below rolls the staged
611
+ // mappings back completely (no committed capacity, counter or epoch).
612
+ let prospectiveUnits = text.length;
613
+ for (const staged of stagedSpans) {
614
+ prospectiveUnits += staged.token.length - (staged.end - staged.start);
615
+ }
616
+ if (chargedUnits + prospectiveUnits > limits.maxUnitsPerOperation) {
617
+ return fail("operation_limit");
618
+ }
619
+ // Assemble the output once from checked pieces instead of repeated
620
+ // large-slice concatenations.
621
+ const pieces = [];
622
+ let cursor = 0;
623
+ for (const staged of stagedSpans) {
624
+ if (cursor < staged.start)
625
+ pieces.push(text.slice(cursor, staged.start));
626
+ pieces.push(staged.token);
627
+ cursor = staged.end;
628
+ }
629
+ if (cursor < text.length)
630
+ pieces.push(text.slice(cursor));
631
+ const substituted = pieces.join("");
632
+ // Rescan the substituted output (defense in depth against engine collapse).
633
+ // Current/staged issued tokens are validated FIRST and never decoded as
634
+ // user content; the shared scanForModelBoundary seam also re-examines
635
+ // URL-context windows the replacement may have pulled a token into.
636
+ // Every remaining finding must live fully inside a validated token.
637
+ // Crossing findings and any residual content are rejected.
638
+ const outTokens = scanOwnedTokenSpans(substituted, (token) => tx.live?.reverse.get(token) !== undefined || tx.staged?.reverse.get(token) !== undefined, preserveUnknownMarkers);
639
+ if (!outTokens.ok)
640
+ return outTokens;
641
+ const rescan = scanForModelBoundary(substituted, config, outTokens.spans);
642
+ if (!rescan.ok)
643
+ return rescan;
644
+ const rescanSpans = validateFindingSpans(substituted, rescan.original.findings);
645
+ if (!rescanSpans.ok)
646
+ return rescanSpans;
647
+ for (const span of rescanSpans.spans) {
648
+ if (!containedInAnySpan(span, outTokens.spans))
649
+ return fail("residual_sensitive_content");
650
+ }
651
+ // Independent absence check of every detected original outside validated
652
+ // owned tokens (covers key/value strings for JSON operations too).
653
+ for (const original of tx.detectedOriginals) {
654
+ if (!absenceHolds(substituted, original, outTokens.spans)) {
655
+ return fail("residual_sensitive_content");
656
+ }
657
+ }
658
+ return { ok: true, text: substituted };
659
+ }
660
+ /** Severity rank for category selection when overlapping findings merge. */
661
+ const SEVERITY_RANK = { HIGH: 3, MEDIUM: 2, LOW: 1 };
662
+ /** Category labels must fit the v2 token grammar (FindingType values do). */
663
+ const CATEGORY_LABEL_SHAPE = /^[A-Z][A-Z_]{0,31}$/;
664
+ function categoryLabelOf(category) {
665
+ return CATEGORY_LABEL_SHAPE.test(category) ? category : undefined;
666
+ }
667
+ /**
668
+ * Random letter-only SGP2 payload: three 4-letter lowercase segments joined
669
+ * by hyphens (≈56.6 bits). No digits (digit-based detector families cannot
670
+ * match), no shell metacharacters, and ≤4-char runs defeat hex-like shapes.
671
+ * Rejection-sampled bytes keep the alphabet uniform; the bounded draw count
672
+ * makes exhaustion return undefined (caller fails statically).
673
+ */
674
+ function mintSgp2Payload() {
675
+ const segments = [];
676
+ for (let segment = 0; segment < PAYLOAD_SEGMENTS; segment += 1) {
677
+ let chunk = "";
678
+ for (let draw = 0; draw < 4 && chunk.length < PAYLOAD_SEGMENT_CHARS; draw += 1) {
679
+ const bytes = randomBytes(PAYLOAD_SEGMENT_CHARS * 2);
680
+ for (let i = 0; i < bytes.length && chunk.length < PAYLOAD_SEGMENT_CHARS; i += 1) {
681
+ const byte = bytes[i];
682
+ if (byte >= PAYLOAD_BYTE_CEILING)
683
+ continue;
684
+ chunk += PAYLOAD_ALPHABET[byte % PAYLOAD_ALPHABET.length];
685
+ }
686
+ }
687
+ if (chunk.length < PAYLOAD_SEGMENT_CHARS)
688
+ return undefined;
689
+ segments.push(chunk);
690
+ }
691
+ return segments.join("-");
692
+ }
693
+ function stageToken(tx, limits, original, category) {
694
+ const existing = tx.staged?.forward.get(original) ?? tx.live?.forward.get(original);
695
+ if (existing !== undefined)
696
+ return { ok: true, token: existing }; // idempotent reuse
697
+ if (tx.staged === undefined) {
698
+ if (tx.live === undefined && tx.registry.sessions.size >= limits.maxSessions) {
699
+ return fail("session_limit");
700
+ }
701
+ // Fresh 128-bit epoch per session creation; existing sessions keep theirs.
702
+ const epoch = tx.live ? tx.live.epoch : randomBytes(EPOCH_HEX_CHARS / 2).toString("hex");
703
+ if (tx.live === undefined && tx.registry.epochs.has(epoch)) {
704
+ return fail("epoch_collision"); // bounded fail-closed, no retry loop
705
+ }
706
+ tx.staged = {
707
+ epoch,
708
+ counter: tx.live?.counter ?? 0,
709
+ forward: new Map(tx.live?.forward),
710
+ reverse: new Map(tx.live?.reverse),
711
+ entries: tx.live?.entries ?? 0,
712
+ units: tx.live?.units ?? 0,
713
+ };
714
+ tx.baseline = { entries: tx.staged.entries, units: tx.staged.units };
715
+ if (tx.live === undefined) {
716
+ // Session identity is charged once, when the session is first committed.
717
+ if (tx.sessionId.length > limits.maxSessionUnits)
718
+ return fail("session_capacity");
719
+ tx.staged.units += tx.sessionId.length;
720
+ }
721
+ }
722
+ const staged = tx.staged;
723
+ const label = categoryLabelOf(category);
724
+ const payload = label === undefined ? undefined : mintSgp2Payload();
725
+ if (label === undefined || payload === undefined)
726
+ return fail("internal_failure");
727
+ // W1 (2026-10-07): new mints are versioned, category-labelled tokens. The
728
+ // legacy epoch/counter namespace remains recognized for restoration of
729
+ // mappings issued before the switch.
730
+ const token = `${PSEUDONYM_TOKEN_PREFIX_V2}${label}-${payload}]`;
731
+ if (staged.reverse.has(token) || tx.live?.reverse.has(token))
732
+ return fail("token_collision");
733
+ const entryUnits = original.length + token.length + ENTRY_OVERHEAD_UNITS;
734
+ if (staged.entries + 1 > limits.maxEntriesPerSession)
735
+ return fail("entry_limit");
736
+ if (staged.units + entryUnits > limits.maxSessionUnits)
737
+ return fail("session_capacity");
738
+ const totalEntriesAfter = tx.registry.totalEntries + (staged.entries - tx.baseline.entries) + 1;
739
+ if (totalEntriesAfter > limits.maxEntriesTotal)
740
+ return fail("aggregate_capacity");
741
+ const totalUnitsAfter = tx.registry.totalUnits + (staged.units - tx.baseline.units) + entryUnits;
742
+ if (totalUnitsAfter > limits.maxUnitsTotal)
743
+ return fail("aggregate_capacity");
744
+ staged.forward.set(original, token);
745
+ staged.reverse.set(token, original);
746
+ staged.entries += 1;
747
+ staged.units += entryUnits;
748
+ return { ok: true, token };
749
+ }
750
+ function commitTransaction(tx) {
751
+ const staged = tx.staged;
752
+ if (staged === undefined)
753
+ return; // safe plaintext never consumes a session
754
+ tx.registry.sessions.set(tx.sessionId, staged);
755
+ tx.registry.epochs.add(staged.epoch);
756
+ tx.registry.totalEntries += staged.entries - tx.baseline.entries;
757
+ tx.registry.totalUnits += staged.units - tx.baseline.units;
758
+ }
759
+ // ─── Restore pipeline (no registry mutation, all-or-nothing) ─────────────────
760
+ /**
761
+ * Replaces registered tokens with their exact original. Strict tool callers
762
+ * reject unknown markers; display callers retain them as literals. `chargedUnits`
763
+ * is the UTF-16-unit amount already charged against limits.maxUnitsPerOperation for
764
+ * this operation INCLUDING the input string itself (text.length for the text
765
+ * entry point, the walk's aggregate budget for JSON strings/keys), so the
766
+ * combined input+output charge is enforced exactly once. Every literal and
767
+ * replacement length is charged BEFORE the piece is appended, and the final
768
+ * join happens only after the whole output is known to fit: an oversized
769
+ * expansion is refused before it is materialized. Token-bearing inputs are
770
+ * charged by their ACTUAL prospective replacement pieces — never by the
771
+ * unchanged input length — so a shrinking restoration (a short original
772
+ * recovered from a long token) is not refused for output it never produces.
773
+ */
774
+ function restoreStringTx(live, limits, text, chargedUnits, preserveUnknownMarkers = false) {
775
+ // Token-free path: output === input, charged combined with the input
776
+ // exactly like the replacement path (budget 10 must refuse "abcdef").
777
+ if (!containsTokenPrefix(text)) {
778
+ if (chargedUnits + text.length > limits.maxUnitsPerOperation) {
779
+ return fail("operation_limit");
780
+ }
781
+ return { ok: true, text };
782
+ }
783
+ const pieces = [];
784
+ let outputUnits = 0;
785
+ const appendPiece = (piece) => {
786
+ if (chargedUnits + outputUnits + piece.length > limits.maxUnitsPerOperation) {
787
+ return fail("operation_limit");
788
+ }
789
+ outputUnits += piece.length;
790
+ pieces.push(piece);
791
+ return null;
792
+ };
793
+ let from = 0;
794
+ let cursor = findTokenPrefix(text, 0);
795
+ while (cursor !== undefined) {
796
+ const { at, prefix } = cursor;
797
+ const token = matchTokenShape(text, at, prefix);
798
+ const original = token === undefined ? undefined : live?.reverse.get(token);
799
+ if (token === undefined || original === undefined) {
800
+ if (!preserveUnknownMarkers)
801
+ return fail(token === undefined ? "malformed_token" : "unknown_token");
802
+ const next = findTokenPrefix(text, at + prefix.length);
803
+ const close = text.indexOf("]", at + prefix.length);
804
+ const end = token !== undefined
805
+ ? at + token.length
806
+ : next !== undefined && (close === -1 || next.at < close)
807
+ ? next.at
808
+ : close === -1
809
+ ? text.length
810
+ : close + 1;
811
+ const literalFailed = appendPiece(text.slice(from, end));
812
+ if (literalFailed !== null)
813
+ return literalFailed;
814
+ from = end;
815
+ cursor = findTokenPrefix(text, from);
816
+ continue;
817
+ }
818
+ const literalFailed = appendPiece(text.slice(from, at));
819
+ if (literalFailed !== null)
820
+ return literalFailed;
821
+ const replacementFailed = appendPiece(original);
822
+ if (replacementFailed !== null)
823
+ return replacementFailed;
824
+ from = at + token.length;
825
+ cursor = findTokenPrefix(text, from);
826
+ }
827
+ const tailFailed = appendPiece(text.slice(from));
828
+ if (tailFailed !== null)
829
+ return tailFailed;
830
+ return { ok: true, text: pieces.join("") };
831
+ }
832
+ const INDEX_KEY = /^(0|[1-9][0-9]*)$/;
833
+ /**
834
+ * Descriptor-based strict-JSON walk. Accepts only strings, finite numbers,
835
+ * booleans, null, dense arrays and plain/null-prototype objects. Rejects
836
+ * proxies (checked with types.isProxy BEFORE any reflective traversal so no
837
+ * trap fires), accessors (without invoking them), symbol keys, cycles, sparse
838
+ * arrays, unexpected array properties, and unsupported types. Builds fresh
839
+ * outputs via Object.defineProperty (safe for `__proto__` keys); never mutates
840
+ * the input. Shared non-cyclic references are cloned again.
841
+ */
842
+ function walkStrictJson(value, depth, path, budget, limits, transform) {
843
+ budget.nodes += 1;
844
+ budget.units += NODE_OVERHEAD_UNITS;
845
+ if (budget.nodes > limits.maxNodes || budget.units > limits.maxUnitsPerOperation) {
846
+ return fail("operation_limit");
847
+ }
848
+ if (depth > limits.maxDepth)
849
+ return fail("operation_limit");
850
+ if (typeof value === "string") {
851
+ budget.units += value.length;
852
+ if (budget.units > limits.maxUnitsPerOperation)
853
+ return fail("operation_limit");
854
+ const transformed = transform(value);
855
+ if (!transformed.ok)
856
+ return transformed;
857
+ budget.units += transformed.text.length;
858
+ if (budget.units > limits.maxUnitsPerOperation)
859
+ return fail("operation_limit");
860
+ return { ok: true, value: transformed.text };
861
+ }
862
+ if (value === null || typeof value === "boolean")
863
+ return { ok: true, value };
864
+ if (typeof value === "number") {
865
+ if (!Number.isFinite(value))
866
+ return fail("unsafe_structure");
867
+ return { ok: true, value };
868
+ }
869
+ if (typeof value !== "object")
870
+ return fail("unsafe_structure"); // undefined/bigint/function/symbol
871
+ if (types.isProxy(value))
872
+ return fail("unsafe_structure");
873
+ if (path.has(value))
874
+ return fail("unsafe_structure"); // cycle
875
+ const keys = Reflect.ownKeys(value);
876
+ for (const key of keys) {
877
+ if (typeof key === "symbol")
878
+ return fail("unsafe_structure");
879
+ const descriptor = Object.getOwnPropertyDescriptor(value, key);
880
+ if (descriptor === undefined || descriptor.get !== undefined || descriptor.set !== undefined) {
881
+ return fail("unsafe_structure");
882
+ }
883
+ }
884
+ if (Array.isArray(value)) {
885
+ if (Object.getPrototypeOf(value) !== Array.prototype)
886
+ return fail("unsafe_structure");
887
+ const length = value.length;
888
+ if (length > limits.maxNodes)
889
+ return fail("operation_limit");
890
+ const indexKeys = keys.filter((key) => key !== "length");
891
+ if (indexKeys.length !== length) {
892
+ return fail("unsafe_structure"); // sparse array and/or unexpected properties
893
+ }
894
+ for (const key of indexKeys) {
895
+ // Canonical own indices only: reject "01", out-of-range, or extra props.
896
+ if (!INDEX_KEY.test(key) || Number(key) >= length)
897
+ return fail("unsafe_structure");
898
+ }
899
+ path.add(value);
900
+ const output = [];
901
+ for (let i = 0; i < length; i++) {
902
+ const item = walkStrictJson(value[i], depth + 1, path, budget, limits, transform);
903
+ if (!item.ok)
904
+ return item;
905
+ output.push(item.value);
906
+ }
907
+ path.delete(value);
908
+ return { ok: true, value: output };
909
+ }
910
+ const prototype = Object.getPrototypeOf(value);
911
+ if (prototype !== Object.prototype && prototype !== null)
912
+ return fail("unsafe_structure");
913
+ path.add(value);
914
+ const output = {};
915
+ const seenKeys = new Set();
916
+ for (const key of keys) {
917
+ budget.units += key.length;
918
+ if (budget.units > limits.maxUnitsPerOperation)
919
+ return fail("operation_limit");
920
+ const transformedKey = transform(key);
921
+ if (!transformedKey.ok)
922
+ return transformedKey;
923
+ budget.units += transformedKey.text.length;
924
+ if (budget.units > limits.maxUnitsPerOperation)
925
+ return fail("operation_limit");
926
+ if (seenKeys.has(transformedKey.text))
927
+ return fail("key_collision");
928
+ seenKeys.add(transformedKey.text);
929
+ const item = walkStrictJson(value[key], depth + 1, path, budget, limits, transform);
930
+ if (!item.ok)
931
+ return item;
932
+ Object.defineProperty(output, transformedKey.text, {
933
+ value: item.value,
934
+ writable: true,
935
+ enumerable: true,
936
+ configurable: true,
937
+ });
938
+ }
939
+ path.delete(value);
940
+ return { ok: true, value: output };
941
+ }
942
+ function buildService(config, limits) {
943
+ const registry = {
944
+ sessions: new Map(),
945
+ epochs: new Set(),
946
+ totalEntries: 0,
947
+ totalUnits: 0,
948
+ };
949
+ const newTransaction = (sessionId) => ({
950
+ registry,
951
+ sessionId,
952
+ live: registry.sessions.get(sessionId),
953
+ staged: undefined,
954
+ baseline: { entries: 0, units: 0 },
955
+ detectedOriginals: new Set(),
956
+ outputStrings: [],
957
+ });
958
+ const isTextSafe = (text) => {
959
+ if (typeof text !== "string" || text.length > limits.maxUnitsPerOperation)
960
+ return false;
961
+ try {
962
+ const result = scanForModelBoundary(text, config, []);
963
+ return result.ok && result.original.safe;
964
+ }
965
+ catch {
966
+ return false;
967
+ }
968
+ };
969
+ /**
970
+ * Structural positions (identifiers, transport metadata) are never masked
971
+ * or renamed, so marker-shaped content is judged, not rejected: registered
972
+ * markers are exempt from interior scanning (their digits are issued, not
973
+ * user content), unregistered well-shaped markers and malformed/bare
974
+ * prefixes scan as ordinary text. Unsafe only on a real finding (the
975
+ * position cannot be protected without breaking the protocol) or a
976
+ * scanning failure — P1, 2026-10-06b.
977
+ */
978
+ const isStructuralIdentifierSafe = (sessionId, text) => {
979
+ if (typeof text !== "string" || text.length > limits.maxUnitsPerOperation)
980
+ return false;
981
+ if (!isValidSessionId(sessionId))
982
+ return false;
983
+ try {
984
+ const session = registry.sessions.get(sessionId);
985
+ const owned = scanOwnedTokenSpans(text, (token) => session?.reverse.get(token) !== undefined, true);
986
+ if (!owned.ok)
987
+ return false;
988
+ const scanned = scanForModelBoundary(text, config, owned.spans);
989
+ return scanned.ok && scanned.original.safe;
990
+ }
991
+ catch {
992
+ return false;
993
+ }
994
+ };
995
+ const protectTextWithPolicy = (sessionId, text, preserveUnknownMarkers) => {
996
+ if (!isValidSessionId(sessionId))
997
+ return fail("invalid_session");
998
+ if (typeof text !== "string")
999
+ return fail("invalid_input");
1000
+ if (text.length > limits.maxUnitsPerOperation)
1001
+ return fail("operation_limit");
1002
+ try {
1003
+ const tx = newTransaction(sessionId);
1004
+ const result = protectStringTx(tx, config, limits, text, text.length, preserveUnknownMarkers);
1005
+ if (!result.ok)
1006
+ return result;
1007
+ if (text.length + result.text.length > limits.maxUnitsPerOperation) {
1008
+ return fail("operation_limit");
1009
+ }
1010
+ commitTransaction(tx);
1011
+ return result;
1012
+ }
1013
+ catch {
1014
+ return fail("internal_failure");
1015
+ }
1016
+ };
1017
+ const protectText = (sessionId, text) => protectTextWithPolicy(sessionId, text, false);
1018
+ const protectTextForModel = (sessionId, text) => protectTextWithPolicy(sessionId, text, true);
1019
+ const restoreTextWithPolicy = (sessionId, text, preserveUnknownMarkers) => {
1020
+ if (!isValidSessionId(sessionId))
1021
+ return fail("invalid_session");
1022
+ if (typeof text !== "string")
1023
+ return fail("invalid_input");
1024
+ if (text.length > limits.maxUnitsPerOperation)
1025
+ return fail("operation_limit");
1026
+ try {
1027
+ return restoreStringTx(registry.sessions.get(sessionId), limits, text, text.length, preserveUnknownMarkers);
1028
+ }
1029
+ catch {
1030
+ return fail("internal_failure");
1031
+ }
1032
+ };
1033
+ const restoreText = (sessionId, text) => restoreTextWithPolicy(sessionId, text, false);
1034
+ const restoreTextForDisplay = (sessionId, text) => restoreTextWithPolicy(sessionId, text, true);
1035
+ const protectJsonWithPolicy = (sessionId, value, preserveUnknownMarkers) => {
1036
+ if (!isValidSessionId(sessionId))
1037
+ return fail("invalid_session");
1038
+ try {
1039
+ const tx = newTransaction(sessionId);
1040
+ const budget = { nodes: 0, units: 0 };
1041
+ const result = walkStrictJson(value, 0, new Set(), budget, limits, (text) => {
1042
+ const protectedString = protectStringTx(tx, config, limits, text, budget.units, preserveUnknownMarkers);
1043
+ if (protectedString.ok)
1044
+ tx.outputStrings.push(protectedString.text);
1045
+ return protectedString;
1046
+ });
1047
+ if (!result.ok)
1048
+ return result;
1049
+ for (const outputString of tx.outputStrings) {
1050
+ const tokenSpans = scanOwnedTokenSpans(outputString, (token) => tx.live?.reverse.get(token) !== undefined || tx.staged?.reverse.get(token) !== undefined, preserveUnknownMarkers);
1051
+ if (!tokenSpans.ok)
1052
+ return tokenSpans;
1053
+ for (const original of tx.detectedOriginals) {
1054
+ if (!absenceHolds(outputString, original, tokenSpans.spans)) {
1055
+ return fail("residual_sensitive_content");
1056
+ }
1057
+ }
1058
+ }
1059
+ commitTransaction(tx);
1060
+ return result;
1061
+ }
1062
+ catch {
1063
+ return fail("internal_failure");
1064
+ }
1065
+ };
1066
+ const protectJson = (sessionId, value) => protectJsonWithPolicy(sessionId, value, false);
1067
+ const protectJsonForModel = (sessionId, value) => protectJsonWithPolicy(sessionId, value, true);
1068
+ const restoreJson = (sessionId, value) => {
1069
+ if (!isValidSessionId(sessionId))
1070
+ return fail("invalid_session");
1071
+ try {
1072
+ const budget = { nodes: 0, units: 0 };
1073
+ return walkStrictJson(value, 0, new Set(), budget, limits, (text) => restoreStringTx(registry.sessions.get(sessionId), limits, text, budget.units));
1074
+ }
1075
+ catch {
1076
+ return fail("internal_failure");
1077
+ }
1078
+ };
1079
+ const seedSession = (sessionId, seed) => {
1080
+ if (!isValidSessionId(sessionId))
1081
+ return fail("invalid_session");
1082
+ try {
1083
+ if (registry.sessions.has(sessionId))
1084
+ return fail("invalid_session");
1085
+ if (typeof seed.epoch !== "string" || !/^[0-9a-f]{32}$/.test(seed.epoch)) {
1086
+ return fail("invalid_input");
1087
+ }
1088
+ if (!Array.isArray(seed.entries) || seed.entries.length === 0)
1089
+ return fail("invalid_input");
1090
+ // R-round (F1.3): cheap caps FIRST — a hostile or hand-edited seed must
1091
+ // be sized before any map allocation (memory-exhaustion guard), and the
1092
+ // per-entry unit guard below bounds the loop itself.
1093
+ if (registry.sessions.size >= limits.maxSessions)
1094
+ return fail("session_limit");
1095
+ if (seed.entries.length > limits.maxEntriesPerSession)
1096
+ return fail("entry_limit");
1097
+ // R2-14: two phases. Phase 1 validates shape/category and accumulates
1098
+ // the unit budget WITHOUT any map allocation or key hashing — a hostile
1099
+ // or hand-edited seed is fully sized before the first Map.set, so an
1100
+ // oversized original cannot make the loop hash megabytes before its
1101
+ // rejection. Only then does phase 2 build the forward/reverse maps.
1102
+ let units = sessionId.length;
1103
+ for (const entry of seed.entries) {
1104
+ const token = entry?.token;
1105
+ const original = entry?.original;
1106
+ if (typeof token !== "string" || typeof original !== "string" || original.length === 0) {
1107
+ return fail("invalid_input");
1108
+ }
1109
+ // Exact reserved-shape match, either version (matchTokenShape binds
1110
+ // to the version implied by the token's own prefix).
1111
+ const prefix = PSEUDONYM_TOKEN_PREFIXES.find((candidate) => token.startsWith(candidate));
1112
+ if (prefix === undefined)
1113
+ return fail("malformed_token");
1114
+ if (matchTokenShape(token, 0, prefix) !== token)
1115
+ return fail("malformed_token");
1116
+ if (prefix === PSEUDONYM_TOKEN_PREFIX_V2) {
1117
+ const category = token.slice(PSEUDONYM_TOKEN_PREFIX_V2.length, token.indexOf("-", PSEUDONYM_TOKEN_PREFIX_V2.length));
1118
+ if (!KNOWN_SGP2_CATEGORIES.has(category))
1119
+ return fail("malformed_token");
1120
+ }
1121
+ units += original.length + token.length + ENTRY_OVERHEAD_UNITS;
1122
+ if (units > limits.maxSessionUnits)
1123
+ return fail("session_capacity");
1124
+ }
1125
+ const forward = new Map();
1126
+ const reverse = new Map();
1127
+ for (const entry of seed.entries) {
1128
+ const { token, original } = entry;
1129
+ if (reverse.has(token))
1130
+ return fail("token_collision");
1131
+ if (forward.has(original))
1132
+ return fail("key_collision");
1133
+ forward.set(original, token);
1134
+ reverse.set(token, original);
1135
+ }
1136
+ if (registry.epochs.has(seed.epoch))
1137
+ return fail("epoch_collision");
1138
+ if (registry.sessions.size >= limits.maxSessions)
1139
+ return fail("session_limit");
1140
+ if (seed.entries.length > limits.maxEntriesPerSession)
1141
+ return fail("entry_limit");
1142
+ if (units > limits.maxSessionUnits)
1143
+ return fail("session_capacity");
1144
+ if (registry.totalEntries + seed.entries.length > limits.maxEntriesTotal) {
1145
+ return fail("aggregate_capacity");
1146
+ }
1147
+ if (registry.totalUnits + units > limits.maxUnitsTotal)
1148
+ return fail("aggregate_capacity");
1149
+ registry.sessions.set(sessionId, {
1150
+ epoch: seed.epoch,
1151
+ counter: 0,
1152
+ forward,
1153
+ reverse,
1154
+ entries: seed.entries.length,
1155
+ units,
1156
+ });
1157
+ registry.epochs.add(seed.epoch);
1158
+ registry.totalEntries += seed.entries.length;
1159
+ registry.totalUnits += units;
1160
+ return { ok: true };
1161
+ }
1162
+ catch {
1163
+ return fail("internal_failure");
1164
+ }
1165
+ };
1166
+ const hasSession = (sessionId) => isValidSessionId(sessionId) && registry.sessions.has(sessionId);
1167
+ const exportSession = (sessionId) => {
1168
+ if (!isValidSessionId(sessionId))
1169
+ return null;
1170
+ const session = registry.sessions.get(sessionId);
1171
+ if (session === undefined)
1172
+ return null;
1173
+ const entries = Array.from(session.forward, ([original, token]) => ({ token, original }));
1174
+ return { epoch: session.epoch, entries };
1175
+ };
1176
+ const clearSession = (sessionId) => {
1177
+ if (!isValidSessionId(sessionId))
1178
+ return; // idempotent, never throws
1179
+ const session = registry.sessions.get(sessionId);
1180
+ if (session === undefined)
1181
+ return;
1182
+ registry.sessions.delete(sessionId);
1183
+ registry.epochs.delete(session.epoch);
1184
+ registry.totalEntries -= session.entries;
1185
+ registry.totalUnits -= session.units;
1186
+ };
1187
+ return {
1188
+ isTextSafe,
1189
+ isStructuralIdentifierSafe,
1190
+ seedSession,
1191
+ protectText,
1192
+ protectTextForModel,
1193
+ restoreText,
1194
+ restoreTextForDisplay,
1195
+ protectJson,
1196
+ protectJsonForModel,
1197
+ restoreJson,
1198
+ clearSession,
1199
+ hasSession,
1200
+ exportSession,
1201
+ };
1202
+ }
1203
+ // ─── Factory ─────────────────────────────────────────────────────────────────
1204
+ /**
1205
+ * Creates a synchronous, in-memory pseudonymizer service. The factory itself
1206
+ * only fails on statically invalid arguments (malformed config or limits) with
1207
+ * the single static reason "STATIC_CODE"; per-operation failures use their own
1208
+ * static reasons. The result spreads the service methods, so no `this` binding
1209
+ * is required.
1210
+ */
1211
+ export function createPseudonymizer(config, limits) {
1212
+ if (!isValidConfigShape(config))
1213
+ return { ok: false, reason: "STATIC_CODE" };
1214
+ // Snapshot the caller config so the trusted-caller boundary stays durable
1215
+ // after construction; re-validate so a snapshot that could not carry the
1216
+ // validated fields fails statically instead of dropping protection.
1217
+ const snapshot = snapshotConfig(config);
1218
+ if (snapshot === null || !isValidConfigShape(snapshot)) {
1219
+ return { ok: false, reason: "STATIC_CODE" };
1220
+ }
1221
+ const resolved = resolveLimits(limits);
1222
+ if (resolved === null)
1223
+ return { ok: false, reason: "STATIC_CODE" };
1224
+ try {
1225
+ return { ok: true, ...buildService(snapshot, resolved) };
1226
+ }
1227
+ catch {
1228
+ return { ok: false, reason: "STATIC_CODE" };
1229
+ }
1230
+ }