anonyma 1.0.0 → 1.1.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.
- package/CHANGELOG.md +273 -144
- package/README.md +427 -143
- package/dist/ai/index.cjs +522 -0
- package/dist/ai/index.cjs.map +1 -0
- package/dist/ai/index.d.cts +322 -0
- package/dist/ai/index.d.ts +322 -0
- package/dist/ai/index.js +505 -0
- package/dist/ai/index.js.map +1 -0
- package/dist/audit/index.cjs +359 -0
- package/dist/audit/index.cjs.map +1 -0
- package/dist/audit/index.d.cts +287 -0
- package/dist/audit/index.d.ts +287 -0
- package/dist/audit/index.js +340 -0
- package/dist/audit/index.js.map +1 -0
- package/dist/chunk-26IHMQHL.cjs +662 -0
- package/dist/chunk-26IHMQHL.cjs.map +1 -0
- package/dist/chunk-2F2GWGTB.js +174 -0
- package/dist/chunk-2F2GWGTB.js.map +1 -0
- package/dist/chunk-2NNMJ55L.cjs +45 -0
- package/dist/chunk-2NNMJ55L.cjs.map +1 -0
- package/dist/chunk-2YG7R4KJ.cjs +114 -0
- package/dist/chunk-2YG7R4KJ.cjs.map +1 -0
- package/dist/chunk-2ZZHLCEJ.js +237 -0
- package/dist/chunk-2ZZHLCEJ.js.map +1 -0
- package/dist/chunk-3CY6ATKS.cjs +308 -0
- package/dist/chunk-3CY6ATKS.cjs.map +1 -0
- package/dist/chunk-3D5ZCJ7R.js +268 -0
- package/dist/chunk-3D5ZCJ7R.js.map +1 -0
- package/dist/chunk-6LDAIJBL.js +103 -0
- package/dist/chunk-6LDAIJBL.js.map +1 -0
- package/dist/chunk-7HK2V5Q4.js +111 -0
- package/dist/chunk-7HK2V5Q4.js.map +1 -0
- package/dist/chunk-AAP472NG.js +177 -0
- package/dist/chunk-AAP472NG.js.map +1 -0
- package/dist/chunk-AP4JIUNW.js +42 -0
- package/dist/chunk-AP4JIUNW.js.map +1 -0
- package/dist/chunk-BBJPQPGP.js +457 -0
- package/dist/chunk-BBJPQPGP.js.map +1 -0
- package/dist/chunk-CRXRJZEV.cjs +82 -0
- package/dist/chunk-CRXRJZEV.cjs.map +1 -0
- package/dist/chunk-E3PICZYI.js +20 -0
- package/dist/chunk-E3PICZYI.js.map +1 -0
- package/dist/chunk-F7O2FA3F.cjs +1255 -0
- package/dist/chunk-F7O2FA3F.cjs.map +1 -0
- package/dist/chunk-FB56NAAH.cjs +243 -0
- package/dist/chunk-FB56NAAH.cjs.map +1 -0
- package/dist/chunk-G4AN7FND.js +1063 -0
- package/dist/chunk-G4AN7FND.js.map +1 -0
- package/dist/chunk-GS3FRH4K.js +294 -0
- package/dist/chunk-GS3FRH4K.js.map +1 -0
- package/dist/chunk-GYMG5OI3.cjs +186 -0
- package/dist/chunk-GYMG5OI3.cjs.map +1 -0
- package/dist/chunk-IHEIYZPL.cjs +301 -0
- package/dist/chunk-IHEIYZPL.cjs.map +1 -0
- package/dist/chunk-IJAMLYOT.cjs +1087 -0
- package/dist/chunk-IJAMLYOT.cjs.map +1 -0
- package/dist/chunk-ISL5B4LU.cjs +181 -0
- package/dist/chunk-ISL5B4LU.cjs.map +1 -0
- package/dist/chunk-JKW36IPT.js +179 -0
- package/dist/chunk-JKW36IPT.js.map +1 -0
- package/dist/chunk-KOCQBDI4.cjs +179 -0
- package/dist/chunk-KOCQBDI4.cjs.map +1 -0
- package/dist/chunk-OGNLB2KA.js +79 -0
- package/dist/chunk-OGNLB2KA.js.map +1 -0
- package/dist/chunk-PKHZ7CVI.js +28 -0
- package/dist/chunk-PKHZ7CVI.js.map +1 -0
- package/dist/chunk-QYD4F6T7.cjs +114 -0
- package/dist/chunk-QYD4F6T7.cjs.map +1 -0
- package/dist/chunk-RCW5IPPR.js +1288 -0
- package/dist/chunk-RCW5IPPR.js.map +1 -0
- package/dist/chunk-RMMKYHUN.cjs +35 -0
- package/dist/chunk-RMMKYHUN.cjs.map +1 -0
- package/dist/chunk-S4BJ2ADB.cjs +22 -0
- package/dist/chunk-S4BJ2ADB.cjs.map +1 -0
- package/dist/chunk-S7NH6CHY.cjs +462 -0
- package/dist/chunk-S7NH6CHY.cjs.map +1 -0
- package/dist/chunk-SIHPDZXA.js +176 -0
- package/dist/chunk-SIHPDZXA.js.map +1 -0
- package/dist/chunk-TW7PM3UJ.cjs +30 -0
- package/dist/chunk-TW7PM3UJ.cjs.map +1 -0
- package/dist/chunk-UA3EOFBS.cjs +1322 -0
- package/dist/chunk-UA3EOFBS.cjs.map +1 -0
- package/dist/chunk-VE4CCW7W.js +32 -0
- package/dist/chunk-VE4CCW7W.js.map +1 -0
- package/dist/chunk-W6RBCHYF.js +651 -0
- package/dist/chunk-W6RBCHYF.js.map +1 -0
- package/dist/chunk-WLJN7GIS.cjs +189 -0
- package/dist/chunk-WLJN7GIS.cjs.map +1 -0
- package/dist/chunk-YMLR375Z.js +1244 -0
- package/dist/chunk-YMLR375Z.js.map +1 -0
- package/dist/compliance/index.cjs +88 -0
- package/dist/compliance/index.cjs.map +1 -0
- package/dist/compliance/index.d.cts +277 -0
- package/dist/compliance/index.d.ts +277 -0
- package/dist/compliance/index.js +47 -0
- package/dist/compliance/index.js.map +1 -0
- package/dist/crypto.cjs +12 -136
- package/dist/crypto.cjs.map +1 -1
- package/dist/crypto.d.cts +4 -3
- package/dist/crypto.d.ts +4 -3
- package/dist/crypto.js +3 -137
- package/dist/crypto.js.map +1 -1
- package/dist/detectors/index.cjs +146 -1483
- package/dist/detectors/index.cjs.map +1 -1
- package/dist/detectors/index.d.cts +1 -1
- package/dist/detectors/index.d.ts +1 -1
- package/dist/detectors/index.js +3 -1449
- package/dist/detectors/index.js.map +1 -1
- package/dist/engine/index.cjs +441 -0
- package/dist/engine/index.cjs.map +1 -0
- package/dist/engine/index.d.cts +728 -0
- package/dist/engine/index.d.ts +728 -0
- package/dist/engine/index.js +189 -0
- package/dist/engine/index.js.map +1 -0
- package/dist/hash-2PSYNDMM.cjs +14 -0
- package/dist/hash-2PSYNDMM.cjs.map +1 -0
- package/dist/hash-CELLDNKN.js +5 -0
- package/dist/hash-CELLDNKN.js.map +1 -0
- package/dist/index.cjs +153 -2816
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +93 -11
- package/dist/index.d.ts +93 -11
- package/dist/index.js +13 -2791
- package/dist/index.js.map +1 -1
- package/dist/json-CKDvlRtl.d.ts +147 -0
- package/dist/json-s8ny-RCo.d.cts +147 -0
- package/dist/mcp/index.cjs +751 -0
- package/dist/mcp/index.cjs.map +1 -0
- package/dist/mcp/index.d.cts +226 -0
- package/dist/mcp/index.d.ts +226 -0
- package/dist/mcp/index.js +744 -0
- package/dist/mcp/index.js.map +1 -0
- package/dist/middleware/express.cjs +93 -0
- package/dist/middleware/express.cjs.map +1 -0
- package/dist/middleware/express.d.cts +90 -0
- package/dist/middleware/express.d.ts +90 -0
- package/dist/middleware/express.js +91 -0
- package/dist/middleware/express.js.map +1 -0
- package/dist/middleware/hono.cjs +58 -0
- package/dist/middleware/hono.cjs.map +1 -0
- package/dist/middleware/hono.d.cts +75 -0
- package/dist/middleware/hono.d.ts +75 -0
- package/dist/middleware/hono.js +56 -0
- package/dist/middleware/hono.js.map +1 -0
- package/dist/middleware/index.cjs +24 -0
- package/dist/middleware/index.cjs.map +1 -0
- package/dist/middleware/index.d.cts +106 -0
- package/dist/middleware/index.d.ts +106 -0
- package/dist/middleware/index.js +15 -0
- package/dist/middleware/index.js.map +1 -0
- package/dist/schemas.cjs +5 -5
- package/dist/schemas.cjs.map +1 -1
- package/dist/schemas.d.cts +20 -10
- package/dist/schemas.d.ts +20 -10
- package/dist/schemas.js +5 -5
- package/dist/schemas.js.map +1 -1
- package/dist/session-BdRftyZ5.d.cts +102 -0
- package/dist/session-Cs2zlNQp.d.ts +102 -0
- package/dist/stream.cjs +13 -2262
- package/dist/stream.cjs.map +1 -1
- package/dist/stream.d.cts +1 -1
- package/dist/stream.d.ts +1 -1
- package/dist/stream.js +6 -2255
- package/dist/stream.js.map +1 -1
- package/dist/types--tPm_AjY.d.ts +199 -0
- package/dist/types-0BJH_wqc.d.cts +199 -0
- package/dist/types-CPUhjvl8.d.cts +629 -0
- package/dist/types-Dtht33aq.d.ts +629 -0
- package/dist/{types-D-9HzVuy.d.cts → types-EJTj_BKY.d.cts} +38 -7
- package/dist/{types-D-9HzVuy.d.ts → types-EJTj_BKY.d.ts} +38 -7
- package/dist/types-Zt_bZvwS.d.cts +182 -0
- package/dist/types-Zt_bZvwS.d.ts +182 -0
- package/dist/validators.cjs +39 -181
- package/dist/validators.cjs.map +1 -1
- package/dist/validators.js +1 -174
- package/dist/validators.js.map +1 -1
- package/dist/vault/index.cjs +688 -0
- package/dist/vault/index.cjs.map +1 -0
- package/dist/vault/index.d.cts +385 -0
- package/dist/vault/index.d.ts +385 -0
- package/dist/vault/index.js +669 -0
- package/dist/vault/index.js.map +1 -0
- package/package.json +128 -11
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/engine/resolve.ts","../src/engine/pipeline.ts","../src/engine/replacers.ts","../src/engine/precise.ts","../src/engine/compile.ts"],"names":["ValidationError","AsyncStrategyError","redact","mask","pseudonymize","generalize","synthesize","hash","encrypt","defineDetector","ibanMod97","luhn","BUILTIN_CATEGORIES","UnknownCategoryError","LEGACY_AGGRESSIVE_DETECTORS","LEGACY_DETECTORS","getPreset","defineRegexDetector"],"mappings":";;;;;;;;;;;AAwCA,IAAM,UAAA,GAAa,IAAA;AAMnB,SAAS,cAAc,UAAA,EAA8C;AACnE,EAAA,MAAM,SAAS,CAAC,GAAG,UAAU,CAAA,CAAE,KAAK,CAAC,CAAA,EAAG,CAAA,KAAM,CAAA,CAAE,QAAQ,CAAA,CAAE,KAAA,IAAS,CAAA,CAAE,UAAA,GAAa,EAAE,UAAU,CAAA;AAC9F,EAAA,MAAM,MAAkB,EAAC;AACzB,EAAA,IAAI,MAAA,GAAS,CAAA;AACb,EAAA,KAAA,MAAW,aAAa,MAAA,EAAQ;AAC9B,IAAA,IAAI,SAAA,CAAU,QAAQ,MAAA,EAAQ;AAC9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AA,GAAgB,iBAAA;AACtE,IAAA,MAAA,CAAO,IAAI,KAAK,CAAA;AAChB,IAAA,MAAA,CAAO,GAAA,CAAI,KAAA,CAAM,OAAA,CAAQ,mCAAA,EAAqC,EAAE,CAAC,CAAA;AAAA,EACnE;AACA,EAAA,MAAA,CAAO,OAAO,EAAE,CAAA;AAEhB,EAAA,OAAO,cAAA,CAAe;AAAA,IACpB,SAAA;AAAA,IACA,SAAS,EAAE,QAAA,EAAU,iBAAiB,eAAA,EAAiB,YAAY,GAAG,UAAA,EAAW;AAAA,IACjF,GAAI,KAAK,aAAA,KAAkB,MAAA,GAAY,EAAE,aAAA,EAAe,IAAA,CAAK,aAAA,EAAc,GAAI,EAAC;AAAA,IAChF,KAAA,EAAO,CAAC,GAAI,IAAA,CAAK,SAAS,EAAC,EAAI,GAAG,MAAM,CAAA;AAAA,IACxC,GAAI,KAAK,kBAAA,KAAuB,MAAA,GAC5B,EAAE,kBAAA,EAAoB,IAAA,CAAK,kBAAA,EAAmB,GAC9C,EAAC;AAAA,IACL,GAAI,KAAK,OAAA,KAAY,MAAA,GAAY,EAAE,OAAA,EAAS,IAAA,CAAK,OAAA,EAAQ,GAAI;AAAC,GAC/D,CAAA;AACH","file":"chunk-IJAMLYOT.cjs","sourcesContent":["/**\n * @module engine/resolve\n * @description Overlap resolution on spans. Turns the raw, possibly\n * overlapping hits of several detectors into a list of disjoint spans.\n */\n\nimport type { OverlapPolicy } from \"./types.js\";\n\n/**\n * A raw detector hit.\n */\nexport interface Candidate {\n /** Start offset in the scanned text. */\n readonly start: number;\n /** Exclusive end offset in the scanned text. */\n readonly end: number;\n /** Confidence score in [0, 1]. */\n readonly confidence: number;\n /** Index of the reporting detector in the pipeline's detector list. */\n readonly detector: number;\n /** `true` when the hit matches an allow rule and must be left untouched. */\n readonly allowed: boolean;\n}\n\n/**\n * A span that survived overlap resolution.\n */\nexport interface Resolved {\n /** Start offset in the scanned text. */\n readonly start: number;\n /** Exclusive end offset in the scanned text. */\n readonly end: number;\n /** Confidence score in [0, 1]. */\n readonly confidence: number;\n /** Index of the reporting detector in the pipeline's detector list. */\n readonly detector: number;\n /** `true` for the uncovered remainder of a hit that lost to another one. */\n readonly residual: boolean;\n}\n\nconst WHITESPACE = /\\s/;\n\n/**\n * The 1.x rule: earliest start wins, ties go to the higher confidence, and\n * every hit that overlaps an accepted one is dropped entirely.\n */\nfunction resolveLegacy(candidates: readonly Candidate[]): Resolved[] {\n const sorted = [...candidates].sort((a, b) => a.start - b.start || b.confidence - a.confidence);\n const out: Resolved[] = [];\n let cursor = 0;\n for (const candidate of sorted) {\n if (candidate.start < cursor) continue;\n cursor = candidate.end;\n if (candidate.allowed) continue;\n out.push({\n start: candidate.start,\n end: candidate.end,\n confidence: candidate.confidence,\n detector: candidate.detector,\n residual: false,\n });\n }\n return out;\n}\n\n/** Order in which overlapping hits are accepted. */\nfunction byPriority(a: Candidate, b: Candidate): number {\n return (\n b.confidence - a.confidence ||\n b.end - b.start - (a.end - a.start) ||\n a.start - b.start ||\n a.detector - b.detector\n );\n}\n\n/**\n * Resolve one group of transitively overlapping hits, which lie in\n * `text[base, end)`. One flag per character records what has been claimed, so\n * the cost is the total length of the hits rather than their number squared.\n */\nfunction resolveCluster(\n text: string,\n cluster: Candidate[],\n base: number,\n end: number,\n out: Resolved[],\n): void {\n const [only] = cluster;\n if (cluster.length === 1 && only !== undefined) {\n if (!only.allowed) out.push({ ...stripAllowed(only), residual: false });\n return;\n }\n\n cluster.sort(byPriority);\n const claimed = new Uint8Array(end - base);\n\n for (const candidate of cluster) {\n // Collect what the candidate adds to the characters claimed so far.\n const gaps: { start: number; end: number }[] = [];\n let open = -1;\n for (let at = candidate.start; at < candidate.end; at++) {\n if (claimed[at - base] === 0) {\n if (open < 0) open = at;\n } else if (open >= 0) {\n gaps.push({ start: open, end: at });\n open = -1;\n }\n }\n if (open >= 0) gaps.push({ start: open, end: candidate.end });\n\n const [first] = gaps;\n const untouched =\n gaps.length === 1 && first?.start === candidate.start && first.end === candidate.end;\n\n if (untouched) {\n claimed.fill(1, candidate.start - base, candidate.end - base);\n if (!candidate.allowed) out.push({ ...stripAllowed(candidate), residual: false });\n continue;\n }\n\n // A hit the caller allow-listed never produces partial replacements.\n if (candidate.allowed) continue;\n\n for (const gap of gaps) {\n // Keep the whitespace around a remainder, so words do not run together.\n let { start, end: stop } = gap;\n while (start < stop && WHITESPACE.test(text.charAt(start))) start++;\n while (stop > start && WHITESPACE.test(text.charAt(stop - 1))) stop--;\n if (start === stop) continue;\n claimed.fill(1, start - base, stop - base);\n out.push({\n start,\n end: stop,\n confidence: candidate.confidence,\n detector: candidate.detector,\n residual: true,\n });\n }\n }\n}\n\nfunction stripAllowed(candidate: Candidate): Omit<Resolved, \"residual\"> {\n return {\n start: candidate.start,\n end: candidate.end,\n confidence: candidate.confidence,\n detector: candidate.detector,\n };\n}\n\n/**\n * The default rule: within each group of overlapping hits, hits are accepted\n * by priority, and whatever a losing hit covers beyond the accepted ones is\n * kept as a residual span. No detected character is left uncovered.\n */\nfunction resolveCover(text: string, candidates: readonly Candidate[]): Resolved[] {\n const sorted = [...candidates].sort((a, b) => a.start - b.start || a.end - b.end);\n const out: Resolved[] = [];\n\n let cluster: Candidate[] = [];\n let clusterStart = 0;\n let clusterEnd = -1;\n for (const candidate of sorted) {\n if (cluster.length > 0 && candidate.start >= clusterEnd) {\n resolveCluster(text, cluster, clusterStart, clusterEnd, out);\n cluster = [];\n }\n if (cluster.length === 0) clusterStart = candidate.start;\n cluster.push(candidate);\n clusterEnd = Math.max(clusterEnd, candidate.end);\n }\n if (cluster.length > 0) resolveCluster(text, cluster, clusterStart, clusterEnd, out);\n\n return out.sort((a, b) => a.start - b.start);\n}\n\n/**\n * Resolve overlapping hits into disjoint spans in document order.\n *\n * @param text - The scanned text (used to trim whitespace from remainders).\n * @param candidates - Raw hits, in any order.\n * @param policy - The overlap policy.\n * @returns Disjoint spans sorted by start offset. Allow-listed hits are not returned.\n *\n * @example\n * ```ts\n * resolveSpans(\"a@b.co\", [{ start: 0, end: 6, confidence: 0.99, detector: 0, allowed: false }], \"cover\");\n * // [{ start: 0, end: 6, confidence: 0.99, detector: 0, residual: false }]\n * ```\n */\nexport function resolveSpans(\n text: string,\n candidates: readonly Candidate[],\n policy: OverlapPolicy,\n): Resolved[] {\n if (candidates.length === 0) return [];\n return policy === \"legacy\" ? resolveLegacy(candidates) : resolveCover(text, candidates);\n}\n","/**\n * @module engine/pipeline\n * @description The pipeline orchestrator: runs detectors, filters and\n * resolves their hits on offsets, and assembles the output in one\n * left-to-right pass.\n */\n\nimport { AsyncStrategyError, ValidationError } from \"../errors.js\";\nimport { resolveSpans } from \"./resolve.js\";\nimport type { Candidate, Resolved } from \"./resolve.js\";\nimport type {\n AllowRule,\n AppliedSpan,\n DetectedSpan,\n Pipeline,\n PipelineOptions,\n ReplaceContext,\n Replacer,\n SpanDetector,\n TransformResult,\n} from \"./types.js\";\n\nconst NO_SPANS: readonly AppliedSpan[] = Object.freeze([]);\n\nconst OVERLAP_POLICIES: ReadonlySet<string> = new Set([\"cover\", \"legacy\"]);\n\n/** Signals `collect()` to stop after the first qualifying hit. */\nconst STOP = Symbol(\"stop\");\n\ntype AllowTest = (\n value: string,\n start: number,\n end: number,\n owner: SpanDetector,\n confidence: number,\n) => boolean;\n\nfunction isThenable(value: unknown): value is PromiseLike<unknown> {\n return (\n typeof value === \"object\" &&\n value !== null &&\n typeof (value as { then?: unknown }).then === \"function\"\n );\n}\n\n/**\n * Compile allow rules into a single predicate. Returns `undefined` when there\n * are no rules, so callers can skip the check entirely.\n */\nfunction compileAllow(rules: readonly AllowRule[], caseSensitive: boolean): AllowTest | undefined {\n if (rules.length === 0) return undefined;\n\n const exact = new Set<string>();\n const patterns: RegExp[] = [];\n const predicates: ((value: string, span: DetectedSpan) => boolean)[] = [];\n\n for (const rule of rules) {\n if (typeof rule === \"string\") {\n exact.add(caseSensitive ? rule : rule.toLowerCase());\n } else if (rule instanceof RegExp) {\n // Drop `g` and `y`: a stateful `lastIndex` would make `test()` alternate.\n patterns.push(new RegExp(rule.source, rule.flags.replace(/[gy]/g, \"\")));\n } else if (typeof rule === \"function\") {\n predicates.push(rule);\n } else {\n throw new ValidationError(\"allow\", \"entries must be strings, RegExp instances or functions\");\n }\n }\n\n return (value, start, end, owner, confidence) => {\n if (exact.has(caseSensitive ? value : value.toLowerCase())) return true;\n for (const pattern of patterns) if (pattern.test(value)) return true;\n if (predicates.length === 0) return false;\n const span: DetectedSpan = {\n start,\n end,\n category: owner.category,\n confidence,\n detector: owner.id,\n residual: false,\n };\n return predicates.some((predicate) => predicate(value, span));\n };\n}\n\n/**\n * Create a reusable detection-and-replacement pipeline.\n *\n * @param options - Detectors, replacement plan and filters.\n * @returns An immutable {@link Pipeline}.\n * @throws {@link ValidationError} When the configuration is invalid.\n *\n * @example\n * ```ts\n * import { createPipeline, emailDetector, creditCardDetector, redactWith, maskWith } from \"anonyma/engine\";\n *\n * const pipeline = createPipeline({\n * detectors: [emailDetector, creditCardDetector],\n * replace: {\n * fallback: redactWith(),\n * byCategory: { \"credit-card\": maskWith({ keepTrailing: 4 }) },\n * },\n * });\n *\n * pipeline.transform(\"Mail alice@example.com, card 4111 1111 1111 1111\").text;\n * // \"Mail [REDACTED], card ***************1111\"\n * ```\n */\nexport function createPipeline(options: PipelineOptions): Pipeline {\n const detectors = Object.freeze([...options.detectors]);\n const { minConfidence = 0, overlap = \"cover\", allowCaseSensitive = false } = options;\n\n const seen = new Set<string>();\n for (const detector of detectors) {\n if (seen.has(detector.id)) {\n throw new ValidationError(\"detectors\", `contains the id \"${detector.id}\" more than once`);\n }\n seen.add(detector.id);\n }\n if (typeof minConfidence !== \"number\" || !(minConfidence >= 0 && minConfidence <= 1)) {\n throw new ValidationError(\"minConfidence\", \"must be a number between 0 and 1\");\n }\n if (!OVERLAP_POLICIES.has(overlap)) {\n throw new ValidationError(\"overlap\", 'must be \"cover\" or \"legacy\"');\n }\n if (typeof options.replace.fallback !== \"function\") {\n throw new ValidationError(\"replace.fallback\", \"must be a function\");\n }\n\n const fallback = options.replace.fallback;\n const byCategory = new Map<string, Replacer>();\n for (const [category, replacer] of Object.entries(options.replace.byCategory ?? {})) {\n if (typeof replacer !== \"function\") {\n throw new ValidationError(`replace.byCategory.${category}`, \"must be a function\");\n }\n byCategory.set(category, replacer);\n }\n\n const allow = compileAllow(options.allow ?? [], allowCaseSensitive);\n\n function owner(index: number): SpanDetector {\n const detector = detectors[index];\n /* v8 ignore next 3 -- indices only ever come from this pipeline's own detector list */\n if (detector === undefined) {\n throw new ValidationError(\"detector\", \"index out of range\");\n }\n return detector;\n }\n\n /**\n * Run every detector and collect the hits that pass the confidence filter.\n * With `first` set, returns `STOP` as soon as one hit that is not\n * allow-listed has been seen.\n */\n function collect(text: string, first: boolean): Candidate[] | typeof STOP {\n if (typeof text !== \"string\") {\n throw new ValidationError(\"text\", \"must be a string\");\n }\n const candidates: Candidate[] = [];\n const state = { index: 0, found: false };\n\n const emit = (start: number, end: number, confidence: number): void => {\n if (\n !Number.isInteger(start) ||\n !Number.isInteger(end) ||\n start < 0 ||\n end <= start ||\n end > text.length ||\n !(confidence >= 0 && confidence <= 1)\n ) {\n throw new ValidationError(\n \"detector\",\n `\"${owner(state.index).id}\" reported an invalid span`,\n );\n }\n if (confidence < minConfidence) return;\n const allowed =\n allow?.(text.slice(start, end), start, end, owner(state.index), confidence) === true;\n if (!allowed) state.found = true;\n candidates.push({ start, end, confidence, detector: state.index, allowed });\n };\n\n for (const [index, detector] of detectors.entries()) {\n if (detector.prefilter?.(text) === false) continue;\n state.index = index;\n detector.scan(text, emit);\n if (first && state.found) return STOP;\n }\n return candidates;\n }\n\n function describe(resolved: Resolved): DetectedSpan {\n const detector = owner(resolved.detector);\n return {\n start: resolved.start,\n end: resolved.end,\n category: detector.category,\n confidence: resolved.confidence,\n detector: detector.id,\n residual: resolved.residual,\n };\n }\n\n function scan(text: string): DetectedSpan[] {\n const candidates = collect(text, false);\n /* v8 ignore next -- collect() only stops early when asked to */\n if (candidates === STOP) return [];\n return resolveSpans(text, candidates, overlap).map(describe);\n }\n\n function test(text: string): boolean {\n // Without allow rules any hit survives resolution in some form. With allow\n // rules an allow-listed hit can shadow others, so resolve to be exact.\n if (allow === undefined) return collect(text, true) === STOP;\n return scan(text).length > 0;\n }\n\n function context(span: DetectedSpan, ordinal: number): ReplaceContext {\n return {\n category: span.category,\n detector: span.detector,\n confidence: span.confidence,\n start: span.start,\n end: span.end,\n ordinal,\n residual: span.residual,\n };\n }\n\n function replace(value: string, replaceContext: ReplaceContext): string | Promise<string> {\n return (byCategory.get(replaceContext.category) ?? fallback)(value, replaceContext);\n }\n\n function checked(replacement: unknown, category: string): string {\n if (typeof replacement !== \"string\") {\n throw new ValidationError(\n \"replace\",\n `the replacer for category \"${category}\" must return a string`,\n );\n }\n return replacement;\n }\n\n function transform(text: string): TransformResult {\n const spans = scan(text);\n if (spans.length === 0) return { text, spans: NO_SPANS };\n\n const parts: string[] = [];\n const applied: AppliedSpan[] = [];\n let cursor = 0;\n let outLength = 0;\n\n for (const [i, span] of spans.entries()) {\n const replacement = replace(text.slice(span.start, span.end), context(span, i));\n if (isThenable(replacement)) {\n // Do not leave a rejection unhandled when the caller picked the wrong entry point.\n void Promise.resolve(replacement).catch(() => undefined);\n throw new AsyncStrategyError(span.category);\n }\n const value = checked(replacement, span.category);\n parts.push(text.slice(cursor, span.start), value);\n outLength += span.start - cursor;\n applied.push({ ...span, outStart: outLength, outEnd: outLength + value.length });\n outLength += value.length;\n cursor = span.end;\n }\n parts.push(text.slice(cursor));\n return { text: parts.join(\"\"), spans: applied };\n }\n\n async function transformAsync(text: string): Promise<TransformResult> {\n const spans = scan(text);\n if (spans.length === 0) return { text, spans: NO_SPANS };\n\n const parts: string[] = [];\n const applied: AppliedSpan[] = [];\n let cursor = 0;\n let outLength = 0;\n\n for (const [i, span] of spans.entries()) {\n const value = checked(\n await replace(text.slice(span.start, span.end), context(span, i)),\n span.category,\n );\n parts.push(text.slice(cursor, span.start), value);\n outLength += span.start - cursor;\n applied.push({ ...span, outStart: outLength, outEnd: outLength + value.length });\n outLength += value.length;\n cursor = span.end;\n }\n parts.push(text.slice(cursor));\n return { text: parts.join(\"\"), spans: applied };\n }\n\n return Object.freeze({ detectors, scan, test, replace, transform, transformAsync });\n}\n\n/**\n * Return the text a span refers to.\n *\n * @param text - The text the span was detected in.\n * @param span - The span.\n * @returns The matched text.\n *\n * @example\n * ```ts\n * const [span] = pipeline.scan(\"Mail alice@example.com\");\n * spanText(\"Mail alice@example.com\", span); // \"alice@example.com\"\n * ```\n */\nexport function spanText(text: string, span: Pick<DetectedSpan, \"start\" | \"end\">): string {\n return text.slice(span.start, span.end);\n}\n","/**\n * @module engine/replacers\n * @description Replacer factories for the span engine. Each factory can be\n * imported on its own, so a pipeline only pulls in the strategies it uses.\n *\n * Every built-in replacer fails closed: if a strategy would hand back the\n * original value unchanged, the value is redacted instead.\n */\n\nimport { ValidationError } from \"../errors.js\";\nimport { encrypt } from \"../strategies/encrypt.js\";\nimport { generalize } from \"../strategies/generalize.js\";\nimport { hash } from \"../strategies/hash.js\";\nimport { mask } from \"../strategies/mask.js\";\nimport { pseudonymize } from \"../strategies/pseudonymize.js\";\nimport { redact } from \"../strategies/redact.js\";\nimport { synthesize } from \"../strategies/synthesize.js\";\nimport type {\n EncryptOptions,\n GeneralizeOptions,\n HashOptions,\n MaskOptions,\n PseudonymizeOptions,\n RedactOptions,\n SynthesizeOptions,\n} from \"../types.js\";\nimport type { CompileDependencies, Replacer, StrategySpec } from \"./types.js\";\n\n/**\n * Replacement used when a strategy would otherwise return the original value.\n * @internal\n */\nexport const FAIL_CLOSED_LABEL = \"[REDACTED]\";\n\n/** A range may show this many leading digits of a number; beyond that it is an identifier. */\nconst MAX_REVEALED_DIGITS = 3;\n\nfunction failClosed(value: string, replacement: string): string {\n return replacement === value && value.length > 0 ? FAIL_CLOSED_LABEL : replacement;\n}\n\n/**\n * Replace every value with the same fixed string.\n *\n * @param replacement - The replacement text. Must not be empty.\n * @returns A synchronous {@link Replacer}.\n * @throws {@link ValidationError} When `replacement` is empty or whitespace only.\n *\n * @example\n * ```ts\n * constant(\"***\")(\"alice@example.com\", context); // \"***\"\n * ```\n */\nexport function constant(replacement: string): Replacer {\n if (typeof replacement !== \"string\" || replacement.trim().length === 0) {\n throw new ValidationError(\"replacement\", \"must be a non-empty string\");\n }\n return () => replacement;\n}\n\n/**\n * Replace every value with a label (the `redact` strategy).\n *\n * @param options - Redaction options. The label defaults to `\"[REDACTED]\"`.\n * @returns A synchronous {@link Replacer}.\n * @throws {@link ValidationError} When the label is empty.\n *\n * @example\n * ```ts\n * redactWith({ label: \"[EMAIL]\" })(\"alice@example.com\", context); // \"[EMAIL]\"\n * ```\n */\nexport function redactWith(options: RedactOptions = {}): Replacer {\n const label = redact(\"\", options);\n return () => label;\n}\n\n/**\n * Mask every value (the `mask` strategy). A configuration that would leave a\n * value fully visible redacts it instead.\n *\n * @param options - Masking options.\n * @returns A synchronous {@link Replacer}.\n * @throws {@link ValidationError} When the options are invalid.\n *\n * @example\n * ```ts\n * maskWith({ keepTrailing: 4 })(\"4111 1111 1111 1111\", context); // \"***************1111\"\n * ```\n */\nexport function maskWith(options: MaskOptions = {}): Replacer {\n mask(\"\", options);\n return (value) => failClosed(value, mask(value, options));\n}\n\n/**\n * Replace every value with a pseudonym (the `pseudonymize` strategy).\n *\n * @param options - Pseudonymization options.\n * @returns A synchronous {@link Replacer}.\n * @throws {@link ValidationError} When the prefix is invalid.\n *\n * @remarks\n * The seeded form of this strategy is not cryptographic. For keyed,\n * deterministic pseudonyms use a keyed tokenizer from `\"anonyma/vault\"`.\n *\n * @example\n * ```ts\n * pseudonymizeWith({ prefix: \"user_\" })(\"alice@example.com\", context); // \"user_9d1ba6c1f89a49d9\"\n * ```\n */\nexport function pseudonymizeWith(options: PseudonymizeOptions = {}): Replacer {\n pseudonymize(\"\", options);\n return (value) => failClosed(value, pseudonymize(value, options));\n}\n\n/**\n * Replace numeric values with a range (the `generalize` strategy). Values that\n * are not numeric are redacted rather than passed through, and so is a number\n * whose range would still show more than three of its leading digits: a range\n * hides a quantity such as an age or a year, not an identifier such as an\n * account or a card number.\n *\n * @param options - Generalization options.\n * @returns A synchronous {@link Replacer}.\n * @throws {@link ValidationError} When `bucketSize` is invalid or `1`.\n *\n * @example\n * ```ts\n * generalizeWith({ bucketSize: 10 })(\"27\", context); // \"20-29\"\n * generalizeWith()(\"alice@example.com\", context); // \"[REDACTED]\"\n * generalizeWith()(\"123456789\", context); // \"[REDACTED]\"\n * ```\n */\nexport function generalizeWith(options: GeneralizeOptions = {}): Replacer {\n generalize(\"0\", options);\n const bucketSize = options.bucketSize ?? 10;\n if (bucketSize < 2) {\n throw new ValidationError(\n \"bucketSize\",\n \"must be at least 2: a range of one value hides nothing\",\n );\n }\n const hiddenDigits = Math.floor(Math.log10(bucketSize));\n return (value) => {\n const parsed = Number(value);\n if (value.trim().length === 0 || !Number.isFinite(parsed)) return FAIL_CLOSED_LABEL;\n const digits = String(Math.abs(Math.trunc(parsed))).length;\n if (digits - hiddenDigits > MAX_REVEALED_DIGITS) return FAIL_CLOSED_LABEL;\n return failClosed(value, generalize(value, options));\n };\n}\n\n/**\n * Replace every value with format-preserving synthetic data (the `synthesize`\n * strategy), using the category of the span to pick the generator.\n *\n * @param options - Synthesis options.\n * @returns A synchronous {@link Replacer}.\n *\n * @example\n * ```ts\n * synthesizeWith({ seed: \"s3cret\" })(\"alice@example.com\", context); // \"grace.taylor95@demo.io\"\n * ```\n */\nexport function synthesizeWith(options: SynthesizeOptions = {}): Replacer {\n return (value, context) => failClosed(value, synthesize(value, context.category, options));\n}\n\n/**\n * Replace every value with a SHA-256 digest (the `hash` strategy).\n *\n * @param options - Hashing options.\n * @returns An asynchronous {@link Replacer}.\n * @throws {@link ValidationError} When `truncate` is not an integer between 1 and 64.\n *\n * @remarks\n * A hash of a low-entropy identifier can be reversed by enumeration. Supply a\n * `pepper`, or prefer a keyed tokenizer from `\"anonyma/vault\"`.\n *\n * @example\n * ```ts\n * await hashWith({ pepper: \"p\", truncate: 32 })(\"alice@example.com\", context);\n * ```\n */\nexport function hashWith(options: HashOptions = {}): Replacer {\n const { truncate = 16 } = options;\n if (!Number.isInteger(truncate) || truncate < 1 || truncate > 64) {\n throw new ValidationError(\"truncate\", \"must be an integer between 1 and 64 (inclusive)\");\n }\n return (value) => hash(value, options);\n}\n\n/**\n * Replace every value with AES-GCM ciphertext in the 1.x `encrypt()` format.\n *\n * @param options - Key material and encoding.\n * @returns An asynchronous {@link Replacer}.\n * @throws {@link ValidationError} When neither `passphrase` nor `keyBytes` is given,\n * `keyBytes` is not 16 or 32 bytes long, or `encoding` is unknown.\n *\n * @remarks\n * With a `passphrase` the key is derived again for every value, which costs\n * tens of milliseconds each. Pass `keyBytes`, or use a sealed tokenizer from\n * `\"anonyma/vault\"`, for anything but small inputs.\n *\n * @example\n * ```ts\n * await encryptWith({ keyBytes })(\"alice@example.com\", context); // \"base64:…:…\"\n * ```\n */\nexport function encryptWith(options: EncryptOptions): Replacer {\n if (options.keyBytes === undefined && (options.passphrase ?? \"\") === \"\") {\n throw new ValidationError(\"encryption\", \"requires `passphrase` or `keyBytes`\");\n }\n if (\n options.keyBytes !== undefined &&\n options.keyBytes.length !== 16 &&\n options.keyBytes.length !== 32\n ) {\n throw new ValidationError(\"encryption.keyBytes\", \"must be 16 or 32 bytes long\");\n }\n const encoding: unknown = options.encoding;\n if (encoding !== undefined && encoding !== \"base64\" && encoding !== \"hex\") {\n throw new ValidationError(\"encryption.encoding\", 'must be \"base64\" or \"hex\"');\n }\n return (value) => encrypt(value, options);\n}\n\n/**\n * Build the replacer for a strategy given as data.\n *\n * @param spec - The strategy.\n * @param dependencies - Provider and secrets for strategies that need them.\n * @returns The {@link Replacer} implementing the strategy.\n * @throws {@link ValidationError} When the strategy needs a dependency that was not supplied,\n * or its options are invalid.\n *\n * @example\n * ```ts\n * const replacer = strategyReplacer({ strategy: \"mask\", keepTrailing: 4 });\n * ```\n */\nexport function strategyReplacer(\n spec: StrategySpec,\n dependencies: CompileDependencies = {},\n): Replacer {\n const secrets = dependencies.secrets ?? {};\n switch (spec.strategy) {\n case \"redact\":\n return redactWith(spec);\n case \"mask\":\n return maskWith(spec);\n case \"generalize\":\n return generalizeWith(spec);\n case \"pseudonymize\":\n return pseudonymizeWith(\n spec.seed === undefined && secrets.pseudonymizeSeed !== undefined\n ? { ...spec, seed: secrets.pseudonymizeSeed }\n : spec,\n );\n case \"synthesize\":\n return synthesizeWith(\n spec.seed === undefined && secrets.synthesizeSeed !== undefined\n ? { ...spec, seed: secrets.synthesizeSeed }\n : spec,\n );\n case \"hash\":\n return hashWith(\n spec.pepper === undefined && secrets.hashPepper !== undefined\n ? { ...spec, pepper: secrets.hashPepper }\n : spec,\n );\n case \"encrypt\": {\n if (dependencies.encryption === undefined) {\n throw new ValidationError(\"encryption\", \"is required by the `encrypt` strategy\");\n }\n return encryptWith(dependencies.encryption);\n }\n case \"tokenize\": {\n const provider = dependencies.tokenization;\n if (provider === undefined) {\n throw new ValidationError(\"tokenization\", \"is required by the `tokenize` strategy\");\n }\n return (value, context) => provider.tokenize(value, { category: context.category });\n }\n default: {\n const unknown: never = spec;\n throw new ValidationError(\n \"strategy\",\n `\"${String((unknown as { strategy?: unknown }).strategy)}\" is not a known strategy`,\n );\n }\n }\n}\n","/**\n * @module engine/precise\n * @description Native span detectors for the five identifier families whose\n * formats are defined by a standard: email addresses, US Social Security\n * Numbers, IBANs, IP addresses and payment card numbers.\n *\n * Unlike the 1.x detectors they validate what they match (issuer ranges and\n * Luhn for cards, the ISO 13616 country length table and mod-97 for IBANs,\n * SSA allocation rules for SSNs, the RFC 4291 text grammar for IPv6) and they\n * look at the surrounding text to reject look-alikes such as version strings,\n * ZIP+4 codes, file names and MAC addresses. Their patterns are compiled once.\n */\n\nimport { ibanMod97, luhn } from \"../validators.js\";\nimport { defineDetector } from \"./detector.js\";\nimport type { EmitSpan, SpanDetector } from \"./types.js\";\n\n// ---------------------------------------------------------------------------\n// Email\n// ---------------------------------------------------------------------------\n\n// The local part is bounded (RFC 5321 allows 64 octets), so that a long run of\n// local-part characters costs a fixed amount per start position.\nconst EMAIL_PATTERN =\n /(?<![\\p{L}\\p{N}_%+-])[\\p{L}\\p{N}_%+-](?:[\\p{L}\\p{N}._%+'-]{0,62}[\\p{L}\\p{N}_%+-])?@((?:[\\p{L}\\p{N}](?:[\\p{L}\\p{N}-]{0,61}[\\p{L}\\p{N}])?\\.)+)(xn--[a-z0-9-]{1,59}|\\p{L}{2,24})(?!\\p{L})/giu;\n\n/** \"Top-level domains\" that are really asset or unit-file suffixes. */\nconst NOT_A_TLD: ReadonlySet<string> = new Set([\n \"png\",\n \"jpg\",\n \"jpeg\",\n \"gif\",\n \"svg\",\n \"webp\",\n \"ico\",\n \"bmp\",\n \"css\",\n \"js\",\n \"json\",\n \"map\",\n \"service\",\n \"socket\",\n \"timer\",\n \"mount\",\n \"target\",\n \"slice\",\n \"scope\",\n]);\n\n/** Top-level domains common enough that `x@y.com(` is an address and not a method call. */\nconst COMMON_TLD: ReadonlySet<string> = new Set([\n \"com\",\n \"org\",\n \"net\",\n \"edu\",\n \"gov\",\n \"mil\",\n \"int\",\n \"info\",\n \"biz\",\n \"name\",\n \"pro\",\n \"io\",\n \"co\",\n \"me\",\n \"dev\",\n \"app\",\n \"ai\",\n]);\n\n/**\n * `scheme://user[:password]` immediately before the match: URL userinfo, not\n * an address. Only characters that occur in a user name or a password may sit\n * between the scheme and the match, so `\"https://acme.com\",\"email\":\"a@b.co\"`\n * and `https://acme.com,a@b.co` are still addresses.\n */\nconst URL_USERINFO_BEFORE = /[a-z][a-z0-9+.-]*:\\/\\/[a-z0-9._~%!$*+:-]*$/i;\n/** A mail header whose value is a list of `<message identifiers>`, not of addresses. */\nconst MESSAGE_ID_BEFORE =\n /\\b(?:message-id|in-reply-to|references)\\s*:\\s*(?:<[^\\s<>]*>\\s*)*<[^\\s<>@]*$/i;\n\nfunction scanEmail(text: string, emit: EmitSpan): void {\n EMAIL_PATTERN.lastIndex = 0;\n let match: RegExpExecArray | null;\n while ((match = EMAIL_PATTERN.exec(text)) !== null) {\n const start = match.index;\n const end = start + match[0].length;\n const domain = match[1] ?? \"\";\n const tld = (match[2] ?? \"\").toLowerCase();\n\n if (NOT_A_TLD.has(tld)) continue;\n // \"name@1.0.0-beta\": a package version, not a domain.\n if (/^\\d+\\.\\d+\\./.test(domain)) continue;\n // \"W@x.flatten()\": a call on a short identifier, not an address.\n if (\n text.charCodeAt(end) === 40 &&\n match[0].indexOf(\"@\") <= 2 &&\n tld.length > 2 &&\n !COMMON_TLD.has(tld)\n ) {\n continue;\n }\n // The account every Git remote uses (\"git@github.com:org/repo.git\") is nobody's address.\n if (match[0].startsWith(\"git@\")) continue;\n\n const before = text.slice(Math.max(0, start - 96), start);\n if (URL_USERINFO_BEFORE.test(before) || MESSAGE_ID_BEFORE.test(before)) continue;\n\n emit(start, end, 0.99);\n }\n}\n\n/**\n * Email addresses, including internationalised ones (RFC 6531).\n *\n * @example\n * ```ts\n * import { createPipeline, emailDetector, redactWith } from \"anonyma/engine\";\n *\n * createPipeline({ detectors: [emailDetector], replace: { fallback: redactWith() } })\n * .transform(\"Write to josé.garcia@example.com\").text;\n * // \"Write to [REDACTED]\"\n * ```\n */\nexport const emailDetector: SpanDetector = defineDetector({\n id: \"email\",\n category: \"email\",\n prefilter: (text) => text.includes(\"@\"),\n scan: scanEmail,\n maxMatchLength: 320,\n});\n\nconst OBFUSCATED_EMAIL_PATTERN =\n /(?<![\\p{L}\\p{N}._%+-])[\\p{L}\\p{N}_%+-][\\p{L}\\p{N}._%+-]{0,63}(?:\\s*(?:\\[at\\]|\\(at\\)|\\{at\\}|\\[@\\])\\s*|[ \\t]+@[ \\t]*|@[ \\t]+)[\\p{L}\\p{N}](?:[\\p{L}\\p{N}-]*[\\p{L}\\p{N}])?(?:\\s*(?:\\[dot\\]|\\(dot\\)|\\{dot\\}|\\[\\.\\]|\\.)\\s*[\\p{L}\\p{N}](?:[\\p{L}\\p{N}-]*[\\p{L}\\p{N}])?)*\\s*(?:\\[dot\\]|\\(dot\\)|\\{dot\\}|\\[\\.\\]|\\.)\\s*\\p{L}{2,24}(?![\\p{L}\\p{N}])/giu;\n\n/**\n * Obfuscated email addresses such as `user [at] example [dot] com`,\n * `user[@]example[.]com` and `user @ example.com`. Used by aggressive\n * pipelines in addition to {@link emailDetector}.\n *\n * @example\n * ```ts\n * createPipeline({ detectors: [emailDetector, obfuscatedEmailDetector], replace: { fallback: redactWith() } });\n * ```\n */\nexport const obfuscatedEmailDetector: SpanDetector = defineDetector({\n id: \"email/obfuscated\",\n category: \"email\",\n prefilter: (text) => /\\[at\\]|\\(at\\)|\\{at\\}|@/i.test(text),\n scan(text, emit) {\n OBFUSCATED_EMAIL_PATTERN.lastIndex = 0;\n let match: RegExpExecArray | null;\n while ((match = OBFUSCATED_EMAIL_PATTERN.exec(text)) !== null) {\n emit(match.index, match.index + match[0].length, 0.75);\n }\n },\n maxMatchLength: 320,\n});\n\n// ---------------------------------------------------------------------------\n// US Social Security Number\n// ---------------------------------------------------------------------------\n\nconst SSN_SEPARATOR = String.raw`(?:\\s?[-\\u2010-\\u2015\\u2212.]\\s?|\\s{1,2})`;\nconst SSN_SEPARATED_PATTERN = new RegExp(\n String.raw`(?<!\\d)(?<!\\d[-\\u2010-\\u2015\\u2212./])(\\d{3})${SSN_SEPARATOR}(\\d{2})${SSN_SEPARATOR}(\\d{4})(?![-\\u2010-\\u2015\\u2212.]?\\d)`,\n \"g\",\n);\n// After the label, up to 24 characters that are neither digits nor the end of\n// a sentence may precede the number: \"SSN is\", \"SSN of the applicant:\".\nconst SSN_LABELLED_PATTERN =\n /(?:\\bssn|\\bss#|\\bsocial\\s+security)(?:\\s*(?:number|num\\.?|no\\.?|#))?[^\\d\\n.;!?]{0,24}(\\d{9})(?!\\d)/dgi;\n\n/** SSA allocation rules: no area 000, 666 or 900-999, no group 00, no serial 0000. */\nfunction isAssignableSsn(area: string, group: string, serial: string): boolean {\n return (\n area !== \"000\" && area !== \"666\" && !area.startsWith(\"9\") && group !== \"00\" && serial !== \"0000\"\n );\n}\n\nfunction scanSsn(text: string, emit: EmitSpan): void {\n SSN_SEPARATED_PATTERN.lastIndex = 0;\n let match: RegExpExecArray | null;\n while ((match = SSN_SEPARATED_PATTERN.exec(text)) !== null) {\n if (isAssignableSsn(match[1] ?? \"\", match[2] ?? \"\", match[3] ?? \"\")) {\n emit(match.index, match.index + match[0].length, 0.95);\n }\n }\n SSN_LABELLED_PATTERN.lastIndex = 0;\n while ((match = SSN_LABELLED_PATTERN.exec(text)) !== null) {\n const digits = match[1] ?? \"\";\n const bounds = match.indices?.[1];\n if (\n bounds !== undefined &&\n isAssignableSsn(digits.slice(0, 3), digits.slice(3, 5), digits.slice(5))\n ) {\n emit(bounds[0], bounds[1], 0.9);\n }\n }\n}\n\n/**\n * US Social Security Numbers written with separators (`123-45-6789`), and\n * unseparated nine-digit numbers only when a label such as `SSN` or\n * `social security number` precedes them in the same sentence. A bare\n * nine-digit number is not reported.\n *\n * @example\n * ```ts\n * createPipeline({ detectors: [ssnDetector], replace: { fallback: redactWith() } })\n * .transform(\"SSN 123-45-6789, ZIP 10001-1234\").text;\n * // \"SSN [REDACTED], ZIP 10001-1234\"\n * ```\n */\nexport const ssnDetector: SpanDetector = defineDetector({\n id: \"ssn\",\n category: \"ssn\",\n prefilter: (text) => /\\d{4}/.test(text),\n scan: scanSsn,\n maxMatchLength: 48,\n});\n\nconst SSN_BARE_PATTERN = /(?<![\\d.,])(\\d{3})(\\d{2})(\\d{4})(?![\\d.,]?\\d)/g;\n\n/**\n * Unseparated nine-digit numbers that satisfy the SSA allocation rules. Most\n * such numbers are not SSNs, so the confidence is low. Used by aggressive\n * pipelines in addition to {@link ssnDetector}.\n *\n * @example\n * ```ts\n * createPipeline({ detectors: [ssnDetector, bareSsnDetector], replace: { fallback: redactWith() } });\n * ```\n */\nexport const bareSsnDetector: SpanDetector = defineDetector({\n id: \"ssn/bare\",\n category: \"ssn\",\n prefilter: (text) => /\\d{9}/.test(text),\n scan(text, emit) {\n SSN_BARE_PATTERN.lastIndex = 0;\n let match: RegExpExecArray | null;\n while ((match = SSN_BARE_PATTERN.exec(text)) !== null) {\n if (isAssignableSsn(match[1] ?? \"\", match[2] ?? \"\", match[3] ?? \"\")) {\n emit(match.index, match.index + 9, 0.5);\n }\n }\n },\n maxMatchLength: 12,\n});\n\n// ---------------------------------------------------------------------------\n// IBAN\n// ---------------------------------------------------------------------------\n\n/**\n * IBAN length per country: the ISO 13616 registry, followed by the countries\n * that issue IBAN-format account numbers without being in the registry.\n */\nconst IBAN_LENGTHS: Readonly<Record<string, number>> = {\n AD: 24,\n AE: 23,\n AL: 28,\n AT: 20,\n AZ: 28,\n BA: 20,\n BE: 16,\n BG: 22,\n BH: 22,\n BI: 27,\n BR: 29,\n BY: 28,\n CH: 21,\n CR: 22,\n CY: 28,\n CZ: 24,\n DE: 22,\n DJ: 27,\n DK: 18,\n DO: 28,\n EE: 20,\n EG: 29,\n ES: 24,\n FI: 18,\n FK: 18,\n FO: 18,\n FR: 27,\n GB: 22,\n GE: 22,\n GI: 23,\n GL: 18,\n GR: 27,\n GT: 28,\n HN: 28,\n HR: 21,\n HU: 28,\n IE: 22,\n IL: 23,\n IQ: 23,\n IS: 26,\n IT: 27,\n JO: 30,\n KW: 30,\n KZ: 20,\n LB: 28,\n LC: 32,\n LI: 21,\n LT: 20,\n LU: 20,\n LV: 21,\n LY: 25,\n MC: 27,\n MD: 24,\n ME: 22,\n MK: 19,\n MN: 20,\n MR: 27,\n MT: 31,\n MU: 30,\n NI: 28,\n NL: 18,\n NO: 15,\n OM: 23,\n PK: 24,\n PL: 28,\n PS: 29,\n PT: 25,\n QA: 29,\n RO: 24,\n RS: 22,\n RU: 33,\n SA: 24,\n SC: 31,\n SD: 18,\n SE: 24,\n SI: 19,\n SK: 24,\n SM: 27,\n SO: 23,\n ST: 25,\n SV: 28,\n TL: 23,\n TN: 24,\n TR: 26,\n UA: 29,\n VA: 22,\n VG: 24,\n XK: 20,\n YE: 30,\n // Not in the registry.\n AO: 25,\n BF: 28,\n BJ: 28,\n CF: 27,\n CG: 27,\n CI: 28,\n CM: 27,\n CV: 25,\n DZ: 26,\n GA: 27,\n GQ: 27,\n GW: 25,\n IR: 26,\n KM: 27,\n MA: 28,\n MG: 27,\n ML: 28,\n MZ: 25,\n NE: 28,\n SN: 28,\n TD: 27,\n TG: 28,\n};\n\nconst IBAN_START_PATTERN = /(?<![A-Za-z0-9])[A-Za-z]{2}\\d{2}/g;\n\nfunction isAlphanumeric(code: number): boolean {\n return (code >= 48 && code <= 57) || (code >= 65 && code <= 90) || (code >= 97 && code <= 122);\n}\n\n/** Space, no-break space, hyphen, tab, line feed or carriage return. */\nfunction isIbanSeparator(code: number): boolean {\n return code === 32 || code === 160 || code === 45 || code === 9 || code === 10 || code === 13;\n}\n\nfunction isValidIban(collected: string): boolean {\n const normalised = collected.toUpperCase();\n const checkDigits = Number(normalised.slice(2, 4));\n return checkDigits >= 2 && checkDigits <= 98 && ibanMod97(normalised);\n}\n\n/**\n * End offset of the IBAN that starts at `start`, or -1. Exactly `length`\n * alphanumerics are collected, with at most two separators in a row.\n */\nfunction endOfIban(text: string, start: number, length: number): number {\n let collected = \"\";\n let at = start;\n let end = start;\n let separators = 2;\n while (collected.length < length && at < text.length) {\n const code = text.charCodeAt(at);\n if (isAlphanumeric(code)) {\n collected += text.charAt(at);\n separators = 0;\n end = at + 1;\n } else if (separators < 2 && isIbanSeparator(code)) {\n separators++;\n } else {\n break;\n }\n at++;\n }\n if (collected.length !== length || isAlphanumeric(text.charCodeAt(end))) return -1;\n return isValidIban(collected) ? end : -1;\n}\n\nfunction scanIban(text: string, emit: EmitSpan): void {\n IBAN_START_PATTERN.lastIndex = 0;\n let match: RegExpExecArray | null;\n while ((match = IBAN_START_PATTERN.exec(text)) !== null) {\n const start = match.index;\n const country = match[0].slice(0, 2).toUpperCase();\n if (!Object.hasOwn(IBAN_LENGTHS, country)) continue;\n const end = endOfIban(text, start, IBAN_LENGTHS[country] ?? 0);\n if (end < 0) continue;\n\n emit(start, end, 0.99);\n IBAN_START_PATTERN.lastIndex = end;\n }\n}\n\n/**\n * International Bank Account Numbers, validated against the country's length\n * and the mod-97 check. Spaces or hyphens between groups and lower-case\n * letters are accepted. The length table holds the ISO 13616 registry and the\n * countries that issue IBAN-format numbers outside it.\n *\n * @example\n * ```ts\n * createPipeline({ detectors: [ibanDetector], replace: { fallback: redactWith() } })\n * .transform(\"IBAN: BE68 5390 0754 7034 BIC: GKCCBEBB\").text;\n * // \"IBAN: [REDACTED] BIC: GKCCBEBB\"\n * ```\n */\nexport const ibanDetector: SpanDetector = defineDetector({\n id: \"iban\",\n category: \"iban\",\n prefilter: (text) => /[A-Za-z]{2}\\d{2}/.test(text),\n scan: scanIban,\n maxMatchLength: 72,\n});\n\n// ---------------------------------------------------------------------------\n// IPv4\n// ---------------------------------------------------------------------------\n\nconst IPV4_PATTERN =\n /(?<![\\d.])((?:25[0-5]|2[0-4]\\d|[01]?\\d?\\d)\\.)((?:25[0-5]|2[0-4]\\d|[01]?\\d?\\d)\\.(?:25[0-5]|2[0-4]\\d|[01]?\\d?\\d)\\.(?:25[0-5]|2[0-4]\\d|[01]?\\d?\\d))(\\/(?:3[0-2]|[12]?\\d)(?![\\w/.]))?(?!\\.?\\d)/g;\n\n/** Words that always introduce a version number. */\nconst VERSION_BEFORE = /(?:\\bv|version|\\bver\\.?|\\bfirmware|\\brev\\.?)\\s*[:=#(\"']{0,3}\\s*$/i;\n/**\n * A product token such as `Chrome/` directly before the value. A path segment\n * (`/geoip/203.0.113.57`) and a protocol name (`tcp/203.0.113.9`) are not\n * product tokens.\n */\nconst PRODUCT_BEFORE =\n /(?<![/\\w.+-])(?!(?:tcp|udp|sctp|icmp|ip|ipv4|inet|ssh|dns|peer|host|addr|src|dst)\\/)[a-z][\\w.+-]*\\/\\s*$/i;\n/** Words that introduce a section or clause number, or an object identifier. */\nconst NUMBERING_BEFORE =\n /(?:\\bsection|\\bsec\\.|\\bchapter|\\bclause|\\bappendix|\\bannex|\\boid|\\u00a7)\\s*[:=#(\"']{0,3}\\s*$/i;\n/** Words that introduce a version or a number, and just as often an address. */\nconst WEAK_VERSION_BEFORE = /(?:\\brelease|\\bbuild)\\s*[:=#(\"']{0,3}\\s*$/i;\n/** Capitalised references (\"Table 3.2.1.1\", \"ISO-27001 5.1.2.3\"). */\nconst REFERENCE_BEFORE = /(?:\\bTable|\\bFigure|\\bFig\\.|\\b[A-Z]{2,6}-\\d+)\\s*[:=#(\"']{0,3}\\s*$/;\n/** A suffix that makes the value a version or a file name (\"1.2.3.4-beta\", \"1.2.3.4.tar\"). */\nconst VERSION_SUFFIX_AFTER = /^(?:[-.][A-Za-z]|-\\d+[A-Za-z])/;\n\n/**\n * `true` for addresses in the private, loopback, link-local, shared and\n * documentation ranges. A value in one of them is an address even where the\n * surrounding words suggest a version or a reference number.\n */\nfunction isReservedIpv4(octets: readonly string[]): boolean {\n const first = Number(octets[0]);\n const second = Number(octets[1]);\n const third = Number(octets[2]);\n return (\n first === 10 ||\n first === 127 ||\n (first === 172 && second >= 16 && second <= 31) ||\n (first === 192 && second === 168) ||\n (first === 169 && second === 254) ||\n (first === 100 && second >= 64 && second <= 127) ||\n (first === 192 && second === 0 && third === 2) ||\n (first === 198 && second === 51 && third === 100) ||\n (first === 203 && second === 0 && third === 113)\n );\n}\n\nfunction scanIpv4(text: string, emit: EmitSpan): void {\n IPV4_PATTERN.lastIndex = 0;\n let match: RegExpExecArray | null;\n while ((match = IPV4_PATTERN.exec(text)) !== null) {\n const start = match.index;\n let value = match[0];\n // Netmasks, broadcast and the unspecified address identify nobody.\n if (match[1] === \"255.\" || value.startsWith(\"0.0.0.0\")) continue;\n // Zero-padded octets are only credible when padded to three digits throughout\n // (\"192.168.001.010\"); \"1.200.000.000\" and \"02.123.45.67\" are numbers and phones.\n const octets = value.split(\"/\", 1).join(\"\").split(\".\");\n if (octets.some((octet) => octet.length === 2 && octet.startsWith(\"0\"))) continue;\n if (octets.includes(\"000\") && octets.some((octet) => octet.length !== 3)) continue;\n\n const before = text.slice(Math.max(0, start - 48), start);\n if (VERSION_BEFORE.test(before) || PRODUCT_BEFORE.test(before)) continue;\n // Section and clause numbers are small; an address after such a word usually is not.\n const small = octets.every((octet) => octet.length <= 2);\n if (small && NUMBERING_BEFORE.test(before)) continue;\n if (!isReservedIpv4(octets)) {\n if (WEAK_VERSION_BEFORE.test(before) || (small && REFERENCE_BEFORE.test(before))) continue;\n const end = start + value.length;\n if (VERSION_SUFFIX_AFTER.test(text.slice(end, end + 8))) continue;\n }\n // After \"//\" a slash starts a URL path, not a prefix length.\n if (match[3] !== undefined && before.endsWith(\"//\")) {\n value = value.slice(0, -match[3].length);\n }\n emit(start, start + value.length, 0.95);\n }\n}\n\n/**\n * IPv4 addresses in dotted-decimal notation, with an optional CIDR prefix\n * length. Version strings, section numbers, OIDs, netmasks and numbers with\n * more than four parts are not reported.\n *\n * @example\n * ```ts\n * createPipeline({ detectors: [ipv4Detector], replace: { fallback: redactWith() } })\n * .transform(\"client 203.0.113.57, Chrome/124.0.0.0\").text;\n * // \"client [REDACTED], Chrome/124.0.0.0\"\n * ```\n */\nexport const ipv4Detector: SpanDetector = defineDetector({\n id: \"ipv4\",\n category: \"ipv4\",\n prefilter: (text) => /\\d\\.\\d/.test(text),\n scan: scanIpv4,\n maxMatchLength: 40,\n});\n\n// ---------------------------------------------------------------------------\n// IPv6\n// ---------------------------------------------------------------------------\n\nconst IPV6_RUN_PATTERN = /[0-9A-Fa-f:.]{2,}/g;\nconst HEX_GROUP = /^[0-9A-Fa-f]{1,4}$/;\nconst DOTTED_QUAD =\n /^(?:(?:25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)\\.){3}(?:25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)$/;\n\n/** Number of 16-bit groups in one side of an address, or -1 when it is malformed. */\nfunction countGroups(side: string, allowIpv4Tail: boolean): number {\n if (side === \"\") return 0;\n const groups = side.split(\":\");\n let count = 0;\n for (const [index, group] of groups.entries()) {\n if (HEX_GROUP.test(group)) count += 1;\n else if (allowIpv4Tail && index === groups.length - 1 && DOTTED_QUAD.test(group)) count += 2;\n else return -1;\n }\n return count;\n}\n\n/** RFC 4291 §2.2 text representation. */\nfunction isIpv6(candidate: string): boolean {\n const compression = candidate.indexOf(\"::\");\n if (compression < 0) {\n const groups = candidate.split(\":\");\n // Eight groups of two hex digits is an EUI-64 / MAC-style identifier.\n if (groups.length === 8 && groups.every((group) => group.length === 2)) return false;\n return countGroups(candidate, true) === 8;\n }\n if (candidate.includes(\"::\", compression + 1)) return false;\n const head = countGroups(candidate.slice(0, compression), false);\n const tail = countGroups(candidate.slice(compression + 2), true);\n return head >= 0 && tail >= 0 && head + tail <= 7 && head + tail > 0;\n}\n\nconst WORD_CHARACTER = /[\\p{L}\\p{N}_]/u;\n\nfunction scanIpv6(text: string, emit: EmitSpan): void {\n IPV6_RUN_PATTERN.lastIndex = 0;\n let match: RegExpExecArray | null;\n while ((match = IPV6_RUN_PATTERN.exec(text)) !== null) {\n let start = match.index;\n let value = match[0];\n // A run that starts inside a label (\"IPv6:2001:db8::1\", \"eth0:fe80::1\") or\n // right after one (\"addr:fe80::1\"): the address begins after the first colon.\n // \"x2001:db8::1\" is a malformed token, not a label.\n const glued = start > 0 && WORD_CHARACTER.test(text.charAt(start - 1));\n const colon = value.indexOf(\":\");\n if (!value.startsWith(\"::\") && (colon === 0 || (glued && colon > 0 && colon <= 2))) {\n start += colon + 1;\n value = value.slice(colon + 1);\n } else if (glued) {\n continue;\n }\n // Trailing sentence punctuation and a single trailing colon are not part of an address.\n while (value.endsWith(\".\")) value = value.slice(0, -1);\n if (value.endsWith(\":\") && !value.endsWith(\"::\")) value = value.slice(0, -1);\n // No address is longer than 45 characters.\n if (value.length < 3 || value.length > 45) continue;\n if (value.indexOf(\":\") === value.lastIndexOf(\":\")) continue;\n\n const end = start + value.length;\n if (WORD_CHARACTER.test(text.charAt(end))) continue;\n // \"Add::add\" and \"dead::beef\" are identifiers and words, not addresses.\n if (!/\\d/.test(value) && value.split(\":\").filter((group) => group !== \"\").length < 3) continue;\n if (!isIpv6(value)) continue;\n\n emit(start, end, 0.95);\n }\n}\n\n/**\n * IPv6 addresses in every RFC 4291 text form: full, `::`-compressed and with\n * an embedded IPv4 tail. MAC-style identifiers, times and `::` scope\n * operators are not reported.\n *\n * @example\n * ```ts\n * createPipeline({ detectors: [ipv6Detector], replace: { fallback: redactWith() } })\n * .transform(\"from 2001:db8::1 at 12:30:45\").text;\n * // \"from [REDACTED] at 12:30:45\"\n * ```\n */\nexport const ipv6Detector: SpanDetector = defineDetector({\n id: \"ipv6\",\n category: \"ipv6\",\n prefilter: (text) => text.includes(\":\"),\n scan: scanIpv6,\n maxMatchLength: 64,\n});\n\n// ---------------------------------------------------------------------------\n// Payment cards\n// ---------------------------------------------------------------------------\n\nfunction isDigit(code: number): boolean {\n return code >= 48 && code <= 57;\n}\n\n/** Digit-group layouts in which card numbers are written, longest first. */\nconst CARD_GROUPINGS: readonly (readonly number[])[] = [\n [4, 4, 4, 4, 3],\n [4, 4, 4, 4],\n [4, 4, 4, 3],\n [4, 4, 4, 2],\n [4, 4, 4, 1],\n [4, 6, 5],\n [4, 6, 4],\n [8, 8],\n [6, 13],\n];\n\nconst SEPARATOR_NONE = 0;\nconst SEPARATOR_SPACE = 1;\nconst SEPARATOR_HYPHEN = 2;\nconst SEPARATOR_DOT = 3;\nconst SEPARATOR_NEWLINE = 4;\n\n/** Kind of group separator in `text[from, to)`, or `SEPARATOR_NONE` when it is not one. */\nfunction separatorKind(text: string, from: number, to: number): number {\n const first = text.charCodeAt(from);\n if (to - from === 1) {\n if (first === 32 || first === 160) return SEPARATOR_SPACE;\n if (first === 45) return SEPARATOR_HYPHEN;\n if (first === 46) return SEPARATOR_DOT;\n if (first === 10) return SEPARATOR_NEWLINE;\n return SEPARATOR_NONE;\n }\n if (to - from !== 2) return SEPARATOR_NONE;\n const second = text.charCodeAt(from + 1);\n if ((first === 32 || first === 160) && (second === 32 || second === 160)) return SEPARATOR_SPACE;\n if (first === 13 && second === 10) return SEPARATOR_NEWLINE;\n return SEPARATOR_NONE;\n}\n\nfunction inRange(digits: string, length: number, low: number, high: number): boolean {\n const prefix = Number(digits.slice(0, length));\n return prefix >= low && prefix <= high;\n}\n\n/**\n * `true` when the prefix and length belong to a card network (ISO/IEC 7812\n * issuer ranges). `grouped` tells whether the number was written in groups.\n */\nfunction isIssuedRange(digits: string, grouped: boolean): boolean {\n const length = digits.length;\n if (digits.startsWith(\"4\")) return length === 13 || length === 16 || length === 19;\n if (inRange(digits, 2, 51, 55) || inRange(digits, 4, 2221, 2720)) return length === 16;\n if (digits.startsWith(\"34\") || digits.startsWith(\"37\")) return length === 15;\n // UATP; an unseparated 15-digit number that starts with 1 is too often something else.\n if (digits.startsWith(\"1\")) return grouped && length === 15;\n if (length === 14) return inRange(digits, 3, 300, 305) || /^3(?:095|6|8|9)/.test(digits);\n if (length < 16) return false;\n return (\n digits.startsWith(\"6011\") ||\n inRange(digits, 3, 644, 649) ||\n digits.startsWith(\"65\") ||\n digits.startsWith(\"62\") ||\n inRange(digits, 4, 3528, 3589) ||\n inRange(digits, 3, 300, 305) ||\n /^3(?:095|6|8|9)/.test(digits) ||\n inRange(digits, 4, 2200, 2205) ||\n digits.startsWith(\"50\") ||\n inRange(digits, 2, 56, 69) ||\n // RuPay, UzCard, Humo, Troy, NAPAS, T-Union.\n inRange(digits, 2, 81, 82) ||\n digits.startsWith(\"8600\") ||\n digits.startsWith(\"9860\") ||\n digits.startsWith(\"9792\") ||\n digits.startsWith(\"9704\") ||\n digits.startsWith(\"31\")\n );\n}\n\ninterface CardCandidate {\n /** Index of the first digit run of the candidate. */\n readonly run: number;\n readonly start: number;\n readonly end: number;\n readonly confidence: number;\n}\n\n/**\n * Every position at which a digit run begins is tried on its own, in every\n * layout, so a number that fails the checks never hides the one that starts\n * inside it (\"2024\\n4111 1111 1111 1111\", a column of card numbers).\n */\nfunction scanCard(text: string, emit: EmitSpan): void {\n // The digit runs of the text, found without a regular expression: a dense\n // text has one every few characters, and a match object for each adds up.\n const starts: number[] = [];\n const ends: number[] = [];\n for (let at = 0; at < text.length; at++) {\n if (!isDigit(text.charCodeAt(at))) continue;\n starts.push(at);\n while (at < text.length && isDigit(text.charCodeAt(at))) at++;\n ends.push(at);\n }\n\n const candidates: CardCandidate[] = [];\n /** Per first run: the furthest end of a candidate that starts there. */\n const reach = new Map<number, number>();\n const add = (run: number, end: number, confidence: number): void => {\n candidates.push({ run, start: starts[run] ?? 0, end, confidence });\n reach.set(run, Math.max(reach.get(run) ?? 0, end));\n };\n\n for (const [run, start] of starts.entries()) {\n const length = (ends[run] ?? start) - start;\n\n if (length >= 13 && length <= 19) {\n const digits = text.slice(start, start + length);\n if (isIssuedRange(digits, false) && luhn(digits)) add(run, start + length, 0.92);\n continue;\n }\n\n for (const grouping of CARD_GROUPINGS) {\n if (grouping[0] !== length) continue;\n let digits = \"\";\n let uniform = true;\n let kind = SEPARATOR_NONE;\n let fits = true;\n for (const [offset, size] of grouping.entries()) {\n const from = starts[run + offset];\n const to = ends[run + offset];\n if (from === undefined || to === undefined || to - from !== size) {\n fits = false;\n break;\n }\n if (offset > 0) {\n const between = separatorKind(text, ends[run + offset - 1] ?? from, from);\n if (between === SEPARATOR_NONE) {\n fits = false;\n break;\n }\n if (kind !== SEPARATOR_NONE && between !== kind) uniform = false;\n kind = between;\n }\n digits += text.slice(from, to);\n }\n if (!fits || !luhn(digits)) continue;\n\n const end = ends[run + grouping.length - 1] ?? start;\n if (isIssuedRange(digits, true)) {\n add(run, end, uniform ? 0.97 : 0.85);\n } else if (\n uniform &&\n digits.length === 16 &&\n grouping.length === 4 &&\n !/^(\\d)\\1+$/.test(digits)\n ) {\n // Four groups of four with a valid check digit: a card of a network outside the table.\n add(run, end, 0.6);\n }\n }\n }\n\n // Report the candidates that add something. One that only covers the end of\n // an accepted number and the beginning of the next candidate is the same\n // digits read out of phase.\n let covered = -1;\n for (const candidate of candidates) {\n if (candidate.end <= covered) continue;\n if (candidate.start < covered) {\n let next = candidate.run;\n while ((starts[next] ?? Infinity) < covered) next++;\n if ((reach.get(next) ?? 0) >= candidate.end) continue;\n }\n emit(candidate.start, candidate.end, candidate.confidence);\n covered = Math.max(covered, candidate.end);\n }\n}\n\n/**\n * Payment card numbers (PANs): 13 to 19 digits, unseparated or in the usual\n * groupings, that fall in an issuer range and pass the Luhn check. Four groups\n * of four digits that pass the Luhn check are reported with a low confidence\n * when no issuer range matches.\n *\n * @example\n * ```ts\n * createPipeline({ detectors: [creditCardDetector], replace: { fallback: redactWith() } })\n * .transform(\"4111 1111 1111 1111 12/25, IMEI 490154203237518\").text;\n * // \"[REDACTED] 12/25, IMEI 490154203237518\"\n * ```\n */\nexport const creditCardDetector: SpanDetector = defineDetector({\n id: \"credit-card\",\n category: \"credit-card\",\n prefilter: (text) => /\\d{4}/.test(text),\n scan: scanCard,\n maxMatchLength: 48,\n});\n\nconst MASKED_CARD_PATTERN =\n /(?<![\\w*])(?:[*Xx\\u2022]{4}[ -]?){2,3}(?:[*Xx\\u2022]{2}\\d{2}|\\d{4})(?!\\d)/g;\n\n/**\n * Partially masked card numbers such as `****-****-****-1234` and\n * `XXXX XXXX XXXX 1234`. Used by aggressive pipelines in addition to\n * {@link creditCardDetector}.\n *\n * @example\n * ```ts\n * createPipeline({ detectors: [creditCardDetector, maskedCardDetector], replace: { fallback: redactWith() } });\n * ```\n */\nexport const maskedCardDetector: SpanDetector = defineDetector({\n id: \"credit-card/masked\",\n category: \"credit-card\",\n prefilter: (text) => /[*Xx\\u2022]{4}/.test(text),\n scan(text, emit) {\n MASKED_CARD_PATTERN.lastIndex = 0;\n let match: RegExpExecArray | null;\n while ((match = MASKED_CARD_PATTERN.exec(text)) !== null) {\n emit(match.index, match.index + match[0].length, 0.8);\n }\n },\n maxMatchLength: 24,\n});\n","/**\n * @module engine/compile\n * @description Compiles a declarative {@link PipelineSpec} into a pipeline.\n */\n\nimport { UnknownCategoryError, ValidationError } from \"../errors.js\";\nimport { getPreset } from \"../presets.js\";\nimport type { PiiCategory } from \"../types.js\";\nimport { BUILTIN_CATEGORIES, LEGACY_AGGRESSIVE_DETECTORS, LEGACY_DETECTORS } from \"./builtin.js\";\nimport { defineRegexDetector } from \"./detector.js\";\nimport { createPipeline } from \"./pipeline.js\";\nimport {\n bareSsnDetector,\n creditCardDetector,\n emailDetector,\n ibanDetector,\n ipv4Detector,\n ipv6Detector,\n maskedCardDetector,\n obfuscatedEmailDetector,\n ssnDetector,\n} from \"./precise.js\";\nimport { FAIL_CLOSED_LABEL, strategyReplacer } from \"./replacers.js\";\nimport type {\n CompileDependencies,\n Pipeline,\n PipelineSpec,\n Replacer,\n SpanDetector,\n StrategySpec,\n} from \"./types.js\";\n\n/** The validating detectors, and the extra detectors each gains in aggressive mode. */\nconst PRECISE: Readonly<Partial<Record<PiiCategory, readonly [SpanDetector, ...SpanDetector[]]>>> =\n {\n email: [emailDetector, obfuscatedEmailDetector],\n ssn: [ssnDetector, bareSsnDetector],\n iban: [ibanDetector],\n ipv4: [ipv4Detector],\n ipv6: [ipv6Detector],\n \"credit-card\": [creditCardDetector, maskedCardDetector],\n };\n\nconst DEFAULT_STRATEGY: StrategySpec = { strategy: \"redact\" };\n\nfunction isBuiltinCategory(category: string): category is PiiCategory {\n return (BUILTIN_CATEGORIES as readonly string[]).includes(category);\n}\n\n/**\n * Return the built-in span detectors for a set of categories.\n *\n * @param categories - The categories to detect. Defaults to every built-in category.\n * @param options - `detection` selects the validating or the 1.x detectors,\n * `aggressive` adds the permissive variants.\n * @returns The detectors, in scan order.\n * @throws {@link UnknownCategoryError} When a category is not built in.\n *\n * @example\n * ```ts\n * import { builtinDetectors, createPipeline, redactWith } from \"anonyma/engine\";\n *\n * const pipeline = createPipeline({\n * detectors: builtinDetectors([\"email\", \"phone\"]),\n * replace: { fallback: redactWith() },\n * });\n * ```\n */\nexport function builtinDetectors(\n categories: readonly PiiCategory[] = BUILTIN_CATEGORIES,\n options: { readonly detection?: \"precise\" | \"legacy\"; readonly aggressive?: boolean } = {},\n): SpanDetector[] {\n const { detection = \"precise\", aggressive = false } = options;\n const out: SpanDetector[] = [];\n const seen = new Set<string>();\n\n for (const category of categories) {\n if (!isBuiltinCategory(category)) throw new UnknownCategoryError(category);\n if (seen.has(category)) continue;\n seen.add(category);\n\n const precise = detection === \"precise\" ? PRECISE[category] : undefined;\n if (precise !== undefined) {\n out.push(...(aggressive ? precise : [precise[0]]));\n } else {\n out.push((aggressive ? LEGACY_AGGRESSIVE_DETECTORS : LEGACY_DETECTORS)[category]);\n }\n }\n return out;\n}\n\n/**\n * Compile a declarative pipeline specification.\n *\n * Every strategy is instantiated while compiling, so an invalid option or a\n * missing dependency is reported here rather than on the first match.\n *\n * @param spec - The specification. An empty object detects every built-in\n * category and redacts it.\n * @param dependencies - Tokenization provider, encryption key and secrets for\n * the strategies that need them.\n * @returns The compiled {@link Pipeline}.\n * @throws {@link UnknownCategoryError} When a listed category is not built in.\n * @throws {@link ValidationError} When a strategy, pattern or option is invalid.\n *\n * @example\n * ```ts\n * import { compilePipeline } from \"anonyma/engine\";\n *\n * const pipeline = compilePipeline({\n * preset: \"pci-dss\",\n * rules: { email: { strategy: \"mask\", keepLeading: 1 } },\n * minConfidence: 0.8,\n * });\n * pipeline.transform(\"Card 4111 1111 1111 1111\").text; // \"Card ***************1111\"\n * ```\n */\nexport function compilePipeline(\n spec: PipelineSpec = {},\n dependencies: CompileDependencies = {},\n): Pipeline {\n const input: unknown = spec;\n if (typeof input !== \"object\" || input === null) {\n throw new ValidationError(\"spec\", \"must be an object\");\n }\n const preset = spec.preset === undefined ? undefined : getPreset(spec.preset);\n const detection: unknown = spec.detection;\n if (detection !== undefined && detection !== \"precise\" && detection !== \"legacy\") {\n throw new ValidationError(\"detection\", 'must be \"precise\" or \"legacy\"');\n }\n\n const detectors = builtinDetectors(spec.categories ?? preset?.categories ?? BUILTIN_CATEGORIES, {\n ...(spec.detection !== undefined ? { detection: spec.detection } : {}),\n ...(spec.aggressive !== undefined ? { aggressive: spec.aggressive } : {}),\n });\n\n for (const [index, pattern] of (spec.patterns ?? []).entries()) {\n if (typeof pattern.category !== \"string\" || pattern.category.length === 0) {\n throw new ValidationError(\n `patterns[${String(index)}].category`,\n \"must be a non-empty string\",\n );\n }\n const { confidence } = pattern;\n if (\n confidence !== undefined &&\n !(typeof confidence === \"number\" && confidence >= 0 && confidence <= 1)\n ) {\n throw new ValidationError(\n `patterns[${String(index)}].confidence`,\n \"must be a number between 0 and 1\",\n );\n }\n let compiled: RegExp;\n try {\n compiled = new RegExp(pattern.source, pattern.flags ?? \"\");\n } catch {\n throw new ValidationError(`patterns[${String(index)}]`, \"is not a valid regular expression\");\n }\n detectors.push(\n defineRegexDetector({\n id: `pattern/${String(index)}`,\n category: pattern.category,\n pattern: compiled,\n ...(pattern.confidence !== undefined ? { confidence: pattern.confidence } : {}),\n }),\n );\n }\n\n const strategies = new Map<string, StrategySpec>();\n for (const rule of preset?.rules ?? []) {\n // Preset rules never use the strategies that need a dependency.\n strategies.set(rule.category, rule.strategy as StrategySpec);\n }\n for (const [category, strategy] of Object.entries(spec.rules ?? {})) {\n const rule: unknown = strategy;\n if (typeof rule !== \"object\" || rule === null) {\n throw new ValidationError(`rules.${category}`, \"must be a strategy object\");\n }\n strategies.set(category, strategy);\n }\n\n const byCategory: Record<string, Replacer> = {};\n for (const [category, strategy] of strategies) {\n Object.defineProperty(byCategory, category, {\n value: strategyReplacer(strategy, dependencies),\n enumerable: true,\n });\n }\n\n const defaultStrategy =\n spec.defaultStrategy ??\n (preset?.defaultStrategy as StrategySpec | undefined) ??\n DEFAULT_STRATEGY;\n\n // A redaction label must survive a second pass unchanged. The 1.x bank-account\n // detector reads any eight-letter upper-case word, \"REDACTED\" included, as a\n // BIC, so the labels in use are exempt from detection. That includes the label\n // the other strategies fall back to when they cannot change a value.\n const labels = new Set<string>();\n for (const strategy of [defaultStrategy, ...strategies.values()]) {\n if (strategy.strategy === \"tokenize\" || strategy.strategy === \"hash\") continue;\n if (strategy.strategy === \"encrypt\") continue;\n const label =\n strategy.strategy === \"redact\" ? (strategy.label ?? \"[REDACTED]\") : FAIL_CLOSED_LABEL;\n labels.add(label);\n labels.add(label.replace(/^[^\\p{L}\\p{N}]+|[^\\p{L}\\p{N}]+$/gu, \"\"));\n }\n labels.delete(\"\");\n\n return createPipeline({\n detectors,\n replace: { fallback: strategyReplacer(defaultStrategy, dependencies), byCategory },\n ...(spec.minConfidence !== undefined ? { minConfidence: spec.minConfidence } : {}),\n allow: [...(spec.allow ?? []), ...labels],\n ...(spec.allowCaseSensitive !== undefined\n ? { allowCaseSensitive: spec.allowCaseSensitive }\n : {}),\n ...(spec.overlap !== undefined ? { overlap: spec.overlap } : {}),\n });\n}\n"]}
|
|
@@ -0,0 +1,181 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
var chunkRMMKYHUN_cjs = require('./chunk-RMMKYHUN.cjs');
|
|
4
|
+
var chunkS7NH6CHY_cjs = require('./chunk-S7NH6CHY.cjs');
|
|
5
|
+
var chunkIJAMLYOT_cjs = require('./chunk-IJAMLYOT.cjs');
|
|
6
|
+
var chunkWLJN7GIS_cjs = require('./chunk-WLJN7GIS.cjs');
|
|
7
|
+
|
|
8
|
+
// src/middleware/core.ts
|
|
9
|
+
var JSON_TYPE = /^application\/(?:[\w.+-]*\+)?json\b/i;
|
|
10
|
+
var TEXT_TYPE = /^(?:text\/|application\/(?:(?:[\w.-]*\+)?xml|x-ndjson|ndjson|jsonl|javascript|x-javascript|ecmascript|x-www-form-urlencoded|graphql|yaml|x-yaml|csv)\b)/i;
|
|
11
|
+
var EVENT_STREAM_TYPE = /^text\/event-stream\b/i;
|
|
12
|
+
var CHARSET = /;\s*charset\s*=\s*"?([^";\s]+)"?/i;
|
|
13
|
+
var EVENT_END = /\r\n\r\n|\n\n|\r\r/;
|
|
14
|
+
function tooLarge() {
|
|
15
|
+
return new chunkWLJN7GIS_cjs.ValidationError("body", "is larger than maxBodyLength and was not scrubbed");
|
|
16
|
+
}
|
|
17
|
+
function decode(bytes, contentType) {
|
|
18
|
+
const label = CHARSET.exec(contentType)?.[1] ?? "utf-8";
|
|
19
|
+
let decoder;
|
|
20
|
+
try {
|
|
21
|
+
decoder = new TextDecoder(label, { fatal: true });
|
|
22
|
+
} catch {
|
|
23
|
+
throw new chunkWLJN7GIS_cjs.ValidationError("body", "is in a character set that cannot be decoded");
|
|
24
|
+
}
|
|
25
|
+
try {
|
|
26
|
+
return decoder.decode(bytes);
|
|
27
|
+
} catch {
|
|
28
|
+
throw new chunkWLJN7GIS_cjs.ValidationError("body", "is not text in its declared character set");
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
function asUtf8(contentType) {
|
|
32
|
+
return CHARSET.test(contentType) ? contentType.replace(CHARSET, "; charset=utf-8") : contentType;
|
|
33
|
+
}
|
|
34
|
+
async function readBytes(stream, limit) {
|
|
35
|
+
const reader = stream.getReader();
|
|
36
|
+
const chunks = [];
|
|
37
|
+
let length = 0;
|
|
38
|
+
for (; ; ) {
|
|
39
|
+
const { value, done } = await reader.read();
|
|
40
|
+
if (done) break;
|
|
41
|
+
length += value.length;
|
|
42
|
+
if (length > limit) {
|
|
43
|
+
await reader.cancel();
|
|
44
|
+
throw tooLarge();
|
|
45
|
+
}
|
|
46
|
+
chunks.push(value);
|
|
47
|
+
}
|
|
48
|
+
const out = new Uint8Array(length);
|
|
49
|
+
let offset = 0;
|
|
50
|
+
for (const chunk of chunks) {
|
|
51
|
+
out.set(chunk, offset);
|
|
52
|
+
offset += chunk.length;
|
|
53
|
+
}
|
|
54
|
+
return out;
|
|
55
|
+
}
|
|
56
|
+
function compressionOf(bytes, encoding) {
|
|
57
|
+
if (bytes[0] === 31 && bytes[1] === 139) return "gzip";
|
|
58
|
+
const zlib = bytes[0] === 120 && (bytes[0] << 8 | (bytes[1] ?? 0)) % 31 === 0;
|
|
59
|
+
return encoding === "deflate" && zlib ? "deflate" : void 0;
|
|
60
|
+
}
|
|
61
|
+
function createScrubber(options = {}) {
|
|
62
|
+
const pipeline = options.pipeline ?? chunkIJAMLYOT_cjs.compilePipeline(options.spec ?? {});
|
|
63
|
+
const {
|
|
64
|
+
keyRules,
|
|
65
|
+
keys,
|
|
66
|
+
numberDigits,
|
|
67
|
+
audit,
|
|
68
|
+
actor,
|
|
69
|
+
policyId,
|
|
70
|
+
maxBodyLength = 5e6
|
|
71
|
+
} = options;
|
|
72
|
+
const onAuditError = options.onAuditError ?? (() => void 0);
|
|
73
|
+
const jsonOptions = {
|
|
74
|
+
pipeline,
|
|
75
|
+
...keyRules !== void 0 ? { keyRules } : {},
|
|
76
|
+
...keys !== void 0 ? { keys } : {},
|
|
77
|
+
...numberDigits !== void 0 ? { numberDigits } : {}
|
|
78
|
+
};
|
|
79
|
+
chunkS7NH6CHY_cjs.sanitizeJson(null, jsonOptions);
|
|
80
|
+
function report(fields, source) {
|
|
81
|
+
if (audit === void 0 || fields.length === 0) return;
|
|
82
|
+
audit.record({
|
|
83
|
+
operation: "anonymize",
|
|
84
|
+
source,
|
|
85
|
+
fields,
|
|
86
|
+
...actor !== void 0 ? { actor } : {},
|
|
87
|
+
...policyId !== void 0 ? { policy: { id: policyId } } : {}
|
|
88
|
+
}).catch(onAuditError);
|
|
89
|
+
}
|
|
90
|
+
function json(value, source) {
|
|
91
|
+
let result = chunkS7NH6CHY_cjs.sanitizeJson(value, jsonOptions);
|
|
92
|
+
if (result.skipped.length > 0) {
|
|
93
|
+
const serialised = JSON.stringify(value);
|
|
94
|
+
if (serialised === void 0) return value;
|
|
95
|
+
result = chunkS7NH6CHY_cjs.sanitizeJson(JSON.parse(serialised), jsonOptions);
|
|
96
|
+
}
|
|
97
|
+
report(result.fields, source);
|
|
98
|
+
return result.value;
|
|
99
|
+
}
|
|
100
|
+
function text(input, source) {
|
|
101
|
+
if (input.length > maxBodyLength) throw tooLarge();
|
|
102
|
+
const result = pipeline.transform(input);
|
|
103
|
+
report(chunkRMMKYHUN_cjs.summarizeSpans(result.spans, { rule: (category) => category }), source);
|
|
104
|
+
return result.text;
|
|
105
|
+
}
|
|
106
|
+
function body(input, contentType, source) {
|
|
107
|
+
const type = contentType ?? "";
|
|
108
|
+
if (JSON_TYPE.test(type)) {
|
|
109
|
+
if (input.length > maxBodyLength) throw tooLarge();
|
|
110
|
+
let parsed;
|
|
111
|
+
try {
|
|
112
|
+
parsed = chunkS7NH6CHY_cjs.parseJsonLossless(input);
|
|
113
|
+
} catch {
|
|
114
|
+
return text(input, source);
|
|
115
|
+
}
|
|
116
|
+
const result = chunkS7NH6CHY_cjs.sanitizeJson(parsed.value, {
|
|
117
|
+
...jsonOptions,
|
|
118
|
+
...parsed.marker !== void 0 ? { rawNumberMarker: parsed.marker } : {}
|
|
119
|
+
});
|
|
120
|
+
report(result.fields, source);
|
|
121
|
+
return result.replaced === 0 ? input : chunkS7NH6CHY_cjs.stringifyJsonLossless(result.value, parsed.marker);
|
|
122
|
+
}
|
|
123
|
+
return TEXT_TYPE.test(type) ? text(input, source) : input;
|
|
124
|
+
}
|
|
125
|
+
function bytes(input, contentType, source) {
|
|
126
|
+
const type = contentType ?? "";
|
|
127
|
+
if (!JSON_TYPE.test(type) && !TEXT_TYPE.test(type)) return void 0;
|
|
128
|
+
if (input.length > maxBodyLength * 4) throw tooLarge();
|
|
129
|
+
return body(decode(input, type), type, source);
|
|
130
|
+
}
|
|
131
|
+
function events(source) {
|
|
132
|
+
let pending = "";
|
|
133
|
+
return new TransformStream({
|
|
134
|
+
transform(chunk, controller) {
|
|
135
|
+
pending += chunk;
|
|
136
|
+
for (; ; ) {
|
|
137
|
+
const end = EVENT_END.exec(pending);
|
|
138
|
+
if (end === null) break;
|
|
139
|
+
const length = end.index + end[0].length;
|
|
140
|
+
controller.enqueue(text(pending.slice(0, length), source));
|
|
141
|
+
pending = pending.slice(length);
|
|
142
|
+
}
|
|
143
|
+
if (pending.length > maxBodyLength) throw tooLarge();
|
|
144
|
+
},
|
|
145
|
+
flush(controller) {
|
|
146
|
+
if (pending.length > 0) controller.enqueue(text(pending, source));
|
|
147
|
+
}
|
|
148
|
+
});
|
|
149
|
+
}
|
|
150
|
+
async function response(original, source) {
|
|
151
|
+
const type = original.headers.get("content-type");
|
|
152
|
+
if (original.body === null || type === null || !(JSON_TYPE.test(type) || TEXT_TYPE.test(type))) {
|
|
153
|
+
return original;
|
|
154
|
+
}
|
|
155
|
+
const headers = new Headers(original.headers);
|
|
156
|
+
headers.delete("content-length");
|
|
157
|
+
headers.delete("content-encoding");
|
|
158
|
+
headers.delete("etag");
|
|
159
|
+
const init = { status: original.status, statusText: original.statusText, headers };
|
|
160
|
+
if (EVENT_STREAM_TYPE.test(type)) {
|
|
161
|
+
const stream = original.body.pipeThrough(new TextDecoderStream()).pipeThrough(events(source)).pipeThrough(new TextEncoderStream());
|
|
162
|
+
return new Response(stream, init);
|
|
163
|
+
}
|
|
164
|
+
let raw = await readBytes(original.body, maxBodyLength * 4);
|
|
165
|
+
const encoding = (original.headers.get("content-encoding") ?? "").trim().toLowerCase();
|
|
166
|
+
if (encoding !== "" && encoding !== "identity") {
|
|
167
|
+
const format = compressionOf(raw, encoding);
|
|
168
|
+
if (format !== void 0) {
|
|
169
|
+
const inflated = new Blob([raw]).stream().pipeThrough(new DecompressionStream(format));
|
|
170
|
+
raw = await readBytes(inflated, maxBodyLength * 4);
|
|
171
|
+
}
|
|
172
|
+
}
|
|
173
|
+
headers.set("content-type", asUtf8(type));
|
|
174
|
+
return new Response(body(decode(raw, type), type, source), init);
|
|
175
|
+
}
|
|
176
|
+
return Object.freeze({ json, text, body, bytes, response });
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
exports.createScrubber = createScrubber;
|
|
180
|
+
//# sourceMappingURL=chunk-ISL5B4LU.cjs.map
|
|
181
|
+
//# sourceMappingURL=chunk-ISL5B4LU.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/middleware/core.ts"],"names":["ValidationError","compilePipeline","sanitizeJson","summarizeSpans","parseJsonLossless","stringifyJsonLossless"],"mappings":";;;;;;;;AA+FA,IAAM,SAAA,GAAY,sCAAA;AAClB,IAAM,SAAA,GACJ,0JAAA;AACF,IAAM,iBAAA,GAAoB,wBAAA;AAC1B,IAAM,OAAA,GAAU,mCAAA;AAEhB,IAAM,SAAA,GAAY,oBAAA;AAElB,SAAS,QAAA,GAA4B;AACnC,EAAA,OAAO,IAAIA,iCAAA,CAAgB,MAAA,EAAQ,mDAAmD,CAAA;AACxF;AAGA,SAAS,MAAA,CAAO,OAAmB,WAAA,EAA6B;AAC9D,EAAA,MAAM,QAAQ,OAAA,CAAQ,IAAA,CAAK,WAAW,CAAA,GAAI,CAAC,CAAA,IAAK,OAAA;AAChD,EAAA,IAAI,OAAA;AACJ,EAAA,IAAI;AACF,IAAA,OAAA,GAAU,IAAI,WAAA,CAAY,KAAA,EAAO,EAAE,KAAA,EAAO,MAAM,CAAA;AAAA,EAClD,CAAA,CAAA,MAAQ;AACN,IAAA,MAAM,IAAIA,iCAAA,CAAgB,MAAA,EAAQ,8CAA8C,CAAA;AAAA,EAClF;AACA,EAAA,IAAI;AACF,IAAA,OAAO,OAAA,CAAQ,OAAO,KAAK,CAAA;AAAA,EAC7B,CAAA,CAAA,MAAQ;AACN,IAAA,MAAM,IAAIA,iCAAA,CAAgB,MAAA,EAAQ,2CAA2C,CAAA;AAAA,EAC/E;AACF;AAGA,SAAS,OAAO,WAAA,EAA6B;AAC3C,EAAA,OAAO,OAAA,CAAQ,KAAK,WAAW,CAAA,GAAI,YAAY,OAAA,CAAQ,OAAA,EAAS,iBAAiB,CAAA,GAAI,WAAA;AACvF;AAGA,eAAe,SAAA,CAAU,QAAoC,KAAA,EAA+B;AAC1F,EAAA,MAAM,MAAA,GAAS,OAAO,SAAA,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AAmB,CAAA;AACtC,MAAA,OAAO,IAAI,QAAA,CAAS,MAAA,EAAQ,IAAI,CAAA;AAAA,IAClC;AAEA,IAAA,IAAI,MAAM,MAAM,SAAA,CAAU,QAAA,CAAS,IAAA,EAAM,gBAAgB,CAAC,CAAA;AAC1D,IAAA,MAAM,QAAA,GAAA,CAAY,SAAS,OAAA,CAAQ,GAAA,CAAI,kBAAkB,CAAA,IAAK,EAAA,EAAI,IAAA,EAAK,CAAE,WAAA,EAAY;AACrF,IAAA,IAAI,QAAA,KAAa,EAAA,IAAM,QAAA,KAAa,UAAA,EAAY;AAE9C,MAAA,MAAM,MAAA,GAAS,aAAA,CAAc,GAAA,EAAK,QAAQ,CAAA;AAC1C,MAAA,IAAI,WAAW,MAAA,EAAW;AACxB,QAAA,MAAM,QAAA,GAAW,IAAI,IAAA,CAAK,CAAC,GAAG,CAAC,CAAA,CAAE,MAAA,EAAO,CAAE,WAAA,CAAY,IAAI,mBAAA,CAAoB,MAAM,CAAC,CAAA;AACrF,QAAA,GAAA,GAAM,MAAM,SAAA,CAAU,QAAA,EAAU,aAAA,GAAgB,CAAC,CAAA;AAAA,MACnD;AAAA,IACF;AACA,IAAA,OAAA,CAAQ,GAAA,CAAI,cAAA,EAAgB,MAAA,CAAO,IAAI,CAAC,CAAA;AACxC,IAAA,OAAO,IAAI,QAAA,CAAS,IAAA,CAAK,MAAA,CAAO,GAAA,EAAK,IAAI,CAAA,EAAG,IAAA,EAAM,MAAM,CAAA,EAAG,IAAI,CAAA;AAAA,EACjE;AAEA,EAAA,OAAO,MAAA,CAAO,OAAO,EAAE,IAAA,EAAM,MAAM,IAAA,EAAM,KAAA,EAAO,UAAU,CAAA;AAC5D","file":"chunk-ISL5B4LU.cjs","sourcesContent":["/**\n * @module middleware/core\n * @description Framework-independent payload scrubbing for HTTP services:\n * one object that sanitizes JSON values, text and Fetch API responses with a\n * pipeline, and records what it did in the audit log.\n */\n\nimport { ValidationError } from \"../errors.js\";\nimport { sanitizeJson } from \"../ai/json.js\";\nimport type { KeyRule } from \"../ai/json.js\";\nimport { summarizeSpans } from \"../audit/fields.js\";\nimport type { AuditFieldEntry, AuditLogger } from \"../audit/types.js\";\nimport { compilePipeline } from \"../engine/compile.js\";\nimport type { Pipeline, PipelineSpec } from \"../engine/types.js\";\nimport type { Bytes } from \"../internal/encoding.js\";\nimport { parseJsonLossless, stringifyJsonLossless } from \"../internal/json-numbers.js\";\n\n/**\n * Options shared by every middleware.\n */\nexport interface ScrubberOptions {\n /** The pipeline to apply. Its replacers must be synchronous. Takes precedence over `spec`. */\n readonly pipeline?: Pipeline;\n /** A pipeline specification, compiled once. Defaults to detecting every category and redacting it. */\n readonly spec?: PipelineSpec;\n /** Keys whose values are replaced whole, such as `password` or `ssn`. */\n readonly keyRules?: readonly KeyRule[];\n /**\n * What happens to a JSON object key in which the pipeline detects something:\n * `\"replace\"` (default) rewrites it like a value, `\"flag\"` leaves it.\n */\n readonly keys?: \"replace\" | \"flag\";\n /**\n * A JSON integer with at least this many digits is scanned as text and\n * becomes a string when a detector matches it. Defaults to `12`; shorter\n * numbers (phone numbers, timestamps) need a key rule.\n */\n readonly numberDigits?: number;\n /** Records every scrubbed payload, without its content. */\n readonly audit?: AuditLogger;\n /** Name of the service, recorded as the actor in audit records. */\n readonly actor?: string;\n /** Identifier of the policy in force, recorded in audit records. */\n readonly policyId?: string;\n /**\n * Largest text body, in characters, that is scrubbed. A larger body is not\n * sent on: scrubbing fails. For a `text/event-stream` response the limit\n * applies to each event. Defaults to 5,000,000.\n */\n readonly maxBodyLength?: number;\n /** Called when an audit record cannot be written. Defaults to ignoring the failure. */\n readonly onAuditError?: (error: unknown) => void;\n}\n\n/**\n * Scrubs payloads and reports to the audit log.\n */\nexport interface Scrubber {\n /**\n * Scrub a value that is about to be serialised as JSON. Returns a\n * structural copy. A value that is not plain JSON data (a class instance,\n * an object with `toJSON`, a `Date`) is first reduced to what\n * `JSON.stringify` would write, so the copy is what gets sent.\n */\n readonly json: <T>(value: T, source: string) => T;\n /** Scrub a text. */\n readonly text: (text: string, source: string) => string;\n /**\n * Scrub a serialised body according to its content type: JSON is parsed,\n * scrubbed and serialised again (a body in which nothing is replaced is\n * returned exactly as it was); textual types are scrubbed as text; anything\n * else is returned unchanged.\n */\n readonly body: (body: string, contentType: string | null | undefined, source: string) => string;\n /**\n * Scrub a body held as bytes. Returns the scrubbed text, or `undefined`\n * when the content type is not one the scrubber handles and the bytes\n * should be sent as they are.\n *\n * @throws ValidationError When the bytes are not text in the declared character set.\n */\n readonly bytes: (\n bytes: Uint8Array,\n contentType: string | null | undefined,\n source: string,\n ) => string | undefined;\n /**\n * Scrub a Fetch API `Response` with a JSON or text body. A\n * `text/event-stream` response is scrubbed event by event as it streams;\n * any other body is read to its end first. Other responses are returned as\n * they are.\n */\n readonly response: (response: Response, source: string) => Promise<Response>;\n}\n\nconst JSON_TYPE = /^application\\/(?:[\\w.+-]*\\+)?json\\b/i;\nconst TEXT_TYPE =\n /^(?:text\\/|application\\/(?:(?:[\\w.-]*\\+)?xml|x-ndjson|ndjson|jsonl|javascript|x-javascript|ecmascript|x-www-form-urlencoded|graphql|yaml|x-yaml|csv)\\b)/i;\nconst EVENT_STREAM_TYPE = /^text\\/event-stream\\b/i;\nconst CHARSET = /;\\s*charset\\s*=\\s*\"?([^\";\\s]+)\"?/i;\n/** The blank line that ends a server-sent event. */\nconst EVENT_END = /\\r\\n\\r\\n|\\n\\n|\\r\\r/;\n\nfunction tooLarge(): ValidationError {\n return new ValidationError(\"body\", \"is larger than maxBodyLength and was not scrubbed\");\n}\n\n/** Decode `bytes` in the character set `contentType` declares (UTF-8 when it declares none). */\nfunction decode(bytes: Uint8Array, contentType: string): string {\n const label = CHARSET.exec(contentType)?.[1] ?? \"utf-8\";\n let decoder: TextDecoder;\n try {\n decoder = new TextDecoder(label, { fatal: true });\n } catch {\n throw new ValidationError(\"body\", \"is in a character set that cannot be decoded\");\n }\n try {\n return decoder.decode(bytes);\n } catch {\n throw new ValidationError(\"body\", \"is not text in its declared character set\");\n }\n}\n\n/** `contentType` with its character set changed to UTF-8, which is what a scrubbed body is. */\nfunction asUtf8(contentType: string): string {\n return CHARSET.test(contentType) ? contentType.replace(CHARSET, \"; charset=utf-8\") : contentType;\n}\n\n/** Read a body to its end, giving up as soon as it is longer than `limit` bytes. */\nasync function readBytes(stream: ReadableStream<Uint8Array>, limit: number): Promise<Bytes> {\n const reader = stream.getReader();\n const chunks: Uint8Array[] = [];\n let length = 0;\n for (;;) {\n const { value, done } = await reader.read();\n if (done) break;\n length += value.length;\n if (length > limit) {\n await reader.cancel();\n throw tooLarge();\n }\n chunks.push(value);\n }\n const out = new Uint8Array(length);\n let offset = 0;\n for (const chunk of chunks) {\n out.set(chunk, offset);\n offset += chunk.length;\n }\n return out;\n}\n\n/** The format `DecompressionStream` needs for bytes that really are compressed, if any. */\nfunction compressionOf(bytes: Uint8Array, encoding: string): \"gzip\" | \"deflate\" | undefined {\n if (bytes[0] === 0x1f && bytes[1] === 0x8b) return \"gzip\";\n const zlib = bytes[0] === 0x78 && ((bytes[0] << 8) | (bytes[1] ?? 0)) % 31 === 0;\n return encoding === \"deflate\" && zlib ? \"deflate\" : undefined;\n}\n\n/**\n * Create a scrubber.\n *\n * @param options - Pipeline, key rules and audit settings.\n * @returns The {@link Scrubber}.\n * @throws {@link ValidationError} When the spec is invalid.\n *\n * @example\n * ```ts\n * import { createScrubber } from \"anonyma/middleware\";\n *\n * const scrubber = createScrubber({ spec: { preset: \"gdpr\" } });\n *\n * // A Next.js route handler, a Cloudflare Worker, or any other Fetch API handler:\n * export async function GET(request: Request): Promise<Response> {\n * return scrubber.response(await upstream(request), \"GET /api/tickets\");\n * }\n * ```\n */\nexport function createScrubber(options: ScrubberOptions = {}): Scrubber {\n const pipeline = options.pipeline ?? compilePipeline(options.spec ?? {});\n const {\n keyRules,\n keys,\n numberDigits,\n audit,\n actor,\n policyId,\n maxBodyLength = 5_000_000,\n } = options;\n const onAuditError = options.onAuditError ?? ((): void => undefined);\n const jsonOptions = {\n pipeline,\n ...(keyRules !== undefined ? { keyRules } : {}),\n ...(keys !== undefined ? { keys } : {}),\n ...(numberDigits !== undefined ? { numberDigits } : {}),\n };\n // Fail on an invalid option now, not on the first response.\n sanitizeJson(null, jsonOptions);\n\n function report(fields: readonly AuditFieldEntry[], source: string): void {\n if (audit === undefined || fields.length === 0) return;\n audit\n .record({\n operation: \"anonymize\",\n source,\n fields,\n ...(actor !== undefined ? { actor } : {}),\n ...(policyId !== undefined ? { policy: { id: policyId } } : {}),\n })\n .catch(onAuditError);\n }\n\n function json<T>(value: T, source: string): T {\n let result = sanitizeJson(value, jsonOptions);\n if (result.skipped.length > 0) {\n // Not plain data: scrub what JSON.stringify would write, since that is what is sent.\n const serialised = JSON.stringify(value) as string | undefined;\n if (serialised === undefined) return value;\n result = sanitizeJson(JSON.parse(serialised) as T, jsonOptions);\n }\n report(result.fields, source);\n return result.value;\n }\n\n function text(input: string, source: string): string {\n if (input.length > maxBodyLength) throw tooLarge();\n const result = pipeline.transform(input);\n report(summarizeSpans(result.spans, { rule: (category) => category }), source);\n return result.text;\n }\n\n function body(input: string, contentType: string | null | undefined, source: string): string {\n const type = contentType ?? \"\";\n if (JSON_TYPE.test(type)) {\n if (input.length > maxBodyLength) throw tooLarge();\n let parsed: ReturnType<typeof parseJsonLossless>;\n try {\n parsed = parseJsonLossless(input);\n } catch {\n // Mislabelled or truncated JSON: still scrub it, as text.\n return text(input, source);\n }\n const result = sanitizeJson(parsed.value, {\n ...jsonOptions,\n ...(parsed.marker !== undefined ? { rawNumberMarker: parsed.marker } : {}),\n });\n report(result.fields, source);\n // Nothing replaced: the body goes out exactly as it came in.\n return result.replaced === 0 ? input : stringifyJsonLossless(result.value, parsed.marker);\n }\n return TEXT_TYPE.test(type) ? text(input, source) : input;\n }\n\n function bytes(\n input: Uint8Array,\n contentType: string | null | undefined,\n source: string,\n ): string | undefined {\n const type = contentType ?? \"\";\n if (!JSON_TYPE.test(type) && !TEXT_TYPE.test(type)) return undefined;\n // Four bytes are at most four characters, so this bound never rejects a body that fits.\n if (input.length > maxBodyLength * 4) throw tooLarge();\n return body(decode(input, type), type, source);\n }\n\n /** Scrub a stream of server-sent events one event at a time. */\n function events(source: string): TransformStream<string, string> {\n let pending = \"\";\n return new TransformStream<string, string>({\n transform(chunk, controller): void {\n pending += chunk;\n for (;;) {\n const end = EVENT_END.exec(pending);\n if (end === null) break;\n const length = end.index + end[0].length;\n controller.enqueue(text(pending.slice(0, length), source));\n pending = pending.slice(length);\n }\n if (pending.length > maxBodyLength) throw tooLarge();\n },\n flush(controller): void {\n if (pending.length > 0) controller.enqueue(text(pending, source));\n },\n });\n }\n\n async function response(original: Response, source: string): Promise<Response> {\n const type = original.headers.get(\"content-type\");\n if (\n original.body === null ||\n type === null ||\n !(JSON_TYPE.test(type) || TEXT_TYPE.test(type))\n ) {\n return original;\n }\n const headers = new Headers(original.headers);\n headers.delete(\"content-length\");\n headers.delete(\"content-encoding\");\n headers.delete(\"etag\");\n const init = { status: original.status, statusText: original.statusText, headers };\n\n if (EVENT_STREAM_TYPE.test(type)) {\n // A stream is never read to its end first: it may not have one.\n const stream = original.body\n .pipeThrough(new TextDecoderStream())\n .pipeThrough(events(source))\n .pipeThrough(new TextEncoderStream());\n return new Response(stream, init);\n }\n\n let raw = await readBytes(original.body, maxBodyLength * 4);\n const encoding = (original.headers.get(\"content-encoding\") ?? \"\").trim().toLowerCase();\n if (encoding !== \"\" && encoding !== \"identity\") {\n // fetch() hands over a decoded body under the original header; a handler may hand over compressed bytes.\n const format = compressionOf(raw, encoding);\n if (format !== undefined) {\n const inflated = new Blob([raw]).stream().pipeThrough(new DecompressionStream(format));\n raw = await readBytes(inflated, maxBodyLength * 4);\n }\n }\n headers.set(\"content-type\", asUtf8(type));\n return new Response(body(decode(raw, type), type, source), init);\n }\n\n return Object.freeze({ json, text, body, bytes, response });\n}\n"]}
|