flare-redact 1.4.1 → 1.5.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 (57) hide show
  1. package/CHANGELOG.md +130 -0
  2. package/README.md +134 -2
  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 +17 -61
  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 +237 -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/help.d.ts +32 -0
  40. package/dist/help.d.ts.map +1 -0
  41. package/dist/help.js +423 -0
  42. package/dist/help.js.map +1 -0
  43. package/dist/pack.d.ts +88 -0
  44. package/dist/pack.d.ts.map +1 -0
  45. package/dist/pack.js +350 -0
  46. package/dist/pack.js.map +1 -0
  47. package/docker/Dockerfile +47 -0
  48. package/docker/README.md +219 -0
  49. package/docker/docker-compose.yml +55 -0
  50. package/docker/flare-gateway.example.json +48 -0
  51. package/package.json +27 -7
  52. package/spec/SPEC.md +469 -0
  53. package/spec/conformance/README.md +60 -0
  54. package/spec/conformance/cases.json +149 -0
  55. package/spec/conformance/expected.json +1683 -0
  56. package/spec/detectors.json +1812 -0
  57. package/spec/detectors.schema.json +196 -0
package/dist/pack.js ADDED
@@ -0,0 +1,350 @@
1
+ /**
2
+ * FRS-1 detector packs.
3
+ *
4
+ * A pack is a JSON description of a detector set, written in a restricted
5
+ * pattern subset that compiles to the same automaton in JavaScript, Python, Go
6
+ * and Rust. Loading one here turns it into ordinary `Detector` objects, so a
7
+ * pack behaves exactly like a built-in detector — including in overlap
8
+ * resolution, `enable`/`disable`, vaults and every adapter.
9
+ *
10
+ * import { loadPack } from 'flare-redact/pack';
11
+ * import { redact } from 'flare-redact';
12
+ *
13
+ * const pack = loadPack(JSON.parse(await readFile('detectors/acme.json', 'utf8')));
14
+ * redact(text, { detectors: pack.detectors });
15
+ *
16
+ * The loader is strict on purpose. A pack that uses a construct this engine
17
+ * cannot execute exactly as `spec/SPEC.md` describes — a lookahead, a `\d` whose
18
+ * meaning differs between languages, a checksum this build does not know — fails
19
+ * to load. Failing open is how a redactor leaks.
20
+ */
21
+ import { entropy, keepLast, keepPrefix, phoneValid, } from './detectors.js';
22
+ import { aadhaarValid, abaValid, bsnValid, cnResidentIdValid, codiceFiscaleValid, cpfValid, deTaxIdValid, dniValid, frNirValid, ibanValid, jpMyNumberValid, luhnCheck, nhsValid, peselValid, ssnValid, tcknValid, tfnValid, vinValid, } from './checksums.js';
23
+ import { FlareRedactError } from './engine.js';
24
+ export const SPEC_REVISION = 'FRS-1';
25
+ export class PackError extends FlareRedactError {
26
+ constructor(message) {
27
+ super('ERR_PACK_INVALID', message);
28
+ this.name = 'PackError';
29
+ }
30
+ }
31
+ const ASCII = {
32
+ lower: 'abcdefghijklmnopqrstuvwxyz',
33
+ upper: 'ABCDEFGHIJKLMNOPQRSTUVWXYZ',
34
+ digits: '0123456789',
35
+ };
36
+ function charSet(...parts) {
37
+ return new Set(parts.join(''));
38
+ }
39
+ /** Neighbour characters a captured span may not touch. See `spec/SPEC.md` §3.1. */
40
+ export const BOUNDARY_CLASSES = {
41
+ word: charSet(ASCII.lower, ASCII.upper, ASCII.digits, '_'),
42
+ alnum: charSet(ASCII.lower, ASCII.upper, ASCII.digits),
43
+ digit: charSet(ASCII.digits),
44
+ hex: charSet(ASCII.digits, 'abcdefABCDEF'),
45
+ base64: charSet(ASCII.lower, ASCII.upper, ASCII.digits, '+/='),
46
+ base64url: charSet(ASCII.lower, ASCII.upper, ASCII.digits, '_+/=-'),
47
+ word_dash: charSet(ASCII.lower, ASCII.upper, ASCII.digits, '_-'),
48
+ };
49
+ const RISKS = ['low', 'medium', 'high', 'critical'];
50
+ // Engine-side expansion of the two portable tokens. `[\s\S]` is total, so it
51
+ // means "any character" no matter how `\s` is defined; `\p{L}` needs the `u`
52
+ // flag, which is why only patterns that use it are compiled with it.
53
+ const ANY = '[\\s\\S]';
54
+ const LETTER = '\\p{L}';
55
+ function expandTokens(pattern) {
56
+ return pattern.split('{{ANY}}').join(ANY).split('{{L}}').join(LETTER);
57
+ }
58
+ const FORBIDDEN_ESCAPES = new Set('bBdDwWsSpP123456789AZzGkK'.split(''));
59
+ /** Reject constructs whose meaning differs between the FRS-1 target engines. */
60
+ function assertPortable(pattern, where) {
61
+ let index = 0;
62
+ let inClass = false;
63
+ while (index < pattern.length) {
64
+ const ch = pattern[index];
65
+ if (ch === '\\') {
66
+ const next = pattern[index + 1];
67
+ if (next === undefined)
68
+ throw new PackError(`${where}: pattern ends with a dangling backslash`);
69
+ if (FORBIDDEN_ESCAPES.has(next)) {
70
+ throw new PackError(`${where}: '\\${next}' is not portable across FRS-1 engines; ` +
71
+ 'write the character class out, or use {{ANY}} / {{L}}');
72
+ }
73
+ index += 2;
74
+ continue;
75
+ }
76
+ if (inClass) {
77
+ if (ch === ']')
78
+ inClass = false;
79
+ index++;
80
+ continue;
81
+ }
82
+ if (ch === '[') {
83
+ index++;
84
+ if (pattern[index] === '^')
85
+ index++;
86
+ if (pattern[index] === ']')
87
+ index++;
88
+ inClass = true;
89
+ continue;
90
+ }
91
+ if (ch === '(' && pattern[index + 1] === '?') {
92
+ const kind = pattern[index + 2];
93
+ if (kind !== ':') {
94
+ throw new PackError(`${where}: '(?${kind ?? ''}' is not portable across FRS-1 engines; ` +
95
+ "only '(...)' and '(?:...)' groups are allowed");
96
+ }
97
+ index += 3;
98
+ continue;
99
+ }
100
+ if (ch === '^' || ch === '$') {
101
+ throw new PackError(`${where}: anchors are not allowed inside a detector pattern`);
102
+ }
103
+ index++;
104
+ }
105
+ if (inClass)
106
+ throw new PackError(`${where}: unterminated character class`);
107
+ }
108
+ function compile(pattern, { flags = '', where, portable = true, anchor }) {
109
+ if (portable)
110
+ assertPortable(pattern, where);
111
+ const expanded = expandTokens(pattern);
112
+ const body = anchor === 'prefix' ? `^(?:${expanded})` : anchor === 'full' ? `^(?:${expanded})$` : expanded;
113
+ // `u` is only added when the pattern needs it: it also tightens escape rules,
114
+ // and a pack author should not have to satisfy them for patterns that never
115
+ // mention a Unicode property.
116
+ const jsFlags = (flags.includes('i') ? 'i' : '') + (expanded.includes('\\p{') ? 'u' : '') + (anchor ? '' : 'g');
117
+ try {
118
+ return new RegExp(body, jsFlags);
119
+ }
120
+ catch (error) {
121
+ throw new PackError(`${where}: invalid pattern (${error.message})`);
122
+ }
123
+ }
124
+ /** Substitute `$1`–`$9` (and `$$`) in a mask replacement template. */
125
+ function expandReplacement(template, match) {
126
+ let out = '';
127
+ for (let index = 0; index < template.length; index++) {
128
+ const ch = template[index];
129
+ const next = template[index + 1];
130
+ if (ch === '$' && next === '$') {
131
+ out += '$';
132
+ index++;
133
+ continue;
134
+ }
135
+ if (ch === '$' && next !== undefined && next >= '1' && next <= '9') {
136
+ out += match[Number(next)] ?? '';
137
+ index++;
138
+ continue;
139
+ }
140
+ out += ch;
141
+ }
142
+ return out;
143
+ }
144
+ function buildMask(spec, where) {
145
+ switch (spec.type) {
146
+ case 'fixed': {
147
+ const text = String(spec.text ?? '***');
148
+ return () => text;
149
+ }
150
+ case 'keepPrefix':
151
+ return keepPrefix(Number(spec.n));
152
+ case 'keepLast':
153
+ return keepLast(Number(spec.n));
154
+ case 'keepThroughSeparator': {
155
+ const separator = String(spec.separator);
156
+ const count = Number(spec.count);
157
+ return (value) => {
158
+ let index = -separator.length;
159
+ for (let n = 0; n < count; n++) {
160
+ index = value.indexOf(separator, index + separator.length);
161
+ if (index < 0)
162
+ return '***';
163
+ }
164
+ return value.slice(0, index + separator.length) + '***';
165
+ };
166
+ }
167
+ case 'replace': {
168
+ const re = compile(String(spec.pattern), {
169
+ where: `${where} mask`,
170
+ portable: false,
171
+ anchor: 'full',
172
+ flags: String(spec.flags ?? ''),
173
+ });
174
+ const replacement = String(spec.replacement);
175
+ return (value) => {
176
+ re.lastIndex = 0;
177
+ const match = re.exec(value);
178
+ return match ? expandReplacement(replacement, match) : value;
179
+ };
180
+ }
181
+ default:
182
+ throw new PackError(`${where}: unknown mask type ${JSON.stringify(spec.type)}`);
183
+ }
184
+ }
185
+ const NAMED_VALIDATORS = {
186
+ phone: phoneValid,
187
+ iban: ibanValid,
188
+ tckn: tcknValid,
189
+ cpf: cpfValid,
190
+ dni: dniValid,
191
+ bsn: bsnValid,
192
+ pesel: peselValid,
193
+ de_tax_id: deTaxIdValid,
194
+ codice_fiscale: codiceFiscaleValid,
195
+ fr_nir: frNirValid,
196
+ aadhaar: aadhaarValid,
197
+ tfn: tfnValid,
198
+ cn_resident_id: cnResidentIdValid,
199
+ jp_my_number: jpMyNumberValid,
200
+ us_ssn: ssnValid,
201
+ aba: abaValid,
202
+ nhs: nhsValid,
203
+ vin: vinValid,
204
+ };
205
+ const DIGITS_ONLY = /[^0-9]/g;
206
+ function buildValidator(spec, where) {
207
+ if (spec.name === 'normalized_match') {
208
+ const strip = spec.strip
209
+ ? compile(String(spec.strip), { where: `${where} validator strip`, portable: false })
210
+ : undefined;
211
+ const target = compile(String(spec.pattern), { where: `${where} validator`, portable: false, anchor: 'full' });
212
+ return (value) => {
213
+ const candidate = strip ? value.replace(strip, '') : value;
214
+ target.lastIndex = 0;
215
+ return target.test(candidate);
216
+ };
217
+ }
218
+ if (spec.name === 'luhn') {
219
+ const min = Number(spec.minDigits ?? 2);
220
+ const max = Number(spec.maxDigits ?? 0);
221
+ return (value) => {
222
+ const digits = value.replace(DIGITS_ONLY, '');
223
+ if (digits.length < min)
224
+ return false;
225
+ if (max && digits.length > max)
226
+ return false;
227
+ return luhnCheck(digits);
228
+ };
229
+ }
230
+ if (spec.name === 'entropy') {
231
+ const min = Number(spec.min);
232
+ return (value) => entropy(value) >= min;
233
+ }
234
+ const named = NAMED_VALIDATORS[spec.name];
235
+ if (!named) {
236
+ throw new PackError(`${where}: unknown validator ${JSON.stringify(spec.name)}. Refusing to load a pack ` +
237
+ 'whose checks this engine cannot perform.');
238
+ }
239
+ return named;
240
+ }
241
+ function boundaryClass(name, where) {
242
+ if (name === undefined)
243
+ return undefined;
244
+ const members = BOUNDARY_CLASSES[name];
245
+ if (!members)
246
+ throw new PackError(`${where}: unknown boundary class ${JSON.stringify(name)}`);
247
+ return members;
248
+ }
249
+ function toDetector(spec) {
250
+ for (const field of ['id', 'label', 'why', 'pattern', 'mask', 'default', 'risk', 'confidence']) {
251
+ if (spec[field] === undefined)
252
+ throw new PackError(`detector is missing required field ${JSON.stringify(field)}`);
253
+ }
254
+ const where = `detector ${JSON.stringify(spec.id)}`;
255
+ if (!RISKS.includes(spec.risk))
256
+ throw new PackError(`${where}: risk must be one of ${RISKS.join(', ')}`);
257
+ if (!(spec.confidence >= 0 && spec.confidence <= 1)) {
258
+ throw new PackError(`${where}: confidence must be between 0 and 1`);
259
+ }
260
+ const flags = spec.flags ?? '';
261
+ if (flags !== '' && flags !== 'i')
262
+ throw new PackError(`${where}: only the 'i' flag is portable`);
263
+ const pattern = compile(spec.pattern, { flags, where });
264
+ pattern.lastIndex = 0;
265
+ const empty = new RegExp(pattern.source, pattern.flags.replace('g', ''));
266
+ if (empty.test(''))
267
+ throw new PackError(`${where}: pattern matches the empty string`);
268
+ // Count capture groups by making the whole pattern optional and matching the
269
+ // empty string: the result array is one entry per group, plus the whole match.
270
+ const capture = spec.capture ?? 0;
271
+ const probe = new RegExp(`(?:${pattern.source})|`, pattern.flags.replace(/[gdy]/g, ''));
272
+ const groups = (probe.exec('')?.length ?? 1) - 1;
273
+ if (capture > groups)
274
+ throw new PackError(`${where}: capture group ${capture} does not exist`);
275
+ const context = spec.context;
276
+ return {
277
+ id: spec.id,
278
+ label: spec.label,
279
+ why: spec.why,
280
+ pattern,
281
+ ...(capture > 0 ? { capture } : {}),
282
+ ...(spec.boundary
283
+ ? {
284
+ boundary: {
285
+ ...(spec.boundary.before ? { before: boundaryClass(spec.boundary.before, where) } : {}),
286
+ ...(spec.boundary.after ? { after: boundaryClass(spec.boundary.after, where) } : {}),
287
+ },
288
+ }
289
+ : {}),
290
+ ...(spec.reject?.length
291
+ ? { reject: spec.reject.map((p) => compile(p, { flags, where: `${where} reject`, portable: false, anchor: 'prefix' })) }
292
+ : {}),
293
+ ...(spec.validators?.length
294
+ ? {
295
+ validate: ((validators) => (value) => validators.every((check) => check(value)))(spec.validators.map((v) => buildValidator(v, where))),
296
+ }
297
+ : {}),
298
+ mask: buildMask(spec.mask, where),
299
+ default: spec.default,
300
+ ...(spec.tags?.length ? { tags: spec.tags } : {}),
301
+ risk: spec.risk,
302
+ ...(spec.priority ? { priority: spec.priority } : {}),
303
+ confidence: spec.confidence,
304
+ ...(spec.refine ? { refine: true } : {}),
305
+ ...(spec.prefilter?.length ? { prefilter: spec.prefilter } : {}),
306
+ ...(context
307
+ ? {
308
+ context: {
309
+ ...(context.positive
310
+ ? { positive: compile(context.positive, { flags: 'i', where: `${where} context`, portable: false, anchor: undefined }) }
311
+ : {}),
312
+ ...(context.negative
313
+ ? { negative: compile(context.negative, { flags: 'i', where: `${where} context`, portable: false, anchor: undefined }) }
314
+ : {}),
315
+ ...(context.window ? { window: context.window } : {}),
316
+ },
317
+ }
318
+ : {}),
319
+ };
320
+ }
321
+ /**
322
+ * Compile an FRS-1 pack document into detectors this engine can run.
323
+ * Throws {@link PackError} for anything it cannot honour exactly.
324
+ */
325
+ export function loadPack(document) {
326
+ if (document?.spec !== SPEC_REVISION) {
327
+ throw new PackError(`unsupported pack revision ${JSON.stringify(document?.spec)}; this engine implements ${SPEC_REVISION}`);
328
+ }
329
+ if (!Array.isArray(document.detectors) || document.detectors.length === 0) {
330
+ throw new PackError('a pack must declare at least one detector');
331
+ }
332
+ const detectors = [];
333
+ const byId = new Map();
334
+ for (const spec of document.detectors) {
335
+ const detector = toDetector(spec);
336
+ if (byId.has(detector.id))
337
+ throw new PackError(`duplicate detector id ${JSON.stringify(detector.id)}`);
338
+ byId.set(detector.id, detector);
339
+ detectors.push(detector);
340
+ }
341
+ return {
342
+ id: document.id,
343
+ version: document.version,
344
+ title: document.title ?? document.id,
345
+ detectors,
346
+ byId,
347
+ ...(document.confidenceModel ? { confidenceModel: document.confidenceModel } : {}),
348
+ };
349
+ }
350
+ //# sourceMappingURL=pack.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"pack.js","sourceRoot":"","sources":["../src/pack.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;GAmBG;AAEH,OAAO,EACL,OAAO,EACP,QAAQ,EACR,UAAU,EACV,UAAU,GAEX,MAAM,gBAAgB,CAAC;AACxB,OAAO,EACL,YAAY,EACZ,QAAQ,EACR,QAAQ,EACR,iBAAiB,EACjB,kBAAkB,EAClB,QAAQ,EACR,YAAY,EACZ,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+ # Build from the repository root so the build context contains the sources:
4
+ # docker build -f docker/Dockerfile -t flare-redact-gateway .
5
+ #
6
+ # The image ships only the compiled output and production dependencies, runs as
7
+ # an unprivileged user, and listens on 0.0.0.0 because a container's loopback is
8
+ # not reachable from its neighbours. Publish it to 127.0.0.1 on the host, or keep
9
+ # it on an internal network — see docker/README.md.
10
+
11
+ # ---- build ------------------------------------------------------------------
12
+ FROM node:22-alpine AS build
13
+ WORKDIR /src
14
+
15
+ # Dependencies first, so a source-only change does not reinstall the toolchain.
16
+ COPY package.json package-lock.json ./
17
+ RUN npm ci
18
+
19
+ COPY tsconfig.json ./
20
+ COPY src ./src
21
+ RUN npm run build
22
+
23
+ # Reinstall without dev dependencies for the runtime layer.
24
+ RUN npm ci --omit=dev
25
+
26
+ # ---- runtime ----------------------------------------------------------------
27
+ FROM node:22-alpine AS runtime
28
+ ENV NODE_ENV=production \
29
+ FLARE_GATEWAY_HOST=0.0.0.0 \
30
+ FLARE_GATEWAY_PORT=8787
31
+
32
+ WORKDIR /app
33
+ COPY --from=build /src/node_modules ./node_modules
34
+ COPY --from=build /src/dist ./dist
35
+ COPY --from=build /src/package.json ./package.json
36
+ COPY bin/flare-gateway.mjs ./bin/flare-gateway.mjs
37
+
38
+ # node:alpine already provides an unprivileged `node` user.
39
+ USER node
40
+ EXPOSE 8787
41
+
42
+ # Liveness only — readiness is the same endpoint, since the gateway is ready as
43
+ # soon as it can accept a connection.
44
+ HEALTHCHECK --interval=30s --timeout=3s --start-period=5s --retries=3 \
45
+ CMD node -e "fetch('http://127.0.0.1:'+(process.env.FLARE_GATEWAY_PORT||8787)+'/healthz').then(r=>process.exit(r.ok?0:1)).catch(()=>process.exit(1))"
46
+
47
+ ENTRYPOINT ["node", "bin/flare-gateway.mjs"]
@@ -0,0 +1,219 @@
1
+ # The flare-redact gateway
2
+
3
+ A redaction sidecar. Point a vendor SDK's base URL at it and the request body is
4
+ scrubbed on the way out and the originals are put back on the way in — streaming
5
+ included. Your application keeps sending and receiving real data; the vendor
6
+ never sees it.
7
+
8
+ ```bash
9
+ docker build -f docker/Dockerfile -t flare-redact-gateway .
10
+
11
+ docker run --rm -p 127.0.0.1:8787:8787 \
12
+ -e FLARE_REDACT_ENABLE=pii \
13
+ flare-redact-gateway --upstream https://api.openai.com
14
+ ```
15
+
16
+ ```diff
17
+ - OPENAI_BASE_URL=https://api.openai.com/v1
18
+ + OPENAI_BASE_URL=http://127.0.0.1:8787/v1
19
+ ```
20
+
21
+ That diff is the whole integration. No middleware, no wrapper, no import — which
22
+ is the point: the teams that most need this are the ones whose Python service,
23
+ PHP monolith and Node worker all call the same vendor and cannot each grow a new
24
+ dependency.
25
+
26
+ Without Docker: `npx flare-redact gateway --upstream https://api.openai.com`.
27
+
28
+ ## Contents
29
+
30
+ - [What it does to a request](#what-it-does-to-a-request)
31
+ - [Routes](#routes)
32
+ - [Which parts of the body](#which-parts-of-the-body)
33
+ - [Restoring the answer](#restoring-the-answer)
34
+ - [The redaction API](#the-redaction-api)
35
+ - [Configuration](#configuration)
36
+ - [Operating it](#operating-it)
37
+ - [Security model](#security-model)
38
+ - [What it deliberately does not do](#what-it-deliberately-does-not-do)
39
+
40
+ ## What it does to a request
41
+
42
+ ```
43
+ your app ──▶ gateway ──▶ vendor
44
+ real data │ placeholders
45
+ │
46
+ real data ◀──┘◀────────── placeholders
47
+ ```
48
+
49
+ 1. Read the body, up to `maxBodyBytes`.
50
+ 2. Redact it — the whole body by default, or only the JSON paths you name.
51
+ 3. Forward it with your headers untouched, including `Authorization`.
52
+ 4. Restore the originals in the response, buffered for JSON and incrementally
53
+ for `text/event-stream`.
54
+
55
+ ## Routes
56
+
57
+ One upstream:
58
+
59
+ ```bash
60
+ flare-redact gateway --upstream https://api.openai.com
61
+ ```
62
+
63
+ Several, by prefix:
64
+
65
+ ```bash
66
+ flare-redact gateway \
67
+ --route /openai=https://api.openai.com \
68
+ --route /anthropic=https://api.anthropic.com
69
+ ```
70
+
71
+ ```
72
+ OPENAI_BASE_URL=http://127.0.0.1:8787/openai/v1
73
+ ANTHROPIC_BASE_URL=http://127.0.0.1:8787/anthropic
74
+ ```
75
+
76
+ The longest matching prefix wins, so `/openai/v1` can be routed differently from
77
+ `/openai`. A route may not claim `/healthz`, `/readyz`, `/metrics` or `/v1/` —
78
+ the gateway answers those itself, and a config that would shadow one is rejected
79
+ at startup rather than mysteriously at runtime.
80
+
81
+ ## Which parts of the body
82
+
83
+ Redacting the entire body is the safe default and the one you get. For a chat
84
+ completion it also rewrites the model name and the tool schema, which is usually
85
+ harmless and occasionally not — so name the paths that hold what a human typed:
86
+
87
+ ```bash
88
+ --paths 'messages[*].content,input,prompt,system'
89
+ ```
90
+
91
+ `a.b`, `a[0]`, `a[*]` and `*` are supported. A path that does not exist in a
92
+ given request is a no-op, so one configuration covers several endpoint shapes.
93
+
94
+ Non-JSON bodies pass through untouched unless you add `--redact-text`, which
95
+ extends handling to `application/x-www-form-urlencoded` and `text/*`. A body that
96
+ claims to be JSON but does not parse is redacted as text rather than forwarded:
97
+ its framing is already broken, and the failure mode that matters is leaking.
98
+
99
+ ## Restoring the answer
100
+
101
+ Redaction uses a per-request vault, so `ada@example.com` becomes
102
+ `[FR_EMAIL_9f2c…]` on the way out and comes back on the way in. The model's reply
103
+ reads correctly to your user, and the vendor never held the address.
104
+
105
+ For a streamed response the restorer holds back the longest suffix that could
106
+ still be the start of a placeholder, so a token split across two SSE frames is
107
+ still restored exactly once. Substituted values are escaped for the JSON string
108
+ context those frames use, so a name containing a quote cannot break the client's
109
+ parser.
110
+
111
+ Turn it off with `--no-restore` when the upstream never echoes the prompt back
112
+ and you would rather save the work.
113
+
114
+ ## The redaction API
115
+
116
+ The gateway is also a service the [Python](../sdk/python/README.md) and
117
+ [Go](../sdk/go/README.md) clients talk to, for the cases where a native engine is
118
+ not what you want:
119
+
120
+ | | |
121
+ |---|---|
122
+ | `POST /v1/redact` | `{"input": …, "options": {…}}` → `{"output": …, "summary": {…}}` |
123
+ | `POST /v1/scan` | → `{"findings": [...], "summary": {…}}` |
124
+ | `GET /v1/detectors` | the catalogue, plus this gateway's selectors |
125
+ | `POST /v1/sessions` | open a server-side vault → `{"id", "expiresAt"}` |
126
+ | `POST /v1/sessions/:id/redact` | mask, remembering the mapping |
127
+ | `POST /v1/sessions/:id/restore` | put the originals back |
128
+ | `DELETE /v1/sessions/:id` | discard the mapping |
129
+ | `GET /healthz`, `GET /readyz` | liveness |
130
+ | `GET /metrics` | Prometheus text |
131
+
132
+ Set `FLARE_GATEWAY_TOKEN` and every `/v1` call needs
133
+ `Authorization: Bearer <token>`. Health and metrics stay open so a probe does not
134
+ need a credential.
135
+
136
+ Those eight paths are the only ones the gateway answers itself, and they are the
137
+ only ones that shadow your upstream. Everything else under `/v1` — `/v1/chat/
138
+ completions`, `/v1/models`, `/v1/messages` — is proxied like any other path, which
139
+ is the whole point of putting the sidecar in front of a vendor that owns that
140
+ namespace.
141
+
142
+ Sessions are held in memory, expire after `sessions.ttlMs` and are capped at
143
+ `sessions.max`. An unbounded map of secrets is a memory leak with a disclosure
144
+ attached. Because they are per-process, a replicated gateway needs sticky routing
145
+ for session traffic — the stateless `/v1/redact` path does not.
146
+
147
+ ## Configuration
148
+
149
+ Three layers, later winning: a config file, the environment, the command line.
150
+
151
+ ```bash
152
+ flare-redact gateway --config docker/flare-gateway.example.json --print-config
153
+ ```
154
+
155
+ | Environment variable | |
156
+ |---|---|
157
+ | `FLARE_UPSTREAM` | single-upstream shorthand |
158
+ | `FLARE_GATEWAY_HOST` / `FLARE_GATEWAY_PORT` | bind address (default `127.0.0.1:8787`) |
159
+ | `FLARE_GATEWAY_TOKEN` | bearer token for `/v1` |
160
+ | `FLARE_REDACT_ONLY` / `_ENABLE` / `_DISABLE` | detector selection |
161
+ | `FLARE_REDACT_MODE` | `mask`, `label`, `hash`, `pseudonym`, `surrogate` |
162
+ | `FLARE_REDACT_SECRET` | key for the keyed modes |
163
+ | `FLARE_GATEWAY_MAX_BODY_BYTES` | default 8 MiB |
164
+ | `FLARE_GATEWAY_TIMEOUT_MS` | default 120 s |
165
+ | `FLARE_GATEWAY_SESSION_TTL_MS` | default 30 min |
166
+ | `FLARE_GATEWAY_LOG` | `silent`, `info`, `debug` |
167
+
168
+ See [`flare-gateway.example.json`](./flare-gateway.example.json) for the full
169
+ shape, including per-route policies.
170
+
171
+ ## Operating it
172
+
173
+ The audit log is JSON lines and contains counts, never content:
174
+
175
+ ```json
176
+ {"time":"2026-08-05T09:12:44.031Z","level":"info","name":"flare-gateway","msg":"proxied",
177
+ "route":"openai","method":"POST","path":"/openai/v1/chat/completions","status":200,
178
+ "durationMs":412,"findings":{"email":2,"phone":1},"placeholders":3}
179
+ ```
180
+
181
+ `/metrics` exposes `flare_gateway_requests_total{route,status}`,
182
+ `flare_gateway_findings_total{detector}`, request and response byte counters,
183
+ error counters and an active-session gauge. Counting findings costs one extra
184
+ scan per request; set `auditFindings: false` if you would rather have the
185
+ throughput than the numbers.
186
+
187
+ Every response carries `X-Flare-Redact: route=…; findings=N; restored=on|off`,
188
+ which makes "is the proxy actually in the path?" answerable from a single curl.
189
+
190
+ ## Security model
191
+
192
+ - **Your credential is forwarded, never redacted.** The `Authorization` header
193
+ that authenticates you *to* the vendor is not the secret being hidden *from*
194
+ it. Header values pass through untouched.
195
+ - **Bodies, headers and matched values are never logged.**
196
+ - **The gateway's policy wins.** A client may pass options, but the configured
197
+ policy is layered over them, so no caller can send `{"disable":["email"]}` and
198
+ opt out. `transformSecret` from a client is rejected outright.
199
+ - **It binds to loopback by default.** In a container that has to be `0.0.0.0`;
200
+ publish it as `127.0.0.1:8787:8787` or keep it on an internal network. A
201
+ redaction proxy reachable from the internet is a proxy anyone can send data
202
+ through.
203
+ - **Failures are refusals.** An oversized body is a 413, an unreachable upstream
204
+ is a 502. Neither is a partially redacted request that quietly reaches the
205
+ vendor.
206
+ - **Hop-by-hop headers are stripped** in both directions, and redirects are not
207
+ followed — an upstream cannot bounce your data somewhere the config never
208
+ named.
209
+
210
+ ## What it deliberately does not do
211
+
212
+ - **No TLS interception.** This is a reverse proxy you point at, not a MITM that
213
+ forges certificates. Changing one base URL is a smaller, more auditable change
214
+ than installing a root CA on every host.
215
+ - **No shared session store.** Sessions are per-process. Distributing them would
216
+ mean replicating a map of plaintext secrets across your cluster.
217
+ - **No response redaction.** The gateway restores what it masked; it does not
218
+ scan what the vendor sent back. If the *upstream* is the untrusted party, redact
219
+ its response in your application with the library.