flare-redact 1.4.0 → 1.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (53) hide show
  1. package/CHANGELOG.md +114 -0
  2. package/README.md +115 -1
  3. package/SECURITY.md +36 -0
  4. package/bin/flare-gateway.mjs +6 -0
  5. package/dist/cli.d.ts.map +1 -1
  6. package/dist/cli.js +12 -0
  7. package/dist/cli.js.map +1 -1
  8. package/dist/detectors.d.ts +17 -0
  9. package/dist/detectors.d.ts.map +1 -1
  10. package/dist/detectors.js.map +1 -1
  11. package/dist/engine.d.ts +5 -0
  12. package/dist/engine.d.ts.map +1 -1
  13. package/dist/engine.js +50 -7
  14. package/dist/engine.js.map +1 -1
  15. package/dist/gateway/body.d.ts +90 -0
  16. package/dist/gateway/body.d.ts.map +1 -0
  17. package/dist/gateway/body.js +185 -0
  18. package/dist/gateway/body.js.map +1 -0
  19. package/dist/gateway/cli.d.ts +26 -0
  20. package/dist/gateway/cli.d.ts.map +1 -0
  21. package/dist/gateway/cli.js +230 -0
  22. package/dist/gateway/cli.js.map +1 -0
  23. package/dist/gateway/config.d.ts +110 -0
  24. package/dist/gateway/config.d.ts.map +1 -0
  25. package/dist/gateway/config.js +212 -0
  26. package/dist/gateway/config.js.map +1 -0
  27. package/dist/gateway/index.d.ts +21 -0
  28. package/dist/gateway/index.d.ts.map +1 -0
  29. package/dist/gateway/index.js +21 -0
  30. package/dist/gateway/index.js.map +1 -0
  31. package/dist/gateway/runtime.d.ts +80 -0
  32. package/dist/gateway/runtime.d.ts.map +1 -0
  33. package/dist/gateway/runtime.js +0 -0
  34. package/dist/gateway/runtime.js.map +1 -0
  35. package/dist/gateway/server.d.ts +37 -0
  36. package/dist/gateway/server.d.ts.map +1 -0
  37. package/dist/gateway/server.js +560 -0
  38. package/dist/gateway/server.js.map +1 -0
  39. package/dist/pack.d.ts +88 -0
  40. package/dist/pack.d.ts.map +1 -0
  41. package/dist/pack.js +350 -0
  42. package/dist/pack.js.map +1 -0
  43. package/docker/Dockerfile +47 -0
  44. package/docker/README.md +219 -0
  45. package/docker/docker-compose.yml +55 -0
  46. package/docker/flare-gateway.example.json +48 -0
  47. package/package.json +28 -5
  48. package/spec/SPEC.md +469 -0
  49. package/spec/conformance/README.md +60 -0
  50. package/spec/conformance/cases.json +149 -0
  51. package/spec/conformance/expected.json +1683 -0
  52. package/spec/detectors.json +1812 -0
  53. package/spec/detectors.schema.json +196 -0
package/spec/SPEC.md ADDED
@@ -0,0 +1,469 @@
1
+ # FRS-1 — flare-redact portable redaction spec
2
+
3
+ **Status:** stable · **Revision:** FRS-1 · **Reference pack:** [`detectors.json`](./detectors.json) · **Schema:** [`detectors.schema.json`](./detectors.schema.json)
4
+
5
+ FRS-1 defines how a *detector pack* is written and how an engine must execute it,
6
+ in enough detail that four independent implementations — JavaScript/TypeScript,
7
+ Python, Go and Rust — produce **byte-identical output** for the same input,
8
+ options and pack. The [conformance corpus](./conformance/) is the executable form
9
+ of this document; a change that breaks it breaks the spec.
10
+
11
+ The reason for a spec rather than four ports is drift. Detection logic that lives
12
+ in four hand-maintained copies diverges within a release or two, and a redactor
13
+ that behaves differently per language is worse than no redactor, because the team
14
+ stops being able to reason about what leaves the process.
15
+
16
+ ## Contents
17
+
18
+ - [1. Why a restricted regular-expression subset](#1-why-a-restricted-regular-expression-subset)
19
+ - [2. The pattern subset](#2-the-pattern-subset)
20
+ - [3. Detector fields](#3-detector-fields)
21
+ - [4. The scan algorithm](#4-the-scan-algorithm)
22
+ - [5. Overlap resolution](#5-overlap-resolution)
23
+ - [6. Confidence](#6-confidence)
24
+ - [7. Replacement modes](#7-replacement-modes)
25
+ - [8. Keyed transforms](#8-keyed-transforms)
26
+ - [9. Sensitive keys, allowlists and terms](#9-sensitive-keys-allowlists-and-terms)
27
+ - [10. Structured data](#10-structured-data)
28
+ - [11. Vaults and reversible redaction](#11-vaults-and-reversible-redaction)
29
+ - [12. Limits and failure modes](#12-limits-and-failure-modes)
30
+ - [13. Conformance](#13-conformance)
31
+ - [14. Deliberate deviations from the Node detector set](#14-deliberate-deviations-from-the-node-detector-set)
32
+
33
+ ---
34
+
35
+ ## 1. Why a restricted regular-expression subset
36
+
37
+ The four target engines do not agree on the syntax or the semantics of a "normal"
38
+ regular expression:
39
+
40
+ | Construct | JavaScript | Python `re` | Go `regexp` (RE2) | Rust `regex` |
41
+ |---|---|---|---|---|
42
+ | Lookahead / lookbehind | yes | yes | **no** | **no** |
43
+ | Backreferences | yes | yes | **no** | **no** |
44
+ | `\b` | ASCII | **Unicode** | ASCII | **Unicode** |
45
+ | `\d`, `\w` | ASCII | **Unicode** | ASCII | **Unicode** |
46
+ | `\s` | +Unicode spaces | Unicode | **ASCII, no `\v`** | Unicode |
47
+ | `\p{L}` | with `u` flag | **unsupported** | yes | yes |
48
+ | `(?s:…)` scoped flags | **no** | yes | yes | yes |
49
+ | `$` without multiline | end of input | **also before a final newline** | end of input | end of input |
50
+
51
+ Every one of those rows is a silent behaviour difference — the kind that makes a
52
+ secret redacted on the Node service and passed through on the Python worker. FRS-1
53
+ removes the ambiguity by forbidding each divergent construct and providing an
54
+ explicit, engine-substituted replacement.
55
+
56
+ The subset is also RE2-safe by construction: no backtracking constructs means no
57
+ catastrophic backtracking, so a pack cannot introduce a ReDoS into a host process.
58
+
59
+ ## 2. The pattern subset
60
+
61
+ A pattern **may** use:
62
+
63
+ - literals, and `.` (which never matches a line terminator)
64
+ - character classes `[…]`, `[^…]`, ranges, and the escapes `\t \n \r \f \x0B \xHH \\ \. \* \+ \? \( \) \[ \] \{ \} \| \^ \$ \/ \-`
65
+ - groups `(…)` (capturing) and `(?:…)` (non-capturing)
66
+ - alternation `|`
67
+ - quantifiers `* + ? {n} {n,} {n,m}` and their lazy forms `*? +? ?? {n,m}?`
68
+ - the two substitution tokens below
69
+
70
+ A pattern **must not** use:
71
+
72
+ - any lookaround — `(?=…) (?!…) (?<=…) (?<!…)` — use [`boundary`](#31-boundary) and [`reject`](#32-reject)
73
+ - backreferences `\1`, named groups, conditionals, atomic groups, possessive quantifiers
74
+ - the shorthands `\b \B \d \D \w \W \s \S` — write the class out (`[0-9]`, `[A-Za-z0-9_]`, `[ \t\n\x0B\f\r]`)
75
+ - `\p{…}` / `\P{…}` — use `{{L}}`
76
+ - inline flag groups `(?i)`, `(?s:…)` — use the `flags` field and `{{ANY}}`
77
+ - anchors `^` and `$` inside `pattern` (they are meaningful only in `reject`, `validators.pattern` and `mask.pattern`, where the spec fixes their semantics)
78
+
79
+ ### Substitution tokens
80
+
81
+ Engines textually replace these **before** compiling, so the compiled automaton is
82
+ native and fast:
83
+
84
+ | Token | Meaning | JavaScript | Python | Go | Rust |
85
+ |---|---|---|---|---|---|
86
+ | `{{ANY}}` | any single character, including line terminators | `[\s\S]` | `[\s\S]` | `(?s:.)` | `(?s:.)` |
87
+ | `{{L}}` | any single Unicode letter | `\p{L}` | `[^\W\d_]` | `\p{L}` | `\p{L}` |
88
+
89
+ `{{L}}` must not appear inside a character class — write `(?:{{L}}|[0-9.-])`
90
+ instead of `[{{L}}0-9.-]`. This is what lets the Python engine expand it to the
91
+ `[^\W\d_]` idiom, which is a complete class and cannot be nested.
92
+
93
+ ### Flags
94
+
95
+ `flags` is `""` or `"i"`. Case-insensitive matching is Unicode simple case folding.
96
+ Engines compile with:
97
+
98
+ | | |
99
+ |---|---|
100
+ | JavaScript | `new RegExp(pattern, "gu")` / `"giu"` |
101
+ | Python | `re.compile(pattern)` / `re.IGNORECASE` (never `re.ASCII`) |
102
+ | Go | `regexp.MustCompile(pattern)` / `"(?i)" + pattern` |
103
+ | Rust | `RegexBuilder::new(pattern).case_insensitive(flag)` |
104
+
105
+ ### Anchored sub-patterns
106
+
107
+ Three fields hold patterns with fixed, engine-independent anchoring:
108
+
109
+ | Field | Semantics |
110
+ |---|---|
111
+ | `reject[]` | **prefix match** — the pattern must match starting at offset 0 of the captured value; it need not consume it |
112
+ | `validators[].pattern` | **full match** — the pattern must consume the entire (normalised) value |
113
+ | `mask.pattern` | **full match**, with `$1`…`$9` group references available in `replacement` |
114
+
115
+ Implementations wrap these themselves (`^(?:…)` and `^(?:…)$`, or `re.match` /
116
+ `re.fullmatch`). Because the wrapping is applied by the engine and never by the
117
+ pack author, Python's "`$` also matches before a trailing newline" behaviour is
118
+ avoided: Python engines use `re.match` / `re.fullmatch`, which do not have it.
119
+
120
+ ## 3. Detector fields
121
+
122
+ See [`detectors.schema.json`](./detectors.schema.json) for the machine-readable
123
+ contract. The fields that carry semantics beyond their names:
124
+
125
+ ### 3.1 `boundary`
126
+
127
+ `{"before": <class>, "after": <class>}`. The character immediately *before* the
128
+ captured span must **not** belong to `before`'s class, and the character
129
+ immediately *after* must not belong to `after`'s class. The start and the end of
130
+ the input always satisfy a boundary.
131
+
132
+ | Class | Members |
133
+ |---|---|
134
+ | `word` | `[A-Za-z0-9_]` |
135
+ | `alnum` | `[A-Za-z0-9]` |
136
+ | `digit` | `[0-9]` |
137
+ | `hex` | `[0-9A-Fa-f]` |
138
+ | `base64` | `[A-Za-z0-9+/=]` |
139
+ | `base64url` | `[A-Za-z0-9_+/=-]` |
140
+ | `word_dash` | `[A-Za-z0-9_-]` |
141
+
142
+ Membership is tested on UTF-16 code units in JavaScript, Unicode scalar values
143
+ elsewhere; every class is ASCII-only, so the two agree.
144
+
145
+ `{"before": "word", "after": "word"}` is the portable spelling of `\b…\b` for a
146
+ pattern that starts and ends with a word character.
147
+
148
+ ### 3.2 `reject`
149
+
150
+ Prefix patterns evaluated against the captured value. Any match discards the
151
+ candidate. This replaces negative lookahead inside a pattern: `sk-(?!ant-|or-)…`
152
+ becomes `"pattern": "sk-…"` plus `"reject": ["sk-(?:ant|or)-"]`.
153
+
154
+ ### 3.3 `validators`
155
+
156
+ Named, arity-fixed checks implemented natively by every engine. A candidate
157
+ survives only if **all** validators return true.
158
+
159
+ | Name | Check |
160
+ |---|---|
161
+ | `normalized_match` | remove every character matching `strip`, then full-match `pattern` |
162
+ | `luhn` | digits only; length within `[minDigits, maxDigits]` (defaults 2 / unbounded); Luhn sum ≡ 0 (mod 10) |
163
+ | `entropy` | Shannon entropy over Unicode code points ≥ `min` bits/symbol |
164
+ | `phone` | 8–15 digits; a value without a leading `+` needs ≥ 9 digits and must not end in a separated `19xx`/`20xx` year |
165
+ | `iban` | ISO 13616 mod-97 |
166
+ | `tckn` | Türkiye T.C. Kimlik No, two check digits |
167
+ | `cpf` | Brazil, two mod-11 check digits, rejects repeated digits |
168
+ | `dni` | Spain DNI/NIE control letter (mod 23) |
169
+ | `bsn` | Netherlands 11-test |
170
+ | `pesel` | Poland weighted mod-10 |
171
+ | `de_tax_id` | Germany ISO 7064 MOD 11,10 |
172
+ | `codice_fiscale` | Italy odd/even table checksum |
173
+ | `fr_nir` | France INSEE key = 97 − (n mod 97), Corsica 2A→19 / 2B→18 |
174
+ | `aadhaar` | India Verhoeff, first digit 2–9 |
175
+ | `tfn` | Australia weighted sum ≡ 0 (mod 11) |
176
+ | `cn_resident_id` | China ISO 7064 MOD 11-2 |
177
+ | `jp_my_number` | Japan weighted mod-11 |
178
+ | `us_ssn` | never-issued ranges (area 0, 666, ≥ 900; group 0; serial 0) |
179
+ | `aba` | US routing 3-7-1 mod-10 |
180
+ | `nhs` | UK weighted mod-11, rejects repeated digits |
181
+ | `vin` | transliterated weighted mod-11, check character at position 9 |
182
+
183
+ Adding a validator name is a spec revision, not a pack change: an engine that
184
+ does not know a name **must fail loudly** when loading the pack rather than
185
+ silently skipping the check. Failing open is how a redactor leaks.
186
+
187
+ ### 3.4 `prefilter`
188
+
189
+ Case-insensitive literals. If none occurs in the subject, the detector is skipped
190
+ without running its pattern. A prefilter is only correct when **every** string the
191
+ pattern can match contains at least one of the literals; the conformance corpus
192
+ exists partly to catch a prefilter that is not.
193
+
194
+ ### 3.5 `context`
195
+
196
+ `positive` / `negative` are searched (substring semantics, always case-insensitive)
197
+ in the window of `window` characters — default 80 — on each side of the captured
198
+ span. See [§6](#6-confidence).
199
+
200
+ ## 4. The scan algorithm
201
+
202
+ For a subject string *S* and a resolved, ordered detector list *D*:
203
+
204
+ 1. **Zero-width normalisation.** If *S* contains any of `U+200B U+200C U+200D
205
+ U+2060 U+FEFF`, build *S′* with those removed plus an index map back to *S*.
206
+ Otherwise *S′* = *S*. All matching happens on *S′*; every offset reported is
207
+ translated back to *S*, and the reported value is the slice of *S* — so
208
+ `p a s​s w o r d` is caught and the original characters are what get
209
+ replaced.
210
+ 2. For each detector *d* in *D*, **in pack order**:
211
+ 1. If `prefilter` is set and no literal occurs in *S′* (case-insensitive), skip *d*.
212
+ 2. Scan *S′* left to right for successive non-overlapping matches of `pattern`.
213
+ 3. For each match:
214
+ 1. Take the span of capture group `capture` (0 = whole match). If the group
215
+ did not participate, discard the candidate.
216
+ 2. Apply `boundary` against the neighbours of that span in *S′*.
217
+ 3. Apply `reject` against the captured value.
218
+ 4. Apply `validators` against the captured value.
219
+ 5. Compute confidence ([§6](#6-confidence)); discard if `< minConfidence`.
220
+ 6. Translate the span to *S* and emit a candidate.
221
+ 7. **A discarded candidate does not rewind the cursor**: scanning resumes at
222
+ the end of the match that produced it. This is what makes the traversal
223
+ order deterministic and identical in a backtracking engine and in RE2.
224
+ 3. Append candidates from the semantic provider, if the host supplied one.
225
+ 4. Resolve overlaps ([§5](#5-overlap-resolution)).
226
+ 5. Return the surviving candidates sorted by `start`, then `end`.
227
+
228
+ `redact` walks the result once, copying the text between candidates and emitting
229
+ the replacement for each — one pass, no nested replacement, and a replacement can
230
+ never itself be re-scanned.
231
+
232
+ ## 5. Overlap resolution
233
+
234
+ Candidates from different detectors routinely cover the same or overlapping text
235
+ (`sk-or-v1-…` is both an OpenRouter key and a high-entropy string; an IBAN is also
236
+ a run of alphanumerics). FRS-1 picks the **maximum-weight set of non-overlapping
237
+ candidates** — weighted interval scheduling — rather than "first detector wins",
238
+ because first-wins depends on pack ordering and produces different masking for the
239
+ same secret depending on what else is nearby.
240
+
241
+ ```
242
+ weight(c) = riskWeight(c.risk) + 10 × c.priority + c.confidence + (c.end − c.start) / 1e6
243
+
244
+ riskWeight: critical = 1e9, high = 1e6, medium = 1e3, low = 1
245
+ ```
246
+
247
+ The algorithm:
248
+
249
+ 1. Sort candidates by `end`, then `start`, **stably** — insertion order (pack
250
+ order, then left-to-right match order) breaks remaining ties.
251
+ 2. For each *i*, binary-search `p[i]` = the greatest *j* < *i* with `end[j] ≤ start[i]`.
252
+ 3. `best[i] = max(best[i−1], weight(i) + best[p[i]+1])`.
253
+ 4. Walk back from the end, taking *i* when `weight(i) + best[p[i]+1] > best[i−1]`.
254
+
255
+ Every step is integer/IEEE-754 double arithmetic with a fixed evaluation order, so
256
+ all four engines compute the same sums. Sort stability is guaranteed by the
257
+ language in all four cases (`Array.prototype.sort`, `sorted`, `sort.SliceStable`,
258
+ `slice::sort_by`).
259
+
260
+ A single candidate short-circuits: with fewer than two candidates the list is
261
+ returned unchanged.
262
+
263
+ ## 6. Confidence
264
+
265
+ ```
266
+ score = detector.confidence
267
+ if context.positive matches the window: score += 0.06
268
+ if context.negative matches the window: score −= 0.25
269
+ if refineConfidence and detector.refine: score += (P(secret) − 0.5) × 0.4
270
+ score = clamp(score, 0, 1)
271
+ ```
272
+
273
+ `P(secret)` comes from the logistic model carried in the pack's `confidenceModel`.
274
+ Its 14 features are computed over the captured value plus a ±64-character window:
275
+
276
+ `log2Len`, `entropy`, `fracLower`, `fracUpper`, `fracDigit`, `fracSymbol`,
277
+ `fracHex`, `vowelFrac`, `classTransitionRate`, `hasMixedClasses`, `maxRunFrac`,
278
+ `structuredHexId`, `ctxSecret`, `ctxBenign`.
279
+
280
+ Feature extraction is defined over UTF-16 code units in JavaScript and over
281
+ Unicode scalar values elsewhere; the features are ASCII-classifying, and `entropy`
282
+ is defined over code points in every engine, so the vectors agree for any input.
283
+ The model only ever moves a score that a detector opted into with `refine: true`,
284
+ and only when the host passes `refineConfidence`. Checksum-validated detectors
285
+ never opt in — they are already certain.
286
+
287
+ ## 7. Replacement modes
288
+
289
+ | Mode | Replacement |
290
+ |---|---|
291
+ | `mask` (default) | the detector's `mask` strategy |
292
+ | `label` | `[REDACTED:<detector id>]` |
293
+ | `hash` | `<detector id>_<HMAC-SHA256(secret, value) truncated to 16 bytes, lowercase hex>` |
294
+ | `pseudonym` | keyed, shape-preserving character substitution ([§8](#8-keyed-transforms)) |
295
+ | `surrogate` | a type-consistent synthetic value ([§8](#8-keyed-transforms)) |
296
+
297
+ Mask strategies:
298
+
299
+ | `type` | Result |
300
+ |---|---|
301
+ | `fixed` | `text` |
302
+ | `keepPrefix` | `value.length ≤ n` → `***`, else first `n` characters + `***` |
303
+ | `keepLast` | digits only; last `n` digits, prefixed by `**** ` repeated `ceil((digits − n) / 4)` times, trimmed |
304
+ | `keepThroughSeparator` | everything up to and including the `count`-th `separator`, + `***` |
305
+ | `replace` | full-match `pattern` → `replacement` with `$1`…`$9`; if the value does not fully match, the value is returned unchanged |
306
+
307
+ A host-supplied `mask` string or function overrides the strategy for every
308
+ detector, and takes precedence over `mode`.
309
+
310
+ ## 8. Keyed transforms
311
+
312
+ All keyed output derives from HMAC-SHA256 with the host's `transformSecret`. An
313
+ empty secret is an **error**, not a silent fallback to unkeyed output.
314
+
315
+ ```
316
+ deriveBytes(secret, context, n):
317
+ out = b""
318
+ counter = 0
319
+ while len(out) < n:
320
+ out += HMAC-SHA256(secret, context + "\x00" + str(counter))
321
+ counter += 1
322
+ return out[:n]
323
+ ```
324
+
325
+ - **`hash`** — `HMAC-SHA256(secret, value)[:16]` as lowercase hex, prefixed with
326
+ the detector id and `_`.
327
+ - **`pseudonym`** — `deriveBytes(secret, "pseudonym:" + value, len(value))`; each
328
+ character is replaced by `alphabet[byte % len(alphabet)]` where the alphabet is
329
+ `a–z`, `A–Z` or `0–9` matching the original character's class. Any other
330
+ character is passed through, so shape (length, punctuation, separators) survives.
331
+ This is **not** format-preserving encryption and is **not** reversible; it is a
332
+ deterministic pseudonym.
333
+ - **`surrogate`** — type-consistent synthetic data, per detector id:
334
+ `email` → `user_<HMAC[:6] hex>@example.invalid`; `credit_card` → digit
335
+ substitution with a recomputed Luhn check digit; `phone` → digit substitution;
336
+ `person_name` → a name from the fixed given/family lists; `street_address` →
337
+ `<number> <street> Street`; anything else falls back to `pseudonym`.
338
+
339
+ Indexing is by **Unicode scalar value** in Python, Go and Rust, and by UTF-16 code
340
+ unit in JavaScript. Because the alphabets are ASCII and non-ASCII characters are
341
+ passed through unchanged, the outputs agree for all inputs. The `deriveBytes`
342
+ length is the length in the engine's own unit; a pack that needs cross-language
343
+ identical pseudonyms for astral-plane input should mask those detectors instead.
344
+
345
+ ## 9. Sensitive keys, allowlists and terms
346
+
347
+ - **`redactKeys`** — when a structured input has a string value under a key that is
348
+ sensitive by name, the value is replaced without pattern matching. The default
349
+ key test is `SENSITIVE_KEY_RE` (`password`, `secret`, `token`, `api_key`,
350
+ `authorization`, `cookie`, `session_id`, `credit_card`, `cvv`, `ssn`, …) **or**
351
+ membership in the multilingual keyword set. The finding is reported as detector
352
+ `sensitive_key`, risk `critical`, confidence `0.98`.
353
+ - **`allow`** — exact values (or a host regular expression) that are never
354
+ redacted. Tested against the raw slice *and* against the zero-width-normalised
355
+ slice, so `​`-padded look-alikes cannot slip past an allowlist entry.
356
+ - **`terms`** — host-supplied literals, matched longest-first with Unicode letter/
357
+ digit boundaries, reported as detector `custom_term`. Terms are prepended to the
358
+ detector list, so they take part in overlap resolution like any other candidate.
359
+
360
+ ## 10. Structured data
361
+
362
+ Redacting a structure is defined as redacting every string reachable from it:
363
+
364
+ - object/dict values, array/list elements, map keys and values, set members
365
+ - error/exception messages
366
+ - the string form of URLs and query strings
367
+
368
+ Cycles are visited once. Non-string leaves (numbers, booleans, null, binary
369
+ buffers, dates) are returned as-is; a redactor that stringifies numbers changes
370
+ meaning, and a redactor that walks binary blobs wastes the caller's CPU.
371
+
372
+ Finding paths use the host language's natural notation: `user.contact.email`,
373
+ `items[0].token`, `headers.<map-key:0>`.
374
+
375
+ **Traversal order is observable**, because it fixes the order of findings and the
376
+ order in which a vault mints placeholders. Sequences are visited in index order.
377
+ Mappings are visited in insertion order where the language preserves it
378
+ (JavaScript objects, Python dicts, `serde_json::Map` with `preserve_order`) and
379
+ in ascending key order where it does not (Go maps). The conformance corpus only
380
+ contains mappings whose insertion order already equals their sorted key order, so
381
+ the two rules cannot disagree on a conforming input; outside the corpus, treat
382
+ mapping traversal order as unspecified and do not depend on it.
383
+
384
+ ## 11. Vaults and reversible redaction
385
+
386
+ A vault mints a stable placeholder per distinct original value and remembers the
387
+ mapping, so the same secret gets the same placeholder everywhere in a session and
388
+ `restore` puts the originals back — the round trip that makes "send a prompt to a
389
+ model without sending the data" work.
390
+
391
+ - Default placeholders are **opaque**: `[FR_<DETECTOR_ID>_<12 random bytes, hex>]`.
392
+ They carry no counter, so an observer cannot tell how many distinct values a
393
+ session has seen or which appeared first.
394
+ - `readable` placeholders (`[EMAIL_1]`) are predictable and are for local
395
+ debugging only.
396
+ - Restoration replaces the longest placeholders first, so a placeholder that is a
397
+ prefix of another cannot clobber it.
398
+ - A generator that mints a duplicate placeholder for two different values is an
399
+ error; silently merging them would restore the wrong secret.
400
+
401
+ Streaming restoration holds back the longest proper prefix of any placeholder that
402
+ the emitted tail could still be starting, so a placeholder split across two chunks
403
+ is still restored exactly once.
404
+
405
+ ## 12. Limits and failure modes
406
+
407
+ | Limit | Default | On breach |
408
+ |---|---|---|
409
+ | `maxInputLength` | 16 MiB per scanned string | error |
410
+ | `maxFindings` | 50 000 per scanned string | error |
411
+
412
+ Both fail **closed** — an error, never a truncated or partially-redacted result.
413
+ A caller who receives a partially-redacted string has no way to know it, which is
414
+ exactly the failure mode a redactor must not have.
415
+
416
+ Engines must also reject, at pack-load time: an unknown `spec` revision, an
417
+ unknown validator or mask `type`, a pattern containing a forbidden construct, a
418
+ duplicate detector id, and a pattern that can match the empty string.
419
+
420
+ ## 13. Conformance
421
+
422
+ [`conformance/cases.json`](./conformance/cases.json) holds inputs and options;
423
+ [`conformance/expected.json`](./conformance/expected.json) holds the required
424
+ output for each. Every implementation ships a test that runs the whole corpus:
425
+
426
+ | Implementation | Command |
427
+ |---|---|
428
+ | TypeScript / Node | `npm test` (`test/conformance.test.mjs`) |
429
+ | Python | `python -m unittest discover sdk/python/tests` |
430
+ | Go | `go test ./...` in `sdk/go` |
431
+ | Rust | `cargo test` in `sdk/rust` |
432
+
433
+ The corpus covers each detector's positive and negative cases, overlap resolution,
434
+ zero-width evasion, every replacement mode, keyed transform vectors, structured
435
+ input, allowlists, terms, confidence thresholds and the limits.
436
+
437
+ Regenerate expectations with `npm run spec:conformance` after an intentional
438
+ behaviour change, and read the diff — an unexplained line in that diff is a bug
439
+ report.
440
+
441
+ ## 14. Deliberate deviations from the Node detector set
442
+
443
+ The Node package's built-in `DETECTORS` remain the reference for the Node API;
444
+ `detectors.json` is the portable profile of them. Where they differ, it is on
445
+ purpose and listed here.
446
+
447
+ 1. **`seed_phrase` (BIP-39 mnemonics) is not in FRS-1 v1.** Its validator needs the
448
+ 2048-word English wordlist, which is a 14 KB payload every SDK would embed for
449
+ one opt-in detector. Node keeps it; a future revision may add a `wordlists`
450
+ section.
451
+ 2. **Trailing boundaries on dash-terminated tokens are stricter.** `\bglpat-[A-Za-z0-9_-]{20}\b`
452
+ in JavaScript requires a *word* character after a token ending in `-`, which
453
+ truncates such tokens. FRS-1 uses `word_dash`, which does not.
454
+ 3. **`coordinates` accepts a leading minus after a word character.** The JavaScript
455
+ `\b-?` construction only permitted the minus after a word character, which is
456
+ the opposite of what was intended.
457
+ 4. **`person_name` matches `name is X` as `\s+is\s+`** rather than `\s*\bis\b\s*`,
458
+ which requires the whitespace that the word boundary implied anyway.
459
+ 5. **Whitespace inside patterns is the six ASCII space characters** `[ \t\n\x0B\f\r]`,
460
+ not `\s`. No detector in this pack intends to match a non-breaking space or an
461
+ ideographic space as a separator.
462
+ 6. **`risk` and `confidence` are explicit on every detector** rather than inferred
463
+ from tags and id substrings. The inferred values are preserved exactly; making
464
+ them data removes a rule engines would otherwise have to reimplement.
465
+
466
+ ---
467
+
468
+ Copyright © Umud Hasanli. Released under the MIT licence with the rest of the
469
+ project. Ports are welcome — implement the spec, pass the corpus, open a PR.
@@ -0,0 +1,60 @@
1
+ # The conformance corpus
2
+
3
+ Four engines, one answer. `cases.json` holds inputs and options; `expected.json`
4
+ holds the output every FRS-1 implementation must produce for them.
5
+
6
+ | File | What it is |
7
+ |---|---|
8
+ | `cases.json` | authored by hand — inputs, options, and which checks to run |
9
+ | `expected.json` | generated — the required result for every case |
10
+
11
+ ## Running it
12
+
13
+ | Engine | Command |
14
+ |---|---|
15
+ | JavaScript / Node | `npm test` |
16
+ | Python | `python -m unittest discover -s sdk/python/tests -t sdk/python` |
17
+ | Go | `cd sdk/go && go test ./...` |
18
+ | Rust | `cd sdk/rust && cargo test` |
19
+
20
+ ## Regenerating expectations
21
+
22
+ ```bash
23
+ npm run spec:conformance -- --write
24
+ ```
25
+
26
+ Any conforming engine can generate the file — that is the point — but regenerate
27
+ from one and **read the diff**. An unexplained line in it is a bug report, not a
28
+ formatting change.
29
+
30
+ ## Writing a case
31
+
32
+ ```json
33
+ { "name": "email/basic", "input": "contact ada@example.com", "options": { "enable": ["pii"] } }
34
+ ```
35
+
36
+ - `name` is unique and reads as `area/behaviour`.
37
+ - `input` is any JSON value. Objects must have their keys in sorted order — see
38
+ [SPEC.md §10](../SPEC.md#10-structured-data) for why traversal order is
39
+ observable and how the corpus keeps the four engines in agreement.
40
+ - `options` uses the JSON wire names (camelCase), the same ones the gateway
41
+ accepts.
42
+ - `checks` defaults to `["redact", "scan"]`; add `"vault"` for a round trip, and
43
+ set `"vault": {"placeholderStyle": "readable"}` so the placeholders are
44
+ deterministic.
45
+
46
+ A good case answers a question someone will actually ask. The corpus is
47
+ deliberately full of negatives — a Luhn-invalid card, a random 12-digit run, a
48
+ date that looks like a phone number — because a redactor that fires on everything
49
+ gets turned off.
50
+
51
+ ## Ground rules
52
+
53
+ - **No astral-plane characters.** Offsets are reported in the host language's
54
+ natural string unit: UTF-16 code units in JavaScript, scalar values elsewhere.
55
+ These coincide for everything below U+10000, and the corpus stays there.
56
+ - **No wall-clock or randomness.** Vault cases use readable placeholders; keyed
57
+ transforms use a fixed `transformSecret`.
58
+ - **Confidence is compared at six decimal places**, which is finer than any
59
+ decision the library makes with the value and coarse enough that four
60
+ languages' floating-point formatting cannot disagree about the text.