flare-redact 0.9.0 → 1.0.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.
package/dist/graph.js ADDED
@@ -0,0 +1,94 @@
1
+ function isAtomicObject(value) {
2
+ return value instanceof Date
3
+ || value instanceof RegExp
4
+ || value instanceof Promise
5
+ || value instanceof WeakMap
6
+ || value instanceof WeakSet
7
+ || value instanceof ArrayBuffer
8
+ || ArrayBuffer.isView(value);
9
+ }
10
+ /**
11
+ * Clone and transform a JavaScript object graph without losing cycles, shared
12
+ * references, Map/Set contents, symbol metadata, or custom prototypes.
13
+ */
14
+ export function mapGraph(input, mapString, mapSensitiveValue) {
15
+ const seen = new WeakMap();
16
+ const walk = (value) => {
17
+ if (typeof value === 'string')
18
+ return mapString(value);
19
+ if (!value || typeof value !== 'object')
20
+ return value;
21
+ const cached = seen.get(value);
22
+ if (cached !== undefined)
23
+ return cached;
24
+ if (value instanceof Error) {
25
+ const out = Object.create(Object.getPrototypeOf(value));
26
+ seen.set(value, out);
27
+ Object.defineProperties(out, {
28
+ name: { value: value.name, writable: true, configurable: true },
29
+ message: { value: mapString(value.message), writable: true, configurable: true },
30
+ ...(typeof value.stack === 'string'
31
+ ? { stack: { value: mapString(value.stack), writable: true, configurable: true } }
32
+ : {}),
33
+ });
34
+ copyEnumerable(value, out, walk, mapSensitiveValue);
35
+ return out;
36
+ }
37
+ if (value instanceof URL) {
38
+ const out = new URL(mapString(value.toString()));
39
+ seen.set(value, out);
40
+ return out;
41
+ }
42
+ if (value instanceof URLSearchParams) {
43
+ const out = new URLSearchParams(mapString(value.toString()));
44
+ seen.set(value, out);
45
+ return out;
46
+ }
47
+ if (isAtomicObject(value))
48
+ return value;
49
+ if (value instanceof Map) {
50
+ const out = new Map();
51
+ seen.set(value, out);
52
+ for (const [key, entry] of value)
53
+ out.set(walk(key), walk(entry));
54
+ return out;
55
+ }
56
+ if (value instanceof Set) {
57
+ const out = new Set();
58
+ seen.set(value, out);
59
+ for (const entry of value)
60
+ out.add(walk(entry));
61
+ return out;
62
+ }
63
+ if (Array.isArray(value)) {
64
+ const out = new Array(value.length);
65
+ seen.set(value, out);
66
+ for (let i = 0; i < value.length; i++) {
67
+ if (Object.prototype.hasOwnProperty.call(value, i))
68
+ out[i] = walk(value[i]);
69
+ }
70
+ copyEnumerable(value, out, walk, mapSensitiveValue, new Set(['length', ...Object.keys(value).filter((k) => /^\d+$/.test(k))]));
71
+ return out;
72
+ }
73
+ const out = Object.create(Object.getPrototypeOf(value));
74
+ seen.set(value, out);
75
+ copyEnumerable(value, out, walk, mapSensitiveValue);
76
+ return out;
77
+ };
78
+ return walk(input);
79
+ }
80
+ function copyEnumerable(source, target, walk, mapSensitiveValue, skip = new Set()) {
81
+ for (const key of Reflect.ownKeys(source)) {
82
+ if (skip.has(key))
83
+ continue;
84
+ const descriptor = Object.getOwnPropertyDescriptor(source, key);
85
+ if (!descriptor?.enumerable || !('value' in descriptor))
86
+ continue;
87
+ const raw = descriptor.value;
88
+ const next = typeof key === 'string' && typeof raw === 'string' && mapSensitiveValue
89
+ ? mapSensitiveValue(key, raw)
90
+ : walk(raw);
91
+ Object.defineProperty(target, key, { ...descriptor, value: next });
92
+ }
93
+ }
94
+ //# sourceMappingURL=graph.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"graph.js","sourceRoot":"","sources":["../src/graph.ts"],"names":[],"mappings":"AAGA,SAAS,cAAc,CAAC,KAAa;IACnC,OAAO,KAAK,YAAY,IAAI;WACvB,KAAK,YAAY,MAAM;WACvB,KAAK,YAAY,OAAO;WACxB,KAAK,YAAY,OAAO;WACxB,KAAK,YAAY,OAAO;WACxB,KAAK,YAAY,WAAW;WAC5B,WAAW,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC;AACjC,CAAC;AAED;;;GAGG;AACH,MAAM,UAAU,QAAQ,CACtB,KAAc,EACd,SAAuB,EACvB,iBAAwC;IAExC,MAAM,IAAI,GAAG,IAAI,OAAO,E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5B,MAAM,UAAU,GAAG,MAAM,CAAC,wBAAwB,CAAC,MAAM,EAAE,GAAG,CAAC,CAAC;QAChE,IAAI,CAAC,UAAU,EAAE,UAAU,IAAI,CAAC,CAAC,OAAO,IAAI,UAAU,CAAC;YAAE,SAAS;QAClE,MAAM,GAAG,GAAG,UAAU,CAAC,KAAgB,CAAC;QACxC,MAAM,IAAI,GAAG,OAAO,GAAG,KAAK,QAAQ,IAAI,OAAO,GAAG,KAAK,QAAQ,IAAI,iBAAiB;YAClF,CAAC,CAAC,iBAAiB,CAAC,GAAG,EAAE,GAAG,CAAC;YAC7B,CAAC,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC;QACd,MAAM,CAAC,cAAc,CAAC,MAAM,EAAE,GAAG,EAAE,EAAE,GAAG,UAAU,EAAE,KAAK,EAAE,IAAI,EAAE,CAAC,CAAC;IACrE,CAAC;AACH,CAAC"}
package/dist/http.d.ts CHANGED
@@ -16,6 +16,11 @@ export interface RedactedRequest {
16
16
  params: unknown;
17
17
  body: unknown;
18
18
  }
19
+ /**
20
+ * Redact credentials, path segments, query values, and fragments while keeping
21
+ * an absolute or relative URL usable in a log message.
22
+ */
23
+ export declare function redactUrl(input: string, opts?: RedactOptions): string;
19
24
  /**
20
25
  * A safe-to-log snapshot of a request. Authorization/Cookie headers, and any
21
26
  * secret or PII in the query, params, or body, are masked — while ordinary
@@ -1 +1 @@
1
- {"version":3,"file":"http.d.ts","sourceRoot":"","sources":["../src/http.ts"],"names":[],"mappings":"AAAA,OAAO,EAAU,KAAK,aAAa,EAAE,MAAM,YAAY,CAAC;AAExD,MAAM,WAAW,eAAe;IAC9B,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,GAAG,CAAC,EAAE,MAAM,CAAC;IACb,WAAW,CAAC,EAAE,MAAM,CAAC;IACrB,OAAO,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;IAClC,KAAK,CAAC,EAAE,OAAO,CAAC;IAChB,MAAM,C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,MAAM,EAAE,IAAI,GAAE,aAAkB,GAAG,MAAM,CAgCzE;AAED;;;;GAIG;AACH,wBAAgB,UAAU,CAAC,GAAG,EAAE,eAAe,EAAE,IAAI,GAAE,aAAkB,GAAG,eAAe,CAW1F;AAED;;;;;;;GAOG;AACH,wBAAgB,YAAY,CAAC,IAAI,GAAE,aAAkB,IAC3C,KAAK,eAAe,EAAE,MAAM,OAAO,EAAE,MAAM,MAAM,IAAI,KAAG,IAAI,CASrE"}
package/dist/http.js CHANGED
@@ -1,4 +1,55 @@
1
1
  import { redact } from './index.js';
2
+ function decode(value) {
3
+ try {
4
+ return decodeURIComponent(value);
5
+ }
6
+ catch {
7
+ return value;
8
+ }
9
+ }
10
+ /**
11
+ * Redact credentials, path segments, query values, and fragments while keeping
12
+ * an absolute or relative URL usable in a log message.
13
+ */
14
+ export function redactUrl(input, opts = {}) {
15
+ const absolute = /^[a-z][a-z\d+.-]*:/i.test(input);
16
+ const protocolRelative = input.startsWith('//');
17
+ const queryOnly = input.startsWith('?');
18
+ const hashOnly = input.startsWith('#');
19
+ const leadingSlash = input.startsWith('/');
20
+ try {
21
+ const parsed = new URL(input, 'http://flare-redact.invalid');
22
+ if (parsed.username)
23
+ parsed.username = '***';
24
+ if (parsed.password)
25
+ parsed.password = '***';
26
+ parsed.pathname = parsed.pathname
27
+ .split('/')
28
+ .map((segment) => encodeURIComponent(redact(decode(segment), opts)))
29
+ .join('/');
30
+ const query = new URLSearchParams();
31
+ for (const [key, value] of parsed.searchParams) {
32
+ const keyed = redact({ [key]: value }, opts);
33
+ query.append(redact(key, opts), keyed[key] ?? redact(value, opts));
34
+ }
35
+ parsed.search = query.toString();
36
+ if (parsed.hash)
37
+ parsed.hash = encodeURIComponent(redact(decode(parsed.hash.slice(1)), opts));
38
+ if (absolute)
39
+ return parsed.toString();
40
+ if (protocolRelative)
41
+ return `//${parsed.host}${parsed.pathname}${parsed.search}${parsed.hash}`;
42
+ if (queryOnly)
43
+ return `${parsed.search}${parsed.hash}`;
44
+ if (hashOnly)
45
+ return parsed.hash;
46
+ const path = leadingSlash ? parsed.pathname : parsed.pathname.replace(/^\//, '');
47
+ return `${path}${parsed.search}${parsed.hash}`;
48
+ }
49
+ catch {
50
+ return redact(input, opts);
51
+ }
52
+ }
2
53
  /**
3
54
  * A safe-to-log snapshot of a request. Authorization/Cookie headers, and any
4
55
  * secret or PII in the query, params, or body, are masked — while ordinary
@@ -7,7 +58,9 @@ import { redact } from './index.js';
7
58
  export function redactHttp(req, opts = {}) {
8
59
  return {
9
60
  method: req.method,
10
- url: req.originalUrl ?? req.url,
61
+ url: typeof (req.originalUrl ?? req.url) === 'string'
62
+ ? redactUrl((req.originalUrl ?? req.url), opts)
63
+ : undefined,
11
64
  headers: redact(req.headers ?? {}, opts),
12
65
  query: redact(req.query, opts),
13
66
  params: redact(req.params, opts),
package/dist/http.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"http.js","sourceRoot":"","sources":["../src/http.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,EAAsB,MAAM,YAAY,CAAC;AAqBxD;;;;GAIG;AACH,MAAM,UAAU,UAAU,CAAC,GAAoB,EAAE,OAAsB,EAAE;IACvE,OAAO;QACL,MAAM,EAAE,GAAG,CAAC,MAAM;QAClB,GAAG,EAAE,GAAG,CAAC,WAAW,IAAI,GAAG,CAAC,GAAG;QAC/B,OAAO,EAAE,MAAM,CAAC,GAAG,CAAC,OAAO,IAAI,EAAE,EAAE,IAAI,CAAC;QACxC,KAAK,EAAE,MAAM,CAAC,GAAG,CAAC,KAAK,EAAE,IAAI,CAAC;QAC9B,MAAM,EAAE,MAAM,CAAC,GAAG,CAAC,MAAM,EAAE,IAAI,CAAC;QAChC,IAAI,EAAE,MAAM,CAAC,GAAG,CAAC,IAAI,EAAE,IAAI,CAAC;KAC7B,CAAC;AACJ,CAAC;AAED;;;;;;;GAOG;AACH,MAAM,UAAU,YAAY,CAAC,OAAsB,EAAE;IACnD,OAAO,CAAC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GAAG,EAAE,IAAI,CAAC;YAClC,UAAU,EAAE,KAAK;YACjB,YAAY,EAAE,IAAI;YAClB,QAAQ,EAAE,IAAI;SACf,CAAC,CAAC;QACH,IAAI,EAAE,CAAC;IACT,CAAC,CAAC;AACJ,CAAC"}
package/dist/index.d.ts CHANGED
@@ -1,18 +1,17 @@
1
1
  import { type RedactOptions, type Finding } from './engine.js';
2
2
  export type { Mode, Risk, Finding, RedactOptions, SemanticFinding, SemanticProvider } from './engine.js';
3
- export { RedactionLimitError } from './engine.js';
3
+ export { FlareRedactError, RedactionLimitError } from './engine.js';
4
4
  export type { Detector } from './detectors.js';
5
5
  export { DETECTORS, SENSITIVE_KEY_RE, keepPrefix, keepLast, luhn, entropy, fnv1a, } from './detectors.js';
6
6
  export { pseudonymize, surrogate, fpe } from './transforms.js';
7
7
  export { hmacFingerprint } from './crypto.js';
8
- export { createVault, restore, buildRestore, type Vault, type VaultOptions } from './vault.js';
8
+ export { createVault, restore, buildRestore, buildStreamRestore, type IncrementalRestorer, type Vault, type VaultOptions, } from './vault.js';
9
9
  export { sealVault, openVault, isSealedVault, type SealedVaultV1, type SealVaultOptions, } from './secure-vault.js';
10
10
  export { createSession, type Session, type SessionOptions, type StreamRestorer } from './session.js';
11
11
  export declare function redact<T>(input: T, opts?: RedactOptions): T;
12
12
  /** Async counterpart for local ML/NER providers whose `detect()` returns a Promise. */
13
13
  export declare function redactAsync<T>(input: T, opts?: RedactOptions): Promise<T>;
14
14
  export declare function scan(input: unknown, opts?: RedactOptions): Finding[];
15
- /** Async counterpart for local ML/NER providers whose `detect()` returns a Promise. */
16
15
  export declare function scanAsync(input: unknown, opts?: RedactOptions): Promise<Finding[]>;
17
16
  export declare function isCleanAsync(input: unknown, opts?: RedactOptions): Promise<boolean>;
18
17
  export declare function isClean(input: unknown, opts?: RedactOptions): boolean;
@@ -27,11 +26,14 @@ export declare function summary(input: unknown, opts?: RedactOptions): {
27
26
  * adapter (`flare-redact/pino`, `/winston`, `/http`, `/llm`) accepts, so a
28
27
  * secret is masked the same way across your whole system.
29
28
  */
30
- export declare function createRedactor(opts?: RedactOptions): {
29
+ export declare function compilePolicy(opts?: RedactOptions): {
31
30
  options: RedactOptions;
32
31
  redact: <T>(input: T) => T;
32
+ redactAsync: <T>(input: T) => Promise<T>;
33
33
  scan: (input: unknown) => Finding[];
34
+ scanAsync: (input: unknown) => Promise<Finding[]>;
34
35
  isClean: (input: unknown) => boolean;
36
+ isCleanAsync: (input: unknown) => Promise<boolean>;
35
37
  summary: (input: unknown) => {
36
38
  total: number;
37
39
  byDetector: Record<string, number>;
@@ -40,7 +42,9 @@ export declare function createRedactor(opts?: RedactOptions): {
40
42
  vault: () => import("./vault.js").Vault;
41
43
  wrapConsole: (target?: Console) => () => void;
42
44
  };
45
+ /** Backward-compatible name for a precompiled reusable policy. */
46
+ export declare const createRedactor: typeof compilePolicy;
43
47
  /** Alias for {@link createRedactor}, read as "define the masking policy once". */
44
- export declare const definePolicy: typeof createRedactor;
48
+ export declare const definePolicy: typeof compilePolicy;
45
49
  export declare function wrapConsole(opts?: RedactOptions, target?: Console): () => void;
46
50
  //# sourceMappingURL=index.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAEA,OAAO,EAOL,KAAK,aAAa,EAClB,KAAK,OAAO,EAEb,MAAM,aAAa,CAAC;AAErB,YAAY,EAAE,IAAI,EAAE,IAAI,EAAE,OAAO,EAAE,aAAa,EAAE,eAAe,EAAE,gBAAgB,EAAE,MAAM,aAAa,CAAC;AACzG,OAAO,EAAE,mBAAmB,EAAE,MAAM,aAAa,CAAC;AAClD,YAAY,EAAE,QAAQ,EAAE,MAAM,gBAAgB,CAAC;AAC/C,OAAO,EACL,SAAS,EACT,gBAAgB,EAChB,UAAU,EACV,QAAQ,EACR,IAAI,EACJ,OAAO,EACP,KAAK,GACN,MAAM,gBAAgB,CAAC;AACxB,OAAO,EAAE,YAAY,EAAE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qBACT,OAAO;0BACI,OAAO;qBAClB,OAAO;eA1BhB,MAAM;oBAAc,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC;gBAAU,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC;;;2BA4B3D,OAAO,WAasD,IAAI;EAX3F;AAED,kEAAkE;AAClE,eAAO,MAAM,cAAc,sBAAgB,CAAC;AAE5C,kFAAkF;AAClF,eAAO,MAAM,YAAY,sBAAgB,CAAC;AAK1C,wBAAgB,WAAW,CAAC,IAAI,GAAE,aAAkB,EAAE,MAAM,GAAE,OAAiB,GAAG,MAAM,IAAI,CAY3F"}
package/dist/index.js CHANGED
@@ -1,38 +1,31 @@
1
1
  import { SENSITIVE_KEY_DETECTOR } from './detectors.js';
2
2
  import { createVault } from './vault.js';
3
+ import { mapGraph } from './graph.js';
3
4
  import { resolveDetectors, keyMatcher, allowMatcher, makeReplacer, scanString, redactString, } from './engine.js';
4
- export { RedactionLimitError } from './engine.js';
5
+ export { FlareRedactError, RedactionLimitError } from './engine.js';
5
6
  export { DETECTORS, SENSITIVE_KEY_RE, keepPrefix, keepLast, luhn, entropy, fnv1a, } from './detectors.js';
6
7
  export { pseudonymize, surrogate, fpe } from './transforms.js';
7
8
  export { hmacFingerprint } from './crypto.js';
8
- export { createVault, restore, buildRestore } from './vault.js';
9
+ export { createVault, restore, buildRestore, buildStreamRestore, } from './vault.js';
9
10
  export { sealVault, openVault, isSealedVault, } from './secure-vault.js';
10
11
  export { createSession } from './session.js';
11
- export function redact(input, opts = {}) {
12
- const dets = resolveDetectors(opts);
13
- const allow = allowMatcher(opts);
14
- const replace = makeReplacer(opts);
15
- const matchKey = keyMatcher(opts);
16
- const walk = (value) => {
17
- if (typeof value === 'string')
18
- return redactString(value, dets, allow, replace, opts);
19
- if (Array.isArray(value))
20
- return value.map(walk);
21
- if (value && typeof value === 'object') {
22
- const out = {};
23
- for (const [k, v] of Object.entries(value)) {
24
- if (typeof v === 'string' && matchKey(k) && !allow(v)) {
25
- out[k] = replace(v, SENSITIVE_KEY_DETECTOR);
26
- }
27
- else {
28
- out[k] = walk(v);
29
- }
30
- }
31
- return out;
32
- }
33
- return value;
12
+ function preparePolicy(opts) {
13
+ return {
14
+ opts,
15
+ dets: resolveDetectors(opts),
16
+ allow: allowMatcher(opts),
17
+ replace: makeReplacer(opts),
18
+ matchKey: keyMatcher(opts),
34
19
  };
35
- return walk(input);
20
+ }
21
+ function redactPrepared(input, policy) {
22
+ const { opts, dets, allow, replace, matchKey } = policy;
23
+ return mapGraph(input, (value) => redactString(value, dets, allow, replace, opts), (key, value) => matchKey(key) && !allow(value)
24
+ ? replace(value, SENSITIVE_KEY_DETECTOR)
25
+ : redactString(value, dets, allow, replace, opts));
26
+ }
27
+ export function redact(input, opts = {}) {
28
+ return redactPrepared(input, preparePolicy(opts));
36
29
  }
37
30
  async function resolvedSemanticOptions(text, opts) {
38
31
  if (!opts.semanticProvider)
@@ -41,40 +34,108 @@ async function resolvedSemanticOptions(text, opts) {
41
34
  return { ...opts, semanticProvider: { detect: () => findings } };
42
35
  }
43
36
  /** Async counterpart for local ML/NER providers whose `detect()` returns a Promise. */
44
- export async function redactAsync(input, opts = {}) {
45
- const dets = resolveDetectors(opts);
46
- const allow = allowMatcher(opts);
47
- const replace = makeReplacer(opts);
48
- const matchKey = keyMatcher(opts);
37
+ async function redactAsyncPrepared(input, policy) {
38
+ const { opts, dets, allow, replace, matchKey } = policy;
39
+ const seen = new WeakMap();
49
40
  const walk = async (value) => {
50
41
  if (typeof value === 'string') {
51
42
  const localOpts = await resolvedSemanticOptions(value, opts);
52
43
  return redactString(value, dets, allow, replace, localOpts);
53
44
  }
54
- if (Array.isArray(value))
55
- return Promise.all(value.map(walk));
56
- if (value && typeof value === 'object') {
57
- const out = {};
58
- for (const [k, v] of Object.entries(value)) {
59
- if (typeof v === 'string' && matchKey(k) && !allow(v))
60
- out[k] = replace(v, SENSITIVE_KEY_DETECTOR);
61
- else
62
- out[k] = await walk(v);
45
+ if (!value || typeof value !== 'object')
46
+ return value;
47
+ const cached = seen.get(value);
48
+ if (cached !== undefined)
49
+ return cached;
50
+ if (value instanceof Error) {
51
+ const out = Object.create(Object.getPrototypeOf(value));
52
+ seen.set(value, out);
53
+ Object.defineProperties(out, {
54
+ name: { value: value.name, writable: true, configurable: true },
55
+ message: {
56
+ value: redactString(value.message, dets, allow, replace, await resolvedSemanticOptions(value.message, opts)),
57
+ writable: true,
58
+ configurable: true,
59
+ },
60
+ ...(typeof value.stack === 'string'
61
+ ? {
62
+ stack: {
63
+ value: redactString(value.stack, dets, allow, replace, await resolvedSemanticOptions(value.stack, opts)),
64
+ writable: true,
65
+ configurable: true,
66
+ },
67
+ }
68
+ : {}),
69
+ });
70
+ for (const key of Reflect.ownKeys(value)) {
71
+ const descriptor = Object.getOwnPropertyDescriptor(value, key);
72
+ if (!descriptor?.enumerable || !('value' in descriptor))
73
+ continue;
74
+ Object.defineProperty(out, key, { ...descriptor, value: await walk(descriptor.value) });
63
75
  }
64
76
  return out;
65
77
  }
66
- return value;
78
+ if (value instanceof URL) {
79
+ const localOpts = await resolvedSemanticOptions(value.toString(), opts);
80
+ const out = new URL(redactString(value.toString(), dets, allow, replace, localOpts));
81
+ seen.set(value, out);
82
+ return out;
83
+ }
84
+ if (value instanceof URLSearchParams) {
85
+ const localOpts = await resolvedSemanticOptions(value.toString(), opts);
86
+ const out = new URLSearchParams(redactString(value.toString(), dets, allow, replace, localOpts));
87
+ seen.set(value, out);
88
+ return out;
89
+ }
90
+ if (value instanceof Map) {
91
+ const out = new Map();
92
+ seen.set(value, out);
93
+ for (const [key, entry] of value)
94
+ out.set(await walk(key), await walk(entry));
95
+ return out;
96
+ }
97
+ if (value instanceof Set) {
98
+ const out = new Set();
99
+ seen.set(value, out);
100
+ for (const entry of value)
101
+ out.add(await walk(entry));
102
+ return out;
103
+ }
104
+ if (value instanceof Date || value instanceof RegExp || value instanceof ArrayBuffer || ArrayBuffer.isView(value)) {
105
+ return value;
106
+ }
107
+ const out = Array.isArray(value)
108
+ ? new Array(value.length)
109
+ : Object.create(Object.getPrototypeOf(value));
110
+ seen.set(value, out);
111
+ for (const key of Reflect.ownKeys(value)) {
112
+ if (Array.isArray(value) && key === 'length')
113
+ continue;
114
+ const descriptor = Object.getOwnPropertyDescriptor(value, key);
115
+ if (!descriptor?.enumerable || !('value' in descriptor))
116
+ continue;
117
+ const raw = descriptor.value;
118
+ const next = typeof key === 'string' && typeof raw === 'string' && matchKey(key) && !allow(raw)
119
+ ? replace(raw, SENSITIVE_KEY_DETECTOR)
120
+ : await walk(raw);
121
+ Object.defineProperty(out, key, { ...descriptor, value: next });
122
+ }
123
+ return out;
67
124
  };
68
125
  return walk(input);
69
126
  }
70
- export function scan(input, opts = {}) {
71
- const dets = resolveDetectors(opts);
72
- const allow = allowMatcher(opts);
73
- const matchKey = keyMatcher(opts);
127
+ /** Async counterpart for local ML/NER providers whose `detect()` returns a Promise. */
128
+ export async function redactAsync(input, opts = {}) {
129
+ return redactAsyncPrepared(input, preparePolicy(opts));
130
+ }
131
+ function scanPrepared(input, policy) {
132
+ const { opts, dets, allow, matchKey } = policy;
74
133
  const out = [];
134
+ const seen = new WeakSet();
75
135
  const push = (h, location, path) => {
76
136
  const { det: _det, ...f } = h;
77
- out.push(path ? { ...f, ...location, path } : { ...f, ...location });
137
+ const safe = opts.includeValues ? f : withoutValue(f);
138
+ out.push(path ? { ...safe, ...location, path } : { ...safe, ...location });
78
139
  };
79
140
  const walk = (value, path) => {
80
141
  if (typeof value === 'string') {
@@ -94,18 +155,53 @@ export function scan(input, opts = {}) {
94
155
  push(h, { line, column: start - lineStart + 1 }, path || undefined);
95
156
  }
96
157
  }
97
- else if (Array.isArray(value)) {
158
+ else if (value && typeof value === 'object') {
159
+ if (seen.has(value))
160
+ return;
161
+ seen.add(value);
162
+ if (value instanceof Error) {
163
+ walk(value.message, path ? `${path}.message` : 'message');
164
+ }
165
+ if (value instanceof URL || value instanceof URLSearchParams) {
166
+ walk(value.toString(), path);
167
+ return;
168
+ }
169
+ if (value instanceof Map) {
170
+ let index = 0;
171
+ for (const [key, entry] of value) {
172
+ walk(key, `${path}.<map-key:${index}>`);
173
+ walk(entry, `${path}.<map-value:${index}>`);
174
+ index++;
175
+ }
176
+ return;
177
+ }
178
+ if (value instanceof Set) {
179
+ let index = 0;
180
+ for (const entry of value)
181
+ walk(entry, `${path}[${index++}]`);
182
+ return;
183
+ }
184
+ if (value instanceof Date || value instanceof RegExp || value instanceof ArrayBuffer || ArrayBuffer.isView(value)) {
185
+ return;
186
+ }
187
+ }
188
+ if (Array.isArray(value)) {
98
189
  value.forEach((v, i) => walk(v, `${path}[${i}]`));
99
190
  }
100
191
  else if (value && typeof value === 'object') {
101
- for (const [k, v] of Object.entries(value)) {
102
- const child = path ? `${path}.${k}` : k;
103
- if (typeof v === 'string' && matchKey(k) && !allow(v)) {
192
+ for (const key of Reflect.ownKeys(value)) {
193
+ const descriptor = Object.getOwnPropertyDescriptor(value, key);
194
+ if (!descriptor?.enumerable || !('value' in descriptor))
195
+ continue;
196
+ const v = descriptor.value;
197
+ const name = typeof key === 'symbol' ? `[${String(key)}]` : key;
198
+ const child = path ? `${path}.${name}` : name;
199
+ if (typeof key === 'string' && typeof v === 'string' && matchKey(key) && !allow(v)) {
104
200
  out.push({
105
201
  detector: 'sensitive_key',
106
202
  label: 'Sensitive field',
107
- why: `Value stored under a sensitive field name ("${k}").`,
108
- value: v,
203
+ why: `Value stored under a sensitive field name ("${key}").`,
204
+ ...(opts.includeValues ? { value: v } : {}),
109
205
  path: child,
110
206
  risk: 'critical',
111
207
  confidence: 0.98,
@@ -120,12 +216,18 @@ export function scan(input, opts = {}) {
120
216
  walk(input, '');
121
217
  return out;
122
218
  }
219
+ export function scan(input, opts = {}) {
220
+ return scanPrepared(input, preparePolicy(opts));
221
+ }
222
+ function withoutValue(finding) {
223
+ const { value: _value, ...safe } = finding;
224
+ return safe;
225
+ }
123
226
  /** Async counterpart for local ML/NER providers whose `detect()` returns a Promise. */
124
- export async function scanAsync(input, opts = {}) {
125
- const dets = resolveDetectors(opts);
126
- const allow = allowMatcher(opts);
127
- const matchKey = keyMatcher(opts);
227
+ async function scanAsyncPrepared(input, policy) {
228
+ const { opts, dets, allow, matchKey } = policy;
128
229
  const out = [];
230
+ const seen = new WeakSet();
129
231
  const walk = async (value, path) => {
130
232
  if (typeof value === 'string') {
131
233
  const localOpts = await resolvedSemanticOptions(value, opts);
@@ -143,23 +245,62 @@ export async function scanAsync(input, opts = {}) {
143
245
  cursor++;
144
246
  }
145
247
  const { det: _det, ...finding } = h;
146
- const located = { ...finding, line, column: start - lineStart + 1 };
248
+ const located = {
249
+ ...(opts.includeValues ? finding : withoutValue(finding)),
250
+ line,
251
+ column: start - lineStart + 1,
252
+ };
147
253
  out.push(path ? { ...located, path } : located);
148
254
  }
149
255
  }
150
- else if (Array.isArray(value)) {
256
+ else if (value && typeof value === 'object') {
257
+ if (seen.has(value))
258
+ return;
259
+ seen.add(value);
260
+ if (value instanceof Error) {
261
+ await walk(value.message, path ? `${path}.message` : 'message');
262
+ }
263
+ if (value instanceof URL || value instanceof URLSearchParams) {
264
+ await walk(value.toString(), path);
265
+ return;
266
+ }
267
+ if (value instanceof Map) {
268
+ let index = 0;
269
+ for (const [key, entry] of value) {
270
+ await walk(key, `${path}.<map-key:${index}>`);
271
+ await walk(entry, `${path}.<map-value:${index}>`);
272
+ index++;
273
+ }
274
+ return;
275
+ }
276
+ if (value instanceof Set) {
277
+ let index = 0;
278
+ for (const entry of value)
279
+ await walk(entry, `${path}[${index++}]`);
280
+ return;
281
+ }
282
+ if (value instanceof Date || value instanceof RegExp || value instanceof ArrayBuffer || ArrayBuffer.isView(value)) {
283
+ return;
284
+ }
285
+ }
286
+ if (Array.isArray(value)) {
151
287
  for (let i = 0; i < value.length; i++)
152
288
  await walk(value[i], `${path}[${i}]`);
153
289
  }
154
290
  else if (value && typeof value === 'object') {
155
- for (const [k, v] of Object.entries(value)) {
156
- const child = path ? `${path}.${k}` : k;
157
- if (typeof v === 'string' && matchKey(k) && !allow(v)) {
291
+ for (const key of Reflect.ownKeys(value)) {
292
+ const descriptor = Object.getOwnPropertyDescriptor(value, key);
293
+ if (!descriptor?.enumerable || !('value' in descriptor))
294
+ continue;
295
+ const v = descriptor.value;
296
+ const name = typeof key === 'symbol' ? `[${String(key)}]` : key;
297
+ const child = path ? `${path}.${name}` : name;
298
+ if (typeof key === 'string' && typeof v === 'string' && matchKey(key) && !allow(v)) {
158
299
  out.push({
159
300
  detector: 'sensitive_key',
160
301
  label: 'Sensitive field',
161
- why: `Value stored under a sensitive field name ("${k}").`,
162
- value: v,
302
+ why: `Value stored under a sensitive field name ("${key}").`,
303
+ ...(opts.includeValues ? { value: v } : {}),
163
304
  path: child,
164
305
  risk: 'critical',
165
306
  confidence: 0.98,
@@ -174,6 +315,9 @@ export async function scanAsync(input, opts = {}) {
174
315
  await walk(input, '');
175
316
  return out;
176
317
  }
318
+ export async function scanAsync(input, opts = {}) {
319
+ return scanAsyncPrepared(input, preparePolicy(opts));
320
+ }
177
321
  export async function isCleanAsync(input, opts = {}) {
178
322
  return (await scanAsync(input, opts)).length === 0;
179
323
  }
@@ -181,9 +325,11 @@ export function isClean(input, opts = {}) {
181
325
  return scan(input, opts).length === 0;
182
326
  }
183
327
  export function summary(input, opts = {}) {
328
+ return summarizeFindings(scan(input, opts));
329
+ }
330
+ function summarizeFindings(findings) {
184
331
  const byDetector = {};
185
332
  const byRisk = {};
186
- const findings = scan(input, opts);
187
333
  for (const f of findings) {
188
334
  byDetector[f.detector] = (byDetector[f.detector] ?? 0) + 1;
189
335
  byRisk[f.risk] = (byRisk[f.risk] ?? 0) + 1;
@@ -196,19 +342,25 @@ export function summary(input, opts = {}) {
196
342
  * adapter (`flare-redact/pino`, `/winston`, `/http`, `/llm`) accepts, so a
197
343
  * secret is masked the same way across your whole system.
198
344
  */
199
- export function createRedactor(opts = {}) {
345
+ export function compilePolicy(opts = {}) {
346
+ const policy = preparePolicy(opts);
200
347
  return {
201
348
  options: opts,
202
- redact: (input) => redact(input, opts),
203
- scan: (input) => scan(input, opts),
204
- isClean: (input) => isClean(input, opts),
205
- summary: (input) => summary(input, opts),
349
+ redact: (input) => redactPrepared(input, policy),
350
+ redactAsync: (input) => redactAsyncPrepared(input, policy),
351
+ scan: (input) => scanPrepared(input, policy),
352
+ scanAsync: (input) => scanAsyncPrepared(input, policy),
353
+ isClean: (input) => scanPrepared(input, policy).length === 0,
354
+ isCleanAsync: async (input) => (await scanAsyncPrepared(input, policy)).length === 0,
355
+ summary: (input) => summarizeFindings(scanPrepared(input, policy)),
206
356
  vault: () => createVault(opts),
207
357
  wrapConsole: (target) => wrapConsole(opts, target),
208
358
  };
209
359
  }
360
+ /** Backward-compatible name for a precompiled reusable policy. */
361
+ export const createRedactor = compilePolicy;
210
362
  /** Alias for {@link createRedactor}, read as "define the masking policy once". */
211
- export const definePolicy = createRedactor;
363
+ export const definePolicy = compilePolicy;
212
364
  export function wrapConsole(opts = {}, target = console) {
213
365
  const sink = target;
214
366
  const methods = ['log', 'info', 'warn', 'error', 'debug'];